@trillboards/edge-platform-rtsp 0.2.17 → 0.2.20
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/dist/LiveViewH264Capture.d.ts +39 -0
- package/dist/LiveViewH264Capture.d.ts.map +1 -0
- package/dist/LiveViewH264Capture.js +211 -0
- package/dist/LiveViewH264Capture.js.map +1 -0
- package/dist/MainStreamSession.d.ts +426 -0
- package/dist/MainStreamSession.d.ts.map +1 -0
- package/dist/MainStreamSession.js +1269 -0
- package/dist/MainStreamSession.js.map +1 -0
- package/dist/RTSPStreamCameraProvider.d.ts +72 -0
- package/dist/RTSPStreamCameraProvider.d.ts.map +1 -1
- package/dist/RTSPStreamCameraProvider.js +125 -4
- package/dist/RTSPStreamCameraProvider.js.map +1 -1
- package/dist/index.d.ts +8 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +29 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,1269 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
+
if (mod && mod.__esModule) return mod;
|
|
20
|
+
var result = {};
|
|
21
|
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
+
__setModuleDefault(result, mod);
|
|
23
|
+
return result;
|
|
24
|
+
};
|
|
25
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
+
exports.probeMainStream = exports.FramecrcPacketReader = exports.buildMainStreamProbeOutputArgs = exports.MainStreamRingOutput = exports.MainStreamSession = exports.buildMainStreamInputArgs = exports.__resetMainStreamAdmissionForTests = exports.mainStreamSessionStatsFor = exports.acquireMainStreamSlot = exports.MAIN_STREAM_WORKDIR_PREFIX = exports.MAIN_STREAM_CLOCK_WINDOW_MS = exports.MAIN_STREAM_STARTUP_TIMEOUT_MS = exports.MAIN_STREAM_HEALTHY_RUN_MS = exports.MAIN_STREAM_RESTART_MAX_MS = exports.MAIN_STREAM_RESTART_BASE_MS = exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE = void 0;
|
|
27
|
+
const child_process_1 = require("child_process");
|
|
28
|
+
const events_1 = require("events");
|
|
29
|
+
const fs = __importStar(require("fs"));
|
|
30
|
+
const os = __importStar(require("os"));
|
|
31
|
+
const path = __importStar(require("path"));
|
|
32
|
+
const RTSPCameraProvider_1 = require("./RTSPCameraProvider");
|
|
33
|
+
const RTSPStreamCameraProvider_1 = require("./RTSPStreamCameraProvider");
|
|
34
|
+
const ffmpegStderr_1 = require("./ffmpegStderr");
|
|
35
|
+
/**
|
|
36
|
+
* MainStreamSession — the camera's MAIN stream, on a session of its own.
|
|
37
|
+
*
|
|
38
|
+
* A connector feed reads each camera's SUBSTREAM (640x480 / 800x448 on the Texas
|
|
39
|
+
* recorder), where a hand is 5-10 px. Whether a model can see theft in the act
|
|
40
|
+
* on full-resolution pixels is a question about the MAIN stream, so this module
|
|
41
|
+
* opens it beside the feed's substream session, on the store PC, as cheaply as
|
|
42
|
+
* a stream can be read: one RTSP session, every output a stream copy.
|
|
43
|
+
*
|
|
44
|
+
* ── ONE SESSION, PLUGGABLE OUTPUTS ────────────────────────────────────────
|
|
45
|
+
*
|
|
46
|
+
* The session owns the process: the input (credentials in a 0600 ffconcat file,
|
|
47
|
+
* never argv), its admission, its stderr, its clock, its restarts. Everything it
|
|
48
|
+
* PRODUCES is an output (`MainStreamOutput`): each contributes its own ffmpeg
|
|
49
|
+
* output arguments to the next session and handles what it writes. The ring
|
|
50
|
+
* recorder is one output (`MainStreamRingOutput`: segments into the feed's local
|
|
51
|
+
* ring). A second output — a decoded face-zone crop for one camera, say — is a
|
|
52
|
+
* second class implementing the same interface, added with `addOutput`; the
|
|
53
|
+
* session restarts once to carry it and the recorder is untouched. At most one
|
|
54
|
+
* output may claim the session's stdout (`pipe:1`).
|
|
55
|
+
*
|
|
56
|
+
* ── NO DECODE, AND THEREFORE NO LOOKS ─────────────────────────────────────
|
|
57
|
+
*
|
|
58
|
+
* The ring output is `-map 0:v -c:v copy` into the segment muxer, exactly the
|
|
59
|
+
* second output the substream session has always used (`buildSegmentOutputArgs`,
|
|
60
|
+
* audio left out): ffmpeg opens no decoder for a stream it only copies, scales
|
|
61
|
+
* nothing and emits no frame. Nothing here is a `CameraProvider`, so no look,
|
|
62
|
+
* detector call or review can read from it: a camera that records its main
|
|
63
|
+
* stream and has no alert route is looked at exactly as before (its substream
|
|
64
|
+
* provider is idle and pulls one health frame a minute).
|
|
65
|
+
*
|
|
66
|
+
* ── BOUNDED AGAINST THE RECORDER ──────────────────────────────────────────
|
|
67
|
+
*
|
|
68
|
+
* Main-stream sessions — the probe and the recorder alike — are admitted from
|
|
69
|
+
* their OWN lane per physical recorder (`captureSourceKey`: host:port), capped
|
|
70
|
+
* at `DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE` (1). The substream lanes
|
|
71
|
+
* (`CaptureAdmission`, the persistent-session lane) are untouched by a probe,
|
|
72
|
+
* which is the shape `RTSPAudioProvider` took for the same reason: a long-lived
|
|
73
|
+
* pull must never take a slot the frame path counts on. A RECORDING session
|
|
74
|
+
* additionally holds a priority-0 ticket in the recorder's persistent-session
|
|
75
|
+
* lane, so a recorder that turns out to be full sheds the main-stream recording
|
|
76
|
+
* before any feed and never before an alert camera (priority 1). The lane never
|
|
77
|
+
* queues: a refused session reports `session_limit` and tries again after the
|
|
78
|
+
* restart delay. Restarts double from `MAIN_STREAM_RESTART_BASE_MS` to
|
|
79
|
+
* `MAIN_STREAM_RESTART_MAX_MS` (one an hour on a fault that persists); a session
|
|
80
|
+
* that ran `MAIN_STREAM_HEALTHY_RUN_MS` resets the delay.
|
|
81
|
+
*
|
|
82
|
+
* ── THE CLOCK ─────────────────────────────────────────────────────────────
|
|
83
|
+
*
|
|
84
|
+
* The substream session dates its segments from its first DECODED frame. This
|
|
85
|
+
* session decodes nothing, so it reads ffmpeg's `-progress` instead: every half
|
|
86
|
+
* second ffmpeg reports how far into the output it is (`out_time_us`), and
|
|
87
|
+
* `wall clock - out_time` is when output time 0 happened. The smallest value
|
|
88
|
+
* over the last minute (`MAIN_STREAM_CLOCK_WINDOW_MS`) is the least-delayed
|
|
89
|
+
* report, and following it lets the anchor track a camera clock that drifts
|
|
90
|
+
* against the PC's over a session that runs for days.
|
|
91
|
+
*/
|
|
92
|
+
// ---------------------------------------------------------------------------
|
|
93
|
+
// Constants
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
/** Main-stream sessions (probe or recorder) one connector holds per recorder host:port. */
|
|
96
|
+
exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE = 1;
|
|
97
|
+
/** First restart delay after a session ends; doubles to the max. */
|
|
98
|
+
exports.MAIN_STREAM_RESTART_BASE_MS = 10000;
|
|
99
|
+
/** Ceiling on the restart delay: at most one retry an hour against a fault that persists. */
|
|
100
|
+
exports.MAIN_STREAM_RESTART_MAX_MS = 3600000;
|
|
101
|
+
/** A session that ran this long, with output flowing, resets the restart delay. */
|
|
102
|
+
exports.MAIN_STREAM_HEALTHY_RUN_MS = 60000;
|
|
103
|
+
/** A session whose output has not started this long after spawn is killed (and counted). */
|
|
104
|
+
exports.MAIN_STREAM_STARTUP_TIMEOUT_MS = 30000;
|
|
105
|
+
/** The window the clock's minimum is taken over. */
|
|
106
|
+
exports.MAIN_STREAM_CLOCK_WINDOW_MS = 60000;
|
|
107
|
+
/** Session work directories of the main-stream recorder: never the substream's `rec-`. */
|
|
108
|
+
exports.MAIN_STREAM_WORKDIR_PREFIX = 'main-';
|
|
109
|
+
/** How often the session ticks its outputs (the ring output reads its segment list). */
|
|
110
|
+
const TICK_MS = 1000;
|
|
111
|
+
const DEFAULT_TIMEOUT_US = 10000000;
|
|
112
|
+
/** A segment cannot end after it was observed closed. */
|
|
113
|
+
const CLOSE_FUTURE_TOLERANCE_MS = 1000;
|
|
114
|
+
/** ffmpeg's -progress keys: kept out of the stderr buffer so the last error stays readable. */
|
|
115
|
+
const PROGRESS_LINE_RE = /^[a-z0-9_]+=/;
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
// Admission: the main-stream lane, one per recorder
|
|
118
|
+
// ---------------------------------------------------------------------------
|
|
119
|
+
class MainStreamLane {
|
|
120
|
+
constructor(limit) {
|
|
121
|
+
this.active = 0;
|
|
122
|
+
this.limit = limit;
|
|
123
|
+
}
|
|
124
|
+
tightenLimit(limit) {
|
|
125
|
+
this.limit = Math.min(this.limit, limit);
|
|
126
|
+
}
|
|
127
|
+
getActive() {
|
|
128
|
+
return this.active;
|
|
129
|
+
}
|
|
130
|
+
getLimit() {
|
|
131
|
+
return this.limit;
|
|
132
|
+
}
|
|
133
|
+
tryAcquire() {
|
|
134
|
+
if (this.active >= this.limit)
|
|
135
|
+
return null;
|
|
136
|
+
this.active += 1;
|
|
137
|
+
let released = false;
|
|
138
|
+
return () => {
|
|
139
|
+
if (released)
|
|
140
|
+
return;
|
|
141
|
+
released = true;
|
|
142
|
+
this.active = Math.max(0, this.active - 1);
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const mainLaneBySource = new Map();
|
|
147
|
+
/**
|
|
148
|
+
* One main-stream session slot on the recorder this URL names, or null when the
|
|
149
|
+
* connector already holds as many as `limit` there (or the URL names no
|
|
150
|
+
* recorder). Never queues. Release it exactly once.
|
|
151
|
+
*/
|
|
152
|
+
function acquireMainStreamSlot(streamUrl, limit = exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE) {
|
|
153
|
+
const key = (0, RTSPCameraProvider_1.captureSourceKey)(streamUrl);
|
|
154
|
+
if (!key)
|
|
155
|
+
return null;
|
|
156
|
+
const bounded = Math.max(1, Math.trunc(limit));
|
|
157
|
+
let lane = mainLaneBySource.get(key);
|
|
158
|
+
if (!lane) {
|
|
159
|
+
lane = new MainStreamLane(bounded);
|
|
160
|
+
mainLaneBySource.set(key, lane);
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
lane.tightenLimit(bounded);
|
|
164
|
+
}
|
|
165
|
+
return lane.tryAcquire();
|
|
166
|
+
}
|
|
167
|
+
exports.acquireMainStreamSlot = acquireMainStreamSlot;
|
|
168
|
+
/** Live main-stream occupancy for a recorder, for diagnostics. */
|
|
169
|
+
function mainStreamSessionStatsFor(streamUrl) {
|
|
170
|
+
const key = (0, RTSPCameraProvider_1.captureSourceKey)(streamUrl);
|
|
171
|
+
if (!key)
|
|
172
|
+
return null;
|
|
173
|
+
const lane = mainLaneBySource.get(key);
|
|
174
|
+
return lane ? { key, active: lane.getActive(), limit: lane.getLimit() } : null;
|
|
175
|
+
}
|
|
176
|
+
exports.mainStreamSessionStatsFor = mainStreamSessionStatsFor;
|
|
177
|
+
/** Test seam: forget every recorder's main-stream lane. */
|
|
178
|
+
function __resetMainStreamAdmissionForTests() {
|
|
179
|
+
mainLaneBySource.clear();
|
|
180
|
+
}
|
|
181
|
+
exports.__resetMainStreamAdmissionForTests = __resetMainStreamAdmissionForTests;
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
// The input, with the URL kept out of argv
|
|
184
|
+
// ---------------------------------------------------------------------------
|
|
185
|
+
/**
|
|
186
|
+
* ffmpeg input args for an RTSP URL: the URL goes into a 0600 ffconcat file and
|
|
187
|
+
* only the file's path reaches argv, exactly as every provider in this package
|
|
188
|
+
* does, so a password (an XMEye path carries one) never appears in `ps` output.
|
|
189
|
+
*/
|
|
190
|
+
function buildMainStreamInputArgs(o) {
|
|
191
|
+
if (!/^rtsps?:\/\//i.test(o.rtspUrl))
|
|
192
|
+
return { args: ['-i', o.rtspUrl], cleanup: () => undefined };
|
|
193
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trillboards-rtsp-main-'));
|
|
194
|
+
const file = path.join(dir, 'input.ffconcat');
|
|
195
|
+
fs.writeFileSync(file, [
|
|
196
|
+
'ffconcat version 1.0',
|
|
197
|
+
`file '${(0, RTSPCameraProvider_1.escapeFfconcatValue)(o.rtspUrl)}'`,
|
|
198
|
+
`option rtsp_transport ${o.transport}`,
|
|
199
|
+
`option ${o.ffmpegMajorVersion >= 5 ? 'timeout' : 'stimeout'} ${Math.trunc(o.timeoutUs)}`,
|
|
200
|
+
'',
|
|
201
|
+
].join('\n'), { mode: 0o600 });
|
|
202
|
+
try {
|
|
203
|
+
fs.chmodSync(file, 0o600);
|
|
204
|
+
}
|
|
205
|
+
catch {
|
|
206
|
+
/* best-effort on platforms with ACL semantics */
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
args: ['-protocol_whitelist', 'file,crypto,tcp,tls,rtp,rtsp,udp,http,https', '-safe', '0', '-f', 'concat', '-i', file],
|
|
210
|
+
cleanup: () => {
|
|
211
|
+
try {
|
|
212
|
+
fs.unlinkSync(file);
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
/* already gone */
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
fs.rmdirSync(dir);
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
/* best-effort */
|
|
222
|
+
}
|
|
223
|
+
},
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
exports.buildMainStreamInputArgs = buildMainStreamInputArgs;
|
|
227
|
+
/**
|
|
228
|
+
* One long-lived ffmpeg on a camera's main stream, carrying every output that
|
|
229
|
+
* wants it. Events: `'state'` (MainStreamSessionState) on every change and
|
|
230
|
+
* `'session_end'` (MainStreamSessionEnd) when a session ends.
|
|
231
|
+
*/
|
|
232
|
+
class MainStreamSession extends events_1.EventEmitter {
|
|
233
|
+
constructor(config) {
|
|
234
|
+
super();
|
|
235
|
+
this.outputs = new Map();
|
|
236
|
+
this.wanted = false;
|
|
237
|
+
this.state = 'idle';
|
|
238
|
+
this.live = null;
|
|
239
|
+
this.sessions = 0;
|
|
240
|
+
this.restarts = 0;
|
|
241
|
+
this.retryTimer = null;
|
|
242
|
+
this.retryAtMs = null;
|
|
243
|
+
this.tickTimer = null;
|
|
244
|
+
this.startupTimer = null;
|
|
245
|
+
this.releaseSlot = null;
|
|
246
|
+
this.laneTicket = null;
|
|
247
|
+
this.input = null;
|
|
248
|
+
/** (wall ms - out_time ms) per progress report over the clock window. */
|
|
249
|
+
this.clockSamples = [];
|
|
250
|
+
this.mediaZeroWallMs = null;
|
|
251
|
+
this.lastEnd = null;
|
|
252
|
+
if (!config?.rtspUrl)
|
|
253
|
+
throw new Error('rtspUrl is required for MainStreamSession');
|
|
254
|
+
this.rtspUrl = config.rtspUrl;
|
|
255
|
+
this.transport = config.transport ?? 'tcp';
|
|
256
|
+
this.timeoutUs = config.timeoutUs ?? DEFAULT_TIMEOUT_US;
|
|
257
|
+
this.ffmpegPath = config.ffmpegPath ?? 'ffmpeg';
|
|
258
|
+
this.ffmpegMajorVersion = config.ffmpegMajorVersion ?? 6;
|
|
259
|
+
this.maxSessionsPerSource = Math.max(1, Math.trunc(config.maxSessionsPerSource ?? exports.DEFAULT_MAX_MAIN_STREAM_SESSIONS_PER_SOURCE));
|
|
260
|
+
this.sharePersistentLane = config.sharePersistentLane !== false;
|
|
261
|
+
this.restartDelayMs = Math.max(0, config.restartDelayMs ?? exports.MAIN_STREAM_RESTART_BASE_MS);
|
|
262
|
+
this.maxRestartDelayMs = Math.max(this.restartDelayMs, config.maxRestartDelayMs ?? exports.MAIN_STREAM_RESTART_MAX_MS);
|
|
263
|
+
this.healthyRunMs = Math.max(0, config.healthyRunMs ?? exports.MAIN_STREAM_HEALTHY_RUN_MS);
|
|
264
|
+
this.startupTimeoutMs = Math.max(1, config.startupTimeoutMs ?? exports.MAIN_STREAM_STARTUP_TIMEOUT_MS);
|
|
265
|
+
this.spawnFn = config.spawnFn ?? child_process_1.spawn;
|
|
266
|
+
this.now = config.now ?? Date.now;
|
|
267
|
+
this.onLog = config.onLog;
|
|
268
|
+
this.currentDelayMs = this.restartDelayMs;
|
|
269
|
+
}
|
|
270
|
+
/** Add (or replace, by name) an output. A running session restarts once to carry it. */
|
|
271
|
+
addOutput(output) {
|
|
272
|
+
if (!output || typeof output.name !== 'string' || !output.name)
|
|
273
|
+
throw new Error('an output needs a name');
|
|
274
|
+
this.outputs.set(output.name, output);
|
|
275
|
+
this.refresh();
|
|
276
|
+
}
|
|
277
|
+
removeOutput(name) {
|
|
278
|
+
if (!this.outputs.delete(name))
|
|
279
|
+
return;
|
|
280
|
+
this.refresh();
|
|
281
|
+
}
|
|
282
|
+
/** Want a session from now on. Idempotent. */
|
|
283
|
+
start() {
|
|
284
|
+
if (this.state === 'stopped')
|
|
285
|
+
return;
|
|
286
|
+
this.wanted = true;
|
|
287
|
+
this.ensureSession();
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Re-read every output's arguments. A running session whose argv no longer
|
|
291
|
+
* matches restarts once (its replacement starts as it exits); one that no
|
|
292
|
+
* output wants stops and gives its slots back.
|
|
293
|
+
*/
|
|
294
|
+
refresh() {
|
|
295
|
+
if (this.state === 'stopped')
|
|
296
|
+
return;
|
|
297
|
+
const live = this.live;
|
|
298
|
+
if (!live) {
|
|
299
|
+
this.ensureSession();
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (live.superseded || live.stopped)
|
|
303
|
+
return;
|
|
304
|
+
const plan = this.plan();
|
|
305
|
+
if (plan && plan.key === live.planKey)
|
|
306
|
+
return;
|
|
307
|
+
live.superseded = true;
|
|
308
|
+
this.killLive(live);
|
|
309
|
+
}
|
|
310
|
+
/** Stop for good: kill the session and release every slot. */
|
|
311
|
+
async stop() {
|
|
312
|
+
this.wanted = false;
|
|
313
|
+
this.clearRetry();
|
|
314
|
+
const live = this.live;
|
|
315
|
+
this.setState('stopped');
|
|
316
|
+
if (live && !live.ended) {
|
|
317
|
+
live.stopped = true;
|
|
318
|
+
await new Promise((resolve) => {
|
|
319
|
+
const done = () => resolve();
|
|
320
|
+
live.proc.once('close', done);
|
|
321
|
+
this.killLive(live);
|
|
322
|
+
const t = setTimeout(done, 4000);
|
|
323
|
+
if (typeof t.unref === 'function')
|
|
324
|
+
t.unref();
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
this.releaseSlots();
|
|
328
|
+
}
|
|
329
|
+
getStats() {
|
|
330
|
+
return {
|
|
331
|
+
state: this.state,
|
|
332
|
+
sessions: this.sessions,
|
|
333
|
+
restarts: this.restarts,
|
|
334
|
+
input: this.input,
|
|
335
|
+
mediaZeroWallMs: this.mediaZeroWallMs,
|
|
336
|
+
outputs: [...this.outputs.keys()],
|
|
337
|
+
nextRetryAtMs: this.retryAtMs,
|
|
338
|
+
lastEnd: this.lastEnd,
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
getState() {
|
|
342
|
+
return this.state;
|
|
343
|
+
}
|
|
344
|
+
// ── internals ────────────────────────────────────────────────────────────
|
|
345
|
+
context(id) {
|
|
346
|
+
return {
|
|
347
|
+
session: id,
|
|
348
|
+
input: this.input,
|
|
349
|
+
mediaZeroWallMs: this.mediaZeroWallMs,
|
|
350
|
+
ffmpegMajorVersion: this.ffmpegMajorVersion,
|
|
351
|
+
now: () => this.now(),
|
|
352
|
+
log: (level, message) => this.log(level, message),
|
|
353
|
+
refresh: () => {
|
|
354
|
+
// Deferred: an output may ask from inside its own callback.
|
|
355
|
+
setImmediate(() => this.refresh());
|
|
356
|
+
},
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
/** The outputs that want the next session, in add order, and their joined plan key; null when none does. */
|
|
360
|
+
plan() {
|
|
361
|
+
const ctx = this.context(this.sessions + 1);
|
|
362
|
+
const keys = [];
|
|
363
|
+
const outputs = [];
|
|
364
|
+
let stdoutClaimed = false;
|
|
365
|
+
for (const output of this.outputs.values()) {
|
|
366
|
+
let key = null;
|
|
367
|
+
try {
|
|
368
|
+
key = output.plan(ctx);
|
|
369
|
+
}
|
|
370
|
+
catch (err) {
|
|
371
|
+
this.log('warn', `main stream output ${output.name} could not plan: ${errorText(err)}`);
|
|
372
|
+
key = null;
|
|
373
|
+
}
|
|
374
|
+
if (key === null)
|
|
375
|
+
continue;
|
|
376
|
+
if (output.writesStdout) {
|
|
377
|
+
if (stdoutClaimed) {
|
|
378
|
+
this.log('warn', `main stream output ${output.name} also writes to stdout; left out of this session`);
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
stdoutClaimed = true;
|
|
382
|
+
}
|
|
383
|
+
keys.push(`${output.name}:${key}`);
|
|
384
|
+
outputs.push(output);
|
|
385
|
+
}
|
|
386
|
+
return outputs.length ? { key: keys.join('|'), outputs } : null;
|
|
387
|
+
}
|
|
388
|
+
ensureSession() {
|
|
389
|
+
if (!this.wanted || this.live || this.retryTimer || this.state === 'stopped')
|
|
390
|
+
return;
|
|
391
|
+
const plan = this.plan();
|
|
392
|
+
if (!plan) {
|
|
393
|
+
this.releaseSlots();
|
|
394
|
+
this.setState('idle');
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (!this.releaseSlot) {
|
|
398
|
+
this.releaseSlot = acquireMainStreamSlot(this.rtspUrl, this.maxSessionsPerSource);
|
|
399
|
+
if (!this.releaseSlot) {
|
|
400
|
+
this.refused('this connector already holds the recorder\'s main-stream session');
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
if (this.sharePersistentLane && !this.laneTicket) {
|
|
405
|
+
this.laneTicket = (0, RTSPStreamCameraProvider_1.acquirePersistentSessionSlot)(this.rtspUrl, () => this.shed(), 0);
|
|
406
|
+
if (!this.laneTicket && (0, RTSPCameraProvider_1.captureSourceKey)(this.rtspUrl) !== null) {
|
|
407
|
+
this.releaseSlots();
|
|
408
|
+
this.refused('the recorder\'s persistent-session lane is full');
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
this.spawnSession(plan.key, plan.outputs);
|
|
413
|
+
}
|
|
414
|
+
spawnSession(planKey, planned) {
|
|
415
|
+
const ctx = this.context(this.sessions + 1);
|
|
416
|
+
const outputArgs = [];
|
|
417
|
+
const outputs = [];
|
|
418
|
+
for (const output of planned) {
|
|
419
|
+
let args = null;
|
|
420
|
+
try {
|
|
421
|
+
args = output.outputArgs(ctx);
|
|
422
|
+
}
|
|
423
|
+
catch (err) {
|
|
424
|
+
this.log('warn', `main stream output ${output.name} could not prepare its arguments: ${errorText(err)}`);
|
|
425
|
+
}
|
|
426
|
+
if (!args || args.length === 0)
|
|
427
|
+
continue;
|
|
428
|
+
outputArgs.push(...args);
|
|
429
|
+
outputs.push(output);
|
|
430
|
+
}
|
|
431
|
+
if (!outputs.length) {
|
|
432
|
+
this.releaseSlots();
|
|
433
|
+
this.scheduleRetry('no main stream output could prepare its arguments');
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
let input;
|
|
437
|
+
try {
|
|
438
|
+
input = buildMainStreamInputArgs({
|
|
439
|
+
rtspUrl: this.rtspUrl, transport: this.transport, timeoutUs: this.timeoutUs, ffmpegMajorVersion: this.ffmpegMajorVersion,
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
catch (err) {
|
|
443
|
+
this.scheduleRetry(`main stream input file could not be written: ${errorText(err)}`);
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
const args = [
|
|
447
|
+
'-hide_banner', '-nostdin', '-nostats', '-loglevel', 'info',
|
|
448
|
+
// Progress on stderr every half second: the session's only clock (see the header).
|
|
449
|
+
'-progress', 'pipe:2',
|
|
450
|
+
// Before the input, so it binds to a decoder, should an output ever ask for one.
|
|
451
|
+
'-threads', '1',
|
|
452
|
+
...input.args,
|
|
453
|
+
...outputArgs,
|
|
454
|
+
];
|
|
455
|
+
const wantsStdout = outputs.some((output) => output.writesStdout === true);
|
|
456
|
+
let proc;
|
|
457
|
+
try {
|
|
458
|
+
proc = this.spawnFn(this.ffmpegPath, args, { stdio: ['ignore', wantsStdout ? 'pipe' : 'ignore', 'pipe'], windowsHide: true });
|
|
459
|
+
}
|
|
460
|
+
catch (err) {
|
|
461
|
+
input.cleanup();
|
|
462
|
+
this.scheduleRetry(`main stream ffmpeg could not start: ${errorText(err)}`);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
this.sessions += 1;
|
|
466
|
+
const live = {
|
|
467
|
+
id: this.sessions,
|
|
468
|
+
proc,
|
|
469
|
+
planKey,
|
|
470
|
+
outputs,
|
|
471
|
+
startedAtMs: this.now(),
|
|
472
|
+
probe: new RTSPStreamCameraProvider_1.InputStreamProbe(),
|
|
473
|
+
progressed: false,
|
|
474
|
+
stopped: false,
|
|
475
|
+
superseded: false,
|
|
476
|
+
ended: false,
|
|
477
|
+
cleanupInput: input.cleanup,
|
|
478
|
+
stderr: new ffmpegStderr_1.BoundedSessionStderr(),
|
|
479
|
+
progressPartial: '',
|
|
480
|
+
lastOutTimeUs: 0,
|
|
481
|
+
};
|
|
482
|
+
this.live = live;
|
|
483
|
+
this.clockSamples = [];
|
|
484
|
+
this.mediaZeroWallMs = null;
|
|
485
|
+
this.setState('starting');
|
|
486
|
+
this.startupTimer = setTimeout(() => {
|
|
487
|
+
this.startupTimer = null;
|
|
488
|
+
if (this.live !== live || live.progressed)
|
|
489
|
+
return;
|
|
490
|
+
this.log('warn', `main stream session produced no output ${Math.round(this.startupTimeoutMs / 1000)}s after it started`);
|
|
491
|
+
this.killLive(live);
|
|
492
|
+
}, this.startupTimeoutMs);
|
|
493
|
+
if (typeof this.startupTimer.unref === 'function')
|
|
494
|
+
this.startupTimer.unref();
|
|
495
|
+
this.tickTimer = setInterval(() => this.tick(live), TICK_MS);
|
|
496
|
+
if (typeof this.tickTimer.unref === 'function')
|
|
497
|
+
this.tickTimer.unref();
|
|
498
|
+
if (wantsStdout) {
|
|
499
|
+
proc.stdout?.on('data', (chunk) => {
|
|
500
|
+
if (this.live !== live)
|
|
501
|
+
return;
|
|
502
|
+
for (const output of live.outputs) {
|
|
503
|
+
if (output.onStdout) {
|
|
504
|
+
try {
|
|
505
|
+
output.onStdout(chunk);
|
|
506
|
+
}
|
|
507
|
+
catch (err) {
|
|
508
|
+
this.log('warn', `main stream output ${output.name} stdout handler threw: ${errorText(err)}`);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
}
|
|
514
|
+
proc.stderr?.on('data', (chunk) => this.onStderr(live, chunk.toString()));
|
|
515
|
+
proc.on('error', (err) => {
|
|
516
|
+
live.stderr.append(`\n${err.message}\n`);
|
|
517
|
+
this.onEnd(live, null);
|
|
518
|
+
});
|
|
519
|
+
proc.on('close', (code) => this.onEnd(live, code));
|
|
520
|
+
}
|
|
521
|
+
onStderr(live, text) {
|
|
522
|
+
const lines = (live.progressPartial + text).split(/\r\n|\r|\n/);
|
|
523
|
+
live.progressPartial = lines.pop() ?? '';
|
|
524
|
+
if (live.progressPartial.length > 4096)
|
|
525
|
+
live.progressPartial = live.progressPartial.slice(-4096);
|
|
526
|
+
const kept = [];
|
|
527
|
+
for (const line of lines) {
|
|
528
|
+
if (!PROGRESS_LINE_RE.test(line)) {
|
|
529
|
+
kept.push(line);
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
const eq = line.indexOf('=');
|
|
533
|
+
const key = line.slice(0, eq);
|
|
534
|
+
const value = line.slice(eq + 1).trim();
|
|
535
|
+
if (key === 'out_time_us') {
|
|
536
|
+
const us = Number(value);
|
|
537
|
+
if (Number.isFinite(us))
|
|
538
|
+
live.lastOutTimeUs = us;
|
|
539
|
+
}
|
|
540
|
+
else if (key === 'progress') {
|
|
541
|
+
this.onProgress(live);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
if (kept.length) {
|
|
545
|
+
const block = kept.join('\n') + '\n';
|
|
546
|
+
live.stderr.append(block);
|
|
547
|
+
if (!live.probe.done) {
|
|
548
|
+
const info = live.probe.push(block);
|
|
549
|
+
if (info && this.live === live) {
|
|
550
|
+
this.input = info;
|
|
551
|
+
for (const output of live.outputs) {
|
|
552
|
+
try {
|
|
553
|
+
output.onInput?.(this.context(live.id));
|
|
554
|
+
}
|
|
555
|
+
catch (err) {
|
|
556
|
+
this.log('warn', `main stream output ${output.name} input handler threw: ${errorText(err)}`);
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
/** One -progress report: advance the clock and mark the stream as delivering. */
|
|
564
|
+
onProgress(live) {
|
|
565
|
+
if (this.live !== live || live.lastOutTimeUs <= 0)
|
|
566
|
+
return;
|
|
567
|
+
const nowMs = this.now();
|
|
568
|
+
if (!live.progressed) {
|
|
569
|
+
live.progressed = true;
|
|
570
|
+
if (this.startupTimer) {
|
|
571
|
+
clearTimeout(this.startupTimer);
|
|
572
|
+
this.startupTimer = null;
|
|
573
|
+
}
|
|
574
|
+
this.setState('running');
|
|
575
|
+
}
|
|
576
|
+
this.clockSamples.push({ atMs: nowMs, zeroMs: nowMs - live.lastOutTimeUs / 1000 });
|
|
577
|
+
const horizon = nowMs - exports.MAIN_STREAM_CLOCK_WINDOW_MS;
|
|
578
|
+
while (this.clockSamples.length > 1 && this.clockSamples[0].atMs < horizon)
|
|
579
|
+
this.clockSamples.shift();
|
|
580
|
+
let best = Infinity;
|
|
581
|
+
for (const sample of this.clockSamples)
|
|
582
|
+
best = Math.min(best, sample.zeroMs);
|
|
583
|
+
this.mediaZeroWallMs = Math.round(best);
|
|
584
|
+
}
|
|
585
|
+
tick(live) {
|
|
586
|
+
if (this.live !== live)
|
|
587
|
+
return;
|
|
588
|
+
const ctx = this.context(live.id);
|
|
589
|
+
for (const output of live.outputs) {
|
|
590
|
+
try {
|
|
591
|
+
output.onTick?.(ctx);
|
|
592
|
+
}
|
|
593
|
+
catch (err) {
|
|
594
|
+
this.log('warn', `main stream output ${output.name} tick threw: ${errorText(err)}`);
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
onEnd(live, code) {
|
|
599
|
+
if (live.ended)
|
|
600
|
+
return;
|
|
601
|
+
live.ended = true;
|
|
602
|
+
if (live.progressPartial && !PROGRESS_LINE_RE.test(live.progressPartial))
|
|
603
|
+
live.stderr.append(live.progressPartial);
|
|
604
|
+
live.progressPartial = '';
|
|
605
|
+
try {
|
|
606
|
+
live.cleanupInput();
|
|
607
|
+
}
|
|
608
|
+
catch {
|
|
609
|
+
/* best-effort */
|
|
610
|
+
}
|
|
611
|
+
const current = this.live === live;
|
|
612
|
+
if (current) {
|
|
613
|
+
this.live = null;
|
|
614
|
+
if (this.tickTimer)
|
|
615
|
+
clearInterval(this.tickTimer);
|
|
616
|
+
this.tickTimer = null;
|
|
617
|
+
if (this.startupTimer)
|
|
618
|
+
clearTimeout(this.startupTimer);
|
|
619
|
+
this.startupTimer = null;
|
|
620
|
+
}
|
|
621
|
+
const ranMs = Math.max(0, this.now() - live.startedAtMs);
|
|
622
|
+
const stopped = live.stopped || live.superseded;
|
|
623
|
+
const stderr = (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(live.stderr.text());
|
|
624
|
+
const end = { exitCode: code, ranMs, progressed: live.progressed, stopped, stderr };
|
|
625
|
+
const ctx = this.context(live.id);
|
|
626
|
+
for (const output of live.outputs) {
|
|
627
|
+
try {
|
|
628
|
+
output.onSessionEnd?.(ctx, end);
|
|
629
|
+
}
|
|
630
|
+
catch (err) {
|
|
631
|
+
this.log('warn', `main stream output ${output.name} end handler threw: ${errorText(err)}`);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
this.lastEnd = { exitCode: code, ranMs, progressed: live.progressed, stopped, atMs: this.now(),
|
|
635
|
+
summary: (0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr, 300) };
|
|
636
|
+
try {
|
|
637
|
+
this.emit('session_end', end);
|
|
638
|
+
}
|
|
639
|
+
catch (err) {
|
|
640
|
+
this.log('warn', `a main stream 'session_end' listener threw: ${errorText(err)}`);
|
|
641
|
+
}
|
|
642
|
+
if (!current || this.state === 'stopped')
|
|
643
|
+
return;
|
|
644
|
+
if (live.superseded) {
|
|
645
|
+
// A reconfigure: the replacement starts now, with the slots it already holds.
|
|
646
|
+
this.ensureSession();
|
|
647
|
+
return;
|
|
648
|
+
}
|
|
649
|
+
if (live.stopped)
|
|
650
|
+
return; // a shed: its handler scheduled the retry
|
|
651
|
+
if (live.progressed && ranMs >= this.healthyRunMs)
|
|
652
|
+
this.currentDelayMs = this.restartDelayMs;
|
|
653
|
+
this.releaseSlots();
|
|
654
|
+
this.scheduleRetry(`main stream session ended (exit ${code}) after ${Math.round(ranMs / 1000)}s: ${(0, RTSPCameraProvider_1.summarizeFfmpegStderr)(stderr, 200)}`);
|
|
655
|
+
}
|
|
656
|
+
shed() {
|
|
657
|
+
// Called by the persistent-session lane while it reconciles: no await, no throw.
|
|
658
|
+
this.laneTicket = null;
|
|
659
|
+
const live = this.live;
|
|
660
|
+
if (live && !live.ended) {
|
|
661
|
+
live.stopped = true;
|
|
662
|
+
this.killLive(live);
|
|
663
|
+
}
|
|
664
|
+
this.releaseSlots();
|
|
665
|
+
this.refused('the recorder\'s persistent-session lane shed the main stream to make room for a feed');
|
|
666
|
+
}
|
|
667
|
+
refused(reason) {
|
|
668
|
+
this.log('warn', `main stream not started: ${reason}`);
|
|
669
|
+
this.scheduleRetry(null, 'session_limit');
|
|
670
|
+
}
|
|
671
|
+
scheduleRetry(reason, state = 'backoff') {
|
|
672
|
+
if (!this.wanted || this.state === 'stopped')
|
|
673
|
+
return;
|
|
674
|
+
if (reason)
|
|
675
|
+
this.log('warn', `${reason}; retrying in ${Math.round(this.currentDelayMs / 1000)}s`);
|
|
676
|
+
const delay = this.currentDelayMs;
|
|
677
|
+
this.currentDelayMs = Math.min(this.maxRestartDelayMs, Math.max(1, this.currentDelayMs * 2));
|
|
678
|
+
this.restarts += 1;
|
|
679
|
+
this.clearRetry();
|
|
680
|
+
this.retryAtMs = this.now() + delay;
|
|
681
|
+
this.retryTimer = setTimeout(() => {
|
|
682
|
+
this.retryTimer = null;
|
|
683
|
+
this.retryAtMs = null;
|
|
684
|
+
this.ensureSession();
|
|
685
|
+
}, delay);
|
|
686
|
+
if (typeof this.retryTimer.unref === 'function')
|
|
687
|
+
this.retryTimer.unref();
|
|
688
|
+
this.setState(state);
|
|
689
|
+
}
|
|
690
|
+
clearRetry() {
|
|
691
|
+
if (this.retryTimer)
|
|
692
|
+
clearTimeout(this.retryTimer);
|
|
693
|
+
this.retryTimer = null;
|
|
694
|
+
this.retryAtMs = null;
|
|
695
|
+
}
|
|
696
|
+
killLive(live) {
|
|
697
|
+
try {
|
|
698
|
+
live.proc.kill('SIGTERM');
|
|
699
|
+
}
|
|
700
|
+
catch {
|
|
701
|
+
/* already gone */
|
|
702
|
+
}
|
|
703
|
+
// Bounded escalation, as every session in this package does: an ffmpeg
|
|
704
|
+
// wedged on a half-open socket ignores SIGTERM.
|
|
705
|
+
const t = setTimeout(() => {
|
|
706
|
+
try {
|
|
707
|
+
live.proc.kill('SIGKILL');
|
|
708
|
+
}
|
|
709
|
+
catch {
|
|
710
|
+
/* already gone */
|
|
711
|
+
}
|
|
712
|
+
}, 2000);
|
|
713
|
+
if (typeof t.unref === 'function')
|
|
714
|
+
t.unref();
|
|
715
|
+
}
|
|
716
|
+
releaseSlots() {
|
|
717
|
+
if (this.releaseSlot) {
|
|
718
|
+
this.releaseSlot();
|
|
719
|
+
this.releaseSlot = null;
|
|
720
|
+
}
|
|
721
|
+
if (this.laneTicket) {
|
|
722
|
+
const ticket = this.laneTicket;
|
|
723
|
+
this.laneTicket = null;
|
|
724
|
+
ticket.release();
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
setState(next) {
|
|
728
|
+
if (next === this.state)
|
|
729
|
+
return;
|
|
730
|
+
this.state = next;
|
|
731
|
+
try {
|
|
732
|
+
this.emit('state', next);
|
|
733
|
+
}
|
|
734
|
+
catch (err) {
|
|
735
|
+
this.log('warn', `a main stream 'state' listener threw: ${errorText(err)}`);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
log(level, message) {
|
|
739
|
+
this.onLog?.(level, (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(message));
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
exports.MainStreamSession = MainStreamSession;
|
|
743
|
+
function errorText(err) {
|
|
744
|
+
return err instanceof Error ? err.message : String(err);
|
|
745
|
+
}
|
|
746
|
+
/** Segments named `seg_000000.mp4` by `segmentPatternFor`. */
|
|
747
|
+
const SEGMENT_FILE_RE = /^seg_\d+\.mp4$/i;
|
|
748
|
+
/**
|
|
749
|
+
* The main-stream RECORDER: a stream copy of the main stream's video into the
|
|
750
|
+
* segment muxer, every closed segment handed to the feed's ring (`sink`), where
|
|
751
|
+
* the alert-window cut, the uploader and the buffer report find it exactly as
|
|
752
|
+
* they find a substream segment. Same file shape (`buildSegmentOutputArgs`,
|
|
753
|
+
* video only), same sidecar and name (the sink writes them), the work
|
|
754
|
+
* directories prefixed `main-` so the substream session's recovery never reads
|
|
755
|
+
* a live one. Leftovers of an earlier process are handed to the sink once,
|
|
756
|
+
* before this output's first session.
|
|
757
|
+
*/
|
|
758
|
+
class MainStreamRingOutput {
|
|
759
|
+
constructor(options) {
|
|
760
|
+
this.name = 'ring';
|
|
761
|
+
this.config = null;
|
|
762
|
+
this.work = null;
|
|
763
|
+
this.recoveredFor = null;
|
|
764
|
+
this.unsupportedCodec = null;
|
|
765
|
+
this.counters = {
|
|
766
|
+
closed: 0,
|
|
767
|
+
recovered: 0,
|
|
768
|
+
seconds: 0,
|
|
769
|
+
bytes: 0,
|
|
770
|
+
partialsDeleted: 0,
|
|
771
|
+
lastSegmentAtMs: null,
|
|
772
|
+
lastError: null,
|
|
773
|
+
};
|
|
774
|
+
this.sink = options.sink;
|
|
775
|
+
this.now = options.now ?? Date.now;
|
|
776
|
+
}
|
|
777
|
+
/** Change what to record; the session's `refresh` restarts it once when the arguments change. */
|
|
778
|
+
setRecording(next) {
|
|
779
|
+
this.config = next && typeof next.dir === 'string' && next.dir
|
|
780
|
+
? { ...next, segmentSeconds: Math.max(1, Math.trunc(Number(next.segmentSeconds) || 10)) }
|
|
781
|
+
: null;
|
|
782
|
+
}
|
|
783
|
+
getConfig() {
|
|
784
|
+
return this.config ? { ...this.config } : null;
|
|
785
|
+
}
|
|
786
|
+
getStats() {
|
|
787
|
+
const c = this.counters;
|
|
788
|
+
let state = 'off';
|
|
789
|
+
if (this.config?.enabled)
|
|
790
|
+
state = this.unsupportedCodec ? 'unsupported_codec' : this.work && this.work.closed > 0 ? 'recording' : 'waiting';
|
|
791
|
+
return {
|
|
792
|
+
state,
|
|
793
|
+
segmentsClosed: c.closed,
|
|
794
|
+
segmentsRecovered: c.recovered,
|
|
795
|
+
secondsClosed: Math.round(c.seconds * 1000) / 1000,
|
|
796
|
+
bytesClosed: c.bytes,
|
|
797
|
+
measuredBytesPerSec: c.seconds > 0 ? Math.round(c.bytes / c.seconds) : null,
|
|
798
|
+
partialsDeleted: c.partialsDeleted,
|
|
799
|
+
lastSegmentAtMs: c.lastSegmentAtMs,
|
|
800
|
+
lastError: c.lastError,
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
plan(ctx) {
|
|
804
|
+
const cfg = this.config;
|
|
805
|
+
if (!cfg || !cfg.enabled)
|
|
806
|
+
return null;
|
|
807
|
+
const codec = ctx.input?.codec ?? cfg.codec ?? null;
|
|
808
|
+
if (codec !== null && !RTSPStreamCameraProvider_1.RECORDABLE_CODECS.includes(codec))
|
|
809
|
+
return null;
|
|
810
|
+
// The tag follows the probe's codec only: on H.264 a speculative hvc1 tag is
|
|
811
|
+
// a no-op (the segment comes out avc1), so the input's description never
|
|
812
|
+
// costs a restart to drop it.
|
|
813
|
+
return JSON.stringify([cfg.dir, cfg.segmentSeconds, cfg.label, cfg.codec !== 'h264', ctx.ffmpegMajorVersion >= 5]);
|
|
814
|
+
}
|
|
815
|
+
outputArgs(ctx) {
|
|
816
|
+
const cfg = this.config;
|
|
817
|
+
if (!cfg || !cfg.enabled || this.plan(ctx) === null)
|
|
818
|
+
return null;
|
|
819
|
+
if (this.recoveredFor !== cfg.dir)
|
|
820
|
+
this.recover(cfg.dir);
|
|
821
|
+
const workDir = path.join(cfg.dir, `${exports.MAIN_STREAM_WORKDIR_PREFIX}${this.now()}-${ctx.session}`);
|
|
822
|
+
try {
|
|
823
|
+
fs.mkdirSync(path.join(cfg.dir, RTSPStreamCameraProvider_1.CLOSED_SEGMENTS_DIRNAME), { recursive: true });
|
|
824
|
+
fs.mkdirSync(workDir, { recursive: true });
|
|
825
|
+
if (cfg.label)
|
|
826
|
+
fs.writeFileSync(path.join(workDir, 'label.json'), JSON.stringify({ label: cfg.label }));
|
|
827
|
+
}
|
|
828
|
+
catch (err) {
|
|
829
|
+
this.counters.lastError = `main stream work directory: ${errorText(err)}`;
|
|
830
|
+
return null;
|
|
831
|
+
}
|
|
832
|
+
this.work = {
|
|
833
|
+
dir: cfg.dir,
|
|
834
|
+
workDir,
|
|
835
|
+
csvPath: path.join(workDir, 'segments.csv'),
|
|
836
|
+
csvOffset: 0,
|
|
837
|
+
csvRemainder: '',
|
|
838
|
+
pending: [],
|
|
839
|
+
handled: new Set(),
|
|
840
|
+
label: cfg.label,
|
|
841
|
+
closed: 0,
|
|
842
|
+
};
|
|
843
|
+
return (0, RTSPStreamCameraProvider_1.buildSegmentOutputArgs)({
|
|
844
|
+
csvPath: this.work.csvPath,
|
|
845
|
+
segmentPattern: (0, RTSPStreamCameraProvider_1.segmentPatternFor)(workDir),
|
|
846
|
+
segmentSeconds: cfg.segmentSeconds,
|
|
847
|
+
// Tagged unless the probe KNOWS it is H.264 (as the substream session does).
|
|
848
|
+
tagHvc1: cfg.codec !== 'h264',
|
|
849
|
+
minSegDuration: ctx.ffmpegMajorVersion >= 5,
|
|
850
|
+
audio: null,
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
onInput(ctx) {
|
|
854
|
+
const codec = ctx.input?.codec ?? null;
|
|
855
|
+
this.unsupportedCodec = codec !== null && !RTSPStreamCameraProvider_1.RECORDABLE_CODECS.includes(codec) ? codec : null;
|
|
856
|
+
// A codec the index cannot hold: the session drops this output (and stops if it was the only one).
|
|
857
|
+
if (this.unsupportedCodec)
|
|
858
|
+
ctx.refresh();
|
|
859
|
+
}
|
|
860
|
+
onTick(ctx) {
|
|
861
|
+
const work = this.work;
|
|
862
|
+
if (!work)
|
|
863
|
+
return;
|
|
864
|
+
try {
|
|
865
|
+
this.readList(work);
|
|
866
|
+
this.flush(work, ctx, false);
|
|
867
|
+
}
|
|
868
|
+
catch (err) {
|
|
869
|
+
this.counters.lastError = `main stream segment list: ${errorText(err)}`;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
onSessionEnd(ctx, _end) {
|
|
873
|
+
const work = this.work;
|
|
874
|
+
if (!work)
|
|
875
|
+
return;
|
|
876
|
+
this.work = null;
|
|
877
|
+
try {
|
|
878
|
+
this.readList(work);
|
|
879
|
+
this.flush(work, ctx, true);
|
|
880
|
+
}
|
|
881
|
+
catch (err) {
|
|
882
|
+
this.counters.lastError = `main stream segment list: ${errorText(err)}`;
|
|
883
|
+
}
|
|
884
|
+
// What was never listed is the segment ffmpeg was still writing.
|
|
885
|
+
if (work.pending.length === 0)
|
|
886
|
+
this.removeWorkDir(work.workDir);
|
|
887
|
+
}
|
|
888
|
+
readList(work) {
|
|
889
|
+
let size;
|
|
890
|
+
try {
|
|
891
|
+
size = fs.statSync(work.csvPath).size;
|
|
892
|
+
}
|
|
893
|
+
catch {
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
if (size < work.csvOffset) {
|
|
897
|
+
work.csvOffset = 0;
|
|
898
|
+
work.csvRemainder = '';
|
|
899
|
+
}
|
|
900
|
+
if (size === work.csvOffset)
|
|
901
|
+
return;
|
|
902
|
+
const buf = Buffer.alloc(size - work.csvOffset);
|
|
903
|
+
const fd = fs.openSync(work.csvPath, 'r');
|
|
904
|
+
let read = 0;
|
|
905
|
+
try {
|
|
906
|
+
read = fs.readSync(fd, buf, 0, buf.length, work.csvOffset);
|
|
907
|
+
}
|
|
908
|
+
finally {
|
|
909
|
+
fs.closeSync(fd);
|
|
910
|
+
}
|
|
911
|
+
work.csvOffset += read;
|
|
912
|
+
const { entries, remainder } = (0, RTSPStreamCameraProvider_1.parseSegmentListCsv)(work.csvRemainder + buf.subarray(0, read).toString('utf8'));
|
|
913
|
+
work.csvRemainder = remainder;
|
|
914
|
+
for (const entry of entries) {
|
|
915
|
+
if (work.handled.has(entry.name))
|
|
916
|
+
continue;
|
|
917
|
+
work.handled.add(entry.name);
|
|
918
|
+
work.pending.push(entry);
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
/** Hand every listed segment to the ring, in list order; a refused move waits for the next tick. */
|
|
922
|
+
flush(work, ctx, final) {
|
|
923
|
+
while (work.pending.length > 0) {
|
|
924
|
+
const entry = work.pending[0];
|
|
925
|
+
const src = path.join(work.workDir, entry.name);
|
|
926
|
+
let bytes = 0;
|
|
927
|
+
try {
|
|
928
|
+
const st = fs.statSync(src);
|
|
929
|
+
bytes = st.isFile() ? st.size : 0;
|
|
930
|
+
}
|
|
931
|
+
catch {
|
|
932
|
+
work.pending.shift();
|
|
933
|
+
continue;
|
|
934
|
+
}
|
|
935
|
+
if (bytes <= 0) {
|
|
936
|
+
this.unlink(src);
|
|
937
|
+
this.counters.partialsDeleted += 1;
|
|
938
|
+
work.pending.shift();
|
|
939
|
+
continue;
|
|
940
|
+
}
|
|
941
|
+
const captureStartMs = this.captureStartFor(entry, ctx);
|
|
942
|
+
this.persistAnchor(work, ctx);
|
|
943
|
+
const adopted = this.sink.adoptSegment({
|
|
944
|
+
src,
|
|
945
|
+
tag: path.basename(work.workDir),
|
|
946
|
+
startSec: entry.startSec,
|
|
947
|
+
endSec: entry.endSec,
|
|
948
|
+
captureStartMs,
|
|
949
|
+
bytes,
|
|
950
|
+
stream: ctx.input,
|
|
951
|
+
label: work.label,
|
|
952
|
+
recovered: false,
|
|
953
|
+
});
|
|
954
|
+
if (!adopted) {
|
|
955
|
+
if (final)
|
|
956
|
+
this.counters.lastError = 'the ring refused a main-stream segment; it stays for the next start';
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
work.pending.shift();
|
|
960
|
+
work.closed += 1;
|
|
961
|
+
const seconds = Math.max(0, entry.endSec - entry.startSec);
|
|
962
|
+
this.counters.closed += 1;
|
|
963
|
+
this.counters.seconds += seconds;
|
|
964
|
+
this.counters.bytes += bytes;
|
|
965
|
+
this.counters.lastSegmentAtMs = this.now();
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
/**
|
|
969
|
+
* When a segment's first frame was captured: the session's progress clock,
|
|
970
|
+
* held to the one fact a close gives — a segment cannot end after it was seen
|
|
971
|
+
* closed. Without a clock yet, its end is the moment it was seen closed.
|
|
972
|
+
*/
|
|
973
|
+
captureStartFor(entry, ctx) {
|
|
974
|
+
const nowMs = this.now();
|
|
975
|
+
const durationMs = Math.max(0, (entry.endSec - entry.startSec) * 1000);
|
|
976
|
+
let startMs = ctx.mediaZeroWallMs !== null ? ctx.mediaZeroWallMs + entry.startSec * 1000 : nowMs - durationMs;
|
|
977
|
+
if (startMs + durationMs > nowMs + CLOSE_FUTURE_TOLERANCE_MS)
|
|
978
|
+
startMs = nowMs - durationMs;
|
|
979
|
+
return Math.round(startMs);
|
|
980
|
+
}
|
|
981
|
+
persistAnchor(work, ctx) {
|
|
982
|
+
if (ctx.mediaZeroWallMs === null)
|
|
983
|
+
return;
|
|
984
|
+
try {
|
|
985
|
+
const tmp = path.join(work.workDir, 'anchor.json.tmp');
|
|
986
|
+
fs.writeFileSync(tmp, JSON.stringify({ mediaZeroWallMs: ctx.mediaZeroWallMs, stream: ctx.input, label: work.label }));
|
|
987
|
+
fs.renameSync(tmp, path.join(work.workDir, 'anchor.json'));
|
|
988
|
+
}
|
|
989
|
+
catch {
|
|
990
|
+
/* recovery falls back to the file's own last write */
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Hand out what an earlier process left in `<dir>/main-*`: listed segments go
|
|
995
|
+
* to the ring (recovered), everything else is a partial and is deleted.
|
|
996
|
+
*/
|
|
997
|
+
recover(dir) {
|
|
998
|
+
this.recoveredFor = dir;
|
|
999
|
+
let names;
|
|
1000
|
+
try {
|
|
1001
|
+
names = fs.readdirSync(dir).filter((n) => n.startsWith(exports.MAIN_STREAM_WORKDIR_PREFIX)).sort();
|
|
1002
|
+
}
|
|
1003
|
+
catch {
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
for (const name of names) {
|
|
1007
|
+
const workDir = path.join(dir, name);
|
|
1008
|
+
try {
|
|
1009
|
+
if (!fs.statSync(workDir).isDirectory())
|
|
1010
|
+
continue;
|
|
1011
|
+
this.recoverWorkDir(workDir);
|
|
1012
|
+
}
|
|
1013
|
+
catch (err) {
|
|
1014
|
+
this.counters.lastError = `main stream recovery: ${errorText(err)}`;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
recoverWorkDir(workDir) {
|
|
1019
|
+
let text = '';
|
|
1020
|
+
try {
|
|
1021
|
+
text = fs.readFileSync(path.join(workDir, 'segments.csv'), 'utf8');
|
|
1022
|
+
}
|
|
1023
|
+
catch {
|
|
1024
|
+
text = '';
|
|
1025
|
+
}
|
|
1026
|
+
let zero = null;
|
|
1027
|
+
let stream = null;
|
|
1028
|
+
let label = null;
|
|
1029
|
+
try {
|
|
1030
|
+
const raw = JSON.parse(fs.readFileSync(path.join(workDir, 'anchor.json'), 'utf8'));
|
|
1031
|
+
if (Number.isFinite(raw?.mediaZeroWallMs))
|
|
1032
|
+
zero = raw.mediaZeroWallMs;
|
|
1033
|
+
if (raw?.stream && typeof raw.stream.codec === 'string')
|
|
1034
|
+
stream = raw.stream;
|
|
1035
|
+
if (typeof raw?.label === 'string')
|
|
1036
|
+
label = raw.label;
|
|
1037
|
+
}
|
|
1038
|
+
catch {
|
|
1039
|
+
/* no clock was reported before it ended */
|
|
1040
|
+
}
|
|
1041
|
+
if (label === null) {
|
|
1042
|
+
try {
|
|
1043
|
+
const raw = JSON.parse(fs.readFileSync(path.join(workDir, 'label.json'), 'utf8'));
|
|
1044
|
+
if (typeof raw?.label === 'string')
|
|
1045
|
+
label = raw.label;
|
|
1046
|
+
}
|
|
1047
|
+
catch {
|
|
1048
|
+
/* unlabelled */
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
let leftBehind = false;
|
|
1052
|
+
for (const entry of (0, RTSPStreamCameraProvider_1.parseSegmentListCsv)(text).entries) {
|
|
1053
|
+
const src = path.join(workDir, entry.name);
|
|
1054
|
+
let st;
|
|
1055
|
+
try {
|
|
1056
|
+
st = fs.statSync(src);
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
if (!st.isFile() || st.size <= 0)
|
|
1062
|
+
continue;
|
|
1063
|
+
const captureStartMs = zero !== null
|
|
1064
|
+
? Math.round(zero + entry.startSec * 1000)
|
|
1065
|
+
: Math.round(st.mtimeMs - (entry.endSec - entry.startSec) * 1000);
|
|
1066
|
+
const adopted = this.sink.adoptSegment({
|
|
1067
|
+
src, tag: path.basename(workDir), startSec: entry.startSec, endSec: entry.endSec, captureStartMs,
|
|
1068
|
+
bytes: st.size, stream, label, recovered: true,
|
|
1069
|
+
});
|
|
1070
|
+
if (adopted)
|
|
1071
|
+
this.counters.recovered += 1;
|
|
1072
|
+
else
|
|
1073
|
+
leftBehind = true;
|
|
1074
|
+
}
|
|
1075
|
+
if (!leftBehind)
|
|
1076
|
+
this.removeWorkDir(workDir);
|
|
1077
|
+
}
|
|
1078
|
+
removeWorkDir(workDir) {
|
|
1079
|
+
let names = [];
|
|
1080
|
+
try {
|
|
1081
|
+
names = fs.readdirSync(workDir);
|
|
1082
|
+
}
|
|
1083
|
+
catch {
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
for (const name of names) {
|
|
1087
|
+
if (this.unlink(path.join(workDir, name)) && SEGMENT_FILE_RE.test(name))
|
|
1088
|
+
this.counters.partialsDeleted += 1;
|
|
1089
|
+
}
|
|
1090
|
+
try {
|
|
1091
|
+
fs.rmdirSync(workDir);
|
|
1092
|
+
}
|
|
1093
|
+
catch {
|
|
1094
|
+
/* best-effort */
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
unlink(file) {
|
|
1098
|
+
try {
|
|
1099
|
+
fs.unlinkSync(file);
|
|
1100
|
+
return true;
|
|
1101
|
+
}
|
|
1102
|
+
catch {
|
|
1103
|
+
return false;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
exports.MainStreamRingOutput = MainStreamRingOutput;
|
|
1108
|
+
/** The probe's argv after the input: the first video stream, copied, ~`sampleSeconds`, as packet lines. */
|
|
1109
|
+
function buildMainStreamProbeOutputArgs(sampleSeconds) {
|
|
1110
|
+
return ['-map', '0:v:0', '-c', 'copy', '-t', String(sampleSeconds), '-f', 'framecrc', 'pipe:1'];
|
|
1111
|
+
}
|
|
1112
|
+
exports.buildMainStreamProbeOutputArgs = buildMainStreamProbeOutputArgs;
|
|
1113
|
+
/**
|
|
1114
|
+
* Read ffmpeg's `framecrc` packet lines: `#tb 0: 1/90000` gives the time base,
|
|
1115
|
+
* then one line per packet, `stream, dts, pts, duration, size, crc[, F=..]`.
|
|
1116
|
+
*/
|
|
1117
|
+
class FramecrcPacketReader {
|
|
1118
|
+
constructor() {
|
|
1119
|
+
this.partial = '';
|
|
1120
|
+
this.tb = null;
|
|
1121
|
+
this.packets = 0;
|
|
1122
|
+
this.bytes = 0;
|
|
1123
|
+
this.firstPts = null;
|
|
1124
|
+
this.lastEnd = null;
|
|
1125
|
+
}
|
|
1126
|
+
push(text) {
|
|
1127
|
+
const lines = (this.partial + text).split('\n');
|
|
1128
|
+
this.partial = lines.pop() ?? '';
|
|
1129
|
+
if (this.partial.length > 4096)
|
|
1130
|
+
this.partial = '';
|
|
1131
|
+
for (const raw of lines) {
|
|
1132
|
+
const line = raw.trim();
|
|
1133
|
+
if (!line)
|
|
1134
|
+
continue;
|
|
1135
|
+
if (line.startsWith('#')) {
|
|
1136
|
+
const m = /^#tb 0:\s*(\d+)\/(\d+)/.exec(line);
|
|
1137
|
+
if (m && Number(m[2]) > 0)
|
|
1138
|
+
this.tb = Number(m[1]) / Number(m[2]);
|
|
1139
|
+
continue;
|
|
1140
|
+
}
|
|
1141
|
+
const fields = line.split(',').map((f) => f.trim());
|
|
1142
|
+
if (fields.length < 5 || fields[0] !== '0')
|
|
1143
|
+
continue;
|
|
1144
|
+
const pts = Number(fields[2]);
|
|
1145
|
+
const duration = Number(fields[3]);
|
|
1146
|
+
const size = Number(fields[4]);
|
|
1147
|
+
if (!Number.isFinite(size) || size < 0)
|
|
1148
|
+
continue;
|
|
1149
|
+
this.packets += 1;
|
|
1150
|
+
this.bytes += size;
|
|
1151
|
+
if (Number.isFinite(pts)) {
|
|
1152
|
+
if (this.firstPts === null || pts < this.firstPts)
|
|
1153
|
+
this.firstPts = pts;
|
|
1154
|
+
const end = pts + (Number.isFinite(duration) && duration > 0 ? duration : 0);
|
|
1155
|
+
if (this.lastEnd === null || end > this.lastEnd)
|
|
1156
|
+
this.lastEnd = end;
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
/** Media seconds from the first packet's pts to the last packet's end, or null. */
|
|
1161
|
+
mediaSeconds() {
|
|
1162
|
+
if (this.tb === null || this.firstPts === null || this.lastEnd === null)
|
|
1163
|
+
return null;
|
|
1164
|
+
const seconds = (this.lastEnd - this.firstPts) * this.tb;
|
|
1165
|
+
return Number.isFinite(seconds) && seconds > 0 ? seconds : null;
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
exports.FramecrcPacketReader = FramecrcPacketReader;
|
|
1169
|
+
/**
|
|
1170
|
+
* One bounded look at a main stream: ffmpeg copies about `sampleSeconds` of its
|
|
1171
|
+
* video packets (no decode) and reports each one; the probe measures the size,
|
|
1172
|
+
* codec, frame rate and bitrate the camera really sends. Killed at `deadlineMs`
|
|
1173
|
+
* whatever happens. Never retries: a refusal, an auth failure or a timeout is
|
|
1174
|
+
* what the caller reports. The caller holds the recorder's main-stream slot
|
|
1175
|
+
* (`acquireMainStreamSlot`) around it.
|
|
1176
|
+
*/
|
|
1177
|
+
function probeMainStream(options) {
|
|
1178
|
+
const spawnFn = options.spawnFn ?? child_process_1.spawn;
|
|
1179
|
+
const now = options.now ?? Date.now;
|
|
1180
|
+
const sampleSeconds = Math.max(1, Math.min(30, Number(options.sampleSeconds ?? 5)));
|
|
1181
|
+
const deadlineMs = Math.max(1000, Math.trunc(options.deadlineMs ?? 25000));
|
|
1182
|
+
const startedAt = now();
|
|
1183
|
+
return new Promise((resolve) => {
|
|
1184
|
+
let input;
|
|
1185
|
+
const empty = (stderr) => ({
|
|
1186
|
+
stream: null, packets: 0, bytes: 0, mediaSeconds: null, fps: null, bitrateBps: null, inputOpened: false,
|
|
1187
|
+
timedOut: false, exitCode: null, stderr, elapsedMs: Math.max(0, now() - startedAt),
|
|
1188
|
+
});
|
|
1189
|
+
try {
|
|
1190
|
+
input = buildMainStreamInputArgs({
|
|
1191
|
+
rtspUrl: options.rtspUrl,
|
|
1192
|
+
transport: options.transport ?? 'tcp',
|
|
1193
|
+
timeoutUs: options.timeoutUs ?? DEFAULT_TIMEOUT_US,
|
|
1194
|
+
ffmpegMajorVersion: options.ffmpegMajorVersion ?? 6,
|
|
1195
|
+
});
|
|
1196
|
+
}
|
|
1197
|
+
catch (err) {
|
|
1198
|
+
resolve(empty(`probe input file could not be written: ${errorText(err)}`));
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
const args = ['-hide_banner', '-nostdin', '-nostats', '-loglevel', 'info', ...input.args,
|
|
1202
|
+
...buildMainStreamProbeOutputArgs(sampleSeconds)];
|
|
1203
|
+
let proc;
|
|
1204
|
+
try {
|
|
1205
|
+
proc = spawnFn(options.ffmpegPath ?? 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
|
|
1206
|
+
}
|
|
1207
|
+
catch (err) {
|
|
1208
|
+
input.cleanup();
|
|
1209
|
+
resolve(empty(`probe ffmpeg could not start: ${errorText(err)}`));
|
|
1210
|
+
return;
|
|
1211
|
+
}
|
|
1212
|
+
const reader = new FramecrcPacketReader();
|
|
1213
|
+
const probe = new RTSPStreamCameraProvider_1.InputStreamProbe();
|
|
1214
|
+
const stderr = new ffmpegStderr_1.BoundedSessionStderr();
|
|
1215
|
+
let timedOut = false;
|
|
1216
|
+
let settled = false;
|
|
1217
|
+
const timer = setTimeout(() => {
|
|
1218
|
+
timedOut = true;
|
|
1219
|
+
try {
|
|
1220
|
+
proc.kill('SIGKILL');
|
|
1221
|
+
}
|
|
1222
|
+
catch {
|
|
1223
|
+
/* already gone */
|
|
1224
|
+
}
|
|
1225
|
+
}, deadlineMs);
|
|
1226
|
+
if (typeof timer.unref === 'function')
|
|
1227
|
+
timer.unref();
|
|
1228
|
+
proc.stdout?.on('data', (chunk) => reader.push(chunk.toString('latin1')));
|
|
1229
|
+
proc.stderr?.on('data', (chunk) => {
|
|
1230
|
+
const text = chunk.toString();
|
|
1231
|
+
stderr.append(text);
|
|
1232
|
+
if (!probe.done)
|
|
1233
|
+
probe.push(text);
|
|
1234
|
+
});
|
|
1235
|
+
const finish = (code) => {
|
|
1236
|
+
if (settled)
|
|
1237
|
+
return;
|
|
1238
|
+
settled = true;
|
|
1239
|
+
clearTimeout(timer);
|
|
1240
|
+
input.cleanup();
|
|
1241
|
+
// A stream described by a run that never reached a line after it: finish the read.
|
|
1242
|
+
if (!probe.done)
|
|
1243
|
+
probe.push('\nEnd\n');
|
|
1244
|
+
const stream = probe.info ?? null;
|
|
1245
|
+
const mediaSeconds = reader.mediaSeconds();
|
|
1246
|
+
const measuredFps = mediaSeconds !== null && reader.packets > 1 ? reader.packets / mediaSeconds : null;
|
|
1247
|
+
resolve({
|
|
1248
|
+
stream,
|
|
1249
|
+
packets: reader.packets,
|
|
1250
|
+
bytes: reader.bytes,
|
|
1251
|
+
mediaSeconds: mediaSeconds === null ? null : Math.round(mediaSeconds * 1000) / 1000,
|
|
1252
|
+
fps: measuredFps !== null ? Math.round(measuredFps * 100) / 100 : stream?.fps ?? null,
|
|
1253
|
+
bitrateBps: mediaSeconds !== null && reader.bytes > 0 ? Math.round((reader.bytes * 8) / mediaSeconds) : null,
|
|
1254
|
+
inputOpened: probe.inputOpened,
|
|
1255
|
+
timedOut,
|
|
1256
|
+
exitCode: code,
|
|
1257
|
+
stderr: (0, RTSPCameraProvider_1.sanitizeStreamUrlForLog)(stderr.text()),
|
|
1258
|
+
elapsedMs: Math.max(0, now() - startedAt),
|
|
1259
|
+
});
|
|
1260
|
+
};
|
|
1261
|
+
proc.on('error', (err) => {
|
|
1262
|
+
stderr.append(`\n${err.message}\n`);
|
|
1263
|
+
finish(null);
|
|
1264
|
+
});
|
|
1265
|
+
proc.on('close', (code) => finish(code));
|
|
1266
|
+
});
|
|
1267
|
+
}
|
|
1268
|
+
exports.probeMainStream = probeMainStream;
|
|
1269
|
+
//# sourceMappingURL=MainStreamSession.js.map
|