@trillboards/edge-platform-rtsp 0.2.16 → 0.2.19

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.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;
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.reserveLiveViewStreamSession = 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"));
@@ -616,6 +616,7 @@ exports.FrameRing = FrameRing;
616
616
  class StreamSessionAdmission {
617
617
  constructor(limit) {
618
618
  this.active = 0;
619
+ this.liveView = null;
619
620
  this.learnedCeiling = null;
620
621
  /**
621
622
  * Live holders in admission order. Shedding takes the LOWEST priority, and
@@ -714,6 +715,11 @@ class StreamSessionAdmission {
714
715
  * full until every feed happened to reconnect.
715
716
  */
716
717
  shedOverQuota() {
718
+ if (this.active > this.limit && this.liveView) {
719
+ this.stopLiveView();
720
+ if (this.liveView)
721
+ return;
722
+ }
717
723
  while (this.active > this.limit && this.holders.length > 0) {
718
724
  this.shedHolder(this.lowestHolder());
719
725
  }
@@ -751,6 +757,11 @@ class StreamSessionAdmission {
751
757
  * first-come rule, so ordinary feeds behave exactly as before.
752
758
  */
753
759
  tryAcquire(shed = () => undefined, priority = 0) {
760
+ if (this.liveViewBlocksNextMonitor()) {
761
+ this.stopLiveView();
762
+ if (this.liveView)
763
+ return null;
764
+ }
754
765
  if (this.active >= this.limit) {
755
766
  const victim = this.lowestHolder();
756
767
  if (!victim || victim.priority >= priority)
@@ -787,6 +798,37 @@ class StreamSessionAdmission {
787
798
  },
788
799
  };
789
800
  }
801
+ reserveLiveView(safeLimit, stop) {
802
+ if (this.liveView || this.retakeInFlight || this.waiters.length || this.active === 0 ||
803
+ this.active >= Math.min(this.limit, safeLimit))
804
+ return null;
805
+ const reservation = { safeLimit, stop, stopping: false };
806
+ this.liveView = reservation;
807
+ this.active++;
808
+ return {
809
+ release: () => {
810
+ if (this.liveView !== reservation)
811
+ return;
812
+ this.liveView = null;
813
+ this.active--;
814
+ this.shedOverQuota();
815
+ this.scheduleOffer();
816
+ },
817
+ };
818
+ }
819
+ liveViewBlocksNextMonitor() {
820
+ return this.liveView !== null && this.active >= Math.min(this.limit, this.liveView.safeLimit);
821
+ }
822
+ stopLiveView() {
823
+ const view = this.liveView;
824
+ if (!view || view.stopping)
825
+ return;
826
+ view.stopping = true;
827
+ try {
828
+ view.stop();
829
+ }
830
+ catch { /* Only the exact owner can confirm release. */ }
831
+ }
790
832
  /** Queue a refused feed. `retake` must call its `done` once the attempt settles. */
791
833
  addWaiter(priority, retake) {
792
834
  const waiter = { priority, seq: (this.seq += 1), retake };
@@ -836,6 +878,11 @@ class StreamSessionAdmission {
836
878
  }
837
879
  if (!top || top.priority <= 0)
838
880
  return;
881
+ if (this.liveViewBlocksNextMonitor()) {
882
+ this.stopLiveView();
883
+ if (this.liveView)
884
+ return;
885
+ }
839
886
  if (this.active >= this.limit) {
840
887
  const victim = this.lowestHolder();
841
888
  if (!victim || victim.priority >= top.priority)
@@ -876,6 +923,15 @@ function streamAdmissionFor(streamUrl, limit) {
876
923
  streamAdmissionBySource.set(key, admission);
877
924
  return admission;
878
925
  }
926
+ /** A viewer can only borrow an existing recorder pool's spare capacity. */
927
+ function reserveLiveViewStreamSession(streamUrl, qualification, stop) {
928
+ const key = (0, RTSPCameraProvider_1.captureSourceKey)(streamUrl);
929
+ const { sourceKey, safePersistentLimit } = qualification;
930
+ if (!key || key !== sourceKey || !Number.isSafeInteger(safePersistentLimit) || safePersistentLimit < 1)
931
+ return null;
932
+ return streamAdmissionBySource.get(key)?.reserveLiveView(safePersistentLimit, stop) ?? null;
933
+ }
934
+ exports.reserveLiveViewStreamSession = reserveLiveViewStreamSession;
879
935
  /** Test seam: forget every recorder's persistent-session budget. */
880
936
  function __resetStreamAdmissionForTests() {
881
937
  streamAdmissionBySource.clear();
@@ -1489,6 +1545,15 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1489
1545
  * one frame later.
1490
1546
  */
1491
1547
  this.fallbackOpenError = null;
1548
+ /**
1549
+ * The per-grab fallback's open() while it runs. A feed that changes paths
1550
+ * mid-life (a live session handed back when the feed goes idle) is not a
1551
+ * closed camera: `getFrame()` waits for this instead of answering the
1552
+ * fallback's own "Camera not opened", which the manager reads as RTSP down
1553
+ * (the first Windows field run of this change logged exactly that, once per idle
1554
+ * camera, then a 10-s reconnect).
1555
+ */
1556
+ this.fallbackOpening = null;
1492
1557
  /** The live ffmpeg session, or null between sessions. */
1493
1558
  this.session = null;
1494
1559
  /** This recorder's persistent-session lane, for the learned ceiling. */
@@ -1508,6 +1573,8 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1508
1573
  this.ringIndex = null;
1509
1574
  /** 0 = an ordinary feed; higher holds its persistent session ahead of lower ones. */
1510
1575
  this.sessionPriority = 0;
1576
+ /** No live review needs this feed (setIdle); with no recording it runs per-grab. */
1577
+ this.idle = false;
1511
1578
  /** This feed's place in its recorder's queue for a session, while the lane refused it. */
1512
1579
  this.sessionWaiter = null;
1513
1580
  /** Earliest moment a refused retake may try again (capacity refusals back off). */
@@ -1663,6 +1730,9 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1663
1730
  this.recoverSegments();
1664
1731
  }
1665
1732
  this.reconcileRecording();
1733
+ // Recording needs the continuous stream: an idle feed that starts recording
1734
+ // retakes its session, and one that stops gives it back.
1735
+ this.reconcileIdle();
1666
1736
  }
1667
1737
  /**
1668
1738
  * Rank this feed for its recorder's persistent sessions. 0 is an ordinary
@@ -1685,6 +1755,81 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1685
1755
  getSessionPriority() {
1686
1756
  return this.sessionPriority;
1687
1757
  }
1758
+ /**
1759
+ * Whether anything is looking at this feed. A feed with no live review (a
1760
+ * camera with no alert profile: Texas had 27 of 32) reads one health frame a
1761
+ * minute, yet its persistent session decoded the camera at its full 6.6-25 fps
1762
+ * (~444 of the box's ~529 decoded frames a second, 2026-11-08). Idle and not
1763
+ * recording, the feed gives its session back and each `getFrame()` is one
1764
+ * per-grab pull, admitted by the same per-recorder bound as every pull.
1765
+ *
1766
+ * Leaving idle (or a recording that starts) retakes a session through the
1767
+ * same path a refused feed uses: the per-grab path keeps answering until the
1768
+ * new session's first frame, so a feed that becomes live never has a gap. A
1769
+ * recording feed always keeps its session: the local video an alert window is
1770
+ * cut from needs the continuous stream. Idempotent; called on every look.
1771
+ */
1772
+ setIdle(idle) {
1773
+ this.idle = idle === true;
1774
+ this.reconcileIdle();
1775
+ }
1776
+ isIdle() {
1777
+ return this.idle;
1778
+ }
1779
+ /** Recording needs the continuous stream whatever the review does. */
1780
+ needsSession() {
1781
+ return !this.idle || this.segmentConfig?.enabled === true;
1782
+ }
1783
+ reconcileIdle() {
1784
+ if (!this.persistentRequested)
1785
+ return;
1786
+ if (this.needsSession()) {
1787
+ if (this.degradedReason !== 'idle' || !this.fallback || this.retake)
1788
+ return;
1789
+ // Wanted again: retake a session while the per-grab path keeps serving.
1790
+ this.degradedReason = 'session_limit';
1791
+ const admission = streamAdmissionFor(this.rtspUrl, this.maxStreamSessionsPerSource);
1792
+ if (!admission)
1793
+ return;
1794
+ this.admission = admission;
1795
+ this.log('info', 'RTSP feed is watched again; retaking its persistent session');
1796
+ this.retakeSession(admission, () => undefined);
1797
+ return;
1798
+ }
1799
+ if (this.retake && this.opened && this.fallback) {
1800
+ // A retake in flight is abandoned: the per-grab path never stopped serving.
1801
+ this.retake = null;
1802
+ this.opened = false;
1803
+ this.startingUp = false;
1804
+ this.stopProcess();
1805
+ this.releaseSlot();
1806
+ }
1807
+ if (this.fallback) {
1808
+ // Already per-grab. A feed queued for a session no longer wants one.
1809
+ if (this.degradedReason === 'session_limit') {
1810
+ this.leaveSessionQueue();
1811
+ this.degradedReason = 'idle';
1812
+ }
1813
+ return;
1814
+ }
1815
+ // A live persistent session (never one still starting: the next call settles it).
1816
+ if (!this.opened || this.startingUp)
1817
+ return;
1818
+ this.opened = false;
1819
+ this.leaveSessionQueue();
1820
+ if (this.restartTimer) {
1821
+ clearTimeout(this.restartTimer);
1822
+ this.restartTimer = null;
1823
+ }
1824
+ this.stopProcess();
1825
+ this.releaseSlot();
1826
+ this.ring.clear();
1827
+ this.splitter.reset();
1828
+ this.wakeWaiters();
1829
+ void this.degradeTo('idle').catch((err) => {
1830
+ this.fallbackOpenError = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err instanceof Error ? err.message : String(err));
1831
+ });
1832
+ }
1688
1833
  // ── CameraProvider ───────────────────────────────────────────────────────
1689
1834
  /**
1690
1835
  * Take a recorder session slot and start streaming. NEVER throws because the
@@ -1737,6 +1882,10 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1737
1882
  await this.degradeTo('disabled');
1738
1883
  return;
1739
1884
  }
1885
+ if (!this.needsSession()) {
1886
+ await this.degradeTo('idle');
1887
+ return;
1888
+ }
1740
1889
  const admission = streamAdmissionFor(this.rtspUrl, this.maxStreamSessionsPerSource);
1741
1890
  this.admission = admission;
1742
1891
  if (admission) {
@@ -1886,23 +2035,17 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1886
2035
  * permanently.
1887
2036
  */
1888
2037
  async getFrame() {
1889
- if (this.fallback) {
1890
- // A fallback that never opened cannot answer, and the reason it could not
1891
- // is the one thing worth saying. Re-throwing the recorder's own words
1892
- // keeps `classifyRtspFailureClass` looking at evidence instead of at a
1893
- // message about how this API is called.
1894
- if (this.fallbackOpenError !== null) {
1895
- throw new Error(`RTSP per-grab fallback is not open for ${(0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(this.rtspUrl)}: ` +
1896
- this.fallbackOpenError);
1897
- }
1898
- return this.fallback.getFrame();
1899
- }
2038
+ if (this.fallback)
2039
+ return this.fallbackFrame();
1900
2040
  if (!this.opened)
1901
2041
  throw new Error('Camera not opened. Call open() first.');
1902
2042
  const fresh = this.takeFreshFrame();
1903
2043
  if (fresh)
1904
2044
  return fresh;
1905
2045
  const arrived = await this.waitForFrame(this.frameWaitMs);
2046
+ // The session was handed back (the feed went idle) while this call waited.
2047
+ if (this.fallback)
2048
+ return this.fallbackFrame();
1906
2049
  if (arrived) {
1907
2050
  const next = this.takeFreshFrame();
1908
2051
  if (next)
@@ -1913,6 +2056,31 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1913
2056
  const ageMs = newest ? this.now() - newest.atMs : this.frameWaitMs;
1914
2057
  throw new RtspStreamStaleError(this.rtspUrl, ageMs, this.restarts);
1915
2058
  }
2059
+ /** A frame from the per-grab path, once a fallback still opening has opened. */
2060
+ async fallbackFrame() {
2061
+ const opening = this.fallbackOpening;
2062
+ if (opening) {
2063
+ try {
2064
+ await opening;
2065
+ }
2066
+ catch {
2067
+ /* its reason is in fallbackOpenError, reported below */
2068
+ }
2069
+ }
2070
+ const fallback = this.fallback;
2071
+ // A session replaced the fallback, or close() ran, while this call waited.
2072
+ if (!fallback)
2073
+ return this.getFrame();
2074
+ // A fallback that never opened cannot answer, and the reason it could not
2075
+ // is the one thing worth saying. Re-throwing the recorder's own words
2076
+ // keeps `classifyRtspFailureClass` looking at evidence instead of at a
2077
+ // message about how this API is called.
2078
+ if (this.fallbackOpenError !== null) {
2079
+ throw new Error(`RTSP per-grab fallback is not open for ${(0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(this.rtspUrl)}: ` +
2080
+ this.fallbackOpenError);
2081
+ }
2082
+ return fallback.getFrame();
2083
+ }
1916
2084
  getResolution() {
1917
2085
  return { width: this.width, height: this.height };
1918
2086
  }
@@ -1920,8 +2088,9 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1920
2088
  return this.streamFps;
1921
2089
  }
1922
2090
  isOpen() {
2091
+ // A fallback still opening is a feed changing paths; getFrame() waits for it.
1923
2092
  if (this.fallback)
1924
- return this.fallback.isOpen();
2093
+ return this.fallbackOpening !== null || this.fallback.isOpen();
1925
2094
  return this.opened;
1926
2095
  }
1927
2096
  async close() {
@@ -1993,7 +2162,10 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
1993
2162
  const generation = this.openGeneration;
1994
2163
  this.mode = 'per_grab';
1995
2164
  this.degradedReason = reason;
1996
- if (reason !== 'disabled') {
2165
+ if (reason === 'idle') {
2166
+ this.log('info', 'RTSP feed idle (no live review, no recording): one per-grab pull per frame');
2167
+ }
2168
+ else if (reason !== 'disabled') {
1997
2169
  this.log('warn', `RTSP persistent session unavailable (${reason}); falling back to per-grab capture` +
1998
2170
  (this.lastErrorMessage ? `: ${this.lastErrorMessage}` : ''));
1999
2171
  }
@@ -2007,8 +2179,15 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2007
2179
  // feed takes one when it frees or a lower-ranked holder can give way).
2008
2180
  if (reason === 'session_limit')
2009
2181
  this.joinSessionQueue();
2182
+ const opening = fallback.open();
2183
+ this.fallbackOpening = opening;
2184
+ const settled = () => {
2185
+ if (this.fallbackOpening === opening)
2186
+ this.fallbackOpening = null;
2187
+ };
2010
2188
  try {
2011
- await fallback.open();
2189
+ await opening;
2190
+ settled();
2012
2191
  if (generation !== this.openGeneration || this.fallback !== fallback) {
2013
2192
  try {
2014
2193
  await fallback.close();
@@ -2018,6 +2197,7 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2018
2197
  }
2019
2198
  catch (err) {
2020
2199
  if (generation !== this.openGeneration || this.fallback !== fallback) {
2200
+ settled();
2021
2201
  try {
2022
2202
  await fallback.close();
2023
2203
  }
@@ -2026,9 +2206,11 @@ class RTSPStreamCameraProvider extends events_1.EventEmitter {
2026
2206
  }
2027
2207
  // KEEP the reason. It is the only description of what the recorder did,
2028
2208
  // and without it `getFrame()` falls back to a message about how the
2029
- // caller used the API — see `fallbackOpenError`.
2209
+ // caller used the API — see `fallbackOpenError`. Set before the opening
2210
+ // is marked settled, so a frame call waiting on it reads the reason.
2030
2211
  this.fallbackOpenError = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err instanceof Error ? err.message : String(err));
2031
2212
  this.lastErrorMessage = this.fallbackOpenError;
2213
+ settled();
2032
2214
  throw err;
2033
2215
  }
2034
2216
  }