@trillboards/edge-sdk 0.2.211 → 0.2.214
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/deploy/windows/ci/test-alert-window-field.ps1 +252 -0
- package/dist/AlertClips.d.ts +131 -0
- package/dist/AlertClips.d.ts.map +1 -0
- package/dist/AlertClips.js +476 -0
- package/dist/AlertClips.js.map +1 -0
- package/dist/ConnectorStatusClient.d.ts +10 -0
- package/dist/ConnectorStatusClient.d.ts.map +1 -1
- package/dist/ConnectorStatusClient.js +11 -1
- package/dist/ConnectorStatusClient.js.map +1 -1
- package/dist/DetectorFields.d.ts +2 -1
- package/dist/DetectorFields.d.ts.map +1 -1
- package/dist/DetectorFields.js +6 -5
- package/dist/DetectorFields.js.map +1 -1
- package/dist/EdgeAgent.js +1 -1
- package/dist/LocalVideoBuffer.d.ts +59 -0
- package/dist/LocalVideoBuffer.d.ts.map +1 -0
- package/dist/LocalVideoBuffer.js +214 -0
- package/dist/LocalVideoBuffer.js.map +1 -0
- package/dist/NativeReadiness.d.ts.map +1 -1
- package/dist/NativeReadiness.js +2 -1
- package/dist/NativeReadiness.js.map +1 -1
- package/dist/PhoneHeldInHand.d.ts +9 -1
- package/dist/PhoneHeldInHand.d.ts.map +1 -1
- package/dist/PhoneHeldInHand.js +19 -7
- package/dist/PhoneHeldInHand.js.map +1 -1
- package/dist/ScopedVlmReview.d.ts.map +1 -1
- package/dist/ScopedVlmReview.js +5 -1
- package/dist/ScopedVlmReview.js.map +1 -1
- package/dist/SensingProfileClient.d.ts +62 -5
- package/dist/SensingProfileClient.d.ts.map +1 -1
- package/dist/SensingProfileClient.js +76 -1
- package/dist/SensingProfileClient.js.map +1 -1
- package/dist/VideoSegmentUploader.d.ts +169 -5
- package/dist/VideoSegmentUploader.d.ts.map +1 -1
- package/dist/VideoSegmentUploader.js +543 -32
- package/dist/VideoSegmentUploader.js.map +1 -1
- package/dist/autoSense.d.ts.map +1 -1
- package/dist/autoSense.js +4 -0
- package/dist/autoSense.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +3 -0
- package/dist/cli.js.map +1 -1
- package/dist/connectorUpdate.d.ts +9 -0
- package/dist/connectorUpdate.d.ts.map +1 -1
- package/dist/connectorUpdate.js +21 -2
- package/dist/connectorUpdate.js.map +1 -1
- package/dist/diagnose.d.ts +1 -1
- package/dist/diagnose.js +1 -1
- package/dist/localSenseE2eHarness.d.ts +1 -1
- package/dist/localSenseE2eHarness.d.ts.map +1 -1
- package/dist/localSenseE2eHarness.js +7 -4
- package/dist/localSenseE2eHarness.js.map +1 -1
- package/dist/localSensing.d.ts +58 -0
- package/dist/localSensing.d.ts.map +1 -1
- package/dist/localSensing.js +115 -10
- package/dist/localSensing.js.map +1 -1
- package/package.json +5 -5
- package/retained/__tests__/evidence-uploads.test.cjs +130 -0
- package/retained/manager.cjs +2 -0
- package/retained/website-api-capability.cjs +7 -1
|
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
35
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.CctvVideoRecorder = exports.VideoSegmentUploader = exports.defaultBlobPutter = exports.MAX_SEGMENT_BYTES = void 0;
|
|
36
|
+
exports.CctvVideoRecorder = exports.EVENT_CLIPS_DIRNAME = exports.LOCAL_BUFFER_SEGMENT_LABEL = exports.ALERT_BUFFER_SEGMENT_SECONDS = exports.VideoSegmentUploader = exports.defaultBlobPutter = exports.MAX_SEGMENT_BYTES = void 0;
|
|
37
37
|
exports.putTimeoutMs = putTimeoutMs;
|
|
38
38
|
exports.probeMp4File = probeMp4File;
|
|
39
39
|
exports.hashFile = hashFile;
|
|
@@ -42,6 +42,7 @@ exports.hostUploadNetwork = hostUploadNetwork;
|
|
|
42
42
|
exports.__resetHostUploadNetworkForTests = __resetHostUploadNetworkForTests;
|
|
43
43
|
exports.attachCctvVideoRecorder = attachCctvVideoRecorder;
|
|
44
44
|
exports.activeCctvVideoRecorders = activeCctvVideoRecorders;
|
|
45
|
+
exports.videoBufferReportForToken = videoBufferReportForToken;
|
|
45
46
|
exports.__resetCctvVideoRecordersForTests = __resetCctvVideoRecordersForTests;
|
|
46
47
|
const fs = __importStar(require("fs"));
|
|
47
48
|
const http = __importStar(require("http"));
|
|
@@ -52,6 +53,8 @@ const crypto_1 = require("crypto");
|
|
|
52
53
|
const AudienceAnalyzeClient_1 = require("./AudienceAnalyzeClient");
|
|
53
54
|
const enterpriseNetwork_1 = require("./enterpriseNetwork");
|
|
54
55
|
const SensingProfileClient_1 = require("./SensingProfileClient");
|
|
56
|
+
const AlertClips_1 = require("./AlertClips");
|
|
57
|
+
const LocalVideoBuffer_1 = require("./LocalVideoBuffer");
|
|
55
58
|
/** The route's ceiling on one segment: 256 MiB (268,435,456 bytes). */
|
|
56
59
|
exports.MAX_SEGMENT_BYTES = 268435456;
|
|
57
60
|
/** `PUT` budget floor, and the throughput it assumes: max(60 s, 2 x bytes / 125,000 B/s). */
|
|
@@ -563,10 +566,25 @@ function connectorVersion() {
|
|
|
563
566
|
return '';
|
|
564
567
|
}
|
|
565
568
|
}
|
|
569
|
+
/**
|
|
570
|
+
* Every live uploader on the box, so an event clip anywhere holds back every
|
|
571
|
+
* continuous upload everywhere: the alert window goes first on the uplink.
|
|
572
|
+
*/
|
|
573
|
+
const liveUploaders = new Set();
|
|
574
|
+
/**
|
|
575
|
+
* A queued event clip holds continuous uploads back only while it is being
|
|
576
|
+
* delivered or due within this long. One stuck in a long backoff (the server
|
|
577
|
+
* refusing it) must not stop continuous delivery for good.
|
|
578
|
+
*/
|
|
579
|
+
const EVENT_PRIORITY_HORIZON_MS = 5000;
|
|
580
|
+
/** How soon a held-back continuous upload looks again. */
|
|
581
|
+
const EVENT_PRIORITY_RECHECK_MS = 1000;
|
|
566
582
|
class VideoSegmentUploader {
|
|
567
583
|
constructor(options) {
|
|
568
584
|
this.queue = [];
|
|
569
585
|
this.inFlight = null;
|
|
586
|
+
/** dropContinuous ran while a continuous segment was in flight: never queue that one again. */
|
|
587
|
+
this.inFlightContinuousDropped = false;
|
|
570
588
|
this.draining = false;
|
|
571
589
|
this.timer = null;
|
|
572
590
|
this.stopped = false;
|
|
@@ -585,6 +603,9 @@ class VideoSegmentUploader {
|
|
|
585
603
|
lastStatus: null,
|
|
586
604
|
lastError: null,
|
|
587
605
|
lastUploadAtMs: null,
|
|
606
|
+
eventsUploaded: 0,
|
|
607
|
+
eventsQueued: 0,
|
|
608
|
+
heldForEvents: 0,
|
|
588
609
|
};
|
|
589
610
|
if (!options.apiBaseUrl)
|
|
590
611
|
throw new Error('apiBaseUrl is required for VideoSegmentUploader');
|
|
@@ -601,8 +622,27 @@ class VideoSegmentUploader {
|
|
|
601
622
|
this.retryBaseMs = Math.max(0, options.retryBaseMs ?? DEFAULT_RETRY_BASE_MS);
|
|
602
623
|
this.retryMaxMs = Math.max(this.retryBaseMs, options.retryMaxMs ?? DEFAULT_RETRY_MAX_MS);
|
|
603
624
|
this.log = options.log ?? ((level, message) => (level === 'warn' ? console.warn : console.log)(message));
|
|
625
|
+
this.onDone = options.onDone;
|
|
626
|
+
liveUploaders.add(this);
|
|
604
627
|
}
|
|
605
|
-
/**
|
|
628
|
+
/**
|
|
629
|
+
* True while an event clip is being delivered, or is due within the
|
|
630
|
+
* priority horizon, by ANY uploader on the box (this one included).
|
|
631
|
+
*/
|
|
632
|
+
static eventDeliveryActive(nowMs = Date.now()) {
|
|
633
|
+
for (const uploader of liveUploaders)
|
|
634
|
+
if (uploader.hasActiveEvent(nowMs))
|
|
635
|
+
return true;
|
|
636
|
+
return false;
|
|
637
|
+
}
|
|
638
|
+
hasActiveEvent(nowMs) {
|
|
639
|
+
if (this.stopped)
|
|
640
|
+
return false;
|
|
641
|
+
if (this.inFlight && isEvent(this.inFlight.segment))
|
|
642
|
+
return true;
|
|
643
|
+
return this.queue.some((item) => isEvent(item.segment) && item.nextAtMs <= nowMs + EVENT_PRIORITY_HORIZON_MS);
|
|
644
|
+
}
|
|
645
|
+
/** Queue a closed segment. Event clips first, then oldest capture first; a file already queued is ignored. */
|
|
606
646
|
enqueue(segment) {
|
|
607
647
|
if (this.stopped || !segment?.file)
|
|
608
648
|
return;
|
|
@@ -611,7 +651,7 @@ class VideoSegmentUploader {
|
|
|
611
651
|
if (this.queue.some((item) => item.segment.file === segment.file))
|
|
612
652
|
return;
|
|
613
653
|
this.queue.push({ segment, attempts: 0, nextAtMs: this.now(), phase: 'upload' });
|
|
614
|
-
this.
|
|
654
|
+
this.sortQueue();
|
|
615
655
|
this.kick();
|
|
616
656
|
}
|
|
617
657
|
/** The ring deleted this file; stop trying to deliver it. */
|
|
@@ -619,11 +659,33 @@ class VideoSegmentUploader {
|
|
|
619
659
|
const i = this.queue.findIndex((item) => item.segment.file === file);
|
|
620
660
|
if (i < 0)
|
|
621
661
|
return;
|
|
622
|
-
this.queue.splice(i, 1);
|
|
662
|
+
const [item] = this.queue.splice(i, 1);
|
|
623
663
|
this.stats.missing += 1;
|
|
664
|
+
this.done(item.segment, 'missing');
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Stop delivering every queued CONTINUOUS segment: the camera left the paid
|
|
668
|
+
* continuous mode. The files stay where they are (the provider's ring), so
|
|
669
|
+
* they become local buffer; event clips keep their place.
|
|
670
|
+
*/
|
|
671
|
+
dropContinuous() {
|
|
672
|
+
let dropped = 0;
|
|
673
|
+
for (let i = this.queue.length - 1; i >= 0; i -= 1) {
|
|
674
|
+
if (isEvent(this.queue[i].segment))
|
|
675
|
+
continue;
|
|
676
|
+
this.queue.splice(i, 1);
|
|
677
|
+
dropped += 1;
|
|
678
|
+
}
|
|
679
|
+
// The one mid-upload finishes if it can; a failure does not queue it again.
|
|
680
|
+
if (this.inFlight && !isEvent(this.inFlight.segment)) {
|
|
681
|
+
this.inFlightContinuousDropped = true;
|
|
682
|
+
dropped += 1;
|
|
683
|
+
}
|
|
684
|
+
return dropped;
|
|
624
685
|
}
|
|
625
686
|
stop() {
|
|
626
687
|
this.stopped = true;
|
|
688
|
+
liveUploaders.delete(this);
|
|
627
689
|
if (this.timer) {
|
|
628
690
|
clearTimeout(this.timer);
|
|
629
691
|
this.timer = null;
|
|
@@ -636,6 +698,7 @@ class VideoSegmentUploader {
|
|
|
636
698
|
inFlight: this.inFlight !== null,
|
|
637
699
|
rejected: { ...this.stats.rejected },
|
|
638
700
|
failures: { ...this.stats.failures },
|
|
701
|
+
eventsQueued: this.queue.filter((item) => isEvent(item.segment)).length + (this.inFlight && isEvent(this.inFlight.segment) ? 1 : 0),
|
|
639
702
|
};
|
|
640
703
|
}
|
|
641
704
|
/** Deliver every item that is due now, one at a time. Resolves when none is due. */
|
|
@@ -643,16 +706,25 @@ class VideoSegmentUploader {
|
|
|
643
706
|
if (this.draining)
|
|
644
707
|
return;
|
|
645
708
|
this.draining = true;
|
|
709
|
+
let heldUntilMs = null;
|
|
646
710
|
try {
|
|
647
711
|
for (;;) {
|
|
648
712
|
if (this.stopped)
|
|
649
713
|
break;
|
|
650
714
|
const nowMs = this.now();
|
|
715
|
+
// Event clips first (the queue is sorted so), then oldest capture.
|
|
651
716
|
const i = this.queue.findIndex((item) => item.nextAtMs <= nowMs);
|
|
652
717
|
if (i < 0)
|
|
653
718
|
break;
|
|
719
|
+
// An alert window anywhere on the box goes ahead of this continuous segment.
|
|
720
|
+
if (!isEvent(this.queue[i].segment) && VideoSegmentUploader.eventDeliveryActive(nowMs)) {
|
|
721
|
+
this.stats.heldForEvents += 1;
|
|
722
|
+
heldUntilMs = nowMs + EVENT_PRIORITY_RECHECK_MS;
|
|
723
|
+
break;
|
|
724
|
+
}
|
|
654
725
|
const [item] = this.queue.splice(i, 1);
|
|
655
726
|
this.inFlight = item;
|
|
727
|
+
this.inFlightContinuousDropped = false;
|
|
656
728
|
let outcome;
|
|
657
729
|
try {
|
|
658
730
|
outcome = await this.deliver(item);
|
|
@@ -664,23 +736,28 @@ class VideoSegmentUploader {
|
|
|
664
736
|
finally {
|
|
665
737
|
this.inFlight = null;
|
|
666
738
|
}
|
|
667
|
-
|
|
739
|
+
const dropped = this.inFlightContinuousDropped && !isEvent(item.segment);
|
|
740
|
+
this.inFlightContinuousDropped = false;
|
|
741
|
+
if (outcome === 'retry' && !this.stopped && !dropped) {
|
|
668
742
|
item.attempts += 1;
|
|
669
743
|
item.nextAtMs = this.now() + Math.min(this.retryMaxMs, this.retryBaseMs * 2 ** Math.min(item.attempts - 1, 20));
|
|
670
744
|
this.queue.push(item);
|
|
671
|
-
this.
|
|
745
|
+
this.sortQueue();
|
|
672
746
|
}
|
|
673
747
|
}
|
|
674
748
|
}
|
|
675
749
|
finally {
|
|
676
750
|
this.draining = false;
|
|
677
|
-
this.kick();
|
|
751
|
+
this.kick(heldUntilMs);
|
|
678
752
|
}
|
|
679
753
|
}
|
|
680
|
-
|
|
754
|
+
sortQueue() {
|
|
755
|
+
this.queue.sort((a, b) => Number(isEvent(b.segment)) - Number(isEvent(a.segment)) || a.segment.captureStartMs - b.segment.captureStartMs);
|
|
756
|
+
}
|
|
757
|
+
kick(notBeforeMs = null) {
|
|
681
758
|
if (this.stopped || this.draining || this.queue.length === 0)
|
|
682
759
|
return;
|
|
683
|
-
const due = Math.min(...this.queue.map((item) => item.nextAtMs));
|
|
760
|
+
const due = Math.max(Math.min(...this.queue.map((item) => item.nextAtMs)), notBeforeMs ?? 0);
|
|
684
761
|
const delay = Math.max(0, due - this.now());
|
|
685
762
|
if (this.timer)
|
|
686
763
|
clearTimeout(this.timer);
|
|
@@ -691,6 +768,16 @@ class VideoSegmentUploader {
|
|
|
691
768
|
if (typeof this.timer.unref === 'function')
|
|
692
769
|
this.timer.unref();
|
|
693
770
|
}
|
|
771
|
+
done(segment, outcome) {
|
|
772
|
+
if (!this.onDone)
|
|
773
|
+
return;
|
|
774
|
+
try {
|
|
775
|
+
this.onDone(segment, outcome);
|
|
776
|
+
}
|
|
777
|
+
catch {
|
|
778
|
+
/* a listener cannot break delivery */
|
|
779
|
+
}
|
|
780
|
+
}
|
|
694
781
|
/** One attempt at one segment: presign → PUT → finalize, resuming at finalize. */
|
|
695
782
|
async deliver(item) {
|
|
696
783
|
const { segment } = item;
|
|
@@ -700,6 +787,7 @@ class VideoSegmentUploader {
|
|
|
700
787
|
}
|
|
701
788
|
catch {
|
|
702
789
|
this.stats.missing += 1;
|
|
790
|
+
this.done(segment, 'missing');
|
|
703
791
|
return 'done';
|
|
704
792
|
}
|
|
705
793
|
if (!item.probe) {
|
|
@@ -764,7 +852,10 @@ class VideoSegmentUploader {
|
|
|
764
852
|
this.stats.uploadedBytes += bytes;
|
|
765
853
|
this.stats.uploadedSeconds += item.probe.durationMs / 1000;
|
|
766
854
|
this.stats.lastUploadAtMs = this.now();
|
|
855
|
+
if (isEvent(segment))
|
|
856
|
+
this.stats.eventsUploaded += 1;
|
|
767
857
|
this.deleteLocal(segment);
|
|
858
|
+
this.done(segment, 'uploaded');
|
|
768
859
|
return 'done';
|
|
769
860
|
}
|
|
770
861
|
if (finalize.statusCode === 422) {
|
|
@@ -773,6 +864,7 @@ class VideoSegmentUploader {
|
|
|
773
864
|
this.stats.rejected[reason] = (this.stats.rejected[reason] ?? 0) + 1;
|
|
774
865
|
this.log('warn', `[video] ${path.basename(segment.file)} rejected at finalize (${reason}); deleted locally`);
|
|
775
866
|
this.deleteLocal(segment);
|
|
867
|
+
this.done(segment, 'rejected');
|
|
776
868
|
return 'done';
|
|
777
869
|
}
|
|
778
870
|
this.stats.failures.finalize += 1;
|
|
@@ -807,8 +899,8 @@ class VideoSegmentUploader {
|
|
|
807
899
|
has_audio: audio !== null,
|
|
808
900
|
audio_codec: audio?.codec === 'aac' ? 'aac' : null,
|
|
809
901
|
audio_bitrate_bps: audioBitrate !== null && Number.isSafeInteger(audioBitrate) && audioBitrate >= 1 ? audioBitrate : null,
|
|
810
|
-
trigger_kind: 'continuous',
|
|
811
|
-
trigger_id: '',
|
|
902
|
+
trigger_kind: isEvent(item.segment) ? 'event' : 'continuous',
|
|
903
|
+
trigger_id: isEvent(item.segment) ? item.segment.triggerId : '',
|
|
812
904
|
agent_version: this.agentVersion,
|
|
813
905
|
calibration_hash: null,
|
|
814
906
|
// No fix on a fixed camera: the server fills the registered location.
|
|
@@ -852,6 +944,7 @@ class VideoSegmentUploader {
|
|
|
852
944
|
discard(segment, why) {
|
|
853
945
|
this.log('warn', `[video] ${path.basename(segment.file)} not uploaded: ${why}; deleted locally`);
|
|
854
946
|
this.deleteLocal(segment);
|
|
947
|
+
this.done(segment, 'discarded');
|
|
855
948
|
}
|
|
856
949
|
deleteLocal(segment) {
|
|
857
950
|
for (const file of [segment.file, segment.metaFile ?? segment.file.replace(/\.mp4$/i, '.json')]) {
|
|
@@ -868,6 +961,10 @@ exports.VideoSegmentUploader = VideoSegmentUploader;
|
|
|
868
961
|
function errorText(err) {
|
|
869
962
|
return err instanceof Error ? err.message : String(err);
|
|
870
963
|
}
|
|
964
|
+
/** An alert window clip, with the trigger id the server can link it by. */
|
|
965
|
+
function isEvent(segment) {
|
|
966
|
+
return segment.triggerKind === 'event' && typeof segment.triggerId === 'string' && /^[a-z0-9_]{1,64}$/.test(segment.triggerId);
|
|
967
|
+
}
|
|
871
968
|
/** Seconds in a UTC day: a budget at or above it is continuous recording. */
|
|
872
969
|
const SECONDS_PER_DAY = 86400;
|
|
873
970
|
/**
|
|
@@ -878,10 +975,48 @@ const SECONDS_PER_DAY = 86400;
|
|
|
878
975
|
*/
|
|
879
976
|
const UNANSWERED_SEGMENT_SECONDS = 60;
|
|
880
977
|
const UNANSWERED_RING_SECONDS = 3600;
|
|
978
|
+
/**
|
|
979
|
+
* Local buffer segments in `alert_windows` mode. An alert's window ends 15 s
|
|
980
|
+
* after its capture; the segment holding that instant closes at most one
|
|
981
|
+
* segment plus one GOP later, so a 10-s segment puts a clip on the uplink
|
|
982
|
+
* about 25-30 s after the alert, where the 60-s continuous segment would take
|
|
983
|
+
* up to 75 s.
|
|
984
|
+
*/
|
|
985
|
+
exports.ALERT_BUFFER_SEGMENT_SECONDS = 10;
|
|
986
|
+
/**
|
|
987
|
+
* The provider label on every local-buffer segment. A switch to continuous or
|
|
988
|
+
* off closes the buffer's last segment under the new mode, and a restart
|
|
989
|
+
* re-emits the whole ring; the label is how those are told apart from video
|
|
990
|
+
* recorded for upload, so a week of buffer never reaches the uplink.
|
|
991
|
+
*/
|
|
992
|
+
exports.LOCAL_BUFFER_SEGMENT_LABEL = 'buffer';
|
|
993
|
+
/** The ring's seconds bound in `alert_windows` mode: a week, so the byte share is what binds. */
|
|
994
|
+
const ALERT_BUFFER_RING_SECONDS = 7 * SECONDS_PER_DAY;
|
|
995
|
+
/**
|
|
996
|
+
* The ring's bound while the box cannot size a share (its platform reports no
|
|
997
|
+
* free space): an hour, the runtime_config ring seed, never a week of video on
|
|
998
|
+
* a disk nobody measured.
|
|
999
|
+
*/
|
|
1000
|
+
const ALERT_BUFFER_UNSIZED_RING_SECONDS = 3600;
|
|
1001
|
+
/** The window when the server names none (its own default). */
|
|
1002
|
+
const DEFAULT_ALERT_WINDOW = { beforeSeconds: 15, afterSeconds: 15 };
|
|
1003
|
+
/**
|
|
1004
|
+
* A window whose end no closed segment has reached this long after the end is
|
|
1005
|
+
* cut from whatever the buffer holds: the session stopped writing (a camera
|
|
1006
|
+
* that dropped), and a shorter clip beats none.
|
|
1007
|
+
*/
|
|
1008
|
+
const ALERT_COVER_GRACE_MS = 60000;
|
|
1009
|
+
const ALERT_PENDING_CHECK_MS = 2000;
|
|
881
1010
|
/** Same cadence as the local profile cache (`DEFAULT_PROFILE_TTL_MS`). */
|
|
882
1011
|
const DEFAULT_KNOB_POLL_MS = 5 * 60 * 1000;
|
|
883
1012
|
const KNOBS_FILE = 'video-knobs.json';
|
|
884
1013
|
const DAILY_FILE = 'video-daily.json';
|
|
1014
|
+
const CLIPS_FILE = 'alert-clips.json';
|
|
1015
|
+
/** Cut alert windows waiting for (or in) upload, beside the ring, never in it. */
|
|
1016
|
+
exports.EVENT_CLIPS_DIRNAME = 'events';
|
|
1017
|
+
/** How long a clip decision is remembered (the server stops asking after an hour). */
|
|
1018
|
+
const CLIP_STATE_KEEP_MS = 7 * 86400000;
|
|
1019
|
+
const CLIP_STATE_MAX = 500;
|
|
885
1020
|
function utcDay(ms) {
|
|
886
1021
|
return new Date(ms).toISOString().slice(0, 10);
|
|
887
1022
|
}
|
|
@@ -890,13 +1025,35 @@ function writeJsonAtomic(file, value) {
|
|
|
890
1025
|
fs.writeFileSync(tmp, JSON.stringify(value));
|
|
891
1026
|
fs.renameSync(tmp, file);
|
|
892
1027
|
}
|
|
893
|
-
|
|
894
|
-
|
|
1028
|
+
/** Do two answers configure recording the same? Clip requests never do. */
|
|
1029
|
+
function sameRecording(a, b) {
|
|
1030
|
+
return !!a && a.dailySeconds === b.dailySeconds && a.segmentSeconds === b.segmentSeconds && a.ringSeconds === b.ringSeconds
|
|
1031
|
+
&& (0, SensingProfileClient_1.effectiveVideoMode)(a) === (0, SensingProfileClient_1.effectiveVideoMode)(b) && (a.alerting === true) === (b.alerting === true)
|
|
1032
|
+
&& a.alertWindow?.beforeSeconds === b.alertWindow?.beforeSeconds && a.alertWindow?.afterSeconds === b.alertWindow?.afterSeconds;
|
|
1033
|
+
}
|
|
1034
|
+
/** The provider's ring figures, read structurally (edge-platform-rtsp is optional). */
|
|
1035
|
+
function ringFigures(provider) {
|
|
1036
|
+
try {
|
|
1037
|
+
const segments = provider.getStats?.()?.segments;
|
|
1038
|
+
const ringBytes = typeof segments?.ringBytes === 'number' && Number.isFinite(segments.ringBytes) ? segments.ringBytes : 0;
|
|
1039
|
+
const rate = segments?.measuredBytesPerSec;
|
|
1040
|
+
return { ringBytes, bytesPerSec: typeof rate === 'number' && Number.isFinite(rate) && rate > 0 ? rate : null };
|
|
1041
|
+
}
|
|
1042
|
+
catch {
|
|
1043
|
+
return { ringBytes: 0, bytesPerSec: null };
|
|
1044
|
+
}
|
|
895
1045
|
}
|
|
896
1046
|
/**
|
|
897
|
-
* One per recording feed. Applies the server's knobs to the provider
|
|
898
|
-
*
|
|
899
|
-
*
|
|
1047
|
+
* One per recording feed. Applies the server's knobs to the provider and runs
|
|
1048
|
+
* the camera's mode:
|
|
1049
|
+
*
|
|
1050
|
+
* continuous a per-UTC-day recorded-seconds budget, and every closed
|
|
1051
|
+
* segment handed to the uploader (the paid add-on);
|
|
1052
|
+
* alert_windows 10-s segments into a local ring sized by the box-wide
|
|
1053
|
+
* `LocalVideoBuffer`, NOTHING uploaded, except the window
|
|
1054
|
+
* around each alert the server fires, cut from the ring and
|
|
1055
|
+
* uploaded as an `event` segment ahead of every other upload;
|
|
1056
|
+
* off no recording; what an earlier run recorded is delivered.
|
|
900
1057
|
*
|
|
901
1058
|
* Knobs follow the deployedCadenceSource rule: a failed fetch, an API that
|
|
902
1059
|
* does not send `video`, and an unreadable `video` all KEEP the last applied
|
|
@@ -914,7 +1071,22 @@ class CctvVideoRecorder {
|
|
|
914
1071
|
this.stopped = false;
|
|
915
1072
|
this.pollTimer = null;
|
|
916
1073
|
this.dayTimer = null;
|
|
917
|
-
this.counts = { polls: 0, keptOnFailedFetch: 0, keptOnSilence: 0, keptOnMalformed: 0 };
|
|
1074
|
+
this.counts = { polls: 0, keptOnFailedFetch: 0, keptOnSilence: 0, keptOnMalformed: 0, bufferSegmentsKept: 0 };
|
|
1075
|
+
/** The mode last applied to the provider. */
|
|
1076
|
+
this.appliedMode = 'off';
|
|
1077
|
+
/** This feed's share of the local buffer, while it buffers. */
|
|
1078
|
+
this.shareBytes = null;
|
|
1079
|
+
/** Capture end of the newest segment the ring closed (alert windows wait for it to pass their end). */
|
|
1080
|
+
this.lastClosedEndMs = 0;
|
|
1081
|
+
this.pendingClips = new Map();
|
|
1082
|
+
this.clipStates = new Map();
|
|
1083
|
+
/** The window being cut right now: a request arriving meanwhile is not queued a second time. */
|
|
1084
|
+
this.cuttingTrigger = null;
|
|
1085
|
+
this.cutting = false;
|
|
1086
|
+
/** The ring's bytes read off disk before the provider has enforced it once (see heldBytes). */
|
|
1087
|
+
this.diskRingBytes = null;
|
|
1088
|
+
this.pendingTimer = null;
|
|
1089
|
+
this.clipCounts = { requested: 0, captured: 0, uploaded: 0, unavailable: 0 };
|
|
918
1090
|
this.provider = options.provider;
|
|
919
1091
|
this.dir = options.dir;
|
|
920
1092
|
this.feedName = options.feedName;
|
|
@@ -923,6 +1095,10 @@ class CctvVideoRecorder {
|
|
|
923
1095
|
this.pollMs = Math.max(1000, options.pollMs ?? DEFAULT_KNOB_POLL_MS);
|
|
924
1096
|
this.now = options.now ?? Date.now;
|
|
925
1097
|
this.log = options.log ?? ((level, message) => (level === 'warn' ? console.warn : console.log)(message));
|
|
1098
|
+
this.ffmpegPath = options.ffmpegPath ?? 'ffmpeg';
|
|
1099
|
+
this.buffer = options.buffer ?? (0, LocalVideoBuffer_1.sharedLocalVideoBuffer)(path.dirname(path.resolve(options.dir)));
|
|
1100
|
+
this.receiptPoller = options.receiptPoller ?? null;
|
|
1101
|
+
this.cutWindow = options.cutWindow ?? AlertClips_1.cutAlertWindow;
|
|
926
1102
|
this.provider.on('segment', (segment) => this.onSegment(segment));
|
|
927
1103
|
this.provider.on('segment_evicted', (evicted) => this.uploader.forget(evicted.file));
|
|
928
1104
|
this.provider.on('opening', () => this.start());
|
|
@@ -934,6 +1110,8 @@ class CctvVideoRecorder {
|
|
|
934
1110
|
this.started = true;
|
|
935
1111
|
this.loadState();
|
|
936
1112
|
this.apply();
|
|
1113
|
+
this.pruneEventClips();
|
|
1114
|
+
this.recoverEventClips();
|
|
937
1115
|
void this.poll();
|
|
938
1116
|
this.pollTimer = setInterval(() => void this.poll(), this.pollMs);
|
|
939
1117
|
if (typeof this.pollTimer.unref === 'function')
|
|
@@ -945,13 +1123,19 @@ class CctvVideoRecorder {
|
|
|
945
1123
|
clearInterval(this.pollTimer);
|
|
946
1124
|
if (this.dayTimer)
|
|
947
1125
|
clearTimeout(this.dayTimer);
|
|
1126
|
+
if (this.pendingTimer)
|
|
1127
|
+
clearInterval(this.pendingTimer);
|
|
948
1128
|
this.pollTimer = null;
|
|
949
1129
|
this.dayTimer = null;
|
|
1130
|
+
this.pendingTimer = null;
|
|
1131
|
+
this.buffer.remove(this.dir);
|
|
1132
|
+
this.receiptPoller?.stop();
|
|
950
1133
|
this.uploader.stop();
|
|
951
1134
|
}
|
|
952
1135
|
getStats() {
|
|
953
1136
|
return {
|
|
954
|
-
knobs: this.knobs ? { ...this.knobs } : null,
|
|
1137
|
+
knobs: this.knobs ? { ...this.knobs, ...(this.knobs.alertClips ? { alertClips: [...this.knobs.alertClips] } : {}) } : null,
|
|
1138
|
+
mode: this.appliedMode,
|
|
955
1139
|
recording: this.recording,
|
|
956
1140
|
day: this.daily.day,
|
|
957
1141
|
recordedSecondsToday: Math.round(this.daily.recordedSeconds * 1000) / 1000,
|
|
@@ -959,8 +1143,64 @@ class CctvVideoRecorder {
|
|
|
959
1143
|
keptOnFailedFetch: this.counts.keptOnFailedFetch,
|
|
960
1144
|
keptOnSilence: this.counts.keptOnSilence,
|
|
961
1145
|
keptOnMalformed: this.counts.keptOnMalformed,
|
|
1146
|
+
bufferSegmentsKept: this.counts.bufferSegmentsKept,
|
|
1147
|
+
clips: { ...this.clipCounts, pending: this.pendingClips.size },
|
|
1148
|
+
bufferShareBytes: this.appliedMode === 'alert_windows' ? this.shareBytes : null,
|
|
962
1149
|
};
|
|
963
1150
|
}
|
|
1151
|
+
/**
|
|
1152
|
+
* The local video this feed holds, for the status beacon: the box's free
|
|
1153
|
+
* bytes and buffer budget, this feed's ring, and how far back it reaches.
|
|
1154
|
+
*/
|
|
1155
|
+
videoBufferReport() {
|
|
1156
|
+
const snapshot = this.buffer.snapshot();
|
|
1157
|
+
const { ringBytes, bytesPerSec } = ringFigures(this.provider);
|
|
1158
|
+
let oldestCaptureAt = null;
|
|
1159
|
+
try {
|
|
1160
|
+
const first = fs.readdirSync(path.join(this.dir, 'closed')).filter((n) => /^\d{13}-.+\.mp4$/i.test(n)).sort()[0];
|
|
1161
|
+
if (first)
|
|
1162
|
+
oldestCaptureAt = new Date(Number(first.slice(0, 13))).toISOString();
|
|
1163
|
+
}
|
|
1164
|
+
catch {
|
|
1165
|
+
/* nothing buffered yet */
|
|
1166
|
+
}
|
|
1167
|
+
return {
|
|
1168
|
+
mode: this.appliedMode,
|
|
1169
|
+
freeBytes: snapshot.freeBytes ?? (0, LocalVideoBuffer_1.volumeFreeBytesOf)(this.dir),
|
|
1170
|
+
budgetBytes: this.appliedMode === 'alert_windows' ? snapshot.budgetBytes : null,
|
|
1171
|
+
bufferBytes: ringBytes,
|
|
1172
|
+
bufferSeconds: bytesPerSec ? Math.round(ringBytes / bytesPerSec) : null,
|
|
1173
|
+
oldestCaptureAt,
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
/**
|
|
1177
|
+
* A review that supported an alert was accepted: follow its receipt for the
|
|
1178
|
+
* clip the server will ask for. Only a buffering feed has anything to cut.
|
|
1179
|
+
*/
|
|
1180
|
+
watchReceipt(evidenceId) {
|
|
1181
|
+
if (this.stopped || this.appliedMode !== 'alert_windows')
|
|
1182
|
+
return;
|
|
1183
|
+
this.receiptPoller?.watch(evidenceId);
|
|
1184
|
+
}
|
|
1185
|
+
/** Clip requests from the receipt or the knobs. Each window is cut once. */
|
|
1186
|
+
requestClips(requests) {
|
|
1187
|
+
if (this.stopped || this.appliedMode !== 'alert_windows')
|
|
1188
|
+
return;
|
|
1189
|
+
let added = 0;
|
|
1190
|
+
for (const request of requests) {
|
|
1191
|
+
if (this.pendingClips.has(request.triggerId) || this.clipStates.has(request.triggerId)
|
|
1192
|
+
|| this.cuttingTrigger === request.triggerId)
|
|
1193
|
+
continue;
|
|
1194
|
+
this.pendingClips.set(request.triggerId, request);
|
|
1195
|
+
this.clipCounts.requested += 1;
|
|
1196
|
+
added += 1;
|
|
1197
|
+
}
|
|
1198
|
+
if (!added)
|
|
1199
|
+
return;
|
|
1200
|
+
this.log('info', `[video] ${this.feedName}: ${added} alert window(s) to capture`);
|
|
1201
|
+
this.ensurePendingTimer();
|
|
1202
|
+
void this.capturePending();
|
|
1203
|
+
}
|
|
964
1204
|
/** One knob fetch. Only an explicit, readable `video` block changes anything. */
|
|
965
1205
|
async poll() {
|
|
966
1206
|
if (this.stopped)
|
|
@@ -985,20 +1225,72 @@ class CctvVideoRecorder {
|
|
|
985
1225
|
this.counts.keptOnMalformed += 1;
|
|
986
1226
|
return;
|
|
987
1227
|
}
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
1228
|
+
const next = profile.video;
|
|
1229
|
+
if (!sameRecording(this.knobs, next)) {
|
|
1230
|
+
this.knobs = { ...next };
|
|
1231
|
+
const { alertClips: _requests, ...persisted } = this.knobs;
|
|
1232
|
+
this.persist(KNOBS_FILE, { version: 1, ...persisted, appliedAtMs: this.now() });
|
|
1233
|
+
const mode = (0, SensingProfileClient_1.effectiveVideoMode)(this.knobs);
|
|
1234
|
+
this.log('info', `[video] ${this.feedName}: mode ${mode}` +
|
|
1235
|
+
(this.knobs.alerting ? ' (alerting)' : '') +
|
|
1236
|
+
(mode === 'alert_windows'
|
|
1237
|
+
? `, local buffer of ${exports.ALERT_BUFFER_SEGMENT_SECONDS}s segments; only alert windows upload`
|
|
1238
|
+
: `, ${this.knobs.dailySeconds}s/day, ${this.knobs.segmentSeconds}s segments, ring ${this.knobs.ringSeconds}s`));
|
|
1239
|
+
this.apply();
|
|
1240
|
+
}
|
|
1241
|
+
else if (this.knobs) {
|
|
1242
|
+
this.knobs.alertClips = next.alertClips;
|
|
1243
|
+
}
|
|
1244
|
+
if (next.alertClips?.length)
|
|
1245
|
+
this.requestClips(next.alertClips);
|
|
994
1246
|
}
|
|
995
1247
|
apply() {
|
|
996
1248
|
if (this.stopped)
|
|
997
1249
|
return;
|
|
998
1250
|
this.rollDay();
|
|
999
1251
|
const k = this.knobs;
|
|
1252
|
+
const mode = (0, SensingProfileClient_1.effectiveVideoMode)(k);
|
|
1253
|
+
const previousMode = this.appliedMode;
|
|
1254
|
+
this.appliedMode = mode;
|
|
1255
|
+
// Rank the session first: a re-open below must already see it.
|
|
1256
|
+
try {
|
|
1257
|
+
this.provider.setSessionPriority?.(k?.alerting === true ? 1 : 0);
|
|
1258
|
+
}
|
|
1259
|
+
catch {
|
|
1260
|
+
/* an older provider: no ranking */
|
|
1261
|
+
}
|
|
1262
|
+
if (mode === 'alert_windows') {
|
|
1263
|
+
this.recording = true;
|
|
1264
|
+
if (previousMode === 'continuous') {
|
|
1265
|
+
const dropped = this.uploader.dropContinuous();
|
|
1266
|
+
if (dropped)
|
|
1267
|
+
this.log('info', `[video] ${this.feedName}: continuous upload off; ${dropped} queued segment(s) stay in the local buffer`);
|
|
1268
|
+
}
|
|
1269
|
+
// Joining computes this feed's share, which reaches the provider through applyShare.
|
|
1270
|
+
if (!this.buffer.has(this.dir)) {
|
|
1271
|
+
this.buffer.add({
|
|
1272
|
+
key: this.dir,
|
|
1273
|
+
bytesPerSecond: () => ringFigures(this.provider).bytesPerSec,
|
|
1274
|
+
heldBytes: () => this.heldRingBytes(),
|
|
1275
|
+
applyShare: (maxBytes) => {
|
|
1276
|
+
this.shareBytes = maxBytes;
|
|
1277
|
+
if (this.appliedMode === 'alert_windows')
|
|
1278
|
+
this.provider.setSegmentRecording(this.bufferConfig());
|
|
1279
|
+
},
|
|
1280
|
+
});
|
|
1281
|
+
}
|
|
1282
|
+
this.provider.setSegmentRecording(this.bufferConfig());
|
|
1283
|
+
return;
|
|
1284
|
+
}
|
|
1285
|
+
if (this.buffer.has(this.dir)) {
|
|
1286
|
+
this.buffer.remove(this.dir);
|
|
1287
|
+
this.shareBytes = null;
|
|
1288
|
+
}
|
|
1289
|
+
this.pendingClips.clear();
|
|
1000
1290
|
if (!k) {
|
|
1001
1291
|
this.recording = false;
|
|
1292
|
+
// No `maxBytes`: the provider reads its absence as "no caller cap", so a
|
|
1293
|
+
// share from an earlier alert_windows run never outlives the mode.
|
|
1002
1294
|
this.provider.setSegmentRecording({
|
|
1003
1295
|
dir: this.dir,
|
|
1004
1296
|
segmentSeconds: UNANSWERED_SEGMENT_SECONDS,
|
|
@@ -1007,18 +1299,77 @@ class CctvVideoRecorder {
|
|
|
1007
1299
|
});
|
|
1008
1300
|
return;
|
|
1009
1301
|
}
|
|
1302
|
+
const continuous = mode === 'continuous';
|
|
1010
1303
|
const budgetLeft = k.dailySeconds >= SECONDS_PER_DAY || this.daily.recordedSeconds < k.dailySeconds;
|
|
1011
|
-
this.recording = k.dailySeconds > 0 && budgetLeft;
|
|
1304
|
+
this.recording = continuous && k.dailySeconds > 0 && budgetLeft;
|
|
1012
1305
|
this.provider.setSegmentRecording({
|
|
1013
1306
|
dir: this.dir,
|
|
1014
1307
|
segmentSeconds: k.segmentSeconds,
|
|
1015
1308
|
ringSeconds: k.ringSeconds,
|
|
1016
1309
|
enabled: this.recording,
|
|
1017
1310
|
});
|
|
1018
|
-
if (k.dailySeconds > 0 && !budgetLeft)
|
|
1311
|
+
if (continuous && k.dailySeconds > 0 && !budgetLeft)
|
|
1019
1312
|
this.scheduleNextDay();
|
|
1020
1313
|
}
|
|
1314
|
+
/**
|
|
1315
|
+
* The bytes this feed's ring holds. The provider reports 0 until it has
|
|
1316
|
+
* enforced the ring once, which after a restart is AFTER the share is first
|
|
1317
|
+
* computed; counting 0 then would hand the ring a share that leaves out its
|
|
1318
|
+
* own week of video and trim the oldest of it at every start. Until the
|
|
1319
|
+
* provider reports, the closed segments are summed off disk (once a minute).
|
|
1320
|
+
*/
|
|
1321
|
+
heldRingBytes() {
|
|
1322
|
+
const reported = ringFigures(this.provider).ringBytes;
|
|
1323
|
+
if (reported > 0)
|
|
1324
|
+
return reported;
|
|
1325
|
+
const nowMs = this.now();
|
|
1326
|
+
if (this.diskRingBytes && nowMs - this.diskRingBytes.atMs < 60000)
|
|
1327
|
+
return this.diskRingBytes.bytes;
|
|
1328
|
+
let bytes = 0;
|
|
1329
|
+
try {
|
|
1330
|
+
const closed = path.join(this.dir, 'closed');
|
|
1331
|
+
for (const name of fs.readdirSync(closed)) {
|
|
1332
|
+
if (!name.toLowerCase().endsWith('.mp4'))
|
|
1333
|
+
continue;
|
|
1334
|
+
try {
|
|
1335
|
+
bytes += fs.statSync(path.join(closed, name)).size;
|
|
1336
|
+
}
|
|
1337
|
+
catch {
|
|
1338
|
+
/* gone meanwhile */
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
catch {
|
|
1343
|
+
/* nothing buffered yet */
|
|
1344
|
+
}
|
|
1345
|
+
this.diskRingBytes = { bytes, atMs: nowMs };
|
|
1346
|
+
return bytes;
|
|
1347
|
+
}
|
|
1348
|
+
/** The provider config in alert_windows mode: short segments, the byte share as the cap. */
|
|
1349
|
+
bufferConfig() {
|
|
1350
|
+
return {
|
|
1351
|
+
dir: this.dir,
|
|
1352
|
+
segmentSeconds: exports.ALERT_BUFFER_SEGMENT_SECONDS,
|
|
1353
|
+
ringSeconds: this.shareBytes === null ? ALERT_BUFFER_UNSIZED_RING_SECONDS : ALERT_BUFFER_RING_SECONDS,
|
|
1354
|
+
enabled: true,
|
|
1355
|
+
maxBytes: this.shareBytes,
|
|
1356
|
+
label: exports.LOCAL_BUFFER_SEGMENT_LABEL,
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
1021
1359
|
onSegment(segment) {
|
|
1360
|
+
if (this.appliedMode === 'alert_windows') {
|
|
1361
|
+
// The local buffer: nothing leaves the box but an alert's window.
|
|
1362
|
+
if (Number.isFinite(segment.captureEndMs))
|
|
1363
|
+
this.lastClosedEndMs = Math.max(this.lastClosedEndMs, segment.captureEndMs);
|
|
1364
|
+
if (this.pendingClips.size)
|
|
1365
|
+
void this.capturePending();
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
if (segment.label === exports.LOCAL_BUFFER_SEGMENT_LABEL) {
|
|
1369
|
+
// Recorded for alert windows: it stays in the ring until the ring evicts it.
|
|
1370
|
+
this.counts.bufferSegmentsKept += 1;
|
|
1371
|
+
return;
|
|
1372
|
+
}
|
|
1022
1373
|
if (!segment.recovered) {
|
|
1023
1374
|
this.rollDay();
|
|
1024
1375
|
this.daily.recordedSeconds += Math.max(0, segment.endSec - segment.startSec);
|
|
@@ -1031,6 +1382,119 @@ class CctvVideoRecorder {
|
|
|
1031
1382
|
}
|
|
1032
1383
|
this.uploader.enqueue(segment);
|
|
1033
1384
|
}
|
|
1385
|
+
ensurePendingTimer() {
|
|
1386
|
+
if (this.pendingTimer || this.stopped)
|
|
1387
|
+
return;
|
|
1388
|
+
this.pendingTimer = setInterval(() => void this.capturePending(), ALERT_PENDING_CHECK_MS);
|
|
1389
|
+
if (typeof this.pendingTimer.unref === 'function')
|
|
1390
|
+
this.pendingTimer.unref();
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Cut every pending window whose end the ring has passed (or that waited past
|
|
1394
|
+
* the grace), one at a time. The window comes from the request; the server
|
|
1395
|
+
* decides it, the box only measures where its buffer starts and ends.
|
|
1396
|
+
*/
|
|
1397
|
+
async capturePending() {
|
|
1398
|
+
if (this.cutting || this.stopped)
|
|
1399
|
+
return;
|
|
1400
|
+
this.cutting = true;
|
|
1401
|
+
try {
|
|
1402
|
+
for (const [triggerId, request] of [...this.pendingClips]) {
|
|
1403
|
+
if (this.stopped || this.appliedMode !== 'alert_windows')
|
|
1404
|
+
break;
|
|
1405
|
+
const windowEndMs = request.capturedAtMs + request.afterSeconds * 1000;
|
|
1406
|
+
const covered = this.lastClosedEndMs >= windowEndMs;
|
|
1407
|
+
if (!covered && this.now() < windowEndMs + ALERT_COVER_GRACE_MS)
|
|
1408
|
+
continue;
|
|
1409
|
+
this.pendingClips.delete(triggerId);
|
|
1410
|
+
if (this.clipStates.has(triggerId))
|
|
1411
|
+
continue;
|
|
1412
|
+
this.cuttingTrigger = triggerId;
|
|
1413
|
+
let result;
|
|
1414
|
+
try {
|
|
1415
|
+
result = await this.cutWindow({
|
|
1416
|
+
ffmpegPath: this.ffmpegPath,
|
|
1417
|
+
closedDir: path.join(this.dir, 'closed'),
|
|
1418
|
+
outDir: path.join(this.dir, exports.EVENT_CLIPS_DIRNAME),
|
|
1419
|
+
request,
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
finally {
|
|
1423
|
+
this.cuttingTrigger = null;
|
|
1424
|
+
}
|
|
1425
|
+
if ('clip' in result) {
|
|
1426
|
+
this.clipCounts.captured += 1;
|
|
1427
|
+
this.setClipState(triggerId, { state: 'captured', atMs: this.now() });
|
|
1428
|
+
this.log('info', `[video] ${this.feedName}: alert window ${triggerId.slice(0, 12)} cut ` +
|
|
1429
|
+
`(${Math.round((result.clip.captureEndMs - result.clip.captureStartMs) / 1000)} s from ${result.clip.sourceSegments} segment(s)); uploading first`);
|
|
1430
|
+
this.uploader.enqueue({
|
|
1431
|
+
file: result.clip.file,
|
|
1432
|
+
metaFile: result.clip.metaFile,
|
|
1433
|
+
startSec: 0,
|
|
1434
|
+
endSec: (result.clip.captureEndMs - result.clip.captureStartMs) / 1000,
|
|
1435
|
+
captureStartMs: result.clip.captureStartMs,
|
|
1436
|
+
captureEndMs: result.clip.captureEndMs,
|
|
1437
|
+
triggerKind: 'event',
|
|
1438
|
+
triggerId,
|
|
1439
|
+
});
|
|
1440
|
+
this.pruneEventClips();
|
|
1441
|
+
}
|
|
1442
|
+
else {
|
|
1443
|
+
this.clipCounts.unavailable += 1;
|
|
1444
|
+
this.setClipState(triggerId, { state: 'unavailable', atMs: this.now(), reason: result.unavailable });
|
|
1445
|
+
this.log('warn', `[video] ${this.feedName}: alert window ${triggerId.slice(0, 12)} not captured (${result.unavailable}` +
|
|
1446
|
+
`${'detail' in result && result.detail ? `: ${result.detail.slice(0, 200)}` : ''})`);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
finally {
|
|
1451
|
+
this.cutting = false;
|
|
1452
|
+
if (!this.pendingClips.size && this.pendingTimer) {
|
|
1453
|
+
clearInterval(this.pendingTimer);
|
|
1454
|
+
this.pendingTimer = null;
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
/** Bound the undelivered clips (EVENT_CLIPS_MAX, EVENT_CLIPS_MAX_AGE_MS); never the one being cut. */
|
|
1459
|
+
pruneEventClips() {
|
|
1460
|
+
const removed = (0, AlertClips_1.pruneEventClips)(path.join(this.dir, exports.EVENT_CLIPS_DIRNAME), { nowMs: this.now() });
|
|
1461
|
+
for (const file of removed)
|
|
1462
|
+
this.uploader.forget(file);
|
|
1463
|
+
if (removed.length)
|
|
1464
|
+
this.log('warn', `[video] ${this.feedName}: ${removed.length} undelivered alert window(s) deleted (too many, or older than three days)`);
|
|
1465
|
+
}
|
|
1466
|
+
/** Clips an earlier process cut and never delivered go first, as before the restart. */
|
|
1467
|
+
recoverEventClips() {
|
|
1468
|
+
for (const clip of (0, AlertClips_1.recoverEventClips)(path.join(this.dir, exports.EVENT_CLIPS_DIRNAME))) {
|
|
1469
|
+
this.uploader.enqueue({
|
|
1470
|
+
file: clip.file,
|
|
1471
|
+
metaFile: clip.metaFile,
|
|
1472
|
+
startSec: 0,
|
|
1473
|
+
endSec: (clip.captureEndMs - clip.captureStartMs) / 1000,
|
|
1474
|
+
captureStartMs: clip.captureStartMs,
|
|
1475
|
+
captureEndMs: clip.captureEndMs,
|
|
1476
|
+
triggerKind: 'event',
|
|
1477
|
+
triggerId: clip.triggerId,
|
|
1478
|
+
recovered: true,
|
|
1479
|
+
});
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
/** The uploader finished an event clip. */
|
|
1483
|
+
noteUploadDone(segment, outcome) {
|
|
1484
|
+
if (segment.triggerKind !== 'event' || !segment.triggerId)
|
|
1485
|
+
return;
|
|
1486
|
+
if (outcome === 'uploaded') {
|
|
1487
|
+
this.clipCounts.uploaded += 1;
|
|
1488
|
+
this.setClipState(segment.triggerId, { state: 'uploaded', atMs: this.now() });
|
|
1489
|
+
}
|
|
1490
|
+
}
|
|
1491
|
+
setClipState(triggerId, state) {
|
|
1492
|
+
this.clipStates.set(triggerId, state);
|
|
1493
|
+
const horizon = this.now() - CLIP_STATE_KEEP_MS;
|
|
1494
|
+
const kept = [...this.clipStates].filter(([, s]) => s.atMs >= horizon).sort((a, b) => b[1].atMs - a[1].atMs).slice(0, CLIP_STATE_MAX);
|
|
1495
|
+
this.clipStates = new Map(kept);
|
|
1496
|
+
this.persist(CLIPS_FILE, { version: 1, clips: Object.fromEntries(kept) });
|
|
1497
|
+
}
|
|
1034
1498
|
rollDay() {
|
|
1035
1499
|
const day = utcDay(this.now());
|
|
1036
1500
|
if (day !== this.daily.day)
|
|
@@ -1053,7 +1517,15 @@ class CctvVideoRecorder {
|
|
|
1053
1517
|
const raw = JSON.parse(fs.readFileSync(path.join(this.dir, KNOBS_FILE), 'utf8'));
|
|
1054
1518
|
const ok = [raw?.dailySeconds, raw?.segmentSeconds, raw?.ringSeconds].every((n) => Number.isInteger(n) && n >= 0);
|
|
1055
1519
|
if (ok && raw.segmentSeconds > 0) {
|
|
1056
|
-
|
|
1520
|
+
const knobs = (0, SensingProfileClient_1.parseVideoKnobs)({
|
|
1521
|
+
dailySeconds: raw.dailySeconds,
|
|
1522
|
+
segmentSeconds: raw.segmentSeconds,
|
|
1523
|
+
ringSeconds: raw.ringSeconds,
|
|
1524
|
+
...(raw.mode !== undefined ? { mode: raw.mode } : {}),
|
|
1525
|
+
...(raw.alerting !== undefined ? { alerting: raw.alerting } : {}),
|
|
1526
|
+
...(raw.alertWindow !== undefined ? { alertWindow: raw.alertWindow } : {}),
|
|
1527
|
+
});
|
|
1528
|
+
this.knobs = knobs ?? { dailySeconds: raw.dailySeconds, segmentSeconds: raw.segmentSeconds, ringSeconds: raw.ringSeconds };
|
|
1057
1529
|
}
|
|
1058
1530
|
}
|
|
1059
1531
|
catch {
|
|
@@ -1068,6 +1540,18 @@ class CctvVideoRecorder {
|
|
|
1068
1540
|
catch {
|
|
1069
1541
|
/* first day */
|
|
1070
1542
|
}
|
|
1543
|
+
try {
|
|
1544
|
+
const raw = JSON.parse(fs.readFileSync(path.join(this.dir, CLIPS_FILE), 'utf8'));
|
|
1545
|
+
const clips = raw?.version === 1 && raw.clips && typeof raw.clips === 'object' ? raw.clips : {};
|
|
1546
|
+
for (const [triggerId, state] of Object.entries(clips)) {
|
|
1547
|
+
if (/^[a-z0-9_]{1,64}$/.test(triggerId) && state && Number.isFinite(state.atMs)
|
|
1548
|
+
&& ['captured', 'uploaded', 'unavailable'].includes(state.state))
|
|
1549
|
+
this.clipStates.set(triggerId, state);
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
catch {
|
|
1553
|
+
/* no alert window captured on this box yet */
|
|
1554
|
+
}
|
|
1071
1555
|
}
|
|
1072
1556
|
persist(name, value) {
|
|
1073
1557
|
try {
|
|
@@ -1095,34 +1579,61 @@ function attachCctvVideoRecorder(args) {
|
|
|
1095
1579
|
if (!provider || typeof provider.setSegmentRecording !== 'function' || typeof provider.on !== 'function') {
|
|
1096
1580
|
return null;
|
|
1097
1581
|
}
|
|
1582
|
+
let recorderRef = null;
|
|
1098
1583
|
const uploader = new VideoSegmentUploader({
|
|
1099
1584
|
apiBaseUrl: args.apiBaseUrl,
|
|
1100
1585
|
deviceToken: args.deviceToken,
|
|
1101
1586
|
...(args.httpPoster ? { poster: args.httpPoster } : {}),
|
|
1587
|
+
onDone: (segment, outcome) => recorderRef?.noteUploadDone(segment, outcome),
|
|
1102
1588
|
});
|
|
1103
1589
|
const profileClient = new SensingProfileClient_1.SensingProfileClient({ apiBaseUrl: args.apiBaseUrl, deviceToken: args.deviceToken }, args.httpPoster);
|
|
1590
|
+
const receiptPoller = args.retainedApiBaseUrl
|
|
1591
|
+
? new AlertClips_1.AlertClipReceiptPoller({
|
|
1592
|
+
apiBaseUrl: args.retainedApiBaseUrl,
|
|
1593
|
+
deviceToken: args.deviceToken,
|
|
1594
|
+
onRequests: (requests) => recorderRef?.requestClips(requests),
|
|
1595
|
+
...(args.httpPoster ? { poster: args.httpPoster } : {}),
|
|
1596
|
+
})
|
|
1597
|
+
: null;
|
|
1104
1598
|
const recorder = new CctvVideoRecorder({
|
|
1105
1599
|
provider: provider,
|
|
1106
1600
|
dir: args.dir,
|
|
1107
1601
|
feedName: args.feedName,
|
|
1108
1602
|
profileClient,
|
|
1109
1603
|
uploader,
|
|
1604
|
+
receiptPoller,
|
|
1605
|
+
...(args.ffmpegPath ? { ffmpegPath: args.ffmpegPath } : {}),
|
|
1110
1606
|
...(args.pollMs !== undefined ? { pollMs: args.pollMs } : {}),
|
|
1111
1607
|
});
|
|
1608
|
+
recorderRef = recorder;
|
|
1112
1609
|
const previous = recordersByDir.get(args.dir);
|
|
1113
1610
|
if (previous)
|
|
1114
|
-
previous.stop();
|
|
1115
|
-
recordersByDir.set(args.dir, recorder);
|
|
1611
|
+
previous.recorder.stop();
|
|
1612
|
+
recordersByDir.set(args.dir, { recorder, deviceToken: args.deviceToken });
|
|
1116
1613
|
return recorder;
|
|
1117
1614
|
}
|
|
1118
1615
|
/** Every attached recorder, for diagnostics. */
|
|
1119
1616
|
function activeCctvVideoRecorders() {
|
|
1120
|
-
return [...recordersByDir.entries()].map(([dir,
|
|
1617
|
+
return [...recordersByDir.entries()].map(([dir, entry]) => ({ dir, recorder: entry.recorder }));
|
|
1618
|
+
}
|
|
1619
|
+
/** The local video report of the feed that uses this device token, or null (no recording feed). */
|
|
1620
|
+
function videoBufferReportForToken(deviceToken) {
|
|
1621
|
+
for (const entry of recordersByDir.values()) {
|
|
1622
|
+
if (entry.deviceToken !== deviceToken)
|
|
1623
|
+
continue;
|
|
1624
|
+
try {
|
|
1625
|
+
return entry.recorder.videoBufferReport();
|
|
1626
|
+
}
|
|
1627
|
+
catch {
|
|
1628
|
+
return null;
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
return null;
|
|
1121
1632
|
}
|
|
1122
1633
|
/** Test seam. */
|
|
1123
1634
|
function __resetCctvVideoRecordersForTests() {
|
|
1124
|
-
for (const
|
|
1125
|
-
recorder.stop();
|
|
1635
|
+
for (const entry of recordersByDir.values())
|
|
1636
|
+
entry.recorder.stop();
|
|
1126
1637
|
recordersByDir.clear();
|
|
1127
1638
|
}
|
|
1128
1639
|
//# sourceMappingURL=VideoSegmentUploader.js.map
|