@trillboards/edge-platform-rtsp 0.2.6 → 0.2.8
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.
- package/README.md +38 -0
- package/dist/RTSPStreamCameraProvider.d.ts +332 -4
- package/dist/RTSPStreamCameraProvider.d.ts.map +1 -1
- package/dist/RTSPStreamCameraProvider.js +1234 -46
- package/dist/RTSPStreamCameraProvider.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -23,8 +23,9 @@ 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.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.InputStreamProbe = exports.parseInputVideoStreamLine = exports.parseSegmentListCsv = 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
|
+
const events_1 = require("events");
|
|
28
29
|
const fs = __importStar(require("fs"));
|
|
29
30
|
const os = __importStar(require("os"));
|
|
30
31
|
const path = __importStar(require("path"));
|
|
@@ -204,6 +205,29 @@ const ffmpegStderr_1 = require("./ffmpegStderr");
|
|
|
204
205
|
* written to a 0600 ffconcat file and only the temp path reaches argv, so a
|
|
205
206
|
* password never appears in `ps` output; stderr is scrubbed through
|
|
206
207
|
* `sanitizeStreamUrlForLog` before it can reach a log line.
|
|
208
|
+
*
|
|
209
|
+
* ── SEGMENT RECORDING: A SECOND OUTPUT ON THE SAME SESSION ────────────────
|
|
210
|
+
*
|
|
211
|
+
* `segmentRecording` adds a second ffmpeg OUTPUT to the session that is already
|
|
212
|
+
* running — `-map 0:v -c:v copy … -f segment` — so the camera's own H.264/HEVC
|
|
213
|
+
* bitstream is written to MP4 segments with no decode and no re-encode, and no
|
|
214
|
+
* second RTSP session is opened against the recorder. The look path's argv is
|
|
215
|
+
* byte-identical when it is absent, and only a crop-less persistent session
|
|
216
|
+
* records (a mosaic tile's crop applies to the look output, never to a copy).
|
|
217
|
+
*
|
|
218
|
+
* Closed segments are found by reading the segment muxer's own CSV list:
|
|
219
|
+
* ffmpeg prints a line only when it ENDS a segment, so a listed file is a
|
|
220
|
+
* closed one. Every listed file moves to `<dir>/closed/` with a JSON sidecar
|
|
221
|
+
* and is emitted as a `'segment'` event; every file still in the session's
|
|
222
|
+
* work directory when the session ends was never listed — the segment that
|
|
223
|
+
* was being written — and is deleted, so a partial file never leaves here.
|
|
224
|
+
* Measured on ffmpeg 6.1.1 against mediamtx: SIGTERM mid-segment leaves that
|
|
225
|
+
* segment unlisted and without a `moov` atom; a listed segment probes clean.
|
|
226
|
+
*
|
|
227
|
+
* Recording can never take the look path down. A session that carried the
|
|
228
|
+
* second output, opened its input and then produced nothing is read as the
|
|
229
|
+
* output's failure: the next session runs look-only and recording retries
|
|
230
|
+
* after a doubling cooldown (`SEGMENT_SUSPEND_BASE_MS`..`SEGMENT_SUSPEND_MAX_MS`).
|
|
207
231
|
*/
|
|
208
232
|
/** The recorder's persistent-session lane is full. Degrade, never queue. */
|
|
209
233
|
class RtspStreamAdmissionError extends Error {
|
|
@@ -741,14 +765,245 @@ function streamSessionStatsFor(streamUrl) {
|
|
|
741
765
|
};
|
|
742
766
|
}
|
|
743
767
|
exports.streamSessionStatsFor = streamSessionStatsFor;
|
|
768
|
+
/** Codecs `video_segment` holds. Anything else is not recorded. */
|
|
769
|
+
exports.RECORDABLE_CODECS = ['h264', 'hevc'];
|
|
770
|
+
/** Closed segments, beside their sidecars, under the feed's directory. */
|
|
771
|
+
exports.CLOSED_SEGMENTS_DIRNAME = 'closed';
|
|
772
|
+
/** Session work directories are `rec-<startMs>-<sessionNumber>`. */
|
|
773
|
+
const SESSION_WORKDIR_PREFIX = 'rec-';
|
|
774
|
+
/**
|
|
775
|
+
* How often the segment list is read. ffmpeg writes a line the moment it
|
|
776
|
+
* closes a segment, so this is the whole detection latency, and it is also
|
|
777
|
+
* the resolution of the anchor drift check below.
|
|
778
|
+
*/
|
|
779
|
+
const SEGMENT_POLL_MS = 1000;
|
|
780
|
+
/** First recording pause after the second output failed a session. */
|
|
781
|
+
exports.SEGMENT_SUSPEND_BASE_MS = 60000;
|
|
782
|
+
/** Ceiling on that pause: at most one look-path restart an hour on a failure that persists. */
|
|
783
|
+
exports.SEGMENT_SUSPEND_MAX_MS = 3600000;
|
|
784
|
+
/**
|
|
785
|
+
* ffmpeg's words for an OUTPUT write failing (a full or read-only volume, a
|
|
786
|
+
* segment file it could not open). An input failure — the camera dropping —
|
|
787
|
+
* reads "Failed reading RTSP data" / "End of file" and matches none of these.
|
|
788
|
+
*/
|
|
789
|
+
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;
|
|
790
|
+
/** The ring may hold at most this fraction of the volume's free bytes. */
|
|
791
|
+
exports.RING_FREE_FRACTION = 0.1;
|
|
792
|
+
/**
|
|
793
|
+
* A segment cannot end after it was observed closed. A predicted end more
|
|
794
|
+
* than this past the poll that found it means the anchor is late.
|
|
795
|
+
*/
|
|
796
|
+
const ANCHOR_FUTURE_TOLERANCE_MS = 1000;
|
|
797
|
+
/**
|
|
798
|
+
* A predicted end more than one poll plus this BEFORE the close was observed
|
|
799
|
+
* means the camera's media clock is running slow against the wall clock.
|
|
800
|
+
*/
|
|
801
|
+
const ANCHOR_LAG_TOLERANCE_MS = 5000;
|
|
802
|
+
/**
|
|
803
|
+
* Parse the segment muxer's CSV list (`-segment_list_type csv`): one line per
|
|
804
|
+
* CLOSED segment, `name,start,end`. The last line is returned as `remainder`
|
|
805
|
+
* when it is not yet newline-terminated, so a half-written line is never read.
|
|
806
|
+
*/
|
|
807
|
+
function parseSegmentListCsv(text) {
|
|
808
|
+
const lines = text.split('\n');
|
|
809
|
+
const remainder = lines.pop() ?? '';
|
|
810
|
+
const entries = [];
|
|
811
|
+
for (const raw of lines) {
|
|
812
|
+
const line = raw.replace(/\r$/, '');
|
|
813
|
+
if (!line)
|
|
814
|
+
continue;
|
|
815
|
+
const endComma = line.lastIndexOf(',');
|
|
816
|
+
const startComma = endComma > 0 ? line.lastIndexOf(',', endComma - 1) : -1;
|
|
817
|
+
if (startComma <= 0)
|
|
818
|
+
continue;
|
|
819
|
+
let name = line.slice(0, startComma);
|
|
820
|
+
if (name.length >= 2 && name.startsWith('"') && name.endsWith('"')) {
|
|
821
|
+
name = name.slice(1, -1).replace(/""/g, '"');
|
|
822
|
+
}
|
|
823
|
+
const startSec = Number(line.slice(startComma + 1, endComma));
|
|
824
|
+
const endSec = Number(line.slice(endComma + 1));
|
|
825
|
+
// The list names basenames inside the session's own work directory. Anything
|
|
826
|
+
// else is not a file this provider wrote, and is never followed.
|
|
827
|
+
if (!name || name !== path.basename(name) || name === '.' || name === '..')
|
|
828
|
+
continue;
|
|
829
|
+
if (!Number.isFinite(startSec) || !Number.isFinite(endSec) || endSec < startSec)
|
|
830
|
+
continue;
|
|
831
|
+
entries.push({ name, startSec, endSec });
|
|
832
|
+
}
|
|
833
|
+
return { entries, remainder };
|
|
834
|
+
}
|
|
835
|
+
exports.parseSegmentListCsv = parseSegmentListCsv;
|
|
836
|
+
/**
|
|
837
|
+
* One `Stream #0:N: Video: …` line from ffmpeg's input description, or null.
|
|
838
|
+
* `90k tbr`-style rates are the RTP clock, not a frame rate, so only an
|
|
839
|
+
* explicit `fps` is read.
|
|
840
|
+
*/
|
|
841
|
+
function parseInputVideoStreamLine(line) {
|
|
842
|
+
const m = /^\s*Stream #0:\d+(?:\[[^\]]*\])?(?:\([^)]*\))?:\s*Video:\s*([A-Za-z0-9_]+)(.*)$/.exec(line);
|
|
843
|
+
if (!m)
|
|
844
|
+
return null;
|
|
845
|
+
const rest = m[2] ?? '';
|
|
846
|
+
const res = /\b(\d{2,5})x(\d{2,5})\b/.exec(rest);
|
|
847
|
+
const fpsMatch = /(\d+(?:\.\d+)?)\s+fps\b/.exec(rest);
|
|
848
|
+
const fps = fpsMatch ? Number(fpsMatch[1]) : null;
|
|
849
|
+
return {
|
|
850
|
+
codec: m[1].toLowerCase(),
|
|
851
|
+
width: res ? Number(res[1]) : null,
|
|
852
|
+
height: res ? Number(res[2]) : null,
|
|
853
|
+
fps: fps !== null && fps > 0 && fps <= 1000 ? fps : null,
|
|
854
|
+
};
|
|
855
|
+
}
|
|
856
|
+
exports.parseInputVideoStreamLine = parseInputVideoStreamLine;
|
|
857
|
+
/**
|
|
858
|
+
* Reads ffmpeg's stderr as it arrives and stops at the first input video
|
|
859
|
+
* stream, or at the first output description — whichever comes first. Bounded:
|
|
860
|
+
* it holds at most one partial line.
|
|
861
|
+
*/
|
|
862
|
+
class InputStreamProbe {
|
|
863
|
+
constructor() {
|
|
864
|
+
this.partial = '';
|
|
865
|
+
this.inInput = false;
|
|
866
|
+
/** The input was opened (ffmpeg described it). */
|
|
867
|
+
this.inputOpened = false;
|
|
868
|
+
this.done = false;
|
|
869
|
+
this.info = null;
|
|
870
|
+
}
|
|
871
|
+
push(text) {
|
|
872
|
+
if (this.done)
|
|
873
|
+
return null;
|
|
874
|
+
const lines = (this.partial + text).split(/\r\n|\r|\n/);
|
|
875
|
+
this.partial = lines.pop() ?? '';
|
|
876
|
+
if (this.partial.length > 8192)
|
|
877
|
+
this.partial = this.partial.slice(-8192);
|
|
878
|
+
for (const line of lines) {
|
|
879
|
+
if (/^Input #0,/.test(line)) {
|
|
880
|
+
this.inInput = true;
|
|
881
|
+
this.inputOpened = true;
|
|
882
|
+
continue;
|
|
883
|
+
}
|
|
884
|
+
if (/^(Output #\d+|Stream mapping:)/.test(line)) {
|
|
885
|
+
this.done = true;
|
|
886
|
+
return null;
|
|
887
|
+
}
|
|
888
|
+
if (!this.inInput)
|
|
889
|
+
continue;
|
|
890
|
+
const info = parseInputVideoStreamLine(line);
|
|
891
|
+
if (info) {
|
|
892
|
+
this.info = info;
|
|
893
|
+
this.done = true;
|
|
894
|
+
return info;
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
return null;
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
exports.InputStreamProbe = InputStreamProbe;
|
|
901
|
+
/** The second output, exactly. Pure, so the argv can be asserted. */
|
|
902
|
+
function buildSegmentOutputArgs(o) {
|
|
903
|
+
return [
|
|
904
|
+
'-map',
|
|
905
|
+
'0:v',
|
|
906
|
+
'-c:v',
|
|
907
|
+
'copy',
|
|
908
|
+
...(o.tagHvc1 ? ['-tag:v', 'hvc1'] : []),
|
|
909
|
+
// The copy starts at the first KEYFRAME, but the output timeline starts at
|
|
910
|
+
// the first packet received, and the segment list reports the first
|
|
911
|
+
// segment as starting at 0 regardless. Measured on the mediamtx rig: a
|
|
912
|
+
// first segment listed 0.000-7.542 held 6.000 s of video starting at
|
|
913
|
+
// 1.541. Shifting the copy so its first packet is 0 makes every listed
|
|
914
|
+
// start true, and with it first-frame wall clock + startSec (3 of 3 runs:
|
|
915
|
+
// listed 0.000-6.083, file 6.000 s from 0.083, the B-frame delay).
|
|
916
|
+
'-avoid_negative_ts',
|
|
917
|
+
'make_zero',
|
|
918
|
+
'-f',
|
|
919
|
+
'segment',
|
|
920
|
+
'-segment_time',
|
|
921
|
+
String(o.segmentSeconds),
|
|
922
|
+
...(o.minSegDuration ? ['-min_seg_duration', String(o.segmentSeconds)] : []),
|
|
923
|
+
'-segment_format',
|
|
924
|
+
'mp4',
|
|
925
|
+
'-reset_timestamps',
|
|
926
|
+
'1',
|
|
927
|
+
'-segment_list',
|
|
928
|
+
o.csvPath,
|
|
929
|
+
'-segment_list_type',
|
|
930
|
+
'csv',
|
|
931
|
+
o.segmentPattern,
|
|
932
|
+
];
|
|
933
|
+
}
|
|
934
|
+
exports.buildSegmentOutputArgs = buildSegmentOutputArgs;
|
|
935
|
+
/** The volume's free bytes, or null where the platform cannot say. */
|
|
936
|
+
function volumeFreeBytes(dir) {
|
|
937
|
+
const statfsSync = fs.statfsSync;
|
|
938
|
+
if (typeof statfsSync !== 'function')
|
|
939
|
+
return null;
|
|
940
|
+
try {
|
|
941
|
+
const s = statfsSync(dir);
|
|
942
|
+
const free = Number(s.bavail) * Number(s.bsize);
|
|
943
|
+
return Number.isFinite(free) && free >= 0 ? free : null;
|
|
944
|
+
}
|
|
945
|
+
catch {
|
|
946
|
+
return null;
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
exports.volumeFreeBytes = volumeFreeBytes;
|
|
950
|
+
function normalizeSegmentRecording(cfg) {
|
|
951
|
+
if (!cfg || typeof cfg.dir !== 'string' || !cfg.dir.trim())
|
|
952
|
+
return null;
|
|
953
|
+
const segmentSeconds = Number(cfg.segmentSeconds);
|
|
954
|
+
const ringSeconds = Number(cfg.ringSeconds);
|
|
955
|
+
if (!Number.isFinite(segmentSeconds) || segmentSeconds <= 0)
|
|
956
|
+
return null;
|
|
957
|
+
if (!Number.isFinite(ringSeconds) || ringSeconds < 0)
|
|
958
|
+
return null;
|
|
959
|
+
return {
|
|
960
|
+
dir: path.resolve(cfg.dir),
|
|
961
|
+
segmentSeconds: Math.max(1, Math.trunc(segmentSeconds)),
|
|
962
|
+
ringSeconds: Math.trunc(ringSeconds),
|
|
963
|
+
enabled: cfg.enabled !== false,
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
function writeFileAtomic(file, body) {
|
|
967
|
+
const tmp = `${file}.tmp`;
|
|
968
|
+
fs.writeFileSync(tmp, body);
|
|
969
|
+
fs.renameSync(tmp, file);
|
|
970
|
+
}
|
|
971
|
+
function readSidecar(file) {
|
|
972
|
+
try {
|
|
973
|
+
const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
974
|
+
const nums = [raw.startSec, raw.endSec, raw.captureStartMs, raw.captureEndMs, raw.bytes];
|
|
975
|
+
if (raw.version !== 1 || nums.some((n) => typeof n !== 'number' || !Number.isFinite(n)))
|
|
976
|
+
return null;
|
|
977
|
+
const stream = raw.stream && typeof raw.stream === 'object' && typeof raw.stream.codec === 'string'
|
|
978
|
+
? raw.stream
|
|
979
|
+
: null;
|
|
980
|
+
return { ...raw, stream };
|
|
981
|
+
}
|
|
982
|
+
catch {
|
|
983
|
+
return null;
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
/** A rename/unlink the OS refused because another process still holds the file. */
|
|
987
|
+
function isBusyError(err) {
|
|
988
|
+
const code = err?.code;
|
|
989
|
+
return code === 'EBUSY' || code === 'EPERM' || code === 'EACCES';
|
|
990
|
+
}
|
|
991
|
+
function errorText(err) {
|
|
992
|
+
return err instanceof Error ? err.message : String(err);
|
|
993
|
+
}
|
|
744
994
|
/**
|
|
745
995
|
* One instance per feed. Implements the SAME `CameraProvider` interface as
|
|
746
996
|
* `RTSPCameraProvider`, so every consumer is unchanged — but `getFrame()` reads
|
|
747
997
|
* the newest frame out of the ring the long-lived session is filling, rather
|
|
748
998
|
* than spawning a process and handshaking a stream per call.
|
|
999
|
+
*
|
|
1000
|
+
* Events: `'segment'` (RecordedSegment) for every closed recording segment,
|
|
1001
|
+
* `'segment_evicted'` (EvictedSegment) when the ring deletes one undelivered,
|
|
1002
|
+
* and `'opening'` at the start of every `open()`.
|
|
749
1003
|
*/
|
|
750
|
-
class RTSPStreamCameraProvider {
|
|
1004
|
+
class RTSPStreamCameraProvider extends events_1.EventEmitter {
|
|
751
1005
|
constructor(config) {
|
|
1006
|
+
super();
|
|
752
1007
|
this.opened = false;
|
|
753
1008
|
this.mode = 'persistent';
|
|
754
1009
|
this.degradedReason = null;
|
|
@@ -766,13 +1021,51 @@ class RTSPStreamCameraProvider {
|
|
|
766
1021
|
* one frame later.
|
|
767
1022
|
*/
|
|
768
1023
|
this.fallbackOpenError = null;
|
|
769
|
-
|
|
1024
|
+
/** The live ffmpeg session, or null between sessions. */
|
|
1025
|
+
this.session = null;
|
|
770
1026
|
/** This recorder's persistent-session lane, for the learned ceiling. */
|
|
771
1027
|
this.admission = null;
|
|
772
1028
|
this.releaseAdmission = null;
|
|
773
1029
|
this.restartTimer = null;
|
|
774
|
-
this.cleanupInput = null;
|
|
775
1030
|
this.startingUp = false;
|
|
1031
|
+
// ── segment recording ────────────────────────────────────────────────────
|
|
1032
|
+
this.segmentConfig = null;
|
|
1033
|
+
/** The newest input description ffmpeg gave; decides the tag and the codec gate. */
|
|
1034
|
+
this.streamInfo = null;
|
|
1035
|
+
this.segmentsRecoveredFor = null;
|
|
1036
|
+
this.segmentPollTimer = null;
|
|
1037
|
+
this.lastSegmentPollAtMs = null;
|
|
1038
|
+
/** A session stopped to change the second output; its exit starts the next one. */
|
|
1039
|
+
this.reconfigurePendingFor = null;
|
|
1040
|
+
/**
|
|
1041
|
+
* Recording paused after the second output failed a session. Provider-wide,
|
|
1042
|
+
* not per argv: the next plan differs only by the tag once ffmpeg has named
|
|
1043
|
+
* the codec, and retrying it at once would spend open()'s last attempt.
|
|
1044
|
+
*/
|
|
1045
|
+
this.segmentSuspension = null;
|
|
1046
|
+
this.segmentSuspendTimer = null;
|
|
1047
|
+
this.consecutiveOutputFailures = 0;
|
|
1048
|
+
this.measuredSegmentBytes = 0;
|
|
1049
|
+
this.measuredSegmentSeconds = 0;
|
|
1050
|
+
this.segCounters = {
|
|
1051
|
+
closed: 0,
|
|
1052
|
+
recovered: 0,
|
|
1053
|
+
secondsClosed: 0,
|
|
1054
|
+
bytesClosed: 0,
|
|
1055
|
+
partialsDeleted: 0,
|
|
1056
|
+
evicted: 0,
|
|
1057
|
+
evictedBytes: 0,
|
|
1058
|
+
reconfigures: 0,
|
|
1059
|
+
outputFailures: 0,
|
|
1060
|
+
reanchors: 0,
|
|
1061
|
+
lastAnchorDriftMs: null,
|
|
1062
|
+
lastSegmentAtMs: null,
|
|
1063
|
+
lastError: null,
|
|
1064
|
+
ringSegments: 0,
|
|
1065
|
+
ringBytes: 0,
|
|
1066
|
+
ringLimitBytes: null,
|
|
1067
|
+
freeBytes: null,
|
|
1068
|
+
};
|
|
776
1069
|
this.sessionStarts = 0;
|
|
777
1070
|
this.restarts = 0;
|
|
778
1071
|
this.framesDecoded = 0;
|
|
@@ -825,6 +1118,40 @@ class RTSPStreamCameraProvider {
|
|
|
825
1118
|
};
|
|
826
1119
|
const make = config.fallbackFactory ?? ((c) => new RTSPCameraProvider_1.RTSPCameraProvider(c));
|
|
827
1120
|
this.buildFallback = () => make(fallbackConfig);
|
|
1121
|
+
this.freeBytesFn = config.freeBytesFn ?? volumeFreeBytes;
|
|
1122
|
+
// No filesystem work here: a provider that is built and never opened (a
|
|
1123
|
+
// test, a manager that is configured and then discarded) must leave no trace.
|
|
1124
|
+
this.segmentConfig = normalizeSegmentRecording(config.segmentRecording ?? null);
|
|
1125
|
+
}
|
|
1126
|
+
on(event, listener) {
|
|
1127
|
+
return super.on(event, listener);
|
|
1128
|
+
}
|
|
1129
|
+
/**
|
|
1130
|
+
* Change segment recording. `null` turns it off and keeps the directory (the
|
|
1131
|
+
* ring and any leftovers stay this provider's). A change that the running
|
|
1132
|
+
* session's argv does not already satisfy restarts the session once — after
|
|
1133
|
+
* its first frame, never during startup.
|
|
1134
|
+
*/
|
|
1135
|
+
setSegmentRecording(next) {
|
|
1136
|
+
if (next === null) {
|
|
1137
|
+
if (this.segmentConfig)
|
|
1138
|
+
this.segmentConfig = { ...this.segmentConfig, enabled: false };
|
|
1139
|
+
}
|
|
1140
|
+
else {
|
|
1141
|
+
const normalized = normalizeSegmentRecording(next);
|
|
1142
|
+
if (!normalized)
|
|
1143
|
+
return;
|
|
1144
|
+
const previous = this.segmentConfig;
|
|
1145
|
+
// New knobs are a new question: a pause earned by the old ones does not carry over.
|
|
1146
|
+
if (!previous || previous.dir !== normalized.dir || previous.segmentSeconds !== normalized.segmentSeconds) {
|
|
1147
|
+
this.clearSegmentSuspension();
|
|
1148
|
+
}
|
|
1149
|
+
this.segmentConfig = normalized;
|
|
1150
|
+
}
|
|
1151
|
+
if (this.opened && this.segmentConfig && this.segmentsRecoveredFor !== this.segmentConfig.dir) {
|
|
1152
|
+
this.recoverSegments();
|
|
1153
|
+
}
|
|
1154
|
+
this.reconcileRecording();
|
|
828
1155
|
}
|
|
829
1156
|
// ── CameraProvider ───────────────────────────────────────────────────────
|
|
830
1157
|
/**
|
|
@@ -836,6 +1163,20 @@ class RTSPStreamCameraProvider {
|
|
|
836
1163
|
async open(_deviceId) {
|
|
837
1164
|
if (this.opened)
|
|
838
1165
|
return;
|
|
1166
|
+
// A controller attached at construction starts here, so a provider that is
|
|
1167
|
+
// built and never opened costs nothing. Its listener may set the recording
|
|
1168
|
+
// config synchronously, which the first session below then carries.
|
|
1169
|
+
try {
|
|
1170
|
+
this.emit('opening');
|
|
1171
|
+
}
|
|
1172
|
+
catch (err) {
|
|
1173
|
+
this.log('warn', `segment recording: an 'opening' listener threw: ${errorText(err)}`);
|
|
1174
|
+
}
|
|
1175
|
+
// Segments an earlier process closed (or left listed in a work directory)
|
|
1176
|
+
// are this feed's, and are handed out before any new one is written.
|
|
1177
|
+
if (this.segmentConfig && this.segmentsRecoveredFor !== this.segmentConfig.dir) {
|
|
1178
|
+
this.recoverSegments();
|
|
1179
|
+
}
|
|
839
1180
|
// A previous open() degraded and left a per-grab provider behind. Re-opening
|
|
840
1181
|
// is the manager's reconnect path, and it is also the ONLY chance to retake
|
|
841
1182
|
// a persistent session from a recorder that has since rebooted, freed a
|
|
@@ -878,15 +1219,29 @@ class RTSPStreamCameraProvider {
|
|
|
878
1219
|
this.currentRestartDelay = this.restartDelayMs;
|
|
879
1220
|
this.startingUp = true;
|
|
880
1221
|
let lastErr;
|
|
1222
|
+
// A failure the second output caused is not the recorder refusing this
|
|
1223
|
+
// feed: it buys one look-only attempt that the validation budget does not
|
|
1224
|
+
// pay for, so recording can never be what degrades a feed to per-grab.
|
|
1225
|
+
let recordingRetryGranted = false;
|
|
881
1226
|
try {
|
|
882
1227
|
for (let attempt = 1; attempt <= this.openValidationAttempts; attempt += 1) {
|
|
1228
|
+
const outputFailuresBefore = this.segCounters.outputFailures;
|
|
883
1229
|
try {
|
|
884
1230
|
await this.startSession();
|
|
1231
|
+
// Anything that changed the recording plan during startup (a config
|
|
1232
|
+
// set from a listener, ffmpeg's description of the input) was held
|
|
1233
|
+
// back until the session proved itself; apply it now.
|
|
1234
|
+
this.startingUp = false;
|
|
1235
|
+
this.reconcileRecording();
|
|
885
1236
|
return;
|
|
886
1237
|
}
|
|
887
1238
|
catch (err) {
|
|
888
1239
|
lastErr = err;
|
|
889
1240
|
this.stopProcess();
|
|
1241
|
+
if (!recordingRetryGranted && this.segCounters.outputFailures > outputFailuresBefore) {
|
|
1242
|
+
recordingRetryGranted = true;
|
|
1243
|
+
attempt -= 1;
|
|
1244
|
+
}
|
|
890
1245
|
if (attempt < this.openValidationAttempts && this.restartDelayMs > 0) {
|
|
891
1246
|
await new Promise((resolve) => setTimeout(resolve, this.restartDelayMs));
|
|
892
1247
|
}
|
|
@@ -1007,7 +1362,14 @@ class RTSPStreamCameraProvider {
|
|
|
1007
1362
|
clearTimeout(this.restartTimer);
|
|
1008
1363
|
this.restartTimer = null;
|
|
1009
1364
|
}
|
|
1365
|
+
if (this.segmentSuspendTimer) {
|
|
1366
|
+
clearTimeout(this.segmentSuspendTimer);
|
|
1367
|
+
this.segmentSuspendTimer = null;
|
|
1368
|
+
}
|
|
1369
|
+
// The session's own exit finishes its recording (final list read, partial
|
|
1370
|
+
// deleted); a process that exits first leaves it for the next open().
|
|
1010
1371
|
this.stopProcess();
|
|
1372
|
+
this.stopSegmentPolling();
|
|
1011
1373
|
this.releaseSlot();
|
|
1012
1374
|
this.ring.clear();
|
|
1013
1375
|
this.splitter.reset();
|
|
@@ -1030,7 +1392,7 @@ class RTSPStreamCameraProvider {
|
|
|
1030
1392
|
opened: this.isOpen(),
|
|
1031
1393
|
mode: this.mode,
|
|
1032
1394
|
degradedReason: this.degradedReason,
|
|
1033
|
-
running: this.
|
|
1395
|
+
running: this.session !== null,
|
|
1034
1396
|
bufferedFrames: this.ring.getFrames(),
|
|
1035
1397
|
bufferedBytes: this.ring.getBytes(),
|
|
1036
1398
|
pendingBytes: this.splitter.getPendingBytes(),
|
|
@@ -1046,6 +1408,7 @@ class RTSPStreamCameraProvider {
|
|
|
1046
1408
|
lastFrameAtMs: this.lastFrameAtMs,
|
|
1047
1409
|
frameAgeMs: newest ? this.now() - newest.atMs : null,
|
|
1048
1410
|
lastErrorMessage: this.lastErrorMessage,
|
|
1411
|
+
segments: this.segmentStats(),
|
|
1049
1412
|
};
|
|
1050
1413
|
}
|
|
1051
1414
|
// ── internals ────────────────────────────────────────────────────────────
|
|
@@ -1180,7 +1543,12 @@ class RTSPStreamCameraProvider {
|
|
|
1180
1543
|
},
|
|
1181
1544
|
};
|
|
1182
1545
|
}
|
|
1183
|
-
|
|
1546
|
+
/**
|
|
1547
|
+
* The session's argv. With no `segmentOutput` it is byte-identical to the
|
|
1548
|
+
* look-only session this provider has always run; with one, the second
|
|
1549
|
+
* output (`buildSegmentOutputArgs`) follows `pipe:1`.
|
|
1550
|
+
*/
|
|
1551
|
+
buildArgs(segmentOutput) {
|
|
1184
1552
|
const input = this.buildInputArgs();
|
|
1185
1553
|
return {
|
|
1186
1554
|
args: [
|
|
@@ -1209,6 +1577,9 @@ class RTSPStreamCameraProvider {
|
|
|
1209
1577
|
'-threads',
|
|
1210
1578
|
String(this.decoderThreads),
|
|
1211
1579
|
'pipe:1',
|
|
1580
|
+
// The second output, when this session records: the input's own video
|
|
1581
|
+
// bitstream, copied — no decode, no encode, no second RTSP session.
|
|
1582
|
+
...(segmentOutput ? buildSegmentOutputArgs(segmentOutput) : []),
|
|
1212
1583
|
],
|
|
1213
1584
|
cleanup: input.cleanup,
|
|
1214
1585
|
};
|
|
@@ -1221,8 +1592,16 @@ class RTSPStreamCameraProvider {
|
|
|
1221
1592
|
*/
|
|
1222
1593
|
startSession() {
|
|
1223
1594
|
return new Promise((resolve, reject) => {
|
|
1224
|
-
const
|
|
1225
|
-
|
|
1595
|
+
const recording = this.prepareSessionRecording();
|
|
1596
|
+
const { args, cleanup } = this.buildArgs(recording
|
|
1597
|
+
? {
|
|
1598
|
+
csvPath: recording.csvPath,
|
|
1599
|
+
segmentPattern: segmentPatternFor(recording.workDir),
|
|
1600
|
+
segmentSeconds: recording.plan.segmentSeconds,
|
|
1601
|
+
tagHvc1: recording.plan.tagHvc1,
|
|
1602
|
+
minSegDuration: recording.plan.minSegDuration,
|
|
1603
|
+
}
|
|
1604
|
+
: null);
|
|
1226
1605
|
this.sessionStarts += 1;
|
|
1227
1606
|
this.splitter.reset();
|
|
1228
1607
|
let proc;
|
|
@@ -1231,11 +1610,26 @@ class RTSPStreamCameraProvider {
|
|
|
1231
1610
|
}
|
|
1232
1611
|
catch (err) {
|
|
1233
1612
|
cleanup();
|
|
1234
|
-
|
|
1613
|
+
if (recording)
|
|
1614
|
+
this.removeWorkDir(recording.workDir);
|
|
1235
1615
|
reject(err instanceof Error ? err : new Error(String(err)));
|
|
1236
1616
|
return;
|
|
1237
1617
|
}
|
|
1238
|
-
|
|
1618
|
+
const session = {
|
|
1619
|
+
id: this.sessionStarts,
|
|
1620
|
+
proc,
|
|
1621
|
+
cleanupInput: cleanup,
|
|
1622
|
+
firstFrameAtMs: null,
|
|
1623
|
+
probe: new InputStreamProbe(),
|
|
1624
|
+
streamInfo: null,
|
|
1625
|
+
recording,
|
|
1626
|
+
superseded: false,
|
|
1627
|
+
detached: false,
|
|
1628
|
+
ended: false,
|
|
1629
|
+
};
|
|
1630
|
+
this.session = session;
|
|
1631
|
+
if (recording)
|
|
1632
|
+
this.ensureSegmentPolling();
|
|
1239
1633
|
const stderrBuffer = new ffmpegStderr_1.BoundedSessionStderr();
|
|
1240
1634
|
let settled = false;
|
|
1241
1635
|
const settle = (fn) => {
|
|
@@ -1245,20 +1639,33 @@ class RTSPStreamCameraProvider {
|
|
|
1245
1639
|
fn();
|
|
1246
1640
|
};
|
|
1247
1641
|
proc.stdout?.on('data', (chunk) => {
|
|
1642
|
+
// A session that is no longer the live one (stopped, or replaced by a
|
|
1643
|
+
// reconfigure) must not feed the ring, nor the splitter the next uses.
|
|
1644
|
+
if (this.session !== session)
|
|
1645
|
+
return;
|
|
1248
1646
|
for (const frame of this.splitter.push(chunk)) {
|
|
1249
1647
|
this.admitFrame(frame);
|
|
1648
|
+
if (session.firstFrameAtMs === null)
|
|
1649
|
+
this.onSessionFirstFrame(session);
|
|
1250
1650
|
// A decoded frame proves the session is healthy — reset the backoff.
|
|
1251
1651
|
this.currentRestartDelay = this.restartDelayMs;
|
|
1252
1652
|
settle(resolve);
|
|
1253
1653
|
}
|
|
1254
1654
|
});
|
|
1255
1655
|
proc.stderr?.on('data', (chunk) => {
|
|
1256
|
-
|
|
1656
|
+
const text = chunk.toString();
|
|
1657
|
+
stderrBuffer.append(text);
|
|
1658
|
+
if (!session.probe.done) {
|
|
1659
|
+
const info = session.probe.push(text);
|
|
1660
|
+
if (info)
|
|
1661
|
+
this.onSessionStreamInfo(session, info);
|
|
1662
|
+
}
|
|
1257
1663
|
});
|
|
1258
1664
|
proc.on('error', (err) => {
|
|
1259
|
-
|
|
1665
|
+
if (!session.superseded)
|
|
1666
|
+
this.lastErrorMessage = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err.message);
|
|
1260
1667
|
settle(() => reject(err));
|
|
1261
|
-
this.handleSessionEnd(stderrBuffer.text());
|
|
1668
|
+
this.handleSessionEnd(session, stderrBuffer.text());
|
|
1262
1669
|
});
|
|
1263
1670
|
proc.on('close', (code) => {
|
|
1264
1671
|
// A CLEAN EXIT IS A FAULT HERE. `code === 0` means success on the
|
|
@@ -1268,40 +1675,57 @@ class RTSPStreamCameraProvider {
|
|
|
1268
1675
|
// RTSP data: End of file". Both are restarts, never successes.
|
|
1269
1676
|
const stderr = stderrBuffer.text();
|
|
1270
1677
|
const summary = (0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr);
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
this.
|
|
1678
|
+
const message = summary || `ffmpeg stream session exited with code ${code}`;
|
|
1679
|
+
// A session stopped on purpose to change its outputs ended because we
|
|
1680
|
+
// asked it to: its last words are not this feed's error.
|
|
1681
|
+
if (!session.superseded)
|
|
1682
|
+
this.lastErrorMessage = message;
|
|
1683
|
+
settle(() => reject(new Error(`RTSP stream session ended during startup: ${message}`)));
|
|
1684
|
+
this.handleSessionEnd(session, stderr);
|
|
1274
1685
|
});
|
|
1275
1686
|
});
|
|
1276
1687
|
}
|
|
1688
|
+
/**
|
|
1689
|
+
* Detach the live session and stop its ffmpeg. Its own exit later finishes
|
|
1690
|
+
* its recording, and is never restarted: whoever called this owns what
|
|
1691
|
+
* happens next (close, shed, or open()'s retry loop).
|
|
1692
|
+
*/
|
|
1277
1693
|
stopProcess() {
|
|
1278
|
-
const
|
|
1279
|
-
this.
|
|
1280
|
-
if (
|
|
1694
|
+
const session = this.session;
|
|
1695
|
+
this.session = null;
|
|
1696
|
+
if (session) {
|
|
1697
|
+
session.detached = true;
|
|
1698
|
+
this.killSession(session);
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
killSession(session) {
|
|
1702
|
+
const proc = session.proc;
|
|
1703
|
+
try {
|
|
1704
|
+
proc.kill('SIGTERM');
|
|
1705
|
+
}
|
|
1706
|
+
catch {
|
|
1707
|
+
/* already gone */
|
|
1708
|
+
}
|
|
1709
|
+
// Bounded escalation: an ffmpeg wedged on a half-open RTSP socket ignores
|
|
1710
|
+
// SIGTERM, and a connector that leaks one child per restart is the
|
|
1711
|
+
// 28-children incident wearing a different hat.
|
|
1712
|
+
const timer = setTimeout(() => {
|
|
1281
1713
|
try {
|
|
1282
|
-
proc.kill('
|
|
1714
|
+
proc.kill('SIGKILL');
|
|
1283
1715
|
}
|
|
1284
1716
|
catch {
|
|
1285
1717
|
/* already gone */
|
|
1286
1718
|
}
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
proc.kill('SIGKILL');
|
|
1293
|
-
}
|
|
1294
|
-
catch {
|
|
1295
|
-
/* already gone */
|
|
1296
|
-
}
|
|
1297
|
-
}, 2000);
|
|
1298
|
-
if (typeof timer.unref === 'function')
|
|
1299
|
-
timer.unref();
|
|
1719
|
+
}, 2000);
|
|
1720
|
+
if (typeof timer.unref === 'function')
|
|
1721
|
+
timer.unref();
|
|
1722
|
+
try {
|
|
1723
|
+
session.cleanupInput();
|
|
1300
1724
|
}
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
this.cleanupInput = null;
|
|
1725
|
+
catch {
|
|
1726
|
+
/* best-effort */
|
|
1304
1727
|
}
|
|
1728
|
+
session.cleanupInput = () => undefined;
|
|
1305
1729
|
}
|
|
1306
1730
|
/**
|
|
1307
1731
|
* A session ended. While the provider is open this ALWAYS schedules a restart
|
|
@@ -1316,17 +1740,45 @@ class RTSPStreamCameraProvider {
|
|
|
1316
1740
|
* Waiters are woken on the way out so a `getFrame()` blocked on a session
|
|
1317
1741
|
* that just died reaches its stale error rather than sitting out the full
|
|
1318
1742
|
* deadline for a stream that is provably not coming back.
|
|
1743
|
+
*
|
|
1744
|
+
* Only the LIVE session's end does any of that. A session already detached
|
|
1745
|
+
* (stopProcess) or superseded (a reconfigure) finishes its recording and
|
|
1746
|
+
* either stops there or, for a reconfigure, starts its replacement.
|
|
1319
1747
|
*/
|
|
1320
|
-
handleSessionEnd(stderr) {
|
|
1321
|
-
if (
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1748
|
+
handleSessionEnd(session, stderr) {
|
|
1749
|
+
if (session.ended)
|
|
1750
|
+
return; // 'error' and 'close' can both arrive
|
|
1751
|
+
session.ended = true;
|
|
1752
|
+
try {
|
|
1753
|
+
session.cleanupInput();
|
|
1754
|
+
}
|
|
1755
|
+
catch {
|
|
1756
|
+
/* best-effort */
|
|
1757
|
+
}
|
|
1758
|
+
session.cleanupInput = () => undefined;
|
|
1759
|
+
if (session.recording)
|
|
1760
|
+
this.finishSessionRecording(session, stderr);
|
|
1761
|
+
const current = this.session === session;
|
|
1762
|
+
if (current) {
|
|
1763
|
+
this.session = null;
|
|
1764
|
+
// Wake anyone blocked in getFrame(): the session that would have fed them
|
|
1765
|
+
// is gone, so they should reach their stale error now rather than sit out
|
|
1766
|
+
// a full deadline waiting for a stream that is provably not coming back.
|
|
1767
|
+
this.wakeWaiters();
|
|
1768
|
+
}
|
|
1769
|
+
if (session.superseded) {
|
|
1770
|
+
if (this.reconfigurePendingFor === session) {
|
|
1771
|
+
this.reconfigurePendingFor = null;
|
|
1772
|
+
if (this.opened && !this.fallback && this.session === null && !this.restartTimer) {
|
|
1773
|
+
this.startSession().catch((err) => {
|
|
1774
|
+
this.lastErrorMessage = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err?.message ?? String(err));
|
|
1775
|
+
});
|
|
1776
|
+
}
|
|
1777
|
+
}
|
|
1778
|
+
return;
|
|
1779
|
+
}
|
|
1780
|
+
if (!current)
|
|
1781
|
+
return;
|
|
1330
1782
|
if (!this.opened)
|
|
1331
1783
|
return;
|
|
1332
1784
|
if (this.startingUp)
|
|
@@ -1349,9 +1801,745 @@ class RTSPStreamCameraProvider {
|
|
|
1349
1801
|
if (typeof this.restartTimer.unref === 'function')
|
|
1350
1802
|
this.restartTimer.unref();
|
|
1351
1803
|
}
|
|
1804
|
+
// ── segment recording ────────────────────────────────────────────────────
|
|
1805
|
+
/** What the NEXT session should record, or null for look-only. */
|
|
1806
|
+
planRecording() {
|
|
1807
|
+
const cfg = this.segmentConfig;
|
|
1808
|
+
if (!cfg || !cfg.enabled)
|
|
1809
|
+
return null;
|
|
1810
|
+
// A crop belongs to the look output; a stream copy would record the whole
|
|
1811
|
+
// composite under one tile's screen. Only a crop-less persistent feed records.
|
|
1812
|
+
if (!this.persistentRequested || this.crop !== undefined)
|
|
1813
|
+
return null;
|
|
1814
|
+
const codec = this.streamInfo?.codec ?? null;
|
|
1815
|
+
if (codec !== null && !exports.RECORDABLE_CODECS.includes(codec))
|
|
1816
|
+
return null;
|
|
1817
|
+
const plan = {
|
|
1818
|
+
dir: cfg.dir,
|
|
1819
|
+
segmentSeconds: cfg.segmentSeconds,
|
|
1820
|
+
// Tagged unless the stream is KNOWN to be H.264. HEVC needs hvc1 (ffmpeg
|
|
1821
|
+
// writes hev1 otherwise), and on H.264 the segment muxer resets a tag
|
|
1822
|
+
// its mp4 muxer maps to another codec — measured on ffmpeg 6.1.1, the
|
|
1823
|
+
// segment comes out avc1 — so the very first session can record before
|
|
1824
|
+
// ffmpeg has described the input, and needs no restart once it has.
|
|
1825
|
+
tagHvc1: codec !== 'h264',
|
|
1826
|
+
// Present since ffmpeg 5; an older binary gets the bare segment_time.
|
|
1827
|
+
minSegDuration: this.ffmpegMajorVersion >= 5,
|
|
1828
|
+
};
|
|
1829
|
+
if (this.segmentSuspension && this.now() < this.segmentSuspension.untilMs)
|
|
1830
|
+
return null;
|
|
1831
|
+
return plan;
|
|
1832
|
+
}
|
|
1833
|
+
/** Does a running session's second output already give what `want` asks for? */
|
|
1834
|
+
sessionSatisfies(have, want) {
|
|
1835
|
+
if (!want)
|
|
1836
|
+
return have === null;
|
|
1837
|
+
if (!have)
|
|
1838
|
+
return false;
|
|
1839
|
+
if (have.dir !== want.dir ||
|
|
1840
|
+
have.segmentSeconds !== want.segmentSeconds ||
|
|
1841
|
+
have.minSegDuration !== want.minSegDuration) {
|
|
1842
|
+
return false;
|
|
1843
|
+
}
|
|
1844
|
+
if (have.tagHvc1 === want.tagHvc1)
|
|
1845
|
+
return true;
|
|
1846
|
+
// A speculative hvc1 tag on what turned out to be H.264 is a no-op.
|
|
1847
|
+
return have.tagHvc1 && this.streamInfo?.codec === 'h264';
|
|
1848
|
+
}
|
|
1849
|
+
/**
|
|
1850
|
+
* Bring the live session's second output in line with the plan — by
|
|
1851
|
+
* restarting it once, only after its first frame, and never with a second
|
|
1852
|
+
* reconfigure already in flight. The restart is not a fault: it is counted
|
|
1853
|
+
* in `segments.reconfigures`, not `restarts`, and keeps the recorder slot.
|
|
1854
|
+
*/
|
|
1855
|
+
reconcileRecording() {
|
|
1856
|
+
const session = this.session;
|
|
1857
|
+
if (!session || !this.opened || this.fallback || this.startingUp)
|
|
1858
|
+
return;
|
|
1859
|
+
if (session.firstFrameAtMs === null || this.reconfigurePendingFor)
|
|
1860
|
+
return;
|
|
1861
|
+
const want = this.planRecording();
|
|
1862
|
+
const have = session.recording ? session.recording.plan : null;
|
|
1863
|
+
if (this.sessionSatisfies(have, want))
|
|
1864
|
+
return;
|
|
1865
|
+
this.segCounters.reconfigures += 1;
|
|
1866
|
+
this.log('info', want
|
|
1867
|
+
? `RTSP stream session restarting to record ${want.segmentSeconds}s segments`
|
|
1868
|
+
: 'RTSP stream session restarting to stop segment recording');
|
|
1869
|
+
session.superseded = true;
|
|
1870
|
+
this.reconfigurePendingFor = session;
|
|
1871
|
+
this.session = null;
|
|
1872
|
+
this.killSession(session);
|
|
1873
|
+
}
|
|
1874
|
+
onSessionFirstFrame(session) {
|
|
1875
|
+
session.firstFrameAtMs = this.now();
|
|
1876
|
+
this.reconcileRecording();
|
|
1877
|
+
}
|
|
1878
|
+
onSessionStreamInfo(session, info) {
|
|
1879
|
+
session.streamInfo = info;
|
|
1880
|
+
if (this.session !== session)
|
|
1881
|
+
return;
|
|
1882
|
+
const previous = this.streamInfo;
|
|
1883
|
+
this.streamInfo = info;
|
|
1884
|
+
if (!previous || previous.codec !== info.codec)
|
|
1885
|
+
this.reconcileRecording();
|
|
1886
|
+
}
|
|
1887
|
+
/** The work directory for a session that will record, or null for look-only. */
|
|
1888
|
+
prepareSessionRecording() {
|
|
1889
|
+
const plan = this.planRecording();
|
|
1890
|
+
if (!plan)
|
|
1891
|
+
return null;
|
|
1892
|
+
const workDir = path.join(plan.dir, `${SESSION_WORKDIR_PREFIX}${this.now()}-${this.sessionStarts + 1}`);
|
|
1893
|
+
try {
|
|
1894
|
+
fs.mkdirSync(path.join(plan.dir, exports.CLOSED_SEGMENTS_DIRNAME), { recursive: true });
|
|
1895
|
+
fs.mkdirSync(workDir, { recursive: true });
|
|
1896
|
+
}
|
|
1897
|
+
catch (err) {
|
|
1898
|
+
// A directory we cannot create is the second output's failure, never the
|
|
1899
|
+
// look path's: say why, pause recording, and run this session look-only.
|
|
1900
|
+
this.suspendRecording(`segment directory unavailable: ${errorText(err)}`);
|
|
1901
|
+
return null;
|
|
1902
|
+
}
|
|
1903
|
+
return {
|
|
1904
|
+
plan,
|
|
1905
|
+
workDir,
|
|
1906
|
+
csvPath: path.join(workDir, 'segments.csv'),
|
|
1907
|
+
csvOffset: 0,
|
|
1908
|
+
csvRemainder: '',
|
|
1909
|
+
pending: [],
|
|
1910
|
+
handled: new Set(),
|
|
1911
|
+
anchor: null,
|
|
1912
|
+
closedCount: 0,
|
|
1913
|
+
};
|
|
1914
|
+
}
|
|
1915
|
+
/** Pause recording, doubling from SEGMENT_SUSPEND_BASE_MS, then reconcile again. */
|
|
1916
|
+
suspendRecording(reason) {
|
|
1917
|
+
this.segCounters.outputFailures += 1;
|
|
1918
|
+
const exponent = Math.min(this.consecutiveOutputFailures, 16);
|
|
1919
|
+
const cooldownMs = Math.min(exports.SEGMENT_SUSPEND_MAX_MS, exports.SEGMENT_SUSPEND_BASE_MS * 2 ** exponent);
|
|
1920
|
+
this.consecutiveOutputFailures += 1;
|
|
1921
|
+
this.segmentSuspension = { untilMs: this.now() + cooldownMs };
|
|
1922
|
+
this.segCounters.lastError = `${reason}; recording paused ${Math.round(cooldownMs / 1000)}s`;
|
|
1923
|
+
this.log('warn', `segment recording: ${this.segCounters.lastError}`);
|
|
1924
|
+
if (this.segmentSuspendTimer)
|
|
1925
|
+
clearTimeout(this.segmentSuspendTimer);
|
|
1926
|
+
this.segmentSuspendTimer = setTimeout(() => {
|
|
1927
|
+
this.segmentSuspendTimer = null;
|
|
1928
|
+
this.reconcileRecording();
|
|
1929
|
+
}, cooldownMs);
|
|
1930
|
+
if (typeof this.segmentSuspendTimer.unref === 'function')
|
|
1931
|
+
this.segmentSuspendTimer.unref();
|
|
1932
|
+
}
|
|
1933
|
+
clearSegmentSuspension() {
|
|
1934
|
+
this.segmentSuspension = null;
|
|
1935
|
+
if (this.segmentSuspendTimer) {
|
|
1936
|
+
clearTimeout(this.segmentSuspendTimer);
|
|
1937
|
+
this.segmentSuspendTimer = null;
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
ensureSegmentPolling() {
|
|
1941
|
+
if (this.segmentPollTimer)
|
|
1942
|
+
return;
|
|
1943
|
+
this.lastSegmentPollAtMs = this.now();
|
|
1944
|
+
this.segmentPollTimer = setInterval(() => this.pollSegments(), SEGMENT_POLL_MS);
|
|
1945
|
+
if (typeof this.segmentPollTimer.unref === 'function')
|
|
1946
|
+
this.segmentPollTimer.unref();
|
|
1947
|
+
}
|
|
1948
|
+
stopSegmentPolling() {
|
|
1949
|
+
if (this.segmentPollTimer) {
|
|
1950
|
+
clearInterval(this.segmentPollTimer);
|
|
1951
|
+
this.segmentPollTimer = null;
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
/** One read of the live session's segment list: new closes move into the ring. */
|
|
1955
|
+
pollSegments() {
|
|
1956
|
+
const nowMs = this.now();
|
|
1957
|
+
const onTime = this.lastSegmentPollAtMs !== null && nowMs - this.lastSegmentPollAtMs <= 2 * SEGMENT_POLL_MS;
|
|
1958
|
+
this.lastSegmentPollAtMs = nowMs;
|
|
1959
|
+
const session = this.session;
|
|
1960
|
+
const rec = session?.recording;
|
|
1961
|
+
if (!session || !rec) {
|
|
1962
|
+
this.stopSegmentPolling();
|
|
1963
|
+
return;
|
|
1964
|
+
}
|
|
1965
|
+
try {
|
|
1966
|
+
const fresh = this.readSegmentList(session);
|
|
1967
|
+
if (fresh.length > 0) {
|
|
1968
|
+
if (!rec.anchor && rec.pending.length > 0) {
|
|
1969
|
+
this.anchorFor(rec, rec.pending[0], session.firstFrameAtMs, session.streamInfo);
|
|
1970
|
+
}
|
|
1971
|
+
this.guardAnchorDrift(rec, fresh[fresh.length - 1], nowMs, onTime, session.streamInfo);
|
|
1972
|
+
}
|
|
1973
|
+
if (rec.pending.length > 0 && this.flushPending(session) > 0)
|
|
1974
|
+
this.enforceRing();
|
|
1975
|
+
}
|
|
1976
|
+
catch (err) {
|
|
1977
|
+
this.segCounters.lastError = `segment list: ${errorText(err)}`;
|
|
1978
|
+
}
|
|
1979
|
+
}
|
|
1980
|
+
/** Read whatever the segment list gained since the last read. */
|
|
1981
|
+
readSegmentList(session) {
|
|
1982
|
+
const rec = session.recording;
|
|
1983
|
+
if (!rec)
|
|
1984
|
+
return [];
|
|
1985
|
+
let size;
|
|
1986
|
+
try {
|
|
1987
|
+
size = fs.statSync(rec.csvPath).size;
|
|
1988
|
+
}
|
|
1989
|
+
catch {
|
|
1990
|
+
return [];
|
|
1991
|
+
}
|
|
1992
|
+
if (size < rec.csvOffset) {
|
|
1993
|
+
rec.csvOffset = 0;
|
|
1994
|
+
rec.csvRemainder = '';
|
|
1995
|
+
}
|
|
1996
|
+
if (size === rec.csvOffset)
|
|
1997
|
+
return [];
|
|
1998
|
+
const buf = Buffer.alloc(size - rec.csvOffset);
|
|
1999
|
+
const fd = fs.openSync(rec.csvPath, 'r');
|
|
2000
|
+
let read = 0;
|
|
2001
|
+
try {
|
|
2002
|
+
read = fs.readSync(fd, buf, 0, buf.length, rec.csvOffset);
|
|
2003
|
+
}
|
|
2004
|
+
finally {
|
|
2005
|
+
fs.closeSync(fd);
|
|
2006
|
+
}
|
|
2007
|
+
rec.csvOffset += read;
|
|
2008
|
+
const { entries, remainder } = parseSegmentListCsv(rec.csvRemainder + buf.subarray(0, read).toString('utf8'));
|
|
2009
|
+
rec.csvRemainder = remainder;
|
|
2010
|
+
const fresh = [];
|
|
2011
|
+
for (const entry of entries) {
|
|
2012
|
+
if (rec.handled.has(entry.name))
|
|
2013
|
+
continue;
|
|
2014
|
+
rec.handled.add(entry.name);
|
|
2015
|
+
rec.pending.push(entry);
|
|
2016
|
+
fresh.push(entry);
|
|
2017
|
+
}
|
|
2018
|
+
return fresh;
|
|
2019
|
+
}
|
|
2020
|
+
/** Move listed segments into the ring, in list order. Returns how many moved. */
|
|
2021
|
+
flushPending(session) {
|
|
2022
|
+
const rec = session.recording;
|
|
2023
|
+
if (!rec)
|
|
2024
|
+
return 0;
|
|
2025
|
+
let closed = 0;
|
|
2026
|
+
while (rec.pending.length > 0) {
|
|
2027
|
+
const outcome = this.closeSegment(session, rec, rec.pending[0]);
|
|
2028
|
+
if (outcome === 'retry')
|
|
2029
|
+
break;
|
|
2030
|
+
rec.pending.shift();
|
|
2031
|
+
if (outcome === 'closed')
|
|
2032
|
+
closed += 1;
|
|
2033
|
+
}
|
|
2034
|
+
return closed;
|
|
2035
|
+
}
|
|
2036
|
+
closeSegment(session, rec, entry) {
|
|
2037
|
+
const src = path.join(rec.workDir, entry.name);
|
|
2038
|
+
let size;
|
|
2039
|
+
try {
|
|
2040
|
+
const st = fs.statSync(src);
|
|
2041
|
+
size = st.isFile() ? st.size : 0;
|
|
2042
|
+
}
|
|
2043
|
+
catch (err) {
|
|
2044
|
+
return err?.code === 'ENOENT' ? 'gone' : 'retry';
|
|
2045
|
+
}
|
|
2046
|
+
if (size <= 0) {
|
|
2047
|
+
try {
|
|
2048
|
+
fs.unlinkSync(src);
|
|
2049
|
+
}
|
|
2050
|
+
catch {
|
|
2051
|
+
/* best-effort */
|
|
2052
|
+
}
|
|
2053
|
+
this.segCounters.partialsDeleted += 1;
|
|
2054
|
+
return 'gone';
|
|
2055
|
+
}
|
|
2056
|
+
const anchor = this.anchorFor(rec, entry, session.firstFrameAtMs, session.streamInfo);
|
|
2057
|
+
const captureStartMs = Math.round(anchor.wallMs + (entry.startSec - anchor.startSec) * 1000);
|
|
2058
|
+
const moved = this.moveIntoRing(rec.plan.dir, src, path.basename(rec.workDir), entry, captureStartMs, size, session.streamInfo, false);
|
|
2059
|
+
if (!moved)
|
|
2060
|
+
return 'retry';
|
|
2061
|
+
rec.closedCount += 1;
|
|
2062
|
+
return 'closed';
|
|
2063
|
+
}
|
|
2064
|
+
/**
|
|
2065
|
+
* The wall clock of the session's FIRST listed segment.
|
|
2066
|
+
*
|
|
2067
|
+
* The first decoded frame and the first copied packet are the same keyframe
|
|
2068
|
+
* (a stream copy drops what precedes it), so the first listed segment starts
|
|
2069
|
+
* at the first frame's wall clock and every later one at its offset from it.
|
|
2070
|
+
* When ffmpeg starts the output timeline at 0 — measured 0.000000 for H.264
|
|
2071
|
+
* and HEVC through mediamtx — that is exactly first frame + startSec.
|
|
2072
|
+
*/
|
|
2073
|
+
anchorFor(rec, entry, firstFrameAtMs, stream) {
|
|
2074
|
+
if (!rec.anchor) {
|
|
2075
|
+
rec.anchor = {
|
|
2076
|
+
wallMs: firstFrameAtMs ?? this.now() - (entry.endSec - entry.startSec) * 1000,
|
|
2077
|
+
startSec: entry.startSec,
|
|
2078
|
+
};
|
|
2079
|
+
this.persistAnchor(rec, stream);
|
|
2080
|
+
}
|
|
2081
|
+
return rec.anchor;
|
|
2082
|
+
}
|
|
2083
|
+
/**
|
|
2084
|
+
* Keep the anchor honest against the one wall-clock fact a close gives us:
|
|
2085
|
+
* a segment cannot end after we saw it closed, and on a timely poll it ended
|
|
2086
|
+
* at most one poll before. The camera's media clock is not the wall clock,
|
|
2087
|
+
* and a session runs for days.
|
|
2088
|
+
*/
|
|
2089
|
+
guardAnchorDrift(rec, newest, nowMs, onTime, stream) {
|
|
2090
|
+
if (!rec.anchor)
|
|
2091
|
+
return;
|
|
2092
|
+
const predictedEndMs = rec.anchor.wallMs + (newest.endSec - rec.anchor.startSec) * 1000;
|
|
2093
|
+
const drift = predictedEndMs - nowMs;
|
|
2094
|
+
this.segCounters.lastAnchorDriftMs = Math.round(drift);
|
|
2095
|
+
let shift = 0;
|
|
2096
|
+
if (drift > ANCHOR_FUTURE_TOLERANCE_MS)
|
|
2097
|
+
shift = -drift;
|
|
2098
|
+
else if (onTime && drift < -(SEGMENT_POLL_MS + ANCHOR_LAG_TOLERANCE_MS))
|
|
2099
|
+
shift = -drift - SEGMENT_POLL_MS / 2;
|
|
2100
|
+
if (shift === 0)
|
|
2101
|
+
return;
|
|
2102
|
+
rec.anchor.wallMs += shift;
|
|
2103
|
+
this.segCounters.reanchors += 1;
|
|
2104
|
+
this.persistAnchor(rec, stream);
|
|
2105
|
+
}
|
|
2106
|
+
persistAnchor(rec, stream) {
|
|
2107
|
+
if (!rec.anchor)
|
|
2108
|
+
return;
|
|
2109
|
+
try {
|
|
2110
|
+
writeFileAtomic(path.join(rec.workDir, 'anchor.json'), JSON.stringify({ ...rec.anchor, stream }));
|
|
2111
|
+
}
|
|
2112
|
+
catch {
|
|
2113
|
+
/* recovery falls back to the file's own last write */
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
/**
|
|
2117
|
+
* Write the sidecar, then move the closed file beside it, then emit. Null
|
|
2118
|
+
* when the move must be retried (Windows refuses to rename a file ffmpeg
|
|
2119
|
+
* still holds; the next poll asks again).
|
|
2120
|
+
*/
|
|
2121
|
+
moveIntoRing(dir, src, tag, entry, captureStartMs, bytes, stream, recovered) {
|
|
2122
|
+
const durationMs = Math.max(0, Math.round((entry.endSec - entry.startSec) * 1000));
|
|
2123
|
+
// Zero-padded capture start first, so a name sort is a time sort — the
|
|
2124
|
+
// ring evicts oldest-first by name.
|
|
2125
|
+
const base = `${String(Math.max(0, captureStartMs)).padStart(13, '0')}-${tag}-${entry.name.replace(/\.mp4$/i, '')}`;
|
|
2126
|
+
const closedDir = path.join(dir, exports.CLOSED_SEGMENTS_DIRNAME);
|
|
2127
|
+
const file = path.join(closedDir, `${base}.mp4`);
|
|
2128
|
+
const metaFile = path.join(closedDir, `${base}.json`);
|
|
2129
|
+
const sidecar = {
|
|
2130
|
+
version: 1,
|
|
2131
|
+
startSec: entry.startSec,
|
|
2132
|
+
endSec: entry.endSec,
|
|
2133
|
+
captureStartMs,
|
|
2134
|
+
captureEndMs: captureStartMs + durationMs,
|
|
2135
|
+
bytes,
|
|
2136
|
+
stream,
|
|
2137
|
+
};
|
|
2138
|
+
try {
|
|
2139
|
+
fs.mkdirSync(closedDir, { recursive: true });
|
|
2140
|
+
writeFileAtomic(metaFile, JSON.stringify(sidecar));
|
|
2141
|
+
}
|
|
2142
|
+
catch (err) {
|
|
2143
|
+
this.segCounters.lastError = `segment sidecar: ${errorText(err)}`;
|
|
2144
|
+
return null;
|
|
2145
|
+
}
|
|
2146
|
+
try {
|
|
2147
|
+
fs.renameSync(src, file);
|
|
2148
|
+
}
|
|
2149
|
+
catch (err) {
|
|
2150
|
+
try {
|
|
2151
|
+
fs.unlinkSync(metaFile);
|
|
2152
|
+
}
|
|
2153
|
+
catch {
|
|
2154
|
+
/* best-effort */
|
|
2155
|
+
}
|
|
2156
|
+
if (!isBusyError(err))
|
|
2157
|
+
this.segCounters.lastError = `segment move: ${errorText(err)}`;
|
|
2158
|
+
return null;
|
|
2159
|
+
}
|
|
2160
|
+
const segment = {
|
|
2161
|
+
file,
|
|
2162
|
+
metaFile,
|
|
2163
|
+
startSec: entry.startSec,
|
|
2164
|
+
endSec: entry.endSec,
|
|
2165
|
+
captureStartMs,
|
|
2166
|
+
captureEndMs: sidecar.captureEndMs,
|
|
2167
|
+
bytes,
|
|
2168
|
+
stream,
|
|
2169
|
+
recovered,
|
|
2170
|
+
};
|
|
2171
|
+
this.countSegment(segment);
|
|
2172
|
+
this.emitSegment(segment);
|
|
2173
|
+
return segment;
|
|
2174
|
+
}
|
|
2175
|
+
countSegment(segment) {
|
|
2176
|
+
const seconds = Math.max(0, segment.endSec - segment.startSec);
|
|
2177
|
+
if (segment.recovered) {
|
|
2178
|
+
this.segCounters.recovered += 1;
|
|
2179
|
+
}
|
|
2180
|
+
else {
|
|
2181
|
+
this.segCounters.closed += 1;
|
|
2182
|
+
this.segCounters.secondsClosed += seconds;
|
|
2183
|
+
this.segCounters.bytesClosed += segment.bytes;
|
|
2184
|
+
this.segCounters.lastSegmentAtMs = this.now();
|
|
2185
|
+
}
|
|
2186
|
+
if (seconds > 0) {
|
|
2187
|
+
this.measuredSegmentBytes += segment.bytes;
|
|
2188
|
+
this.measuredSegmentSeconds += seconds;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
emitSegment(segment) {
|
|
2192
|
+
try {
|
|
2193
|
+
this.emit('segment', segment);
|
|
2194
|
+
}
|
|
2195
|
+
catch (err) {
|
|
2196
|
+
this.log('warn', `segment recording: a 'segment' listener threw: ${errorText(err)}`);
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
/**
|
|
2200
|
+
* A session that recorded has ended: read its list one last time, move what
|
|
2201
|
+
* it closed, judge the second output, and delete what it never listed.
|
|
2202
|
+
*/
|
|
2203
|
+
finishSessionRecording(session, stderr) {
|
|
2204
|
+
const rec = session.recording;
|
|
2205
|
+
if (!rec)
|
|
2206
|
+
return;
|
|
2207
|
+
try {
|
|
2208
|
+
this.readSegmentList(session);
|
|
2209
|
+
if (!rec.anchor && rec.pending.length > 0) {
|
|
2210
|
+
this.anchorFor(rec, rec.pending[0], session.firstFrameAtMs, session.streamInfo);
|
|
2211
|
+
}
|
|
2212
|
+
this.flushPending(session);
|
|
2213
|
+
}
|
|
2214
|
+
catch (err) {
|
|
2215
|
+
this.segCounters.lastError = `segment list: ${errorText(err)}`;
|
|
2216
|
+
}
|
|
2217
|
+
// Judge the second output, for a session we did not stop ourselves:
|
|
2218
|
+
// - its input opened and it never produced a frame: ffmpeg opens the
|
|
2219
|
+
// outputs right after the input, so the second output is what failed;
|
|
2220
|
+
// - it closed nothing and ffmpeg named a write failure.
|
|
2221
|
+
// Either way the next session must not carry it. A camera that dropped
|
|
2222
|
+
// mid-segment says neither, and keeps recording through its restart.
|
|
2223
|
+
const judged = !session.superseded && !session.detached && rec.closedCount === 0;
|
|
2224
|
+
if (judged && session.probe.inputOpened && session.firstFrameAtMs === null) {
|
|
2225
|
+
this.suspendRecording('a session with segment recording opened its input and produced no frame');
|
|
2226
|
+
}
|
|
2227
|
+
else if (judged && SEGMENT_OUTPUT_FAILURE_RE.test(stderr)) {
|
|
2228
|
+
this.suspendRecording(`segment output failed: ${(0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr.match(SEGMENT_OUTPUT_FAILURE_RE)?.[0] ?? '', 120)}`);
|
|
2229
|
+
}
|
|
2230
|
+
else if (rec.closedCount > 0) {
|
|
2231
|
+
this.consecutiveOutputFailures = 0;
|
|
2232
|
+
}
|
|
2233
|
+
// Everything left was never listed: the segment ffmpeg was still writing,
|
|
2234
|
+
// the list and the anchor. A listed file the OS would not let us move yet
|
|
2235
|
+
// keeps the directory for the next open()'s recovery instead.
|
|
2236
|
+
if (rec.pending.length === 0)
|
|
2237
|
+
this.removeWorkDir(rec.workDir, true);
|
|
2238
|
+
this.enforceRing();
|
|
2239
|
+
if (!this.session?.recording)
|
|
2240
|
+
this.stopSegmentPolling();
|
|
2241
|
+
}
|
|
2242
|
+
removeWorkDir(workDir, countPartials = false) {
|
|
2243
|
+
let names = [];
|
|
2244
|
+
try {
|
|
2245
|
+
names = fs.readdirSync(workDir);
|
|
2246
|
+
}
|
|
2247
|
+
catch {
|
|
2248
|
+
return;
|
|
2249
|
+
}
|
|
2250
|
+
for (const name of names) {
|
|
2251
|
+
try {
|
|
2252
|
+
fs.unlinkSync(path.join(workDir, name));
|
|
2253
|
+
if (countPartials && name.toLowerCase().endsWith('.mp4'))
|
|
2254
|
+
this.segCounters.partialsDeleted += 1;
|
|
2255
|
+
}
|
|
2256
|
+
catch {
|
|
2257
|
+
/* best-effort */
|
|
2258
|
+
}
|
|
2259
|
+
}
|
|
2260
|
+
try {
|
|
2261
|
+
fs.rmdirSync(workDir);
|
|
2262
|
+
}
|
|
2263
|
+
catch {
|
|
2264
|
+
/* best-effort */
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
/**
|
|
2268
|
+
* Hand out what an earlier process left: closed segments with sidecars, and
|
|
2269
|
+
* listed segments still in a session work directory. Unlisted files are
|
|
2270
|
+
* partials and are deleted. Runs once per directory, before the first session.
|
|
2271
|
+
*/
|
|
2272
|
+
recoverSegments() {
|
|
2273
|
+
const cfg = this.segmentConfig;
|
|
2274
|
+
if (!cfg)
|
|
2275
|
+
return;
|
|
2276
|
+
this.segmentsRecoveredFor = cfg.dir;
|
|
2277
|
+
let names;
|
|
2278
|
+
try {
|
|
2279
|
+
names = fs.readdirSync(cfg.dir);
|
|
2280
|
+
}
|
|
2281
|
+
catch {
|
|
2282
|
+
return; // nothing recorded here yet
|
|
2283
|
+
}
|
|
2284
|
+
// closed/ FIRST: recovering a work directory below moves files INTO it.
|
|
2285
|
+
const closedDir = path.join(cfg.dir, exports.CLOSED_SEGMENTS_DIRNAME);
|
|
2286
|
+
let closed = [];
|
|
2287
|
+
try {
|
|
2288
|
+
closed = fs.readdirSync(closedDir).sort();
|
|
2289
|
+
}
|
|
2290
|
+
catch {
|
|
2291
|
+
closed = [];
|
|
2292
|
+
}
|
|
2293
|
+
const present = new Set(closed);
|
|
2294
|
+
for (const name of closed) {
|
|
2295
|
+
const file = path.join(closedDir, name);
|
|
2296
|
+
const lower = name.toLowerCase();
|
|
2297
|
+
if (lower.endsWith('.tmp')) {
|
|
2298
|
+
try {
|
|
2299
|
+
fs.unlinkSync(file);
|
|
2300
|
+
}
|
|
2301
|
+
catch {
|
|
2302
|
+
/* best-effort */
|
|
2303
|
+
}
|
|
2304
|
+
continue;
|
|
2305
|
+
}
|
|
2306
|
+
if (lower.endsWith('.json')) {
|
|
2307
|
+
if (!present.has(name.replace(/\.json$/i, '.mp4'))) {
|
|
2308
|
+
try {
|
|
2309
|
+
fs.unlinkSync(file);
|
|
2310
|
+
}
|
|
2311
|
+
catch {
|
|
2312
|
+
/* best-effort */
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
continue;
|
|
2316
|
+
}
|
|
2317
|
+
if (!lower.endsWith('.mp4'))
|
|
2318
|
+
continue;
|
|
2319
|
+
const metaFile = file.replace(/\.mp4$/i, '.json');
|
|
2320
|
+
const sidecar = readSidecar(metaFile);
|
|
2321
|
+
let bytes;
|
|
2322
|
+
try {
|
|
2323
|
+
bytes = fs.statSync(file).size;
|
|
2324
|
+
}
|
|
2325
|
+
catch {
|
|
2326
|
+
continue;
|
|
2327
|
+
}
|
|
2328
|
+
if (!sidecar) {
|
|
2329
|
+
// No capture time, so it can never be indexed.
|
|
2330
|
+
try {
|
|
2331
|
+
fs.unlinkSync(file);
|
|
2332
|
+
}
|
|
2333
|
+
catch {
|
|
2334
|
+
/* best-effort */
|
|
2335
|
+
}
|
|
2336
|
+
this.segCounters.partialsDeleted += 1;
|
|
2337
|
+
continue;
|
|
2338
|
+
}
|
|
2339
|
+
const segment = {
|
|
2340
|
+
file,
|
|
2341
|
+
metaFile,
|
|
2342
|
+
startSec: sidecar.startSec,
|
|
2343
|
+
endSec: sidecar.endSec,
|
|
2344
|
+
captureStartMs: sidecar.captureStartMs,
|
|
2345
|
+
captureEndMs: sidecar.captureEndMs,
|
|
2346
|
+
bytes,
|
|
2347
|
+
stream: sidecar.stream,
|
|
2348
|
+
recovered: true,
|
|
2349
|
+
};
|
|
2350
|
+
this.countSegment(segment);
|
|
2351
|
+
this.emitSegment(segment);
|
|
2352
|
+
}
|
|
2353
|
+
const live = this.session?.recording?.workDir ?? null;
|
|
2354
|
+
for (const name of names.sort()) {
|
|
2355
|
+
if (!name.startsWith(SESSION_WORKDIR_PREFIX))
|
|
2356
|
+
continue;
|
|
2357
|
+
const workDir = path.join(cfg.dir, name);
|
|
2358
|
+
if (workDir === live)
|
|
2359
|
+
continue;
|
|
2360
|
+
try {
|
|
2361
|
+
this.recoverWorkDir(cfg.dir, workDir);
|
|
2362
|
+
}
|
|
2363
|
+
catch (err) {
|
|
2364
|
+
this.segCounters.lastError = `segment recovery: ${errorText(err)}`;
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
this.enforceRing();
|
|
2368
|
+
}
|
|
2369
|
+
recoverWorkDir(dir, workDir) {
|
|
2370
|
+
let text = '';
|
|
2371
|
+
try {
|
|
2372
|
+
text = fs.readFileSync(path.join(workDir, 'segments.csv'), 'utf8');
|
|
2373
|
+
}
|
|
2374
|
+
catch {
|
|
2375
|
+
text = '';
|
|
2376
|
+
}
|
|
2377
|
+
const { entries } = parseSegmentListCsv(text);
|
|
2378
|
+
let anchor = null;
|
|
2379
|
+
let stream = null;
|
|
2380
|
+
try {
|
|
2381
|
+
const raw = JSON.parse(fs.readFileSync(path.join(workDir, 'anchor.json'), 'utf8'));
|
|
2382
|
+
if (Number.isFinite(raw?.wallMs) && Number.isFinite(raw?.startSec)) {
|
|
2383
|
+
anchor = { wallMs: raw.wallMs, startSec: raw.startSec };
|
|
2384
|
+
}
|
|
2385
|
+
if (raw?.stream && typeof raw.stream.codec === 'string')
|
|
2386
|
+
stream = raw.stream;
|
|
2387
|
+
}
|
|
2388
|
+
catch {
|
|
2389
|
+
anchor = null;
|
|
2390
|
+
}
|
|
2391
|
+
const tag = path.basename(workDir);
|
|
2392
|
+
let leftBehind = false;
|
|
2393
|
+
for (const entry of entries) {
|
|
2394
|
+
const src = path.join(workDir, entry.name);
|
|
2395
|
+
let st;
|
|
2396
|
+
try {
|
|
2397
|
+
st = fs.statSync(src);
|
|
2398
|
+
}
|
|
2399
|
+
catch {
|
|
2400
|
+
continue;
|
|
2401
|
+
}
|
|
2402
|
+
if (!st.isFile() || st.size <= 0)
|
|
2403
|
+
continue;
|
|
2404
|
+
// Without the anchor, the file's own last write is its close, i.e. its end.
|
|
2405
|
+
const captureStartMs = anchor
|
|
2406
|
+
? Math.round(anchor.wallMs + (entry.startSec - anchor.startSec) * 1000)
|
|
2407
|
+
: Math.round(st.mtimeMs - (entry.endSec - entry.startSec) * 1000);
|
|
2408
|
+
if (!this.moveIntoRing(dir, src, tag, entry, captureStartMs, st.size, stream, true))
|
|
2409
|
+
leftBehind = true;
|
|
2410
|
+
}
|
|
2411
|
+
if (!leftBehind)
|
|
2412
|
+
this.removeWorkDir(workDir, true);
|
|
2413
|
+
}
|
|
2414
|
+
/**
|
|
2415
|
+
* Hold the closed segments to min(ringSeconds x measured bytes/s, 10% of the
|
|
2416
|
+
* volume's free bytes), deleting oldest first. A file the OS will not let us
|
|
2417
|
+
* delete (Windows, mid-upload) is skipped, never waited on.
|
|
2418
|
+
*/
|
|
2419
|
+
enforceRing() {
|
|
2420
|
+
const cfg = this.segmentConfig;
|
|
2421
|
+
if (!cfg)
|
|
2422
|
+
return;
|
|
2423
|
+
const closedDir = path.join(cfg.dir, exports.CLOSED_SEGMENTS_DIRNAME);
|
|
2424
|
+
let names;
|
|
2425
|
+
try {
|
|
2426
|
+
names = fs.readdirSync(closedDir).filter((n) => n.toLowerCase().endsWith('.mp4')).sort();
|
|
2427
|
+
}
|
|
2428
|
+
catch {
|
|
2429
|
+
this.segCounters.ringSegments = 0;
|
|
2430
|
+
this.segCounters.ringBytes = 0;
|
|
2431
|
+
return;
|
|
2432
|
+
}
|
|
2433
|
+
const items = [];
|
|
2434
|
+
for (const name of names) {
|
|
2435
|
+
const file = path.join(closedDir, name);
|
|
2436
|
+
try {
|
|
2437
|
+
items.push({ file, bytes: fs.statSync(file).size });
|
|
2438
|
+
}
|
|
2439
|
+
catch {
|
|
2440
|
+
/* delivered and deleted under us */
|
|
2441
|
+
}
|
|
2442
|
+
}
|
|
2443
|
+
let total = items.reduce((n, item) => n + item.bytes, 0);
|
|
2444
|
+
let remaining = items.length;
|
|
2445
|
+
const freeBytes = this.freeBytesFn(cfg.dir);
|
|
2446
|
+
const bytesPerSec = this.measuredBytesPerSec();
|
|
2447
|
+
const byRing = bytesPerSec === null ? null : Math.floor(cfg.ringSeconds * bytesPerSec);
|
|
2448
|
+
const byFree = freeBytes === null ? null : Math.floor(exports.RING_FREE_FRACTION * freeBytes);
|
|
2449
|
+
const limit = byRing === null ? byFree : byFree === null ? byRing : Math.min(byRing, byFree);
|
|
2450
|
+
if (limit !== null) {
|
|
2451
|
+
for (const item of items) {
|
|
2452
|
+
if (total <= limit)
|
|
2453
|
+
break;
|
|
2454
|
+
try {
|
|
2455
|
+
fs.unlinkSync(item.file);
|
|
2456
|
+
}
|
|
2457
|
+
catch {
|
|
2458
|
+
continue;
|
|
2459
|
+
}
|
|
2460
|
+
const metaFile = item.file.replace(/\.mp4$/i, '.json');
|
|
2461
|
+
try {
|
|
2462
|
+
fs.unlinkSync(metaFile);
|
|
2463
|
+
}
|
|
2464
|
+
catch {
|
|
2465
|
+
/* best-effort */
|
|
2466
|
+
}
|
|
2467
|
+
total -= item.bytes;
|
|
2468
|
+
remaining -= 1;
|
|
2469
|
+
this.segCounters.evicted += 1;
|
|
2470
|
+
this.segCounters.evictedBytes += item.bytes;
|
|
2471
|
+
try {
|
|
2472
|
+
this.emit('segment_evicted', { file: item.file, metaFile, bytes: item.bytes });
|
|
2473
|
+
}
|
|
2474
|
+
catch (err) {
|
|
2475
|
+
this.log('warn', `segment recording: a 'segment_evicted' listener threw: ${errorText(err)}`);
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
this.segCounters.ringSegments = remaining;
|
|
2480
|
+
this.segCounters.ringBytes = total;
|
|
2481
|
+
this.segCounters.ringLimitBytes = limit;
|
|
2482
|
+
this.segCounters.freeBytes = freeBytes;
|
|
2483
|
+
}
|
|
2484
|
+
measuredBytesPerSec() {
|
|
2485
|
+
return this.measuredSegmentSeconds > 0 ? this.measuredSegmentBytes / this.measuredSegmentSeconds : null;
|
|
2486
|
+
}
|
|
2487
|
+
segmentStats() {
|
|
2488
|
+
const cfg = this.segmentConfig;
|
|
2489
|
+
const suspension = this.segmentSuspension && this.now() < this.segmentSuspension.untilMs ? this.segmentSuspension : null;
|
|
2490
|
+
const bytesPerSec = this.measuredBytesPerSec();
|
|
2491
|
+
const c = this.segCounters;
|
|
2492
|
+
return {
|
|
2493
|
+
state: this.recordingState(suspension !== null),
|
|
2494
|
+
dir: cfg?.dir ?? null,
|
|
2495
|
+
segmentSeconds: cfg?.segmentSeconds ?? null,
|
|
2496
|
+
ringSeconds: cfg?.ringSeconds ?? null,
|
|
2497
|
+
codec: this.streamInfo?.codec ?? null,
|
|
2498
|
+
segmentsClosed: c.closed,
|
|
2499
|
+
segmentsRecovered: c.recovered,
|
|
2500
|
+
secondsClosed: Math.round(c.secondsClosed * 1000) / 1000,
|
|
2501
|
+
bytesClosed: c.bytesClosed,
|
|
2502
|
+
partialsDeleted: c.partialsDeleted,
|
|
2503
|
+
ringSegments: c.ringSegments,
|
|
2504
|
+
ringBytes: c.ringBytes,
|
|
2505
|
+
ringLimitBytes: c.ringLimitBytes,
|
|
2506
|
+
measuredBytesPerSec: bytesPerSec === null ? null : Math.round(bytesPerSec),
|
|
2507
|
+
freeBytes: c.freeBytes,
|
|
2508
|
+
evictedSegments: c.evicted,
|
|
2509
|
+
evictedBytes: c.evictedBytes,
|
|
2510
|
+
reconfigures: c.reconfigures,
|
|
2511
|
+
outputFailures: c.outputFailures,
|
|
2512
|
+
suspendedUntilMs: suspension ? suspension.untilMs : null,
|
|
2513
|
+
reanchors: c.reanchors,
|
|
2514
|
+
lastAnchorDriftMs: c.lastAnchorDriftMs,
|
|
2515
|
+
lastSegmentAtMs: c.lastSegmentAtMs,
|
|
2516
|
+
lastError: c.lastError,
|
|
2517
|
+
};
|
|
2518
|
+
}
|
|
2519
|
+
recordingState(suspended) {
|
|
2520
|
+
const cfg = this.segmentConfig;
|
|
2521
|
+
if (!cfg || !cfg.enabled)
|
|
2522
|
+
return 'off';
|
|
2523
|
+
if (this.crop !== undefined)
|
|
2524
|
+
return 'cropped';
|
|
2525
|
+
if (!this.persistentRequested || this.mode === 'per_grab')
|
|
2526
|
+
return 'per_grab';
|
|
2527
|
+
if (this.session?.recording)
|
|
2528
|
+
return 'recording';
|
|
2529
|
+
const codec = this.streamInfo?.codec ?? null;
|
|
2530
|
+
if (codec !== null && !exports.RECORDABLE_CODECS.includes(codec))
|
|
2531
|
+
return 'unsupported_codec';
|
|
2532
|
+
if (suspended)
|
|
2533
|
+
return 'suspended';
|
|
2534
|
+
return 'waiting_for_session';
|
|
2535
|
+
}
|
|
1352
2536
|
log(level, message) {
|
|
1353
2537
|
this.onLog?.(level, (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(message));
|
|
1354
2538
|
}
|
|
1355
2539
|
}
|
|
1356
2540
|
exports.RTSPStreamCameraProvider = RTSPStreamCameraProvider;
|
|
2541
|
+
/** The segment filename template; `%` in the directory is ffmpeg's to read. */
|
|
2542
|
+
function segmentPatternFor(workDir) {
|
|
2543
|
+
return path.join(workDir.replace(/%/g, '%%'), 'seg_%06d.mp4');
|
|
2544
|
+
}
|
|
1357
2545
|
//# sourceMappingURL=RTSPStreamCameraProvider.js.map
|