@camstack/addon-pipeline 1.1.26 → 1.1.28

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 (48) hide show
  1. package/dist/audio-analyzer/index.js +7 -6
  2. package/dist/audio-analyzer/index.mjs +7 -6
  3. package/dist/audio-codec-ffmpeg/index.js +1 -1
  4. package/dist/audio-codec-ffmpeg/index.mjs +1 -1
  5. package/dist/constants-CAqYVigN.js +6615 -0
  6. package/dist/constants-oYgW36Ty.mjs +3587 -0
  7. package/dist/decoder-ffmpeg/index.js +74 -281
  8. package/dist/decoder-ffmpeg/index.mjs +73 -280
  9. package/dist/decoder-nodeav/index.js +1218 -0
  10. package/dist/decoder-nodeav/index.mjs +1210 -0
  11. package/dist/detection-pipeline/index.js +157 -219
  12. package/dist/detection-pipeline/index.mjs +157 -219
  13. package/dist/{dist-DAIlCdAx.js → dist-Biq62zt4.js} +372 -35
  14. package/dist/{dist-CgEP_0OL.mjs → dist-C6_wgXqF.mjs} +373 -24
  15. package/dist/dist-D3Ytt-_Y.js +41111 -0
  16. package/dist/dist-DluJuxV5.mjs +37976 -0
  17. package/dist/{frame-handle-plane-Dq20KtKL.mjs → frame-handle-plane-BIoY6nRV.mjs} +13 -5
  18. package/dist/{frame-handle-plane-DtTRX_0n.js → frame-handle-plane-D6BzyEgy.js} +13 -5
  19. package/dist/frame-ring-sink-9J0wCdLF.js +444 -0
  20. package/dist/frame-ring-sink-Cs9vby6v.mjs +409 -0
  21. package/dist/motion-wasm/index.js +55 -3
  22. package/dist/motion-wasm/index.mjs +55 -3
  23. package/dist/node-topology-platform-BkR_k6WT.mjs +15 -0
  24. package/dist/node-topology-platform-CFZ7F4xW.js +20 -0
  25. package/dist/pipeline-runner/index.js +50 -16
  26. package/dist/pipeline-runner/index.mjs +50 -16
  27. package/dist/recorder/index.js +36 -40
  28. package/dist/recorder/index.mjs +36 -40
  29. package/dist/stream-broker/_stub.js +2 -2
  30. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-5tQlh9h4.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-DoReAb4y.mjs} +3 -3
  31. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-DhY3MZ2C.mjs +26 -0
  32. 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 → _virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-DtoYGpTp.mjs} +1 -1
  33. package/dist/stream-broker/{hostInit-DyLqyJaS.mjs → hostInit-C0SuwQhL.mjs} +3 -3
  34. package/dist/stream-broker/index.js +81 -40
  35. package/dist/stream-broker/index.mjs +81 -40
  36. package/dist/stream-broker/remoteEntry.js +1 -1
  37. package/embed-dist/assets/{MaskShapeCanvas-DI4BY7W2-BDLNwJ_F.js → MaskShapeCanvas-DI4BY7W2-Br2yi8ah.js} +1 -1
  38. package/embed-dist/assets/{MotionZonesSettings-NcxxQN8r-CoLjNiUN.js → MotionZonesSettings-NcxxQN8r-BSCcPdPf.js} +1 -1
  39. package/embed-dist/assets/{PrivacyMaskSettings-APgPLF7p-DJE3OU-q.js → PrivacyMaskSettings-APgPLF7p-ztxvxSjS.js} +1 -1
  40. package/embed-dist/assets/index-C5UpuPr8.css +2 -0
  41. package/embed-dist/assets/{index-C-pL8ETk.js → index-CeZV1B-2.js} +10 -10
  42. package/embed-dist/index.html +2 -2
  43. package/package.json +31 -3
  44. package/python/inference_pool.py +108 -121
  45. package/python/test_inference_pool_device_selection.py +47 -43
  46. package/python/yamnet_audio.py +1 -1
  47. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-CkOPfV8r.mjs +0 -26
  48. package/embed-dist/assets/index-DrJ0ee3f.css +0 -2
