@trillboards/edge-platform-rtsp 0.2.14 → 0.2.16

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.RTSPStreamCameraProvider = exports.volumeFreeBytes = exports.buildSegmentOutputArgs = exports.readVideoStartSec = exports.videoStartSecFromMoov = exports.audioPlanFor = exports.describeAudioSource = exports.aacBitrateFor = exports.InputStreamProbe = exports.parseInputAudioStreamLine = exports.parseInputVideoStreamLine = exports.parseSegmentListCsv = exports.AUDIO_SUSPEND_MAX_MS = exports.AUDIO_SUSPEND_BASE_MS = exports.AUDIO_START_DEADLINE_MS = exports.RING_FREE_FRACTION = exports.SEGMENT_SUSPEND_MAX_MS = exports.SEGMENT_SUSPEND_BASE_MS = exports.CLOSED_SEGMENTS_DIRNAME = exports.RECORDABLE_CODECS = exports.streamSessionStatsFor = exports.__resetStreamAdmissionForTests = exports.FrameRing = exports.MjpegFrameSplitter = exports.jpegFrameEnd = exports.JPEG_MALFORMED = exports.JPEG_NEED_MORE = exports.DEFAULT_MAX_STREAM_SESSIONS_PER_SOURCE = exports.RtspStreamStaleError = exports.RtspStreamAdmissionError = void 0;
26
+ exports.RTSPStreamCameraProvider = exports.volumeFreeBytes = exports.buildSegmentOutputArgs = exports.readVideoStartSec = exports.videoStartSecFromMoov = exports.audioPlanFor = exports.describeAudioSource = exports.aacBitrateFor = exports.InputStreamProbe = exports.parseInputAudioStreamLine = exports.parseInputVideoStreamLine = exports.parseSegmentListCsv = exports.AUDIO_SUSPEND_MAX_MS = exports.AUDIO_SUSPEND_BASE_MS = exports.AUDIO_START_DEADLINE_MS = exports.RETAKE_BACKOFF_MAX_MS = exports.RETAKE_BACKOFF_BASE_MS = exports.RING_RESYNC_MS = exports.RING_FREE_FRACTION = exports.SEGMENT_SUSPEND_MAX_MS = exports.SEGMENT_SUSPEND_BASE_MS = exports.CLOSED_SEGMENTS_DIRNAME = exports.RECORDABLE_CODECS = exports.streamSessionStatsFor = exports.__resetStreamAdmissionForTests = exports.FrameRing = exports.MjpegFrameSplitter = exports.jpegFrameEnd = exports.JPEG_MALFORMED = exports.JPEG_NEED_MORE = exports.DEFAULT_MAX_STREAM_SESSIONS_PER_SOURCE = exports.RtspStreamStaleError = exports.RtspStreamAdmissionError = 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"));
@@ -613,37 +613,26 @@ class FrameRing {
613
613
  }
614
614
  }
615
615
  exports.FrameRing = FrameRing;
