@camstack/addon-export-hap 1.2.113 → 1.2.114

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.
@@ -84,7 +84,7 @@ function carryForward(base, existing, keys) {
84
84
  return out;
85
85
  }
86
86
  //#endregion
87
- //#region ../types/dist/event-category-ZyX6jcse.mjs
87
+ //#region ../types/dist/event-category-BVDXG4tB.mjs
88
88
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
89
89
  EventCategory["SystemBoot"] = "system.boot";
90
90
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -701,6 +701,20 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
701
701
  * pull-reconcile from the provider's `getStatus` on reconnect. */
702
702
  EventCategory["MeshNetworkChanged"] = "network.mesh.changed";
703
703
  EventCategory["BackupCompleted"] = "backup.completed";
704
+ /**
705
+ * A whole backup RUN finished — every destination attempted, win or lose.
706
+ *
707
+ * `backup.completed` fires once per DESTINATION, which is the right grain for
708
+ * a progress UI and the wrong one for a notification: an operator with three
709
+ * destinations would be told three times. And a run where two of three
710
+ * destinations succeeded is not a clean success — a single "backup
711
+ * completed" that hid the failed one would be a lie, so the count of each is
712
+ * carried here and the message says both.
713
+ *
714
+ * Emitted by the backup orchestrator only after the destination loop, so a
715
+ * run that dies during the BUILD phase produces no completion at all.
716
+ */
717
+ EventCategory["BackupRunCompleted"] = "backup.run-completed";
704
718
  EventCategory["BackupRestored"] = "backup.restored";
705
719
  EventCategory["NotificationDispatched"] = "notification.dispatched";
706
720
  EventCategory["NotificationFailed"] = "notification.failed";
@@ -5431,7 +5445,7 @@ var ZodIssueCode = {
5431
5445
  var ZodFirstPartyTypeKind;
5432
5446
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5433
5447
  //#endregion
5434
- //#region ../types/dist/sleep-DBKu2-U5.mjs
5448
+ //#region ../types/dist/sleep-DEuj7E3j.mjs
5435
5449
  /**
5436
5450
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5437
5451
  * window to float samples (D455).
@@ -8059,6 +8073,28 @@ var EncodeProfileSchema = object({
8059
8073
  outputArgs: array(string()).optional()
8060
8074
  });
8061
8075
  /**
8076
+ * THE target rule: which of two sizes serves a consumer better.
8077
+ *
8078
+ * "Prefer at or above the target so the consumer downscales instead of
8079
+ * upscaling; among those the SMALLEST, because the extra pixels are thrown
8080
+ * away and the decode is not; among the rest the LARGEST, because it is the
8081
+ * closest we can get." One sentence, and until now it was written twice — once
8082
+ * here in lines, once in `stream-selection.ts` in pixels, for the same two
8083
+ * exporters. The two agreed, which is luck, not a property.
8084
+ *
8085
+ * The `size` is whatever measure the caller ranks by: the cap ranks by LINES
8086
+ * (a consumer's requirement is stated in p), the RTSP picker by PIXELS (it
8087
+ * compares entries of possibly different aspect). The rule is the same either
8088
+ * way and the measure is the caller's business.
8089
+ *
8090
+ * Returns a sort delta: negative when `a` should come first.
8091
+ */
8092
+ function compareToTarget(a, b, target) {
8093
+ const aReaches = a >= target;
8094
+ if (aReaches !== b >= target) return aReaches ? -1 : 1;
8095
+ return aReaches ? a - b : b - a;
8096
+ }
8097
+ /**
8062
8098
  * The shape every live egress starts from: H.264 Baseline 3.1 at 720p25.
8063
8099
  * Baseline because it is the one profile every consumer in this repo decodes
8064
8100
  * (Echo, iOS, an old browser); 3.1 because that is what the SDPs advertise.
@@ -9971,6 +10007,47 @@ var LogChannelWindowSchema = object({
9971
10007
  /** `null` = every camera. A non-empty list narrows to those numeric ids. */
9972
10008
  deviceIds: array(number().int()).readonly().nullable()
9973
10009
  });
10010
+ /**
10011
+ * Shared stream-selection picker for export addons.
10012
+ *
10013
+ * Both `addon-export-alexa` and `addon-export-hap` resolve the
10014
+ * operator's `streamPreference` setting against the broker's RTSP
10015
+ * entries before dialling a camera. Each addon used to roll its own:
10016
+ * Alexa had `pickPreferredRtspEntry` under `handlers/`, HAP had an
10017
+ * inline `"prefer /mid, then /high, then first"` chain inside its
10018
+ * camera-streams mapper. The chains drifted (Alexa honoured
10019
+ * `streamPreference`, HAP didn't; only Alexa got the smart
10020
+ * resolution-targeted auto-pick) and the cross-addon import rule
10021
+ * blocks deduping in either direction.
10022
+ *
10023
+ * Lifting the picker into `@camstack/types` lets every exporter call
10024
+ * the same code path with the consumer's target resolution baked into
10025
+ * the call site — Alexa passes 1280×720, HomeKit passes 1920×1080,
10026
+ * the picker handles the rest.
10027
+ *
10028
+ * Selection algorithm:
10029
+ * - pref === '<profile>' → profile-keyed entries (from
10030
+ * `getProfileRtspEntries`) match on `e.profile`;
10031
+ * legacy raw entries match on the brokerId
10032
+ * suffix (`brokerId` ENDS WITH `/${pref}`, shape
10033
+ * `${deviceId}/${camStreamId}`). Addons store the
10034
+ * bare profile/camStream id in their
10035
+ * `ExportDeviceSettings.streamPreference`. Falls
10036
+ * back to 'auto' when no enabled entry matches
10037
+ * either way.
10038
+ * - pref === 'auto' → when `targetResolution` is given, pick the
10039
+ * entry whose source resolution is closest to
10040
+ * it (prefer ≥ target so the consumer
10041
+ * downscales instead of upscaling). Without a
10042
+ * target, fall back to first-enabled. If no
10043
+ * entry advertises a resolution at all
10044
+ * (broker hasn't probed yet), also fall back
10045
+ * to first-enabled so cold start still serves.
10046
+ *
10047
+ * Returns `null` when nothing is publishable — callers fold that into
10048
+ * the consumer's "no stream" error (Alexa: STREAM_TYPE_UNSUPPORTED;
10049
+ * HAP: a thrown error inside `startFfmpegForSession`).
10050
+ */
9974
10051
  function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
