@camstack/addon-pipeline 0.1.19 → 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 (96) hide show
  1. package/dist/audio-analyzer/index.js +736 -716
  2. package/dist/audio-analyzer/index.mjs +726 -676
  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-D_cl0Qqb.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 +2035 -1836
  20. package/dist/pipeline-runner/index.mjs +2031 -1820
  21. package/dist/recorder/index.js +2097 -0
  22. package/dist/recorder/index.mjs +2095 -0
  23. package/dist/stream-broker/_stub.js +1818 -734
  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 +17837 -12904
  33. package/dist/stream-broker/index.mjs +17826 -12896
  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 +75 -9
  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-BbPPvoCx.js +0 -14682
  52. package/dist/index-BbPPvoCx.js.map +0 -1
  53. package/dist/index-Bmlkm0Fd.mjs +0 -14683
  54. package/dist/index-Bmlkm0Fd.mjs.map +0 -1
  55. package/dist/index-D_cl0Qqb.js.map +0 -1
  56. package/dist/index-UbcdLS7a.mjs +0 -5790
  57. package/dist/index-UbcdLS7a.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/stream-broker/@mf-types/compiled-types/stream-broker/widgets/StreamBrokerPanel.d.ts +0 -21
  63. package/dist/stream-broker/@mf-types/compiled-types/stream-broker/widgets/index.d.ts +0 -13
  64. package/dist/stream-broker/@mf-types/widgets.d.ts +0 -2
  65. package/dist/stream-broker/@mf-types.d.ts +0 -3
  66. package/dist/stream-broker/@mf-types.zip +0 -0
  67. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_sdk__loadShare__.mjs-h5aXOPSA.mjs +0 -12
  68. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.mjs-NjF4kxzW.mjs +0 -19
  69. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.mjs-BAv_5ISf.mjs +0 -20
  70. 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
  71. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DeouEaSs.mjs +0 -85
  72. 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
  73. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react__loadShare__.mjs-BsB2G7oY.mjs +0 -88
  74. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react__loadShare__.mjs_commonjs-proxy-xrRiPUpA.mjs +0 -29
  75. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-gBEZsQrp.mjs +0 -36
  76. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom__loadShare__.mjs-DYEKzzY-.mjs +0 -45
  77. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-C0E2yCzO.mjs +0 -6
  78. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-DICOtMTl.mjs +0 -34
  79. package/dist/stream-broker/_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-CupRlwqG.mjs +0 -156
  80. package/dist/stream-broker/client-NPZqorv9.mjs +0 -9836
  81. package/dist/stream-broker/getErrorShape-BPSzUA7W-TlK8ipWe.mjs +0 -211
  82. package/dist/stream-broker/hostInit-Bh4w7o5_.mjs +0 -168
  83. package/dist/stream-broker/index-2Qp8vT3w.mjs +0 -185
  84. package/dist/stream-broker/index-BBcZvb5t.mjs +0 -435
  85. package/dist/stream-broker/index-CIJue-4t.mjs +0 -37880
  86. package/dist/stream-broker/index-CWkKuNLr.mjs +0 -232
  87. package/dist/stream-broker/index-Cc6QBqMk.mjs +0 -1655
  88. package/dist/stream-broker/index-D_1p2K9B.mjs +0 -2603
  89. package/dist/stream-broker/index-Dy2V7VOm.mjs +0 -14379
  90. package/dist/stream-broker/index-mX3Kgiv1.mjs +0 -725
  91. package/dist/stream-broker/index-xncRG7-x.mjs +0 -2713
  92. package/dist/stream-broker/index.js.map +0 -1
  93. package/dist/stream-broker/index.mjs.map +0 -1
  94. package/dist/stream-broker/jsx-runtime-lb0mH5st.mjs +0 -55
  95. package/dist/stream-broker/schemas-ClCuS4qa.mjs +0 -3594
  96. package/dist/stream-broker/virtualExposes-pCd777Rp.mjs +0 -42
@@ -0,0 +1,2095 @@
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";
4
+ import { createFileDataPlaneHandler } from "@camstack/core";
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`;
12
+ }
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
+ };
24
+ }
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;
50
+ }
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;
302
+ }
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;
322
+ }
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;
388
+ }
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
+ };
422
+ }
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
+ };
459
+ }
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
+ });
471
+ }
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;
487
+ }
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);
498
+ }
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";
519
+ }
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";
532
+ }
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
+ }] };
549
+ }
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
+ });
584
+ }
585
+ function serialize(map) {
586
+ const out = {};
587
+ for (const [id, config] of map) out[String(id)] = config;
588
+ return out;
589
+ }
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;
599
+ }
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;
616
+ }
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;
628
+ }
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";
639
+ }
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
654
+ };
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
+ };
671
+ }
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));
675
+ }
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
+ };
731
+ }
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
+ };
742
+ }
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;
752
+ }
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
+ ];
990
+ }
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
+ */
1102
+ function parseEpochStartMs(segPath) {
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;
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
+ */
1119
+ function correctedDurMs(durSeconds, startMs, nextStartMs) {
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);
1125
+ }
1126
+ /** Parse a `live.m3u8` body into ordered `#EXTINF` → segment-path pairs. */
1127
+ function parseLivePlaylist(body) {
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;
1150
+ }
1151
+ /** `fs.stat` size, or null when the path does not exist. */
1152
+ async function statSize(p) {
1153
+ try {
1154
+ return (await promises.stat(p)).size;
1155
+ } catch {
1156
+ return null;
1157
+ }
1158
+ }
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";
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
+ */
1193
+ function planFinalizations(body, processed) {
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
+ };
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
+ */
1220
+ function startSegmentWatcher(deps) {
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
+ } };
1275
+ }
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);
1345
+ }
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);
1356
+ }
1357
+ function activeBandAt(config, date) {
1358
+ return config.bands.find((b) => bandActiveAt(b, date)) ?? null;
1359
+ }
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;
1373
+ }
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());
1387
+ }
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;
1401
+ }
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
+ };
1744
+ }
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);
1750
+ }
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);
1778
+ }
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;
1794
+ }
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
1823
+ };
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 recorder — on 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
+ }
2093
+ };
2094
+ //#endregion
2095
+ export { RecorderV2Addon as default };