@camstack/addon-pipeline 1.1.24 → 1.1.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/audio-analyzer/index.js +2 -2
  2. package/dist/audio-analyzer/index.mjs +2 -2
  3. package/dist/audio-codec-ffmpeg/index.js +1 -1
  4. package/dist/audio-codec-ffmpeg/index.mjs +1 -1
  5. package/dist/decoder-ffmpeg/index.js +84 -12
  6. package/dist/decoder-ffmpeg/index.mjs +84 -12
  7. package/dist/detection-pipeline/index.js +149 -27
  8. package/dist/detection-pipeline/index.mjs +149 -27
  9. package/dist/{dist-pd_-3C0T.mjs → dist-CgEP_0OL.mjs} +794 -16
  10. package/dist/{dist-CE3a05qT.js → dist-DAIlCdAx.js} +799 -15
  11. package/dist/frame-handle-plane-Dq20KtKL.mjs +636 -0
  12. package/dist/frame-handle-plane-DtTRX_0n.js +647 -0
  13. package/dist/hub-hostname-DAJXlOgV.js +54 -0
  14. package/dist/hub-hostname-cCknRYKj.mjs +49 -0
  15. package/dist/{model-download-service-C-IHWnXx-BnQ_awK4.js → model-download-service-C-IHWnXx-DxM2DSns.js} +1 -2
  16. package/dist/motion-wasm/index.js +1 -1
  17. package/dist/motion-wasm/index.mjs +1 -1
  18. package/dist/pipeline-runner/index.js +341 -17
  19. package/dist/pipeline-runner/index.mjs +341 -17
  20. package/dist/recorder/index.js +267 -65
  21. package/dist/recorder/index.mjs +267 -65
  22. package/dist/stream-broker/_stub.js +39 -39
  23. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-BVFAEkIB.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-5tQlh9h4.mjs} +2 -2
  24. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-CkOPfV8r.mjs +26 -0
  25. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-BJK0-svt.mjs +26 -0
  26. package/dist/stream-broker/{hostInit-DHej3Ep9.mjs → hostInit-DyLqyJaS.mjs} +2 -2
  27. package/dist/stream-broker/index.js +7 -639
  28. package/dist/stream-broker/index.mjs +5 -637
  29. package/dist/stream-broker/remoteEntry.js +1 -1
  30. package/embed-dist/assets/{MaskShapeCanvas-DI4BY7W2-BqXU75it.js → MaskShapeCanvas-DI4BY7W2-BDLNwJ_F.js} +1 -1
  31. package/embed-dist/assets/{MotionZonesSettings-NcxxQN8r-Ct2fpgCd.js → MotionZonesSettings-NcxxQN8r-CoLjNiUN.js} +1 -1
  32. package/embed-dist/assets/{PrivacyMaskSettings-APgPLF7p-a9eFVPPl.js → PrivacyMaskSettings-APgPLF7p-DJE3OU-q.js} +1 -1
  33. package/embed-dist/assets/index-C-pL8ETk.js +81 -0
  34. package/embed-dist/assets/index-DrJ0ee3f.css +2 -0
  35. package/embed-dist/index.html +2 -2
  36. package/package.json +1 -1
  37. package/python/inference_pool.py +522 -27
  38. package/python/test_inference_pool_backpressure.py +121 -0
  39. package/python/test_inference_pool_coreml_cache.py +416 -0
  40. package/python/test_inference_pool_device_selection.py +256 -0
  41. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-BFeBlYRQ.mjs +0 -26
  42. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-BC1Jt6G8.mjs +0 -26
  43. package/embed-dist/assets/index-C7SSikPl.css +0 -2
  44. package/embed-dist/assets/index-DhdVxWXL.js +0 -80
  45. package/dist/{model-download-service-C-IHWnXx-3Mmeob3l.mjs → model-download-service-C-IHWnXx-BPy6aoAx.mjs} +1 -1
