@camstack/addon-export-hap 1.2.14 → 1.2.16

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.
@@ -6536,7 +6536,20 @@ var BrokerStatsSchema = object({
6536
6536
  sampleRate: number(),
6537
6537
  channels: number(),
6538
6538
  supported: boolean()
6539
- }).nullable().optional()
6539
+ }).nullable().optional(),
6540
+ /**
6541
+ * BROKER-SIDE AUDIO MUTE (D83). `true` = this broker is deliberately
6542
+ * distributing none of the device's audio, on live or recording.
6543
+ *
6544
+ * Present so a silent camera can be told apart from a broken one on the
6545
+ * stream panel itself, without cross-referencing the switch group: a
6546
+ * broker holding an `audio` track descriptor while `audioMuted` is true is
6547
+ * working exactly as asked. `audioMutedDropped` counts the audio units
6548
+ * thrown away since the current dial — it is how you confirm from stats
6549
+ * alone that the mute is on the packet path and not merely persisted.
6550
+ */
6551
+ audioMuted: boolean().optional(),
6552
+ audioMutedDropped: number().optional()
6540
6553
  });
6541
6554
  /**
6542
6555
  * Exporter-facing "profile restream" entry. Returned by
@@ -7067,104 +7080,7 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7067
7080
  input: unknown()
7068
7081
  }), unknown(), { kind: "mutation" }), method(object({ deviceId: number() }), _void(), { kind: "mutation" }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7069
7082
  //#endregion
7070
- //#region ../types/dist/canonical-hash-7nfBbEqR.mjs
7071
- /**
7072
- * Deterministic SHA-256 hash of an arbitrary serialisable value. The
7073
- * canonical form sorts object keys alphabetically at every depth so two
7074
- * structurally-equal inputs with different key insertion orders produce
7075
- * the same hash. Returns a 64-char lowercase hex digest.
7076
- *
7077
- * Used by export adapters (Alexa, HAP) to short-circuit re-discovery /
7078
- * accessory-rebuild work when the upstream shape is byte-identical to
7079
- * the last applied state — preventing user-visible "re-discovery"
7080
- * notifications on every addon-runner respawn. Each respawn re-fires
7081
- * `DeviceBindingsChanged` for every cap registration, which without
7082
- * this guard would propagate redundant pushes.
7083
- *
7084
- * Note: this is a SYMPTOMATIC fix layered on top of the binding-change
7085
- * subscription. The proper fix is a single "device ready" lifecycle
7086
- * barrier so exports react only when the full cap set has landed —
7087
- * tracked separately for post-HA-integration work.
7088
- */
7089
- function canonicalHash(value) {
7090
- const canonical = JSON.stringify(value, replaceWithSortedKeys);
7091
- return (0, node_crypto.createHash)("sha256").update(canonical ?? "").digest("hex");
7092
- }
7093
- function replaceWithSortedKeys(_key, value) {
7094
- if (value && typeof value === "object" && !Array.isArray(value)) {
7095
- const obj = value;
7096
- const out = {};
7097
- for (const k of Object.keys(obj).toSorted()) out[k] = obj[k];
7098
- return out;
7099
- }
7100
- return value;
7101
- }
7102
- var EncodeProfileSchema = object({
7103
- video: object({
7104
- codec: _enum([
7105
- "h264",
7106
- "h265",
7107
- "copy"
7108
- ]),
7109
- profile: _enum([
7110
- "baseline",
7111
- "main",
7112
- "high"
7113
- ]).optional(),
7114
- /**
7115
- * `-level`, e.g. `'3.1'`. A consumer that ADVERTISES a level in its SDP
7116
- * (`profile-level-id=42e01f` is Baseline 3.1) must constrain the encoder to
7117
- * it, or it ships a stream that does not match its own advertisement — the
7118
- * defect class that kept HomeKit black for a year and that Alexa carried
7119
- * silently. Optional because a browser negotiates the level itself.
7120
- */
7121
- level: string().optional(),
7122
- width: number().int().positive().optional(),
7123
- height: number().int().positive().optional(),
7124
- fps: number().positive().optional(),
7125
- bitrateKbps: number().int().positive().optional(),
7126
- gopFrames: number().int().positive().optional(),
7127
- bf: number().int().min(0).optional(),
7128
- preset: _enum([
7129
- "ultrafast",
7130
- "superfast",
7131
- "veryfast",
7132
- "faster",
7133
- "fast",
7134
- "medium"
7135
- ]).optional(),
7136
- tune: _enum([
7137
- "zerolatency",
7138
- "film",
7139
- "animation"
7140
- ]).optional()
7141
- }),
7142
- audio: union([literal("passthrough"), object({
7143
- codec: _enum([
7144
- "opus",
7145
- "aac",
7146
- "pcmu",
7147
- "pcma",
7148
- "copy"
7149
- ]),
7150
- bitrateKbps: number().int().positive().optional(),
7151
- sampleRateHz: number().int().positive().optional(),
7152
- channels: union([literal(1), literal(2)]).optional()
7153
- })]),
7154
- /**
7155
- * ffmpeg input-side args, inserted between the fixed global flags
7156
- * (`-hide_banner -loglevel error`) and `-i pipe:0`. Free-text array
7157
- * — the widget surfaces a textarea + suggestion chips for the most-
7158
- * used demuxer/format options.
7159
- */
7160
- inputArgs: array(string()).optional(),
7161
- /**
7162
- * ffmpeg output-side args, inserted between the encode block and
7163
- * the final `-f <muxer> pipe:1`. Use for muxer options, bitstream
7164
- * filters, codec-specific overrides. Free-text array.
7165
- */
7166
- outputArgs: array(string()).optional()
7167
- });
7083
+ //#region ../types/dist/fmp4-box-splitter-B53u9-Nu.mjs
7168
7084
  var AUDIO_ENCODER_BY_CODEC = {
7169
7085
  opus: "libopus",
7170
7086
  aac: "aac",
@@ -7345,13 +7261,42 @@ function buildStdoutOrRtspSinkArgs(sink) {
7345
7261
  "pipe:1"
7346
7262
  ];
7347
7263
  }
7264
+ /**
7265
+ * How far BELOW the negotiated fragment length `-min_frag_duration` is set.
7266
+ *
7267
+ * `-min_frag_duration` refuses to cut before that much media has accumulated,
7268
+ * and then waits for the next key frame. Set to exactly `fragmentMs`, the
7269
+ * commonest camera configuration in existence — a key-frame grid EQUAL to the
7270
+ * requested fragment length — lands the deadline on the same instant as the key
7271
+ * frame, loses the race, and skips to the following one: **every fragment comes
7272
+ * out at twice the requested length.**
7273
+ *
7274
+ * Measured on the live fleet 2026-08-07, camera 615, `-c:v copy` (D84):
7275
+ *
7276
+ * | slot | GOP | `-min_frag_duration` | median gap |
7277
+ * | --- | --- | --- | --- |
7278
+ * | 1280×720 | 40 f @ 10 fps = 4.0 s | 4000 ms | **7944 ms** |
7279
+ * | 1280×720 | 40 f @ 10 fps = 4.0 s | 3600 ms | 3973 ms |
7280
+ * | 3840×2160 | 100 f @ 25 fps = 4.0 s | 4000 ms | 8042 ms |
7281
+ * | 3840×2160 | 100 f @ 25 fps = 4.0 s | 3600 ms | 3998 ms |
7282
+ *
7283
+ * A doubled fragment is not a cosmetic overshoot: HKSV requires every fragment
7284
+ * to be no longer than the length the controller SELECTED, so the shipped-but-
7285
+ * inert phase-1 sink would have violated the contract on its first real clip.
7286
+ *
7287
+ * 10 % is chosen against the two failures either side of it. Too small and
7288
+ * ordinary jitter (measured spread 3953-4096 ms) re-loses the race; too large
7289
+ * and a source with a key frame slightly EARLY than the grid gets cut there,
7290
+ * yielding a short fragment for no reason.
7291
+ */
7292
+ var FMP4_MIN_FRAG_MARGIN = .9;
7348
7293
  /** `-movflags … -min_frag_duration <us> -f mp4 pipe:1`. */
