@camstack/addon-pipeline 1.1.34 → 1.1.36

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 (63) hide show
  1. package/assets/reference-audio/dog-bark.wav +0 -0
  2. package/assets/reference-audio/meow.wav +0 -0
  3. package/assets/reference-audio/silence.wav +0 -0
  4. package/assets/reference-audio/siren.wav +0 -0
  5. package/assets/reference-audio/speech.wav +0 -0
  6. package/assets/reference-audio/synthetic-alarm.wav +0 -0
  7. package/assets/reference-audio/synthetic-bark.wav +0 -0
  8. package/assets/reference-audio/synthetic-cry.wav +0 -0
  9. package/assets/reference-audio/synthetic-speech.wav +0 -0
  10. package/assets/reference-images/1-bird.jpg +0 -0
  11. package/assets/reference-images/1-car-plate.jpg +0 -0
  12. package/assets/reference-images/2-birds.jpg +0 -0
  13. package/assets/reference-images/2-cars-plates.jpg +0 -0
  14. package/assets/reference-images/3-persons.jpg +0 -0
  15. package/assets/reference-images/README.md +16 -0
  16. package/assets/reference-images/animals-group.jpg +0 -0
  17. package/assets/reference-images/ground-truth/1-bird.json +22 -0
  18. package/assets/reference-images/ground-truth/1-car-plate.json +85 -0
  19. package/assets/reference-images/ground-truth/2-birds.json +35 -0
  20. package/assets/reference-images/ground-truth/2-cars-plates.json +137 -0
  21. package/assets/reference-images/ground-truth/3-persons.json +186 -0
  22. package/assets/reference-images/ground-truth/animals-group.json +87 -0
  23. package/assets/reference-images/ground-truth/persons-cars-animal.json +136 -0
  24. package/assets/reference-images/ground-truth/sinner.json +73 -0
  25. package/assets/reference-images/persons-cars-animal.jpg +0 -0
  26. package/assets/reference-images/sinner.jpg +0 -0
  27. package/dist/audio-analyzer/index.js +1 -1
  28. package/dist/audio-analyzer/index.mjs +1 -1
  29. package/dist/audio-codec-ffmpeg/index.js +1 -1
  30. package/dist/audio-codec-ffmpeg/index.mjs +1 -1
  31. package/dist/detection-pipeline/index.js +3 -1
  32. package/dist/detection-pipeline/index.mjs +3 -1
  33. package/dist/{dist-CfSORkv2.mjs → dist-BESCfHIV.mjs} +35 -128
  34. package/dist/{dist-BrIE85BG.js → dist-BZBQc2QZ.js} +34 -145
  35. package/dist/{frame-handle-plane-C05rq9Zs.mjs → frame-handle-plane-CYtnVPIg.mjs} +1 -1
  36. package/dist/{frame-handle-plane-zMju9vmk.js → frame-handle-plane-ChjxN8oI.js} +1 -1
  37. package/dist/motion-wasm/index.js +1 -1
  38. package/dist/motion-wasm/index.mjs +1 -1
  39. package/dist/pipeline-runner/index.js +2 -2
  40. package/dist/pipeline-runner/index.mjs +2 -2
  41. package/dist/recorder/index.js +1 -1
  42. package/dist/recorder/index.mjs +1 -1
  43. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-DPFAbcUo.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-BDLr3512.mjs} +2 -2
  44. package/dist/stream-broker/{hostInit-C8slrxw1.mjs → hostInit-C0Y3vfFE.mjs} +2 -2
  45. package/dist/stream-broker/index.js +133 -18
  46. package/dist/stream-broker/index.mjs +119 -4
  47. package/dist/stream-broker/remoteEntry.js +1 -1
  48. package/embed-dist/assets/{MaskShapeCanvas-DI4BY7W2-WUVfFzT-.js → MaskShapeCanvas-DI4BY7W2-BL-S3O0Z.js} +1 -1
  49. package/embed-dist/assets/{MotionZonesSettings-NcxxQN8r-CF7FXXLs.js → MotionZonesSettings-NcxxQN8r-DcnKZAt6.js} +1 -1
  50. package/embed-dist/assets/{PrivacyMaskSettings-APgPLF7p-qQCpVob3.js → PrivacyMaskSettings-APgPLF7p-DQ0MK5T9.js} +1 -1
  51. package/embed-dist/assets/{index-BNhisVUZ.js → index-BCGUC-8v.js} +7 -7
  52. package/embed-dist/index.html +1 -1
  53. package/package.json +3 -57
  54. package/dist/decoder-ffmpeg/index.js +0 -1114
  55. package/dist/decoder-ffmpeg/index.mjs +0 -1097
  56. package/dist/decoder-nodeav/index.js +0 -1422
  57. package/dist/decoder-nodeav/index.mjs +0 -1414
  58. package/dist/ffmpeg-args-CpeRWwL4.mjs +0 -326
  59. package/dist/ffmpeg-args-Dl9mLcOC.js +0 -421
  60. package/dist/frame-dropper-AjheBGMG.mjs +0 -22
  61. package/dist/frame-dropper-DKLM6pMz.js +0 -27
  62. package/dist/frame-ring-sink-1aLGcNNf.mjs +0 -557
  63. package/dist/frame-ring-sink-CvlcAUOu.js +0 -604
