@camstack/addon-pipeline 0.1.20 → 0.2.0

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.
Files changed (101) hide show
  1. package/dist/audio-analyzer/index.js +736 -719
  2. package/dist/audio-analyzer/index.mjs +726 -679
  3. package/dist/audio-codec-nodeav/index.js +304 -461
  4. package/dist/audio-codec-nodeav/index.mjs +300 -462
  5. package/dist/chunk-BdkLduGY.mjs +5 -0
  6. package/dist/chunk-D6vf50IK.js +28 -0
  7. package/dist/codec-runtime-BOk-13PN.js +202 -0
  8. package/dist/codec-runtime-BsqlEjPi.mjs +197 -0
  9. package/dist/constants-B_b0a-6h.mjs +3119 -0
  10. package/dist/{index-CMcx_k6Y.js → constants-D65v6yp6.js} +3107 -2935
  11. package/dist/decoder-nodeav/index.js +1374 -1444
  12. package/dist/decoder-nodeav/index.mjs +1369 -1425
  13. package/dist/detection-pipeline/index.js +6462 -5613
  14. package/dist/detection-pipeline/index.mjs +6451 -5574
  15. package/dist/dist-7ewQjTle.js +22454 -0
  16. package/dist/dist-C5jnNl0n.mjs +22089 -0
  17. package/dist/motion-wasm/index.js +469 -467
  18. package/dist/motion-wasm/index.mjs +464 -446
  19. package/dist/pipeline-runner/index.js +2029 -1827
  20. package/dist/pipeline-runner/index.mjs +2025 -1811
  21. package/dist/recorder/index.js +2045 -2157
  22. package/dist/recorder/index.mjs +2042 -2156
  23. package/dist/stream-broker/_stub.js +1806 -1352
  24. package/dist/stream-broker/_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-D4-DHanK.mjs +156 -0
  25. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-Tf-HACFd.mjs +26 -0
  26. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-C9WX5HNw.mjs +26 -0
  27. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-BO7TIbJV.mjs +26 -0
  28. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare__react__loadShare__.js-C9j-2lBe.mjs +26 -0
  29. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.js-XO0-Pyu6.mjs +26 -0
  30. package/dist/stream-broker/dist-CYZr2fwk.mjs +2726 -0
  31. package/dist/stream-broker/hostInit-Di6vceAU.mjs +129 -0
  32. package/dist/stream-broker/index.js +17778 -15470
  33. package/dist/stream-broker/index.mjs +17769 -15465
  34. package/dist/stream-broker/remoteEntry.js +134 -2973
  35. package/dist/stream-broker/remoteEntry.ssr.js +33 -0
  36. package/dist/stream-broker/virtualExposes-dYNvIwoR.mjs +27 -0
  37. package/dist/stream-broker/virtual_mf-exposes-ssr___mfe_internal__addon_stream_broker_widgets__remoteEntry_js-Cmqfp4i_.mjs +10 -0
  38. package/embed-dist/assets/index-B8VlSD0-.js +150 -0
  39. package/embed-dist/assets/index-ZhDdp1Nd.css +2 -0
  40. package/embed-dist/index.html +13 -0
  41. package/package.json +25 -7
  42. package/wasm/assembly/index.ts +41 -16
  43. package/dist/audio-analyzer/index.js.map +0 -1
  44. package/dist/audio-analyzer/index.mjs.map +0 -1
  45. package/dist/audio-codec-nodeav/index.js.map +0 -1
  46. package/dist/audio-codec-nodeav/index.mjs.map +0 -1
  47. package/dist/decoder-nodeav/index.js.map +0 -1
  48. package/dist/decoder-nodeav/index.mjs.map +0 -1
  49. package/dist/detection-pipeline/index.js.map +0 -1
  50. package/dist/detection-pipeline/index.mjs.map +0 -1
  51. package/dist/index-5aYef068.mjs +0 -17514
  52. package/dist/index-5aYef068.mjs.map +0 -1
  53. package/dist/index-B36NMAdu.js +0 -17513
  54. package/dist/index-B36NMAdu.js.map +0 -1
  55. package/dist/index-CMcx_k6Y.js.map +0 -1
  56. package/dist/index-CYb7cFrv.mjs +0 -5790
  57. package/dist/index-CYb7cFrv.mjs.map +0 -1
  58. package/dist/motion-wasm/index.js.map +0 -1
  59. package/dist/motion-wasm/index.mjs.map +0 -1
  60. package/dist/pipeline-runner/index.js.map +0 -1
  61. package/dist/pipeline-runner/index.mjs.map +0 -1
  62. package/dist/recorder/index.js.map +0 -1
  63. package/dist/recorder/index.mjs.map +0 -1
  64. package/dist/stream-broker/@mf-types/compiled-types/stream-broker/widgets/FfmpegParamsField.d.ts +0 -41
  65. package/dist/stream-broker/@mf-types/compiled-types/stream-broker/widgets/GeometryBuilder.d.ts +0 -54
  66. package/dist/stream-broker/@mf-types/compiled-types/stream-broker/widgets/StreamBrokerPanel.d.ts +0 -21
  67. package/dist/stream-broker/@mf-types/compiled-types/stream-broker/widgets/format-ua.d.ts +0 -13
  68. package/dist/stream-broker/@mf-types/compiled-types/stream-broker/widgets/index.d.ts +0 -15
  69. package/dist/stream-broker/@mf-types/widgets.d.ts +0 -2
  70. package/dist/stream-broker/@mf-types.d.ts +0 -3
  71. package/dist/stream-broker/@mf-types.zip +0 -0
  72. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_sdk__loadShare__.mjs-lantnv8e.mjs +0 -12
  73. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.mjs-DJ3UNg7O.mjs +0 -30
  74. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.mjs-CYXy_bhS.mjs +0 -21
  75. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-U1EUeEPs.mjs +0 -104
  76. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DeouEaSs.mjs +0 -85
  77. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-DHUwjbb9.mjs +0 -62
  78. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react__loadShare__.mjs-CaDEYBIU.mjs +0 -89
  79. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react__loadShare__.mjs_commonjs-proxy-D6EROtlA.mjs +0 -29
  80. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-x6pP3Ghk.mjs +0 -36
  81. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom__loadShare__.mjs-DYEKzzY-.mjs +0 -45
  82. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-CcnN6sbA.mjs +0 -6
  83. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-DICOtMTl.mjs +0 -34
  84. package/dist/stream-broker/_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-CL9DR49k.mjs +0 -156
  85. package/dist/stream-broker/client-BvTmMOQu.mjs +0 -9836
  86. package/dist/stream-broker/getErrorShape-BPSzUA7W-TlK8ipWe.mjs +0 -211
  87. package/dist/stream-broker/hostInit-ChmiMPS0.mjs +0 -168
  88. package/dist/stream-broker/index-BxsFuFmE.mjs +0 -2603
  89. package/dist/stream-broker/index-C-248uOU.mjs +0 -725
  90. package/dist/stream-broker/index-C05B6jqp.mjs +0 -185
  91. package/dist/stream-broker/index-CWkKuNLr.mjs +0 -232
  92. package/dist/stream-broker/index-DOJoSShD.mjs +0 -67784
  93. package/dist/stream-broker/index-DtOI1aTU.mjs +0 -18504
  94. package/dist/stream-broker/index-oMq6ilgR.mjs +0 -1641
  95. package/dist/stream-broker/index-vIWZQBIL.mjs +0 -435
  96. package/dist/stream-broker/index-xncRG7-x.mjs +0 -2713
  97. package/dist/stream-broker/index.js.map +0 -1
  98. package/dist/stream-broker/index.mjs.map +0 -1
  99. package/dist/stream-broker/jsx-runtime-BRT_HL0A.mjs +0 -55
  100. package/dist/stream-broker/schemas-B7L0qZtq.mjs +0 -3599
  101. package/dist/stream-broker/virtualExposes-pCd777Rp.mjs +0 -42
@@ -1,2209 +1,2095 @@
1
- import { spawn } from "node:child_process";
2
- import path__default from "node:path";
3
- import { promises, mkdirSync } from "node:fs";
4
- import { e as errMsg, Q as record, Z as RecordingConfigSchema, s as string, $ as createDurableState, o as object, a as array, a0 as RecordingRetentionSchema, n as number, a1 as literal, d as defineCustomActions, c as customAction, a2 as RecordingRuleSchema, a3 as CamProfileSchema, B as BaseAddon, a4 as recordingCapability, a5 as storageEvictableCapability, E as EventCategory, O as makeProfileBrokerId, r as hydrateSchema, a6 as selectAssignedProfileSlots } from "../index-5aYef068.mjs";
1
+ import { G as recordingCapability, J as storageEvictableCapability, K as selectAssignedProfileSlots, P as hydrateSchema, T as createDurableState, at as record, g as RecordingConfigSchema, i as BaseAddon, j as errMsg, ot as string, p as EventCategory, z as migrateConfigToBands } from "../dist-C5jnNl0n.mjs";
2
+ import { promises } from "node:fs";
3
+ import path from "node:path";
5
4
  import { createFileDataPlaneHandler } from "@camstack/core";
