@camstack/addon-pipeline 0.1.8

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 (107) hide show
  1. package/dist/audio-analyzer/index.js +723 -0
  2. package/dist/audio-analyzer/index.js.map +1 -0
  3. package/dist/audio-analyzer/index.mjs +683 -0
  4. package/dist/audio-analyzer/index.mjs.map +1 -0
  5. package/dist/audio-codec-nodeav/index.js +467 -0
  6. package/dist/audio-codec-nodeav/index.js.map +1 -0
  7. package/dist/audio-codec-nodeav/index.mjs +467 -0
  8. package/dist/audio-codec-nodeav/index.mjs.map +1 -0
  9. package/dist/decoder-nodeav/index.js +929 -0
  10. package/dist/decoder-nodeav/index.js.map +1 -0
  11. package/dist/decoder-nodeav/index.mjs +907 -0
  12. package/dist/decoder-nodeav/index.mjs.map +1 -0
  13. package/dist/detection-pipeline/index.js +5766 -0
  14. package/dist/detection-pipeline/index.js.map +1 -0
  15. package/dist/detection-pipeline/index.mjs +5725 -0
  16. package/dist/detection-pipeline/index.mjs.map +1 -0
  17. package/dist/index-D_cl0Qqb.js +5791 -0
  18. package/dist/index-D_cl0Qqb.js.map +1 -0
  19. package/dist/index-UbcdLS7a.mjs +5790 -0
  20. package/dist/index-UbcdLS7a.mjs.map +1 -0
  21. package/dist/motion-wasm/index.js +476 -0
  22. package/dist/motion-wasm/index.js.map +1 -0
  23. package/dist/motion-wasm/index.mjs +454 -0
  24. package/dist/motion-wasm/index.mjs.map +1 -0
  25. package/dist/pipeline-runner/index.js +1669 -0
  26. package/dist/pipeline-runner/index.js.map +1 -0
  27. package/dist/pipeline-runner/index.mjs +1647 -0
  28. package/dist/pipeline-runner/index.mjs.map +1 -0
  29. package/dist/stream-broker/@mf-types/compiled-types/stream-broker/widgets/StreamBrokerPanel.d.ts +21 -0
  30. package/dist/stream-broker/@mf-types/compiled-types/stream-broker/widgets/index.d.ts +13 -0
  31. package/dist/stream-broker/@mf-types/widgets.d.ts +2 -0
  32. package/dist/stream-broker/@mf-types.d.ts +3 -0
  33. package/dist/stream-broker/@mf-types.zip +0 -0
  34. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_sdk__loadShare__.mjs-h5aXOPSA.mjs +12 -0
  35. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.mjs-C-URP6DW.mjs +17 -0
  36. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.mjs-69eEmXwl.mjs +20 -0
  37. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-U1EUeEPs.mjs +104 -0
  38. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DeouEaSs.mjs +85 -0
  39. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-DHUwjbb9.mjs +62 -0
  40. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react__loadShare__.mjs-DePVYdid.mjs +85 -0
  41. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react__loadShare__.mjs_commonjs-proxy-CBlCGyx5.mjs +29 -0
  42. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-gBEZsQrp.mjs +36 -0
  43. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom__loadShare__.mjs-DYEKzzY-.mjs +45 -0
  44. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-DZchZKbW.mjs +6 -0
  45. package/dist/stream-broker/__mfe_internal__addon_stream_broker_widgets__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-DICOtMTl.mjs +34 -0
  46. package/dist/stream-broker/_stub.js +752 -0
  47. package/dist/stream-broker/_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-D6o1e2ed.mjs +156 -0
  48. package/dist/stream-broker/client-BK73l2KT.mjs +10063 -0
  49. package/dist/stream-broker/getErrorShape-BPSzUA7W-TlK8ipWe.mjs +211 -0
  50. package/dist/stream-broker/hostInit-RCeroTVY.mjs +168 -0
  51. package/dist/stream-broker/index-BYclbfM0.mjs +15806 -0
  52. package/dist/stream-broker/index-BhXZh4lQ.mjs +1617 -0
  53. package/dist/stream-broker/index-BxHaCH3N.mjs +725 -0
  54. package/dist/stream-broker/index-D2-K2YJ7.mjs +19268 -0
  55. package/dist/stream-broker/index-IUYKHbxX.mjs +185 -0
  56. package/dist/stream-broker/index-Ss9m7Jum.mjs +2603 -0
  57. package/dist/stream-broker/index-ns1fRD30.mjs +435 -0
  58. package/dist/stream-broker/index-xncRG7-x.mjs +2713 -0
  59. package/dist/stream-broker/index.js +11171 -0
  60. package/dist/stream-broker/index.js.map +1 -0
  61. package/dist/stream-broker/index.mjs +11130 -0
  62. package/dist/stream-broker/index.mjs.map +1 -0
  63. package/dist/stream-broker/jsx-runtime-ZdY5pIZz.mjs +55 -0
  64. package/dist/stream-broker/remoteEntry.js +2973 -0
  65. package/dist/stream-broker/virtualExposes-pCd777Rp.mjs +42 -0
  66. package/package.json +258 -0
  67. package/python/__pycache__/inference_pool.cpython-313.pyc +0 -0
  68. package/python/inference_pool.py +1088 -0
  69. package/python/postprocessors/__init__.py +24 -0
  70. package/python/postprocessors/__pycache__/__init__.cpython-312.pyc +0 -0
  71. package/python/postprocessors/__pycache__/__init__.cpython-313.pyc +0 -0
  72. package/python/postprocessors/__pycache__/_safety.cpython-313.pyc +0 -0
  73. package/python/postprocessors/__pycache__/arcface.cpython-312.pyc +0 -0
  74. package/python/postprocessors/__pycache__/arcface.cpython-313.pyc +0 -0
  75. package/python/postprocessors/__pycache__/ctc.cpython-312.pyc +0 -0
  76. package/python/postprocessors/__pycache__/ctc.cpython-313.pyc +0 -0
  77. package/python/postprocessors/__pycache__/saliency.cpython-312.pyc +0 -0
  78. package/python/postprocessors/__pycache__/saliency.cpython-313.pyc +0 -0
  79. package/python/postprocessors/__pycache__/scrfd.cpython-312.pyc +0 -0
  80. package/python/postprocessors/__pycache__/scrfd.cpython-313.pyc +0 -0
  81. package/python/postprocessors/__pycache__/softmax.cpython-312.pyc +0 -0
  82. package/python/postprocessors/__pycache__/softmax.cpython-313.pyc +0 -0
  83. package/python/postprocessors/__pycache__/yamnet.cpython-312.pyc +0 -0
  84. package/python/postprocessors/__pycache__/yamnet.cpython-313.pyc +0 -0
  85. package/python/postprocessors/__pycache__/yolo.cpython-312.pyc +0 -0
  86. package/python/postprocessors/__pycache__/yolo.cpython-313.pyc +0 -0
  87. package/python/postprocessors/__pycache__/yolo_seg.cpython-312.pyc +0 -0
  88. package/python/postprocessors/__pycache__/yolo_seg.cpython-313.pyc +0 -0
  89. package/python/postprocessors/arcface.py +31 -0
  90. package/python/postprocessors/ctc.py +68 -0
  91. package/python/postprocessors/saliency.py +44 -0
  92. package/python/postprocessors/scrfd.py +212 -0
  93. package/python/postprocessors/softmax.py +43 -0
  94. package/python/postprocessors/yamnet.py +41 -0
  95. package/python/postprocessors/yolo.py +278 -0
  96. package/python/postprocessors/yolo_seg.py +247 -0
  97. package/python/requirements-coreml.txt +4 -0
  98. package/python/requirements-onnxruntime.txt +3 -0
  99. package/python/requirements-openvino.txt +3 -0
  100. package/python/requirements.txt +9 -0
  101. package/swift/audio-analyzer/apple-sound-classifier +0 -0
  102. package/swift/audio-analyzer/apple-sound-classifier.swift +213 -0
  103. package/swift/detection-pipeline/apple-sound-classifier +0 -0
  104. package/swift/detection-pipeline/apple-sound-classifier.swift +196 -0
  105. package/wasm/assembly/index.ts +290 -0
  106. package/wasm/assembly/tsconfig.json +4 -0
  107. package/wasm/motion.wasm +0 -0
