@camstack/addon-pipeline 1.1.56 → 1.1.57

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 (39) hide show
  1. package/dist/audio-analyzer/index.js +2 -2
  2. package/dist/audio-analyzer/index.mjs +2 -2
  3. package/dist/detection-pipeline/index.js +71 -74
  4. package/dist/detection-pipeline/index.mjs +70 -73
  5. package/dist/{dist-ClE6_i0p.js → dist-CK8Ur-OS.js} +104 -6
  6. package/dist/{dist-CrjLGrkj.mjs → dist-CL531uVA.mjs} +104 -6
  7. package/dist/motion-wasm/index.js +9 -41
  8. package/dist/motion-wasm/index.mjs +9 -41
  9. package/dist/pipeline-runner/index.js +222 -656
  10. package/dist/pipeline-runner/index.mjs +211 -647
  11. package/dist/recorder/index.js +2 -2
  12. package/dist/recorder/index.mjs +2 -2
  13. package/dist/remote-restream-BeHi78PZ.mjs +25 -0
  14. package/dist/remote-restream-CO36Sr30.js +36 -0
  15. package/dist/{step-definitions-dCghpdRo.mjs → step-definitions-1d3_vQ6S.mjs} +44 -2
  16. package/dist/{step-definitions-C9kUXgC7.js → step-definitions-DHAxruAQ.js} +44 -2
  17. package/dist/stream-broker/_stub.js +282 -222
  18. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-D4xH4Tm-.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-Cm_B-hQT.mjs} +1 -1
  19. package/dist/stream-broker/{_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-D2z_vRMH.mjs → _virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-Ba7Eyd47.mjs} +1 -1
  20. package/dist/stream-broker/{hostInit-Di9WUNlQ.mjs → hostInit-DEaqJpGA.mjs} +1 -1
  21. package/dist/stream-broker/index.js +877 -37
  22. package/dist/stream-broker/index.mjs +874 -34
  23. package/dist/stream-broker/remoteEntry.js +1 -1
  24. package/embed-dist/assets/{MaskShapeCanvas-DI4BY7W2-Ca93F1js.js → MaskShapeCanvas-DI4BY7W2-CZUzu3MF.js} +1 -1
  25. package/embed-dist/assets/{MotionZonesSettings-NcxxQN8r-CDqgb-WA.js → MotionZonesSettings-NcxxQN8r-CmZbzLQi.js} +1 -1
  26. package/embed-dist/assets/{PrivacyMaskSettings-APgPLF7p-BlxPhY_w.js → PrivacyMaskSettings-APgPLF7p-BOKDrH0N.js} +1 -1
  27. package/embed-dist/assets/{index-B23riUw8.js → index-DOsK8CZb.js} +10 -10
  28. package/embed-dist/index.html +1 -1
  29. package/package.json +7 -5
  30. package/python/inference_pool.py +172 -28
  31. package/python/postprocessors/__init__.py +2 -0
  32. package/python/postprocessors/ssd.py +128 -0
  33. package/python/requirements-edgetpu.txt +23 -0
  34. package/python/test_inference_pool_layout.py +16 -1
  35. package/python/test_inference_pool_preprocess.py +65 -0
  36. package/dist/remote-source-plane-B28iGi7h.mjs +0 -1001
  37. package/dist/remote-source-plane-BAqEHSgm.js +0 -1030
  38. package/dist/{model-download-service-C-IHWnXx-BPy6aoAx.mjs → model-download-service-C-IHWnXx-3Mmeob3l.mjs} +1 -1
  39. package/dist/{model-download-service-C-IHWnXx-BLXzxpRB.js → model-download-service-C-IHWnXx-D326YNnt.js} +1 -1
@@ -1,12 +1,11 @@
1
- import { $ as boolean, D as nodePin, H as createEvent, I as errMsg, K as makeSourceBrokerId, L as BaseAddon, Q as array, V as EventCategory, Z as _enum, _ as customAction, it as object, k as pipelineRunnerCapability, ot as string, rt as number, tt as lazy, y as defineCustomActions } from "../dist-CrjLGrkj.mjs";
2
- import { n as isRemoteRestream, r as profileForStreamId, t as RemoteSourcePlane } from "../remote-source-plane-B28iGi7h.mjs";
1
+ import { $ as boolean, D as nodePin, H as createEvent, I as errMsg, L as BaseAddon, Q as array, V as EventCategory, Z as _enum, _ as customAction, it as object, k as pipelineRunnerCapability, ot as string, rt as number, tt as lazy, y as defineCustomActions } from "../dist-CL531uVA.mjs";
2
+ import { n as profileForStreamId, t as isRemoteRestream } from "../remote-restream-BeHi78PZ.mjs";
3
3
  import { t as resolveHubHostname } from "../hub-hostname-cCknRYKj.mjs";
4
4
  import { t as isWorkerReply } from "../worker-protocol-CyVJTZEO.mjs";
5
- import { a as getStepDefinition } from "../step-definitions-dCghpdRo.mjs";
6
- import { DecoderFrameRingSink, FrameRingReaderCache, unlinkSegment } from "@camstack/shm-ring";
5
+ import { a as getStepDefinition } from "../step-definitions-1d3_vQ6S.mjs";
7
6
  import { fork } from "node:child_process";
8
7
  import { fileURLToPath } from "node:url";
9
- import { readdirSync } from "node:fs";
8
+ import sharp from "sharp";
10
9
  //#region src/pipeline-runner/bench-actions.ts