9975
10052
  if (entries.length === 0) return null;
9976
10053
  const prefix = `${deviceId}/`;
@@ -10000,30 +10077,23 @@ function pickPreferredRtspEntry(entries, pref, deviceId, options = {}) {
10000
10077
  return toPicked(eligible[0]);
10001
10078
  }
10002
10079
  /**
10003
- * Pick the entry whose `resolution` is closest to `target`. Prefer
10004
- * entries ≥ target (downscale is cheap at the consumer; upscale is
10005
- * lossy). Among the rest pick the LARGEST still ≤ target so the
10006
- * consumer gets the best feasible quality. "Closeness" is the
10007
- * `width × height` pixel delta.
10080
+ * Pick the entry whose `resolution` is closest to `target`, by the ONE target
10081
+ * rule ({@link compareToTarget}): prefer at or above the target so the consumer
10082
+ * downscales instead of upscaling; among those the smallest; among the rest the
10083
+ * largest.
10084
+ *
10085
+ * This function used to implement that rule itself, in pixels, while
10086
+ * `rankStreams` implemented it again in lines — the same sentence written twice
10087
+ * for the same two exporters, agreeing by luck rather than by construction.
10088
+ * Only the MEASURE is this picker's own: it compares whole pixel counts because
10089
+ * its entries can differ in aspect, where the cap's requirement is stated in p.
10008
10090
  */
10009
10091
  function pickClosestResolution(entries, target) {
10010
10092
  const targetPixels = target.width * target.height;
10011
- let bestAbove;
10012
- let bestBelow;
10013
- for (const e of entries) {
10014
- if (e.resolution === void 0) continue;
10015
- const pixels = e.resolution.width * e.resolution.height;
10016
- if (pixels >= targetPixels) {
10017
- if (!bestAbove || pixels < bestAbove.pixels) bestAbove = {
10018
- entry: e,
10019
- pixels
10020
- };
10021
- } else if (!bestBelow || pixels > bestBelow.pixels) bestBelow = {
10022
- entry: e,
10023
- pixels
10024
- };
10025
- }
10026
- return bestAbove?.entry ?? bestBelow?.entry;
10093
+ return [...entries.flatMap((entry) => entry.resolution === void 0 ? [] : [{
10094
+ entry,
10095
+ pixels: entry.resolution.width * entry.resolution.height
10096
+ }])].sort((a, b) => compareToTarget(a.pixels, b.pixels, targetPixels))[0]?.entry;
10027
10097
  }
10028
10098
  var MODEL_FORMATS = [
10029
10099
  "onnx",
@@ -12211,6 +12281,58 @@ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, Broke
12211
12281
  auth: "admin"
12212
12282
  }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
12213
12283
  DeviceType.Camera;
