@sentinel-nvr/web 0.1.2 → 0.2.1

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.
@@ -0,0 +1,1897 @@
1
+ // src/player/rlog.ts
2
+ var brand = "web";
3
+ var client = null;
4
+ function setRlogClient(c, b) {
5
+ client = c;
6
+ if (b) brand = b;
7
+ }
8
+ function rlog(tag, data) {
9
+ if (!client) return;
10
+ let line;
11
+ try {
12
+ line = JSON.stringify({ tag, b: brand, d: data ?? null, ua: navigator.userAgent.slice(0, 80) });
13
+ } catch {
14
+ line = JSON.stringify({ tag, b: brand });
15
+ }
16
+ client.postText("api/clientlog", line);
17
+ }
18
+
19
+ // src/player/webrtc.ts
20
+ var forceRelayGlobal = false;
21
+ function mobileClient() {
22
+ return /iPhone|iPod|Android|Mobile/i.test(navigator.userAgent) || navigator.maxTouchPoints > 1 && Math.min(screen.width || 9999, screen.height || 9999) < 920;
23
+ }
24
+ function rtcOptions() {
25
+ let capabilities;
26
+ try {
27
+ capabilities = RTCRtpReceiver.getCapabilities ? { audio: RTCRtpReceiver.getCapabilities("audio"), video: RTCRtpReceiver.getCapabilities("video") } : void 0;
28
+ } catch {
29
+ }
30
+ return { userAgent: navigator.userAgent, capabilities, screen: { devicePixelRatio: window.devicePixelRatio || 1, width: screen.width || 1920, height: screen.height || 1080 } };
31
+ }
32
+ var WebRtcSession = class {
33
+ ws;
34
+ pc;
35
+ id;
36
+ active = false;
37
+ connectT;
38
+ trackSig = "";
39
+ api;
40
+ opts;
41
+ cb;
42
+ constructor(api, opts, cb) {
43
+ this.api = api;
44
+ this.opts = opts;
45
+ this.cb = cb;
46
+ }
47
+ get connected() {
48
+ const s = this.pc?.iceConnectionState;
49
+ return s === "connected" || s === "completed";
50
+ }
51
+ start() {
52
+ const params = {};
53
+ if (this.opts.mode === "recorded") {
54
+ params.mode = "recorded";
55
+ params.start = String(Math.round(this.opts.startMs || 0));
56
+ }
57
+ if (this.opts.compat ?? mobileClient()) params.compat = "1";
58
+ let ws;
59
+ try {
60
+ ws = new WebSocket(this.api.signalingUrl(this.opts.camId, params));
61
+ } catch {
62
+ this.cb.onFail("ws");
63
+ return;
64
+ }
65
+ this.ws = ws;
66
+ this.active = true;
67
+ this.connectT = window.setTimeout(() => {
68
+ if (this.active && this.ws === ws && !this.connected) {
69
+ rlog("connect-timeout", { kind: this.opts.mode, ice: this.pc?.iceConnectionState });
70
+ if (!forceRelayGlobal) {
71
+ forceRelayGlobal = true;
72
+ rlog("retry-relay-only", { kind: this.opts.mode });
73
+ this.stop();
74
+ this.start();
75
+ return;
76
+ }
77
+ this.fail("timeout");
78
+ }
79
+ }, 12e3);
80
+ ws.onopen = () => {
81
+ try {
82
+ ws.send(JSON.stringify({ type: "options", options: rtcOptions() }));
83
+ } catch {
84
+ }
85
+ };
86
+ ws.onerror = () => {
87
+ if (this.active && this.ws === ws && !this.pc) this.fail("ws-error");
88
+ };
89
+ ws.onclose = () => {
90
+ if (this.active && this.ws === ws && !this.connected) this.fail("ws-closed");
91
+ };
92
+ ws.onmessage = (ev) => {
93
+ let msg;
94
+ try {
95
+ msg = JSON.parse(ev.data);
96
+ } catch {
97
+ return;
98
+ }
99
+ if (msg.type === "createLocalDescription") this.createLocal(ws, msg);
100
+ else if (msg.type === "setRemoteDescription") this.setRemote(ws, msg);
101
+ else if (msg.type === "addIceCandidate") this.pc?.addIceCandidate(msg.candidate).catch(() => {
102
+ });
103
+ else if (msg.type === "sessionStarted") {
104
+ this.id = msg.id;
105
+ this.cb.onSessionId?.(msg.id);
106
+ } else if (msg.type === "error") {
107
+ if (this.active && this.ws === ws) this.fail(msg.reason || "error");
108
+ }
109
+ };
110
+ }
111
+ stop() {
112
+ this.active = false;
113
+ if (this.connectT) {
114
+ clearTimeout(this.connectT);
115
+ this.connectT = void 0;
116
+ }
117
+ try {
118
+ if (this.ws) {
119
+ this.ws.onmessage = null;
120
+ this.ws.onclose = null;
121
+ this.ws.onerror = null;
122
+ this.ws.close();
123
+ }
124
+ } catch {
125
+ }
126
+ try {
127
+ if (this.pc) {
128
+ this.pc.ontrack = null;
129
+ this.pc.oniceconnectionstatechange = null;
130
+ this.pc.onicecandidate = null;
131
+ this.pc.close();
132
+ }
133
+ } catch {
134
+ }
135
+ this.ws = void 0;
136
+ this.pc = void 0;
137
+ this.id = void 0;
138
+ this.trackSig = "";
139
+ }
140
+ fail(reason) {
141
+ if (!this.active) return;
142
+ this.stop();
143
+ this.cb.onFail(reason);
144
+ }
145
+ ensurePc(setup) {
146
+ if (this.pc) return this.pc;
147
+ let cfg = setup && setup.configuration || { iceServers: [{ urls: "stun:stun.l.google.com:19302" }] };
148
+ if (forceRelayGlobal) cfg = { ...cfg, iceTransportPolicy: "relay" };
149
+ const pc = new RTCPeerConnection(cfg);
150
+ this.pc = pc;
151
+ if (setup?.datachannel) {
152
+ try {
153
+ const dc = pc.createDataChannel(setup.datachannel.label, setup.datachannel.dict);
154
+ dc.binaryType = "arraybuffer";
155
+ } catch {
156
+ }
157
+ }
158
+ if (setup?.audio) {
159
+ try {
160
+ pc.addTransceiver("audio", { direction: setup.audio.direction || "recvonly" });
161
+ } catch {
162
+ }
163
+ }
164
+ if (setup?.video) {
165
+ try {
166
+ pc.addTransceiver("video", { direction: setup.video.direction || "recvonly" });
167
+ } catch {
168
+ }
169
+ }
170
+ pc.ontrack = () => {
171
+ if (!this.active || this.pc !== pc) return;
172
+ const ms = new MediaStream();
173
+ pc.getReceivers().forEach((r) => {
174
+ if (r.track) ms.addTrack(r.track);
175
+ });
176
+ if (!ms.getVideoTracks().length) return;
177
+ const sig = ms.getTracks().map((t) => t.id).sort().join(",");
178
+ if (this.trackSig === sig) return;
179
+ this.trackSig = sig;
180
+ this.cb.onStream(ms);
181
+ };
182
+ pc.oniceconnectionstatechange = () => {
183
+ if (!this.active || this.pc !== pc) return;
184
+ const st = pc.iceConnectionState;
185
+ if (st === "connected" || st === "completed") {
186
+ if (this.connectT) {
187
+ clearTimeout(this.connectT);
188
+ this.connectT = void 0;
189
+ }
190
+ window.setTimeout(() => {
191
+ if (!this.active || this.pc !== pc) return;
192
+ pc.getStats().then((s) => {
193
+ let dec = -1, recv = -1, vBytes = -1, aBytes = -1;
194
+ s.forEach((r) => {
195
+ if (r.type === "inbound-rtp" && (r.kind || r.mediaType) === "video") {
196
+ dec = r.framesDecoded || 0;
197
+ recv = r.framesReceived ?? -1;
198
+ vBytes = r.bytesReceived || 0;
199
+ }
200
+ if (r.type === "inbound-rtp" && (r.kind || r.mediaType) === "audio") aBytes = r.bytesReceived || 0;
201
+ });
202
+ if (dec <= 0) {
203
+ rlog("dec-check-fail", { kind: this.opts.mode, dec, recv, vBytes, aBytes, relayForced: forceRelayGlobal });
204
+ if (!forceRelayGlobal && vBytes <= 0 && aBytes <= 0) {
205
+ forceRelayGlobal = true;
206
+ rlog("retry-relay-only", { kind: this.opts.mode });
207
+ this.stop();
208
+ this.start();
209
+ return;
210
+ }
211
+ this.fail("no-decode");
212
+ } else rlog("dec-ok", { kind: this.opts.mode, dec, relayForced: forceRelayGlobal });
213
+ }).catch(() => {
214
+ });
215
+ }, this.opts.mode === "live" ? 5e3 : 9e3);
216
+ }
217
+ if (st === "failed") {
218
+ rlog("ice-failed", { kind: this.opts.mode });
219
+ this.fail("ice-failed");
220
+ }
221
+ };
222
+ return pc;
223
+ }
224
+ createLocal(ws, msg) {
225
+ const pc = this.ensurePc(msg.setup);
226
+ const mid = this.connected;
227
+ if (mid) rlog("reneg", { dtype: msg.dtype, kind: this.opts.mode });
228
+ const reply = (desc) => {
229
+ try {
230
+ ws.send(JSON.stringify({ type: "response", reqId: msg.reqId, description: { type: desc.type, sdp: desc.sdp } }));
231
+ } catch {
232
+ }
233
+ };
234
+ pc.onicecandidate = (ev) => {
235
+ if (ev.candidate) {
236
+ try {
237
+ ws.send(JSON.stringify({ type: "iceCandidate", candidate: JSON.parse(JSON.stringify(ev.candidate)) }));
238
+ } catch {
239
+ }
240
+ }
241
+ };
242
+ const p = msg.dtype === "offer" ? pc.createOffer({ offerToReceiveAudio: !!msg.setup?.audio, offerToReceiveVideo: !!msg.setup?.video }).then((o) => pc.setLocalDescription(o).then(() => reply(o))) : pc.createAnswer().then((a) => pc.setLocalDescription(a).then(() => reply(a)));
243
+ p.catch((e) => {
244
+ rlog("createLocal-fail", { dtype: msg.dtype, name: e?.name, mid });
245
+ if (!mid) this.fail("createLocal");
246
+ });
247
+ }
248
+ setRemote(ws, msg) {
249
+ const pc = this.ensurePc(msg.setup);
250
+ const mid = this.connected;
251
+ pc.setRemoteDescription(msg.description).then(() => {
252
+ try {
253
+ ws.send(JSON.stringify({ type: "response", reqId: msg.reqId, ok: true }));
254
+ } catch {
255
+ }
256
+ }).catch((e) => {
257
+ rlog("sRD-fail", { name: e?.name, mid });
258
+ try {
259
+ ws.send(JSON.stringify({ type: "response", reqId: msg.reqId, ok: false }));
260
+ } catch {
261
+ }
262
+ if (!mid) this.fail("sRD");
263
+ });
264
+ }
265
+ };
266
+
267
+ // src/player/controller.ts
268
+ var MSCls = window.ManagedMediaSource || window.MediaSource;
269
+ var PlayerController = class {
270
+ v;
271
+ fz;
272
+ img;
273
+ stage;
274
+ api;
275
+ opts;
276
+ camId = "";
277
+ camName = "";
278
+ clips = [];
279
+ codecs = null;
280
+ rangeStart = 0;
281
+ rangeEnd = 0;
282
+ live = false;
283
+ rate = 1;
284
+ soundOn = false;
285
+ recPaused = false;
286
+ recPausedTs = null;
287
+ recWebrtcDisabled = false;
288
+ label = "";
289
+ transport = "none";
290
+ // relay session (RW)
291
+ rw;
292
+ rwStartMs = 0;
293
+ rwBase = null;
294
+ rwPosTs = null;
295
+ rwPosAt = 0;
296
+ rwRate = 1;
297
+ rwSrate = 1;
298
+ rwScrub = false;
299
+ rwSeekBusy = false;
300
+ rwPending = null;
301
+ rwLastSeekTs = null;
302
+ rwLastSeekAt = 0;
303
+ rwRateBusy = false;
304
+ rwPendingRate = null;
305
+ rwLastRateAt = 0;
306
+ relayPoll;
307
+ wdLastCt = -1;
308
+ wdLastAt = 0;
309
+ wdDead = 0;
310
+ wdGrace = 0;
311
+ wdResumeLogged = false;
312
+ recoveries = 0;
313
+ posterUntilSeek = false;
314
+ seekTarget = 0;
315
+ // relay-pos answers are only valid for the command generation they were asked under; a poll sent BEFORE a
316
+ // seek/rate change and answered after it would drag the playhead back to the old position (and the
317
+ // auto-follow timeline with it → visible back-and-forth). seekAt: the server may still report the pre-swap
318
+ // position for a moment after a seek — ignore far-off values in that window.
319
+ cmdSeq = 0;
320
+ seekAt = 0;
321
+ // live session (W) + live MSE (L)
322
+ w;
323
+ L = { active: false, ms: null, sb: null, abort: null, queue: [], restarts: 0, lastTrim: 0, stallT: 0 };
324
+ // recorded MSE (M)
325
+ M = { ms: null, sb: null, base: 0, nextIdx: -1, end: 0, active: false, feeding: false, abort: null, q: [], segFirst: false, segOff: 0, pendingSeek: null, mmsGo: true };
326
+ CH = { active: false, target: 0, timer: 0 };
327
+ curClipId = null;
328
+ playIndex = -1;
329
+ lastLoad = 0;
330
+ pendingTs = null;
331
+ pendingT;
332
+ // frame counter / freeze
333
+ fc = { n: 0, tok: {} };
334
+ freezeT = 0;
335
+ freezeTok = null;
336
+ cad = { t: 0, last: -1, lastNew: 0, stalls: 0, maxStall: 0, frames0: -1, t0: 0, gapMax: 0 };
337
+ stallTimer = 0;
338
+ destroyed = false;
339
+ liveRestartT = 0;
340
+ unlisten = [];
341
+ arPrefix;
342
+ constructor(api, opts) {
343
+ this.api = api;
344
+ this.opts = opts;
345
+ this.arPrefix = opts.storagePrefix ?? "snvr-ar-";
346
+ setRlogClient(api, opts.brand);
347
+ }
348
+ attach(r) {
349
+ this.v = r.video;
350
+ this.fz = r.freeze;
351
+ this.img = r.img;
352
+ this.stage = r.stage;
353
+ const v = this.v;
354
+ const on = (n, f) => {
355
+ v.addEventListener(n, f);
356
+ this.unlisten.push(() => v.removeEventListener(n, f));
357
+ };
358
+ on("timeupdate", () => {
359
+ if (this.live) return;
360
+ if (this.rw?.active && this.rwBase == null && v.currentTime > 0) this.rwBase = v.currentTime;
361
+ const ts = this.currentTs();
362
+ if (ts == null) return;
363
+ if (this.M.active || this.rw?.active) {
364
+ const i = this.clipIndexFor(ts);
365
+ if (i >= 0) this.playIndex = i;
366
+ }
367
+ this.feed();
368
+ this.emit();
369
+ });
370
+ on("waiting", () => {
371
+ if (this.live) {
372
+ if (this.L.active && !this.L.stallT) this.L.stallT = window.setTimeout(() => {
373
+ this.L.stallT = 0;
374
+ if (this.live && this.L.active && v.readyState < 3) this.liveRestart();
375
+ }, 4e3);
376
+ return;
377
+ }
378
+ if (!this.rw?.active) this.setLabel("loading");
379
+ if (!this.M.active || this.stallTimer) return;
380
+ this.stallTimer = window.setTimeout(() => {
381
+ this.stallTimer = 0;
382
+ this.handleStall();
383
+ }, 600);
384
+ });
385
+ on("seeking", () => {
386
+ if (!this.live && !this.rw?.active) this.setLabel("loading");
387
+ });
388
+ for (const n of ["loadeddata", "playing", "canplay", "seeked"]) on(n, () => {
389
+ if (v.videoWidth) this.freezeHide();
390
+ if (!this.live && this.label === "loading") this.setLabel("playing");
391
+ if (this.L.stallT) {
392
+ clearTimeout(this.L.stallT);
393
+ this.L.stallT = 0;
394
+ }
395
+ this.emit();
396
+ });
397
+ on("pause", () => {
398
+ if (this.L.stallT) {
399
+ clearTimeout(this.L.stallT);
400
+ this.L.stallT = 0;
401
+ }
402
+ this.emit();
403
+ });
404
+ on("play", () => this.emit());
405
+ on("loadedmetadata", () => this.setAspect(this.v.videoWidth, this.v.videoHeight));
406
+ on("resize", () => this.setAspect(this.v.videoWidth, this.v.videoHeight));
407
+ on("volumechange", () => this.emit());
408
+ on("error", () => {
409
+ const e = v.error;
410
+ rlog("video-error", { code: e?.code, msg: e?.message?.slice(0, 120), src: v.getAttribute("src") ? "src" : "srcObject" });
411
+ });
412
+ on("ended", () => {
413
+ if (this.live || this.M.active || this.rw?.active) return;
414
+ const n = this.playIndex + 1;
415
+ if (n < this.clips.length) {
416
+ const c = this.clips[n];
417
+ this.curClipId = c.id;
418
+ this.playIndex = n;
419
+ v.src = this.api.url(`api/segment?id=${encodeURIComponent(c.videoId || c.id)}`);
420
+ v.load();
421
+ v.onloadedmetadata = () => {
422
+ v.playbackRate = this.rate;
423
+ try {
424
+ v.currentTime = 0;
425
+ } catch {
426
+ }
427
+ this.safePlay();
428
+ };
429
+ this.setLabel("playing");
430
+ }
431
+ });
432
+ this.pendingT = window.setInterval(() => {
433
+ if (this.pendingTs != null && Date.now() - this.lastLoad >= 200) {
434
+ const t = this.pendingTs;
435
+ this.pendingTs = null;
436
+ this.playAt(t, { scrub: true });
437
+ }
438
+ }, 120);
439
+ const vis = () => this.onVisibility();
440
+ document.addEventListener("visibilitychange", vis);
441
+ this.unlisten.push(() => document.removeEventListener("visibilitychange", vis));
442
+ const edge = window.setInterval(() => {
443
+ if (this.live && this.L.active) this.liveEdge();
444
+ }, 1e3);
445
+ this.unlisten.push(() => clearInterval(edge));
446
+ }
447
+ destroy() {
448
+ this.destroyed = true;
449
+ this.live = false;
450
+ this.recPaused = false;
451
+ if (this.liveRestartT) {
452
+ clearTimeout(this.liveRestartT);
453
+ this.liveRestartT = 0;
454
+ }
455
+ this.recWebrtcTeardown();
456
+ this.webrtcTeardown();
457
+ this.mseTeardown();
458
+ this.liveTeardown();
459
+ this.chaseAbort();
460
+ if (this.pendingT) clearInterval(this.pendingT);
461
+ for (const u of this.unlisten) u();
462
+ try {
463
+ this.v.pause();
464
+ this.v.srcObject = null;
465
+ this.v.removeAttribute("src");
466
+ } catch {
467
+ }
468
+ }
469
+ setCamera(camId, name) {
470
+ if (camId !== this.camId) {
471
+ this.recWebrtcDisabled = false;
472
+ this.recoveries = 0;
473
+ }
474
+ this.camId = camId;
475
+ this.camName = name;
476
+ let ar = "";
477
+ try {
478
+ ar = localStorage.getItem(this.arPrefix + camId) || "";
479
+ } catch {
480
+ }
481
+ if (ar) this.stage.style.setProperty("--stage-ar", ar);
482
+ else this.stage.style.removeProperty("--stage-ar");
483
+ }
484
+ /** picture aspect → stage box (mobile layout uses it); posters and video both report it */
485
+ setAspect(w, h) {
486
+ if (!w || !h) return;
487
+ const ar = `${w} / ${h}`;
488
+ if (this.stage.style.getPropertyValue("--stage-ar") === ar) return;
489
+ this.stage.style.setProperty("--stage-ar", ar);
490
+ try {
491
+ localStorage.setItem(this.arPrefix + this.camId, ar);
492
+ } catch {
493
+ }
494
+ }
495
+ /** clips of the loaded range (several days, sorted), codec string, and the range the timeline spans */
496
+ setClips(clips, codecs, rangeStart, rangeEnd) {
497
+ this.clips = clips;
498
+ this.codecs = codecs;
499
+ this.rangeStart = rangeStart;
500
+ this.rangeEnd = rangeEnd;
501
+ }
502
+ // ---- state ---------------------------------------------------------------------
503
+ setLabel(l) {
504
+ this.label = l;
505
+ this.emit();
506
+ }
507
+ emit() {
508
+ if (this.destroyed) return;
509
+ this.opts.onState({ live: this.live, label: this.label, playhead: this.live ? null : this.currentTs(), rate: this.rate, sound: this.soundOn, paused: this.recPaused || this.v.paused && !this.live && !this.rw?.active, transport: this.transport, muted: this.v.muted });
510
+ }
511
+ clipIndexFor(ts) {
512
+ for (let i = 0; i < this.clips.length; i++) {
513
+ const c = this.clips[i];
514
+ if (ts >= c.startTime && ts < c.startTime + (c.duration || 6e4)) return i;
515
+ }
516
+ return -1;
517
+ }
518
+ nearNow(ts) {
519
+ return Date.now() - ts < 8e3;
520
+ }
521
+ clampRange(ts) {
522
+ return Math.min(Math.max(ts, this.rangeStart), Math.min(this.rangeEnd - 1, Date.now()));
523
+ }
524
+ /** Wall-clock position of the picture on screen (Scrypted's getRecordingStreamCurrentTime). */
525
+ currentTs() {
526
+ if (this.rw?.active) {
527
+ if (this.rwPosTs != null) return this.rwPosTs + (Date.now() - this.rwPosAt) * (this.rwRate || 1);
528
+ if (this.rwBase != null && this.v.currentTime > 0) return this.rwStartMs + (this.v.currentTime - this.rwBase) * 1e3 * (this.rwRate || 1);
529
+ return this.rwStartMs;
530
+ }
531
+ if (this.recPaused) return this.recPausedTs;
532
+ if (this.live) return null;
533
+ if (this.M.active) return this.M.base + this.v.currentTime * 1e3;
534
+ const pc = this.playIndex >= 0 ? this.clips[this.playIndex] : void 0;
535
+ if (pc) return pc.startTime + this.v.currentTime * 1e3;
536
+ return null;
537
+ }
538
+ // ---- presented frames / freeze / poster -----------------------------------------
539
+ fcArm() {
540
+ const v = this.v;
541
+ if (!v.requestVideoFrameCallback) return;
542
+ const tok = {};
543
+ this.fc.tok = tok;
544
+ const tick = () => {
545
+ if (this.fc.tok !== tok) return;
546
+ this.fc.n++;
547
+ try {
548
+ v.requestVideoFrameCallback(tick);
549
+ } catch {
550
+ }
551
+ };
552
+ try {
553
+ v.requestVideoFrameCallback(tick);
554
+ } catch {
555
+ }
556
+ }
557
+ presentedFrames() {
558
+ if (this.v.requestVideoFrameCallback) return this.fc.n;
559
+ try {
560
+ return this.v.getVideoPlaybackQuality().totalVideoFrames;
561
+ } catch {
562
+ return -1;
563
+ }
564
+ }
565
+ freezeArm(hold) {
566
+ if (this.freezeT) clearTimeout(this.freezeT);
567
+ this.freezeT = window.setTimeout(() => this.freezeHide(), hold ? 9e4 : 5e3);
568
+ const v = this.v;
569
+ if (hold && v.requestVideoFrameCallback) {
570
+ const tok = {};
571
+ this.freezeTok = tok;
572
+ try {
573
+ v.requestVideoFrameCallback(() => {
574
+ if (this.freezeTok === tok && this.v.videoWidth) this.freezeHide();
575
+ });
576
+ } catch {
577
+ }
578
+ }
579
+ }
580
+ freezeShow(hold = false) {
581
+ try {
582
+ const v = this.v, fc = this.fz;
583
+ if (!v.videoWidth || !v.videoHeight || v.readyState < 2) return;
584
+ if (fc.width !== v.videoWidth) fc.width = v.videoWidth;
585
+ if (fc.height !== v.videoHeight) fc.height = v.videoHeight;
586
+ fc.getContext("2d").drawImage(v, 0, 0, fc.width, fc.height);
587
+ fc.classList.remove("hidden");
588
+ fc.dataset.src = "video";
589
+ this.freezeArm(hold);
590
+ } catch {
591
+ }
592
+ }
593
+ freezeFromImage(img, hold, untilSeek = false, kind = "image") {
594
+ try {
595
+ if (!img.naturalWidth || !img.naturalHeight) return false;
596
+ const fc = this.fz;
597
+ fc.width = img.naturalWidth;
598
+ fc.height = img.naturalHeight;
599
+ fc.getContext("2d").drawImage(img, 0, 0);
600
+ fc.classList.remove("hidden");
601
+ fc.dataset.src = kind;
602
+ this.setAspect(img.naturalWidth, img.naturalHeight);
603
+ if (untilSeek) {
604
+ if (this.freezeT) clearTimeout(this.freezeT);
605
+ this.freezeTok = null;
606
+ this.posterUntilSeek = true;
607
+ this.freezeT = window.setTimeout(() => this.freezeHide(), 6e3);
608
+ } else this.freezeArm(hold);
609
+ return true;
610
+ } catch {
611
+ return false;
612
+ }
613
+ }
614
+ freezeHide() {
615
+ if (this.freezeT) {
616
+ clearTimeout(this.freezeT);
617
+ this.freezeT = 0;
618
+ }
619
+ this.posterUntilSeek = false;
620
+ this.fz.classList.add("hidden");
621
+ delete this.fz.dataset.src;
622
+ }
623
+ posterUp() {
624
+ return !this.fz.classList.contains("hidden");
625
+ }
626
+ freezeHold() {
627
+ if (this.freezeT) {
628
+ clearTimeout(this.freezeT);
629
+ this.freezeT = window.setTimeout(() => this.freezeHide(), 5e3);
630
+ }
631
+ }
632
+ /** Event click: the stored frame is the poster until the seek lands. */
633
+ posterEvent(ts) {
634
+ const cam = this.camId;
635
+ const img = new Image();
636
+ img.crossOrigin = "anonymous";
637
+ img.onload = () => {
638
+ if (this.camId !== cam) return;
639
+ this.freezeFromImage(img, true, !!this.rw?.active && !!this.rw.id, "event");
640
+ };
641
+ img.src = this.api.url(`api/evframe?camera=${encodeURIComponent(cam)}&ts=${ts}`);
642
+ }
643
+ /** Camera opened: newest snapshot in front of the black stage until live plays. */
644
+ posterFromSnapshot() {
645
+ const cam = this.camId;
646
+ const img = new Image();
647
+ img.crossOrigin = "anonymous";
648
+ img.onload = () => {
649
+ if (this.camId !== cam || this.rw?.active || this.recPaused || this.posterUp()) return;
650
+ if (this.v.readyState >= 2 && this.v.videoWidth && !this.v.paused) return;
651
+ this.freezeFromImage(img, true, false, "snapshot");
652
+ };
653
+ img.src = this.api.url(`api/snapshot?camera=${encodeURIComponent(cam)}`) + `&_=${Date.now()}`;
654
+ }
655
+ posterShow(ts) {
656
+ try {
657
+ if (this.posterUp()) return;
658
+ if (this.v.readyState >= 2 && this.v.videoWidth) return;
659
+ const i = this.clipIndexFor(ts);
660
+ const c = i >= 0 ? this.clips[i] : void 0;
661
+ if (!c?.thumbnailId) return;
662
+ const cam = this.camId;
663
+ const img = new Image();
664
+ img.crossOrigin = "anonymous";
665
+ img.onload = () => {
666
+ if (this.camId !== cam || this.destroyed) return;
667
+ if (!this.posterUp()) this.freezeFromImage(img, true, false, "thumb");
668
+ };
669
+ img.src = this.api.url(`api/thumb?id=${encodeURIComponent(c.thumbnailId)}`);
670
+ } catch {
671
+ }
672
+ }
673
+ safePlay() {
674
+ let pr;
675
+ try {
676
+ pr = this.v.play();
677
+ } catch {
678
+ return;
679
+ }
680
+ pr.then(() => this.emit()).catch((e1) => {
681
+ this.v.muted = true;
682
+ this.v.play().then(() => this.emit()).catch((e2) => rlog("play-fail", { e1: e1?.name, e2: e2?.name, rs: this.v.readyState, paused: this.v.paused }));
683
+ });
684
+ }
685
+ // ---- LIVE ---------------------------------------------------------------------------
686
+ goLive() {
687
+ if (!this.camId || this.destroyed) return;
688
+ this.chaseAbort();
689
+ this.freezeShow(true);
690
+ this.exitLiveState();
691
+ this.recWebrtcTeardown();
692
+ this.recPaused = false;
693
+ this.live = true;
694
+ this.playIndex = -1;
695
+ this.curClipId = null;
696
+ this.L.restarts = 0;
697
+ this.setLabel("live");
698
+ if (document.visibilityState === "hidden") return;
699
+ if (window.RTCPeerConnection && window.WebSocket) this.liveStartWebrtc();
700
+ else if (this.liveMseOk()) this.liveStartMse();
701
+ else {
702
+ try {
703
+ this.v.pause();
704
+ } catch {
705
+ }
706
+ this.liveFallbackImg();
707
+ }
708
+ }
709
+ exitLiveState() {
710
+ if (this.live) {
711
+ this.live = false;
712
+ this.webrtcTeardown();
713
+ this.liveTeardown();
714
+ try {
715
+ this.v.srcObject = null;
716
+ } catch {
717
+ }
718
+ this.setMjpeg(false);
719
+ }
720
+ }
721
+ setMjpeg(on) {
722
+ this.img.classList.toggle("hidden", !on);
723
+ this.v.classList.toggle("hidden", on);
724
+ if (!on) this.img.removeAttribute("src");
725
+ }
726
+ webrtcTeardown() {
727
+ this.w?.stop();
728
+ this.w = void 0;
729
+ }
730
+ liveStartWebrtc() {
731
+ if (this.destroyed) return;
732
+ this.v.onloadedmetadata = null;
733
+ this.webrtcTeardown();
734
+ this.recWebrtcTeardown();
735
+ this.mseTeardown();
736
+ this.liveTeardown();
737
+ try {
738
+ this.v.pause();
739
+ } catch {
740
+ }
741
+ try {
742
+ this.v.srcObject = null;
743
+ } catch {
744
+ }
745
+ this.v.removeAttribute("src");
746
+ this.setMjpeg(false);
747
+ const s = new WebRtcSession(this.api, { camId: this.camId, mode: "live" }, {
748
+ onStream: (ms) => {
749
+ if (!this.live || this.w !== s) return;
750
+ this.setMjpeg(false);
751
+ this.v.muted = !this.soundOn;
752
+ try {
753
+ this.v.removeAttribute("src");
754
+ } catch {
755
+ }
756
+ try {
757
+ this.v.srcObject = ms;
758
+ } catch {
759
+ }
760
+ this.fcArm();
761
+ this.safePlay();
762
+ this.transport = "webrtc";
763
+ this.setLabel("liveWebrtc");
764
+ },
765
+ onFail: () => {
766
+ if (this.w === s) this.liveFallbackMse();
767
+ }
768
+ });
769
+ this.w = s;
770
+ this.transport = "webrtc";
771
+ s.start();
772
+ }
773
+ liveFallbackMse() {
774
+ this.webrtcTeardown();
775
+ if (!this.live) return;
776
+ try {
777
+ this.v.srcObject = null;
778
+ } catch {
779
+ }
780
+ if (this.liveMseOk()) this.liveStartMse();
781
+ else this.liveFallbackImg();
782
+ }
783
+ liveCodec() {
784
+ return this.codecs ? this.codecs.split(",")[0] ?? null : null;
785
+ }
786
+ liveMseOk() {
787
+ try {
788
+ const c = this.liveCodec();
789
+ return !!(this.api.corsMedia && MSCls && c && MSCls.isTypeSupported(`video/mp4; codecs="${c}"`));
790
+ } catch {
791
+ return false;
792
+ }
793
+ }
794
+ liveTeardown() {
795
+ const L = this.L;
796
+ L.active = false;
797
+ L.queue = [];
798
+ if (L.stallT) {
799
+ clearTimeout(L.stallT);
800
+ L.stallT = 0;
801
+ }
802
+ try {
803
+ L.abort?.abort();
804
+ } catch {
805
+ }
806
+ L.abort = null;
807
+ if (L.sb && L.ms && L.ms.readyState === "open") {
808
+ try {
809
+ L.sb.abort();
810
+ } catch {
811
+ }
812
+ }
813
+ L.sb = null;
814
+ L.ms = null;
815
+ }
816
+ liveAppend() {
817
+ const L = this.L;
818
+ if (!L.active || !L.sb || L.sb.updating || !L.queue.length) return;
819
+ const buf = L.queue.shift();
820
+ try {
821
+ L.sb.appendBuffer(buf);
822
+ } catch {
823
+ this.liveRestart();
824
+ }
825
+ }
826
+ liveTrim() {
827
+ const L = this.L;
828
+ if (!L.sb || L.sb.updating) return;
829
+ try {
830
+ const b = this.v.buffered;
831
+ if (b.length && this.v.currentTime - b.start(0) > 30) L.sb.remove(0, this.v.currentTime - 10);
832
+ } catch {
833
+ }
834
+ }
835
+ liveEdge() {
836
+ try {
837
+ const b = this.v.buffered;
838
+ if (!b.length) return;
839
+ const end = b.end(b.length - 1);
840
+ if (end - this.v.currentTime > 2.5) this.v.currentTime = end - 0.7;
841
+ if (this.v.paused) this.safePlay();
842
+ } catch {
843
+ }
844
+ }
845
+ liveRestart() {
846
+ if (!this.live || !this.L.active) return;
847
+ this.liveTeardown();
848
+ this.L.restarts++;
849
+ if (this.L.restarts > 5) {
850
+ this.liveFallbackImg();
851
+ return;
852
+ }
853
+ if (this.liveRestartT) clearTimeout(this.liveRestartT);
854
+ this.liveRestartT = window.setTimeout(() => {
855
+ this.liveRestartT = 0;
856
+ if (this.live && !this.destroyed) this.liveStartMse();
857
+ }, 1e3);
858
+ }
859
+ liveStartMse() {
860
+ if (this.destroyed) return;
861
+ this.v.onloadedmetadata = null;
862
+ this.liveTeardown();
863
+ this.mseTeardown();
864
+ const L = this.L;
865
+ L.active = true;
866
+ this.transport = "mse";
867
+ this.setLabel("liveMse");
868
+ this.setMjpeg(false);
869
+ const ms = new MSCls();
870
+ L.ms = ms;
871
+ L.lastTrim = Date.now();
872
+ if (window.ManagedMediaSource && ms instanceof window.ManagedMediaSource) {
873
+ try {
874
+ this.v.disableRemotePlayback = true;
875
+ } catch {
876
+ }
877
+ }
878
+ const u = URL.createObjectURL(ms);
879
+ ms.addEventListener("sourceopen", () => {
880
+ URL.revokeObjectURL(u);
881
+ if (L.ms !== ms) return;
882
+ let sb;
883
+ try {
884
+ sb = ms.addSourceBuffer(`video/mp4; codecs="${this.liveCodec()}"`);
885
+ } catch {
886
+ this.liveFallbackImg();
887
+ return;
888
+ }
889
+ sb.mode = "segments";
890
+ sb.addEventListener("updateend", () => {
891
+ if (Date.now() - L.lastTrim > 1e4) {
892
+ L.lastTrim = Date.now();
893
+ this.liveTrim();
894
+ }
895
+ this.liveAppend();
896
+ });
897
+ sb.addEventListener("error", () => this.liveRestart());
898
+ L.sb = sb;
899
+ L.abort = new AbortController();
900
+ fetch(this.api.url(`api/livemse?camera=${encodeURIComponent(this.camId)}`), { credentials: "same-origin", signal: L.abort.signal }).then((r) => {
901
+ if (!r.ok || !r.body) throw new Error(String(r.status));
902
+ const rd = r.body.getReader();
903
+ const loop = () => {
904
+ rd.read().then((x) => {
905
+ if (!L.active || L.ms !== ms) return;
906
+ if (x.done) {
907
+ this.liveRestart();
908
+ return;
909
+ }
910
+ L.queue.push(x.value);
911
+ this.liveAppend();
912
+ loop();
913
+ }).catch(() => {
914
+ if (L.active && L.ms === ms) this.liveRestart();
915
+ });
916
+ };
917
+ loop();
918
+ }).catch(() => {
919
+ if (L.active && L.ms === ms) this.liveFallbackImg();
920
+ });
921
+ });
922
+ try {
923
+ this.v.srcObject = null;
924
+ } catch {
925
+ }
926
+ this.v.src = u;
927
+ this.v.playbackRate = 1;
928
+ this.v.muted = true;
929
+ this.safePlay();
930
+ }
931
+ liveFallbackImg() {
932
+ this.liveTeardown();
933
+ if (!this.live) return;
934
+ try {
935
+ this.v.pause();
936
+ } catch {
937
+ }
938
+ this.freezeHide();
939
+ this.transport = "mjpeg";
940
+ this.setLabel("liveMjpeg");
941
+ this.setMjpeg(true);
942
+ this.img.src = this.api.url(`api/live?camera=${encodeURIComponent(this.camId)}`) + `&_=${Date.now()}`;
943
+ }
944
+ // ---- RECORDED via relay -----------------------------------------------------------------
945
+ recWebrtcOk() {
946
+ return !this.recWebrtcDisabled && !!(window.RTCPeerConnection && window.WebSocket);
947
+ }
948
+ recWebrtcTeardown() {
949
+ this.posterUntilSeek = false;
950
+ this.stopRelayPoll();
951
+ this.rw?.stop();
952
+ this.rw = void 0;
953
+ this.rwBase = null;
954
+ this.rwPosTs = null;
955
+ this.rwScrub = false;
956
+ this.rwSeekBusy = false;
957
+ this.rwPending = null;
958
+ this.rwLastSeekTs = null;
959
+ this.rwSrate = 1;
960
+ this.rwRate = 1;
961
+ this.rwRateBusy = false;
962
+ this.rwPendingRate = null;
963
+ }
964
+ recWebrtcStart(ts) {
965
+ if (this.destroyed) return;
966
+ this.v.onloadedmetadata = null;
967
+ this.freezeShow(true);
968
+ this.posterShow(ts);
969
+ this.live = false;
970
+ this.recWebrtcTeardown();
971
+ this.webrtcTeardown();
972
+ this.mseTeardown();
973
+ this.liveTeardown();
974
+ try {
975
+ this.v.pause();
976
+ } catch {
977
+ }
978
+ try {
979
+ this.v.removeAttribute("src");
980
+ this.v.srcObject = null;
981
+ } catch {
982
+ }
983
+ this.setMjpeg(false);
984
+ this.transport = "relay";
985
+ this.setLabel("loading");
986
+ this.rwStartMs = ts;
987
+ this.rwBase = null;
988
+ this.rwRate = this.rate;
989
+ this.rwSrate = 1;
990
+ this.seekTarget = ts;
991
+ const compat = mobileClient();
992
+ if (compat) rlog("rec-compat-start", { ts: Math.round(ts) });
993
+ const s = new WebRtcSession(this.api, { camId: this.camId, mode: "recorded", startMs: ts, compat }, {
994
+ onStream: (ms) => {
995
+ if (this.rw !== s || this.live) return;
996
+ try {
997
+ s.pc?.getReceivers().forEach((r) => {
998
+ try {
999
+ r.jitterBufferTarget = 500;
1000
+ } catch {
1001
+ }
1002
+ try {
1003
+ r.playoutDelayHint = 0.5;
1004
+ } catch {
1005
+ }
1006
+ });
1007
+ } catch {
1008
+ }
1009
+ this.setMjpeg(false);
1010
+ this.v.muted = !this.soundOn || this.rate !== 1;
1011
+ try {
1012
+ this.v.removeAttribute("src");
1013
+ } catch {
1014
+ }
1015
+ try {
1016
+ this.v.srcObject = ms;
1017
+ } catch {
1018
+ }
1019
+ this.fcArm();
1020
+ this.rwBase = null;
1021
+ this.safePlay();
1022
+ this.setLabel("playing");
1023
+ },
1024
+ onFail: () => {
1025
+ if (this.rw === s) this.recFallbackMse(ts);
1026
+ },
1027
+ onSessionId: () => {
1028
+ if (this.rw === s && this.rwPending) {
1029
+ const p = this.rwPending;
1030
+ this.rwPending = null;
1031
+ if (Math.abs(p.ts - this.rwStartMs) > 1500) this.recRelaySeek(p.ts, p.rate, p.srate);
1032
+ }
1033
+ }
1034
+ });
1035
+ this.rw = s;
1036
+ s.start();
1037
+ this.startRelayPoll();
1038
+ this.emit();
1039
+ }
1040
+ /** Relay failed: retry the relay up to twice (transient WS/ICE hiccups), only then fall back to MSE for the rest of this camera. */
1041
+ recFallbackMse(ts) {
1042
+ this.recWebrtcTeardown();
1043
+ if (this.live || this.destroyed) return;
1044
+ this.recoveries++;
1045
+ if (this.recoveries <= 2) {
1046
+ rlog("relay-retry", { n: this.recoveries });
1047
+ this.recWebrtcStart(ts);
1048
+ return;
1049
+ }
1050
+ rlog("rec-fallback-mse", { mseOk: this.mseSupported(), after: this.recoveries });
1051
+ this.recWebrtcDisabled = true;
1052
+ this.playAt(ts, {});
1053
+ }
1054
+ /** Hard server-side seek, coalesced: one in flight, latest wins, 150 ms floor. */
1055
+ recRelaySeek(ts, rate = 1, srate = 1) {
1056
+ const s = this.rw;
1057
+ if (!s?.id) return;
1058
+ if (this.rwSeekBusy) {
1059
+ this.rwPending = { ts, rate, srate };
1060
+ return;
1061
+ }
1062
+ if (this.rwLastSeekTs === ts && this.rwRate === rate && this.rwSrate === srate && Date.now() - this.rwLastSeekAt < 1e3) return;
1063
+ const wait = 150 - (Date.now() - this.rwLastSeekAt);
1064
+ if (wait > 0) {
1065
+ this.rwSeekBusy = true;
1066
+ this.rwPending = { ts, rate, srate };
1067
+ window.setTimeout(() => {
1068
+ this.rwSeekBusy = false;
1069
+ const p = this.rwPending;
1070
+ this.rwPending = null;
1071
+ if (p && this.rw?.id) this.recRelaySeek(p.ts, p.rate, p.srate);
1072
+ }, wait);
1073
+ return;
1074
+ }
1075
+ this.rwStartMs = ts;
1076
+ this.rwSrate = srate;
1077
+ this.rwRate = this.rwScrub ? srate : rate;
1078
+ this.rwPendingRate = null;
1079
+ this.rwLastSeekTs = ts;
1080
+ this.rwLastSeekAt = Date.now();
1081
+ this.cad.lastNew = Date.now();
1082
+ this.wdLastCt = -1;
1083
+ this.wdLastAt = Date.now();
1084
+ this.wdGrace = Date.now() + 5e3;
1085
+ this.rwPosTs = ts;
1086
+ this.rwPosAt = Date.now();
1087
+ this.setLabel("loading");
1088
+ this.rwSeekBusy = true;
1089
+ this.seekTarget = ts;
1090
+ this.seekAt = Date.now();
1091
+ this.cmdSeq++;
1092
+ const done = (ok) => {
1093
+ this.rwSeekBusy = false;
1094
+ if (!ok) {
1095
+ this.relayRecover();
1096
+ return;
1097
+ }
1098
+ const p = this.rwPending;
1099
+ this.rwPending = null;
1100
+ if (p && this.rw?.id) this.recRelaySeek(p.ts, p.rate, p.srate);
1101
+ };
1102
+ this.api.control(`api/relay-seek?session=${encodeURIComponent(s.id)}&start=${Math.round(ts)}&rate=${rate}&srate=${srate}`).then((ok) => done(ok));
1103
+ }
1104
+ /** Scrub time-lapse rate, coalesced (120 ms floor, 15 % hysteresis). */
1105
+ recRelayRate(r) {
1106
+ const s = this.rw;
1107
+ if (!s?.active || !s.id || !this.rwScrub) return;
1108
+ if (this.rwRateBusy) {
1109
+ this.rwPendingRate = r;
1110
+ return;
1111
+ }
1112
+ if (this.rwSrate === r) return;
1113
+ if (this.rwSrate !== 1 && r > 0 === this.rwSrate > 0 && Math.abs(r - this.rwSrate) < 0.15 * Math.abs(this.rwSrate)) return;
1114
+ const wait = 120 - (Date.now() - this.rwLastRateAt);
1115
+ if (wait > 0) {
1116
+ this.rwRateBusy = true;
1117
+ this.rwPendingRate = r;
1118
+ window.setTimeout(() => {
1119
+ this.rwRateBusy = false;
1120
+ const p = this.rwPendingRate;
1121
+ this.rwPendingRate = null;
1122
+ if (p != null && this.rw?.id) this.recRelayRate(p);
1123
+ }, wait);
1124
+ return;
1125
+ }
1126
+ const c = this.currentTs();
1127
+ this.rwSrate = r;
1128
+ this.rwRate = r;
1129
+ this.rwLastRateAt = Date.now();
1130
+ this.cmdSeq++;
1131
+ if (c != null) {
1132
+ this.rwPosTs = c;
1133
+ this.rwPosAt = Date.now();
1134
+ }
1135
+ this.wdGrace = Date.now() + 8e3;
1136
+ this.cad.lastNew = Date.now();
1137
+ this.rwRateBusy = true;
1138
+ this.api.control(`api/relay-rate?session=${encodeURIComponent(s.id)}&rate=${r}`).then((ok) => {
1139
+ if (!ok) this.relayRecover();
1140
+ }).then(() => {
1141
+ this.rwRateBusy = false;
1142
+ const p = this.rwPendingRate;
1143
+ this.rwPendingRate = null;
1144
+ if (p != null && this.rw?.id && p !== this.rwSrate) this.recRelayRate(p);
1145
+ });
1146
+ }
1147
+ recRelayScrub(on) {
1148
+ const s = this.rw;
1149
+ if (!s?.active || !s.id || this.rwScrub === on) return;
1150
+ this.rwScrub = on;
1151
+ this.cmdSeq++;
1152
+ if (!on) {
1153
+ const c = this.currentTs();
1154
+ this.rwSrate = 1;
1155
+ this.rwRate = this.rate;
1156
+ this.rwPendingRate = null;
1157
+ if (c != null) {
1158
+ this.rwPosTs = c;
1159
+ this.rwPosAt = Date.now();
1160
+ }
1161
+ }
1162
+ this.wdLastCt = -1;
1163
+ this.wdLastAt = Date.now();
1164
+ this.wdGrace = Date.now() + 5e3;
1165
+ this.cad.lastNew = Date.now();
1166
+ this.api.control(`api/relay-scrub?session=${encodeURIComponent(s.id)}&on=${on ? 1 : 0}`).then((ok) => {
1167
+ if (!ok) this.relayRecover();
1168
+ });
1169
+ }
1170
+ relayRecover() {
1171
+ if (!this.rw?.active) return;
1172
+ const t = this.rwPosTs ?? this.rwStartMs;
1173
+ this.recoveries++;
1174
+ rlog("relay-recover", { n: this.recoveries });
1175
+ if (this.recoveries > 2) {
1176
+ this.recoveries--;
1177
+ this.recFallbackMse(t);
1178
+ return;
1179
+ }
1180
+ this.recWebrtcStart(t);
1181
+ }
1182
+ startRelayPoll() {
1183
+ if (this.relayPoll) return;
1184
+ this.cadStart();
1185
+ this.wdLastCt = -1;
1186
+ this.wdLastAt = Date.now();
1187
+ this.wdDead = 0;
1188
+ this.wdGrace = Date.now() + 8e3;
1189
+ this.relayPoll = window.setInterval(() => {
1190
+ const s = this.rw;
1191
+ const v = this.v;
1192
+ if (!s?.active || !s.id) return;
1193
+ const q = this.presentedFrames();
1194
+ if (v.paused && !this.recPaused && !document.hidden) {
1195
+ if (!this.wdResumeLogged) {
1196
+ this.wdResumeLogged = true;
1197
+ rlog("auto-resume", { rs: v.readyState });
1198
+ }
1199
+ this.safePlay();
1200
+ } else if (!v.paused) this.wdResumeLogged = false;
1201
+ if (!v.paused && !document.hidden && this.rwBase != null) {
1202
+ if (q !== this.wdLastCt) {
1203
+ this.wdLastCt = q;
1204
+ this.wdLastAt = Date.now();
1205
+ this.recoveries = 0;
1206
+ if (!this.posterUntilSeek) this.freezeHide();
1207
+ if (this.label === "loading") this.setLabel("playing");
1208
+ } else if (this.rwScrub) this.wdLastAt = Date.now();
1209
+ else if (Date.now() - this.wdLastAt > 4e3 && Date.now() > this.wdGrace) {
1210
+ this.wdLastAt = Date.now();
1211
+ const o = { ct: Math.round(v.currentTime * 10) / 10, paused: v.paused, muted: v.muted, rs: v.readyState, pf: q, w: v.videoWidth };
1212
+ try {
1213
+ s.pc?.getStats().then((st) => {
1214
+ st.forEach((r) => {
1215
+ if (r.type === "inbound-rtp" && (r.kind || r.mediaType) === "video") {
1216
+ o.recv = r.framesReceived;
1217
+ o.dec = r.framesDecoded;
1218
+ o.drop = r.framesDropped;
1219
+ o.pli = r.pliCount;
1220
+ }
1221
+ });
1222
+ rlog("stall-snap", o);
1223
+ }).catch(() => {
1224
+ });
1225
+ } catch {
1226
+ }
1227
+ this.relayRecover();
1228
+ return;
1229
+ }
1230
+ } else {
1231
+ this.wdLastCt = q;
1232
+ this.wdLastAt = Date.now();
1233
+ }
1234
+ const seq = this.cmdSeq;
1235
+ fetch(this.api.url(`api/relay-pos?session=${encodeURIComponent(s.id)}`), { cache: "no-store" }).then((r) => r.json()).then((d) => {
1236
+ if (seq !== this.cmdSeq) return;
1237
+ if (d && d.t > 0 && Date.now() - this.seekAt < 2500 && Math.abs(d.t - this.seekTarget) > 5e3) return;
1238
+ if (d && d.t > 0) {
1239
+ this.wdDead = 0;
1240
+ this.rwPosTs = d.t;
1241
+ this.rwPosAt = Date.now();
1242
+ if (this.posterUntilSeek && Math.abs(d.t - this.seekTarget) < 4e3 && !this.rwSeekBusy && !this.rwPending) this.freezeHide();
1243
+ this.emit();
1244
+ } else if (d && d.t <= 0) {
1245
+ if (++this.wdDead >= 3) {
1246
+ this.wdDead = 0;
1247
+ this.relayRecover();
1248
+ }
1249
+ }
1250
+ }).catch(() => {
1251
+ });
1252
+ }, 600);
1253
+ }
1254
+ stopRelayPoll() {
1255
+ this.cadStop();
1256
+ if (this.relayPoll) {
1257
+ clearInterval(this.relayPoll);
1258
+ this.relayPoll = void 0;
1259
+ }
1260
+ }
1261
+ cadStart() {
1262
+ this.cadStop();
1263
+ const C = this.cad;
1264
+ C.last = -1;
1265
+ C.frames0 = -1;
1266
+ C.stalls = 0;
1267
+ C.maxStall = 0;
1268
+ C.gapMax = 0;
1269
+ C.t0 = Date.now();
1270
+ C.t = window.setInterval(() => {
1271
+ if (!this.rw?.active || document.hidden) return;
1272
+ const q = this.presentedFrames(), now = Date.now();
1273
+ if (this.rwScrub) {
1274
+ C.last = q;
1275
+ C.lastNew = now;
1276
+ return;
1277
+ }
1278
+ if (C.frames0 < 0) {
1279
+ C.frames0 = q;
1280
+ C.last = q;
1281
+ C.lastNew = now;
1282
+ return;
1283
+ }
1284
+ if (q === C.frames0 && C.last === C.frames0) {
1285
+ C.lastNew = now;
1286
+ return;
1287
+ }
1288
+ if (q > C.last) {
1289
+ const gap = now - C.lastNew;
1290
+ if (gap > C.gapMax) C.gapMax = gap;
1291
+ if (gap >= 400) {
1292
+ C.stalls++;
1293
+ if (gap > C.maxStall) C.maxStall = gap;
1294
+ }
1295
+ C.last = q;
1296
+ C.lastNew = now;
1297
+ }
1298
+ if (now - C.t0 >= 3e4) {
1299
+ const rep = { sec: Math.round((now - C.t0) / 1e3), frames: C.last - C.frames0, stalls: C.stalls, maxStall: C.maxStall, gapMax: C.gapMax, w: this.v.videoWidth };
1300
+ C.t0 = now;
1301
+ C.frames0 = C.last;
1302
+ C.stalls = 0;
1303
+ C.maxStall = 0;
1304
+ C.gapMax = 0;
1305
+ const pc = this.rw?.pc;
1306
+ if (pc) pc.getStats().then((st) => {
1307
+ st.forEach((r) => {
1308
+ if (r.type === "inbound-rtp" && (r.kind || r.mediaType) === "video") {
1309
+ rep.lost = r.packetsLost;
1310
+ rep.jit = Math.round((r.jitter || 0) * 1e3);
1311
+ rep.recv = r.framesReceived;
1312
+ rep.dec = r.framesDecoded;
1313
+ rep.drop = r.framesDropped;
1314
+ }
1315
+ });
1316
+ rlog("cadence", rep);
1317
+ }).catch(() => rlog("cadence", rep));
1318
+ else rlog("cadence", rep);
1319
+ }
1320
+ }, 100);
1321
+ }
1322
+ cadStop() {
1323
+ if (this.cad.t) {
1324
+ clearInterval(this.cad.t);
1325
+ this.cad.t = 0;
1326
+ }
1327
+ }
1328
+ // ---- playAt: relay first, MSE/native fallback ------------------------------------------------
1329
+ playAt(ts, opts = {}) {
1330
+ if (this.destroyed) return;
1331
+ const idx0 = this.clipIndexFor(ts);
1332
+ if (this.recWebrtcOk()) {
1333
+ this.chaseAbort();
1334
+ if (idx0 < 0) {
1335
+ this.setLabel("noRecording");
1336
+ return;
1337
+ }
1338
+ this.recPaused = false;
1339
+ const t0 = Math.max(ts, this.clips[idx0].startTime);
1340
+ if (this.rw?.active && this.rw.id) this.recRelaySeek(t0, this.rate || 1, opts.srate || 1);
1341
+ else if (this.rw?.active && !this.live) this.rwPending = { ts: t0, rate: this.rate || 1, srate: opts.srate || 1 };
1342
+ else {
1343
+ if (this.live) {
1344
+ this.freezeShow(true);
1345
+ this.exitLiveState();
1346
+ }
1347
+ this.recWebrtcStart(t0);
1348
+ }
1349
+ return;
1350
+ }
1351
+ const canChase = !opts.noChase && !this.live && this.M.active && !this.recPaused && this.currentTs() != null && idx0 >= 0;
1352
+ this.chaseAbort();
1353
+ if (canChase && !opts.scrub) {
1354
+ this.startChase(ts);
1355
+ return;
1356
+ }
1357
+ if (idx0 < 0) {
1358
+ this.setLabel("noRecording");
1359
+ return;
1360
+ }
1361
+ if (this.live) {
1362
+ this.freezeShow(true);
1363
+ this.exitLiveState();
1364
+ }
1365
+ this.recPaused = false;
1366
+ const clip = this.clips[idx0];
1367
+ if (ts < clip.startTime) ts = clip.startTime;
1368
+ this.playIndex = idx0;
1369
+ this.v.muted = opts.scrub ? true : !this.soundOn;
1370
+ if (this.mseSupported()) {
1371
+ const t = (ts - this.M.base) / 1e3;
1372
+ if (this.M.active && t >= 0 && (this.bufferedContains(t) || t <= this.M.end + 0.5 && this.M.end - t < 95)) {
1373
+ try {
1374
+ this.v.currentTime = t;
1375
+ } catch {
1376
+ }
1377
+ if (this.v.paused) this.safePlay();
1378
+ this.feed();
1379
+ } else {
1380
+ if (opts.scrub && Date.now() - this.lastLoad < 200) {
1381
+ this.pendingTs = ts;
1382
+ return;
1383
+ }
1384
+ this.lastLoad = Date.now();
1385
+ this.mseStart(idx0, (ts - clip.startTime) / 1e3);
1386
+ }
1387
+ } else {
1388
+ const off = Math.min(Math.max((ts - clip.startTime) / 1e3, 0), (clip.duration || 0) / 1e3);
1389
+ if (clip.id === this.curClipId && this.v.src) {
1390
+ try {
1391
+ this.v.currentTime = off;
1392
+ } catch {
1393
+ }
1394
+ if (this.v.paused) this.safePlay();
1395
+ } else {
1396
+ if (opts.scrub && Date.now() - this.lastLoad < 120) {
1397
+ this.pendingTs = ts;
1398
+ return;
1399
+ }
1400
+ this.freezeShow();
1401
+ this.lastLoad = Date.now();
1402
+ this.curClipId = clip.id;
1403
+ this.transport = "native";
1404
+ rlog("native-fallback", { clip: clip.id });
1405
+ this.v.src = this.api.url(`api/segment?id=${encodeURIComponent(clip.videoId || clip.id)}`);
1406
+ this.v.load();
1407
+ this.v.onloadedmetadata = () => {
1408
+ this.v.playbackRate = this.rate;
1409
+ try {
1410
+ this.v.currentTime = off;
1411
+ } catch {
1412
+ }
1413
+ this.safePlay();
1414
+ };
1415
+ }
1416
+ }
1417
+ this.setLabel(opts.scrub ? "scrub" : "playing");
1418
+ }
1419
+ // ---- MSE recorded ------------------------------------------------------------------------
1420
+ mseSupported() {
1421
+ try {
1422
+ return !!(this.api.corsMedia && MSCls && this.codecs && MSCls.isTypeSupported(`video/mp4; codecs="${this.codecs}"`));
1423
+ } catch {
1424
+ return false;
1425
+ }
1426
+ }
1427
+ mseTeardown() {
1428
+ const M = this.M;
1429
+ M.active = false;
1430
+ M.nextIdx = -1;
1431
+ M.feeding = false;
1432
+ M.end = 0;
1433
+ M.pendingSeek = null;
1434
+ M.q = [];
1435
+ M.segFirst = false;
1436
+ try {
1437
+ M.abort?.abort();
1438
+ } catch {
1439
+ }
1440
+ M.abort = null;
1441
+ if (M.sb && M.ms && M.ms.readyState === "open") {
1442
+ try {
1443
+ M.sb.abort();
1444
+ } catch {
1445
+ }
1446
+ }
1447
+ M.sb = null;
1448
+ M.ms = null;
1449
+ }
1450
+ bufferedContains(t) {
1451
+ try {
1452
+ const b = this.v.buffered;
1453
+ for (let i = 0; i < b.length; i++) if (t >= b.start(i) - 0.3 && t <= b.end(i) + 0.3) return true;
1454
+ } catch {
1455
+ }
1456
+ return false;
1457
+ }
1458
+ mseStart(idx, offSec) {
1459
+ if (this.destroyed) return;
1460
+ this.v.onloadedmetadata = null;
1461
+ this.freezeShow();
1462
+ this.mseTeardown();
1463
+ const M = this.M;
1464
+ const ms = new MSCls();
1465
+ M.ms = ms;
1466
+ M.active = true;
1467
+ M.base = this.clips[idx].startTime;
1468
+ M.nextIdx = idx;
1469
+ M.end = 0;
1470
+ M.mmsGo = true;
1471
+ this.transport = "mse";
1472
+ if (window.ManagedMediaSource && ms instanceof window.ManagedMediaSource) {
1473
+ try {
1474
+ this.v.disableRemotePlayback = true;
1475
+ } catch {
1476
+ }
1477
+ ms.addEventListener("startstreaming", () => {
1478
+ M.mmsGo = true;
1479
+ this.feed();
1480
+ });
1481
+ ms.addEventListener("endstreaming", () => {
1482
+ M.mmsGo = false;
1483
+ });
1484
+ }
1485
+ M.pendingSeek = offSec;
1486
+ const u = URL.createObjectURL(ms);
1487
+ ms.addEventListener("sourceopen", () => {
1488
+ URL.revokeObjectURL(u);
1489
+ if (M.ms !== ms) return;
1490
+ let sb;
1491
+ try {
1492
+ sb = ms.addSourceBuffer(`video/mp4; codecs="${this.codecs}"`);
1493
+ } catch {
1494
+ this.codecs = null;
1495
+ M.active = false;
1496
+ return;
1497
+ }
1498
+ sb.mode = "segments";
1499
+ sb.addEventListener("updateend", () => {
1500
+ if (M.pendingSeek != null && this.v.readyState >= 1) {
1501
+ const t0 = M.pendingSeek;
1502
+ M.pendingSeek = null;
1503
+ try {
1504
+ this.v.currentTime = t0;
1505
+ } catch {
1506
+ }
1507
+ }
1508
+ this.drain();
1509
+ if (!M.feeding && !M.q.length) this.feed();
1510
+ });
1511
+ sb.addEventListener("error", () => {
1512
+ M.active = false;
1513
+ });
1514
+ M.sb = sb;
1515
+ try {
1516
+ this.v.currentTime = offSec;
1517
+ } catch {
1518
+ }
1519
+ this.feed();
1520
+ });
1521
+ try {
1522
+ this.v.srcObject = null;
1523
+ } catch {
1524
+ }
1525
+ this.v.src = u;
1526
+ this.v.playbackRate = this.rate;
1527
+ this.safePlay();
1528
+ }
1529
+ drain() {
1530
+ const M = this.M;
1531
+ if (!M.active || !M.sb || M.sb.updating || !M.q.length) return;
1532
+ if (M.segFirst) {
1533
+ M.segFirst = false;
1534
+ try {
1535
+ M.sb.timestampOffset = M.segOff;
1536
+ } catch {
1537
+ try {
1538
+ M.sb.abort();
1539
+ M.sb.timestampOffset = M.segOff;
1540
+ } catch {
1541
+ M.active = false;
1542
+ return;
1543
+ }
1544
+ }
1545
+ }
1546
+ const buf = M.q.shift();
1547
+ try {
1548
+ M.sb.appendBuffer(buf);
1549
+ } catch {
1550
+ try {
1551
+ M.sb.abort();
1552
+ M.sb.appendBuffer(buf);
1553
+ } catch {
1554
+ M.active = false;
1555
+ }
1556
+ }
1557
+ }
1558
+ feed() {
1559
+ const M = this.M;
1560
+ if (!M.active || M.feeding) return;
1561
+ if (M.mmsGo === false) return;
1562
+ if (M.nextIdx < 0 || M.nextIdx >= this.clips.length) return;
1563
+ if (M.end - this.v.currentTime > 90) return;
1564
+ try {
1565
+ const b = this.v.buffered;
1566
+ if (b.length && this.v.currentTime - b.start(0) > 240 && M.sb && !M.sb.updating && !M.q.length) {
1567
+ M.sb.remove(0, this.v.currentTime - 120);
1568
+ return;
1569
+ }
1570
+ } catch {
1571
+ }
1572
+ const clip = this.clips[M.nextIdx], ms = M.ms;
1573
+ M.feeding = true;
1574
+ M.segFirst = true;
1575
+ M.segOff = (clip.startTime - M.base) / 1e3;
1576
+ M.abort = new AbortController();
1577
+ fetch(this.api.url(`api/segment?id=${encodeURIComponent(clip.videoId || clip.id)}`), { credentials: "same-origin", signal: M.abort.signal }).then((r) => {
1578
+ if (!r.ok || !r.body) throw new Error(String(r.status));
1579
+ const rd = r.body.getReader();
1580
+ const loop = () => {
1581
+ rd.read().then((x) => {
1582
+ if (M.ms !== ms || !M.active) return;
1583
+ if (x.done) {
1584
+ M.feeding = false;
1585
+ M.nextIdx++;
1586
+ M.end = M.segOff + (clip.duration || 6e4) / 1e3;
1587
+ if (!M.q.length) this.feed();
1588
+ return;
1589
+ }
1590
+ M.q.push(x.value);
1591
+ this.drain();
1592
+ loop();
1593
+ }).catch(() => {
1594
+ if (M.ms === ms) M.feeding = false;
1595
+ });
1596
+ };
1597
+ loop();
1598
+ }).catch(() => {
1599
+ if (M.ms !== ms) return;
1600
+ M.feeding = false;
1601
+ M.nextIdx++;
1602
+ this.feed();
1603
+ });
1604
+ }
1605
+ handleStall() {
1606
+ if (this.live || !this.M.active || this.v.paused) return;
1607
+ const t = this.v.currentTime;
1608
+ try {
1609
+ const b = this.v.buffered;
1610
+ for (let i = 0; i < b.length; i++) if (b.start(i) > t && b.start(i) - t < 60) {
1611
+ this.v.currentTime = b.start(i) + 0.05;
1612
+ return;
1613
+ }
1614
+ } catch {
1615
+ }
1616
+ if (this.M.nextIdx >= this.clips.length) this.opts.onClipsRefresh().then((c) => {
1617
+ const cur = this.clips[this.M.nextIdx - 1];
1618
+ this.clips = c;
1619
+ if (cur) {
1620
+ const i = c.findIndex((x) => x.id === cur.id);
1621
+ if (i >= 0) this.M.nextIdx = i + 1;
1622
+ }
1623
+ this.feed();
1624
+ }).catch(() => {
1625
+ });
1626
+ else this.feed();
1627
+ }
1628
+ // trick-play chase inside the MSE buffer
1629
+ chaseAbort() {
1630
+ if (!this.CH.active) return;
1631
+ this.CH.active = false;
1632
+ if (this.CH.timer) {
1633
+ clearInterval(this.CH.timer);
1634
+ this.CH.timer = 0;
1635
+ }
1636
+ this.v.playbackRate = this.rate;
1637
+ this.v.muted = !this.soundOn;
1638
+ }
1639
+ endChase() {
1640
+ const tgt = this.CH.target;
1641
+ this.chaseAbort();
1642
+ try {
1643
+ this.v.currentTime = (tgt - this.M.base) / 1e3;
1644
+ } catch {
1645
+ }
1646
+ this.setLabel("playing");
1647
+ if (this.v.paused) this.safePlay();
1648
+ }
1649
+ startChase(target) {
1650
+ this.chaseAbort();
1651
+ this.freezeHide();
1652
+ this.CH.active = true;
1653
+ this.CH.target = target;
1654
+ try {
1655
+ this.v.pause();
1656
+ } catch {
1657
+ }
1658
+ this.v.muted = true;
1659
+ this.setLabel("scrub");
1660
+ this.CH.timer = window.setInterval(() => {
1661
+ if (!this.CH.active) return;
1662
+ const c = this.currentTs();
1663
+ if (c == null) {
1664
+ this.endChase();
1665
+ return;
1666
+ }
1667
+ const rem = this.CH.target - c;
1668
+ if (Math.abs(rem) <= 250) {
1669
+ this.endChase();
1670
+ return;
1671
+ }
1672
+ let step = rem * 0.2;
1673
+ if (Math.abs(step) < 180) step = rem > 0 ? 180 : -180;
1674
+ const nt = c + step, tt = (nt - this.M.base) / 1e3;
1675
+ if (this.M.active && this.bufferedContains(tt)) {
1676
+ try {
1677
+ this.v.currentTime = tt;
1678
+ } catch {
1679
+ }
1680
+ this.feed();
1681
+ } else {
1682
+ this.endChase();
1683
+ this.playAt(this.CH.target, { noChase: true });
1684
+ }
1685
+ }, 50);
1686
+ }
1687
+ // ---- controls -----------------------------------------------------------------------------
1688
+ togglePlayPause() {
1689
+ if (this.live) return;
1690
+ if (this.CH.active) {
1691
+ this.chaseAbort();
1692
+ try {
1693
+ this.v.pause();
1694
+ } catch {
1695
+ }
1696
+ this.emit();
1697
+ return;
1698
+ }
1699
+ if (this.recPaused) {
1700
+ this.recPaused = false;
1701
+ const t = this.recPausedTs ?? (this.currentTs() ?? Date.now() - 1e3);
1702
+ this.playAt(t, {});
1703
+ return;
1704
+ }
1705
+ if (this.rw?.active) {
1706
+ this.recPausedTs = this.currentTs();
1707
+ this.freezeShow();
1708
+ if (this.freezeT) {
1709
+ clearTimeout(this.freezeT);
1710
+ this.freezeT = 0;
1711
+ }
1712
+ this.recWebrtcTeardown();
1713
+ try {
1714
+ this.v.pause();
1715
+ } catch {
1716
+ }
1717
+ this.recPaused = true;
1718
+ this.transport = "none";
1719
+ this.setLabel("paused");
1720
+ return;
1721
+ }
1722
+ if (this.v.paused) this.safePlay();
1723
+ else this.v.pause();
1724
+ }
1725
+ skip(ms) {
1726
+ const ts = this.live ? Date.now() + ms : (this.currentTs() ?? Date.now()) + ms;
1727
+ if (this.live && ms > 0) return;
1728
+ this.playAt(ts, {});
1729
+ }
1730
+ cycleSpeed() {
1731
+ if (this.live) return this.rate;
1732
+ const rates = [1, 2, 4, 8];
1733
+ this.rate = rates[(rates.indexOf(this.rate) + 1) % rates.length] ?? 1;
1734
+ if (this.rw?.active && this.rw.id) {
1735
+ const c = this.currentTs();
1736
+ this.recRelaySeek(c ?? this.rwStartMs, this.rate);
1737
+ this.v.muted = !this.soundOn || this.rate !== 1;
1738
+ } else this.v.playbackRate = this.rate;
1739
+ this.emit();
1740
+ return this.rate;
1741
+ }
1742
+ setSound(on) {
1743
+ this.soundOn = on;
1744
+ this.v.muted = !on || !!this.rw?.active && this.rate !== 1;
1745
+ if (on && this.v.paused && !this.recPaused) this.safePlay();
1746
+ this.emit();
1747
+ }
1748
+ snapshot() {
1749
+ try {
1750
+ const src = this.live && !this.img.classList.contains("hidden") ? this.img : this.v;
1751
+ const w = src.videoWidth || src.naturalWidth || 1280, h = src.videoHeight || src.naturalHeight || 720;
1752
+ const cv = document.createElement("canvas");
1753
+ cv.width = w;
1754
+ cv.height = h;
1755
+ cv.getContext("2d").drawImage(src, 0, 0, w, h);
1756
+ cv.toBlob((b) => {
1757
+ if (!b) return;
1758
+ const a = document.createElement("a");
1759
+ a.href = URL.createObjectURL(b);
1760
+ const ts = this.currentTs() ?? Date.now();
1761
+ const d = new Date(ts);
1762
+ a.download = `${(this.camName || "snapshot").replace(/[^\w.-]+/g, "_")}_${String(d.getHours()).padStart(2, "0")}${String(d.getMinutes()).padStart(2, "0")}${String(d.getSeconds()).padStart(2, "0")}.jpg`;
1763
+ document.body.appendChild(a);
1764
+ a.click();
1765
+ a.remove();
1766
+ setTimeout(() => URL.revokeObjectURL(a.href), 4e3);
1767
+ }, "image/jpeg", 0.92);
1768
+ } catch {
1769
+ }
1770
+ }
1771
+ capLog(tag, extra) {
1772
+ try {
1773
+ const v = this.v, st = this.stage;
1774
+ rlog(tag, { fsReq: !!st.requestFullscreen, wkFs: !!st.webkitRequestFullscreen, vEnter: !!v.webkitEnterFullscreen, pipReq: !!v.requestPictureInPicture, wkPip: !!(v.webkitSupportsPresentationMode && v.webkitSupportsPresentationMode("picture-in-picture")), rs: v.readyState, vw: v.videoWidth, ...extra || {} });
1775
+ } catch {
1776
+ }
1777
+ }
1778
+ pip() {
1779
+ const v = this.v;
1780
+ this.capLog("pip-btn");
1781
+ try {
1782
+ if (document.pictureInPictureElement || v.webkitPresentationMode === "picture-in-picture") {
1783
+ if (document.pictureInPictureElement) document.exitPictureInPicture().catch(() => {
1784
+ });
1785
+ else v.webkitSetPresentationMode("inline");
1786
+ return;
1787
+ }
1788
+ if (this.v.classList.contains("hidden")) return;
1789
+ const wk = () => {
1790
+ try {
1791
+ if (v.webkitSupportsPresentationMode && v.webkitSupportsPresentationMode("picture-in-picture")) v.webkitSetPresentationMode("picture-in-picture");
1792
+ else this.capLog("pip-unsupported");
1793
+ } catch (e) {
1794
+ this.capLog("pip-fail", { e: String(e?.name || e) });
1795
+ }
1796
+ };
1797
+ if (v.requestPictureInPicture) v.requestPictureInPicture().catch((e) => {
1798
+ this.capLog("pip-fail", { e: String(e?.name || e) });
1799
+ wk();
1800
+ });
1801
+ else wk();
1802
+ } catch (e) {
1803
+ this.capLog("pip-fail", { e: String(e?.name || e) });
1804
+ }
1805
+ }
1806
+ fullscreen() {
1807
+ const st = this.stage, v = this.v, d = document;
1808
+ this.capLog("fs-btn");
1809
+ try {
1810
+ if (d.fullscreenElement || d.webkitFullscreenElement) {
1811
+ (d.exitFullscreen || d.webkitExitFullscreen).call(d);
1812
+ return;
1813
+ }
1814
+ if (st.requestFullscreen) st.requestFullscreen().catch((e) => this.capLog("fs-fail", { e: String(e?.name || e) }));
1815
+ else if (st.webkitRequestFullscreen) st.webkitRequestFullscreen();
1816
+ else if (v.webkitEnterFullscreen && !this.v.classList.contains("hidden")) v.webkitEnterFullscreen();
1817
+ else this.capLog("fs-unsupported");
1818
+ } catch (e) {
1819
+ this.capLog("fs-fail", { e: String(e?.name || e) });
1820
+ }
1821
+ }
1822
+ // ---- scrub (timeline gesture) ------------------------------------------------------------
1823
+ /** first gesture: scrub profile on (relay); MSE: freeze + pause */
1824
+ scrubBegin() {
1825
+ this.chaseAbort();
1826
+ if (!this.rw?.active) {
1827
+ this.freezeShow();
1828
+ if (!this.live) {
1829
+ try {
1830
+ this.v.pause();
1831
+ } catch {
1832
+ }
1833
+ }
1834
+ }
1835
+ this.recRelayScrub(true);
1836
+ }
1837
+ /** scroll position + velocity (timeline-ms per wall-s) while the gesture runs */
1838
+ scrubMove(_centerTs, vel, smoothTs) {
1839
+ if (!this.rw?.active) {
1840
+ this.freezeHold();
1841
+ return;
1842
+ }
1843
+ if (!this.rw.id) return;
1844
+ let r = vel / 1e3;
1845
+ if (Math.abs(r) < 0.1) return;
1846
+ r = Math.min(3e3, Math.max(-3e3, r));
1847
+ r = Math.abs(r) >= 10 ? Math.round(r) : Math.round(r * 10) / 10;
1848
+ const tgt = this.clampRange(smoothTs), cur = this.currentTs();
1849
+ const drift = cur == null ? null : tgt - cur;
1850
+ if (drift == null || Math.abs(drift) > Math.max(4500, 1200 * Math.abs(r))) this.scrubSeek(tgt, r);
1851
+ else this.recRelayRate(r);
1852
+ }
1853
+ /** hold / release: land exactly on the centre at 1× (or go live near now) */
1854
+ scrubSeek(ts, srate = 1) {
1855
+ if (this.nearNow(ts)) {
1856
+ this.goLive();
1857
+ return;
1858
+ }
1859
+ this.playAt(this.clampRange(ts), { scrub: true, srate });
1860
+ }
1861
+ /** gesture settled → normal profile, base rate */
1862
+ scrubIdle() {
1863
+ this.recRelayScrub(false);
1864
+ }
1865
+ // ---- visibility ---------------------------------------------------------------------------
1866
+ hiddenTs = null;
1867
+ onVisibility() {
1868
+ if (document.visibilityState === "hidden") {
1869
+ if (this.live) {
1870
+ this.hiddenTs = null;
1871
+ this.webrtcTeardown();
1872
+ this.liveTeardown();
1873
+ if (this.transport === "mjpeg") this.img.removeAttribute("src");
1874
+ } else if (this.rw?.active) {
1875
+ this.hiddenTs = this.currentTs();
1876
+ this.freezeShow(true);
1877
+ this.recWebrtcTeardown();
1878
+ }
1879
+ } else {
1880
+ if (this.live) this.goLive();
1881
+ else if (this.hiddenTs != null && !this.recPaused) {
1882
+ const t = this.hiddenTs;
1883
+ this.hiddenTs = null;
1884
+ this.playAt(t, {});
1885
+ }
1886
+ }
1887
+ }
1888
+ };
1889
+
1890
+ export {
1891
+ setRlogClient,
1892
+ rlog,
1893
+ mobileClient,
1894
+ WebRtcSession,
1895
+ PlayerController
1896
+ };
1897
+ //# sourceMappingURL=chunk-VHZTAIPQ.js.map