@camstack/addon-export-hap 1.2.14 → 1.2.15

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.
@@ -1,9 +1,9 @@
1
1
  import { createRequire } from "node:module";
2
- import { createHash, randomBytes } from "node:crypto";
2
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
3
3
  import * as path from "node:path";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { spawn } from "node:child_process";
6
- import { Accessory, AudioBitrate, AudioStreamingCodecType, AudioStreamingSamplerate, CameraController, Categories, Characteristic, DoorbellController, H264Level, H264Profile, HAPStorage, SRTPCryptoSuites, Service, uuid } from "@homebridge/hap-nodejs";
6
+ import { Accessory, AudioBitrate, AudioRecordingCodecType, AudioRecordingSamplerate, AudioStreamingCodecType, AudioStreamingSamplerate, CameraController, Categories, Characteristic, DoorbellController, H264Level, H264Profile, HAPStorage, HDSProtocolError, HDSProtocolSpecificErrorReason, MediaContainerType, SRTPCryptoSuites, Service, VideoCodecType, uuid } from "@homebridge/hap-nodejs";
7
7
  import * as fs from "node:fs/promises";
8
8
  import { createSocket } from "node:dgram";
9
9
  import { networkInterfaces } from "node:os";
@@ -6510,7 +6510,20 @@ var BrokerStatsSchema = object({
6510
6510
  sampleRate: number(),
6511
6511
  channels: number(),
6512
6512
  supported: boolean()
6513
- }).nullable().optional()
6513
+ }).nullable().optional(),
6514
+ /**
6515
+ * BROKER-SIDE AUDIO MUTE (D83). `true` = this broker is deliberately
6516
+ * distributing none of the device's audio, on live or recording.
6517
+ *
6518
+ * Present so a silent camera can be told apart from a broken one on the
6519
+ * stream panel itself, without cross-referencing the switch group: a
6520
+ * broker holding an `audio` track descriptor while `audioMuted` is true is
6521
+ * working exactly as asked. `audioMutedDropped` counts the audio units
6522
+ * thrown away since the current dial — it is how you confirm from stats
6523
+ * alone that the mute is on the packet path and not merely persisted.
6524
+ */
6525
+ audioMuted: boolean().optional(),
6526
+ audioMutedDropped: number().optional()
6514
6527
  });
6515
6528
  /**
6516
6529
  * Exporter-facing "profile restream" entry. Returned by
@@ -7041,104 +7054,7 @@ method(object({ deviceId: number() }), array(StreamSourceEntrySchema)), method(o
7041
7054
  input: unknown()
7042
7055
  }), unknown(), { kind: "mutation" }), method(object({ deviceId: number() }), _void(), { kind: "mutation" }), method(object({ deviceId: number() }), unknown().nullable()), method(object({ deviceId: number() }), RawStateResultSchema.nullable(), { auth: "protected" });
7043
7056
  //#endregion
7044
- //#region ../types/dist/canonical-hash-7nfBbEqR.mjs
7045
- /**
7046
- * Deterministic SHA-256 hash of an arbitrary serialisable value. The
7047
- * canonical form sorts object keys alphabetically at every depth so two
7048
- * structurally-equal inputs with different key insertion orders produce
7049
- * the same hash. Returns a 64-char lowercase hex digest.
7050
- *
7051
- * Used by export adapters (Alexa, HAP) to short-circuit re-discovery /
7052
- * accessory-rebuild work when the upstream shape is byte-identical to
7053
- * the last applied state — preventing user-visible "re-discovery"
7054
- * notifications on every addon-runner respawn. Each respawn re-fires
7055
- * `DeviceBindingsChanged` for every cap registration, which without
7056
- * this guard would propagate redundant pushes.
7057
- *
7058
- * Note: this is a SYMPTOMATIC fix layered on top of the binding-change
7059
- * subscription. The proper fix is a single "device ready" lifecycle
7060
- * barrier so exports react only when the full cap set has landed —
7061
- * tracked separately for post-HA-integration work.
7062
- */
7063
- function canonicalHash(value) {
7064
- const canonical = JSON.stringify(value, replaceWithSortedKeys);
7065
- return createHash("sha256").update(canonical ?? "").digest("hex");
7066
- }
7067
- function replaceWithSortedKeys(_key, value) {
7068
- if (value && typeof value === "object" && !Array.isArray(value)) {
7069
- const obj = value;
7070
- const out = {};
7071
- for (const k of Object.keys(obj).toSorted()) out[k] = obj[k];
7072
- return out;
7073
- }
7074
- return value;
7075
- }
7076
- var EncodeProfileSchema = object({
7077
- video: object({
7078
- codec: _enum([
7079
- "h264",
7080
- "h265",
7081
- "copy"
7082
- ]),
7083
- profile: _enum([
7084
- "baseline",
7085
- "main",
7086
- "high"
7087
- ]).optional(),
7088
- /**
7089
- * `-level`, e.g. `'3.1'`. A consumer that ADVERTISES a level in its SDP
7090
- * (`profile-level-id=42e01f` is Baseline 3.1) must constrain the encoder to
7091
- * it, or it ships a stream that does not match its own advertisement — the
7092
- * defect class that kept HomeKit black for a year and that Alexa carried
7093
- * silently. Optional because a browser negotiates the level itself.
7094
- */
7095
- level: string().optional(),
7096
- width: number().int().positive().optional(),
7097
- height: number().int().positive().optional(),
7098
- fps: number().positive().optional(),
7099
- bitrateKbps: number().int().positive().optional(),
7100
- gopFrames: number().int().positive().optional(),
7101
- bf: number().int().min(0).optional(),
7102
- preset: _enum([
7103
- "ultrafast",
7104
- "superfast",
7105
- "veryfast",
7106
- "faster",
7107
- "fast",
7108
- "medium"
7109
- ]).optional(),
7110
- tune: _enum([
7111
- "zerolatency",
7112
- "film",
7113
- "animation"
7114
- ]).optional()
7115
- }),
7116
- audio: union([literal("passthrough"), object({
7117
- codec: _enum([
7118
- "opus",
7119
- "aac",
7120
- "pcmu",
7121
- "pcma",
7122
- "copy"
7123
- ]),
7124
- bitrateKbps: number().int().positive().optional(),
7125
- sampleRateHz: number().int().positive().optional(),
7126
- channels: union([literal(1), literal(2)]).optional()
7127
- })]),
7128
- /**
7129
- * ffmpeg input-side args, inserted between the fixed global flags
7130
- * (`-hide_banner -loglevel error`) and `-i pipe:0`. Free-text array
7131
- * — the widget surfaces a textarea + suggestion chips for the most-
7132
- * used demuxer/format options.
7133
- */
7134
- inputArgs: array(string()).optional(),
7135
- /**
7136
- * ffmpeg output-side args, inserted between the encode block and
7137
- * the final `-f <muxer> pipe:1`. Use for muxer options, bitstream
7138
- * filters, codec-specific overrides. Free-text array.
7139
- */
7140
- outputArgs: array(string()).optional()
7141
- });
7057
+ //#region ../types/dist/fmp4-box-splitter-B53u9-Nu.mjs
7142
7058
  var AUDIO_ENCODER_BY_CODEC = {
7143
7059
  opus: "libopus",
7144
7060
  aac: "aac",
@@ -7319,13 +7235,42 @@ function buildStdoutOrRtspSinkArgs(sink) {
7319
7235
  "pipe:1"
7320
7236
  ];
7321
7237
  }
7238
+ /**
7239
+ * How far BELOW the negotiated fragment length `-min_frag_duration` is set.
7240
+ *
7241
+ * `-min_frag_duration` refuses to cut before that much media has accumulated,
7242
+ * and then waits for the next key frame. Set to exactly `fragmentMs`, the
7243
+ * commonest camera configuration in existence — a key-frame grid EQUAL to the
7244
+ * requested fragment length — lands the deadline on the same instant as the key
7245
+ * frame, loses the race, and skips to the following one: **every fragment comes
7246
+ * out at twice the requested length.**
7247
+ *
7248
+ * Measured on the live fleet 2026-08-07, camera 615, `-c:v copy` (D84):
7249
+ *
7250
+ * | slot | GOP | `-min_frag_duration` | median gap |
7251
+ * | --- | --- | --- | --- |
7252
+ * | 1280×720 | 40 f @ 10 fps = 4.0 s | 4000 ms | **7944 ms** |
7253
+ * | 1280×720 | 40 f @ 10 fps = 4.0 s | 3600 ms | 3973 ms |
7254
+ * | 3840×2160 | 100 f @ 25 fps = 4.0 s | 4000 ms | 8042 ms |
7255
+ * | 3840×2160 | 100 f @ 25 fps = 4.0 s | 3600 ms | 3998 ms |
7256
+ *
7257
+ * A doubled fragment is not a cosmetic overshoot: HKSV requires every fragment
7258
+ * to be no longer than the length the controller SELECTED, so the shipped-but-
7259
+ * inert phase-1 sink would have violated the contract on its first real clip.
7260
+ *
7261
+ * 10 % is chosen against the two failures either side of it. Too small and
7262
+ * ordinary jitter (measured spread 3953-4096 ms) re-loses the race; too large
7263
+ * and a source with a key frame slightly EARLY than the grid gets cut there,
7264
+ * yielding a short fragment for no reason.
7265
+ */
7266
+ var FMP4_MIN_FRAG_MARGIN = .9;
7322
7267
  /** `-movflags … -min_frag_duration <us> -f mp4 pipe:1`. */