@@ -0,0 +1,636 @@
1
+ import { B as errMsg, p as RingBuffer } from "./dist-CgEP_0OL.mjs";
2
+ import { randomUUID } from "node:crypto";
3
+ //#region src/stream-broker/stream-broker/decoder-session-proxy.ts
4
+ var DecoderSessionProxy = class {
5
+ api;
6
+ sessionId;
7
+ polling = false;
8
+ constructor(api, sessionId) {
9
+ this.api = api;
10
+ this.sessionId = sessionId;
11
+ }
12
+ async pushPacket(packet) {
13
+ await this.api.pushPacket({
14
+ sessionId: this.sessionId,
15
+ packet
16
+ });
17
+ }
18
+ async openStream(url) {
19
+ await this.api.openStream({
20
+ sessionId: this.sessionId,
21
+ url
22
+ });
23
+ }
24
+ async startPolling(onFrame) {
25
+ this.polling = true;
26
+ while (this.polling) {
27
+ const frames = await this.api.pullFrames({
28
+ sessionId: this.sessionId,
29
+ maxCount: 4
30
+ });
31
+ for (const frame of frames) onFrame(frame);
32
+ if (frames.length === 0) await new Promise((r) => setTimeout(r, 1));
33
+ }
34
+ }
35
+ /**
36
+ * Poll a `frameSink: 'shm'` session for `FrameHandle`s (Phase 5 / D9).
37
+ * Mirrors `startPolling` but drains `pullHandles` — the decoder has
38
+ * already written the pixels into a shared-memory ring, so what crosses
39
+ * the cap boundary is the tiny serialisable handle. Runs until
40
+ * `stopPolling`, `destroy`, or the session is destroyed externally.
41
+ *
42
+ * When the decoder reports the session is gone (`unknown sessionId` /
43
+ * `Service … not found`) the loop exits gracefully — those errors are
44
+ * expected during decoder restart/shutdown and must not be re-thrown to
45
+ * the caller's `.catch()` handler, which would otherwise spin forever.
46
+ */
47
+ async startHandlePolling(onHandle) {
48
+ this.polling = true;
49
+ while (this.polling) try {
50
+ const handles = await this.api.pullHandles({
51
+ sessionId: this.sessionId,
52
+ maxCount: 4
53
+ });
54
+ for (const handle of handles) onHandle(handle);
55
+ if (handles.length === 0) await new Promise((r) => setTimeout(r, 1));
56
+ } catch (err) {
57
+ this.polling = false;
58
+ const msg = err instanceof Error ? err.message : String(err);
59
+ if (!msg.includes("unknown sessionId") && !msg.includes("Service") && !msg.includes("not found")) throw err;
60
+ return;
61
+ }
62
+ }
63
+ stopPolling() {
64
+ this.polling = false;
65
+ }
66
+ async updateConfig(config) {
67
+ await this.api.updateConfig({
68
+ sessionId: this.sessionId,
69
+ config
70
+ });
71
+ }
72
+ async getStats() {
73
+ return this.api.getStats({ sessionId: this.sessionId });
74
+ }
75
+ async destroy() {
76
+ this.stopPolling();
77
+ await this.api.destroySession({ sessionId: this.sessionId });
78
+ }
79
+ };
80
+ //#endregion
81
+ //#region src/stream-broker/stream-broker/frame-handle-plane.ts
82
+ /**
83
+ * `FrameHandlePlane` — the broker's shared-memory frame-handle surface
84
+ * (Phase 5 / D9).
85
+ *
86
+ * This is the handle-based replacement for `StreamBroker.onDecodedFrame`'s
87
+ * live-object callback path. Instead of fanning pixel `DecodedFrame`s out to
88
+ * in-process callbacks (which cannot cross a process boundary), the broker
89
+ * publishes zero-pixel, serialisable `FrameHandle`s a consumer drains over
90
+ * tRPC and reads back from a shared-memory ring with a `FrameRingReader`.
91
+ *
92
+ * ## Ring-per-format model
93
+ *
94
+ * A `frameSink: 'shm'` decoder session produces exactly ONE pixel format
95
+ * (the decoder's scaler is configured for it). The broker therefore keeps
96
+ * one decoder session — hence one shm ring — per `(brokerId, format)` that a
97
+ * consumer actually subscribes to:
98
+ *
99
+ * - motion subscribes `gray` → one `gray` decoder session + ring
100
+ * - detection subscribes `rgb` → one `rgb` decoder session + ring
101
+ *
102
+ * Only the formats consumers ask for are materialised. There is NO
103
+ * broker-side `sharp` conversion any more — each consumer reads the exact
104
+ * format it requested. A session is reference-counted by its subscriber set
105
+ * and torn down when the last subscriber of that format leaves.
106
+ *
107
+ * ## fps throttling
108
+ *
109
+ * Throttling is implicit: the ring is latest-wins, so a slow consumer that
110
+ * polls `pullFrameHandles` infrequently simply receives the newest handles
111
+ * and the intervening frames are dropped at the ring (a recycled slot the
112
+ * consumer never read). The optional `maxFps` from `subscribeFrames` is NOT
113
+ * enforced here — it is echoed back to the consumer as a reader-side polling
114
+ * cadence hint.
115
+ *
116
+ * ## Packet feed
117
+ *
118
+ * The plane's decoder sessions are push-mode by default: the broker forwards
119
+ * every video `EncodedPacket` to `pushPacket`. For a pull-mode decoder the
120
+ * broker supplies a `pullModeUrl` and the plane calls `openStream` once the
121
+ * session exists.
122
+ */
123
+ /**
124
+ * Collapse a hierarchical Moleculer nodeID (`hub/child-abc`) to its owning
125
+ * node (`hub`). Frame-plane co-location only cares about the physical node, not
126
+ * which forked child within it hosts the session.
127
+ */
128
+ function collapseNodeId(nodeId) {
129
+ const slash = nodeId.indexOf("/");
130
+ return slash >= 0 ? nodeId.slice(0, slash) : nodeId;
131
+ }
132
+ /**
133
+ * Decide whether a decoder session created on `decoderNodeId` is co-located
134
+ * with the broker whose local node is `brokerNodeId`.
135
+ *
136
+ * The broker's shm frame ring is NODE-LOCAL: a decoder session on any other
137
+ * node can never deliver frame handles to this broker's consumers, so a
138
+ * mis-placed session must be rejected. Both ids are collapsed (`hub/child`→
139
+ * `hub`) before comparison.
140
+ *
141
+ * A `null` `brokerNodeId` means the broker's own node is unknown — enforcement
142
+ * is skipped (legacy behavior, accept any placement).
143
+ */
144
+ function isDecoderNodeColocated(brokerNodeId, decoderNodeId) {
145
+ if (brokerNodeId === null) return true;
146
+ return collapseNodeId(brokerNodeId) === collapseNodeId(decoderNodeId);
147
+ }
148
+ /** Per-subscription handle-queue capacity. A handle is tiny; 64 absorbs a
149
+ * burst between two `pullFrameHandles` polls without unbounded growth. */
150
+ var HANDLE_QUEUE_CAPACITY = 64;
151
+ /** Default reader-side cadence hint when a subscriber omits `maxFps`. */
152
+ var DEFAULT_HINT_FPS = 5;
153
+ /** Rolling window for the aggregate `decodeFps` rate, ms. Mirrors the
154
+ * broker's 2s `inputFps` window so the two stats are comparable. */
155
+ var DECODE_FPS_WINDOW_MS = 2e3;
156
+ /**
157
+ * Keep-warm grace before a decoder session with no subscribers is torn down.
158
+ *
159
+ * Subscribers flap on ~30s cadences (occupancy recheck bursts, detection
160
+ * motion-gating watch↔active, onboard gray gating). Destroying the
161
+ * ffmpeg/VAAPI decode session the instant the last subscriber leaves spawns +
162
+ * destroys a full session every cycle — wasted setup/teardown. Chosen >30s so
163
+ * consecutive bursts and watch↔active flips reuse the warm session, yet a
164
+ * genuinely idle session still frees its ffmpeg within ~a minute.
165
+ */
166
+ var SESSION_LINGER_MS = 45e3;
167
+ /**
168
+ * Default retry cooldown after a decoder session lands on a NON-LOCAL node
169
+ * (see `FrameHandlePlaneOptions.sessionRetryCooldownMs`). Long enough to
170
+ * turn a per-packet storm into a slow probe; short enough that the plane
171
+ * recovers within seconds once the local decoder respawns.
172
+ */
173
+ var SESSION_RETRY_COOLDOWN_MS = 1e4;
174
+ /**
175
+ * Owns the broker's shared-memory frame-handle subscriptions and the
176
+ * per-format `frameSink: 'shm'` decoder sessions that feed them.
177
+ */
178
+ var FrameHandlePlane = class {
179
+ decoderApi;
180
+ logger;
181
+ resolveStreamInfo;
182
+ localNodeId;
183
+ sessionRetryCooldownMs;
184
+ subscriptions = /* @__PURE__ */ new Map();
185
+ sessions = /* @__PURE__ */ new Map();
186
+ /** Per-format retry gate set when a session lands on a non-local node:
187
+ * `ensureSession` skips creation until the epoch-ms deadline passes. */
188
+ sessionRetryCooldownUntil = /* @__PURE__ */ new Map();
189
+ /** In-flight `ensureSession` creation per format. Coalesces concurrent
190
+ * same-format callers onto ONE decoder session — without it two callers
191
+ * both pass the `sessions.get` check, both `createSession` (two ffmpeg),
192
+ * and the second registration orphans the first with no `destroySession`. */
193
+ sessionCreating = /* @__PURE__ */ new Map();
194
+ disposed = false;
195
+ /** Re-entrancy guard for `armPendingSessions` — collapses the per-packet
196
+ * `pushPacket` calls into a single in-flight deferred-arm pass. */
197
+ armInFlight = false;
198
+ /** Aggregate decoded-frame rate state — frames fanned out in the current
199
+ * rolling window, the window's start epoch, and the last computed fps. */
200
+ framesInWindow = 0;
201
+ windowStartMs = Date.now();
202
+ decodedFps = 0;
203
+ constructor(options) {
204
+ this.decoderApi = options.decoderApi;
205
+ this.logger = options.logger;
206
+ this.resolveStreamInfo = options.resolveStreamInfo;
207
+ this.localNodeId = options.localNodeId;
208
+ this.sessionRetryCooldownMs = options.sessionRetryCooldownMs ?? SESSION_RETRY_COOLDOWN_MS;
209
+ }
210
+ /** Number of active handle subscriptions — surfaced for diagnostics. */
211
+ get subscriberCount() {
212
+ return this.subscriptions.size;
213
+ }
214
+ /**
215
+ * Moleculer nodeIDs of the decoder providers currently hosting this plane's
216
+ * `frameSink: 'shm'` sessions. Used by the broker-manager's per-agent
217
+ * hwaccel-change handler to decide which brokers need a decoder rotation.
218
+ */
219
+ decoderNodeIds() {
220
+ const ids = [];
221
+ for (const session of this.sessions.values()) if (session.nodeId) ids.push(session.nodeId);
222
+ return ids;
223
+ }
224
+ /**
225
+ * Rotate every shm decoder session hosted on `agentNodeId` — destroy and
226
+ * rebuild it so the new session re-pulls the latest per-agent decoder
227
+ * preferences (hwaccel backend, …). Subscriptions are preserved: the same
228
+ * `subscriptionId`s read from the rebuilt session's fresh ring. A no-op for
229
+ * sessions on other nodes. Returns the number of sessions rotated.
230
+ */
231
+ async rotate(agentNodeId, reason) {
232
+ if (this.disposed) return 0;
233
+ let rotated = 0;
234
+ for (const session of this.sessions.values()) {
235
+ if ((session.nodeId && session.nodeId.includes("/") ? session.nodeId.split("/")[0] : session.nodeId) !== agentNodeId) continue;
236
+ this.logger?.info("frame-handle plane: rotating shm decoder session", { meta: {
237
+ format: session.format,
238
+ reason,
239
+ nodeId: session.nodeId
240
+ } });
241
+ await this.destroySession(session);
242
+ let restarted = false;
243
+ try {
244
+ restarted = await this.startSessionDecoder(session);
245
+ } finally {
246
+ if (!restarted) this.sessions.delete(session.format);
247
+ }
248
+ if (restarted) rotated += 1;
249
+ }
250
+ return rotated;
251
+ }
252
+ /**
253
+ * Register a frame-handle subscription. Spins up (or reuses) a
254
+ * `frameSink: 'shm'` decoder session producing `format`. The returned
255
+ * `subscriptionId` is the handle the consumer passes to
256
+ * `pullFrameHandles` / `unsubscribe`.
257
+ */
258
+ async subscribe(input) {
259
+ if (this.disposed) throw new Error("FrameHandlePlane: subscribe after dispose");
260
+ const subscriptionId = `fh-${randomUUID()}`;
261
+ const maxFps = input.maxFps !== void 0 && input.maxFps > 0 ? input.maxFps : DEFAULT_HINT_FPS;
262
+ const subscription = {
263
+ id: subscriptionId,
264
+ format: input.format,
265
+ maxFps,
266
+ tag: input.tag ?? "unknown",
267
+ subscribedAt: Date.now(),
268
+ queue: new RingBuffer(HANDLE_QUEUE_CAPACITY),
269
+ framesDelivered: 0
270
+ };
271
+ this.subscriptions.set(subscriptionId, subscription);
272
+ await this.ensureSession(input.format, subscriptionId);
273
+ this.logger?.info("frame-handle subscription added", { meta: {
274
+ subscriptionId,
275
+ format: input.format,
276
+ tag: subscription.tag,
277
+ maxFps
278
+ } });
279
+ return {
280
+ subscriptionId,
281
+ maxFps
282
+ };
283
+ }
284
+ /**
285
+ * Drain up to `maxCount` `FrameHandle`s for a subscription, latest-wins.
286
+ * An unknown subscription id returns `[]` (the consumer may have been
287
+ * torn down concurrently).
288
+ */
289
+ pullHandles(subscriptionId, maxCount) {
290
+ const subscription = this.subscriptions.get(subscriptionId);
291
+ if (!subscription) return [];
292
+ const stale = subscription.queue.size - maxCount;
293
+ if (stale > 0) subscription.queue.drain(stale);
294
+ const handles = subscription.queue.drain(maxCount);
295
+ subscription.framesDelivered += handles.length;
296
+ return handles;
297
+ }
298
+ /**
299
+ * Release a subscription. When it was the last reader of its format the
300
+ * underlying decoder session is destroyed (and its shm segment unlinked
301
+ * by the decoder). Returns `true` when a known subscription was released.
302
+ */
303
+ async unsubscribe(subscriptionId, immediate = false) {
304
+ const subscription = this.subscriptions.get(subscriptionId);
305
+ if (!subscription) return false;
306
+ this.subscriptions.delete(subscriptionId);
307
+ const session = this.sessions.get(subscription.format);
308
+ if (session) {
309
+ session.subscriberIds.delete(subscriptionId);
310
+ if (session.subscriberIds.size === 0) if (immediate) {
311
+ this.clearLinger(session);
312
+ this.sessions.delete(subscription.format);
313
+ await this.destroySession(session);
314
+ } else this.scheduleLinger(session);
315
+ }
316
+ this.logger?.info("frame-handle subscription removed", { meta: {
317
+ subscriptionId,
318
+ format: subscription.format
319
+ } });
320
+ return true;
321
+ }
322
+ /**
323
+ * Arm the keep-warm teardown timer for a session whose last subscriber just
324
+ * left. Clears any existing timer first (idempotent). On fire it re-checks
325
+ * `subscriberIds.size === 0` — a subscriber may have returned in the interim,
326
+ * in which case the timer is a no-op — and only then removes the session and
327
+ * destroys the decoder. The timer is `unref`'d so a lingering warm session
328
+ * never keeps the process alive.
329
+ */
330
+ scheduleLinger(session) {
331
+ this.clearLinger(session);
332
+ const timer = setTimeout(() => {
333
+ session.lingerTimer = null;
334
+ if (session.subscriberIds.size > 0) return;
335
+ this.sessions.delete(session.format);
336
+ this.destroySession(session).catch(() => {});
337
+ }, SESSION_LINGER_MS);
338
+ timer.unref?.();
339
+ session.lingerTimer = timer;
340
+ }
341
+ /** Cancel a session's pending keep-warm teardown timer, if any. */
342
+ clearLinger(session) {
343
+ if (session.lingerTimer) {
344
+ clearTimeout(session.lingerTimer);
345
+ session.lingerTimer = null;
346
+ }
347
+ }
348
+ /**
349
+ * Forward a video `EncodedPacket` to every active shm decoder session.
350
+ * Push-mode decoders consume this; a pull-mode decoder ignores it (it
351
+ * reads its own pipe via `openStream`). Audio packets are not forwarded.
352
+ *
353
+ * The packet feed doubles as the plane's stream-ready signal: the broker
354
+ * only calls `pushPacket` once it has a source and the first keyframe has
355
+ * landed — exactly the point `resolveStreamInfo` starts returning a
356
+ * descriptor. Each packet therefore triggers `armPendingSessions`, which
357
+ * re-attempts session creation for any deferred subscription so a lone
358
+ * first subscriber on a not-yet-started broker self-arms without a
359
+ * redundant re-`subscribe`.
360
+ */
361
+ pushPacket(packet) {
362
+ if (this.disposed || packet.type !== "video") return;
363
+ this.armPendingSessions(packet).catch((err) => {
364
+ this.logger?.warn("frame-handle plane: arm pending sessions error", { meta: { error: errMsg(err) } });
365
+ });
366
+ this.feedSessions(packet);
367
+ }
368
+ /** Forward a video `EncodedPacket` to every live shm decoder session. */
369
+ feedSessions(packet) {
370
+ for (const session of this.sessions.values()) {
371
+ if (!session.proxy) continue;
372
+ session.proxy.pushPacket(packet).catch((err) => {
373
+ const msg = errMsg(err);
374
+ this.logger?.warn("frame-handle plane: decoder push error", { meta: {
375
+ format: session.format,
376
+ error: msg
377
+ } });
378
+ if (msg.includes("unknown sessionId") || msg.includes("Service") || msg.includes("not found")) {
379
+ this.logger?.info("frame-handle plane: invalidating stale proxy", { meta: { format: session.format } });
380
+ this.destroySession(session).catch(() => {});
381
+ this.sessions.delete(session.format);
382
+ }
383
+ });
384
+ }
385
+ }
386
+ /**
387
+ * Re-attempt session creation for every subscription whose format has no
388
+ * live `FormatSession` yet — the subscriptions whose `startSessionDecoder`
389
+ * was deferred because the broker had no stream at `subscribe` time. Driven
390
+ * off the `pushPacket` feed (event-driven, no polling timer); a no-op once
391
+ * every subscribed format already owns a session.
392
+ *
393
+ * `armInFlight` collapses re-entrant calls: `pushPacket` fires per packet,
394
+ * but `ensureSession` is async — without the guard a burst of packets would
395
+ * launch overlapping decoder-creation round-trips for the same format.
396
+ *
397
+ * `triggerPacket` is the packet whose arrival armed the pass. Because
398
+ * `ensureSession` is async, the synchronous `feedSessions` in `pushPacket`
399
+ * runs before the session lands in `this.sessions` — so this method feeds
400
+ * the triggering packet to each session it just created, otherwise that
401
+ * first (keyframe-carrying) packet would be lost and a push-mode H264/H265
402
+ * decoder would stall waiting for SPS/PPS.
403
+ */
404
+ async armPendingSessions(triggerPacket) {
405
+ if (this.disposed || this.armInFlight) return;
406
+ const pending = /* @__PURE__ */ new Map();
407
+ for (const subscription of this.subscriptions.values()) {
408
+ if (this.sessions.has(subscription.format)) continue;
409
+ if (!pending.has(subscription.format)) pending.set(subscription.format, subscription.id);
410
+ }
411
+ if (pending.size === 0) return;
412
+ this.armInFlight = true;
413
+ try {
414
+ for (const [format, subscriptionId] of pending) {
415
+ if (this.disposed) return;
416
+ await this.ensureSession(format, subscriptionId);
417
+ const armed = this.sessions.get(format);
418
+ if (armed?.proxy) armed.proxy.pushPacket(triggerPacket).catch((err) => {
419
+ this.logger?.warn("frame-handle plane: decoder push error", { meta: {
420
+ format,
421
+ error: errMsg(err)
422
+ } });
423
+ });
424
+ }
425
+ } finally {
426
+ this.armInFlight = false;
427
+ }
428
+ }
429
+ /**
430
+ * Aggregate decoded-frame rate across every `frameSink: 'shm'` session in
431
+ * this plane, frames/s. Each `fanoutHandle` call is one decoded frame
432
+ * delivered into the plane; the rate is recomputed over a rolling
433
+ * `DECODE_FPS_WINDOW_MS` window. Returns the last computed value between
434
+ * window rolls, and `0` while no session is producing.
435
+ */
436
+ decodeFps() {
437
+ this.rollDecodeFpsWindow();
438
+ return this.decodedFps;
439
+ }
440
+ /**
441
+ * Roll the decoded-fps window when it has elapsed: convert frames seen in
442
+ * the window into a per-second rate, then reset the counter. Called both
443
+ * on every fanout and on every `decodeFps()` read so a stalled session
444
+ * (no fanout) decays its rate to `0` rather than reporting a stale value.
445
+ */
446
+ rollDecodeFpsWindow() {
447
+ const now = Date.now();
448
+ const windowMs = now - this.windowStartMs;
449
+ if (windowMs < DECODE_FPS_WINDOW_MS) return;
450
+ this.decodedFps = this.framesInWindow / windowMs * 1e3;
451
+ this.framesInWindow = 0;
452
+ this.windowStartMs = now;
453
+ }
454
+ /** Diagnostic snapshot of every active frame-handle subscription. */
455
+ listSubscribers() {
456
+ return [...this.subscriptions.values()].map((s) => ({
457
+ tag: s.tag,
458
+ subscribedAt: s.subscribedAt,
459
+ maxFps: s.maxFps,
460
+ framesDelivered: s.framesDelivered
461
+ }));
462
+ }
463
+ /**
464
+ * Force-release every subscription whose tag matches `tag`. Returns the
465
+ * number released. Decoder sessions wind down when their last subscriber
466
+ * leaves, same as a normal `unsubscribe`.
467
+ */
468
+ async killByTag(tag) {
469
+ const victims = [...this.subscriptions.values()].filter((s) => s.tag === tag).map((s) => s.id);
470
+ for (const id of victims) await this.unsubscribe(id, true);
471
+ return victims.length;
472
+ }
473
+ /** Tear down every subscription + decoder session. Idempotent. */
474
+ async dispose() {
475
+ if (this.disposed) return;
476
+ this.disposed = true;
477
+ this.subscriptions.clear();
478
+ const sessions = [...this.sessions.values()];
479
+ this.sessions.clear();
480
+ await Promise.all(sessions.map((s) => this.destroySession(s)));
481
+ }
482
+ /**
483
+ * Ensure a `frameSink: 'shm'` decoder session for `format` exists and add
484
+ * `subscriptionId` to its reader set. Reuses the session when one already
485
+ * runs for that format.
486
+ *
487
+ * When a session is created fresh, its reader set is seeded with EVERY
488
+ * subscription currently reading `format`, not just `subscriptionId` — a
489
+ * deferred-arm pass (`armPendingSessions`) may create the session long
490
+ * after several subscriptions of that format have registered, and the
491
+ * session is reference-counted by `subscriberIds`. Seeding only the one id
492
+ * would let an `unsubscribe` of that id tear the session down while its
493
+ * sibling subscriptions still read it.
494
+ */
495
+ async ensureSession(format, subscriptionId) {
496
+ const existing = this.sessions.get(format);
497
+ if (existing) {
498
+ this.clearLinger(existing);
499
+ existing.subscriberIds.add(subscriptionId);
500
+ return;
501
+ }
502
+ const inflight = this.sessionCreating.get(format);
503
+ if (inflight) {
504
+ await inflight;
505
+ this.sessions.get(format)?.subscriberIds.add(subscriptionId);
506
+ return;
507
+ }
508
+ if (Date.now() < (this.sessionRetryCooldownUntil.get(format) ?? 0)) return;
509
+ const creation = (async () => {
510
+ const subscriberIds = new Set([subscriptionId]);
511
+ for (const subscription of this.subscriptions.values()) if (subscription.format === format) subscriberIds.add(subscription.id);
512
+ const session = {
513
+ format,
514
+ proxy: null,
515
+ nodeId: null,
516
+ subscriberIds,
517
+ lingerTimer: null
518
+ };
519
+ let started = false;
520
+ try {
521
+ started = await this.startSessionDecoder(session);
522
+ } catch (err) {
523
+ this.sessionRetryCooldownUntil.set(format, Date.now() + this.sessionRetryCooldownMs);
524
+ throw err;
525
+ }
526
+ if (started) this.sessions.set(format, session);
527
+ })();
528
+ this.sessionCreating.set(format, creation);
529
+ try {
530
+ await creation;
531
+ } finally {
532
+ this.sessionCreating.delete(format);
533
+ }
534
+ }
535
+ /**
536
+ * Create the `frameSink: 'shm'` decoder for a `FormatSession` and start
537
+ * draining its handle queue. Mutates `session.proxy` / `session.nodeId` in
538
+ * place so a `rotate()` can rebuild a registered session without disturbing
539
+ * its `subscriberIds`. Returns `false` when no stream / unsupported codec
540
+ * means no decoder could be created.
541
+ */
542
+ async startSessionDecoder(session) {
543
+ const { format } = session;
544
+ const info = this.resolveStreamInfo();
545
+ if (!info) {
546
+ this.logger?.info("frame-handle plane: no stream — session deferred", { meta: { format } });
547
+ return false;
548
+ }
549
+ if (!await this.decoderApi.supportsCodec({ codec: info.codec })) {
550
+ this.logger?.warn("frame-handle plane: codec unsupported — session skipped", { meta: {
551
+ format,
552
+ codec: info.codec
553
+ } });
554
+ return false;
555
+ }
556
+ const { sessionId, nodeId } = await this.decoderApi.createSession({
557
+ codec: info.codec,
558
+ maxFps: 0,
559
+ outputFormat: format,
560
+ scale: 1,
561
+ frameSink: "shm",
562
+ ...info.numericDeviceId !== void 0 ? { deviceId: info.numericDeviceId } : {},
563
+ tag: `${info.tag}:shm:${format}`
564
+ });
565
+ if (!isDecoderNodeColocated(this.localNodeId, nodeId)) {
566
+ this.sessionRetryCooldownUntil.set(format, Date.now() + this.sessionRetryCooldownMs);
567
+ this.logger?.warn("frame-handle plane: decoder session landed on a non-local node — destroying (shm ring is node-local)", { meta: {
568
+ format,
569
+ requestedNode: this.localNodeId,
570
+ gotNode: nodeId,
571
+ sessionId,
572
+ retryInMs: this.sessionRetryCooldownMs
573
+ } });
574
+ await this.decoderApi.destroySession({ sessionId }).catch((err) => {
575
+ this.logger?.warn("frame-handle plane: failed to destroy mis-placed decoder session", { meta: {
576
+ format,
577
+ sessionId,
578
+ error: errMsg(err)
579
+ } });
580
+ });
581
+ return false;
582
+ }
583
+ this.sessionRetryCooldownUntil.delete(format);
584
+ const proxy = new DecoderSessionProxy(this.decoderApi, sessionId);
585
+ session.proxy = proxy;
586
+ session.nodeId = nodeId;
587
+ proxy.startHandlePolling((handle) => {
588
+ this.fanoutHandle(format, handle);
589
+ }).catch((err) => {
590
+ this.logger?.warn("frame-handle plane: handle polling error", { meta: {
591
+ format,
592
+ error: errMsg(err)
593
+ } });
594
+ });
595
+ if (info.pullModeUrl) proxy.openStream(info.pullModeUrl).catch((err) => {
596
+ this.logger?.error("frame-handle plane: pull-mode openStream failed", { meta: {
597
+ format,
598
+ error: errMsg(err)
599
+ } });
600
+ });
601
+ this.logger?.info("frame-handle plane: shm decoder session created", { meta: {
602
+ format,
603
+ codec: info.codec,
604
+ sessionId,
605
+ nodeId
606
+ } });
607
+ return true;
608
+ }
609
+ /** Push one decoded `FrameHandle` to every subscription of `format`. */
610
+ fanoutHandle(format, handle) {
611
+ this.rollDecodeFpsWindow();
612
+ this.framesInWindow += 1;
613
+ for (const subscription of this.subscriptions.values()) {
614
+ if (subscription.format !== format) continue;
615
+ subscription.queue.push(handle);
616
+ }
617
+ }
618
+ /** Destroy a decoder session, swallowing teardown errors. */
619
+ async destroySession(session) {
620
+ this.clearLinger(session);
621
+ const proxy = session.proxy;
622
+ session.proxy = null;
623
+ session.nodeId = null;
624
+ if (!proxy) return;
625
+ try {
626
+ await proxy.destroy();
627
+ } catch (err) {
628
+ this.logger?.warn("frame-handle plane: session destroy failed", { meta: {
629
+ format: session.format,
630
+ error: errMsg(err)
631
+ } });
632
+ }
633
+ }
634
+ };
635
+ //#endregion
636
+ export { DecoderSessionProxy as n, FrameHandlePlane as t };