11
10
  /**
12
11
  * Synthetic-bench custom actions for pipeline-runner.
@@ -101,329 +100,6 @@ var pipelineRunnerBenchActions = defineCustomActions({
101
100
  runSyntheticBench: customAction(RunSyntheticBenchInputSchema, RunSyntheticBenchResultSchema, { kind: "mutation" })
102
101
  });
103
102
  //#endregion
104
- //#region src/pipeline-runner/foreign-handle-throttle.ts
105
- var ForeignHandleThrottle = class {
106
- minFetchIntervalMs;
107
- warnIntervalMs;
108
- lastFetchStartedAt = Number.NEGATIVE_INFINITY;
109
- inFlight = false;
110
- lastWarnAt;
111
- _foreignHandles = 0;
112
- _remoteFetches = 0;
113
- _remoteFailures = 0;
114
- _dropped = 0;
115
- constructor(options = {}) {
116
- const maxRemoteFps = options.maxRemoteFps ?? 1;
117
- this.minFetchIntervalMs = maxRemoteFps > 0 ? 1e3 / maxRemoteFps : Number.POSITIVE_INFINITY;
118
- this.warnIntervalMs = options.warnIntervalMs ?? 6e4;
119
- }
120
- /**
121
- * Decide whether the current foreign handle should trigger a remote fetch.
122
- * `'fetch'` only when no fetch is in flight AND at least `1000/maxRemoteFps`
123
- * ms have elapsed since the last fetch started; otherwise `'drop'`.
124
- */
125
- plan(now) {
126
- this._foreignHandles += 1;
127
- const rateOpen = now - this.lastFetchStartedAt >= this.minFetchIntervalMs;
128
- if (this.inFlight || !rateOpen) {
129
- this._dropped += 1;
130
- return "drop";
131
- }
132
- return "fetch";
133
- }
134
- /** Mark a remote fetch as begun (arms single-flight + the rate window). */
135
- noteFetchStart(now) {
136
- this.inFlight = true;
137
- this.lastFetchStartedAt = now;
138
- this._remoteFetches += 1;
139
- }
140
- /** Mark the in-flight remote fetch as finished; records a failure outcome. */
141
- noteFetchEnd(result = "ok") {
142
- this.inFlight = false;
143
- if (result === "failed") this._remoteFailures += 1;
144
- }
145
- /** `true` at most once per `warnIntervalMs`; stamps the window when it fires. */
146
- shouldWarn(now) {
147
- if (this.lastWarnAt !== void 0 && now - this.lastWarnAt < this.warnIntervalMs) return false;
148
- this.lastWarnAt = now;
149
- return true;
150
- }
151
- get counters() {
152
- return {
153
- foreignHandles: this._foreignHandles,
154
- remoteFetches: this._remoteFetches,
155
- remoteFailures: this._remoteFailures,
156
- dropped: this._dropped
157
- };
158
- }
159
- };
160
- //#endregion
161
- //#region src/pipeline-runner/resolve-polled-frame.ts
162
- async function resolvePolledFrame(handle, deps) {
163
- const { ownNodeId, readers, throttle, getRemoteFrame, logger, tag } = deps;
164
- if (handle.nodeId === ownNodeId) return readers.read(handle);
165
- const now = Date.now();
166
- const decision = throttle.plan(now);
167
- if (throttle.shouldWarn(now)) logger.warn("frame poller: foreign handle — decoder session is on another node; using bounded decoder.getFrame fallback", { meta: {
168
- tag,
169
- producerNode: handle.nodeId,
170
- ownNodeId,
171
- ...throttle.counters
172
- } });
173
- if (decision === "drop") return null;
174
- throttle.noteFetchStart(now);
175
- try {
176
- const remote = await getRemoteFrame(handle);
177
- throttle.noteFetchEnd("ok");
178
- return remote;
179
- } catch (err) {
180
- throttle.noteFetchEnd("failed");
181
- logger.debug("frame poller: remote getFrame failed", { meta: {
182
- tag,
183
- producerNode: handle.nodeId,
184
- error: errMsg(err)
185
- } });
186
- return null;
187
- }
188
- }
189
- //#endregion
190
- //#region src/pipeline-runner/frame-handle-poller.ts
191
- /**
192
- * `FrameHandlePoller` — the consumer-side poll loop of the shared-memory frame
193
- * plane (Phase 5 / D9).
194
- *
195
- * Replaces the live-object `IStreamBroker.onDecodedFrame(cb)` callback path.
196
- * A consumer (motion, detection):
197
- *
198
- * 1. `subscribeFrames({ brokerId, format, maxFps, tag })` over tRPC — the
199
- * broker spins up a `frameSink: 'shm'` decoder session for that format
200
- * and returns a `subscriptionId`;
201
- * 2. polls `pullFrameHandles({ subscriptionId, maxCount })` at the cadence
202
- * `maxFps` implies, draining zero-pixel `FrameHandle`s;
203
- * 3. feeds each handle to a `FrameRingReaderCache` which opens the named shm
204
- * segment and reads the pixels back zero-copy;
205
- * 4. on teardown, `unsubscribeFrames` + closes the cached readers.
206
- *
207
- * The loop tolerates an initially-empty stream — `pullFrameHandles` returns
208
- * `[]` until the broker has a source, and a recycled ring slot yields a `null`
209
- * pixel read (a dropped frame, the correct latest-wins behaviour).
210
- *
211
- * Foreign-handle path: a `FrameHandle` carries the `nodeId` of the node whose
212
- * shared memory holds its segment. A LOCAL handle is read back zero-copy; a
213
- * FOREIGN handle (produced on another node — e.g. a camera decoded on the hub
214
- * whose detection was placed on an agent) cannot be `shm_open`ed here. Reading
215
- * it unconditionally floods `openSegment failed shm_open ENOENT` at frame rate,
216
- * so the poll delegates every handle to `resolvePolledFrame`, which gates on
217
- * `handle.nodeId`: local → shm read; foreign → a BOUNDED, single-flight
218
- * `getRemoteFrame` (`decoder.getFrame`) fallback (≤ `maxRemoteFps`) plus a
219
- * rate-limited WARN naming the topology mismatch. `ownNodeId` + `getRemoteFrame`
220
- * are REQUIRED options — every in-repo call site supplies them, so there is no
221
- * silent default that re-creates the unconditional read.
222
- *
223
- * Boot-race tolerance: the broker for a given camStream may not be registered
224
- * yet when a consumer attempts to subscribe (the pipeline-runner spawns before
225
- * provider addons publish their cameraStreams). `subscribeFrames` retries with
226
- * exponential backoff (capped at `MAX_SUBSCRIBE_RETRY_BACKOFF_MS`) until it
227
- * succeeds or the returned teardown closure is invoked. The closure always
228
- * resolves to a function, even when the broker is missing; the function
229
- * cancels pending retries and releases any subscription acquired in flight.
230
- */
231
- /** How many handles to drain per poll — a small burst absorbs jitter. */
232
- var PULL_MAX_COUNT = 4;
233
- /** Floor on the poll period so a 0/absurd `maxFps` can't busy-spin. */
234
- var MIN_POLL_INTERVAL_MS = 20;
235
- /** Poll period when the broker reports a non-positive cadence hint. */
236
- var FALLBACK_POLL_INTERVAL_MS = 200;
237
- /**
238
- * Ceiling on the poll period — we never poll SLOWER than this even when the
239
- * subscriber's `maxFps` implies a longer interval (e.g. detection at 10 fps →
240
- * 100 ms). A decoded frame otherwise sits in the ring up to a full poll period
241
- * before it is picked, and that wait lands directly in `frameAge` (the analyzed
242
- * frame's staleness). Polling faster grabs the freshest frame sooner; because
243
- * the loop reads ONLY the newest handle per tick and the decoder emits at its
244
- * own rate, the extra ticks that find no new frame are near-free (an empty
245
- * `pullHandles` + no pixel read), so this lowers latency without a proportional
246
- * read-cost increase. `maxFps` still bounds the DELIVERED rate downstream via
247
- * the latest-wins queue — this only decouples poll cadence from it.
248
- */
249
- var MAX_POLL_INTERVAL_MS = 50;
250
- /** First subscribe-retry delay, doubled on every subsequent failure. */
251
- var INITIAL_SUBSCRIBE_RETRY_BACKOFF_MS = 250;
252
- /**
253
- * Subscribe-retry backoff ceiling. 5 s is fast enough to recover within a
254
- * single roster refresh of the consuming UI and slow enough that a
255
- * misconfigured camStream costs ~12 op/min, not 50/s.
256
- */
257
- var MAX_SUBSCRIBE_RETRY_BACKOFF_MS = 5e3;
258
- /**
259
- * The default source: the broker's shm plane over tRPC — today's path. The
260
- * methods return the underlying client promises DIRECTLY (no async wrapper)
261
- * so the poller's scheduling is microtask-identical to the pre-seam code.
262
- */
263
- function brokerFrameHandleSource(api, brokerId) {
264
- return {
265
- subscribe: (input) => api.streamBroker.subscribeFrames.mutate({
266
- brokerId,
267
- format: input.format,
268
- maxFps: input.maxFps,
269
- tag: input.tag
270
- }),
271
- pullHandles: (input) => api.streamBroker.pullFrameHandles.query({
272
- subscriptionId: input.subscriptionId,
273
- maxCount: input.maxCount
274
- }),
275
- unsubscribe: (input) => api.streamBroker.unsubscribeFrames.mutate({ subscriptionId: input.subscriptionId }).then(() => void 0)
276
- };
277
- }
278
- /**
279
- * Subscribe to a broker's shm frame stream and start the poll loop. Always
280
- * resolves to a teardown closure — when the broker is not yet registered the
281
- * closure cancels the ongoing retry loop; when polling is active it stops the
282
- * loop, releases the broker subscription, and closes every shm segment the
283
- * reader cache opened.
284
- */
285
- async function startFrameHandlePoller(options) {
286
- const lifecycle = {
287
- stopped: false,
288
- retryTimer: void 0,
289
- activeTeardown: null
290
- };
291
- const teardown = () => {
292
- if (lifecycle.stopped) return;
293
- lifecycle.stopped = true;
294
- if (lifecycle.retryTimer) {
295
- clearTimeout(lifecycle.retryTimer);
296
- lifecycle.retryTimer = void 0;
297
- }
298
- lifecycle.activeTeardown?.();
299
- };
300
- subscribeWithRetry(options, lifecycle);
301
- return teardown;
302
- }
303
- /**
304
- * Run the subscribe → poll handshake with exponential backoff on subscribe
305
- * failures. Resolves once the subscription is acquired (and the poll loop has
306
- * been started) or once `lifecycle.stopped` flips, whichever comes first.
307
- */
308
- async function subscribeWithRetry(options, lifecycle) {
309
- const { api, brokerId, format, maxFps, tag, logger } = options;
310
- const source = options.source ?? brokerFrameHandleSource(api, brokerId);
311
- let backoffMs = INITIAL_SUBSCRIBE_RETRY_BACKOFF_MS;
312
- let attempt = 0;
313
- while (!lifecycle.stopped) {
314
- attempt += 1;
315
- try {
316
- const result = await source.subscribe({
317
- format,
318
- maxFps,
319
- tag
320
- });
321
- if (lifecycle.stopped) {
322
- await source.unsubscribe({ subscriptionId: result.subscriptionId }).catch((err) => {
323
- logger.warn("frame-handle poller: late unsubscribe failed", { meta: {
324
- brokerId,
325
- subscriptionId: result.subscriptionId,
326
- error: errMsg(err)
327
- } });
328
- });
329
- return;
330
- }
331
- lifecycle.activeTeardown = startPolling(options, source, result.subscriptionId, result.maxFps, lifecycle);
332
- return;
333
- } catch (err) {
334
- if (lifecycle.stopped) return;
335
- if (attempt === 1) logger.warn("frame-handle poller: subscribeFrames failed, retrying", { meta: {
336
- brokerId,
337
- format,
338
- tag,
339
- error: errMsg(err),
340
- nextRetryInMs: backoffMs
341
- } });
342
- else logger.debug("frame-handle poller: subscribeFrames still failing", { meta: {
343
- brokerId,
344
- format,
345
- tag,
346
- attempt,
347
- error: errMsg(err),
348
- nextRetryInMs: backoffMs
349
- } });
350
- await sleep(backoffMs, lifecycle);
351
- backoffMs = Math.min(MAX_SUBSCRIBE_RETRY_BACKOFF_MS, backoffMs * 2);
352
- }
353
- }
354
- }
355
- /**
356
- * Sleep `ms` milliseconds, but resolve early when `lifecycle.stopped` flips so
357
- * a teardown during a retry pause doesn't have to wait out the full backoff.
358
- */
359
- function sleep(ms, lifecycle) {
360
- return new Promise((resolve) => {
361
- lifecycle.retryTimer = setTimeout(() => {
362
- lifecycle.retryTimer = void 0;
363
- resolve();
364
- }, ms);
365
- });
366
- }
367
- /**
368
- * Run the steady-state poll loop for a successfully-acquired subscription.
369
- * Returns the teardown closure that stops the loop and releases the
370
- * subscription.
371
- */
372
- function startPolling(options, source, subscriptionId, resolvedMaxFps, lifecycle) {
373
- const { brokerId, onFrame, logger, ownNodeId, getRemoteFrame, tag } = options;
374
- const readers = new FrameRingReaderCache(logger);
375
- const throttle = new ForeignHandleThrottle();
376
- const pollIntervalMs = Math.min(MAX_POLL_INTERVAL_MS, resolvedMaxFps > 0 ? Math.max(MIN_POLL_INTERVAL_MS, Math.round(1e3 / resolvedMaxFps)) : FALLBACK_POLL_INTERVAL_MS);
377
- let timer;
378
- const tick = async () => {
379
- if (lifecycle.stopped) return;
380
- try {
381
- const handles = await source.pullHandles({
382
- subscriptionId,
383
- maxCount: PULL_MAX_COUNT
384
- });
385
- for (let i = handles.length - 1; i >= 0; i -= 1) {
386
- if (lifecycle.stopped) break;
387
- const handle = handles[i];
388
- const frame = await resolvePolledFrame(handle, {
389
- ownNodeId,
390
- readers,
391
- throttle,
392
- getRemoteFrame,
393
- logger,
394
- tag
395
- });
396
- if (frame) {
397
- onFrame(frame, handle);
398
- break;
399
- }
400
- }
401
- } catch (err) {
402
- logger.warn("frame-handle poller: pullFrameHandles failed", { meta: {
403
- brokerId,
404
- subscriptionId,
405
- error: errMsg(err)
406
- } });
407
- }
408
- if (!lifecycle.stopped) timer = setTimeout(() => void tick(), pollIntervalMs);
409
- };
410
- tick();
411
- return () => {
412
- if (timer) {
413
- clearTimeout(timer);
414
- timer = void 0;
415
- }
416
- readers.close();
417
- source.unsubscribe({ subscriptionId }).catch((err) => {
418
- logger.warn("frame-handle poller: unsubscribe failed", { meta: {
419
- brokerId,
420
- subscriptionId,
421
- error: errMsg(err)
422
- } });
423
- });
424
- };
425
- }
426
- //#endregion
427
103
  //#region src/pipeline-runner/frame-governor.ts
