@trillboards/edge-platform-rtsp 0.2.23 → 0.2.24

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.
@@ -23,7 +23,7 @@ var __importStar = (this && this.__importStar) || function (mod) {
23
23
  return result;
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.probeMainStream = exports.FramecrcPacketReader = exports.buildMainStreamProbeOutputArgs = exports.MainStreamRingOutput = exports.MainStreamSession = exports.buildMainStreamInputArgs = exports.__resetMainStreamAdmissionForTests = exports.mainStreamSessionStatsFor = exports.acquireMainStreamSlot = exports.MAIN_STREAM_WORKDIR_PREFIX = exports.MAIN_STREAM_CLOCK_WINDOW_MS = exports.MAIN_STREAM_STARTUP_TIMEOUT_MS = exports.MAIN_STREAM_HEALTHY_RUN_MS = exports.MAIN_STREAM_RESTART_MAX_MS = exports.MAIN_STREAM_RESTART_BASE_MS = exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE = void 0;
26
+ exports.probeMainStream = exports.FramecrcPacketReader = exports.buildMainStreamProbeOutputArgs = exports.MainStreamRingOutput = exports.MainStreamSession = exports.buildMainStreamInputArgs = exports.__resetMainStreamAdmissionForTests = exports.mainStreamSessionStatsFor = exports.acquireMainStreamSlot = exports.getMainStreamSessionsPerSource = exports.setMainStreamSessionsPerSource = exports.MAIN_STREAM_WORKDIR_PREFIX = exports.MAIN_STREAM_CLOCK_WINDOW_MS = exports.MAIN_STREAM_GRACEFUL_STOP_MS = exports.MAIN_STREAM_STARTUP_TIMEOUT_MS = exports.MAIN_STREAM_HEALTHY_RUN_MS = exports.MAIN_STREAM_RESTART_MAX_MS = exports.MAIN_STREAM_RESTART_BASE_MS = exports.MAX_MAIN_STREAM_SESSIONS_PER_SOURCE = exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE = void 0;
27
27
  const child_process_1 = require("child_process");
28
28
  const events_1 = require("events");
29
29
  const fs = __importStar(require("fs"));
@@ -67,7 +67,12 @@ const ffmpegStderr_1 = require("./ffmpegStderr");
67
67
  *
68
68
  * Main-stream sessions — the probe and the recorder alike — are admitted from
69
69
  * their OWN lane per physical recorder (`captureSourceKey`: host:port), capped
70
- * at `DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE` (1). The substream lanes
70
+ * by one box-wide knob, `setMainStreamSessionsPerSource` (the sensing profile's
71
+ * `video.mainSessionsPerRecorder`; `DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE`,
72
+ * 1, until a profile says otherwise). A 32-channel NVR is ONE host:port, so the
73
+ * knob is what lets a second camera's main stream (a face-zone output beside a
74
+ * ring recording) run at all. A raise wakes every session waiting for a slot; a
75
+ * lower stops the newest sessions first until each recorder fits. The substream lanes
71
76
  * (`CaptureAdmission`, the persistent-session lane) are untouched by a probe,
72
77
  * which is the shape `RTSPAudioProvider` took for the same reason: a long-lived
73
78
  * pull must never take a slot the frame path counts on. A RECORDING session
@@ -88,12 +93,36 @@ const ffmpegStderr_1 = require("./ffmpegStderr");
88
93
  * over the last minute (`MAIN_STREAM_CLOCK_WINDOW_MS`) is the least-delayed
89
94
  * report, and following it lets the anchor track a camera clock that drifts
90
95
  * against the PC's over a session that runs for days.