616
- // ---------------------------------------------------------------------------
617
- // Per-recorder admission for LONG-LIVED video sessions
618
- // ---------------------------------------------------------------------------
619
- /**
620
- * Deliberately a different pool from `CaptureAdmission` AND from
621
- * `AudioSessionAdmission`: same key, three separate budgets. `tryAcquire` only
622
- * — this lane never queues.
623
- *
624
- * ── THE LIMIT IS LEARNED FROM THE RECORDER, NOT DECLARED ──────────────────
625
- *
626
- * `maxStreamSessionsPerSource` is a POLICY CEILING on our own occupancy. The
627
- * recorder's ceiling is a property of the recorder, it is not discoverable
628
- * before you reach it, and it is not close to constant across recorders —
629
- * measured 2026-08-19 with `scripts/measure-rtsp-session-ceiling.mjs`:
630
- *
631
- * Happytime ONVIF/RTSP Server V8.1 4 (fixed RUA pool; no config key)
632
- * Nx Media Server 6.1.2.42921 >=160 (never refused)
633
- * mediamtx unbounded (which is why the original
634
- * validation could not see any
635
- * of this)
636
- *
637
- * So `learnCeiling` records what the recorder actually did the first time it
638
- * refused, and every later feed is refused by US — instantly, with no recorder
639
- * traffic — instead of by the recorder.
640
- */
641
616
  class StreamSessionAdmission {
642
617
  constructor(limit) {
643
618
  this.active = 0;
644
619
  this.learnedCeiling = null;
645
- /** Live holders, oldest first. Shedding pops the NEWEST — see `learnCeiling`. */
620
+ /**
621
+ * Live holders in admission order. Shedding takes the LOWEST priority, and
622
+ * among equals the NEWEST — see `learnCeiling` and `lowestHolder`.
623
+ */
646
624
  this.holders = [];
625
+ /**
626
+ * Feeds the lane refused (`session_limit`). Only a waiter ranked above 0 is
627
+ * ever offered a slot here — an ordinary feed keeps the reconnect path it
628
+ * always had — and it is offered one only when a slot is free or a holder
629
+ * ranks below it.
630
+ */
631
+ this.waiters = [];
632
+ this.seq = 0;
633
+ this.offerScheduled = false;
634
+ /** One retake at a time: a slot offered is a slot spoken for until it settles. */
635
+ this.retakeInFlight = false;
647
636
  this.limit = limit;
648
637
  }
649
638
  /** Tighten only, matching the other two lanes: the most cautious caller wins. */
@@ -726,24 +715,55 @@ class StreamSessionAdmission {
726
715
  */
727
716
  shedOverQuota() {
728
717
  while (this.active > this.limit && this.holders.length > 0) {
729
- const holder = this.holders.pop();
730
- // `shed` releases through the same closure `tryAcquire` handed out, so
731
- // `active` cannot drift no matter which side initiates the release.
732
- try {
733
- holder.shed();
734
- }
735
- catch {
736
- /* a provider that cannot shed must not wedge the pool */
718
+ this.shedHolder(this.lowestHolder());
719
+ }
720
+ }
721
+ /**
722
+ * The holder to give up first: the LOWEST priority, and among equals the
723
+ * NEWEST. With every holder at 0 this is exactly the newest-first rule
724
+ * above; a camera with an enabled alert (priority 1) keeps its session over
725
+ * every camera without one, because only a session camera can buffer the
726
+ * video an alert window is cut from.
727
+ */
728
+ lowestHolder() {
729
+ let pick = null;
730
+ for (const holder of this.holders) {
731
+ if (!pick || holder.priority < pick.priority || (holder.priority === pick.priority && holder.seq > pick.seq)) {
732
+ pick = holder;
737
733
  }
738
- holder.release();
739
734
  }
735
+ return pick;
740
736
  }
741
- tryAcquire(shed = () => undefined) {
742
- if (this.active >= this.limit)
743
- return null;
737
+ shedHolder(holder) {
738
+ // `shed` releases through the same closure `tryAcquire` handed out, so
739
+ // `active` cannot drift no matter which side initiates the release.
740
+ try {
741
+ holder.shed();
742
+ }
743
+ catch {
744
+ /* a provider that cannot shed must not wedge the pool */
745
+ }
746
+ holder.release();
747
+ }
748
+ /**
749
+ * Take a slot at `priority`. A full lane admits the caller only by shedding
750
+ * a holder ranked strictly BELOW it (lowest, then newest) — equals keep the
751
+ * first-come rule, so ordinary feeds behave exactly as before.
752
+ */
753
+ tryAcquire(shed = () => undefined, priority = 0) {
754
+ if (this.active >= this.limit) {
755
+ const victim = this.lowestHolder();
756
+ if (!victim || victim.priority >= priority)
757
+ return null;
758
+ this.shedHolder(victim);
759
+ if (this.active >= this.limit)
760
+ return null;
761
+ }
744
762
  this.active += 1;
745
763
  let released = false;
746
764
  const entry = {
765
+ priority,
766
+ seq: (this.seq += 1),
747
767
  shed,
748
768
  release: () => {
749
769
  if (released)
@@ -753,10 +773,93 @@ class StreamSessionAdmission {
753
773
  const i = this.holders.indexOf(entry);
754
774
  if (i >= 0)
755
775
  this.holders.splice(i, 1);
776
+ this.scheduleOffer();
756
777
  },
757
778
  };
758
779
  this.holders.push(entry);
759
- return entry.release;
780
+ return {
781
+ release: entry.release,
782
+ setPriority: (next) => {
783
+ if (released || next === entry.priority)
784
+ return;
785
+ entry.priority = next;
786
+ this.scheduleOffer();
787
+ },
788
+ };
789
+ }
790
+ /** Queue a refused feed. `retake` must call its `done` once the attempt settles. */
791
+ addWaiter(priority, retake) {
792
+ const waiter = { priority, seq: (this.seq += 1), retake };
793
+ this.waiters.push(waiter);
794
+ this.scheduleOffer();
795
+ return {
796
+ remove: () => {
797
+ const i = this.waiters.indexOf(waiter);
798
+ if (i >= 0)
799
+ this.waiters.splice(i, 1);
800
+ },
801
+ setPriority: (next) => {
802
+ if (next === waiter.priority)
803
+ return;
804
+ waiter.priority = next;
805
+ this.scheduleOffer();
806
+ },
807
+ };
808
+ }
809
+ getWaiting() {
810
+ return this.waiters.length;
811
+ }
812
+ /**
813
+ * Deferred and coalesced: a release or a re-rank can happen inside a
814
+ * provider's own close/shed path, and offering synchronously would re-enter
815
+ * it.
816
+ */
817
+ scheduleOffer() {
818
+ if (this.offerScheduled || this.waiters.length === 0)
819
+ return;
820
+ this.offerScheduled = true;
821
+ const timer = setImmediate(() => {
822
+ this.offerScheduled = false;
823
+ this.offerOnce();
824
+ });
825
+ if (typeof timer.unref === 'function')
826
+ timer.unref();
827
+ }
828
+ /** Offer one slot to the top waiter: a free one, or one a lower-ranked holder gives up. */
829
+ offerOnce() {
830
+ if (this.retakeInFlight)
831
+ return;
832
+ let top = null;
833
+ for (const waiter of this.waiters) {
834
+ if (!top || waiter.priority > top.priority || (waiter.priority === top.priority && waiter.seq < top.seq))
835
+ top = waiter;
836
+ }
837
+ if (!top || top.priority <= 0)
838
+ return;
839
+ if (this.active >= this.limit) {
840
+ const victim = this.lowestHolder();
841
+ if (!victim || victim.priority >= top.priority)
842
+ return;
843
+ // Nothing is shed here: the retake's own tryAcquire takes the victim's
844
+ // slot only after its checks pass, so a feed that is still pausing
845
+ // after a refusal never costs another feed its session.
846
+ }
847
+ this.waiters.splice(this.waiters.indexOf(top), 1);
848
+ this.retakeInFlight = true;
849
+ let settled = false;
850
+ const done = () => {
851
+ if (settled)
852
+ return;
853
+ settled = true;
854
+ this.retakeInFlight = false;
855
+ this.scheduleOffer();
856
+ };
857
+ try {
858
+ top.retake(done);
859
+ }
860
+ catch {
861
+ done();
862
+ }
760
863
  }
761
864
  }
762
865
  const streamAdmissionBySource = new Map();
@@ -794,12 +897,15 @@ function streamSessionStatsFor(streamUrl) {
794
897
  };
795
898
  }
796
899
  exports.streamSessionStatsFor = streamSessionStatsFor;
900
+ const SEGMENT_LABEL_RE = /^[a-z0-9_]{1,32}$/;
797
901
  /** Codecs `video_segment` holds. Anything else is not recorded. */
798
902
  exports.RECORDABLE_CODECS = ['h264', 'hevc'];
799
903
  /** Closed segments, beside their sidecars, under the feed's directory. */
800
904
  exports.CLOSED_SEGMENTS_DIRNAME = 'closed';
801
905
  /** Session work directories are `rec-<startMs>-<sessionNumber>`. */
802
906
  const SESSION_WORKDIR_PREFIX = 'rec-';
907
+ /** The session's recording label, written into its work directory at start. */
908
+ const SESSION_LABEL_FILE = 'label.json';
803
909
  /**
804
910
  * How often the segment list is read. ffmpeg writes a line the moment it
805
911
  * closes a segment, so this is the whole detection latency, and it is also
@@ -816,8 +922,17 @@ exports.SEGMENT_SUSPEND_MAX_MS = 3600000;
816
922
  * reads "Failed reading RTSP data" / "End of file" and matches none of these.
817
923
  */
818
924
  const SEGMENT_OUTPUT_FAILURE_RE = /(Failed to open segment[^\n]*|No space left on device|Read-only file system|Disk quota exceeded|Could not write header[^\n]*|Error (?:muxing|submitting|writing) (?:a )?packet[^\n]*)/i;
819
- /** The ring may hold at most this fraction of the volume's free bytes. */
925
+ /** The ring may hold at most this fraction of the volume's free bytes (unless the caller sets `maxBytes`). */
820
926
  exports.RING_FREE_FRACTION = 0.1;
927
+ /**
928
+ * How often the ring's in-memory index is rebuilt from disk. Between rebuilds
929
+ * every close updates it, so a ring of thousands of short segments costs one
930
+ * statfs and no directory listing per close.
931
+ */
932
+ exports.RING_RESYNC_MS = 10 * 60000;
933
+ /** First wait before a feed the recorder refused retakes a session; doubles to the max. */
934
+ exports.RETAKE_BACKOFF_BASE_MS = 60000;
935
+ exports.RETAKE_BACKOFF_MAX_MS = 3600000;
821
936
  /**
822
937
  * A session that maps audio and has written no segment file this long after
823
938
  * its first frame is stalled on a microphone that sends nothing. Measured: with
@@ -1291,11 +1406,19 @@ function normalizeSegmentRecording(cfg) {
1291
1406
  return null;
1292
1407
  if (!Number.isFinite(ringSeconds) || ringSeconds < 0)
1293
1408
  return null;
1409
+ const rawMax = cfg.maxBytes === undefined || cfg.maxBytes === null ? null : Number(cfg.maxBytes);
1410
+ if (rawMax !== null && (!Number.isFinite(rawMax) || rawMax < 0))
1411
+ return null;
1412
+ const label = cfg.label === undefined || cfg.label === null ? null : cfg.label;
1413
+ if (label !== null && (typeof label !== 'string' || !SEGMENT_LABEL_RE.test(label)))
1414
+ return null;
1294
1415
  return {
1295
1416
  dir: path.resolve(cfg.dir),
1296
1417
  segmentSeconds: Math.max(1, Math.trunc(segmentSeconds)),
1297
1418
  ringSeconds: Math.trunc(ringSeconds),
1298
1419
  enabled: cfg.enabled !== false,
1420
+ maxBytes: rawMax === null ? null : Math.floor(rawMax),
1421
+ label,
1299
1422
  };
1300
1423
  }
1301
1424
  function writeFileAtomic(file, body) {
@@ -1316,7 +1439,12 @@ function readSidecar(file) {
1316
1439
  const stream = raw.stream && typeof raw.stream === 'object' && typeof raw.stream.codec === 'string'
1317
1440
  ? raw.stream
1318
1441
  : null;
1319
- return { ...raw, stream };
1442
+ const { label, ...rest } = raw;
1443
+ return {
1444
+ ...rest,
1445
+ stream,
1446
+ ...(typeof label === 'string' && SEGMENT_LABEL_RE.test(label) ? { label } : {}),
1447
+ };
1320
1448
  }
1321
1449
  catch {
1322
1450
  return null;
@@ -1365,11 +1493,31 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1365
1493
  this.session = null;
1366
1494
  /** This recorder's persistent-session lane, for the learned ceiling. */
1367
1495
  this.admission = null;
1368
- this.releaseAdmission = null;
1496
+ this.admissionTicket = null;
1369
1497
  this.restartTimer = null;
1370
1498
  this.startingUp = false;
1371
1499
  // ── segment recording ────────────────────────────────────────────────────
1372
1500
  this.segmentConfig = null;
1501
+ /**
1502
+ * The ring's closed segments, oldest first: rebuilt from disk at most every
1503
+ * `RING_RESYNC_MS` and kept current by every move in between, so a ring of
1504
+ * thousands of 10-s segments is not re-listed and re-stat'ed at every close.
1505
+ * Files a consumer deleted since the last rebuild are dropped when the
1506
+ * eviction walk reaches them (ENOENT) and by the next rebuild.
1507
+ */
1508
+ this.ringIndex = null;
1509
+ /** 0 = an ordinary feed; higher holds its persistent session ahead of lower ones. */
1510
+ this.sessionPriority = 0;
1511
+ /** This feed's place in its recorder's queue for a session, while the lane refused it. */
1512
+ this.sessionWaiter = null;
1513
+ /** Earliest moment a refused retake may try again (capacity refusals back off). */
1514
+ this.retakeNotBeforeMs = 0;
1515
+ /** The pending rejoin after a refusal's pause (cleared by leaveSessionQueue). */
1516
+ this.retakeRejoinTimer = null;
1517
+ this.retakeBackoffMs = exports.RETAKE_BACKOFF_BASE_MS;
1518
+ /** A retake in flight: its token, so a close, a shed or a newer retake can disown it. */
1519
+ this.retake = null;
1520
+ this.retakeTokens = 0;
1373
1521
  /** The newest input description ffmpeg gave; decides the tag and the codec gate. */
1374
1522
  this.streamInfo = null;
1375
1523
  this.segmentsRecoveredFor = null;
@@ -1503,12 +1651,40 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1503
1651
  this.clearSegmentSuspension();
1504
1652
  }
1505
1653
  this.segmentConfig = normalized;
1654
+ // A lower byte cap (a buffer budget that shrank with the free space) is
1655
+ // enforced now, not at the next close. Reads the in-memory ring index:
1656
+ // no listing unless the index is due a rebuild.
1657
+ if (previous && previous.dir === normalized.dir && this.segmentsRecoveredFor === normalized.dir
1658
+ && (normalized.maxBytes ?? Infinity) < (previous.maxBytes ?? Infinity)) {
1659
+ this.enforceRing();
1660
+ }
1506
1661
  }
1507
1662
  if (this.opened && this.segmentConfig && this.segmentsRecoveredFor !== this.segmentConfig.dir) {
1508
1663
  this.recoverSegments();
1509
1664
  }
1510
1665
  this.reconcileRecording();
1511
1666
  }