@@ -0,0 +1,1218 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ const require_dist = require("../dist-Biq62zt4.js");
6
+ const require_frame_ring_sink = require("../frame-ring-sink-9J0wCdLF.js");
7
+ let _camstack_shm_ring = require("@camstack/shm-ring");
8
+ let node_crypto = require("node:crypto");
9
+ //#region src/decoder-nodeav/scaler-geometry.ts
10
+ /**
11
+ * Decide the scaler action for an incoming frame's source geometry.
12
+ *
13
+ * @param current The scaler's configured source geometry, or `null` when no
14
+ * scaler has been built yet.
15
+ * @param incoming The source geometry of the frame about to be scaled.
16
+ */
17
+ function resolveScalerAction(current, incoming) {
18
+ if (current === null) return "init";
19
+ if (current.width === incoming.width && current.height === incoming.height && current.format === incoming.format) return "reuse";
20
+ return "rebuild";
21
+ }
22
+ //#endregion
23
+ //#region src/decoder-nodeav/nodeav-decoder-session.ts
24
+ /** Map our canonical backend name to the node-av `AV_HWDEVICE_TYPE_*` constant. */
25
+ function backendToHwDeviceConst(backend, consts) {
26
+ switch (backend) {
27
+ case "videotoolbox": return consts.AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
28
+ case "cuda": return consts.AV_HWDEVICE_TYPE_CUDA;
29
+ case "nvdec": return consts.AV_HWDEVICE_TYPE_CUDA;
30
+ case "vaapi": return consts.AV_HWDEVICE_TYPE_VAAPI;
31
+ case "qsv": return consts.AV_HWDEVICE_TYPE_QSV;
32
+ case "d3d11va": return consts.AV_HWDEVICE_TYPE_D3D11VA;
33
+ case "dxva2": return consts.AV_HWDEVICE_TYPE_DXVA2;
34
+ case "amf": return consts.AV_HWDEVICE_TYPE_AMF;
35
+ case "vdpau": return consts.AV_HWDEVICE_TYPE_VDPAU;
36
+ case "drm": return consts.AV_HWDEVICE_TYPE_DRM;
37
+ default: return null;
38
+ }
39
+ }
40
+ /** Pick the hw pixel format for a given backend — used in get_format callback. */
41
+ function backendToHwPixFmt(backend, consts) {
42
+ switch (backend) {
43
+ case "videotoolbox": return consts.AV_PIX_FMT_VIDEOTOOLBOX;
44
+ case "cuda": return consts.AV_PIX_FMT_CUDA;
45
+ case "nvdec": return consts.AV_PIX_FMT_CUDA;
46
+ case "vaapi": return consts.AV_PIX_FMT_VAAPI;
47
+ case "qsv": return consts.AV_PIX_FMT_QSV;
48
+ case "d3d11va": return consts.AV_PIX_FMT_D3D11;
49
+ case "dxva2": return consts.AV_PIX_FMT_DXVA2_VLD;
50
+ case "amf": return consts.AV_PIX_FMT_D3D11;
51
+ case "vdpau": return consts.AV_PIX_FMT_VDPAU;
52
+ case "drm": return consts.AV_PIX_FMT_DRM_PRIME;
53
+ default: return null;
54
+ }
55
+ }
56
+ var _nav = null;
57
+ var _consts = null;
58
+ var _sharp = null;
59
+ async function getNodeAv() {
60
+ if (!_nav) _nav = await Promise.resolve().then(() => require("../dist-D3Ytt-_Y.js"));
61
+ return _nav;
62
+ }
63
+ async function getConstants() {
64
+ if (!_consts) _consts = await Promise.resolve().then(() => require("../constants-CAqYVigN.js"));
65
+ return _consts;
66
+ }
67
+ async function getSharp() {
68
+ if (!_sharp) _sharp = (await import("sharp")).default;
69
+ return _sharp;
70
+ }
71
+ var noopLogger = {
72
+ debug() {},
73
+ info() {},
74
+ warn() {},
75
+ error() {},
76
+ child() {
77
+ return noopLogger;
78
+ },
79
+ withTags() {
80
+ return noopLogger;
81
+ }
82
+ };
83
+ var NodeAvDecoderSession = class NodeAvDecoderSession {
84
+ config;
85
+ logger;
86
+ frameCallbacks = /* @__PURE__ */ new Set();
87
+ handleCallbacks = /* @__PURE__ */ new Set();
88
+ destroyed = false;
89
+ /**
90
+ * Frame delivery mode (see {@link DecoderFrameSink}). `'shm'` lazily
91
+ * constructs `frameRingSink` and routes every decoded frame through it.
92
+ */
93
+ frameSink;
94
+ /**
95
+ * The shared-memory ring writer for this stream. Created lazily on the
96
+ * first decoded frame in `'shm'` mode (the segment cannot be sized until
97
+ * the output geometry is known) and torn down in `destroy`.
98
+ */
99
+ frameRingSink = null;
100
+ parser = null;
101
+ codecCtx = null;
102
+ scaler = null;
103
+ avPacket = null;
104
+ avFrame = null;
105
+ dstFrame = null;
106
+ EAGAIN = -11;
107
+ PIX_FMT_GRAY8 = 8;
108
+ PIX_FMT_RGB24 = 2;
109
+ SWS_FAST_BILINEAR = 1;
110
+ /**
111
+ * Decoder output mode. Drives both the scaler's destination pixel
112
+ * format and whether sharp runs the JPEG encode at the end:
113
+ *
114
+ * - `'jpeg'` — scaler→RGB24 → sharp encode → emit JPEG bytes
115
+ * - `'rgb'` — scaler→RGB24 → emit raw RGB24 (no sharp)
116
+ * - `'gray'` — scaler→GRAY8 → emit raw GRAY8 (no sharp)
117
+ *
118
+ * The broker holds the policy decision on which mode to request based
119
+ * on its active subscribers; on-the-fly conversion (e.g. RGB→JPEG for
120
+ * a WebRTC consumer that joined while detection holds the decoder in
121
+ * RGB mode) happens broker-side via the per-frame conversion cache.
122
+ */
123
+ outputMode;
124
+ sharpFn = null;
125
+ /**
126
+ * Backpressure for the sharp JPEG encode pipeline. The broker
127
+ * currently creates sessions with `maxFps: 0` (unlimited) and relies
128
+ * on per-subscriber throttling, so without a bound the
129
+ * fire-and-forget `sharp(...).toBuffer()` chain would accumulate
130
+ * unboundedly whenever sharp falls behind the decoder. Cap at
131
+ * `MAX_JPEG_INFLIGHT` pending encodes per session — any frame that
132
+ * arrives while the cap is saturated is dropped and counted.
133
+ */
134
+ static MAX_JPEG_INFLIGHT = 2;
135
+ jpegEncodeInFlight = 0;
136
+ /**
137
+ * Map a `DecoderSessionConfig.outputFormat` value to one of the three
138
+ * native scaler/encoder modes the session understands. The cap-level
139
+ * format vocabulary is broader (it accepts `bgr`, `yuv420`) than what
140
+ * libav's scaler is wired for here — anything else degrades to RGB
141
+ * (the canonical raw mode) and the broker is expected to convert
142
+ * downstream if a subscriber needs a different shape.
143
+ */
144
+ static resolveOutputMode(format) {
145
+ if (format === "jpeg" || format === void 0) return "jpeg";
146
+ if (format === "gray") return "gray";
147
+ return "rgb";
148
+ }
149
+ initialized = false;
150
+ initializing = false;
151
+ scalerInitializing = false;
152
+ /**
153
+ * Monotonic counter incremented by `updateConfig` whenever the
154
+ * scaler + dstFrame get invalidated (e.g. output format toggle).
155
+ * `initScaler` captures the current value at entry and aborts — or
156
+ * disposes the locally-built scaler — if the epoch moved while
157
+ * its async init was in flight. Without this, a toggle racing an
158
+ * in-flight init could leave two scalers allocated natively while
159
+ * `this.scaler` only holds a reference to one → libav leak.
160
+ */
161
+ scalerEpoch = 0;
162
+ /**
163
+ * One-shot guard for the "first frame" diagnostic log + raw frame
164
+ * dump. Setting this synchronously inside `emitDecodedFrame`
165
+ * prevents re-entry — without it we were using `outputFrames === 0`
166
+ * which stays true until the async sharp encode callback runs, so
167
+ * several decoded frames could trigger the dump before the first
168
+ * JPEG landed.
169
+ */
170
+ firstFrameLogged = false;
171
+ outWidth = 0;
172
+ outHeight = 0;
173
+ /**
174
+ * The SOURCE geometry the current `scaler` was built for. `sws_scale` trusts
175
+ * these dimensions blindly; if a later decoded frame arrives with different
176
+ * width/height/format we MUST rebuild the scaler rather than feed it mismatched
177
+ * planes (an out-of-bounds read/write → uncatchable SIGBUS). `-1` means "no
178
+ * scaler built yet" (mirrors `this.scaler === null`).
179
+ */
180
+ scalerSrcW = -1;
181
+ scalerSrcH = -1;
182
+ scalerSrcFmt = -1;
183
+ lastEmitTime = 0;
184
+ minIntervalMs;
185
+ inputPackets = 0;
186
+ outputFrames = 0;
187
+ droppedFrames = 0;
188
+ totalDecodeTimeMs = 0;
189
+ startTime = Date.now();
190
+ hwaccelPref;
191
+ hwaccelResolver;
192
+ /** Cluster node id stamped into every `FrameHandle` the `'shm'` sink emits. */
193
+ nodeId;
194
+ /** The backend that actually initialised successfully — `'none'` = software fallback. */
195
+ activeHwAccel = "none";
196
+ hwDevice = null;
197
+ swTransferFrame = null;
198
+ constructor(config, logger = noopLogger, options) {
199
+ this.config = { ...config };
200
+ const sessionTags = {};
201
+ if (typeof config.deviceId === "number") sessionTags["deviceId"] = config.deviceId;
202
+ if (typeof config.tag === "string" && config.tag.length > 0) sessionTags["tag"] = config.tag;
203
+ this.logger = Object.keys(sessionTags).length > 0 ? logger.withTags(sessionTags) : logger;
204
+ this.minIntervalMs = config.maxFps > 0 ? 1e3 / config.maxFps : 0;
205
+ this.outputMode = NodeAvDecoderSession.resolveOutputMode(config.outputFormat);
206
+ this.hwaccelPref = options?.hwaccel ?? "auto";
207
+ this.hwaccelResolver = options?.hwaccelResolver ?? null;
208
+ this.frameSink = options?.frameSink ?? "callback";
209
+ this.nodeId = options?.nodeId ?? "local";
210
+ }
211
+ /**
212
+ * The shared-memory ring sink for this stream, or `null` before the first
213
+ * `'shm'`-mode frame lazily creates it. Exposed so the owning addon can
214
+ * surface ring stats via `decoder.getShmStats`.
215
+ */
216
+ get frameRingSinkOrNull() {
217
+ return this.frameRingSink;
218
+ }
219
+ /**
220
+ * Lazily build the shared-memory ring sink for this stream. The segment
221
+ * itself is still created lazily by the sink on its first `writeFrame`,
222
+ * once the decoded geometry is known.
223
+ */
224
+ ensureFrameRingSink() {
225
+ if (this.frameRingSink === null) {
226
+ const seedParts = [];
227
+ if (typeof this.config.deviceId === "number") seedParts.push(String(this.config.deviceId));
228
+ if (typeof this.config.tag === "string" && this.config.tag.length > 0) seedParts.push(this.config.tag);
229
+ const seed = seedParts.length > 0 ? seedParts.join(":") : "anon";
230
+ this.frameRingSink = new require_frame_ring_sink.DecoderFrameRingSink({
231
+ seed,
232
+ logger: this.logger,
233
+ nodeId: this.nodeId
234
+ });
235
+ }
236
+ return this.frameRingSink;
237
+ }
238
+ /**
239
+ * Resolve the backend preference list and try each one against
240
+ * node-av's HW context APIs. The first backend whose
241
+ * `HardwareDeviceContext.create()` succeeds gets attached to
242
+ * `codecCtx.hwDeviceCtx` + its hw pixel format registered via
243
+ * `setHardwarePixelFormat`. On any failure, falls through to the
244
+ * next backend; if all fail, returns with `activeHwAccel='none'`
245
+ * and the decoder runs in software on the same context.
246
+ */
247
+ async tryAttachHwAccel(nav, C) {
248
+ if (!this.codecCtx) return;
249
+ if (this.hwaccelPref === "none") {
250
+ this.activeHwAccel = "none";
251
+ return;
252
+ }
253
+ const explicit = this.hwaccelPref === "auto" ? null : this.hwaccelPref;
254
+ const resolution = this.hwaccelResolver ? await this.hwaccelResolver.resolve(explicit) : explicit ? {
255
+ preferred: [explicit],
256
+ rationale: "explicit (no resolver)"
257
+ } : {
258
+ preferred: [],
259
+ rationale: "auto + no resolver → software"
260
+ };
261
+ if (resolution.preferred.length === 0) {
262
+ this.activeHwAccel = "none";
263
+ return;
264
+ }
265
+ for (const backend of resolution.preferred) {
266
+ const deviceType = backendToHwDeviceConst(backend, C);
267
+ const hwPixFmt = backendToHwPixFmt(backend, C);
268
+ if (!deviceType || !hwPixFmt) continue;
269
+ const device = new nav.HardwareDeviceContext();
270
+ const rc = device.create(deviceType);
271
+ if (rc < 0) {
272
+ this.logger.warn("node-av: hwaccel device create failed — trying next", { meta: {
273
+ backend,
274
+ rc
275
+ } });
276
+ device.free();
277
+ continue;
278
+ }
279
+ try {
280
+ this.codecCtx.hwDeviceCtx = device;
281
+ this.codecCtx.setHardwarePixelFormat(hwPixFmt);
282
+ } catch (err) {
283
+ this.logger.warn("node-av: hwaccel context attach failed — trying next", { meta: {
284
+ backend,
285
+ error: require_dist.errMsg(err)
286
+ } });
287
+ device.free();
288
+ continue;
289
+ }
290
+ this.hwDevice = device;
291
+ this.activeHwAccel = backend;
292
+ return;
293
+ }
294
+ this.logger.warn("node-av: no hwaccel backend initialised — using software", { meta: {
295
+ attempted: resolution.preferred.join(","),
296
+ rationale: resolution.rationale
297
+ } });
298
+ this.activeHwAccel = "none";
299
+ }
300
+ /**
301
+ * Download a HW frame (format == hw pix fmt) into a SW frame so the
302
+ * rest of the pipeline (scaler, JPEG encoder, grayscale passthrough)
303
+ * handles it identically to the pure-software path. Uses the sync
304
+ * variant so the synchronous receive loop below doesn't need to be
305
+ * async-ified. Returns `null` on transfer failure, meaning the
306
+ * caller should drop the frame.
307
+ */
308
+ transferHwFrame(hwFrame) {
309
+ if (this.activeHwAccel === "none" || !this.swTransferFrame) return hwFrame;
310
+ const rc = hwFrame.hwframeTransferDataSync(this.swTransferFrame, 0);
311
+ if (rc < 0) {
312
+ this.logger.warn("node-av: hwframeTransferData failed", { meta: { rc } });
313
+ return null;
314
+ }
315
+ return this.swTransferFrame;
316
+ }
317
+ /**
318
+ * Initialize the decoder pipeline on the first keyframe.
319
+ * After this returns, all hot-path methods are fully synchronous (except JPEG encode).
320
+ */
321
+ async initDecoder() {
322
+ if (this.initialized || this.initializing || this.destroyed) return;
323
+ this.initializing = true;
324
+ try {
325
+ const nav = await getNodeAv();
326
+ const C = await getConstants();
327
+ this.EAGAIN = C.AVERROR_EAGAIN;
328
+ this.PIX_FMT_GRAY8 = C.AV_PIX_FMT_GRAY8;
329
+ this.PIX_FMT_RGB24 = C.AV_PIX_FMT_RGB24;
330
+ this.SWS_FAST_BILINEAR = C.SWS_FAST_BILINEAR;
331
+ if (this.outputMode === "jpeg") this.sharpFn = await getSharp();
332
+ nav.Log.setLevel(C.AV_LOG_FATAL);
333
+ const codecId = this.config.codec === "h265" || this.config.codec === "hevc" ? C.AV_CODEC_ID_HEVC : C.AV_CODEC_ID_H264;
334
+ this.parser = new nav.CodecParser();
335
+ this.parser.init(codecId);
336
+ const codec = nav.Codec.findDecoder(codecId);
337
+ if (!codec) {
338
+ this.logger.error("node-av: no decoder found", { meta: { codec: this.config.codec } });
339
+ return;
340
+ }
341
+ this.codecCtx = new nav.CodecContext();
342
+ this.codecCtx.allocContext3(codec);
343
+ if (this.config.width && this.config.height) {
344
+ this.codecCtx.width = this.config.width;
345
+ this.codecCtx.height = this.config.height;
346
+ }
347
+ this.codecCtx.threadCount = 1;
348
+ await this.tryAttachHwAccel(nav, C);
349
+ const ret = await this.codecCtx.open2(codec);
350
+ if (ret < 0) if (this.activeHwAccel !== "none") {
351
+ this.logger.warn("node-av: open2 failed with hwaccel — retrying in software", { meta: {
352
+ ret,
353
+ hwAccel: this.activeHwAccel
354
+ } });
355
+ this.hwDevice?.free();
356
+ this.hwDevice = null;
357
+ this.activeHwAccel = "none";
358
+ this.codecCtx = new nav.CodecContext();
359
+ this.codecCtx.allocContext3(codec);
360
+ if (this.config.width && this.config.height) {
361
+ this.codecCtx.width = this.config.width;
362
+ this.codecCtx.height = this.config.height;
363
+ }
364
+ this.codecCtx.threadCount = 1;
365
+ const retry = await this.codecCtx.open2(codec);
366
+ if (retry < 0) {
367
+ this.logger.error("node-av: failed to open decoder (sw fallback)", { meta: { ret: retry } });
368
+ return;
369
+ }
370
+ } else {
371
+ this.logger.error("node-av: failed to open decoder", { meta: { ret } });
372
+ return;
373
+ }
374
+ if (this.activeHwAccel !== "none") {
375
+ this.swTransferFrame = new nav.Frame();
376
+ this.swTransferFrame.alloc();
377
+ }
378
+ this.avPacket = new nav.Packet();
379
+ this.avPacket.alloc();
380
+ this.avFrame = new nav.Frame();
381
+ this.avFrame.alloc();
382
+ this.initialized = true;
383
+ this.logger.info("node-av push decoder initialized", { meta: {
384
+ codec: this.config.codec,
385
+ output: this.outputMode,
386
+ hwAccel: this.activeHwAccel
387
+ } });
388
+ } catch (err) {
389
+ this.logger.error("node-av init error", { meta: { error: require_dist.errMsg(err) } });
390
+ } finally {
391
+ this.initializing = false;
392
+ }
393
+ }
394
+ /**
395
+ * Initialize the scaler after the first frame tells us the actual
396
+ * dimensions. Output pixel format: RGB24 for JPEG encoding, GRAY8
397
+ * for raw motion.
398
+ *
399
+ * Builds `scaler` + `dstFrame` on local variables and publishes
400
+ * them onto `this` in a single atomic step at the end. Captures
401
+ * `scalerEpoch` at entry; if `updateConfig` invalidated the scaler
402
+ * while this init was in flight (epoch mismatch), the locally
403
+ * built pair is disposed and discarded so the later init wins.
404
+ * Without the local-first approach, partial state (scaler set,
405
+ * dstFrame still null) could be observed by a concurrent
406
+ * `emitDecodedFrame` call.
407
+ */
408
+ async initScaler(srcW, srcH, srcFmt) {
409
+ if (this.scalerInitializing) return;
410
+ this.scalerInitializing = true;
411
+ const myEpoch = this.scalerEpoch;
412
+ let localScaler = null;
413
+ let localDstFrame = null;
414
+ try {
415
+ const nav = await getNodeAv();
416
+ if (this.destroyed || myEpoch !== this.scalerEpoch) return;
417
+ const scale = this.config.scale > 1 ? this.config.scale : 1;
418
+ const maxW = Math.floor(640 / scale);
419
+ const outWidth = Math.min(srcW, maxW);
420
+ const outHeight = Math.round(outWidth * srcH / srcW);
421
+ const dstFmt = this.outputMode === "gray" ? this.PIX_FMT_GRAY8 : this.PIX_FMT_RGB24;
422
+ const fmtName = this.outputMode === "gray" ? "gray8" : "rgb24";
423
+ localScaler = new nav.SoftwareScaleContext();
424
+ localScaler.getContext(srcW, srcH, srcFmt, outWidth, outHeight, dstFmt, this.SWS_FAST_BILINEAR);
425
+ const ret = localScaler.initContext();
426
+ if (ret < 0) {
427
+ this.logger.error("node-av: sws_init_context failed", { meta: { ret } });
428
+ return;
429
+ }
430
+ localDstFrame = new nav.Frame();
431
+ localDstFrame.alloc();
432
+ localDstFrame.width = outWidth;
433
+ localDstFrame.height = outHeight;
434
+ localDstFrame.format = dstFmt;
435
+ const allocRet = localDstFrame.allocBuffer();
436
+ if (allocRet < 0) {
437
+ this.logger.error("node-av: dst frame allocBuffer failed", { meta: { ret: allocRet } });
438
+ return;
439
+ }
440
+ if (this.destroyed || myEpoch !== this.scalerEpoch) return;
441
+ this.scaler?.[Symbol.dispose]?.();
442
+ this.dstFrame?.[Symbol.dispose]?.();
443
+ this.scaler = localScaler;
444
+ this.dstFrame = localDstFrame;
445
+ this.outWidth = outWidth;
446
+ this.outHeight = outHeight;
447
+ this.scalerSrcW = srcW;
448
+ this.scalerSrcH = srcH;
449
+ this.scalerSrcFmt = srcFmt;
450
+ localScaler = null;
451
+ localDstFrame = null;
452
+ this.logger.info("node-av scaler initialized", { meta: {
453
+ srcWidth: srcW,
454
+ srcHeight: srcH,
455
+ outWidth,
456
+ outHeight,
457
+ format: fmtName
458
+ } });
459
+ } catch (err) {
460
+ this.logger.error("Scaler init failed", { meta: { error: require_dist.errMsg(err) } });
461
+ } finally {
462
+ localScaler?.[Symbol.dispose]?.();
463
+ localDstFrame?.[Symbol.dispose]?.();
464
+ this.scalerInitializing = false;
465
+ }
466
+ }
467
+ pushPacket(packet) {
468
+ if (this.destroyed) return;
469
+ this.inputPackets++;
470
+ if (!this.initialized && !this.initializing && packet.keyframe) {
471
+ this.initDecoder().then(() => {
472
+ if (this.initialized) this.decodeRawData(packet.data, packet.pts ?? Date.now());
473
+ }).catch((err) => {
474
+ this.logger.error("node-av init failed", { meta: { error: require_dist.errMsg(err) } });
475
+ });
476
+ return;
477
+ }
478
+ if (!this.initialized) return;
479
+ this.decodeRawData(packet.data, packet.pts ?? Date.now());
480
+ }
481
+ decodeRawData(data, pts) {
482
+ if (!this.parser || !this.codecCtx || !this.avPacket || !this.avFrame) return;
483
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
484
+ const bigPts = BigInt(pts);
485
+ let offset = 0;
486
+ while (offset < buf.length) {
487
+ const remaining = buf.subarray(offset);
488
+ const consumed = this.parser.parse2(this.codecCtx, this.avPacket, remaining, bigPts, bigPts, offset);
489
+ if (consumed < 0) {
490
+ this.logger.warn("node-av parser error", { meta: { ret: consumed } });
491
+ break;
492
+ }
493
+ offset += consumed;
494
+ if (this.avPacket.size > 0) {
495
+ this.decodePacket();
496
+ this.avPacket.unref();
497
+ }
498
+ }
499
+ }
500
+ decodePacket() {
501
+ if (!this.codecCtx || !this.avFrame) return;
502
+ const sendRet = this.codecCtx.sendPacketSync(this.avPacket);
503
+ if (sendRet < 0 && sendRet !== this.EAGAIN) {
504
+ this.logger.warn("node-av sendPacket error", { meta: { ret: sendRet } });
505
+ return;
506
+ }
507
+ while (true) {
508
+ if (this.codecCtx.receiveFrameSync(this.avFrame) < 0) break;
509
+ const frame = this.transferHwFrame(this.avFrame);
510
+ if (!frame) continue;
511
+ this.emitDecodedFrame(frame);
512
+ }
513
+ }
514
+ emitDecodedFrame(frame) {
515
+ const now = performance.now();
516
+ if (this.minIntervalMs > 0 && now - this.lastEmitTime < this.minIntervalMs) {
517
+ this.droppedFrames++;
518
+ return;
519
+ }
520
+ if (this.scalerInitializing) return;
521
+ const incoming = {
522
+ width: frame.width,
523
+ height: frame.height,
524
+ format: frame.format
525
+ };
526
+ const current = this.scaler !== null ? {
527
+ width: this.scalerSrcW,
528
+ height: this.scalerSrcH,
529
+ format: this.scalerSrcFmt
530
+ } : null;
531
+ const action = resolveScalerAction(current, incoming);
532
+ if (action === "init") {
533
+ this.initScaler(incoming.width, incoming.height, incoming.format);
534
+ return;
535
+ }
536
+ if (action === "rebuild") {
537
+ this.logger.info("node-av: decoded source geometry changed — rebuilding scaler", { meta: {
538
+ from: current,
539
+ to: incoming
540
+ } });
541
+ this.scalerEpoch++;
542
+ this.scaler?.[Symbol.dispose]?.();
543
+ this.scaler = null;
544
+ this.dstFrame?.[Symbol.dispose]?.();
545
+ this.dstFrame = null;
546
+ this.scalerSrcW = -1;
547
+ this.scalerSrcH = -1;
548
+ this.scalerSrcFmt = -1;
549
+ this.initScaler(incoming.width, incoming.height, incoming.format);
550
+ return;
551
+ }
552
+ if (!this.dstFrame || !this.scaler) return;
553
+ const decodeStart = performance.now();
554
+ if (this.frameSink === "shm" && this.outputMode !== "jpeg") {
555
+ this.scaleIntoRingSlot(frame, decodeStart);
556
+ return;
557
+ }
558
+ try {
559
+ this.dstFrame.makeWritable();
560
+ this.scaler.scaleFrameSync(this.dstFrame, frame);
561
+ } catch (err) {
562
+ this.logger.warn("node-av scale error", { meta: { error: require_dist.errMsg(err) } });
563
+ return;
564
+ }
565
+ if (!this.firstFrameLogged) {
566
+ this.firstFrameLogged = true;
567
+ const channels = this.outputMode === "gray" ? 1 : 3;
568
+ const ls = this.dstFrame.linesize;
569
+ const buf = this.dstFrame.toBuffer();
570
+ this.logger.info("dstFrame after scale", { meta: {
571
+ phase: "frame-debug",
572
+ width: this.dstFrame.width,
573
+ height: this.dstFrame.height,
574
+ linesize: [
575
+ ls[0],
576
+ ls[1],
577
+ ls[2]
578
+ ],
579
+ expectedStride: this.dstFrame.width * channels,
580
+ bufLen: buf.length,
581
+ expectedPacked: this.dstFrame.width * channels * this.dstFrame.height,
582
+ srcFormat: frame.format ?? "?"
583
+ } });
584
+ if (this.outputMode !== "gray") import("node:fs").then((fsModule) => {
585
+ import("node:path").then((pathModule) => {
586
+ const dumpPath = pathModule.join(process.cwd(), "camstack-data", "debug-frame-rgb24.raw");
587
+ fsModule.writeFileSync(dumpPath, buf);
588
+ this.logger.info("Dumped first RGB24 frame", { meta: {
589
+ phase: "frame-debug",
590
+ path: dumpPath,
591
+ bytes: buf.length
592
+ } });
593
+ }).catch(() => {});
594
+ }).catch(() => {});
595
+ }
596
+ const rawBuf = this.extractPackedBuffer(this.dstFrame);
597
+ if (this.outputMode === "jpeg") this.encodeAndEmitJpeg(rawBuf, decodeStart);
598
+ else if (this.outputMode === "rgb") this.emitRawFrame(rawBuf, "rgb", decodeStart);
599
+ else this.emitRawFrame(rawBuf, "gray", decodeStart);
600
+ }
601
+ /**
602
+ * Scale a decoded frame **directly into a shared-memory ring slot** — the
603
+ * zero write-side copy path (Phase 5 / D9 Task 7c).
604
+ *
605
+ * `beginFrame` reserves the slot (its seqlock open / odd — readers skip it);
606
+ * `SoftwareScaleContext.scaleSync` (the low-level `sws_scale` mapping) writes
607
+ * the packed pixels straight into the slot buffer with `linesize = width ×
608
+ * bpp` — no linesize padding, so there is nothing to strip and nothing to
609
+ * memcpy; `commitFrame` writes the metadata, closes the seqlock and publishes
610
+ * the slot. The decoded source planes feed `scaleSync` as `srcSlice` +
611
+ * `srcStride` (`frame.data` / `frame.linesize`).
612
+ *
613
+ * Used only for raw output formats (rgb/bgr/gray). The jpeg path keeps the
614
+ * `dstFrame` + sharp encode route because sharp must consume an RGB buffer
615
+ * before the final (variable-length) jpeg bytes exist.
616
+ */
617
+ scaleIntoRingSlot(frame, decodeStart) {
618
+ if (!this.scaler) return;
619
+ const format = this.outputMode === "gray" ? "gray" : "rgb";
620
+ const channels = this.outputMode === "gray" ? 1 : 3;
621
+ const sink = this.ensureFrameRingSink();
622
+ const reserved = sink.beginFrame(this.outWidth, this.outHeight, format);
623
+ if (reserved === null) {
624
+ this.droppedFrames++;
625
+ return;
626
+ }
627
+ const srcPlanes = frame.data;
628
+ if (!srcPlanes || srcPlanes.length === 0) {
629
+ sink.abortFrame(reserved.slot);
630
+ this.droppedFrames++;
631
+ return;
632
+ }
633
+ const dstStride = this.outWidth * channels;
634
+ const needed = dstStride * this.outHeight;
635
+ if (reserved.buffer.length < needed) {
636
+ this.logger.warn("node-av: ring slot too small for scaled frame — dropping", { meta: {
637
+ needed,
638
+ slotBytes: reserved.buffer.length,
639
+ width: this.outWidth,
640
+ height: this.outHeight
641
+ } });
642
+ sink.abortFrame(reserved.slot);
643
+ this.droppedFrames++;
644
+ return;
645
+ }
646
+ try {
647
+ const srcStrides = Array.from(frame.linesize).slice(0, srcPlanes.length);
648
+ this.scaler.scaleSync(Array.from(srcPlanes), srcStrides, 0, frame.height, [reserved.buffer], [dstStride]);
649
+ } catch (err) {
650
+ this.logger.warn("node-av scale-into-slot error", { meta: { error: require_dist.errMsg(err) } });
651
+ sink.abortFrame(reserved.slot);
652
+ this.droppedFrames++;
653
+ return;
654
+ }
655
+ const decodeMs = performance.now() - decodeStart;
656
+ this.totalDecodeTimeMs += decodeMs;
657
+ this.outputFrames++;
658
+ this.lastEmitTime = performance.now();
659
+ if (!this.firstFrameLogged) {
660
+ this.firstFrameLogged = true;
661
+ this.logger.info("node-av: scaled directly into shm ring slot", { meta: {
662
+ phase: "frame-debug",
663
+ width: this.outWidth,
664
+ height: this.outHeight,
665
+ dstStride,
666
+ format
667
+ } });
668
+ }
669
+ if (this.outputFrames === 1 || this.outputFrames % 500 === 0) this.logger.info("node-av frame emitted", { meta: {
670
+ frameNumber: this.outputFrames,
671
+ width: this.outWidth,
672
+ height: this.outHeight,
673
+ format,
674
+ decodeMs,
675
+ sink: "shm",
676
+ subs: this.handleCallbacks.size
677
+ } });
678
+ const handle = sink.commitFrame(reserved.slot, {
679
+ width: this.outWidth,
680
+ height: this.outHeight,
681
+ format,
682
+ pts: performance.now(),
683
+ byteLength: dstStride * this.outHeight
684
+ });
685
+ if (handle === null) {
686
+ this.droppedFrames++;
687
+ return;
688
+ }
689
+ const delivered = {
690
+ handle,
691
+ timestamp: Date.now()
692
+ };
693
+ for (const cb of this.handleCallbacks) cb(delivered);
694
+ }
695
+ /**
696
+ * Extract packed pixel buffer from a decoded frame.
697
+ * FFmpeg's av_frame_get_buffer() may pad each row to alignment (32/64 bytes).
698
+ * Sharp and WASM consumers expect tightly-packed rows (stride = width * channels).
699
+ * If linesize matches expected stride, return the buffer directly (zero-copy).
700
+ */
701
+ extractPackedBuffer(frame) {
702
+ const channels = this.outputMode === "gray" ? 1 : 3;
703
+ const expectedStride = frame.width * channels;
704
+ const actualStride = frame.linesize[0] ?? expectedStride;
705
+ const src = frame.data?.[0];
706
+ if (!src) return frame.toBuffer();
707
+ if (actualStride === expectedStride) return Buffer.from(src.buffer, src.byteOffset, expectedStride * frame.height);
708
+ const dst = Buffer.allocUnsafe(expectedStride * frame.height);
709
+ for (let y = 0; y < frame.height; y++) src.copy(dst, y * expectedStride, y * actualStride, y * actualStride + expectedStride);
710
+ return dst;
711
+ }
712
+ /**
713
+ * Encode RGB24 raw buffer as JPEG and emit.
714
+ *
715
+ * Drops the frame (and counts it) when `MAX_JPEG_INFLIGHT` encodes
716
+ * are already pending — prevents unbounded growth of the
717
+ * fire-and-forget promise chain when sharp cannot keep up with the
718
+ * decode rate.
719
+ */
720
+ encodeAndEmitJpeg(rgb, decodeStart) {
721
+ if (!this.sharpFn) return;
722
+ if (this.jpegEncodeInFlight >= NodeAvDecoderSession.MAX_JPEG_INFLIGHT) {
723
+ this.droppedFrames++;
724
+ return;
725
+ }
726
+ this.jpegEncodeInFlight++;
727
+ this.sharpFn(rgb, { raw: {
728
+ width: this.outWidth,
729
+ height: this.outHeight,
730
+ channels: 3
731
+ } }).jpeg({
732
+ quality: 80,
733
+ mozjpeg: false
734
+ }).toBuffer().then((jpegBuf) => {
735
+ if (this.destroyed) return;
736
+ this.emitRawFrame(jpegBuf, "jpeg", decodeStart);
737
+ }).catch((err) => {
738
+ this.logger.warn("sharp jpeg encode error", { meta: { error: require_dist.errMsg(err) } });
739
+ }).finally(() => {
740
+ this.jpegEncodeInFlight--;
741
+ });
742
+ }
743
+ emitRawFrame(data, format, decodeStart) {
744
+ const decodeMs = performance.now() - decodeStart;
745
+ this.totalDecodeTimeMs += decodeMs;
746
+ this.outputFrames++;
747
+ this.lastEmitTime = performance.now();
748
+ if (this.outputFrames === 1 || this.outputFrames % 500 === 0) this.logger.info("node-av frame emitted", { meta: {
749
+ frameNumber: this.outputFrames,
750
+ width: this.outWidth,
751
+ height: this.outHeight,
752
+ format,
753
+ decodeMs,
754
+ sink: this.frameSink,
755
+ subs: this.frameSink === "shm" ? this.handleCallbacks.size : this.frameCallbacks.size
756
+ } });
757
+ if (this.frameSink === "shm") {
758
+ this.emitShmFrame(data, format);
759
+ return;
760
+ }
761
+ const decodedFrame = {
762
+ data,
763
+ width: this.outWidth,
764
+ height: this.outHeight,
765
+ format,
766
+ timestamp: Date.now()
767
+ };
768
+ for (const cb of this.frameCallbacks) cb(decodedFrame);
769
+ }
770
+ /**
771
+ * Write a decoded frame into this stream's shared-memory ring and deliver
772
+ * the resulting `FrameHandle` to `onFrameHandle` subscribers. No pixel
773
+ * `Buffer` is handed to callbacks — consumers open the segment and read the
774
+ * pixels zero-copy via a `FrameRingReader`.
775
+ */
776
+ emitShmFrame(data, format) {
777
+ const handle = this.ensureFrameRingSink().writeFrame(data, {
778
+ width: this.outWidth,
779
+ height: this.outHeight,
780
+ format,
781
+ pts: performance.now(),
782
+ byteLength: data.byteLength
783
+ });
784
+ if (handle === null) {
785
+ this.droppedFrames++;
786
+ return;
787
+ }
788
+ const frame = {
789
+ handle,
790
+ timestamp: Date.now()
791
+ };
792
+ for (const cb of this.handleCallbacks) cb(frame);
793
+ }
794
+ onFrame(callback) {
795
+ this.frameCallbacks.add(callback);
796
+ return () => {
797
+ this.frameCallbacks.delete(callback);
798
+ };
799
+ }
800
+ /**
801
+ * Subscribe to shared-memory frame handles. Fires only when the session was
802
+ * created with `frameSink: 'shm'`; in the legacy `'callback'` mode no
803
+ * handles are produced and this subscription never fires.
804
+ */
805
+ onFrameHandle(callback) {
806
+ this.handleCallbacks.add(callback);
807
+ return () => {
808
+ this.handleCallbacks.delete(callback);
809
+ };
810
+ }
811
+ updateConfig(update) {
812
+ const prevFormat = this.config.outputFormat;
813
+ this.config = {
814
+ ...this.config,
815
+ ...update
816
+ };
817
+ if (update.maxFps !== void 0) this.minIntervalMs = update.maxFps > 0 ? 1e3 / update.maxFps : 0;
818
+ if (update.outputFormat !== void 0 && update.outputFormat !== prevFormat) {
819
+ const prevMode = this.outputMode;
820
+ this.outputMode = NodeAvDecoderSession.resolveOutputMode(update.outputFormat);
821
+ if (this.outputMode === prevMode) return;
822
+ this.scalerEpoch++;
823
+ if (this.scaler) {
824
+ this.scaler[Symbol.dispose]?.();
825
+ this.scaler = null;
826
+ }
827
+ if (this.dstFrame) {
828
+ this.dstFrame[Symbol.dispose]?.();
829
+ this.dstFrame = null;
830
+ }
831
+ this.scalerSrcW = -1;
832
+ this.scalerSrcH = -1;
833
+ this.scalerSrcFmt = -1;
834
+ if (this.outputMode === "jpeg" && !this.sharpFn) getSharp().then((fn) => {
835
+ this.sharpFn = fn;
836
+ }).catch(() => {});
837
+ this.logger.info("node-av: output format changed — scaler will reinit", { meta: {
838
+ from: prevFormat,
839
+ to: update.outputFormat,
840
+ mode: this.outputMode
841
+ } });
842
+ }
843
+ }
844
+ async destroy() {
845
+ if (this.destroyed) return;
846
+ this.destroyed = true;
847
+ this.frameCallbacks.clear();
848
+ this.handleCallbacks.clear();
849
+ this.frameRingSink?.destroy();
850
+ this.frameRingSink = null;
851
+ this.dstFrame?.[Symbol.dispose]?.();
852
+ this.avFrame?.[Symbol.dispose]?.();
853
+ this.avPacket?.[Symbol.dispose]?.();
854
+ this.scaler?.[Symbol.dispose]?.();
855
+ this.parser?.[Symbol.dispose]?.();
856
+ this.swTransferFrame?.[Symbol.dispose]?.();
857
+ this.codecCtx?.[Symbol.dispose]?.();
858
+ this.hwDevice?.free();
859
+ this.dstFrame = null;
860
+ this.avFrame = null;
861
+ this.avPacket = null;
862
+ this.scaler = null;
863
+ this.parser = null;
864
+ this.codecCtx = null;
865
+ this.swTransferFrame = null;
866
+ this.hwDevice = null;
867
+ }
868
+ getStats() {
869
+ const uptimeSec = Math.max((Date.now() - this.startTime) / 1e3, 1);
870
+ return {
871
+ inputFps: this.inputPackets / uptimeSec,
872
+ outputFps: this.outputFrames / uptimeSec,
873
+ avgDecodeTimeMs: this.outputFrames > 0 ? this.totalDecodeTimeMs / this.outputFrames : 0,
874
+ droppedFrames: this.droppedFrames
875
+ };
876
+ }
877
+ get isPullMode() {
878
+ return false;
879
+ }
880
+ };
881
+ //#endregion
882
+ //#region src/decoder-nodeav/addon/index.ts
883
+ var FRAME_BUFFER_CAPACITY = 32;
884
+ var DecoderNodeAvAddon = class extends require_dist.BaseAddon {
885
+ /**
886
+ * Sessions are stored as the concrete `NodeAvDecoderSession` (the only type
887
+ * this addon ever creates) so `getShmStats` can reach the per-session shm
888
+ * ring sink — `IDecoderSession` does not expose it.
889
+ */
890
+ sessions = /* @__PURE__ */ new Map();
891
+ /** Pixel-frame buffers — populated only for `frameSink: 'callback'` sessions. */
892
+ frameBuffers = /* @__PURE__ */ new Map();
893
+ /** `FrameHandle` buffers — populated only for `frameSink: 'shm'` sessions. */
894
+ handleBuffers = /* @__PURE__ */ new Map();
895
+ unsubscribers = /* @__PURE__ */ new Map();
896
+ sessionMeta = /* @__PURE__ */ new Map();
897
+ /**
898
+ * Per-shm-segment `FrameRingReader` cache backing `getFrame`. Opens each
899
+ * named segment once and reuses the reader for every later handle on it;
900
+ * built in `onInitialize` (it needs the scoped logger) and closed in
901
+ * `onShutdown`.
902
+ */
903
+ frameReaders = null;
904
+ /** Running `getFrame` hit/miss counters surfaced via `getShmStats`. */
905
+ getFrameHits = 0;
906
+ getFrameMisses = 0;
907
+ constructor() {
908
+ super(require_dist.DEFAULT_DECODER_HWACCEL_CONFIG);
909
+ }
910
+ globalSettingsSchema() {
911
+ return this.schema({ sections: [{
912
+ id: "hwaccel",
913
+ title: "Hardware acceleration",
914
+ tab: "decoder",
915
+ description: "Backend used by node-av decoder sessions. \"Auto\" defers to the probed best; concrete backends force it. Changes apply to NEW sessions — existing sessions keep the backend they were created with.",
916
+ fields: [this.field({
917
+ type: "select",
918
+ key: "hwaccel",
919
+ label: "Preferred backend",
920
+ options: [...require_dist.HWACCEL_OPTIONS],
921
+ default: "auto",
922
+ immediate: true
923
+ }), this.field({
924
+ type: "text",
925
+ key: "probedBestHwaccel",
926
+ label: "Probed best",
927
+ description: "Auto-detected best decoder backend on this host. Click the refresh icon to re-run the probe.",
928
+ readonlyField: true,
929
+ default: "",
930
+ perNode: true,
931
+ actions: [{
932
+ action: "reprobe-hwaccel",
933
+ icon: "refresh-cw",
934
+ tooltip: "Re-probe hwaccel"
935
+ }]
936
+ })]
937
+ }] });
938
+ }
939
+ async onInitialize() {
940
+ const backend = await require_frame_ring_sink.resolveDecoderBackend(this.ctx.api, this.resolveLocalNodeId(), this.ctx.logger);
941
+ if (backend !== "nodeav") {
942
+ this.ctx.logger.info("node-av decoder: this node selects a different decoder backend — standing down (no decoder provider registered)", { meta: { selectedBackend: backend } });
943
+ return [];
944
+ }
945
+ this.ctx.logger.info("node-av decoder addon initialized", { meta: { selectedBackend: backend } });
946
+ this.frameReaders = new _camstack_shm_ring.FrameRingReaderCache(this.ctx.logger);
947
+ if (!this.config.probedBestHwaccel) this.reprobeHwaccel().catch((err) => {
948
+ this.ctx.logger.warn("nodeav: auto-reprobe hwaccel failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
949
+ });
950
+ return [{
951
+ capability: require_dist.decoderCapability,
952
+ provider: this
953
+ }];
954
+ }
955
+ /**
956
+ * Resolve the effective hwaccel backend for a new session. Reads
957
+ * this addon's own `hwaccel` setting first. `'auto'` defers to the
958
+ * session's local resolver (`ctx.kernel.hwaccel`) which probes the
959
+ * host and picks. No more orchestrator round-trip — decoder addon
960
+ * is self-sufficient for this setting as of phase 2d.
961
+ */
962
+ resolveHwAccelPref() {
963
+ return this.config.hwaccel;
964
+ }
965
+ /**
966
+ * Re-run the platform probe on this host and persist the detected
967
+ * backend as `probedBestHwaccel`. The operator's `hwaccel` setting
968
+ * is intentionally left alone — the probe only updates the hint.
969
+ */
970
+ async reprobeHwaccel() {
971
+ const resolver = this.ctx.kernel.hwaccel;
972
+ if (!resolver) {
973
+ this.ctx.logger.warn("reprobeHwaccel: no kernel hwaccel resolver — returning none");
974
+ await this.updateGlobalSettings({ probedBestHwaccel: "none" });
975
+ return { backend: "none" };
976
+ }
977
+ try {
978
+ const res = await resolver.resolve();
979
+ const backend = res.preferred[0] ?? "none";
980
+ await this.updateGlobalSettings({ probedBestHwaccel: backend });
981
+ this.ctx.logger.info("reprobeHwaccel: wrote probedBestHwaccel", { meta: {
982
+ backend,
983
+ rationale: res.rationale,
984
+ preferred: res.preferred
985
+ } });
986
+ return { backend };
987
+ } catch (err) {
988
+ this.ctx.logger.warn("reprobeHwaccel failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
989
+ await this.updateGlobalSettings({ probedBestHwaccel: "none" });
990
+ return { backend: "none" };
991
+ }
992
+ }
993
+ async supportsCodec(input) {
994
+ return [
995
+ "h264",
996
+ "h265",
997
+ "hevc"
998
+ ].includes(input.codec.toLowerCase());
999
+ }
1000
+ async getInfo() {
1001
+ return {
1002
+ id: "decoder-nodeav",
1003
+ name: "Decoder (node-av)",
1004
+ isPullMode: false,
1005
+ priority: 10
1006
+ };
1007
+ }
1008
+ /**
1009
+ * The cluster node id of this decoder — the Moleculer nodeID (`hub`,
1010
+ * `dev-agent-0`, …), not the addon id. Stamped into session-owned
1011
+ * `FrameHandle`s so a downstream consumer routes `getFrame` to the node
1012
+ * that holds the shm ring. A hierarchical broker nodeID (`hub/...`) is
1013
+ * collapsed to the cluster-visible parent; in-process boot is left as-is.
1014
+ * Mirrors the resolution `PipelineRunnerAddon.onInitialize` performs.
1015
+ */
1016
+ resolveLocalNodeId() {
1017
+ const raw = this.ctx.kernel.localNodeId ?? this.ctx.id;
1018
+ return raw.includes("/") ? raw.split("/")[0] : raw;
1019
+ }
1020
+ async createSession(config) {
1021
+ const sessionId = (0, node_crypto.randomUUID)();
1022
+ const hwaccel = this.resolveHwAccelPref();
1023
+ const { frameSink } = config;
1024
+ const nodeId = this.resolveLocalNodeId();
1025
+ const session = new NodeAvDecoderSession(config, this.ctx.logger, {
1026
+ hwaccel,
1027
+ hwaccelResolver: this.ctx.kernel.hwaccel,
1028
+ frameSink,
1029
+ nodeId
1030
+ });
1031
+ const unsub = frameSink === "shm" ? this.wireShmSink(sessionId, session) : this.wireCallbackSink(sessionId, session);
1032
+ this.sessions.set(sessionId, session);
1033
+ this.unsubscribers.set(sessionId, unsub);
1034
+ this.sessionMeta.set(sessionId, {
1035
+ codec: config.codec,
1036
+ outputFormat: config.outputFormat,
1037
+ createdAtMs: Date.now()
1038
+ });
1039
+ this.ctx.logger.info("node-av: created session", { meta: {
1040
+ sessionId,
1041
+ codec: config.codec,
1042
+ hwaccelPref: hwaccel,
1043
+ frameSink,
1044
+ nodeId
1045
+ } });
1046
+ return {
1047
+ sessionId,
1048
+ nodeId
1049
+ };
1050
+ }
1051
+ /**
1052
+ * Subscribe a `'callback'` session's pixel frames into a per-session
1053
+ * ring buffer drained by `pullFrames`.
1054
+ */
1055
+ wireCallbackSink(sessionId, session) {
1056
+ const ringBuffer = new require_frame_ring_sink.NotifyingRingBuffer(FRAME_BUFFER_CAPACITY);
1057
+ this.frameBuffers.set(sessionId, ringBuffer);
1058
+ return session.onFrame((frame) => {
1059
+ const { format } = frame;
1060
+ if (format !== "jpeg" && format !== "rgb" && format !== "bgr" && format !== "yuv420" && format !== "gray") return;
1061
+ const arrayBuf = new ArrayBuffer(frame.data.byteLength);
1062
+ new Uint8Array(arrayBuf).set(frame.data);
1063
+ const capFrame = {
1064
+ data: new Uint8Array(arrayBuf),
1065
+ width: frame.width,
1066
+ height: frame.height,
1067
+ format,
1068
+ timestamp: frame.timestamp
1069
+ };
1070
+ ringBuffer.push(capFrame);
1071
+ });
1072
+ }
1073
+ /**
1074
+ * Subscribe a `'shm'` session's `FrameHandle`s into a per-session ring
1075
+ * buffer drained by `pullHandles`. No pixel bytes cross the cap boundary
1076
+ * — the broker opens the named segment and reads the pixels zero-copy.
1077
+ */
1078
+ wireShmSink(sessionId, session) {
1079
+ const handleRing = new require_frame_ring_sink.NotifyingRingBuffer(FRAME_BUFFER_CAPACITY);
1080
+ this.handleBuffers.set(sessionId, handleRing);
1081
+ return session.onFrameHandle((frame) => {
1082
+ handleRing.push(frame.handle);
1083
+ });
1084
+ }
1085
+ async destroySession(input) {
1086
+ const { sessionId } = input;
1087
+ const session = this.sessions.get(sessionId);
1088
+ if (!session) throw new Error(`decoder-nodeav: unknown sessionId ${sessionId}`);
1089
+ const unsub = this.unsubscribers.get(sessionId);
1090
+ if (unsub) unsub();
1091
+ this.frameBuffers.get(sessionId)?.cancel();
1092
+ this.handleBuffers.get(sessionId)?.cancel();
1093
+ await session.destroy();
1094
+ this.sessions.delete(sessionId);
1095
+ this.frameBuffers.delete(sessionId);
1096
+ this.handleBuffers.delete(sessionId);
1097
+ this.unsubscribers.delete(sessionId);
1098
+ this.sessionMeta.delete(sessionId);
1099
+ this.ctx.logger.info("node-av: destroyed session", { meta: { sessionId } });
1100
+ }
1101
+ async listActiveSessions() {
1102
+ const out = [];
1103
+ for (const [sessionId, meta] of this.sessionMeta) out.push({
1104
+ sessionId,
1105
+ codec: meta.codec,
1106
+ outputFormat: meta.outputFormat,
1107
+ createdAtMs: meta.createdAtMs
1108
+ });
1109
+ return out;
1110
+ }
1111
+ async pushPacket(input) {
1112
+ const session = this.sessions.get(input.sessionId);
1113
+ if (!session) throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
1114
+ const rawData = input.packet.data;
1115
+ const data = Buffer.isBuffer(rawData) ? rawData : rawData instanceof Uint8Array ? Buffer.from(rawData.buffer, rawData.byteOffset, rawData.byteLength) : Buffer.from(rawData);
1116
+ session.pushPacket({
1117
+ ...input.packet,
1118
+ data
1119
+ });
1120
+ }
1121
+ async openStream(input) {
1122
+ if (!this.sessions.get(input.sessionId)) throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
1123
+ input.url;
1124
+ }
1125
+ async pullFrames(input) {
1126
+ if (!this.sessions.has(input.sessionId)) throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
1127
+ const ringBuffer = this.frameBuffers.get(input.sessionId);
1128
+ if (!ringBuffer) return [];
1129
+ if (ringBuffer.size === 0 && input.waitMs) await ringBuffer.waitForItem(input.waitMs);
1130
+ return ringBuffer.drain(input.maxCount);
1131
+ }
1132
+ async pullHandles(input) {
1133
+ if (!this.sessions.has(input.sessionId)) throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
1134
+ const handleRing = this.handleBuffers.get(input.sessionId);
1135
+ if (!handleRing) return [];
1136
+ if (handleRing.size === 0 && input.waitMs) await handleRing.waitForItem(input.waitMs);
1137
+ return handleRing.drain(input.maxCount);
1138
+ }
1139
+ async updateConfig(input) {
1140
+ const session = this.sessions.get(input.sessionId);
1141
+ if (!session) throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
1142
+ session.updateConfig(input.config);
1143
+ }
1144
+ async getStats(input) {
1145
+ const session = this.sessions.get(input.sessionId);
1146
+ if (!session) throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
1147
+ return session.getStats();
1148
+ }
1149
+ /**
1150
+ * Read back the pixels a `FrameHandle` refers to from this node's shm ring
1151
+ * (Phase 5 / D9 downstream access). Returns `null` when the slot was
1152
+ * already recycled (latest-wins drop) or the segment could not be opened.
1153
+ * The reader cache opens each named segment once and reuses the reader.
1154
+ *
1155
+ * The reader hands back a `Buffer` view over its **reusable scratch
1156
+ * buffer**, only valid until the next `read` on the same reader; the
1157
+ * cap caller may keep the frame across reads, so the pixels are copied
1158
+ * into a fresh detached `ArrayBuffer` here. This matches the existing
1159
+ * callback-path copy in `wireCallbackSink`.
1160
+ */
1161
+ async getFrame(input) {
1162
+ const frame = this.frameReaders?.read(input.handle) ?? null;
1163
+ if (!frame) {
1164
+ this.getFrameMisses += 1;
1165
+ return null;
1166
+ }
1167
+ this.getFrameHits += 1;
1168
+ const arrayBuf = new ArrayBuffer(frame.data.byteLength);
1169
+ new Uint8Array(arrayBuf).set(frame.data);
1170
+ return {
1171
+ data: new Uint8Array(arrayBuf),
1172
+ width: frame.width,
1173
+ height: frame.height,
1174
+ format: frame.format,
1175
+ timestamp: frame.timestamp
1176
+ };
1177
+ }
1178
+ /**
1179
+ * shm ring usage stats for a `frameSink: 'shm'` session — slot geometry,
1180
+ * frames written, byte budget, plus this addon's running `getFrame`
1181
+ * hit/miss counters. Returns `null` for an unknown session or one whose
1182
+ * shm ring has not yet been armed by a first decoded frame.
1183
+ */
1184
+ async getShmStats(input) {
1185
+ const stats = this.sessions.get(input.sessionId)?.frameRingSinkOrNull?.getShmStats() ?? null;
1186
+ if (!stats) return null;
1187
+ return {
1188
+ sessionId: input.sessionId,
1189
+ ...stats,
1190
+ budgetMb: require_frame_ring_sink.RING_BUDGET_MB,
1191
+ getFrameHits: this.getFrameHits,
1192
+ getFrameMisses: this.getFrameMisses
1193
+ };
1194
+ }
1195
+ async onShutdown() {
1196
+ this.ctx.logger.info("node-av decoder addon shutdown — destroying all sessions");
1197
+ const destroyPromises = [];
1198
+ for (const [sessionId, session] of this.sessions) {
1199
+ const unsub = this.unsubscribers.get(sessionId);
1200
+ if (unsub) unsub();
1201
+ destroyPromises.push(session.destroy());
1202
+ }
1203
+ await Promise.all(destroyPromises);
1204
+ this.sessions.clear();
1205
+ this.frameBuffers.clear();
1206
+ this.handleBuffers.clear();
1207
+ this.unsubscribers.clear();
1208
+ this.sessionMeta.clear();
1209
+ this.frameReaders?.close();
1210
+ this.frameReaders = null;
1211
+ }
1212
+ };
1213
+ //#endregion
1214
+ exports.DecoderFrameRingSink = require_frame_ring_sink.DecoderFrameRingSink;
1215
+ exports.DecoderNodeAvAddon = DecoderNodeAvAddon;
1216
+ exports.NodeAvDecoderSession = NodeAvDecoderSession;
1217
+ exports.default = DecoderNodeAvAddon;
1218
+ exports.makeSegmentName = require_frame_ring_sink.makeSegmentName;