6
- const pad = (n, w = 2) => String(n).padStart(w, "0");
7
- const DEFAULT_SUBTREE = "continuous";
8
- function hourBucketRelPath(startMs) {
9
- const d = new Date(startMs);
10
- return `${d.getUTCFullYear()}/${pad(d.getUTCMonth() + 1)}/${pad(d.getUTCDate())}/${pad(d.getUTCHours())}`;
5
+ import { spawn } from "node:child_process";
6
+ //#region src/recorder/segment-path.ts
7
+ function segmentRelPath(deviceId, profile, startMs, durMs, bytes) {
8
+ if (profile.includes("/")) throw new Error(`segmentRelPath: profile must not contain '/': ${profile}`);
9
+ const d = new Date(startMs);
10
+ const p2 = (n) => String(n).padStart(2, "0");
11
+ return `${deviceId}/${profile}/${d.getUTCFullYear()}/${p2(d.getUTCMonth() + 1)}/${p2(d.getUTCDate())}/${p2(d.getUTCHours())}/${startMs}-${durMs}-${bytes}.m4s`;
11
12
  }
12
- function bucketRelPath(camera, profile, subtree, startMs) {
13
- return `${camera}/${profile}/${subtree}/${hourBucketRelPath(startMs)}`;
13
+ var SEG_RE = /^(\d+)\/([^/]+)\/\d{4}\/\d{2}\/\d{2}\/\d{2}\/(\d+)-(\d+)-(\d+)\.m4s$/;
14
+ function parseSegmentPath(relPath) {
15
+ const m = SEG_RE.exec(relPath);
16
+ if (!m) return null;
17
+ return {
18
+ deviceId: Number(m[1]),
19
+ profile: m[2],
20
+ startMs: Number(m[3]),
21
+ durMs: Number(m[4]),
22
+ bytes: Number(m[5])
23
+ };
14
24
  }
15
- function segmentRelPath(camera, profile, subtree, startMs, durMs) {
16
- return `${bucketRelPath(camera, profile, subtree, startMs)}/${startMs}-${durMs}.m4s`;
25
+ //#endregion
26
+ //#region src/recorder/merge-ranges.ts
27
+ function mergeRanges(segments, gapToleranceMs) {
28
+ if (segments.length === 0) return [];
29
+ const sorted = [...segments].toSorted((a, b) => a.startMs - b.startMs);
30
+ const out = [];
31
+ let curStart = sorted[0].startMs;
32
+ let curEnd = sorted[0].startMs + sorted[0].durMs;
33
+ for (let i = 1; i < sorted.length; i++) {
34
+ const s = sorted[i];
35
+ if (s.startMs <= curEnd + gapToleranceMs) curEnd = Math.max(curEnd, s.startMs + s.durMs);
36
+ else {
37
+ out.push({
38
+ startMs: curStart,
39
+ endMs: curEnd
40
+ });
41
+ curStart = s.startMs;
42
+ curEnd = s.startMs + s.durMs;
43
+ }
44
+ }
45
+ out.push({
46
+ startMs: curStart,
47
+ endMs: curEnd
48
+ });
49
+ return out;
17
50
  }
18
- function parseSegmentRelPath(rel) {
19
- const parts = rel.split("/");
20
- const hasSubtree = parts.length === 8;
21
- if (parts.length !== 7 && parts.length !== 8) return null;
22
- const camera = parts[0];
23
- const profile = parts[1];
24
- const subtreeRaw = hasSubtree ? parts[2] : DEFAULT_SUBTREE;
25
- if (subtreeRaw !== "continuous" && subtreeRaw !== "events") return null;
26
- const file = parts[parts.length - 1];
27
- const m = /^(\d+)-(\d+)\.m4s$/.exec(file);
28
- if (!m) return null;
29
- return { camera, profile, subtree: subtreeRaw, startMs: Number(m[1]), durMs: Number(m[2]) };
51
+ //#endregion
52
+ //#region src/recorder/recording-index.ts
53
+ /**
54
+ * In-memory footage index, keyed by deviceId (relativePath → SegmentRow).
55
+ * The framework `storage` cap's `list()` is the ground truth: `hydrateDevice`
56
+ * rebuilds a camera's set from a `list()` result, and `addSegment`/`removeSegments`
57
+ * keep it write-through on finalize/evict. Because every row is derived from a
58
+ * segment path (which encodes start/dur/bytes), the index can never drift from
59
+ * disk. No SQLite, no persistence of its own.
60
+ */
61
+ var RecordingIndex = class {
62
+ byDevice = /* @__PURE__ */ new Map();
63
+ mapFor(deviceId) {
64
+ let m = this.byDevice.get(deviceId);
65
+ if (!m) {
66
+ m = /* @__PURE__ */ new Map();
67
+ this.byDevice.set(deviceId, m);
68
+ }
69
+ return m;
70
+ }
71
+ /**
72
+ * Replace a device's segments FOR ONE LOCATION from a `storage.list` result (paths relative to that
73
+ * location root). Rows on other locations are preserved. Non-segment paths and other devices are ignored.
74
+ */
75
+ hydrateDevice(deviceId, locationId, relPaths) {
76
+ const m = this.mapFor(deviceId);
77
+ for (const [path, existing] of m) if (existing.locationId === locationId) m.delete(path);
78
+ for (const path of relPaths) {
79
+ const p = parseSegmentPath(path);
80
+ if (!p || p.deviceId !== deviceId) continue;
81
+ m.set(path, {
82
+ deviceId: p.deviceId,
83
+ profile: p.profile,
84
+ startMs: p.startMs,
85
+ durMs: p.durMs,
86
+ bytes: p.bytes,
87
+ path,
88
+ locationId
89
+ });
90
+ }
91
+ }
92
+ /** Insert/replace one finalized segment (idempotent by path). */
93
+ addSegment(s) {
94
+ this.mapFor(s.deviceId).set(s.path, s);
95
+ }
96
+ /** Remove segments by relative path, routing each path to the correct device map via its encoded deviceId. */
97
+ removeSegments(paths) {
98
+ for (const p of paths) {
99
+ const parsed = parseSegmentPath(p);
100
+ if (!parsed) continue;
101
+ this.byDevice.get(parsed.deviceId)?.delete(p);
102
+ }
103
+ }
104
+ /** Rows for a device (optionally one profile), sorted by start. */
105
+ segments(deviceId, profile) {
106
+ const m = this.byDevice.get(deviceId);
107
+ if (!m) return [];
108
+ return [...m.values()].filter((s) => profile == null || s.profile === profile).toSorted((a, b) => a.startMs - b.startMs);
109
+ }
110
+ /** Aggregate accounting for a device across ALL its locations (use `accountingForLocation` for one location). */
111
+ accounting(deviceId) {
112
+ const m = this.byDevice.get(deviceId);
113
+ if (!m || m.size === 0) return {
114
+ bytes: 0,
115
+ count: 0,
116
+ oldestMs: null,
117
+ newestMs: null
118
+ };
119
+ let bytes = 0;
120
+ let oldestMs = Infinity;
121
+ let newestMs = -Infinity;
122
+ for (const s of m.values()) {
123
+ bytes += s.bytes;
124
+ if (s.startMs < oldestMs) oldestMs = s.startMs;
125
+ if (s.startMs > newestMs) newestMs = s.startMs;
126
+ }
127
+ return {
128
+ bytes,
129
+ count: m.size,
130
+ oldestMs,
131
+ newestMs
132
+ };
133
+ }
134
+ /** All segments on a storage location across every device, oldest-first. */
135
+ segmentsOnLocation(locationId) {
136
+ const out = [];
137
+ for (const m of this.byDevice.values()) for (const s of m.values()) if (s.locationId === locationId) out.push(s);
138
+ return out.toSorted((a, b) => a.startMs - b.startMs);
139
+ }
140
+ /** Aggregate accounting for a storage location across every device. */
141
+ accountingForLocation(locationId) {
142
+ let bytes = 0;
143
+ let count = 0;
144
+ let oldestMs = Infinity;
145
+ let newestMs = -Infinity;
146
+ for (const m of this.byDevice.values()) for (const s of m.values()) {
147
+ if (s.locationId !== locationId) continue;
148
+ bytes += s.bytes;
149
+ count += 1;
150
+ if (s.startMs < oldestMs) oldestMs = s.startMs;
151
+ if (s.startMs > newestMs) newestMs = s.startMs;
152
+ }
153
+ if (count === 0) return {
154
+ bytes: 0,
155
+ count: 0,
156
+ oldestMs: null,
157
+ newestMs: null
158
+ };
159
+ return {
160
+ bytes,
161
+ count,
162
+ oldestMs,
163
+ newestMs
164
+ };
165
+ }
166
+ /** Binary-search a start-sorted slice for the segment containing epochMs. */
167
+ segmentAtIn(segs, epochMs) {
168
+ if (segs.length === 0) return null;
169
+ let lo = 0;
170
+ let hi = segs.length - 1;
171
+ let cand = -1;
172
+ while (lo <= hi) {
173
+ const mid = lo + hi >> 1;
174
+ if (segs[mid].startMs <= epochMs) {
175
+ cand = mid;
176
+ lo = mid + 1;
177
+ } else hi = mid - 1;
178
+ }
179
+ if (cand < 0) return null;
180
+ const seg = segs[cand];
181
+ return epochMs < seg.startMs + seg.durMs ? seg : null;
182
+ }
183
+ /** The segment whose [startMs, startMs+durMs) window contains `epochMs`, or null if `epochMs` falls in a gap / there is no footage. */
184
+ segmentAt(deviceId, profile, epochMs) {
185
+ return this.segmentAtIn(this.segments(deviceId, profile), epochMs);
186
+ }
187
+ /**
188
+ * If epochMs is covered, returns it unchanged. Otherwise returns the start of the
189
+ * next covered segment forward. Returns null if there is no forward coverage
190
+ * (epoch past all footage, or no footage at all). Only snaps forward — never backward.
191
+ */
192
+ nearestCoveredEdge(deviceId, profile, epochMs) {
193
+ const segs = this.segments(deviceId, profile);
194
+ if (segs.length === 0) return null;
195
+ if (this.segmentAtIn(segs, epochMs) !== null) return epochMs;
196
+ const next = segs.find((s) => s.startMs >= epochMs);
197
+ return next ? next.startMs : null;
198
+ }
199
+ ranges(deviceId, profile, fromMs, toMs, gapToleranceMs) {
200
+ return mergeRanges(this.segments(deviceId, profile).filter((s) => s.startMs + s.durMs > fromMs && s.startMs < toMs), gapToleranceMs).map((r) => ({
201
+ startMs: Math.max(r.startMs, fromMs),
202
+ endMs: Math.min(r.endMs, toMs)
203
+ }));
204
+ }
205
+ };
206
+ //#endregion
207
+ //#region src/recorder/segment-store.ts
208
+ var SegmentStore = class {
209
+ deps;
210
+ constructor(deps) {
211
+ this.deps = deps;
212
+ }
213
+ async hydrate(deviceId, location) {
214
+ const paths = await this.deps.list({
215
+ location,
216
+ prefix: `${deviceId}/`
217
+ });
218
+ this.deps.index.hydrateDevice(deviceId, location, paths);
219
+ }
220
+ async onFinalized(input) {
221
+ let bytes;
222
+ try {
223
+ bytes = await this.deps.statBytes(input.flatAbsPath);
224
+ } catch (err) {
225
+ this.deps.logger.warn("segment stat failed", err);
226
+ return null;
227
+ }
228
+ if (bytes <= 0) return null;
229
+ const relPath = segmentRelPath(input.deviceId, input.profile, input.startMs, input.durMs, bytes);
230
+ const toAbs = `${input.locationRoot}/${relPath}`;
231
+ try {
232
+ await this.deps.moveFile(input.flatAbsPath, toAbs);
233
+ } catch (err) {
234
+ this.deps.logger.warn("segment relocate failed", err);
235
+ return null;
236
+ }
237
+ const row = {
238
+ deviceId: input.deviceId,
239
+ profile: input.profile,
240
+ startMs: input.startMs,
241
+ durMs: input.durMs,
242
+ bytes,
243
+ path: relPath,
244
+ locationId: input.locationId
245
+ };
246
+ this.deps.index.addSegment(row);
247
+ return row;
248
+ }
249
+ /**
250
+ * Delete `rows` via the storage cap under `location` and de-index the ones that delete
251
+ * successfully; returns the reclaimed byte total. Precondition: every row must belong to
252
+ * `location` (`row.locationId === location`) — the caller guarantees this (e.g. the evictable
253
+ * provider feeds rows from `segmentsOnLocation(location)`). Mixed-location rows would be deleted
254
+ * against the wrong location.
255
+ */
256
+ async evict(location, rows) {
257
+ let reclaimed = 0;
258
+ const removed = [];
259
+ for (const r of rows) try {
260
+ await this.deps.deletePath({
261
+ location,
262
+ relativePath: r.path
263
+ });
264
+ removed.push(r.path);
265
+ reclaimed += r.bytes;
266
+ } catch (err) {
267
+ this.deps.logger.warn("segment delete failed", err);
268
+ }
269
+ if (removed.length > 0) this.deps.index.removeSegments(removed);
270
+ return reclaimed;
271
+ }
272
+ };
273
+ //#endregion
274
+ //#region src/recorder/evict-select.ts
275
+ var DAY_MS$2 = 1440 * 60 * 1e3;
276
+ var GB = 1e9;
277
+ function selectEvictions(segments, limits) {
278
+ const oldestFirst = [...segments].toSorted((a, b) => a.startMs - b.startMs);
279
+ const selected = /* @__PURE__ */ new Set();
280
+ const out = [];
281
+ const select = (s) => {
282
+ if (selected.has(s.path)) return;
283
+ selected.add(s.path);
284
+ out.push(s);
285
+ };
286
+ if (limits.maxAgeDays != null && limits.maxAgeDays > 0) {
287
+ const cutoff = limits.nowMs - limits.maxAgeDays * DAY_MS$2;
288
+ for (const s of oldestFirst) if (s.startMs < cutoff) select(s);
289
+ }
290
+ if (limits.maxSizeGb != null && limits.maxSizeGb > 0) {
291
+ const cap = limits.maxSizeGb * GB;
292
+ let remaining = 0;
293
+ for (const s of oldestFirst) if (!selected.has(s.path)) remaining += s.bytes;
294
+ for (const s of oldestFirst) {
295
+ if (remaining <= cap) break;
296
+ if (selected.has(s.path)) continue;
297
+ select(s);
298
+ remaining -= s.bytes;
299
+ }
300
+ }
301
+ return out;
30
302
  }
31
- const HOUR_MS$1 = 36e5;
32
- class RamIndex {
33
- byCam = /* @__PURE__ */ new Map();
34
- static fromScan(entries) {
35
- const idx = new RamIndex();
36
- for (const e of entries) {
37
- const p = parseSegmentRelPath(e.relPath);
38
- if (p) idx.add(p.camera, p.profile, p.startMs, p.durMs, e.bytes, e.locationId, p.subtree);
39
- }
40
- return idx;
41
- }
42
- add(camera, profile, startMs, durMs, bytes, locationId, subtree = DEFAULT_SUBTREE) {
43
- let profiles = this.byCam.get(camera);
44
- if (!profiles) {
45
- profiles = /* @__PURE__ */ new Map();
46
- this.byCam.set(camera, profiles);
47
- }
48
- let segs = profiles.get(profile);
49
- if (!segs) {
50
- segs = [];
51
- profiles.set(profile, segs);
52
- }
53
- if (segs.some((s) => s.startMs === startMs)) return;
54
- segs.push({ startMs, durMs, bytes, locationId, subtree });
55
- segs.sort((a, b) => a.startMs - b.startMs);
56
- }
57
- remove(camera, profile, startMs) {
58
- const segs = this.byCam.get(camera)?.get(profile);
59
- if (!segs) return;
60
- const i = segs.findIndex((s) => s.startMs === startMs);
61
- if (i >= 0) segs.splice(i, 1);
62
- }
63
- /** Profiles that have at least one segment for this camera. */
64
- profiles(camera) {
65
- return [...this.byCam.get(camera)?.keys() ?? []];
66
- }
67
- /** Camera keys with at least one indexed segment. */
68
- cameras() {
69
- return [...this.byCam.keys()];
70
- }
71
- totalBytes(camera) {
72
- let total = 0;
73
- for (const segs of this.byCam.get(camera)?.values() ?? []) {
74
- for (const s of segs) total += s.bytes;
75
- }
76
- return total;
77
- }
78
- /**
79
- * Raw segments for a single (camera,profile) overlapping [fromMs,toMs],
80
- * sorted ascending by start. Unlike `availability` (which merges
81
- * contiguous segments into ranges) this returns the individual
82
- * fragments — the input needed to build a VOD variant playlist.
83
- */
84
- listSegments(camera, profile, fromMs, toMs) {
85
- const segs = this.byCam.get(camera)?.get(profile);
86
- if (!segs) return [];
87
- const out = [];
88
- for (const s of segs) {
89
- const segEnd = s.startMs + s.durMs;
90
- if (segEnd <= fromMs || s.startMs >= toMs) continue;
91
- out.push({ startMs: s.startMs, durMs: s.durMs, locationId: s.locationId, subtree: s.subtree });
92
- }
93
- return out;
94
- }
95
- /**
96
- * Aggregate this camera's segments into UTC hour buckets — the unit
97
- * retention deletes. Each bucket carries its dir rel path, hour-start ms,
98
- * summed bytes (the RAM size counter the retention math prunes on), the
99
- * storage `locationId` its segments live on, and the `subtree` (continuous vs
100
- * events). Each distinct (subtree, hour, location) is a separate bucket — so
101
- * mixed combinations split apart and each is `rm`'d from the right root under
102
- * its own per-subtree retention policy. Buckets are per profile, ascending.
103
- */
104
- hourBuckets(camera) {
105
- const out = [];
106
- for (const [profile, segs] of this.byCam.get(camera) ?? []) {
107
- const byBucket = /* @__PURE__ */ new Map();
108
- for (const s of segs) {
109
- const hourStartMs = Math.floor(s.startMs / HOUR_MS$1) * HOUR_MS$1;
110
- const key = `${s.subtree} ${hourStartMs} ${s.locationId ?? ""}`;
111
- const cur = byBucket.get(key);
112
- if (cur) {
113
- cur.bytes += s.bytes;
114
- cur.count += 1;
115
- } else byBucket.set(key, { hourStartMs, locationId: s.locationId, subtree: s.subtree, bytes: s.bytes, count: 1 });
116
- }
117
- for (const b of byBucket.values()) {
118
- out.push({
119
- relPath: `${camera}/${profile}/${b.subtree}/${hourBucketRelPath(b.hourStartMs)}`,
120
- hourStartMs: b.hourStartMs,
121
- bytes: b.bytes,
122
- segmentCount: b.count,
123
- locationId: b.locationId,
124
- subtree: b.subtree
125
- });
126
- }
127
- }
128
- return out;
129
- }
130
- /**
131
- * Drop every segment in the hour bucket named by `relPath`
132
- * (`<camera>/<profile>/<subtree>/<Y>/<M>/<D>/<H>`) whose `locationId` matches
133
- * (exact, incl. `undefined === undefined` for legacy single-root segments).
134
- * Scoping by both subtree (in the path) and location keeps the hour's
135
- * other-subtree / other-location segments intact when one bucket is `rm`'d.
136
- * Returns the count removed; a non-bucket or unknown path is a no-op. The
137
- * on-disk dir is removed by the sweeper — this keeps the size counter in sync.
138
- */
139
- removeBucketByRelPath(relPath, locationId) {
140
- const parts = relPath.split("/");
141
- if (parts.length !== 7) return 0;
142
- const [camera, profile, subtree, y, mo, d, h] = parts;
143
- if (subtree !== "continuous" && subtree !== "events") return 0;
144
- const hourStartMs = Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h));
145
- if (Number.isNaN(hourStartMs)) return 0;
146
- const segs = this.byCam.get(camera)?.get(profile);
147
- if (!segs) return 0;
148
- let removed = 0;
149
- for (let i = segs.length - 1; i >= 0; i--) {
150
- const s = segs[i];
151
- if (Math.floor(s.startMs / HOUR_MS$1) * HOUR_MS$1 === hourStartMs && s.locationId === locationId && s.subtree === subtree) {
152
- segs.splice(i, 1);
153
- removed++;
154
- }
155
- }
156
- return removed;
157
- }
158
- /**
159
- * Un-retained segments (the modes-engine policy reaper's work list). A
160
- * segment stays a candidate until {@link markRetained} confirms it falls in a
161
- * trigger window — then the reaper leaves it alone (only retention prunes it).
162
- */
163
- policyCandidates(camera) {
164
- const out = [];
165
- for (const [profile, segs] of this.byCam.get(camera) ?? []) {
166
- for (const s of segs) {
167
- if (s.retained) continue;
168
- out.push({ profile, startMs: s.startMs, durMs: s.durMs, endMs: s.startMs + s.durMs, locationId: s.locationId, subtree: s.subtree });
169
- }
170
- }
171
- return out;
172
- }
173
- /** Mark a segment as policy-retained so the reaper stops reconsidering it. */
174
- markRetained(camera, profile, startMs) {
175
- const seg = this.byCam.get(camera)?.get(profile)?.find((s) => s.startMs === startMs);
176
- if (seg) seg.retained = true;
177
- }
178
- /**
179
- * The earliest `startMs` of any segment for this camera across all profiles
180
- * and subtrees, or `null` when the camera has no indexed segments.
181
- */
182
- oldestStartMs(camera) {
183
- let oldest = null;
184
- for (const segs of this.byCam.get(camera)?.values() ?? []) {
185
- for (const s of segs) {
186
- if (oldest === null || s.startMs < oldest) oldest = s.startMs;
187
- }
188
- }
189
- return oldest;
190
- }
191
- /** Merged availability ranges overlapping [fromMs,toMs], per profile. */
192
- availability(camera, fromMs, toMs) {
193
- const out = [];
194
- for (const [profile, segs] of this.byCam.get(camera) ?? []) {
195
- let cur = null;
196
- for (const s of segs) {
197
- const segEnd = s.startMs + s.durMs;
198
- if (segEnd <= fromMs || s.startMs >= toMs) {
199
- if (cur) {
200
- out.push(cur);
201
- cur = null;
202
- }
203
- continue;
204
- }
205
- if (cur && s.startMs === cur.endMs) {
206
- cur.endMs = segEnd;
207
- } else {
208
- if (cur) out.push(cur);
209
- cur = { profile, startMs: s.startMs, endMs: segEnd };
210
- }
211
- }
212
- if (cur) out.push(cur);
213
- }
214
- return out;
215
- }
303
+ /**
304
+ * Pick the oldest segments whose cumulative bytes reach `targetBytes` (free ≈ targetBytes).
305
+ * Oldest-first, no pinning. Returns all segments if the target exceeds the total; empty for a non-positive target.
306
+ *
307
+ * Selection is segment-granular: the actual reclaimable bytes may EXCEED `targetBytes` by up to
308
+ * the size of the last selected segment (a 1-byte target still evicts one whole segment). Callers
309
+ * sizing a reclaim share (e.g. StoragePressureManager) should expect this overshoot.
310
+ */
311
+ function selectEvictionsByBytes(segments, targetBytes) {
312
+ if (targetBytes <= 0) return [];
313
+ const oldestFirst = [...segments].toSorted((a, b) => a.startMs - b.startMs);
314
+ const out = [];
315
+ let freed = 0;
316
+ for (const s of oldestFirst) {
317
+ if (freed >= targetBytes) break;
318
+ out.push(s);
319
+ freed += s.bytes;
320
+ }
321
+ return out;
216
322
  }
217
- const HOUR_MS = 36e5;
218
- function planRetention(buckets, policy, nowMs) {
219
- const sorted = [...buckets].sort((a, b) => a.hourStartMs - b.hourStartMs);
220
- const survivors = [];
221
- const doomed = [];
222
- if (policy.maxAgeMs != null) {
223
- const cutoff = nowMs - policy.maxAgeMs;
224
- for (const b of sorted) {
225
- if (b.hourStartMs + HOUR_MS <= cutoff) doomed.push({ ...b, reason: "age" });
226
- else survivors.push(b);
227
- }
228
- } else {
229
- survivors.push(...sorted);
230
- }
231
- if (policy.maxSizeBytes != null) {
232
- let total = survivors.reduce((sum, b) => sum + b.bytes, 0);
233
- while (total > policy.maxSizeBytes && survivors.length > 1) {
234
- const oldest = survivors.shift();
235
- total -= oldest.bytes;
236
- doomed.push({ ...oldest, reason: "size" });
237
- }
238
- }
239
- doomed.sort((a, b) => a.hourStartMs - b.hourStartMs);
240
- return {
241
- deleteBuckets: doomed,
242
- reclaimedBytes: doomed.reduce((sum, b) => sum + b.bytes, 0)
243
- };
323
+ //#endregion
324
+ //#region src/recorder/storage-evictable-provider.ts
325
+ /**
326
+ * Implements the `storage-evictable` cap surface for recording footage. The core
327
+ * StoragePressureManager owns the trigger (per-location free-space monitoring); this
328
+ * provider decides WHAT footage is expendable (oldest-first, no pinning) and deletes it
329
+ * via `SegmentStore.evict`, which removes the file through the `storage` cap and de-indexes.
330
+ *
331
+ * The cap's `locationId` is used directly as the storage `location` (identity); see Plan 2d
332
+ * notes. Wiring this class to the cap + the SegmentStore happens in Plan 2e.
333
+ */
334
+ var StorageEvictableProvider = class {
335
+ deps;
336
+ constructor(deps) {
337
+ this.deps = deps;
338
+ }
339
+ async getEvictableUsage(input) {
340
+ return { bytes: this.deps.index.accountingForLocation(input.locationId).bytes };
341
+ }
342
+ async evict(input) {
343
+ const onLocation = this.deps.index.segmentsOnLocation(input.locationId);
344
+ const victims = selectEvictionsByBytes(onLocation, input.targetBytes);
345
+ return {
346
+ reclaimedBytes: await this.deps.store.evict(input.locationId, victims),
347
+ exhausted: victims.length >= onLocation.length
348
+ };
349
+ }
350
+ };
351
+ //#endregion
352
+ //#region src/recorder/redundant-segments.ts
353
+ /**
354
+ * Return the indices (into `segs`) of segments safe to delete: those fully
355
+ * contained within a kept segment `[coverStart, coverEnd]`. Sorting by start
356
+ * ascending, then by end DESCENDING, guarantees the containing (longer) segment
357
+ * is seen first and kept, and any shorter segment nested inside it is removed.
358
+ */
359
+ function selectRedundantSegments(segs) {
360
+ if (segs.length < 2) return [];
361
+ const order = segs.map((s, i) => ({
362
+ start: s.startMs,
363
+ end: s.startMs + s.durMs,
364
+ i
365
+ })).toSorted((a, b) => a.start - b.start || b.end - a.end);
366
+ const remove = [];
367
+ let coverStart = Number.NEGATIVE_INFINITY;
368
+ let coverEnd = Number.NEGATIVE_INFINITY;
369
+ for (const seg of order) if (seg.start >= coverStart && seg.end <= coverEnd && seg.end > seg.start) remove.push(seg.i);
370
+ else {
371
+ coverStart = seg.start;
372
+ coverEnd = seg.end;
373
+ }
374
+ return remove;
375
+ }
376
+ //#endregion
377
+ //#region src/recorder/janitor.ts
378
+ /** Group an array by a string key. */
379
+ function groupBy(items, key) {
380
+ const out = /* @__PURE__ */ new Map();
381
+ for (const it of items) {
382
+ const k = key(it);
383
+ const arr = out.get(k);
384
+ if (arr) arr.push(it);
385
+ else out.set(k, [it]);
386
+ }
387
+ return out;
244
388
  }
245
- function toMinutes(hhmm) {
246
- const [h, m] = hhmm.split(":");
247
- return Number(h) * 60 + Number(m);
389
+ async function runRedundancyJanitor(deps) {
390
+ let files = 0;
391
+ let bytes = 0;
392
+ for (const deviceId of deps.deviceIds) {
393
+ const byProfile = groupBy(deps.segmentsFor(deviceId), (r) => r.profile);
394
+ for (const [profile, rows] of byProfile) {
395
+ const sorted = [...rows].toSorted((a, b) => a.startMs - b.startMs);
396
+ const redundant = selectRedundantSegments(sorted);
397
+ if (redundant.length === 0) continue;
398
+ const victims = redundant.map((i) => sorted[i]);
399
+ for (const [location, vrows] of groupBy(victims, (v) => v.locationId)) try {
400
+ const reclaimed = await deps.evict(location, vrows);
401
+ files += vrows.length;
402
+ bytes += reclaimed;
403
+ } catch (err) {
404
+ deps.logger.warn("janitor: evict failed (skipping)", { meta: {
405
+ deviceId,
406
+ profile,
407
+ location,
408
+ count: vrows.length,
409
+ error: err instanceof Error ? err.message : String(err)
410
+ } });
411
+ }
412
+ }
413
+ }
414
+ if (files > 0) deps.logger.info("janitor: removed redundant recording segments", { meta: {
415
+ files,
416
+ bytes
417
+ } });
418
+ return {
419
+ files,
420
+ bytes
421
+ };
248
422
  }
249
- function isScheduleActive(schedule, clock) {
250
- if (schedule.kind === "always") return true;
251
- if (schedule.days && !schedule.days.includes(clock.weekday)) return false;
252
- const start = toMinutes(schedule.start);
253
- const end = toMinutes(schedule.end);
254
- const m = clock.minutesOfDay;
255
- if (start === end) return false;
256
- if (start < end) return m >= start && m < end;
257
- return m >= start || m < end;
423
+ //#endregion
424
+ //#region src/recorder/event-map.ts
425
+ var EventMap = class {
426
+ byDevice = /* @__PURE__ */ new Map();
427
+ record(deviceId, marker) {
428
+ const list = this.byDevice.get(deviceId) ?? [];
429
+ list.push({ ...marker });
430
+ this.byDevice.set(deviceId, list);
431
+ }
432
+ events(deviceId, fromMs, toMs) {
433
+ const list = this.byDevice.get(deviceId);
434
+ if (!list) return [];
435
+ return list.filter((e) => e.t >= fromMs && e.t <= toMs).toSorted((a, b) => a.t - b.t);
436
+ }
437
+ prune(nowMs, maxAgeMs) {
438
+ const cutoff = nowMs - maxAgeMs;
439
+ let dropped = 0;
440
+ for (const [deviceId, list] of this.byDevice) {
441
+ const kept = list.filter((e) => e.t >= cutoff);
442
+ dropped += list.length - kept.length;
443
+ this.byDevice.set(deviceId, kept);
444
+ }
445
+ return dropped;
446
+ }
447
+ };
448
+ //#endregion
449
+ //#region src/recorder/event-capture.ts
450
+ function markerFromMotion(data, pad) {
451
+ if (!data.detected) return null;
452
+ return {
453
+ t: data.timestamp,
454
+ startMs: data.timestamp - pad.padPreMs,
455
+ endMs: data.timestamp + pad.padPostMs,
456
+ source: "motion",
457
+ ...data.regions !== void 0 ? { metadata: { regions: data.regions } } : {}
458
+ };
258
459
  }
259
- function isRecordingDemanded(rules, clock, triggers, nowMs) {
260
- for (const r of rules) {
261
- if (!isScheduleActive(r.schedule, clock)) continue;
262
- if (r.mode === "continuous") return true;
263
- const lastMs = r.mode === "onMotion" ? triggers.lastMotionMs : triggers.lastAudioMs;
264
- if (lastMs != null && nowMs - lastMs <= r.postBufferSec * 1e3) return true;
265
- }
266
- return false;
460
+ function subscribeEventCapture(deps) {
461
+ const { eventBus, map, padPreMs, padPostMs, onMotion } = deps;
462
+ return eventBus.subscribe({ category: EventCategory.MotionOnMotionChanged }, (event) => {
463
+ const mk = markerFromMotion(event.data, {
464
+ padPreMs,
465
+ padPostMs
466
+ });
467
+ if (!mk) return;
468
+ map.record(event.data.deviceId, mk);
469
+ onMotion?.(event.data.deviceId, event.data.timestamp);
470
+ });
267
471
  }
268
- function isContinuousActive(rules, clock) {
269
- return rules.some((r) => r.mode === "continuous" && isScheduleActive(r.schedule, clock));
472
+ //#endregion
473
+ //#region src/recorder/day-bucket.ts
474
+ /** Pure helpers to bucket recording segment starts into local calendar days. */
475
+ var DAY_MS$1 = 1440 * 60 * 1e3;
476
+ /**
477
+ * Epoch (UTC ms) of the local midnight that starts the day containing `ms`.
478
+ * `tzOffsetMinutes` is minutes to ADD to UTC to get local time — i.e. the client
479
+ * sends `-new Date().getTimezoneOffset()`. Returning a UTC epoch (not a date
480
+ * string) lets the viewer compare directly against the epoch it computes per
481
+ * calendar cell, so markers line up regardless of timezone.
482
+ */
483
+ function localMidnightEpoch(ms, tzOffsetMinutes) {
484
+ const off = tzOffsetMinutes * 6e4;
485
+ const local = ms + off;
486
+ return local - (local % DAY_MS$1 + DAY_MS$1) % DAY_MS$1 - off;
270
487
  }
271
- function isSegmentDemanded(rules, clock, triggers, segStartMs, segEndMs) {
272
- for (const r of rules) {
273
- if (!isScheduleActive(r.schedule, clock)) continue;
274
- if (r.mode === "continuous") return true;
275
- const lastMs = r.mode === "onMotion" ? triggers.lastMotionMs : triggers.lastAudioMs;
276
- if (lastMs == null) continue;
277
- const winStart = lastMs - r.preBufferSec * 1e3;
278
- const winEnd = lastMs + r.postBufferSec * 1e3;
279
- if (segEndMs >= winStart && segStartMs <= winEnd) return true;
280
- }
281
- return false;
488
+ /**
489
+ * Sorted, distinct local-midnight epochs for every segment start in [fromMs, toMs).
490
+ */
491
+ function distinctRecordingDays(startsMs, fromMs, toMs, tzOffsetMinutes) {
492
+ const days = /* @__PURE__ */ new Set();
493
+ for (const s of startsMs) {
494
+ if (s < fromMs || s >= toMs) continue;
495
+ days.add(localMidnightEpoch(s, tzOffsetMinutes));
496
+ }
497
+ return [...days].toSorted((a, b) => a - b);
282
498
  }
283
- class RecorderCore {
284
- constructor(deps) {
285
- this.deps = deps;
286
- }
287
- cameras = /* @__PURE__ */ new Map();
288
- /**
289
- * Index of ALL recordings on disk (attached or not), rebuilt from a periodic
290
- * disk scan. Read-only fallback for queries about a camera that isn't
291
- * currently attached — so past recordings stay playable after detach/restart.
292
- */
293
- playbackIndex = new RamIndex();
294
- /** Replace the playback index from a fresh disk scan (boot + periodic). */
295
- setPlaybackIndex(entries) {
296
- this.playbackIndex = RamIndex.fromScan(entries);
297
- }
298
- /** The index that answers queries for a camera: its live one if attached,
299
- * else the scanned playback index. */
300
- indexFor(deviceId) {
301
- return this.cameras.get(deviceId)?.index ?? this.playbackIndex;
302
- }
303
- /**
304
- * Start continuous recording for a camera: one passthrough writer per
305
- * profile, each pulling its resolved RTSP url into a per-profile output
306
- * directory. Idempotent-ish — re-attaching a live camera detaches first.
307
- */
308
- async attach(input) {
309
- if (input.profiles.length === 0) {
310
- throw new Error(`RecorderCore.attach: no profiles for device ${input.deviceId}`);
311
- }
312
- if (this.cameras.has(input.deviceId)) await this.detach(input.deviceId);
313
- const index = new RamIndex();
314
- const writers = [];
315
- const pipelineKeys = [];
316
- for (const profile of input.profiles) {
317
- const source = await this.deps.acquireSource(input.deviceId, profile);
318
- const outDir = input.outDirs?.[profile] ?? `${this.deps.dataDir}/${input.deviceId}/${profile}`;
319
- const writer = this.deps.makeWriter({ rtspUrl: source.url, outDir, segmentSeconds: input.segmentSeconds });
320
- writer.start();
321
- writers.push(writer);
322
- pipelineKeys.push(source.pipelineKey);
323
- }
324
- this.cameras.set(input.deviceId, {
325
- index,
326
- writers,
327
- profiles: [...input.profiles],
328
- pipelineKeys,
329
- rules: input.rules ? [...input.rules] : [],
330
- triggers: {}
331
- });
332
- this.deps.logger.info("recorder attached", {
333
- meta: {
334
- deviceId: input.deviceId,
335
- profiles: input.profiles,
336
- segmentSeconds: input.segmentSeconds,
337
- ruleCount: input.rules?.length ?? 0
338
- }
339
- });
340
- }
341
- /**
342
- * Record a motion / audio trigger for a camera (drives `onMotion` /
343
- * `onAudioThreshold` rules). The caller applies the threshold test (motion
344
- * happened / audio over `thresholdDbfs`) before calling — the core only
345
- * stores the latest qualifying timestamp. No-op for an unattached camera.
346
- */
347
- recordTrigger(deviceId, kind, tsMs) {
348
- const cam = this.cameras.get(deviceId);
349
- if (!cam) return;
350
- if (kind === "motion") cam.triggers.lastMotionMs = tsMs;
351
- else cam.triggers.lastAudioMs = tsMs;
352
- }
353
- /**
354
- * Feed an audio level (dBFS) sample for a camera. Records an audio trigger
355
- * iff some `onAudioThreshold` rule's `thresholdDbfs` is met (louder = dBFS
356
- * closer to 0, so `dbfs >= thresholdDbfs`). The threshold lives on the rule,
357
- * so the comparison stays here rather than in the event-bus glue. No-op for an
358
- * unattached camera or one with no audio rule.
359
- */
360
- onAudioLevel(deviceId, dbfs, tsMs) {
361
- const cam = this.cameras.get(deviceId);
362
- if (!cam) return;
363
- const over = cam.rules.some(
364
- (r) => r.mode === "onAudioThreshold" && r.thresholdDbfs != null && dbfs >= r.thresholdDbfs
365
- );
366
- if (over) cam.triggers.lastAudioMs = tsMs;
367
- }
368
- /**
369
- * Decide whether a finalized segment `[segStartMs, segEndMs]` should be
370
- * kept (relocated into the permanent tree + indexed) or discarded. No rules
371
- * = continuous (always keep). Trigger modes keep only when recording is
372
- * demanded at the segment's end (within `postBufferSec` of a trigger).
373
- * `preBufferSec` (retroactive retain BEFORE a trigger) is NOT handled here —
374
- * that's increment B. Unknown camera → discard.
375
- */
376
- shouldRetainSegment(deviceId, _segStartMs, segEndMs, clock) {
377
- const cam = this.cameras.get(deviceId);
378
- if (!cam) return false;
379
- if (cam.rules.length === 0) return true;
380
- return isRecordingDemanded(cam.rules, clock, cam.triggers, segEndMs);
381
- }
382
- /** Mark an indexed segment policy-retained (reaper stops reconsidering it). */
383
- markSegmentRetained(deviceId, profile, startMs) {
384
- this.cameras.get(deviceId)?.index.markRetained(String(deviceId), profile, startMs);
385
- }
386
- /**
387
- * Policy reaper — the pre/post-buffer enforcement (modes engine increment B).
388
- * For every rules-camera, walk its un-retained (candidate) segments:
389
- * - inside a trigger window (incl. `preBufferSec` BEFORE a trigger) → mark
390
- * retained so it survives (only retention prunes it after);
391
- * - else, once the segment is older than the longest `preBufferSec` (so a
392
- * late trigger can no longer claim it retroactively) → delete it;
393
- * - otherwise hold it — re-checked next sweep.
394
- * Cameras with NO rules are pure-continuous: skipped here (retention-only).
395
- */
396
- async sweepPolicy(toClock, nowMs, deleteSegment) {
397
- for (const [deviceId, cam] of this.cameras) {
398
- if (cam.rules.length === 0) continue;
399
- const maxPreBufferMs = Math.max(0, ...cam.rules.map((r) => r.preBufferSec)) * 1e3;
400
- const camKey = String(deviceId);
401
- for (const c of cam.index.policyCandidates(camKey)) {
402
- if (isSegmentDemanded(cam.rules, toClock(c.endMs), cam.triggers, c.startMs, c.endMs)) {
403
- cam.index.markRetained(camKey, c.profile, c.startMs);
404
- } else if (c.endMs + maxPreBufferMs <= nowMs) {
405
- try {
406
- await deleteSegment(deviceId, c.profile, c.startMs, c.durMs, c.locationId, c.subtree);
407
- cam.index.remove(camKey, c.profile, c.startMs);
408
- } catch (err) {
409
- this.deps.logger.warn("recorder policy reap rm failed", {
410
- tags: { deviceId },
411
- meta: { deviceId, profile: c.profile, startMs: c.startMs, error: String(err) }
412
- });
413
- }
414
- }
415
- }
416
- }
417
- }
418
- /** Record a finalized segment into the camera's in-memory index. `locationId`
419
- * is the storage location its file was written to; `subtree` the
420
- * continuous/events subtree it was relocated into (per-subtree retention +
421
- * path resolution). */
422
- onSegmentFinalized(deviceId, profile, startMs, durMs, bytes, locationId, subtree = "continuous") {
423
- this.cameras.get(deviceId)?.index.add(String(deviceId), profile, startMs, durMs, bytes, locationId, subtree);
424
- }
425
- /**
426
- * Seed a camera's live index with pre-existing on-disk segments discovered by
427
- * a sized scan. Idempotent: `RamIndex.add` already dedupes by `(profile,
428
- * startMs)` — re-seeding or a concurrent `onSegmentFinalized` for the same
429
- * start timestamp is silently ignored, so there is no double-count.
430
- *
431
- * MUST be called AFTER `core.attach(deviceId, …)` so the seed lands in the
432
- * camera's live index. If the camera is not attached (i.e. `attach` was never
433
- * called or already detached), this is a no-op — warn and return.
434
- */
435
- seedIndexFromScan(deviceId, entries) {
436
- const cam = this.cameras.get(deviceId);
437
- if (!cam) {
438
- this.deps.logger.warn("recorder seedIndexFromScan: device not attached, skipping seed", { tags: { deviceId }, meta: { deviceId } });
439
- return;
440
- }
441
- const camKey = String(deviceId);
442
- for (const e of entries) {
443
- cam.index.add(camKey, e.profile, e.startMs, e.durMs, e.bytes, e.locationId, e.subtree);
444
- }
445
- }
446
- /** Raw segments for one (camera,profile) overlapping [fromMs,toMs]. Falls
447
- * back to the scanned playback index when the camera isn't attached. Each
448
- * ref carries its `locationId` + `subtree` so playback resolves the path. */
449
- listSegments(deviceId, profile, fromMs, toMs) {
450
- return this.indexFor(deviceId).listSegments(String(deviceId), profile, fromMs, toMs);
451
- }
452
- /**
453
- * Classify a finalized segment ending at `segEndMs` into its on-disk subtree:
454
- * `continuous` when continuous recording is active at that time (a continuous
455
- * rule's schedule applies, or the camera has NO rules = pure continuous),
456
- * else `events` (kept only by a motion/audio trigger). Drives where the
457
- * watcher relocates the segment and how it's retained. Unknown camera →
458
- * `continuous` (harmless default; an unattached camera never finalizes).
459
- */
460
- classifySubtree(deviceId, _segEndMs, clock) {
461
- const cam = this.cameras.get(deviceId);
462
- if (!cam || cam.rules.length === 0) return "continuous";
463
- return isContinuousActive(cam.rules, clock) ? "continuous" : "events";
464
- }
465
- /** Profiles this camera has recordings for — live profiles if attached, else
466
- * whatever the disk scan found. */
467
- getProfiles(deviceId) {
468
- const cam = this.cameras.get(deviceId);
469
- return cam ? cam.profiles : this.playbackIndex.profiles(String(deviceId));
470
- }
471
- getAvailability(deviceId, fromMs, toMs) {
472
- return { deviceId, ranges: this.indexFor(deviceId).availability(String(deviceId), fromMs, toMs) };
473
- }
474
- getStatus(deviceId) {
475
- const cam = this.cameras.get(deviceId);
476
- const enabled = (cam?.writers.length ?? 0) > 0;
477
- return {
478
- deviceId,
479
- enabled,
480
- activeMode: enabled ? "continuous" : "off",
481
- nodeId: this.deps.nodeId,
482
- storageBytes: this.indexFor(deviceId).totalBytes(String(deviceId))
483
- };
484
- }
485
- /**
486
- * Prune aged-out / over-cap hour buckets for every attached camera, applying
487
- * the `continuous` and `events` subtree policies INDEPENDENTLY (spec §6 —
488
- * event footage usually outlives continuous).
489
- *
490
- * Per camera: aggregate the RAM index into hour buckets, split them by
491
- * subtree, ask {@link planRetention} which to delete using that subtree's
492
- * policy, `rm` each bucket dir, and — only on a successful `rm` — drop its
493
- * segments from the index so the storage counter stays truthful. A failed
494
- * `rm` leaves the bucket in the index for the next sweep to retry (no silent
495
- * byte-counter drift). Pure decision, injected I/O.
496
- */
497
- async sweepRetention(resolvePolicy, nowMs, removeBucketDir) {
498
- const results = [];
499
- for (const [deviceId, cam] of this.cameras) {
500
- const { deletedBuckets, reclaimedBytes } = await this.pruneSubtrees(
501
- deviceId,
502
- cam.index,
503
- resolvePolicy,
504
- nowMs,
505
- removeBucketDir,
506
- "recorder retention rm failed"
507
- );
508
- results.push({ deviceId, deletedBuckets, reclaimedBytes });
509
- }
510
- return results;
511
- }
512
- /**
513
- * Shared per-device retention prune used by {@link sweepRetention} and
514
- * {@link pruneFootageForDevice}: split the camera's hour buckets by subtree,
515
- * `rm` each doomed bucket, sync the index only on a successful `rm`, and emit
516
- * one structured `recorder eviction` INFO line per (subtree, reason) group
517
- * that actually deleted something — carrying the reason, segment + byte
518
- * totals, and the policy condition that triggered the eviction.
519
- */
520
- async pruneSubtrees(deviceId, index, resolvePolicy, nowMs, removeBucketDir, rmFailedMsg) {
521
- const camKey = String(deviceId);
522
- let deletedBuckets = 0;
523
- let reclaimedBytes = 0;
524
- const bySubtree = /* @__PURE__ */ new Map();
525
- for (const b of index.hourBuckets(camKey)) {
526
- const st = b.subtree ?? "continuous";
527
- const arr = bySubtree.get(st);
528
- if (arr) arr.push(b);
529
- else bySubtree.set(st, [b]);
530
- }
531
- for (const [subtree, buckets] of bySubtree) {
532
- const policy = resolvePolicy(deviceId, subtree);
533
- const usedBytesBefore = index.totalBytes(camKey);
534
- const plan = planRetention(buckets, policy, nowMs);
535
- const byReason = /* @__PURE__ */ new Map();
536
- for (const b of plan.deleteBuckets) {
537
- try {
538
- await removeBucketDir(b.relPath, b.locationId);
539
- } catch (err) {
540
- this.deps.logger.warn(rmFailedMsg, {
541
- tags: { deviceId },
542
- meta: { deviceId, relPath: b.relPath, locationId: b.locationId, error: String(err) }
543
- });
544
- continue;
545
- }
546
- const before = index.totalBytes(camKey);
547
- index.removeBucketByRelPath(b.relPath, b.locationId);
548
- const reclaimed = before - index.totalBytes(camKey);
549
- reclaimedBytes += reclaimed;
550
- deletedBuckets++;
551
- const prev = byReason.get(b.reason);
552
- byReason.set(b.reason, {
553
- deletedBuckets: (prev?.deletedBuckets ?? 0) + 1,
554
- deletedSegments: (prev?.deletedSegments ?? 0) + b.segmentCount,
555
- reclaimedBytes: (prev?.reclaimedBytes ?? 0) + reclaimed
556
- });
557
- }
558
- for (const [reason, tally] of byReason) {
559
- this.deps.logger.info("recorder eviction", {
560
- tags: { deviceId },
561
- meta: {
562
- deviceId,
563
- reason,
564
- subtree,
565
- deletedBuckets: tally.deletedBuckets,
566
- deletedSegments: tally.deletedSegments,
567
- reclaimedBytes: tally.reclaimedBytes,
568
- condition: reason === "age" ? { maxAgeDays: policy.maxAgeMs != null ? policy.maxAgeMs / 864e5 : null } : { maxSizeGb: policy.maxSizeBytes != null ? policy.maxSizeBytes / 1e9 : null, usedBytesBefore }
569
- }
570
- });
571
- }
572
- }
573
- return { deletedBuckets, reclaimedBytes };
574
- }
575
- /**
576
- * Apply this device's retention policy to its footage RIGHT NOW for one
577
- * device, returning the oldest surviving segment start (the "retention
578
- * floor") plus deletion accounting. The floor is the key output B3 uses to
579
- * prune analytics events to the same boundary.
580
- *
581
- * Mirrors the per-device inner loop of {@link sweepRetention} but operates
582
- * on a single camera and exposes the result — reuses the same
583
- * `planRetention` + `removeBucketDir` path so the math stays consistent.
584
- *
585
- * @param deviceId Camera to prune.
586
- * @param nowMs Wall-clock time for the age cutoff.
587
- * @param resolvePolicy Returns the retention policy for each subtree.
588
- * @param removeBucketDir Injected `rm -rf` for one hour-bucket dir.
589
- */
590
- async pruneFootageForDevice(deviceId, nowMs, resolvePolicy, removeBucketDir) {
591
- const cam = this.cameras.get(deviceId);
592
- if (!cam) {
593
- return { floorMs: null, deletedBuckets: 0, reclaimedBytes: 0 };
594
- }
595
- const camKey = String(deviceId);
596
- const { deletedBuckets, reclaimedBytes } = await this.pruneSubtrees(
597
- deviceId,
598
- cam.index,
599
- resolvePolicy,
600
- nowMs,
601
- removeBucketDir,
602
- "recorder pruneFootage rm failed"
603
- );
604
- const floorMs = cam.index.oldestStartMs(camKey);
605
- return { floorMs, deletedBuckets, reclaimedBytes };
606
- }
607
- /**
608
- * Every device with recordings on this node — attached cameras (live RAM
609
- * index) plus detached ones surfaced by the disk-scan playback index. The
610
- * free-space guard frees space "from every device", so it walks the union.
611
- */
612
- recordedDeviceIds() {
613
- const ids = /* @__PURE__ */ new Set();
614
- for (const id of this.cameras.keys()) ids.add(id);
615
- for (const cam of this.playbackIndex.cameras()) {
616
- const n = Number(cam);
617
- if (Number.isFinite(n)) ids.add(n);
618
- }
619
- return [...ids];
620
- }
621
- /**
622
- * Total footage bytes stored on a location, across every recorded device.
623
- * Backs the `storage-evictable` provider's `getEvictableUsage` so the core
624
- * StoragePressureManager can fan out a deficit proportionally.
625
- */
626
- evictableBytesOnLocation(locationId) {
627
- let total = 0;
628
- for (const deviceId of this.recordedDeviceIds()) {
629
- const camKey = String(deviceId);
630
- for (const b of this.indexFor(deviceId).hourBuckets(camKey)) {
631
- if (b.locationId === locationId) total += b.bytes;
632
- }
633
- }
634
- return total;
635
- }
636
- /**
637
- * Free ~`targetBytes` of footage on a location by deleting the OLDEST hour
638
- * buckets first, globally across devices (oldest-anywhere wins). Backs the
639
- * `storage-evictable` provider's `evict`. Only successfully-removed buckets
640
- * count toward `reclaimedBytes`. `exhausted` = ran out of buckets before
641
- * hitting the target. Per-device eviction is logged device-tagged.
642
- */
643
- async evictBytesOnLocation(locationId, targetBytes, removeBucketDir) {
644
- const candidates = [];
645
- for (const deviceId of this.recordedDeviceIds()) {
646
- const camKey = String(deviceId);
647
- for (const b of this.indexFor(deviceId).hourBuckets(camKey)) {
648
- if (b.locationId === locationId) candidates.push({ deviceId, bucket: b });
649
- }
650
- }
651
- candidates.sort((a, b) => a.bucket.hourStartMs - b.bucket.hourStartMs);
652
- let reclaimed = 0;
653
- const perDevice = /* @__PURE__ */ new Map();
654
- let hitTarget = false;
655
- for (const { deviceId, bucket } of candidates) {
656
- if (reclaimed >= targetBytes) {
657
- hitTarget = true;
658
- break;
659
- }
660
- try {
661
- await removeBucketDir(bucket.relPath, bucket.locationId);
662
- } catch (err) {
663
- this.deps.logger.warn("recorder free-space rm failed", {
664
- tags: { deviceId },
665
- meta: { deviceId, relPath: bucket.relPath, locationId: bucket.locationId, error: String(err) }
666
- });
667
- continue;
668
- }
669
- const index = this.indexFor(deviceId);
670
- const camKey = String(deviceId);
671
- const before = index.totalBytes(camKey);
672
- index.removeBucketByRelPath(bucket.relPath, bucket.locationId);
673
- const r = before - index.totalBytes(camKey);
674
- reclaimed += r;
675
- const tally = perDevice.get(deviceId) ?? { buckets: 0, bytes: 0 };
676
- tally.buckets += 1;
677
- tally.bytes += r;
678
- perDevice.set(deviceId, tally);
679
- }
680
- for (const [deviceId, tally] of perDevice) {
681
- if (tally.buckets > 0) {
682
- this.deps.logger.info("recorder eviction", {
683
- tags: { deviceId },
684
- meta: { deviceId, reason: "free-space", locationId, deletedBuckets: tally.buckets, reclaimedBytes: tally.bytes }
685
- });
686
- }
687
- }
688
- return { reclaimedBytes: reclaimed, exhausted: !hitTarget };
689
- }
690
- /**
691
- * Clear the live index for an attached camera so it can be re-seeded from a
692
- * fresh sized disk scan. All writers and policy state are preserved — only the
693
- * segment byte accounting is reset. No-op when the camera is not attached
694
- * (matches the `seedIndexFromScan` contract: seeding a non-attached device is
695
- * also a no-op, so a clear+reseed pair is always safe to call unconditionally).
696
- *
697
- * Intended usage (see `rescanStorage` provider in `index.ts`):
698
- * 1. `core.rescanDevice(deviceId)` — drop stale index entries
699
- * 2. `await seedIndexForDevice(core, deviceId)` — re-populate from disk
700
- * 3. `core.getStatus(deviceId)` — now reflects true on-disk bytes
701
- */
702
- rescanDevice(deviceId) {
703
- const cam = this.cameras.get(deviceId);
704
- if (!cam) return;
705
- this.cameras.set(deviceId, { ...cam, index: new RamIndex() });
706
- }
707
- /**
708
- * Stop all writers for a camera, release its broker sources, and drop its
709
- * index. Writers are stopped FIRST (ffmpeg disconnects from the restream)
710
- * before the broker demand is released, so the broker can idle cleanly.
711
- */
712
- async detach(deviceId) {
713
- const cam = this.cameras.get(deviceId);
714
- if (!cam) return;
715
- for (const w of cam.writers) w.stop();
716
- this.cameras.delete(deviceId);
717
- const releases = await Promise.allSettled(
718
- cam.pipelineKeys.map((key) => this.deps.releaseSource(key))
719
- );
720
- for (const r of releases) {
721
- if (r.status === "rejected") {
722
- this.deps.logger.warn("recorder source release failed", {
723
- tags: { deviceId },
724
- meta: { deviceId, error: String(r.reason) }
725
- });
726
- }
727
- }
728
- this.deps.logger.info("recorder detached", { tags: { deviceId }, meta: { deviceId } });
729
- }
730
- /** Stop every camera — used on addon shutdown. */
731
- async detachAll() {
732
- await Promise.all([...this.cameras.keys()].map((deviceId) => this.detach(deviceId)));
733
- }
734
- /** Device ids currently recording. */
735
- attachedDevices() {
736
- return [...this.cameras.keys()];
737
- }
499
+ //#endregion
500
+ //#region src/recorder/playlist.ts
501
+ /** A VOD variant playlist with an absolute wall-clock anchor per segment. */
502
+ function buildVariantPlaylist(segments) {
503
+ const maxDur = segments.reduce((m, s) => Math.max(m, s.durMs), 0);
504
+ const lines = [
505
+ "#EXTM3U",
506
+ "#EXT-X-VERSION:7",
507
+ "#EXT-X-PLAYLIST-TYPE:VOD",
508
+ `#EXT-X-TARGETDURATION:${Math.ceil(maxDur / 1e3)}`,
509
+ "#EXT-X-MEDIA-SEQUENCE:0"
510
+ ];
511
+ segments.forEach((s, i) => {
512
+ if (i > 0) lines.push("#EXT-X-DISCONTINUITY");
513
+ lines.push(`#EXT-X-PROGRAM-DATE-TIME:${new Date(s.startMs).toISOString()}`);
514
+ lines.push(`#EXTINF:${(s.durMs / 1e3).toFixed(3)},`);
515
+ lines.push(s.uri);
516
+ });
517
+ lines.push("#EXT-X-ENDLIST");
518
+ return lines.join("\n") + "\n";
738
519
  }
739
- async function pruneDeviceWithEvents(core, deviceId, nowMs, resolvePolicy, removeBucketDir, api, logger) {
740
- const result = await core.pruneFootageForDevice(
741
- deviceId,
742
- nowMs,
743
- resolvePolicy,
744
- removeBucketDir
745
- );
746
- if (result.deletedBuckets > 0) {
747
- logger.info("recorder footage eviction", {
748
- meta: {
749
- deviceId,
750
- deletedBuckets: result.deletedBuckets,
751
- reclaimedBytes: result.reclaimedBytes,
752
- floorMs: result.floorMs
753
- }
754
- });
755
- }
756
- if (result.floorMs == null) return;
757
- try {
758
- await api.pipelineAnalytics.pruneEventsBefore.mutate({ deviceId, cutoffMs: result.floorMs });
759
- } catch (err) {
760
- logger.warn("recorder: pruneEventsBefore failed", {
761
- meta: { deviceId, error: errMsg(err) }
762
- });
763
- }
520
+ /** A master (multi-variant) playlist enabling client ABR / profile selection. */
521
+ function buildMasterPlaylist(variants) {
522
+ const lines = ["#EXTM3U", "#EXT-X-VERSION:7"];
523
+ for (const v of variants) {
524
+ const attrs = [`BANDWIDTH=${v.bandwidth}`];
525
+ if (v.resolution) attrs.push(`RESOLUTION=${v.resolution.width}x${v.resolution.height}`);
526
+ if (v.codecs) attrs.push(`CODECS="${v.codecs}"`);
527
+ attrs.push(`NAME="${v.profile}"`);
528
+ lines.push(`#EXT-X-STREAM-INF:${attrs.join(",")}`);
529
+ lines.push(v.uri);
530
+ }
531
+ return lines.join("\n") + "\n";
764
532
  }
765
- const MS_PER_DAY = 864e5;
766
- const BYTES_PER_GB = 1e9;
767
- function resolveDeviceRetention(override, defaultAgeDays, defaultSizeGb) {
768
- const ageDays = override?.maxAgeDays && override.maxAgeDays > 0 ? override.maxAgeDays : defaultAgeDays;
769
- const sizeGb = override?.maxSizeGb && override.maxSizeGb > 0 ? override.maxSizeGb : defaultSizeGb;
770
- return {
771
- maxAgeMs: ageDays > 0 ? ageDays * MS_PER_DAY : void 0,
772
- maxSizeBytes: sizeGb > 0 ? sizeGb * BYTES_PER_GB : void 0
773
- };
533
+ //#endregion
534
+ //#region src/recorder/recording-device-settings.ts
535
+ function buildRecordingDeviceSchema() {
536
+ return { sections: [{
537
+ id: "recording-playback",
538
+ tab: "recording",
539
+ location: "top-tab",
540
+ title: "Recording",
541
+ order: 10,
542
+ fields: [{
543
+ type: "widget",
544
+ key: "_recordingPanel",
545
+ label: "",
546
+ widgetId: "host/recording-panel"
547
+ }]
548
+ }] };
774
549
  }
775
- const RecordingTargetSchema = RecordingConfigSchema;
776
- const RecordingTargetsBlobSchema = record(string(), RecordingTargetSchema);
777
- const RECORDING_TARGETS_KEY = "recordingTargets";
778
- function targetsState(store) {
779
- return createDurableState({
780
- key: RECORDING_TARGETS_KEY,
781
- schema: RecordingTargetsBlobSchema,
782
- fallback: {},
783
- read: () => store.readAddonStore(),
784
- write: (patch) => store.writeAddonStore(patch)
785
- });
550
+ //#endregion
551
+ //#region src/recorder/addon/config-store.ts
552
+ /**
553
+ * Per-device recording-config persistence for the recorder addon.
554
+ *
555
+ * Every camera's `RecordingConfig` lives in ONE addon-store blob keyed by
556
+ * (stringified) numeric deviceId — enumerable for boot hydrate (so the addon
557
+ * knows which devices have persisted footage to index without scanning every
558
+ * device store). The whole Zod-validated blob round-trips on every read/write
559
+ * via a {@link createDurableState} handle, so no per-device field can be
560
+ * silently dropped on persist. A corrupt blob reads back as EMPTY rather than
561
+ * crashing boot.
562
+ *
563
+ * On read the legacy `mode`/`schedules`/`triggers` fields are derived once into
564
+ * the authoritative `bands` via `migrateConfigToBands`, then persisted, so the
565
+ * UI reads `bands` directly forever after.
566
+ */
567
+ /** The addon-store key holding the deviceId → RecordingConfig map. */
568
+ var RECORDING_CONFIGS_KEY = "recordingConfigs";
569
+ /** Persisted shape: stringified numeric deviceId → full RecordingConfig. */
570
+ var RecordingConfigsBlobSchema = record(string(), RecordingConfigSchema);
571
+ /** Cold-start default for a camera that has never been configured: disabled, no bands. */
572
+ var DEFAULT_DEVICE_CONFIG = {
573
+ enabled: false,
574
+ bands: []
575
+ };
576
+ function blobState(store) {
577
+ return createDurableState({
578
+ key: RECORDING_CONFIGS_KEY,
579
+ schema: RecordingConfigsBlobSchema,
580
+ fallback: {},
581
+ read: () => store.readAddonStore(),
582
+ write: (patch) => store.writeAddonStore(patch)
583
+ });
786
584
  }
787
- async function readRecordingTargets(store) {
788
- const blob = await targetsState(store).get();
789
- const map = /* @__PURE__ */ new Map();
790
- for (const [key, target] of Object.entries(blob)) {
791
- const id = Number(key);
792
- if (Number.isInteger(id)) map.set(id, target);
793
- }
794
- return map;
585
+ function serialize(map) {
586
+ const out = {};
587
+ for (const [id, config] of map) out[String(id)] = config;
588
+ return out;
795
589
  }
796
- async function upsertRecordingTarget(store, deviceId, target) {
797
- const map = await readRecordingTargets(store);
798
- map.set(deviceId, target);
799
- await targetsState(store).set(serialize(map));
590
+ /** Read every persisted device config, keyed by numeric deviceId. */
591
+ async function readDeviceConfigs(store) {
592
+ const blob = await blobState(store).get();
593
+ const map = /* @__PURE__ */ new Map();
594
+ for (const [key, config] of Object.entries(blob)) {
595
+ const id = Number(key);
596
+ if (Number.isInteger(id)) map.set(id, config);
597
+ }
598
+ return map;
800
599
  }
801
- async function removeRecordingTarget(store, deviceId) {
802
- const map = await readRecordingTargets(store);
803
- if (!map.delete(deviceId)) return;
804
- await targetsState(store).set(serialize(map));
600
+ /**
601
+ * The persisted config for a device with `bands` guaranteed materialized.
602
+ * Legacy blobs (mode/schedules/triggers, no bands) are migrated into bands and
603
+ * re-persisted so the stored shape converges on the authoritative model. An
604
+ * unconfigured device returns {@link DEFAULT_DEVICE_CONFIG}.
605
+ */
606
+ async function loadDeviceConfig(store, deviceId) {
607
+ const stored = (await readDeviceConfigs(store)).get(deviceId);
608
+ if (!stored) return DEFAULT_DEVICE_CONFIG;
609
+ if (stored.bands) return stored;
610
+ const migrated = {
611
+ ...stored,
612
+ bands: migrateConfigToBands(stored)
613
+ };
614
+ await saveDeviceConfig(store, deviceId, migrated);
615
+ return migrated;
805
616
  }
806
- function serialize(map) {
807
- const out = {};
808
- for (const [id, target] of map) out[String(id)] = target;
809
- return out;
617
+ /**
618
+ * Persist (insert or replace) a device's config. Validates against
619
+ * `RecordingConfigSchema` at the boundary (untrusted cap input). Returns the
620
+ * validated config that was persisted.
621
+ */
622
+ async function saveDeviceConfig(store, deviceId, config) {
623
+ const validated = RecordingConfigSchema.parse(config);
624
+ const map = await readDeviceConfigs(store);
625
+ map.set(deviceId, validated);
626
+ await blobState(store).set(serialize(map));
627
+ return validated;
810
628
  }
811
- function buildRecordingDeviceSchema() {
812
- return {
813
- sections: [
814
- {
815
- id: "recording-playback",
816
- tab: "recording",
817
- location: "top-tab",
818
- title: "Recording",
819
- order: 10,
820
- fields: [
821
- { type: "widget", key: "_recordingPanel", label: "", widgetId: "host/recording-panel" }
822
- ]
823
- }
824
- ]
825
- };
629
+ /**
630
+ * Determine the active recording mode for a config's bands — the value the
631
+ * `recording` cap status reports. `continuous` wins when any band records
632
+ * continuously, else `events` when any band exists, else `off`.
633
+ */
634
+ function activeModeForConfig(config) {
635
+ const bands = config.bands ?? [];
636
+ if (!config.enabled || bands.length === 0) return "off";
637
+ if (bands.some((b) => b.mode === "continuous")) return "continuous";
638
+ return "events";
826
639
  }
827
- const RecordingPlacementBlobSchema = object({
828
- assignments: record(string(), array(string())).optional()
829
- });
830
- const DEFAULT_RECORDING_PLACEMENT = {
831
- high: ["recordings:default"],
832
- mid: ["recordings:default"],
833
- low: ["recordingsLow:default"],
834
- scrub: ["recordingsLow:default"]
640
+ //#endregion
641
+ //#region src/recorder/addon/recording-provider.ts
642
+ /**
643
+ * Builds the `recording` cap provider (`IRecordingProvider`) on the recorder
644
+ * core. NO ffmpeg / segment writing here — that arrives in B2/B3. This shell
645
+ * answers reads from the v2 `RecordingIndex` (hydrated from `storage.list`),
646
+ * persists per-device config via durable-state, and prunes footage through
647
+ * `selectEvictions` + `SegmentStore.evict`.
648
+ */
649
+ /** Bandwidth hint per profile for the master playlist (real bitrate is a later refinement). */
650
+ var PROFILE_BANDWIDTH = {
651
+ high: 4e6,
652
+ mid: 15e5,
653
+ low: 5e5
835
654
  };
836
- function resolveAssignedLocations(placement, key) {
837
- return placement.assignments[key] ?? [];
655
+ var DEFAULT_BANDWIDTH = 1e6;
656
+ /**
657
+ * Max gap (ms) between consecutive segments still treated as ONE continuous
658
+ * availability range. Absorbs the few-ms EXTINF-rounding jitter at every segment
659
+ * boundary and a single dropped/late ~4s segment; a larger gap (recorder off,
660
+ * multiple missing segments) splits the ranges so real discontinuities show.
661
+ */
662
+ var RANGE_MERGE_GAP_MS = 5e3;
663
+ /** Empty "no playback" manifest. */
664
+ function noPlayback(deviceId) {
665
+ return {
666
+ deviceId,
667
+ localMasterPath: null,
668
+ playbackUrl: null,
669
+ playbackEndpoints: []
670
+ };
838
671
  }
839
- function chooseWriteLocation(locationIds, free) {
840
- let best = null;
841
- let bestBytes = -Infinity;
842
- for (const id of locationIds) {
843
- const entry = free.find((f) => f.locationId === id);
844
- const bytes = entry?.availableBytes ?? -1;
845
- if (best === null || bytes > bestBytes) {
846
- best = id;
847
- bestBytes = bytes;
848
- }
849
- }
850
- return best;
672
+ /** Absolute dir the playback playlists for a device are written to (served root = `<dataDir>/playback`). */
673
+ function playbackDirFor(dataDir, deviceId) {
674
+ return path.join(dataDir, "playback", String(deviceId));
851
675
  }
852
- function buildPassthroughArgs(a) {
853
- return [
854
- "-rtsp_transport",
855
- "tcp",
856
- "-i",
857
- a.rtspUrl,
858
- // Map ALL input streams (video + audio). Without this the segment muxer
859
- // selects nothing and ffmpeg aborts with "Output file does not contain
860
- // any stream".
861
- "-map",
862
- "0",
863
- // Copy the (already-fragmentable) video, but always re-encode audio to AAC.
864
- // The MP4 segment muxer rejects raw G.711 (pcm_mulaw/pcm_alaw, common on
865
- // Hikvision/ONVIF) with "codec not currently supported in container",
866
- // which made ffmpeg exit before writing a single frame → 0-byte segments,
867
- // no playlist, empty availability. The broker cannot report the source
868
- // audio codec reliably (it advertises AAC even for µ-law streams), so we
869
- // unconditionally transcode audio to AAC: cheap (low-bitrate mono/stereo)
870
- // and muxable across every vendor. An `-c:a` with no audio stream is a no-op.
871
- "-c:v",
872
- "copy",
873
- "-c:a",
874
- "aac",
875
- "-f",
876
- "segment",
877
- "-segment_time",
878
- String(a.segmentSeconds),
879
- "-segment_format",
880
- "mp4",
881
- "-segment_format_options",
882
- "movflags=+frag_keyframe+empty_moov+default_base_moof",
883
- "-reset_timestamps",
884
- "1",
885
- "-strftime",
886
- "1",
887
- "-segment_list",
888
- `${a.outDir}/live.m3u8`,
889
- "-segment_list_type",
890
- "m3u8",
891
- // FLAT epoch-named segments directly under `outDir`. We deliberately do
892
- // NOT let ffmpeg write the date buckets: its segment muxer cannot create
893
- // directories on this ffmpeg build (`-strftime_mkdir` is absent) and its
894
- // `-strftime` expands in LOCAL time, whereas the playback layout
895
- // (`segmentRelPath`) is UTC. The watcher relocates into the UTC bucket so
896
- // disk + playback URIs stay consistent.
897
- `${a.outDir}/%s.m4s`
898
- ];
676
+ /**
677
+ * Build a master + per-profile variant HLS playlist on disk for the requested
678
+ * window and return a RELATIVE playback URL through the hub's data-plane
679
+ * reverse-proxy. Only segments actually present on disk are referenced (a
680
+ * missing file would 404 mid-playlist). Returns "no playback" when the device
681
+ * has no footage in range or the data-plane isn't served yet. Variant/segment
682
+ * URIs are relative so the master + variants + segments form a self-contained
683
+ * tree the player resolves against the master URL.
684
+ */
685
+ async function buildPlaybackManifest(deps, deviceId, fromMs, toMs) {
686
+ const base = deps.playbackBaseUrl();
687
+ if (base === null) return noPlayback(deviceId);
688
+ const rootById = new Map(deps.locations().map((l) => [l.id, l.root]));
689
+ const playbackDir = playbackDirFor(deps.dataDir, deviceId);
690
+ const profiles = [...new Set(deps.index.segments(deviceId).map((s) => s.profile))];
691
+ const variants = [];
692
+ for (const profile of profiles) {
693
+ const segs = deps.index.segments(deviceId, profile).filter((s) => s.startMs < toMs && s.startMs + s.durMs > fromMs).toSorted((a, b) => a.startMs - b.startMs);
694
+ if (segs.length === 0) continue;
695
+ const variantSegments = [];
696
+ for (const s of segs) {
697
+ const rel = segmentRelPath(deviceId, profile, s.startMs, s.durMs, s.bytes);
698
+ const root = rootById.get(s.locationId);
699
+ if (root === void 0) continue;
700
+ try {
701
+ await promises.stat(path.join(root, rel));
702
+ } catch {
703
+ continue;
704
+ }
705
+ variantSegments.push({
706
+ uri: rel.split("/").slice(1).join("/"),
707
+ startMs: s.startMs,
708
+ durMs: s.durMs
709
+ });
710
+ }
711
+ if (variantSegments.length === 0) continue;
712
+ await promises.mkdir(playbackDir, { recursive: true });
713
+ await promises.writeFile(path.join(playbackDir, `${profile}.m3u8`), buildVariantPlaylist(variantSegments), "utf8");
714
+ variants.push({
715
+ profile,
716
+ bandwidth: PROFILE_BANDWIDTH[profile] ?? DEFAULT_BANDWIDTH,
717
+ uri: `${profile}.m3u8`
718
+ });
719
+ }
720
+ if (variants.length === 0) return noPlayback(deviceId);
721
+ await promises.mkdir(playbackDir, { recursive: true });
722
+ const masterPath = path.join(playbackDir, "master.m3u8");
723
+ await promises.writeFile(masterPath, buildMasterPlaylist(variants), "utf8");
724
+ const playbackUrl = `${base}/${deviceId}/master.m3u8?from=${fromMs}&to=${toMs}`;
725
+ return {
726
+ deviceId,
727
+ localMasterPath: masterPath,
728
+ playbackUrl,
729
+ playbackEndpoints: [playbackUrl]
730
+ };
899
731
  }
900
- const MAX_RESTARTS = 10;
901
- const STDERR_TAIL_LINES = 12;
902
- class SegmentWriter {
903
- constructor(cfg, deps) {
904
- this.cfg = cfg;
905
- this.deps = deps;
906
- }
907
- proc = null;
908
- stopped = false;
909
- restarts = 0;
910
- start() {
911
- if (this.stopped || this.proc) return;
912
- const args = buildPassthroughArgs(this.cfg);
913
- const proc = this.deps.spawn(this.deps.ffmpegPath ?? "ffmpeg", args);
914
- this.proc = proc;
915
- const stderrTail = [];
916
- proc.stderr?.on("data", (chunk) => {
917
- const text = chunk instanceof Buffer ? chunk.toString("utf8") : String(chunk);
918
- for (const line of text.split("\n")) {
919
- const trimmed = line.trim();
920
- if (!trimmed) continue;
921
- stderrTail.push(trimmed);
922
- if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();
923
- }
924
- });
925
- proc.on("exit", (code) => {
926
- this.proc = null;
927
- if (this.stopped) return;
928
- if (this.restarts >= MAX_RESTARTS) {
929
- this.deps.logger.warn("SegmentWriter giving up after max restarts", {
930
- meta: { outDir: this.cfg.outDir, code, stderrTail: stderrTail.join(" | ") }
931
- });
932
- return;
933
- }
934
- this.restarts++;
935
- this.deps.logger.info("SegmentWriter restarting", { meta: { outDir: this.cfg.outDir, attempt: this.restarts } });
936
- this.start();
937
- });
938
- }
939
- stop() {
940
- this.stopped = true;
941
- this.proc?.kill();
942
- this.proc = null;
943
- }
732
+ /** Number of days in ms — for the retention floor returned by `pruneFootage`. */
733
+ var DAY_MS = 1440 * 60 * 1e3;
734
+ function statusFor(deps, deviceId, config) {
735
+ return {
736
+ deviceId,
737
+ enabled: config.enabled,
738
+ activeMode: activeModeForConfig(config),
739
+ nodeId: deps.nodeId,
740
+ storageBytes: deps.index.accounting(deviceId).bytes
741
+ };
944
742
  }
945
- function buildVariantPlaylist(segments) {
946
- const maxDur = segments.reduce((m, s) => Math.max(m, s.durMs), 0);
947
- const lines = [
948
- "#EXTM3U",
949
- "#EXT-X-VERSION:7",
950
- "#EXT-X-PLAYLIST-TYPE:VOD",
951
- `#EXT-X-TARGETDURATION:${Math.ceil(maxDur / 1e3)}`,
952
- "#EXT-X-MEDIA-SEQUENCE:0"
953
- ];
954
- segments.forEach((s, i) => {
955
- if (i > 0) lines.push("#EXT-X-DISCONTINUITY");
956
- lines.push(`#EXT-X-PROGRAM-DATE-TIME:${new Date(s.startMs).toISOString()}`);
957
- lines.push(`#EXTINF:${(s.durMs / 1e3).toFixed(3)},`);
958
- lines.push(s.uri);
959
- });
960
- lines.push("#EXT-X-ENDLIST");
961
- return lines.join("\n") + "\n";
743
+ /** Group a device's segments by their storage location id. */
744
+ function segmentsByLocation(rows) {
745
+ const out = /* @__PURE__ */ new Map();
746
+ for (const r of rows) {
747
+ const list = out.get(r.locationId);
748
+ if (list) list.push(r);
749
+ else out.set(r.locationId, [r]);
750
+ }
751
+ return out;
962
752
  }
963
- function buildMasterPlaylist(variants) {
964
- const lines = ["#EXTM3U", "#EXT-X-VERSION:7"];
965
- for (const v of variants) {
966
- const attrs = [`BANDWIDTH=${v.bandwidth}`];
967
- if (v.resolution) attrs.push(`RESOLUTION=${v.resolution.width}x${v.resolution.height}`);
968
- if (v.codecs) attrs.push(`CODECS="${v.codecs}"`);
969
- attrs.push(`NAME="${v.profile}"`);
970
- lines.push(`#EXT-X-STREAM-INF:${attrs.join(",")}`);
971
- lines.push(v.uri);
972
- }
973
- return lines.join("\n") + "\n";
753
+ /**
754
+ * Build the `IRecordingProvider`. The provider is a thin façade over the v2
755
+ * core; all storage I/O flows through the injected deps.
756
+ */
757
+ function buildRecordingProvider(deps) {
758
+ const readFile = deps.readFile ?? ((absPath) => promises.readFile(absPath));
759
+ return {
760
+ getStatus: async ({ deviceId }) => {
761
+ return statusFor(deps, deviceId, await loadDeviceConfig(deps.configStore, deviceId));
762
+ },
763
+ getAvailability: async ({ deviceId, fromMs, toMs }) => {
764
+ return {
765
+ deviceId,
766
+ ranges: [...new Set(deps.index.segments(deviceId).map((s) => s.profile))].flatMap((profile) => deps.index.ranges(deviceId, profile, fromMs, toMs, RANGE_MERGE_GAP_MS).map((r) => ({
767
+ profile,
768
+ startMs: r.startMs,
769
+ endMs: r.endMs
770
+ })))
771
+ };
772
+ },
773
+ getDaysWithRecordings: async ({ deviceId, fromMs, toMs, tzOffsetMinutes }) => {
774
+ return {
775
+ deviceId,
776
+ days: distinctRecordingDays(deps.index.segments(deviceId).map((s) => s.startMs), fromMs, toMs, tzOffsetMinutes)
777
+ };
778
+ },
779
+ getPlaybackManifest: ({ deviceId, fromMs, toMs }) => buildPlaybackManifest(deps, deviceId, fromMs, toMs),
780
+ getStorageUsage: async () => {
781
+ const locations = deps.locations();
782
+ const devices = [];
783
+ const seenDevices = /* @__PURE__ */ new Set();
784
+ for (const loc of locations) for (const row of deps.index.segmentsOnLocation(loc.id)) seenDevices.add(row.deviceId);
785
+ let totalUsedBytes = 0;
786
+ for (const deviceId of seenDevices) {
787
+ const usedBytes = deps.index.accounting(deviceId).bytes;
788
+ totalUsedBytes += usedBytes;
789
+ devices.push({
790
+ deviceId,
791
+ usedBytes
792
+ });
793
+ }
794
+ const locationUsages = await Promise.all(locations.map(async (loc) => {
795
+ const cap = await deps.capacity(loc.root);
796
+ return {
797
+ locationId: loc.id,
798
+ usedBytes: deps.index.accountingForLocation(loc.id).bytes,
799
+ availableBytes: cap.availableBytes,
800
+ totalBytes: cap.totalBytes
801
+ };
802
+ }));
803
+ devices.sort((a, b) => b.usedBytes - a.usedBytes);
804
+ return {
805
+ nodeId: deps.nodeId,
806
+ totalUsedBytes,
807
+ devices,
808
+ locations: locationUsages
809
+ };
810
+ },
811
+ getDeviceConfig: async ({ deviceId }) => loadDeviceConfig(deps.configStore, deviceId),
812
+ locateSegment: async ({ deviceId, profile, epochMs }) => {
813
+ const seg = deps.index.segmentAt(deviceId, profile, epochMs);
814
+ if (seg) return {
815
+ kind: "segment",
816
+ startMs: seg.startMs,
817
+ durMs: seg.durMs,
818
+ bytes: seg.bytes
819
+ };
820
+ return {
821
+ kind: "gap",
822
+ nearestEdgeMs: deps.index.nearestCoveredEdge(deviceId, profile, epochMs)
823
+ };
824
+ },
825
+ readSegmentBytes: async ({ deviceId, profile, startMs }) => {
826
+ const seg = deps.index.segments(deviceId, profile).find((s) => s.startMs === startMs);
827
+ if (!seg) throw new Error(`recording: no segment at start ${startMs} for ${deviceId}/${profile}`);
828
+ const loc = deps.locations().find((l) => l.id === seg.locationId);
829
+ if (!loc) throw new Error(`recording: unknown location ${seg.locationId}`);
830
+ const data = await readFile(path.join(loc.root, seg.path));
831
+ return { data: Uint8Array.from(data) };
832
+ },
833
+ setDeviceConfig: async ({ deviceId, config }) => {
834
+ const saved = await saveDeviceConfig(deps.configStore, deviceId, config);
835
+ if (deps.onConfigChanged) try {
836
+ await deps.onConfigChanged(deviceId);
837
+ } catch (err) {
838
+ deps.logger.warn("recorder: re-evaluate after setDeviceConfig failed", {
839
+ tags: { deviceId },
840
+ meta: { error: errMsg(err) }
841
+ });
842
+ }
843
+ return saved;
844
+ },
845
+ rescanStorage: async ({ deviceId }) => {
846
+ const locations = await deps.refreshLocations();
847
+ await deps.hydrateDevice(deviceId, locations);
848
+ return statusFor(deps, deviceId, await loadDeviceConfig(deps.configStore, deviceId));
849
+ },
850
+ pruneFootage: async ({ deviceId }) => {
851
+ const retention = (await loadDeviceConfig(deps.configStore, deviceId)).retention;
852
+ const nowMs = Date.now();
853
+ const victims = selectEvictions(deps.index.segments(deviceId), {
854
+ maxAgeDays: retention?.maxAgeDays,
855
+ maxSizeGb: retention?.maxSizeGb,
856
+ nowMs
857
+ });
858
+ let reclaimedBytes = 0;
859
+ let deletedBuckets = 0;
860
+ for (const [locationId, locVictims] of segmentsByLocation(victims)) try {
861
+ const freed = await deps.segmentStore.evict(locationId, locVictims);
862
+ reclaimedBytes += freed;
863
+ if (freed > 0) deletedBuckets += locVictims.length;
864
+ } catch (err) {
865
+ deps.logger.warn("recorder pruneFootage evict failed for location", {
866
+ tags: { deviceId },
867
+ meta: {
868
+ locationId,
869
+ error: errMsg(err)
870
+ }
871
+ });
872
+ }
873
+ return {
874
+ floorMs: deps.index.accounting(deviceId).oldestMs ?? (retention?.maxAgeDays ? nowMs - retention.maxAgeDays * DAY_MS : null),
875
+ deletedBuckets,
876
+ reclaimedBytes
877
+ };
878
+ },
879
+ getDeviceSettingsContribution: async () => hydrateSchema(buildRecordingDeviceSchema(), {}),
880
+ getDeviceLiveContribution: async () => null,
881
+ applyDeviceSettingsPatch: async ({ patch }) => {
882
+ const keys = Object.keys(patch ?? {});
883
+ if (keys.length > 0) deps.logger.debug("recorder: ignoring legacy settings patch (widget owns settings)", { meta: { keys } });
884
+ return { success: true };
885
+ }
886
+ };
887
+ }
888
+ //#endregion
889
+ //#region src/recorder/addon/roots.ts
890
+ /**
891
+ * Storage-root resolution + boot hydrate for the recorder addon.
892
+ *
893
+ * Recordings live in the managed `recordings` / `recordingsLow` storage
894
+ * locations (operator-configurable, multi-disk-ready), resolved through the
895
+ * `storage` cap. The v2 `RecordingIndex` is hydrated by walking each location
896
+ * root's `<deviceId>/` subtree on disk — segment paths encode start/dur/bytes,
897
+ * so the in-memory index can never drift from disk. (We walk the filesystem
898
+ * directly instead of `storage.list` because that cap lists only a directory's
899
+ * IMMEDIATE children, not the `<deviceId>/<profile>/Y/M/D/H/*.m4s` tree — using
900
+ * it dropped the entire index to ~empty on every restart/rescan; the recorder
901
+ * already does local fs I/O for stat/move on these same roots.)
902
+ */
903
+ /** The two recordings location types the recorder addon writes/reads. */
904
+ var RECORDING_LOCATION_TYPES = new Set(["recordings", "recordingsLow"]);
905
+ /**
906
+ * Resolve every recordings storage location (`recordings` + `recordingsLow`)
907
+ * to `{ id, root }`. Returns an empty list when the storage cap is unreachable
908
+ * or no recordings location exists — callers degrade rather than crash.
909
+ */
910
+ async function resolveRecordingsLocations(api, logger) {
911
+ try {
912
+ const recordings = (await api.storage.listLocations.query({})).filter((l) => RECORDING_LOCATION_TYPES.has(l.type));
913
+ return Promise.all(recordings.map(async (l) => ({
914
+ id: l.id,
915
+ root: await api.storage.resolve.query({
916
+ location: l.id,
917
+ relativePath: ""
918
+ })
919
+ })));
920
+ } catch (err) {
921
+ logger.warn("recorder: listLocations failed — no recordings locations resolved", { meta: { error: errMsg(err) } });
922
+ return [];
923
+ }
924
+ }
925
+ /**
926
+ * Hydrate the v2 `RecordingIndex` for one device from every recordings location
927
+ * by recursively walking `<root>/<deviceId>/` for `*.m4s` segments and feeding
928
+ * the location-relative paths (`<deviceId>/<profile>/Y/M/D/H/<file>.m4s`, which
929
+ * `parseSegmentPath` understands) to `index.hydrateDevice`. A missing device dir
930
+ * (no footage yet) and any per-location failure are warned + skipped
931
+ * (best-effort), so one bad volume never blocks the rest of the hydrate.
932
+ */
933
+ async function hydrateDeviceFromStorage(_api, index, deviceId, locations, logger) {
934
+ for (const loc of locations) {
935
+ const deviceDir = path.join(loc.root, String(deviceId));
936
+ let entries;
937
+ try {
938
+ entries = await promises.readdir(deviceDir, { recursive: true });
939
+ } catch (err) {
940
+ if (err.code !== "ENOENT") logger.warn("recorder: hydrateDevice walk failed for location", {
941
+ tags: { deviceId },
942
+ meta: {
943
+ locationId: loc.id,
944
+ error: errMsg(err)
945
+ }
946
+ });
947
+ continue;
948
+ }
949
+ const relPaths = entries.filter((e) => e.endsWith(".m4s")).map((e) => `${deviceId}/${e.split(path.sep).join("/")}`);
950
+ index.hydrateDevice(deviceId, loc.id, relPaths);
951
+ }
952
+ }
953
+ //#endregion
954
+ //#region src/recorder/addon/ffmpeg-args.ts
955
+ /** ffmpeg argv: pull RTSP (TCP), copy video / transcode audio to AAC, write
956
+ * fragmented-mp4 segments named by epoch seconds FLAT under `outDir`, plus a
957
+ * rolling `live.m3u8` playlist. The recorder segment-watcher tails the
958
+ * playlist and hands each finalized flat file to `SegmentStore.onFinalized`,
959
+ * which stats + relocates it into the bucket tree (`segmentRelPath`). */
960
+ function buildPassthroughArgs(a) {
961
+ return [
962
+ "-rtsp_transport",
963
+ "tcp",
964
+ "-i",
965
+ a.rtspUrl,
966
+ "-map",
967
+ "0",
968
+ "-c:v",
969
+ "copy",
970
+ "-c:a",
971
+ "aac",
972
+ "-f",
973
+ "segment",
974
+ "-segment_time",
975
+ String(a.segmentSeconds),
976
+ "-segment_format",
977
+ "mp4",
978
+ "-segment_format_options",
979
+ "movflags=+frag_keyframe+empty_moov+default_base_moof",
980
+ "-reset_timestamps",
981
+ "1",
982
+ "-strftime",
983
+ "1",
984
+ "-segment_list",
985
+ `${a.outDir}/live.m3u8`,
986
+ "-segment_list_type",
987
+ "m3u8",
988
+ `${a.outDir}/%s.m4s`
989
+ ];
974
990
  }
975
- const EPOCH_NAME_RE = /^(\d+)\.m4s$/;
976
- const MAX_PENDING_TICKS = 8;
991
+ //#endregion
992
+ //#region src/recorder/addon/segment-writer.ts
993
+ /** Max CONSECUTIVE rapid restarts before giving up (reset by a stable run). */
994
+ var MAX_RESTARTS = 10;
995
+ /** How many trailing ffmpeg stderr lines to keep for the give-up diagnostic. */
996
+ var STDERR_TAIL_LINES = 12;
997
+ /** Restart backoff: base delay, doubled per consecutive attempt, capped. */
998
+ var RESTART_BASE_MS = 500;
999
+ var RESTART_MAX_MS = 1e4;
1000
+ /** A process that ran at least this long is "stable" → reset the restart count,
1001
+ * so sporadic blips over a long lifetime never accumulate into a give-up. */
1002
+ var STABLE_RUN_MS = 3e4;
1003
+ /** Supervises one passthrough ffmpeg for a single (camera, profile). */
1004
+ var SegmentWriter = class {
1005
+ cfg;
1006
+ deps;
1007
+ proc = null;
1008
+ stopped = false;
1009
+ restarts = 0;
1010
+ restartTimer = null;
1011
+ startedAt = 0;
1012
+ constructor(cfg, deps) {
1013
+ this.cfg = cfg;
1014
+ this.deps = deps;
1015
+ }
1016
+ start() {
1017
+ if (this.stopped || this.proc) return;
1018
+ const args = buildPassthroughArgs(this.cfg);
1019
+ const proc = this.deps.spawn(this.deps.ffmpegPath ?? "ffmpeg", args);
1020
+ this.proc = proc;
1021
+ this.startedAt = Date.now();
1022
+ const stderrTail = [];
1023
+ proc.stderr?.on("data", (chunk) => {
1024
+ const text = chunk instanceof Buffer ? chunk.toString("utf8") : String(chunk);
1025
+ for (const line of text.split("\n")) {
1026
+ const trimmed = line.trim();
1027
+ if (!trimmed) continue;
1028
+ stderrTail.push(trimmed);
1029
+ if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();
1030
+ }
1031
+ });
1032
+ proc.on("exit", (code) => {
1033
+ this.proc = null;
1034
+ if (this.stopped) return;
1035
+ const ranMs = Date.now() - this.startedAt;
1036
+ if (ranMs >= STABLE_RUN_MS) this.restarts = 0;
1037
+ if (this.restarts >= MAX_RESTARTS) {
1038
+ this.deps.logger.warn("SegmentWriter giving up after max restarts", { meta: {
1039
+ outDir: this.cfg.outDir,
1040
+ code,
1041
+ stderrTail: stderrTail.join(" | ")
1042
+ } });
1043
+ this.stopped = true;
1044
+ this.deps.onGaveUp?.();
1045
+ return;
1046
+ }
1047
+ this.restarts++;
1048
+ const delayMs = Math.min(RESTART_BASE_MS * 2 ** (this.restarts - 1), RESTART_MAX_MS);
1049
+ this.deps.logger.info("SegmentWriter restarting", { meta: {
1050
+ outDir: this.cfg.outDir,
1051
+ attempt: this.restarts,
1052
+ delayMs,
1053
+ ranMs
1054
+ } });
1055
+ this.restartTimer = setTimeout(() => {
1056
+ this.restartTimer = null;
1057
+ this.start();
1058
+ }, delayMs);
1059
+ });
1060
+ }
1061
+ stop() {
1062
+ this.stopped = true;
1063
+ if (this.restartTimer) {
1064
+ clearTimeout(this.restartTimer);
1065
+ this.restartTimer = null;
1066
+ }
1067
+ this.proc?.kill();
1068
+ this.proc = null;
1069
+ }
1070
+ };
1071
+ //#endregion
1072
+ //#region src/recorder/addon/segment-watcher.ts
1073
+ /**
1074
+ * Poll-based tail of an ffmpeg `-segment_list` (`live.m3u8`) for one
1075
+ * (camera, profile) output dir — recorder variant.
1076
+ *
1077
+ * Adapted from the old recorder (`addon-pipeline/src/recorder/segment-watcher.ts`).
1078
+ * The robust playlist-tailing core is unchanged: it polls `live.m3u8`, derives
1079
+ * `startMs` from the flat `<epochSec>.m4s` filename, corrects the inflated
1080
+ * first-segment EXTINF duration against the successor's start, and handles
1081
+ * pending/phantom (file-not-yet-flushed) entries with a bounded retry.
1082
+ *
1083
+ * KEY ADAPTATION vs the old watcher: this watcher does NOT relocate the flat
1084
+ * file, does NOT classify a continuous/events subtree, and does NOT touch a RAM
1085
+ * index. For each finalized flat segment it simply calls
1086
+ * `onFinalized(startMs, durMs, flatAbsPath)` and lets the v2 `SegmentStore`
1087
+ * (`onFinalized`) do the stat + relocate-into-bucket + index. The watcher only
1088
+ * verifies the flat file is on disk (so `onFinalized` does not race the flush)
1089
+ * before handing it off; the SegmentStore re-stats for the authoritative byte
1090
+ * count that goes into the path. B2 records CONTINUOUS bands only, so there is
1091
+ * no subtree to classify.
1092
+ */
1093
+ var EPOCH_NAME_RE = /^(\d+)\.m4s$/;
1094
+ /** How many consecutive ticks to wait for a finalized segment's flat file to
1095
+ * land before giving up on it (a genuine phantom). At a 2s watch interval this
1096
+ * is ~16s — far longer than ffmpeg's slow-first-segment flush. */
1097
+ var MAX_PENDING_TICKS = 8;
1098
+ /**
1099
+ * Derive `startMs` (epoch milliseconds) from a flat ffmpeg segment path
1100
+ * (`<epochSec>.m4s`, possibly absolute). Returns null for any non-epoch path.
1101
+ */
977
1102
  function parseEpochStartMs(segPath) {
978
- const m = EPOCH_NAME_RE.exec(path__default.basename(segPath));
979
- if (!m) return null;
980
- const epochSec = Number(m[1]);
981
- return Number.isFinite(epochSec) ? epochSec * 1e3 : null;
1103
+ const m = EPOCH_NAME_RE.exec(path.basename(segPath));
1104
+ if (!m) return null;
1105
+ const epochSec = Number(m[1]);
1106
+ return Number.isFinite(epochSec) ? epochSec * 1e3 : null;
982
1107
  }
1108
+ /**
1109
+ * Correct a finalized segment's duration. ffmpeg's first-segment `#EXTINF` is
1110
+ * unreliable under `-c copy` from RTSP — it is inflated by the initial PTS
1111
+ * offset (observed: 87.961s for a segment whose successor starts only 12s
1112
+ * later). A segment physically cannot outlast the start of the next segment, so
1113
+ * when a successor exists we clamp the rounded EXTINF to the inter-segment gap.
1114
+ * For normal segments EXTINF (millisecond-accurate) is below the
1115
+ * integer-second start gap and wins, preserving sub-second precision. When
1116
+ * there is no successor (genuine last segment) or the gap is non-positive
1117
+ * (restart / same-second), we trust EXTINF.
1118
+ */
983
1119
  function correctedDurMs(durSeconds, startMs, nextStartMs) {
984
- const extinfMs = Math.round(durSeconds * 1e3);
985
- if (nextStartMs === null) return extinfMs;
986
- const gapMs = nextStartMs - startMs;
987
- if (gapMs <= 0) return extinfMs;
988
- return Math.min(extinfMs, gapMs);
1120
+ const extinfMs = Math.round(durSeconds * 1e3);
1121
+ if (nextStartMs === null) return extinfMs;
1122
+ const gapMs = nextStartMs - startMs;
1123
+ if (gapMs <= 0) return extinfMs;
1124
+ return Math.min(extinfMs, gapMs);
989
1125
  }
1126
+ /** Parse a `live.m3u8` body into ordered `#EXTINF` → segment-path pairs. */
990
1127
  function parseLivePlaylist(body) {
991
- const lines = body.split("\n");
992
- const out = [];
993
- let pendingDur = null;
994
- for (const raw of lines) {
995
- const line = raw.trim();
996
- if (line.length === 0) continue;
997
- if (line.startsWith("#EXTINF:")) {
998
- const v = line.slice("#EXTINF:".length).replace(/,.*$/, "");
999
- const dur = Number(v);
1000
- pendingDur = Number.isFinite(dur) ? dur : null;
1001
- continue;
1002
- }
1003
- if (line.startsWith("#")) continue;
1004
- if (pendingDur !== null) {
1005
- out.push({ durSeconds: pendingDur, segPath: line });
1006
- pendingDur = null;
1007
- }
1008
- }
1009
- return out;
1010
- }
1011
- function resolveFinalizedSegment(outDir, segPath, durMs, subtree) {
1012
- const abs = path__default.isAbsolute(segPath) ? segPath : path__default.join(outDir, segPath);
1013
- const startMs = parseEpochStartMs(abs);
1014
- if (startMs === null) return null;
1015
- const newAbs = path__default.join(outDir, subtree, hourBucketRelPath(startMs), `${startMs}-${durMs}.m4s`);
1016
- return { startMs, durMs, oldAbs: abs, newAbs };
1128
+ const lines = body.split("\n");
1129
+ const out = [];
1130
+ let pendingDur = null;
1131
+ for (const raw of lines) {
1132
+ const line = raw.trim();
1133
+ if (line.length === 0) continue;
1134
+ if (line.startsWith("#EXTINF:")) {
1135
+ const v = line.slice(8).replace(/,.*$/, "");
1136
+ const dur = Number(v);
1137
+ pendingDur = Number.isFinite(dur) ? dur : null;
1138
+ continue;
1139
+ }
1140
+ if (line.startsWith("#")) continue;
1141
+ if (pendingDur !== null) {
1142
+ out.push({
1143
+ durSeconds: pendingDur,
1144
+ segPath: line
1145
+ });
1146
+ pendingDur = null;
1147
+ }
1148
+ }
1149
+ return out;
1017
1150
  }
1151
+ /** `fs.stat` size, or null when the path does not exist. */
1018
1152
  async function statSize(p) {
1019
- try {
1020
- return (await promises.stat(p)).size;
1021
- } catch {
1022
- return null;
1023
- }
1153
+ try {
1154
+ return (await promises.stat(p)).size;
1155
+ } catch {
1156
+ return null;
1157
+ }
1024
1158
  }
1025
- async function handleSegmentEntry(outDir, entry, durMs, classify, onSegment, logger) {
1026
- const startMs = parseEpochStartMs(path__default.isAbsolute(entry.segPath) ? entry.segPath : path__default.join(outDir, entry.segPath));
1027
- if (startMs === null) return "skipped";
1028
- const subtree = classify(startMs, durMs);
1029
- const resolved = resolveFinalizedSegment(outDir, entry.segPath, durMs, subtree);
1030
- if (!resolved) return "skipped";
1031
- const existing = await statSize(resolved.newAbs);
1032
- if (existing !== null) {
1033
- onSegment(resolved.startMs, resolved.durMs, existing, subtree);
1034
- return "retained";
1035
- }
1036
- if (await statSize(resolved.oldAbs) === null) {
1037
- logger.debug?.("segment flat file not on disk yet — will retry", { meta: { path: resolved.oldAbs } });
1038
- return "pending";
1039
- }
1040
- try {
1041
- await promises.mkdir(path__default.dirname(resolved.newAbs), { recursive: true });
1042
- await promises.rename(resolved.oldAbs, resolved.newAbs);
1043
- } catch {
1044
- logger.debug?.("segment relocate failed", { meta: { from: resolved.oldAbs, to: resolved.newAbs } });
1045
- }
1046
- const bytes = await statSize(resolved.newAbs);
1047
- if (bytes === null) return "pending";
1048
- onSegment(resolved.startMs, resolved.durMs, bytes, subtree);
1049
- return "retained";
1159
+ /**
1160
+ * Process ONE finalized playlist entry: verify the flat file is on disk and, if
1161
+ * so, hand it to `onFinalized` (the v2 SegmentStore stats + relocates + indexes
1162
+ * it). Returns:
1163
+ * - `'retained'` the flat file is on disk and was handed off;
1164
+ * - `'skipped'` not a relocatable epoch-named segment (caller advances past it);
1165
+ * - `'pending'` a valid segment whose flat file has NOT landed on disk yet.
1166
+ * ffmpeg's first segment is slow to flush, so the caller must RETRY this
1167
+ * entry on a later tick instead of orphaning it.
1168
+ *
1169
+ * Unlike the old recorder, this watcher does NOT relocate or re-stat: the
1170
+ * SegmentStore owns the move + the authoritative byte count.
1171
+ */
1172
+ async function handleSegmentEntry(outDir, entry, durMs, onFinalized, logger) {
1173
+ const flatAbsPath = path.isAbsolute(entry.segPath) ? entry.segPath : path.join(outDir, entry.segPath);
1174
+ const startMs = parseEpochStartMs(flatAbsPath);
1175
+ if (startMs === null) return "skipped";
1176
+ if (await statSize(flatAbsPath) === null) {
1177
+ logger.debug("segment flat file not on disk yet — will retry", { meta: { path: flatAbsPath } });
1178
+ return "pending";
1179
+ }
1180
+ onFinalized(startMs, durMs, flatAbsPath);
1181
+ return "retained";
1050
1182
  }
1183
+ /**
1184
+ * Decide which playlist entries are FINALIZABLE this tick and their corrected
1185
+ * durations, given the previously-processed high-water mark. Pure (no I/O) so
1186
+ * the tick loop is just: read file → plan → hand each off → advance mark.
1187
+ *
1188
+ * The live tail entry is held back while recording continues: a segment's true
1189
+ * duration needs its SUCCESSOR's start (ffmpeg's first-segment EXTINF is
1190
+ * inflated by the initial PTS offset). Once `#EXT-X-ENDLIST` appears the tail
1191
+ * is flushed too — by then it is never the unreliable first segment.
1192
+ */
1051
1193
  function planFinalizations(body, processed) {
1052
- const entries = parseLivePlaylist(body);
1053
- const endlist = body.includes("#EXT-X-ENDLIST");
1054
- const hw = entries.length < processed ? 0 : processed;
1055
- const finalizable = endlist ? entries.length : Math.max(0, entries.length - 1);
1056
- const toHandle = [];
1057
- for (let i = hw; i < finalizable; i++) {
1058
- const entry = entries[i];
1059
- const startMs = parseEpochStartMs(entry.segPath);
1060
- const nextStartMs = i + 1 < entries.length ? parseEpochStartMs(entries[i + 1].segPath) : null;
1061
- const durMs = startMs === null ? Math.round(entry.durSeconds * 1e3) : correctedDurMs(entry.durSeconds, startMs, nextStartMs);
1062
- toHandle.push({ entry, durMs });
1063
- }
1064
- return { toHandle, from: hw, processed: Math.max(hw, finalizable) };
1194
+ const entries = parseLivePlaylist(body);
1195
+ const endlist = body.includes("#EXT-X-ENDLIST");
1196
+ const hw = entries.length < processed ? 0 : processed;
1197
+ const finalizable = endlist ? entries.length : Math.max(0, entries.length - 1);
1198
+ const toHandle = [];
1199
+ for (let i = hw; i < finalizable; i++) {
1200
+ const entry = entries[i];
1201
+ const startMs = parseEpochStartMs(entry.segPath);
1202
+ const nextStartMs = i + 1 < entries.length ? parseEpochStartMs(entries[i + 1].segPath) : null;
1203
+ const durMs = startMs === null ? Math.round(entry.durSeconds * 1e3) : correctedDurMs(entry.durSeconds, startMs, nextStartMs);
1204
+ toHandle.push({
1205
+ entry,
1206
+ durMs
1207
+ });
1208
+ }
1209
+ return {
1210
+ toHandle,
1211
+ from: hw,
1212
+ processed: Math.max(hw, finalizable)
1213
+ };
1065
1214
  }
1215
+ /**
1216
+ * Start polling `<outDir>/live.m3u8`. Returns a handle whose `stop()`
1217
+ * cancels the timer. Errors during a tick are swallowed (logged at debug)
1218
+ * — a transient read race self-corrects on the next interval.
1219
+ */
1066
1220
  function startSegmentWatcher(deps) {
1067
- const playlistPath = path__default.join(deps.outDir, "live.m3u8");
1068
- let processed = 0;
1069
- let stopped = false;
1070
- let ticking = false;
1071
- let pendingIndex = -1;
1072
- let pendingTicks = 0;
1073
- const tick = async () => {
1074
- if (stopped || ticking) return;
1075
- ticking = true;
1076
- try {
1077
- let body;
1078
- try {
1079
- body = await promises.readFile(playlistPath, "utf8");
1080
- } catch {
1081
- return;
1082
- }
1083
- const plan = planFinalizations(body, processed);
1084
- let index = plan.from;
1085
- for (const { entry, durMs } of plan.toHandle) {
1086
- const status = await handleSegmentEntry(deps.outDir, entry, durMs, deps.classify, deps.onSegment, deps.logger);
1087
- if (status === "pending") {
1088
- if (pendingIndex === index) {
1089
- pendingTicks++;
1090
- if (pendingTicks >= MAX_PENDING_TICKS) {
1091
- deps.logger.warn("segment file never landed — skipping", { meta: { seg: entry.segPath } });
1092
- pendingIndex = -1;
1093
- pendingTicks = 0;
1094
- index++;
1095
- continue;
1096
- }
1097
- } else {
1098
- pendingIndex = index;
1099
- pendingTicks = 1;
1100
- }
1101
- break;
1102
- }
1103
- index++;
1104
- }
1105
- if (pendingIndex !== index) {
1106
- pendingIndex = -1;
1107
- pendingTicks = 0;
1108
- }
1109
- processed = index;
1110
- } finally {
1111
- ticking = false;
1112
- }
1113
- };
1114
- const timer = setInterval(() => {
1115
- void tick();
1116
- }, deps.intervalMs);
1117
- timer.unref?.();
1118
- return {
1119
- stop() {
1120
- stopped = true;
1121
- clearInterval(timer);
1122
- }
1123
- };
1221
+ const playlistPath = path.join(deps.outDir, "live.m3u8");
1222
+ let processed = 0;
1223
+ let stopped = false;
1224
+ let ticking = false;
1225
+ let pendingIndex = -1;
1226
+ let pendingTicks = 0;
1227
+ const tick = async () => {
1228
+ if (stopped || ticking) return;
1229
+ ticking = true;
1230
+ try {
1231
+ let body;
1232
+ try {
1233
+ body = await promises.readFile(playlistPath, "utf8");
1234
+ } catch {
1235
+ return;
1236
+ }
1237
+ const plan = planFinalizations(body, processed);
1238
+ let index = plan.from;
1239
+ for (const { entry, durMs } of plan.toHandle) {
1240
+ if (await handleSegmentEntry(deps.outDir, entry, durMs, deps.onFinalized, deps.logger) === "pending") {
1241
+ if (pendingIndex === index) {
1242
+ pendingTicks++;
1243
+ if (pendingTicks >= MAX_PENDING_TICKS) {
1244
+ deps.logger.warn("segment file never landed — skipping", { meta: { seg: entry.segPath } });
1245
+ pendingIndex = -1;
1246
+ pendingTicks = 0;
1247
+ index++;
1248
+ continue;
1249
+ }
1250
+ } else {
1251
+ pendingIndex = index;
1252
+ pendingTicks = 1;
1253
+ }
1254
+ break;
1255
+ }
1256
+ index++;
1257
+ }
1258
+ if (pendingIndex !== index) {
1259
+ pendingIndex = -1;
1260
+ pendingTicks = 0;
1261
+ }
1262
+ processed = index;
1263
+ } finally {
1264
+ ticking = false;
1265
+ }
1266
+ };
1267
+ const timer = setInterval(() => {
1268
+ tick();
1269
+ }, deps.intervalMs);
1270
+ timer.unref?.();
1271
+ return { stop() {
1272
+ stopped = true;
1273
+ clearInterval(timer);
1274
+ } };
1124
1275
  }
1125
- async function scanRecordings(rootDir, opts) {
1126
- const locationId = opts?.locationId;
1127
- const withSizes = opts?.withSizes ?? false;
1128
- let names;
1129
- try {
1130
- names = await promises.readdir(rootDir, { recursive: true });
1131
- } catch {
1132
- return [];
1133
- }
1134
- const entries = [];
1135
- for (const name of names) {
1136
- const rel = name.split(path__default.sep).join("/");
1137
- if (!parseSegmentRelPath(rel)) continue;
1138
- if (withSizes) {
1139
- let st;
1140
- try {
1141
- st = await promises.stat(path__default.join(rootDir, name));
1142
- } catch {
1143
- continue;
1144
- }
1145
- entries.push({ relPath: rel, bytes: st.size, locationId });
1146
- } else {
1147
- entries.push({ relPath: rel, bytes: 0, locationId });
1148
- }
1149
- }
1150
- return entries;
1276
+ //#endregion
1277
+ //#region src/recorder/addon/readiness-restore.ts
1278
+ var ReadinessRestore = class {
1279
+ deps;
1280
+ pending = /* @__PURE__ */ new Map();
1281
+ draining = false;
1282
+ rerun = false;
1283
+ unsub = null;
1284
+ constructor(deps) {
1285
+ this.deps = deps;
1286
+ }
1287
+ /** Seed the pending set, subscribe to readiness, and drain once immediately
1288
+ * (covers the already-ready case). Returns when the first drain settles. */
1289
+ async start(items) {
1290
+ for (const [k, v] of items) this.pending.set(k, v);
1291
+ if (this.unsub === null) this.unsub = this.deps.subscribeReady(() => {
1292
+ this.drain();
1293
+ });
1294
+ await this.drain();
1295
+ }
1296
+ /** Add (or replace) one pending item without re-subscribing. Does NOT drain. */
1297
+ add(key, value) {
1298
+ this.pending.set(key, value);
1299
+ }
1300
+ /** Remove one pending item (e.g. the camera was disabled before it attached). */
1301
+ remove(key) {
1302
+ this.pending.delete(key);
1303
+ }
1304
+ /** Unsubscribe from readiness. Call on shutdown. */
1305
+ stop() {
1306
+ this.unsub?.();
1307
+ this.unsub = null;
1308
+ this.pending.clear();
1309
+ }
1310
+ get pendingCount() {
1311
+ return this.pending.size;
1312
+ }
1313
+ hasPending(key) {
1314
+ return this.pending.has(key);
1315
+ }
1316
+ /** Attempt every still-pending item; repeat once if a readiness signal arrived
1317
+ * mid-flight. Re-entrant and self-coalescing. */
1318
+ async drain() {
1319
+ if (this.draining) {
1320
+ this.rerun = true;
1321
+ return;
1322
+ }
1323
+ if (this.pending.size === 0) return;
1324
+ this.draining = true;
1325
+ try {
1326
+ do {
1327
+ this.rerun = false;
1328
+ for (const [key, value] of [...this.pending]) try {
1329
+ await this.deps.attempt(key, value);
1330
+ this.pending.delete(key);
1331
+ } catch (err) {
1332
+ this.deps.onDefer?.(key, value, err);
1333
+ }
1334
+ } while (this.rerun && this.pending.size > 0);
1335
+ } finally {
1336
+ this.draining = false;
1337
+ }
1338
+ }
1339
+ };
1340
+ //#endregion
1341
+ //#region src/recorder/band-engine.ts
1342
+ function toMin(hhmm) {
1343
+ const [h, m] = hhmm.split(":");
1344
+ return Number(h) * 60 + Number(m);
1151
1345
  }
1152
- async function sizeRecordingsTree(rootDir) {
1153
- let names;
1154
- try {
1155
- names = await promises.readdir(rootDir, { recursive: true });
1156
- } catch {
1157
- return { perDevice: /* @__PURE__ */ new Map(), totalBytes: 0 };
1158
- }
1159
- const perDevice = /* @__PURE__ */ new Map();
1160
- let totalBytes = 0;
1161
- for (const name of names) {
1162
- const rel = name.split(path__default.sep).join("/");
1163
- const parsed = parseSegmentRelPath(rel);
1164
- if (!parsed) continue;
1165
- let size;
1166
- try {
1167
- size = (await promises.stat(path__default.join(rootDir, name))).size;
1168
- } catch {
1169
- continue;
1170
- }
1171
- perDevice.set(parsed.camera, (perDevice.get(parsed.camera) ?? 0) + size);
1172
- totalBytes += size;
1173
- }
1174
- return { perDevice, totalBytes };
1346
+ function bandActiveAt(band, date) {
1347
+ const wd = date.getDay();
1348
+ const prevWd = (wd + 6) % 7;
1349
+ const t = date.getHours() * 60 + date.getMinutes();
1350
+ const s = toMin(band.start);
1351
+ const e = toMin(band.end);
1352
+ const applies = (d) => band.days.length === 0 || band.days.includes(d);
1353
+ if (s < e) return applies(wd) && t >= s && t < e;
1354
+ if (s > e) return applies(wd) && t >= s || applies(prevWd) && t < e;
1355
+ return applies(wd);
1175
1356
  }
1176
- function mergeRootUsage(usages) {
1177
- const perDevice = /* @__PURE__ */ new Map();
1178
- let totalBytes = 0;
1179
- for (const u of usages) {
1180
- for (const [device, bytes] of u.perDevice) {
1181
- perDevice.set(device, (perDevice.get(device) ?? 0) + bytes);
1182
- }
1183
- totalBytes += u.totalBytes;
1184
- }
1185
- return { perDevice, totalBytes };
1357
+ function activeBandAt(config, date) {
1358
+ return config.bands.find((b) => bandActiveAt(b, date)) ?? null;
1186
1359
  }
1187
- const CONTAINER_BOXES = /* @__PURE__ */ new Set(["moov", "trak", "mdia", "minf", "stbl"]);
1188
- const H264_CODINGS = /* @__PURE__ */ new Set(["avc1", "avc3"]);
1189
- const HEVC_CODINGS = /* @__PURE__ */ new Set(["hvc1", "hev1"]);
1190
- function readBoxHeader(buf, o) {
1191
- if (o + 8 > buf.length) return null;
1192
- let size = buf.readUInt32BE(o);
1193
- let headerSize = 8;
1194
- if (size === 1) {
1195
- if (o + 16 > buf.length) return null;
1196
- size = Number(buf.readBigUInt64BE(o + 8));
1197
- headerSize = 16;
1198
- }
1199
- const type = buf.toString("latin1", o + 4, o + 8);
1200
- if (size < headerSize) return null;
1201
- return { size, type, headerSize };
1360
+ //#endregion
1361
+ //#region src/recorder/addon/band-decision.ts
1362
+ /**
1363
+ * Is an `events` band's live demand window open at `atMs`? True iff a trigger
1364
+ * the band listens for fired within `postBufferSec` of now. `preBufferSec` is
1365
+ * deliberately NOT consulted here (see file header).
1366
+ */
1367
+ function eventsBandDemanded(band, triggers, atMs) {
1368
+ const postMs = (band.postBufferSec ?? 0) * 1e3;
1369
+ const fresh = (lastMs) => lastMs != null && atMs - lastMs <= postMs;
1370
+ if (band.triggers?.motion && fresh(triggers.lastMotionMs)) return true;
1371
+ if (band.triggers?.audioThresholdDbfs != null && fresh(triggers.lastAudioMs)) return true;
1372
+ return false;
1202
1373
  }
1203
- function findChild(buf, start, end, wanted) {
1204
- let o = start;
1205
- while (o + 8 <= end) {
1206
- const h = readBoxHeader(buf, o);
1207
- if (!h) return null;
1208
- if (h.type === wanted) return { contentStart: o + h.headerSize, end: Math.min(o + h.size, end) };
1209
- o += h.size;
1210
- }
1211
- return null;
1374
+ /**
1375
+ * Should recording (any mode) be active for this device at `at`? The live
1376
+ * attach/detach gate: enabled + a band covers `at` + that band demands now
1377
+ * (continuous always; events within `postBufferSec` of a qualifying trigger).
1378
+ */
1379
+ function shouldRecordAt(config, triggers, at) {
1380
+ if (!config.enabled) return false;
1381
+ const bands = config.bands;
1382
+ if (!bands || bands.length === 0) return false;
1383
+ const band = activeBandAt({ bands }, at);
1384
+ if (!band) return false;
1385
+ if (band.mode === "continuous") return true;
1386
+ return eventsBandDemanded(band, triggers, at.getTime());
1212
1387
  }
1213
- function avcCodecString(buf, avcCContentStart) {
1214
- const profile = buf.readUInt8(avcCContentStart + 1);
1215
- const compat = buf.readUInt8(avcCContentStart + 2);
1216
- const level = buf.readUInt8(avcCContentStart + 3);
1217
- const hex = (n) => n.toString(16).padStart(2, "0");
1218
- return `avc1.${hex(profile)}${hex(compat)}${hex(level)}`;
1388
+ /**
1389
+ * Should a finalized segment `[segStartMs, segEndMs]` recorded under an
1390
+ * `events` band be KEPT (else discarded)? Kept iff it overlaps any qualifying
1391
+ * trigger's full window `[trigger - preBufferSec, trigger + postBufferSec]`.
1392
+ * This is where `preBufferSec` retroactively retains pre-trigger footage.
1393
+ */
1394
+ function segmentRetainedForEvents(segStartMs, segEndMs, band, triggers) {
1395
+ const preMs = (band.preBufferSec ?? 0) * 1e3;
1396
+ const postMs = (band.postBufferSec ?? 0) * 1e3;
1397
+ const overlaps = (lastMs) => lastMs != null && segStartMs <= lastMs + postMs && segEndMs >= lastMs - preMs;
1398
+ if (band.triggers?.motion && overlaps(triggers.lastMotionMs)) return true;
1399
+ if (band.triggers?.audioThresholdDbfs != null && overlaps(triggers.lastAudioMs)) return true;
1400
+ return false;
1219
1401
  }
1220
- function extractVideoCodecInfo(buf) {
1221
- let result = null;
1222
- const walk = (start, end) => {
1223
- let o = start;
1224
- while (o + 8 <= end && !result) {
1225
- const h = readBoxHeader(buf, o);
1226
- if (!h) return;
1227
- const boxEnd = Math.min(o + h.size, end);
1228
- if (CONTAINER_BOXES.has(h.type)) {
1229
- walk(o + h.headerSize, boxEnd);
1230
- } else if (h.type === "stsd") {
1231
- let p = o + h.headerSize + 8;
1232
- while (p + 8 <= boxEnd && !result) {
1233
- const e = readBoxHeader(buf, p);
1234
- if (!e) break;
1235
- const isH264 = H264_CODINGS.has(e.type);
1236
- const isHevc = HEVC_CODINGS.has(e.type);
1237
- if (isH264 || isHevc) {
1238
- const width = p + 34 <= boxEnd ? buf.readUInt16BE(p + 32) : 0;
1239
- const height = p + 36 <= boxEnd ? buf.readUInt16BE(p + 34) : 0;
1240
- let codec;
1241
- if (isH264) {
1242
- const avcC = findChild(buf, p + 8 + 78, Math.min(p + e.size, boxEnd), "avcC");
1243
- codec = avcC ? avcCodecString(buf, avcC.contentStart) : "avc1.640029";
1244
- } else {
1245
- codec = `${e.type}.1.6.L120.B0`;
1246
- }
1247
- result = { codec, width, height };
1248
- }
1249
- p += e.size;
1250
- }
1251
- }
1252
- o += h.size;
1253
- }
1254
- };
1255
- walk(0, buf.length);
1256
- return result;
1402
+ //#endregion
1403
+ //#region src/recorder/addon/recording-controller.ts
1404
+ /**
1405
+ * recorder recording controller — the B2 continuous-band write path.
1406
+ *
1407
+ * Owns, per (deviceId, profile), the lifecycle of:
1408
+ * - a broker stream lease (`getStreamWithCodec`, released on detach),
1409
+ * - an ffmpeg `SegmentWriter` (passthrough segmenter into a temp outDir),
1410
+ * - a `live.m3u8` `SegmentWatcher` that hands each finalized flat segment to
1411
+ * the v2 `SegmentStore.onFinalized` (stat + relocate + index).
1412
+ *
1413
+ * Per device it decides whether a CONTINUOUS band is active right now
1414
+ * (`shouldRecordContinuousAt`) and ensures the writer set is running iff so.
1415
+ * It re-evaluates on three triggers:
1416
+ * 1. `setDeviceConfig` (operator changed the bands / enable),
1417
+ * 2. a periodic tick (catches band boundaries crossed with no config change),
1418
+ * 3. a `stream-broker` ready transition (boot restore — via `ReadinessRestore`).
1419
+ *
1420
+ * EVENTS bands are treated as "not recording continuously" in B2 B3 adds
1421
+ * trigger-gating. The enable intent is persisted in durable-state by the
1422
+ * config-store, so `restoreEnabledDevices` on boot re-attaches every device
1423
+ * whose persisted config records continuously now.
1424
+ *
1425
+ * Source acquisition rides the broker's single source dial: the controller
1426
+ * gates each broker call on the broker's readiness via the cached capability
1427
+ * handle (`useCapability(...).call(fn)`) — no bespoke retry/backoff, the
1428
+ * `ReadinessRegistry` is the single source of truth.
1429
+ */
1430
+ var DEFAULT_WATCH_INTERVAL_MS = 2e3;
1431
+ /** Periodic re-evaluation to catch band boundaries crossed with no config change. */
1432
+ var TICK_MS = 3e4;
1433
+ var RecordingController = class {
1434
+ deps;
1435
+ active = /* @__PURE__ */ new Map();
1436
+ /** Latest qualifying trigger timestamps per device — drives `events`-band gating. */
1437
+ triggers = /* @__PURE__ */ new Map();
1438
+ restore = null;
1439
+ tickTimer = null;
1440
+ stopped = false;
1441
+ constructor(deps) {
1442
+ this.deps = deps;
1443
+ }
1444
+ now() {
1445
+ return this.deps.now?.() ?? Date.now();
1446
+ }
1447
+ /**
1448
+ * Boot restore: seed the readiness-gated queue with every persisted device and
1449
+ * (re)evaluate each on every `stream-broker` ready transition. Also arms the
1450
+ * periodic tick. Idempotent — safe to call once after the index is hydrated.
1451
+ */
1452
+ async start() {
1453
+ if (this.stopped) return;
1454
+ let ids;
1455
+ try {
1456
+ ids = await this.deps.enabledDeviceIds();
1457
+ } catch (err) {
1458
+ this.deps.logger.warn("recorder controller: reading persisted devices failed", { meta: { error: errMsg(err) } });
1459
+ ids = [];
1460
+ }
1461
+ this.restore = new ReadinessRestore({
1462
+ subscribeReady: (handler) => this.deps.onBrokerReady(handler),
1463
+ attempt: async (deviceId) => {
1464
+ await this.evaluateDevice(deviceId);
1465
+ },
1466
+ onDefer: (deviceId, _v, err) => this.deps.logger.warn("recorder controller: device evaluate deferred (retries on next broker ready)", {
1467
+ tags: { deviceId },
1468
+ meta: { error: errMsg(err) }
1469
+ })
1470
+ });
1471
+ if (this.tickTimer === null) {
1472
+ this.tickTimer = setInterval(() => {
1473
+ this.tick();
1474
+ }, TICK_MS);
1475
+ this.tickTimer.unref?.();
1476
+ }
1477
+ await this.restore.start(ids.map((id) => [id, true]));
1478
+ }
1479
+ /** Re-evaluate every currently-tracked OR active device on the periodic tick. */
1480
+ async tick() {
1481
+ if (this.stopped) return;
1482
+ const ids = new Set(this.active.keys());
1483
+ let persisted = [];
1484
+ try {
1485
+ persisted = await this.deps.enabledDeviceIds();
1486
+ } catch {}
1487
+ for (const id of persisted) ids.add(id);
1488
+ for (const id of ids) try {
1489
+ await this.evaluateDevice(id);
1490
+ } catch (err) {
1491
+ this.deps.logger.warn("recorder controller: tick evaluate failed", {
1492
+ tags: { deviceId: id },
1493
+ meta: { error: errMsg(err) }
1494
+ });
1495
+ }
1496
+ }
1497
+ /**
1498
+ * Re-evaluate one device after a config change (called from `setDeviceConfig`).
1499
+ * Failures propagate so the caller can surface them, but the persisted config
1500
+ * has already been written by the time this runs.
1501
+ */
1502
+ async onConfigChanged(deviceId) {
1503
+ if (this.stopped) return;
1504
+ await this.evaluateDevice(deviceId);
1505
+ }
1506
+ /**
1507
+ * One profile's ffmpeg writer exhausted its bounded inner restarts and gave
1508
+ * up. The device is still in `active` with a dead writer, so `evaluateDevice`
1509
+ * would short-circuit at "already recording — converged" and never recover.
1510
+ * Detach the WHOLE device (releases every broker lease + stops watchers, so the
1511
+ * idle source can re-dial cleanly), then re-evaluate: if the band still demands
1512
+ * recording, `evaluateDevice` re-queues + re-attaches a fresh writer set. If
1513
+ * the broker is not ready, the re-attach throws and the device stays on the
1514
+ * readiness queue (retried on the next broker ready) — and the periodic tick is
1515
+ * the backstop. Bounded OUTER retry (TICK_MS cadence), never a tight loop.
1516
+ */
1517
+ async recoverWriterGaveUp(deviceId) {
1518
+ if (this.stopped) return;
1519
+ this.deps.logger.warn("recorder: writer gave up — detaching + re-evaluating device", { tags: { deviceId } });
1520
+ try {
1521
+ await this.detachDevice(deviceId);
1522
+ await this.evaluateDevice(deviceId);
1523
+ } catch (err) {
1524
+ this.restore?.add(deviceId, true);
1525
+ this.deps.logger.warn("recorder: writer give-up recovery deferred (retries on next broker ready/tick)", {
1526
+ tags: { deviceId },
1527
+ meta: { error: errMsg(err) }
1528
+ });
1529
+ }
1530
+ }
1531
+ /** Current trigger state for a device (cold default = no triggers seen). */
1532
+ triggersFor(deviceId) {
1533
+ return this.triggers.get(deviceId) ?? {
1534
+ lastMotionMs: null,
1535
+ lastAudioMs: null
1536
+ };
1537
+ }
1538
+ /**
1539
+ * Record a qualifying trigger (motion/audio) for a device and converge: an
1540
+ * `events` band whose window this opens attaches now; the periodic tick
1541
+ * detaches it once `postBufferSec` elapses. Called from the addon's
1542
+ * EventCapture subscription. The qualification test (motion detected / audio
1543
+ * over threshold) is done upstream — by the time we're here, it qualified.
1544
+ */
1545
+ async onTrigger(deviceId, source, atMs) {
1546
+ if (this.stopped) return;
1547
+ const prev = this.triggersFor(deviceId);
1548
+ this.triggers.set(deviceId, {
1549
+ lastMotionMs: source === "motion" ? atMs : prev.lastMotionMs,
1550
+ lastAudioMs: source === "audio" ? atMs : prev.lastAudioMs
1551
+ });
1552
+ await this.evaluateDevice(deviceId);
1553
+ }
1554
+ /**
1555
+ * Decide-and-converge for one device: if its active band demands recording now
1556
+ * (continuous always; events within `postBufferSec` of a trigger) and the
1557
+ * device is enabled, ensure its writer set is running; otherwise stop it.
1558
+ * Re-attaches via the readiness queue if the broker is not ready (the broker
1559
+ * call throws → `ReadinessRestore.attempt` defers → retried on next ready).
1560
+ */
1561
+ async evaluateDevice(deviceId) {
1562
+ if (this.stopped) return;
1563
+ const config = await this.deps.loadConfig(deviceId);
1564
+ if (!shouldRecordAt(config, this.triggersFor(deviceId), new Date(this.now()))) {
1565
+ await this.detachDevice(deviceId);
1566
+ this.restore?.remove(deviceId);
1567
+ return;
1568
+ }
1569
+ if (this.active.has(deviceId)) return;
1570
+ this.restore?.add(deviceId, true);
1571
+ const profiles = await this.resolveProfiles(deviceId, config.profiles);
1572
+ if (profiles.length === 0) throw new Error(`recorder controller: no assigned broker sources for device ${deviceId}`);
1573
+ const segmentSeconds = config.segmentSeconds ?? this.deps.segmentSeconds;
1574
+ const recordings = [];
1575
+ try {
1576
+ for (const profile of profiles) recordings.push(await this.attachProfile(deviceId, profile, segmentSeconds));
1577
+ } catch (err) {
1578
+ for (const r of recordings) await this.teardownProfile(deviceId, r);
1579
+ throw err;
1580
+ }
1581
+ this.active.set(deviceId, recordings);
1582
+ this.deps.logger.info("recorder pinned broker source(s) for recording", {
1583
+ tags: { deviceId },
1584
+ meta: {
1585
+ profiles,
1586
+ segmentSeconds,
1587
+ pipelineKeys: recordings.map((r) => r.pipelineKey)
1588
+ }
1589
+ });
1590
+ }
1591
+ /**
1592
+ * Pick which profiles to record. The broker enumerates assigned profile slots,
1593
+ * deduped by physical source (`selectAssignedProfileSlots`) so the same camera
1594
+ * encoder is never recorded twice. An operator `override` DISABLES the
1595
+ * unselected profiles (assigned ∩ selection); a selection matching none of the
1596
+ * assigned sources is ignored (record every assigned source — minimum of 1).
1597
+ */
1598
+ async resolveProfiles(deviceId, override) {
1599
+ const assigned = selectAssignedProfileSlots(await this.deps.brokerCall(() => this.deps.api.streamBroker.listAllProfileSlots.query()), deviceId).map((slot) => slot.profile);
1600
+ if (!override || override.length === 0) return assigned;
1601
+ const selected = assigned.filter((p) => override.includes(p));
1602
+ return selected.length > 0 ? selected : assigned;
1603
+ }
1604
+ /**
1605
+ * Attach one (device, profile): acquire the broker source, mkdir the temp
1606
+ * outDir, spawn the SegmentWriter, and start the watcher that feeds finalized
1607
+ * flat segments into `SegmentStore.onFinalized`.
1608
+ */
1609
+ async attachProfile(deviceId, profile, segmentSeconds) {
1610
+ const source = await this.deps.brokerCall(() => this.deps.api.streamBroker.getStreamWithCodec.mutate({
1611
+ deviceId,
1612
+ video: "copy",
1613
+ audio: "aac",
1614
+ profile,
1615
+ ...this.deps.consumerHostname !== void 0 ? { hostname: this.deps.consumerHostname } : {},
1616
+ tag: `recorder:${deviceId}/${profile}`
1617
+ }));
1618
+ const outDir = path.join(this.deps.tmpRoot, String(deviceId), profile);
1619
+ await promises.mkdir(outDir, { recursive: true });
1620
+ const writer = new SegmentWriter({
1621
+ rtspUrl: source.url,
1622
+ outDir,
1623
+ segmentSeconds
1624
+ }, {
1625
+ spawn: this.deps.spawn,
1626
+ logger: this.deps.logger,
1627
+ onGaveUp: () => {
1628
+ this.recoverWriterGaveUp(deviceId);
1629
+ }
1630
+ });
1631
+ writer.start();
1632
+ const placement = this.resolvePlacement(profile);
1633
+ return {
1634
+ profile,
1635
+ writer,
1636
+ watcher: startSegmentWatcher({
1637
+ outDir,
1638
+ intervalMs: this.deps.watchIntervalMs > 0 ? this.deps.watchIntervalMs : DEFAULT_WATCH_INTERVAL_MS,
1639
+ onFinalized: (startMs, durMs, flatAbsPath) => {
1640
+ this.handleFinalizedSegment(deviceId, profile, placement, startMs, durMs, flatAbsPath);
1641
+ },
1642
+ logger: this.deps.logger
1643
+ }),
1644
+ pipelineKey: source.pipelineKey,
1645
+ outDir
1646
+ };
1647
+ }
1648
+ /**
1649
+ * Index a finalized segment — unless it was recorded under an `events` band
1650
+ * and falls OUTSIDE every trigger's `[trigger-preBufferSec, trigger+postBufferSec]`
1651
+ * window, in which case it is discarded (deleted, never indexed). Continuous
1652
+ * footage (or any segment with no active events band) is always indexed: the
1653
+ * keep/discard gate touches `events`-mode segments only, so the continuous
1654
+ * path is unchanged.
1655
+ */
1656
+ async handleFinalizedSegment(deviceId, profile, placement, startMs, durMs, flatAbsPath) {
1657
+ try {
1658
+ const band = activeBandAt({ bands: (await this.deps.loadConfig(deviceId)).bands ?? [] }, new Date(startMs + durMs));
1659
+ if (band?.mode === "events" && !segmentRetainedForEvents(startMs, startMs + durMs, band, this.triggersFor(deviceId))) {
1660
+ await promises.unlink(flatAbsPath).catch(() => {});
1661
+ return;
1662
+ }
1663
+ await this.deps.segmentStore.onFinalized({
1664
+ deviceId,
1665
+ profile,
1666
+ locationId: placement.id,
1667
+ locationRoot: placement.root,
1668
+ flatAbsPath,
1669
+ startMs,
1670
+ durMs
1671
+ });
1672
+ } catch (err) {
1673
+ this.deps.logger.warn("recorder: onFinalized failed", {
1674
+ tags: { deviceId },
1675
+ meta: {
1676
+ profile,
1677
+ error: errMsg(err)
1678
+ }
1679
+ });
1680
+ }
1681
+ }
1682
+ /**
1683
+ * Resolve the storage location a profile writes to: `low` → the recordingsLow
1684
+ * location when present, every other profile → the recordings location. Falls
1685
+ * back to the first resolved location when the preferred type is absent — both
1686
+ * types resolve to the same path today, so the split is free-and-future-proof.
1687
+ */
1688
+ resolvePlacement(profile) {
1689
+ const locations = this.deps.locations();
1690
+ if (locations.length === 0) throw new Error("recorder controller: no recordings storage locations resolved");
1691
+ const preferLow = profile === "low";
1692
+ return locations.find((l) => preferLow ? l.id === "recordingsLow" : l.id === "recordings") ?? locations[0];
1693
+ }
1694
+ /** Stop one profile's writer + watcher and release its broker lease. */
1695
+ async teardownProfile(deviceId, r) {
1696
+ try {
1697
+ r.watcher.stop();
1698
+ } catch {}
1699
+ try {
1700
+ r.writer.stop();
1701
+ } catch {}
1702
+ try {
1703
+ await this.deps.api.streamBroker.releaseStreamWithCodec.mutate({ pipelineKey: r.pipelineKey });
1704
+ } catch (err) {
1705
+ this.deps.logger.warn("recorder: releaseStreamWithCodec failed", {
1706
+ tags: { deviceId },
1707
+ meta: {
1708
+ profile: r.profile,
1709
+ pipelineKey: r.pipelineKey,
1710
+ error: errMsg(err)
1711
+ }
1712
+ });
1713
+ }
1714
+ }
1715
+ /** Stop every profile recording for a device (no-op when not recording). */
1716
+ async detachDevice(deviceId) {
1717
+ const recordings = this.active.get(deviceId);
1718
+ if (!recordings) return;
1719
+ this.active.delete(deviceId);
1720
+ for (const r of recordings) await this.teardownProfile(deviceId, r);
1721
+ this.deps.logger.info("recorder unpinned broker source(s) — recording stopped", {
1722
+ tags: { deviceId },
1723
+ meta: { pipelineKeys: recordings.map((r) => r.pipelineKey) }
1724
+ });
1725
+ }
1726
+ /** Tear EVERYTHING down: timer, restore subscription, every writer/watcher/lease. */
1727
+ async stop() {
1728
+ this.stopped = true;
1729
+ if (this.tickTimer !== null) {
1730
+ clearInterval(this.tickTimer);
1731
+ this.tickTimer = null;
1732
+ }
1733
+ this.restore?.stop();
1734
+ this.restore = null;
1735
+ for (const deviceId of [...this.active.keys()]) await this.detachDevice(deviceId);
1736
+ }
1737
+ };
1738
+ /** Build a `stream-broker` readiness scope for one node. */
1739
+ function brokerScope(nodeId) {
1740
+ return {
1741
+ type: "node",
1742
+ nodeId
1743
+ };
1257
1744
  }
1258
- const AttachCameraInputSchema = object({
1259
- deviceId: number().int().nonnegative(),
1260
- profiles: array(CamProfileSchema).optional(),
1261
- segmentSeconds: number().int().positive().optional(),
1262
- rules: array(RecordingRuleSchema).optional(),
1263
- retention: RecordingRetentionSchema.optional()
1264
- });
1265
- const AttachCameraResultSchema = object({
1266
- success: literal(true)
1267
- });
1268
- const DetachCameraInputSchema = object({
1269
- deviceId: number().int().nonnegative()
1270
- });
1271
- const DetachCameraResultSchema = object({
1272
- success: literal(true)
1273
- });
1274
- const SetPlacementInputSchema = object({
1275
- assignments: record(string(), array(string()))
1276
- });
1277
- const SetPlacementResultSchema = object({
1278
- success: literal(true)
1279
- });
1280
- const recorderActions = defineCustomActions({
1281
- attachCamera: customAction(AttachCameraInputSchema, AttachCameraResultSchema, { kind: "mutation" }),
1282
- detachCamera: customAction(DetachCameraInputSchema, DetachCameraResultSchema, { kind: "mutation" }),
1283
- setPlacement: customAction(SetPlacementInputSchema, SetPlacementResultSchema, { kind: "mutation" })
1284
- });
1285
- function configFromTarget(target) {
1286
- if (!target) return { enabled: false, rules: [] };
1287
- return {
1288
- enabled: target.enabled,
1289
- profiles: target.profiles,
1290
- segmentSeconds: target.segmentSeconds,
1291
- rules: target.rules ?? [],
1292
- retention: target.retention
1293
- };
1745
+ /** Default broker readiness gate timeout (ms) — matches the old recorder. */
1746
+ var BROKER_READY_TIMEOUT_MS = 1e4;
1747
+ /** Wrap a cached capability handle into the `brokerCall` gate the controller needs. */
1748
+ function makeBrokerCall(handle) {
1749
+ return (fn) => handle.call(fn, BROKER_READY_TIMEOUT_MS);
1294
1750
  }
1295
- function targetFromConfig(config) {
1296
- return {
1297
- enabled: config.enabled,
1298
- profiles: config.profiles,
1299
- segmentSeconds: config.segmentSeconds,
1300
- rules: config.rules,
1301
- retention: config.retention
1302
- };
1751
+ //#endregion
1752
+ //#region src/recorder/addon/recording-hub-host.ts
1753
+ /**
1754
+ * Resolve the host a REMOTE recording node should use to dial the hub-only
1755
+ * stream-broker's restream port.
1756
+ *
1757
+ * The broker mints `127.0.0.1` restream URLs (hub-local). When the operator
1758
+ * designates an AGENT as the recording node, that agent's recorder must pull
1759
+ * from the hub, so it needs the hub's cluster-resolvable host. Resolution
1760
+ * order:
1761
+ *
1762
+ * 1. `override` — the `recordingHubHostname` global setting, when the
1763
+ * operator set one explicitly (e.g. the auto-derived host isn't reachable
1764
+ * for RTSP on the recording interface).
1765
+ * 2. `hubUrl` — derived from the agent's `CAMSTACK_HUB_URL` (the address it
1766
+ * already uses to reach the hub). The RTSP restream port differs from the
1767
+ * hub API port, but the HOST is the same — only the host is extracted.
1768
+ *
1769
+ * Returns `undefined` when neither yields a host (the caller logs and the pull
1770
+ * stays hub-local, which simply won't reach a remote node — never a crash).
1771
+ *
1772
+ * Pure: the env string is passed in (not read here) so it can be unit-tested.
1773
+ */
1774
+ function resolveRecordingHubHostname(override, hubUrl) {
1775
+ const trimmedOverride = override?.trim();
1776
+ if (trimmedOverride !== void 0 && trimmedOverride.length > 0) return trimmedOverride;
1777
+ return extractHost(hubUrl);
1303
1778
  }
1304
- function resolveStorageBytes(input) {
1305
- const { indexBytes, hasRanges, statSize: statSize2 } = input;
1306
- if (indexBytes > 0) return indexBytes;
1307
- if (hasRanges) return statSize2;
1308
- return 0;
1779
+ /** Extract the bare host from a URL/authority string, scheme + port optional. */
1780
+ function extractHost(raw) {
1781
+ const value = raw?.trim();
1782
+ if (value === void 0 || value.length === 0) return void 0;
1783
+ try {
1784
+ const parsed = new URL(value);
1785
+ if (parsed.hostname.length > 0) return parsed.hostname;
1786
+ } catch {}
1787
+ const authority = value.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//, "").split("/")[0] ?? "";
1788
+ if (authority.startsWith("[")) {
1789
+ const end = authority.indexOf("]");
1790
+ if (end > 0) return authority.slice(0, end + 1);
1791
+ }
1792
+ const host = authority.split(":")[0] ?? "";
1793
+ return host.length > 0 ? host : void 0;
1309
1794
  }
1310
- const STAT_CACHE_TTL_MS = 3e4;
1311
- const DEFAULT_CONFIG = {
1312
- segmentSeconds: 4,
1313
- watchIntervalMs: 2e3,
1314
- // Sane default so an attached camera can't fill the disk unbounded; the
1315
- // operator raises/lowers it via global addon settings (and, in P6, per
1316
- // device). Age-only by default size cap is opt-in.
1317
- retentionMaxAgeDays: 14,
1318
- retentionMaxSizeGb: 0,
1319
- // 0 = inherit the global default; operator raises the event window for longer
1320
- // motion/audio-clip retention. Present in defaults so resolveConfig reads them.
1321
- continuousRetentionMaxAgeDays: 0,
1322
- continuousRetentionMaxSizeGb: 0,
1323
- eventRetentionMaxAgeDays: 0,
1324
- eventRetentionMaxSizeGb: 0,
1325
- retentionSweepIntervalMs: 15 * 6e4,
1326
- policySweepIntervalMs: 5e3,
1327
- playbackRescanIntervalMs: 5 * 6e4,
1328
- // Present in defaults so `BaseAddon.resolveConfig` reads it from the store
1329
- // (it only merges keys that exist in defaults). Seeded to the standard
1330
- // placement so a fresh install routes high/mid → recordings, low/scrub →
1331
- // recordingsLow automatically, without operator intervention.
1332
- recordingPlacement: { assignments: DEFAULT_RECORDING_PLACEMENT }
1795
+ //#endregion
1796
+ //#region src/recorder/addon/index.ts
1797
+ /**
1798
+ * recorder addon SHELL — recording + storage-evictable providers on the
1799
+ * unit-tested recorder core (`recorder/*.ts`).
1800
+ *
1801
+ * B1 scope (THIS file): the addon lifecycle + provider wiring with NO ffmpeg
1802
+ * and NO live recording. It resolves the `recordings` / `recordingsLow`
1803
+ * storage roots via the `storage` cap, hydrates the v2 `RecordingIndex` from
1804
+ * `storage.list` for every persisted-config device on boot, persists per-device
1805
+ * band config via durable-state, answers the `recording` cap reads from the
1806
+ * index, prunes footage via `selectEvictions` + `SegmentStore.evict`, and
1807
+ * mounts the v2 `StorageEvictableProvider` for disk-pressure eviction.
1808
+ *
1809
+ * DEFERRED to B2/B3 (search "B2/B3 HOOK" below for the exact insertion points):
1810
+ * - ffmpeg `SegmentWriter` (per-profile passthrough segmenter)
1811
+ * - segment watcher → `SegmentStore.onFinalized` (stat + relocate + index)
1812
+ * - `BandEngine` attach/detach on enable/disable (`activeBandAt`/`bandActiveAt`)
1813
+ * - `EventCapture` (motion/audio markers feeding events-mode bands)
1814
+ * - playback data-plane (getPlaybackManifest currently STUBs null)
1815
+ *
1816
+ * The old recorder (`addon-pipeline/src/recorder`) stays the live `recording`
1817
+ * provider until the controller swaps the manifest entry in a later step — this
1818
+ * file ships dormant (separate tree, not wired into the manifest yet).
1819
+ */
1820
+ var DEFAULT_CONFIG = {
1821
+ segmentSeconds: 4,
1822
+ watchIntervalMs: 2e3
1333
1823
  };
1334
- const PROFILE_BANDWIDTH = {
1335
- high: 4e6,
1336
- mid: 15e5,
1337
- low: 5e5
1338
- };
1339
- const DEFAULT_BANDWIDTH = 2e6;
1340
- class RecorderAddon extends BaseAddon {
1341
- core = null;
1342
- nodeId = "hub";
1343
- dataDir = "";
1344
- /** Storage location recordings are written to (the managed `recordings`
1345
- * location). `undefined` = legacy addon-local fallback (storage cap down). */
1346
- recordingLocationId = void 0;
1347
- /** Resolved placement: profile/track location ids. NO fallbackan
1348
- * unassigned profile fails to record, explicitly. */
1349
- placement = { assignments: {} };
1350
- /** Durable handle over the `recordingPlacement` addon-store key. Both the
1351
- * boot load and `setPlacement` route through it so the WHOLE blob round-trips
1352
- * (no hand-listed field can be dropped on save). Built in `onInitialize`. */
1353
- placementState = null;
1354
- /** Cache of locationId absolute root path (via `storage.resolve`). */
1355
- locationRootCache = /* @__PURE__ */ new Map();
1356
- /** Cache of `${deviceId}/${profile}` → master-playlist codec/resolution,
1357
- * probed once from a segment's moov (codec is stable per camera profile). */
1358
- profileCodecCache = /* @__PURE__ */ new Map();
1359
- /** GLOBAL write location chosen per profile/track. Cached so EVERY camera
1360
- * records a given profile to the SAME location (assignment is global, not
1361
- * per-camera). Reset on addon restart (re-config). */
1362
- profileWriteLocation = /* @__PURE__ */ new Map();
1363
- /** One watcher per (deviceId, profile). Keyed `${deviceId}/${profile}`. */
1364
- watchers = /* @__PURE__ */ new Map();
1365
- /** Periodic retention sweep; cleared on shutdown. */
1366
- retentionTimer = null;
1367
- /** Periodic modes-engine policy reaper (pre/post-buffer enforcement). */
1368
- policyTimer = null;
1369
- /** Playback HTTP data-plane (hub reverse-proxies to it); null until served. */
1370
- playbackDataPlane = null;
1371
- /** Periodic disk rescan rebuilding the playback index (past recordings). */
1372
- playbackRescanTimer = null;
1373
- /** In-memory mirror of persisted targets so the SYNC retention resolver can
1374
- * read per-device overrides without I/O. Refreshed on attach/detach/setConfig
1375
- * and boot-restore. */
1376
- deviceTargets = /* @__PURE__ */ new Map();
1377
- /** Short-lived stat-based byte counts keyed by deviceId — used ONLY in the
1378
- * `getStatus` fallback path (index === 0 && footage exists). Entries expire
1379
- * after {@link STAT_CACHE_TTL_MS} so repeated polls don't re-stat on every
1380
- * call, yet the value stays reasonably fresh. */
1381
- statSizeCache = /* @__PURE__ */ new Map();
1382
- constructor() {
1383
- super({ ...DEFAULT_CONFIG });
1384
- }
1385
- async onInitialize() {
1386
- const raw = this.ctx.kernel.localNodeId ?? this.ctx.id;
1387
- this.nodeId = raw.includes("/") ? raw.split("/")[0] : raw;
1388
- const loc = await this.resolveRecordingsLocation();
1389
- this.dataDir = loc.root;
1390
- this.recordingLocationId = loc.locationId;
1391
- if (loc.locationId) this.locationRootCache.set(loc.locationId, loc.root);
1392
- const fallbackAssignments = {};
1393
- for (const [key, ids] of Object.entries(this.config.recordingPlacement?.assignments ?? {})) {
1394
- fallbackAssignments[key] = [...ids];
1395
- }
1396
- this.placementState = this.state(
1397
- "recordingPlacement",
1398
- RecordingPlacementBlobSchema,
1399
- { assignments: fallbackAssignments }
1400
- );
1401
- const loadedPlacement = await this.placementState.get();
1402
- this.placement = { assignments: loadedPlacement.assignments ?? {} };
1403
- this.core = new RecorderCore({
1404
- dataDir: this.dataDir,
1405
- nodeId: this.nodeId,
1406
- acquireSource: (deviceId, profile) => this.acquireSource(deviceId, profile),
1407
- releaseSource: (pipelineKey) => this.releaseSource(pipelineKey),
1408
- makeWriter: (cfg) => {
1409
- mkdirSync(cfg.outDir, { recursive: true });
1410
- return new SegmentWriter(cfg, { spawn, logger: this.ctx.logger });
1411
- },
1412
- logger: this.ctx.logger
1413
- });
1414
- this.startRetentionTimer();
1415
- this.startPolicyTimer();
1416
- this.subscribeTriggers();
1417
- try {
1418
- const handler = createFileDataPlaneHandler({ getRoots: () => this.playbackRoots() });
1419
- this.playbackDataPlane = await this.ctx.dataPlane?.serve({ prefix: "playback", access: "admin", handler }) ?? null;
1420
- this.ctx.logger.info("recorder playback data-plane served", {
1421
- meta: { baseUrl: this.playbackDataPlane?.baseUrl ?? "(no dataPlane facility)" }
1422
- });
1423
- } catch (err) {
1424
- this.ctx.logger.warn("recorder playback data-plane failed to serve", { meta: { error: errMsg(err) } });
1425
- }
1426
- await this.rescanPlayback();
1427
- this.startPlaybackRescanTimer();
1428
- this.ctx.logger.info("recorder addon started", {
1429
- tags: { nodeId: this.nodeId },
1430
- meta: {
1431
- dataDir: this.dataDir,
1432
- segmentSeconds: this.config.segmentSeconds,
1433
- retentionMaxAgeDays: this.config.retentionMaxAgeDays,
1434
- retentionMaxSizeGb: this.config.retentionMaxSizeGb,
1435
- placement: this.placement
1436
- }
1437
- });
1438
- const provider = {
1439
- getStatus: async ({ deviceId }) => {
1440
- if (!this.core) return null;
1441
- const status = this.core.getStatus(deviceId);
1442
- const indexBytes = status.storageBytes;
1443
- if (indexBytes > 0) return status;
1444
- const availability = this.core.getAvailability(deviceId, 0, Date.now());
1445
- const hasRanges = availability.ranges.length > 0;
1446
- const statSize2 = await this.deviceStatSize(deviceId, hasRanges);
1447
- return { ...status, storageBytes: resolveStorageBytes({ indexBytes, hasRanges, statSize: statSize2 }) };
1448
- },
1449
- getAvailability: async ({ deviceId, fromMs, toMs }) => {
1450
- if (!this.core) return { deviceId, ranges: [] };
1451
- return this.core.getAvailability(deviceId, fromMs, toMs);
1452
- },
1453
- getPlaybackManifest: ({ deviceId, fromMs, toMs }) => this.buildPlaybackManifest(deviceId, fromMs, toMs),
1454
- getStorageUsage: () => this.buildStorageUsage(),
1455
- getDeviceConfig: async ({ deviceId }) => {
1456
- const settings = this.ctxIfReady?.settings;
1457
- const target = settings ? (await readRecordingTargets(settings)).get(deviceId) : void 0;
1458
- return configFromTarget(target);
1459
- },
1460
- rescanStorage: async ({ deviceId }) => {
1461
- const core = this.core;
1462
- if (!core) return {
1463
- deviceId,
1464
- enabled: false,
1465
- activeMode: "off",
1466
- nodeId: this.nodeId,
1467
- storageBytes: 0
1468
- };
1469
- core.rescanDevice(deviceId);
1470
- await this.seedIndexForDevice(core, deviceId);
1471
- this.statSizeCache.delete(deviceId);
1472
- const status = core.getStatus(deviceId);
1473
- const indexBytes = status.storageBytes;
1474
- if (indexBytes > 0) return status;
1475
- const availability = core.getAvailability(deviceId, 0, Date.now());
1476
- const hasRanges = availability.ranges.length > 0;
1477
- const statSize2 = await this.deviceStatSize(deviceId, hasRanges);
1478
- return { ...status, storageBytes: resolveStorageBytes({ indexBytes, hasRanges, statSize: statSize2 }) };
1479
- },
1480
- setDeviceConfig: async ({ deviceId, config }) => {
1481
- const next = targetFromConfig(config);
1482
- if (next.enabled) {
1483
- await this.attachCamera({ deviceId, profiles: next.profiles, segmentSeconds: next.segmentSeconds, rules: next.rules, retention: next.retention });
1484
- } else {
1485
- await this.detachCamera({ deviceId });
1486
- const disabledSettings = this.ctx.settings;
1487
- if (disabledSettings) {
1488
- await upsertRecordingTarget(disabledSettings, deviceId, next);
1489
- }
1490
- }
1491
- this.deviceTargets.set(deviceId, next);
1492
- return configFromTarget(next);
1493
- },
1494
- // Per-device recording settings surfaced in device-details (the system
1495
- // contributions pass consults this cap even though it isn't device-bound).
1496
- getDeviceSettingsContribution: (_input) => this.buildDeviceSettingsContribution(),
1497
- getDeviceLiveContribution: async () => null,
1498
- applyDeviceSettingsPatch: async ({ patch }) => {
1499
- const keys = Object.keys(patch ?? {});
1500
- if (keys.length > 0) {
1501
- this.ctx.logger.debug("recorder: ignoring legacy settings patch (widget owns settings)", { meta: { keys } });
1502
- }
1503
- return { success: true };
1504
- },
1505
- pruneFootage: async ({ deviceId }) => {
1506
- const core = this.core;
1507
- if (!core) return { floorMs: null, deletedBuckets: 0, reclaimedBytes: 0 };
1508
- return core.pruneFootageForDevice(
1509
- deviceId,
1510
- Date.now(),
1511
- (id, subtree) => this.resolveRetentionPolicy(id, subtree),
1512
- (relPath, locationId) => this.removeBucketDir(relPath, locationId)
1513
- );
1514
- }
1515
- };
1516
- const evictableProvider = {
1517
- getEvictableUsage: async ({ locationId }) => {
1518
- const core = this.core;
1519
- return { bytes: core ? core.evictableBytesOnLocation(locationId) : 0 };
1520
- },
1521
- evict: async ({ locationId, targetBytes }) => {
1522
- const core = this.core;
1523
- if (!core) return { reclaimedBytes: 0, exhausted: true };
1524
- return core.evictBytesOnLocation(
1525
- locationId,
1526
- targetBytes,
1527
- (relPath, locId) => this.removeBucketDir(relPath, locId)
1528
- );
1529
- }
1530
- };
1531
- return {
1532
- providers: [
1533
- { capability: recordingCapability, provider },
1534
- { capability: storageEvictableCapability, provider: evictableProvider }
1535
- ],
1536
- customActions: recorderActions,
1537
- actionHandlers: {
1538
- attachCamera: async (input) => this.attachCamera(input),
1539
- detachCamera: async (input) => this.detachCamera(input),
1540
- setPlacement: async (input) => this.setPlacement(input)
1541
- }
1542
- };
1543
- }
1544
- async onShutdown() {
1545
- if (this.retentionTimer) {
1546
- clearInterval(this.retentionTimer);
1547
- this.retentionTimer = null;
1548
- }
1549
- if (this.policyTimer) {
1550
- clearInterval(this.policyTimer);
1551
- this.policyTimer = null;
1552
- }
1553
- if (this.playbackRescanTimer) {
1554
- clearInterval(this.playbackRescanTimer);
1555
- this.playbackRescanTimer = null;
1556
- }
1557
- for (const handle of this.watchers.values()) handle.stop();
1558
- this.watchers.clear();
1559
- await this.playbackDataPlane?.dispose();
1560
- this.playbackDataPlane = null;
1561
- await this.core?.detachAll();
1562
- this.core = null;
1563
- }
1564
- // ── Modes engine triggers ──────────────────────────────────────────────
1565
- /**
1566
- * Feed motion events into the policy engine. A `detected:true` transition for
1567
- * a camera records a motion trigger; `onMotion` rules then retain segments
1568
- * for their `postBufferSec`. Recording continuously-connected cameras get the
1569
- * event even though the recorder is a separate process (UDS event bridge).
1570
- * `onAudioThreshold` ingestion is deferred (audio analysis is stream-demand
1571
- * gated) the policy schema already supports it.
1572
- */
1573
- subscribeTriggers() {
1574
- this.ctx.eventBus.subscribe({ category: EventCategory.MotionOnMotionChanged }, (event) => {
1575
- if (!event.data.detected) return;
1576
- this.core?.recordTrigger(event.data.deviceId, "motion", event.data.timestamp);
1577
- });
1578
- this.ctx.eventBus.subscribe({ category: EventCategory.PipelineAudioInferenceResult }, (event) => {
1579
- const dbfs = event.data.frame.level?.dbfs;
1580
- if (dbfs == null) return;
1581
- this.core?.onAudioLevel(event.data.deviceId, dbfs, event.data.frame.timestamp);
1582
- });
1583
- }
1584
- // ── Modes engine policy reaper (pre/post-buffer enforcement) ────────────
1585
- startPolicyTimer() {
1586
- const timer = setInterval(() => void this.sweepPolicy(), this.config.policySweepIntervalMs);
1587
- timer.unref?.();
1588
- this.policyTimer = timer;
1589
- }
1590
- /** Run one policy sweep: retain triggered segments, reap expired-untriggered. */
1591
- async sweepPolicy() {
1592
- const core = this.core;
1593
- if (!core) return;
1594
- try {
1595
- await core.sweepPolicy(
1596
- localClock,
1597
- Date.now(),
1598
- (deviceId, profile, startMs, durMs, locationId, subtree) => this.deleteSegmentFile(deviceId, profile, startMs, durMs, locationId, subtree)
1599
- );
1600
- } catch (err) {
1601
- this.ctx.logger.warn("recorder policy sweep failed", { meta: { error: errMsg(err) } });
1602
- }
1603
- }
1604
- /** Delete one relocated segment file under its storage location's root, in the
1605
- * subtree it was written to. */
1606
- async deleteSegmentFile(deviceId, profile, startMs, durMs, locationId, subtree) {
1607
- const root = await this.locationRootOrDefault(locationId);
1608
- const abs = path__default.resolve(root, segmentRelPath(String(deviceId), profile, subtree, startMs, durMs));
1609
- await promises.rm(abs, { force: true });
1610
- }
1611
- // ── Retention ──────────────────────────────────────────────────────────
1612
- startRetentionTimer() {
1613
- const intervalMs = this.config.retentionSweepIntervalMs;
1614
- const timer = setInterval(() => void this.sweepRetention(), intervalMs);
1615
- timer.unref?.();
1616
- this.retentionTimer = timer;
1617
- }
1618
- /** Run one retention sweep across every attached camera, then enforce the
1619
- * disk-pressure free-space guard across every device. */
1620
- async sweepRetention() {
1621
- const core = this.core;
1622
- if (!core) return;
1623
- const nowMs = Date.now();
1624
- for (const deviceId of core.attachedDevices()) {
1625
- try {
1626
- await pruneDeviceWithEvents(
1627
- core,
1628
- deviceId,
1629
- nowMs,
1630
- (id, subtree) => this.resolveRetentionPolicy(id, subtree),
1631
- (relPath, locationId) => this.removeBucketDir(relPath, locationId),
1632
- this.ctx.api,
1633
- this.ctx.logger
1634
- );
1635
- } catch (err) {
1636
- this.ctx.logger.warn("recorder retention sweep failed for device", { tags: { deviceId }, meta: { error: errMsg(err) } });
1637
- }
1638
- }
1639
- }
1640
- /** Available + total bytes on a volume (`statfs`); null when unstattable. */
1641
- async rootCapacity(root) {
1642
- try {
1643
- const st = await promises.statfs(root);
1644
- return { availableBytes: st.bavail * st.bsize, totalBytes: st.blocks * st.bsize };
1645
- } catch {
1646
- return null;
1647
- }
1648
- }
1649
- // ── Storage-usage report (stat-based, on-demand) ───────────────────────
1650
- /**
1651
- * Accurate recordings storage usage for this node: global total + per-camera
1652
- * (summed over every profile/subtree/location) + per-location used/available.
1653
- * Stat-based so detached cameras count correctly (the playback index is
1654
- * name-only). Includes the read-only legacy root (locationId null) in the
1655
- * totals + per-camera, but never as a guarded managed location.
1656
- */
1657
- async buildStorageUsage() {
1658
- const managed = await this.listRecordingsLocations();
1659
- const roots = managed.map((l) => ({ id: l.id ?? null, root: l.root }));
1660
- const sized = await Promise.all(
1661
- roots.map(async (r) => ({ ...r, usage: await sizeRecordingsTree(r.root) }))
1662
- );
1663
- const merged = mergeRootUsage(sized.map((s) => s.usage));
1664
- const devices = [...merged.perDevice].map(([camera, usedBytes]) => ({ deviceId: Number(camera), usedBytes })).filter((d) => Number.isFinite(d.deviceId)).sort((a, b) => b.usedBytes - a.usedBytes);
1665
- const locations = await Promise.all(
1666
- sized.map(async (s) => {
1667
- const cap = await this.rootCapacity(s.root);
1668
- return {
1669
- locationId: s.id,
1670
- usedBytes: s.usage.totalBytes,
1671
- availableBytes: cap?.availableBytes ?? null,
1672
- totalBytes: cap?.totalBytes ?? null
1673
- };
1674
- })
1675
- );
1676
- return { nodeId: this.nodeId, totalUsedBytes: merged.totalBytes, devices, locations };
1677
- }
1678
- /**
1679
- * Stat the on-disk tree for a single device and return its total bytes.
1680
- * Uses a short-lived cache ({@link STAT_CACHE_TTL_MS}) so repeated `getStatus`
1681
- * polls on the zero-index fallback path don't re-stat on every call.
1682
- *
1683
- * Called ONLY when `indexBytes === 0 && hasRanges` — not on the common
1684
- * non-zero path, so disk I/O cost is limited to the edge case.
1685
- *
1686
- * @param deviceId The device to size.
1687
- * @param hasRanges If false the call is skipped and 0 is returned immediately.
1688
- */
1689
- async deviceStatSize(deviceId, hasRanges) {
1690
- if (!hasRanges) return 0;
1691
- const now = Date.now();
1692
- const cached = this.statSizeCache.get(deviceId);
1693
- if (cached && now < cached.expiresAt) return cached.bytes;
1694
- const roots = this.playbackRoots();
1695
- const key = String(deviceId);
1696
- let total = 0;
1697
- for (const root of roots) {
1698
- const usage = await sizeRecordingsTree(root);
1699
- total += usage.perDevice.get(key) ?? 0;
1700
- }
1701
- this.statSizeCache.set(deviceId, { bytes: total, expiresAt: now + STAT_CACHE_TTL_MS });
1702
- return total;
1703
- }
1704
- /**
1705
- * Resolve the retention policy for a device's `continuous` vs `events`
1706
- * subtree: the per-subtree override (`> 0`) wins, else the global default.
1707
- * P2: global addon config only (per-device override arrives with the
1708
- * per-device settings UI in P6 — `deviceId` is already threaded for that swap).
1709
- */
1710
- resolveRetentionPolicy(deviceId, subtree) {
1711
- const c = this.config;
1712
- const pick = (ovr, base) => ovr > 0 ? ovr : base;
1713
- const defaultAgeDays = subtree === "events" ? pick(c.eventRetentionMaxAgeDays, c.retentionMaxAgeDays) : pick(c.continuousRetentionMaxAgeDays, c.retentionMaxAgeDays);
1714
- const defaultSizeGb = subtree === "events" ? pick(c.eventRetentionMaxSizeGb, c.retentionMaxSizeGb) : pick(c.continuousRetentionMaxSizeGb, c.retentionMaxSizeGb);
1715
- const override = this.deviceTargets.get(deviceId)?.retention;
1716
- return resolveDeviceRetention(override, defaultAgeDays, defaultSizeGb);
1717
- }
1718
- /**
1719
- * `rm -rf` one hour-bucket directory under its storage location's root.
1720
- * `relPath` originates from our own RAM index
1721
- * (`<deviceId>/<profile>/<Y>/<M>/<D>/<H>`) and `locationId` is the location it
1722
- * lives on; resolve against that location's root and refuse anything that
1723
- * escapes it as a defense-in-depth guard.
1724
- */
1725
- async removeBucketDir(relPath, locationId) {
1726
- const root = path__default.resolve(await this.locationRootOrDefault(locationId));
1727
- const abs = path__default.resolve(root, relPath);
1728
- if (abs !== root && !abs.startsWith(root + path__default.sep)) {
1729
- throw new Error(`recorder retention: refusing to rm outside location root: ${relPath}`);
1730
- }
1731
- await promises.rm(abs, { recursive: true, force: true });
1732
- }
1733
- // ── Custom actions ────────────────────────────────────────────────────
1734
- async attachCamera(input) {
1735
- const core = this.core;
1736
- if (!core) throw new Error("RecorderAddon: attachCamera called before initialize completed");
1737
- const profiles = await this.resolveRecordingProfiles(input.deviceId, input.profiles);
1738
- if (profiles.length === 0) {
1739
- throw new Error(
1740
- `RecorderAddon.attachCamera: no assigned broker sources for device ${input.deviceId}`
1741
- );
1742
- }
1743
- const segmentSeconds = input.segmentSeconds ?? this.config.segmentSeconds;
1744
- const rules = input.rules ?? [];
1745
- this.stopWatchers(input.deviceId);
1746
- const placements = await this.resolveProfilePlacements(input.deviceId, profiles);
1747
- const outDirs = {};
1748
- for (const [profile, pl] of placements) outDirs[profile] = pl.outDir;
1749
- await core.attach({ deviceId: input.deviceId, profiles, segmentSeconds, rules, outDirs });
1750
- for (const profile of profiles) {
1751
- const pl = placements.get(profile);
1752
- const key = makeProfileBrokerId(input.deviceId, profile);
1753
- const handle = startSegmentWatcher({
1754
- outDir: pl.outDir,
1755
- intervalMs: this.config.watchIntervalMs,
1756
- // Classify each finalized segment into its continuous/events subtree
1757
- // (node-local clock) so the watcher relocates it into the right tree.
1758
- classify: (startMs, durMs) => this.core?.classifySubtree(input.deviceId, startMs + durMs, localClock(startMs + durMs)) ?? "continuous",
1759
- onSegment: (startMs, durMs, bytes, subtree) => {
1760
- const core2 = this.core;
1761
- if (!core2) return;
1762
- core2.onSegmentFinalized(input.deviceId, profile, startMs, durMs, bytes, pl.locationId, subtree);
1763
- if (core2.shouldRetainSegment(input.deviceId, startMs, startMs + durMs, localClock(startMs + durMs))) {
1764
- core2.markSegmentRetained(input.deviceId, profile, startMs);
1765
- }
1766
- },
1767
- logger: this.ctx.logger
1768
- });
1769
- this.watchers.set(key, handle);
1770
- }
1771
- await this.persistTarget(input);
1772
- this.deviceTargets.set(input.deviceId, {
1773
- enabled: true,
1774
- profiles: input.profiles ? [...input.profiles] : void 0,
1775
- segmentSeconds: input.segmentSeconds,
1776
- rules: input.rules ? [...input.rules] : void 0,
1777
- retention: input.retention
1778
- });
1779
- await this.seedIndexForDevice(core, input.deviceId);
1780
- this.ctx.logger.info("recorder attachCamera", {
1781
- tags: { deviceId: input.deviceId },
1782
- meta: { profiles, segmentSeconds }
1783
- });
1784
- return { success: true };
1785
- }
1786
- /**
1787
- * Set the GLOBAL recording placement (profile/track → location ids). Persists
1788
- * to the addon store (so it survives restarts) and rebuilds `this.placement`
1789
- * + clears the per-profile location cache so the next attach re-resolves. The
1790
- * admin UI (and the live-verification path) call this.
1791
- */
1792
- async setPlacement(input) {
1793
- const assignments = {};
1794
- for (const [key, ids] of Object.entries(input.assignments ?? {})) assignments[key] = [...ids];
1795
- await this.placementState?.set({ assignments });
1796
- this.placement = { assignments: input.assignments ?? {} };
1797
- this.profileWriteLocation.clear();
1798
- this.ctx.logger.info("recorder placement updated", { meta: { assignments: input.assignments } });
1799
- return { success: true };
1800
- }
1801
- async detachCamera(input) {
1802
- await this.clearTarget(input.deviceId);
1803
- this.stopWatchers(input.deviceId);
1804
- await this.core?.detach(input.deviceId);
1805
- await this.rescanPlayback();
1806
- this.ctx.logger.info("recorder detachCamera", { tags: { deviceId: input.deviceId } });
1807
- return { success: true };
1808
- }
1809
- // ── Boot-time index seeding (sized scan per device) ──────────────────────
1810
- /**
1811
- * Scan every recordings location for this device's sub-tree (with sizes) and
1812
- * seed the live RAM index so `storageBytes` and size-retention reflect ALL
1813
- * on-disk footage, not just segments finalized since the last attach. Scoping
1814
- * the scan to `<root>/<deviceId>/` keeps it cheap on large volumes.
1815
- *
1816
- * Must be called after `core.attach(deviceId, …)` so the seed lands in the
1817
- * camera's live index (not a stale pre-attach sentinel). Best-effort: any
1818
- * per-location failure is warned and skipped.
1819
- */
1820
- async seedIndexForDevice(core, deviceId) {
1821
- let locations;
1822
- try {
1823
- locations = await this.listRecordingsLocations();
1824
- } catch (err) {
1825
- this.ctx.logger.warn("recorder seedIndex: could not list locations", {
1826
- tags: { deviceId },
1827
- meta: { error: errMsg(err) }
1828
- });
1829
- return;
1830
- }
1831
- const roots = [...locations];
1832
- const segments = [];
1833
- for (const loc of roots) {
1834
- const deviceRoot = path__default.join(loc.root, String(deviceId));
1835
- try {
1836
- const entries = await scanRecordings(deviceRoot, { locationId: loc.id, withSizes: true });
1837
- for (const e of entries) {
1838
- const fullRelPath = `${deviceId}/${e.relPath}`;
1839
- const parsed = parseSegmentRelPath(fullRelPath);
1840
- if (!parsed) continue;
1841
- segments.push({
1842
- profile: parsed.profile,
1843
- startMs: parsed.startMs,
1844
- durMs: parsed.durMs,
1845
- bytes: e.bytes,
1846
- locationId: e.locationId,
1847
- subtree: parsed.subtree
1848
- });
1849
- }
1850
- } catch (err) {
1851
- this.ctx.logger.warn("recorder seedIndex: scan failed for location", {
1852
- tags: { deviceId },
1853
- meta: { locationId: loc.id, error: errMsg(err) }
1854
- });
1855
- }
1856
- }
1857
- if (segments.length === 0) return;
1858
- core.seedIndexFromScan(deviceId, segments);
1859
- this.ctx.logger.info("recorder seedIndex: seeded from disk scan", {
1860
- tags: { deviceId },
1861
- meta: { segmentCount: segments.length }
1862
- });
1863
- }
1864
- // ── Playback index (past recordings via disk scan) ──────────────────────
1865
- startPlaybackRescanTimer() {
1866
- const timer = setInterval(() => void this.rescanPlayback(), this.config.playbackRescanIntervalMs);
1867
- timer.unref?.();
1868
- this.playbackRescanTimer = timer;
1869
- }
1870
- /** Rebuild the playback index from a shallow disk scan of EVERY recordings
1871
- * storage location plus the read-only legacy root, stamping each segment with
1872
- * the location it came from. */
1873
- async rescanPlayback() {
1874
- const core = this.core;
1875
- if (!core) return;
1876
- try {
1877
- const locations = await this.listRecordingsLocations();
1878
- const scanRoots = [...locations];
1879
- const scanned = await Promise.all(scanRoots.map((l) => scanRecordings(l.root, { locationId: l.id })));
1880
- core.setPlaybackIndex(scanned.flat());
1881
- } catch (err) {
1882
- this.ctx.logger.warn("recorder playback rescan failed", { meta: { error: errMsg(err) } });
1883
- }
1884
- }
1885
- /** All recordings storage locations (every `recordings*` type) as
1886
- * `{ id, root }`, resolving (and caching) each root. Falls back to the
1887
- * single default root when the storage cap is unreachable. */
1888
- async listRecordingsLocations() {
1889
- try {
1890
- const locs = await this.ctx.api.storage.listLocations.query({});
1891
- const recordings = locs.filter((l) => l.type === "recordings" || l.type === "recordingsLow");
1892
- if (recordings.length > 0) {
1893
- return Promise.all(recordings.map(async (l) => ({ id: l.id, root: await this.resolveLocationRoot(l.id) })));
1894
- }
1895
- } catch (err) {
1896
- this.ctx.logger.warn("recorder: listLocations failed — scanning default root only", { meta: { error: errMsg(err) } });
1897
- }
1898
- return [{ id: this.recordingLocationId, root: this.dataDir }];
1899
- }
1900
- /**
1901
- * Resolve the recordings write root via the `storage` cap (the default
1902
- * `recordings` location). Falls back to the addon-local data dir with no
1903
- * locationId when the storage cap is unreachable at boot, so recording still
1904
- * works degraded rather than not at all.
1905
- */
1906
- async resolveRecordingsLocation() {
1907
- try {
1908
- const def = await this.ctx.api.storage.getDefaultLocation.query({ type: "recordings" });
1909
- if (def) {
1910
- const root = await this.ctx.api.storage.resolve.query({ location: def.id, relativePath: "" });
1911
- return { root, locationId: def.id };
1912
- }
1913
- this.ctx.logger.warn("recorder: no default recordings storage location — using addon data dir");
1914
- } catch (err) {
1915
- this.ctx.logger.warn("recorder: storage cap unreachable — using addon data dir", { meta: { error: errMsg(err) } });
1916
- }
1917
- return { root: path__default.join(this.ctx.dataDir, "recordings"), locationId: void 0 };
1918
- }
1919
- /** Distinct recordings roots the playback server searches: the default
1920
- * location root plus every location root we've resolved (write or scan). */
1921
- playbackRoots() {
1922
- return [.../* @__PURE__ */ new Set([this.dataDir, ...this.locationRootCache.values()])];
1923
- }
1924
- /** Absolute root of a storage location (cached `storage.resolve(id, '')`). */
1925
- async resolveLocationRoot(locationId) {
1926
- const cached = this.locationRootCache.get(locationId);
1927
- if (cached) return cached;
1928
- const root = await this.ctx.api.storage.resolve.query({ location: locationId, relativePath: "" });
1929
- this.locationRootCache.set(locationId, root);
1930
- return root;
1931
- }
1932
- /** A location's absolute root, or the default recordings root when the id is
1933
- * absent (legacy) or unresolvable. */
1934
- async locationRootOrDefault(locationId) {
1935
- if (!locationId) return this.dataDir;
1936
- try {
1937
- return await this.resolveLocationRoot(locationId);
1938
- } catch {
1939
- return this.dataDir;
1940
- }
1941
- }
1942
- /** Free bytes available on a location's volume (`statfs`); null on failure. */
1943
- async locationFreeBytes(locationId) {
1944
- try {
1945
- const st = await promises.statfs(await this.resolveLocationRoot(locationId));
1946
- return st.bavail * st.bsize;
1947
- } catch {
1948
- return null;
1949
- }
1950
- }
1951
- /**
1952
- * The GLOBAL write location for a profile/track — camera-independent, so all
1953
- * cameras record that profile to the SAME location. The placement-assigned
1954
- * location(s) are chosen by free space (least-full wins) ONCE and cached.
1955
- * Returns `null` when the profile is UNASSIGNED — there is no fallback; the
1956
- * caller must fail the recording explicitly. (Free-space-driven switching
1957
- * when a disk fills is part of the deferred multi-location structure rework.)
1958
- */
1959
- async resolveGlobalProfileLocation(profile) {
1960
- const cached = this.profileWriteLocation.get(profile);
1961
- if (cached) return cached;
1962
- const ids = resolveAssignedLocations(this.placement, profile);
1963
- if (ids.length === 0) return null;
1964
- const free = await Promise.all(
1965
- ids.map(async (id) => ({ locationId: id, availableBytes: await this.locationFreeBytes(id) }))
1966
- );
1967
- const chosen = chooseWriteLocation(ids, free);
1968
- if (chosen === null) return null;
1969
- const choice = { locationId: chosen, root: await this.resolveLocationRoot(chosen) };
1970
- this.profileWriteLocation.set(profile, choice);
1971
- return choice;
1972
- }
1973
- /**
1974
- * Resolve where each profile's segments are written for this camera: the
1975
- * global per-profile location's root + `<deviceId>/<profile>`. THROWS a clear
1976
- * error when any profile has no assigned storage location — recording must
1977
- * fail explicitly rather than write somewhere unintended.
1978
- */
1979
- async resolveProfilePlacements(deviceId, profiles) {
1980
- const out = /* @__PURE__ */ new Map();
1981
- const unassigned = [];
1982
- for (const profile of profiles) {
1983
- const choice = await this.resolveGlobalProfileLocation(profile);
1984
- if (choice === null) {
1985
- unassigned.push(profile);
1986
- continue;
1987
- }
1988
- out.set(profile, { outDir: path__default.join(choice.root, String(deviceId), profile), locationId: choice.locationId });
1989
- }
1990
- if (unassigned.length > 0) {
1991
- throw new Error(
1992
- `recorder: no storage location assigned for profile(s) [${unassigned.join(", ")}] — assign one in recording settings before enabling recording`
1993
- );
1994
- }
1995
- return out;
1996
- }
1997
- // ── Per-device settings (device-details recording widget) ─────────────
1998
- /** Build the device-details recording contribution: the widget section only. */
1999
- async buildDeviceSettingsContribution() {
2000
- if (!this.ctxIfReady?.settings) return null;
2001
- return hydrateSchema(buildRecordingDeviceSchema(), {});
2002
- }
2003
- // ── Durable enable (persisted recording targets) ───────────────────────
2004
- /** Best-effort persist of one camera's recording intent. */
2005
- async persistTarget(input) {
2006
- const settings = this.ctx.settings;
2007
- if (!settings) return;
2008
- try {
2009
- await upsertRecordingTarget(settings, input.deviceId, {
2010
- enabled: true,
2011
- profiles: input.profiles ? [...input.profiles] : void 0,
2012
- segmentSeconds: input.segmentSeconds,
2013
- rules: input.rules ? [...input.rules] : void 0,
2014
- retention: input.retention
2015
- });
2016
- } catch (err) {
2017
- this.ctx.logger.warn("recorder persist target failed", {
2018
- meta: { deviceId: input.deviceId, error: errMsg(err) }
2019
- });
2020
- }
2021
- }
2022
- /** Best-effort removal of one camera's persisted recording intent. */
2023
- async clearTarget(deviceId) {
2024
- const settings = this.ctx.settings;
2025
- if (!settings) return;
2026
- try {
2027
- await removeRecordingTarget(settings, deviceId);
2028
- } catch (err) {
2029
- this.ctx.logger.warn("recorder clear target failed", { meta: { deviceId, error: errMsg(err) } });
2030
- }
2031
- }
2032
- /**
2033
- * Re-attach every persisted enabled camera once the hub is reachable
2034
- * (`ctx.api.*` is safe here, not in `onInitialize`). Per-device failures —
2035
- * a camera that's offline at boot — are logged and kept (they resume on the
2036
- * next attach), never aborting the rest of the restore.
2037
- */
2038
- async onHubReachable() {
2039
- const settings = this.ctx.settings;
2040
- if (!settings) return;
2041
- const targets = await readRecordingTargets(settings);
2042
- const enabled = [...targets].filter(([, t]) => t.enabled);
2043
- if (enabled.length === 0) return;
2044
- try {
2045
- await this.ctx.acquireCapability("stream-broker", { type: "node", nodeId: this.nodeId }, { timeoutMs: 6e4 });
2046
- } catch (err) {
2047
- this.ctx.logger.warn("recorder restore: stream-broker not ready in time, attempting anyway", {
2048
- meta: { error: errMsg(err) }
2049
- });
2050
- }
2051
- this.ctx.logger.info("recorder restoring recording targets", { meta: { count: enabled.length } });
2052
- for (const [deviceId, target] of enabled) {
2053
- this.deviceTargets.set(deviceId, target);
2054
- try {
2055
- await this.attachCamera({ deviceId, profiles: target.profiles, segmentSeconds: target.segmentSeconds, rules: target.rules, retention: target.retention });
2056
- } catch (err) {
2057
- this.ctx.logger.warn("recorder restore attach failed", {
2058
- tags: { deviceId },
2059
- meta: { error: errMsg(err) }
2060
- });
2061
- }
2062
- }
2063
- }
2064
- stopWatchers(deviceId) {
2065
- const prefix = `${deviceId}/`;
2066
- for (const [key, handle] of [...this.watchers]) {
2067
- if (!key.startsWith(prefix)) continue;
2068
- handle.stop();
2069
- this.watchers.delete(key);
2070
- }
2071
- }
2072
- // ── Source resolution (broker single-dial) ─────────────────────────────
2073
- /**
2074
- * Pick which profiles to record for a device. The recorder enumerates the
2075
- * broker's ASSIGNED profile slots, deduped by physical source
2076
- * (`selectAssignedProfileSlots`) so the same camera encoder is never recorded
2077
- * twice. An operator `override` (the per-device "Profiles" multiselect)
2078
- * DISABLES the unselected profiles: the result is the assigned set INTERSECTED
2079
- * with the selection. Per the spec, recording keeps a MINIMUM OF 1 — if the
2080
- * selection matches none of the assigned sources (stale pick / wrong camera),
2081
- * it's ignored and every assigned profile is recorded. Empty/absent override =
2082
- * record every assigned source.
2083
- */
2084
- async resolveRecordingProfiles(deviceId, override) {
2085
- const api = this.ctx.api;
2086
- if (!api) throw new Error(`RecorderAddon.resolveRecordingProfiles: ctx.api unavailable (device ${deviceId})`);
2087
- const slots = await api.streamBroker.listAllProfileSlots.query();
2088
- const assigned = selectAssignedProfileSlots(slots, deviceId).map((slot) => slot.profile);
2089
- if (!override || override.length === 0) return assigned;
2090
- const selected = assigned.filter((p) => override.includes(p));
2091
- return selected.length > 0 ? selected : assigned;
2092
- }
2093
- /**
2094
- * Acquire a demand-counted broker stream for one (deviceId, profile) via
2095
- * `getStreamWithCodec` (passthrough — `video:'copy'`). The returned
2096
- * `pipelineKey` is released on detach, so the recorder rides the broker's
2097
- * single source dial instead of opening a second camera connection.
2098
- */
2099
- async acquireSource(deviceId, profile) {
2100
- const api = this.ctx.api;
2101
- if (!api) throw new Error(`RecorderAddon.acquireSource: ctx.api unavailable (device ${deviceId})`);
2102
- const source = await api.streamBroker.getStreamWithCodec.mutate({
2103
- deviceId,
2104
- video: "copy",
2105
- audio: "aac",
2106
- profile,
2107
- tag: `recorder:${deviceId}/${profile}`
2108
- });
2109
- return { url: source.url, pipelineKey: source.pipelineKey };
2110
- }
2111
- async releaseSource(pipelineKey) {
2112
- const api = this.ctx.api;
2113
- if (!api) return;
2114
- try {
2115
- await api.streamBroker.releaseStreamWithCodec.mutate({ pipelineKey });
2116
- } catch (err) {
2117
- this.ctx.logger.warn("releaseStreamWithCodec failed", {
2118
- meta: { pipelineKey, error: errMsg(err) }
2119
- });
2120
- }
2121
- }
2122
- // ── Playback manifest ─────────────────────────────────────────────────
2123
- /**
2124
- * Build a master + per-profile variant playlist on disk for the
2125
- * requested window and return the local master path. Returns
2126
- * `localMasterPath: null` when the camera has no recorded segments in
2127
- * the range.
2128
- */
2129
- /**
2130
- * Probe a profile's video codec + resolution for the master playlist, reading
2131
- * only the head of one segment (the `moov` sits at the start) and caching per
2132
- * (device, profile) — the camera's encoding is stable. Returns null on any
2133
- * read/parse failure (the variant then ships without CODECS, as before).
2134
- */
2135
- async probeProfileCodec(deviceId, profile, segAbsPath) {
2136
- const key = `${deviceId}/${profile}`;
2137
- const cached = this.profileCodecCache.get(key);
2138
- if (cached) return cached;
2139
- try {
2140
- const fh = await promises.open(segAbsPath, "r");
2141
- try {
2142
- const buf = Buffer.alloc(65536);
2143
- const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
2144
- const info = extractVideoCodecInfo(buf.subarray(0, bytesRead));
2145
- if (!info) return null;
2146
- const result = { codecs: info.codec, resolution: { width: info.width, height: info.height } };
2147
- this.profileCodecCache.set(key, result);
2148
- return result;
2149
- } finally {
2150
- await fh.close();
2151
- }
2152
- } catch {
2153
- return null;
2154
- }
2155
- }
2156
- async buildPlaybackManifest(deviceId, fromMs, toMs) {
2157
- const core = this.core;
2158
- if (!core) return { deviceId, localMasterPath: null, playbackUrl: null, playbackEndpoints: [] };
2159
- const profiles = core.getProfiles(deviceId);
2160
- const deviceDir = path__default.join(this.dataDir, String(deviceId));
2161
- const variants = [];
2162
- for (const profile of profiles) {
2163
- const segments = core.listSegments(deviceId, profile, fromMs, toMs);
2164
- if (segments.length === 0) continue;
2165
- const variantSegments = [];
2166
- let firstSegAbs = null;
2167
- for (const s of segments) {
2168
- const rel = segmentRelPath(String(deviceId), profile, s.subtree, s.startMs, s.durMs);
2169
- const segRoot = await this.locationRootOrDefault(s.locationId);
2170
- const segAbs = path__default.join(segRoot, rel);
2171
- try {
2172
- await promises.stat(segAbs);
2173
- } catch {
2174
- continue;
2175
- }
2176
- if (firstSegAbs === null) firstSegAbs = segAbs;
2177
- variantSegments.push({ uri: rel.split("/").slice(1).join("/"), startMs: s.startMs, durMs: s.durMs });
2178
- }
2179
- if (variantSegments.length === 0) continue;
2180
- const variantBody = buildVariantPlaylist(variantSegments);
2181
- const variantPath = path__default.join(deviceDir, `${profile}.m3u8`);
2182
- await promises.mkdir(deviceDir, { recursive: true });
2183
- await promises.writeFile(variantPath, variantBody, "utf8");
2184
- const codec = firstSegAbs ? await this.probeProfileCodec(deviceId, profile, firstSegAbs) : null;
2185
- variants.push({
2186
- profile,
2187
- bandwidth: PROFILE_BANDWIDTH[profile] ?? DEFAULT_BANDWIDTH,
2188
- uri: `${profile}.m3u8`,
2189
- ...codec ? { codecs: codec.codecs, resolution: codec.resolution } : {}
2190
- });
2191
- }
2192
- if (variants.length === 0) return { deviceId, localMasterPath: null, playbackUrl: null, playbackEndpoints: [] };
2193
- const masterPath = path__default.join(deviceDir, "master.m3u8");
2194
- await promises.mkdir(deviceDir, { recursive: true });
2195
- await promises.writeFile(masterPath, buildMasterPlaylist(variants), "utf8");
2196
- const playbackUrl = `/addon/recorder/playback/${deviceId}/master.m3u8?from=${fromMs}&to=${toMs}`;
2197
- return { deviceId, localMasterPath: masterPath, playbackUrl, playbackEndpoints: [playbackUrl] };
2198
- }
2199
- }
2200
- function localClock(ms) {
2201
- const d = new Date(ms);
2202
- return { weekday: d.getDay(), minutesOfDay: d.getHours() * 60 + d.getMinutes() };
2203
- }
2204
- export {
2205
- RecorderCore,
2206
- recorderActions as customActions,
2207
- RecorderAddon as default
1824
+ /** Playback-marker window padding around a motion event (EventMap only; the
1825
+ * controller's events-band gating uses the raw trigger ms, not this pad). */
1826
+ var MARKER_PAD_PRE_MS = 2e3;
1827
+ var MARKER_PAD_POST_MS = 5e3;
1828
+ /** This addon's manifest id + the playback data-plane prefix — together they
1829
+ * form the hub reverse-proxy client path `/addon/recorder/playback`. */
1830
+ var RECORDER_ADDON_ID = "recorder";
1831
+ var PLAYBACK_PREFIX = "playback";
1832
+ /** Default designated recording node (`recordingNodeId` global setting). The
1833
+ * stream-broker is hub-only and recording is a single-node global function, so
1834
+ * the hub is the safe default mirrors pipeline-analytics' post-processing
1835
+ * node gate. */
1836
+ var RECORDING_NODE_DEFAULT = "hub";
1837
+ /** Node the hub-only `stream-broker` runs on. Every recorderon the hub or on
1838
+ * a designated agent gates on, and pulls from, THIS node's broker. */
1839
+ var BROKER_HOST_NODE_ID = "hub";
1840
+ var RecorderV2Addon = class extends BaseAddon {
1841
+ nodeId = "hub";
1842
+ /** True when THIS node is the designated recording node (`recordingNodeId`).
1843
+ * Every other node stays fully inert — registers no providers, serves no
1844
+ * playback, runs no controller. Resolved in `onInitialize`. */
1845
+ isRecordingNode = true;
1846
+ index = new RecordingIndex();
1847
+ segmentStore = null;
1848
+ /** Continuous + events band write-path controller (ffmpeg writers + watchers). */
1849
+ controller = null;
1850
+ /** Per-device motion/audio markers for playback (B3 events feed the controller). */
1851
+ eventMap = new EventMap();
1852
+ /** Unsubscribe handle for the EventCapture motion subscription. */
1853
+ eventUnsub = null;
1854
+ /** Resolved recordings locations (id + root). Refreshed on boot + rescan. */
1855
+ resolvedLocations = [];
1856
+ /** Base URL of the playback HTTP data-plane, null until served in onHubReachable. */
1857
+ playbackBaseUrl = null;
1858
+ constructor() {
1859
+ super({ ...DEFAULT_CONFIG });
1860
+ }
1861
+ async onInitialize() {
1862
+ const raw = this.ctx.kernel.localNodeId ?? this.ctx.id;
1863
+ this.nodeId = raw.includes("/") ? raw.split("/")[0] : raw;
1864
+ const store = await this.ctx.settings?.readAddonStore() ?? {};
1865
+ const rawNode = store["recordingNodeId"];
1866
+ const designated = typeof rawNode === "string" && rawNode.length > 0 ? rawNode : RECORDING_NODE_DEFAULT;
1867
+ this.isRecordingNode = this.nodeId === designated;
1868
+ if (!this.isRecordingNode) {
1869
+ this.ctx.logger.info("recorder INERT on this node recording assigned elsewhere", { meta: {
1870
+ ownNodeId: this.nodeId,
1871
+ designatedNode: designated
1872
+ } });
1873
+ return { providers: [] };
1874
+ }
1875
+ const rawHubHostname = store["recordingHubHostname"];
1876
+ const consumerHostname = this.nodeId === BROKER_HOST_NODE_ID ? void 0 : resolveRecordingHubHostname(typeof rawHubHostname === "string" ? rawHubHostname : void 0, process.env["CAMSTACK_HUB_URL"]);
1877
+ if (this.nodeId !== BROKER_HOST_NODE_ID) {
1878
+ this.ctx.logger.info("recorder is a REMOTE recording node — pulling broker streams cross-node", { meta: {
1879
+ ownNodeId: this.nodeId,
1880
+ brokerHost: BROKER_HOST_NODE_ID,
1881
+ consumerHostname: consumerHostname ?? "(unresolved)"
1882
+ } });
1883
+ if (consumerHostname === void 0) this.ctx.logger.warn("recorder: could not resolve the hub host for cross-node pull — set the `recordingHubHostname` global setting or CAMSTACK_HUB_URL; recording will not reach this node", { meta: { ownNodeId: this.nodeId } });
1884
+ }
1885
+ const segmentStoreDeps = {
1886
+ index: this.index,
1887
+ list: (input) => this.ctx.api.storage.list.query(input),
1888
+ deletePath: (input) => this.ctx.api.storage.delete.mutate(input),
1889
+ statBytes: async (absPath) => (await promises.stat(absPath)).size,
1890
+ moveFile: async (fromAbs, toAbs) => {
1891
+ await promises.mkdir(path.dirname(toAbs), { recursive: true });
1892
+ await promises.rename(fromAbs, toAbs);
1893
+ },
1894
+ logger: { warn: (message, extras) => this.ctx.logger.warn(message, { meta: { extras } }) }
1895
+ };
1896
+ this.segmentStore = new SegmentStore(segmentStoreDeps);
1897
+ const tmpRoot = path.join(this.ctx.dataDir, "rec-tmp");
1898
+ const brokerHandle = this.ctx.useCapability("stream-broker", brokerScope(BROKER_HOST_NODE_ID));
1899
+ this.controller = new RecordingController({
1900
+ api: this.ctx.api,
1901
+ logger: this.ctx.logger,
1902
+ nodeId: this.nodeId,
1903
+ segmentStore: this.segmentStore,
1904
+ loadConfig: (deviceId) => loadDeviceConfig(this.configStore(), deviceId),
1905
+ enabledDeviceIds: async () => [...(await readDeviceConfigs(this.configStore())).keys()],
1906
+ locations: () => this.resolvedLocations,
1907
+ tmpRoot,
1908
+ spawn,
1909
+ segmentSeconds: this.config.segmentSeconds,
1910
+ watchIntervalMs: this.config.watchIntervalMs,
1911
+ ...consumerHostname !== void 0 ? { consumerHostname } : {},
1912
+ onBrokerReady: (handler) => this.ctx.onCapabilityStateChange("stream-broker", brokerScope(BROKER_HOST_NODE_ID), (state) => {
1913
+ if (state === "ready") handler();
1914
+ }),
1915
+ brokerCall: makeBrokerCall(brokerHandle)
1916
+ });
1917
+ const recordingProvider = buildRecordingProvider({
1918
+ index: this.index,
1919
+ segmentStore: this.segmentStore,
1920
+ nodeId: this.nodeId,
1921
+ logger: this.ctx.logger,
1922
+ configStore: this.configStore(),
1923
+ locations: () => this.resolvedLocations,
1924
+ refreshLocations: () => this.refreshLocations(),
1925
+ capacity: (root) => this.locationCapacity(root),
1926
+ hydrateDevice: (deviceId, locations) => hydrateDeviceFromStorage(this.ctx.api, this.index, deviceId, locations, this.ctx.logger),
1927
+ onConfigChanged: (deviceId) => this.controller?.onConfigChanged(deviceId) ?? Promise.resolve(),
1928
+ dataDir: this.ctx.dataDir,
1929
+ playbackBaseUrl: () => this.playbackBaseUrl
1930
+ });
1931
+ const evictableProvider = new StorageEvictableProvider({
1932
+ index: this.index,
1933
+ store: this.segmentStore
1934
+ });
1935
+ try {
1936
+ const handler = createFileDataPlaneHandler({ getRoots: () => this.playbackRoots() });
1937
+ const served = await this.ctx.dataPlane?.serve({
1938
+ prefix: PLAYBACK_PREFIX,
1939
+ access: "authenticated",
1940
+ handler
1941
+ });
1942
+ this.playbackBaseUrl = served ? `/addon/${RECORDER_ADDON_ID}/${PLAYBACK_PREFIX}` : null;
1943
+ this.ctx.logger.info("recorder playback data-plane served", { meta: {
1944
+ clientBase: this.playbackBaseUrl ?? "(no dataPlane facility)",
1945
+ internal: served?.baseUrl
1946
+ } });
1947
+ } catch (err) {
1948
+ this.ctx.logger.warn("recorder playback data-plane failed to serve", { meta: { error: errMsg(err) } });
1949
+ }
1950
+ this.ctx.logger.info("recorder addon started (continuous write path active)", {
1951
+ tags: { nodeId: this.nodeId },
1952
+ meta: {
1953
+ segmentSeconds: this.config.segmentSeconds,
1954
+ watchIntervalMs: this.config.watchIntervalMs
1955
+ }
1956
+ });
1957
+ return { providers: [{
1958
+ capability: recordingCapability,
1959
+ provider: recordingProvider
1960
+ }, {
1961
+ capability: storageEvictableCapability,
1962
+ provider: evictableProvider
1963
+ }] };
1964
+ }
1965
+ async onShutdown() {
1966
+ this.eventUnsub?.();
1967
+ this.eventUnsub = null;
1968
+ await this.controller?.stop();
1969
+ this.controller = null;
1970
+ this.segmentStore = null;
1971
+ }
1972
+ /**
1973
+ * Boot hydrate: once the hub is reachable (`ctx.api.*` safe), resolve the
1974
+ * recordings locations and rebuild the in-memory index from `storage.list`
1975
+ * for every device that has a persisted config. The list result is the
1976
+ * ground truth — segment paths encode start/dur/bytes, so the index can never
1977
+ * drift from disk.
1978
+ */
1979
+ async onHubReachable() {
1980
+ if (!this.isRecordingNode) return;
1981
+ this.resolvedLocations = await resolveRecordingsLocations(this.ctx.api, this.ctx.logger);
1982
+ if (this.resolvedLocations.length === 0) {
1983
+ this.ctx.logger.warn("recorder: no recordings storage locations resolved — index not hydrated");
1984
+ return;
1985
+ }
1986
+ let configs;
1987
+ try {
1988
+ configs = await readDeviceConfigs(this.configStore());
1989
+ } catch (err) {
1990
+ this.ctx.logger.warn("recorder: reading persisted device configs failed — skipping hydrate", { meta: { error: errMsg(err) } });
1991
+ return;
1992
+ }
1993
+ for (const deviceId of configs.keys()) await hydrateDeviceFromStorage(this.ctx.api, this.index, deviceId, this.resolvedLocations, this.ctx.logger);
1994
+ this.ctx.logger.info("recorder: hydrated index from storage", { meta: {
1995
+ deviceCount: configs.size,
1996
+ locationCount: this.resolvedLocations.length
1997
+ } });
1998
+ const store = this.segmentStore;
1999
+ if (store) try {
2000
+ await runRedundancyJanitor({
2001
+ deviceIds: [...configs.keys()],
2002
+ segmentsFor: (deviceId, profile) => this.index.segments(deviceId, profile),
2003
+ evict: (location, rows) => store.evict(location, rows),
2004
+ logger: this.ctx.logger
2005
+ });
2006
+ } catch (err) {
2007
+ this.ctx.logger.warn("recorder: redundancy janitor failed", { meta: { error: errMsg(err) } });
2008
+ }
2009
+ try {
2010
+ await this.controller?.start();
2011
+ } catch (err) {
2012
+ this.ctx.logger.warn("recorder: controller start failed", { meta: { error: errMsg(err) } });
2013
+ }
2014
+ if (this.eventUnsub === null) this.eventUnsub = subscribeEventCapture({
2015
+ eventBus: this.ctx.eventBus,
2016
+ map: this.eventMap,
2017
+ padPreMs: MARKER_PAD_PRE_MS,
2018
+ padPostMs: MARKER_PAD_POST_MS,
2019
+ onMotion: (deviceId, atMs) => {
2020
+ this.controller?.onTrigger(deviceId, "motion", atMs);
2021
+ }
2022
+ });
2023
+ }
2024
+ /** Re-resolve recordings locations (rescanStorage picks up newly-added disks). */
2025
+ async refreshLocations() {
2026
+ this.resolvedLocations = await resolveRecordingsLocations(this.ctx.api, this.ctx.logger);
2027
+ return this.resolvedLocations;
2028
+ }
2029
+ /**
2030
+ * Roots the playback data-plane handler searches, IN ORDER: `<dataDir>/playback`
2031
+ * FIRST (the freshly-written master/variant `.m3u8` playlists), then every
2032
+ * recordings location root (the segment `.m4s` files at
2033
+ * `<root>/<deviceId>/<profile>/Y/M/D/H/<file>`). Playlists-first matters: the
2034
+ * OLD recorder left stale `<recordingsRoot>/<deviceId>/master.m3u8` playlists
2035
+ * that would otherwise shadow ours; segments never collide (only `.m4s` live in
2036
+ * the location roots, only `.m3u8` in the playback dir), so the two form one
2037
+ * served tree with our playlists authoritative.
2038
+ */
2039
+ playbackRoots() {
2040
+ return [path.join(this.ctx.dataDir, "playback"), ...this.resolvedLocations.map((l) => l.root)];
2041
+ }
2042
+ /** Free + total bytes on a location's volume (`statfs`); null when unstattable. */
2043
+ async locationCapacity(root) {
2044
+ try {
2045
+ const st = await promises.statfs(root);
2046
+ return {
2047
+ availableBytes: st.bavail * st.bsize,
2048
+ totalBytes: st.blocks * st.bsize
2049
+ };
2050
+ } catch {
2051
+ return {
2052
+ availableBytes: null,
2053
+ totalBytes: null
2054
+ };
2055
+ }
2056
+ }
2057
+ /**
2058
+ * Global settings surfaced in the admin UI (and persisted to the addon
2059
+ * store). The cluster Recording tab drives `recordingNodeId` via a node
2060
+ * picker; `recordingHubHostname` is an advanced override for cross-node
2061
+ * pulls. Both take effect on addon restart (read once in `onInitialize`).
2062
+ */
2063
+ globalSettingsSchema() {
2064
+ return this.schema({ sections: [{
2065
+ id: "cluster-recording",
2066
+ title: "Cluster recording",
2067
+ description: "Which node runs recording (continuous + events write path). A SINGLE node — no multi-node balancing; every other node stays fully inert. Default: hub.",
2068
+ columns: 1,
2069
+ fields: [{
2070
+ type: "text",
2071
+ key: "recordingNodeId",
2072
+ label: "Recording node",
2073
+ description: "Node id that records + serves playback (e.g. \"hub\"). Leave \"hub\" unless you intentionally move recording to an agent. Takes effect on addon restart.",
2074
+ default: RECORDING_NODE_DEFAULT
2075
+ }, {
2076
+ type: "text",
2077
+ key: "recordingHubHostname",
2078
+ label: "Hub host (cross-node)",
2079
+ description: "Advanced: only used when the recording node is an AGENT. The hub's host the agent dials to pull broker streams (the RTSP restream port must be reachable there). Leave empty to auto-derive from the agent's hub connection.",
2080
+ default: ""
2081
+ }]
2082
+ }] });
2083
+ }
2084
+ /** The addon-store slice config-store reads/writes the deviceId→config blob on. */
2085
+ configStore() {
2086
+ const settings = this.ctx.settings;
2087
+ if (!settings) throw new Error("RecorderV2Addon: ctx.settings unavailable — cannot persist recording config");
2088
+ return {
2089
+ readAddonStore: () => settings.readAddonStore(),
2090
+ writeAddonStore: (patch) => settings.writeAddonStore(patch)
2091
+ };
2092
+ }
2208
2093
  };
2209
- //# sourceMappingURL=index.mjs.map
2094
+ //#endregion
2095
+ export { RecorderV2Addon as default };