7349
7294
  function buildFmp4SinkArgs(sink) {
7350
7295
  return [
7351
7296
  "-movflags",
7352
7297
  FMP4_MOVFLAGS,
7353
7298
  "-min_frag_duration",
7354
- String(Math.max(0, Math.round(sink.fragmentMs * 1e3))),
7299
+ String(Math.max(0, Math.round(sink.fragmentMs * FMP4_MIN_FRAG_MARGIN * 1e3))),
7355
7300
  "-f",
7356
7301
  "mp4",
7357
7302
  "pipe:1"
@@ -7430,6 +7375,287 @@ function buildFfmpegArgs(inv) {
7430
7375
  ];
7431
7376
  }
7432
7377
  /**
7378
+ * Deterministic SHA-256 hash of an arbitrary serialisable value. The
7379
+ * canonical form sorts object keys alphabetically at every depth so two
7380
+ * structurally-equal inputs with different key insertion orders produce
7381
+ * the same hash. Returns a 64-char lowercase hex digest.
7382
+ *
7383
+ * Used by export adapters (Alexa, HAP) to short-circuit re-discovery /
7384
+ * accessory-rebuild work when the upstream shape is byte-identical to
7385
+ * the last applied state — preventing user-visible "re-discovery"
7386
+ * notifications on every addon-runner respawn. Each respawn re-fires
7387
+ * `DeviceBindingsChanged` for every cap registration, which without
7388
+ * this guard would propagate redundant pushes.
7389
+ *
7390
+ * Note: this is a SYMPTOMATIC fix layered on top of the binding-change
7391
+ * subscription. The proper fix is a single "device ready" lifecycle
7392
+ * barrier so exports react only when the full cap set has landed —
7393
+ * tracked separately for post-HA-integration work.
7394
+ */
7395
+ function canonicalHash(value) {
7396
+ const canonical = JSON.stringify(value, replaceWithSortedKeys);
7397
+ return (0, node_crypto.createHash)("sha256").update(canonical ?? "").digest("hex");
7398
+ }
7399
+ function replaceWithSortedKeys(_key, value) {
7400
+ if (value && typeof value === "object" && !Array.isArray(value)) {
7401
+ const obj = value;
7402
+ const out = {};
7403
+ for (const k of Object.keys(obj).toSorted()) out[k] = obj[k];
7404
+ return out;
7405
+ }
7406
+ return value;
7407
+ }
7408
+ var DEFAULT_MAX_UNIT_BYTES = 16 * 1024 * 1024;
7409
+ /** Header size for a normal box, and for one carrying a 64-bit `largesize`. */
7410
+ var BOX_HEADER_BYTES = 8;
7411
+ var LARGE_BOX_HEADER_BYTES = 16;
7412
+ var Fmp4BoxSplitter = class {
7413
+ maxUnitBytes;
7414
+ /** Bytes of the CURRENT unit plus any partial box after it. */
7415
+ buffer = new Uint8Array(0);
7416
+ /** Where the current unit starts inside {@link buffer}. */
7417
+ unitStart = 0;
7418
+ /** Where the box scanner has reached inside {@link buffer}. */
7419
+ cursor = 0;
7420
+ state = "init";
7421
+ nextSequence = 0;
7422
+ faultReason = null;
7423
+ interstitial = /* @__PURE__ */ new Set();
7424
+ constructor(options = {}) {
7425
+ this.maxUnitBytes = options.maxUnitBytes ?? DEFAULT_MAX_UNIT_BYTES;
7426
+ }
7427
+ /**
7428
+ * Non-null once the stream cannot be split. The splitter emits nothing
7429
+ * further, so a caller polls this to kill the child rather than watching a
7430
+ * silent stall — a fragmenter that quietly stops producing looks exactly like
7431
+ * a camera with no motion.
7432
+ */
7433
+ get fault() {
7434
+ return this.faultReason;
7435
+ }
7436
+ /** Bytes currently held. The memory bound, observable rather than asserted. */
7437
+ get pendingBytes() {
7438
+ return this.buffer.length - this.unitStart;
7439
+ }
7440
+ /**
7441
+ * Top-level box types seen BETWEEN fragments and discarded — `mfra`, `free`,
7442
+ * a stray `sidx`. Reported rather than dropped in silence: they are legal and
7443
+ * useless to a fragment consumer, but a type nobody expected showing up here
7444
+ * is the first symptom of a muxer that is not writing what we think it is.
7445
+ */
7446
+ get discardedInterstitialTypes() {
7447
+ return [...this.interstitial];
7448
+ }
7449
+ /**
7450
+ * Feed bytes; get back whatever units completed. Returns `[]` once faulted.
7451
+ */
7452
+ push(chunk) {
7453
+ if (this.faultReason !== null || chunk.length === 0) return [];
7454
+ this.append(chunk);
7455
+ if (this.pendingBytes > this.maxUnitBytes) return this.fail(`a single fMP4 unit exceeded ${this.maxUnitBytes} bytes — this stream is not fragmented`);
7456
+ return this.drainBoxes();
7457
+ }
7458
+ append(chunk) {
7459
+ if (this.buffer.length === 0) {
7460
+ this.buffer = chunk.slice();
7461
+ return;
7462
+ }
7463
+ const next = new Uint8Array(this.buffer.length + chunk.length);
7464
+ next.set(this.buffer, 0);
7465
+ next.set(chunk, this.buffer.length);
7466
+ this.buffer = next;
7467
+ }
7468
+ /** Consume every COMPLETE top-level box now in the buffer. */
7469
+ drainBoxes() {
7470
+ const units = [];
7471
+ for (;;) {
7472
+ const header = this.readHeader();
7473
+ if (this.faultReason !== null) return units;
7474
+ if (header === null) break;
7475
+ if (this.cursor + header.totalBytes > this.buffer.length) break;
7476
+ const boxStart = this.cursor;
7477
+ const boxEnd = boxStart + header.totalBytes;
7478
+ this.cursor = boxEnd;
7479
+ const unit = this.consumeBox(header.type, boxStart, boxEnd);
7480
+ if (this.faultReason !== null) return units;
7481
+ if (unit !== null) units.push(unit);
7482
+ }
7483
+ this.compact();
7484
+ return units;
7485
+ }
7486
+ /**
7487
+ * Apply one box to the state machine. Returns a unit when this box CLOSED
7488
+ * one, `null` otherwise.
7489
+ */
7490
+ consumeBox(type, boxStart, boxEnd) {
7491
+ if (this.state === "init") {
7492
+ if (type !== "moof") return null;
7493
+ if (boxStart === this.unitStart) {
7494
+ this.fail("a moof arrived before any initialisation box — there is no ftyp/moov to send");
7495
+ return null;
7496
+ }
7497
+ const init = this.emit("init", this.unitStart, boxStart);
7498
+ this.unitStart = boxStart;
7499
+ this.state = "fragment";
7500
+ return init;
7501
+ }
7502
+ if (this.state === "idle") {
7503
+ if (type !== "moof") {
7504
+ this.interstitial.add(type);
7505
+ this.unitStart = boxEnd;
7506
+ return null;
7507
+ }
7508
+ this.unitStart = boxStart;
7509
+ this.state = "fragment";
7510
+ return null;
7511
+ }
7512
+ if (type !== "mdat") return null;
7513
+ const fragment = this.emit("fragment", this.unitStart, boxEnd);
7514
+ this.unitStart = boxEnd;
7515
+ this.state = "idle";
7516
+ return fragment;
7517
+ }
7518
+ /**
7519
+ * Parse the header at {@link cursor}, or `null` when too few bytes have
7520
+ * arrived to know. Faults on a size the splitter cannot honour.
7521
+ */
7522
+ readHeader() {
7523
+ const available = this.buffer.length - this.cursor;
7524
+ if (available < BOX_HEADER_BYTES) return null;
7525
+ const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);
7526
+ const size = view.getUint32(this.cursor);
7527
+ const type = String.fromCharCode(this.buffer[this.cursor + 4] ?? 0, this.buffer[this.cursor + 5] ?? 0, this.buffer[this.cursor + 6] ?? 0, this.buffer[this.cursor + 7] ?? 0);
7528
+ if (size === 0) {
7529
+ this.fail(`box "${type}" declares size 0 (to EOF) — an unbounded box cannot be fragmented`);
7530
+ return null;
7531
+ }
7532
+ if (size === 1) {
7533
+ if (available < LARGE_BOX_HEADER_BYTES) return null;
7534
+ const large = view.getBigUint64(this.cursor + BOX_HEADER_BYTES);
7535
+ if (large > BigInt(this.maxUnitBytes)) {
7536
+ this.fail(`box "${type}" declares ${large} bytes, over the ${this.maxUnitBytes} byte bound`);
7537
+ return null;
7538
+ }
7539
+ return {
7540
+ type,
7541
+ totalBytes: Number(large)
7542
+ };
7543
+ }
7544
+ if (size < BOX_HEADER_BYTES) {
7545
+ this.fail(`box "${type}" declares an impossible size of ${size} bytes`);
7546
+ return null;
7547
+ }
7548
+ return {
7549
+ type,
7550
+ totalBytes: size
7551
+ };
7552
+ }
7553
+ emit(kind, start, end) {
7554
+ const sequence = this.nextSequence;
7555
+ this.nextSequence += 1;
7556
+ return {
7557
+ kind,
7558
+ data: this.buffer.slice(start, end),
7559
+ sequence
7560
+ };
7561
+ }
7562
+ /**
7563
+ * Drop everything already emitted or discarded. Without this the buffer is
7564
+ * the whole stream and the process dies in hours, not minutes.
7565
+ */
7566
+ compact() {
7567
+ if (this.unitStart === 0) return;
7568
+ this.buffer = this.buffer.slice(this.unitStart);
7569
+ this.cursor -= this.unitStart;
7570
+ this.unitStart = 0;
7571
+ }
7572
+ fail(reason) {
7573
+ this.faultReason = reason;
7574
+ this.buffer = new Uint8Array(0);
7575
+ this.unitStart = 0;
7576
+ this.cursor = 0;
7577
+ return [];
7578
+ }
7579
+ };
7580
+ //#endregion
7581
+ //#region ../types/dist/err-msg-IQTHeDzc.mjs
7582
+ /**
7583
+ import { errMsg } from '@camstack/types'
7584
+ * Extract a human-readable message from an unknown error value.
7585
+ * Replaces the ubiquitous `errMsg(err)` pattern.
7586
+ */
7587
+ function errMsg$12(err) {
7588
+ if (err instanceof Error) return err.message;
7589
+ if (typeof err === "string") return err;
7590
+ return String(err);
7591
+ }
7592
+ var EncodeProfileSchema = object({
7593
+ video: object({
7594
+ codec: _enum([
7595
+ "h264",
7596
+ "h265",
7597
+ "copy"
7598
+ ]),
7599
+ profile: _enum([
7600
+ "baseline",
7601
+ "main",
7602
+ "high"
7603
+ ]).optional(),
7604
+ /**
7605
+ * `-level`, e.g. `'3.1'`. A consumer that ADVERTISES a level in its SDP
7606
+ * (`profile-level-id=42e01f` is Baseline 3.1) must constrain the encoder to
7607
+ * it, or it ships a stream that does not match its own advertisement — the
7608
+ * defect class that kept HomeKit black for a year and that Alexa carried
7609
+ * silently. Optional because a browser negotiates the level itself.
7610
+ */
7611
+ level: string().optional(),
7612
+ width: number().int().positive().optional(),
7613
+ height: number().int().positive().optional(),
7614
+ fps: number().positive().optional(),
7615
+ bitrateKbps: number().int().positive().optional(),
7616
+ gopFrames: number().int().positive().optional(),
7617
+ bf: number().int().min(0).optional(),
7618
+ preset: _enum([
7619
+ "ultrafast",
7620
+ "superfast",
7621
+ "veryfast",
7622
+ "faster",
7623
+ "fast",
7624
+ "medium"
7625
+ ]).optional(),
7626
+ tune: _enum([
7627
+ "zerolatency",
7628
+ "film",
7629
+ "animation"
7630
+ ]).optional()
7631
+ }),
7632
+ audio: union([literal("passthrough"), object({
7633
+ codec: _enum([
7634
+ "opus",
7635
+ "aac",
7636
+ "pcmu",
7637
+ "pcma",
7638
+ "copy"
7639
+ ]),
7640
+ bitrateKbps: number().int().positive().optional(),
7641
+ sampleRateHz: number().int().positive().optional(),
7642
+ channels: union([literal(1), literal(2)]).optional()
7643
+ })]),
7644
+ /**
7645
+ * ffmpeg input-side args, inserted between the fixed global flags
7646
+ * (`-hide_banner -loglevel error`) and `-i pipe:0`. Free-text array
7647
+ * — the widget surfaces a textarea + suggestion chips for the most-
7648
+ * used demuxer/format options.
7649
+ */
7650
+ inputArgs: array(string()).optional(),
7651
+ /**
7652
+ * ffmpeg output-side args, inserted between the encode block and
7653
+ * the final `-f <muxer> pipe:1`. Use for muxer options, bitstream
7654
+ * filters, codec-specific overrides. Free-text array.
7655
+ */
7656
+ outputArgs: array(string()).optional()
7657
+ });
7658
+ /**
7433
7659
  * The shape every live egress starts from: H.264 Baseline 3.1 at 720p25.
7434
7660
  * Baseline because it is the one profile every consumer in this repo decodes
7435
7661
  * (Echo, iOS, an old browser); 3.1 because that is what the SDPs advertise.
@@ -7549,6 +7775,19 @@ object({
7549
7775
  * | `notifications` | `notificationRules.setDeviceMuted` | `NotificationCenter.evaluateAndEnqueue` returns before any rule is evaluated |
7550
7776
  * | `privacy-mask` | `privacyMask.setMask({ enabled })` → the CAMERA | the camera blanks the masked regions itself; every stream and recording carries the black boxes |
7551
7777
  * | `device-audio` | `privacyMask.setAudioEnabled` → the CAMERA | the camera stops encoding an audio track at all; every consumer sees silent video |
7778
+ * | `broker-audio` | `streamBroker.setDeviceAudioMute` → `DeviceOverride.audioMuted` | `StreamBroker.setAudioMuted` drops the audio plane at the source: no `type:'audio'` packet leaves `fanOutEncoded`, no RTP reaches the restreamer, and the restreamer serves the video-only SDP |
7779
+ *
7780
+ * ## `device-audio` and `broker-audio` are two functions, not two knobs
7781
+ *
7782
+ * They look adjacent and they are not the same control ([D83](../../../../docs/decisions/adr-0083.md)):
7783
+ * `device-audio` writes the CAMERA, so it is hardware privacy — the microphone
7784
+ * genuinely stops, it survives CamStack entirely, and it costs a multi-second
7785
+ * encoder restart on every flip. `broker-audio` writes THIS server, so it is
7786
+ * instant, vendor-independent and reversible without touching the camera, and
7787
+ * a camera that ignores or lacks the ISAPI/Reolink control is still silenced.
7788
+ * D62 forbids a second switch that *disagrees* with the first; these two
7789
+ * cannot disagree, because neither reads the other's store — the camera holds
7790
+ * one, the broker holds the other, and each reports its own fact.
7552
7791
  *
7553
7792
  * ## The two switches whose authority is not on this server
7554
7793
  *
@@ -7610,6 +7849,7 @@ var CameraSwitchIdSchema = _enum([
7610
7849
  "object-detection",
7611
7850
  "privacy-mask",
7612
7851
  "device-audio",
7852
+ "broker-audio",
7613
7853
  "audio-analysis",
7614
7854
  "recording",
7615
7855
  "notifications"
@@ -7635,7 +7875,8 @@ var CameraSwitchAuthoritySchema = discriminatedUnion("kind", [
7635
7875
  object({
7636
7876
  kind: literal("camera-mask"),
7637
7877
  capName: string()
7638
- })
7878
+ }),
7879
+ object({ kind: literal("broker-audio-mute") })
7639
7880
  ]);
7640
7881
  /**
7641
7882
  * Why a switch is not offered for this camera. Rendered instead of the
@@ -9886,7 +10127,25 @@ method(object({
9886
10127
  }), _void(), {
9887
10128
  kind: "mutation",
9888
10129
  auth: "admin"
9889
- }), method(object({ brokerId: string() }), boolean()), object({
10130
+ }), method(object({ brokerId: string() }), boolean()), method(object({ deviceId: number().int() }), object({
10131
+ muted: boolean(),
10132
+ /**
10133
+ * How many live non-derived brokers currently hold the mute. Purely
10134
+ * diagnostic: `muted` is the policy and is authoritative on its own
10135
+ * (it applies to brokers that do not exist yet), while this says
10136
+ * whether anything is presently being silenced.
10137
+ */
10138
+ appliedBrokers: number().int().nonnegative()
10139
+ })), method(object({
10140
+ deviceId: number().int(),
10141
+ muted: boolean()
10142
+ }), object({
10143
+ muted: boolean(),
10144
+ appliedBrokers: number().int().nonnegative()
10145
+ }), {
10146
+ kind: "mutation",
10147
+ auth: "admin"
10148
+ }), object({
9890
10149
  deviceId: number().int().nonnegative(),
9891
10150
  camStreamId: string(),
9892
10151
  profile: CamProfileSchema
@@ -15209,6 +15468,30 @@ var TrackSourceSchema = _enum([
15209
15468
  "audio"
15210
15469
  ]);
15211
15470
  /**
15471
+ * Where a track sits in the RETRAIN lifecycle (D81).
15472
+ *
15473
+ * - `none` — never marked, or un-marked. Evictable.
15474
+ * - `staging` — the operator wants this track as training material and has not
15475
+ * finished with it. **This is the only state retention holds**: the track and
15476
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
15477
+ * the device's age window.
15478
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
15479
+ * were COPIED into the retrain dataset at selection time, so the dataset no
15480
+ * longer depends on the track's media and the track becomes EVICTABLE again.
15481
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
15482
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
15483
+ *
15484
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
15485
+ * the store's filter language has only positive equality and `whereIn` — no
15486
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
15487
+ * would make the entire pre-column history immortal in one deploy.
15488
+ */
15489
+ var RetrainStatusSchema = _enum([
15490
+ "none",
15491
+ "staging",
15492
+ "trained"
15493
+ ]);
15494
+ /**
15212
15495
  * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
15213
15496
  * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
15214
15497
  * so the two surfaces cannot drift.
@@ -15218,18 +15501,31 @@ var TrackSourceSchema = _enum([
15218
15501
  * columns existed read as absent, and a consumer that needs a boolean should say
15219
15502
  * `flag === true`, not `flag !== false`.
15220
15503
  *
15221
- * What the flags DO is deliberately UNDEFINED at the time of writing: they are
15222
- * operator curation, and the behaviour they drive will be specified separately.
15223
- * In particular a `markForTrain` track is NOT pinned against retention — see
15224
- * `docs/decisions/adr-0059.md` for why that is a store-level change, not a flag.
15504
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
15505
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
15506
+ * `true` moves `none → staging`, writing `false` moves `staging none`, and a
15507
+ * `trained` track reports `false` while refusing both writes. The boolean is
15508
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
15509
+ * "never marked" from "already trained" must read `retrainStatus`.
15510
+ *
15511
+ * `debug` does NOT pin; it is attention, not durability.
15225
15512
  */
15226
15513
  var TrackFlagFields = {
15227
- /** Operator marked this track as training material. */
15514
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
15515
+ * `'staging'`. */
15228
15516
  markForTrain: boolean().optional(),
15229
15517
  /** Operator marked this track for diagnostic attention. */
15230
15518
  debug: boolean().optional()
15231
15519
  };
15232
15520
  /**
15521
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
15522
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
15523
+ * write patch, and the status is not something the toggle sets — it is what the
15524
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
15525
+ * always present on a persisted row (the column default materialises `'none'`).
15526
+ */
15527
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
15528
+ /**
15233
15529
  * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
15234
15530
  * one flag can never clear the other — the toggles are independent and are
15235
15531
  * driven from three surfaces that do not know about each other.
@@ -15243,13 +15539,92 @@ var TrackFlagsPatchSchema = object(TrackFlagFields);
15243
15539
  var TrackFlagsSchema = object({
15244
15540
  trackId: string(),
15245
15541
  markForTrain: boolean(),
15246
- debug: boolean()
15542
+ debug: boolean(),
15543
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
15544
+ * a track row) because this shape is only ever produced by the write body,
15545
+ * which always knows it — and a surface that has just written needs to render
15546
+ * `trained` without a re-fetch. */
15547
+ retrainStatus: RetrainStatusSchema
15548
+ });
15549
+ union([literal(1), literal(2)]);
15550
+ /**
15551
+ * WHO decided a label, and when. Carried per tier so a value can be traced to
15552
+ * the step and model that produced it — which is what makes the write rule
15553
+ * arguable after the fact ("why is 592's label `dog` and not `Canis lupus`?")
15554
+ * and what lets a migrated, UNATTRIBUTED value be told apart from a real one.
15555
+ *
15556
+ * `stepId` is the pipeline step id (`animal-classifier`, `bird-classifier`,
15557
+ * `plate-ocr`, `face-embedding`, `object-detection`), or the sentinel
15558
+ * `migration:4g` for a value the 4g migration moved from the single-slot era —
15559
+ * that value has no provenance, and the write rule lets ANY properly-attributed
15560
+ * write of the same tier replace it regardless of score.
15561
+ */
15562
+ var LabelAttributionSchema = object({
15563
+ stepId: string(),
15564
+ modelId: string().optional(),
15565
+ decidedAt: number()
15566
+ });
15567
+ /**
15568
+ * The TIERED label model (roadmap 4g), spread into `TrackSchema` and
15569
+ * `ObjectEventSchema` from ONE place so the two surfaces cannot drift — a
15570
+ * track and its events always answer the same question the same way.
15571
+ *
15572
+ * Two scalar columns, not an array: every consumer wants "the coarse one" or
15573
+ * "the fine one", and an array made both a scan. `label` is tier 1, `subLabel`
15574
+ * is tier 2, and each carries its own score + attribution.
15575
+ *
15576
+ * **Reading it.** What a human should be shown is `subLabel ?? label` — the
15577
+ * finest thing known. Before 4g the single `label` column held the finest
15578
+ * value, so a consumer that has not been updated reads the tier-1 slot and
15579
+ * shows nothing on a species-only row; that is why the migration puts every
15580
+ * pre-4g value in tier 2 (it cannot regress a display that reads the fallback)
15581
+ * and why the read surfaces were changed in the same train.
15582
+ *
15583
+ * **Writing it.** The slots are independent, which is the whole point: a
15584
+ * tier-1 write (`bird`) can never overwrite a tier-2 value (`Turdus
15585
+ * migratorius`), so fineness cannot regress by construction. Within a tier the
15586
+ * higher score wins. One rule, one implementation — see
15587
+ * `pipeline/label-tier.ts` in addon-post-analysis.
15588
+ */
15589
+ var TieredLabelFields = {
15590
+ /** Tier 1 — the sub-class. See {@link LabelTierSchema}. */
15591
+ label: string().optional(),
15592
+ /** Confidence of the tier-1 value, as reported by the deciding step. */
15593
+ labelScore: number().optional(),
15594
+ /** Provenance of the tier-1 value. See {@link LabelAttributionSchema}. */
15595
+ labelMeta: LabelAttributionSchema.optional(),
15596
+ /** Tier 2 — the instance. See {@link LabelTierSchema}. */
15597
+ subLabel: string().optional(),
15598
+ /** Confidence of the tier-2 value, as reported by the deciding step. */
15599
+ subLabelScore: number().optional(),
15600
+ /** Provenance of the tier-2 value. See {@link LabelAttributionSchema}. */
15601
+ subLabelMeta: LabelAttributionSchema.optional()
15602
+ };
15603
+ /** Per-camera slice of a training-export estimate. */
15604
+ var TrainingExportDeviceTotalsSchema = object({
15605
+ deviceId: number(),
15606
+ tracks: number().int(),
15607
+ files: number().int(),
15608
+ bytes: number().int()
15609
+ });
15610
+ /**
15611
+ * What a training export WOULD contain. Computed from media index rows only —
15612
+ * no blob is read to produce this.
15613
+ */
15614
+ var TrainingExportSummarySchema = object({
15615
+ generatedAt: number(),
15616
+ trackCount: number().int(),
15617
+ fileCount: number().int(),
15618
+ byteCount: number().int(),
15619
+ /** More marked tracks exist than a single pass carries. */
15620
+ truncated: boolean(),
15621
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
15247
15622
  });
