@camstack/addon-pipeline 1.1.34 → 1.1.35

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