12284
+ /**
12285
+ * The signals a device can emit to WAKE its own stream.
12286
+ *
12287
+ * A camera whose stream is built on demand sleeps until something asks for it,
12288
+ * and "something" cannot be a consumer that is merely attached — a Frigate-style
12289
+ * puller holds a session open for ever, and treating that as demand would keep
12290
+ * a battery camera awake for ever, which is the whole thing the battery is for
12291
+ * (D173). So the wake has to come from the CAMERA: an event it noticed by
12292
+ * itself, with no stream running.
12293
+ *
12294
+ * ## The vocabulary is the PROVIDER'S, not ours
12295
+ *
12296
+ * Like `consumables`, this cap declares no vocabulary of its own. A provider
12297
+ * names each signal with a `code` it chooses and a `label` an operator reads.
12298
+ * Reolink offers motion and camera-native detection; another provider may offer
12299
+ * a tamper, a doorbell press, a PIR, or something no camera in this fleet has
12300
+ * yet. A fixed enum here would mean every new signal is a framework release.
12301
+ *
12302
+ * It is deliberately NOT derived from the caps a device already binds. Whether
12303
+ * a camera CAN push firmware motion is expressed by `motionSources` containing
12304
+ * `'onboard'`, and whether it does AI on-camera by the `native-object-detection`
12305
+ * binding — but both answer "what drives the detection pipeline", which is a
12306
+ * different question from "what may wake a sleeping stream". A camera can do
12307
+ * the first and not be trusted with the second, and the operator picks per
12308
+ * camera. Two questions, two authorities.
12309
+ *
12310
+ * ## Availability is not permission
12311
+ *
12312
+ * `listSignals` says what the device CAN emit. Whether a given signal actually
12313
+ * wakes the stream is the operator's per-camera choice, held by the broker
12314
+ * alongside the cooldown — see the stream-broker cap's wake settings. A
12315
+ * provider declaring a signal is not a provider enabling it.
12316
+ */
12317
+ /** One signal a device can emit. */
12318
+ var StreamSignalSchema = object({
12319
+ /** Stable id chosen by the provider, e.g. `'motion'`, `'person'`, `'tamper'`. */
12320
+ code: string().min(1),
12321
+ /** What an operator reads in the picker. The provider's own wording. */
12322
+ label: string().min(1),
12323
+ /**
12324
+ * Whether the provider recommends this signal ON when a camera is first set
12325
+ * up. A provider knows which of its signals are cheap and reliable; an
12326
+ * operator should not have to discover that by trial. Reolink recommends
12327
+ * both of its own.
12328
+ */
12329
+ recommended: boolean()
12330
+ });
12331
+ object({
12332
+ signals: array(StreamSignalSchema),
12333
+ lastFetchedAt: number()
12334
+ });
12335
+ Object.values(DeviceType), method(_void(), array(StreamSignalSchema).readonly());
12214
12336
  /** Stream delivery format. (Relocated from the retired `streaming-engine` cap.) */
