@trillboards/edge-platform-rtsp 0.2.0 → 0.2.3

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,644 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.RTSPAudioProvider = exports.audioSessionStatsFor = exports.__resetAudioAdmissionForTests = exports.RtspAudioNoTrackError = exports.RtspAudioAdmissionError = void 0;
27
+ const child_process_1 = require("child_process");
28
+ const fs = __importStar(require("fs"));
29
+ const os = __importStar(require("os"));
30
+ const path = __importStar(require("path"));
31
+ const RTSPCameraProvider_1 = require("./RTSPCameraProvider");
32
+ /**
33
+ * RTSPAudioProvider — continuous audio off an RTSP camera/NVR channel, as a
34
+ * LONG-LIVED ffmpeg session feeding a bounded ring buffer.
35
+ *
36
+ * ── THE DESIGN PROBLEM, AND IT IS THE WHOLE FILE. Video capture in this
37
+ * package is ONE-SHOT-PER-FRAME behind a recorder-scoped admission gate
38
+ * (`CaptureAdmission`, default 2 concurrent pulls per host:port). That gate is
39
+ * incident-derived: a 32-channel NVR accumulated 28 simultaneous ffmpeg
40
+ * children when pulls started outliving the cadence, and the recorder answered
41
+ * with rotating timeouts, CSeq mismatches and cameras flapping into "needs
42
+ * attention" (.claude/lessons/2026-08-17-rtsp-session-admission-and-frame-integrity.md).
43
+ * The rule that came out of it is that admission must be shared by PHYSICAL
44
+ * RECORDER (host:port), never scoped to a provider instance.
45
+ *
46
+ * Audio cannot be one-shot. Sampling three seconds out of every thirty misses
47
+ * ~90% of the events audio exists to catch, and the point of the acoustic
48
+ * channel is precisely to hear what happens BETWEEN frame pulls. So it needs a
49
+ * session that stays open — which is the one shape the existing gate is least
50
+ * able to absorb, because a permanent holder of a 2-slot pool is a 50%
51
+ * permanent tax on frame capture for that recorder, and two of them deadlock
52
+ * video entirely.
53
+ *
54
+ * ── THE RESOLUTION: A SECOND, SEPARATE LANE ON THE SAME RECORDER KEY.
55
+ * Long-lived audio sessions are admitted from `audioAdmissionBySource`, keyed
56
+ * by the SAME `captureSourceKey(url)` — host:port, credentials and channel path
57
+ * deliberately excluded so 32 channels of one NVR share one budget — but
58
+ * counted in their OWN pool with its own cap (`maxAudioSessionsPerSource`,
59
+ * DEFAULT 1). Three properties fall out, and all three are the point:
60
+ *
61
+ * 1. Audio can NEVER consume a video pull slot, so the incident's failure
62
+ * mode is untouched: frame capture's concurrency against a recorder is
63
+ * exactly what it was before this file existed.
64
+ * 2. Audio is bounded per PHYSICAL RECORDER, which is the lesson's actual
65
+ * rule. A 32-channel NVR gets ONE continuous audio session, not 32 — the
66
+ * naive per-camera design would recreate the incident with processes that
67
+ * never exit, which is strictly worse than the one we already had.
68
+ * 3. The bound is on ADMISSION, so it cannot be exceeded and then reconciled.
69
+ *
70
+ * ── THE SESSION IS ALSO WHY AUDIO IS CHEAP, AND THAT WAS MEASURED ELSEWHERE.
71
+ * `buildCaptureArgs` spawns ONE ffmpeg per grab, so every video look pays a full
72
+ * RTSP handshake plus a keyframe wait: p50 ~2,000 ms against a real stream
73
+ * versus 20–30 ms against a local file, i.e. ~99% of a look is session SETUP,
74
+ * not imaging. That per-look tax is what caps the video cadence. This provider
75
+ * pays it ONCE per recorder and then streams, so the acoustic channel gets
76
+ * CONTINUOUS coverage for a single handshake while video gets one instant per
77
+ * ~2 s of setup. Audio is therefore structurally cheaper per unit of coverage
78
+ * than video is, and it is cheapest exactly where video is dearest — between
79
+ * looks, which is the interval the whole acoustic channel exists to cover. The
80
+ * one-shot/long-lived split is not an awkward asymmetry to be tidied away
81
+ * later; it is the reason this design earns its keep.
82
+ *
83
+ * ── DROP, NEVER QUEUE. A camera that cannot get the slot runs WITHOUT audio
84
+ * and says so (`RtspAudioAdmissionError`); it does not wait. This mirrors
85
+ * `VlmAdmissionGate` for the same reason — a queued audio session would be
86
+ * admitted minutes later against a scene nobody is asking about any more — and
87
+ * it keeps audio strictly supplementary: no failure in this file may ever be
88
+ * able to stop a camera from producing frames.
89
+ *
90
+ * ── A CAMERA WITH NO AUDIO TRACK MUST NOT HOLD THE SLOT. Most CCTV channels
91
+ * carry no audio at all. If such a feed took the recorder's single audio slot
92
+ * and then sat there failing, it would silently deny audio to the one camera on
93
+ * that NVR that actually has a microphone — a defect that looks exactly like
94
+ * "audio doesn't work" and is invisible to every health check. So a missing
95
+ * audio stream is classified as its own PERMANENT outcome: the session stops,
96
+ * the slot is RELEASED immediately, and `open()` rejects with
97
+ * `RtspAudioNoTrackError`. Re-probing is the caller's explicit decision, never
98
+ * a silent retry loop against a recorder.
99
+ *
100
+ * ── RESTARTS RE-ARM, AT STARTUP AS WELL AS AT RUNTIME. Any other failure
101
+ * (dropped TCP, recorder reboot, network blip) is transient. A RUNNING session
102
+ * is retried with exponential backoff capped at `maxRestartDelayMs` and NEVER
103
+ * permanently retires the feed while the provider is open. An OPENING session
104
+ * gets `openValidationAttempts` tries (default 4, mirroring
105
+ * `RTSPCameraProvider`) — because a supervisor that only covers the running
106
+ * case leaves the hole exactly where an unattended 24/7 connector is most
107
+ * likely to fall in it: a recorder that is merely slow or rebooting at boot
108
+ * would otherwise cost that feed its audio for the LIFE OF THE PROCESS. That is deliberate and incident-derived from the other direction:
109
+ * on the Ember fleet `shouldGiveUp` retired a camera permanently after a fixed
110
+ * 411 s and NOTHING re-armed it — `onCameraStartFailed` was telemetry-only, no
111
+ * config push restarted the analyzer, and `setMaxRetries` had zero call sites,
112
+ * so 7,359 escalations became permanent silence
113
+ * (docs/runbooks/ember-camera-health-taxonomy.md). A capped-backoff retry that
114
+ * never gives up IS the re-arm; the cap is what keeps it from being a hammer.
115
+ *
116
+ * ── SECRET HYGIENE, INHERITED. RTSP URLs carry passwords. Exactly as
117
+ * `RTSPCameraProvider` does, the URL is written to a 0600 ffconcat file and
118
+ * only the temp path reaches argv, so a password never appears in `ps` output;
119
+ * stderr is scrubbed through `sanitizeStreamUrlForLog` before it can reach a
120
+ * log line.
121
+ *
122
+ * ── NO CACHED CAPABILITY BOOLEAN, ON PURPOSE. The obvious addition here is a
123
+ * `cap_audio` flag set once at startup. Do not add one. On the Android DOOH
124
+ * fleet `cap_audio_classification` is `false` FLEET-WIDE — including on devices
125
+ * shipping live YAMNet classifications — because `detectCapabilities()` read a
126
+ * synchronous "still probing" value, the async probe resolved later, and
127
+ * NOTHING ever re-wrote the flag. It is published to DSPs in that state
128
+ * (docs/runbooks/audio-sensing-substrate.md). Audio capability here is
129
+ * genuinely asynchronous for the same reason — whether a stream carries audio
130
+ * is only knowable after ffmpeg has answered — so `getStats()` DERIVES every
131
+ * field live on each call (`running`, `noAudioTrack`, `buffered`,
132
+ * `lastPcmAtMs`) and there is no stored boolean that can outlive its truth. If
133
+ * a caller ever does need a flag, it must be recomputed from these, never
134
+ * latched at boot.
135
+ *
136
+ * ── LAYERING. This package is TRANSPORT. It knows nothing about onsets,
137
+ * motion or models — `AudioOnsetDetector` and the gate wiring live in
138
+ * `@trillboards/edge-sdk`, which is also the only package that may depend on
139
+ * both. `onPcm()` is the seam: this file produces a continuous mono Float32
140
+ * stream, and the SDK decides what it means.
141
+ */
142
+ /** Admission was refused: this recorder already runs its allowed audio sessions. */
143
+ class RtspAudioAdmissionError extends Error {
144
+ constructor(sourceKey, limit) {
145
+ super(`RTSP audio session refused: recorder ${sourceKey} already runs ${limit} audio session(s). ` +
146
+ 'Audio is supplementary; this feed continues without it.');
147
+ this.code = 'RTSP_AUDIO_SESSION_LIMIT';
148
+ this.name = 'RtspAudioAdmissionError';
149
+ }
150
+ }
151
+ exports.RtspAudioAdmissionError = RtspAudioAdmissionError;
152
+ /** The stream carries no audio track. Permanent for this URL until re-probed. */
153
+ class RtspAudioNoTrackError extends Error {
154
+ constructor(url) {
155
+ super(`RTSP stream has no audio track: ${(0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(url)}`);
156
+ this.code = 'RTSP_AUDIO_NO_TRACK';
157
+ this.name = 'RtspAudioNoTrackError';
158
+ }
159
+ }
160
+ exports.RtspAudioNoTrackError = RtspAudioNoTrackError;
161
+ /** ffmpeg's answer when `-map 0:a` matches nothing, across versions. */
162
+ const NO_AUDIO_STREAM_RE = /(stream map '0:a[^']*' matches no streams|does not contain any stream|audio stream not found|output file #0 does not contain any stream)/i;
163
+ const DEFAULT_SAMPLE_RATE = 16000;
164
+ const DEFAULT_BUFFER_SECONDS = 30;
165
+ const DEFAULT_MAX_AUDIO_SESSIONS_PER_SOURCE = 1;
166
+ const DEFAULT_TIMEOUT_US = 12000000;
167
+ const DEFAULT_RESTART_DELAY_MS = 1000;
168
+ const DEFAULT_MAX_RESTART_DELAY_MS = 60000;
169
+ /** Transient startup misses tolerated before open() gives up, as the camera path does. */
170
+ const DEFAULT_OPEN_VALIDATION_ATTEMPTS = 4;
171
+ /** stderr kept per session for diagnosis; bounded so a chatty feed cannot grow it. */
172
+ const STDERR_LIMIT = 8000;
173
+ /**
174
+ * Recorder-scoped admission for LONG-LIVED audio sessions. Deliberately a
175
+ * different pool from `CaptureAdmission`: same key, separate budget, and
176
+ * `tryAcquire` only — there is no `acquire()` because this lane never queues.
177
+ */
178
+ class AudioSessionAdmission {
179
+ constructor(limit) {
180
+ this.active = 0;
181
+ this.limit = limit;
182
+ }
183
+ /** Tighten only, matching CaptureAdmission: the most cautious caller wins. */
184
+ tightenLimit(limit) {
185
+ this.limit = Math.min(this.limit, limit);
186
+ }
187
+ getLimit() {
188
+ return this.limit;
189
+ }
190
+ getActive() {
191
+ return this.active;
192
+ }
193
+ tryAcquire() {
194
+ if (this.active >= this.limit)
195
+ return null;
196
+ this.active += 1;
197
+ let released = false;
198
+ return () => {
199
+ if (released)
200
+ return;
201
+ released = true;
202
+ this.active = Math.max(0, this.active - 1);
203
+ };
204
+ }
205
+ }
206
+ const audioAdmissionBySource = new Map();
207
+ function audioAdmissionFor(streamUrl, limit) {
208
+ const key = (0, RTSPCameraProvider_1.captureSourceKey)(streamUrl);
209
+ if (!key)
210
+ return null;
211
+ const existing = audioAdmissionBySource.get(key);
212
+ if (existing) {
213
+ existing.tightenLimit(limit);
214
+ return existing;
215
+ }
216
+ const admission = new AudioSessionAdmission(limit);
217
+ audioAdmissionBySource.set(key, admission);
218
+ return admission;
219
+ }
220
+ /** Test seam: forget every recorder's audio budget. */
221
+ function __resetAudioAdmissionForTests() {
222
+ audioAdmissionBySource.clear();
223
+ }
224
+ exports.__resetAudioAdmissionForTests = __resetAudioAdmissionForTests;
225
+ /** Live audio-lane occupancy for a recorder, for diagnostics. */
226
+ function audioSessionStatsFor(streamUrl) {
227
+ const key = (0, RTSPCameraProvider_1.captureSourceKey)(streamUrl);
228
+ if (!key)
229
+ return null;
230
+ const admission = audioAdmissionBySource.get(key);
231
+ if (!admission)
232
+ return null;
233
+ return { key, active: admission.getActive(), limit: admission.getLimit() };
234
+ }
235
+ exports.audioSessionStatsFor = audioSessionStatsFor;
236
+ /**
237
+ * One instance per audio-carrying feed. Implements the SAME `AudioProvider`
238
+ * interface as the Linux/Windows/web providers, so `AudienceSensingService`
239
+ * consumes it unchanged — but the pull (`getAudioChunk`) reads from the ring
240
+ * that the long-lived session is continuously filling, rather than spawning a
241
+ * process per call the way a microphone provider does.
242
+ */
243
+ class RTSPAudioProvider {
244
+ constructor(config) {
245
+ this.ringWrite = 0;
246
+ this.ringFilled = 0;
247
+ this.opened = false;
248
+ this.proc = null;
249
+ this.releaseAdmission = null;
250
+ this.restartTimer = null;
251
+ /** While true, `open()` owns retries and the supervisor must not schedule any. */
252
+ this.startingUp = false;
253
+ this.cleanupInput = null;
254
+ /** Odd trailing byte carried between stdout chunks so samples are never torn. */
255
+ this.pendingByte = null;
256
+ this.listeners = [];
257
+ this.totalSamples = 0;
258
+ this.sessionStarts = 0;
259
+ this.restarts = 0;
260
+ this.noAudioTrack = false;
261
+ this.lastErrorMessage = null;
262
+ this.lastPcmAtMs = null;
263
+ if (!config?.rtspUrl)
264
+ throw new Error('RTSPAudioProvider requires an rtspUrl');
265
+ this.rtspUrl = config.rtspUrl;
266
+ this.sampleRate = config.sampleRate ?? DEFAULT_SAMPLE_RATE;
267
+ const bufferSeconds = config.bufferSeconds ?? DEFAULT_BUFFER_SECONDS;
268
+ this.capacity = Math.max(this.sampleRate, Math.round(this.sampleRate * bufferSeconds));
269
+ this.ring = new Float32Array(this.capacity);
270
+ this.maxAudioSessionsPerSource = Math.max(1, Math.trunc(config.maxAudioSessionsPerSource ?? DEFAULT_MAX_AUDIO_SESSIONS_PER_SOURCE));
271
+ this.transport = config.transport ?? 'tcp';
272
+ this.timeoutUs = config.timeoutUs ?? DEFAULT_TIMEOUT_US;
273
+ this.ffmpegPath = config.ffmpegPath ?? 'ffmpeg';
274
+ this.ffmpegMajorVersion = config.ffmpegMajorVersion ?? 6;
275
+ this.openValidationAttempts = Math.max(1, Math.trunc(config.openValidationAttempts ?? DEFAULT_OPEN_VALIDATION_ATTEMPTS));
276
+ this.restartDelayMs = Math.max(0, config.restartDelayMs ?? DEFAULT_RESTART_DELAY_MS);
277
+ this.maxRestartDelayMs = Math.max(this.restartDelayMs, config.maxRestartDelayMs ?? DEFAULT_MAX_RESTART_DELAY_MS);
278
+ this.currentRestartDelay = this.restartDelayMs;
279
+ this.spawnFn = config.spawnFn ?? child_process_1.spawn;
280
+ this.now = config.now ?? Date.now;
281
+ this.onLog = config.onLog;
282
+ }
283
+ getSampleRate() {
284
+ return this.sampleRate;
285
+ }
286
+ isOpen() {
287
+ return this.opened;
288
+ }
289
+ getStats() {
290
+ return {
291
+ opened: this.opened,
292
+ running: this.proc !== null,
293
+ buffered: this.ringFilled,
294
+ capacity: this.capacity,
295
+ totalSamples: this.totalSamples,
296
+ sessionStarts: this.sessionStarts,
297
+ restarts: this.restarts,
298
+ noAudioTrack: this.noAudioTrack,
299
+ lastErrorMessage: this.lastErrorMessage,
300
+ lastPcmAtMs: this.lastPcmAtMs,
301
+ };
302
+ }
303
+ /**
304
+ * Subscribe to the continuous stream. Returns an unsubscribe function.
305
+ * This is the seam the SDK's onset detector attaches to; `getAudioChunk`
306
+ * remains the pull-based `AudioProvider` contract for everything else.
307
+ */
308
+ onPcm(listener) {
309
+ this.listeners.push(listener);
310
+ return () => {
311
+ this.listeners = this.listeners.filter((l) => l !== listener);
312
+ };
313
+ }
314
+ /**
315
+ * Take a recorder audio slot and start the session. Rejects with
316
+ * `RtspAudioAdmissionError` when the recorder's audio lane is full, and with
317
+ * `RtspAudioNoTrackError` when the stream turns out to carry no audio — both
318
+ * of which a caller should treat as "this feed has no audio", never as a
319
+ * camera fault.
320
+ */
321
+ async open() {
322
+ if (this.opened)
323
+ return;
324
+ const admission = audioAdmissionFor(this.rtspUrl, this.maxAudioSessionsPerSource);
325
+ if (admission) {
326
+ const release = admission.tryAcquire();
327
+ if (!release) {
328
+ throw new RtspAudioAdmissionError((0, RTSPCameraProvider_1.captureSourceKey)(this.rtspUrl) ?? 'unknown', admission.getLimit());
329
+ }
330
+ this.releaseAdmission = release;
331
+ }
332
+ this.opened = true;
333
+ this.noAudioTrack = false;
334
+ this.currentRestartDelay = this.restartDelayMs;
335
+ this.startingUp = true;
336
+ let lastErr;
337
+ try {
338
+ for (let attempt = 1; attempt <= this.openValidationAttempts; attempt++) {
339
+ try {
340
+ await this.startSession();
341
+ return;
342
+ }
343
+ catch (err) {
344
+ lastErr = err;
345
+ // A stream with no audio track is settled — never retried.
346
+ if (err instanceof RtspAudioNoTrackError)
347
+ break;
348
+ this.stopProcess();
349
+ if (attempt < this.openValidationAttempts && this.restartDelayMs > 0) {
350
+ await new Promise((resolve) => setTimeout(resolve, this.restartDelayMs));
351
+ }
352
+ if (!this.opened)
353
+ break; // closed underneath us
354
+ }
355
+ }
356
+ }
357
+ finally {
358
+ this.startingUp = false;
359
+ }
360
+ // Startup failed for good — give the slot back immediately so an
361
+ // audio-carrying camera on the same recorder can use it.
362
+ this.opened = false;
363
+ this.stopProcess();
364
+ this.releaseSlot();
365
+ throw lastErr instanceof Error ? lastErr : new Error(String(lastErr ?? 'RTSP audio open failed'));
366
+ }
367
+ /**
368
+ * Most recent `durationMs` of audio from the ring. Returns whatever is
369
+ * available when the buffer holds less — a short read is a normal startup
370
+ * condition, not an error, and throwing here would make a supplementary
371
+ * signal able to break a caller.
372
+ */
373
+ async getAudioChunk(durationMs) {
374
+ if (!this.opened)
375
+ throw new Error('Audio not opened. Call open() first.');
376
+ const want = Math.max(0, Math.round((this.sampleRate * durationMs) / 1000));
377
+ return this.readMostRecent(Math.min(want, this.ringFilled));
378
+ }
379
+ /** Everything currently buffered, oldest first. */
380
+ drain() {
381
+ return this.readMostRecent(this.ringFilled);
382
+ }
383
+ async close() {
384
+ this.opened = false;
385
+ if (this.restartTimer) {
386
+ clearTimeout(this.restartTimer);
387
+ this.restartTimer = null;
388
+ }
389
+ this.stopProcess();
390
+ this.releaseSlot();
391
+ this.listeners = [];
392
+ }
393
+ // ── internals ────────────────────────────────────────────────────────────
394
+ releaseSlot() {
395
+ if (this.releaseAdmission) {
396
+ this.releaseAdmission();
397
+ this.releaseAdmission = null;
398
+ }
399
+ }
400
+ readMostRecent(count) {
401
+ const n = Math.min(count, this.ringFilled);
402
+ const out = new Float32Array(n);
403
+ if (n === 0)
404
+ return out;
405
+ // The newest sample sits just behind ringWrite.
406
+ let start = this.ringWrite - n;
407
+ while (start < 0)
408
+ start += this.capacity;
409
+ for (let i = 0; i < n; i++) {
410
+ out[i] = this.ring[(start + i) % this.capacity];
411
+ }
412
+ return out;
413
+ }
414
+ appendSamples(samples) {
415
+ for (let i = 0; i < samples.length; i++) {
416
+ this.ring[this.ringWrite] = samples[i];
417
+ this.ringWrite = (this.ringWrite + 1) % this.capacity;
418
+ }
419
+ this.ringFilled = Math.min(this.capacity, this.ringFilled + samples.length);
420
+ this.totalSamples += samples.length;
421
+ }
422
+ /**
423
+ * ffmpeg args for a continuous mono PCM pull. The URL goes into a 0600
424
+ * ffconcat file exactly as the camera path does, so it never reaches argv.
425
+ */
426
+ buildInputArgs() {
427
+ const isRtsp = /^rtsps?:\/\//i.test(this.rtspUrl);
428
+ if (!isRtsp) {
429
+ return { args: ['-i', this.rtspUrl], cleanup: () => undefined };
430
+ }
431
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trillboards-rtsp-audio-'));
432
+ const file = path.join(dir, 'input.ffconcat');
433
+ const timeoutOpt = this.ffmpegMajorVersion >= 5 ? 'timeout' : 'stimeout';
434
+ fs.writeFileSync(file, [
435
+ 'ffconcat version 1.0',
436
+ `file '${(0, RTSPCameraProvider_1.escapeFfconcatValue)(this.rtspUrl)}'`,
437
+ `option rtsp_transport ${this.transport}`,
438
+ `option ${timeoutOpt} ${this.timeoutUs}`,
439
+ '',
440
+ ].join('\n'), { mode: 0o600 });
441
+ try {
442
+ fs.chmodSync(file, 0o600);
443
+ }
444
+ catch {
445
+ /* best-effort on platforms with ACL semantics */
446
+ }
447
+ return {
448
+ args: ['-protocol_whitelist', 'file,crypto,tcp,tls,rtp,rtsp,udp,http,https', '-safe', '0', '-f', 'concat', '-i', file],
449
+ cleanup: () => {
450
+ try {
451
+ fs.unlinkSync(file);
452
+ }
453
+ catch {
454
+ /* already gone */
455
+ }
456
+ try {
457
+ fs.rmdirSync(dir);
458
+ }
459
+ catch {
460
+ /* best-effort */
461
+ }
462
+ },
463
+ };
464
+ }
465
+ buildArgs() {
466
+ const input = this.buildInputArgs();
467
+ return {
468
+ args: [
469
+ '-nostdin',
470
+ ...input.args,
471
+ '-vn',
472
+ '-map', '0:a:0',
473
+ '-ac', '1',
474
+ '-ar', String(this.sampleRate),
475
+ '-f', 's16le',
476
+ 'pipe:1',
477
+ ],
478
+ cleanup: input.cleanup,
479
+ };
480
+ }
481
+ /**
482
+ * Start one ffmpeg session. Resolves once the process is spawned AND has
483
+ * survived long enough to rule out the "no audio track" classification —
484
+ * ffmpeg reports that within milliseconds, before any PCM flows, so waiting
485
+ * for the FIRST of (first PCM | early exit) settles it without a timer.
486
+ */
487
+ startSession() {
488
+ return new Promise((resolve, reject) => {
489
+ const { args, cleanup } = this.buildArgs();
490
+ this.cleanupInput = cleanup;
491
+ this.sessionStarts++;
492
+ let proc;
493
+ try {
494
+ proc = this.spawnFn(this.ffmpegPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
495
+ }
496
+ catch (err) {
497
+ cleanup();
498
+ this.cleanupInput = null;
499
+ reject(err instanceof Error ? err : new Error(String(err)));
500
+ return;
501
+ }
502
+ this.proc = proc;
503
+ this.pendingByte = null;
504
+ let stderr = '';
505
+ let settled = false;
506
+ const settle = (fn) => {
507
+ if (settled)
508
+ return;
509
+ settled = true;
510
+ fn();
511
+ };
512
+ proc.stdout?.on('data', (chunk) => {
513
+ this.consumePcm(chunk);
514
+ // First PCM proves the stream has audio and the session is healthy.
515
+ this.currentRestartDelay = this.restartDelayMs;
516
+ settle(resolve);
517
+ });
518
+ proc.stderr?.on('data', (chunk) => {
519
+ if (stderr.length < STDERR_LIMIT)
520
+ stderr += chunk.toString();
521
+ });
522
+ proc.on('error', (err) => {
523
+ this.lastErrorMessage = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err.message);
524
+ settle(() => reject(err));
525
+ this.handleSessionEnd(stderr);
526
+ });
527
+ proc.on('close', () => {
528
+ const summary = (0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr);
529
+ if (NO_AUDIO_STREAM_RE.test(stderr)) {
530
+ this.noAudioTrack = true;
531
+ this.lastErrorMessage = summary;
532
+ settle(() => reject(new RtspAudioNoTrackError(this.rtspUrl)));
533
+ this.handleSessionEnd(stderr);
534
+ return;
535
+ }
536
+ this.lastErrorMessage = summary;
537
+ settle(() => reject(new Error(`RTSP audio session ended during startup: ${summary}`)));
538
+ this.handleSessionEnd(stderr);
539
+ });
540
+ });
541
+ }
542
+ /** s16le → Float32, carrying an odd trailing byte between chunks. */
543
+ consumePcm(chunk) {
544
+ let buf = chunk;
545
+ if (this.pendingByte) {
546
+ buf = Buffer.concat([this.pendingByte, chunk]);
547
+ this.pendingByte = null;
548
+ }
549
+ const usable = buf.length - (buf.length % 2);
550
+ if (usable < buf.length)
551
+ this.pendingByte = buf.subarray(usable);
552
+ if (usable === 0)
553
+ return;
554
+ const samples = new Float32Array(usable / 2);
555
+ for (let i = 0; i < samples.length; i++) {
556
+ samples[i] = buf.readInt16LE(i * 2) / 32768;
557
+ }
558
+ this.appendSamples(samples);
559
+ const at = this.now();
560
+ this.lastPcmAtMs = at;
561
+ for (const listener of this.listeners) {
562
+ try {
563
+ listener(samples, at);
564
+ }
565
+ catch (err) {
566
+ this.log('warn', `audio listener threw: ${err?.message ?? String(err)}`);
567
+ }
568
+ }
569
+ }
570
+ stopProcess() {
571
+ const proc = this.proc;
572
+ this.proc = null;
573
+ if (proc) {
574
+ try {
575
+ proc.kill('SIGTERM');
576
+ }
577
+ catch {
578
+ /* already gone */
579
+ }
580
+ // Bounded escalation: an ffmpeg wedged on a half-open RTSP socket ignores
581
+ // SIGTERM, and a connector that leaks one child per restart is the
582
+ // 28-children incident wearing a different hat.
583
+ const timer = setTimeout(() => {
584
+ try {
585
+ proc.kill('SIGKILL');
586
+ }
587
+ catch {
588
+ /* already gone */
589
+ }
590
+ }, 2000);
591
+ if (typeof timer.unref === 'function')
592
+ timer.unref();
593
+ }
594
+ if (this.cleanupInput) {
595
+ this.cleanupInput();
596
+ this.cleanupInput = null;
597
+ }
598
+ }
599
+ /**
600
+ * A session ended. If the provider is still open and the stream is not known
601
+ * to be audio-less, schedule a restart with capped exponential backoff. This
602
+ * loop is what re-arms the feed and it is never allowed to give up — see the
603
+ * header on the Ember permanent-retirement failure.
604
+ */
605
+ handleSessionEnd(stderr) {
606
+ if (this.cleanupInput) {
607
+ this.cleanupInput();
608
+ this.cleanupInput = null;
609
+ }
610
+ this.proc = null;
611
+ if (!this.opened)
612
+ return;
613
+ if (this.noAudioTrack) {
614
+ // Never hold a recorder's audio slot for a stream that has no audio.
615
+ this.opened = false;
616
+ this.releaseSlot();
617
+ this.log('info', `RTSP audio: no audio track, releasing recorder slot (${(0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr, 200)})`);
618
+ return;
619
+ }
620
+ if (this.startingUp)
621
+ return; // open() owns the retry loop during startup
622
+ if (this.restartTimer)
623
+ return;
624
+ const delay = this.currentRestartDelay;
625
+ this.currentRestartDelay = Math.min(this.maxRestartDelayMs, Math.max(1, this.currentRestartDelay * 2));
626
+ this.restarts++;
627
+ this.log('warn', `RTSP audio session ended, restarting in ${delay}ms`);
628
+ this.restartTimer = setTimeout(() => {
629
+ this.restartTimer = null;
630
+ if (!this.opened)
631
+ return;
632
+ this.startSession().catch((err) => {
633
+ this.lastErrorMessage = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err?.message ?? String(err));
634
+ });
635
+ }, delay);
636
+ if (typeof this.restartTimer.unref === 'function')
637
+ this.restartTimer.unref();
638
+ }
639
+ log(level, message) {
640
+ this.onLog?.(level, (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(message));
641
+ }
642
+ }
643
+ exports.RTSPAudioProvider = RTSPAudioProvider;
644
+ //# sourceMapping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