96
+ *
97
+ * ── GPU DECODE, ONLY FOR AN OUTPUT THAT DECODES ───────────────────────────
98
+ *
99
+ * An output that decodes the main stream (`decodes`: the face zone, which
100
+ * filters and encodes it) is the session's only per-frame CPU cost: Texas cam
101
+ * 1's 2880x1616 HEVC at 20.6 fps costs 0.26 cores to decode in software. A
102
+ * session carrying one decodes on the GPU (`-hwaccel d3d11va`, before the input,
103
+ * so it binds to the decoder: a stream copy opens none, and the ring's bytes do
104
+ * not move) when this host's GPU decode probe decoded the main stream's codec
105
+ * there: plan v7 W8's probe (`hardwareDecodeProbeFor`), read once it has settled
106
+ * and never started here (`settledHardwareDecodeProbe`). ffmpeg names the codec
107
+ * on the first session, which decodes in software; once it runs, a session that
108
+ * may decode on the GPU restarts onto it once. That restart, like every one
109
+ * `refresh` makes, asks ffmpeg to quit (`q` on stdin, `closeLive`): the ring
110
+ * segment in progress is closed and kept, and the GPU session starts as the
111
+ * software one exits, so the recording loses only the reconnect and the wait for
112
+ * a keyframe. GPU decode that fails falls back
113
+ * to software for the rest of this session's life: inside the running ffmpeg
114
+ * (`Failed setup for format d3d11`: it goes on, recording and all, and is never
115
+ * restarted for it), or by ending a session (a failure ffmpeg names, or a GPU
116
+ * session that never delivered), whose replacement starts at once, in software,
117
+ * with the slots it held.
91
118
  */
92
119
  // ---------------------------------------------------------------------------
93
120
  // Constants
94
121
  // ---------------------------------------------------------------------------
95
- /** Main-stream sessions (probe or recorder) one connector holds per recorder host:port. */
122
+ /** Main-stream sessions (probe or recorder) one connector holds per recorder host:port until the knob says otherwise. */
96
123
  exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE = 1;
124
+ /** The most the box-wide knob can ask for per recorder (the API clamps `video.mainSessionsPerRecorder` to the same). */
125
+ exports.MAX_MAIN_STREAM_SESSIONS_PER_SOURCE = 8;
97
126
  /** First restart delay after a session ends; doubles to the max. */
98
127
  exports.MAIN_STREAM_RESTART_BASE_MS = 10000;
99
128
  /** Ceiling on the restart delay: at most one retry an hour against a fault that persists. */
@@ -102,6 +131,8 @@ exports.MAIN_STREAM_RESTART_MAX_MS = 3600000;
102
131
  exports.MAIN_STREAM_HEALTHY_RUN_MS = 60000;
103
132
  /** A session whose output has not started this long after spawn is killed (and counted). */
104
133
  exports.MAIN_STREAM_STARTUP_TIMEOUT_MS = 30000;
134
+ /** A restarting session asked to quit (`q`) that has not exited this long after is killed. */
135
+ exports.MAIN_STREAM_GRACEFUL_STOP_MS = 4000;
105
136
  /** The window the clock's minimum is taken over. */
106
137
  exports.MAIN_STREAM_CLOCK_WINDOW_MS = 60000;
107
138
  /** Session work directories of the main-stream recorder: never the substream's `rec-`. */
@@ -113,56 +144,128 @@ const DEFAULT_TIMEOUT_US = 10000000;
113
144
  const CLOSE_FUTURE_TOLERANCE_MS = 1000;
114
145
  /** ffmpeg's -progress keys: kept out of the stderr buffer so the last error stays readable. */
115
146
  const PROGRESS_LINE_RE = /^[a-z0-9_]+=/;