@@ -1,557 +0,0 @@
1
- import { d as HWACCEL_OPTIONS, p as RingBuffer } from "./dist-CfSORkv2.mjs";
2
- import { FrameRingWriter, MIN_RING_SLOTS, computeSegmentSize, computeSlotByteLength, createSegment, deriveSlotCount } from "@camstack/shm-ring";
3
- //#region src/shared/decoder-backend-keys.ts
4
- /** Built-in default when a node has no selection — the in-process node-av
5
- * decoder. node-av is the standing default everywhere; the ffmpeg subprocess
6
- * decoder is an explicit opt-in fallback only. A stale/failed settings read at
7
- * boot therefore resolves to node-av (never leaves the node with no decoder). */
8
- var DEFAULT_DECODER_BACKEND = "nodeav";
9
- /** Narrow an unknown settings value to a {@link DecoderBackend}, else `null`. */
10
- function parseDecoderBackend(value) {
11
- return value === "ffmpeg" || value === "nodeav" ? value : null;
12
- }
13
- /**
14
- * Normalise a raw kernel node id to the bare node id used for scoping.
15
- * `localNodeId` can carry a `<node>/<addon>` suffix; the decoder selection is
16
- * per-NODE, so strip the addon segment. Falls back to `hub`.
17
- */
18
- function normalizeDecoderNodeId(rawNodeId) {
19
- const raw = rawNodeId ?? "hub";
20
- return raw.includes("/") ? raw.split("/")[0] ?? "hub" : raw;
21
- }
22
- //#endregion
23
- //#region src/shared/decoder-backend.ts
24
- /**
25
- * Decoder backend selection — decides which decoder addon registers the
26
- * `decoder` cap on a node.
27
- *
28
- * Two decoder addons ship in this bundle: `decoder-ffmpeg` (subprocess
29
- * decode; a decode crash is isolated to the child) and `decoder-nodeav`
30
- * (in-process decode via FFmpeg native bindings; no subprocess lifecycle).
31
- * Both are installed on every node, but only ONE may provide the `decoder`
32
- * cap at a time.
33
- *
34
- * ## Why selection happens at REGISTRATION time (race-free by construction)
35
- *
36
- * The `decoder` cap is a singleton. Historically both decoder addons
37
- * registered a provider and the active slot was resolved AFTER the fact —
38
- * which exposed a boot-order race: whichever addon's runner initialised
39
- * first briefly held the active slot, and any consumer that resolved the
40
- * cap inside that window was dispatched to the wrong backend (the
41
- * cap-declared `preferredProvider` override only corrects the slot when
42
- * the preferred addon's registration eventually lands).
43
- *
44
- * This module removes the race by construction instead of arbitrating it:
45
- * each decoder addon calls {@link resolveDecoderBackend} at the START of
46
- * its `onInitialize` and registers its provider ONLY when it is the
47
- * selected backend — the other addon returns no registrations at all. At
48
- * most one `decoder` provider ever exists per node, so no resolution layer
49
- * (kernel `CapabilityRegistry`, route resolver, UDS child preference) can
50
- * pick a wrong one, regardless of boot order or timing.
51
- *
52
- * ## The setting
53
- *
54
- * The per-node selection lives in the `decoder-ffmpeg` OWNER addon's global
55
- * settings — the standard `addon-settings` surface, visible in the admin UI
56
- * as the owner's `backend` select field. The store is hub-central and the
57
- * value is persisted node-scoped as `backend@<nodeId>`
58
- * (`decoder-backend-keys.ts`); the owner's `getGlobalSettings` projects the
59
- * requested node's value onto the bare `backend` field.
60
- *
61
- * Both decoder addons read it the SAME way, placement-agnostically: via
62
- * `ctx.api.addonSettings.getGlobalSettings({ addonId: 'decoder-ffmpeg',
63
- * nodeId })`. The `addon-settings` cap is hub-routed at the system level
64
- * (`AddonCallGateway.classify` sends settings calls to the addon's base
65
- * node — the hub instance answers for every node), so an agent addon
66
- * transparently reads the hub-central store with no placement branching.
67
- * NOT used: `ctx.settings.getSection` (node-local — empty on an agent, the
68
- * original bug), the raw settings-store cap, or any custom side channel.
69
- *
70
- * Resolution: the node's scoped value → the built-in default
71
- * {@link DEFAULT_DECODER_BACKEND} (`'nodeav'` — node-av is primary everywhere;
72
- * ffmpeg is an explicit opt-in fallback only). There is deliberately NO
73
- * bare-key fallback (see `decoder-backend-keys.ts`), and any read failure
74
- * resolves to the default so a decoder still comes up — and, because the
75
- * default IS the primary backend, a stale/failed read can never leave the node
76
- * with NO decoder (the old `'ffmpeg'` default made node-av stand down on a
77
- * missed read → both addons down).
78
- *
79
- * ## Switching backends
80
- *
81
- * Because registration is decided once at addon init, changing the setting
82
- * takes effect on the next restart of the two decoder addons on the
83
- * affected node (addon restart / redeploy / node reboot). This is the
84
- * price of race-freedom: there is deliberately NO live re-arbitration
85
- * path — a live hand-off would reintroduce a window with two providers.
86
- */
87
- /** The addon whose global settings OWN the per-node `backend` field. */
88
- var DECODER_OWNER_ADDON_ID = "decoder-ffmpeg";
89
- /** Fail-safe when the owner's hwaccel can't be read: defer to the local probe. */
90
- var DEFAULT_DECODER_HWACCEL = "auto";
91
- /** Narrow an arbitrary stored value to a known {@link HwAccelChoice}, else null. */
92
- function parseDecoderHwAccel(raw) {
93
- if (typeof raw !== "string") return null;
94
- const match = HWACCEL_OPTIONS.find((o) => o.value === raw);
95
- return match ? match.value : null;
96
- }
97
- function isHydratedField(entry) {
98
- return typeof entry === "object" && entry !== null && "key" in entry;
99
- }
100
- /**
101
- * Pure selection from an already-read hydrated settings payload: extract the
102
- * owner's `backend` field value (which the owner projected per-node from its
103
- * scoped store key) and narrow it. A missing/invalid field or a null payload
104
- * resolves to {@link DEFAULT_DECODER_BACKEND} — never a bare store key.
105
- */
106
- function pickDecoderBackendFromSettings(view) {
107
- if (view === null) return DEFAULT_DECODER_BACKEND;
108
- for (const section of view.sections) for (const entry of section.fields) {
109
- if (!isHydratedField(entry) || entry.key !== "backend") continue;
110
- return parseDecoderBackend(entry.value) ?? "nodeav";
111
- }
112
- return DEFAULT_DECODER_BACKEND;
113
- }
114
- /**
115
- * Resolve the OWNER addon's (`decoder-ffmpeg`) own per-node backend from its
116
- * ALREADY-PROJECTED global store — the store `BaseAddon.resolveGlobalStore`
117
- * returns, where the `perNode` `backend` field carries THIS node's value on
118
- * its bare key. The owner MUST use this instead of {@link resolveDecoderBackend}:
119
- * routing `addonSettings.getGlobalSettings({addonId:'decoder-ffmpeg'})` back to
120
- * itself during its OWN `onInitialize` DEADLOCKS (the addon is not "loaded" on
121
- * the node until init completes, but init is blocked on the read) → the read
122
- * throws `transport-failed (addon not loaded)` → it silently defaults to the
123
- * built-in default and mis-decides its own registration (e.g. an explicitly
124
- * selected `ffmpeg` fallback would never come up). Reading its own store is
125
- * local, race-free, and has no deadlock.
126
- */
127
- function resolveOwnDecoderBackend(projectedGlobalStore) {
128
- return parseDecoderBackend(projectedGlobalStore["backend"]) ?? "nodeav";
129
- }
130
- /** Transient transport/settings-store fingerprints worth retrying on. */
131
- function isTransientSettingsError(message) {
132
- return /not routable/i.test(message) || /not loaded/i.test(message) || /transport-failed/i.test(message) || /not connected/i.test(message) || /provider not available/i.test(message) || /SqliteSettingsBackend not initialized/i.test(message);
133
- }
134
- /**
135
- * Resolve the decoder backend a NON-OWNER addon (`decoder-nodeav`) should run,
136
- * by reading the OWNER's (`decoder-ffmpeg`) hub-central per-node `backend`.
137
- *
138
- * The read routes to the owner addon's child runner; during a simultaneous
139
- * (re)start the owner may not be up yet → a transient `transport-failed (addon
140
- * not loaded)`. Immediately defaulting here would ignore an explicit `ffmpeg`
141
- * selection (the node would silently run the node-av default instead). So retry
142
- * on the transient fingerprints with a bounded budget (mirrors
143
- * `BaseAddon.readAddonStoreWithRetry`) until the owner answers; only a
144
- * persistent failure falls back to {@link DEFAULT_DECODER_BACKEND}.
145
- *
146
- * The OWNER addon must NOT call this (it would self-route + deadlock) — it uses
147
- * {@link resolveOwnDecoderBackend} against its own store instead.
148
- */
149
- async function resolveDecoderBackend(api, nodeId, logger) {
150
- if (!api) {
151
- logger.warn("decoder-backend: no api surface — using default backend", { meta: { default: DEFAULT_DECODER_BACKEND } });
152
- return DEFAULT_DECODER_BACKEND;
153
- }
154
- const normalized = normalizeDecoderNodeId(nodeId);
155
- const delaysMs = [
156
- 150,
157
- 350,
158
- 600,
159
- 900,
160
- 1200
161
- ];
162
- let lastErr;
163
- for (let attempt = 0; attempt <= delaysMs.length; attempt++) {
164
- try {
165
- const view = await api.addonSettings.getGlobalSettings.query({
166
- addonId: DECODER_OWNER_ADDON_ID,
167
- nodeId: normalized
168
- });
169
- if (view !== null) return pickDecoderBackendFromSettings(view);
170
- lastErr = /* @__PURE__ */ new Error("owner settings unavailable (null)");
171
- } catch (err) {
172
- lastErr = err;
173
- const msg = err instanceof Error ? err.message : String(err);
174
- if (!isTransientSettingsError(msg)) {
175
- logger.warn("decoder-backend: settings read failed — using default backend", { meta: {
176
- default: DEFAULT_DECODER_BACKEND,
177
- error: msg
178
- } });
179
- return DEFAULT_DECODER_BACKEND;
180
- }
181
- }
182
- if (attempt === delaysMs.length) break;
183
- await new Promise((resolve) => setTimeout(resolve, delaysMs[attempt]));
184
- }
185
- logger.warn("decoder-backend: owner settings unavailable after retries — using default backend", { meta: {
186
- default: DEFAULT_DECODER_BACKEND,
187
- owner: DECODER_OWNER_ADDON_ID,
188
- error: lastErr instanceof Error ? lastErr.message : String(lastErr)
189
- } });
190
- return DEFAULT_DECODER_BACKEND;
191
- }
192
- /**
193
- * Pure selection of the owner's `hwaccel` field from an already-read hydrated
194
- * settings payload. Missing/invalid/null → {@link DEFAULT_DECODER_HWACCEL}.
195
- */
196
- function pickDecoderHwAccelFromSettings(view) {
197
- if (view === null) return DEFAULT_DECODER_HWACCEL;
198
- for (const section of view.sections) for (const entry of section.fields) {
199
- if (!isHydratedField(entry) || entry.key !== "hwaccel") continue;
200
- return parseDecoderHwAccel(entry.value) ?? "auto";
201
- }
202
- return DEFAULT_DECODER_HWACCEL;
203
- }
204
- /**
205
- * Resolve the effective decoder hwaccel override for a node by reading the
206
- * `decoder-ffmpeg` OWNER's `hwaccel@<node>` setting — the exact same
207
- * hub-routed, placement-agnostic read as {@link resolveDecoderBackend}, so
208
- * node-av and ffmpeg honour ONE per-node value (the one the UI edits). Fails
209
- * safe to {@link DEFAULT_DECODER_HWACCEL} (`'auto'` → the session's local probe).
210
- */
211
- async function resolveDecoderHwAccel(api, nodeId, logger) {
212
- if (!api) return DEFAULT_DECODER_HWACCEL;
213
- try {
214
- return pickDecoderHwAccelFromSettings(await api.addonSettings.getGlobalSettings.query({
215
- addonId: DECODER_OWNER_ADDON_ID,
216
- nodeId: normalizeDecoderNodeId(nodeId)
217
- }));
218
- } catch (err) {
219
- logger.warn("decoder-hwaccel: owner settings read failed — deferring to local probe", { meta: { error: err instanceof Error ? err.message : String(err) } });
220
- return DEFAULT_DECODER_HWACCEL;
221
- }
222
- }
223
- //#endregion
224
- //#region src/shared/notifying-ring-buffer.ts
225
- /**
226
- * A {@link RingBuffer} that can notify a single blocked consumer the moment an
227
- * item commits — the server side of the `pullFrames`/`pullHandles` long-poll.
228
- *
229
- * The decoder's `onFrame`/`onFrameHandle` callback drives `push()`; a consumer
230
- * that finds the ring momentarily empty calls {@link waitForItem} and is woken
231
- * on the very next `push()` (a real commit signal) rather than spinning at
232
- * ~1kHz on `setTimeout(…,1)`. If nothing commits it resolves after `waitMs`,
233
- * and {@link cancel} (session teardown) resolves any in-flight wait promptly so
234
- * a blocked long-poll never waits out `waitMs` on destroy.
235
- *
236
- * Semantics are otherwise identical to `RingBuffer`: fixed capacity,
237
- * latest-wins overwrite when full, FIFO `drain`.
238
- */
239
- var NotifyingRingBuffer = class {
240
- ring;
241
- waiters = /* @__PURE__ */ new Set();
242
- constructor(capacity) {
243
- this.ring = new RingBuffer(capacity);
244
- }
245
- get size() {
246
- return this.ring.size;
247
- }
248
- push(item) {
249
- this.ring.push(item);
250
- this.wakeAll();
251
- }
252
- drain(maxCount) {
253
- return this.ring.drain(maxCount);
254
- }
255
- /**
256
- * Resolve as soon as an item commits to the ring, or after `waitMs`,
257
- * whichever comes first. Returns immediately when items are already present
258
- * or `waitMs <= 0` (legacy immediate-return). {@link cancel} also resolves an
259
- * in-flight wait.
260
- */
261
- async waitForItem(waitMs) {
262
- if (this.ring.size > 0 || waitMs <= 0) return;
263
- await new Promise((resolve) => {
264
- let settled = false;
265
- const finish = () => {
266
- if (settled) return;
267
- settled = true;
268
- this.waiters.delete(wake);
269
- clearTimeout(timer);
270
- resolve();
271
- };
272
- const wake = () => finish();
273
- const timer = setTimeout(finish, waitMs);
274
- if (typeof timer.unref === "function") timer.unref();
275
- this.waiters.add(wake);
276
- });
277
- }
278
- /**
279
- * Cancel every in-flight {@link waitForItem} — called on session teardown so
280
- * a blocked long-poll returns promptly instead of waiting out `waitMs`.
281
- */
282
- cancel() {
283
- this.wakeAll();
284
- }
285
- wakeAll() {
286
- if (this.waiters.size === 0) return;
287
- const pending = [...this.waiters];
288
- this.waiters.clear();
289
- for (const wake of pending) wake();
290
- }
291
- };
292
- //#endregion
293
- //#region src/decoder-ffmpeg/frame-ring-sink.ts
294
- /**
295
- * `DecoderFrameRingSink` — the decoder's shared-memory write side (Phase 5 / D9).
296
- *
297
- * When a decoder session is configured with `frameSink: 'shm'`, the decoder
298
- * **owns** the shared-memory ring segment for that stream: it creates the
299
- * segment on the first decoded frame (when the output geometry is known),
300
- * writes every subsequent decoded frame into the ring via a `FrameRingWriter`,
301
- * and closes + unlinks the segment when the session is destroyed.
302
- *
303
- * What leaves the decoder is no longer the pixel `Buffer` — it is a tiny,
304
- * serialisable `FrameHandle` (`FrameRingWriter.writeFrame`'s return value).
305
- * Same-host consumers (motion, detection, the WebRTC encoder) open the same
306
- * segment with a `FrameRingReader` and read the pixels zero-copy.
307
- *
308
- * ## Lazy segment creation
309
- *
310
- * The segment cannot be sized until the first frame: `slotByteLength` is
311
- * `width × height × bytesPerPixel`, and the output dimensions are only known
312
- * once the scaler has produced its first `dstFrame`. So `writeFrame` is a
313
- * no-op-until-armed: the first call sizes + creates the segment, every later
314
- * call writes into it.
315
- *
316
- * ## Resolution-change decision
317
- *
318
- * A live camera stream can change resolution mid-stream (the decoder's scaler
319
- * is rebuilt on a config toggle, or the source renegotiates). The slot is
320
- * sized for the **first** frame's geometry. A later frame that no longer fits
321
- * the slot triggers a **segment re-create**: the old segment is closed +
322
- * unlinked and a fresh, larger segment is created under a new generation-tagged
323
- * name. This is simpler and leak-free versus over-allocating slots for a
324
- * worst-case 4K frame on every stream; resolution changes on a live camera are
325
- * rare, and a brief gap while consumers re-open the segment is acceptable
326
- * (latest-wins — a missed frame is correct behaviour).
327
- */
328
- /**
329
- * Per-ring shared-memory budget (MB) — the slot count is derived per-resolution
330
- * from this budget via {@link deriveSlotCount}, so a 360p stream gets many
331
- * slots and a 4K stream a few, both inside the same memory footprint.
332
- *
333
- * Read ONCE at module load from `CAMSTACK_SHM_RING_BUDGET_MB`; a non-finite or
334
- * non-positive value falls back to the 16 MB default.
335
- *
336
- * The default is deliberately small (16 MB) so many concurrent per-camera rings
337
- * fit inside a bounded `/dev/shm`. The decoder output is capped at 640px wide, so
338
- * a slot is ≤ ~920 KB and 16 MB still yields ~17–70 latest-wins slots. A ring
339
- * segment larger than the container's `/dev/shm` tmpfs backing (Docker default is
340
- * only 64 MB) faults an **uncatchable SIGBUS** on write past `st_size` — the old
341
- * 128 MB default overflowed a 64 MB `/dev/shm` and crashed the decoder on 8MP
342
- * streams. Pair this with a `--shm-size` that scales with concurrent-decode load.
343
- */
344
- var RING_BUDGET_MB = (() => {
345
- const raw = Number(process.env["CAMSTACK_SHM_RING_BUDGET_MB"]);
346
- return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 16;
347
- })();
348
- /** {@link RING_BUDGET_MB} in bytes — the budget passed to `deriveSlotCount`. */
349
- var RING_BUDGET_BYTES = RING_BUDGET_MB * 1024 * 1024;
350
- /** A unique, stable shared-memory segment name for a decoder stream.
351
- *
352
- * macOS POSIX shm names are capped at ~31 characters (`PSHMNAMLEN`). A
353
- * `camstack.frames.<deviceId>.<streamId>` scheme overflows that for realistic
354
- * ids, so the sink uses a short, collision-resistant scheme instead:
355
- * `csf.<base36 hash>.<gen>`. The hash folds the device id, the session tag
356
- * and a per-process random salt; the generation suffix makes a re-created
357
- * segment (resolution change) a distinct name so a stale consumer mapping is
358
- * never silently reused.
359
- */
360
- function makeSegmentName(seed, generation) {
361
- let hash = 5381;
362
- for (let i = 0; i < seed.length; i += 1) hash = (hash << 5) + hash + seed.charCodeAt(i) | 0;
363
- return `csf.${(hash >>> 0).toString(36)}.${generation}`;
364
- }
365
- /**
366
- * The decoder-side owner of one stream's shared-memory frame ring.
367
- *
368
- * Not constructed until a session actually uses the shm sink; the segment
369
- * itself is created lazily on the first `writeFrame`.
370
- */
371
- var DecoderFrameRingSink = class {
372
- seed;
373
- logger;
374
- nodeId;
375
- segment = null;
376
- writer = null;
377
- segmentName = null;
378
- slotByteLength = 0;
379
- generation = 0;
380
- destroyed = false;
381
- /** Frames committed into the ring across this sink's lifetime (all generations). */
382
- framesWritten = 0;
383
- constructor(options) {
384
- const salt = Math.random().toString(36).slice(2, 8);
385
- this.seed = `${options.seed}.${salt}`;
386
- this.logger = options.logger;
387
- this.nodeId = options.nodeId;
388
- }
389
- /** Whether a segment has been created (i.e. at least one frame written). */
390
- get isArmed() {
391
- return this.writer !== null;
392
- }
393
- /** The current segment name, or `null` before the first frame. */
394
- get currentSegmentName() {
395
- return this.segmentName;
396
- }
397
- /**
398
- * Write one decoded frame into the ring and return its `FrameHandle`.
399
- *
400
- * On the first call (or after a geometry change that overflows the current
401
- * slot) the segment is created / re-created sized for this frame. Returns
402
- * `null` only when the sink has been destroyed.
403
- *
404
- * This is the copy-in convenience form (it copies `pixels` into the slot).
405
- * The decoder's hot path uses the zero-copy {@link beginFrame} /
406
- * {@link commitFrame} scatter-write pair instead — the scaler produces its
407
- * packed output directly into the slot, eliminating the write-side memcpy.
408
- */
409
- writeFrame(pixels, meta) {
410
- if (this.destroyed) return null;
411
- if (this.writer === null || computeSlotByteLength(meta.width, meta.height, meta.format) > this.slotByteLength) this.recreateSegment(computeSlotByteLength(meta.width, meta.height, meta.format));
412
- const writer = this.writer;
413
- if (writer === null) return null;
414
- const handle = writer.writeFrame(pixels, meta);
415
- this.framesWritten += 1;
416
- return handle;
417
- }
418
- /**
419
- * Reserve a ring slot for a frame of the given geometry — the **zero-copy**
420
- * scatter-write entry point (Phase 5 / D9 Task 7c).
421
- *
422
- * The segment is created / re-created here if this is the first frame or the
423
- * geometry overflows the current slot capacity, so the slot is correctly
424
- * sized before the caller fills it. The returned `buffer` is a writable view
425
- * **directly over the mapped segment** — the node-av scaler scatters its
426
- * packed output straight into it, with no intermediate copy. The caller MUST
427
- * call {@link commitFrame} with the returned `slot` once the slot is filled.
428
- *
429
- * Returns `null` when the sink is destroyed or the segment cannot be created.
430
- */
431
- beginFrame(width, height, format) {
432
- if (this.destroyed) return null;
433
- const requiredSlotBytes = computeSlotByteLength(width, height, format);
434
- if (this.writer === null || requiredSlotBytes > this.slotByteLength) this.recreateSegment(requiredSlotBytes);
435
- const writer = this.writer;
436
- if (writer === null) return null;
437
- const { slot, buffer } = writer.beginFrame();
438
- return {
439
- slot,
440
- buffer
441
- };
442
- }
443
- /**
444
- * Publish the frame whose slot was reserved by {@link beginFrame} and filled
445
- * in place by the caller. `slot` MUST be the value from the matching
446
- * `beginFrame`. Returns the published `FrameHandle`, or `null` if the sink
447
- * was destroyed (or the segment lost) between begin and commit.
448
- */
449
- commitFrame(slot, meta) {
450
- if (this.destroyed) return null;
451
- const writer = this.writer;
452
- if (writer === null) return null;
453
- const handle = writer.commitFrame(slot, meta);
454
- this.framesWritten += 1;
455
- return handle;
456
- }
457
- /**
458
- * Current shm ring usage — `null` until the first frame arms the segment.
459
- * Surfaced through `decoder.getShmStats` so a downstream consumer can
460
- * observe ring pressure (slot depth, byte budget, frames written).
461
- */
462
- getShmStats() {
463
- if (this.writer === null) return null;
464
- return {
465
- slotCount: this.writer.slotCount,
466
- slotByteLength: this.slotByteLength,
467
- segmentBytes: computeSegmentSize(this.writer.slotCount, this.slotByteLength),
468
- framesWritten: this.framesWritten
469
- };
470
- }
471
- /**
472
- * Abandon a slot reserved by {@link beginFrame} **without publishing it** —
473
- * the degenerate-path counterpart of {@link commitFrame}.
474
- *
475
- * A caller that reserved a slot but then could not produce valid pixels (no
476
- * decoded source planes, or the scaler threw) MUST call this instead of
477
- * `commitFrame`: it closes the open seqlock without advancing `writeIndex`,
478
- * so no reader ever sees the slot's uninitialised bytes as a real frame, and
479
- * no `FrameHandle` is handed downstream. `slot` MUST be the value from the
480
- * matching `beginFrame`. A no-op if the sink was destroyed (or the segment
481
- * lost) between begin and abort.
482
- */
483
- abortFrame(slot) {
484
- if (this.destroyed) return;
485
- const writer = this.writer;
486
- if (writer === null) return;
487
- writer.abortFrame(slot);
488
- }
489
- /** Close + unlink the segment. Idempotent. */
490
- destroy() {
491
- if (this.destroyed) return;
492
- this.destroyed = true;
493
- this.releaseSegment();
494
- }
495
- /**
496
- * Create a fresh segment sized for at least `slotByteLength` bytes per slot,
497
- * replacing any prior one. A re-create bumps the generation so the new
498
- * segment has a distinct name — a consumer holding the old mapping is never
499
- * silently handed a resized segment.
500
- */
501
- recreateSegment(slotByteLength) {
502
- this.releaseSegment();
503
- this.generation += 1;
504
- const name = makeSegmentName(this.seed, this.generation);
505
- const slotCount = deriveSlotCount(RING_BUDGET_BYTES, slotByteLength);
506
- if (slotCount === MIN_RING_SLOTS && MIN_RING_SLOTS * slotByteLength > RING_BUDGET_BYTES) this.logger.warn("decoder shm ring: budget too small for resolution — using MIN slots", { meta: {
507
- slotByteLength,
508
- budgetMb: RING_BUDGET_MB
509
- } });
510
- const totalBytes = computeSegmentSize(slotCount, slotByteLength);
511
- try {
512
- const segment = createSegment(name, totalBytes);
513
- this.segment = segment;
514
- this.segmentName = name;
515
- this.slotByteLength = slotByteLength;
516
- this.writer = new FrameRingWriter(segment.buffer, name, slotCount, slotByteLength, this.nodeId);
517
- this.logger.info("decoder shm ring: segment created", { meta: {
518
- segment: name,
519
- slotCount,
520
- slotByteLength,
521
- totalBytes,
522
- generation: this.generation
523
- } });
524
- } catch (err) {
525
- this.segment = null;
526
- this.writer = null;
527
- this.segmentName = null;
528
- this.slotByteLength = 0;
529
- this.logger.error("decoder shm ring: segment create failed", { meta: {
530
- segment: name,
531
- slotByteLength,
532
- error: err instanceof Error ? err.message : String(err)
533
- } });
534
- }
535
- }
536
- /** Unmap + unlink the current segment, if any. */
537
- releaseSegment() {
538
- const segment = this.segment;
539
- if (segment === null) return;
540
- this.segment = null;
541
- this.writer = null;
542
- const name = this.segmentName;
543
- this.segmentName = null;
544
- try {
545
- segment.close();
546
- segment.unlink();
547
- this.logger.info("decoder shm ring: segment released", { meta: { segment: name } });
548
- } catch (err) {
549
- this.logger.warn("decoder shm ring: segment release failed", { meta: {
550
- segment: name,
551
- error: err instanceof Error ? err.message : String(err)
552
- } });
553
- }
554
- }
555
- };
556
- //#endregion
557
- export { resolveDecoderBackend as a, DEFAULT_DECODER_BACKEND as c, NotifyingRingBuffer as i, RING_BUDGET_MB as n, resolveDecoderHwAccel as o, makeSegmentName as r, resolveOwnDecoderBackend as s, DecoderFrameRingSink as t };