@trillboards/edge-platform-rtsp 0.2.6 → 0.2.9

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,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.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;
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,54 @@ 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`).
231
+ *
232
+ * ── THE CAMERA'S AUDIO RIDES IN THE SAME SEGMENTS ─────────────────────────
233
+ *
234
+ * When ffmpeg's input description names an audio stream, the second output
235
+ * also maps the camera's first audio track (`-map 0:a:0?`): AAC is copied as
236
+ * is; every other codec (G.711, G.726, Opus, PCM, …) is transcoded ONCE to
237
+ * AAC-LC at the camera's own rate and channel count (`audioPlanFor`). The look
238
+ * output keeps `-an`, the video stays a copy, and a camera with no audio track
239
+ * gets exactly the video-only argv. Measured on the mediamtx rig (ffmpeg
240
+ * 6.1.1; the CPU cost is in `aacBitrateFor`), three facts shape the code:
241
+ *
242
+ * 1. The audio starts at the first audio PACKET and the copy at the first
243
+ * video KEYFRAME, so with audio mapped the segment list's zero moves
244
+ * earlier by that gap (0.905 s on a 6 fps HEVC camera; one GOP at most).
245
+ * `anchorFor` reads the gap back from the first segment's own edit list.
246
+ * 2. A camera that ANNOUNCES a microphone and sends no audio packets stalls
247
+ * the whole second output: the AAC encoder never starts, so the segment
248
+ * muxer never writes a file (40 s, nothing on disk, look path fine). With
249
+ * audio flowing the first file exists within 0.1 s of the first frame, so
250
+ * no file `AUDIO_START_DEADLINE_MS` after the first frame is a stall.
251
+ * 3. Audio is the junior track. Any failure of a session that mapped audio —
252
+ * a stall, a death before the first frame, a write error — suspends AUDIO
253
+ * (`AUDIO_SUSPEND_BASE_MS`..`AUDIO_SUSPEND_MAX_MS`) and the next session
254
+ * records video exactly as before. Only a video-only failure suspends
255
+ * recording.
207
256
  */
208
257
  /** The recorder's persistent-session lane is full. Degrade, never queue. */
209
258
  class RtspStreamAdmissionError extends Error {
@@ -741,14 +790,551 @@ function streamSessionStatsFor(streamUrl) {
741
790
  };
742
791
  }
743
792
  exports.streamSessionStatsFor = streamSessionStatsFor;
793
+ /** Codecs `video_segment` holds. Anything else is not recorded. */
794
+ exports.RECORDABLE_CODECS = ['h264', 'hevc'];
795
+ /** Closed segments, beside their sidecars, under the feed's directory. */
796
+ exports.CLOSED_SEGMENTS_DIRNAME = 'closed';
797
+ /** Session work directories are `rec-<startMs>-<sessionNumber>`. */
798
+ const SESSION_WORKDIR_PREFIX = 'rec-';
799
+ /**
800
+ * How often the segment list is read. ffmpeg writes a line the moment it
801
+ * closes a segment, so this is the whole detection latency, and it is also
802
+ * the resolution of the anchor drift check below.
803
+ */
804
+ const SEGMENT_POLL_MS = 1000;
805
+ /** First recording pause after the second output failed a session. */
806
+ exports.SEGMENT_SUSPEND_BASE_MS = 60000;
807
+ /** Ceiling on that pause: at most one look-path restart an hour on a failure that persists. */
808
+ exports.SEGMENT_SUSPEND_MAX_MS = 3600000;
809
+ /**
810
+ * ffmpeg's words for an OUTPUT write failing (a full or read-only volume, a
811
+ * segment file it could not open). An input failure — the camera dropping —
812
+ * reads "Failed reading RTSP data" / "End of file" and matches none of these.
813
+ */
814
+ 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;
815
+ /** The ring may hold at most this fraction of the volume's free bytes. */
816
+ exports.RING_FREE_FRACTION = 0.1;
817
+ /**
818
+ * A session that maps audio and has written no segment file this long after
819
+ * its first frame is stalled on a microphone that sends nothing. Measured: with
820
+ * audio flowing the first file existed within 0.1 s of the first frame on three
821
+ * rig cameras (polled every 100 ms); with an announced-but-silent track, no file
822
+ * in 40 s.
823
+ */
824
+ exports.AUDIO_START_DEADLINE_MS = 15000;
825
+ /** First audio pause after a session with audio mapped failed. */
826
+ exports.AUDIO_SUSPEND_BASE_MS = 10 * 60000;
827
+ /**
828
+ * Ceiling on that pause. Each retry of a camera whose audio keeps failing costs
829
+ * one look-path restart and, for a stall, the deadline's worth of video, so it
830
+ * settles at one retry a day rather than one an hour.
831
+ */
832
+ exports.AUDIO_SUSPEND_MAX_MS = 24 * 3600000;
833
+ /** AAC-LC's ceiling, enforced by ffmpeg's encoder: 6,144 bits per 1,024-sample frame per channel. */
834
+ const AAC_MAX_BITS_PER_FRAME_PER_CHANNEL = 6144;
835
+ /** Transcode target per channel where the ceiling allows it (11.025 kHz and up). */
836
+ const AAC_TARGET_BPS_PER_CHANNEL = 64000;
837
+ /**
838
+ * A segment cannot end after it was observed closed. A predicted end more
839
+ * than this past the poll that found it means the anchor is late.
840
+ */
841
+ const ANCHOR_FUTURE_TOLERANCE_MS = 1000;
842
+ /**
843
+ * A predicted end more than one poll plus this BEFORE the close was observed
844
+ * means the camera's media clock is running slow against the wall clock.
845
+ */
846
+ const ANCHOR_LAG_TOLERANCE_MS = 5000;
847
+ /**
848
+ * Parse the segment muxer's CSV list (`-segment_list_type csv`): one line per
849
+ * CLOSED segment, `name,start,end`. The last line is returned as `remainder`
850
+ * when it is not yet newline-terminated, so a half-written line is never read.
851
+ */
852
+ function parseSegmentListCsv(text) {
853
+ const lines = text.split('\n');
854
+ const remainder = lines.pop() ?? '';
855
+ const entries = [];
856
+ for (const raw of lines) {
857
+ const line = raw.replace(/\r$/, '');
858
+ if (!line)
859
+ continue;
860
+ const endComma = line.lastIndexOf(',');
861
+ const startComma = endComma > 0 ? line.lastIndexOf(',', endComma - 1) : -1;
862
+ if (startComma <= 0)
863
+ continue;
864
+ let name = line.slice(0, startComma);
865
+ if (name.length >= 2 && name.startsWith('"') && name.endsWith('"')) {
866
+ name = name.slice(1, -1).replace(/""/g, '"');
867
+ }
868
+ const startSec = Number(line.slice(startComma + 1, endComma));
869
+ const endSec = Number(line.slice(endComma + 1));
870
+ // The list names basenames inside the session's own work directory. Anything
871
+ // else is not a file this provider wrote, and is never followed.
872
+ if (!name || name !== path.basename(name) || name === '.' || name === '..')
873
+ continue;
874
+ if (!Number.isFinite(startSec) || !Number.isFinite(endSec) || endSec < startSec)
875
+ continue;
876
+ entries.push({ name, startSec, endSec });
877
+ }
878
+ return { entries, remainder };
879
+ }
880
+ exports.parseSegmentListCsv = parseSegmentListCsv;
881
+ /**
882
+ * One `Stream #0:N: Video: …` line from ffmpeg's input description, or null.
883
+ * `90k tbr`-style rates are the RTP clock, not a frame rate, so only an
884
+ * explicit `fps` is read.
885
+ */
886
+ function parseInputVideoStreamLine(line) {
887
+ const m = /^\s*Stream #0:\d+(?:\[[^\]]*\])?(?:\([^)]*\))?:\s*Video:\s*([A-Za-z0-9_]+)(.*)$/.exec(line);
888
+ if (!m)
889
+ return null;
890
+ const rest = m[2] ?? '';
891
+ const res = /\b(\d{2,5})x(\d{2,5})\b/.exec(rest);
892
+ const fpsMatch = /(\d+(?:\.\d+)?)\s+fps\b/.exec(rest);
893
+ const fps = fpsMatch ? Number(fpsMatch[1]) : null;
894
+ return {
895
+ codec: m[1].toLowerCase(),
896
+ width: res ? Number(res[1]) : null,
897
+ height: res ? Number(res[2]) : null,
898
+ fps: fps !== null && fps > 0 && fps <= 1000 ? fps : null,
899
+ };
900
+ }
901
+ exports.parseInputVideoStreamLine = parseInputVideoStreamLine;
902
+ /** ffmpeg's channel-layout words, as its input description prints them. */
903
+ const CHANNEL_LAYOUTS = new Map([
904
+ ['mono', 1],
905
+ ['stereo', 2],
906
+ ['2.1', 3],
907
+ ['3.0', 3],
908
+ ['3.0(back)', 3],
909
+ ['4.0', 4],
910
+ ['quad', 4],
911
+ ['quad(side)', 4],
912
+ ['3.1', 4],
913
+ ['5.0', 5],
914
+ ['5.0(side)', 5],
915
+ ['4.1', 5],
916
+ ['5.1', 6],
917
+ ['5.1(side)', 6],
918
+ ['6.0', 6],
919
+ ['hexagonal', 6],
920
+ ['6.1', 7],
921
+ ['7.0', 7],
922
+ ['7.1', 8],
923
+ ['octagonal', 8],
924
+ ]);
925
+ /**
926
+ * One `Stream #0:N: Audio: …` line from ffmpeg's input description, or null.
927
+ * Real lines (mediamtx rig, ffmpeg 6.1.1): `Audio: pcm_alaw, 8000 Hz, mono,
928
+ * s16, 64 kb/s`, `Audio: aac (LC), 16000 Hz, mono, fltp`, `Audio: opus, 48000
929
+ * Hz, stereo, fltp`; older builds print `1 channels`.
930
+ */
931
+ function parseInputAudioStreamLine(line) {
932
+ const m = /^\s*Stream #0:\d+(?:\[[^\]]*\])?(?:\([^)]*\))?:\s*Audio:\s*([A-Za-z0-9_]+)(.*)$/.exec(line);
933
+ if (!m)
934
+ return null;
935
+ const fields = (m[2] ?? '').split(',').map((f) => f.trim());
936
+ let sampleRate = null;
937
+ let channels = null;
938
+ for (const field of fields) {
939
+ const hz = /^(\d{3,6})\s*Hz$/.exec(field);
940
+ if (hz && sampleRate === null)
941
+ sampleRate = Number(hz[1]);
942
+ const count = /^(\d{1,2})\s+channels?\b/.exec(field);
943
+ if (count && channels === null)
944
+ channels = Number(count[1]);
945
+ const layout = CHANNEL_LAYOUTS.get(field.toLowerCase());
946
+ if (layout !== undefined && channels === null)
947
+ channels = layout;
948
+ }
949
+ return {
950
+ codec: m[1].toLowerCase(),
951
+ sampleRate: sampleRate !== null && sampleRate > 0 ? sampleRate : null,
952
+ channels: channels !== null && channels > 0 ? channels : null,
953
+ };
954
+ }
955
+ exports.parseInputAudioStreamLine = parseInputAudioStreamLine;
956
+ /**
957
+ * Reads ffmpeg's stderr as it arrives and finishes at the end of the INPUT
958
+ * description — the first line after `Input #0,` that is not indented (`Stream
959
+ * mapping:`, `Output #N`, a component's `[x @ …]` line). It answers with the
960
+ * first video stream, plus the first audio stream when the input has one; the
961
+ * audio line can come before or after the video line, which is why it does not
962
+ * stop at the video. Bounded: it holds at most one partial line.
963
+ */
964
+ class InputStreamProbe {
965
+ constructor() {
966
+ this.partial = '';
967
+ this.inInput = false;
968
+ this.video = null;
969
+ this.audio = null;
970
+ /** The input was opened (ffmpeg described it). */
971
+ this.inputOpened = false;
972
+ this.done = false;
973
+ this.info = null;
974
+ }
975
+ push(text) {
976
+ if (this.done)
977
+ return null;
978
+ const lines = (this.partial + text).split(/\r\n|\r|\n/);
979
+ this.partial = lines.pop() ?? '';
980
+ if (this.partial.length > 8192)
981
+ this.partial = this.partial.slice(-8192);
982
+ for (const line of lines) {
983
+ if (/^Input #0,/.test(line)) {
984
+ this.inInput = true;
985
+ this.inputOpened = true;
986
+ continue;
987
+ }
988
+ const ended = this.inInput ? line.length > 0 && !/^\s/.test(line) : /^(Output #\d+|Stream mapping:)/.test(line);
989
+ if (ended)
990
+ return this.finish();
991
+ if (!this.inInput)
992
+ continue;
993
+ if (!this.video) {
994
+ const video = parseInputVideoStreamLine(line);
995
+ if (video) {
996
+ this.video = video;
997
+ continue;
998
+ }
999
+ }
1000
+ if (!this.audio)
1001
+ this.audio = parseInputAudioStreamLine(line);
1002
+ }
1003
+ return null;
1004
+ }
1005
+ finish() {
1006
+ this.done = true;
1007
+ if (!this.video)
1008
+ return null;
1009
+ this.info = this.audio ? { ...this.video, audio: this.audio } : this.video;
1010
+ return this.info;
1011
+ }
1012
+ }
1013
+ exports.InputStreamProbe = InputStreamProbe;
1014
+ /**
1015
+ * The transcode's `-b:a`: 64 kb/s per channel, capped at AAC-LC's ceiling of
1016
+ * 6,144 bits per 1,024-sample frame per channel — which at 8 kHz, where almost
1017
+ * every CCTV microphone sits (G.711), is 48,000 b/s, the most AAC can spend on
1018
+ * it. Null when the camera named no rate or channel count.
1019
+ *
1020
+ * Measured (ffmpeg 6.1.1, one core of the dev box, one hour of 8 kHz G.711
1021
+ * A-law pink noise plus a tone): decode + AAC at 48 kb/s costs 40.9 s of CPU
1022
+ * per hour of audio, 1.14% of one core per camera, at 33.9 dB signal-to-
1023
+ * distortion against the decoded G.711 (G.711's own floor is ~38 dB). 48 kHz
1024
+ * stereo Opus to 128 kb/s costs 110 s an hour, 3.1%. A copy (AAC) costs no
1025
+ * codec work. ffmpeg's `-aac_coder fast` halves the cost at 30.9 dB.
1026
+ */
1027
+ function aacBitrateFor(sampleRate, channels) {
1028
+ if (!sampleRate || !channels)
1029
+ return null;
1030
+ const ceiling = Math.floor((AAC_MAX_BITS_PER_FRAME_PER_CHANNEL * sampleRate) / 1024);
1031
+ return Math.min(AAC_TARGET_BPS_PER_CHANNEL, ceiling) * channels;
1032
+ }
1033
+ exports.aacBitrateFor = aacBitrateFor;
1034
+ /** The camera's own audio in ffmpeg's words: `pcm_alaw 8000 Hz 1ch`. */
1035
+ function describeAudioSource(audio) {
1036
+ return [audio.codec, audio.sampleRate ? `${audio.sampleRate} Hz` : null, audio.channels ? `${audio.channels}ch` : null]
1037
+ .filter((part) => part !== null)
1038
+ .join(' ');
1039
+ }
1040
+ exports.describeAudioSource = describeAudioSource;
1041
+ /**
1042
+ * What the second output does with this audio stream: copy AAC (MP4-legal as
1043
+ * is), transcode anything else once to AAC, and leave out a stream ffmpeg
1044
+ * could not identify (it cannot be decoded, so mapping it would only fail).
1045
+ */
1046
+ function audioPlanFor(audio) {
1047
+ if (!audio || !audio.codec || audio.codec === 'none')
1048
+ return null;
1049
+ const source = describeAudioSource(audio);
1050
+ if (audio.codec === 'aac')
1051
+ return { mode: 'copy', bitrateBps: null, source };
1052
+ return { mode: 'aac', bitrateBps: aacBitrateFor(audio.sampleRate, audio.channels), source };
1053
+ }
1054
+ exports.audioPlanFor = audioPlanFor;
1055
+ function sameAudioPlan(a, b) {
1056
+ if (!a || !b)
1057
+ return a === b;
1058
+ return a.mode === b.mode && a.bitrateBps === b.bitrateBps && a.source === b.source;
1059
+ }
1060
+ function sameAudioInfo(a, b) {
1061
+ if (!a || !b)
1062
+ return a === b;
1063
+ return a.codec === b.codec && a.sampleRate === b.sampleRate && a.channels === b.channels;
1064
+ }
1065
+ // ---------------------------------------------------------------------------
1066
+ // The video's start inside a segment, read from the segment's own edit list
1067
+ // ---------------------------------------------------------------------------
1068
+ /** A moov larger than this is not one of our segments (its tables are kilobytes). */
1069
+ const MAX_SEGMENT_MOOV_BYTES = 16 * 1024 * 1024;
1070
+ /** A lead longer than any GOP a camera sends is a misread, not a lead. */
1071
+ const MAX_VIDEO_LEAD_SEC = 60;
1072
+ function mp4Children(buf, start, end) {
1073
+ const out = [];
1074
+ let o = start;
1075
+ while (o + 8 <= end) {
1076
+ let size = buf.readUInt32BE(o);
1077
+ const type = buf.toString('latin1', o + 4, o + 8);
1078
+ let header = 8;
1079
+ if (size === 1) {
1080
+ if (o + 16 > end)
1081
+ break;
1082
+ const big = buf.readBigUInt64BE(o + 8);
1083
+ if (big > BigInt(Number.MAX_SAFE_INTEGER))
1084
+ break;
1085
+ size = Number(big);
1086
+ header = 16;
1087
+ }
1088
+ else if (size === 0) {
1089
+ size = end - o;
1090
+ }
1091
+ if (size < header || o + size > end)
1092
+ break;
1093
+ out.push({ type, start: o + header, end: o + size });
1094
+ o += size;
1095
+ }
1096
+ return out;
1097
+ }
1098
+ function mp4Child(buf, parent, type) {
1099
+ return mp4Children(buf, parent.start, parent.end).find((b) => b.type === type) ?? null;
1100
+ }
1101
+ /** A full box's timescale: mvhd and mdhd both carry it at 12 (version 0) or 20 (version 1). */
1102
+ function fullBoxTimescale(buf, box) {
1103
+ const v1 = buf[box.start] === 1;
1104
+ const at = box.start + (v1 ? 20 : 12);
1105
+ if (at + 4 > box.end)
1106
+ return null;
1107
+ const ts = buf.readUInt32BE(at);
1108
+ return ts > 0 ? ts : null;
1109
+ }
1110
+ /**
1111
+ * Where the video track starts on a segment's timeline, in seconds, from its
1112
+ * `moov`: the leading empty edits (movie timescale) minus the first media
1113
+ * edit's start (track timescale). ffmpeg's mov muxer writes exactly that pair
1114
+ * — an empty edit of the first sample's presentation time, then a media edit
1115
+ * from its composition offset — so the difference is the first video packet's
1116
+ * decode time: 0 for a video-only copy (with or without B-frames), and the
1117
+ * audio lead when the audio started first. 0 for anything it cannot read.
1118
+ */
1119
+ function videoStartSecFromMoov(moov) {
1120
+ const root = { type: 'moov', start: 0, end: moov.length };
1121
+ const mvhd = mp4Child(moov, root, 'mvhd');
1122
+ const movieTimescale = mvhd ? fullBoxTimescale(moov, mvhd) : null;
1123
+ if (!movieTimescale)
1124
+ return 0;
1125
+ for (const trak of mp4Children(moov, root.start, root.end).filter((b) => b.type === 'trak')) {
1126
+ const mdia = mp4Child(moov, trak, 'mdia');
1127
+ const hdlr = mdia ? mp4Child(moov, mdia, 'hdlr') : null;
1128
+ if (!mdia || !hdlr || hdlr.end - hdlr.start < 12)
1129
+ continue;
1130
+ if (moov.toString('latin1', hdlr.start + 8, hdlr.start + 12) !== 'vide')
1131
+ continue;
1132
+ const mdhd = mp4Child(moov, mdia, 'mdhd');
1133
+ const trackTimescale = mdhd ? fullBoxTimescale(moov, mdhd) : null;
1134
+ const edts = mp4Child(moov, trak, 'edts');
1135
+ const elst = edts ? mp4Child(moov, edts, 'elst') : null;
1136
+ if (!trackTimescale || !elst || elst.end - elst.start < 8)
1137
+ return 0;
1138
+ const v1 = moov[elst.start] === 1;
1139
+ const entrySize = v1 ? 20 : 12;
1140
+ const count = moov.readUInt32BE(elst.start + 4);
1141
+ let emptySec = 0;
1142
+ let mediaSec = 0;
1143
+ for (let i = 0; i < count; i += 1) {
1144
+ const at = elst.start + 8 + i * entrySize;
1145
+ if (at + entrySize > elst.end)
1146
+ return 0;
1147
+ const duration = v1 ? Number(moov.readBigUInt64BE(at)) : moov.readUInt32BE(at);
1148
+ const mediaTime = v1 ? Number(moov.readBigInt64BE(at + 8)) : moov.readInt32BE(at + 4);
1149
+ if (mediaTime === -1) {
1150
+ emptySec += duration / movieTimescale;
1151
+ continue;
1152
+ }
1153
+ mediaSec = mediaTime / trackTimescale;
1154
+ break;
1155
+ }
1156
+ const lead = emptySec - mediaSec;
1157
+ return Number.isFinite(lead) && lead > 0 && lead <= MAX_VIDEO_LEAD_SEC ? lead : 0;
1158
+ }
1159
+ return 0;
1160
+ }
1161
+ exports.videoStartSecFromMoov = videoStartSecFromMoov;
1162
+ /** `videoStartSecFromMoov` of a closed segment file; 0 when it cannot be read. */
1163
+ function readVideoStartSec(file) {
1164
+ let fd;
1165
+ try {
1166
+ fd = fs.openSync(file, 'r');
1167
+ }
1168
+ catch {
1169
+ return 0;
1170
+ }
1171
+ try {
1172
+ const size = fs.fstatSync(fd).size;
1173
+ const head = Buffer.alloc(16);
1174
+ let offset = 0;
1175
+ while (offset + 8 <= size) {
1176
+ const n = fs.readSync(fd, head, 0, 16, offset);
1177
+ if (n < 8)
1178
+ return 0;
1179
+ let boxSize = head.readUInt32BE(0);
1180
+ const type = head.toString('latin1', 4, 8);
1181
+ let header = 8;
1182
+ if (boxSize === 1) {
1183
+ if (n < 16)
1184
+ return 0;
1185
+ const big = head.readBigUInt64BE(8);
1186
+ if (big > BigInt(Number.MAX_SAFE_INTEGER))
1187
+ return 0;
1188
+ boxSize = Number(big);
1189
+ header = 16;
1190
+ }
1191
+ else if (boxSize === 0) {
1192
+ boxSize = size - offset;
1193
+ }
1194
+ if (boxSize < header || offset + boxSize > size)
1195
+ return 0;
1196
+ if (type === 'moov') {
1197
+ if (boxSize - header > MAX_SEGMENT_MOOV_BYTES)
1198
+ return 0;
1199
+ const moov = Buffer.alloc(boxSize - header);
1200
+ if (fs.readSync(fd, moov, 0, moov.length, offset + header) !== moov.length)
1201
+ return 0;
1202
+ return videoStartSecFromMoov(moov);
1203
+ }
1204
+ offset += boxSize;
1205
+ }
1206
+ return 0;
1207
+ }
1208
+ catch {
1209
+ return 0;
1210
+ }
1211
+ finally {
1212
+ fs.closeSync(fd);
1213
+ }
1214
+ }
1215
+ exports.readVideoStartSec = readVideoStartSec;
1216
+ /** The second output, exactly. Pure, so the argv can be asserted. */
1217
+ function buildSegmentOutputArgs(o) {
1218
+ const audio = o.audio ?? null;
1219
+ return [
1220
+ '-map',
1221
+ '0:v',
1222
+ // The FIRST audio track only, and optional: a camera whose next session
1223
+ // no longer has it records video rather than failing the output.
1224
+ ...(audio ? ['-map', '0:a:0?'] : []),
1225
+ '-c:v',
1226
+ 'copy',
1227
+ ...(o.tagHvc1 ? ['-tag:v', 'hvc1'] : []),
1228
+ ...(audio
1229
+ ? [
1230
+ '-c:a',
1231
+ audio.mode === 'copy' ? 'copy' : 'aac',
1232
+ ...(audio.mode === 'aac' && audio.bitrateBps !== null ? ['-b:a', String(audio.bitrateBps)] : []),
1233
+ // The camera's own codec, rate and channels travel inside the file:
1234
+ // a transcode leaves AAC in the box, and this is the one place that
1235
+ // still says it began as, say, 8 kHz G.711.
1236
+ '-metadata:s:a:0',
1237
+ `handler_name=camera ${audio.source}`,
1238
+ ]
1239
+ : []),
1240
+ // The copy starts at the first KEYFRAME, but the output timeline starts at
1241
+ // the first packet received, and the segment list reports the first
1242
+ // segment as starting at 0 regardless. Measured on the mediamtx rig: a
1243
+ // first segment listed 0.000-7.542 held 6.000 s of video starting at
1244
+ // 1.541. Shifting the copy so its first packet is 0 makes every listed
1245
+ // start true, and with it first-frame wall clock + startSec (3 of 3 runs:
1246
+ // listed 0.000-6.083, file 6.000 s from 0.083, the B-frame delay).
1247
+ '-avoid_negative_ts',
1248
+ 'make_zero',
1249
+ '-f',
1250
+ 'segment',
1251
+ '-segment_time',
1252
+ String(o.segmentSeconds),
1253
+ ...(o.minSegDuration ? ['-min_seg_duration', String(o.segmentSeconds)] : []),
1254
+ '-segment_format',
1255
+ 'mp4',
1256
+ '-reset_timestamps',
1257
+ '1',
1258
+ '-segment_list',
1259
+ o.csvPath,
1260
+ '-segment_list_type',
1261
+ 'csv',
1262
+ o.segmentPattern,
1263
+ ];
1264
+ }
1265
+ exports.buildSegmentOutputArgs = buildSegmentOutputArgs;
1266
+ /** The volume's free bytes, or null where the platform cannot say. */
1267
+ function volumeFreeBytes(dir) {
1268
+ const statfsSync = fs.statfsSync;
1269
+ if (typeof statfsSync !== 'function')
1270
+ return null;
1271
+ try {
1272
+ const s = statfsSync(dir);
1273
+ const free = Number(s.bavail) * Number(s.bsize);
1274
+ return Number.isFinite(free) && free >= 0 ? free : null;
1275
+ }
1276
+ catch {
1277
+ return null;
1278
+ }
1279
+ }
1280
+ exports.volumeFreeBytes = volumeFreeBytes;
1281
+ function normalizeSegmentRecording(cfg) {
1282
+ if (!cfg || typeof cfg.dir !== 'string' || !cfg.dir.trim())
1283
+ return null;
1284
+ const segmentSeconds = Number(cfg.segmentSeconds);
1285
+ const ringSeconds = Number(cfg.ringSeconds);
1286
+ if (!Number.isFinite(segmentSeconds) || segmentSeconds <= 0)
1287
+ return null;
1288
+ if (!Number.isFinite(ringSeconds) || ringSeconds < 0)
1289
+ return null;
1290
+ return {
1291
+ dir: path.resolve(cfg.dir),
1292
+ segmentSeconds: Math.max(1, Math.trunc(segmentSeconds)),
1293
+ ringSeconds: Math.trunc(ringSeconds),
1294
+ enabled: cfg.enabled !== false,
1295
+ };
1296
+ }
1297
+ function writeFileAtomic(file, body) {
1298
+ const tmp = `${file}.tmp`;
1299
+ fs.writeFileSync(tmp, body);
1300
+ fs.renameSync(tmp, file);
1301
+ }
1302
+ function readSidecar(file) {
1303
+ try {
1304
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
1305
+ const nums = [raw.startSec, raw.endSec, raw.captureStartMs, raw.captureEndMs, raw.bytes];
1306
+ if (raw.version !== 1 || nums.some((n) => typeof n !== 'number' || !Number.isFinite(n)))
1307
+ return null;
1308
+ const stream = raw.stream && typeof raw.stream === 'object' && typeof raw.stream.codec === 'string'
1309
+ ? raw.stream
1310
+ : null;
1311
+ return { ...raw, stream };
1312
+ }
1313
+ catch {
1314
+ return null;
1315
+ }
1316
+ }
1317
+ /** A rename/unlink the OS refused because another process still holds the file. */
1318
+ function isBusyError(err) {
1319
+ const code = err?.code;
1320
+ return code === 'EBUSY' || code === 'EPERM' || code === 'EACCES';
1321
+ }
1322
+ function errorText(err) {
1323
+ return err instanceof Error ? err.message : String(err);
1324
+ }
744
1325
  /**
745
1326
  * One instance per feed. Implements the SAME `CameraProvider` interface as
746
1327
  * `RTSPCameraProvider`, so every consumer is unchanged — but `getFrame()` reads
747
1328
  * the newest frame out of the ring the long-lived session is filling, rather
748
1329
  * than spawning a process and handshaking a stream per call.
1330
+ *
1331
+ * Events: `'segment'` (RecordedSegment) for every closed recording segment,
1332
+ * `'segment_evicted'` (EvictedSegment) when the ring deletes one undelivered,
1333
+ * and `'opening'` at the start of every `open()`.
749
1334
  */
750
- class RTSPStreamCameraProvider {
1335
+ class RTSPStreamCameraProvider extends events_1.EventEmitter {
751
1336
  constructor(config) {
1337
+ super();
752
1338
  this.opened = false;
753
1339
  this.mode = 'persistent';
754
1340
  this.degradedReason = null;
@@ -766,13 +1352,61 @@ class RTSPStreamCameraProvider {
766
1352
  * one frame later.
767
1353
  */
768
1354
  this.fallbackOpenError = null;
769
- this.proc = null;
1355
+ /** The live ffmpeg session, or null between sessions. */
1356
+ this.session = null;
770
1357
  /** This recorder's persistent-session lane, for the learned ceiling. */
771
1358
  this.admission = null;
772
1359
  this.releaseAdmission = null;
773
1360
  this.restartTimer = null;
774
- this.cleanupInput = null;
775
1361
  this.startingUp = false;
1362
+ // ── segment recording ────────────────────────────────────────────────────
1363
+ this.segmentConfig = null;
1364
+ /** The newest input description ffmpeg gave; decides the tag and the codec gate. */
1365
+ this.streamInfo = null;
1366
+ this.segmentsRecoveredFor = null;
1367
+ this.segmentPollTimer = null;
1368
+ this.lastSegmentPollAtMs = null;
1369
+ /** A session stopped to change the second output; its exit starts the next one. */
1370
+ this.reconfigurePendingFor = null;
1371
+ /**
1372
+ * Recording paused after the second output failed a session. Provider-wide,
1373
+ * not per argv: the next plan differs only by the tag once ffmpeg has named
1374
+ * the codec, and retrying it at once would spend open()'s last attempt.
1375
+ */
1376
+ this.segmentSuspension = null;
1377
+ this.segmentSuspendTimer = null;
1378
+ this.consecutiveOutputFailures = 0;
1379
+ /** The camera's audio left out of the segments after a session that mapped it failed. */
1380
+ this.audioSuspension = null;
1381
+ this.audioSuspendTimer = null;
1382
+ this.consecutiveAudioFailures = 0;
1383
+ this.audioCounters = {
1384
+ failures: 0,
1385
+ stalls: 0,
1386
+ lastVideoLeadMs: null,
1387
+ lastError: null,
1388
+ };
1389
+ this.measuredSegmentBytes = 0;
1390
+ this.measuredSegmentSeconds = 0;
1391
+ this.segCounters = {
1392
+ closed: 0,
1393
+ recovered: 0,
1394
+ secondsClosed: 0,
1395
+ bytesClosed: 0,
1396
+ partialsDeleted: 0,
1397
+ evicted: 0,
1398
+ evictedBytes: 0,
1399
+ reconfigures: 0,
1400
+ outputFailures: 0,
1401
+ reanchors: 0,
1402
+ lastAnchorDriftMs: null,
1403
+ lastSegmentAtMs: null,
1404
+ lastError: null,
1405
+ ringSegments: 0,
1406
+ ringBytes: 0,
1407
+ ringLimitBytes: null,
1408
+ freeBytes: null,
1409
+ };
776
1410
  this.sessionStarts = 0;
777
1411
  this.restarts = 0;
778
1412
  this.framesDecoded = 0;
@@ -825,6 +1459,40 @@ class RTSPStreamCameraProvider {
825
1459
  };
826
1460
  const make = config.fallbackFactory ?? ((c) => new RTSPCameraProvider_1.RTSPCameraProvider(c));
827
1461
  this.buildFallback = () => make(fallbackConfig);
1462
+ this.freeBytesFn = config.freeBytesFn ?? volumeFreeBytes;
1463
+ // No filesystem work here: a provider that is built and never opened (a
1464
+ // test, a manager that is configured and then discarded) must leave no trace.
1465
+ this.segmentConfig = normalizeSegmentRecording(config.segmentRecording ?? null);
1466
+ }
1467
+ on(event, listener) {
1468
+ return super.on(event, listener);
1469
+ }
1470
+ /**
1471
+ * Change segment recording. `null` turns it off and keeps the directory (the
1472
+ * ring and any leftovers stay this provider's). A change that the running
1473
+ * session's argv does not already satisfy restarts the session once — after
1474
+ * its first frame, never during startup.
1475
+ */
1476
+ setSegmentRecording(next) {
1477
+ if (next === null) {
1478
+ if (this.segmentConfig)
1479
+ this.segmentConfig = { ...this.segmentConfig, enabled: false };
1480
+ }
1481
+ else {
1482
+ const normalized = normalizeSegmentRecording(next);
1483
+ if (!normalized)
1484
+ return;
1485
+ const previous = this.segmentConfig;
1486
+ // New knobs are a new question: a pause earned by the old ones does not carry over.
1487
+ if (!previous || previous.dir !== normalized.dir || previous.segmentSeconds !== normalized.segmentSeconds) {
1488
+ this.clearSegmentSuspension();
1489
+ }
1490
+ this.segmentConfig = normalized;
1491
+ }
1492
+ if (this.opened && this.segmentConfig && this.segmentsRecoveredFor !== this.segmentConfig.dir) {
1493
+ this.recoverSegments();
1494
+ }
1495
+ this.reconcileRecording();
828
1496
  }
829
1497
  // ── CameraProvider ───────────────────────────────────────────────────────
830
1498
  /**
@@ -836,6 +1504,20 @@ class RTSPStreamCameraProvider {
836
1504
  async open(_deviceId) {
837
1505
  if (this.opened)
838
1506
  return;
1507
+ // A controller attached at construction starts here, so a provider that is
1508
+ // built and never opened costs nothing. Its listener may set the recording
1509
+ // config synchronously, which the first session below then carries.
1510
+ try {
1511
+ this.emit('opening');
1512
+ }
1513
+ catch (err) {
1514
+ this.log('warn', `segment recording: an 'opening' listener threw: ${errorText(err)}`);
1515
+ }
1516
+ // Segments an earlier process closed (or left listed in a work directory)
1517
+ // are this feed's, and are handed out before any new one is written.
1518
+ if (this.segmentConfig && this.segmentsRecoveredFor !== this.segmentConfig.dir) {
1519
+ this.recoverSegments();
1520
+ }
839
1521
  // A previous open() degraded and left a per-grab provider behind. Re-opening
840
1522
  // is the manager's reconnect path, and it is also the ONLY chance to retake
841
1523
  // a persistent session from a recorder that has since rebooted, freed a
@@ -877,16 +1559,34 @@ class RTSPStreamCameraProvider {
877
1559
  this.degradedReason = null;
878
1560
  this.currentRestartDelay = this.restartDelayMs;
879
1561
  this.startingUp = true;
1562
+ // An audio pause outlives close(); its end must still bring the audio back.
1563
+ this.armAudioRetry();
880
1564
  let lastErr;
1565
+ // A failure the second output caused is not the recorder refusing this
1566
+ // feed: it buys one more attempt that the validation budget does not pay
1567
+ // for, so recording can never be what degrades a feed to per-grab. At most
1568
+ // two — each one strips the second output (audio first, then recording),
1569
+ // so the third session is look-only.
1570
+ let recordingRetriesGranted = 0;
881
1571
  try {
882
1572
  for (let attempt = 1; attempt <= this.openValidationAttempts; attempt += 1) {
1573
+ const outputFailuresBefore = this.segCounters.outputFailures;
883
1574
  try {
884
1575
  await this.startSession();
1576
+ // Anything that changed the recording plan during startup (a config
1577
+ // set from a listener, ffmpeg's description of the input) was held
1578
+ // back until the session proved itself; apply it now.
1579
+ this.startingUp = false;
1580
+ this.reconcileRecording();
885
1581
  return;
886
1582
  }
887
1583
  catch (err) {
888
1584
  lastErr = err;
889
1585
  this.stopProcess();
1586
+ if (recordingRetriesGranted < 2 && this.segCounters.outputFailures > outputFailuresBefore) {
1587
+ recordingRetriesGranted += 1;
1588
+ attempt -= 1;
1589
+ }
890
1590
  if (attempt < this.openValidationAttempts && this.restartDelayMs > 0) {
891
1591
  await new Promise((resolve) => setTimeout(resolve, this.restartDelayMs));
892
1592
  }
@@ -1007,7 +1707,18 @@ class RTSPStreamCameraProvider {
1007
1707
  clearTimeout(this.restartTimer);
1008
1708
  this.restartTimer = null;
1009
1709
  }
1710
+ if (this.segmentSuspendTimer) {
1711
+ clearTimeout(this.segmentSuspendTimer);
1712
+ this.segmentSuspendTimer = null;
1713
+ }
1714
+ if (this.audioSuspendTimer) {
1715
+ clearTimeout(this.audioSuspendTimer);
1716
+ this.audioSuspendTimer = null;
1717
+ }
1718
+ // The session's own exit finishes its recording (final list read, partial
1719
+ // deleted); a process that exits first leaves it for the next open().
1010
1720
  this.stopProcess();
1721
+ this.stopSegmentPolling();
1011
1722
  this.releaseSlot();
1012
1723
  this.ring.clear();
1013
1724
  this.splitter.reset();
@@ -1030,7 +1741,7 @@ class RTSPStreamCameraProvider {
1030
1741
  opened: this.isOpen(),
1031
1742
  mode: this.mode,
1032
1743
  degradedReason: this.degradedReason,
1033
- running: this.proc !== null,
1744
+ running: this.session !== null,
1034
1745
  bufferedFrames: this.ring.getFrames(),
1035
1746
  bufferedBytes: this.ring.getBytes(),
1036
1747
  pendingBytes: this.splitter.getPendingBytes(),
@@ -1046,6 +1757,7 @@ class RTSPStreamCameraProvider {
1046
1757
  lastFrameAtMs: this.lastFrameAtMs,
1047
1758
  frameAgeMs: newest ? this.now() - newest.atMs : null,
1048
1759
  lastErrorMessage: this.lastErrorMessage,
1760
+ segments: this.segmentStats(),
1049
1761
  };
1050
1762
  }
1051
1763
  // ── internals ────────────────────────────────────────────────────────────
@@ -1180,7 +1892,12 @@ class RTSPStreamCameraProvider {
1180
1892
  },
1181
1893
  };
1182
1894
  }
1183
- buildArgs() {
1895
+ /**
1896
+ * The session's argv. With no `segmentOutput` it is byte-identical to the
1897
+ * look-only session this provider has always run; with one, the second
1898
+ * output (`buildSegmentOutputArgs`) follows `pipe:1`.
1899
+ */
1900
+ buildArgs(segmentOutput) {
1184
1901
  const input = this.buildInputArgs();
1185
1902
  return {
1186
1903
  args: [
@@ -1209,6 +1926,9 @@ class RTSPStreamCameraProvider {
1209
1926
  '-threads',
1210
1927
  String(this.decoderThreads),
1211
1928
  'pipe:1',
1929
+ // The second output, when this session records: the input's own video
1930
+ // bitstream, copied — no decode, no encode, no second RTSP session.
1931
+ ...(segmentOutput ? buildSegmentOutputArgs(segmentOutput) : []),
1212
1932
  ],
1213
1933
  cleanup: input.cleanup,
1214
1934
  };
@@ -1221,8 +1941,17 @@ class RTSPStreamCameraProvider {
1221
1941
  */
1222
1942
  startSession() {
1223
1943
  return new Promise((resolve, reject) => {
1224
- const { args, cleanup } = this.buildArgs();
1225
- this.cleanupInput = cleanup;
1944
+ const recording = this.prepareSessionRecording();
1945
+ const { args, cleanup } = this.buildArgs(recording
1946
+ ? {
1947
+ csvPath: recording.csvPath,
1948
+ segmentPattern: segmentPatternFor(recording.workDir),
1949
+ segmentSeconds: recording.plan.segmentSeconds,
1950
+ tagHvc1: recording.plan.tagHvc1,
1951
+ minSegDuration: recording.plan.minSegDuration,
1952
+ audio: recording.plan.audio,
1953
+ }
1954
+ : null);
1226
1955
  this.sessionStarts += 1;
1227
1956
  this.splitter.reset();
1228
1957
  let proc;
@@ -1231,11 +1960,26 @@ class RTSPStreamCameraProvider {
1231
1960
  }
1232
1961
  catch (err) {
1233
1962
  cleanup();
1234
- this.cleanupInput = null;
1963
+ if (recording)
1964
+ this.removeWorkDir(recording.workDir);
1235
1965
  reject(err instanceof Error ? err : new Error(String(err)));
1236
1966
  return;
1237
1967
  }
1238
- this.proc = proc;
1968
+ const session = {
1969
+ id: this.sessionStarts,
1970
+ proc,
1971
+ cleanupInput: cleanup,
1972
+ firstFrameAtMs: null,
1973
+ probe: new InputStreamProbe(),
1974
+ streamInfo: null,
1975
+ recording,
1976
+ superseded: false,
1977
+ detached: false,
1978
+ ended: false,
1979
+ };
1980
+ this.session = session;
1981
+ if (recording)
1982
+ this.ensureSegmentPolling();
1239
1983
  const stderrBuffer = new ffmpegStderr_1.BoundedSessionStderr();
1240
1984
  let settled = false;
1241
1985
  const settle = (fn) => {
@@ -1245,20 +1989,33 @@ class RTSPStreamCameraProvider {
1245
1989
  fn();
1246
1990
  };
1247
1991
  proc.stdout?.on('data', (chunk) => {
1992
+ // A session that is no longer the live one (stopped, or replaced by a
1993
+ // reconfigure) must not feed the ring, nor the splitter the next uses.
1994
+ if (this.session !== session)
1995
+ return;
1248
1996
  for (const frame of this.splitter.push(chunk)) {
1249
1997
  this.admitFrame(frame);
1998
+ if (session.firstFrameAtMs === null)
1999
+ this.onSessionFirstFrame(session);
1250
2000
  // A decoded frame proves the session is healthy — reset the backoff.
1251
2001
  this.currentRestartDelay = this.restartDelayMs;
1252
2002
  settle(resolve);
1253
2003
  }
1254
2004
  });
1255
2005
  proc.stderr?.on('data', (chunk) => {
1256
- stderrBuffer.append(chunk.toString());
2006
+ const text = chunk.toString();
2007
+ stderrBuffer.append(text);
2008
+ if (!session.probe.done) {
2009
+ const info = session.probe.push(text);
2010
+ if (info)
2011
+ this.onSessionStreamInfo(session, info);
2012
+ }
1257
2013
  });
1258
2014
  proc.on('error', (err) => {
1259
- this.lastErrorMessage = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err.message);
2015
+ if (!session.superseded)
2016
+ this.lastErrorMessage = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err.message);
1260
2017
  settle(() => reject(err));
1261
- this.handleSessionEnd(stderrBuffer.text());
2018
+ this.handleSessionEnd(session, stderrBuffer.text());
1262
2019
  });
1263
2020
  proc.on('close', (code) => {
1264
2021
  // A CLEAN EXIT IS A FAULT HERE. `code === 0` means success on the
@@ -1268,40 +2025,57 @@ class RTSPStreamCameraProvider {
1268
2025
  // RTSP data: End of file". Both are restarts, never successes.
1269
2026
  const stderr = stderrBuffer.text();
1270
2027
  const summary = (0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr);
1271
- this.lastErrorMessage = summary || `ffmpeg stream session exited with code ${code}`;
1272
- settle(() => reject(new Error(`RTSP stream session ended during startup: ${this.lastErrorMessage}`)));
1273
- this.handleSessionEnd(stderr);
2028
+ const message = summary || `ffmpeg stream session exited with code ${code}`;
2029
+ // A session stopped on purpose to change its outputs ended because we
2030
+ // asked it to: its last words are not this feed's error.
2031
+ if (!session.superseded)
2032
+ this.lastErrorMessage = message;
2033
+ settle(() => reject(new Error(`RTSP stream session ended during startup: ${message}`)));
2034
+ this.handleSessionEnd(session, stderr);
1274
2035
  });
1275
2036
  });
1276
2037
  }
2038
+ /**
2039
+ * Detach the live session and stop its ffmpeg. Its own exit later finishes
2040
+ * its recording, and is never restarted: whoever called this owns what
2041
+ * happens next (close, shed, or open()'s retry loop).
2042
+ */
1277
2043
  stopProcess() {
1278
- const proc = this.proc;
1279
- this.proc = null;
1280
- if (proc) {
2044
+ const session = this.session;
2045
+ this.session = null;
2046
+ if (session) {
2047
+ session.detached = true;
2048
+ this.killSession(session);
2049
+ }
2050
+ }
2051
+ killSession(session) {
2052
+ const proc = session.proc;
2053
+ try {
2054
+ proc.kill('SIGTERM');
2055
+ }
2056
+ catch {
2057
+ /* already gone */
2058
+ }
2059
+ // Bounded escalation: an ffmpeg wedged on a half-open RTSP socket ignores
2060
+ // SIGTERM, and a connector that leaks one child per restart is the
2061
+ // 28-children incident wearing a different hat.
2062
+ const timer = setTimeout(() => {
1281
2063
  try {
1282
- proc.kill('SIGTERM');
2064
+ proc.kill('SIGKILL');
1283
2065
  }
1284
2066
  catch {
1285
2067
  /* already gone */
1286
2068
  }
1287
- // Bounded escalation: an ffmpeg wedged on a half-open RTSP socket ignores
1288
- // SIGTERM, and a connector that leaks one child per restart is the
1289
- // 28-children incident wearing a different hat.
1290
- const timer = setTimeout(() => {
1291
- try {
1292
- proc.kill('SIGKILL');
1293
- }
1294
- catch {
1295
- /* already gone */
1296
- }
1297
- }, 2000);
1298
- if (typeof timer.unref === 'function')
1299
- timer.unref();
2069
+ }, 2000);
2070
+ if (typeof timer.unref === 'function')
2071
+ timer.unref();
2072
+ try {
2073
+ session.cleanupInput();
1300
2074
  }
1301
- if (this.cleanupInput) {
1302
- this.cleanupInput();
1303
- this.cleanupInput = null;
2075
+ catch {
2076
+ /* best-effort */
1304
2077
  }
2078
+ session.cleanupInput = () => undefined;
1305
2079
  }
1306
2080
  /**
1307
2081
  * A session ended. While the provider is open this ALWAYS schedules a restart
@@ -1316,17 +2090,45 @@ class RTSPStreamCameraProvider {
1316
2090
  * Waiters are woken on the way out so a `getFrame()` blocked on a session
1317
2091
  * that just died reaches its stale error rather than sitting out the full
1318
2092
  * deadline for a stream that is provably not coming back.
2093
+ *
2094
+ * Only the LIVE session's end does any of that. A session already detached
2095
+ * (stopProcess) or superseded (a reconfigure) finishes its recording and
2096
+ * either stops there or, for a reconfigure, starts its replacement.
1319
2097
  */
1320
- handleSessionEnd(stderr) {
1321
- if (this.cleanupInput) {
1322
- this.cleanupInput();
1323
- this.cleanupInput = null;
1324
- }
1325
- this.proc = null;
1326
- // Wake anyone blocked in getFrame(): the session that would have fed them
1327
- // is gone, so they should reach their stale error now rather than sit out a
1328
- // full deadline waiting for a stream that is provably not coming back.
1329
- this.wakeWaiters();
2098
+ handleSessionEnd(session, stderr) {
2099
+ if (session.ended)
2100
+ return; // 'error' and 'close' can both arrive
2101
+ session.ended = true;
2102
+ try {
2103
+ session.cleanupInput();
2104
+ }
2105
+ catch {
2106
+ /* best-effort */
2107
+ }
2108
+ session.cleanupInput = () => undefined;
2109
+ if (session.recording)
2110
+ this.finishSessionRecording(session, stderr);
2111
+ const current = this.session === session;
2112
+ if (current) {
2113
+ this.session = null;
2114
+ // Wake anyone blocked in getFrame(): the session that would have fed them
2115
+ // is gone, so they should reach their stale error now rather than sit out
2116
+ // a full deadline waiting for a stream that is provably not coming back.
2117
+ this.wakeWaiters();
2118
+ }
2119
+ if (session.superseded) {
2120
+ if (this.reconfigurePendingFor === session) {
2121
+ this.reconfigurePendingFor = null;
2122
+ if (this.opened && !this.fallback && this.session === null && !this.restartTimer) {
2123
+ this.startSession().catch((err) => {
2124
+ this.lastErrorMessage = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(err?.message ?? String(err));
2125
+ });
2126
+ }
2127
+ }
2128
+ return;
2129
+ }
2130
+ if (!current)
2131
+ return;
1330
2132
  if (!this.opened)
1331
2133
  return;
1332
2134
  if (this.startingUp)
@@ -1349,9 +2151,888 @@ class RTSPStreamCameraProvider {
1349
2151
  if (typeof this.restartTimer.unref === 'function')
1350
2152
  this.restartTimer.unref();
1351
2153
  }
2154
+ // ── segment recording ────────────────────────────────────────────────────
2155
+ /** What the NEXT session should record, or null for look-only. */
2156
+ planRecording() {
2157
+ const cfg = this.segmentConfig;
2158
+ if (!cfg || !cfg.enabled)
2159
+ return null;
2160
+ // A crop belongs to the look output; a stream copy would record the whole
2161
+ // composite under one tile's screen. Only a crop-less persistent feed records.
2162
+ if (!this.persistentRequested || this.crop !== undefined)
2163
+ return null;
2164
+ const codec = this.streamInfo?.codec ?? null;
2165
+ if (codec !== null && !exports.RECORDABLE_CODECS.includes(codec))
2166
+ return null;
2167
+ const plan = {
2168
+ dir: cfg.dir,
2169
+ segmentSeconds: cfg.segmentSeconds,
2170
+ // Tagged unless the stream is KNOWN to be H.264. HEVC needs hvc1 (ffmpeg
2171
+ // writes hev1 otherwise), and on H.264 the segment muxer resets a tag
2172
+ // its mp4 muxer maps to another codec — measured on ffmpeg 6.1.1, the
2173
+ // segment comes out avc1 — so the very first session can record before
2174
+ // ffmpeg has described the input, and needs no restart once it has.
2175
+ tagHvc1: codec !== 'h264',
2176
+ // Present since ffmpeg 5; an older binary gets the bare segment_time.
2177
+ minSegDuration: this.ffmpegMajorVersion >= 5,
2178
+ audio: this.planAudio(),
2179
+ };
2180
+ if (this.segmentSuspension && this.now() < this.segmentSuspension.untilMs)
2181
+ return null;
2182
+ return plan;
2183
+ }
2184
+ /**
2185
+ * The camera's audio for the next session — decided ONLY from ffmpeg's own
2186
+ * description of this input, never speculated: a session that has not been
2187
+ * described yet records video only, exactly as before, and the description
2188
+ * of an audio track then costs one reconfigure. Speculating would put audio
2189
+ * options on every camera with no microphone (ffmpeg warns that `-b:a` was
2190
+ * never used) and risk the stall above on a camera nobody has seen yet.
2191
+ */
2192
+ planAudio() {
2193
+ if (this.audioSuspension && this.now() < this.audioSuspension.untilMs)
2194
+ return null;
2195
+ return audioPlanFor(this.streamInfo?.audio);
2196
+ }
2197
+ /** Does a running session's second output already give what `want` asks for? */
2198
+ sessionSatisfies(have, want) {
2199
+ if (!want)
2200
+ return have === null;
2201
+ if (!have)
2202
+ return false;
2203
+ if (have.dir !== want.dir ||
2204
+ have.segmentSeconds !== want.segmentSeconds ||
2205
+ have.minSegDuration !== want.minSegDuration ||
2206
+ !sameAudioPlan(have.audio, want.audio)) {
2207
+ return false;
2208
+ }
2209
+ if (have.tagHvc1 === want.tagHvc1)
2210
+ return true;
2211
+ // A speculative hvc1 tag on what turned out to be H.264 is a no-op.
2212
+ return have.tagHvc1 && this.streamInfo?.codec === 'h264';
2213
+ }
2214
+ /**
2215
+ * Bring the live session's second output in line with the plan — by
2216
+ * restarting it once, only after its first frame, and never with a second
2217
+ * reconfigure already in flight. The restart is not a fault: it is counted
2218
+ * in `segments.reconfigures`, not `restarts`, and keeps the recorder slot.
2219
+ */
2220
+ reconcileRecording() {
2221
+ const session = this.session;
2222
+ if (!session || !this.opened || this.fallback || this.startingUp)
2223
+ return;
2224
+ if (session.firstFrameAtMs === null || this.reconfigurePendingFor)
2225
+ return;
2226
+ const want = this.planRecording();
2227
+ const have = session.recording ? session.recording.plan : null;
2228
+ if (this.sessionSatisfies(have, want))
2229
+ return;
2230
+ this.segCounters.reconfigures += 1;
2231
+ this.log('info', want
2232
+ ? `RTSP stream session restarting to record ${want.segmentSeconds}s segments` +
2233
+ (want.audio ? ` with the camera's audio (${want.audio.mode === 'copy' ? 'copied' : 'to AAC'}, ${want.audio.source})` : '')
2234
+ : 'RTSP stream session restarting to stop segment recording');
2235
+ session.superseded = true;
2236
+ this.reconfigurePendingFor = session;
2237
+ this.session = null;
2238
+ this.killSession(session);
2239
+ }
2240
+ onSessionFirstFrame(session) {
2241
+ session.firstFrameAtMs = this.now();
2242
+ this.reconcileRecording();
2243
+ }
2244
+ onSessionStreamInfo(session, info) {
2245
+ session.streamInfo = info;
2246
+ if (this.session !== session)
2247
+ return;
2248
+ const previous = this.streamInfo;
2249
+ this.streamInfo = info;
2250
+ if (!previous || previous.codec !== info.codec || !sameAudioInfo(previous.audio, info.audio)) {
2251
+ this.reconcileRecording();
2252
+ }
2253
+ }
2254
+ /** The work directory for a session that will record, or null for look-only. */
2255
+ prepareSessionRecording() {
2256
+ const plan = this.planRecording();
2257
+ if (!plan)
2258
+ return null;
2259
+ const workDir = path.join(plan.dir, `${SESSION_WORKDIR_PREFIX}${this.now()}-${this.sessionStarts + 1}`);
2260
+ try {
2261
+ fs.mkdirSync(path.join(plan.dir, exports.CLOSED_SEGMENTS_DIRNAME), { recursive: true });
2262
+ fs.mkdirSync(workDir, { recursive: true });
2263
+ }
2264
+ catch (err) {
2265
+ // A directory we cannot create is the second output's failure, never the
2266
+ // look path's: say why, pause recording, and run this session look-only.
2267
+ this.suspendRecording(`segment directory unavailable: ${errorText(err)}`);
2268
+ return null;
2269
+ }
2270
+ return {
2271
+ plan,
2272
+ workDir,
2273
+ csvPath: path.join(workDir, 'segments.csv'),
2274
+ csvOffset: 0,
2275
+ csvRemainder: '',
2276
+ pending: [],
2277
+ handled: new Set(),
2278
+ anchor: null,
2279
+ closedCount: 0,
2280
+ outputStarted: false,
2281
+ };
2282
+ }
2283
+ /** Pause recording, doubling from SEGMENT_SUSPEND_BASE_MS, then reconcile again. */
2284
+ suspendRecording(reason) {
2285
+ this.segCounters.outputFailures += 1;
2286
+ const exponent = Math.min(this.consecutiveOutputFailures, 16);
2287
+ const cooldownMs = Math.min(exports.SEGMENT_SUSPEND_MAX_MS, exports.SEGMENT_SUSPEND_BASE_MS * 2 ** exponent);
2288
+ this.consecutiveOutputFailures += 1;
2289
+ this.segmentSuspension = { untilMs: this.now() + cooldownMs };
2290
+ this.segCounters.lastError = `${reason}; recording paused ${Math.round(cooldownMs / 1000)}s`;
2291
+ this.log('warn', `segment recording: ${this.segCounters.lastError}`);
2292
+ if (this.segmentSuspendTimer)
2293
+ clearTimeout(this.segmentSuspendTimer);
2294
+ this.segmentSuspendTimer = setTimeout(() => {
2295
+ this.segmentSuspendTimer = null;
2296
+ this.reconcileRecording();
2297
+ }, cooldownMs);
2298
+ if (typeof this.segmentSuspendTimer.unref === 'function')
2299
+ this.segmentSuspendTimer.unref();
2300
+ }
2301
+ clearSegmentSuspension() {
2302
+ this.segmentSuspension = null;
2303
+ if (this.segmentSuspendTimer) {
2304
+ clearTimeout(this.segmentSuspendTimer);
2305
+ this.segmentSuspendTimer = null;
2306
+ }
2307
+ }
2308
+ /**
2309
+ * Leave the camera's audio out of the segments for a doubling pause
2310
+ * (`AUDIO_SUSPEND_BASE_MS`..`AUDIO_SUSPEND_MAX_MS`), then reconcile again.
2311
+ * Counted as a second-output failure too, so `open()` does not spend a
2312
+ * validation attempt on it; video recording is untouched.
2313
+ */
2314
+ suspendAudio(reason, stall) {
2315
+ this.segCounters.outputFailures += 1;
2316
+ this.audioCounters.failures += 1;
2317
+ if (stall)
2318
+ this.audioCounters.stalls += 1;
2319
+ const exponent = Math.min(this.consecutiveAudioFailures, 16);
2320
+ const cooldownMs = Math.min(exports.AUDIO_SUSPEND_MAX_MS, exports.AUDIO_SUSPEND_BASE_MS * 2 ** exponent);
2321
+ this.consecutiveAudioFailures += 1;
2322
+ this.audioSuspension = { untilMs: this.now() + cooldownMs };
2323
+ this.audioCounters.lastError = `${reason}; audio paused ${Math.round(cooldownMs / 1000)}s, video keeps recording`;
2324
+ this.log('warn', `segment recording: ${this.audioCounters.lastError}`);
2325
+ this.armAudioRetry();
2326
+ }
2327
+ /**
2328
+ * The ONE thing that brings audio back after a pause: reconcile when the
2329
+ * pause ends. Armed by `suspendAudio`, and re-armed by `open()` — `close()`
2330
+ * cancels the timer but keeps the pause, so a feed reopened mid-pause would
2331
+ * otherwise record video only until some unrelated restart.
2332
+ */
2333
+ armAudioRetry() {
2334
+ if (this.audioSuspendTimer)
2335
+ clearTimeout(this.audioSuspendTimer);
2336
+ this.audioSuspendTimer = null;
2337
+ if (!this.audioSuspension)
2338
+ return;
2339
+ const remainingMs = this.audioSuspension.untilMs - this.now();
2340
+ if (remainingMs <= 0)
2341
+ return; // already over: the next plan maps audio
2342
+ this.audioSuspendTimer = setTimeout(() => {
2343
+ this.audioSuspendTimer = null;
2344
+ this.reconcileRecording();
2345
+ }, remainingMs);
2346
+ if (typeof this.audioSuspendTimer.unref === 'function')
2347
+ this.audioSuspendTimer.unref();
2348
+ }
2349
+ /**
2350
+ * A session that maps audio and has written no file `AUDIO_START_DEADLINE_MS`
2351
+ * after its first frame is stalled on a microphone that sends nothing: drop
2352
+ * the audio and restart the session video-only. Checked once, at the deadline.
2353
+ */
2354
+ checkAudioStall(session, rec, nowMs) {
2355
+ if (!rec.plan.audio || rec.outputStarted || session.firstFrameAtMs === null)
2356
+ return false;
2357
+ if (nowMs - session.firstFrameAtMs < exports.AUDIO_START_DEADLINE_MS)
2358
+ return false;
2359
+ let written = rec.handled.size > 0;
2360
+ if (!written) {
2361
+ try {
2362
+ written = fs.readdirSync(rec.workDir).some((name) => /^seg_\d+\.mp4$/i.test(name));
2363
+ }
2364
+ catch {
2365
+ written = false;
2366
+ }
2367
+ }
2368
+ if (written) {
2369
+ rec.outputStarted = true;
2370
+ return false;
2371
+ }
2372
+ this.suspendAudio(`the segment output wrote nothing ${Math.round(exports.AUDIO_START_DEADLINE_MS / 1000)}s after the first frame with ` +
2373
+ `the camera's audio (${rec.plan.audio.source}) mapped: its microphone sends no audio`, true);
2374
+ this.reconcileRecording();
2375
+ return true;
2376
+ }
2377
+ ensureSegmentPolling() {
2378
+ if (this.segmentPollTimer)
2379
+ return;
2380
+ this.lastSegmentPollAtMs = this.now();
2381
+ this.segmentPollTimer = setInterval(() => this.pollSegments(), SEGMENT_POLL_MS);
2382
+ if (typeof this.segmentPollTimer.unref === 'function')
2383
+ this.segmentPollTimer.unref();
2384
+ }
2385
+ stopSegmentPolling() {
2386
+ if (this.segmentPollTimer) {
2387
+ clearInterval(this.segmentPollTimer);
2388
+ this.segmentPollTimer = null;
2389
+ }
2390
+ }
2391
+ /** One read of the live session's segment list: new closes move into the ring. */
2392
+ pollSegments() {
2393
+ const nowMs = this.now();
2394
+ const onTime = this.lastSegmentPollAtMs !== null && nowMs - this.lastSegmentPollAtMs <= 2 * SEGMENT_POLL_MS;
2395
+ this.lastSegmentPollAtMs = nowMs;
2396
+ const session = this.session;
2397
+ const rec = session?.recording;
2398
+ if (!session || !rec) {
2399
+ this.stopSegmentPolling();
2400
+ return;
2401
+ }
2402
+ try {
2403
+ const fresh = this.readSegmentList(session);
2404
+ if (fresh.length > 0) {
2405
+ if (!rec.anchor && rec.pending.length > 0) {
2406
+ this.anchorFor(rec, rec.pending[0], session.firstFrameAtMs, session.streamInfo);
2407
+ }
2408
+ this.guardAnchorDrift(rec, fresh[fresh.length - 1], nowMs, onTime, session.streamInfo);
2409
+ }
2410
+ if (rec.pending.length > 0 && this.flushPending(session) > 0)
2411
+ this.enforceRing();
2412
+ this.checkAudioStall(session, rec, nowMs);
2413
+ }
2414
+ catch (err) {
2415
+ this.segCounters.lastError = `segment list: ${errorText(err)}`;
2416
+ }
2417
+ }
2418
+ /** Read whatever the segment list gained since the last read. */
2419
+ readSegmentList(session) {
2420
+ const rec = session.recording;
2421
+ if (!rec)
2422
+ return [];
2423
+ let size;
2424
+ try {
2425
+ size = fs.statSync(rec.csvPath).size;
2426
+ }
2427
+ catch {
2428
+ return [];
2429
+ }
2430
+ if (size < rec.csvOffset) {
2431
+ rec.csvOffset = 0;
2432
+ rec.csvRemainder = '';
2433
+ }
2434
+ if (size === rec.csvOffset)
2435
+ return [];
2436
+ const buf = Buffer.alloc(size - rec.csvOffset);
2437
+ const fd = fs.openSync(rec.csvPath, 'r');
2438
+ let read = 0;
2439
+ try {
2440
+ read = fs.readSync(fd, buf, 0, buf.length, rec.csvOffset);
2441
+ }
2442
+ finally {
2443
+ fs.closeSync(fd);
2444
+ }
2445
+ rec.csvOffset += read;
2446
+ const { entries, remainder } = parseSegmentListCsv(rec.csvRemainder + buf.subarray(0, read).toString('utf8'));
2447
+ rec.csvRemainder = remainder;
2448
+ const fresh = [];
2449
+ for (const entry of entries) {
2450
+ if (rec.handled.has(entry.name))
2451
+ continue;
2452
+ rec.handled.add(entry.name);
2453
+ rec.pending.push(entry);
2454
+ fresh.push(entry);
2455
+ }
2456
+ return fresh;
2457
+ }
2458
+ /** Move listed segments into the ring, in list order. Returns how many moved. */
2459
+ flushPending(session) {
2460
+ const rec = session.recording;
2461
+ if (!rec)
2462
+ return 0;
2463
+ let closed = 0;
2464
+ while (rec.pending.length > 0) {
2465
+ const outcome = this.closeSegment(session, rec, rec.pending[0]);
2466
+ if (outcome === 'retry')
2467
+ break;
2468
+ rec.pending.shift();
2469
+ if (outcome === 'closed')
2470
+ closed += 1;
2471
+ }
2472
+ return closed;
2473
+ }
2474
+ closeSegment(session, rec, entry) {
2475
+ const src = path.join(rec.workDir, entry.name);
2476
+ let size;
2477
+ try {
2478
+ const st = fs.statSync(src);
2479
+ size = st.isFile() ? st.size : 0;
2480
+ }
2481
+ catch (err) {
2482
+ return err?.code === 'ENOENT' ? 'gone' : 'retry';
2483
+ }
2484
+ if (size <= 0) {
2485
+ try {
2486
+ fs.unlinkSync(src);
2487
+ }
2488
+ catch {
2489
+ /* best-effort */
2490
+ }
2491
+ this.segCounters.partialsDeleted += 1;
2492
+ return 'gone';
2493
+ }
2494
+ const anchor = this.anchorFor(rec, entry, session.firstFrameAtMs, session.streamInfo);
2495
+ const captureStartMs = Math.round(anchor.wallMs + (entry.startSec - anchor.startSec) * 1000);
2496
+ const moved = this.moveIntoRing(rec.plan.dir, src, path.basename(rec.workDir), entry, captureStartMs, size, session.streamInfo, false);
2497
+ if (!moved)
2498
+ return 'retry';
2499
+ rec.closedCount += 1;
2500
+ return 'closed';
2501
+ }
2502
+ /**
2503
+ * The wall clock of the session's FIRST listed segment.
2504
+ *
2505
+ * The first decoded frame and the first copied packet are the same keyframe
2506
+ * (a stream copy drops what precedes it), so the first listed segment starts
2507
+ * at the first frame's wall clock and every later one at its offset from it.
2508
+ * When ffmpeg starts the output timeline at 0 — measured 0.000000 for H.264
2509
+ * and HEVC through mediamtx — that is exactly first frame + startSec.
2510
+ *
2511
+ * With the camera's audio mapped the timeline starts at the first audio
2512
+ * PACKET instead, which can arrive before the first video keyframe (rig:
2513
+ * 0.905 s on a 6 fps HEVC camera, every listed time shifted by it). The first
2514
+ * frame then sits at the first segment's VIDEO start, which the file's own
2515
+ * edit list states (`readVideoStartSec`), so that is the anchor's media time.
2516
+ * Without it every segment of the session would be dated up to a GOP late.
2517
+ */
2518
+ anchorFor(rec, entry, firstFrameAtMs, stream) {
2519
+ if (!rec.anchor) {
2520
+ const leadSec = rec.plan.audio && firstFrameAtMs !== null ? readVideoStartSec(path.join(rec.workDir, entry.name)) : 0;
2521
+ if (rec.plan.audio && firstFrameAtMs !== null)
2522
+ this.audioCounters.lastVideoLeadMs = Math.round(leadSec * 1000);
2523
+ rec.anchor = {
2524
+ wallMs: firstFrameAtMs ?? this.now() - (entry.endSec - entry.startSec) * 1000,
2525
+ startSec: entry.startSec + leadSec,
2526
+ };
2527
+ this.persistAnchor(rec, stream);
2528
+ }
2529
+ return rec.anchor;
2530
+ }
2531
+ /**
2532
+ * Keep the anchor honest against the one wall-clock fact a close gives us:
2533
+ * a segment cannot end after we saw it closed, and on a timely poll it ended
2534
+ * at most one poll before. The camera's media clock is not the wall clock,
2535
+ * and a session runs for days.
2536
+ */
2537
+ guardAnchorDrift(rec, newest, nowMs, onTime, stream) {
2538
+ if (!rec.anchor)
2539
+ return;
2540
+ const predictedEndMs = rec.anchor.wallMs + (newest.endSec - rec.anchor.startSec) * 1000;
2541
+ const drift = predictedEndMs - nowMs;
2542
+ this.segCounters.lastAnchorDriftMs = Math.round(drift);
2543
+ let shift = 0;
2544
+ if (drift > ANCHOR_FUTURE_TOLERANCE_MS)
2545
+ shift = -drift;
2546
+ else if (onTime && drift < -(SEGMENT_POLL_MS + ANCHOR_LAG_TOLERANCE_MS))
2547
+ shift = -drift - SEGMENT_POLL_MS / 2;
2548
+ if (shift === 0)
2549
+ return;
2550
+ rec.anchor.wallMs += shift;
2551
+ this.segCounters.reanchors += 1;
2552
+ this.persistAnchor(rec, stream);
2553
+ }
2554
+ persistAnchor(rec, stream) {
2555
+ if (!rec.anchor)
2556
+ return;
2557
+ try {
2558
+ writeFileAtomic(path.join(rec.workDir, 'anchor.json'), JSON.stringify({ ...rec.anchor, stream }));
2559
+ }
2560
+ catch {
2561
+ /* recovery falls back to the file's own last write */
2562
+ }
2563
+ }
2564
+ /**
2565
+ * Write the sidecar, then move the closed file beside it, then emit. Null
2566
+ * when the move must be retried (Windows refuses to rename a file ffmpeg
2567
+ * still holds; the next poll asks again).
2568
+ */
2569
+ moveIntoRing(dir, src, tag, entry, captureStartMs, bytes, stream, recovered) {
2570
+ const durationMs = Math.max(0, Math.round((entry.endSec - entry.startSec) * 1000));
2571
+ // Zero-padded capture start first, so a name sort is a time sort — the
2572
+ // ring evicts oldest-first by name.
2573
+ const base = `${String(Math.max(0, captureStartMs)).padStart(13, '0')}-${tag}-${entry.name.replace(/\.mp4$/i, '')}`;
2574
+ const closedDir = path.join(dir, exports.CLOSED_SEGMENTS_DIRNAME);
2575
+ const file = path.join(closedDir, `${base}.mp4`);
2576
+ const metaFile = path.join(closedDir, `${base}.json`);
2577
+ const sidecar = {
2578
+ version: 1,
2579
+ startSec: entry.startSec,
2580
+ endSec: entry.endSec,
2581
+ captureStartMs,
2582
+ captureEndMs: captureStartMs + durationMs,
2583
+ bytes,
2584
+ stream,
2585
+ };
2586
+ try {
2587
+ fs.mkdirSync(closedDir, { recursive: true });
2588
+ writeFileAtomic(metaFile, JSON.stringify(sidecar));
2589
+ }
2590
+ catch (err) {
2591
+ this.segCounters.lastError = `segment sidecar: ${errorText(err)}`;
2592
+ return null;
2593
+ }
2594
+ try {
2595
+ fs.renameSync(src, file);
2596
+ }
2597
+ catch (err) {
2598
+ try {
2599
+ fs.unlinkSync(metaFile);
2600
+ }
2601
+ catch {
2602
+ /* best-effort */
2603
+ }
2604
+ if (!isBusyError(err))
2605
+ this.segCounters.lastError = `segment move: ${errorText(err)}`;
2606
+ return null;
2607
+ }
2608
+ const segment = {
2609
+ file,
2610
+ metaFile,
2611
+ startSec: entry.startSec,
2612
+ endSec: entry.endSec,
2613
+ captureStartMs,
2614
+ captureEndMs: sidecar.captureEndMs,
2615
+ bytes,
2616
+ stream,
2617
+ recovered,
2618
+ };
2619
+ this.countSegment(segment);
2620
+ this.emitSegment(segment);
2621
+ return segment;
2622
+ }
2623
+ countSegment(segment) {
2624
+ const seconds = Math.max(0, segment.endSec - segment.startSec);
2625
+ if (segment.recovered) {
2626
+ this.segCounters.recovered += 1;
2627
+ }
2628
+ else {
2629
+ this.segCounters.closed += 1;
2630
+ this.segCounters.secondsClosed += seconds;
2631
+ this.segCounters.bytesClosed += segment.bytes;
2632
+ this.segCounters.lastSegmentAtMs = this.now();
2633
+ }
2634
+ if (seconds > 0) {
2635
+ this.measuredSegmentBytes += segment.bytes;
2636
+ this.measuredSegmentSeconds += seconds;
2637
+ }
2638
+ }
2639
+ emitSegment(segment) {
2640
+ try {
2641
+ this.emit('segment', segment);
2642
+ }
2643
+ catch (err) {
2644
+ this.log('warn', `segment recording: a 'segment' listener threw: ${errorText(err)}`);
2645
+ }
2646
+ }
2647
+ /**
2648
+ * A session that recorded has ended: read its list one last time, move what
2649
+ * it closed, judge the second output, and delete what it never listed.
2650
+ */
2651
+ finishSessionRecording(session, stderr) {
2652
+ const rec = session.recording;
2653
+ if (!rec)
2654
+ return;
2655
+ try {
2656
+ this.readSegmentList(session);
2657
+ if (!rec.anchor && rec.pending.length > 0) {
2658
+ this.anchorFor(rec, rec.pending[0], session.firstFrameAtMs, session.streamInfo);
2659
+ }
2660
+ this.flushPending(session);
2661
+ }
2662
+ catch (err) {
2663
+ this.segCounters.lastError = `segment list: ${errorText(err)}`;
2664
+ }
2665
+ // Judge the second output, for a session we did not stop ourselves:
2666
+ // - its input opened and it never produced a frame: ffmpeg opens the
2667
+ // outputs right after the input, so the second output is what failed;
2668
+ // - it closed nothing and ffmpeg named a write failure.
2669
+ // Either way the next session must not carry it. A camera that dropped
2670
+ // mid-segment says neither, and keeps recording through its restart.
2671
+ // When the session carried the camera's audio, the audio is what goes:
2672
+ // the next session records video exactly as it did before audio existed,
2673
+ // and only a failure of THAT session pauses recording.
2674
+ const judged = !session.superseded && !session.detached && rec.closedCount === 0;
2675
+ const noFrame = judged && session.probe.inputOpened && session.firstFrameAtMs === null;
2676
+ const writeFailure = judged && !noFrame && SEGMENT_OUTPUT_FAILURE_RE.test(stderr);
2677
+ if ((noFrame || writeFailure) && rec.plan.audio) {
2678
+ this.suspendAudio(noFrame
2679
+ ? `a session with the camera's audio (${rec.plan.audio.source}) mapped opened its input and produced no frame`
2680
+ : `segment output failed with the camera's audio (${rec.plan.audio.source}) mapped: ` +
2681
+ (0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr.match(SEGMENT_OUTPUT_FAILURE_RE)?.[0] ?? '', 120), false);
2682
+ }
2683
+ else if (noFrame) {
2684
+ this.suspendRecording('a session with segment recording opened its input and produced no frame');
2685
+ }
2686
+ else if (writeFailure) {
2687
+ this.suspendRecording(`segment output failed: ${(0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr.match(SEGMENT_OUTPUT_FAILURE_RE)?.[0] ?? '', 120)}`);
2688
+ }
2689
+ else if (rec.closedCount > 0) {
2690
+ this.consecutiveOutputFailures = 0;
2691
+ if (rec.plan.audio)
2692
+ this.consecutiveAudioFailures = 0;
2693
+ }
2694
+ // Everything left was never listed: the segment ffmpeg was still writing,
2695
+ // the list and the anchor. A listed file the OS would not let us move yet
2696
+ // keeps the directory for the next open()'s recovery instead.
2697
+ if (rec.pending.length === 0)
2698
+ this.removeWorkDir(rec.workDir, true);
2699
+ this.enforceRing();
2700
+ if (!this.session?.recording)
2701
+ this.stopSegmentPolling();
2702
+ }
2703
+ removeWorkDir(workDir, countPartials = false) {
2704
+ let names = [];
2705
+ try {
2706
+ names = fs.readdirSync(workDir);
2707
+ }
2708
+ catch {
2709
+ return;
2710
+ }
2711
+ for (const name of names) {
2712
+ try {
2713
+ fs.unlinkSync(path.join(workDir, name));
2714
+ if (countPartials && name.toLowerCase().endsWith('.mp4'))
2715
+ this.segCounters.partialsDeleted += 1;
2716
+ }
2717
+ catch {
2718
+ /* best-effort */
2719
+ }
2720
+ }
2721
+ try {
2722
+ fs.rmdirSync(workDir);
2723
+ }
2724
+ catch {
2725
+ /* best-effort */
2726
+ }
2727
+ }
2728
+ /**
2729
+ * Hand out what an earlier process left: closed segments with sidecars, and
2730
+ * listed segments still in a session work directory. Unlisted files are
2731
+ * partials and are deleted. Runs once per directory, before the first session.
2732
+ */
2733
+ recoverSegments() {
2734
+ const cfg = this.segmentConfig;
2735
+ if (!cfg)
2736
+ return;
2737
+ this.segmentsRecoveredFor = cfg.dir;
2738
+ let names;
2739
+ try {
2740
+ names = fs.readdirSync(cfg.dir);
2741
+ }
2742
+ catch {
2743
+ return; // nothing recorded here yet
2744
+ }
2745
+ // closed/ FIRST: recovering a work directory below moves files INTO it.
2746
+ const closedDir = path.join(cfg.dir, exports.CLOSED_SEGMENTS_DIRNAME);
2747
+ let closed = [];
2748
+ try {
2749
+ closed = fs.readdirSync(closedDir).sort();
2750
+ }
2751
+ catch {
2752
+ closed = [];
2753
+ }
2754
+ const present = new Set(closed);
2755
+ for (const name of closed) {
2756
+ const file = path.join(closedDir, name);
2757
+ const lower = name.toLowerCase();
2758
+ if (lower.endsWith('.tmp')) {
2759
+ try {
2760
+ fs.unlinkSync(file);
2761
+ }
2762
+ catch {
2763
+ /* best-effort */
2764
+ }
2765
+ continue;
2766
+ }
2767
+ if (lower.endsWith('.json')) {
2768
+ if (!present.has(name.replace(/\.json$/i, '.mp4'))) {
2769
+ try {
2770
+ fs.unlinkSync(file);
2771
+ }
2772
+ catch {
2773
+ /* best-effort */
2774
+ }
2775
+ }
2776
+ continue;
2777
+ }
2778
+ if (!lower.endsWith('.mp4'))
2779
+ continue;
2780
+ const metaFile = file.replace(/\.mp4$/i, '.json');
2781
+ const sidecar = readSidecar(metaFile);
2782
+ let bytes;
2783
+ try {
2784
+ bytes = fs.statSync(file).size;
2785
+ }
2786
+ catch {
2787
+ continue;
2788
+ }
2789
+ if (!sidecar) {
2790
+ // No capture time, so it can never be indexed.
2791
+ try {
2792
+ fs.unlinkSync(file);
2793
+ }
2794
+ catch {
2795
+ /* best-effort */
2796
+ }
2797
+ this.segCounters.partialsDeleted += 1;
2798
+ continue;
2799
+ }
2800
+ const segment = {
2801
+ file,
2802
+ metaFile,
2803
+ startSec: sidecar.startSec,
2804
+ endSec: sidecar.endSec,
2805
+ captureStartMs: sidecar.captureStartMs,
2806
+ captureEndMs: sidecar.captureEndMs,
2807
+ bytes,
2808
+ stream: sidecar.stream,
2809
+ recovered: true,
2810
+ };
2811
+ this.countSegment(segment);
2812
+ this.emitSegment(segment);
2813
+ }
2814
+ const live = this.session?.recording?.workDir ?? null;
2815
+ for (const name of names.sort()) {
2816
+ if (!name.startsWith(SESSION_WORKDIR_PREFIX))
2817
+ continue;
2818
+ const workDir = path.join(cfg.dir, name);
2819
+ if (workDir === live)
2820
+ continue;
2821
+ try {
2822
+ this.recoverWorkDir(cfg.dir, workDir);
2823
+ }
2824
+ catch (err) {
2825
+ this.segCounters.lastError = `segment recovery: ${errorText(err)}`;
2826
+ }
2827
+ }
2828
+ this.enforceRing();
2829
+ }
2830
+ recoverWorkDir(dir, workDir) {
2831
+ let text = '';
2832
+ try {
2833
+ text = fs.readFileSync(path.join(workDir, 'segments.csv'), 'utf8');
2834
+ }
2835
+ catch {
2836
+ text = '';
2837
+ }
2838
+ const { entries } = parseSegmentListCsv(text);
2839
+ let anchor = null;
2840
+ let stream = null;
2841
+ try {
2842
+ const raw = JSON.parse(fs.readFileSync(path.join(workDir, 'anchor.json'), 'utf8'));
2843
+ if (Number.isFinite(raw?.wallMs) && Number.isFinite(raw?.startSec)) {
2844
+ anchor = { wallMs: raw.wallMs, startSec: raw.startSec };
2845
+ }
2846
+ if (raw?.stream && typeof raw.stream.codec === 'string')
2847
+ stream = raw.stream;
2848
+ }
2849
+ catch {
2850
+ anchor = null;
2851
+ }
2852
+ const tag = path.basename(workDir);
2853
+ let leftBehind = false;
2854
+ for (const entry of entries) {
2855
+ const src = path.join(workDir, entry.name);
2856
+ let st;
2857
+ try {
2858
+ st = fs.statSync(src);
2859
+ }
2860
+ catch {
2861
+ continue;
2862
+ }
2863
+ if (!st.isFile() || st.size <= 0)
2864
+ continue;
2865
+ // Without the anchor, the file's own last write is its close, i.e. its end.
2866
+ const captureStartMs = anchor
2867
+ ? Math.round(anchor.wallMs + (entry.startSec - anchor.startSec) * 1000)
2868
+ : Math.round(st.mtimeMs - (entry.endSec - entry.startSec) * 1000);
2869
+ if (!this.moveIntoRing(dir, src, tag, entry, captureStartMs, st.size, stream, true))
2870
+ leftBehind = true;
2871
+ }
2872
+ if (!leftBehind)
2873
+ this.removeWorkDir(workDir, true);
2874
+ }
2875
+ /**
2876
+ * Hold the closed segments to min(ringSeconds x measured bytes/s, 10% of the
2877
+ * volume's free bytes), deleting oldest first. A file the OS will not let us
2878
+ * delete (Windows, mid-upload) is skipped, never waited on.
2879
+ */
2880
+ enforceRing() {
2881
+ const cfg = this.segmentConfig;
2882
+ if (!cfg)
2883
+ return;
2884
+ const closedDir = path.join(cfg.dir, exports.CLOSED_SEGMENTS_DIRNAME);
2885
+ let names;
2886
+ try {
2887
+ names = fs.readdirSync(closedDir).filter((n) => n.toLowerCase().endsWith('.mp4')).sort();
2888
+ }
2889
+ catch {
2890
+ this.segCounters.ringSegments = 0;
2891
+ this.segCounters.ringBytes = 0;
2892
+ return;
2893
+ }
2894
+ const items = [];
2895
+ for (const name of names) {
2896
+ const file = path.join(closedDir, name);
2897
+ try {
2898
+ items.push({ file, bytes: fs.statSync(file).size });
2899
+ }
2900
+ catch {
2901
+ /* delivered and deleted under us */
2902
+ }
2903
+ }
2904
+ let total = items.reduce((n, item) => n + item.bytes, 0);
2905
+ let remaining = items.length;
2906
+ const freeBytes = this.freeBytesFn(cfg.dir);
2907
+ const bytesPerSec = this.measuredBytesPerSec();
2908
+ const byRing = bytesPerSec === null ? null : Math.floor(cfg.ringSeconds * bytesPerSec);
2909
+ const byFree = freeBytes === null ? null : Math.floor(exports.RING_FREE_FRACTION * freeBytes);
2910
+ const limit = byRing === null ? byFree : byFree === null ? byRing : Math.min(byRing, byFree);
2911
+ if (limit !== null) {
2912
+ for (const item of items) {
2913
+ if (total <= limit)
2914
+ break;
2915
+ try {
2916
+ fs.unlinkSync(item.file);
2917
+ }
2918
+ catch {
2919
+ continue;
2920
+ }
2921
+ const metaFile = item.file.replace(/\.mp4$/i, '.json');
2922
+ try {
2923
+ fs.unlinkSync(metaFile);
2924
+ }
2925
+ catch {
2926
+ /* best-effort */
2927
+ }
2928
+ total -= item.bytes;
2929
+ remaining -= 1;
2930
+ this.segCounters.evicted += 1;
2931
+ this.segCounters.evictedBytes += item.bytes;
2932
+ try {
2933
+ this.emit('segment_evicted', { file: item.file, metaFile, bytes: item.bytes });
2934
+ }
2935
+ catch (err) {
2936
+ this.log('warn', `segment recording: a 'segment_evicted' listener threw: ${errorText(err)}`);
2937
+ }
2938
+ }
2939
+ }
2940
+ this.segCounters.ringSegments = remaining;
2941
+ this.segCounters.ringBytes = total;
2942
+ this.segCounters.ringLimitBytes = limit;
2943
+ this.segCounters.freeBytes = freeBytes;
2944
+ }
2945
+ measuredBytesPerSec() {
2946
+ return this.measuredSegmentSeconds > 0 ? this.measuredSegmentBytes / this.measuredSegmentSeconds : null;
2947
+ }
2948
+ segmentStats() {
2949
+ const cfg = this.segmentConfig;
2950
+ const suspension = this.segmentSuspension && this.now() < this.segmentSuspension.untilMs ? this.segmentSuspension : null;
2951
+ const bytesPerSec = this.measuredBytesPerSec();
2952
+ const c = this.segCounters;
2953
+ return {
2954
+ state: this.recordingState(suspension !== null),
2955
+ dir: cfg?.dir ?? null,
2956
+ segmentSeconds: cfg?.segmentSeconds ?? null,
2957
+ ringSeconds: cfg?.ringSeconds ?? null,
2958
+ codec: this.streamInfo?.codec ?? null,
2959
+ segmentsClosed: c.closed,
2960
+ segmentsRecovered: c.recovered,
2961
+ secondsClosed: Math.round(c.secondsClosed * 1000) / 1000,
2962
+ bytesClosed: c.bytesClosed,
2963
+ partialsDeleted: c.partialsDeleted,
2964
+ ringSegments: c.ringSegments,
2965
+ ringBytes: c.ringBytes,
2966
+ ringLimitBytes: c.ringLimitBytes,
2967
+ measuredBytesPerSec: bytesPerSec === null ? null : Math.round(bytesPerSec),
2968
+ freeBytes: c.freeBytes,
2969
+ evictedSegments: c.evicted,
2970
+ evictedBytes: c.evictedBytes,
2971
+ reconfigures: c.reconfigures,
2972
+ outputFailures: c.outputFailures,
2973
+ suspendedUntilMs: suspension ? suspension.untilMs : null,
2974
+ reanchors: c.reanchors,
2975
+ lastAnchorDriftMs: c.lastAnchorDriftMs,
2976
+ lastSegmentAtMs: c.lastSegmentAtMs,
2977
+ lastError: c.lastError,
2978
+ audio: this.audioStats(),
2979
+ };
2980
+ }
2981
+ /** The camera's audio in the segments. Derived on every call, like the rest. */
2982
+ audioStats() {
2983
+ const source = this.streamInfo?.audio ?? null;
2984
+ const suspension = this.audioSuspension && this.now() < this.audioSuspension.untilMs ? this.audioSuspension : null;
2985
+ const live = this.session?.recording?.plan.audio ?? null;
2986
+ let state;
2987
+ if (live)
2988
+ state = live.mode === 'copy' ? 'copy' : 'transcode';
2989
+ else if (!this.streamInfo)
2990
+ state = 'unknown';
2991
+ else if (!source)
2992
+ state = 'no_audio_track';
2993
+ else if (!audioPlanFor(source))
2994
+ state = 'unsupported_codec';
2995
+ else if (suspension)
2996
+ state = 'suspended';
2997
+ else
2998
+ state = 'waiting_for_session';
2999
+ return {
3000
+ state,
3001
+ codec: source?.codec ?? null,
3002
+ sampleRate: source?.sampleRate ?? null,
3003
+ channels: source?.channels ?? null,
3004
+ bitrateBps: live?.bitrateBps ?? null,
3005
+ failures: this.audioCounters.failures,
3006
+ stalls: this.audioCounters.stalls,
3007
+ suspendedUntilMs: suspension ? suspension.untilMs : null,
3008
+ lastVideoLeadMs: this.audioCounters.lastVideoLeadMs,
3009
+ lastError: this.audioCounters.lastError,
3010
+ };
3011
+ }
3012
+ recordingState(suspended) {
3013
+ const cfg = this.segmentConfig;
3014
+ if (!cfg || !cfg.enabled)
3015
+ return 'off';
3016
+ if (this.crop !== undefined)
3017
+ return 'cropped';
3018
+ if (!this.persistentRequested || this.mode === 'per_grab')
3019
+ return 'per_grab';
3020
+ if (this.session?.recording)
3021
+ return 'recording';
3022
+ const codec = this.streamInfo?.codec ?? null;
3023
+ if (codec !== null && !exports.RECORDABLE_CODECS.includes(codec))
3024
+ return 'unsupported_codec';
3025
+ if (suspended)
3026
+ return 'suspended';
3027
+ return 'waiting_for_session';
3028
+ }
1352
3029
  log(level, message) {
1353
3030
  this.onLog?.(level, (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(message));
1354
3031
  }
1355
3032
  }
1356
3033
  exports.RTSPStreamCameraProvider = RTSPStreamCameraProvider;
3034
+ /** The segment filename template; `%` in the directory is ffmpeg's to read. */
3035
+ function segmentPatternFor(workDir) {
3036
+ return path.join(workDir.replace(/%/g, '%%'), 'seg_%06d.mp4');
3037
+ }
1357
3038
  //# sourceMappingURL=RTSPStreamCameraProvider.js.map