@trillboards/edge-platform-rtsp 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,535 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ import { spawn } from 'child_process';
5
+ import type { CameraProvider } from '@trillboards/edge-core';
6
+ import { type CropRegion, type RTSPCameraConfig } from './RTSPCameraProvider';
7
+ /**
8
+ * RTSPStreamCameraProvider — video frames off an RTSP camera/NVR channel as a
9
+ * LONG-LIVED ffmpeg session feeding a bounded in-memory ring, so that a LOOK
10
+ * becomes a memory read instead of an RTSP handshake.
11
+ *
12
+ * ── THE PROBLEM THIS EXISTS TO REMOVE, AND IT IS ONE MEASUREMENT ───────────
13
+ *
14
+ * `RTSPCameraProvider.buildCaptureArgs` spawns ONE ffmpeg per grab with
15
+ * `-frames:v 1`, so every look pays a process start, a full RTSP
16
+ * DESCRIBE/SETUP/PLAY handshake, and a wait for the camera's next keyframe
17
+ * before anything can be decoded. Measured through that provider against
18
+ * mediamtx re-streaming a real CCTV clip at the documented degraded profile
19
+ * (640x360 / 399 kbps): p50 **1,986-2,025 ms** per grab at a 1-2 s keyframe
20
+ * interval, 4,005 ms at 4 s. The control — the SAME ffmpeg args against a local
21
+ * file, so spawn + decode + scale + pad + JPEG encode with no stream — is
22
+ * **20-30 ms**. So ~99% of a look is session SETUP, not imaging.
23
+ *
24
+ * That is the whole catch-rate problem. An event is catchable only if a look
25
+ * lands inside it, so catch rate is bounded by `E[min(d/T,1)]` for a look
26
+ * cadence `T`; the Brief group (median ~2.4 s, heavy sub-second tail) needs
27
+ * **0.75 s** to clear the 90% target, which is 2.7x BELOW what one grab
28
+ * physically costs. `connectorCadence.ts` says so in as many words: "Closing
29
+ * that gap needs a persistent RTSP session — one long-lived ffmpeg per feed
30
+ * instead of one per grab — which is an architecture change, not a number."
31
+ * This is that change.
32
+ *
33
+ * Measured through THIS provider against the same rig: the handshake is paid
34
+ * ONCE at open, and thereafter frames arrive every ~250 ms (`streamFps` 4) and
35
+ * `getFrame()` returns in **microseconds** because it reads the newest frame
36
+ * out of memory. See `scripts/measure-persistent-capture.mjs` for the driver
37
+ * and the committed numbers.
38
+ *
39
+ * ── PROCESS COUNT GOES DOWN, NOT UP. SAY IT OUT LOUD ───────────────────────
40
+ *
41
+ * A reviewer reads "persistent session" as "more load on the recorder". It is
42
+ * the opposite, and the incident this package is written around is the reason.
43
+ * A 32-channel NVR once accumulated **28 simultaneous ffmpeg children** because
44
+ * one-shot pulls started outliving the cadence, and the recorder answered with
45
+ * rotating timeouts, CSeq mismatches and cameras flapping into "needs
46
+ * attention" — which is why `CaptureAdmission` caps at 2 concurrent pulls per
47
+ * physical recorder
48
+ * (.claude/lessons/2026-08-17-rtsp-session-admission-and-frame-integrity.md).
49
+ *
50
+ * Compare the two designs on the SAME 16-feed recorder:
51
+ *
52
+ * per-grab (today) 16 feeds x 1 look / 16 s = 1.0 RTSP session SETUP per
53
+ * second, forever — 3,600 DESCRIBE/SETUP/PLAY/TEARDOWN
54
+ * cycles per hour and 3,600 process spawns per hour, with
55
+ * 2 concurrent at any instant and an unbounded pile-up
56
+ * under load (the incident).
57
+ *
58
+ * persistent 16 session setups TOTAL, then nothing. 16 processes,
59
+ * bounded by construction, and 16 concurrent substream
60
+ * readers — which is exactly what the recorder's OWN
61
+ * client app opens for a 16-up grid view, i.e. its designed
62
+ * workload.
63
+ *
64
+ * So the churn goes to zero and the process count per hour falls by ~225x. The
65
+ * one number that goes UP is steady-state concurrent sessions (2 -> N), and
66
+ * that is why the persistent lane is bounded per recorder and degrades rather
67
+ * than fails — see ADMISSION below. It is also the honest limit of what was
68
+ * measurable here: mediamtx will serve any number of readers, so the ceiling of
69
+ * a real consumer NVR is NOT established by this work and the default is a
70
+ * stated judgement, not a measurement.
71
+ *
72
+ * ── ADMISSION: A SECOND LANE, AND IT REFUSES RATHER THAN QUEUES ────────────
73
+ *
74
+ * A long-lived session cannot be admitted from `CaptureAdmission`: a permanent
75
+ * holder of a 2-slot pool is a 50% permanent tax on frame capture for that
76
+ * recorder, and two of them deadlock it entirely. So persistent sessions are
77
+ * admitted from `streamAdmissionBySource`, keyed by the SAME
78
+ * `captureSourceKey(url)` — host:port, credentials and channel path
79
+ * deliberately excluded so 32 channels of one NVR share one budget — counted in
80
+ * their OWN pool with its own cap. Exactly the split `RTSPAudioProvider` uses,
81
+ * for exactly the same reason.
82
+ *
83
+ * The lane never queues. A queued video session would be admitted minutes later
84
+ * against a scene nobody is asking about any more, and a feed waiting on a slot
85
+ * is a feed that is not sensing.
86
+ *
87
+ * ── DEGRADE, NEVER FAIL. THIS IS THE PROPERTY THAT LETS THIS SHIP ──────────
88
+ *
89
+ * When the persistent session cannot be had — the recorder's lane is full, or
90
+ * the recorder refuses the session, or ffmpeg cannot hold it open — this
91
+ * provider does NOT throw. It falls back to an internal `RTSPCameraProvider`
92
+ * and runs the per-grab path, which is precisely what the connector does today.
93
+ * So no camera that works today can be broken by this change; the worst case is
94
+ * that it is no faster than it was.
95
+ *
96
+ * The degrade is a REPORTED STATE, never a hidden branch: `getStats().mode` is
97
+ * `'persistent' | 'per_grab'`, `degradedReason` says which of the three causes
98
+ * fired, and it is logged at warn. A silent downgrade would be the same defect
99
+ * as a silent drop — it would move the problem somewhere nobody looks.
100
+ *
101
+ * ── A DEAD STREAM MUST BE LOUD, AND A PERSISTENT SESSION MAKES THAT HARDER ─
102
+ *
103
+ * The connector's recurring defect is a signal that cannot report its own
104
+ * failure: a recorder that accepts a connection and then stops sending frames
105
+ * is ~50 minutes of beacon silence rendered as "connector not running". A
106
+ * persistent session makes that MORE likely, because the process is still
107
+ * alive and the socket is still open. Three things make it loud instead:
108
+ *
109
+ * 1. `getFrame()` NEVER returns a frame it has already returned. It waits up
110
+ * to `frameWaitMs` for a genuinely new one and then throws
111
+ * `RtspStreamStaleError` carrying the age. Handing back a stale frame is
112
+ * the failure mode, not the fallback: it would keep stamping the camera's
113
+ * `lastFrameAtMs`, and a frozen camera would report as healthy forever.
114
+ * 2. The error message is worded so `classifyRtspFailureClass` reads it as
115
+ * `no_frames` — the recorder answered, no video arrived — and NOT as a
116
+ * reachability class, which would wrongly implicate the LAN grant. The
117
+ * ffmpeg stderr summary is deliberately kept OUT of that message and put
118
+ * in `getStats().lastErrorMessage`, so the classification is deterministic
119
+ * instead of depending on which warning ffmpeg happened to print.
120
+ * 3. `getStats()` DERIVES `frameAgeMs`, `running`, `mode` and the counters
121
+ * live on every call. There is no cached capability boolean. On the
122
+ * Android fleet `cap_audio_classification` is false FLEET-WIDE, including
123
+ * on devices shipping live classifications, because a flag was latched at
124
+ * boot from a value that was still "probing" and nothing ever re-wrote it
125
+ * (docs/runbooks/audio-sensing-substrate.md).
126
+ *
127
+ * A CLEAN EXIT IS A FAULT HERE. `code === 0` means success on the one-shot
128
+ * path; on a persistent session it means the stream ended, which is never what
129
+ * we asked for. Measured against the rig: killing the publisher made ffmpeg
130
+ * exit 0 within 26 ms, and freezing it (session held open, no RTP) made ffmpeg
131
+ * exit 0 after ~10 s with "Failed reading RTSP data: End of file". Both are
132
+ * restarts here, both are counted, and neither is ever silent.
133
+ *
134
+ * ── BOUNDED MEMORY, ENFORCED ON ADMISSION ─────────────────────────────────
135
+ *
136
+ * `VlmCandidateBuffer` gets this right and this copies its discipline: the
137
+ * ceiling is checked on the way IN, in exact bytes, and every eviction is
138
+ * COUNTED. A ring that grows under back-pressure is an OOM on a 7 GB box.
139
+ *
140
+ * There are TWO bounds because there are two places bytes accumulate, and the
141
+ * second one is the easy one to miss: the ring holds complete frames, but the
142
+ * SPLITTER holds a partially-received one. A stream that emits an SOI and then
143
+ * never an EOI — a corrupt feed, a mid-frame protocol change — would grow that
144
+ * accumulator without limit. `maxFrameBytes` bounds it, and an overflow resyncs
145
+ * and is counted as `oversizeFrames`.
146
+ *
147
+ * ── JPEG ONLY, ON PURPOSE ─────────────────────────────────────────────────
148
+ *
149
+ * `RTSPCameraProvider` supports `outputFormat: 'rgb24'` for the ONNX face
150
+ * zoo. A persistent rgb24 stream is 640x480x3 = 921,600 bytes per frame, i.e.
151
+ * 3.7 MB/s per camera at 4 fps and ~59 MB/s across 16 feeds, through pipes and
152
+ * into a ring. The same stream as MJPEG is ~0.12 MB/s per camera (measured:
153
+ * 29.6 KB/frame at q:v 11 on the degraded profile). So this provider is JPEG
154
+ * only and the rgb24 zoo keeps the one-shot path, which is also the right split
155
+ * by product: the zoo is the DOOH audience rail, and the look-cadence problem
156
+ * is the CCTV sensing rail.
157
+ *
158
+ * ── RATE LIMITING WITHOUT FABRICATION ─────────────────────────────────────
159
+ *
160
+ * The output is rate-limited with the `fps` filter rather than by an output
161
+ * `-r`, and the difference matters for constraint 3. The `fps` filter is driven
162
+ * BY ARRIVING INPUT FRAMES: when no frames arrive it emits nothing. Verified
163
+ * against the rig — freezing the source produced zero further output, so a
164
+ * frozen camera cannot manufacture "fresh" frames and defeat the staleness
165
+ * signal. Decode cost is unaffected by the filter (ffmpeg must decode the
166
+ * stream to produce any frame at all); what `streamFps` bounds is scale, pad,
167
+ * JPEG encode and pipe traffic.
168
+ *
169
+ * ── SECRET HYGIENE, INHERITED ─────────────────────────────────────────────
170
+ *
171
+ * RTSP URLs carry passwords. Exactly as the other two providers do, the URL is
172
+ * written to a 0600 ffconcat file and only the temp path reaches argv, so a
173
+ * password never appears in `ps` output; stderr is scrubbed through
174
+ * `sanitizeStreamUrlForLog` before it can reach a log line.
175
+ */
176
+ /** The recorder's persistent-session lane is full. Degrade, never queue. */
177
+ export declare class RtspStreamAdmissionError extends Error {
178
+ readonly code = "RTSP_STREAM_SESSION_LIMIT";
179
+ constructor(sourceKey: string, limit: number);
180
+ }
181
+ /**
182
+ * No NEW frame arrived within the deadline.
183
+ *
184
+ * The wording is load bearing. `classifyRtspFailureClass` tests, in order,
185
+ * auth -> nvr-busy -> unreachable -> timeout -> decode -> no-frames, so this
186
+ * message must avoid every earlier class's vocabulary ("timeout", "timed out",
187
+ * "refused", "corrupt", "eof") and must contain "no frame". A stale persistent
188
+ * session is not a reachability failure — the recorder answered and the socket
189
+ * is up — and misclassifying it as one would send the health surface to
190
+ * `local_network_denied` and blame the operator's macOS LAN grant for a camera
191
+ * that is plainly reachable.
192
+ */
193
+ export declare class RtspStreamStaleError extends Error {
194
+ readonly code = "RTSP_STREAM_STALE";
195
+ readonly ageMs: number;
196
+ constructor(url: string, ageMs: number, restarts: number);
197
+ }
198
+ /**
199
+ * The per-grab provider this one degrades to.
200
+ *
201
+ * `CameraProvider.getFrame()` is declared as `Promise<Buffer | EdgeImageData>`
202
+ * because a locally-attached webcam adapter may hand back decoded pixels. Every
203
+ * RTSP path in this package produces encoded bytes, and this provider is JPEG
204
+ * only, so the fallback is narrowed here rather than cast at the call site — a
205
+ * cast would be a claim, and this is a constraint.
206
+ */
207
+ export type PerGrabCameraProvider = Omit<CameraProvider, 'getFrame'> & {
208
+ getFrame(): Promise<Buffer>;
209
+ };
210
+ /** Why a feed is running the per-grab path instead of a persistent session. */
211
+ export type StreamDegradeReason =
212
+ /** The recorder's persistent-session lane was already full. */
213
+ 'session_limit'
214
+ /** ffmpeg could not hold a session open through `openValidationAttempts`. */
215
+ | 'session_unavailable'
216
+ /** The caller asked for the per-grab path explicitly. */
217
+ | 'disabled';
218
+ export type StreamCaptureMode = 'persistent' | 'per_grab';
219
+ /** A complete JPEG ends at this offset; -1 = need more bytes; -2 = malformed. */
220
+ export declare const JPEG_NEED_MORE = -1;
221
+ export declare const JPEG_MALFORMED = -2;
222
+ /**
223
+ * Offset just past the EOI of the JPEG starting at `start`, by walking JPEG
224
+ * segments — NOT by scanning for the `FF D9` byte pair.
225
+ *
226
+ * A plain byte scan is wrong and the failure is silent. Marker segments carry
227
+ * arbitrary payloads (a DQT's 64 quantisation values, a DHT's code lengths, an
228
+ * APPn's contents), any of which may contain `FF D9`, and a scanner that found
229
+ * one would cut the frame short and hand a truncated JPEG downstream — which
230
+ * `RTSPCameraProvider` already refuses on the one-shot path precisely because a
231
+ * truncated JPEG renders as grey and becomes alert evidence.
232
+ *
233
+ * So: step over each segment by its declared length until SOS, then scan the
234
+ * entropy-coded data honouring JPEG byte stuffing (`FF 00` is a literal `FF`,
235
+ * `FF D0`-`FF D7` are restart markers, `FF FF` is fill) until a real marker
236
+ * appears. In ffmpeg's baseline MJPEG output that marker is EOI.
237
+ */
238
+ export declare function jpegFrameEnd(buf: Buffer, start?: number): number;
239
+ /**
240
+ * Cuts a byte stream of concatenated JPEGs into whole frames, with a HARD
241
+ * ceiling on the partially-received one.
242
+ *
243
+ * The ceiling is the bound people forget: the ring is bounded, but the thing
244
+ * feeding it is an accumulator, and an accumulator with no cap is the same leak
245
+ * one layer up. On overflow the accumulator is dropped and the splitter resyncs
246
+ * to the next SOI, and the event is COUNTED rather than swallowed.
247
+ */
248
+ export declare class MjpegFrameSplitter {
249
+ private readonly maxFrameBytes;
250
+ private acc;
251
+ private oversize;
252
+ private resyncs;
253
+ constructor(maxFrameBytes: number);
254
+ getOversizeFrames(): number;
255
+ getResyncs(): number;
256
+ getPendingBytes(): number;
257
+ reset(): void;
258
+ /** Append a chunk and return every complete frame it completed, in order. */
259
+ push(chunk: Buffer): Buffer[];
260
+ /** Drop bytes up to the next SOI. Returns false when there is no next SOI. */
261
+ private resyncToNextSoi;
262
+ }
263
+ /**
264
+ * Bounded newest-first frame ring. Byte- and count-bounded, enforced when a
265
+ * frame is ADMITTED, and every eviction counted — `VlmCandidateBuffer`'s
266
+ * discipline, for the same reason: a silent eviction moves a lost frame from
267
+ * one invisible place to another.
268
+ */
269
+ export declare class FrameRing {
270
+ private readonly maxFrames;
271
+ private readonly maxBytes;
272
+ private frames;
273
+ private bytes;
274
+ private evicted;
275
+ private rejected;
276
+ private seq;
277
+ constructor(maxFrames: number, maxBytes: number);
278
+ /** Admit a frame. Returns its sequence number, or null if it cannot fit. */
279
+ push(bytes: Buffer, atMs: number): number | null;
280
+ newest(): {
281
+ bytes: Buffer;
282
+ atMs: number;
283
+ seq: number;
284
+ } | null;
285
+ getBytes(): number;
286
+ getFrames(): number;
287
+ getEvicted(): number;
288
+ getRejected(): number;
289
+ clear(): void;
290
+ }
291
+ /** Test seam: forget every recorder's persistent-session budget. */
292
+ export declare function __resetStreamAdmissionForTests(): void;
293
+ /** Live persistent-session occupancy for a recorder, for diagnostics. */
294
+ export declare function streamSessionStatsFor(streamUrl: string): {
295
+ key: string;
296
+ active: number;
297
+ limit: number;
298
+ } | null;
299
+ export interface RTSPStreamCameraConfig {
300
+ /** RTSP stream URL. Credentials never reach argv — see the header. */
301
+ rtspUrl: string;
302
+ /** Output width in pixels (default 640). */
303
+ width?: number;
304
+ /** Output height in pixels (default 480). */
305
+ height?: number;
306
+ /** Mosaic tile carve, applied BEFORE scale — same math as the one-shot path. */
307
+ crop?: CropRegion;
308
+ /** RTSP transport. Default 'tcp'. */
309
+ transport?: 'tcp' | 'udp';
310
+ /** Socket I/O timeout (µs). Default 12000000. */
311
+ timeoutUs?: number;
312
+ /** ffmpeg binary. Default 'ffmpeg'. */
313
+ ffmpegPath?: string;
314
+ /** ffmpeg major version, for the `-timeout` vs `-stimeout` split. Default 6. */
315
+ ffmpegMajorVersion?: number;
316
+ /** JPEG quality 1-100. Default 70, matching the one-shot path. */
317
+ jpegQuality?: number;
318
+ /**
319
+ * Frames DECODED-AND-ENCODED per second by the session. Default 4 (250 ms).
320
+ *
321
+ * This is the ceiling on how fresh a look can be, so it must sit comfortably
322
+ * under the look cadence: at `LOOK_INTERVAL_MS` = 500 ms a 4 fps stream
323
+ * always has an unseen frame in hand and `getFrame()` never blocks. Raising
324
+ * it does not reduce decode cost (ffmpeg decodes the stream regardless) but
325
+ * does raise scale/encode/pipe cost, which is the only per-frame cost this
326
+ * knob controls.
327
+ */
328
+ streamFps?: number;
329
+ /**
330
+ * Decoder/encoder threads for the session. Default 1, and that is a
331
+ * MEASUREMENT, not thrift — see `DEFAULT_DECODER_THREADS`.
332
+ */
333
+ decoderThreads?: number;
334
+ /** Persistent sessions per recorder host:port. Default 16 — see the constant. */
335
+ maxStreamSessionsPerSource?: number;
336
+ /** Complete frames held in the ring. Default 4. */
337
+ ringMaxFrames?: number;
338
+ /** Total bytes of complete frames held. Default 4 MiB. */
339
+ ringMaxBytes?: number;
340
+ /** Ceiling on one partially-received frame. Default 2 MiB. */
341
+ maxFrameBytes?: number;
342
+ /**
343
+ * How long `getFrame()` waits for a NEW frame before declaring the stream
344
+ * stale. Default `max(3000, 6 x frame interval)`.
345
+ */
346
+ frameWaitMs?: number;
347
+ /** Session-start attempts before degrading to per-grab. Default 2. */
348
+ openValidationAttempts?: number;
349
+ /** First restart delay (ms), doubling to `maxRestartDelayMs`. Default 1000. */
350
+ restartDelayMs?: number;
351
+ /** Backoff ceiling (ms). Default 60000. */
352
+ maxRestartDelayMs?: number;
353
+ /**
354
+ * Force the per-grab path. The provider still presents one interface, and
355
+ * `getStats().degradedReason` reports `'disabled'` so the choice is visible.
356
+ */
357
+ persistent?: boolean;
358
+ /** Passed through to the per-grab fallback provider. */
359
+ fallbackConfig?: Partial<RTSPCameraConfig>;
360
+ /** DHCP recovery hook, forwarded to the per-grab fallback. */
361
+ streamUrlResolver?: RTSPCameraConfig['streamUrlResolver'];
362
+ /** Injected spawn, for tests. */
363
+ spawnFn?: typeof spawn;
364
+ /** Injected per-grab fallback, for tests. */
365
+ fallbackFactory?: (config: RTSPCameraConfig) => PerGrabCameraProvider;
366
+ /** Clock injection for tests. */
367
+ now?: () => number;
368
+ /** Optional log sink; messages are already URL-scrubbed. */
369
+ onLog?: (level: 'debug' | 'info' | 'warn' | 'error', message: string) => void;
370
+ }
371
+ export interface RTSPStreamStats {
372
+ opened: boolean;
373
+ /** Which path this feed is ACTUALLY running. Derived, never latched. */
374
+ mode: StreamCaptureMode;
375
+ degradedReason: StreamDegradeReason | null;
376
+ /** True when an ffmpeg session is currently alive. */
377
+ running: boolean;
378
+ /** Complete frames in the ring, and their exact byte total. */
379
+ bufferedFrames: number;
380
+ bufferedBytes: number;
381
+ /** Bytes of a partially-received frame. */
382
+ pendingBytes: number;
383
+ /** ffmpeg session starts, including restarts. */
384
+ sessionStarts: number;
385
+ restarts: number;
386
+ /** Frames admitted to the ring over the session's life. */
387
+ framesDecoded: number;
388
+ /** Frames handed to a caller by getFrame(). */
389
+ framesServed: number;
390
+ /** Ring evictions (a newer frame displaced an unread older one). */
391
+ framesEvicted: number;
392
+ /** Frames refused because one frame exceeded the whole byte budget. */
393
+ framesRejected: number;
394
+ /** Partial frames dropped for exceeding `maxFrameBytes`. */
395
+ oversizeFrames: number;
396
+ /** Splitter resyncs after malformed bytes. */
397
+ resyncs: number;
398
+ /** getFrame() calls that found no new frame within the deadline. */
399
+ staleReads: number;
400
+ /** Wall-clock ms of the newest frame, or null. */
401
+ lastFrameAtMs: number | null;
402
+ /** Age of the newest frame at the moment getStats() was called, or null. */
403
+ frameAgeMs: number | null;
404
+ lastErrorMessage: string | null;
405
+ }
406
+ /**
407
+ * One instance per feed. Implements the SAME `CameraProvider` interface as
408
+ * `RTSPCameraProvider`, so every consumer is unchanged — but `getFrame()` reads
409
+ * the newest frame out of the ring the long-lived session is filling, rather
410
+ * than spawning a process and handshaking a stream per call.
411
+ */
412
+ export declare class RTSPStreamCameraProvider implements CameraProvider {
413
+ private readonly rtspUrl;
414
+ private readonly width;
415
+ private readonly height;
416
+ private readonly crop?;
417
+ private readonly transport;
418
+ private readonly timeoutUs;
419
+ private readonly ffmpegPath;
420
+ private readonly ffmpegMajorVersion;
421
+ private readonly jpegQuality;
422
+ private readonly streamFps;
423
+ private readonly decoderThreads;
424
+ private readonly frameIntervalMs;
425
+ private readonly maxStreamSessionsPerSource;
426
+ private readonly frameWaitMs;
427
+ private readonly openValidationAttempts;
428
+ private readonly restartDelayMs;
429
+ private readonly maxRestartDelayMs;
430
+ private readonly persistentRequested;
431
+ private readonly spawnFn;
432
+ private readonly now;
433
+ private readonly onLog?;
434
+ private readonly buildFallback;
435
+ private readonly ring;
436
+ private readonly splitter;
437
+ private opened;
438
+ private mode;
439
+ private degradedReason;
440
+ private fallback;
441
+ private proc;
442
+ private releaseAdmission;
443
+ private restartTimer;
444
+ private currentRestartDelay;
445
+ private cleanupInput;
446
+ private startingUp;
447
+ private sessionStarts;
448
+ private restarts;
449
+ private framesDecoded;
450
+ private framesServed;
451
+ private staleReads;
452
+ private lastFrameAtMs;
453
+ private lastServedSeq;
454
+ private lastErrorMessage;
455
+ /** Resolvers waiting for the next frame. Woken by `admitFrame`. */
456
+ private frameWaiters;
457
+ constructor(config: RTSPStreamCameraConfig);
458
+ /**
459
+ * Take a recorder session slot and start streaming. NEVER throws because the
460
+ * persistent path was unavailable — it degrades to the per-grab provider and
461
+ * says so. It throws only when the per-grab path ALSO fails, which is exactly
462
+ * what the connector does today, so no working camera can be broken here.
463
+ */
464
+ open(_deviceId?: string): Promise<void>;
465
+ /**
466
+ * The newest frame this feed has produced AND NOT YET SERVED.
467
+ *
468
+ * On the persistent path this is a memory read — microseconds — when a fresh
469
+ * frame is in hand, which at `streamFps` 4 against a 500 ms look cadence is
470
+ * every time. When it is not, the call waits up to `frameWaitMs` and is woken
471
+ * by the next arrival; a wait that expires is a STALE STREAM and throws.
472
+ *
473
+ * Never returning a repeat is the whole loudness guarantee. Handing back the
474
+ * same frame would report a frozen camera as healthy forever, and would also
475
+ * feed the motion detector a constant — which is the documented `file://`
476
+ * fixture trap (`-frames:v 1` with no `-ss` returns frame 0 forever), where
477
+ * the gate calibrates against a constant and settles into `no_motion`
478
+ * permanently.
479
+ */
480
+ getFrame(): Promise<Buffer>;
481
+ getResolution(): {
482
+ width: number;
483
+ height: number;
484
+ };
485
+ getFps(): number;
486
+ isOpen(): boolean;
487
+ close(): Promise<void>;
488
+ /**
489
+ * Every field DERIVED on each call. There is no cached capability boolean
490
+ * here and one must never be added — see the header on
491
+ * `cap_audio_classification`.
492
+ */
493
+ getStats(): RTSPStreamStats;
494
+ private degradeTo;
495
+ private releaseSlot;
496
+ /** The newest frame if it has not been served yet, else null. */
497
+ private takeFreshFrame;
498
+ private waitForFrame;
499
+ private wakeWaiters;
500
+ private admitFrame;
501
+ /**
502
+ * ffmpeg args for a CONTINUOUS MJPEG pull. The URL goes into a 0600 ffconcat
503
+ * file exactly as the other two providers do, so it never reaches argv.
504
+ */
505
+ private buildInputArgs;
506
+ buildArgs(): {
507
+ args: string[];
508
+ cleanup: () => void;
509
+ };
510
+ /**
511
+ * Start one ffmpeg session. Resolves on the FIRST decoded frame — which is
512
+ * the only evidence that matters, because a spawned process that never
513
+ * produces an image is precisely the failure this provider exists to make
514
+ * loud. Rejects when the session ends before that.
515
+ */
516
+ private startSession;
517
+ private stopProcess;
518
+ /**
519
+ * A session ended. While the provider is open this ALWAYS schedules a restart
520
+ * with capped exponential backoff, and it is never allowed to give up. On the
521
+ * Ember fleet `shouldGiveUp` retired a camera permanently after a fixed 411 s
522
+ * and NOTHING re-armed it — `onCameraStartFailed` was telemetry-only, no
523
+ * config push restarted the analyzer, and `setMaxRetries` had zero call sites
524
+ * — so 7,359 escalations became permanent silence
525
+ * (docs/runbooks/ember-camera-health-taxonomy.md). The cap is what keeps a
526
+ * never-give-up retry from being a hammer.
527
+ *
528
+ * Waiters are woken on the way out so a `getFrame()` blocked on a session
529
+ * that just died reaches its stale error rather than sitting out the full
530
+ * deadline for a stream that is provably not coming back.
531
+ */
532
+ private handleSessionEnd;
533
+ private log;
534
+ }
535
+ //# sourceMappingURL=RTSPStreamCameraProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RTSPStreamCameraProvider.d.ts","sourceRoot":"","sources":["../src/RTSPStreamCameraProvider.ts"],"names":[],"mappings":";;;AAAA,OAAO,EAAE,KAAK,EAAgB,MAAM,eAAe,CAAC;AAIpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAQL,KAAK,UAAU,EACf,KAAK,gBAAgB,EACtB,MAAM,sBAAsB,CAAC;AAG9B;;;;;;;;;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