7323
7268
  function buildFmp4SinkArgs(sink) {
7324
7269
  return [
7325
7270
  "-movflags",
7326
7271
  FMP4_MOVFLAGS,
7327
7272
  "-min_frag_duration",
7328
- String(Math.max(0, Math.round(sink.fragmentMs * 1e3))),
7273
+ String(Math.max(0, Math.round(sink.fragmentMs * FMP4_MIN_FRAG_MARGIN * 1e3))),
7329
7274
  "-f",
7330
7275
  "mp4",
7331
7276
  "pipe:1"
@@ -7404,6 +7349,287 @@ function buildFfmpegArgs(inv) {
7404
7349
  ];
7405
7350
  }
7406
7351
  /**
7352
+ * Deterministic SHA-256 hash of an arbitrary serialisable value. The
7353
+ * canonical form sorts object keys alphabetically at every depth so two
7354
+ * structurally-equal inputs with different key insertion orders produce
7355
+ * the same hash. Returns a 64-char lowercase hex digest.
7356
+ *
7357
+ * Used by export adapters (Alexa, HAP) to short-circuit re-discovery /
7358
+ * accessory-rebuild work when the upstream shape is byte-identical to
7359
+ * the last applied state — preventing user-visible "re-discovery"
7360
+ * notifications on every addon-runner respawn. Each respawn re-fires
7361
+ * `DeviceBindingsChanged` for every cap registration, which without
7362
+ * this guard would propagate redundant pushes.
7363
+ *
7364
+ * Note: this is a SYMPTOMATIC fix layered on top of the binding-change
7365
+ * subscription. The proper fix is a single "device ready" lifecycle
7366
+ * barrier so exports react only when the full cap set has landed —
7367
+ * tracked separately for post-HA-integration work.
7368
+ */
7369
+ function canonicalHash(value) {
7370
+ const canonical = JSON.stringify(value, replaceWithSortedKeys);
7371
+ return createHash("sha256").update(canonical ?? "").digest("hex");
7372
+ }
7373
+ function replaceWithSortedKeys(_key, value) {
7374
+ if (value && typeof value === "object" && !Array.isArray(value)) {
7375
+ const obj = value;
7376
+ const out = {};
7377
+ for (const k of Object.keys(obj).toSorted()) out[k] = obj[k];
7378
+ return out;
7379
+ }
7380
+ return value;
7381
+ }
7382
+ var DEFAULT_MAX_UNIT_BYTES = 16 * 1024 * 1024;
7383
+ /** Header size for a normal box, and for one carrying a 64-bit `largesize`. */
7384
+ var BOX_HEADER_BYTES = 8;
7385
+ var LARGE_BOX_HEADER_BYTES = 16;
7386
+ var Fmp4BoxSplitter = class {
7387
+ maxUnitBytes;
7388
+ /** Bytes of the CURRENT unit plus any partial box after it. */
7389
+ buffer = new Uint8Array(0);
7390
+ /** Where the current unit starts inside {@link buffer}. */
7391
+ unitStart = 0;
7392
+ /** Where the box scanner has reached inside {@link buffer}. */
7393
+ cursor = 0;
7394
+ state = "init";
7395
+ nextSequence = 0;
7396
+ faultReason = null;
7397
+ interstitial = /* @__PURE__ */ new Set();
7398
+ constructor(options = {}) {
7399
+ this.maxUnitBytes = options.maxUnitBytes ?? DEFAULT_MAX_UNIT_BYTES;
7400
+ }
7401
+ /**
7402
+ * Non-null once the stream cannot be split. The splitter emits nothing
7403
+ * further, so a caller polls this to kill the child rather than watching a
7404
+ * silent stall — a fragmenter that quietly stops producing looks exactly like
7405
+ * a camera with no motion.
7406
+ */
7407
+ get fault() {
7408
+ return this.faultReason;
7409
+ }
7410
+ /** Bytes currently held. The memory bound, observable rather than asserted. */
7411
+ get pendingBytes() {
7412
+ return this.buffer.length - this.unitStart;
7413
+ }
7414
+ /**
7415
+ * Top-level box types seen BETWEEN fragments and discarded — `mfra`, `free`,
7416
+ * a stray `sidx`. Reported rather than dropped in silence: they are legal and
7417
+ * useless to a fragment consumer, but a type nobody expected showing up here
7418
+ * is the first symptom of a muxer that is not writing what we think it is.
7419
+ */
7420
+ get discardedInterstitialTypes() {
7421
+ return [...this.interstitial];
7422
+ }
7423
+ /**
7424
+ * Feed bytes; get back whatever units completed. Returns `[]` once faulted.
7425
+ */
7426
+ push(chunk) {
7427
+ if (this.faultReason !== null || chunk.length === 0) return [];
7428
+ this.append(chunk);
7429
+ if (this.pendingBytes > this.maxUnitBytes) return this.fail(`a single fMP4 unit exceeded ${this.maxUnitBytes} bytes — this stream is not fragmented`);
7430
+ return this.drainBoxes();
7431
+ }
7432
+ append(chunk) {
7433
+ if (this.buffer.length === 0) {
7434
+ this.buffer = chunk.slice();
7435
+ return;
7436
+ }
7437
+ const next = new Uint8Array(this.buffer.length + chunk.length);
7438
+ next.set(this.buffer, 0);
7439
+ next.set(chunk, this.buffer.length);
7440
+ this.buffer = next;
7441
+ }
7442
+ /** Consume every COMPLETE top-level box now in the buffer. */
7443
+ drainBoxes() {
7444
+ const units = [];
7445
+ for (;;) {
7446
+ const header = this.readHeader();
7447
+ if (this.faultReason !== null) return units;
7448
+ if (header === null) break;
7449
+ if (this.cursor + header.totalBytes > this.buffer.length) break;
7450
+ const boxStart = this.cursor;
7451
+ const boxEnd = boxStart + header.totalBytes;
7452
+ this.cursor = boxEnd;
7453
+ const unit = this.consumeBox(header.type, boxStart, boxEnd);
7454
+ if (this.faultReason !== null) return units;
7455
+ if (unit !== null) units.push(unit);
7456
+ }
7457
+ this.compact();
7458
+ return units;
7459
+ }
7460
+ /**
7461
+ * Apply one box to the state machine. Returns a unit when this box CLOSED
7462
+ * one, `null` otherwise.
7463
+ */
7464
+ consumeBox(type, boxStart, boxEnd) {
7465
+ if (this.state === "init") {
7466
+ if (type !== "moof") return null;
7467
+ if (boxStart === this.unitStart) {
7468
+ this.fail("a moof arrived before any initialisation box — there is no ftyp/moov to send");
7469
+ return null;
7470
+ }
7471
+ const init = this.emit("init", this.unitStart, boxStart);
7472
+ this.unitStart = boxStart;
7473
+ this.state = "fragment";
7474
+ return init;
7475
+ }
7476
+ if (this.state === "idle") {
7477
+ if (type !== "moof") {
7478
+ this.interstitial.add(type);
7479
+ this.unitStart = boxEnd;
7480
+ return null;
7481
+ }
7482
+ this.unitStart = boxStart;
7483
+ this.state = "fragment";
7484
+ return null;
7485
+ }
7486
+ if (type !== "mdat") return null;
7487
+ const fragment = this.emit("fragment", this.unitStart, boxEnd);
7488
+ this.unitStart = boxEnd;
7489
+ this.state = "idle";
7490
+ return fragment;
7491
+ }
7492
+ /**
7493
+ * Parse the header at {@link cursor}, or `null` when too few bytes have
7494
+ * arrived to know. Faults on a size the splitter cannot honour.
7495
+ */
7496
+ readHeader() {
7497
+ const available = this.buffer.length - this.cursor;
7498
+ if (available < BOX_HEADER_BYTES) return null;
7499
+ const view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);
7500
+ const size = view.getUint32(this.cursor);
7501
+ 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);
7502
+ if (size === 0) {
7503
+ this.fail(`box "${type}" declares size 0 (to EOF) — an unbounded box cannot be fragmented`);
7504
+ return null;
7505
+ }
7506
+ if (size === 1) {
7507
+ if (available < LARGE_BOX_HEADER_BYTES) return null;
7508
+ const large = view.getBigUint64(this.cursor + BOX_HEADER_BYTES);
7509
+ if (large > BigInt(this.maxUnitBytes)) {
7510
+ this.fail(`box "${type}" declares ${large} bytes, over the ${this.maxUnitBytes} byte bound`);
7511
+ return null;
7512
+ }
7513
+ return {
7514
+ type,
7515
+ totalBytes: Number(large)
7516
+ };
7517
+ }
7518
+ if (size < BOX_HEADER_BYTES) {
7519
+ this.fail(`box "${type}" declares an impossible size of ${size} bytes`);
7520
+ return null;
7521
+ }
7522
+ return {
7523
+ type,
7524
+ totalBytes: size
7525
+ };
7526
+ }
7527
+ emit(kind, start, end) {
7528
+ const sequence = this.nextSequence;
7529
+ this.nextSequence += 1;
7530
+ return {
7531
+ kind,
7532
+ data: this.buffer.slice(start, end),
7533
+ sequence
7534
+ };
7535
+ }
7536
+ /**
7537
+ * Drop everything already emitted or discarded. Without this the buffer is
7538
+ * the whole stream and the process dies in hours, not minutes.
7539
+ */
7540
+ compact() {
7541
+ if (this.unitStart === 0) return;
7542
+ this.buffer = this.buffer.slice(this.unitStart);
7543
+ this.cursor -= this.unitStart;
7544
+ this.unitStart = 0;
7545
+ }
7546
+ fail(reason) {
7547
+ this.faultReason = reason;
7548
+ this.buffer = new Uint8Array(0);
7549
+ this.unitStart = 0;
7550
+ this.cursor = 0;
7551
+ return [];
7552
+ }
7553
+ };
7554
+ //#endregion
7555
+ //#region ../types/dist/err-msg-IQTHeDzc.mjs
7556
+ /**
7557
+ import { errMsg } from '@camstack/types'
7558
+ * Extract a human-readable message from an unknown error value.
7559
+ * Replaces the ubiquitous `errMsg(err)` pattern.
7560
+ */
7561
+ function errMsg$12(err) {
7562
+ if (err instanceof Error) return err.message;
7563
+ if (typeof err === "string") return err;
7564
+ return String(err);
7565
+ }
7566
+ var EncodeProfileSchema = object({
7567
+ video: object({
7568
+ codec: _enum([
7569
+ "h264",
7570
+ "h265",
7571
+ "copy"
7572
+ ]),
7573
+ profile: _enum([
7574
+ "baseline",
7575
+ "main",
7576
+ "high"
7577
+ ]).optional(),
7578
+ /**
7579
+ * `-level`, e.g. `'3.1'`. A consumer that ADVERTISES a level in its SDP
7580
+ * (`profile-level-id=42e01f` is Baseline 3.1) must constrain the encoder to
7581
+ * it, or it ships a stream that does not match its own advertisement — the
7582
+ * defect class that kept HomeKit black for a year and that Alexa carried
7583
+ * silently. Optional because a browser negotiates the level itself.
7584
+ */
7585
+ level: string().optional(),
7586
+ width: number().int().positive().optional(),
7587
+ height: number().int().positive().optional(),
7588
+ fps: number().positive().optional(),
7589
+ bitrateKbps: number().int().positive().optional(),
7590
+ gopFrames: number().int().positive().optional(),
7591
+ bf: number().int().min(0).optional(),
7592
+ preset: _enum([
7593
+ "ultrafast",
7594
+ "superfast",
7595
+ "veryfast",
7596
+ "faster",
7597
+ "fast",
7598
+ "medium"
7599
+ ]).optional(),
7600
+ tune: _enum([
7601
+ "zerolatency",
7602
+ "film",
7603
+ "animation"
7604
+ ]).optional()
7605
+ }),
7606
+ audio: union([literal("passthrough"), object({
7607
+ codec: _enum([
7608
+ "opus",
7609
+ "aac",
7610
+ "pcmu",
7611
+ "pcma",
7612
+ "copy"
7613
+ ]),
7614
+ bitrateKbps: number().int().positive().optional(),
7615
+ sampleRateHz: number().int().positive().optional(),
7616
+ channels: union([literal(1), literal(2)]).optional()
7617
+ })]),
7618
+ /**
7619
+ * ffmpeg input-side args, inserted between the fixed global flags
7620
+ * (`-hide_banner -loglevel error`) and `-i pipe:0`. Free-text array
7621
+ * — the widget surfaces a textarea + suggestion chips for the most-
7622
+ * used demuxer/format options.
7623
+ */
7624
+ inputArgs: array(string()).optional(),
7625
+ /**
7626
+ * ffmpeg output-side args, inserted between the encode block and
7627
+ * the final `-f <muxer> pipe:1`. Use for muxer options, bitstream
7628
+ * filters, codec-specific overrides. Free-text array.
7629
+ */
7630
+ outputArgs: array(string()).optional()
7631
+ });
7632
+ /**
7407
7633
  * The shape every live egress starts from: H.264 Baseline 3.1 at 720p25.
7408
7634
  * Baseline because it is the one profile every consumer in this repo decodes
7409
7635
  * (Echo, iOS, an old browser); 3.1 because that is what the SDPs advertise.
@@ -7523,6 +7749,19 @@ object({
7523
7749
  * | `notifications` | `notificationRules.setDeviceMuted` | `NotificationCenter.evaluateAndEnqueue` returns before any rule is evaluated |
7524
7750
  * | `privacy-mask` | `privacyMask.setMask({ enabled })` → the CAMERA | the camera blanks the masked regions itself; every stream and recording carries the black boxes |
7525
7751
  * | `device-audio` | `privacyMask.setAudioEnabled` → the CAMERA | the camera stops encoding an audio track at all; every consumer sees silent video |
7752
+ * | `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 |
7753
+ *
7754
+ * ## `device-audio` and `broker-audio` are two functions, not two knobs
7755
+ *
7756
+ * They look adjacent and they are not the same control ([D83](../../../../docs/decisions/adr-0083.md)):
7757
+ * `device-audio` writes the CAMERA, so it is hardware privacy — the microphone
7758
+ * genuinely stops, it survives CamStack entirely, and it costs a multi-second
7759
+ * encoder restart on every flip. `broker-audio` writes THIS server, so it is
7760
+ * instant, vendor-independent and reversible without touching the camera, and
7761
+ * a camera that ignores or lacks the ISAPI/Reolink control is still silenced.
7762
+ * D62 forbids a second switch that *disagrees* with the first; these two
7763
+ * cannot disagree, because neither reads the other's store — the camera holds
7764
+ * one, the broker holds the other, and each reports its own fact.
7526
7765
  *
7527
7766
  * ## The two switches whose authority is not on this server
7528
7767
  *
@@ -7584,6 +7823,7 @@ var CameraSwitchIdSchema = _enum([
7584
7823
  "object-detection",
7585
7824
  "privacy-mask",
7586
7825
  "device-audio",
7826
+ "broker-audio",
7587
7827
  "audio-analysis",
7588
7828
  "recording",
7589
7829
  "notifications"
@@ -7609,7 +7849,8 @@ var CameraSwitchAuthoritySchema = discriminatedUnion("kind", [
7609
7849
  object({
7610
7850
  kind: literal("camera-mask"),
7611
7851
  capName: string()
7612
- })
7852
+ }),
7853
+ object({ kind: literal("broker-audio-mute") })
7613
7854
  ]);
7614
7855
  /**
7615
7856
  * Why a switch is not offered for this camera. Rendered instead of the
@@ -9860,7 +10101,25 @@ method(object({
9860
10101
  }), _void(), {
9861
10102
  kind: "mutation",
9862
10103
  auth: "admin"
9863
- }), method(object({ brokerId: string() }), boolean()), object({
10104
+ }), method(object({ brokerId: string() }), boolean()), method(object({ deviceId: number().int() }), object({
10105
+ muted: boolean(),
10106
+ /**
10107
+ * How many live non-derived brokers currently hold the mute. Purely
10108
+ * diagnostic: `muted` is the policy and is authoritative on its own
10109
+ * (it applies to brokers that do not exist yet), while this says
10110
+ * whether anything is presently being silenced.
10111
+ */
10112
+ appliedBrokers: number().int().nonnegative()
10113
+ })), method(object({
10114
+ deviceId: number().int(),
10115
+ muted: boolean()
10116
+ }), object({
10117
+ muted: boolean(),
10118
+ appliedBrokers: number().int().nonnegative()
10119
+ }), {
10120
+ kind: "mutation",
10121
+ auth: "admin"
10122
+ }), object({
9864
10123
  deviceId: number().int().nonnegative(),
9865
10124
  camStreamId: string(),
9866
10125
  profile: CamProfileSchema
@@ -15183,6 +15442,30 @@ var TrackSourceSchema = _enum([
15183
15442
  "audio"
15184
15443
  ]);
15185
15444
  /**
15445
+ * Where a track sits in the RETRAIN lifecycle (D81).
15446
+ *
15447
+ * - `none` — never marked, or un-marked. Evictable.
15448
+ * - `staging` — the operator wants this track as training material and has not
15449
+ * finished with it. **This is the only state retention holds**: the track and
15450
+ * everything it owns (object events, crops, keyframes, CLIP vector) survive
15451
+ * the device's age window.
15452
+ * - `trained` — the retrain page has taken what it needed. The frames it chose
15453
+ * were COPIED into the retrain dataset at selection time, so the dataset no
15454
+ * longer depends on the track's media and the track becomes EVICTABLE again.
15455
+ * Terminal for the plain `markForTrain` toggle: returning it to `staging` is
15456
+ * a deliberate action of the retrain page, not a side effect of a checkbox.
15457
+ *
15458
+ * There is no `null`. The state is stored `TEXT NOT NULL DEFAULT 'none'` because
15459
+ * the store's filter language has only positive equality and `whereIn` — no
15460
+ * negation, no IS NULL — so a NULL would be unselectable by ANY predicate and
15461
+ * would make the entire pre-column history immortal in one deploy.
15462
+ */
15463
+ var RetrainStatusSchema = _enum([
15464
+ "none",
15465
+ "staging",
15466
+ "trained"
15467
+ ]);
15468
+ /**
15186
15469
  * Per-track OPERATOR flags — set by hand from the admin UI or the viewer, never
15187
15470
  * by the pipeline. Spread into `TrackSchema` and `KeyEventSchema` from one place
15188
15471
  * so the two surfaces cannot drift.
@@ -15192,18 +15475,31 @@ var TrackSourceSchema = _enum([
15192
15475
  * columns existed read as absent, and a consumer that needs a boolean should say
15193
15476
  * `flag === true`, not `flag !== false`.
15194
15477
  *
15195
- * What the flags DO is deliberately UNDEFINED at the time of writing: they are
15196
- * operator curation, and the behaviour they drive will be specified separately.
15197
- * In particular a `markForTrain` track is NOT pinned against retention — see
15198
- * `docs/decisions/adr-0059.md` for why that is a store-level change, not a flag.
15478
+ * `markForTrain` is the WIRE FACE of {@link RetrainStatusSchema}, not a column:
15479
+ * it is exactly `retrainStatus === 'staging'`, in both directions. Writing
15480
+ * `true` moves `none → staging`, writing `false` moves `staging none`, and a
15481
+ * `trained` track reports `false` while refusing both writes. The boolean is
15482
+ * kept because three surfaces drive a toggle off it; anything that needs to tell
15483
+ * "never marked" from "already trained" must read `retrainStatus`.
15484
+ *
15485
+ * `debug` does NOT pin; it is attention, not durability.
15199
15486
  */
15200
15487
  var TrackFlagFields = {
15201
- /** Operator marked this track as training material. */
15488
+ /** Operator marked this track as training material — i.e. `retrainStatus` is
15489
+ * `'staging'`. */
15202
15490
  markForTrain: boolean().optional(),
15203
15491
  /** Operator marked this track for diagnostic attention. */
15204
15492
  debug: boolean().optional()
15205
15493
  };
15206
15494
  /**
15495
+ * The lifecycle field itself, on the READ surfaces only (`Track`, `KeyEvent`).
15496
+ * Deliberately NOT part of {@link TrackFlagFields}: that group also builds the
15497
+ * write patch, and the status is not something the toggle sets — it is what the
15498
+ * toggle's boolean is derived from. Absent on an in-RAM track never touched;
15499
+ * always present on a persisted row (the column default materialises `'none'`).
15500
+ */
15501
+ var TrackRetrainFields = { retrainStatus: RetrainStatusSchema.optional() };
15502
+ /**
15207
15503
  * The write half: a PARTIAL patch. An omitted key is left untouched, so setting
15208
15504
  * one flag can never clear the other — the toggles are independent and are
15209
15505
  * driven from three surfaces that do not know about each other.
@@ -15217,7 +15513,32 @@ var TrackFlagsPatchSchema = object(TrackFlagFields);
15217
15513
  var TrackFlagsSchema = object({
15218
15514
  trackId: string(),
15219
15515
  markForTrain: boolean(),
15220
- debug: boolean()
15516
+ debug: boolean(),
15517
+ /** The lifecycle state the boolean was derived from. Required here (unlike on
15518
+ * a track row) because this shape is only ever produced by the write body,
15519
+ * which always knows it — and a surface that has just written needs to render
15520
+ * `trained` without a re-fetch. */
15521
+ retrainStatus: RetrainStatusSchema
15522
+ });
15523
+ /** Per-camera slice of a training-export estimate. */
15524
+ var TrainingExportDeviceTotalsSchema = object({
15525
+ deviceId: number(),
15526
+ tracks: number().int(),
15527
+ files: number().int(),
15528
+ bytes: number().int()
15529
+ });
15530
+ /**
15531
+ * What a training export WOULD contain. Computed from media index rows only —
15532
+ * no blob is read to produce this.
15533
+ */
15534
+ var TrainingExportSummarySchema = object({
15535
+ generatedAt: number(),
15536
+ trackCount: number().int(),
15537
+ fileCount: number().int(),
15538
+ byteCount: number().int(),
15539
+ /** More marked tracks exist than a single pass carries. */
15540
+ truncated: boolean(),
15541
+ devices: array(TrainingExportDeviceTotalsSchema).readonly()
15221
15542
  });