1667
+ /**
1668
+ * Rank this feed for its recorder's persistent sessions. 0 is an ordinary
1669
+ * feed; the connector raises a camera with an enabled alert to 1, because
1670
+ * only a feed holding a persistent session records the local video an alert
1671
+ * window is cut from. When the recorder cannot serve every feed, a higher
1672
+ * rank keeps or TAKES a session from a lower one (lowest, then newest, gives
1673
+ * way), and a ranked feed the lane refused retakes one as soon as a slot is
1674
+ * free or a lower-ranked holder can give way. Equal ranks keep first come,
1675
+ * first served, so with every feed at 0 nothing changes.
1676
+ */
1677
+ setSessionPriority(priority) {
1678
+ const next = Number.isFinite(priority) ? Math.max(0, Math.trunc(priority)) : 0;
1679
+ if (next === this.sessionPriority)
1680
+ return;
1681
+ this.sessionPriority = next;
1682
+ this.admissionTicket?.setPriority(next);
1683
+ this.sessionWaiter?.setPriority(next);
1684
+ }
1685
+ getSessionPriority() {
1686
+ return this.sessionPriority;
1687
+ }
1512
1688
  // ── CameraProvider ───────────────────────────────────────────────────────
1513
1689
  /**
1514
1690
  * Take a recorder session slot and start streaming. NEVER throws because the
@@ -1541,6 +1717,9 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1541
1717
  // provider that degraded once and could never come back would be the Ember
1542
1718
  // permanent-retirement shape (see handleSessionEnd) at the capture layer.
1543
1719
  // Drop the old provider rather than leaking one per reconnect.
1720
+ // This open() decides admission afresh: a queued or running retake from
1721
+ // the previous degrade is disowned first.
1722
+ this.leaveSessionQueue();
1544
1723
  if (this.fallback) {
1545
1724
  const previous = this.fallback;
1546
1725
  this.fallback = null;
@@ -1563,14 +1742,15 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1563
1742
  if (admission) {
1564
1743
  // The shed callback is how a LEARNED ceiling reaches a session that was
1565
1744
  // admitted before we knew it. It must not throw and must not await: the
1566
- // pool calls it while it is reconciling occupancy.
1567
- const release = admission.tryAcquire(() => this.shedPersistentSession());
1568
- if (!release) {
1745
+ // pool calls it while it is reconciling occupancy. A ranked feed (an
1746
+ // alert camera) may take the slot of a lower-ranked holder here.
1747
+ const ticket = admission.tryAcquire(() => this.shedPersistentSession(), this.sessionPriority);
1748
+ if (!ticket) {
1569
1749
  this.lastErrorMessage = new RtspStreamAdmissionError((0, RTSPCameraProvider_1.captureSourceKey)(this.rtspUrl) ?? 'unknown', admission.getLimit()).message;
1570
1750
  await this.degradeTo('session_limit');
1571
1751
  return;
1572
1752
  }
1573
- this.releaseAdmission = release;
1753
+ this.admissionTicket = ticket;
1574
1754
  }
1575
1755
  this.opened = true;
1576
1756
  this.mode = 'persistent';
@@ -1661,9 +1841,22 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1661
1841
  * its failure rather than the generic not-opened message.
1662
1842
  */