@@ -0,0 +1,907 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { errMsg, BaseAddon, DEFAULT_DECODER_HWACCEL_CONFIG, HWACCEL_OPTIONS, decoderCapability, RingBuffer } from "@camstack/types";
3
+ function backendToHwDeviceConst(backend, consts) {
4
+ switch (backend) {
5
+ case "videotoolbox":
6
+ return consts.AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
7
+ case "cuda":
8
+ return consts.AV_HWDEVICE_TYPE_CUDA;
9
+ case "nvdec":
10
+ return consts.AV_HWDEVICE_TYPE_CUDA;
11
+ // node-av exposes only CUDA; nvdec aliases to it
12
+ case "vaapi":
13
+ return consts.AV_HWDEVICE_TYPE_VAAPI;
14
+ case "qsv":
15
+ return consts.AV_HWDEVICE_TYPE_QSV;
16
+ case "d3d11va":
17
+ return consts.AV_HWDEVICE_TYPE_D3D11VA;
18
+ case "dxva2":
19
+ return consts.AV_HWDEVICE_TYPE_DXVA2;
20
+ case "amf":
21
+ return consts.AV_HWDEVICE_TYPE_AMF;
22
+ case "vdpau":
23
+ return consts.AV_HWDEVICE_TYPE_VDPAU;
24
+ case "drm":
25
+ return consts.AV_HWDEVICE_TYPE_DRM;
26
+ default:
27
+ return null;
28
+ }
29
+ }
30
+ function backendToHwPixFmt(backend, consts) {
31
+ switch (backend) {
32
+ case "videotoolbox":
33
+ return consts.AV_PIX_FMT_VIDEOTOOLBOX;
34
+ case "cuda":
35
+ return consts.AV_PIX_FMT_CUDA;
36
+ case "nvdec":
37
+ return consts.AV_PIX_FMT_CUDA;
38
+ case "vaapi":
39
+ return consts.AV_PIX_FMT_VAAPI;
40
+ case "qsv":
41
+ return consts.AV_PIX_FMT_QSV;
42
+ case "d3d11va":
43
+ return consts.AV_PIX_FMT_D3D11;
44
+ case "dxva2":
45
+ return consts.AV_PIX_FMT_DXVA2_VLD;
46
+ case "amf":
47
+ return consts.AV_PIX_FMT_D3D11;
48
+ case "vdpau":
49
+ return consts.AV_PIX_FMT_VDPAU;
50
+ case "drm":
51
+ return consts.AV_PIX_FMT_DRM_PRIME;
52
+ default:
53
+ return null;
54
+ }
55
+ }
56
+ let _nav = null;
57
+ let _consts = null;
58
+ let _sharp = null;
59
+ async function getNodeAv() {
60
+ if (!_nav) _nav = await import("node-av");
61
+ return _nav;
62
+ }
63
+ async function getConstants() {
64
+ if (!_consts) _consts = await import("../index-UbcdLS7a.mjs");
65
+ return _consts;
66
+ }
67
+ async function getSharp() {
68
+ if (!_sharp) {
69
+ const mod = await import("sharp");
70
+ _sharp = mod.default;
71
+ }
72
+ return _sharp;
73
+ }
74
+ const noopLogger = {
75
+ debug() {
76
+ },
77
+ info() {
78
+ },
79
+ warn() {
80
+ },
81
+ error() {
82
+ },
83
+ child() {
84
+ return noopLogger;
85
+ },
86
+ withTags() {
87
+ return noopLogger;
88
+ }
89
+ };
90
+ class NodeAvDecoderSession {
91
+ config;
92
+ logger;
93
+ frameCallbacks = /* @__PURE__ */ new Set();
94
+ destroyed = false;
95
+ // Low-level node-av objects (initialized on first keyframe)
96
+ parser = null;
97
+ codecCtx = null;
98
+ scaler = null;
99
+ avPacket = null;
100
+ avFrame = null;
101
+ dstFrame = null;
102
+ // Cached constants (loaded during init, used in hot path)
103
+ // Hard-coded numeric defaults are replaced in initDecoder() with the real
104
+ // branded constants from `node-av/constants`. The `as` cast at the literal
105
+ // is a one-time branding bridge — once initDecoder runs we hold the exact
106
+ // AVPixelFormat/SwsFlags/AVError values.
107
+ EAGAIN = -11;
108
+ PIX_FMT_GRAY8 = 8;
109
+ PIX_FMT_RGB24 = 2;
110
+ SWS_FAST_BILINEAR = 1;
111
+ /**
112
+ * Decoder output mode. Drives both the scaler's destination pixel
113
+ * format and whether sharp runs the JPEG encode at the end:
114
+ *
115
+ * - `'jpeg'` — scaler→RGB24 → sharp encode → emit JPEG bytes
116
+ * - `'rgb'` — scaler→RGB24 → emit raw RGB24 (no sharp)
117
+ * - `'gray'` — scaler→GRAY8 → emit raw GRAY8 (no sharp)
118
+ *
119
+ * The broker holds the policy decision on which mode to request based
120
+ * on its active subscribers; on-the-fly conversion (e.g. RGB→JPEG for
121
+ * a WebRTC consumer that joined while detection holds the decoder in
122
+ * RGB mode) happens broker-side via the per-frame conversion cache.
123
+ */
124
+ outputMode;
125
+ sharpFn = null;
126
+ /**
127
+ * Backpressure for the sharp JPEG encode pipeline. The broker
128
+ * currently creates sessions with `maxFps: 0` (unlimited) and relies
129
+ * on per-subscriber throttling, so without a bound the
130
+ * fire-and-forget `sharp(...).toBuffer()` chain would accumulate
131
+ * unboundedly whenever sharp falls behind the decoder. Cap at
132
+ * `MAX_JPEG_INFLIGHT` pending encodes per session — any frame that
133
+ * arrives while the cap is saturated is dropped and counted.
134
+ */
135
+ static MAX_JPEG_INFLIGHT = 2;
136
+ jpegEncodeInFlight = 0;
137
+ /**
138
+ * Map a `DecoderSessionConfig.outputFormat` value to one of the three
139
+ * native scaler/encoder modes the session understands. The cap-level
140
+ * format vocabulary is broader (it accepts `bgr`, `yuv420`) than what
141
+ * libav's scaler is wired for here — anything else degrades to RGB
142
+ * (the canonical raw mode) and the broker is expected to convert
143
+ * downstream if a subscriber needs a different shape.
144
+ */
145
+ static resolveOutputMode(format) {
146
+ if (format === "jpeg" || format === void 0) return "jpeg";
147
+ if (format === "gray") return "gray";
148
+ return "rgb";
149
+ }
150
+ initialized = false;
151
+ initializing = false;
152
+ scalerInitializing = false;
153
+ /**
154
+ * Monotonic counter incremented by `updateConfig` whenever the
155
+ * scaler + dstFrame get invalidated (e.g. output format toggle).
156
+ * `initScaler` captures the current value at entry and aborts — or
157
+ * disposes the locally-built scaler — if the epoch moved while
158
+ * its async init was in flight. Without this, a toggle racing an
159
+ * in-flight init could leave two scalers allocated natively while
160
+ * `this.scaler` only holds a reference to one → libav leak.
161
+ */
162
+ scalerEpoch = 0;
163
+ /**
164
+ * One-shot guard for the "first frame" diagnostic log + raw frame
165
+ * dump. Setting this synchronously inside `emitDecodedFrame`
166
+ * prevents re-entry — without it we were using `outputFrames === 0`
167
+ * which stays true until the async sharp encode callback runs, so
168
+ * several decoded frames could trigger the dump before the first
169
+ * JPEG landed.
170
+ */
171
+ firstFrameLogged = false;
172
+ // Output dimensions
173
+ outWidth = 0;
174
+ outHeight = 0;
175
+ // FPS limiter
176
+ lastEmitTime = 0;
177
+ minIntervalMs;
178
+ // Stats
179
+ inputPackets = 0;
180
+ outputFrames = 0;
181
+ droppedFrames = 0;
182
+ totalDecodeTimeMs = 0;
183
+ startTime = Date.now();
184
+ hwaccelPref;
185
+ hwaccelResolver;
186
+ /** The backend that actually initialised successfully — `'none'` = software fallback. */
187
+ activeHwAccel = "none";
188
+ hwDevice = null;
189
+ swTransferFrame = null;
190
+ constructor(config, logger = noopLogger, options) {
191
+ this.config = { ...config };
192
+ const sessionTags = {};
193
+ if (typeof config.deviceId === "number") sessionTags["deviceId"] = config.deviceId;
194
+ if (typeof config.tag === "string" && config.tag.length > 0) sessionTags["tag"] = config.tag;
195
+ this.logger = Object.keys(sessionTags).length > 0 ? logger.withTags(sessionTags) : logger;
196
+ this.minIntervalMs = config.maxFps > 0 ? 1e3 / config.maxFps : 0;
197
+ this.outputMode = NodeAvDecoderSession.resolveOutputMode(config.outputFormat);
198
+ this.hwaccelPref = options?.hwaccel ?? "auto";
199
+ this.hwaccelResolver = options?.hwaccelResolver ?? null;
200
+ }
201
+ /**
202
+ * Resolve the backend preference list and try each one against
203
+ * node-av's HW context APIs. The first backend whose
204
+ * `HardwareDeviceContext.create()` succeeds gets attached to
205
+ * `codecCtx.hwDeviceCtx` + its hw pixel format registered via
206
+ * `setHardwarePixelFormat`. On any failure, falls through to the
207
+ * next backend; if all fail, returns with `activeHwAccel='none'`
208
+ * and the decoder runs in software on the same context.
209
+ */
210
+ async tryAttachHwAccel(nav, C) {
211
+ if (!this.codecCtx) return;
212
+ if (this.hwaccelPref === "none") {
213
+ this.activeHwAccel = "none";
214
+ return;
215
+ }
216
+ const explicit = this.hwaccelPref === "auto" ? null : this.hwaccelPref;
217
+ const resolution = this.hwaccelResolver ? await this.hwaccelResolver.resolve(explicit) : explicit ? { preferred: [explicit], rationale: "explicit (no resolver)" } : { preferred: [], rationale: "auto + no resolver → software" };
218
+ if (resolution.preferred.length === 0) {
219
+ this.activeHwAccel = "none";
220
+ return;
221
+ }
222
+ for (const backend of resolution.preferred) {
223
+ const deviceType = backendToHwDeviceConst(backend, C);
224
+ const hwPixFmt = backendToHwPixFmt(backend, C);
225
+ if (!deviceType || !hwPixFmt) continue;
226
+ const device = new nav.HardwareDeviceContext();
227
+ const rc = device.create(deviceType);
228
+ if (rc < 0) {
229
+ this.logger.warn("node-av: hwaccel device create failed — trying next", {
230
+ meta: { backend, rc }
231
+ });
232
+ device.free();
233
+ continue;
234
+ }
235
+ try {
236
+ this.codecCtx.hwDeviceCtx = device;
237
+ this.codecCtx.setHardwarePixelFormat(hwPixFmt);
238
+ } catch (err) {
239
+ this.logger.warn("node-av: hwaccel context attach failed — trying next", {
240
+ meta: { backend, error: errMsg(err) }
241
+ });
242
+ device.free();
243
+ continue;
244
+ }
245
+ this.hwDevice = device;
246
+ this.activeHwAccel = backend;
247
+ return;
248
+ }
249
+ this.logger.warn("node-av: no hwaccel backend initialised — using software", {
250
+ meta: { attempted: resolution.preferred.join(","), rationale: resolution.rationale }
251
+ });
252
+ this.activeHwAccel = "none";
253
+ }
254
+ /**
255
+ * Download a HW frame (format == hw pix fmt) into a SW frame so the
256
+ * rest of the pipeline (scaler, JPEG encoder, grayscale passthrough)
257
+ * handles it identically to the pure-software path. Uses the sync
258
+ * variant so the synchronous receive loop below doesn't need to be
259
+ * async-ified. Returns `null` on transfer failure, meaning the
260
+ * caller should drop the frame.
261
+ */
262
+ transferHwFrame(hwFrame) {
263
+ if (this.activeHwAccel === "none" || !this.swTransferFrame) return hwFrame;
264
+ const rc = hwFrame.hwframeTransferDataSync(this.swTransferFrame, 0);
265
+ if (rc < 0) {
266
+ this.logger.warn("node-av: hwframeTransferData failed", { meta: { rc } });
267
+ return null;
268
+ }
269
+ return this.swTransferFrame;
270
+ }
271
+ /**
272
+ * Initialize the decoder pipeline on the first keyframe.
273
+ * After this returns, all hot-path methods are fully synchronous (except JPEG encode).
274
+ */
275
+ async initDecoder() {
276
+ if (this.initialized || this.initializing || this.destroyed) return;
277
+ this.initializing = true;
278
+ try {
279
+ const nav = await getNodeAv();
280
+ const C = await getConstants();
281
+ this.EAGAIN = C.AVERROR_EAGAIN;
282
+ this.PIX_FMT_GRAY8 = C.AV_PIX_FMT_GRAY8;
283
+ this.PIX_FMT_RGB24 = C.AV_PIX_FMT_RGB24;
284
+ this.SWS_FAST_BILINEAR = C.SWS_FAST_BILINEAR;
285
+ if (this.outputMode === "jpeg") {
286
+ this.sharpFn = await getSharp();
287
+ }
288
+ nav.Log.setLevel(C.AV_LOG_FATAL);
289
+ const isHevc = this.config.codec === "h265" || this.config.codec === "hevc";
290
+ const codecId = isHevc ? C.AV_CODEC_ID_HEVC : C.AV_CODEC_ID_H264;
291
+ this.parser = new nav.CodecParser();
292
+ this.parser.init(codecId);
293
+ const codec = nav.Codec.findDecoder(codecId);
294
+ if (!codec) {
295
+ this.logger.error("node-av: no decoder found", { meta: { codec: this.config.codec } });
296
+ return;
297
+ }
298
+ this.codecCtx = new nav.CodecContext();
299
+ this.codecCtx.allocContext3(codec);
300
+ if (this.config.width && this.config.height) {
301
+ this.codecCtx.width = this.config.width;
302
+ this.codecCtx.height = this.config.height;
303
+ }
304
+ this.codecCtx.threadCount = 1;
305
+ await this.tryAttachHwAccel(nav, C);
306
+ const ret = await this.codecCtx.open2(codec);
307
+ if (ret < 0) {
308
+ if (this.activeHwAccel !== "none") {
309
+ this.logger.warn("node-av: open2 failed with hwaccel — retrying in software", {
310
+ meta: { ret, hwAccel: this.activeHwAccel }
311
+ });
312
+ this.hwDevice?.free();
313
+ this.hwDevice = null;
314
+ this.activeHwAccel = "none";
315
+ this.codecCtx = new nav.CodecContext();
316
+ this.codecCtx.allocContext3(codec);
317
+ if (this.config.width && this.config.height) {
318
+ this.codecCtx.width = this.config.width;
319
+ this.codecCtx.height = this.config.height;
320
+ }
321
+ this.codecCtx.threadCount = 1;
322
+ const retry = await this.codecCtx.open2(codec);
323
+ if (retry < 0) {
324
+ this.logger.error("node-av: failed to open decoder (sw fallback)", { meta: { ret: retry } });
325
+ return;
326
+ }
327
+ } else {
328
+ this.logger.error("node-av: failed to open decoder", { meta: { ret } });
329
+ return;
330
+ }
331
+ }
332
+ if (this.activeHwAccel !== "none") {
333
+ this.swTransferFrame = new nav.Frame();
334
+ this.swTransferFrame.alloc();
335
+ }
336
+ this.avPacket = new nav.Packet();
337
+ this.avPacket.alloc();
338
+ this.avFrame = new nav.Frame();
339
+ this.avFrame.alloc();
340
+ this.initialized = true;
341
+ this.logger.info("node-av push decoder initialized", {
342
+ meta: {
343
+ codec: this.config.codec,
344
+ output: this.outputMode,
345
+ // Reports the backend that actually succeeded at
346
+ // `open2(codec)` with `hwDeviceCtx` attached, or `'none'` if
347
+ // we fell back to software (explicit `hwaccel: 'none'`
348
+ // override, empty resolver output, or every attempted
349
+ // backend failed init).
350
+ hwAccel: this.activeHwAccel
351
+ }
352
+ });
353
+ } catch (err) {
354
+ this.logger.error("node-av init error", { meta: { error: errMsg(err) } });
355
+ } finally {
356
+ this.initializing = false;
357
+ }
358
+ }
359
+ /**
360
+ * Initialize the scaler after the first frame tells us the actual
361
+ * dimensions. Output pixel format: RGB24 for JPEG encoding, GRAY8
362
+ * for raw motion.
363
+ *
364
+ * Builds `scaler` + `dstFrame` on local variables and publishes
365
+ * them onto `this` in a single atomic step at the end. Captures
366
+ * `scalerEpoch` at entry; if `updateConfig` invalidated the scaler
367
+ * while this init was in flight (epoch mismatch), the locally
368
+ * built pair is disposed and discarded so the later init wins.
369
+ * Without the local-first approach, partial state (scaler set,
370
+ * dstFrame still null) could be observed by a concurrent
371
+ * `emitDecodedFrame` call.
372
+ */
373
+ async initScaler(srcW, srcH, srcFmt) {
374
+ if (this.scalerInitializing) return;
375
+ this.scalerInitializing = true;
376
+ const myEpoch = this.scalerEpoch;
377
+ let localScaler = null;
378
+ let localDstFrame = null;
379
+ try {
380
+ const nav = await getNodeAv();
381
+ if (this.destroyed || myEpoch !== this.scalerEpoch) return;
382
+ const scale = this.config.scale > 1 ? this.config.scale : 1;
383
+ const maxW = Math.floor(640 / scale);
384
+ const outWidth = Math.min(srcW, maxW);
385
+ const outHeight = Math.round(outWidth * srcH / srcW);
386
+ const dstFmt = this.outputMode === "gray" ? this.PIX_FMT_GRAY8 : this.PIX_FMT_RGB24;
387
+ const fmtName = this.outputMode === "gray" ? "gray8" : "rgb24";
388
+ localScaler = new nav.SoftwareScaleContext();
389
+ localScaler.getContext(
390
+ srcW,
391
+ srcH,
392
+ srcFmt,
393
+ outWidth,
394
+ outHeight,
395
+ dstFmt,
396
+ this.SWS_FAST_BILINEAR
397
+ );
398
+ const ret = localScaler.initContext();
399
+ if (ret < 0) {
400
+ this.logger.error("node-av: sws_init_context failed", { meta: { ret } });
401
+ return;
402
+ }
403
+ localDstFrame = new nav.Frame();
404
+ localDstFrame.alloc();
405
+ localDstFrame.width = outWidth;
406
+ localDstFrame.height = outHeight;
407
+ localDstFrame.format = dstFmt;
408
+ const allocRet = localDstFrame.allocBuffer();
409
+ if (allocRet < 0) {
410
+ this.logger.error("node-av: dst frame allocBuffer failed", { meta: { ret: allocRet } });
411
+ return;
412
+ }
413
+ if (this.destroyed || myEpoch !== this.scalerEpoch) return;
414
+ this.scaler?.[Symbol.dispose]?.();
415
+ this.dstFrame?.[Symbol.dispose]?.();
416
+ this.scaler = localScaler;
417
+ this.dstFrame = localDstFrame;
418
+ this.outWidth = outWidth;
419
+ this.outHeight = outHeight;
420
+ localScaler = null;
421
+ localDstFrame = null;
422
+ this.logger.info("node-av scaler initialized", {
423
+ meta: { srcWidth: srcW, srcHeight: srcH, outWidth, outHeight, format: fmtName }
424
+ });
425
+ } catch (err) {
426
+ this.logger.error("Scaler init failed", { meta: { error: errMsg(err) } });
427
+ } finally {
428
+ localScaler?.[Symbol.dispose]?.();
429
+ localDstFrame?.[Symbol.dispose]?.();
430
+ this.scalerInitializing = false;
431
+ }
432
+ }
433
+ pushPacket(packet) {
434
+ if (this.destroyed) return;
435
+ this.inputPackets++;
436
+ if (!this.initialized && !this.initializing && packet.keyframe) {
437
+ this.initDecoder().then(() => {
438
+ if (this.initialized) this.decodeRawData(packet.data, packet.pts ?? Date.now());
439
+ }).catch((err) => {
440
+ this.logger.error("node-av init failed", { meta: { error: errMsg(err) } });
441
+ });
442
+ return;
443
+ }
444
+ if (!this.initialized) return;
445
+ this.decodeRawData(packet.data, packet.pts ?? Date.now());
446
+ }
447
+ decodeRawData(data, pts) {
448
+ if (!this.parser || !this.codecCtx || !this.avPacket || !this.avFrame) return;
449
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
450
+ const bigPts = BigInt(pts);
451
+ let offset = 0;
452
+ while (offset < buf.length) {
453
+ const remaining = buf.subarray(offset);
454
+ const consumed = this.parser.parse2(
455
+ this.codecCtx,
456
+ this.avPacket,
457
+ remaining,
458
+ bigPts,
459
+ bigPts,
460
+ offset
461
+ );
462
+ if (consumed < 0) {
463
+ this.logger.warn("node-av parser error", { meta: { ret: consumed } });
464
+ break;
465
+ }
466
+ offset += consumed;
467
+ if (this.avPacket.size > 0) {
468
+ this.decodePacket();
469
+ this.avPacket.unref();
470
+ }
471
+ }
472
+ }
473
+ decodePacket() {
474
+ if (!this.codecCtx || !this.avFrame) return;
475
+ const sendRet = this.codecCtx.sendPacketSync(this.avPacket);
476
+ if (sendRet < 0 && sendRet !== this.EAGAIN) {
477
+ this.logger.warn("node-av sendPacket error", { meta: { ret: sendRet } });
478
+ return;
479
+ }
480
+ while (true) {
481
+ const recvRet = this.codecCtx.receiveFrameSync(this.avFrame);
482
+ if (recvRet < 0) break;
483
+ const frame = this.transferHwFrame(this.avFrame);
484
+ if (!frame) continue;
485
+ this.emitDecodedFrame(frame);
486
+ }
487
+ }
488
+ emitDecodedFrame(frame) {
489
+ const now = performance.now();
490
+ if (this.minIntervalMs > 0 && now - this.lastEmitTime < this.minIntervalMs) {
491
+ this.droppedFrames++;
492
+ return;
493
+ }
494
+ if (!this.scaler && !this.scalerInitializing) {
495
+ this.initScaler(frame.width, frame.height, frame.format);
496
+ return;
497
+ }
498
+ if (!this.dstFrame || !this.scaler) return;
499
+ const decodeStart = performance.now();
500
+ try {
501
+ this.dstFrame.makeWritable();
502
+ this.scaler.scaleFrameSync(this.dstFrame, frame);
503
+ } catch (err) {
504
+ this.logger.warn("node-av scale error", { meta: { error: errMsg(err) } });
505
+ return;
506
+ }
507
+ if (!this.firstFrameLogged) {
508
+ this.firstFrameLogged = true;
509
+ const channels = this.outputMode === "gray" ? 1 : 3;
510
+ const ls = this.dstFrame.linesize;
511
+ const buf = this.dstFrame.toBuffer();
512
+ this.logger.info("dstFrame after scale", {
513
+ meta: {
514
+ phase: "frame-debug",
515
+ width: this.dstFrame.width,
516
+ height: this.dstFrame.height,
517
+ linesize: [ls[0], ls[1], ls[2]],
518
+ expectedStride: this.dstFrame.width * channels,
519
+ bufLen: buf.length,
520
+ expectedPacked: this.dstFrame.width * channels * this.dstFrame.height,
521
+ srcFormat: frame.format ?? "?"
522
+ }
523
+ });
524
+ if (this.outputMode !== "gray") {
525
+ import("node:fs").then((fsModule) => {
526
+ import("node:path").then((pathModule) => {
527
+ const dumpPath = pathModule.join(process.cwd(), "camstack-data", "debug-frame-rgb24.raw");
528
+ fsModule.writeFileSync(dumpPath, buf);
529
+ this.logger.info("Dumped first RGB24 frame", { meta: { phase: "frame-debug", path: dumpPath, bytes: buf.length } });
530
+ }).catch(() => {
531
+ });
532
+ }).catch(() => {
533
+ });
534
+ }
535
+ }
536
+ const rawBuf = this.extractPackedBuffer(this.dstFrame);
537
+ if (this.outputMode === "jpeg") {
538
+ this.encodeAndEmitJpeg(rawBuf, decodeStart);
539
+ } else if (this.outputMode === "rgb") {
540
+ this.emitRawFrame(rawBuf, "rgb", decodeStart);
541
+ } else {
542
+ this.emitRawFrame(rawBuf, "gray", decodeStart);
543
+ }
544
+ }
545
+ /**
546
+ * Extract packed pixel buffer from a decoded frame.
547
+ * FFmpeg's av_frame_get_buffer() may pad each row to alignment (32/64 bytes).
548
+ * Sharp and WASM consumers expect tightly-packed rows (stride = width * channels).
549
+ * If linesize matches expected stride, return the buffer directly (zero-copy).
550
+ */
551
+ extractPackedBuffer(frame) {
552
+ const channels = this.outputMode === "gray" ? 1 : 3;
553
+ const expectedStride = frame.width * channels;
554
+ const actualStride = frame.linesize[0] ?? expectedStride;
555
+ const src = frame.data?.[0];
556
+ if (!src) {
557
+ return frame.toBuffer();
558
+ }
559
+ if (actualStride === expectedStride) {
560
+ return Buffer.from(src.buffer, src.byteOffset, expectedStride * frame.height);
561
+ }
562
+ const dst = Buffer.allocUnsafe(expectedStride * frame.height);
563
+ for (let y = 0; y < frame.height; y++) {
564
+ src.copy(dst, y * expectedStride, y * actualStride, y * actualStride + expectedStride);
565
+ }
566
+ return dst;
567
+ }
568
+ /**
569
+ * Encode RGB24 raw buffer as JPEG and emit.
570
+ *
571
+ * Drops the frame (and counts it) when `MAX_JPEG_INFLIGHT` encodes
572
+ * are already pending — prevents unbounded growth of the
573
+ * fire-and-forget promise chain when sharp cannot keep up with the
574
+ * decode rate.
575
+ */
576
+ encodeAndEmitJpeg(rgb, decodeStart) {
577
+ if (!this.sharpFn) return;
578
+ if (this.jpegEncodeInFlight >= NodeAvDecoderSession.MAX_JPEG_INFLIGHT) {
579
+ this.droppedFrames++;
580
+ return;
581
+ }
582
+ this.jpegEncodeInFlight++;
583
+ this.sharpFn(rgb, {
584
+ raw: { width: this.outWidth, height: this.outHeight, channels: 3 }
585
+ }).jpeg({ quality: 80, mozjpeg: false }).toBuffer().then((jpegBuf) => {
586
+ if (this.destroyed) return;
587
+ this.emitRawFrame(jpegBuf, "jpeg", decodeStart);
588
+ }).catch((err) => {
589
+ this.logger.warn("sharp jpeg encode error", { meta: { error: errMsg(err) } });
590
+ }).finally(() => {
591
+ this.jpegEncodeInFlight--;
592
+ });
593
+ }
594
+ emitRawFrame(data, format, decodeStart) {
595
+ const decodeMs = performance.now() - decodeStart;
596
+ this.totalDecodeTimeMs += decodeMs;
597
+ this.outputFrames++;
598
+ this.lastEmitTime = performance.now();
599
+ if (this.outputFrames === 1 || this.outputFrames % 500 === 0) {
600
+ this.logger.info("node-av frame emitted", {
601
+ meta: {
602
+ frameNumber: this.outputFrames,
603
+ width: this.outWidth,
604
+ height: this.outHeight,
605
+ format,
606
+ decodeMs,
607
+ subs: this.frameCallbacks.size
608
+ }
609
+ });
610
+ }
611
+ const decodedFrame = {
612
+ data,
613
+ width: this.outWidth,
614
+ height: this.outHeight,
615
+ format,
616
+ timestamp: Date.now()
617
+ };
618
+ for (const cb of this.frameCallbacks) {
619
+ cb(decodedFrame);
620
+ }
621
+ }
622
+ onFrame(callback) {
623
+ this.frameCallbacks.add(callback);
624
+ return () => {
625
+ this.frameCallbacks.delete(callback);
626
+ };
627
+ }
628
+ updateConfig(update) {
629
+ const prevFormat = this.config.outputFormat;
630
+ this.config = { ...this.config, ...update };
631
+ if (update.maxFps !== void 0) {
632
+ this.minIntervalMs = update.maxFps > 0 ? 1e3 / update.maxFps : 0;
633
+ }
634
+ if (update.outputFormat !== void 0 && update.outputFormat !== prevFormat) {
635
+ const prevMode = this.outputMode;
636
+ this.outputMode = NodeAvDecoderSession.resolveOutputMode(update.outputFormat);
637
+ if (this.outputMode === prevMode) return;
638
+ this.scalerEpoch++;
639
+ if (this.scaler) {
640
+ this.scaler[Symbol.dispose]?.();
641
+ this.scaler = null;
642
+ }
643
+ if (this.dstFrame) {
644
+ this.dstFrame[Symbol.dispose]?.();
645
+ this.dstFrame = null;
646
+ }
647
+ if (this.outputMode === "jpeg" && !this.sharpFn) {
648
+ getSharp().then((fn) => {
649
+ this.sharpFn = fn;
650
+ }).catch(() => {
651
+ });
652
+ }
653
+ this.logger.info("node-av: output format changed — scaler will reinit", {
654
+ meta: { from: prevFormat, to: update.outputFormat, mode: this.outputMode }
655
+ });
656
+ }
657
+ }
658
+ async destroy() {
659
+ if (this.destroyed) return;
660
+ this.destroyed = true;
661
+ this.frameCallbacks.clear();
662
+ this.dstFrame?.[Symbol.dispose]?.();
663
+ this.avFrame?.[Symbol.dispose]?.();
664
+ this.avPacket?.[Symbol.dispose]?.();
665
+ this.scaler?.[Symbol.dispose]?.();
666
+ this.parser?.[Symbol.dispose]?.();
667
+ this.swTransferFrame?.[Symbol.dispose]?.();
668
+ this.codecCtx?.[Symbol.dispose]?.();
669
+ this.hwDevice?.free();
670
+ this.dstFrame = null;
671
+ this.avFrame = null;
672
+ this.avPacket = null;
673
+ this.scaler = null;
674
+ this.parser = null;
675
+ this.codecCtx = null;
676
+ this.swTransferFrame = null;
677
+ this.hwDevice = null;
678
+ }
679
+ getStats() {
680
+ const uptimeSec = Math.max((Date.now() - this.startTime) / 1e3, 1);
681
+ return {
682
+ inputFps: this.inputPackets / uptimeSec,
683
+ outputFps: this.outputFrames / uptimeSec,
684
+ avgDecodeTimeMs: this.outputFrames > 0 ? this.totalDecodeTimeMs / this.outputFrames : 0,
685
+ droppedFrames: this.droppedFrames
686
+ };
687
+ }
688
+ get isPullMode() {
689
+ return false;
690
+ }
691
+ }
692
+ const FRAME_BUFFER_CAPACITY = 32;
693
+ class DecoderNodeAvAddon extends BaseAddon {
694
+ sessions = /* @__PURE__ */ new Map();
695
+ frameBuffers = /* @__PURE__ */ new Map();
696
+ unsubscribers = /* @__PURE__ */ new Map();
697
+ sessionMeta = /* @__PURE__ */ new Map();
698
+ constructor() {
699
+ super(DEFAULT_DECODER_HWACCEL_CONFIG);
700
+ }
701
+ globalSettingsSchema() {
702
+ return this.schema({
703
+ sections: [{
704
+ id: "hwaccel",
705
+ title: "Hardware acceleration",
706
+ tab: "decoder",
707
+ 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.',
708
+ fields: [
709
+ this.field({
710
+ type: "select",
711
+ key: "hwaccel",
712
+ label: "Preferred backend",
713
+ options: [...HWACCEL_OPTIONS],
714
+ default: "auto",
715
+ immediate: true
716
+ }),
717
+ this.field({
718
+ type: "text",
719
+ key: "probedBestHwaccel",
720
+ label: "Probed best",
721
+ description: "Auto-detected best decoder backend on this host. Click the refresh icon to re-run the probe.",
722
+ readonlyField: true,
723
+ default: "",
724
+ actions: [
725
+ { action: "reprobe-hwaccel", icon: "refresh-cw", tooltip: "Re-probe hwaccel" }
726
+ ]
727
+ })
728
+ ]
729
+ }]
730
+ });
731
+ }
732
+ async onInitialize() {
733
+ this.ctx.logger.info("node-av decoder addon initialized");
734
+ if (!this.config.probedBestHwaccel) {
735
+ this.reprobeHwaccel().catch((err) => {
736
+ this.ctx.logger.warn("nodeav: auto-reprobe hwaccel failed", {
737
+ meta: { error: err instanceof Error ? err.message : String(err) }
738
+ });
739
+ });
740
+ }
741
+ return [{ capability: decoderCapability, provider: this }];
742
+ }
743
+ /**
744
+ * Resolve the effective hwaccel backend for a new session. Reads
745
+ * this addon's own `hwaccel` setting first. `'auto'` defers to the
746
+ * session's local resolver (`ctx.kernel.hwaccel`) which probes the
747
+ * host and picks. No more orchestrator round-trip — decoder addon
748
+ * is self-sufficient for this setting as of phase 2d.
749
+ */
750
+ resolveHwAccelPref() {
751
+ return this.config.hwaccel;
752
+ }
753
+ /**
754
+ * Re-run the platform probe on this host and persist the detected
755
+ * backend as `probedBestHwaccel`. The operator's `hwaccel` setting
756
+ * is intentionally left alone — the probe only updates the hint.
757
+ */
758
+ async reprobeHwaccel() {
759
+ const resolver = this.ctx.kernel.hwaccel;
760
+ if (!resolver) {
761
+ this.ctx.logger.warn("reprobeHwaccel: no kernel hwaccel resolver — returning none");
762
+ await this.ctx.settings?.writeAddonStore({ probedBestHwaccel: "none" });
763
+ return { backend: "none" };
764
+ }
765
+ try {
766
+ const res = await resolver.resolve();
767
+ const backend = res.preferred[0] ?? "none";
768
+ await this.ctx.settings?.writeAddonStore({ probedBestHwaccel: backend });
769
+ this.ctx.logger.info("reprobeHwaccel: wrote probedBestHwaccel", {
770
+ meta: { backend, rationale: res.rationale, preferred: res.preferred }
771
+ });
772
+ return { backend };
773
+ } catch (err) {
774
+ this.ctx.logger.warn("reprobeHwaccel failed", {
775
+ meta: { error: err instanceof Error ? err.message : String(err) }
776
+ });
777
+ await this.ctx.settings?.writeAddonStore({ probedBestHwaccel: "none" });
778
+ return { backend: "none" };
779
+ }
780
+ }
781
+ async supportsCodec(input) {
782
+ return ["h264", "h265", "hevc"].includes(input.codec.toLowerCase());
783
+ }
784
+ async getInfo() {
785
+ return {
786
+ id: "decoder-nodeav",
787
+ name: "Decoder (node-av)",
788
+ isPullMode: false,
789
+ priority: 10
790
+ };
791
+ }
792
+ async createSession(config) {
793
+ const sessionId = randomUUID();
794
+ const hwaccel = this.resolveHwAccelPref();
795
+ const session = new NodeAvDecoderSession(config, this.ctx.logger, {
796
+ hwaccel,
797
+ hwaccelResolver: this.ctx.kernel.hwaccel
798
+ });
799
+ const ringBuffer = new RingBuffer(FRAME_BUFFER_CAPACITY);
800
+ const unsub = session.onFrame((frame) => {
801
+ const { format } = frame;
802
+ if (format !== "jpeg" && format !== "rgb" && format !== "bgr" && format !== "yuv420" && format !== "gray") return;
803
+ const arrayBuf = new ArrayBuffer(frame.data.byteLength);
804
+ new Uint8Array(arrayBuf).set(frame.data);
805
+ const capData = new Uint8Array(arrayBuf);
806
+ const capFrame = {
807
+ data: capData,
808
+ width: frame.width,
809
+ height: frame.height,
810
+ format,
811
+ timestamp: frame.timestamp
812
+ };
813
+ ringBuffer.push(capFrame);
814
+ });
815
+ this.sessions.set(sessionId, session);
816
+ this.frameBuffers.set(sessionId, ringBuffer);
817
+ this.unsubscribers.set(sessionId, unsub);
818
+ this.sessionMeta.set(sessionId, {
819
+ codec: config.codec,
820
+ outputFormat: config.outputFormat,
821
+ createdAtMs: Date.now()
822
+ });
823
+ this.ctx.logger.info("node-av: created session", { meta: { sessionId, codec: config.codec, hwaccelPref: hwaccel } });
824
+ return { sessionId, nodeId: this.ctx.kernel.localNodeId ?? "local" };
825
+ }
826
+ async destroySession(input) {
827
+ const { sessionId } = input;
828
+ const session = this.sessions.get(sessionId);
829
+ if (!session) {
830
+ throw new Error(`decoder-nodeav: unknown sessionId ${sessionId}`);
831
+ }
832
+ const unsub = this.unsubscribers.get(sessionId);
833
+ if (unsub) unsub();
834
+ await session.destroy();
835
+ this.sessions.delete(sessionId);
836
+ this.frameBuffers.delete(sessionId);
837
+ this.unsubscribers.delete(sessionId);
838
+ this.sessionMeta.delete(sessionId);
839
+ this.ctx.logger.info("node-av: destroyed session", { meta: { sessionId } });
840
+ }
841
+ async listActiveSessions() {
842
+ const out = [];
843
+ for (const [sessionId, meta] of this.sessionMeta) {
844
+ out.push({ sessionId, codec: meta.codec, outputFormat: meta.outputFormat, createdAtMs: meta.createdAtMs });
845
+ }
846
+ return out;
847
+ }
848
+ async pushPacket(input) {
849
+ const session = this.sessions.get(input.sessionId);
850
+ if (!session) {
851
+ throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
852
+ }
853
+ const rawData = input.packet.data;
854
+ const data = Buffer.isBuffer(rawData) ? rawData : rawData instanceof Uint8Array ? Buffer.from(rawData.buffer, rawData.byteOffset, rawData.byteLength) : Buffer.from(rawData);
855
+ session.pushPacket({ ...input.packet, data });
856
+ }
857
+ async openStream(input) {
858
+ const session = this.sessions.get(input.sessionId);
859
+ if (!session) {
860
+ throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
861
+ }
862
+ if (session.openStream) {
863
+ await session.openStream(input.url);
864
+ }
865
+ }
866
+ async pullFrames(input) {
867
+ const ringBuffer = this.frameBuffers.get(input.sessionId);
868
+ if (!ringBuffer) {
869
+ throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
870
+ }
871
+ return ringBuffer.drain(input.maxCount);
872
+ }
873
+ async updateConfig(input) {
874
+ const session = this.sessions.get(input.sessionId);
875
+ if (!session) {
876
+ throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
877
+ }
878
+ session.updateConfig(input.config);
879
+ }
880
+ async getStats(input) {
881
+ const session = this.sessions.get(input.sessionId);
882
+ if (!session) {
883
+ throw new Error(`decoder-nodeav: unknown sessionId ${input.sessionId}`);
884
+ }
885
+ return session.getStats();
886
+ }
887
+ async onShutdown() {
888
+ this.ctx.logger.info("node-av decoder addon shutdown — destroying all sessions");
889
+ const destroyPromises = [];
890
+ for (const [sessionId, session] of this.sessions) {
891
+ const unsub = this.unsubscribers.get(sessionId);
892
+ if (unsub) unsub();
893
+ destroyPromises.push(session.destroy());
894
+ }
895
+ await Promise.all(destroyPromises);
896
+ this.sessions.clear();
897
+ this.frameBuffers.clear();
898
+ this.unsubscribers.clear();
899
+ this.sessionMeta.clear();
900
+ }
901
+ }
902
+ export {
903
+ DecoderNodeAvAddon,
904
+ NodeAvDecoderSession,
905
+ DecoderNodeAvAddon as default
906
+ };
907
+ //# sourceMappingURL=index.mjs.map