15222
15543
  var TrackSchema = object({
15223
15544
  trackId: string(),
@@ -15262,7 +15583,8 @@ var TrackSchema = object({
15262
15583
  * Populated from the persisted envelope columns on historical reads;
15263
15584
  * absent on legacy rows, dims-less tracks and active (in-RAM) tracks. */
15264
15585
  envelope: TrackEnvelopeSchema.optional(),
15265
- ...TrackFlagFields
15586
+ ...TrackFlagFields,
15587
+ ...TrackRetrainFields
15266
15588
  });
15267
15589
  var BaseEventFields = {
15268
15590
  id: string(),
@@ -15476,7 +15798,8 @@ var KeyEventSchema = object({
15476
15798
  bestEventId: string(),
15477
15799
  /** Track lifetime in ms (lastSeen - firstSeen). */
15478
15800
  windowMs: number().optional(),
15479
- ...TrackFlagFields
15801
+ ...TrackFlagFields,
15802
+ ...TrackRetrainFields
15480
15803
  });
15481
15804
  object({
15482
15805
  trackId: string(),
@@ -15737,6 +16060,12 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
15737
16060
  }), method(OpsLogQueryInputSchema, array(OpsLogEntrySchema).readonly(), {
15738
16061
  kind: "query",
15739
16062
  auth: "admin"
16063
+ }), method(object({ deviceIds: array(number()).optional() }), TrainingExportSummarySchema, {
16064
+ kind: "query",
16065
+ auth: "admin"
16066
+ }), method(object({ deviceIds: array(number()).optional() }), object({ url: string() }), {
16067
+ kind: "query",
16068
+ auth: "admin"
15740
16069
  }), method(object({
15741
16070
  eventId: string(),
15742
16071
  kind: MediaFileKindEnum.optional()
@@ -21397,6 +21726,173 @@ DeviceType.Camera, method(object({
21397
21726
  status: OsdStatusSchema
21398
21727
  });
21399
21728
  /**
21729
+ * `osd-manager` — the ORCHESTRATOR over the device-scope `osd` cap.
21730
+ *
21731
+ * The `osd` cap is the firmware contract: it probes a camera's overlay
21732
+ * SLOTS and writes literal text into one. It has no idea WHERE that text
21733
+ * comes from, and it must not — a driver that grew a "show the temperature
21734
+ * here" feature would grow it once per vendor.
21735
+ *
21736
+ * This cap owns the other half: a per-(camera, slot) BINDING that says
21737
+ * which value feeds the slot, how it is formatted, and under which
21738
+ * conditions it is shown at all. One addon renders every binding on every
21739
+ * camera, so a new source costs zero driver code.
21740
+ *
21741
+ * Three deliberate choices, each with a rejected alternative:
21742
+ *
21743
+ * 1. A source is `(capName, valuePath)` over the kernel's device
21744
+ * runtime-state mirror — NOT a closed enum of source kinds. Every
21745
+ * cap-keyed slice a device publishes is bindable the day the cap
21746
+ * ships. The rejected alternative (one enum member per source, with
21747
+ * a resolver branch each) is what makes "add the humidity too" a
21748
+ * code change.
21749
+ * 2. The display gate reuses `NcConditionsSchema` verbatim — the
21750
+ * notification centre's condition vocabulary — rather than a parallel
21751
+ * model. An operator who has learned one condition editor has learned
21752
+ * both.
21753
+ * 3. Because the renderer's facts are device STATE and not a detection
21754
+ * record, only a SUBSET of that vocabulary can be answered here.
21755
+ * `setSlotBinding` REJECTS the rest at write time (see
21756
+ * `getConditionSupport`). It does not accept-then-fail-closed: a
21757
+ * condition that can never be true renders a permanently blank
21758
+ * overlay, and a blank overlay looks exactly like a broken camera.
21759
+ */
21760
+ /** Where a slot's value comes from. */
21761
+ var OsdSourceSchema = discriminatedUnion("kind", [
21762
+ object({
21763
+ kind: literal("static"),
21764
+ text: string().max(64)
21765
+ }),
21766
+ object({
21767
+ kind: literal("clock"),
21768
+ /** Token pattern: `YYYY MM DD HH mm ss`. Everything else is literal. */
21769
+ pattern: string().min(1).max(32).default("HH:mm"),
21770
+ /** IANA zone. Omitted = the server's zone. */
21771
+ timezone: string().min(1).max(64).optional()
21772
+ }),
21773
+ object({
21774
+ kind: literal("device-state"),
21775
+ deviceId: number().int().optional(),
21776
+ capName: string().min(1).max(64),
21777
+ /** Dot path inside the slice, e.g. `detected`, `value`, `mode`. */
21778
+ valuePath: string().min(1).max(64)
21779
+ })
21780
+ ]);
21781
+ var OsdSlotBindingSchema = object({
21782
+ /** Off = the manager stops driving this slot. It does NOT clear it. */
21783
+ enabled: boolean().default(true),
21784
+ source: OsdSourceSchema,
21785
+ /** `${value}` and `${unit}` are substituted; every occurrence. */
21786
+ template: string().max(96).default("${value}"),
21787
+ /** Truncate with an ellipsis past this length. Absent = no limit. */
21788
+ maxCharacters: number().int().min(4).max(64).optional(),
21789
+ /**
21790
+ * Decimal places for a numeric value. `0` yields an integer — the
21791
+ * documented workaround for firmwares that reject `.` in overlay text.
21792
+ */
21793
+ maxDecimals: number().int().min(0).max(4).default(1),
21794
+ /** Appended via `${unit}`. The state mirror does not carry units. */
21795
+ unitLabel: string().max(8).optional(),
21796
+ /** Raw value → display text, e.g. `{"true":"MOTION","false":""}`. */
21797
+ valueMap: record(string(), string()).optional(),
21798
+ /** Time windows in which the slot is shown. Absent = always. */
21799
+ schedule: NcScheduleSchema.optional(),
21800
+ /**
21801
+ * Display gate, in the notification centre's condition vocabulary.
21802
+ * Only the keys reported by `getConditionSupport` are accepted.
21803
+ */
21804
+ conditions: NcConditionsSchema.optional(),
21805
+ /** Rendered when the gate is closed or the value unreadable. Empty = hide. */
21806
+ fallbackText: string().max(64).default("")
21807
+ });
21808
+ /** One camera slot, as the operator sees it: firmware truth + our binding. */
21809
+ var OsdSlotViewSchema = object({
21810
+ slotId: string(),
21811
+ kind: OsdOverlayKindEnum,
21812
+ /** Firmware refuses text edits (a timestamp, the channel name). */
21813
+ readOnly: boolean(),
21814
+ cameraEnabled: boolean(),
21815
+ cameraText: string().optional(),
21816
+ binding: OsdSlotBindingSchema.nullable()
21817
+ });
21818
+ /**
21819
+ * What happened to one slot on one render pass. `unchanged` exists so the
21820
+ * operator can tell "we are driving this and the value is steady" from
21821
+ * "we never got there" — and so the loop can prove it is not rewriting
21822
+ * identical text to the camera every tick.
21823
+ */
21824
+ var OsdRenderOutcomeEnum = _enum([
21825
+ "written",
21826
+ "unchanged",
21827
+ "gated",
21828
+ "unreadable",
21829
+ "disabled",
21830
+ "unbound",
21831
+ "failed"
21832
+ ]);
21833
+ var OsdRenderResultSchema = object({
21834
+ slotId: string(),
21835
+ outcome: OsdRenderOutcomeEnum,
21836
+ /** The text the slot should carry. Empty = the slot is switched off. */
21837
+ text: string(),
21838
+ /** Why, whenever the outcome is not a plain write. Never silent. */
21839
+ reason: string().optional()
21840
+ });
21841
+ var OsdSourceValueTypeEnum = _enum([
21842
+ "number",
21843
+ "boolean",
21844
+ "string",
21845
+ "enum"
21846
+ ]);
21847
+ /**
21848
+ * One bindable value, derived from a cap's `runtimeState` schema — never
21849
+ * hand-listed. The editor renders from this, so a cap that ships a new
21850
+ * state field becomes bindable with no UI change.
21851
+ */
21852
+ var OsdSourceOptionSchema = object({
21853
+ deviceId: number().int(),
21854
+ deviceName: string(),
21855
+ capName: string(),
21856
+ valuePath: string(),
21857
+ label: string(),
21858
+ valueType: OsdSourceValueTypeEnum,
21859
+ /** Present for `enum`; the editor offers these as `valueMap` keys. */
21860
+ enumValues: array(string()).readonly().optional()
21861
+ });
21862
+ method(object({ deviceId: number().int() }), object({
21863
+ supported: boolean(),
21864
+ slots: array(OsdSlotViewSchema)
21865
+ }), { auth: "admin" }), method(object({ deviceId: number().int() }), object({ sources: array(OsdSourceOptionSchema) }), { auth: "admin" }), method(object({}), object({
21866
+ supported: array(string()),
21867
+ catalog: array(NcConditionDescriptorSchema)
21868
+ }), { auth: "admin" }), method(object({
21869
+ deviceId: number().int(),
21870
+ slotId: string().min(1),
21871
+ binding: OsdSlotBindingSchema
21872
+ }), object({
21873
+ slot: OsdSlotViewSchema,
21874
+ render: OsdRenderResultSchema
21875
+ }), {
21876
+ kind: "mutation",
21877
+ auth: "admin"
21878
+ }), method(object({
21879
+ deviceId: number().int(),
21880
+ slotId: string().min(1)
21881
+ }), object({ success: literal(true) }), {
21882
+ kind: "mutation",
21883
+ auth: "admin"
21884
+ }), method(object({
21885
+ deviceId: number().int(),
21886
+ slotId: string().min(1),
21887
+ binding: OsdSlotBindingSchema.optional()
21888
+ }), OsdRenderResultSchema, {
21889
+ kind: "mutation",
21890
+ auth: "admin"
21891
+ }), method(object({ deviceId: number().int() }), object({ results: array(OsdRenderResultSchema) }), {
21892
+ kind: "mutation",
21893
+ auth: "admin"
21894
+ });
21895
+ /**
21400
21896
  * Feeder connectivity / power status — mirrors the HA petkit device-status
21401
21897
  * enum: `normal` (online, mains), `offline` (not reaching PetKit cloud),
21402
21898
  * `on_batteries` (running on battery backup). `null` until first reported.
@@ -26352,6 +26848,48 @@ Object.freeze({
26352
26848
  addonId: null,
26353
26849
  access: "create"
26354
26850
  },
26851
+ "osdManager.clearSlotBinding": {
26852
+ capName: "osd-manager",
26853
+ capScope: "system",
26854
+ addonId: null,
26855
+ access: "delete"
26856
+ },
26857
+ "osdManager.getConditionSupport": {
26858
+ capName: "osd-manager",
26859
+ capScope: "system",
26860
+ addonId: null,
26861
+ access: "view"
26862
+ },
26863
+ "osdManager.getDeviceOsd": {
26864
+ capName: "osd-manager",
26865
+ capScope: "system",
26866
+ addonId: null,
26867
+ access: "view"
26868
+ },
26869
+ "osdManager.getSourceCatalog": {
26870
+ capName: "osd-manager",
26871
+ capScope: "system",
26872
+ addonId: null,
26873
+ access: "view"
26874
+ },
26875
+ "osdManager.previewSlot": {
26876
+ capName: "osd-manager",
26877
+ capScope: "system",
26878
+ addonId: null,
26879
+ access: "create"
26880
+ },
26881
+ "osdManager.renderDevice": {
26882
+ capName: "osd-manager",
26883
+ capScope: "system",
26884
+ addonId: null,
26885
+ access: "create"
26886
+ },
26887
+ "osdManager.setSlotBinding": {
26888
+ capName: "osd-manager",
26889
+ capScope: "system",
26890
+ addonId: null,
26891
+ access: "create"
26892
+ },
26355
26893
  "petFeeder.callPet": {
26356
26894
  capName: "pet-feeder",
26357
26895
  capScope: "device",
@@ -26514,6 +27052,18 @@ Object.freeze({
26514
27052
  addonId: null,
26515
27053
  access: "view"
26516
27054
  },
27055
+ "pipelineAnalytics.getTrainingExportSummary": {
27056
+ capName: "pipeline-analytics",
27057
+ capScope: "device",
27058
+ addonId: null,
27059
+ access: "view"
27060
+ },
27061
+ "pipelineAnalytics.getTrainingExportUrl": {
27062
+ capName: "pipeline-analytics",
27063
+ capScope: "device",
27064
+ addonId: null,
27065
+ access: "view"
27066
+ },
26517
27067
  "pipelineAnalytics.listEventKinds": {
26518
27068
  capName: "pipeline-analytics",
26519
27069
  capScope: "device",
@@ -27990,6 +28540,12 @@ Object.freeze({
27990
28540
  addonId: null,
27991
28541
  access: "view"
27992
28542
  },
28543
+ "streamBroker.getDeviceAudioMute": {
28544
+ capName: "stream-broker",
28545
+ capScope: "system",
28546
+ addonId: null,
28547
+ access: "view"
28548
+ },
27993
28549
  "streamBroker.getPreBufferInfo": {
27994
28550
  capName: "stream-broker",
27995
28551
  capScope: "system",
@@ -28110,6 +28666,12 @@ Object.freeze({
28110
28666
  addonId: null,
28111
28667
  access: "create"
28112
28668
  },
28669
+ "streamBroker.setDeviceAudioMute": {
28670
+ capName: "stream-broker",
28671
+ capScope: "system",
28672
+ addonId: null,
28673
+ access: "create"
28674
+ },
28113
28675
  "streamBroker.setPreBufferDuration": {
28114
28676
  capName: "stream-broker",
28115
28677
  capScope: "system",
@@ -28978,6 +29540,506 @@ function resolveExportFingerprint(input) {
28978
29540
  if (input.ready) return input.fresh;
28979
29541
  return input.persisted ?? input.fresh;
28980
29542
  }
29543
+ /**
29544
+ * Fmp4FragmentPlane — a SUBSCRIBABLE fragmented-MP4 plane, fed by one
29545
+ * {@link import('./fmp4-box-splitter.js').Fmp4BoxSplitter}.
29546
+ *
29547
+ * ## Why a plane and not a callback
29548
+ *
29549
+ * The operator's requirement for HKSV was explicit: the live fMP4 source built
29550
+ * for it must be **dual-use**, so a HomeKit-triggered recording also lands in
29551
+ * CamStack as an additional videoclip source alongside the recorder and the NC
29552
+ * clip ring — *one fragmenter, two consumers; do not build an HKSV-only pipe*
29553
+ * (`docs/roadmap.md` item 4b). A single-callback pipe makes the second consumer
29554
+ * a second ffmpeg child of the same camera. So this is the same shape the
29555
+ * broker's other multi-consumer surfaces already have
29556
+ * (`AudioChunkPlane`, the push packet plane): N independent subscriptions over
29557
+ * one producer.
29558
+ *
29559
+ * **Nothing consumes it yet.** Phase 4 brings the HKSV delegate and phase 4b the
29560
+ * clip source; both are named here so the seam is not re-invented, and neither
29561
+ * is built.
29562
+ *
29563
+ * ## The init segment is RETAINED
29564
+ *
29565
+ * A subscriber that attaches mid-stream — the clip consumer joining an already
29566
+ * running HKSV session, which is the whole dual-use case — receives the
29567
+ * retained `ftyp`+`moov` as its first packet and then live fragments. Without
29568
+ * retention its fragments are undecodable and the failure looks like a codec
29569
+ * problem.
29570
+ *
29571
+ * ## A slow subscriber is CLOSED, never silently gapped
29572
+ *
29573
+ * `AudioChunkPlane` drops its oldest chunk on overflow, which for audio costs a
29574
+ * click. An fMP4 stream with a hole is not a shorter clip, it is a corrupt one:
29575
+ * `moof` sequence numbers jump, the consumer's demuxer desynchronises, and HKSV
29576
+ * shows a clip that fails to play with nothing anywhere saying why. So a
29577
+ * subscription whose queue overflows is ENDED with a reason, loudly, and the
29578
+ * other subscriptions are untouched.
29579
+ *
29580
+ * ## The PREBUFFER (phase 3)
29581
+ *
29582
+ * HKSV asks for context BEFORE the trigger — `CameraRecordingOptions.prebufferLength`
29583
+ * is a HAP-mandated minimum of 4000 ms — and a subscriber that attaches at the
29584
+ * motion edge has none. So the plane optionally retains the last few fragments
29585
+ * and replays them to a subscriber that asks for them.
29586
+ *
29587
+ * Three things this ring gets right, each of which is a measured fact rather
29588
+ * than a preference (see [D84](../../../../docs/decisions/adr-0084.md)):
29589
+ *
29590
+ * - **It is bounded by TIME *and* BYTES.** On the live fleet a 720p copy
29591
+ * fragment is ~255 KB and a 4K one is ~6.35 MB — a 25× spread over the same
29592
+ * window. A time-only bound is a per-camera RAM figure nobody can predict.
29593
+ * - **The window is measured on ARRIVAL, not parsed from `tfdt`.** The
29594
+ * splitter deliberately never computes a fragment's duration (a second
29595
+ * opinion about a fact the muxer owns), and a prebuffer cares about how long
29596
+ * ago the bytes turned up, which is exactly what arrival time answers.
29597
+ * - **A replay is not backlog.** A subscriber taking N retained fragments gets
29598
+ * its queue capacity raised by N for them, because closing a subscriber as a
29599
+ * slow consumer for the prebuffer it explicitly asked for would be the
29600
+ * stupidest possible failure — and, with `DEFAULT_QUEUE_CAPACITY` of 4 and a
29601
+ * ring of 4, the guaranteed one.
29602
+ *
29603
+ * ## `isLast`
29604
+ *
29605
+ * hap-nodejs requires the delegate to mark exactly one `RecordingPacket` with
29606
+ * `isLast` — a generator that finishes without it produces the twelve-second
29607
+ * timeout loop [D50](../../../../../docs/decisions/adr-0050.md) deleted. The
29608
+ * plane therefore computes it at DELIVERY time: a packet is last when the plane
29609
+ * has ended and nothing remains queued behind it. A subscription that ends
29610
+ * having delivered NOTHING says so through {@link Fmp4Subscription.delivered};
29611
+ * the future delegate must not open an HDS stream it cannot feed.
29612
+ */
29613
+ var DEFAULT_QUEUE_CAPACITY = 4;
29614
+ var Fmp4FragmentPlane = class {
29615
+ logger;
29616
+ prebuffer;
29617
+ now;
29618
+ subscriptions = /* @__PURE__ */ new Map();
29619
+ /** The last init unit seen, handed to every later subscriber. */
29620
+ retainedInit = null;
29621
+ ended = false;
29622
+ /** Oldest first. Empty unless {@link Fmp4PrebufferOptions} was supplied. */
29623
+ ring = [];
29624
+ ringBytes = 0;
29625
+ constructor(logger, prebuffer, now = Date.now) {
29626
+ this.logger = logger;
29627
+ this.prebuffer = prebuffer;
29628
+ this.now = now;
29629
+ }
29630
+ get subscriberCount() {
29631
+ return this.subscriptions.size;
29632
+ }
29633
+ /** True once {@link end} has been called — no further units are accepted. */
29634
+ get isEnded() {
29635
+ return this.ended;
29636
+ }
29637
+ /** What the prebuffer ring holds right now. All zeroes when disabled. */
29638
+ prebufferStats() {
29639
+ const oldest = this.ring[0];
29640
+ return {
29641
+ fragments: this.ring.length,
29642
+ bytes: this.ringBytes,
29643
+ spanMs: oldest === void 0 ? 0 : this.now() - oldest.arrivedAt
29644
+ };
29645
+ }
29646
+ subscribe(input) {
29647
+ const replay = input.withPrebuffer === true ? this.trimmedRing() : [];
29648
+ const requested = Math.max(1, input.queueCapacity ?? DEFAULT_QUEUE_CAPACITY);
29649
+ const sub = {
29650
+ id: `fmp4-${randomUUID()}`,
29651
+ tag: input.tag,
29652
+ subscribedAt: this.now(),
29653
+ capacity: requested + replay.length,
29654
+ queue: [],
29655
+ delivered: 0,
29656
+ closedReason: null,
29657
+ wake: null,
29658
+ iterating: false
29659
+ };
29660
+ this.subscriptions.set(sub.id, sub);
29661
+ if (this.retainedInit !== null) this.enqueue(sub, this.retainedInit);
29662
+ for (const retained of replay) this.enqueue(sub, retained.unit);
29663
+ if (this.ended) this.closeSubscription(sub, "ended");
29664
+ this.logger?.info("fmp4 plane: subscribed", { meta: {
29665
+ subscriptionId: sub.id,
29666
+ tag: sub.tag,
29667
+ hasRetainedInit: this.retainedInit !== null,
29668
+ prebufferFragments: replay.length,
29669
+ prebufferBytes: replay.reduce((n, r) => n + r.unit.data.length, 0)
29670
+ } });
29671
+ return this.facade(sub);
29672
+ }
29673
+ /**
29674
+ * Fan one splitter unit out. An `init` REPLACES the retained one — ffmpeg
29675
+ * emits exactly one per child, and a second means the child was respawned, in
29676
+ * which case the old one describes a stream that no longer exists.
29677
+ */
29678
+ publish(unit) {
29679
+ if (this.ended) return;
29680
+ if (unit.kind === "init") {
29681
+ this.retainedInit = unit;
29682
+ this.ring.length = 0;
29683
+ this.ringBytes = 0;
29684
+ } else this.retain(unit);
29685
+ for (const sub of this.subscriptions.values()) {
29686
+ if (sub.closedReason !== null) continue;
29687
+ this.enqueue(sub, unit);
29688
+ }
29689
+ }
29690
+ /**
29691
+ * The producer stopped. Every subscriber drains what it holds; its final
29692
+ * packet carries `isLast`, and its generator then completes.
29693
+ */
29694
+ end(reason = "producer ended") {
29695
+ if (this.ended) return;
29696
+ this.ended = true;
29697
+ this.logger?.info("fmp4 plane: ended", { meta: {
29698
+ reason,
29699
+ subscribers: this.subscriptions.size
29700
+ } });
29701
+ for (const sub of this.subscriptions.values()) if (sub.closedReason === null) this.closeSubscription(sub, "ended");
29702
+ }
29703
+ listSubscribers() {
29704
+ return [...this.subscriptions.values()].map((s) => ({
29705
+ tag: s.tag,
29706
+ subscribedAt: s.subscribedAt,
29707
+ delivered: s.delivered,
29708
+ closedReason: s.closedReason
29709
+ }));
29710
+ }
29711
+ /** End and forget everything. Idempotent. */
29712
+ dispose() {
29713
+ this.end("disposed");
29714
+ this.subscriptions.clear();
29715
+ this.retainedInit = null;
29716
+ this.ring.length = 0;
29717
+ this.ringBytes = 0;
29718
+ }
29719
+ /**
29720
+ * Add one fragment to the ring and evict from the front until BOTH bounds
29721
+ * hold. Eviction is oldest-first, which is the one place in this file where
29722
+ * dropping is correct: the ring is context, not stream — nobody is mid-decode
29723
+ * on it, and a subscriber only ever receives a contiguous tail of it.
29724
+ */
29725
+ retain(unit) {
29726
+ const prebuffer = this.prebuffer;
29727
+ if (prebuffer === void 0) return;
29728
+ const arrivedAt = this.now();
29729
+ this.ring.push({
29730
+ unit,
29731
+ arrivedAt
29732
+ });
29733
+ this.ringBytes += unit.data.length;
29734
+ const cutoff = arrivedAt - prebuffer.windowMs;
29735
+ while (this.ring.length > 0) {
29736
+ const oldest = this.ring[0];
29737
+ if (oldest === void 0) break;
29738
+ const tooOld = oldest.arrivedAt < cutoff;
29739
+ const tooBig = this.ringBytes > prebuffer.maxBytes;
29740
+ if (!tooOld && !tooBig || this.ring.length === 1) break;
29741
+ this.ring.shift();
29742
+ this.ringBytes -= oldest.unit.data.length;
29743
+ }
29744
+ }
29745
+ /**
29746
+ * The ring as a subscriber should receive it — window applied AT SUBSCRIBE
29747
+ * time, not only at publish time. A camera that went quiet keeps its last
29748
+ * fragment in the ring indefinitely (see the never-evict-the-newest rule),
29749
+ * and replaying a 40-second-old fragment as "prebuffer" would put stale video
29750
+ * at the head of a clip iOS presents as the moment of the event.
29751
+ */
29752
+ trimmedRing() {
29753
+ const prebuffer = this.prebuffer;
29754
+ if (prebuffer === void 0) return [];
29755
+ const cutoff = this.now() - prebuffer.windowMs;
29756
+ return this.ring.filter((r) => r.arrivedAt >= cutoff);
29757
+ }
29758
+ enqueue(sub, unit) {
29759
+ if (sub.queue.length >= sub.capacity) {
29760
+ this.logger?.warn("fmp4 plane: subscriber fell behind — CLOSING it rather than gapping it", { meta: {
29761
+ subscriptionId: sub.id,
29762
+ tag: sub.tag,
29763
+ capacity: sub.capacity,
29764
+ delivered: sub.delivered
29765
+ } });
29766
+ this.closeSubscription(sub, "slow-consumer");
29767
+ return;
29768
+ }
29769
+ sub.queue.push({
29770
+ kind: unit.kind,
29771
+ data: unit.data,
29772
+ sequence: unit.sequence,
29773
+ isLast: false
29774
+ });
29775
+ this.wake(sub);
29776
+ }
29777
+ closeSubscription(sub, reason) {
29778
+ if (sub.closedReason !== null) return;
29779
+ sub.closedReason = reason;
29780
+ if (reason === "slow-consumer") sub.queue.length = 0;
29781
+ this.wake(sub);
29782
+ }
29783
+ wake(sub) {
29784
+ const resume = sub.wake;
29785
+ sub.wake = null;
29786
+ resume?.();
29787
+ }
29788
+ facade(sub) {
29789
+ const plane = this;
29790
+ return {
29791
+ id: sub.id,
29792
+ tag: sub.tag,
29793
+ get delivered() {
29794
+ return sub.delivered;
29795
+ },
29796
+ get closedReason() {
29797
+ return sub.closedReason;
29798
+ },
29799
+ packets: () => plane.iterate(sub),
29800
+ release: () => {
29801
+ plane.closeSubscription(sub, "released");
29802
+ plane.subscriptions.delete(sub.id);
29803
+ }
29804
+ };
29805
+ }
29806
+ async *iterate(sub) {
29807
+ if (sub.iterating) throw new Error(`fmp4 plane: subscription ${sub.tag} is already being consumed — take a second subscription`);
29808
+ sub.iterating = true;
29809
+ for (;;) {
29810
+ const next = sub.queue.shift();
29811
+ if (next === void 0) {
29812
+ if (sub.closedReason !== null) return;
29813
+ await new Promise((resolve) => {
29814
+ sub.wake = resolve;
29815
+ });
29816
+ continue;
29817
+ }
29818
+ const isLast = sub.closedReason === "ended" && sub.queue.length === 0;
29819
+ sub.delivered += 1;
29820
+ yield {
29821
+ ...next,
29822
+ isLast
29823
+ };
29824
+ if (isLast) return;
29825
+ }
29826
+ }
29827
+ };
29828
+ var DEFAULT_FIRST_UNIT_TIMEOUT_MS = 12e3;
29829
+ /** Heartbeat cadence — ~2 minutes of 4 s fragments. */
29830
+ var FRAGMENT_LOG_EVERY = 30;
29831
+ var Fmp4FragmentChild = class {
29832
+ deps;
29833
+ args;
29834
+ child = null;
29835
+ splitter = new Fmp4BoxSplitter();
29836
+ stopped = false;
29837
+ unitsOut = 0;
29838
+ activeHwAccel = null;
29839
+ constructor(deps, args) {
29840
+ this.deps = deps;
29841
+ this.args = args;
29842
+ }
29843
+ /** Spawn, and resolve once the INIT segment has been cut out of stdout. */
29844
+ async start() {
29845
+ const requested = this.args.invocation.decodeHwAccel;
29846
+ this.activeHwAccel = requested;
29847
+ try {
29848
+ await this.spawnAttempt(requested);
29849
+ return;
29850
+ } catch (err) {
29851
+ if (this.stopped) throw err;
29852
+ if (requested === null || isSoftwareDecode(requested)) throw err;
29853
+ this.deps.logger.warn("fmp4 fragment child: hardware decode produced NO fragment — retrying in SOFTWARE", {
29854
+ tags: { deviceId: this.args.deviceId },
29855
+ meta: {
29856
+ sourceId: this.args.sourceId,
29857
+ decodeHwAccel: requested,
29858
+ error: errMsg$12(err)
29859
+ }
29860
+ });
29861
+ this.killChild();
29862
+ this.splitter = new Fmp4BoxSplitter();
29863
+ this.activeHwAccel = null;
29864
+ await this.spawnAttempt(null);
29865
+ }
29866
+ }
29867
+ /** The backend the child ACTUALLY ran with — `null` for software. */
29868
+ activeDecodeHwAccel() {
29869
+ const value = this.activeHwAccel;
29870
+ return value === null || value === "none" || value === "copy" ? null : value;
29871
+ }
29872
+ /** Kill ffmpeg and end the plane. Idempotent. */
29873
+ async stop() {
29874
+ if (this.stopped) return;
29875
+ this.stopped = true;
29876
+ this.killChild();
29877
+ this.args.plane.end("the fragment child stopped");
29878
+ }
29879
+ spawnAttempt(decodeHwAccel) {
29880
+ const args = buildFfmpegArgs({
29881
+ ...this.args.invocation,
29882
+ decodeHwAccel,
29883
+ sink: {
29884
+ kind: "stdout",
29885
+ container: "mp4",
29886
+ fragmentMs: this.args.fragmentMs
29887
+ }
29888
+ });
29889
+ this.deps.logger.info("fmp4 fragment child: spawning ffmpeg", {
29890
+ tags: { deviceId: this.args.deviceId },
29891
+ meta: {
29892
+ sourceId: this.args.sourceId,
29893
+ fragmentMs: this.args.fragmentMs,
29894
+ decodeHwAccel: decodeHwAccel ?? "software",
29895
+ argv: args.join(" ")
29896
+ }
29897
+ });
29898
+ return new Promise((resolve, reject) => {
29899
+ const child = this.deps.spawnFn(this.deps.ffmpegBinaryPath, args, { stdio: [
29900
+ "ignore",
29901
+ "pipe",
29902
+ "pipe"
29903
+ ] });
29904
+ this.child = child;
29905
+ let settled = false;
29906
+ /**
29907
+ * This attempt FAILED. Set before the kill, because SIGTERM makes the
29908
+ * child exit and that exit must not be reported as a death: the retry —
29909
+ * or the caller's rejection — already owns what happens next. Without it
29910
+ * the timeout path ends the plane the software retry is about to fill,
29911
+ * and the consumer sees a stream that stopped for no reason. A "which
29912
+ * spawn is current" counter does NOT cover this: the retry has not been
29913
+ * spawned when the kill's exit arrives.
29914
+ */
29915
+ let failed = false;
29916
+ /**
29917
+ * This attempt is still the live producer: it has not failed (a failure
29918
+ * hands ownership to the retry, or to the caller's rejection) and nothing
29919
+ * has stopped the child. Those two cover every way an attempt stops being
29920
+ * current — `start` only respawns after a rejection.
29921
+ */
29922
+ const isCurrent = () => !this.stopped && !failed;
29923
+ const timeoutMs = this.deps.firstUnitTimeoutMs ?? DEFAULT_FIRST_UNIT_TIMEOUT_MS;
29924
+ const settle = (fail) => {
29925
+ if (settled) return;
29926
+ settled = true;
29927
+ clearTimeout(timer);
29928
+ if (fail) {
29929
+ failed = true;
29930
+ reject(fail);
29931
+ } else resolve();
29932
+ };
29933
+ const timer = setTimeout(() => {
29934
+ settle(/* @__PURE__ */ new Error(`fmp4 fragment child: no fragment within ${timeoutMs}ms`));
29935
+ this.killChild();
29936
+ }, timeoutMs);
29937
+ timer.unref?.();
29938
+ child.stdout?.on("data", (chunk) => {
29939
+ for (const unit of this.splitter.push(chunk)) {
29940
+ this.unitsOut += 1;
29941
+ this.args.plane.publish(unit);
29942
+ if (unit.kind === "init") {
29943
+ this.deps.logger.info("fmp4 fragment child: INIT segment cut", {
29944
+ tags: { deviceId: this.args.deviceId },
29945
+ meta: {
29946
+ sourceId: this.args.sourceId,
29947
+ bytes: unit.data.length
29948
+ }
29949
+ });
29950
+ settle();
29951
+ } else if (this.unitsOut % FRAGMENT_LOG_EVERY === 0) this.deps.logger.info("fmp4 fragment child: fragments still flowing", {
29952
+ tags: { deviceId: this.args.deviceId },
29953
+ meta: {
29954
+ sourceId: this.args.sourceId,
29955
+ unitsOut: this.unitsOut,
29956
+ bytes: unit.data.length,
29957
+ subscribers: this.args.plane.subscriberCount
29958
+ }
29959
+ });
29960
+ }
29961
+ const fault = this.splitter.fault;
29962
+ if (fault !== null) this.onFault(fault, settled, isCurrent(), settle);
29963
+ });
29964
+ child.stderr?.setEncoding("utf8");
29965
+ child.stderr?.on("data", (line) => {
29966
+ this.deps.logger.debug("fmp4 fragment child ffmpeg", {
29967
+ tags: { deviceId: this.args.deviceId },
29968
+ meta: {
29969
+ sourceId: this.args.sourceId,
29970
+ line: line.trim()
29971
+ }
29972
+ });
29973
+ });
29974
+ child.once("error", (err) => {
29975
+ if (!settled) {
29976
+ settle(err);
29977
+ return;
29978
+ }
29979
+ if (!isCurrent()) return;
29980
+ this.args.plane.end("the fragment child errored");
29981
+ this.deps.onChildExit?.(err);
29982
+ });
29983
+ child.once("exit", (code, signal) => {
29984
+ if (!settled) {
29985
+ settle(/* @__PURE__ */ new Error(`fmp4 fragment child: ffmpeg exited before any fragment (code=${code} signal=${signal})`));
29986
+ return;
29987
+ }
29988
+ if (!isCurrent()) return;
29989
+ const error = /* @__PURE__ */ new Error(`fmp4 fragment child: ffmpeg exited while live (code=${code} signal=${signal})`);
29990
+ this.deps.logger.warn("fmp4 fragment child: ffmpeg exited while live", {
29991
+ tags: { deviceId: this.args.deviceId },
29992
+ meta: {
29993
+ sourceId: this.args.sourceId,
29994
+ code,
29995
+ signal,
29996
+ unitsOut: this.unitsOut
29997
+ }
29998
+ });
29999
+ this.args.plane.end("the fragment child exited");
30000
+ this.deps.onChildExit?.(error);
30001
+ });
30002
+ });
30003
+ }
30004
+ /**
30005
+ * The byte stream stopped being splittable. Not recoverable — the splitter
30006
+ * cannot resynchronise mid-box — so the child is a corpse and every consumer
30007
+ * has to be told, loudly, with the reason.
30008
+ */
30009
+ onFault(reason, wasLive, current, settle) {
30010
+ const error = /* @__PURE__ */ new Error(`fmp4 fragment child: ${reason}`);
30011
+ this.deps.logger.error("fmp4 fragment child: the ffmpeg output stopped parsing as fMP4", {
30012
+ tags: { deviceId: this.args.deviceId },
30013
+ meta: {
30014
+ sourceId: this.args.sourceId,
30015
+ unitsOut: this.unitsOut,
30016
+ interstitial: this.splitter.discardedInterstitialTypes,
30017
+ reason
30018
+ }
30019
+ });
30020
+ this.killChild();
30021
+ settle(error);
30022
+ if (wasLive && current) {
30023
+ this.args.plane.end("the fragment child produced unsplittable output");
30024
+ this.deps.onChildExit?.(error);
30025
+ }
30026
+ }
30027
+ killChild() {
30028
+ const child = this.child;
30029
+ this.child = null;
30030
+ if (child && !child.killed) try {
30031
+ child.kill("SIGTERM");
30032
+ } catch (err) {
30033
+ this.deps.logger.warn("fmp4 fragment child: kill error", {
30034
+ tags: { deviceId: this.args.deviceId },
30035
+ meta: {
30036
+ sourceId: this.args.sourceId,
30037
+ error: errMsg$12(err)
30038
+ }
30039
+ });
30040
+ }
30041
+ }
30042
+ };
28981
30043
  //#endregion
28982
30044
  //#region src/accessory-publisher.ts
28983
30045
  /**
@@ -42634,9 +43696,18 @@ async function buildIntercom(input) {
42634
43696
  * (`proxy.motion.isDetected({})`) when the motion cap is bound.
42635
43697
  */
42636
43698
  var RESET_DEBOUNCE_MS = 5e3;
42637
- async function buildMotionSensor(bctx) {
43699
+ /**
43700
+ * @param existing - The controller's OWN `MotionSensor`, when HomeKit Secure
43701
+ * Video is advertised. HKSV derives its `EventTriggerOption.MOTION` from the
43702
+ * service the `CameraController` created (`sensors: { motion: true }`) and is
43703
+ * blind to any other one — a second MotionSensor added here would keep working
43704
+ * as a sensor in the Home app while silently triggering no recording at all.
43705
+ * `null` when recording is off, in which case this builder owns the service as
43706
+ * it always has.
43707
+ */
43708
+ async function buildMotionSensor(bctx, existing = null) {
42638
43709
  const { ctx, accessory, proxy, numericDeviceId, displayName } = bctx;
42639
- const motionService = accessory.addService(Service.MotionSensor, hapServiceName([displayName], `Camera ${numericDeviceId}`));
43710
+ const motionService = existing ?? accessory.addService(Service.MotionSensor, hapServiceName([displayName], `Camera ${numericDeviceId}`));
42640
43711
  motionService.setCharacteristic(Characteristic.MotionDetected, false);
42641
43712
  try {
42642
43713
  const detected = await proxy.motion?.isDetected({});
@@ -43032,6 +44103,814 @@ async function probe(call, label, log) {
43032
44103
  }
43033
44104
  }
43034
44105
  //#endregion
44106
+ //#region src/hksv/recording-options.ts
44107
+ /**
44108
+ * The HomeKit Secure Video ADVERTISEMENT — `CameraRecordingOptions`, derived
44109
+ * from what the fMP4 sink will actually produce for THIS camera.
44110
+ *
44111
+ * ## The rule this file exists to enforce
44112
+ *
44113
+ * Never advertise something we cannot serve. That is not a slogan here: it is
44114
+ * the diagnosis of [D50](../../../../docs/decisions/adr-0050.md) — an
44115
+ * advertised `recording` whose delegate yielded nothing put every motion-capable
44116
+ * camera into a ~12 s timeout loop every 20-60 s, all day. So every number below
44117
+ * is derived from the picked source (`recording-source.ts`) or from a measured
44118
+ * property of the sink, and none of them is a plausible-looking constant.
44119
+ *
44120
+ * ## The fragment length is the subtle one
44121
+ *
44122
+ * HKSV requires every media fragment to be **no longer** than the length the
44123
+ * controller selected. On the copy branch the fragment length is the SOURCE's
44124
+ * key-frame cadence ([D80](../../../../docs/decisions/adr-0080.md)) — we do not
44125
+ * get to choose it, we can only be honest about it. So:
44126
+ *
44127
+ * - when the camera reports its GOP (`stream-params`), the advertised length is
44128
+ * the smallest offered value that COVERS it;
44129
+ * - when it does not, we advertise the 4000 ms every HKSV camera uses and the
44130
+ * delegate warns at `warn` with `tags: { deviceId }` if the fragments that
44131
+ * actually arrive are longer.
44132
+ *
44133
+ * A camera whose GOP exceeds the longest value we offer does not advertise
44134
+ * recording at all. See {@link deriveFragmentLengthMs}.
44135
+ */
44136
+ /**
44137
+ * The prebuffer we promise. HAP's floor is 4000 ms and its documented sensible
44138
+ * range is [4000, 8000]; the plane's ring is sized from this, so the two cannot
44139
+ * disagree. Asking for more than we retain would be the same lie in the other
44140
+ * direction.
44141
+ */
44142
+ var HKSV_PREBUFFER_MS = 4e3;
44143
+ /**
44144
+ * The fragment lengths we are willing to advertise, shortest first. 4000 ms is
44145
+ * what every shipping HKSV camera uses; 8000 exists for a camera whose GOP is
44146
+ * 8 s, which is common enough on this fleet's defaults to be worth covering
44147
+ * rather than refusing.
44148
+ */
44149
+ var HKSV_FRAGMENT_LENGTHS_MS = [4e3, 8e3];
44150
+ /**
44151
+ * AAC-LC at 24 kHz mono. Fixed rather than negotiated: an fMP4 fragment carries
44152
+ * its audio in-band, so unlike the live SRTP path there is no second plane on
44153
+ * which to answer a different sample rate, and D80 records that HKSV takes AAC
44154
+ * and nothing else.
44155
+ */
44156
+ var HKSV_AUDIO_SAMPLE_RATE_HZ = 24e3;
44157
+ /**
44158
+ * The advertised fragment length for a camera whose key-frame cadence is
44159
+ * `sourceGopMs`, or `null` when no offered length covers it.
44160
+ *
44161
+ * `undefined` — the camera does not report a GOP — takes the shortest offered
44162
+ * length. That is a guess, and it is the RIGHT guess (4 s is the near-universal
44163
+ * default), but it is a guess: the delegate measures the arriving cadence and
44164
+ * says so when reality disagrees.
44165
+ */
44166
+ function deriveFragmentLengthMs(sourceGopMs) {
44167
+ const shortest = HKSV_FRAGMENT_LENGTHS_MS[0];
44168
+ if (shortest === void 0) return null;
44169
+ if (sourceGopMs === void 0 || sourceGopMs <= 0) return shortest;
44170
+ return HKSV_FRAGMENT_LENGTHS_MS.find((ms) => ms >= sourceGopMs) ?? null;
44171
+ }
44172
+ /**
44173
+ * Build the advertisement.
44174
+ *
44175
+ * ONE resolution is advertised — the one slot the recording child pulls. HAP's
44176
+ * documentation lists 1920×1080 and 1280×720 as "required to be supported", and
44177
+ * listing both when the source is only one of them is precisely the D50 failure
44178
+ * in miniature: iOS would select a configuration we then cannot deliver, on the
44179
+ * copy branch, with no encoder to resize with.
44180
+ */
44181
+ function buildRecordingOptions(input) {
44182
+ const resolution = [
44183
+ input.width,
44184
+ input.height,
44185
+ Math.max(1, Math.round(input.fps))
44186
+ ];
44187
+ return {
44188
+ prebufferLength: HKSV_PREBUFFER_MS,
44189
+ mediaContainerConfiguration: {
44190
+ type: MediaContainerType.FRAGMENTED_MP4,
44191
+ fragmentLength: input.fragmentLengthMs
44192
+ },
44193
+ video: {
44194
+ type: VideoCodecType.H264,
44195
+ parameters: {
44196
+ profiles: [
44197
+ H264Profile.BASELINE,
44198
+ H264Profile.MAIN,
44199
+ H264Profile.HIGH
44200
+ ],
44201
+ levels: [
44202
+ H264Level.LEVEL3_1,
44203
+ H264Level.LEVEL3_2,
44204
+ H264Level.LEVEL4_0
44205
+ ]
44206
+ },
44207
+ resolutions: [resolution]
44208
+ },
44209
+ audio: { codecs: [{
44210
+ type: AudioRecordingCodecType.AAC_LC,
44211
+ audioChannels: 1,
44212
+ bitrateMode: AudioBitrate.VARIABLE,
44213
+ samplerate: [AudioRecordingSamplerate.KHZ_24]
44214
+ }] }
44215
+ };
44216
+ }
44217
+ //#endregion
44218
+ //#region src/hksv/fragment-source.ts
44219
+ /**
44220
+ * How far back the prebuffer ring reaches.
44221
+ *
44222
+ * Twice {@link HKSV_PREBUFFER_MS}, and the factor is structural rather than
44223
+ * generous: the ring holds WHOLE fragments, so a window of exactly 4 s can hold
44224
+ * a single 4 s fragment that is about to age out — a trigger landing a moment
44225
+ * later would replay nothing. Two fragment lengths guarantee at least one
44226
+ * covering fragment at every instant.
44227
+ */
44228
+ var PREBUFFER_WINDOW_MS = HKSV_PREBUFFER_MS * 2;
44229
+ /**
44230
+ * The ring's hard byte ceiling, per camera.
44231
+ *
44232
+ * Measured fragment sizes on this fleet: ~145 KB for 4 s at 720p, ~3.6 MB for
44233
+ * 4 s at 4K. 16 MB covers two 4K fragments with room and bounds the exporter's
44234
+ * heap at a figure an operator can multiply by the camera count — which is the
44235
+ * number a time-only bound refuses to give.
44236
+ */
44237
+ var PREBUFFER_MAX_BYTES = 16 * 1024 * 1024;
44238
+ /** Backoff after a child that died while live. Bounded, never a tight loop. */
44239
+ var RESPAWN_BACKOFF_MS = [
44240
+ 2e3,
44241
+ 5e3,
44242
+ 15e3,
44243
+ 3e4
44244
+ ];
44245
+ var HksvFragmentSource = class {
44246
+ input;
44247
+ plane = null;
44248
+ child = null;
44249
+ stopped = false;
44250
+ starting = null;
44251
+ respawnAttempt = 0;
44252
+ respawnTimer = null;
44253
+ audioActive;
44254
+ log;
44255
+ constructor(input) {
44256
+ this.input = input;
44257
+ this.audioActive = input.audioActive;
44258
+ this.log = input.logger;
44259
+ }
44260
+ /** True once a child has produced its initialisation segment. */
44261
+ get isRunning() {
44262
+ return this.child !== null && this.plane !== null && !this.plane.isEnded;
44263
+ }
44264
+ /**
44265
+ * Spawn the child and start filling the ring. Idempotent, and concurrent
44266
+ * calls share one attempt — `updateRecordingActive(true)` and a stream
44267
+ * request can arrive in either order.
44268
+ */
44269
+ async start() {
44270
+ if (this.stopped) throw new Error("hksv fragment source: already stopped");
44271
+ if (this.isRunning) return;
44272
+ const inflight = this.starting;
44273
+ if (inflight !== null) return inflight;
44274
+ const attempt = this.spawn();
44275
+ this.starting = attempt;
44276
+ try {
44277
+ await attempt;
44278
+ } finally {
44279
+ this.starting = null;
44280
+ }
44281
+ }
44282
+ /** Stop the child, end the plane, forget the ring. Idempotent. */
44283
+ async stop(reason) {
44284
+ if (this.stopped) return;
44285
+ this.stopped = true;
44286
+ this.clearRespawn();
44287
+ this.log.info("hksv fragment source: stopping", {
44288
+ tags: { deviceId: this.input.deviceId },
44289
+ meta: {
44290
+ reason,
44291
+ brokerId: this.input.source.brokerId
44292
+ }
44293
+ });
44294
+ const child = this.child;
44295
+ this.child = null;
44296
+ if (child) await child.stop();
44297
+ this.plane?.dispose();
44298
+ this.plane = null;
44299
+ }
44300
+ /**
44301
+ * iOS turned recording audio on or off. Respawns onto the other url when it
44302
+ * genuinely changed — the fragments themselves must carry or omit the track,
44303
+ * there is nothing to strip downstream.
44304
+ */
44305
+ async setAudioActive(active) {
44306
+ if (active === this.audioActive) return;
44307
+ this.audioActive = active;
44308
+ this.log.info("hksv fragment source: RecordingAudioActive changed — respawning the child", {
44309
+ tags: { deviceId: this.input.deviceId },
44310
+ meta: {
44311
+ audioActive: active,
44312
+ brokerId: this.input.source.brokerId
44313
+ }
44314
+ });
44315
+ if (!this.isRunning) return;
44316
+ const child = this.child;
44317
+ this.child = null;
44318
+ if (child) await child.stop();
44319
+ this.plane?.dispose();
44320
+ this.plane = null;
44321
+ await this.start();
44322
+ }
44323
+ /**
44324
+ * Subscribe to the live fragments, replaying the prebuffer first.
44325
+ *
44326
+ * Returns `null` when there is no plane — the caller MUST treat that as
44327
+ * "cannot serve this recording" rather than opening an HDS stream it cannot
44328
+ * feed, which is the D50 failure exactly.
44329
+ */
44330
+ subscribe(tag) {
44331
+ const plane = this.plane;
44332
+ if (plane === null || plane.isEnded) return null;
44333
+ const stats = plane.prebufferStats();
44334
+ this.log.info("hksv fragment source: subscribing a recording stream", {
44335
+ tags: { deviceId: this.input.deviceId },
44336
+ meta: {
44337
+ tag,
44338
+ prebufferFragments: stats.fragments,
44339
+ prebufferBytes: stats.bytes,
44340
+ prebufferSpanMs: stats.spanMs
44341
+ }
44342
+ });
44343
+ return plane.subscribe({
44344
+ tag,
44345
+ withPrebuffer: true
44346
+ });
44347
+ }
44348
+ /** What the ring holds — surfaced so the delegate can log what it served. */
44349
+ prebufferSpanMs() {
44350
+ return this.plane?.prebufferStats().spanMs ?? 0;
44351
+ }
44352
+ async spawn() {
44353
+ const plane = new Fmp4FragmentPlane(this.log.child("hksv-plane"), {
44354
+ windowMs: PREBUFFER_WINDOW_MS,
44355
+ maxBytes: PREBUFFER_MAX_BYTES
44356
+ }, this.input.now ?? Date.now);
44357
+ const child = new Fmp4FragmentChild({
44358
+ logger: this.log.child("hksv-fmp4"),
44359
+ ffmpegBinaryPath: this.input.ffmpegBinaryPath,
44360
+ spawnFn: this.input.spawnFn,
44361
+ onChildExit: (error) => this.onChildExit(error)
44362
+ }, {
44363
+ sourceId: `hksv/${this.input.deviceId}`,
44364
+ deviceId: this.input.deviceId,
44365
+ fragmentMs: this.input.fragmentMs,
44366
+ invocation: this.buildInvocation(),
44367
+ plane
44368
+ });
44369
+ this.plane = plane;
44370
+ this.child = child;
44371
+ try {
44372
+ await child.start();
44373
+ this.respawnAttempt = 0;
44374
+ this.log.info("hksv fragment source: prebuffer running", {
44375
+ tags: { deviceId: this.input.deviceId },
44376
+ meta: {
44377
+ brokerId: this.input.source.brokerId,
44378
+ resolution: `${this.input.source.width}x${this.input.source.height}`,
44379
+ fragmentMs: this.input.fragmentMs,
44380
+ audioActive: this.audioActive,
44381
+ windowMs: PREBUFFER_WINDOW_MS
44382
+ }
44383
+ });
44384
+ } catch (err) {
44385
+ this.plane = null;
44386
+ this.child = null;
44387
+ plane.dispose();
44388
+ throw err;
44389
+ }
44390
+ }
44391
+ /**
44392
+ * The child died while live. The prebuffer is gone with it — and saying so is
44393
+ * the point: a source that silently stopped filling reads, from the delegate,
44394
+ * exactly like a camera nothing ever happens on.
44395
+ */
44396
+ onChildExit(error) {
44397
+ if (this.stopped) return;
44398
+ this.child = null;
44399
+ this.plane = null;
44400
+ const delay = RESPAWN_BACKOFF_MS[Math.min(this.respawnAttempt, RESPAWN_BACKOFF_MS.length - 1)];
44401
+ this.respawnAttempt += 1;
44402
+ this.log.warn("hksv fragment source: the child DIED — the prebuffer is empty until it respawns", {
44403
+ tags: { deviceId: this.input.deviceId },
44404
+ meta: {
44405
+ brokerId: this.input.source.brokerId,
44406
+ attempt: this.respawnAttempt,
44407
+ respawnInMs: delay,
44408
+ error: error.message
44409
+ }
44410
+ });
44411
+ this.clearRespawn();
44412
+ const schedule = this.input.setTimeoutFn ?? setTimeout;
44413
+ this.respawnTimer = schedule(() => {
44414
+ this.respawnTimer = null;
44415
+ if (this.stopped) return;
44416
+ this.start().catch((err) => {
44417
+ this.log.warn("hksv fragment source: respawn failed", {
44418
+ tags: { deviceId: this.input.deviceId },
44419
+ meta: {
44420
+ brokerId: this.input.source.brokerId,
44421
+ error: err instanceof Error ? err.message : String(err)
44422
+ }
44423
+ });
44424
+ });
44425
+ }, delay ?? 3e4);
44426
+ this.respawnTimer?.unref?.();
44427
+ }
44428
+ clearRespawn() {
44429
+ if (this.respawnTimer !== null) {
44430
+ clearTimeout(this.respawnTimer);
44431
+ this.respawnTimer = null;
44432
+ }
44433
+ }
44434
+ /**
44435
+ * The invocation, minus the sink the child owns.
44436
+ *
44437
+ * `kind: 'copy'` is not a preference: it is the 128× measurement, and it is
44438
+ * why `pickRecordingSource` refuses a camera whose only slots are H.265. The
44439
+ * audio IS encoded — the source mic is G.711/PCM depending on vendor and HKSV
44440
+ * takes AAC only — which the same measurement priced at 0.4 % of a core.
44441
+ */
44442
+ buildInvocation() {
44443
+ const audio = this.audioActive ? {
44444
+ kind: "encode",
44445
+ codec: "aac",
44446
+ bitrateKbps: 32,
44447
+ sampleRateHz: HKSV_AUDIO_SAMPLE_RATE_HZ,
44448
+ channels: 1
44449
+ } : { kind: "none" };
44450
+ return {
44451
+ logLevel: "error",
44452
+ decodeHwAccel: null,
44453
+ input: {
44454
+ url: this.audioActive ? this.input.source.url : this.input.source.mutedUrl,
44455
+ rtspTransport: "tcp",
44456
+ analyzeDurationUs: 1e6,
44457
+ probeSizeBytes: 1e6
44458
+ },
44459
+ video: { kind: "copy" },
44460
+ audio,
44461
+ threadCount: 0,
44462
+ outputArgs: []
44463
+ };
44464
+ }
44465
+ };
44466
+ //#endregion
44467
+ //#region src/hksv/recording-delegate.ts
44468
+ /**
44469
+ * `HDSProtocolSpecificErrorReason` is a `const enum`, so there is no reverse
44470
+ * map to index — and a bare number in the log is the difference between "iOS
44471
+ * closed it normally" and "iOS rejected our data", which is the whole reason
44472
+ * this line exists.
44473
+ */
44474
+ var HDS_REASON_NAMES = {
44475
+ [HDSProtocolSpecificErrorReason.NORMAL]: "normal",
44476
+ [HDSProtocolSpecificErrorReason.NOT_ALLOWED]: "not-allowed",
44477
+ [HDSProtocolSpecificErrorReason.BUSY]: "busy",
44478
+ [HDSProtocolSpecificErrorReason.CANCELLED]: "cancelled",
44479
+ [HDSProtocolSpecificErrorReason.UNSUPPORTED]: "unsupported",
44480
+ [HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE]: "unexpected-failure",
44481
+ [HDSProtocolSpecificErrorReason.TIMEOUT]: "timeout",
44482
+ [HDSProtocolSpecificErrorReason.BAD_DATA]: "bad-data",
44483
+ [HDSProtocolSpecificErrorReason.PROTOCOL_ERROR]: "protocol-error",
44484
+ [HDSProtocolSpecificErrorReason.INVALID_CONFIGURATION]: "invalid-configuration"
44485
+ };
44486
+ function hdsReasonName(reason) {
44487
+ return HDS_REASON_NAMES[reason] ?? `unknown(${String(reason)})`;
44488
+ }
44489
+ var HksvRecordingDelegate = class {
44490
+ input;
44491
+ active = false;
44492
+ configuration = void 0;
44493
+ source = null;
44494
+ log;
44495
+ /** The stream currently being yielded, so `closeRecordingStream` can end it. */
44496
+ open = null;
44497
+ constructor(input) {
44498
+ this.input = input;
44499
+ this.log = input.logger;
44500
+ }
44501
+ /** Test/diagnostic view — the prebuffer is running for this camera. */
44502
+ get prebufferRunning() {
44503
+ return this.source?.isRunning === true;
44504
+ }
44505
+ updateRecordingActive(active) {
44506
+ if (active === this.active) return;
44507
+ this.active = active;
44508
+ this.log.info("hksv: recording active changed", {
44509
+ tags: { deviceId: this.input.deviceId },
44510
+ meta: {
44511
+ active,
44512
+ hasConfiguration: this.configuration !== void 0
44513
+ }
44514
+ });
44515
+ this.reconcile("recording-active");
44516
+ }
44517
+ updateRecordingConfiguration(configuration) {
44518
+ this.configuration = configuration;
44519
+ if (configuration === void 0) {
44520
+ this.log.info("hksv: the selected configuration was CLEARED — stopping the prebuffer", { tags: { deviceId: this.input.deviceId } });
44521
+ this.reconcile("configuration-cleared");
44522
+ return;
44523
+ }
44524
+ const selectedMs = configuration.mediaContainerConfiguration.fragmentLength;
44525
+ this.log.info("hksv: iOS selected a recording configuration", {
44526
+ tags: { deviceId: this.input.deviceId },
44527
+ meta: {
44528
+ fragmentLengthMs: selectedMs,
44529
+ prebufferLengthMs: configuration.prebufferLength,
44530
+ resolution: configuration.videoCodec.resolution.join("x"),
44531
+ audioCodec: configuration.audioCodec.type,
44532
+ eventTriggers: configuration.eventTriggerTypes
44533
+ }
44534
+ });
44535
+ if (selectedMs < this.input.advertisedFragmentMs) this.log.warn("hksv: iOS selected a SHORTER fragment length than the source can cut", {
44536
+ tags: { deviceId: this.input.deviceId },
44537
+ meta: {
44538
+ selectedMs,
44539
+ advertisedMs: this.input.advertisedFragmentMs
44540
+ }
44541
+ });
44542
+ this.reconcile("configuration-selected");
44543
+ }
44544
+ async *handleRecordingStreamRequest(streamId, signal) {
44545
+ const source = this.source;
44546
+ if (source === null || !source.isRunning) {
44547
+ this.log.warn("hksv: recording stream requested with NO prebuffer running — refusing", {
44548
+ tags: { deviceId: this.input.deviceId },
44549
+ meta: {
44550
+ streamId,
44551
+ active: this.active,
44552
+ hasConfiguration: this.configuration !== void 0
44553
+ }
44554
+ });
44555
+ throw new HDSProtocolError(HDSProtocolSpecificErrorReason.NOT_ALLOWED);
44556
+ }
44557
+ const subscription = source.subscribe(`hksv/${this.input.deviceId}#${streamId}`);
44558
+ if (subscription === null) {
44559
+ this.log.warn("hksv: the fragment plane refused a subscription — refusing the stream", {
44560
+ tags: { deviceId: this.input.deviceId },
44561
+ meta: { streamId }
44562
+ });
44563
+ throw new HDSProtocolError(HDSProtocolSpecificErrorReason.NOT_ALLOWED);
44564
+ }
44565
+ this.open = {
44566
+ streamId,
44567
+ subscription
44568
+ };
44569
+ const startedAt = Date.now();
44570
+ const prebufferSpanMs = source.prebufferSpanMs();
44571
+ let packets = 0;
44572
+ let bytes = 0;
44573
+ let markedLast = false;
44574
+ let longestFragmentGapMs = 0;
44575
+ let lastPacketAt = startedAt;
44576
+ try {
44577
+ for await (const packet of subscription.packets()) {
44578
+ if (signal?.aborted === true) {
44579
+ this.log.info("hksv: the recording stream was aborted — ending the generator", {
44580
+ tags: { deviceId: this.input.deviceId },
44581
+ meta: {
44582
+ streamId,
44583
+ packets
44584
+ }
44585
+ });
44586
+ return;
44587
+ }
44588
+ packets += 1;
44589
+ bytes += packet.data.length;
44590
+ if (packet.kind === "fragment") {
44591
+ const now = Date.now();
44592
+ longestFragmentGapMs = Math.max(longestFragmentGapMs, now - lastPacketAt);
44593
+ lastPacketAt = now;
44594
+ }
44595
+ markedLast = markedLast || packet.isLast;
44596
+ yield {
44597
+ data: Buffer.from(packet.data),
44598
+ isLast: packet.isLast
44599
+ };
44600
+ if (packet.isLast) return;
44601
+ }
44602
+ if (!markedLast && subscription.closedReason !== "released") {
44603
+ this.log.warn("hksv: the fragment stream ended without a final packet", {
44604
+ tags: { deviceId: this.input.deviceId },
44605
+ meta: {
44606
+ streamId,
44607
+ packets,
44608
+ closedReason: subscription.closedReason,
44609
+ truncated: subscription.closedReason === "slow-consumer"
44610
+ }
44611
+ });
44612
+ if (packets === 0) throw new HDSProtocolError(HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE);
44613
+ yield {
44614
+ data: Buffer.alloc(0),
44615
+ isLast: true
44616
+ };
44617
+ }
44618
+ } finally {
44619
+ subscription.release();
44620
+ if (this.open?.streamId === streamId) this.open = null;
44621
+ const fragmentOverrun = longestFragmentGapMs > this.input.advertisedFragmentMs * 1.5;
44622
+ this.log.info("hksv: recording stream finished", {
44623
+ tags: { deviceId: this.input.deviceId },
44624
+ meta: {
44625
+ streamId,
44626
+ packets,
44627
+ bytes,
44628
+ durationMs: Date.now() - startedAt,
44629
+ prebufferSpanMs,
44630
+ longestFragmentGapMs,
44631
+ closedReason: subscription.closedReason,
44632
+ markedLast
44633
+ }
44634
+ });
44635
+ if (fragmentOverrun) this.log.warn("hksv: fragments arrived LONGER than the advertised length", {
44636
+ tags: { deviceId: this.input.deviceId },
44637
+ meta: {
44638
+ longestFragmentGapMs,
44639
+ advertisedMs: this.input.advertisedFragmentMs
44640
+ }
44641
+ });
44642
+ }
44643
+ }
44644
+ acknowledgeStream(streamId) {
44645
+ this.log.info("hksv: iOS acknowledged the end of stream — the clip landed", {
44646
+ tags: { deviceId: this.input.deviceId },
44647
+ meta: { streamId }
44648
+ });
44649
+ }
44650
+ closeRecordingStream(streamId, reason) {
44651
+ this.log.info("hksv: the recording stream was closed by the controller", {
44652
+ tags: { deviceId: this.input.deviceId },
44653
+ meta: {
44654
+ streamId,
44655
+ reason: reason === void 0 ? "connection-closed" : hdsReasonName(reason)
44656
+ }
44657
+ });
44658
+ const open = this.open;
44659
+ if (open?.streamId === streamId) {
44660
+ open.subscription.release();
44661
+ this.open = null;
44662
+ }
44663
+ }
44664
+ /** Tear the prebuffer down — the accessory is being unexposed. */
44665
+ async dispose() {
44666
+ this.open?.subscription.release();
44667
+ this.open = null;
44668
+ const source = this.source;
44669
+ this.source = null;
44670
+ if (source) await source.stop("accessory disposed");
44671
+ }
44672
+ /**
44673
+ * Start the prebuffer when iOS wants recording AND has chosen how, stop it
44674
+ * otherwise. Called from every state edge rather than each edge deciding for
44675
+ * itself: the two characteristics arrive in an order hap-nodejs explicitly
44676
+ * does not guarantee, and a per-edge decision has to re-derive the same
44677
+ * conjunction in two places.
44678
+ */
44679
+ async reconcile(trigger) {
44680
+ if (!(this.active && this.configuration !== void 0)) {
44681
+ const source = this.source;
44682
+ this.source = null;
44683
+ if (source) await source.stop(`recording no longer wanted (${trigger})`);
44684
+ return;
44685
+ }
44686
+ const configuration = this.configuration;
44687
+ if (configuration === void 0) return;
44688
+ const audioActive = this.input.isAudioActive();
44689
+ const existing = this.source;
44690
+ if (existing !== null) {
44691
+ await existing.setAudioActive(audioActive);
44692
+ if (!existing.isRunning) await existing.start();
44693
+ return;
44694
+ }
44695
+ const source = this.input.createSource({
44696
+ fragmentMs: configuration.mediaContainerConfiguration.fragmentLength,
44697
+ audioActive
44698
+ });
44699
+ this.source = source;
44700
+ try {
44701
+ await source.start();
44702
+ } catch (err) {
44703
+ this.source = null;
44704
+ this.log.error("hksv: the prebuffer FAILED to start — this camera will record nothing", {
44705
+ tags: { deviceId: this.input.deviceId },
44706
+ meta: {
44707
+ trigger,
44708
+ error: err instanceof Error ? err.message : String(err)
44709
+ }
44710
+ });
44711
+ }
44712
+ }
44713
+ };
44714
+ //#endregion
44715
+ //#region src/hksv/recording-source.ts
44716
+ /** The tallest frame the recording path will hold in its prebuffer. */
44717
+ var MAX_RECORDING_HEIGHT = 1080;
44718
+ /** HKSV takes H.264 only — AAC audio and H.264 video, no negotiation. */
44719
+ var RECORDABLE_CODEC = "h264";
44720
+ /**
44721
+ * Pick the slot the recording child pulls.
44722
+ *
44723
+ * Deliberately NOT `pickPreferredRtspEntry`: that picker resolves the operator's
44724
+ * LIVE preference and, on `auto`, steers by the resolution iOS negotiated for a
44725
+ * live session — neither is a fact about recording, and on 615 it selects `mid`,
44726
+ * a 10 fps slot. Recording has one criterion, applied here and nowhere else:
44727
+ * the largest copyable frame that does not exceed {@link MAX_RECORDING_HEIGHT}.
44728
+ */
44729
+ function pickRecordingSource(entries) {
44730
+ const enabled = entries.filter((e) => e.enabled);
44731
+ if (enabled.length === 0) return {
44732
+ ok: false,
44733
+ refusal: "no-enabled-stream"
44734
+ };
44735
+ const h264 = enabled.filter((e) => normaliseCodec(e.codec) === RECORDABLE_CODEC);
44736
+ if (h264.length === 0) return {
44737
+ ok: false,
44738
+ refusal: "no-h264-stream"
44739
+ };
44740
+ const sized = h264.filter(hasUsableResolution);
44741
+ if (sized.length === 0) return {
44742
+ ok: false,
44743
+ refusal: "no-resolution"
44744
+ };
44745
+ const withinCeiling = sized.filter((e) => height(e) <= MAX_RECORDING_HEIGHT);
44746
+ const best = [...withinCeiling.length > 0 ? withinCeiling : sized].sort((a, b) => withinCeiling.length > 0 ? height(b) - height(a) : height(a) - height(b))[0];
44747
+ if (best === void 0 || best.resolution === void 0) return {
44748
+ ok: false,
44749
+ refusal: "no-resolution"
44750
+ };
44751
+ return {
44752
+ ok: true,
44753
+ source: {
44754
+ brokerId: best.brokerId,
44755
+ profile: best.profile ?? best.brokerId,
44756
+ url: best.url,
44757
+ mutedUrl: best.mutedUrl,
44758
+ width: best.resolution.width,
44759
+ height: best.resolution.height
44760
+ }
44761
+ };
44762
+ }
44763
+ /** A one-line reason for the log — silence about a withdrawn service reads as a bug. */
44764
+ function refusalReason(refusal) {
44765
+ switch (refusal) {
44766
+ case "no-enabled-stream": return "the camera has no enabled RTSP profile";
44767
+ case "no-h264-stream": return "every enabled profile is H.265 — HKSV takes H.264 only, and a permanent transcode costs 128x a copy";
44768
+ case "no-resolution": return "no enabled profile declares a resolution, so nothing honest could be advertised";
44769
+ }
44770
+ }
44771
+ function height(entry) {
44772
+ return entry.resolution?.height ?? 0;
44773
+ }
44774
+ function hasUsableResolution(entry) {
44775
+ const r = entry.resolution;
44776
+ return r !== void 0 && r.width > 0 && r.height > 0;
44777
+ }
44778
+ /** Publishers spell H.265 four ways; the same normalisation the broker uses. */
44779
+ function normaliseCodec(codec) {
44780
+ return (codec ?? "").toLowerCase().replace(/[.\s-]/g, "");
44781
+ }
44782
+ //#endregion
44783
+ //#region src/hksv/build-recording.ts
44784
+ /**
44785
+ * Assemble HomeKit Secure Video for one camera — the ADVERTISEMENT and the
44786
+ * DELEGATE, together, or neither.
44787
+ *
44788
+ * That pairing is the whole rule and it is why nothing shipped for HKSV before
44789
+ * this: `recording` is optional on `CameraControllerOptions`, and passing it IS
44790
+ * the entire user-visible change. There is no "phase 1 behind a flag" for an
44791
+ * advertisement — either iOS is offered a recording toggle backed by a delegate
44792
+ * that yields real fragments, or the services are not on the accessory at all
44793
+ * ([D50](../../../../docs/decisions/adr-0050.md)).
44794
+ *
44795
+ * So this returns `null` for every reason a camera cannot record, and each of
44796
+ * them is logged at `info`/`warn` with `tags: { deviceId }`. A withdrawn
44797
+ * capability that says nothing is indistinguishable from a bug — and on this
44798
+ * surface the operator's first question is always "why does 617 have it and 615
44799
+ * not?".
44800
+ */
44801
+ /**
44802
+ * The ffmpeg on `PATH`, exactly as the live streaming path resolves it
44803
+ * (`camera-streams.ts` spawns `'ffmpeg'`). One resolution per addon, not two.
44804
+ */
44805
+ var FFMPEG_BINARY = "ffmpeg";
44806
+ /** Fallback when nothing measured a rate for the picked slot. */
44807
+ var ASSUMED_RECORDING_FPS = 15;
44808
+ async function buildHksvRecording(input) {
44809
+ const { bctx } = input;
44810
+ const { ctx, numericDeviceId } = bctx;
44811
+ const log = ctx.logger.withTags({ deviceId: numericDeviceId });
44812
+ const entries = await readProfileEntries(bctx);
44813
+ if (entries === null) {
44814
+ log.warn("export-hap: HKSV withheld — could not read the camera profiles", {});
44815
+ return null;
44816
+ }
44817
+ const choice = pickRecordingSource(entries);
44818
+ if (!choice.ok) {
44819
+ log.info("export-hap: HKSV withheld — no recordable stream", { meta: {
44820
+ refusal: choice.refusal,
44821
+ reason: refusalReason(choice.refusal)
44822
+ } });
44823
+ return null;
44824
+ }
44825
+ const source = choice.source;
44826
+ const gopMs = await readSourceGopMs(bctx, source.width, source.height);
44827
+ const fragmentLengthMs = deriveFragmentLengthMs(gopMs);
44828
+ if (fragmentLengthMs === null) {
44829
+ log.warn("export-hap: HKSV withheld — the camera key-frame interval is longer than any fragment length we advertise", { meta: {
44830
+ gopMs,
44831
+ brokerId: source.brokerId
44832
+ } });
44833
+ return null;
44834
+ }
44835
+ const fps = resolveFps(input.fpsByProfile, source.profile);
44836
+ const options = buildRecordingOptions({
44837
+ width: source.width,
44838
+ height: source.height,
44839
+ fps,
44840
+ fragmentLengthMs
44841
+ });
44842
+ const delegate = new HksvRecordingDelegate({
44843
+ logger: log,
44844
+ deviceId: numericDeviceId,
44845
+ isAudioActive: input.isAudioActive,
44846
+ advertisedFragmentMs: fragmentLengthMs,
44847
+ createSource: ({ fragmentMs, audioActive }) => new HksvFragmentSource({
44848
+ logger: log,
44849
+ deviceId: numericDeviceId,
44850
+ ffmpegBinaryPath: FFMPEG_BINARY,
44851
+ spawnFn: spawn,
44852
+ source,
44853
+ fragmentMs,
44854
+ audioActive
44855
+ })
44856
+ });
44857
+ log.info("export-hap: HKSV ADVERTISED — recording is offered for this camera", { meta: {
44858
+ brokerId: source.brokerId,
44859
+ profile: source.profile,
44860
+ resolution: `${source.width}x${source.height}`,
44861
+ fps,
44862
+ fragmentLengthMs,
44863
+ sourceGopMs: gopMs ?? "unknown"
44864
+ } });
44865
+ return {
44866
+ options,
44867
+ delegate,
44868
+ dispose: () => delegate.dispose()
44869
+ };
44870
+ }
44871
+ /** `cameraStreams.getProfileRtspEntries`, or `null` when the cap is unreachable. */
44872
+ async function readProfileEntries(bctx) {
44873
+ try {
44874
+ return await bctx.proxy.cameraStreams?.getProfileRtspEntries({}) ?? null;
44875
+ } catch {
44876
+ return null;
44877
+ }
44878
+ }
44879
+ /**
44880
+ * The camera's own key-frame interval in ms, from `stream-params`, matched to
44881
+ * the picked slot BY RESOLUTION.
44882
+ *
44883
+ * By resolution and not by name on purpose: `stream-params` names its profiles
44884
+ * `main`/`sub`/`ext` while the broker names its slots `high`/`mid`/`low`, and
44885
+ * on 615 `ext` is the 1280×720 slot the broker calls `mid` — a name-based match
44886
+ * would silently read the 4K slot's GOP for a 720p recording.
44887
+ *
44888
+ * `undefined` when the cap is not bound, which is most non-Hikvision providers.
44889
+ */
44890
+ async function readSourceGopMs(bctx, width, height) {
44891
+ try {
44892
+ const status = await bctx.proxy.streamParams?.getStatus({});
44893
+ if (!status) return void 0;
44894
+ for (const profile of [
44895
+ status.main,
44896
+ status.sub,
44897
+ status.ext
44898
+ ]) {
44899
+ if (!profile) continue;
44900
+ if (profile.width !== width || profile.height !== height) continue;
44901
+ const { gop, framerate } = profile;
44902
+ if (gop === void 0 || gop <= 0 || framerate <= 0) return void 0;
44903
+ return Math.round(gop / framerate * 1e3);
44904
+ }
44905
+ return;
44906
+ } catch {
44907
+ return;
44908
+ }
44909
+ }
44910
+ function resolveFps(fpsByProfile, profile) {
44911
+ return fpsByProfile.get(profile)?.fps ?? ASSUMED_RECORDING_FPS;
44912
+ }
44913
+ //#endregion
43035
44914
  //#region src/mappers/builders/child-switch.ts
43036
44915
  /**
43037
44916
  * Child-switch builder — turns a camstack accessory child device (siren,
@@ -43237,19 +45116,39 @@ async function buildCameraAccessory(input) {
43237
45116
  displayName,
43238
45117
  options
43239
45118
  };
43240
- const streams = buildCameraStreamingDelegate(bctx, await probeAdvertisedVideoProfile(bctx));
45119
+ const advertisedVideo = await probeAdvertisedVideoProfile(bctx);
45120
+ const streams = buildCameraStreamingDelegate(bctx, advertisedVideo);
43241
45121
  const handles = [];
43242
45122
  if (capNames.has("intercom")) handles.push(await buildIntercom({
43243
45123
  bctx,
43244
45124
  streamingOptions: streams.streamingOptions
43245
45125
  }));
45126
+ const recordingEnabled = options.hapDeviceSettings.hksvRecording === true;
45127
+ let recordingAudioActive = true;
45128
+ const recording = recordingEnabled ? await buildHksvRecording({
45129
+ bctx,
45130
+ fpsByProfile: advertisedVideo.fpsByProfile,
45131
+ isAudioActive: () => recordingAudioActive
45132
+ }) : null;
43246
45133
  const controller = new (isDoorbell ? DoorbellController : CameraController)({
43247
45134
  delegate: streams.delegate,
43248
45135
  streamingOptions: streams.streamingOptions,
43249
- cameraStreamCount: 2
45136
+ cameraStreamCount: 2,
45137
+ ...recording === null ? {} : { recording },
45138
+ ...recording === null || !capNames.has("motion-detection") ? {} : { sensors: { motion: true } }
43250
45139
  });
43251
45140
  accessory.configureController(controller);
43252
- if (capNames.has("motion-detection")) handles.push(await buildMotionSensor(bctx));
45141
+ if (recording !== null) {
45142
+ handles.push({ dispose: () => recording.dispose() });
45143
+ const audioCharacteristic = (controller.recordingManagement?.operatingModeService)?.getCharacteristic(Characteristic.RecordingAudioActive);
45144
+ if (audioCharacteristic) {
45145
+ recordingAudioActive = audioCharacteristic.value !== 0 && audioCharacteristic.value !== false;
45146
+ audioCharacteristic.on("change", ({ newValue }) => {
45147
+ recordingAudioActive = newValue !== 0 && newValue !== false;
45148
+ });
45149
+ }
45150
+ }
45151
+ if (capNames.has("motion-detection")) handles.push(await buildMotionSensor(bctx, recording === null ? null : controller.motionService ?? null));
43253
45152
  if (isDoorbell && controller instanceof DoorbellController) handles.push(await buildDoorbell({
43254
45153
  bctx,
43255
45154
  controller
@@ -43494,7 +45393,10 @@ function syncStateToJson(map) {
43494
45393
  * intercom upload bridge, HomeKit Secure Video, recording, native
43495
45394
  * H.264 stream tap (currently uses RTSP + ffmpeg copy).
43496
45395
  */
43497
- var DEFAULT_DEVICE_SETTINGS = { streamPreference: "auto" };
45396
+ var DEFAULT_DEVICE_SETTINGS = {
45397
+ streamPreference: "auto",
45398
+ hksvRecording: false
45399
+ };
43498
45400
  var HAP_STREAM_PREFERENCE_OPTIONS = [
43499
45401
  {
43500
45402
  value: "auto",
@@ -43769,7 +45671,10 @@ var ExportHapAddon = class extends BaseAddon {
43769
45671
  options: {
43770
45672
  ptzPulseMs: this.config.ptzPulseMs,
43771
45673
  decodeMemos: this.decodeMemos,
43772
- hapDeviceSettings: { streamPreference: entrySettings.streamPreference ?? "auto" }
45674
+ hapDeviceSettings: {
45675
+ streamPreference: entrySettings.streamPreference ?? "auto",
45676
+ hksvRecording: entrySettings.hksvRecording === true
45677
+ }
43773
45678
  }
43774
45679
  });
43775
45680
  for (const accessory of mapper.accessories) await publishStandalone(accessory, {
@@ -44044,6 +45949,7 @@ var ExportHapAddon = class extends BaseAddon {
44044
45949
  const enabled = entry !== null;
44045
45950
  const enabledKey = `hap:${deviceId}:enabled`;
44046
45951
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
45952
+ const hksvKey = `hap:${deviceId}:hksvRecording`;
44047
45953
  const mapper = this.exposed.get(String(deviceId)) ?? null;
44048
45954
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
44049
45955
  const name = entry?.displayName ?? `Device ${deviceId}`;
@@ -44111,6 +46017,19 @@ var ExportHapAddon = class extends BaseAddon {
44111
46017
  equals: true
44112
46018
  },
44113
46019
  immediate: true
46020
+ },
46021
+ {
46022
+ type: "boolean",
46023
+ key: hksvKey,
46024
+ label: "HomeKit recording (Secure Video)",
46025
+ 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).",
46026
+ style: "switch",
46027
+ value: settings.hksvRecording === true,
46028
+ showWhen: {
46029
+ field: enabledKey,
46030
+ equals: true
46031
+ },
46032
+ immediate: true
44114
46033
  }
44115
46034
  ]
44116
46035
  }]
@@ -44135,12 +46054,15 @@ var ExportHapAddon = class extends BaseAddon {
44135
46054
  const wasEnabled = this.exposed.has(deviceIdStr);
44136
46055
  const enabledKey = `hap:${deviceId}:enabled`;
44137
46056
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
46057
+ const hksvKey = `hap:${deviceId}:hksvRecording`;
44138
46058
  const enabledValue = enabledKey in patch ? Boolean(patch[enabledKey]) : wasEnabled;
44139
46059
  const streamPreferenceRaw = streamPreferenceKey in patch ? patch[streamPreferenceKey] : current?.settings?.streamPreference;
44140
46060
  const streamPreference = typeof streamPreferenceRaw === "string" && streamPreferenceRaw.trim().length > 0 ? streamPreferenceRaw : "auto";
46061
+ const hksvRecording = hksvKey in patch ? Boolean(patch[hksvKey]) : current?.settings?.hksvRecording === true;
44141
46062
  const nextSettings = {
44142
46063
  ...current?.settings ?? DEFAULT_DEVICE_SETTINGS,
44143
- streamPreference
46064
+ streamPreference,
46065
+ hksvRecording
44144
46066
  };
44145
46067
  if (!enabledValue) {
44146
46068
  if (wasEnabled) await this.unexposeDevice(deviceIdStr);
@@ -44152,17 +46074,24 @@ var ExportHapAddon = class extends BaseAddon {
44152
46074
  return { success: true };
44153
46075
  }
44154
46076
  const currentPref = current?.settings?.streamPreference ?? "auto";
46077
+ const currentHksv = current?.settings?.hksvRecording === true;
44155
46078
  await this.updateEntrySettings(deviceIdStr, nextSettings);
44156
- if (currentPref !== streamPreference) {
44157
- log.info("export-hap: streamPreference changed — refreshing accessory", { meta: {
44158
- from: currentPref,
44159
- to: streamPreference
46079
+ if (currentPref !== streamPreference || currentHksv !== hksvRecording) {
46080
+ log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
46081
+ streamPreference: {
46082
+ from: currentPref,
46083
+ to: streamPreference
46084
+ },
46085
+ hksvRecording: {
46086
+ from: currentHksv,
46087
+ to: hksvRecording
46088
+ }
44160
46089
  } });
44161
46090
  try {
44162
46091
  await this.unexposeDevice(deviceIdStr, { clearPairing: false });
44163
46092
  await this.exposeDevice(deviceIdStr);
44164
46093
  } catch (err) {
44165
- log.warn("export-hap: failed to refresh accessory after streamPreference change", { meta: { error: errMsg(err) } });
46094
+ log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });
44166
46095
  }
44167
46096
  }
44168
46097
  return { success: true };