12215
12337
  var StreamFormatSchema = _enum([
12216
12338
  "webrtc",
@@ -12607,6 +12729,22 @@ var EgressTranscodeSchema = object({
12607
12729
  camStreamId: string().nullable()
12608
12730
  });
12609
12731
  method(object({
12732
+ deviceId: number().int().nonnegative(),
12733
+ /** The provider's signal code. */
12734
+ code: string().min(1),
12735
+ /** Ms epoch. Absent ⇒ now. */
12736
+ at: number().optional()
12737
+ }), object({
12738
+ /** Whether the broker acted on it, and if not, why. */
12739
+ accepted: boolean(),
12740
+ reason: _enum([
12741
+ "woke",
12742
+ "hold-extended",
12743
+ "not-enabled",
12744
+ "no-consumer",
12745
+ "unknown-code"
12746
+ ])
12747
+ }), { kind: "mutation" }), method(object({
12610
12748
  deviceId: number().int().nonnegative(),
12611
12749
  camStreamId: string().min(1),
12612
12750
  kind: CamStreamKindSchema,
@@ -12861,6 +12999,16 @@ var PickStreamRequirementsSchema = object({
12861
12999
  acceptCodecs: array(StreamCodecSchema).readonly().optional(),
12862
13000
  /** Minimum vertical resolution. Streams shorter than this are dropped. */
12863
13001
  minHeight: number().int().positive().optional(),
13002
+ /**
13003
+ * Maximum vertical resolution. Streams TALLER than this are dropped.
13004
+ *
13005
+ * A consumer can have a ceiling as real as its floor: Alexa documents
13006
+ * 480p to 1080p, and a 4K stream is as unusable to an Echo as a 360p one.
13007
+ * Without this the ceiling had to be re-implemented by every caller — and
13008
+ * one caller implementing it privately is how a second scoring authority
13009
+ * gets born.
13010
+ */
13011
+ maxHeight: number().int().positive().optional(),
12864
13012
  /** Minimum horizontal resolution. */
12865
13013
  minWidth: number().int().positive().optional(),
12866
13014
  /**
@@ -12877,7 +13025,22 @@ var PickStreamRequirementsSchema = object({
12877
13025
  * transcoded" guard: if the device is already serving the consumer's
12878
13026
  * codec end-to-end, there's nothing to optimise.
12879
13027
  */
12880
- requireSiblingCodec: array(StreamCodecSchema).readonly().optional()
13028
+ requireSiblingCodec: array(StreamCodecSchema).readonly().optional(),
13029
+ /**
13030
+ * Whether a stream the consumer CANNOT decode may still be picked, on the
13031
+ * understanding that it will be transcoded.
13032
+ *
13033
+ * Default `false` — today's behaviour, and the right one for a bypass
13034
+ * question ("is there a stream I can forward untouched?"). Set `true` to
13035
+ * ask the larger question: "what is the best stream for me, transcoding if
13036
+ * I must?" A stream that satisfies `acceptCodecs` always outranks one that
13037
+ * does not, so a passthrough is never lost to a transcode; the answer says
13038
+ * which it is in {@link PickedCamStreamSchema.transcodes}.
13039
+ *
13040
+ * This is what lets one picker serve both the bypass and the full source
13041
+ * choice, instead of a consumer scoring privately when the bypass misses.
13042
+ */
13043
+ allowTranscode: boolean().optional()
12881
13044
  }).readonly();
12882
13045
  var PickStreamPreferencesSchema = object({
12883
13046
  /**
@@ -12891,12 +13054,32 @@ var PickStreamPreferencesSchema = object({
12891
13054
  * picks the tallest stream; `'lowest'` picks the shortest (used by
12892
13055
  * memory-constrained consumers / Apple Home guest sessions).
12893
13056
  */
12894
- resolutionPreference: _enum(["highest", "lowest"]).optional()
13057
+ resolutionPreference: _enum(["highest", "lowest"]).optional(),
13058
+ /**
13059
+ * The height the consumer actually wants to DELIVER.
13060
+ *
13061
+ * Not a constraint — an ordering. With it set, the SMALLEST stream at or
13062
+ * above the target wins, and only if nothing reaches it does the tallest
13063
+ * take over. Pulling 1296 lines to draw 720 on a 1280x800 Echo panel costs
13064
+ * a decode and buys nothing, and `resolutionPreference: 'highest'` cannot
13065
+ * express that: it says "as big as possible", which is a different wish.
13066
+ *
13067
+ * Ignored when absent, so every existing caller keeps its ordering.
13068
+ */
13069
+ targetHeight: number().int().positive().optional()
12895
13070
  }).readonly();
12896
13071
  var PickedCamStreamSchema = object({
12897
13072
  camStreamId: string(),
12898
13073
  codec: string().optional(),
12899
13074
  resolution: CamStreamResolutionSchema.optional(),
13075
+ /**
13076
+ * Whether serving this stream requires a decode + re-encode.
13077
+ *
13078
+ * `false` is a stream the consumer can take as it stands. Only ever `true`
13079
+ * when the caller asked for it with `allowTranscode`, so a caller that did
13080
+ * not ask cannot be handed a cost it never agreed to pay.
13081
+ */
13082
+ transcodes: boolean(),
12900
13083
  /** One-line explanation of why this stream won — for logs / debug UI. */
12901
13084
  reason: string()
12902
13085
  });
@@ -17166,6 +17349,8 @@ var NcSystemEventKindSchema = _enum([
17166
17349
  "device-enabled",
17167
17350
  "device-battery-low",
17168
17351
  "device-battery-normal",
17352
+ "device-consumable-low",
17353
+ "device-consumable-normal",
17169
17354
  "stream-online",
17170
17355
  "stream-offline",
17171
17356
  "node-online",
@@ -17184,6 +17369,7 @@ var NcSystemEventKindSchema = _enum([
17184
17369
  "addon-updated",
17185
17370
  "server-updated",
17186
17371
  "export-completed",
17372
+ "backup-completed",
17187
17373
  "camera-online",
17188
17374
  "camera-offline",
17189
17375
  "camera-disabled",
@@ -24425,10 +24611,28 @@ DeviceType.Camera, method(object({ deviceId: number().int().nonnegative() }), ar
24425
24611
  }), boolean()), method(object({
24426
24612
  deviceId: number().int().nonnegative(),
24427
24613
  sessionId: string()
24428
- }), object({ pendingRenegotiation: object({
24429
- target: WebrtcStreamTargetSchema,
24430
- epoch: number()
24431
- }).nullable() }));
24614
+ }), object({
24615
+ pendingRenegotiation: object({
24616
+ target: WebrtcStreamTargetSchema,
24617
+ epoch: number()
24618
+ }).nullable(),
24619
+ /**
24620
+ * Whether the session still EXISTS.
24621
+ *
24622
+ * A consumer that holds a resource for the life of a session needs to
24623
+ * be able to ask, because a session does not always end the way it
24624
+ * began. Measured on this hub 2026-09-13: an Echo that got stuck never
24625
+ * sent `SessionDisconnected`, so the Alexa exporter's
24626
+ * `releaseEgressTranscode` never ran, and a 2304x1296 HEVC to 720p
24627
+ * H.264 transcode kept running for NOBODY for more than twenty
24628
+ * minutes. The WebRTC session had logged `WebRTC session closed`
24629
+ * minutes earlier — the broker knew; the holder had no way to ask.
24630
+ *
24631
+ * `false` for a session id the provider has never heard of, which is
24632
+ * the same answer as "it ended": either way nothing is holding it up.
24633
+ */
24634
+ alive: boolean()
24635
+ }));
24432
24636
  object({
24433
24637
  /** All accessory children of the parent. */
24434
24638
  childDeviceIds: array(number()).readonly(),
@@ -36993,6 +37197,12 @@ Object.freeze({
36993
37197
  addonId: null,
36994
37198
  access: "create"
36995
37199
  },
37200
+ "streamBroker.reportStreamSignal": {
37201
+ capName: "stream-broker",
37202
+ capScope: "system",
37203
+ addonId: null,
37204
+ access: "create"
37205
+ },
36996
37206
  "streamBroker.restartProfile": {
36997
37207
  capName: "stream-broker",
36998
37208
  capScope: "system",
@@ -37077,6 +37287,12 @@ Object.freeze({
37077
37287
  addonId: null,
37078
37288
  access: "create"
37079
37289
  },
37290
+ "streamSignals.listSignals": {
37291
+ capName: "stream-signals",
37292
+ capScope: "device",
37293
+ addonId: null,
37294
+ access: "view"
37295
+ },
37080
37296
  "switch.setState": {
37081
37297
  capName: "switch",
37082
37298
  capScope: "device",
@@ -39449,6 +39665,11 @@ Object.freeze({
39449
39665
  form: "single",
39450
39666
  optional: false
39451
39667
  }],
39668
+ "streamBroker.reportStreamSignal": [{
39669
+ name: "deviceId",
39670
+ form: "single",
39671
+ optional: false
39672
+ }],
39452
39673
  "streamBroker.restartProfile": [{
39453
39674
  name: "deviceId",
39454
39675
  form: "single",
@@ -87070,6 +87291,123 @@ function clearPairingFiles(accessoryUuid, logger) {
87070
87291
  } });
87071
87292
  }
87072
87293
  }
87294
+ /**
87295
+ * Whether this device's accessory belongs on the bridge.
87296
+ *
87297
+ * A camera is `false` whatever the operator picked — the answer is HomeKit's,
87298
+ * not ours, and an operator who switched it on before the field was gated must
87299
+ * not end up with a camera nobody can pair.
87300
+ *
87301
+ * Absent means ON for everything else: the field did not exist for entries
87302
+ * persisted before it, and the default the operator asked for is the bridge.
87303
+ */
87304
+ function shouldBridge(input) {
87305
+ if (input.mapperKind === "camera") return false;
87306
+ return input.useBridge !== false;
87307
+ }
87308
+ /** Whether the bridge has room for one more. */
87309
+ function bridgeHasRoom(current) {
87310
+ return current < 149;
87311
+ }
87312
+ //#endregion
87313
+ //#region src/bridge-host.ts
87314
+ /**
87315
+ * THE bridge accessory — one per node, created on demand, holding every
87316
+ * non-camera accessory the operator routed onto it.
87317
+ *
87318
+ * One mDNS advertisement, one HAP connection, one pairing, N accessories
87319
+ * inside. The alternative — what this addon did until now — gives every
87320
+ * switch, sensor and alarm panel its own port, its own advertisement and its
87321
+ * own "Add Accessory" in the Home app. Cameras stay standalone, because
87322
+ * HomeKit forbids bridging them (`bridge-policy.ts`).
87323
+ *
87324
+ * ONE bridge, deliberately. The ceiling is 149 accessories
87325
+ * ({@link MAX_BRIDGED_ACCESSORIES}) and this hub exposes 46 devices in total,
87326
+ * cameras included; a second bridge is a thing to build when the count
87327
+ * approaches the ceiling, not before, and the refusal at the ceiling is
87328
+ * explicit rather than a library throw.
87329
+ *
87330
+ * The bridge is LAZY: it is published the first time an accessory needs it,
87331
+ * so a fleet of nothing but cameras advertises no empty bridge. It is not
87332
+ * unpublished when the last accessory leaves — an unpublish would drop the
87333
+ * pairing record the operator already entered a code for, and an empty bridge
87334
+ * in the Home app is a far smaller cost than a re-pair.
87335
+ */
87336
+ var BridgeHost = class {
87337
+ opts;
87338
+ bridge = null;
87339
+ published = false;
87340
+ constructor(opts) {
87341
+ this.opts = opts;
87342
+ }
87343
+ /** The live bridge accessory, or `null` before anything needed one. */
87344
+ get accessory() {
87345
+ return this.bridge;
87346
+ }
87347
+ /** How many accessories are riding it right now. */
87348
+ get size() {
87349
+ return this.bridge?.bridgedAccessories.length ?? 0;
87350
+ }
87351
+ /**
87352
+ * Put an accessory on the bridge, publishing the bridge if this is the
87353
+ * first. Returns `false` — without throwing, and having logged — when the
87354
+ * bridge is full: the caller then falls back to standalone, which is worse
87355
+ * for the operator and still works.
87356
+ */
87357
+ async add(accessory) {
87358
+ const bridge = this.ensure();
87359
+ if (!bridgeHasRoom(bridge.bridgedAccessories.length)) {
87360
+ this.opts.logger.warn("export-hap: the bridge is FULL — publishing standalone instead", { meta: {
87361
+ uuid: accessory.UUID,
87362
+ bridged: bridge.bridgedAccessories.length,
87363
+ max: 149
87364
+ } });
87365
+ return false;
87366
+ }
87367
+ bridge.addBridgedAccessory(accessory);
87368
+ await this.publishOnce();
87369
+ return true;
87370
+ }
87371
+ /** Take an accessory off the bridge. A bridged accessory is never
87372
+ * `unpublish`ed — it has no server of its own. */
87373
+ remove(accessory) {
87374
+ if (this.bridge === null) return;
87375
+ if (!this.bridge.bridgedAccessories.some((a) => a.UUID === accessory.UUID)) return;
87376
+ this.bridge.removeBridgedAccessory(accessory, false);
87377
+ }
87378
+ /** Whether this accessory is currently on the bridge. */
87379
+ holds(accessory) {
87380
+ return this.bridge?.bridgedAccessories.some((a) => a.UUID === accessory.UUID) ?? false;
87381
+ }
87382
+ /** Tear the bridge down — process shutdown only. */
87383
+ async dispose() {
87384
+ if (this.bridge === null || !this.published) return;
87385
+ await unpublishAccessory(this.bridge, this.opts.logger);
87386
+ this.published = false;
87387
+ }
87388
+ ensure() {
87389
+ if (this.bridge !== null) return this.bridge;
87390
+ const bridge = new import_dist.Accessory(this.opts.displayName, this.opts.uuid);
87391
+ bridge.category = import_dist.Categories.BRIDGE;
87392
+ this.bridge = bridge;
87393
+ return bridge;
87394
+ }
87395
+ async publishOnce() {
87396
+ if (this.published || this.bridge === null) return;
87397
+ if (this.opts.publish !== void 0) await this.opts.publish(this.bridge, this.opts.pincode);
87398
+ else await publishStandalone(this.bridge, {
87399
+ pincode: this.opts.pincode,
87400
+ port: 0,
87401
+ bind: this.opts.bind,
87402
+ logger: this.opts.logger
87403
+ });
87404
+ this.published = true;
87405
+ this.opts.logger.info("export-hap: the bridge is published", { meta: {
87406
+ displayName: this.opts.displayName,
87407
+ uuid: this.opts.uuid
87408
+ } });
87409
+ }
87410
+ };
87073
87411
  //#endregion
87074
87412
  //#region src/hap-setup-uri.ts
87075
87413
  function errMsg$15(e) {
@@ -99477,6 +99815,19 @@ async function startFfmpegForSession(bctx, session, sessionId, video, advertised
99477
99815
  } });
99478
99816
  throw new Error(`export-hap: no enabled RTSP entries for device ${numericDeviceId}`);
99479
99817
  }
99818
+ if (fit.kind === "transcode" && bctx.options.hapDeviceSettings?.allowTranscode === false) {
99819
+ startLog.warn("export-hap: stream start REFUSED — transcoding is switched off", {
99820
+ tags: { deviceId: numericDeviceId },
99821
+ meta: {
99822
+ sessionId,
99823
+ streamPreference: pref,
99824
+ negotiated: `${video.width}x${video.height}`,
99825
+ pickedProfile: fit.profile,
99826
+ pickedCodec: fit.picked.codec ?? "unknown"
99827
+ }
99828
+ });
99829
+ throw new Error(`export-hap: device ${numericDeviceId} needs a transcode and transcoding is switched off`);
99830
+ }
99480
99831
  const picked = fit.picked;
99481
99832
  const rtspUrl = picked.url;
99482
99833
  const slot = brokerStreams.find((s) => s.profile === fit.profile);
@@ -102596,6 +102947,12 @@ var ExportHapAddon = class extends BaseAddon {
102596
102947
  * hardware init.
102597
102948
  */
102598
102949
  decodeMemos = createHapDecodeMemos();
102950
+ /**
102951
+ * THE bridge. Lazily created and published the first time a non-camera
102952
+ * accessory needs it; never torn down while the addon runs, because an
102953
+ * unpublish would drop a pairing the operator already entered a code for.
102954
+ */
102955
+ bridgeHost = null;
102599
102956
  constructor() {
102600
102957
  super({ ...DEFAULT_CONFIG });
102601
102958
  }
@@ -102603,6 +102960,13 @@ var ExportHapAddon = class extends BaseAddon {
102603
102960
  const identity = await this.ensureIdentity();
102604
102961
  this.pincode = identity.pincode;
102605
102962
  this.bind = this.config.interfaceName || void 0;
102963
+ this.bridgeHost = new BridgeHost({
102964
+ displayName: this.config.bridgeName,
102965
+ uuid: identity.uuid,
102966
+ pincode: identity.pincode,
102967
+ bind: this.bind,
102968
+ logger: this.ctx.logger
102969
+ });
102606
102970
  try {
102607
102971
  await initHapStorage(node_path.join(this.ctx.dataDir, "hap-store"));
102608
102972
  } catch (err) {
@@ -102631,6 +102995,7 @@ var ExportHapAddon = class extends BaseAddon {
102631
102995
  }
102632
102996
  this.ctx.addDisposer(async () => {
102633
102997
  await this.detachAll();
102998
+ await this.bridgeHost?.dispose();
102634
102999
  });
102635
103000
  this.subscribeDeviceProvisionedForReconcile();
102636
103001
  this.subscribeDeviceReadyForReconcile();
@@ -102787,16 +103152,24 @@ var ExportHapAddon = class extends BaseAddon {
102787
103152
  decodeMemos: this.decodeMemos,
102788
103153
  hapDeviceSettings: {
102789
103154
  streamPreference: entrySettings.streamPreference ?? "auto",
102790
- hksvRecording: resolveHksvRecording(entrySettings)
103155
+ hksvRecording: resolveHksvRecording(entrySettings),
103156
+ allowTranscode: entrySettings.allowTranscode !== false
102791
103157
  }
102792
103158
  }
102793
103159
  });
102794
- for (const accessory of mapper.accessories) await publishStandalone(accessory, {
102795
- pincode: this.pincode,
102796
- port: 0,
102797
- bind: this.bind,
102798
- logger: this.ctx.logger
103160
+ const wantsBridge = shouldBridge({
103161
+ mapperKind: entry.mapperKind,
103162
+ useBridge: entry.settings?.useBridge
102799
103163
  });
103164
+ for (const accessory of mapper.accessories) {
103165
+ if (wantsBridge && this.bridgeHost !== null && await this.bridgeHost.add(accessory)) continue;
103166
+ await publishStandalone(accessory, {
103167
+ pincode: this.pincode,
103168
+ port: 0,
103169
+ bind: this.bind,
103170
+ logger: this.ctx.logger
103171
+ });
103172
+ }
102800
103173
  this.exposed.set(entry.deviceId, mapper);
102801
103174
  return { childAccessoryUuids: [] };
102802
103175
  }
@@ -102809,7 +103182,13 @@ var ExportHapAddon = class extends BaseAddon {
102809
103182
  const mapper = this.exposed.get(deviceId);
102810
103183
  if (!mapper) return;
102811
103184
  this.exposed.delete(deviceId);
102812
- for (const accessory of mapper.accessories) await unpublishAccessory(accessory, this.ctx.logger);
103185
+ for (const accessory of mapper.accessories) {
103186
+ if (this.bridgeHost?.holds(accessory) === true) {
103187
+ this.bridgeHost.remove(accessory);
103188
+ continue;
103189
+ }
103190
+ await unpublishAccessory(accessory, this.ctx.logger);
103191
+ }
102813
103192
  await mapper.dispose().catch((err) => {
102814
103193
  this.ctx.logger.withTags({ deviceId: Number.parseInt(deviceId, 10) }).warn("export-hap: mapper dispose failed", { meta: { error: errMsg(err) } });
102815
103194
  });
@@ -103104,42 +103483,79 @@ var ExportHapAddon = class extends BaseAddon {
103104
103483
  const enabledKey = `hap:${deviceId}:enabled`;
103105
103484
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
103106
103485
  const hksvKey = `hap:${deviceId}:hksvRecording`;
103486
+ const useBridgeKey = `hap:${deviceId}:useBridge`;
103487
+ const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
103107
103488
  const mapper = this.exposed.get(String(deviceId)) ?? null;
103108
103489
  const paired = mapper ? accessoryPaired(mapper.accessory) : false;
103490
+ const bridged = mapper !== null && this.bridgeHost?.holds(mapper.accessory) === true;
103109
103491
  const name = entry?.displayName ?? `Device ${deviceId}`;
103110
- const statusLabel = !enabled ? "Not exposed" : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${this.config.identity.pincode}.`;
103492
+ const bridgePaired = this.bridgeHost?.accessory !== null && this.bridgeHost?.accessory !== void 0 ? accessoryPaired(this.bridgeHost.accessory) : false;
103493
+ const statusLabel = !enabled ? "Not exposed" : bridged ? bridgePaired ? `On the “${this.config.bridgeName}” bridge, as “${name}”` : `On the “${this.config.bridgeName}” bridge, as “${name}” — the BRIDGE is not paired yet. In iOS Home: + → Add Accessory → “${this.config.bridgeName}”, then enter setup code ${this.config.identity.pincode}. Every bridged device arrives with it.` : paired ? `Paired — exposed as “${name}”` : `Exposed as “${name}” — not paired yet. In iOS Home: + → Add Accessory → “${name}”, then enter setup code ${this.config.identity.pincode}.`;
103494
+ const qrSource = bridged ? this.bridgeHost?.accessory ?? null : mapper?.accessory ?? null;
103111
103495
  let qrValue = "";
103112
- if (mapper) try {
103113
- qrValue = mapper.accessory.setupURI();
103496
+ if (qrSource) try {
103497
+ qrValue = qrSource.setupURI();
103114
103498
  } catch (err) {
103115
103499
  this.ctx.logger.withTags({ deviceId }).debug("export-hap: setupURI failed for per-device contribution", { meta: { error: errMsg(err) } });
103116
103500
  }
103117
- const cameraFields = kind !== "camera" ? [] : [{
103118
- type: "select",
103119
- key: streamPreferenceKey,
103120
- label: "Source stream (HomeKit)",
103121
- description: "Which camstack profile slot HomeKit pulls. Auto = the broker picks the slot closest to 1080p at session start.",
103122
- options: HAP_STREAM_PREFERENCE_OPTIONS,
103123
- required: true,
103124
- value: settings.streamPreference,
103125
- showWhen: {
103126
- field: enabledKey,
103127
- equals: true
103128
- },
103129
- immediate: true
103130
- }, {
103501
+ const bridgeFields = kind === "camera" ? [] : [{
103131
103502
  type: "boolean",
103132
- key: hksvKey,
103133
- label: "HomeKit recording (Secure Video)",
103134
- 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).",
103503
+ key: useBridgeKey,
103504
+ label: "Export through the bridge",
103505
+ description: "Publish this device inside the shared CamStack bridge — one pairing and one entry in Add Accessory for every non-camera device, instead of one each. Turning this off gives it its own advertisement. Either way the switch REBUILDS the accessory and it must be added to the Home app again.",
103135
103506
  style: "switch",
103136
- value: resolveHksvRecording(settings),
103507
+ value: shouldBridge({
103508
+ mapperKind: kind,
103509
+ useBridge: settings.useBridge
103510
+ }),
103137
103511
  showWhen: {
103138
103512
  field: enabledKey,
103139
103513
  equals: true
103140
103514
  },
103141
103515
  immediate: true
103142
103516
  }];
103517
+ const cameraFields = kind !== "camera" ? [] : [
103518
+ {
103519
+ type: "select",
103520
+ key: streamPreferenceKey,
103521
+ label: "Source stream (HomeKit)",
103522
+ description: "Which camstack profile slot HomeKit pulls. Auto = the broker picks the slot closest to 1080p at session start.",
103523
+ options: HAP_STREAM_PREFERENCE_OPTIONS,
103524
+ required: true,
103525
+ value: settings.streamPreference,
103526
+ showWhen: {
103527
+ field: enabledKey,
103528
+ equals: true
103529
+ },
103530
+ immediate: true
103531
+ },
103532
+ {
103533
+ type: "boolean",
103534
+ key: hksvKey,
103535
+ label: "HomeKit recording (Secure Video)",
103536
+ 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).",
103537
+ style: "switch",
103538
+ value: resolveHksvRecording(settings),
103539
+ showWhen: {
103540
+ field: enabledKey,
103541
+ equals: true
103542
+ },
103543
+ immediate: true
103544
+ },
103545
+ {
103546
+ type: "boolean",
103547
+ key: allowTranscodeKey,
103548
+ label: "Allow transcoding for HomeKit",
103549
+ description: "Let the hub re-encode this camera when the resolution HomeKit negotiated cannot be served by a direct copy. Off means only a stream that can be forwarded as-is is offered — cheaper, but a session HomeKit negotiates outside what the camera publishes will be refused instead of transcoded.",
103550
+ style: "switch",
103551
+ value: settings.allowTranscode !== false,
103552
+ showWhen: {
103553
+ field: enabledKey,
103554
+ equals: true
103555
+ },
103556
+ immediate: true
103557
+ }
103558
+ ];
103143
103559
  return {
103144
103560
  tabs: [{
103145
103561
  id: "export",
@@ -103184,6 +103600,7 @@ var ExportHapAddon = class extends BaseAddon {
103184
103600
  value: enabled,
103185
103601
  immediate: true
103186
103602
  },
103603
+ ...bridgeFields,
103187
103604
  ...cameraFields
103188
103605
  ]
103189
103606
  }]
@@ -103209,14 +103626,20 @@ var ExportHapAddon = class extends BaseAddon {
103209
103626
  const enabledKey = `hap:${deviceId}:enabled`;
103210
103627
  const streamPreferenceKey = `hap:${deviceId}:streamPreference`;
103211
103628
  const hksvKey = `hap:${deviceId}:hksvRecording`;
103629
+ const useBridgeKey = `hap:${deviceId}:useBridge`;
103630
+ const allowTranscodeKey = `hap:${deviceId}:allowTranscode`;
103212
103631
  const enabledValue = enabledKey in patch ? Boolean(patch[enabledKey]) : wasEnabled;
103213
103632
  const streamPreferenceRaw = streamPreferenceKey in patch ? patch[streamPreferenceKey] : current?.settings?.streamPreference;
103214
103633
  const streamPreference = typeof streamPreferenceRaw === "string" && streamPreferenceRaw.trim().length > 0 ? streamPreferenceRaw : "auto";
103215
103634
  const hksvRecording = hksvKey in patch ? Boolean(patch[hksvKey]) : resolveHksvRecording(current?.settings);
103635
+ const useBridge = useBridgeKey in patch ? Boolean(patch[useBridgeKey]) : current?.settings?.useBridge !== false;
103636
+ const allowTranscode = allowTranscodeKey in patch ? Boolean(patch[allowTranscodeKey]) : current?.settings?.allowTranscode !== false;
103216
103637
  const nextSettings = {
103217
103638
  ...current?.settings ?? DEFAULT_DEVICE_SETTINGS,
103218
103639
  streamPreference,
103219
- hksvRecording
103640
+ hksvRecording,
103641
+ useBridge,
103642
+ allowTranscode
103220
103643
  };
103221
103644
  if (!enabledValue) {
103222
103645
  if (wasEnabled) await this.unexposeDevice(deviceIdStr);
@@ -103229,8 +103652,17 @@ var ExportHapAddon = class extends BaseAddon {
103229
103652
  }
103230
103653
  const currentPref = current?.settings?.streamPreference ?? "auto";
103231
103654
  const currentHksv = resolveHksvRecording(current?.settings);
103655
+ const mapperKind = current?.mapperKind ?? "generic";
103656
+ const wasBridged = shouldBridge({
103657
+ mapperKind,
103658
+ useBridge: current?.settings?.useBridge
103659
+ });
103660
+ const willBridge = shouldBridge({
103661
+ mapperKind,
103662
+ useBridge
103663
+ });
103232
103664
  await this.updateEntrySettings(deviceIdStr, nextSettings);
103233
- if (currentPref !== streamPreference || currentHksv !== hksvRecording) {
103665
+ if (currentPref !== streamPreference || currentHksv !== hksvRecording || wasBridged !== willBridge) {
103234
103666
  log.info("export-hap: per-camera export settings changed — refreshing accessory", { meta: {
103235
103667
  streamPreference: {
103236
103668
  from: currentPref,
@@ -103239,10 +103671,14 @@ var ExportHapAddon = class extends BaseAddon {
103239
103671
  hksvRecording: {
103240
103672
  from: currentHksv,
103241
103673
  to: hksvRecording
103674
+ },
103675
+ bridged: {
103676
+ from: wasBridged,
103677
+ to: willBridge
103242
103678
  }
103243
103679
  } });
103244
103680
  try {
103245
- await this.unexposeDevice(deviceIdStr, { clearPairing: false });
103681
+ await this.unexposeDevice(deviceIdStr, { clearPairing: wasBridged !== willBridge });
103246
103682
  await this.exposeDevice(deviceIdStr);
103247
103683
  } catch (err) {
103248
103684
  log.warn("export-hap: failed to refresh accessory after a settings change", { meta: { error: errMsg(err) } });