116
- // ---------------------------------------------------------------------------
117
- // Admission: the main-stream lane, one per recorder
118
- // ---------------------------------------------------------------------------
147
+ /**
148
+ * ffmpeg's words when GPU decode did not work: the fallback to software inside a
149
+ * running ffmpeg (`Failed setup for format d3d11: hwaccel initialisation returned
150
+ * error`, after `Failed to create D3D11VA video decoder`: the look session's own
151
+ * three, `RTSPStreamCameraProvider`'s capture stderr) and the device failures that
152
+ * end the session (`Device setup failed for decoder` in ffmpeg 6, `Hardware device
153
+ * setup failed for decoder` in 7, after `Failed to create Direct3D device`).
154
+ */
155
+ const HW_DECODE_FAILURE_RE = /(Failed setup for format d3d11[^\n]*|hwaccel initiali[sz]ation returned error[^\n]*|Failed to (?:create|get) (?:D3D11|decoder)[^\n]*|device setup failed for decoder[^\n]*|Failed to create Direct3D device[^\n]*)/i;
119
156
  class MainStreamLane {
120
157
  constructor(limit) {
121
- this.active = 0;
158
+ /** Who holds a slot, oldest first: a lower limit sheds from the end. */
159
+ this.holders = [];
122
160
  this.limit = limit;
123
161
  }
124
- tightenLimit(limit) {
125
- this.limit = Math.min(this.limit, limit);
162
+ /**
163
+ * Raise or lower the cap. A raise admits nothing by itself (each waiting
164
+ * session is woken to ask again); a lower sheds the newest holders that can
165
+ * be shed, one by one, until the lane fits.
166
+ */
167
+ setLimit(limit) {
168
+ this.limit = limit;
169
+ for (const holder of this.holders.filter((h) => h.shed).reverse()) {
170
+ if (this.holders.length <= this.limit)
171
+ break;
172
+ this.drop(holder);
173
+ try {
174
+ holder.shed();
175
+ }
176
+ catch {
177
+ /* a session's shed handler can never break the lane */
178
+ }
179
+ }
126
180
  }
127
181
  getActive() {
128
- return this.active;
182
+ return this.holders.length;
129
183
  }
130
184
  getLimit() {
131
185
  return this.limit;
132
186
  }
133
- tryAcquire() {
134
- if (this.active >= this.limit)
187
+ tryAcquire(shed) {
188
+ if (this.holders.length >= this.limit)
135
189
  return null;
136
- this.active += 1;
137
- let released = false;
138
- return () => {
139
- if (released)
140
- return;
141
- released = true;
142
- this.active = Math.max(0, this.active - 1);
143
- };
190
+ const holder = { released: false, ...(shed ? { shed } : {}) };
191
+ this.holders.push(holder);
192
+ return () => this.drop(holder);
193
+ }
194
+ drop(holder) {
195
+ if (holder.released)
196
+ return;
197
+ holder.released = true;
198
+ const index = this.holders.indexOf(holder);
199
+ if (index >= 0)
200
+ this.holders.splice(index, 1);
144
201
  }
145
202
  }
146
203
  const mainLaneBySource = new Map();
204
+ /** The box-wide knob: main-stream sessions per recorder host:port. */
205
+ let mainSessionsPerSource = exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE;
206
+ /** Sessions the main-stream lane refused, waiting for room: a raise wakes them all. */
207
+ const mainLaneWaiters = new Set();
208
+ function boundedSessionsPerSource(limit) {
209
+ if (typeof limit !== 'number' || !Number.isFinite(limit))
210
+ return null;
211
+ return Math.min(exports.MAX_MAIN_STREAM_SESSIONS_PER_SOURCE, Math.max(1, Math.trunc(limit)));
212
+ }
213
+ /**
214
+ * The box-wide knob (the sensing profile's `video.mainSessionsPerRecorder`, the
215
+ * same on every camera): how many main-stream sessions this connector holds per
216
+ * recorder host:port, applied to every recorder's lane now and to each lane
217
+ * created later. A raise wakes every session waiting for a slot, so it asks
218
+ * again at once instead of at its next retry; a lower stops the newest sessions
219
+ * first until each recorder fits (a probe is never stopped: it ends on its own).
220
+ * Bounded to 1..MAX_MAIN_STREAM_SESSIONS_PER_SOURCE; anything but a number
221
+ * leaves it as it is. Returns the cap in force.
222
+ */
223
+ function setMainStreamSessionsPerSource(limit) {
224
+ const bounded = boundedSessionsPerSource(limit);
225
+ if (bounded === null || bounded === mainSessionsPerSource)
226
+ return mainSessionsPerSource;
227
+ const raised = bounded > mainSessionsPerSource;
228
+ mainSessionsPerSource = bounded;
229
+ for (const lane of mainLaneBySource.values())
230
+ lane.setLimit(bounded);
231
+ if (raised) {
232
+ for (const wake of [...mainLaneWaiters]) {
233
+ try {
234
+ wake();
235
+ }
236
+ catch {
237
+ /* one waiter cannot keep the others asleep */
238
+ }
239
+ }
240
+ }
241
+ return bounded;
242
+ }
243
+ exports.setMainStreamSessionsPerSource = setMainStreamSessionsPerSource;
244
+ /** The box-wide main-stream sessions per recorder now in force. */
245
+ function getMainStreamSessionsPerSource() {
246
+ return mainSessionsPerSource;
247
+ }
248
+ exports.getMainStreamSessionsPerSource = getMainStreamSessionsPerSource;
147
249
  /**
148
250
  * One main-stream session slot on the recorder this URL names, or null when the
149
- * connector already holds as many as `limit` there (or the URL names no
150
- * recorder). Never queues. Release it exactly once.
251
+ * connector already holds as many as the box-wide knob allows there (or as many
252
+ * as `limit`, a caller's own tighter cap), or the URL names no recorder. Never
253
+ * queues. Release it exactly once. `shed` is called (after the slot is taken
254
+ * back) when a lower knob stops this holder; a probe passes none.
151
255
  */
152
- function acquireMainStreamSlot(streamUrl, limit = exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE) {
256
+ function acquireMainStreamSlot(streamUrl, limit, shed) {
153
257
  const key = (0, RTSPCameraProvider_1.captureSourceKey)(streamUrl);
154
258
  if (!key)
155
259
  return null;
156
- const bounded = Math.max(1, Math.trunc(limit));
157
260
  let lane = mainLaneBySource.get(key);
158
261
  if (!lane) {
159
- lane = new MainStreamLane(bounded);
262
+ lane = new MainStreamLane(mainSessionsPerSource);
160
263
  mainLaneBySource.set(key, lane);
161
264
  }
162
- else {
163
- lane.tightenLimit(bounded);
164
- }
165
- return lane.tryAcquire();
265
+ const own = limit === undefined ? null : boundedSessionsPerSource(limit);
266
+ if (own !== null && lane.getActive() >= own)
267
+ return null;
268
+ return lane.tryAcquire(shed);
166
269
  }
167
270
  exports.acquireMainStreamSlot = acquireMainStreamSlot;
168
271
  /** Live main-stream occupancy for a recorder, for diagnostics. */
@@ -174,9 +277,11 @@ function mainStreamSessionStatsFor(streamUrl) {
174
277
  return lane ? { key, active: lane.getActive(), limit: lane.getLimit() } : null;
175
278
  }
176
279
  exports.mainStreamSessionStatsFor = mainStreamSessionStatsFor;
177
- /** Test seam: forget every recorder's main-stream lane. */
280
+ /** Test seam: forget every recorder's main-stream lane, its waiters and the knob. */
178
281
  function __resetMainStreamAdmissionForTests() {
179
282
  mainLaneBySource.clear();
283
+ mainLaneWaiters.clear();
284
+ mainSessionsPerSource = exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE;
180
285
  }
181
286
  exports.__resetMainStreamAdmissionForTests = __resetMainStreamAdmissionForTests;
182
287
  // ---------------------------------------------------------------------------
@@ -249,6 +354,10 @@ class MainStreamSession extends events_1.EventEmitter {
249
354
  this.clockSamples = [];
250
355
  this.mediaZeroWallMs = null;
251
356
  this.lastEnd = null;
357
+ /** Why GPU decode failed on this camera's main stream: every later session decodes in software. */
358
+ this.hwDecodeFailure = null;
359
+ /** Registered while the main-stream lane has no room for this session: a raised knob calls it. */
360
+ this.wakeForRoom = () => this.readmit();
252
361
  if (!config?.rtspUrl)
253
362
  throw new Error('rtspUrl is required for MainStreamSession');
254
363
  this.rtspUrl = config.rtspUrl;
@@ -256,12 +365,16 @@ class MainStreamSession extends events_1.EventEmitter {
256
365
  this.timeoutUs = config.timeoutUs ?? DEFAULT_TIMEOUT_US;
257
366
  this.ffmpegPath = config.ffmpegPath ?? 'ffmpeg';
258
367
  this.ffmpegMajorVersion = config.ffmpegMajorVersion ?? 6;
259
- this.maxSessionsPerSource = Math.max(1, Math.trunc(config.maxSessionsPerSource ?? exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE));
368
+ this.maxSessionsPerSource = config.maxSessionsPerSource === undefined
369
+ ? undefined
370
+ : Math.max(1, Math.trunc(config.maxSessionsPerSource));
260
371
  this.sharePersistentLane = config.sharePersistentLane !== false;
261
372
  this.restartDelayMs = Math.max(0, config.restartDelayMs ?? exports.MAIN_STREAM_RESTART_BASE_MS);
262
373
  this.maxRestartDelayMs = Math.max(this.restartDelayMs, config.maxRestartDelayMs ?? exports.MAIN_STREAM_RESTART_MAX_MS);
263
374
  this.healthyRunMs = Math.max(0, config.healthyRunMs ?? exports.MAIN_STREAM_HEALTHY_RUN_MS);
264
375
  this.startupTimeoutMs = Math.max(1, config.startupTimeoutMs ?? exports.MAIN_STREAM_STARTUP_TIMEOUT_MS);
376
+ this.gracefulStopMs = Math.max(1, config.gracefulStopMs ?? exports.MAIN_STREAM_GRACEFUL_STOP_MS);
377
+ this.hardwareDecode = config.hardwareDecode ?? RTSPCameraProvider_1.settledHardwareDecodeProbe;
265
378
  this.spawnFn = config.spawnFn ?? child_process_1.spawn;
266
379
  this.now = config.now ?? Date.now;
267
380
  this.onLog = config.onLog;
@@ -286,10 +399,24 @@ class MainStreamSession extends events_1.EventEmitter {
286
399
  this.wanted = true;
287
400
  this.ensureSession();
288
401
  }
402
+ /**
403
+ * A session waiting for room (`session_limit`) asks for its slots again now,
404
+ * instead of at its next retry: a raised knob, or the owner's periodic check.
405
+ * The restart delay starts over, because this connector's own cap refusing it
406
+ * says nothing about the recorder. Any other state is left alone.
407
+ */
408
+ readmit() {
409
+ if (this.state !== 'session_limit' || !this.wanted || this.live)
410
+ return;
411
+ this.clearRetry();
412
+ this.currentDelayMs = this.restartDelayMs;
413
+ this.ensureSession();
414
+ }
289
415
  /**
290
416
  * Re-read every output's arguments. A running session whose argv no longer
291
417
  * matches restarts once (its replacement starts as it exits); one that no
292
- * output wants stops and gives its slots back.
418
+ * output wants stops and gives its slots back. Either way it is asked to quit
419
+ * (`closeLive`), so the ring segment it was writing is closed and kept.
293
420
  */
294
421
  refresh() {
295
422
  if (this.state === 'stopped')
@@ -302,14 +429,19 @@ class MainStreamSession extends events_1.EventEmitter {
302
429
  if (live.superseded || live.stopped)
303
430
  return;
304
431
  const plan = this.plan();
305
- if (plan && plan.key === live.planKey)
432
+ // The same arguments keep it, unless it may now decode on the GPU. Never restarted to go
433
+ // back to software: a GPU decode that failed in a running ffmpeg decodes in software there.
434
+ if (plan && plan.key === live.planKey && (live.hwDecode || !plan.hwDecode))
306
435
  return;
436
+ if (plan && plan.key === live.planKey)
437
+ this.log('info', 'main stream session restarting to decode on the GPU (d3d11va)');
307
438
  live.superseded = true;
308
- this.killLive(live);
439
+ this.closeLive(live);
309
440
  }
310
441
  /** Stop for good: kill the session and release every slot. */
311
442
  async stop() {
312
443
  this.wanted = false;
444
+ mainLaneWaiters.delete(this.wakeForRoom);
313
445
  this.clearRetry();
314
446
  const live = this.live;
315
447
  this.setState('stopped');
@@ -336,6 +468,7 @@ class MainStreamSession extends events_1.EventEmitter {
336
468
  outputs: [...this.outputs.keys()],
337
469
  nextRetryAtMs: this.retryAtMs,
338
470
  lastEnd: this.lastEnd,
471
+ gpuDecode: { active: this.live !== null && this.live.hwDecode && !this.live.hwFailed, failure: this.hwDecodeFailure },
339
472
  };
340
473
  }
341
474
  getState() {
@@ -356,7 +489,10 @@ class MainStreamSession extends events_1.EventEmitter {
356
489
  },
357
490
  };
358
491
  }
359
- /** The outputs that want the next session, in add order, and their joined plan key; null when none does. */
492
+ /**
493
+ * The outputs that want the next session, in add order, their joined plan key and
494
+ * whether it may decode on the GPU; null when none does.
495
+ */
360
496
  plan() {
361
497
  const ctx = this.context(this.sessions + 1);
362
498
  const keys = [];
@@ -383,23 +519,55 @@ class MainStreamSession extends events_1.EventEmitter {
383
519
  keys.push(`${output.name}:${key}`);
384
520
  outputs.push(output);
385
521
  }
386
- return outputs.length ? { key: keys.join('|'), outputs } : null;
522
+ return outputs.length ? { key: keys.join('|'), outputs, hwDecode: this.planHwDecode(outputs) } : null;
523
+ }
524
+ /**
525
+ * `-hwaccel d3d11va` for a session carrying these outputs? Only when one of them
526
+ * decodes, ffmpeg has named the main stream's codec (a first session decodes in
527
+ * software), this host's probe decoded that codec on the GPU, and GPU decode has
528
+ * not failed on this camera.
529
+ */
530
+ planHwDecode(outputs) {
531
+ if (this.hwDecodeFailure !== null || !outputs.some((output) => output.decodes === true))
532
+ return false;
533
+ const codec = this.input?.codec ?? null;
534
+ if (codec !== 'h264' && codec !== 'hevc')
535
+ return false;
536
+ let probe = null;
537
+ try {
538
+ probe = this.hardwareDecode(this.ffmpegPath);
539
+ }
540
+ catch {
541
+ probe = null;
542
+ }
543
+ return probe !== null && probe.state === 'passed' && probe[codec] === true;
544
+ }
545
+ /** GPU decode failed on this camera: logged once, and every later session decodes in software. */
546
+ failHwDecode(reason) {
547
+ if (this.hwDecodeFailure !== null)
548
+ return;
549
+ this.hwDecodeFailure = reason;
550
+ this.log('warn', `main stream GPU decode failed; decoding in software from now on: ${reason}`);
387
551
  }
388
552
  ensureSession() {
389
553
  if (!this.wanted || this.live || this.retryTimer || this.state === 'stopped')
390
554
  return;
391
555
  const plan = this.plan();
392
556
  if (!plan) {
557
+ mainLaneWaiters.delete(this.wakeForRoom);
393
558
  this.releaseSlots();
394
559
  this.setState('idle');
395
560
  return;
396
561
  }
397
562
  if (!this.releaseSlot) {
398
- this.releaseSlot = acquireMainStreamSlot(this.rtspUrl, this.maxSessionsPerSource);
563
+ this.releaseSlot = acquireMainStreamSlot(this.rtspUrl, this.maxSessionsPerSource, () => this.shedFromMainLane());
399
564
  if (!this.releaseSlot) {
400
- this.refused('this connector already holds the recorder\'s main-stream session');
565
+ if ((0, RTSPCameraProvider_1.captureSourceKey)(this.rtspUrl) !== null)
566
+ mainLaneWaiters.add(this.wakeForRoom);
567
+ this.refused(`this connector already holds ${getMainStreamSessionsPerSource()} main-stream session(s) on the recorder`);
401
568
  return;
402
569
  }
570
+ mainLaneWaiters.delete(this.wakeForRoom);
403
571
  }
404
572
  if (this.sharePersistentLane && !this.laneTicket) {
405
573
  this.laneTicket = (0, RTSPStreamCameraProvider_1.acquirePersistentSessionSlot)(this.rtspUrl, () => this.shed(), 0);
@@ -443,19 +611,24 @@ class MainStreamSession extends events_1.EventEmitter {
443
611
  this.scheduleRetry(`main stream input file could not be written: ${errorText(err)}`);
444
612
  return;
445
613
  }
614
+ // The outputs that prepared their arguments decide it: see the header.
615
+ const hwDecode = this.planHwDecode(outputs);
446
616
  const args = [
447
- '-hide_banner', '-nostdin', '-nostats', '-loglevel', 'info',
617
+ // No -nostdin: stdin is the pipe a restart asks the session to quit on (`q`, `closeLive`).
618
+ '-hide_banner', '-nostats', '-loglevel', 'info',
448
619
  // Progress on stderr every half second: the session's only clock (see the header).
449
620
  '-progress', 'pipe:2',
450
621
  // Before the input, so it binds to a decoder, should an output ever ask for one.
451
622
  '-threads', '1',
623
+ // A decoder option, before the input: a stream copy opens no decoder, so the ring's bytes do not move.
624
+ ...(hwDecode ? ['-hwaccel', 'd3d11va'] : []),
452
625
  ...input.args,
453
626
  ...outputArgs,
454
627
  ];
455
628
  const wantsStdout = outputs.some((output) => output.writesStdout === true);
456
629
  let proc;
457
630
  try {
458
- proc = this.spawnFn(this.ffmpegPath, args, { stdio: ['ignore', wantsStdout ? 'pipe' : 'ignore', 'pipe'], windowsHide: true });
631
+ proc = this.spawnFn(this.ffmpegPath, args, { stdio: ['pipe', wantsStdout ? 'pipe' : 'ignore', 'pipe'], windowsHide: true });
459
632
  }
460
633
  catch (err) {
461
634
  input.cleanup();
@@ -478,8 +651,12 @@ class MainStreamSession extends events_1.EventEmitter {
478
651
  stderr: new ffmpegStderr_1.BoundedSessionStderr(),
479
652
  progressPartial: '',
480
653
  lastOutTimeUs: 0,
654
+ hwDecode,
655
+ hwFailed: false,
481
656
  };
482
657
  this.live = live;
658
+ if (hwDecode)
659
+ this.log('info', 'main stream session decoding on the GPU (d3d11va)');
483
660
  this.clockSamples = [];
484
661
  this.mediaZeroWallMs = null;
485
662
  this.setState('starting');
@@ -512,6 +689,8 @@ class MainStreamSession extends events_1.EventEmitter {
512
689
  });
513
690
  }
514
691
  proc.stderr?.on('data', (chunk) => this.onStderr(live, chunk.toString()));
692
+ // A write after ffmpeg exited (EPIPE) is not this session's failure: its exit already says what happened.
693
+ proc.stdin?.on('error', () => undefined);
515
694
  proc.on('error', (err) => {
516
695
  live.stderr.append(`\n${err.message}\n`);
517
696
  this.onEnd(live, null);
@@ -544,6 +723,13 @@ class MainStreamSession extends events_1.EventEmitter {
544
723
  if (kept.length) {
545
724
  const block = kept.join('\n') + '\n';
546
725
  live.stderr.append(block);
726
+ if (live.hwDecode && !live.hwFailed) {
727
+ const failed = HW_DECODE_FAILURE_RE.exec(block);
728
+ if (failed) {
729
+ live.hwFailed = true;
730
+ this.failHwDecode((0, RTSPCameraProvider_1.summarizeFfmpegStderr)(failed[1], 200));
731
+ }
732
+ }
547
733
  if (!live.probe.done) {
548
734
  const info = live.probe.push(block);
549
735
  if (info && this.live === live) {
@@ -594,6 +780,9 @@ class MainStreamSession extends events_1.EventEmitter {
594
780
  this.log('warn', `main stream output ${output.name} tick threw: ${errorText(err)}`);
595
781
  }
596
782
  }
783
+ // The probe settled, or ffmpeg named the codec, while this session runs: onto the GPU once it delivers.
784
+ if (this.live === live && live.progressed && !live.hwDecode && this.planHwDecode(live.outputs))
785
+ this.refresh();
597
786
  }
598
787
  onEnd(live, code) {
599
788
  if (live.ended)
@@ -648,6 +837,17 @@ class MainStreamSession extends events_1.EventEmitter {
648
837
  }
649
838
  if (live.stopped)
650
839
  return; // a shed: its handler scheduled the retry
840
+ if (live.hwDecode && (live.hwFailed || !live.progressed)) {
841
+ // GPU decode did not work here (ffmpeg said so, or the session never delivered): the next
842
+ // session decodes in software NOW, with the slots this one held, so the recording it carries
843
+ // does not wait out a restart delay. Once: no later session of this camera asks for the GPU.
844
+ if (!live.hwFailed) {
845
+ this.failHwDecode(`the session ended (exit ${code}) before it delivered: ${(0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr, 160)}`);
846
+ }
847
+ this.restarts += 1;
848
+ this.ensureSession();
849
+ return;
850
+ }
651
851
  if (live.progressed && ranMs >= this.healthyRunMs)
652
852
  this.currentDelayMs = this.restartDelayMs;
653
853
  this.releaseSlots();
@@ -664,6 +864,20 @@ class MainStreamSession extends events_1.EventEmitter {
664
864
  this.releaseSlots();
665
865
  this.refused('the recorder\'s persistent-session lane shed the main stream to make room for a feed');
666
866
  }
867
+ /** A lower knob took this session's main-stream slot back (the lane already dropped it). */
868
+ shedFromMainLane() {
869
+ this.releaseSlot = null;
870
+ const live = this.live;
871
+ if (live && !live.ended) {
872
+ live.stopped = true;
873
+ this.killLive(live);
874
+ }
875
+ this.releaseSlots();
876
+ if (!this.wanted || this.state === 'stopped')
877
+ return;
878
+ mainLaneWaiters.add(this.wakeForRoom);
879
+ this.refused(`the recorder's main-stream sessions were lowered to ${getMainStreamSessionsPerSource()}; this one stopped (the newest go first)`);
880
+ }
667
881
  refused(reason) {
668
882
  this.log('warn', `main stream not started: ${reason}`);
669
883
  this.scheduleRetry(null, 'session_limit');
@@ -693,6 +907,36 @@ class MainStreamSession extends events_1.EventEmitter {
693
907
  this.retryTimer = null;
694
908
  this.retryAtMs = null;
695
909
  }
910
+ /**
911
+ * Ask a restarting session to quit the way ffmpeg finishes its files: `q` on
912
+ * its stdin. ffmpeg closes the ring segment it was writing and lists it, so the
913
+ * ring keeps the seconds up to the restart (the GPU switch, a new output, a
914
+ * changed recording). A kill cannot do that on a store PC: Node's SIGTERM is
915
+ * TerminateProcess on Windows, and the segment in progress (up to the ring's
916
+ * 10 s) was lost at every restart. Bounded: a session that has not exited
917
+ * `gracefulStopMs` later (an ffmpeg wedged on its socket) is killed.
918
+ */
919
+ closeLive(live) {
920
+ const stdin = live.proc.stdin;
921
+ if (!stdin || stdin.destroyed || !stdin.writable) {
922
+ this.killLive(live);
923
+ return;
924
+ }
925
+ try {
926
+ stdin.write('q');
927
+ stdin.end();
928
+ }
929
+ catch {
930
+ this.killLive(live);
931
+ return;
932
+ }
933
+ const t = setTimeout(() => {
934
+ if (!live.ended)
935
+ this.killLive(live);
936
+ }, this.gracefulStopMs);
937
+ if (typeof t.unref === 'function')
938
+ t.unref();
939
+ }
696
940
  killLive(live) {
697
941
  try {
698
942
  live.proc.kill('SIGTERM');