15248
15623
  var TrackSchema = object({
15249
15624
  trackId: string(),
15250
15625
  deviceId: number(),
15251
15626
  className: string(),
15252
- label: string().optional(),
15627
+ ...TieredLabelFields,
15253
15628
  producingDeviceName: string().optional(),
15254
15629
  /** Track provenance. Absent ⇒ `pipeline` (legacy rows). */
15255
15630
  source: TrackSourceSchema.optional(),
@@ -15288,7 +15663,8 @@ var TrackSchema = object({
15288
15663
  * Populated from the persisted envelope columns on historical reads;
15289
15664
  * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
15290
15665
  envelope: TrackEnvelopeSchema.optional(),
15291
- ...TrackFlagFields
15666
+ ...TrackFlagFields,
15667
+ ...TrackRetrainFields
15292
15668
  });
15293
15669
  var BaseEventFields = {
15294
15670
  id: string(),
@@ -15361,7 +15737,7 @@ var ObjectEventSchema = object({
15361
15737
  /** Omitted in slim projection. */
15362
15738
  trackId: string().optional(),
15363
15739
  className: string(),
15364
- label: string().optional(),
15740
+ ...TieredLabelFields,
15365
15741
  /** Omitted in slim projection. */
15366
15742
  confidence: number().optional(),
15367
15743
  /** Heavy JSON — omitted in slim projection. */
@@ -15442,6 +15818,173 @@ var MediaFileSchema = object({
15442
15818
  * stored blob and a `?variant=thumb` rendering without fetching either.
15443
15819
  */
15444
15820
  var MediaFileInfoSchema = MediaFileSchema.omit({ base64: true });
15821
+ /**
15822
+ * The MACRO tier of an annotation — a CLOSED set.
15823
+ *
15824
+ * This is what the exported detector predicts, so a typo here is a new class
15825
+ * with one example in it. `label` and `subLabel` are open strings by contrast:
15826
+ * the whole point of the page is teaching the model things it does not know
15827
+ * yet, and constraining that vocabulary would make it useless.
15828
+ *
15829
+ * A macro class is NEVER a label. The provider refuses a write whose `label` or
15830
+ * `subLabel` is one of these values, in any casing, because once `person`
15831
+ * exists in both tiers "every person box" stops being answerable without
15832
+ * knowing every string anyone ever typed — and the damage is retroactive.
15833
+ */
15834
+ var RetrainMacroClassSchema = _enum([
15835
+ "person",
15836
+ "vehicle",
15837
+ "animal",
15838
+ "package",
15839
+ "face",
15840
+ "plate"
15841
+ ]);
15842
+ /** A subject to learn, or a phantom to unlearn (taught by OMISSION). */
15843
+ var RetrainAnnotationKindSchema = _enum(["subject", "model_error"]);
15844
+ /** Did a human draw this box, or did the assist propose it? */
15845
+ var RetrainAnnotationSourceSchema = _enum(["operator", "assist"]);
15846
+ /** Normalised `[0,1]` rectangle against the FULL frame — the canonical form. */
15847
+ var RetrainBboxSchema = object({
15848
+ x: number(),
15849
+ y: number(),
15850
+ w: number(),
15851
+ h: number()
15852
+ });
15853
+ /**
15854
+ * One annotated subject.
15855
+ *
15856
+ * `bbox` is normalised against the full frame, ALWAYS. The per-model shapes
15857
+ * (letterboxed root / zone-cropped package / subject-cropped classifier) are
15858
+ * derived from it at export and never stored — storing them is how one feature
15859
+ * space ends up holding two crops of the same subject (D52).
15860
+ */
15861
+ var RetrainAnnotationSchema = object({
15862
+ id: string(),
15863
+ trackId: string(),
15864
+ deviceId: number(),
15865
+ /** The COPY in retrain storage — never the source track's media key. */
15866
+ mediaKey: string(),
15867
+ bbox: RetrainBboxSchema,
15868
+ macroClass: RetrainMacroClassSchema,
15869
+ label: string().optional(),
15870
+ subLabel: string().optional(),
15871
+ kind: RetrainAnnotationKindSchema,
15872
+ source: RetrainAnnotationSourceSchema,
15873
+ /** Which model proposed this box — or, on a `model_error`, drew the phantom. */
15874
+ assistModelId: string().optional(),
15875
+ assistScore: number().optional(),
15876
+ exportedInBatch: string().optional(),
15877
+ createdAt: number()
15878
+ });
15879
+ /** The write form — the server owns `id`, `createdAt` and the frame binding. */
15880
+ var RetrainAnnotationDraftSchema = RetrainAnnotationSchema.omit({
15881
+ id: true,
15882
+ trackId: true,
15883
+ deviceId: true,
15884
+ mediaKey: true,
15885
+ createdAt: true,
15886
+ exportedInBatch: true
15887
+ });
15888
+ /** A track sitting in `staging`, with everything the worklist needs to rank it. */
15889
+ var RetrainTrackSchema = object({
15890
+ trackId: string(),
15891
+ deviceId: number(),
15892
+ className: string(),
15893
+ label: string().optional(),
15894
+ firstSeen: number(),
15895
+ lastSeen: number(),
15896
+ /** How many frames the dataset already holds from this track. */
15897
+ frameCount: number().int(),
15898
+ /** How many subjects have been annotated on those frames. `0` with
15899
+ * `frameCount: 0` is exactly "staging, still to work". */
15900
+ annotationCount: number().int()
15901
+ });
15902
+ /** A frame the picker may offer — an index row, no blob was read to produce it. */
15903
+ var RetrainFrameCandidateSchema = object({
15904
+ mediaKey: string(),
15905
+ kind: MediaFileKindEnum,
15906
+ timestamp: number(),
15907
+ sizeBytes: number().int(),
15908
+ /** A copy of this original already exists — selecting it is free and cannot
15909
+ * fail, whatever became of the original. */
15910
+ copied: boolean()
15911
+ });
15912
+ /** A frame the dataset OWNS: bytes copied at selection time. */
15913
+ var RetrainFrameSchema = object({
15914
+ frameId: string(),
15915
+ deviceId: number(),
15916
+ trackId: string(),
15917
+ /** Provenance only. It may already point at nothing — that is expected. */
15918
+ sourceMediaKey: string(),
15919
+ sourceKind: MediaFileKindEnum,
15920
+ sizeBytes: number().int(),
15921
+ width: number().int(),
15922
+ height: number().int(),
15923
+ copiedAt: number()
15924
+ });
15925
+ /** Why a copy-on-select could not be honoured — named, never a silent skip. */
15926
+ var RetrainCopyRefusalSchema = _enum([
15927
+ "source-missing",
15928
+ "unreadable-image",
15929
+ "write-failed"
15930
+ ]);
15931
+ var RetrainFrameSelectionSchema = object({
15932
+ copied: array(RetrainFrameSchema).readonly(),
15933
+ refused: array(object({
15934
+ sourceMediaKey: string(),
15935
+ reason: RetrainCopyRefusalSchema
15936
+ })).readonly()
15937
+ });
15938
+ var RetrainFrameListSchema = object({
15939
+ candidates: array(RetrainFrameCandidateSchema).readonly(),
15940
+ copies: array(RetrainFrameSchema).readonly(),
15941
+ /** What the page pre-selects — the native key frame when one survives. */
15942
+ autoPickMediaKey: string().optional()
15943
+ });
15944
+ /** What the operator asked the assist to look for. */
15945
+ var RetrainAssistSubjectSchema = discriminatedUnion("kind", [object({
15946
+ kind: literal("package"),
15947
+ zone: RetrainBboxSchema.optional()
15948
+ }), object({
15949
+ kind: literal("objects"),
15950
+ modelId: string(),
15951
+ minScore: number().optional()
15952
+ })]);
15953
+ /**
15954
+ * The assist's answer — a discriminated union, because "the model saw nothing"
15955
+ * and "this node cannot run that model" lead to different next moves and a
15956
+ * nullable result cannot tell them apart.
15957
+ */
15958
+ var RetrainAssistResultSchema = discriminatedUnion("kind", [object({
15959
+ kind: literal("proposed"),
15960
+ modelId: string(),
15961
+ stepId: string(),
15962
+ minScore: number(),
15963
+ /** Drafts, ready to edit. `source: 'assist'` until the operator touches one. */
15964
+ proposals: array(RetrainAnnotationDraftSchema).readonly(),
15965
+ /** Returned by the runner but removed by the threshold. */
15966
+ belowThreshold: number().int()
15967
+ }), object({
15968
+ kind: literal("refused"),
15969
+ /** `no-zone` is ours; the rest are the runner's own refusal vocabulary. */
15970
+ reason: string(),
15971
+ detail: string().optional()
15972
+ })]);
15973
+ /** The outcome of a lifecycle move owned by the retrain page. */
15974
+ var RetrainTransitionResultSchema = object({
15975
+ trackId: string(),
15976
+ /** Where the track ended up, whatever happened. */
15977
+ retrainStatus: RetrainStatusSchema,
15978
+ /** `false` ⇒ the move was refused or was a no-op; `reason` says which. */
15979
+ changed: boolean(),
15980
+ reason: _enum([
15981
+ "unknown-track",
15982
+ "no-frames-copied",
15983
+ "not-staging",
15984
+ "not-trained",
15985
+ "unchanged"
15986
+ ]).optional()
15987
+ });
15445
15988
  var DEFAULT_EVENT_QUERY_LIMIT = 1e3;
15446
15989
  var MAX_EVENT_QUERY_LIMIT = 5e3;
15447
15990
  var DeviceEventQueryInput = object({
@@ -15496,13 +16039,14 @@ var KeyEventSchema = object({
15496
16039
  /** Track start time (firstSeen). */
15497
16040
  timestamp: number(),
15498
16041
  className: string(),
15499
- label: string().optional(),
16042
+ ...TieredLabelFields,
15500
16043
  importance: number(),
15501
16044
  /** Highest-confidence ObjectEvent id for the track (empty when none). */
15502
16045
  bestEventId: string(),
15503
16046
  /** Track lifetime in ms (lastSeen - firstSeen). */
15504
16047
  windowMs: number().optional(),
15505
- ...TrackFlagFields
16048
+ ...TrackFlagFields,
16049
+ ...TrackRetrainFields
15506
16050
  });
15507
16051
  object({
15508
16052
  trackId: string(),
@@ -15763,6 +16307,85 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
15763
16307
  }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
15764
16308
  kind: "query",
15765
16309
  auth: "admin"
16310
+ }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
16311
+ kind: "query",
16312
+ auth: "admin"
16313
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
16314
+ kind: "query",
16315
+ auth: "admin"
16316
+ }), method(object({
16317
+ /** Empty ⇒ every camera that has staging tracks. A LIST, not a single
16318
+ * `deviceId`, deliberately: `deviceId` would make this device-bound and
16319
+ * route it at one camera's owner, and "every camera" would stop being
16320
+ * expressible at all. */
16321
+ deviceIds: array(number()).optional(),
16322
+ limit: number().int().min(1).max(500).optional()
16323
+ }), array(RetrainTrackSchema).readonly(), {
16324
+ kind: "query",
16325
+ auth: "admin"
16326
+ }), method(object({ trackId: string() }), RetrainFrameListSchema, {
16327
+ kind: "query",
16328
+ auth: "admin"
16329
+ }), method(object({
16330
+ deviceId: number(),
16331
+ trackId: string(),
16332
+ mediaKeys: array(string()).min(1)
16333
+ }), RetrainFrameSelectionSchema, {
16334
+ kind: "mutation",
16335
+ auth: "admin"
16336
+ }), method(object({
16337
+ deviceId: number(),
16338
+ trackId: string(),
16339
+ frameId: string()
16340
+ }), object({
16341
+ removed: boolean(),
16342
+ removedAnnotations: number().int()
16343
+ }), {
16344
+ kind: "mutation",
16345
+ auth: "admin"
16346
+ }), method(object({ frameId: string() }), object({
16347
+ base64: string(),
16348
+ width: number().int(),
16349
+ height: number().int()
16350
+ }), {
16351
+ kind: "query",
16352
+ auth: "admin"
16353
+ }), method(object({
16354
+ deviceId: number(),
16355
+ trackId: string(),
16356
+ frameId: string(),
16357
+ subject: RetrainAssistSubjectSchema,
16358
+ /** Which node runs it. Absent ⇒ wherever an unowned call lands. */
16359
+ nodeId: string().optional()
16360
+ }), RetrainAssistResultSchema, {
16361
+ kind: "mutation",
16362
+ auth: "admin"
16363
+ }), method(object({ trackId: string() }), array(RetrainAnnotationSchema).readonly(), {
16364
+ kind: "query",
16365
+ auth: "admin"
16366
+ }), method(object({
16367
+ deviceId: number(),
16368
+ trackId: string(),
16369
+ frameId: string(),
16370
+ annotations: array(RetrainAnnotationDraftSchema)
16371
+ }), array(RetrainAnnotationSchema).readonly(), {
16372
+ kind: "mutation",
16373
+ auth: "admin"
16374
+ }), method(object({
16375
+ deviceId: number(),
16376
+ trackId: string()
16377
+ }), RetrainTransitionResultSchema, {
16378
+ kind: "mutation",
16379
+ auth: "admin"
16380
+ }), method(object({
16381
+ deviceId: number(),
16382
+ trackId: string()
16383
+ }), RetrainTransitionResultSchema, {
16384
+ kind: "mutation",
16385
+ auth: "admin"
16386
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
16387
+ kind: "query",
16388
+ auth: "admin"
15766
16389
  }), method(object({
15767
16390
  eventId: string(),
15768
16391
  kind: MediaFileKindEnum.optional()
@@ -16342,6 +16965,22 @@ var DetailResultSchema = object({
16342
16965
  bbox: NativeCropBboxSchema.optional(),
16343
16966
  embedding: string().optional(),
16344
16967
  label: string().optional(),
16968
+ /**
16969
+ * The tier `label` occupies, copied VERBATIM from the producing step's
16970
+ * `StepDefinition.labelTier` (roadmap 4g). Present only when `label` is.
16971
+ *
16972
+ * It rides the wire rather than being resolved by the consumer because the
16973
+ * declaration lives with the step definition, which only the executing node
16974
+ * has: post-analysis holds no step registry, and re-deriving the tier from
16975
+ * `className` there would be exactly the inference this model exists to
16976
+ * forbid. A `label` that arrives WITHOUT this field is refused by the write
16977
+ * rule and logged (`label tier undeclared`) — an older runner therefore
16978
+ * stops enriching rather than guessing, which is why addon-pipeline is
16979
+ * deployed BEFORE addon-post-analysis.
16980
+ */
16981
+ labelTier: union([literal(1), literal(2)]).optional(),
16982
+ /** Model that produced `label` — carried into the tier's attribution. */
16983
+ labelModelId: string().optional(),
16345
16984
  alignedCropJpeg: string().optional(),
16346
16985
  /** Face short side (px) measured on the NATIVE crop surface. The `bbox`
16347
16986
  * above is detection-frame px (≈6× smaller on a 4K camera) — min-face-size
@@ -21423,6 +22062,173 @@ DeviceType.Camera, method(object({
21423
22062
  status: OsdStatusSchema
21424
22063
  });
21425
22064
  /**
22065
+ * `osd-manager` — the ORCHESTRATOR over the device-scope `osd` cap.
22066
+ *
22067
+ * The `osd` cap is the firmware contract: it probes a camera's overlay
22068
+ * SLOTS and writes literal text into one. It has no idea WHERE that text
22069
+ * comes from, and it must not — a driver that grew a "show the temperature
22070
+ * here" feature would grow it once per vendor.
22071
+ *
22072
+ * This cap owns the other half: a per-(camera, slot) BINDING that says
22073
+ * which value feeds the slot, how it is formatted, and under which
22074
+ * conditions it is shown at all. One addon renders every binding on every
22075
+ * camera, so a new source costs zero driver code.
22076
+ *
22077
+ * Three deliberate choices, each with a rejected alternative:
22078
+ *
22079
+ * 1. A source is `(capName, valuePath)` over the kernel's device
22080
+ * runtime-state mirror — NOT a closed enum of source kinds. Every
22081
+ * cap-keyed slice a device publishes is bindable the day the cap
22082
+ * ships. The rejected alternative (one enum member per source, with
22083
+ * a resolver branch each) is what makes "add the humidity too" a
22084
+ * code change.
22085
+ * 2. The display gate reuses `NcConditionsSchema` verbatim — the
22086
+ * notification centre's condition vocabulary — rather than a parallel
22087
+ * model. An operator who has learned one condition editor has learned
22088
+ * both.
22089
+ * 3. Because the renderer's facts are device STATE and not a detection
22090
+ * record, only a SUBSET of that vocabulary can be answered here.
22091
+ * `setSlotBinding` REJECTS the rest at write time (see
22092
+ * `getConditionSupport`). It does not accept-then-fail-closed: a
22093
+ * condition that can never be true renders a permanently blank
22094
+ * overlay, and a blank overlay looks exactly like a broken camera.
22095
+ */
22096
+ /** Where a slot's value comes from. */
22097
+ var OsdSourceSchema = discriminatedUnion("kind", [
22098
+ object({
22099
+ kind: literal("static"),
22100
+ text: string().max(64)
22101
+ }),
22102
+ object({
22103
+ kind: literal("clock"),
22104
+ /** Token pattern: `YYYY MM DD HH mm ss`. Everything else is literal. */
22105
+ pattern: string().min(1).max(32).default("HH:mm"),
22106
+ /** IANA zone. Omitted = the server's zone. */
22107
+ timezone: string().min(1).max(64).optional()
22108
+ }),
22109
+ object({
22110
+ kind: literal("device-state"),
22111
+ deviceId: number().int().optional(),
22112
+ capName: string().min(1).max(64),
22113
+ /** Dot path inside the slice, e.g. `detected`, `value`, `mode`. */
22114
+ valuePath: string().min(1).max(64)
22115
+ })
22116
+ ]);
22117
+ var OsdSlotBindingSchema = object({
22118
+ /** Off = the manager stops driving this slot. It does NOT clear it. */
22119
+ enabled: boolean().default(true),
22120
+ source: OsdSourceSchema,
22121
+ /** `${value}` and `${unit}` are substituted; every occurrence. */
22122
+ template: string().max(96).default("${value}"),
22123
+ /** Truncate with an ellipsis past this length. Absent = no limit. */
22124
+ maxCharacters: number().int().min(4).max(64).optional(),
22125
+ /**
22126
+ * Decimal places for a numeric value. `0` yields an integer — the
22127
+ * documented workaround for firmwares that reject `.` in overlay text.
22128
+ */
22129
+ maxDecimals: number().int().min(0).max(4).default(1),
22130
+ /** Appended via `${unit}`. The state mirror does not carry units. */
22131
+ unitLabel: string().max(8).optional(),
22132
+ /** Raw value → display text, e.g. `{"true":"MOTION","false":""}`. */
22133
+ valueMap: record(string(), string()).optional(),
22134
+ /** Time windows in which the slot is shown. Absent = always. */
22135
+ schedule: NcScheduleSchema.optional(),
22136
+ /**
22137
+ * Display gate, in the notification centre's condition vocabulary.
22138
+ * Only the keys reported by `getConditionSupport` are accepted.
22139
+ */
22140
+ conditions: NcConditionsSchema.optional(),
22141
+ /** Rendered when the gate is closed or the value unreadable. Empty = hide. */
22142
+ fallbackText: string().max(64).default("")
22143
+ });
22144
+ /** One camera slot, as the operator sees it: firmware truth + our binding. */
22145
+ var OsdSlotViewSchema = object({
22146
+ slotId: string(),
22147
+ kind: OsdOverlayKindEnum,
22148
+ /** Firmware refuses text edits (a timestamp, the channel name). */
22149
+ readOnly: boolean(),
22150
+ cameraEnabled: boolean(),
22151
+ cameraText: string().optional(),
22152
+ binding: OsdSlotBindingSchema.nullable()
22153
+ });
22154
+ /**
22155
+ * What happened to one slot on one render pass. `unchanged` exists so the
22156
+ * operator can tell "we are driving this and the value is steady" from
22157
+ * "we never got there" — and so the loop can prove it is not rewriting
22158
+ * identical text to the camera every tick.
22159
+ */
22160
+ var OsdRenderOutcomeEnum = _enum([
22161
+ "written",
22162
+ "unchanged",
22163
+ "gated",
22164
+ "unreadable",
22165
+ "disabled",
22166
+ "unbound",
22167
+ "failed"
22168
+ ]);
22169
+ var OsdRenderResultSchema = object({
22170
+ slotId: string(),
22171
+ outcome: OsdRenderOutcomeEnum,
22172
+ /** The text the slot should carry. Empty = the slot is switched off. */
22173
+ text: string(),
22174
+ /** Why, whenever the outcome is not a plain write. Never silent. */
22175
+ reason: string().optional()
22176
+ });
22177
+ var OsdSourceValueTypeEnum = _enum([
22178
+ "number",
22179
+ "boolean",
22180
+ "string",
22181
+ "enum"
22182
+ ]);
22183
+ /**
22184
+ * One bindable value, derived from a cap's `runtimeState` schema — never
22185
+ * hand-listed. The editor renders from this, so a cap that ships a new
22186
+ * state field becomes bindable with no UI change.
22187
+ */
22188
+ var OsdSourceOptionSchema = object({
22189
+ deviceId: number().int(),
22190
+ deviceName: string(),
22191
+ capName: string(),
22192
+ valuePath: string(),
22193
+ label: string(),
22194
+ valueType: OsdSourceValueTypeEnum,
22195
+ /** Present for `enum`; the editor offers these as `valueMap` keys. */
22196
+ enumValues: array(string()).readonly().optional()
22197
+ });
22198
+ method(object({ deviceId: number().int() }), object({
22199
+ supported: boolean(),
22200
+ slots: array(OsdSlotViewSchema)
22201
+ }), { auth: "admin" }), method(object({ deviceId: number().int() }), object({ sources: array(OsdSourceOptionSchema) }), { auth: "admin" }), method(object({}), object({
22202
+ supported: array(string()),
22203
+ catalog: array(NcConditionDescriptorSchema)
22204
+ }), { auth: "admin" }), method(object({
22205
+ deviceId: number().int(),
22206
+ slotId: string().min(1),
22207
+ binding: OsdSlotBindingSchema
22208
+ }), object({
22209
+ slot: OsdSlotViewSchema,
22210
+ render: OsdRenderResultSchema
22211
+ }), {
22212
+ kind: "mutation",
22213
+ auth: "admin"
22214
+ }), method(object({
22215
+ deviceId: number().int(),
22216
+ slotId: string().min(1)
22217
+ }), object({ success: literal(true) }), {
22218
+ kind: "mutation",
22219
+ auth: "admin"
22220
+ }), method(object({
22221
+ deviceId: number().int(),
22222
+ slotId: string().min(1),
22223
+ binding: OsdSlotBindingSchema.optional()
22224
+ }), OsdRenderResultSchema, {
22225
+ kind: "mutation",
22226
+ auth: "admin"
22227
+ }), method(object({ deviceId: number().int() }), object({ results: array(OsdRenderResultSchema) }), {
22228
+ kind: "mutation",
22229
+ auth: "admin"
22230
+ });
22231
+ /**
21426
22232
  * Feeder connectivity / power status — mirrors the HA petkit device-status
21427
22233
  * enum: `normal` (online, mains), `offline` (not reaching PetKit cloud),
21428
22234
  * `on_batteries` (running on battery backup). `null` until first reported.
@@ -26378,6 +27184,48 @@ Object.freeze({
26378
27184
  addonId: null,
26379
27185
  access: "create"
26380
27186
  },
27187
+ "osdManager.clearSlotBinding": {
27188
+ capName: "osd-manager",
27189
+ capScope: "system",
27190
+ addonId: null,
27191
+ access: "delete"
27192
+ },
27193
+ "osdManager.getConditionSupport": {
27194
+ capName: "osd-manager",
27195
+ capScope: "system",
27196
+ addonId: null,
27197
+ access: "view"
27198
+ },
27199
+ "osdManager.getDeviceOsd": {
27200
+ capName: "osd-manager",
27201
+ capScope: "system",
27202
+ addonId: null,
27203
+ access: "view"
27204
+ },
27205
+ "osdManager.getSourceCatalog": {
27206
+ capName: "osd-manager",
27207
+ capScope: "system",
27208
+ addonId: null,
27209
+ access: "view"
27210
+ },
27211
+ "osdManager.previewSlot": {
27212
+ capName: "osd-manager",
27213
+ capScope: "system",
27214
+ addonId: null,
27215
+ access: "create"
27216
+ },
27217
+ "osdManager.renderDevice": {
27218
+ capName: "osd-manager",
27219
+ capScope: "system",
27220
+ addonId: null,
27221
+ access: "create"
27222
+ },
27223
+ "osdManager.setSlotBinding": {
27224
+ capName: "osd-manager",
27225
+ capScope: "system",
27226
+ addonId: null,
27227
+ access: "create"
27228
+ },
26381
27229
  "petFeeder.callPet": {
26382
27230
  capName: "pet-feeder",
26383
27231
  capScope: "device",
@@ -26450,6 +27298,12 @@ Object.freeze({
26450
27298
  addonId: null,
26451
27299
  access: "delete"
26452
27300
  },
27301
+ "pipelineAnalytics.completeRetrainTrack": {
27302
+ capName: "pipeline-analytics",
27303
+ capScope: "device",
27304
+ addonId: null,
27305
+ access: "create"
27306
+ },
26453
27307
  "pipelineAnalytics.deleteDeviceEvents": {
26454
27308
  capName: "pipeline-analytics",
26455
27309
  capScope: "device",
@@ -26462,6 +27316,12 @@ Object.freeze({
26462
27316
  addonId: null,
26463
27317
  access: "delete"
26464
27318
  },
27319
+ "pipelineAnalytics.deselectRetrainFrame": {
27320
+ capName: "pipeline-analytics",
27321
+ capScope: "device",
27322
+ addonId: null,
27323
+ access: "create"
27324
+ },
26465
27325
  "pipelineAnalytics.getActiveTracks": {
26466
27326
  capName: "pipeline-analytics",
26467
27327
  capScope: "device",
@@ -26522,6 +27382,18 @@ Object.freeze({
26522
27382
  addonId: null,
26523
27383
  access: "view"
26524
27384
  },
27385
+ "pipelineAnalytics.getRetrainExportUrl": {
27386
+ capName: "pipeline-analytics",
27387
+ capScope: "device",
27388
+ addonId: null,
27389
+ access: "view"
27390
+ },
27391
+ "pipelineAnalytics.getRetrainFrameImage": {
27392
+ capName: "pipeline-analytics",
27393
+ capScope: "device",
27394
+ addonId: null,
27395
+ access: "view"
27396
+ },
26525
27397
  "pipelineAnalytics.getSensorEvents": {
26526
27398
  capName: "pipeline-analytics",
26527
27399
  capScope: "device",
@@ -26540,6 +27412,18 @@ Object.freeze({
26540
27412
  addonId: null,
26541
27413
  access: "view"
26542
27414
  },
27415
+ "pipelineAnalytics.getTrainingExportSummary": {
27416
+ capName: "pipeline-analytics",
27417
+ capScope: "device",
27418
+ addonId: null,
27419
+ access: "view"
27420
+ },
27421
+ "pipelineAnalytics.getTrainingExportUrl": {
27422
+ capName: "pipeline-analytics",
27423
+ capScope: "device",
27424
+ addonId: null,
27425
+ access: "view"
27426
+ },
26543
27427
  "pipelineAnalytics.listEventKinds": {
26544
27428
  capName: "pipeline-analytics",
26545
27429
  capScope: "device",
@@ -26564,6 +27448,24 @@ Object.freeze({
26564
27448
  addonId: null,
26565
27449
  access: "view"
26566
27450
  },
27451
+ "pipelineAnalytics.listRetrainAnnotations": {
27452
+ capName: "pipeline-analytics",
27453
+ capScope: "device",
27454
+ addonId: null,
27455
+ access: "view"
27456
+ },
27457
+ "pipelineAnalytics.listRetrainFrames": {
27458
+ capName: "pipeline-analytics",
27459
+ capScope: "device",
27460
+ addonId: null,
27461
+ access: "view"
27462
+ },
27463
+ "pipelineAnalytics.listRetrainStaging": {
27464
+ capName: "pipeline-analytics",
27465
+ capScope: "device",
27466
+ addonId: null,
27467
+ access: "view"
27468
+ },
26567
27469
  "pipelineAnalytics.listTrackMedia": {
26568
27470
  capName: "pipeline-analytics",
26569
27471
  capScope: "device",
@@ -26576,6 +27478,12 @@ Object.freeze({
26576
27478
  addonId: null,
26577
27479
  access: "view"
26578
27480
  },
27481
+ "pipelineAnalytics.proposeRetrainAnnotations": {
27482
+ capName: "pipeline-analytics",
27483
+ capScope: "device",
27484
+ addonId: null,
27485
+ access: "create"
27486
+ },
26579
27487
  "pipelineAnalytics.pruneEvents": {
26580
27488
  capName: "pipeline-analytics",
26581
27489
  capScope: "device",
@@ -26606,12 +27514,30 @@ Object.freeze({
26606
27514
  addonId: null,
26607
27515
  access: "create"
26608
27516
  },
27517
+ "pipelineAnalytics.restageRetrainTrack": {
27518
+ capName: "pipeline-analytics",
27519
+ capScope: "device",
27520
+ addonId: null,
27521
+ access: "create"
27522
+ },
27523
+ "pipelineAnalytics.saveRetrainAnnotations": {
27524
+ capName: "pipeline-analytics",
27525
+ capScope: "device",
27526
+ addonId: null,
27527
+ access: "create"
27528
+ },
26609
27529
  "pipelineAnalytics.searchObjectEvents": {
26610
27530
  capName: "pipeline-analytics",
26611
27531
  capScope: "device",
26612
27532
  addonId: null,
26613
27533
  access: "view"
26614
27534
  },
27535
+ "pipelineAnalytics.selectRetrainFrames": {
27536
+ capName: "pipeline-analytics",
27537
+ capScope: "device",
27538
+ addonId: null,
27539
+ access: "create"
27540
+ },
26615
27541
  "pipelineAnalytics.setTrackFlags": {
26616
27542
  capName: "pipeline-analytics",
26617
27543
  capScope: "device",
@@ -28016,6 +28942,12 @@ Object.freeze({
28016
28942
  addonId: null,
28017
28943
  access: "view"
28018
28944
  },
28945
+ "streamBroker.getDeviceAudioMute": {
28946
+ capName: "stream-broker",
28947
+ capScope: "system",
28948
+ addonId: null,
28949
+ access: "view"
28950
+ },
28019
28951
  "streamBroker.getPreBufferInfo": {
28020
28952
  capName: "stream-broker",
28021
28953
  capScope: "system",
@@ -28136,6 +29068,12 @@ Object.freeze({
28136
29068
  addonId: null,
28137
29069
  access: "create"
28138
29070
  },
29071
+ "streamBroker.setDeviceAudioMute": {
29072
+ capName: "stream-broker",
29073
+ capScope: "system",
29074
+ addonId: null,
29075
+ access: "create"
29076
+ },
28139
29077
  "streamBroker.setPreBufferDuration": {
28140
29078
  capName: "stream-broker",
28141
29079
  capScope: "system",
@@ -29004,6 +29942,506 @@ function resolveExportFingerprint(input) {
29004
29942
  if (input.ready) return input.fresh;
29005
29943
  return input.persisted ?? input.fresh;
29006
29944
  }
29945
+ /**
29946
+ * Fmp4FragmentPlane — a SUBSCRIBABLE fragmented-MP4 plane, fed by one
29947
+ * {@link import('./fmp4-box-splitter.js').Fmp4BoxSplitter}.
29948
+ *
29949
+ * ## Why a plane and not a callback
29950
+ *
29951
+ * The operator's requirement for HKSV was explicit: the live fMP4 source built
29952
+ * for it must be **dual-use**, so a HomeKit-triggered recording also lands in
29953
+ * CamStack as an additional videoclip source alongside the recorder and the NC
29954
+ * clip ring — *one fragmenter, two consumers; do not build an HKSV-only pipe*
29955
+ * (`docs/roadmap.md` item 4b). A single-callback pipe makes the second consumer
29956
+ * a second ffmpeg child of the same camera. So this is the same shape the
29957
+ * broker's other multi-consumer surfaces already have
29958
+ * (`AudioChunkPlane`, the push packet plane): N independent subscriptions over
29959
+ * one producer.
29960
+ *
29961
+ * **Nothing consumes it yet.** Phase 4 brings the HKSV delegate and phase 4b the
29962
+ * clip source; both are named here so the seam is not re-invented, and neither
29963
+ * is built.
29964
+ *
29965
+ * ## The init segment is RETAINED
29966
+ *
29967
+ * A subscriber that attaches mid-stream — the clip consumer joining an already
29968
+ * running HKSV session, which is the whole dual-use case — receives the
29969
+ * retained `ftyp`+`moov` as its first packet and then live fragments. Without
29970
+ * retention its fragments are undecodable and the failure looks like a codec
29971
+ * problem.
29972
+ *
29973
+ * ## A slow subscriber is CLOSED, never silently gapped
29974
+ *
29975
+ * `AudioChunkPlane` drops its oldest chunk on overflow, which for audio costs a
29976
+ * click. An fMP4 stream with a hole is not a shorter clip, it is a corrupt one:
29977
+ * `moof` sequence numbers jump, the consumer's demuxer desynchronises, and HKSV
29978
+ * shows a clip that fails to play with nothing anywhere saying why. So a
29979
+ * subscription whose queue overflows is ENDED with a reason, loudly, and the
29980
+ * other subscriptions are untouched.
29981
+ *
29982
+ * ## The PREBUFFER (phase 3)
29983
+ *
29984
+ * HKSV asks for context BEFORE the trigger — `CameraRecordingOptions.prebufferLength`
29985
+ * is a HAP-mandated minimum of 4000 ms — and a subscriber that attaches at the
29986
+ * motion edge has none. So the plane optionally retains the last few fragments
29987
+ * and replays them to a subscriber that asks for them.
29988
+ *
29989
+ * Three things this ring gets right, each of which is a measured fact rather
29990
+ * than a preference (see [D84](../../../../docs/decisions/adr-0084.md)):
29991
+ *
29992
+ * - **It is bounded by TIME *and* BYTES.** On the live fleet a 720p copy
29993
+ * fragment is ~255 KB and a 4K one is ~6.35 MB — a 25× spread over the same
29994
+ * window. A time-only bound is a per-camera RAM figure nobody can predict.
29995
+ * - **The window is measured on ARRIVAL, not parsed from `tfdt`.** The
29996
+ * splitter deliberately never computes a fragment's duration (a second
29997
+ * opinion about a fact the muxer owns), and a prebuffer cares about how long
29998
+ * ago the bytes turned up, which is exactly what arrival time answers.
29999
+ * - **A replay is not backlog.** A subscriber taking N retained fragments gets
30000
+ * its queue capacity raised by N for them, because closing a subscriber as a
30001
+ * slow consumer for the prebuffer it explicitly asked for would be the
30002
+ * stupidest possible failure — and, with `DEFAULT_QUEUE_CAPACITY` of 4 and a
30003
+ * ring of 4, the guaranteed one.
30004
+ *
30005
+ * ## `isLast`
30006
+ *
30007
+ * hap-nodejs requires the delegate to mark exactly one `RecordingPacket` with
30008
+ * `isLast` — a generator that finishes without it produces the twelve-second
30009
+ * timeout loop [D50](../../../../../docs/decisions/adr-0050.md) deleted. The
30010
+ * plane therefore computes it at DELIVERY time: a packet is last when the plane
30011
+ * has ended and nothing remains queued behind it. A subscription that ends
30012
+ * having delivered NOTHING says so through {@link Fmp4Subscription.delivered};
30013
+ * the future delegate must not open an HDS stream it cannot feed.
30014
+ */
30015
+ var DEFAULT_QUEUE_CAPACITY = 4;
30016
+ var Fmp4FragmentPlane = class {
30017
+ logger;
30018
+ prebuffer;
30019
+ now;
30020
+ subscriptions = /* @__PURE__ */ new Map();
30021
+ /** The last init unit seen, handed to every later subscriber. */
30022
+ retainedInit = null;
30023
+ ended = false;
30024
+ /** Oldest first. Empty unless {@link Fmp4PrebufferOptions} was supplied. */
30025
+ ring = [];
30026
+ ringBytes = 0;
30027
+ constructor(logger, prebuffer, now = Date.now) {
30028
+ this.logger = logger;
30029
+ this.prebuffer = prebuffer;
30030
+ this.now = now;
30031
+ }
30032
+ get subscriberCount() {
30033
+ return this.subscriptions.size;
30034
+ }
30035
+ /** True once {@link end} has been called — no further units are accepted. */
30036
+ get isEnded() {
30037
+ return this.ended;
30038
+ }
30039
+ /** What the prebuffer ring holds right now. All zeroes when disabled. */
30040
+ prebufferStats() {
30041
+ const oldest = this.ring[0];
30042
+ return {
30043
+ fragments: this.ring.length,
30044
+ bytes: this.ringBytes,
30045
+ spanMs: oldest === void 0 ? 0 : this.now() - oldest.arrivedAt
30046
+ };
30047
+ }
30048
+ subscribe(input) {
30049
+ const replay = input.withPrebuffer === true ? this.trimmedRing() : [];
30050
+ const requested = Math.max(1, input.queueCapacity ?? DEFAULT_QUEUE_CAPACITY);
30051
+ const sub = {
30052
+ id: `fmp4-${(0, node_crypto.randomUUID)()}`,
30053
+ tag: input.tag,
30054
+ subscribedAt: this.now(),
30055
+ capacity: requested + replay.length,
30056
+ queue: [],
30057
+ delivered: 0,
30058
+ closedReason: null,
30059
+ wake: null,
30060
+ iterating: false
30061
+ };
30062
+ this.subscriptions.set(sub.id, sub);
30063
+ if (this.retainedInit !== null) this.enqueue(sub, this.retainedInit);
30064
+ for (const retained of replay) this.enqueue(sub, retained.unit);
30065
+ if (this.ended) this.closeSubscription(sub, "ended");
30066
+ this.logger?.info("fmp4 plane: subscribed", { meta: {
30067
+ subscriptionId: sub.id,
30068
+ tag: sub.tag,
30069
+ hasRetainedInit: this.retainedInit !== null,
30070
+ prebufferFragments: replay.length,
30071
+ prebufferBytes: replay.reduce((n, r) => n + r.unit.data.length, 0)
30072
+ } });
30073
+ return this.facade(sub);
30074
+ }
30075
+ /**
30076
+ * Fan one splitter unit out. An `init` REPLACES the retained one — ffmpeg
30077
+ * emits exactly one per child, and a second means the child was respawned, in
30078
+ * which case the old one describes a stream that no longer exists.
30079
+ */
30080
+ publish(unit) {
30081
+ if (this.ended) return;
30082
+ if (unit.kind === "init") {
30083
+ this.retainedInit = unit;
30084
+ this.ring.length = 0;
30085
+ this.ringBytes = 0;
30086
+ } else this.retain(unit);
30087
+ for (const sub of this.subscriptions.values()) {
30088
+ if (sub.closedReason !== null) continue;
30089
+ this.enqueue(sub, unit);
30090
+ }
30091
+ }
30092
+ /**
30093
+ * The producer stopped. Every subscriber drains what it holds; its final
30094
+ * packet carries `isLast`, and its generator then completes.
30095
+ */
30096
+ end(reason = "producer ended") {
30097
+ if (this.ended) return;
30098
+ this.ended = true;
30099
+ this.logger?.info("fmp4 plane: ended", { meta: {
30100
+ reason,
30101
+ subscribers: this.subscriptions.size
30102
+ } });
30103
+ for (const sub of this.subscriptions.values()) if (sub.closedReason === null) this.closeSubscription(sub, "ended");
30104
+ }
30105
+ listSubscribers() {
30106
+ return [...this.subscriptions.values()].map((s) => ({
30107
+ tag: s.tag,
30108
+ subscribedAt: s.subscribedAt,
30109
+ delivered: s.delivered,
30110
+ closedReason: s.closedReason
30111
+ }));
30112
+ }
30113
+ /** End and forget everything. Idempotent. */
30114
+ dispose() {
30115
+ this.end("disposed");
30116
+ this.subscriptions.clear();
30117
+ this.retainedInit = null;
30118
+ this.ring.length = 0;
30119
+ this.ringBytes = 0;
30120
+ }
30121
+ /**
30122
+ * Add one fragment to the ring and evict from the front until BOTH bounds
30123
+ * hold. Eviction is oldest-first, which is the one place in this file where
30124
+ * dropping is correct: the ring is context, not stream — nobody is mid-decode
30125
+ * on it, and a subscriber only ever receives a contiguous tail of it.
30126
+ */
30127
+ retain(unit) {
30128
+ const prebuffer = this.prebuffer;
30129
+ if (prebuffer === void 0) return;
30130
+ const arrivedAt = this.now();
30131
+ this.ring.push({
30132
+ unit,
30133
+ arrivedAt
30134
+ });
30135
+ this.ringBytes += unit.data.length;
30136
+ const cutoff = arrivedAt - prebuffer.windowMs;
30137
+ while (this.ring.length > 0) {
30138
+ const oldest = this.ring[0];
30139
+ if (oldest === void 0) break;
30140
+ const tooOld = oldest.arrivedAt < cutoff;
30141
+ const tooBig = this.ringBytes > prebuffer.maxBytes;
30142
+ if (!tooOld && !tooBig || this.ring.length === 1) break;
30143
+ this.ring.shift();
30144
+ this.ringBytes -= oldest.unit.data.length;
30145
+ }
30146
+ }
30147
+ /**
30148
+ * The ring as a subscriber should receive it — window applied AT SUBSCRIBE
30149
+ * time, not only at publish time. A camera that went quiet keeps its last
30150
+ * fragment in the ring indefinitely (see the never-evict-the-newest rule),
30151
+ * and replaying a 40-second-old fragment as "prebuffer" would put stale video
30152
+ * at the head of a clip iOS presents as the moment of the event.
30153
+ */
30154
+ trimmedRing() {
30155
+ const prebuffer = this.prebuffer;
30156
+ if (prebuffer === void 0) return [];
30157
+ const cutoff = this.now() - prebuffer.windowMs;
30158
+ return this.ring.filter((r) => r.arrivedAt >= cutoff);
30159
+ }
30160
+ enqueue(sub, unit) {
30161
+ if (sub.queue.length >= sub.capacity) {
30162
+ this.logger?.warn("fmp4 plane: subscriber fell behind — CLOSING it rather than gapping it", { meta: {
30163
+ subscriptionId: sub.id,
30164
+ tag: sub.tag,
30165
+ capacity: sub.capacity,
30166
+ delivered: sub.delivered
30167
+ } });
30168
+ this.closeSubscription(sub, "slow-consumer");
30169
+ return;
30170
+ }
30171
+ sub.queue.push({
30172
+ kind: unit.kind,
30173
+ data: unit.data,
30174
+ sequence: unit.sequence,
30175
+ isLast: false
30176
+ });
30177
+ this.wake(sub);
30178
+ }
30179
+ closeSubscription(sub, reason) {
30180
+ if (sub.closedReason !== null) return;
30181
+ sub.closedReason = reason;
30182
+ if (reason === "slow-consumer") sub.queue.length = 0;
30183
+ this.wake(sub);
30184
+ }
30185
+ wake(sub) {
30186
+ const resume = sub.wake;
30187
+ sub.wake = null;
30188
+ resume?.();
30189
+ }
30190
+ facade(sub) {
30191
+ const plane = this;
30192
+ return {
30193
+ id: sub.id,
30194
+ tag: sub.tag,
30195
+ get delivered() {
30196
+ return sub.delivered;
30197
+ },
30198
+ get closedReason() {
30199
+ return sub.closedReason;
30200
+ },
30201
+ packets: () => plane.iterate(sub),
30202
+ release: () => {
30203
+ plane.closeSubscription(sub, "released");
30204
+ plane.subscriptions.delete(sub.id);
30205
+ }
30206
+ };
30207
+ }
30208
+ async *iterate(sub) {
30209
+ if (sub.iterating) throw new Error(`fmp4 plane: subscription ${sub.tag} is already being consumed — take a second subscription`);
30210
+ sub.iterating = true;
30211
+ for (;;) {
30212
+ const next = sub.queue.shift();
30213
+ if (next === void 0) {
30214
+ if (sub.closedReason !== null) return;
30215
+ await new Promise((resolve) => {
30216
+ sub.wake = resolve;
30217
+ });
30218
+ continue;
30219
+ }
30220
+ const isLast = sub.closedReason === "ended" && sub.queue.length === 0;
30221
+ sub.delivered += 1;
30222
+ yield {
30223
+ ...next,
30224
+ isLast
30225
+ };
30226
+ if (isLast) return;
30227
+ }
30228
+ }
30229
+ };
30230
+ var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
30231
+ /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
30232
+ var FRAGMENT_LOG_EVERY = 30;
30233
+ var Fmp4FragmentChild = class {
30234
+ deps;
30235
+ args;
30236
+ child = null;
30237
+ splitter = new Fmp4BoxSplitter();
30238
+ stopped = false;
30239
+ unitsOut = 0;
30240
+ activeHwAccel = null;
30241
+ constructor(deps, args) {
30242
+ this.deps = deps;
30243
+ this.args = args;
30244
+ }
30245
+ /** Spawn, and resolve once the INIT segment has been cut out of stdout. */
30246
+ async start() {
30247
+ const requested = this.args.invocation.decodeHwAccel;
30248
+ this.activeHwAccel = requested;
30249
+ try {
30250
+ await this.spawnAttempt(requested);
30251
+ return;
30252
+ } catch (err) {
30253
+ if (this.stopped) throw err;
30254
+ if (requested === null || isSoftwareDecode(requested)) throw err;
30255
+ this.deps.logger.warn("fmp4 fragment child: hardware decode produced NO fragment — retrying in SOFTWARE", {
30256
+ tags: { deviceId: this.args.deviceId },
30257
+ meta: {
30258
+ sourceId: this.args.sourceId,
30259
+ decodeHwAccel: requested,
30260
+ error: errMsg$12(err)
30261
+ }
30262
+ });
30263
+ this.killChild();
30264
+ this.splitter = new Fmp4BoxSplitter();
30265
+ this.activeHwAccel = null;
30266
+ await this.spawnAttempt(null);
30267
+ }
30268
+ }
30269
+ /** The backend the child ACTUALLY ran with — `null` for software. */
30270
+ activeDecodeHwAccel() {
30271
+ const value = this.activeHwAccel;
30272
+ return value === null || value === "none" || value === "copy" ? null : value;
30273
+ }
30274
+ /** Kill ffmpeg and end the plane. Idempotent. */
30275
+ async stop() {
30276
+ if (this.stopped) return;
30277
+ this.stopped = true;
30278
+ this.killChild();
30279
+ this.args.plane.end("the fragment child stopped");
30280
+ }
30281
+ spawnAttempt(decodeHwAccel) {
30282
+ const args = buildFfmpegArgs({
30283
+ ...this.args.invocation,
30284
+ decodeHwAccel,
30285
+ sink: {
30286
+ kind: "stdout",
30287
+ container: "mp4",
30288
+ fragmentMs: this.args.fragmentMs
30289
+ }
30290
+ });
30291
+ this.deps.logger.info("fmp4 fragment child: spawning ffmpeg", {
30292
+ tags: { deviceId: this.args.deviceId },
30293
+ meta: {
30294
+ sourceId: this.args.sourceId,
30295
+ fragmentMs: this.args.fragmentMs,
30296
+ decodeHwAccel: decodeHwAccel ?? "software",
30297
+ argv: args.join(" ")
30298
+ }
30299
+ });
30300
+ return new Promise((resolve, reject) => {
30301
+ const child = this.deps.spawnFn(this.deps.ffmpegBinaryPath, args, { stdio: [
30302
+ "ignore",
30303
+ "pipe",
30304
+ "pipe"
30305
+ ] });
30306
+ this.child = child;
30307
+ let settled = false;
30308
+ /**
30309
+ * This attempt FAILED. Set before the kill, because SIGTERM makes the
30310
+ * child exit and that exit must not be reported as a death: the retry —
30311
+ * or the caller's rejection — already owns what happens next. Without it
30312
+ * the timeout path ends the plane the software retry is about to fill,
30313
+ * and the consumer sees a stream that stopped for no reason. A "which
30314
+ * spawn is current" counter does NOT cover this: the retry has not been
30315
+ * spawned when the kill's exit arrives.
30316
+ */
30317
+ let failed = false;
30318
+ /**
30319
+ * This attempt is still the live producer: it has not failed (a failure
30320
+ * hands ownership to the retry, or to the caller's rejection) and nothing
30321
+ * has stopped the child. Those two cover every way an attempt stops being
30322
+ * current — `start` only respawns after a rejection.
30323
+ */
30324
+ const isCurrent = () => !this.stopped && !failed;
30325
+ const timeoutMs = this.deps.firstUnitTimeoutMs ?? DEFAULT_FIRST_UNIT_TIMEOUT_MS;
30326
+ const settle = (fail) => {
30327
+ if (settled) return;
30328
+ settled = true;
30329
+ clearTimeout(timer);
30330
+ if (fail) {
30331
+ failed = true;
30332
+ reject(fail);
30333
+ } else resolve();
30334
+ };
30335
+ const timer = setTimeout(() => {
30336
+ settle(/* @__PURE__ */ new Error(`fmp4 fragment child: no fragment within ${timeoutMs}ms`));
30337
+ this.killChild();
30338
+ }, timeoutMs);
30339
+ timer.unref?.();
30340
+ child.stdout?.on("data", (chunk) => {
30341
+ for (const unit of this.splitter.push(chunk)) {
30342
+ this.unitsOut += 1;
30343
+ this.args.plane.publish(unit);
30344
+ if (unit.kind === "init") {
30345
+ this.deps.logger.info("fmp4 fragment child: INIT segment cut", {
30346
+ tags: { deviceId: this.args.deviceId },
30347
+ meta: {
30348
+ sourceId: this.args.sourceId,
30349
+ bytes: unit.data.length
30350
+ }
30351
+ });
30352
+ settle();
30353
+ } else if (this.unitsOut % FRAGMENT_LOG_EVERY === 0) this.deps.logger.info("fmp4 fragment child: fragments still flowing", {
30354
+ tags: { deviceId: this.args.deviceId },
30355
+ meta: {
30356
+ sourceId: this.args.sourceId,
30357
+ unitsOut: this.unitsOut,
30358
+ bytes: unit.data.length,
30359
+ subscribers: this.args.plane.subscriberCount
30360
+ }
30361
+ });
30362
+ }
30363
+ const fault = this.splitter.fault;
30364
+ if (fault !== null) this.onFault(fault, settled, isCurrent(), settle);
30365
+ });
30366
+ child.stderr?.setEncoding("utf8");
30367
+ child.stderr?.on("data", (line) => {
30368
+ this.deps.logger.debug("fmp4 fragment child ffmpeg", {
30369
+ tags: { deviceId: this.args.deviceId },
30370
+ meta: {
30371
+ sourceId: this.args.sourceId,
30372
+ line: line.trim()
30373
+ }
30374
+ });
30375
+ });
30376
+ child.once("error", (err) => {
30377
+ if (!settled) {
30378
+ settle(err);
30379
+ return;
30380
+ }
30381
+ if (!isCurrent()) return;
30382
+ this.args.plane.end("the fragment child errored");
30383
+ this.deps.onChildExit?.(err);
30384
+ });
30385
+ child.once("exit", (code, signal) => {
30386
+ if (!settled) {
30387
+ settle(/* @__PURE__ */ new Error(`fmp4 fragment child: ffmpeg exited before any fragment (code=${code} signal=${signal})`));
30388
+ return;
30389
+ }
30390
+ if (!isCurrent()) return;
30391
+ const error = /* @__PURE__ */ new Error(`fmp4 fragment child: ffmpeg exited while live (code=${code} signal=${signal})`);
30392
+ this.deps.logger.warn("fmp4 fragment child: ffmpeg exited while live", {
30393
+ tags: { deviceId: this.args.deviceId },
30394
+ meta: {
30395
+ sourceId: this.args.sourceId,
30396
+ code,
30397
+ signal,
30398
+ unitsOut: this.unitsOut
30399
+ }
30400
+ });
30401
+ this.args.plane.end("the fragment child exited");
30402
+ this.deps.onChildExit?.(error);
30403
+ });
30404
+ });
30405
+ }
30406
+ /**
30407
+ * The byte stream stopped being splittable. Not recoverable — the splitter
30408
+ * cannot resynchronise mid-box — so the child is a corpse and every consumer
30409
+ * has to be told, loudly, with the reason.
30410
+ */
30411
+ onFault(reason, wasLive, current, settle) {
30412
+ const error = /* @__PURE__ */ new Error(`fmp4 fragment child: ${reason}`);
30413
+ this.deps.logger.error("fmp4 fragment child: the ffmpeg output stopped parsing as fMP4", {
30414
+ tags: { deviceId: this.args.deviceId },
30415
+ meta: {
30416
+ sourceId: this.args.sourceId,
30417
+ unitsOut: this.unitsOut,
30418
+ interstitial: this.splitter.discardedInterstitialTypes,
30419
+ reason
30420
+ }
30421
+ });
30422
+ this.killChild();
30423
+ settle(error);
30424
+ if (wasLive && current) {
30425
+ this.args.plane.end("the fragment child produced unsplittable output");
30426
+ this.deps.onChildExit?.(error);
30427
+ }
30428
+ }
30429
+ killChild() {
30430
+ const child = this.child;
30431
+ this.child = null;
30432
+ if (child && !child.killed) try {
30433
+ child.kill("SIGTERM");
30434
+ } catch (err) {
30435
+ this.deps.logger.warn("fmp4 fragment child: kill error", {
30436
+ tags: { deviceId: this.args.deviceId },
30437
+ meta: {
30438
+ sourceId: this.args.sourceId,
30439
+ error: errMsg$12(err)
30440
+ }
30441
+ });
30442
+ }
30443
+ }
30444
+ };
29007
30445
  //#endregion
29008
30446
  //#region src/accessory-publisher.ts
29009
30447
  /**
@@ -42660,9 +44098,18 @@ async function buildIntercom(input) {
42660
44098
  * (`proxy.motion.isDetected({})`) when the motion cap is bound.
42661
44099
  */
42662
44100
  var RESET_DEBOUNCE_MS = 5e3;
42663
- async function buildMotionSensor(bctx) {
44101
+ /**
44102
+ * @param existing - The controller's OWN `MotionSensor`, when HomeKit Secure
44103
+ * Video is advertised. HKSV derives its `EventTriggerOption.MOTION` from the
44104
+ * service the `CameraController` created (`sensors: { motion: true }`) and is
44105
+ * blind to any other one — a second MotionSensor added here would keep working
44106
+ * as a sensor in the Home app while silently triggering no recording at all.
44107
+ * `null` when recording is off, in which case this builder owns the service as
44108
+ * it always has.
44109
+ */
44110
+ async function buildMotionSensor(bctx, existing = null) {
42664
44111
  const { ctx, accessory, proxy, numericDeviceId, displayName } = bctx;
42665
- const motionService = accessory.addService(_homebridge_hap_nodejs.Service.MotionSensor, hapServiceName([displayName], `Camera ${numericDeviceId}`));
44112
+ const motionService = existing ?? accessory.addService(_homebridge_hap_nodejs.Service.MotionSensor, hapServiceName([displayName], `Camera ${numericDeviceId}`));
42666
44113
  motionService.setCharacteristic(_homebridge_hap_nodejs.Characteristic.MotionDetected, false);
42667
44114
  try {
42668
44115
  const detected = await proxy.motion?.isDetected({});
@@ -43058,6 +44505,814 @@ async function probe(call, label, log) {
43058
44505
  }
43059
44506
  }
43060
44507
  //#endregion
44508
+ //#region src/hksv/recording-options.ts
44509
+ /**
44510
+ * The HomeKit Secure Video ADVERTISEMENT — `CameraRecordingOptions`, derived
44511
+ * from what the fMP4 sink will actually produce for THIS camera.
44512
+ *
44513
+ * ## The rule this file exists to enforce
44514
+ *
44515
+ * Never advertise something we cannot serve. That is not a slogan here: it is
44516
+ * the diagnosis of [D50](../../../../docs/decisions/adr-0050.md) — an
44517
+ * advertised `recording` whose delegate yielded nothing put every motion-capable
44518
+ * camera into a ~12 s timeout loop every 20-60 s, all day. So every number below
44519
+ * is derived from the picked source (`recording-source.ts`) or from a measured
44520
+ * property of the sink, and none of them is a plausible-looking constant.
44521
+ *
44522
+ * ## The fragment length is the subtle one
44523
+ *
44524
+ * HKSV requires every media fragment to be **no longer** than the length the
44525
+ * controller selected. On the copy branch the fragment length is the SOURCE's
44526
+ * key-frame cadence ([D80](../../../../docs/decisions/adr-0080.md)) — we do not
44527
+ * get to choose it, we can only be honest about it. So:
44528
+ *
44529
+ * - when the camera reports its GOP (`stream-params`), the advertised length is
44530
+ * the smallest offered value that COVERS it;
44531
+ * - when it does not, we advertise the 4000 ms every HKSV camera uses and the
44532
+ * delegate warns at `warn` with `tags: { deviceId }` if the fragments that
44533
+ * actually arrive are longer.
44534
+ *
44535
+ * A camera whose GOP exceeds the longest value we offer does not advertise
44536
+ * recording at all. See {@link deriveFragmentLengthMs}.
44537
+ */
44538
+ /**
44539
+ * The prebuffer we promise. HAP's floor is 4000 ms and its documented sensible
44540
+ * range is [4000, 8000]; the plane's ring is sized from this, so the two cannot
44541
+ * disagree. Asking for more than we retain would be the same lie in the other
44542
+ * direction.
44543
+ */
44544
+ var HKSV_PREBUFFER_MS = 4e3;
44545
+ /**
44546
+ * The fragment lengths we are willing to advertise, shortest first. 4000 ms is
44547
+ * what every shipping HKSV camera uses; 8000 exists for a camera whose GOP is
44548
+ * 8 s, which is common enough on this fleet's defaults to be worth covering
44549
+ * rather than refusing.
44550
+ */
44551
+ var HKSV_FRAGMENT_LENGTHS_MS = [4e3, 8e3];
44552
+ /**
44553
+ * AAC-LC at 24 kHz mono. Fixed rather than negotiated: an fMP4 fragment carries
44554
+ * its audio in-band, so unlike the live SRTP path there is no second plane on
44555
+ * which to answer a different sample rate, and D80 records that HKSV takes AAC
44556
+ * and nothing else.
44557
+ */
44558
+ var HKSV_AUDIO_SAMPLE_RATE_HZ = 24e3;
44559
+ /**
44560
+ * The advertised fragment length for a camera whose key-frame cadence is
44561
+ * `sourceGopMs`, or `null` when no offered length covers it.
44562
+ *
44563
+ * `undefined` — the camera does not report a GOP — takes the shortest offered
44564
+ * length. That is a guess, and it is the RIGHT guess (4 s is the near-universal
44565
+ * default), but it is a guess: the delegate measures the arriving cadence and
44566
+ * says so when reality disagrees.
44567
+ */
44568
+ function deriveFragmentLengthMs(sourceGopMs) {
44569
+ const shortest = HKSV_FRAGMENT_LENGTHS_MS[0];
44570
+ if (shortest === void 0) return null;
44571
+ if (sourceGopMs === void 0 || sourceGopMs <= 0) return shortest;
44572
+ return HKSV_FRAGMENT_LENGTHS_MS.find((ms) => ms >= sourceGopMs) ?? null;
44573
+ }
44574
+ /**
44575
+ * Build the advertisement.
44576
+ *
44577
+ * ONE resolution is advertised — the one slot the recording child pulls. HAP's
44578
+ * documentation lists 1920×1080 and 1280×720 as "required to be supported", and
44579
+ * listing both when the source is only one of them is precisely the D50 failure
44580
+ * in miniature: iOS would select a configuration we then cannot deliver, on the
44581
+ * copy branch, with no encoder to resize with.
44582
+ */
44583
+ function buildRecordingOptions(input) {
44584
+ const resolution = [
44585
+ input.width,
44586
+ input.height,
44587
+ Math.max(1, Math.round(input.fps))
44588
+ ];
44589
+ return {
44590
+ prebufferLength: HKSV_PREBUFFER_MS,
44591
+ mediaContainerConfiguration: {
44592
+ type: _homebridge_hap_nodejs.MediaContainerType.FRAGMENTED_MP4,
44593
+ fragmentLength: input.fragmentLengthMs
44594
+ },
44595
+ video: {
44596
+ type: _homebridge_hap_nodejs.VideoCodecType.H264,
44597
+ parameters: {
44598
+ profiles: [
44599
+ _homebridge_hap_nodejs.H264Profile.BASELINE,
44600
+ _homebridge_hap_nodejs.H264Profile.MAIN,
44601
+ _homebridge_hap_nodejs.H264Profile.HIGH
44602
+ ],
44603
+ levels: [
44604
+ _homebridge_hap_nodejs.H264Level.LEVEL3_1,
44605
+ _homebridge_hap_nodejs.H264Level.LEVEL3_2,
44606
+ _homebridge_hap_nodejs.H264Level.LEVEL4_0
44607
+ ]
44608
+ },
44609
+ resolutions: [resolution]
44610
+ },
44611
+ audio: { codecs: [{
44612
+ type: _homebridge_hap_nodejs.AudioRecordingCodecType.AAC_LC,
44613
+ audioChannels: 1,
44614
+ bitrateMode: _homebridge_hap_nodejs.AudioBitrate.VARIABLE,
44615
+ samplerate: [_homebridge_hap_nodejs.AudioRecordingSamplerate.KHZ_24]
44616
+ }] }
44617
+ };
44618
+ }
44619
+ //#endregion
44620
+ //#region src/hksv/fragment-source.ts
44621
+ /**
44622
+ * How far back the prebuffer ring reaches.
44623
+ *
44624
+ * Twice {@link HKSV_PREBUFFER_MS}, and the factor is structural rather than
44625
+ * generous: the ring holds WHOLE fragments, so a window of exactly 4 s can hold
44626
+ * a single 4 s fragment that is about to age out — a trigger landing a moment
44627
+ * later would replay nothing. Two fragment lengths guarantee at least one
44628
+ * covering fragment at every instant.
44629
+ */
44630
+ var PREBUFFER_WINDOW_MS = HKSV_PREBUFFER_MS * 2;
44631
+ /**
44632
+ * The ring's hard byte ceiling, per camera.
44633
+ *
44634
+ * Measured fragment sizes on this fleet: ~145 KB for 4 s at 720p, ~3.6 MB for
44635
+ * 4 s at 4K. 16 MB covers two 4K fragments with room and bounds the exporter's
44636
+ * heap at a figure an operator can multiply by the camera count — which is the
44637
+ * number a time-only bound refuses to give.
44638
+ */
44639
+ var PREBUFFER_MAX_BYTES = 16 * 1024 * 1024;
44640
+ /** Backoff after a child that died while live. Bounded, never a tight loop. */
44641
+ var RESPAWN_BACKOFF_MS = [
44642
+ 2e3,
44643
+ 5e3,
44644
+ 15e3,
44645
+ 3e4
44646
+ ];
44647
+ var HksvFragmentSource = class {
44648
+ input;
44649
+ plane = null;
44650
+ child = null;
44651
+ stopped = false;
44652
+ starting = null;
44653
+ respawnAttempt = 0;
44654
+ respawnTimer = null;
44655
+ audioActive;
44656
+ log;
44657
+ constructor(input) {
44658
+ this.input = input;
44659
+ this.audioActive = input.audioActive;
44660
+ this.log = input.logger;
44661
+ }
44662
+ /** True once a child has produced its initialisation segment. */
44663
+ get isRunning() {
44664
+ return this.child !== null && this.plane !== null && !this.plane.isEnded;
44665
+ }
44666
+ /**
44667
+ * Spawn the child and start filling the ring. Idempotent, and concurrent
44668
+ * calls share one attempt — `updateRecordingActive(true)` and a stream
44669
+ * request can arrive in either order.
44670
+ */
44671
+ async start() {
44672
+ if (this.stopped) throw new Error("hksv fragment source: already stopped");
44673
+ if (this.isRunning) return;
44674
+ const inflight = this.starting;
44675
+ if (inflight !== null) return inflight;
44676
+ const attempt = this.spawn();
44677
+ this.starting = attempt;
44678
+ try {
44679
+ await attempt;
44680
+ } finally {
44681
+ this.starting = null;
44682
+ }
44683
+ }
44684
+ /** Stop the child, end the plane, forget the ring. Idempotent. */
44685
+ async stop(reason) {
44686
+ if (this.stopped) return;
44687
+ this.stopped = true;
44688
+ this.clearRespawn();
44689
+ this.log.info("hksv fragment source: stopping", {
44690
+ tags: { deviceId: this.input.deviceId },
44691
+ meta: {
44692
+ reason,
44693
+ brokerId: this.input.source.brokerId
44694
+ }
44695
+ });
44696
+ const child = this.child;
44697
+ this.child = null;
44698
+ if (child) await child.stop();
44699
+ this.plane?.dispose();
44700
+ this.plane = null;
44701
+ }
44702
+ /**
44703
+ * iOS turned recording audio on or off. Respawns onto the other url when it
44704
+ * genuinely changed — the fragments themselves must carry or omit the track,
44705
+ * there is nothing to strip downstream.
44706
+ */
44707
+ async setAudioActive(active) {
44708
+ if (active === this.audioActive) return;
44709
+ this.audioActive = active;
44710
+ this.log.info("hksv fragment source: RecordingAudioActive changed — respawning the child", {
44711
+ tags: { deviceId: this.input.deviceId },
44712
+ meta: {
44713
+ audioActive: active,
44714
+ brokerId: this.input.source.brokerId
44715
+ }
44716
+ });
44717
+ if (!this.isRunning) return;
44718
+ const child = this.child;
44719
+ this.child = null;
44720
+ if (child) await child.stop();
44721
+ this.plane?.dispose();
44722
+ this.plane = null;
44723
+ await this.start();
44724
+ }
44725
+ /**
44726
+ * Subscribe to the live fragments, replaying the prebuffer first.
44727
+ *
44728
+ * Returns `null` when there is no plane — the caller MUST treat that as
44729
+ * "cannot serve this recording" rather than opening an HDS stream it cannot
44730
+ * feed, which is the D50 failure exactly.
44731
+ */
44732
+ subscribe(tag) {
44733
+ const plane = this.plane;
44734
+ if (plane === null || plane.isEnded) return null;
44735
+ const stats = plane.prebufferStats();
44736
+ this.log.info("hksv fragment source: subscribing a recording stream", {
44737
+ tags: { deviceId: this.input.deviceId },
44738
+ meta: {
44739
+ tag,
44740
+ prebufferFragments: stats.fragments,
44741
+ prebufferBytes: stats.bytes,
44742
+ prebufferSpanMs: stats.spanMs
44743
+ }
44744
+ });
44745
+ return plane.subscribe({
44746
+ tag,
44747
+ withPrebuffer: true
44748
+ });
44749
+ }
44750
+ /** What the ring holds — surfaced so the delegate can log what it served. */
44751
+ prebufferSpanMs() {
44752
+ return this.plane?.prebufferStats().spanMs ?? 0;
44753
+ }
44754
+ async spawn() {
44755
+ const plane = new Fmp4FragmentPlane(this.log.child("hksv-plane"), {
44756
+ windowMs: PREBUFFER_WINDOW_MS,
44757
+ maxBytes: PREBUFFER_MAX_BYTES
44758
+ }, this.input.now ?? Date.now);
44759
+ const child = new Fmp4FragmentChild({
44760
+ logger: this.log.child("hksv-fmp4"),
44761
+ ffmpegBinaryPath: this.input.ffmpegBinaryPath,
44762
+ spawnFn: this.input.spawnFn,
44763
+ onChildExit: (error) => this.onChildExit(error)
44764
+ }, {
44765
+ sourceId: `hksv/${this.input.deviceId}`,
44766
+ deviceId: this.input.deviceId,
44767
+ fragmentMs: this.input.fragmentMs,
44768
+ invocation: this.buildInvocation(),
44769
+ plane
44770
+ });
44771
+ this.plane = plane;
44772
+ this.child = child;
44773
+ try {
44774
+ await child.start();
44775
+ this.respawnAttempt = 0;
44776
+ this.log.info("hksv fragment source: prebuffer running", {
44777
+ tags: { deviceId: this.input.deviceId },
44778
+ meta: {
44779
+ brokerId: this.input.source.brokerId,
44780
+ resolution: `${this.input.source.width}x${this.input.source.height}`,
44781
+ fragmentMs: this.input.fragmentMs,
44782
+ audioActive: this.audioActive,
44783
+ windowMs: PREBUFFER_WINDOW_MS
44784
+ }
44785
+ });
44786
+ } catch (err) {
44787
+ this.plane = null;
44788
+ this.child = null;
44789
+ plane.dispose();
44790
+ throw err;
44791
+ }
44792
+ }
44793
+ /**
44794
+ * The child died while live. The prebuffer is gone with it — and saying so is
44795
+ * the point: a source that silently stopped filling reads, from the delegate,
44796
+ * exactly like a camera nothing ever happens on.
44797
+ */
44798
+ onChildExit(error) {
44799
+ if (this.stopped) return;
44800
+ this.child = null;
44801
+ this.plane = null;
44802
+ const delay = RESPAWN_BACKOFF_MS[Math.min(this.respawnAttempt, RESPAWN_BACKOFF_MS.length - 1)];
44803
+ this.respawnAttempt += 1;
44804
+ this.log.warn("hksv fragment source: the child DIED — the prebuffer is empty until it respawns", {
44805
+ tags: { deviceId: this.input.deviceId },
44806
+ meta: {
44807
+ brokerId: this.input.source.brokerId,
44808
+ attempt: this.respawnAttempt,
44809
+ respawnInMs: delay,
44810
+ error: error.message
44811
+ }
44812
+ });
44813
+ this.clearRespawn();
44814
+ const schedule = this.input.setTimeoutFn ?? setTimeout;
44815
+ this.respawnTimer = schedule(() => {
44816
+ this.respawnTimer = null;
44817
+ if (this.stopped) return;
44818
+ this.start().catch((err) => {
44819
+ this.log.warn("hksv fragment source: respawn failed", {
44820
+ tags: { deviceId: this.input.deviceId },
44821
+ meta: {
44822
+ brokerId: this.input.source.brokerId,
44823
+ error: err instanceof Error ? err.message : String(err)
44824
+ }
44825
+ });
44826
+ });
44827
+ }, delay ?? 3e4);
44828
+ this.respawnTimer?.unref?.();
44829
+ }
44830
+ clearRespawn() {
44831
+ if (this.respawnTimer !== null) {
44832
+ clearTimeout(this.respawnTimer);
44833
+ this.respawnTimer = null;
44834
+ }
44835
+ }
44836
+ /**
44837
+ * The invocation, minus the sink the child owns.
44838
+ *
44839
+ * `kind: 'copy'` is not a preference: it is the 128× measurement, and it is
44840
+ * why `pickRecordingSource` refuses a camera whose only slots are H.265. The
44841
+ * audio IS encoded — the source mic is G.711/PCM depending on vendor and HKSV
44842
+ * takes AAC only — which the same measurement priced at 0.4 % of a core.
44843
+ */
44844
+ buildInvocation() {
44845
+ const audio = this.audioActive ? {
44846
+ kind: "encode",
44847
+ codec: "aac",
44848
+ bitrateKbps: 32,
44849
+ sampleRateHz: HKSV_AUDIO_SAMPLE_RATE_HZ,
44850
+ channels: 1
44851
+ } : { kind: "none" };
44852
+ return {
44853
+ logLevel: "error",
44854
+ decodeHwAccel: null,
44855
+ input: {
44856
+ url: this.audioActive ? this.input.source.url : this.input.source.mutedUrl,
44857
+ rtspTransport: "tcp",
44858
+ analyzeDurationUs: 1e6,
44859
+ probeSizeBytes: 1e6
44860
+ },
44861
+ video: { kind: "copy" },
44862
+ audio,
44863
+ threadCount: 0,
44864
+ outputArgs: []
44865
+ };
44866
+ }
44867
+ };
44868
+ //#endregion
44869
+ //#region src/hksv/recording-delegate.ts
44870
+ /**
44871
+ * `HDSProtocolSpecificErrorReason` is a `const enum`, so there is no reverse
44872
+ * map to index — and a bare number in the log is the difference between "iOS
44873
+ * closed it normally" and "iOS rejected our data", which is the whole reason
44874
+ * this line exists.
44875
+ */
44876
+ var HDS_REASON_NAMES = {
44877
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.NORMAL]: "normal",
44878
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.NOT_ALLOWED]: "not-allowed",
44879
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.BUSY]: "busy",
44880
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.CANCELLED]: "cancelled",
44881
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.UNSUPPORTED]: "unsupported",
44882
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE]: "unexpected-failure",
44883
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.TIMEOUT]: "timeout",
44884
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.BAD_DATA]: "bad-data",
44885
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.PROTOCOL_ERROR]: "protocol-error",
44886
+ [_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION]: "invalid-configuration"
44887
+ };
44888
+ function hdsReasonName(reason) {
44889
+ return HDS_REASON_NAMES[reason] ?? `unknown(${String(reason)})`;
44890
+ }
44891
+ var HksvRecordingDelegate = class {
44892
+ input;
44893
+ active = false;
44894
+ configuration = void 0;
44895
+ source = null;
44896
+ log;
44897
+ /** The stream currently being yielded, so `closeRecordingStream` can end it. */
44898
+ open = null;
44899
+ constructor(input) {
44900
+ this.input = input;
44901
+ this.log = input.logger;
44902
+ }
44903
+ /** Test/diagnostic view — the prebuffer is running for this camera. */
44904
+ get prebufferRunning() {
44905
+ return this.source?.isRunning === true;
44906
+ }
44907
+ updateRecordingActive(active) {
44908
+ if (active === this.active) return;
44909
+ this.active = active;
44910
+ this.log.info("hksv: recording active changed", {
44911
+ tags: { deviceId: this.input.deviceId },
44912
+ meta: {
44913
+ active,
44914
+ hasConfiguration: this.configuration !== void 0
44915
+ }
44916
+ });
44917
+ this.reconcile("recording-active");
44918
+ }
44919
+ updateRecordingConfiguration(configuration) {
44920
+ this.configuration = configuration;
44921
+ if (configuration === void 0) {
44922
+ this.log.info("hksv: the selected configuration was CLEARED — stopping the prebuffer", { tags: { deviceId: this.input.deviceId } });
44923
+ this.reconcile("configuration-cleared");
44924
+ return;
44925
+ }
44926
+ const selectedMs = configuration.mediaContainerConfiguration.fragmentLength;
44927
+ this.log.info("hksv: iOS selected a recording configuration", {
44928
+ tags: { deviceId: this.input.deviceId },
44929
+ meta: {
44930
+ fragmentLengthMs: selectedMs,
44931
+ prebufferLengthMs: configuration.prebufferLength,
44932
+ resolution: configuration.videoCodec.resolution.join("x"),
44933
+ audioCodec: configuration.audioCodec.type,
44934
+ eventTriggers: configuration.eventTriggerTypes
44935
+ }
44936
+ });
44937
+ if (selectedMs < this.input.advertisedFragmentMs) this.log.warn("hksv: iOS selected a SHORTER fragment length than the source can cut", {
44938
+ tags: { deviceId: this.input.deviceId },
44939
+ meta: {
44940
+ selectedMs,
44941
+ advertisedMs: this.input.advertisedFragmentMs
44942
+ }
44943
+ });
44944
+ this.reconcile("configuration-selected");
44945
+ }
44946
+ async *handleRecordingStreamRequest(streamId, signal) {
44947
+ const source = this.source;
44948
+ if (source === null || !source.isRunning) {
44949
+ this.log.warn("hksv: recording stream requested with NO prebuffer running — refusing", {
44950
+ tags: { deviceId: this.input.deviceId },
44951
+ meta: {
44952
+ streamId,
44953
+ active: this.active,
44954
+ hasConfiguration: this.configuration !== void 0
44955
+ }
44956
+ });
44957
+ throw new _homebridge_hap_nodejs.HDSProtocolError(_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.NOT_ALLOWED);
44958
+ }
44959
+ const subscription = source.subscribe(`hksv/${this.input.deviceId}#${streamId}`);
44960
+ if (subscription === null) {
44961
+ this.log.warn("hksv: the fragment plane refused a subscription — refusing the stream", {
44962
+ tags: { deviceId: this.input.deviceId },
44963
+ meta: { streamId }
44964
+ });
44965
+ throw new _homebridge_hap_nodejs.HDSProtocolError(_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.NOT_ALLOWED);
44966
+ }
44967
+ this.open = {
44968
+ streamId,
44969
+ subscription
44970
+ };
44971
+ const startedAt = Date.now();
44972
+ const prebufferSpanMs = source.prebufferSpanMs();
44973
+ let packets = 0;
44974
+ let bytes = 0;
44975
+ let markedLast = false;
44976
+ let longestFragmentGapMs = 0;
44977
+ let lastPacketAt = startedAt;
44978
+ try {
44979
+ for await (const packet of subscription.packets()) {
44980
+ if (signal?.aborted === true) {
44981
+ this.log.info("hksv: the recording stream was aborted — ending the generator", {
44982
+ tags: { deviceId: this.input.deviceId },
44983
+ meta: {
44984
+ streamId,
44985
+ packets
44986
+ }
44987
+ });
44988
+ return;
44989
+ }
44990
+ packets += 1;
44991
+ bytes += packet.data.length;
44992
+ if (packet.kind === "fragment") {
44993
+ const now = Date.now();
44994
+ longestFragmentGapMs = Math.max(longestFragmentGapMs, now - lastPacketAt);
44995
+ lastPacketAt = now;
44996
+ }
44997
+ markedLast = markedLast || packet.isLast;
44998
+ yield {
44999
+ data: Buffer.from(packet.data),
45000
+ isLast: packet.isLast
45001
+ };
45002
+ if (packet.isLast) return;
45003
+ }
45004
+ if (!markedLast && subscription.closedReason !== "released") {
45005
+ this.log.warn("hksv: the fragment stream ended without a final packet", {
45006
+ tags: { deviceId: this.input.deviceId },
45007
+ meta: {
45008
+ streamId,
45009
+ packets,
45010
+ closedReason: subscription.closedReason,
45011
+ truncated: subscription.closedReason === "slow-consumer"
45012
+ }
45013
+ });
45014
+ if (packets === 0) throw new _homebridge_hap_nodejs.HDSProtocolError(_homebridge_hap_nodejs.HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE);
45015
+ yield {
45016
+ data: Buffer.alloc(0),
45017
+ isLast: true
45018
+ };
45019
+ }
45020
+ } finally {
45021
+ subscription.release();
45022
+ if (this.open?.streamId === streamId) this.open = null;
45023
+ const fragmentOverrun = longestFragmentGapMs > this.input.advertisedFragmentMs * 1.5;
45024
+ this.log.info("hksv: recording stream finished", {
45025
+ tags: { deviceId: this.input.deviceId },
45026
+ meta: {
45027
+ streamId,
45028
+ packets,
45029
+ bytes,
45030
+ durationMs: Date.now() - startedAt,
45031
+ prebufferSpanMs,
45032
+ longestFragmentGapMs,
45033
+ closedReason: subscription.closedReason,
45034
+ markedLast
45035
+ }
45036
+ });
45037
+ if (fragmentOverrun) this.log.warn("hksv: fragments arrived LONGER than the advertised length", {
45038
+ tags: { deviceId: this.input.deviceId },
45039
+ meta: {
45040
+ longestFragmentGapMs,
45041
+ advertisedMs: this.input.advertisedFragmentMs
45042
+ }
45043
+ });
45044
+ }
45045
+ }
45046
+ acknowledgeStream(streamId) {
45047
+ this.log.info("hksv: iOS acknowledged the end of stream — the clip landed", {
45048
+ tags: { deviceId: this.input.deviceId },
45049
+ meta: { streamId }
45050
+ });
45051
+ }
45052
+ closeRecordingStream(streamId, reason) {
45053
+ this.log.info("hksv: the recording stream was closed by the controller", {
45054
+ tags: { deviceId: this.input.deviceId },
45055
+ meta: {
45056
+ streamId,
45057
+ reason: reason === void 0 ? "connection-closed" : hdsReasonName(reason)
45058
+ }
45059
+ });
45060
+ const open = this.open;
45061
+ if (open?.streamId === streamId) {
45062
+ open.subscription.release();
45063
+ this.open = null;
45064
+ }
45065
+ }
45066
+ /** Tear the prebuffer down — the accessory is being unexposed. */
45067
+ async dispose() {
45068
+ this.open?.subscription.release();
45069
+ this.open = null;
45070
+ const source = this.source;
45071
+ this.source = null;
45072
+ if (source) await source.stop("accessory disposed");
45073
+ }
45074
+ /**
45075
+ * Start the prebuffer when iOS wants recording AND has chosen how, stop it
45076
+ * otherwise. Called from every state edge rather than each edge deciding for
45077
+ * itself: the two characteristics arrive in an order hap-nodejs explicitly
45078
+ * does not guarantee, and a per-edge decision has to re-derive the same
45079
+ * conjunction in two places.
45080
+ */
45081
+ async reconcile(trigger) {
45082
+ if (!(this.active && this.configuration !== void 0)) {
45083
+ const source = this.source;
45084
+ this.source = null;
45085
+ if (source) await source.stop(`recording no longer wanted (${trigger})`);
45086
+ return;
45087
+ }
45088
+ const configuration = this.configuration;
45089
+ if (configuration === void 0) return;
45090
+ const audioActive = this.input.isAudioActive();
45091
+ const existing = this.source;
45092
+ if (existing !== null) {
45093
+ await existing.setAudioActive(audioActive);
45094
+ if (!existing.isRunning) await existing.start();
45095
+ return;
45096
+ }
45097
+ const source = this.input.createSource({
45098
+ fragmentMs: configuration.mediaContainerConfiguration.fragmentLength,
45099
+ audioActive
45100
+ });
45101
+ this.source = source;
45102
+ try {
45103
+ await source.start();
45104
+ } catch (err) {
45105
+ this.source = null;
45106
+ this.log.error("hksv: the prebuffer FAILED to start — this camera will record nothing", {
45107
+ tags: { deviceId: this.input.deviceId },
45108
+ meta: {
45109
+ trigger,
45110
+ error: err instanceof Error ? err.message : String(err)
45111
+ }
45112
+ });
45113
+ }
45114
+ }
45115
+ };
45116
+ //#endregion
45117
+ //#region src/hksv/recording-source.ts
45118
+ /** The tallest frame the recording path will hold in its prebuffer. */
45119
+ var MAX_RECORDING_HEIGHT = 1080;
45120
+ /** HKSV takes H.264 only — AAC audio and H.264 video, no negotiation. */
45121
+ var RECORDABLE_CODEC = "h264";
45122
+ /**
45123
+ * Pick the slot the recording child pulls.
45124
+ *
45125
+ * Deliberately NOT `pickPreferredRtspEntry`: that picker resolves the operator's
45126
+ * LIVE preference and, on `auto`, steers by the resolution iOS negotiated for a
45127
+ * live session — neither is a fact about recording, and on 615 it selects `mid`,
45128
+ * a 10 fps slot. Recording has one criterion, applied here and nowhere else:
45129
+ * the largest copyable frame that does not exceed {@link MAX_RECORDING_HEIGHT}.
45130
+ */
45131
+ function pickRecordingSource(entries) {
45132
+ const enabled = entries.filter((e) => e.enabled);
45133
+ if (enabled.length === 0) return {
45134
+ ok: false,
45135
+ refusal: "no-enabled-stream"
45136
+ };
45137
+ const h264 = enabled.filter((e) => normaliseCodec(e.codec) === RECORDABLE_CODEC);
45138
+ if (h264.length === 0) return {
45139
+ ok: false,
45140
+ refusal: "no-h264-stream"
45141
+ };
45142
+ const sized = h264.filter(hasUsableResolution);
45143
+ if (sized.length === 0) return {
45144
+ ok: false,
45145
+ refusal: "no-resolution"
45146
+ };
45147
+ const withinCeiling = sized.filter((e) => height(e) <= MAX_RECORDING_HEIGHT);
45148
+ const best = [...withinCeiling.length > 0 ? withinCeiling : sized].sort((a, b) => withinCeiling.length > 0 ? height(b) - height(a) : height(a) - height(b))[0];
45149
+ if (best === void 0 || best.resolution === void 0) return {
45150
+ ok: false,
45151
+ refusal: "no-resolution"
45152
+ };
45153
+ return {
45154
+ ok: true,
45155
+ source: {
45156
+ brokerId: best.brokerId,
45157
+ profile: best.profile ?? best.brokerId,
45158
+ url: best.url,
45159
+ mutedUrl: best.mutedUrl,
45160
+ width: best.resolution.width,
45161
+ height: best.resolution.height
45162
+ }
45163
+ };
45164
+ }
45165
+ /** A one-line reason for the log — silence about a withdrawn service reads as a bug. */
45166
+ function refusalReason(refusal) {
45167
+ switch (refusal) {
45168
+ case "no-enabled-stream": return "the camera has no enabled RTSP profile";
45169
+ case "no-h264-stream": return "every enabled profile is H.265 — HKSV takes H.264 only, and a permanent transcode costs 128x a copy";
45170
+ case "no-resolution": return "no enabled profile declares a resolution, so nothing honest could be advertised";
45171
+ }
45172
+ }
45173
+ function height(entry) {
45174
+ return entry.resolution?.height ?? 0;
45175
+ }
45176
+ function hasUsableResolution(entry) {
45177
+ const r = entry.resolution;
45178
+ return r !== void 0 && r.width > 0 && r.height > 0;
45179
+ }
45180
+ /** Publishers spell H.265 four ways; the same normalisation the broker uses. */
45181
+ function normaliseCodec(codec) {
45182
+ return (codec ?? "").toLowerCase().replace(/[.\s-]/g, "");
45183
+ }
45184
+ //#endregion
45185
+ //#region src/hksv/build-recording.ts
45186
+ /**
45187
+ * Assemble HomeKit Secure Video for one camera — the ADVERTISEMENT and the
45188
+ * DELEGATE, together, or neither.
45189
+ *
45190
+ * That pairing is the whole rule and it is why nothing shipped for HKSV before
45191
+ * this: `recording` is optional on `CameraControllerOptions`, and passing it IS
45192
+ * the entire user-visible change. There is no "phase 1 behind a flag" for an
45193
+ * advertisement — either iOS is offered a recording toggle backed by a delegate
45194
+ * that yields real fragments, or the services are not on the accessory at all
45195
+ * ([D50](../../../../docs/decisions/adr-0050.md)).
45196
+ *
45197
+ * So this returns `null` for every reason a camera cannot record, and each of
45198
+ * them is logged at `info`/`warn` with `tags: { deviceId }`. A withdrawn
45199
+ * capability that says nothing is indistinguishable from a bug — and on this
45200
+ * surface the operator's first question is always "why does 617 have it and 615
45201
+ * not?".
45202
+ */
45203
+ /**
45204
+ * The ffmpeg on `PATH`, exactly as the live streaming path resolves it
45205
+ * (`camera-streams.ts` spawns `'ffmpeg'`). One resolution per addon, not two.
45206
+ */
45207
+ var FFMPEG_BINARY = "ffmpeg";
45208
+ /** Fallback when nothing measured a rate for the picked slot. */
45209
+ var ASSUMED_RECORDING_FPS = 15;
45210
+ async function buildHksvRecording(input) {
45211
+ const { bctx } = input;
45212
+ const { ctx, numericDeviceId } = bctx;
45213
+ const log = ctx.logger.withTags({ deviceId: numericDeviceId });
45214
+ const entries = await readProfileEntries(bctx);
45215
+ if (entries === null) {
45216
+ log.warn("export-hap: HKSV withheld — could not read the camera profiles", {});
45217
+ return null;
45218
+ }
45219
+ const choice = pickRecordingSource(entries);
45220
+ if (!choice.ok) {
45221
+ log.info("export-hap: HKSV withheld — no recordable stream", { meta: {
45222
+ refusal: choice.refusal,
45223
+ reason: refusalReason(choice.refusal)
45224
+ } });
45225
+ return null;
45226
+ }
45227
+ const source = choice.source;
45228
+ const gopMs = await readSourceGopMs(bctx, source.width, source.height);
45229
+ const fragmentLengthMs = deriveFragmentLengthMs(gopMs);
45230
+ if (fragmentLengthMs === null) {
45231
+ log.warn("export-hap: HKSV withheld — the camera key-frame interval is longer than any fragment length we advertise", { meta: {
45232
+ gopMs,
45233
+ brokerId: source.brokerId
45234
+ } });
45235
+ return null;
45236
+ }
45237
+ const fps = resolveFps(input.fpsByProfile, source.profile);
45238
+ const options = buildRecordingOptions({
45239
+ width: source.width,
45240
+ height: source.height,
45241
+ fps,
45242
+ fragmentLengthMs
45243
+ });
45244
+ const delegate = new HksvRecordingDelegate({
45245
+ logger: log,
45246
+ deviceId: numericDeviceId,
45247
+ isAudioActive: input.isAudioActive,
45248
+ advertisedFragmentMs: fragmentLengthMs,
45249
+ createSource: ({ fragmentMs, audioActive }) => new HksvFragmentSource({
45250
+ logger: log,
45251
+ deviceId: numericDeviceId,
45252
+ ffmpegBinaryPath: FFMPEG_BINARY,
45253
+ spawnFn: node_child_process.spawn,
45254
+ source,
45255
+ fragmentMs,
45256
+ audioActive
45257
+ })
45258
+ });
45259
+ log.info("export-hap: HKSV ADVERTISED — recording is offered for this camera", { meta: {
45260
+ brokerId: source.brokerId,
45261
+ profile: source.profile,
45262
+ resolution: `${source.width}x${source.height}`,
45263
+ fps,
45264
+ fragmentLengthMs,
45265
+ sourceGopMs: gopMs ?? "unknown"
45266
+ } });
45267
+ return {
45268
+ options,
45269
+ delegate,
45270
+ dispose: () => delegate.dispose()
45271
+ };
45272
+ }
45273
+ /** `cameraStreams.getProfileRtspEntries`, or `null` when the cap is unreachable. */
45274
+ async function readProfileEntries(bctx) {
45275
+ try {
45276
+ return await bctx.proxy.cameraStreams?.getProfileRtspEntries({}) ?? null;
45277
+ } catch {
45278
+ return null;
45279
+ }
45280
+ }
45281
+ /**
45282
+ * The camera's own key-frame interval in ms, from `stream-params`, matched to
45283
+ * the picked slot BY RESOLUTION.
45284
+ *
45285
+ * By resolution and not by name on purpose: `stream-params` names its profiles
45286
+ * `main`/`sub`/`ext` while the broker names its slots `high`/`mid`/`low`, and
45287
+ * on 615 `ext` is the 1280×720 slot the broker calls `mid` — a name-based match
45288
+ * would silently read the 4K slot's GOP for a 720p recording.
45289
+ *
45290
+ * `undefined` when the cap is not bound, which is most non-Hikvision providers.
45291
+ */
45292
+ async function readSourceGopMs(bctx, width, height) {
45293
+ try {
45294
+ const status = await bctx.proxy.streamParams?.getStatus({});
45295
+ if (!status) return void 0;
45296
+ for (const profile of [
45297
+ status.main,
45298
+ status.sub,
45299
+ status.ext
45300
+ ]) {
45301
+ if (!profile) continue;
45302
+ if (profile.width !== width || profile.height !== height) continue;
45303
+ const { gop, framerate } = profile;
45304
+ if (gop === void 0 || gop <= 0 || framerate <= 0) return void 0;
45305
+ return Math.round(gop / framerate * 1e3);
45306
+ }
45307
+ return;
45308
+ } catch {
45309
+ return;
45310
+ }
45311
+ }
45312
+ function resolveFps(fpsByProfile, profile) {
45313
+ return fpsByProfile.get(profile)?.fps ?? ASSUMED_RECORDING_FPS;
45314
+ }
45315
+ //#endregion
43061
45316
  //#region src/mappers/builders/child-switch.ts
43062
45317
  /**
43063
45318
  * Child-switch builder — turns a camstack accessory child device (siren,
@@ -43263,19 +45518,39 @@ async function buildCameraAccessory(input) {
43263
45518
  displayName,
43264
45519
  options
43265
45520
  };
43266
- const streams = buildCameraStreamingDelegate(bctx, await probeAdvertisedVideoProfile(bctx));
45521
+ const advertisedVideo = await probeAdvertisedVideoProfile(bctx);
45522
+ const streams = buildCameraStreamingDelegate(bctx, advertisedVideo);
43267
45523
  const handles = [];
43268
45524
  if (capNames.has("intercom")) handles.push(await buildIntercom({
43269
45525
  bctx,
43270
45526
  streamingOptions: streams.streamingOptions
43271
45527
  }));
45528
+ const recordingEnabled = options.hapDeviceSettings.hksvRecording === true;
45529
+ let recordingAudioActive = true;
45530
+ const recording = recordingEnabled ? await buildHksvRecording({
45531
+ bctx,
45532
+ fpsByProfile: advertisedVideo.fpsByProfile,
45533
+ isAudioActive: () => recordingAudioActive
45534
+ }) : null;
43272
45535
  const controller = new (isDoorbell ? _homebridge_hap_nodejs.DoorbellController : _homebridge_hap_nodejs.CameraController)({
43273
45536
  delegate: streams.delegate,
43274
45537
  streamingOptions: streams.streamingOptions,
43275
- cameraStreamCount: 2
45538
+ cameraStreamCount: 2,
45539
+ ...recording === null ? {} : { recording },
45540
+ ...recording === null || !capNames.has("motion-detection") ? {} : { sensors: { motion: true } }
43276
45541
  });
43277
45542
  accessory.configureController(controller);
43278
- if (capNames.has("motion-detection")) handles.push(await buildMotionSensor(bctx));
45543
+ if (recording !== null) {
45544
+ handles.push({ dispose: () => recording.dispose() });
45545
+ const audioCharacteristic = (controller.recordingManagement?.operatingModeService)?.getCharacteristic(_homebridge_hap_nodejs.Characteristic.RecordingAudioActive);
45546
+ if (audioCharacteristic) {
45547
+ recordingAudioActive = audioCharacteristic.value !== 0 && audioCharacteristic.value !== false;
45548
+ audioCharacteristic.on("change", ({ newValue }) => {
45549
+ recordingAudioActive = newValue !== 0 && newValue !== false;
45550
+ });
45551
+ }
45552
+ }
45553
+ if (capNames.has("motion-detection")) handles.push(await buildMotionSensor(bctx, recording === null ? null : controller.motionService ?? null));
43279
45554
  if (isDoorbell && controller instanceof _homebridge_hap_nodejs.DoorbellController) handles.push(await buildDoorbell({
43280
45555
  bctx,
43281
45556
  controller
@@ -43520,7 +45795,23 @@ function syncStateToJson(map) {
43520
45795
  * intercom upload bridge, HomeKit Secure Video, recording, native
43521
45796
  * H.264 stream tap (currently uses RTSP + ffmpeg copy).
43522
45797
  */
43523
- var DEFAULT_DEVICE_SETTINGS = { streamPreference: "auto" };
45798
+ var DEFAULT_DEVICE_SETTINGS = {
45799
+ streamPreference: "auto",
45800
+ hksvRecording: true
45801
+ };
45802
+ /**
45803
+ * ON unless explicitly switched off — operator decision 2026-08-08 (flipped
45804
+ * from the launch default of off). ABSENT must resolve to ON or the flip is a
45805
+ * lie for every entry persisted before the field existed, so every read goes
45806
+ * through this one resolver (`!== false`), never a scattered `=== true`. The
45807
+ * cost that made off-by-default look prudent is measured and small on the only
45808
+ * branch the recorder accepts (copy: 0.7 % of a core / ~30 MB RSS, D84), and a
45809
+ * camera the recorder cannot copy refuses recording with a logged reason
45810
+ * rather than paying for a transcode.
45811
+ */
45812
+ function resolveHksvRecording(settings) {
45813
+ return settings?.hksvRecording !== false;
45814
+ }
43524
45815
  var HAP_STREAM_PREFERENCE_OPTIONS = [
43525
45816
  {
43526
45817
  value: "auto",
@@ -43795,7 +46086,10 @@ var ExportHapAddon = class extends BaseAddon {
43795
46086
  options: {
43796
46087
  ptzPulseMs: this.config.ptzPulseMs,
43797
46088
  decodeMemos: this.decodeMemos,
43798
- hapDeviceSettings: { streamPreference: entrySettings.streamPreference ?? "auto" }
46089
+ hapDeviceSettings: {
46090
+ streamPreference: entrySettings.streamPreference ?? "auto",
46091
+ hksvRecording: resolveHksvRecording(entrySettings)
46092
+ }
43799
46093
  }
43800
46094
  });
43801
46095
  for (const accessory of mapper.accessories) await publishStandalone(accessory, {
@@ -44070,6 +46364,7 @@ var ExportHapAddon = class extends BaseAddon {
44070
46364
  const enabled = entry !== null;
44071
46365
  const enabledKey = `hap:${deviceId}:enabled`;
44072
46366
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
46367
+ const hksvKey = `hap:${deviceId}:hksvRecording`;
44073
46368
  const mapper = this.exposed.get(String(deviceId)) ?? null;
44074
46369
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
44075
46370
  const name = entry?.displayName ?? `Device ${deviceId}`;
@@ -44137,6 +46432,19 @@ var ExportHapAddon = class extends BaseAddon {
44137
46432
  equals: true
44138
46433
  },
44139
46434
  immediate: true
46435
+ },
46436
+ {
46437
+ type: "boolean",
46438
+ key: hksvKey,
46439
+ label: "HomeKit recording (Secure Video)",
46440
+ description: "Offer “Stream and Allow Recording” in iOS Home. Requires iCloud+ and a home hub. Keeps a continuous 8s prebuffer for this camera (~0.7% of one CPU core, H.264 sources only).",
46441
+ style: "switch",
46442
+ value: resolveHksvRecording(settings),
46443
+ showWhen: {
46444
+ field: enabledKey,
46445
+ equals: true
46446
+ },
46447
+ immediate: true
44140
46448
  }
44141
46449
  ]
44142
46450
  }]
@@ -44161,12 +46469,15 @@ var ExportHapAddon = class extends BaseAddon {
44161
46469
  const wasEnabled = this.exposed.has(deviceIdStr);
44162
46470
  const enabledKey = `hap:${deviceId}:enabled`;
44163
46471
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
46472
+ const hksvKey = `hap:${deviceId}:hksvRecording`;
44164
46473
  const enabledValue = enabledKey in patch ? Boolean(patch[enabledKey]) : wasEnabled;
44165
46474
  const streamPreferenceRaw = streamPreferenceKey in patch ? patch[streamPreferenceKey] : current?.settings?.streamPreference;
44166
46475
  const streamPreference = typeof streamPreferenceRaw === "string" && streamPreferenceRaw.trim().length > 0 ? streamPreferenceRaw : "auto";
46476
+ const hksvRecording = hksvKey in patch ? Boolean(patch[hksvKey]) : resolveHksvRecording(current?.settings);
44167
46477
  const nextSettings = {
44168
46478
  ...current?.settings ?? DEFAULT_DEVICE_SETTINGS,
44169
- streamPreference
46479
+ streamPreference,
46480
+ hksvRecording
44170
46481
  };
44171
46482
  if (!enabledValue) {
44172
46483
  if (wasEnabled) await this.unexposeDevice(deviceIdStr);
@@ -44178,17 +46489,24 @@ var ExportHapAddon = class extends BaseAddon {
44178
46489
  return { success: true };
44179
46490
  }
44180
46491
  const currentPref = current?.settings?.streamPreference ?? "auto";
46492
+ const currentHksv = resolveHksvRecording(current?.settings);
44181
46493
  await this.updateEntrySettings(deviceIdStr, nextSettings);
44182
- if (currentPref !== streamPreference) {
44183
- log.info("export-hap: streamPreference changed — refreshing accessory", { meta: {
44184
- from: currentPref,
44185
- to: streamPreference
46494
+ if (currentPref !== streamPreference || currentHksv !== hksvRecording) {
46495
+ log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
46496
+ streamPreference: {
46497
+ from: currentPref,
46498
+ to: streamPreference
46499
+ },
46500
+ hksvRecording: {
46501
+ from: currentHksv,
46502
+ to: hksvRecording
46503
+ }
44186
46504
  } });
44187
46505
  try {
44188
46506
  await this.unexposeDevice(deviceIdStr, { clearPairing: false });
44189
46507
  await this.exposeDevice(deviceIdStr);
44190
46508
  } catch (err) {
44191
- log.warn("export-hap: failed to refresh accessory after streamPreference change", { meta: { error: errMsg(err) } });
46509
+ log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });
44192
46510
  }
44193
46511
  }
44194
46512
  return { success: true };
@@ -44231,4 +46549,5 @@ exports.default = ExportHapAddon;
44231
46549
  exports.deriveUsername = deriveUsername;
44232
46550
  exports.initHapStorage = initHapStorage;
44233
46551
  exports.publishStandalone = publishStandalone;
46552
+ exports.resolveHksvRecording = resolveHksvRecording;
44234
46553
  exports.unpublishAccessory = unpublishAccessory;