428
104
  var FrameGovernor = class {
429
105
  config;
@@ -1460,137 +1136,141 @@ function startGuardedSessionDecode(deps) {
1460
1136
  if (release) release();
1461
1137
  };
1462
1138
  }
1463
- //#endregion
1464
- //#region src/session-decode/retention-sink.ts
1465
- /**
1466
- * Session-decode frame retention ring (Shape-2, Slice 1).
1467
- *
1468
- * The default detection path is **session-decode** (`useSessionDecode` true):
1469
- * a per-session forked decode worker hands the runner decoded rgb pixels over
1470
- * IPC — the frames never touch shared memory, so the emitted
1471
- * `PipelineInferenceResult` carried NO `FrameHandle`, and hub-side post-analysis
1472
- * (which gates ALL event/face/track crop media on a present handle) produced no
1473
- * media. This ring restores that: every decoded detection frame is copied into
1474
- * a short shared-memory retention ring on the runner's node, and the resulting
1475
- * `FrameHandle` rides the inference-result event so post-analysis can resolve
1476
- * the exact frame zero-copy and cut crops from it.
1477
- *
1478
- * ## Why a distinct prefix (`csr.`)
1479
- *
1480
- * The decoder addon runs `purgeOrphanSegments('csf.')` at startup and unlinks
1481
- * EVERY `csf.*` segment on the node. A retention ring under the `csf.` prefix
1482
- * would be reclaimed out from under a live session on every decoder redeploy.
1483
- * The retention ring therefore uses its own prefix `csr.` and its own startup
1484
- * orphan purge (`shm-retention-purge.ts`).
1485
- *
1486
- * ## Sizing
1487
- *
1488
- * Retention is ring depth: `slots ≈ detectionFps × retainSeconds`. At the
1489
- * Slice-1 ≤640-wide detection geometry a slot is ~0.69 MB, so the 32 MB default
1490
- * budget yields ~46 latest-wins slots (~4.6 s @10 fps). Budget is per active
1491
- * session; the sink is armed lazily on the first rgb frame and destroyed on
1492
- * session teardown, so idle cameras hold no shared memory.
1493
- */
1494
- /** Segment name prefix for session-decode retention rings — isolated from the
1495
- * decoder's `csf.` orphan purge so a decoder redeploy never reclaims a live
1496
- * retention ring. */
1497
- var RETENTION_SEGMENT_PREFIX = "csr.";
1498
- /** {@link RETAIN_BUDGET_MB} in bytes. */
1499
- var RETAIN_BUDGET_BYTES = (() => {
1139
+ /** {@link RETAINED_FRAME_BUDGET_MB} in bytes. */
1140
+ var RETAINED_FRAME_BUDGET_BYTES = (() => {
1500
1141
  const raw = Number(process.env["CAMSTACK_SESSION_RETAIN_MB"]);
1501
1142
  return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 32;
1502
1143
  })() * 1024 * 1024;
1503
- /**
1504
- * Create a session-decode retention ring for one device. The underlying
1505
- * shared-memory segment is created lazily on the first rgb frame.
1506
- */
1507
- function createSessionRetentionSink(options) {
1508
- const { deviceId, nodeId, logger } = options;
1509
- const sink = new DecoderFrameRingSink({
1510
- seed: `retain:${deviceId}`,
1511
- logger,
1512
- nodeId,
1513
- segmentPrefix: RETENTION_SEGMENT_PREFIX,
1514
- budgetBytes: RETAIN_BUDGET_BYTES
1515
- });
1516
- return {
1517
- write(frame) {
1518
- if (frame.format !== "rgb") return null;
1519
- return sink.writeFrame(frame.data, {
1520
- width: frame.width,
1521
- height: frame.height,
1522
- format: frame.format,
1523
- pts: performance.now(),
1524
- byteLength: frame.data.byteLength
1525
- });
1526
- },
1527
- destroy() {
1528
- sink.destroy();
1529
- },
1530
- get currentSegmentName() {
1531
- return sink.currentSegmentName;
1532
- }
1533
- };
1144
+ /** Opaque RAM-key prefix stamped into a retained frame's `FrameHandle.shmId`. */
1145
+ var RETAINED_FRAME_KEY_PREFIX = "ram:";
1146
+ /** A retention frame is uniquely identified by its key + slot + committed seq. */
1147
+ function keyOf(handle) {
1148
+ return `${handle.shmId}#${handle.slot}#${handle.seq}`;
1534
1149
  }
1535
- //#endregion
1536
- //#region src/pipeline-runner/shm-retention-purge.ts
1537
- /**
1538
- * Startup reclamation of orphaned session-decode retention segments.
1539
- *
1540
- * The retention ring (`retention-sink.ts`) writes decoded detection frames into
1541
- * named `/dev/shm` segments under the `csr.` prefix and unlinks each on graceful
1542
- * session teardown. When the runner process dies ungracefully (SIGBUS, OOM-kill,
1543
- * SIGKILL during redeploy) that teardown never runs and the segment is orphaned.
1544
- * Across crashes/redeploys these accumulate until `/dev/shm` fills, at which
1545
- * point the next `mmap` write faults with an uncatchable SIGBUS.
1546
- *
1547
- * This is the retention-ring analogue of the decoder addon's
1548
- * `purgeOrphanSegments('csf.')`: a fresh pipeline-runner owns no live sessions,
1549
- * so every pre-existing `csr.*` segment is by definition an orphan from a dead
1550
- * instance. It MUST use the `csr.` prefix (never `csf.`): the decoder purge owns
1551
- * `csf.` and unlinking a live retention ring would break media mid-session.
1552
- *
1553
- * `shm_unlink` only removes the name — a consumer still holding a mapping keeps
1554
- * reading valid memory until it closes (POSIX deferred reclaim + the ring
1555
- * seqlock), so unlinking is safe even if a stale reader is momentarily attached.
1556
- *
1557
- * POSIX-only: segments surface as files under `/dev/shm` on Linux. On platforms
1558
- * without that directory (Windows, macOS) the scan finds nothing — no-op.
1559
- */
1560
- /** Default tmpfs directory where POSIX shared-memory segments appear on Linux. */
1561
- var DEFAULT_SHM_DIR = "/dev/shm";
1562
1150
  /**
1563
- * Unlink every session-decode retention segment whose name starts with
1564
- * `prefix`. Intended to run ONCE at pipeline-runner startup, before any session
1565
- * is created, to reclaim segments orphaned by a previously-crashed instance. A
1566
- * per-file unlink failure is swallowed so one stuck segment cannot block
1567
- * reclaiming the rest.
1151
+ * Node-level RAM store of retained rgb detection frames, keyed by
1152
+ * `FrameHandle` identity. Latest-wins with a byte budget.
1568
1153
  */
1569
- function purgeOrphanSegments(prefix, options = {}) {
1570
- const dir = options.dir ?? DEFAULT_SHM_DIR;
1571
- const unlink = options.unlink ?? unlinkSegment;
1572
- let entries;
1573
- try {
1574
- entries = readdirSync(dir);
1575
- } catch {
1576
- return {
1577
- scanned: 0,
1578
- removed: 0,
1579
- names: []
1154
+ var RetainedFrameStore = class RetainedFrameStore {
1155
+ nodeId;
1156
+ budgetBytes;
1157
+ /** Insertion-ordered (Map) → oldest is `keys().next()`. */
1158
+ entries = /* @__PURE__ */ new Map();
1159
+ bytes = 0;
1160
+ seq = 0;
1161
+ /** Ring width used only to spread the `slot` field; the map key is authoritative. */
1162
+ static SLOT_SPREAD = 1024;
1163
+ constructor(options) {
1164
+ this.nodeId = options.nodeId;
1165
+ this.budgetBytes = options.budgetBytes ?? RETAINED_FRAME_BUDGET_BYTES;
1166
+ }
1167
+ /** Number of retained frames (tests / metrics). */
1168
+ get size() {
1169
+ return this.entries.size;
1170
+ }
1171
+ /** Total retained bytes (tests / metrics). */
1172
+ get retainedBytes() {
1173
+ return this.bytes;
1174
+ }
1175
+ /**
1176
+ * Retain one decoded rgb frame and return its `FrameHandle`. Returns `null`
1177
+ * for a non-rgb frame (motion gray is never retained — post-analysis crops
1178
+ * from the rgb frame). The frame buffer is retained by reference: the
1179
+ * decode-worker IPC delivers a fresh Buffer per frame, so no defensive copy
1180
+ * is needed.
1181
+ */
1182
+ write(deviceId, frame) {
1183
+ if (frame.format !== "rgb") return null;
1184
+ const seq = ++this.seq;
1185
+ const byteLength = frame.data.byteLength;
1186
+ const handle = {
1187
+ shmId: `${RETAINED_FRAME_KEY_PREFIX}${this.nodeId}:${deviceId}`,
1188
+ slot: seq % RetainedFrameStore.SLOT_SPREAD,
1189
+ seq,
1190
+ width: frame.width,
1191
+ height: frame.height,
1192
+ format: "rgb",
1193
+ pts: performance.now(),
1194
+ byteLength,
1195
+ nodeId: this.nodeId,
1196
+ slotCount: RetainedFrameStore.SLOT_SPREAD
1580
1197
  };
1198
+ this.entries.set(keyOf(handle), frame);
1199
+ this.bytes += byteLength;
1200
+ this.evictToBudget();
1201
+ return handle;
1581
1202
  }
1582
- const names = [];
1583
- for (const name of entries) {
1584
- if (!name.startsWith(prefix)) continue;
1585
- try {
1586
- unlink(name);
1587
- names.push(name);
1588
- } catch {}
1203
+ /** The retained frame for `handle`, or `null` if never retained / already evicted. */
1204
+ getFrame(handle) {
1205
+ return this.entries.get(keyOf(handle)) ?? null;
1206
+ }
1207
+ /**
1208
+ * Crop (and optionally downscale) the retained rgb frame for `handle` to the
1209
+ * normalized `bbox`. A full-frame `bbox` ({x:0,y:0,w:1,h:1}) with no
1210
+ * `maxWidth` returns the whole frame. Returns `null` when the frame is no
1211
+ * longer retained. Nearest-neighbour scale — this is the best-effort
1212
+ * post-analysis fallback path; native-resolution ROI crops come from the
1213
+ * decode worker's surface (`getNativeCrop`), not here.
1214
+ */
1215
+ crop(handle, bbox, maxWidth) {
1216
+ const frame = this.entries.get(keyOf(handle));
1217
+ if (!frame || frame.format !== "rgb") return null;
1218
+ return cropRgb(frame, bbox, maxWidth);
1219
+ }
1220
+ /** Drop every retained frame (node/addon shutdown). */
1221
+ clear() {
1222
+ this.entries.clear();
1223
+ this.bytes = 0;
1224
+ }
1225
+ /** Evict oldest frames until the retained bytes fit the budget (keep ≥1). */
1226
+ evictToBudget() {
1227
+ while (this.bytes > this.budgetBytes && this.entries.size > 1) {
1228
+ const oldest = this.entries.keys().next().value;
1229
+ if (oldest === void 0) break;
1230
+ const evicted = this.entries.get(oldest);
1231
+ this.entries.delete(oldest);
1232
+ if (evicted) this.bytes -= evicted.data.byteLength;
1233
+ }
1234
+ if (this.bytes < 0) this.bytes = 0;
1235
+ }
1236
+ };
1237
+ /**
1238
+ * Nearest-neighbour crop + optional downscale of a packed RGB24 frame to a
1239
+ * normalized `bbox`. Exported for unit coverage. Clamps the bbox into the frame
1240
+ * and never allocates more than the output size.
1241
+ */
1242
+ function cropRgb(frame, bbox, maxWidth) {
1243
+ const srcW = frame.width;
1244
+ const srcH = frame.height;
1245
+ const nx = Math.min(Math.max(bbox.x, 0), 1);
1246
+ const ny = Math.min(Math.max(bbox.y, 0), 1);
1247
+ const nw = Math.min(Math.max(bbox.w, 0), 1 - nx);
1248
+ const nh = Math.min(Math.max(bbox.h, 0), 1 - ny);
1249
+ const cropX = Math.floor(nx * srcW);
1250
+ const cropY = Math.floor(ny * srcH);
1251
+ const cropW = Math.max(1, Math.round(nw * srcW));
1252
+ const cropH = Math.max(1, Math.round(nh * srcH));
1253
+ const clampedW = Math.min(cropW, srcW - cropX);
1254
+ const clampedH = Math.min(cropH, srcH - cropY);
1255
+ const outW = maxWidth && maxWidth > 0 && maxWidth < clampedW ? maxWidth : clampedW;
1256
+ const outH = outW === clampedW ? clampedH : Math.max(1, Math.round(outW * clampedH / clampedW));
1257
+ const src = frame.data;
1258
+ const out = Buffer.allocUnsafe(outW * outH * 3);
1259
+ for (let oy = 0; oy < outH; oy += 1) {
1260
+ const srcRow = (cropY + Math.min(clampedH - 1, Math.floor(oy * clampedH / outH))) * srcW * 3;
1261
+ const outRow = oy * outW * 3;
1262
+ for (let ox = 0; ox < outW; ox += 1) {
1263
+ const s = srcRow + (cropX + Math.min(clampedW - 1, Math.floor(ox * clampedW / outW))) * 3;
1264
+ const o = outRow + ox * 3;
1265
+ out[o] = src[s];
1266
+ out[o + 1] = src[s + 1];
1267
+ out[o + 2] = src[s + 2];
1268
+ }
1589
1269
  }
1590
1270
  return {
1591
- scanned: entries.length,
1592
- removed: names.length,
1593
- names
1271
+ bytes: out,
1272
+ width: outW,
1273
+ height: outH
1594
1274
  };
1595
1275
  }
1596
1276
  //#endregion
@@ -1980,19 +1660,6 @@ function createSessionDecodeCoordinator(deps) {
1980
1660
  //#endregion
1981
1661
  //#region src/session-decode/session-decode-pump.ts
1982
1662
  /**
1983
- * Pure gate: does this runner route camera decode through a per-session
1984
- * decode worker (Epic C) instead of the shm frame-handle poller? This is now
1985
- * a RUNNER-LEVEL setting (the pipeline-runner addon's own config,
1986
- * `this.config.useSessionDecode`) rather than a per-camera one — every
1987
- * camera attached to this node shares the same decode path. DEFAULT TRUE:
1988
- * the caller passes the runner's own `useSessionDecode` config value;
1989
- * an operator unchecks it (node-wide) to fall back to the shared shm
1990
- * frame-handle poller for every camera on this node.
1991
- */
1992
- function shouldUseSessionDecode(enabled) {
1993
- return enabled === true;
1994
- }
1995
- /**
1996
1663
  * Detection working width cap — mirrors the shm decoder's
1997
1664
  * `initScaler` (`nodeav-decoder-session.ts`: `maxW = floor(640 / scale)`,
1998
1665
  * `scale = 1` default). The worker decodes full source resolution (e.g. a 4K
@@ -2359,7 +2026,6 @@ var DEFAULT_CONFIG = {
2359
2026
  maxConcurrentInferences: 16,
2360
2027
  targetLoadPercent: 80,
2361
2028
  minThrottledFps: 1,
2362
- useSessionDecode: true,
2363
2029
  maxConcurrentDecodeSpawns: 3
2364
2030
  };
2365
2031
  /**
@@ -2375,6 +2041,11 @@ var DEFAULT_CONFIG = {
2375
2041
  * cameras produced when every gate open/close forked and killed a worker.
2376
2042
  * Mirrors Scrypted's decode-fork ~15s idle-timeout.
2377
2043
  */
2044
+ /** JPEG quality for the runner→executor detection-frame hop. q82 keeps
2045
+ * detector-relevant detail (source is h264 anyway) at ~10-15× less payload
2046
+ * than raw RGB — the hop transits the hub main process (UDS child↔child
2047
+ * routing), which OOM'd under raw frames. */
2048
+ var DETECTION_HOP_JPEG_QUALITY = 82;
2378
2049
  var DETECTION_KEEPWARM_MS = 15e3;
2379
2050
  /**
2380
2051
  * Occupancy-burst safety timeout (both the dial path and the analyzer-tap
@@ -2664,6 +2335,15 @@ var PipelineRunnerAddon = class extends BaseAddon {
2664
2335
  * to the detection-frame crop). See {@link NativeCropRegistry}.
2665
2336
  */
2666
2337
  nativeCropRegistry = new NativeCropRegistry();
2338
+ /**
2339
+ * Node-level RAM store of retained rgb detection frames, keyed by the
2340
+ * `FrameHandle` that rides the inference-result event (shm-ring removal
2341
+ * 2026-07-16 — replaces the `csr.` shm retention ring). Backs the
2342
+ * FULL-FRAME branch of `getNativeCrop` so hub-side post-analysis resolves a
2343
+ * frame's pixels over tRPC (routed by `handle.nodeId`) with no `/dev/shm`.
2344
+ * Initialised in {@link onInitialize} once `nodeId` is known.
2345
+ */
2346
+ retainedFrames = null;
2667
2347
  attached = /* @__PURE__ */ new Map();
2668
2348
  nodeId = "unknown";
2669
2349
  metricsSnapshotTimer = null;
@@ -2700,7 +2380,6 @@ var PipelineRunnerAddon = class extends BaseAddon {
2700
2380
  * payloads (`local-broker` / absent) — the map stays empty and every code
2701
2381
  * path is identical to pre-Phase-2. Torn down on detach / shutdown.
2702
2382
  */
2703
- remotePlanes = /* @__PURE__ */ new Map();
2704
2383
  /**
2705
2384
  * Devices whose motion currently rides the detection session-decode worker
2706
2385
  * (P4 co-active sharing) instead of a dedicated motion worker. Membership →
@@ -2760,8 +2439,8 @@ var PipelineRunnerAddon = class extends BaseAddon {
2760
2439
  occupancyMaxConcurrent = 3;
2761
2440
  /**
2762
2441
  * TAP-based occupancy bursts in flight, keyed by deviceId (Task 10). See
2763
- * {@link OccupancyTapState}. A device has an entry here XOR is dialing via
2764
- * `startFrameHandlePoller` in `runOccupancyBurst` — never both; the choice
2442
+ * {@link OccupancyTapState}. A device has an entry here XOR is dialing a
2443
+ * session-decode burst in `runOccupancyBurst` — never both; the choice
2765
2444
  * is made once at burst start based on `attachment.motionUnsubscribe`.
2766
2445
  */
2767
2446
  occupancyTaps = /* @__PURE__ */ new Map();
@@ -2781,16 +2460,10 @@ var PipelineRunnerAddon = class extends BaseAddon {
2781
2460
  async onInitialize() {
2782
2461
  const raw = this.ctx.kernel.localNodeId ?? this.ctx.id;
2783
2462
  this.nodeId = raw.includes("/") ? raw.split("/")[0] : raw;
2784
- try {
2785
- const purged = purgeOrphanSegments(RETENTION_SEGMENT_PREFIX);
2786
- if (purged.removed > 0) this.ctx.logger.info("session-decode retention: reclaimed orphaned shm segments", { meta: {
2787
- removed: purged.removed,
2788
- scanned: purged.scanned,
2789
- prefix: RETENTION_SEGMENT_PREFIX
2790
- } });
2791
- } catch (err) {
2792
- this.ctx.logger.warn("session-decode retention: orphan purge failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
2793
- }
2463
+ this.retainedFrames = new RetainedFrameStore({
2464
+ nodeId: this.nodeId,
2465
+ logger: this.ctx.logger.child("retained-frames")
2466
+ });
2794
2467
  this.runner = new PipelineRunner({
2795
2468
  maxQueueDepth: this.config.maxQueueDepth,
2796
2469
  maxConcurrentInferences: this.config.maxConcurrentInferences,
@@ -2863,9 +2536,6 @@ var PipelineRunnerAddon = class extends BaseAddon {
2863
2536
  }
2864
2537
  this.lastAnalyzerDetected.clear();
2865
2538
  for (const deviceId of [...this.onboardAnalyzerTeardownTimers.keys(), ...this.onboardAnalyzerSubs.keys()]) this.clearOnboardAnalyzer(deviceId);
2866
- const remotePlanes = [...this.remotePlanes.values()];
2867
- this.remotePlanes.clear();
2868
- await Promise.all(remotePlanes.map((plane) => plane.dispose().catch(() => {})));
2869
2539
  if (this.runner) {
2870
2540
  this.runner.stop();
2871
2541
  this.runner = null;
@@ -2880,6 +2550,9 @@ var PipelineRunnerAddon = class extends BaseAddon {
2880
2550
  }
2881
2551
  this.attached.clear();
2882
2552
  this.lastMotionFrameAt.clear();
2553
+ this.nativeCropRegistry.clear();
2554
+ this.retainedFrames?.clear();
2555
+ this.retainedFrames = null;
2883
2556
  }
2884
2557
  async cacheBenchFrame(input) {
2885
2558
  const sharp = (await import("sharp")).default;
@@ -3270,13 +2943,23 @@ var PipelineRunnerAddon = class extends BaseAddon {
3270
2943
  * worker downloads ONLY the ROI — a full native frame never travels the wire.
3271
2944
  */
3272
2945
  async getNativeCrop(input) {
3273
- const requester = this.nativeCropRegistry.get(input.handle);
3274
- if (!requester) return null;
3275
- const result = await requester(input.bbox, input.maxWidth);
3276
- return result ? {
3277
- bytes: result.bytes,
3278
- width: result.width,
3279
- height: result.height
2946
+ const b = input.bbox;
2947
+ if (!(b.x <= .001 && b.y <= .001 && b.w >= .999 && b.h >= .999)) {
2948
+ const requester = this.nativeCropRegistry.get(input.handle);
2949
+ if (requester) {
2950
+ const result = await requester(input.bbox, input.maxWidth);
2951
+ if (result) return {
2952
+ bytes: result.bytes,
2953
+ width: result.width,
2954
+ height: result.height
2955
+ };
2956
+ }
2957
+ }
2958
+ const crop = this.retainedFrames?.crop(input.handle, input.bbox, input.maxWidth);
2959
+ return crop ? {
2960
+ bytes: crop.bytes,
2961
+ width: crop.width,
2962
+ height: crop.height
3280
2963
  } : null;
3281
2964
  }
3282
2965
  /**
@@ -3409,16 +3092,6 @@ var PipelineRunnerAddon = class extends BaseAddon {
3409
3092
  attachment.detectionUnsubscribe?.();
3410
3093
  this.lastMotionFrameAt.delete(deviceId);
3411
3094
  this.lastDecodeUnexpectedEndAt.delete(deviceId);
3412
- const remotePlane = this.remotePlanes.get(deviceId);
3413
- if (remotePlane) {
3414
- this.remotePlanes.delete(deviceId);
3415
- remotePlane.dispose().catch((err) => {
3416
- this.ctx?.logger.debug("remote-source plane dispose failed on detach", {
3417
- tags: { deviceId },
3418
- meta: { error: errMsg(err) }
3419
- });
3420
- });
3421
- }
3422
3095
  this.attached.delete(deviceId);
3423
3096
  this.lastMotionAt.delete(deviceId);
3424
3097
  this.lastEmittedCameraMetrics.delete(deviceId);
@@ -3536,65 +3209,6 @@ var PipelineRunnerAddon = class extends BaseAddon {
3536
3209
  return [...this.attached.keys()];
3537
3210
  }
3538
3211
  /**
3539
- * Cross-node frame fetch for FOREIGN handles (segment on another node). Wired
3540
- * into every `startFrameHandlePoller` call so `resolvePolledFrame` can take
3541
- * the bounded `decoder.getFrame` fallback instead of an unmappable local shm
3542
- * read. The `nodeId` selector routes the call to the producing node (the
3543
- * cap's `nodeIdMode: 'routing'` default; agent→hub via `$hub-cap-fwd`). The
3544
- * wire schema returns `data: Uint8Array`; downstream inference expects a Node
3545
- * `Buffer`, so we adapt it here exactly as post-analysis does.
3546
- */
3547
- async getRemoteFrame(handle) {
3548
- const api = this.ctx.api;
3549
- if (!api) return null;
3550
- const remote = await api.decoder.getFrame.query({
3551
- handle,
3552
- nodeId: handle.nodeId
3553
- });
3554
- if (!remote) return null;
3555
- return {
3556
- data: Buffer.from(remote.data),
3557
- width: remote.width,
3558
- height: remote.height,
3559
- format: remote.format,
3560
- timestamp: remote.timestamp
3561
- };
3562
- }
3563
- /**
3564
- * The remote-source leg for a camera, or `null` for today's co-located
3565
- * broker path (P2d). Created lazily on the FIRST subscription of a
3566
- * `remote-restream` camera and shared by its motion + detection pollers;
3567
- * `detachInternal` / `onShutdown` dispose it. With rollout OFF every
3568
- * attach payload is `local-broker` (or absent) → always `null` → the
3569
- * subscribe paths below are byte-identical to pre-Phase-2.
3570
- */
3571
- remoteSourceFor(config) {
3572
- const frameSource = config.frameSource;
3573
- if (!isRemoteRestream(frameSource)) return null;
3574
- const existing = this.remotePlanes.get(config.deviceId);
3575
- if (existing) return existing;
3576
- const api = this.ctx.api;
3577
- if (!api) return null;
3578
- const hostname = resolveOwnerRestreamHost(frameSource, process.env["CAMSTACK_HUB_URL"]);
3579
- const plane = new RemoteSourcePlane({
3580
- api,
3581
- logger: this.ctx.logger,
3582
- deviceId: config.deviceId,
3583
- ownNodeId: this.nodeId,
3584
- ownerNodeId: frameSource.ownerNodeId,
3585
- hostname
3586
- });
3587
- this.ctx.logger.info("remote-source leg armed for camera", {
3588
- tags: { deviceId: config.deviceId },
3589
- meta: {
3590
- ownerNodeId: frameSource.ownerNodeId,
3591
- hostname: hostname ?? "(unresolved — acquires will fail until set)"
3592
- }
3593
- });
3594
- this.remotePlanes.set(config.deviceId, plane);
3595
- return plane;
3596
- }
3597
- /**
3598
3212
  * Thin delegator to the module-level {@link acquireSessionDecodeRestreamFrom}
3599
3213
  * (see its doc for the acquire behavior) — supplies this addon's `ctx.logger`.
3600
3214
  * Kept as a method so the two call sites need no change.
@@ -3696,11 +3310,7 @@ var PipelineRunnerAddon = class extends BaseAddon {
3696
3310
  const runner = this.runner;
3697
3311
  const log = this.ctx.logger.withTags({ deviceId: config.deviceId });
3698
3312
  if (!runner) return () => {};
3699
- const retentionSink = createSessionRetentionSink({
3700
- deviceId: config.deviceId,
3701
- nodeId: this.nodeId,
3702
- logger: log
3703
- });
3313
+ const retainedFrames = this.retainedFrames;
3704
3314
  const teardown = startGuardedSessionDecode({
3705
3315
  logger: log,
3706
3316
  acquire: () => this.acquireSessionDecodeRestream(api, config.deviceId, config.detectionStreamId, `session-decode:detect:${config.deviceId}`, resolveSessionDecodeHostname(config, process.env["CAMSTACK_HUB_URL"]), resolveSessionDecodeOwnerNodeId(config)),
@@ -3720,7 +3330,7 @@ var PipelineRunnerAddon = class extends BaseAddon {
3720
3330
  acquireSpawnSlot: this.buildDecodeSpawnAcquire(log, "detect"),
3721
3331
  onEnded: () => this.handleDetectionDecodeEnded(config.deviceId),
3722
3332
  onDecodedFrame: (frame, nativeCrop) => {
3723
- const handle = retentionSink.write(frame) ?? void 0;
3333
+ const handle = retainedFrames?.write(config.deviceId, frame) ?? void 0;
3724
3334
  if (handle && nativeCrop) this.nativeCropRegistry.register(handle, nativeCrop);
3725
3335
  this.enqueueSharedDetectionFrame(config.deviceId, frame, handle);
3726
3336
  }
@@ -3729,7 +3339,6 @@ var PipelineRunnerAddon = class extends BaseAddon {
3729
3339
  });
3730
3340
  return () => {
3731
3341
  teardown();
3732
- retentionSink.destroy();
3733
3342
  };
3734
3343
  }
3735
3344
  /**
@@ -3795,30 +3404,8 @@ var PipelineRunnerAddon = class extends BaseAddon {
3795
3404
  log.warn("subscribeMotionFrames: this.ctx.api not available");
3796
3405
  return null;
3797
3406
  }
3798
- if (shouldUseSessionDecode(this.config.useSessionDecode)) {
3799
- if (resolveMotionFrameSource(config, opts?.sharedWithDetection === true).shared) return this.registerSharedMotionSink(config.deviceId, config.motionFps);
3800
- return this.startMotionSessionDecode(config, api);
3801
- }
3802
- const src = resolveMotionFrameSource(config, opts?.sharedWithDetection === true);
3803
- const shared = src.shared;
3804
- const streamId = src.streamId;
3805
- const remote = this.remoteSourceFor(config);
3806
- return startFrameHandlePoller({
3807
- api,
3808
- brokerId: makeSourceBrokerId(config.deviceId, streamId),
3809
- format: src.format,
3810
- maxFps: config.motionFps,
3811
- tag: shared ? "motion-shared" : "motion",
3812
- logger: log,
3813
- ownNodeId: this.nodeId,
3814
- getRemoteFrame: (handle) => this.getRemoteFrame(handle),
3815
- ...remote ? { source: remote.makeSource(streamId) } : {},
3816
- onFrame: shared ? (frame) => {
3817
- runner.enqueueMotionFrame(config.deviceId, rgbFrameToGrayFrame(frame), void 0);
3818
- } : (frame, handle) => {
3819
- runner.enqueueMotionFrame(config.deviceId, frame, handle);
3820
- }
3821
- });
3407
+ if (resolveMotionFrameSource(config, opts?.sharedWithDetection === true).shared) return this.registerSharedMotionSink(config.deviceId, config.motionFps);
3408
+ return this.startMotionSessionDecode(config, api);
3822
3409
  }
3823
3410
  handleDetectionStreamChange(deviceId, action) {
3824
3411
  const attachment = this.attached.get(deviceId);
@@ -3906,24 +3493,9 @@ var PipelineRunnerAddon = class extends BaseAddon {
3906
3493
  log.warn("subscribeDetectionFrames: this.ctx.api not available");
3907
3494
  return null;
3908
3495
  }
3909
- if (shouldUseSessionDecode(this.config.useSessionDecode)) return this.startDetectionSessionDecode(config, api);
3910
- const remote = this.remoteSourceFor(config);
3911
- return startFrameHandlePoller({
3912
- api,
3913
- brokerId: makeSourceBrokerId(config.deviceId, config.detectionStreamId),
3914
- format: "rgb",
3915
- maxFps: config.detectionFps,
3916
- tag: "detection",
3917
- logger: log,
3918
- ownNodeId: this.nodeId,
3919
- getRemoteFrame: (handle) => this.getRemoteFrame(handle),
3920
- ...remote ? { source: remote.makeSource(config.detectionStreamId) } : {},
3921
- onFrame: (frame, handle) => {
3922
- runner.enqueueDetectionFrame(config.deviceId, frame, handle);
3923
- }
3924
- });
3496
+ return this.startDetectionSessionDecode(config, api);
3925
3497
  }
3926
- async runInference(deviceId, frame, handle) {
3498
+ async runInference(deviceId, frame, _handle) {
3927
3499
  if (!this.ctx) return null;
3928
3500
  const log = this.ctx.logger.withTags({ deviceId });
3929
3501
  const api = this.ctx.api;
@@ -3937,11 +3509,20 @@ var PipelineRunnerAddon = class extends BaseAddon {
3937
3509
  return null;
3938
3510
  }
3939
3511
  if (steps.length === 0) return null;
3940
- const useHandle = handle !== void 0 && handle.nodeId === this.nodeId && handle.width === frame.width && handle.height === frame.height;
3512
+ let image;
3513
+ if (frame.format === "rgb") try {
3514
+ image = await sharp(frame.data, { raw: {
3515
+ width: frame.width,
3516
+ height: frame.height,
3517
+ channels: 3
3518
+ } }).jpeg({ quality: DETECTION_HOP_JPEG_QUALITY }).toBuffer();
3519
+ } catch (err) {
3520
+ log.debug("runInference: frame JPEG encode failed — falling back to raw pixels", { meta: { error: errMsg(err) } });
3521
+ }
3941
3522
  try {
3942
3523
  return await api.pipelineExecutor.runPipeline.mutate({
3943
3524
  steps: [...steps],
3944
- ...useHandle ? { frameHandle: handle } : { frame },
3525
+ ...image !== void 0 ? { image } : { frame },
3945
3526
  deviceId,
3946
3527
  plane: "frame"
3947
3528
  });
@@ -3965,10 +3546,9 @@ var PipelineRunnerAddon = class extends BaseAddon {
3965
3546
  log.warn("runMotionAnalysis: this.ctx.api not available");
3966
3547
  return;
3967
3548
  }
3968
- const useHandle = handle !== void 0 && handle.nodeId === this.nodeId;
3969
3549
  const result = await api.motionDetection.analyze.mutate({
3970
3550
  deviceId,
3971
- ...useHandle ? { frameHandle: handle } : { frame: toFrameInput(frame) }
3551
+ frame: toFrameInput(frame)
3972
3552
  });
3973
3553
  if (!result) return;
3974
3554
  const detected = result.regions.length > 0;
@@ -4186,9 +3766,9 @@ var PipelineRunnerAddon = class extends BaseAddon {
4186
3766
  await this.runOccupancyDial(deviceId, frames, attachment, runner, api, log, false);
4187
3767
  }
4188
3768
  /**
4189
- * Dial-path occupancy burst: subscribes a fresh main-stream decode session
4190
- * via `startFrameHandlePoller` and collects `frames` handles (or times out
4191
- * at {@link OCCUPANCY_BURST_SAFETY_TIMEOUT_MS}). Called either directly
3769
+ * Dial-path occupancy burst: spins up a fresh per-session decode worker
3770
+ * (session-decode) over the main stream and collects `frames` decoded frames
3771
+ * (or times out at {@link OCCUPANCY_BURST_SAFETY_TIMEOUT_MS}). Called either directly
4192
3772
  * from `runOccupancyBurst` (no live/fresh motion tap available,
4193
3773
  * `alreadyInFlight: false`) or as the Task 10 hardening #2 fallback after
4194
3774
  * a zero-collected tap (`alreadyInFlight: true` — the tap already claimed
@@ -4197,6 +3777,7 @@ var PipelineRunnerAddon = class extends BaseAddon {
4197
3777
  */
4198
3778
  async runOccupancyDial(deviceId, frames, attachment, runner, api, log, alreadyInFlight) {
4199
3779
  const config = attachment.config;
3780
+ const retainedFrames = this.retainedFrames;
4200
3781
  if (!alreadyInFlight) {
4201
3782
  this.occupancyBurstInFlight.add(deviceId);
4202
3783
  this.occupancyBurstFound.delete(deviceId);
@@ -4206,37 +3787,35 @@ var PipelineRunnerAddon = class extends BaseAddon {
4206
3787
  fallback: alreadyInFlight
4207
3788
  } });
4208
3789
  let count = 0;
4209
- let unsubscribe = null;
4210
- let unsubbed = false;
4211
3790
  let settled = false;
4212
- const doUnsub = () => {
4213
- if (!unsubbed && unsubscribe) {
4214
- unsubbed = true;
4215
- unsubscribe();
4216
- }
4217
- };
3791
+ let teardown = null;
4218
3792
  const cleanup = () => {
4219
3793
  if (settled) return;
4220
3794
  settled = true;
4221
- doUnsub();
3795
+ teardown?.();
4222
3796
  this.finishOccupancyBurst(deviceId, log, count);
4223
3797
  };
4224
3798
  const safetyTimer = setTimeout(() => {
4225
3799
  log.debug("occupancy re-check: safety timeout reached", { meta: { collected: count } });
4226
3800
  cleanup();
4227
3801
  }, OCCUPANCY_BURST_SAFETY_TIMEOUT_MS);
4228
- try {
4229
- unsubscribe = await startFrameHandlePoller({
4230
- api,
4231
- brokerId: makeSourceBrokerId(config.deviceId, config.detectionStreamId),
4232
- format: "rgb",
4233
- maxFps: config.detectionFps,
4234
- tag: "occupancy",
3802
+ teardown = startGuardedSessionDecode({
3803
+ logger: log,
3804
+ acquire: () => this.acquireSessionDecodeRestream(api, config.deviceId, config.detectionStreamId, `session-decode:occupancy:${config.deviceId}`, resolveSessionDecodeHostname(config, process.env["CAMSTACK_HUB_URL"]), resolveSessionDecodeOwnerNodeId(config)),
3805
+ startPump: (source) => startSessionDecodePump({
3806
+ fork: forkDecodeWorker,
4235
3807
  logger: log,
4236
- ownNodeId: this.nodeId,
4237
- getRemoteFrame: (handle) => this.getRemoteFrame(handle),
4238
- onFrame: (frame, handle) => {
3808
+ source,
3809
+ opts: {
3810
+ fps: config.detectionFps,
3811
+ format: "rgb"
3812
+ },
3813
+ acquireSpawnSlot: this.buildDecodeSpawnAcquire(log, "occupancy"),
3814
+ onEnded: () => cleanup(),
3815
+ onDecodedFrame: (frame, nativeCrop) => {
4239
3816
  if (settled) return;
3817
+ const handle = retainedFrames?.write(config.deviceId, frame) ?? void 0;
3818
+ if (handle && nativeCrop) this.nativeCropRegistry.register(handle, nativeCrop);
4240
3819
  runner.enqueueOccupancyFrame(deviceId, frame, handle);
4241
3820
  count++;
4242
3821
  if (count >= frames) {
@@ -4244,17 +3823,11 @@ var PipelineRunnerAddon = class extends BaseAddon {
4244
3823
  cleanup();
4245
3824
  }
4246
3825
  }
4247
- });
4248
- } catch (err) {
4249
- clearTimeout(safetyTimer);
4250
- this.occupancyBurstInFlight.delete(deviceId);
4251
- this.occupancyBurstFound.delete(deviceId);
4252
- log.debug("occupancy re-check: poller start failed", { meta: { error: errMsg(err) } });
4253
- return;
4254
- }
3826
+ })
3827
+ });
4255
3828
  if (settled) {
4256
3829
  clearTimeout(safetyTimer);
4257
- doUnsub();
3830
+ teardown();
4258
3831
  }
4259
3832
  }
4260
3833
  emitInferenceResult(deviceId, frame, result, handle) {
@@ -4388,14 +3961,6 @@ var PipelineRunnerAddon = class extends BaseAddon {
4388
3961
  default: DEFAULT_CONFIG.minThrottledFps,
4389
3962
  showValue: true
4390
3963
  },
4391
- {
4392
- type: "boolean",
4393
- key: "useSessionDecode",
4394
- style: "checkbox",
4395
- label: "Use per-session decode workers",
4396
- description: "Default decode path for every camera on this runner/node: each attached camera decodes in a disposable per-session worker process instead of the shared shm frame-handle poller, freeing the VAAPI/GPU decode pool (and any /dev/shm ring segments) as soon as it goes idle. Uncheck to fall this node back to the shared shm frame-handle poller for ALL its cameras — no per-camera override.",
4397
- default: DEFAULT_CONFIG.useSessionDecode
4398
- },
4399
3964
  {
4400
3965
  type: "slider",
4401
3966
  key: "maxConcurrentDecodeSpawns",
@@ -4418,7 +3983,6 @@ var PipelineRunnerAddon = class extends BaseAddon {
4418
3983
  maxConcurrentInferences: this.config.maxConcurrentInferences,
4419
3984
  targetLoadPercent: this.config.targetLoadPercent,
4420
3985
  minThrottledFps: this.config.minThrottledFps,
4421
- useSessionDecode: this.config.useSessionDecode,
4422
3986
  maxConcurrentDecodeSpawns: this.config.maxConcurrentDecodeSpawns
4423
3987
  } });
4424
3988
  }