1663
1843
  shedPersistentSession() {
1844
+ if (this.retake && this.opened && this.fallback) {
1845
+ // Shed mid-retake: the fallback never stopped serving, so abandon the
1846
+ // new session and queue again. The pool releases the ticket on return.
1847
+ this.retake = null;
1848
+ this.opened = false;
1849
+ this.startingUp = false;
1850
+ this.stopProcess();
1851
+ this.admissionTicket = null;
1852
+ this.joinSessionQueue();
1853
+ return;
1854
+ }
1664
1855
  if (!this.opened || this.fallback)
1665
1856
  return;
1666
1857
  this.opened = false;
1858
+ // The pool releases this ticket as soon as this returns.
1859
+ this.admissionTicket = null;
1667
1860
  if (this.restartTimer) {
1668
1861
  clearTimeout(this.restartTimer);
1669
1862
  this.restartTimer = null;
@@ -1735,6 +1928,9 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1735
1928
  this.openGeneration += 1;
1736
1929
  this.startingUp = false;
1737
1930
  this.opened = false;
1931
+ this.leaveSessionQueue();
1932
+ // A re-open rebuilds the ring index from disk once.
1933
+ this.ringIndex = null;
1738
1934
  if (this.restartTimer) {
1739
1935
  clearTimeout(this.restartTimer);
1740
1936
  this.restartTimer = null;
@@ -1807,6 +2003,10 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1807
2003
  // which is exactly what a connector sees today.
1808
2004
  this.fallback = fallback;
1809
2005
  this.fallbackOpenError = null;
2006
+ // Refused by our own lane, not by the camera: wait for a slot (a ranked
2007
+ // feed takes one when it frees or a lower-ranked holder can give way).
2008
+ if (reason === 'session_limit')
2009
+ this.joinSessionQueue();
1810
2010
  try {
1811
2011
  await fallback.open();
1812
2012
  if (generation !== this.openGeneration || this.fallback !== fallback) {
@@ -1833,10 +2033,145 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1833
2033
  }
1834
2034
  }
1835
2035
  releaseSlot() {
1836
- if (this.releaseAdmission) {
1837
- this.releaseAdmission();
1838
- this.releaseAdmission = null;
2036
+ if (this.admissionTicket) {
2037
+ this.admissionTicket.release();
2038
+ this.admissionTicket = null;
2039
+ }
2040
+ }
2041
+ // ── retaking a session the lane refused ────────────────────────────────────
2042
+ /**
2043
+ * Queue this feed for a session after the lane refused it (`session_limit`).
2044
+ * The lane offers a slot only to a waiter ranked above 0 (see
2045
+ * `StreamSessionAdmission.offerOnce`), so an ordinary feed keeps exactly the
2046
+ * reconnect path it always had; registering one costs nothing.
2047
+ */
2048
+ joinSessionQueue() {
2049
+ if (this.sessionWaiter || this.degradedReason !== 'session_limit' || !this.persistentRequested)
2050
+ return;
2051
+ // Pausing after a recorder refusal: queue once the pause is over, never
2052
+ // sooner, so an offer cannot reach a feed that would only decline it.
2053
+ if (this.now() < this.retakeNotBeforeMs) {
2054
+ this.rejoinSessionQueueAt(this.retakeNotBeforeMs);
2055
+ return;
2056
+ }
2057
+ const admission = streamAdmissionFor(this.rtspUrl, this.maxStreamSessionsPerSource);
2058
+ if (!admission)
2059
+ return;
2060
+ const generation = this.openGeneration;
2061
+ this.sessionWaiter = admission.addWaiter(this.sessionPriority, (done) => {
2062
+ this.sessionWaiter = null;
2063
+ if (generation !== this.openGeneration) {
2064
+ done();
2065
+ return;
2066
+ }
2067
+ this.retakeSession(admission, done);
2068
+ });
2069
+ }
2070
+ /** Join the queue at `atMs`; one pending rejoin per feed, owned by this open. */
2071
+ rejoinSessionQueueAt(atMs) {
2072
+ if (this.retakeRejoinTimer)
2073
+ clearTimeout(this.retakeRejoinTimer);
2074
+ const generation = this.openGeneration;
2075
+ this.retakeRejoinTimer = setTimeout(() => {
2076
+ this.retakeRejoinTimer = null;
2077
+ if (generation === this.openGeneration)
2078
+ this.joinSessionQueue();
2079
+ }, Math.max(0, atMs - this.now()));
2080
+ if (typeof this.retakeRejoinTimer.unref === 'function')
2081
+ this.retakeRejoinTimer.unref();
2082
+ }
2083
+ /** Disown any queued, pending or running retake: close(), a fresh open(), a shed. */
2084
+ leaveSessionQueue() {
2085
+ this.sessionWaiter?.remove();
2086
+ this.sessionWaiter = null;
2087
+ this.retake = null;
2088
+ if (this.retakeRejoinTimer) {
2089
+ clearTimeout(this.retakeRejoinTimer);
2090
+ this.retakeRejoinTimer = null;
2091
+ }
2092
+ }
2093
+ /**
2094
+ * Take a persistent session for a feed running the per-grab fallback,
2095
+ * WITHOUT a gap: the fallback answers every look until the new session's
2096
+ * first frame, then the session replaces it. A refusal by the recorder
2097
+ * teaches the lane its ceiling exactly as `open()` does and queues the feed
2098
+ * again after a doubling pause; any other failure leaves the feed on the
2099
+ * fallback, like any feed that could not hold a session.
2100
+ */
2101
+ retakeSession(admission, done) {
2102
+ const now = this.now();
2103
+ if (!this.fallback || this.opened || this.degradedReason !== 'session_limit' || this.retake) {
2104
+ done();
2105
+ return;
2106
+ }
2107
+ if (now < this.retakeNotBeforeMs) {
2108
+ // Too soon after a refusal: queue again once the pause is over.
2109
+ this.rejoinSessionQueueAt(this.retakeNotBeforeMs);
2110
+ done();
2111
+ return;
2112
+ }
2113
+ const ticket = admission.tryAcquire(() => this.shedPersistentSession(), this.sessionPriority);
2114
+ if (!ticket) {
2115
+ this.joinSessionQueue();
2116
+ done();
2117
+ return;
1839
2118
  }
2119
+ const generation = this.openGeneration;
2120
+ const token = (this.retakeTokens += 1);
2121
+ this.retake = { token };
2122
+ this.admissionTicket = ticket;
2123
+ this.admission = admission;
2124
+ this.opened = true;
2125
+ this.startingUp = true;
2126
+ this.currentRestartDelay = this.restartDelayMs;
2127
+ this.log('info', `RTSP persistent session retaken ahead of a lower-ranked feed (priority ${this.sessionPriority})`);
2128
+ const owned = () => generation === this.openGeneration && this.retake?.token === token;
2129
+ const outputFailuresBefore = this.segCounters.outputFailures;
2130
+ this.startSession().then(async () => {
2131
+ if (!owned())
2132
+ return; // closed, re-opened or shed meanwhile: they own the cleanup
2133
+ const previous = this.fallback;
2134
+ this.retake = null;
2135
+ this.fallback = null;
2136
+ this.fallbackOpenError = null;
2137
+ this.mode = 'persistent';
2138
+ this.degradedReason = null;
2139
+ this.lastErrorMessage = null;
2140
+ this.startingUp = false;
2141
+ this.retakeBackoffMs = exports.RETAKE_BACKOFF_BASE_MS;
2142
+ this.reconcileRecording();
2143
+ if (previous) {
2144
+ try {
2145
+ await previous.close();
2146
+ }
2147
+ catch {
2148
+ /* the session is already serving; a stuck fallback close cannot undo that */
2149
+ }
2150
+ }
2151
+ }, (err) => {
2152
+ if (!owned())
2153
+ return;
2154
+ this.retake = null;
2155
+ this.startingUp = false;
2156
+ this.opened = false;
2157
+ this.stopProcess();
2158
+ this.releaseSlot();
2159
+ const message = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err instanceof Error ? err.message : String(err));
2160
+ const recorderRefused = err instanceof RtspStreamStartupError && !err.inputAccepted && err.reason === 'ended';
2161
+ this.log('warn', `RTSP session retake failed; staying on per-grab capture: ${message}`);
2162
+ if (this.segCounters.outputFailures > outputFailuresBefore) {
2163
+ // The recording output failed the session, not the recorder: that
2164
+ // output is paused now, so the next attempt runs without it (open()
2165
+ // grants the same extra attempt).
2166
+ this.joinSessionQueue();
2167
+ }
2168
+ else if (recorderRefused) {
2169
+ admission.learnCeiling(admission.getActive(), message);
2170
+ this.retakeNotBeforeMs = this.now() + this.retakeBackoffMs;
2171
+ this.retakeBackoffMs = Math.min(exports.RETAKE_BACKOFF_MAX_MS, this.retakeBackoffMs * 2);
2172
+ this.rejoinSessionQueueAt(this.retakeNotBeforeMs);
2173
+ }
2174
+ }).finally(done);
1840
2175
  }
1841
2176
  /** The newest frame if it has not been served yet, else null. */
1842
2177
  takeFreshFrame() {
@@ -2235,6 +2570,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2235
2570
  // Present since ffmpeg 5; an older binary gets the bare segment_time.
2236
2571
  minSegDuration: this.ffmpegMajorVersion >= 5,
2237
2572
  audio: this.planAudio(),
2573
+ label: cfg.label,
2238
2574
  };
2239
2575
  if (this.segmentSuspension && this.now() < this.segmentSuspension.untilMs)
2240
2576
  return null;
@@ -2262,6 +2598,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2262
2598
  if (have.dir !== want.dir ||
2263
2599
  have.segmentSeconds !== want.segmentSeconds ||
2264
2600
  have.minSegDuration !== want.minSegDuration ||
2601
+ have.label !== want.label ||
2265
2602
  !sameAudioPlan(have.audio, want.audio)) {
2266
2603
  return false;
2267
2604
  }
@@ -2319,6 +2656,10 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2319
2656
  try {
2320
2657
  fs.mkdirSync(path.join(plan.dir, exports.CLOSED_SEGMENTS_DIRNAME), { recursive: true });
2321
2658
  fs.mkdirSync(workDir, { recursive: true });
2659
+ // The label is on disk before ffmpeg writes a byte, so a crash before the
2660
+ // first anchor still recovers every segment under its own label.
2661
+ if (plan.label)
2662
+ writeFileAtomic(path.join(workDir, SESSION_LABEL_FILE), JSON.stringify({ label: plan.label }));
2322
2663
  }
2323
2664
  catch (err) {
2324
2665
  // A directory we cannot create is the second output's failure, never the
@@ -2552,7 +2893,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2552
2893
  }
2553
2894
  const anchor = this.anchorFor(rec, entry, session.firstFrameAtMs, session.streamInfo);
2554
2895
  const captureStartMs = Math.round(anchor.wallMs + (entry.startSec - anchor.startSec) * 1000);
2555
- const moved = this.moveIntoRing(rec.plan.dir, src, path.basename(rec.workDir), entry, captureStartMs, size, session.streamInfo, false);
2896
+ const moved = this.moveIntoRing(rec.plan.dir, src, path.basename(rec.workDir), entry, captureStartMs, size, session.streamInfo, false, rec.plan.label);
2556
2897
  if (!moved)
2557
2898
  return 'retry';
2558
2899
  rec.closedCount += 1;
@@ -2614,7 +2955,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2614
2955
  if (!rec.anchor)
2615
2956
  return;
2616
2957
  try {
2617
- writeFileAtomic(path.join(rec.workDir, 'anchor.json'), JSON.stringify({ ...rec.anchor, stream }));
2958
+ writeFileAtomic(path.join(rec.workDir, 'anchor.json'), JSON.stringify({ ...rec.anchor, stream, ...(rec.plan.label ? { label: rec.plan.label } : {}) }));
2618
2959
  }
2619
2960
  catch {
2620
2961
  /* recovery falls back to the file's own last write */
@@ -2625,7 +2966,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2625
2966
  * when the move must be retried (Windows refuses to rename a file ffmpeg
2626
2967
  * still holds; the next poll asks again).
2627
2968
  */
2628
- moveIntoRing(dir, src, tag, entry, captureStartMs, bytes, stream, recovered) {
2969
+ moveIntoRing(dir, src, tag, entry, captureStartMs, bytes, stream, recovered, label) {
2629
2970
  const durationMs = Math.max(0, Math.round((entry.endSec - entry.startSec) * 1000));
2630
2971
  // Zero-padded capture start first, so a name sort is a time sort — the
2631
2972
  // ring evicts oldest-first by name.
@@ -2641,6 +2982,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2641
2982
  captureEndMs: captureStartMs + durationMs,
2642
2983
  bytes,
2643
2984
  stream,
2985
+ ...(label ? { label } : {}),
2644
2986
  };
2645
2987
  try {
2646
2988
  fs.mkdirSync(closedDir, { recursive: true });
@@ -2674,7 +3016,9 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2674
3016
  bytes,
2675
3017
  stream,
2676
3018
  recovered,
3019
+ label,
2677
3020
  };
3021
+ this.noteRingFile(dir, file, bytes);
2678
3022
  this.countSegment(segment);
2679
3023
  this.emitSegment(segment);
2680
3024
  return segment;
@@ -2870,6 +3214,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2870
3214
  bytes,
2871
3215
  stream: sidecar.stream,
2872
3216
  recovered: true,
3217
+ label: sidecar.label ?? null,
2873
3218
  };
2874
3219
  this.countSegment(segment);
2875
3220
  this.emitSegment(segment);
@@ -2901,6 +3246,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2901
3246
  const { entries } = parseSegmentListCsv(text);
2902
3247
  let anchor = null;
2903
3248
  let stream = null;
3249
+ let label = null;
2904
3250
  try {
2905
3251
  const raw = JSON.parse(fs.readFileSync(path.join(workDir, 'anchor.json'), 'utf8'));
2906
3252
  if (Number.isFinite(raw?.wallMs) && Number.isFinite(raw?.startSec)) {
@@ -2908,10 +3254,22 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2908
3254
  }
2909
3255
  if (raw?.stream && typeof raw.stream.codec === 'string')
2910
3256
  stream = raw.stream;
3257
+ if (typeof raw?.label === 'string' && SEGMENT_LABEL_RE.test(raw.label))
3258
+ label = raw.label;
2911
3259
  }
2912
3260
  catch {
2913
3261
  anchor = null;
2914
3262
  }
3263
+ if (label === null) {
3264
+ try {
3265
+ const raw = JSON.parse(fs.readFileSync(path.join(workDir, SESSION_LABEL_FILE), 'utf8'));
3266
+ if (typeof raw?.label === 'string' && SEGMENT_LABEL_RE.test(raw.label))
3267
+ label = raw.label;
3268
+ }
3269
+ catch {
3270
+ /* an unlabelled session, or one from before the label file */
3271
+ }
3272
+ }
2915
3273
  const tag = path.basename(workDir);
2916
3274
  let leftBehind = false;
2917
3275
  for (const entry of entries) {
@@ -2929,30 +3287,21 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2929
3287
  const captureStartMs = anchor
2930
3288
  ? Math.round(anchor.wallMs + (entry.startSec - anchor.startSec) * 1000)
2931
3289
  : Math.round(st.mtimeMs - (entry.endSec - entry.startSec) * 1000);
2932
- if (!this.moveIntoRing(dir, src, tag, entry, captureStartMs, st.size, stream, true))
3290
+ if (!this.moveIntoRing(dir, src, tag, entry, captureStartMs, st.size, stream, true, label))
2933
3291
  leftBehind = true;
2934
3292
  }
2935
3293
  if (!leftBehind)
2936
3294
  this.removeWorkDir(workDir, true);
2937
3295
  }
2938
- /**
2939
- * Hold the closed segments to min(ringSeconds x measured bytes/s, 10% of the
2940
- * volume's free bytes), deleting oldest first. A file the OS will not let us
2941
- * delete (Windows, mid-upload) is skipped, never waited on.
2942
- */
2943
- enforceRing() {
2944
- const cfg = this.segmentConfig;
2945
- if (!cfg)
2946
- return;
2947
- const closedDir = path.join(cfg.dir, exports.CLOSED_SEGMENTS_DIRNAME);
3296
+ /** List and stat the ring once; every close until the next rebuild updates the result in memory. */
3297
+ rebuildRingIndex(dir) {
3298
+ const closedDir = path.join(dir, exports.CLOSED_SEGMENTS_DIRNAME);
2948
3299
  let names;
2949
3300
  try {
2950
3301
  names = fs.readdirSync(closedDir).filter((n) => n.toLowerCase().endsWith('.mp4')).sort();
2951
3302
  }
2952
3303
  catch {
2953
- this.segCounters.ringSegments = 0;
2954
- this.segCounters.ringBytes = 0;
2955
- return;
3304
+ names = [];
2956
3305
  }
2957
3306
  const items = [];
2958
3307
  for (const name of names) {
@@ -2964,32 +3313,79 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2964
3313
  /* delivered and deleted under us */
2965
3314
  }
2966
3315
  }
3316
+ this.ringIndex = { dir, items, rebuiltAtMs: this.now() };
3317
+ return items;
3318
+ }
3319
+ /** A file just moved into `closed/`: keep the index in name (= capture time) order. */
3320
+ noteRingFile(dir, file, bytes) {
3321
+ const index = this.ringIndex;
3322
+ if (!index || index.dir !== dir)
3323
+ return;
3324
+ const items = index.items;
3325
+ if (!items.length || items[items.length - 1].file < file) {
3326
+ items.push({ file, bytes });
3327
+ return;
3328
+ }
3329
+ if (items.some((item) => item.file === file))
3330
+ return;
3331
+ const at = items.findIndex((item) => item.file > file);
3332
+ items.splice(at < 0 ? items.length : at, 0, { file, bytes });
3333
+ }
3334
+ /**
3335
+ * Hold the closed segments to min(ringSeconds x measured bytes/s, the cap),
3336
+ * deleting oldest first. The cap is the caller's `maxBytes` when it set one
3337
+ * (its share of a buffer sized across every feed on the volume), else 10% of
3338
+ * the volume's free bytes. A file the OS will not let us delete (Windows,
3339
+ * mid-upload) is skipped, never waited on; a file already gone (its consumer
3340
+ * delivered and deleted it) leaves the index without counting as evicted.
3341
+ */
3342
+ enforceRing() {
3343
+ const cfg = this.segmentConfig;
3344
+ if (!cfg)
3345
+ return;
3346
+ const index = this.ringIndex;
3347
+ const items = !index || index.dir !== cfg.dir || this.now() - index.rebuiltAtMs >= exports.RING_RESYNC_MS
3348
+ ? this.rebuildRingIndex(cfg.dir)
3349
+ : index.items;
2967
3350
  let total = items.reduce((n, item) => n + item.bytes, 0);
2968
- let remaining = items.length;
2969
3351
  const freeBytes = this.freeBytesFn(cfg.dir);
2970
3352
  const bytesPerSec = this.measuredBytesPerSec();
2971
3353
  const byRing = bytesPerSec === null ? null : Math.floor(cfg.ringSeconds * bytesPerSec);
2972
- const byFree = freeBytes === null ? null : Math.floor(exports.RING_FREE_FRACTION * freeBytes);
3354
+ const byFree = cfg.maxBytes !== null
3355
+ ? cfg.maxBytes
3356
+ : freeBytes === null ? null : Math.floor(exports.RING_FREE_FRACTION * freeBytes);
2973
3357
  const limit = byRing === null ? byFree : byFree === null ? byRing : Math.min(byRing, byFree);
2974
3358
  if (limit !== null) {
2975
- for (const item of items) {
2976
- if (total <= limit)
2977
- break;
3359
+ let i = 0;
3360
+ while (total > limit && i < items.length) {
3361
+ const item = items[i];
3362
+ const metaFile = item.file.replace(/\.mp4$/i, '.json');
2978
3363
  try {
2979
3364
  fs.unlinkSync(item.file);
2980
3365
  }
2981
- catch {
3366
+ catch (err) {
3367
+ if (err?.code === 'ENOENT') {
3368
+ total -= item.bytes;
3369
+ items.splice(i, 1);
3370
+ try {
3371
+ fs.unlinkSync(metaFile);
3372
+ }
3373
+ catch {
3374
+ /* its consumer took both */
3375
+ }
3376
+ continue;
3377
+ }
3378
+ i += 1;
2982
3379
  continue;
2983
3380
  }
2984
- const metaFile = item.file.replace(/\.mp4$/i, '.json');
2985
3381
  try {
2986
3382
  fs.unlinkSync(metaFile);
2987
3383
  }
2988
3384
  catch {
2989
3385
  /* best-effort */
2990
3386
  }
3387
+ items.splice(i, 1);
2991
3388
  total -= item.bytes;
2992
- remaining -= 1;
2993
3389
  this.segCounters.evicted += 1;
2994
3390
  this.segCounters.evictedBytes += item.bytes;
2995
3391
  try {
@@ -3000,7 +3396,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
3000
3396
  }
3001
3397
  }
3002
3398
  }
3003
- this.segCounters.ringSegments = remaining;
3399
+ this.segCounters.ringSegments = items.length;
3004
3400
  this.segCounters.ringBytes = total;
3005
3401
  this.segCounters.ringLimitBytes = limit;
3006
3402
  this.segCounters.freeBytes = freeBytes;