@camstack/addon-pipeline 1.1.17 → 1.1.19

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 (31) hide show
  1. package/dist/audio-analyzer/index.js +1 -1
  2. package/dist/audio-analyzer/index.mjs +1 -1
  3. package/dist/audio-codec-nodeav/index.js +1 -1
  4. package/dist/audio-codec-nodeav/index.mjs +1 -1
  5. package/dist/decoder-ffmpeg/index.js +1179 -0
  6. package/dist/decoder-ffmpeg/index.mjs +1162 -0
  7. package/dist/detection-pipeline/index.js +1 -1
  8. package/dist/detection-pipeline/index.mjs +1 -1
  9. package/dist/{dist-CBcVKDyT.mjs → dist-7Yx2dmuV.mjs} +1 -0
  10. package/dist/{dist-CRzS7bK1.js → dist-BgoBMCez.js} +1 -0
  11. package/dist/ffmpeg-args-common-CASoNt42.js +68 -0
  12. package/dist/ffmpeg-args-common-c3p-nWtU.mjs +51 -0
  13. package/dist/motion-wasm/index.js +1 -1
  14. package/dist/motion-wasm/index.mjs +1 -1
  15. package/dist/pipeline-runner/index.js +1 -1
  16. package/dist/pipeline-runner/index.mjs +1 -1
  17. package/dist/recorder/index.js +1 -1
  18. package/dist/recorder/index.mjs +1 -1
  19. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-Cu2RfLyo.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-w2pP0MYO.mjs} +1 -1
  20. package/dist/stream-broker/{hostInit-D2VENktw.mjs → hostInit-BUEbBinp.mjs} +1 -1
  21. package/dist/stream-broker/index.js +68 -73
  22. package/dist/stream-broker/index.mjs +58 -63
  23. package/dist/stream-broker/remoteEntry.js +1 -1
  24. package/embed-dist/assets/{MaskShapeCanvas-DI4BY7W2-ohKbGSOY.js → MaskShapeCanvas-DI4BY7W2-CYmHXacX.js} +1 -1
  25. package/embed-dist/assets/{MotionZonesSettings-NcxxQN8r-m6kOetLh.js → MotionZonesSettings-NcxxQN8r-B-BkPQvX.js} +1 -1
  26. package/embed-dist/assets/{PrivacyMaskSettings-APgPLF7p-BNbgX3su.js → PrivacyMaskSettings-APgPLF7p-DC3Jw85p.js} +1 -1
  27. package/embed-dist/assets/{index-CqqHOFtM.js → index-B0IQgci0.js} +4 -4
  28. package/embed-dist/index.html +1 -1
  29. package/package.json +8 -8
  30. package/dist/decoder-nodeav/index.js +0 -1393
  31. package/dist/decoder-nodeav/index.mjs +0 -1385
@@ -0,0 +1,1162 @@
1
+ import { B as BaseAddon, b as decoderCapability, f as RingBuffer, s as DEFAULT_DECODER_HWACCEL_CONFIG, u as HWACCEL_OPTIONS, z as errMsg } from "../dist-7Yx2dmuV.mjs";
2
+ import { n as logBannerArgs, r as FrameDropper } from "../ffmpeg-args-common-c3p-nWtU.mjs";
3
+ import { FrameRingReaderCache, FrameRingWriter, MIN_RING_SLOTS, computeSegmentSize, computeSlotByteLength, createSegment, deriveSlotCount } from "@camstack/shm-ring";
4
+ import { randomUUID } from "node:crypto";
5
+ import { spawn } from "node:child_process";
6
+ //#region src/decoder-nodeav/frame-ring-sink.ts
7
+ /**
8
+ * `DecoderFrameRingSink` — the decoder's shared-memory write side (Phase 5 / D9).
9
+ *
10
+ * When a decoder session is configured with `frameSink: 'shm'`, the decoder
11
+ * **owns** the shared-memory ring segment for that stream: it creates the
12
+ * segment on the first decoded frame (when the output geometry is known),
13
+ * writes every subsequent decoded frame into the ring via a `FrameRingWriter`,
14
+ * and closes + unlinks the segment when the session is destroyed.
15
+ *
16
+ * What leaves the decoder is no longer the pixel `Buffer` — it is a tiny,
17
+ * serialisable `FrameHandle` (`FrameRingWriter.writeFrame`'s return value).
18
+ * Same-host consumers (motion, detection, the WebRTC encoder) open the same
19
+ * segment with a `FrameRingReader` and read the pixels zero-copy.
20
+ *
21
+ * ## Lazy segment creation
22
+ *
23
+ * The segment cannot be sized until the first frame: `slotByteLength` is
24
+ * `width × height × bytesPerPixel`, and the output dimensions are only known
25
+ * once the scaler has produced its first `dstFrame`. So `writeFrame` is a
26
+ * no-op-until-armed: the first call sizes + creates the segment, every later
27
+ * call writes into it.
28
+ *
29
+ * ## Resolution-change decision
30
+ *
31
+ * A live camera stream can change resolution mid-stream (the decoder's scaler
32
+ * is rebuilt on a config toggle, or the source renegotiates). The slot is
33
+ * sized for the **first** frame's geometry. A later frame that no longer fits
34
+ * the slot triggers a **segment re-create**: the old segment is closed +
35
+ * unlinked and a fresh, larger segment is created under a new generation-tagged
36
+ * name. This is simpler and leak-free versus over-allocating slots for a
37
+ * worst-case 4K frame on every stream; resolution changes on a live camera are
38
+ * rare, and a brief gap while consumers re-open the segment is acceptable
39
+ * (latest-wins — a missed frame is correct behaviour).
40
+ */
41
+ /**
42
+ * Per-ring shared-memory budget (MB) — the slot count is derived per-resolution
43
+ * from this budget via {@link deriveSlotCount}, so a 360p stream gets many
44
+ * slots and a 4K stream a few, both inside the same memory footprint.
45
+ *
46
+ * Read ONCE at module load from `CAMSTACK_SHM_RING_BUDGET_MB`; a non-finite or
47
+ * non-positive value falls back to the 16 MB default.
48
+ *
49
+ * The default is deliberately small (16 MB) so many concurrent per-camera rings
50
+ * fit inside a bounded `/dev/shm`. The decoder output is capped at 640px wide, so
51
+ * a slot is ≤ ~920 KB and 16 MB still yields ~17–70 latest-wins slots. A ring
52
+ * segment larger than the container's `/dev/shm` tmpfs backing (Docker default is
53
+ * only 64 MB) faults an **uncatchable SIGBUS** on write past `st_size` — the old
54
+ * 128 MB default overflowed a 64 MB `/dev/shm` and crashed the decoder on 8MP
55
+ * streams. Pair this with a `--shm-size` that scales with concurrent-decode load.
56
+ */
57
+ var RING_BUDGET_MB = (() => {
58
+ const raw = Number(process.env["CAMSTACK_SHM_RING_BUDGET_MB"]);
59
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 16;
60
+ })();
61
+ /** {@link RING_BUDGET_MB} in bytes — the budget passed to `deriveSlotCount`. */
62
+ var RING_BUDGET_BYTES = RING_BUDGET_MB * 1024 * 1024;
63
+ /** A unique, stable shared-memory segment name for a decoder stream.
64
+ *
65
+ * macOS POSIX shm names are capped at ~31 characters (`PSHMNAMLEN`). A
66
+ * `camstack.frames.<deviceId>.<streamId>` scheme overflows that for realistic
67
+ * ids, so the sink uses a short, collision-resistant scheme instead:
68
+ * `csf.<base36 hash>.<gen>`. The hash folds the device id, the session tag
69
+ * and a per-process random salt; the generation suffix makes a re-created
70
+ * segment (resolution change) a distinct name so a stale consumer mapping is
71
+ * never silently reused.
72
+ */
73
+ function makeSegmentName(seed, generation) {
74
+ let hash = 5381;
75
+ for (let i = 0; i < seed.length; i += 1) hash = (hash << 5) + hash + seed.charCodeAt(i) | 0;
76
+ return `csf.${(hash >>> 0).toString(36)}.${generation}`;
77
+ }
78
+ /**
79
+ * The decoder-side owner of one stream's shared-memory frame ring.
80
+ *
81
+ * Not constructed until a session actually uses the shm sink; the segment
82
+ * itself is created lazily on the first `writeFrame`.
83
+ */
84
+ var DecoderFrameRingSink = class {
85
+ seed;
86
+ logger;
87
+ nodeId;
88
+ segment = null;
89
+ writer = null;
90
+ segmentName = null;
91
+ slotByteLength = 0;
92
+ generation = 0;
93
+ destroyed = false;
94
+ /** Frames committed into the ring across this sink's lifetime (all generations). */
95
+ framesWritten = 0;
96
+ constructor(options) {
97
+ const salt = Math.random().toString(36).slice(2, 8);
98
+ this.seed = `${options.seed}.${salt}`;
99
+ this.logger = options.logger;
100
+ this.nodeId = options.nodeId;
101
+ }
102
+ /** Whether a segment has been created (i.e. at least one frame written). */
103
+ get isArmed() {
104
+ return this.writer !== null;
105
+ }
106
+ /** The current segment name, or `null` before the first frame. */
107
+ get currentSegmentName() {
108
+ return this.segmentName;
109
+ }
110
+ /**
111
+ * Write one decoded frame into the ring and return its `FrameHandle`.
112
+ *
113
+ * On the first call (or after a geometry change that overflows the current
114
+ * slot) the segment is created / re-created sized for this frame. Returns
115
+ * `null` only when the sink has been destroyed.
116
+ *
117
+ * This is the copy-in convenience form (it copies `pixels` into the slot).
118
+ * The decoder's hot path uses the zero-copy {@link beginFrame} /
119
+ * {@link commitFrame} scatter-write pair instead — the scaler produces its
120
+ * packed output directly into the slot, eliminating the write-side memcpy.
121
+ */
122
+ writeFrame(pixels, meta) {
123
+ if (this.destroyed) return null;
124
+ if (this.writer === null || computeSlotByteLength(meta.width, meta.height, meta.format) > this.slotByteLength) this.recreateSegment(computeSlotByteLength(meta.width, meta.height, meta.format));
125
+ const writer = this.writer;
126
+ if (writer === null) return null;
127
+ const handle = writer.writeFrame(pixels, meta);
128
+ this.framesWritten += 1;
129
+ return handle;
130
+ }
131
+ /**
132
+ * Reserve a ring slot for a frame of the given geometry — the **zero-copy**
133
+ * scatter-write entry point (Phase 5 / D9 Task 7c).
134
+ *
135
+ * The segment is created / re-created here if this is the first frame or the
136
+ * geometry overflows the current slot capacity, so the slot is correctly
137
+ * sized before the caller fills it. The returned `buffer` is a writable view
138
+ * **directly over the mapped segment** — the node-av scaler scatters its
139
+ * packed output straight into it, with no intermediate copy. The caller MUST
140
+ * call {@link commitFrame} with the returned `slot` once the slot is filled.
141
+ *
142
+ * Returns `null` when the sink is destroyed or the segment cannot be created.
143
+ */
144
+ beginFrame(width, height, format) {
145
+ if (this.destroyed) return null;
146
+ const requiredSlotBytes = computeSlotByteLength(width, height, format);
147
+ if (this.writer === null || requiredSlotBytes > this.slotByteLength) this.recreateSegment(requiredSlotBytes);
148
+ const writer = this.writer;
149
+ if (writer === null) return null;
150
+ const { slot, buffer } = writer.beginFrame();
151
+ return {
152
+ slot,
153
+ buffer
154
+ };
155
+ }
156
+ /**
157
+ * Publish the frame whose slot was reserved by {@link beginFrame} and filled
158
+ * in place by the caller. `slot` MUST be the value from the matching
159
+ * `beginFrame`. Returns the published `FrameHandle`, or `null` if the sink
160
+ * was destroyed (or the segment lost) between begin and commit.
161
+ */
162
+ commitFrame(slot, meta) {
163
+ if (this.destroyed) return null;
164
+ const writer = this.writer;
165
+ if (writer === null) return null;
166
+ const handle = writer.commitFrame(slot, meta);
167
+ this.framesWritten += 1;
168
+ return handle;
169
+ }
170
+ /**
171
+ * Current shm ring usage — `null` until the first frame arms the segment.
172
+ * Surfaced through `decoder.getShmStats` so a downstream consumer can
173
+ * observe ring pressure (slot depth, byte budget, frames written).
174
+ */
175
+ getShmStats() {
176
+ if (this.writer === null) return null;
177
+ return {
178
+ slotCount: this.writer.slotCount,
179
+ slotByteLength: this.slotByteLength,
180
+ segmentBytes: computeSegmentSize(this.writer.slotCount, this.slotByteLength),
181
+ framesWritten: this.framesWritten
182
+ };
183
+ }
184
+ /**
185
+ * Abandon a slot reserved by {@link beginFrame} **without publishing it** —
186
+ * the degenerate-path counterpart of {@link commitFrame}.
187
+ *
188
+ * A caller that reserved a slot but then could not produce valid pixels (no
189
+ * decoded source planes, or the scaler threw) MUST call this instead of
190
+ * `commitFrame`: it closes the open seqlock without advancing `writeIndex`,
191
+ * so no reader ever sees the slot's uninitialised bytes as a real frame, and
192
+ * no `FrameHandle` is handed downstream. `slot` MUST be the value from the
193
+ * matching `beginFrame`. A no-op if the sink was destroyed (or the segment
194
+ * lost) between begin and abort.
195
+ */
196
+ abortFrame(slot) {
197
+ if (this.destroyed) return;
198
+ const writer = this.writer;
199
+ if (writer === null) return;
200
+ writer.abortFrame(slot);
201
+ }
202
+ /** Close + unlink the segment. Idempotent. */
203
+ destroy() {
204
+ if (this.destroyed) return;
205
+ this.destroyed = true;
206
+ this.releaseSegment();
207
+ }
208
+ /**
209
+ * Create a fresh segment sized for at least `slotByteLength` bytes per slot,
210
+ * replacing any prior one. A re-create bumps the generation so the new
211
+ * segment has a distinct name — a consumer holding the old mapping is never
212
+ * silently handed a resized segment.
213
+ */
214
+ recreateSegment(slotByteLength) {
215
+ this.releaseSegment();
216
+ this.generation += 1;
217
+ const name = makeSegmentName(this.seed, this.generation);
218
+ const slotCount = deriveSlotCount(RING_BUDGET_BYTES, slotByteLength);
219
+ if (slotCount === MIN_RING_SLOTS && MIN_RING_SLOTS * slotByteLength > RING_BUDGET_BYTES) this.logger.warn("decoder shm ring: budget too small for resolution — using MIN slots", { meta: {
220
+ slotByteLength,
221
+ budgetMb: RING_BUDGET_MB
222
+ } });
223
+ const totalBytes = computeSegmentSize(slotCount, slotByteLength);
224
+ try {
225
+ const segment = createSegment(name, totalBytes);
226
+ this.segment = segment;
227
+ this.segmentName = name;
228
+ this.slotByteLength = slotByteLength;
229
+ this.writer = new FrameRingWriter(segment.buffer, name, slotCount, slotByteLength, this.nodeId);
230
+ this.logger.info("decoder shm ring: segment created", { meta: {
231
+ segment: name,
232
+ slotCount,
233
+ slotByteLength,
234
+ totalBytes,
235
+ generation: this.generation
236
+ } });
237
+ } catch (err) {
238
+ this.segment = null;
239
+ this.writer = null;
240
+ this.segmentName = null;
241
+ this.slotByteLength = 0;
242
+ this.logger.error("decoder shm ring: segment create failed", { meta: {
243
+ segment: name,
244
+ slotByteLength,
245
+ error: err instanceof Error ? err.message : String(err)
246
+ } });
247
+ }
248
+ }
249
+ /** Unmap + unlink the current segment, if any. */
250
+ releaseSegment() {
251
+ const segment = this.segment;
252
+ if (segment === null) return;
253
+ this.segment = null;
254
+ this.writer = null;
255
+ const name = this.segmentName;
256
+ this.segmentName = null;
257
+ try {
258
+ segment.close();
259
+ segment.unlink();
260
+ this.logger.info("decoder shm ring: segment released", { meta: { segment: name } });
261
+ } catch (err) {
262
+ this.logger.warn("decoder shm ring: segment release failed", { meta: {
263
+ segment: name,
264
+ error: err instanceof Error ? err.message : String(err)
265
+ } });
266
+ }
267
+ }
268
+ };
269
+ //#endregion
270
+ //#region src/decoder-ffmpeg/ffmpeg-args.ts
271
+ /**
272
+ * Pure, side-effect-free ffmpeg argument construction for the
273
+ * `decoder-ffmpeg` addon.
274
+ *
275
+ * The addon decodes video in an **ffmpeg subprocess** (unlike `decoder-nodeav`
276
+ * which decodes in-process via node-av's native bindings). On the Intel hub,
277
+ * node-av's VA-API decode path SIGBUSes (uncatchable) on 8MP h264 and takes the
278
+ * whole decoder runner down; ffmpeg-as-subprocess decodes the same hardware
279
+ * cleanly because a crash is isolated to the child process.
280
+ *
281
+ * These helpers are extracted from the session so the argument shape is
282
+ * unit-testable without spawning a real ffmpeg binary.
283
+ *
284
+ * Validated working command on the Intel hub (renderD128, 8MP h264, ~50fps,
285
+ * exit 0):
286
+ *
287
+ * ffmpeg -hwaccel vaapi -hwaccel_device /dev/dri/renderD128 \
288
+ * -hwaccel_output_format vaapi -f h264 -i <in> \
289
+ * -vf hwdownload,format=nv12,scale=640:360,format=gray \
290
+ * -f rawvideo -y /dev/null
291
+ */
292
+ /** Default DRM render node used for the VA-API / QSV hardware decode path. */
293
+ var DEFAULT_VAAPI_RENDER_DEVICE = "/dev/dri/renderD128";
294
+ /** Whether a resolved hwaccel value means "decode in software" (no `-hwaccel`). */
295
+ function isSoftwareHwAccel(hwaccel) {
296
+ return hwaccel === null || hwaccel === "" || hwaccel === "none";
297
+ }
298
+ /** Backends whose decoded frames stay on the GPU and need an explicit
299
+ * `-hwaccel_output_format <m>` + `hwdownload,format=nv12` chain. */
300
+ function needsHwDownload(hwaccel) {
301
+ return hwaccel === "vaapi" || hwaccel === "qsv";
302
+ }
303
+ /** Map a cap codec string to the ffmpeg `-f` input demuxer/format. */
304
+ function codecToInputFormat(codec) {
305
+ switch (codec.toLowerCase()) {
306
+ case "h265":
307
+ case "hevc": return "hevc";
308
+ default: return "h264";
309
+ }
310
+ }
311
+ /** Map the cap-level output format to a raw ffmpeg pixel format. */
312
+ function rawPixelForFormat(outputFormat) {
313
+ return outputFormat === "gray" ? "gray" : "rgb24";
314
+ }
315
+ /** Packed bytes-per-pixel for a raw output format (rgb24 = 3, gray = 1). */
316
+ function channelsForPixel(pixel) {
317
+ return pixel === "gray" ? 1 : 3;
318
+ }
319
+ /**
320
+ * The maximum output width for a given `scale` divisor — matches the node-av
321
+ * scaler's `maxW = floor(640 / scale)` rule so both decoders produce
322
+ * comparably-sized frames for the motion / detection pipeline.
323
+ */
324
+ function maxDecodeWidth(scale) {
325
+ return Math.max(2, Math.floor(640 / (scale > 1 ? scale : 1)));
326
+ }
327
+ /**
328
+ * Compute exact output geometry from a known source resolution — the node-av
329
+ * rule (`outWidth = min(srcW, floor(640/scale))`, `outHeight =
330
+ * round(outWidth*srcH/srcW)`). Provided for callers that DO know the source
331
+ * dimensions; the live broker path leaves them to ffmpeg (`-2` height).
332
+ */
333
+ function computeOutputGeometry(srcWidth, srcHeight, scale) {
334
+ const width = Math.min(srcWidth, maxDecodeWidth(scale));
335
+ return {
336
+ width,
337
+ height: Math.round(width * srcHeight / srcWidth)
338
+ };
339
+ }
340
+ /** Build the `-vf` filtergraph string for the requested hwaccel + pixel format. */
341
+ function buildVideoFilter(hwaccel, pixel, outWidth, outHeight, maxW) {
342
+ const scaleAndFormat = `scale=${outWidth !== void 0 && outWidth > 0 && outHeight !== void 0 && outHeight > 0 ? `${outWidth}:${outHeight}` : `min(iw\\,${maxW}):-2`},format=${pixel}`;
343
+ return needsHwDownload(hwaccel) ? `hwdownload,format=nv12,${scaleAndFormat}` : scaleAndFormat;
344
+ }
345
+ /**
346
+ * Build the full ffmpeg argv for a decode session. PURE — no spawn, no env
347
+ * access — so the argument shape is asserted in unit tests.
348
+ *
349
+ * Notes:
350
+ * - `-loglevel info -nostats`: the session parses the muxer's `Output #0`
351
+ * stream line from stderr to learn the exact output W×H (the broker does not
352
+ * pass source geometry for the shm path). `-nostats` suppresses the periodic
353
+ * `frame= …` counter while keeping the one-shot Output block.
354
+ * - The input is `pipe:0` (Annex-B packets written to stdin); the output is raw
355
+ * video on `pipe:1`.
356
+ */
357
+ function buildFfmpegDecodeArgs(config, options) {
358
+ const inputFormat = codecToInputFormat(config.codec);
359
+ const pixel = rawPixelForFormat(config.outputFormat);
360
+ const maxW = maxDecodeWidth(config.scale);
361
+ const vf = buildVideoFilter(options.hwaccel, pixel, options.outWidth, options.outHeight, maxW);
362
+ const { hwaccel } = options;
363
+ let hwaccelArgs;
364
+ if (isSoftwareHwAccel(hwaccel) || hwaccel === null) hwaccelArgs = [];
365
+ else if (needsHwDownload(hwaccel)) hwaccelArgs = [
366
+ "-hwaccel",
367
+ hwaccel,
368
+ "-hwaccel_device",
369
+ options.renderDevice ?? "/dev/dri/renderD128",
370
+ "-hwaccel_output_format",
371
+ hwaccel
372
+ ];
373
+ else hwaccelArgs = ["-hwaccel", hwaccel];
374
+ return [
375
+ ...logBannerArgs("info"),
376
+ "-nostats",
377
+ "-fflags",
378
+ "+nobuffer+flush_packets",
379
+ "-flags",
380
+ "low_delay",
381
+ "-probesize",
382
+ "1M",
383
+ "-analyzeduration",
384
+ "0",
385
+ ...hwaccelArgs,
386
+ "-f",
387
+ inputFormat,
388
+ "-i",
389
+ "pipe:0",
390
+ "-vf",
391
+ vf,
392
+ "-f",
393
+ "rawvideo",
394
+ "-pix_fmt",
395
+ pixel,
396
+ "pipe:1"
397
+ ];
398
+ }
399
+ /**
400
+ * Parse the exact output geometry from ffmpeg's stderr. The muxer prints an
401
+ * `Output #0, rawvideo …` block whose `Stream #0:0: Video: rawvideo …, <fmt>,
402
+ * WIDTHxHEIGHT …` line carries the scaled dimensions. Gating on the `Output #`
403
+ * marker avoids picking up the INPUT stream's (source) resolution, which is
404
+ * printed earlier.
405
+ *
406
+ * Returns `null` until the Output block with a `WxH` token has been seen.
407
+ */
408
+ function parseFfmpegOutputDims(stderr) {
409
+ const outputIdx = stderr.indexOf("Output #");
410
+ if (outputIdx < 0) return null;
411
+ const match = stderr.slice(outputIdx).match(/(\d{2,5})x(\d{2,5})/);
412
+ if (!match) return null;
413
+ const width = Number(match[1]);
414
+ const height = Number(match[2]);
415
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) return null;
416
+ return {
417
+ width,
418
+ height
419
+ };
420
+ }
421
+ /**
422
+ * Pick the first kernel-preferred `-hwaccel` method the configured ffmpeg build
423
+ * actually supports, or `null` (software) when it supports none. Mirrors the
424
+ * broker's `pickDecodeHwAccel` (`ffmpeg-invocation.ts`) so the decoder gates
425
+ * decode-hwaccel against the same probed evidence:
426
+ * - empty `preferred` → `null` (software);
427
+ * - empty `supportedMethods` (probe miss) → keep the top preference and let the
428
+ * session's per-child software fallback cover a genuine failure;
429
+ * - otherwise the first preference the build supports, or `null`.
430
+ */
431
+ function pickDecodeHwAccel(preferred, supportedMethods) {
432
+ if (preferred.length === 0) return null;
433
+ if (supportedMethods.length === 0) return preferred[0] ?? null;
434
+ const supported = new Set(supportedMethods.map((m) => m.toLowerCase()));
435
+ return preferred.find((name) => supported.has(name.toLowerCase())) ?? null;
436
+ }
437
+ /**
438
+ * Canonical decode-hwaccel preference order for the ffmpeg-subprocess decoder.
439
+ *
440
+ * `vaapi` is ranked ABOVE `qsv` deliberately: on the Intel hub the `qsv` decode
441
+ * child exits early (`code=171`, no frames) while the `vaapi` path decodes 8MP
442
+ * h264 cleanly at ~50fps. The kernel probe (`resolveHwAccel`) tends to surface
443
+ * `qsv` first on Intel, so we re-rank its result through this table before
444
+ * building the attempt chain. `videotoolbox` leads for macOS; `cuda` / `nvdec`
445
+ * trail for NVIDIA. A method not listed here keeps its incoming relative order,
446
+ * placed AFTER every ranked one.
447
+ */
448
+ var DECODE_HWACCEL_RANK = [
449
+ "videotoolbox",
450
+ "vaapi",
451
+ "qsv",
452
+ "cuda",
453
+ "nvdec",
454
+ "d3d11va",
455
+ "dxva2",
456
+ "amf",
457
+ "vdpau",
458
+ "drm"
459
+ ];
460
+ /** Rank index for {@link DECODE_HWACCEL_RANK} — unranked methods sort last. */
461
+ function decodeHwAccelRankIndex(method) {
462
+ const idx = DECODE_HWACCEL_RANK.indexOf(method.toLowerCase());
463
+ return idx < 0 ? DECODE_HWACCEL_RANK.length : idx;
464
+ }
465
+ /**
466
+ * Build the ORDERED list of hardware `-hwaccel` methods to attempt for an
467
+ * `'auto'` decode session, best-first. The session walks this chain on an
468
+ * early-exit-with-no-frames and only falls to software once it is exhausted.
469
+ *
470
+ * Strategy:
471
+ * - Seed candidates from the kernel-preferred order UNION the canonical rank
472
+ * UNION the build's supported list, so a method the kernel omitted but the
473
+ * build supports (the Intel `vaapi` case — kernel surfaces only `qsv`) is
474
+ * still attempted.
475
+ * - When the build's supported-method list is known (non-empty), keep only
476
+ * methods it actually offers; on a probe miss (empty) keep just the kernel
477
+ * preferences (avoid blindly spawning every backend).
478
+ * - Re-rank the survivors by {@link DECODE_HWACCEL_RANK} so `vaapi` precedes
479
+ * `qsv`. A supported method not in the rank table keeps its position AFTER
480
+ * every ranked one (stable sort). Returns lowercased method names; empty ⇒
481
+ * pure software.
482
+ */
483
+ function rankDecodeHwAccels(preferred, supportedMethods) {
484
+ const supported = new Set(supportedMethods.map((m) => m.toLowerCase()));
485
+ const hasSupportList = supported.size > 0;
486
+ const pool = hasSupportList ? [
487
+ ...preferred,
488
+ ...DECODE_HWACCEL_RANK,
489
+ ...supportedMethods
490
+ ] : [...preferred];
491
+ const seen = /* @__PURE__ */ new Set();
492
+ const candidates = [];
493
+ for (const raw of pool) {
494
+ const method = raw.toLowerCase();
495
+ if (seen.has(method)) continue;
496
+ seen.add(method);
497
+ if (hasSupportList && !supported.has(method)) continue;
498
+ candidates.push(method);
499
+ }
500
+ return candidates.sort((a, b) => decodeHwAccelRankIndex(a) - decodeHwAccelRankIndex(b));
501
+ }
502
+ //#endregion
503
+ //#region src/decoder-ffmpeg/ffmpeg-decoder-session.ts
504
+ /**
505
+ * FfmpegDecoderSession — an `IDecoderSession` that decodes video in an **ffmpeg
506
+ * subprocess** and feeds the shared-memory frame ring (Phase 5 / D9), the same
507
+ * ring `decoder-nodeav` writes into.
508
+ *
509
+ * Why a subprocess: on the Intel hub, node-av's in-process VA-API decode path
510
+ * SIGBUSes (uncatchable) on 8MP h264 and kills the whole decoder runner. ffmpeg
511
+ * decodes the identical hardware cleanly because it runs out-of-process — a
512
+ * crashing child just stops producing frames; the addon survives and the
513
+ * frame-plane rotates/retries.
514
+ *
515
+ * Data flow per session:
516
+ * Annex-B packets → ffmpeg stdin (pipe:0)
517
+ * ffmpeg → `-vf [hwdownload,format=nv12,]scale=…,format=<rgb24|gray>`
518
+ * raw video → ffmpeg stdout (pipe:1) → fixed-size frame slices
519
+ * each slice → `DecoderFrameRingSink.writeFrame` → `FrameHandle` (shm mode)
520
+ * or `DecodedFrame` via `onFrame` (callback mode)
521
+ *
522
+ * Output geometry: the broker does not pass source width/height for the shm
523
+ * path, so ffmpeg picks the height (`scale=min(iw\,maxW):-2`) and the session
524
+ * learns the exact output W×H by parsing the muxer's `Output #0` stderr block
525
+ * ({@link parseFfmpegOutputDims}). Until dims are known, stdout is buffered.
526
+ */
527
+ var noopLogger = {
528
+ debug() {},
529
+ info() {},
530
+ warn() {},
531
+ error() {},
532
+ child() {
533
+ return noopLogger;
534
+ },
535
+ withTags() {
536
+ return noopLogger;
537
+ }
538
+ };
539
+ /** A hardware child that dies faster than this (with no frames) advances the
540
+ * session to the NEXT decode path (next hwaccel, else software) — a genuine
541
+ * hwaccel init failure (missing render node, unsupported codec on GPU, the
542
+ * Intel `qsv` `code=171`) surfaces this early. */
543
+ var HWACCEL_FALLBACK_WINDOW_MS = 4e3;
544
+ var FfmpegDecoderSession = class {
545
+ config;
546
+ logger;
547
+ frameSink;
548
+ nodeId;
549
+ renderDevice;
550
+ ffmpegPath;
551
+ /**
552
+ * Ordered hardware decode paths to attempt, best-first. Empty ⇒ software
553
+ * only. The session walks it via {@link hwaccelIndex}; an index past the end
554
+ * means software (`null`).
555
+ */
556
+ hwaccelChain;
557
+ hwaccelIndex = 0;
558
+ hwaccel;
559
+ process = null;
560
+ spawnedAtMs = 0;
561
+ outputBuffer = Buffer.alloc(0);
562
+ stderrAccum = "";
563
+ destroyed = false;
564
+ pixel;
565
+ channels;
566
+ /** The cap-facing raw format label (`'rgb'` / `'gray'`) stamped into frames. */
567
+ frameFormat;
568
+ outWidth = 0;
569
+ outHeight = 0;
570
+ frameSize = 0;
571
+ frameRingSink = null;
572
+ frameCallbacks = /* @__PURE__ */ new Set();
573
+ handleCallbacks = /* @__PURE__ */ new Set();
574
+ frameDropper;
575
+ inputPackets = 0;
576
+ outputFrames = 0;
577
+ droppedFrames = 0;
578
+ startTime = Date.now();
579
+ constructor(config, logger = noopLogger, options) {
580
+ this.config = { ...config };
581
+ const sessionTags = {};
582
+ if (typeof config.deviceId === "number") sessionTags["deviceId"] = config.deviceId;
583
+ if (typeof config.tag === "string" && config.tag.length > 0) sessionTags["tag"] = config.tag;
584
+ this.logger = Object.keys(sessionTags).length > 0 ? logger.withTags(sessionTags) : logger;
585
+ this.frameSink = options?.frameSink ?? "callback";
586
+ this.nodeId = options?.nodeId ?? "local";
587
+ this.renderDevice = options?.renderDevice;
588
+ this.ffmpegPath = options?.ffmpegPath ?? "ffmpeg";
589
+ const seededChain = options?.hwaccelChain ?? (options?.hwaccel != null && !isSoftwareHwAccel(options.hwaccel) ? [options.hwaccel] : []);
590
+ this.hwaccelChain = seededChain.filter((m) => !isSoftwareHwAccel(m));
591
+ this.hwaccel = this.currentHwAccel();
592
+ this.pixel = rawPixelForFormat(config.outputFormat);
593
+ this.channels = channelsForPixel(this.pixel);
594
+ this.frameFormat = this.pixel === "gray" ? "gray" : "rgb";
595
+ this.frameDropper = new FrameDropper(config.maxFps);
596
+ this.spawnFfmpeg();
597
+ }
598
+ /** Exposed so the owning addon can surface ring stats via `getShmStats`. */
599
+ get frameRingSinkOrNull() {
600
+ return this.frameRingSink;
601
+ }
602
+ get isPullMode() {
603
+ return false;
604
+ }
605
+ ensureFrameRingSink() {
606
+ if (this.frameRingSink === null) {
607
+ const seedParts = [];
608
+ if (typeof this.config.deviceId === "number") seedParts.push(String(this.config.deviceId));
609
+ if (typeof this.config.tag === "string" && this.config.tag.length > 0) seedParts.push(this.config.tag);
610
+ const seed = seedParts.length > 0 ? seedParts.join(":") : "anon";
611
+ this.frameRingSink = new DecoderFrameRingSink({
612
+ seed,
613
+ logger: this.logger,
614
+ nodeId: this.nodeId
615
+ });
616
+ }
617
+ return this.frameRingSink;
618
+ }
619
+ spawnFfmpeg() {
620
+ if (this.destroyed) return;
621
+ this.killFfmpeg();
622
+ this.outputBuffer = Buffer.alloc(0);
623
+ this.stderrAccum = "";
624
+ this.outWidth = 0;
625
+ this.outHeight = 0;
626
+ this.frameSize = 0;
627
+ const args = buildFfmpegDecodeArgs({
628
+ codec: this.config.codec,
629
+ scale: this.config.scale,
630
+ outputFormat: this.config.outputFormat
631
+ }, {
632
+ hwaccel: this.hwaccel,
633
+ renderDevice: this.renderDevice
634
+ });
635
+ let child;
636
+ try {
637
+ child = spawn(this.ffmpegPath, args);
638
+ } catch (err) {
639
+ this.logger.error("ffmpeg decoder: spawn threw", { meta: { error: errMsg(err) } });
640
+ return;
641
+ }
642
+ this.process = child;
643
+ this.spawnedAtMs = Date.now();
644
+ child.stdin?.on("error", () => {});
645
+ child.stdout?.on("data", (chunk) => this.handleStdout(chunk));
646
+ child.stderr?.on("data", (data) => this.handleStderr(data));
647
+ child.on("error", (err) => {
648
+ this.logger.error("ffmpeg decoder: process error", { meta: { error: err.message } });
649
+ });
650
+ child.on("exit", (code, signal) => this.handleExit(code, signal));
651
+ this.logger.info("ffmpeg decoder: spawned", { meta: {
652
+ hwaccel: this.hwaccel,
653
+ codec: this.config.codec,
654
+ format: this.frameFormat,
655
+ sink: this.frameSink
656
+ } });
657
+ }
658
+ killFfmpeg() {
659
+ const child = this.process;
660
+ if (!child) return;
661
+ this.process = null;
662
+ try {
663
+ child.stdin?.end();
664
+ } catch {}
665
+ try {
666
+ child.kill("SIGTERM");
667
+ } catch {}
668
+ const pid = child.pid;
669
+ setTimeout(() => {
670
+ if (pid !== void 0 && !child.killed) try {
671
+ child.kill("SIGKILL");
672
+ } catch {}
673
+ }, 500).unref?.();
674
+ }
675
+ /** The decode path for the current attempt — `hwaccelChain[index]`, or `null`
676
+ * (software) once the chain is exhausted. */
677
+ currentHwAccel() {
678
+ return this.hwaccelChain[this.hwaccelIndex] ?? null;
679
+ }
680
+ handleExit(code, signal) {
681
+ if (this.destroyed) return;
682
+ const diedFast = Date.now() - this.spawnedAtMs < HWACCEL_FALLBACK_WINDOW_MS;
683
+ if (!isSoftwareHwAccel(this.hwaccel) && this.outputFrames === 0 && diedFast) {
684
+ const failed = this.hwaccel;
685
+ this.hwaccelIndex += 1;
686
+ this.hwaccel = this.currentHwAccel();
687
+ const next = isSoftwareHwAccel(this.hwaccel) ? "software" : this.hwaccel;
688
+ this.logger.warn("ffmpeg decoder: hwaccel child exited early with no frames — trying next decode path", { meta: {
689
+ failed,
690
+ next,
691
+ code,
692
+ signal
693
+ } });
694
+ this.process = null;
695
+ this.spawnFfmpeg();
696
+ return;
697
+ }
698
+ this.process = null;
699
+ this.logger.warn("ffmpeg decoder: child exited", { meta: {
700
+ code,
701
+ signal,
702
+ outputFrames: this.outputFrames
703
+ } });
704
+ }
705
+ handleStderr(data) {
706
+ const text = data.toString();
707
+ if (this.frameSize === 0) {
708
+ this.stderrAccum = (this.stderrAccum + text).slice(-16384);
709
+ this.tryLearnGeometry();
710
+ }
711
+ const line = text.trim();
712
+ if (line) this.logger.debug("ffmpeg stderr", { meta: { line } });
713
+ }
714
+ /** Parse the muxer's Output block once to size the raw frames. */
715
+ tryLearnGeometry() {
716
+ const idx = this.stderrAccum.indexOf("Output #");
717
+ if (idx < 0) return;
718
+ const match = this.stderrAccum.slice(idx).match(/(\d{2,5})x(\d{2,5})/);
719
+ if (!match) return;
720
+ const width = Number(match[1]);
721
+ const height = Number(match[2]);
722
+ if (width <= 0 || height <= 0) return;
723
+ this.outWidth = width;
724
+ this.outHeight = height;
725
+ this.frameSize = width * height * this.channels;
726
+ this.logger.info("ffmpeg decoder: learned output geometry", { meta: {
727
+ width,
728
+ height,
729
+ channels: this.channels,
730
+ frameSize: this.frameSize
731
+ } });
732
+ this.drainFrames();
733
+ }
734
+ handleStdout(chunk) {
735
+ this.outputBuffer = this.outputBuffer.length === 0 ? chunk : Buffer.concat([this.outputBuffer, chunk]);
736
+ if (this.frameSize === 0) return;
737
+ this.drainFrames();
738
+ }
739
+ drainFrames() {
740
+ const size = this.frameSize;
741
+ if (size === 0) return;
742
+ let offset = 0;
743
+ while (this.outputBuffer.length - offset >= size) {
744
+ const slice = this.outputBuffer.subarray(offset, offset + size);
745
+ offset += size;
746
+ this.emitFrame(slice);
747
+ }
748
+ if (offset > 0) this.outputBuffer = Buffer.from(this.outputBuffer.subarray(offset));
749
+ }
750
+ emitFrame(slice) {
751
+ if (!this.frameDropper.shouldKeep()) {
752
+ this.droppedFrames++;
753
+ return;
754
+ }
755
+ const pixels = Buffer.from(slice);
756
+ this.outputFrames++;
757
+ if (this.frameSink === "shm") {
758
+ const handle = this.ensureFrameRingSink().writeFrame(pixels, {
759
+ width: this.outWidth,
760
+ height: this.outHeight,
761
+ format: this.frameFormat,
762
+ pts: performance.now(),
763
+ byteLength: pixels.byteLength
764
+ });
765
+ if (handle === null) {
766
+ this.droppedFrames++;
767
+ return;
768
+ }
769
+ const delivered = {
770
+ handle,
771
+ timestamp: Date.now()
772
+ };
773
+ for (const cb of this.handleCallbacks) cb(delivered);
774
+ return;
775
+ }
776
+ const frame = {
777
+ data: pixels,
778
+ width: this.outWidth,
779
+ height: this.outHeight,
780
+ format: this.frameFormat,
781
+ timestamp: Date.now()
782
+ };
783
+ for (const cb of this.frameCallbacks) cb(frame);
784
+ }
785
+ pushPacket(packet) {
786
+ if (this.destroyed) return;
787
+ const stdin = this.process?.stdin;
788
+ if (!stdin) return;
789
+ this.inputPackets++;
790
+ try {
791
+ stdin.write(packet.data);
792
+ } catch {}
793
+ }
794
+ onFrame(callback) {
795
+ this.frameCallbacks.add(callback);
796
+ return () => {
797
+ this.frameCallbacks.delete(callback);
798
+ };
799
+ }
800
+ /** Subscribe to shared-memory frame handles — fires only in `'shm'` mode. */
801
+ onFrameHandle(callback) {
802
+ this.handleCallbacks.add(callback);
803
+ return () => {
804
+ this.handleCallbacks.delete(callback);
805
+ };
806
+ }
807
+ updateConfig(update) {
808
+ const needsRestart = update.scale !== void 0 && update.scale !== this.config.scale || update.outputFormat !== void 0 && update.outputFormat !== this.config.outputFormat || update.codec !== void 0 && update.codec !== this.config.codec;
809
+ this.config = {
810
+ ...this.config,
811
+ ...update
812
+ };
813
+ if (update.maxFps !== void 0) this.frameDropper.setMaxFps(update.maxFps);
814
+ if (needsRestart) this.spawnFfmpeg();
815
+ }
816
+ async destroy() {
817
+ if (this.destroyed) return;
818
+ this.destroyed = true;
819
+ this.killFfmpeg();
820
+ this.frameRingSink?.destroy();
821
+ this.frameRingSink = null;
822
+ this.frameCallbacks.clear();
823
+ this.handleCallbacks.clear();
824
+ }
825
+ getStats() {
826
+ const uptimeSec = Math.max((Date.now() - this.startTime) / 1e3, 1);
827
+ return {
828
+ inputFps: this.inputPackets / uptimeSec,
829
+ outputFps: this.outputFrames / uptimeSec,
830
+ avgDecodeTimeMs: 0,
831
+ droppedFrames: this.droppedFrames
832
+ };
833
+ }
834
+ };
835
+ //#endregion
836
+ //#region src/decoder-ffmpeg/addon/index.ts
837
+ var FRAME_BUFFER_CAPACITY = 32;
838
+ var DecoderFfmpegAddon = class extends BaseAddon {
839
+ sessions = /* @__PURE__ */ new Map();
840
+ frameBuffers = /* @__PURE__ */ new Map();
841
+ handleBuffers = /* @__PURE__ */ new Map();
842
+ unsubscribers = /* @__PURE__ */ new Map();
843
+ sessionMeta = /* @__PURE__ */ new Map();
844
+ frameReaders = null;
845
+ getFrameHits = 0;
846
+ getFrameMisses = 0;
847
+ /**
848
+ * The ffmpeg binary every session spawns — resolved once at init from the
849
+ * cluster `ffmpeg` config section (`binaryPath`), defaulting to PATH
850
+ * `ffmpeg`. MUST be the same binary the broker / recorder / probe use so the
851
+ * decode-accel probe reports for the right build.
852
+ */
853
+ ffmpegPath = "ffmpeg";
854
+ constructor() {
855
+ super(DEFAULT_DECODER_HWACCEL_CONFIG);
856
+ }
857
+ globalSettingsSchema() {
858
+ return this.schema({ sections: [{
859
+ id: "hwaccel",
860
+ title: "Hardware acceleration",
861
+ tab: "decoder",
862
+ description: "Backend used by ffmpeg-subprocess decoder sessions. \"Auto\" defers to the probed best (VA-API on Intel); \"Off\" forces pure software. Only the VA-API hardware path is validated — other concrete backends degrade to software. Changes apply to NEW sessions.",
863
+ fields: [this.field({
864
+ type: "select",
865
+ key: "hwaccel",
866
+ label: "Preferred backend",
867
+ options: [...HWACCEL_OPTIONS],
868
+ default: "auto",
869
+ immediate: true
870
+ }), this.field({
871
+ type: "text",
872
+ key: "probedBestHwaccel",
873
+ label: "Probed best",
874
+ description: "Auto-detected best decoder backend on this host. Click the refresh icon to re-run the probe.",
875
+ readonlyField: true,
876
+ default: "",
877
+ actions: [{
878
+ action: "reprobe-hwaccel",
879
+ icon: "refresh-cw",
880
+ tooltip: "Re-probe hwaccel"
881
+ }]
882
+ })]
883
+ }] });
884
+ }
885
+ async onInitialize() {
886
+ this.ctx.logger.info("ffmpeg decoder addon initialized");
887
+ this.frameReaders = new FrameRingReaderCache(this.ctx.logger);
888
+ this.ffmpegPath = await this.resolveFfmpegBinaryPath();
889
+ if (!this.config.probedBestHwaccel) this.reprobeHwaccel().catch((err) => {
890
+ this.ctx.logger.warn("ffmpeg: auto-reprobe hwaccel failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
891
+ });
892
+ return [{
893
+ capability: decoderCapability,
894
+ provider: this
895
+ }];
896
+ }
897
+ /**
898
+ * Resolve the ffmpeg binary the sessions spawn.
899
+ *
900
+ * Precedence:
901
+ * 1. An explicit operator override in the cluster `ffmpeg` config section
902
+ * (`binaryPath`) — wins when set, so a hand-picked build can be forced.
903
+ * 2. Otherwise `ctx.deps.ensureFfmpeg()` — provisions a portable static
904
+ * ffmpeg into the node's deps dir when the system has none and returns its
905
+ * absolute path. This GUARANTEES ffmpeg on every node (hub, agent, Mac),
906
+ * so there is no missing-ffmpeg case and no node-av fallback.
907
+ *
908
+ * `ensureFfmpeg()` is single-flighted, so we resolve once at init and reuse
909
+ * the path for every session. If it throws (e.g. a download failure) we log a
910
+ * loud ERROR and fall back to PATH `ffmpeg`; the addon still registers the
911
+ * decoder cap and a later session spawn re-runs the ensure.
912
+ */
913
+ async resolveFfmpegBinaryPath() {
914
+ try {
915
+ const bp = (await this.ctx.settings?.getSection("ffmpeg") ?? {})["binaryPath"];
916
+ if (typeof bp === "string" && bp.trim().length > 0) return bp;
917
+ } catch {}
918
+ try {
919
+ return await this.ctx.deps.ensureFfmpeg();
920
+ } catch (err) {
921
+ this.ctx.logger.error("decoder-ffmpeg: ensureFfmpeg() failed to provision ffmpeg — falling back to PATH \"ffmpeg\"; a later session will retry", { meta: { error: err instanceof Error ? err.message : String(err) } });
922
+ return "ffmpeg";
923
+ }
924
+ }
925
+ /**
926
+ * Resolve the ORDERED decode-hwaccel chain for a new session — NEVER
927
+ * hardcoded. The session tries the chain best-first and only falls to
928
+ * software once every hardware option is exhausted.
929
+ *
930
+ * - `'none'` → `[]` (pure software).
931
+ * - explicit backend → `[<backend>]` (forced; the session still falls to
932
+ * software if that one child fails).
933
+ * - `'auto'` → asks `platform-probe.resolveHwAccel` for the kernel-preferred
934
+ * order + the node's supported `-hwaccel` methods
935
+ * (`getHardwareDecodeAccels`), then ranks them via {@link rankDecodeHwAccels}
936
+ * (vaapi ABOVE qsv, since qsv is broken on the Intel stack while vaapi
937
+ * works). On a probe error → `[]` (software).
938
+ */
939
+ async resolveDecodeHwaccelChain() {
940
+ const pref = this.config.hwaccel;
941
+ if (pref === "none") return [];
942
+ if (pref !== "auto") return [pref];
943
+ try {
944
+ const res = await this.ctx.api.platformProbe.resolveHwAccel.query({ prefer: null });
945
+ const supported = await this.ctx.api.platformProbe.getHardwareDecodeAccels.query();
946
+ return rankDecodeHwAccels(res.preferred, supported.methods);
947
+ } catch (err) {
948
+ this.ctx.logger.warn("ffmpeg: decode-hwaccel probe failed — software decode", { meta: { error: err instanceof Error ? err.message : String(err) } });
949
+ return [];
950
+ }
951
+ }
952
+ async reprobeHwaccel() {
953
+ const resolver = this.ctx.kernel.hwaccel;
954
+ if (!resolver) {
955
+ this.ctx.logger.warn("reprobeHwaccel: no kernel hwaccel resolver — returning none");
956
+ await this.ctx.settings?.writeAddonStore({ probedBestHwaccel: "none" });
957
+ return { backend: "none" };
958
+ }
959
+ try {
960
+ const res = await resolver.resolve();
961
+ const backend = res.preferred[0] ?? "none";
962
+ await this.ctx.settings?.writeAddonStore({ probedBestHwaccel: backend });
963
+ this.ctx.logger.info("reprobeHwaccel: wrote probedBestHwaccel", { meta: {
964
+ backend,
965
+ rationale: res.rationale,
966
+ preferred: res.preferred
967
+ } });
968
+ return { backend };
969
+ } catch (err) {
970
+ this.ctx.logger.warn("reprobeHwaccel failed", { meta: { error: err instanceof Error ? err.message : String(err) } });
971
+ await this.ctx.settings?.writeAddonStore({ probedBestHwaccel: "none" });
972
+ return { backend: "none" };
973
+ }
974
+ }
975
+ async supportsCodec(input) {
976
+ return [
977
+ "h264",
978
+ "h265",
979
+ "hevc"
980
+ ].includes(input.codec.toLowerCase());
981
+ }
982
+ async getInfo() {
983
+ return {
984
+ id: "decoder-ffmpeg",
985
+ name: "Decoder (ffmpeg)",
986
+ isPullMode: false,
987
+ priority: 20
988
+ };
989
+ }
990
+ /**
991
+ * The cluster node id of this decoder — stamped into session-owned
992
+ * `FrameHandle`s so a downstream consumer routes `getFrame` to the node that
993
+ * holds the shm ring. Mirrors `decoder-nodeav`.
994
+ */
995
+ resolveLocalNodeId() {
996
+ const raw = this.ctx.kernel.localNodeId ?? this.ctx.id;
997
+ return raw.includes("/") ? raw.split("/")[0] : raw;
998
+ }
999
+ async createSession(config) {
1000
+ const sessionId = randomUUID();
1001
+ const { frameSink } = config;
1002
+ const nodeId = this.resolveLocalNodeId();
1003
+ const hwaccelChain = await this.resolveDecodeHwaccelChain();
1004
+ const session = new FfmpegDecoderSession(config, this.ctx.logger, {
1005
+ hwaccelChain,
1006
+ ffmpegPath: this.ffmpegPath,
1007
+ frameSink,
1008
+ nodeId
1009
+ });
1010
+ const unsub = frameSink === "shm" ? this.wireShmSink(sessionId, session) : this.wireCallbackSink(sessionId, session);
1011
+ this.sessions.set(sessionId, session);
1012
+ this.unsubscribers.set(sessionId, unsub);
1013
+ this.sessionMeta.set(sessionId, {
1014
+ codec: config.codec,
1015
+ outputFormat: config.outputFormat,
1016
+ createdAtMs: Date.now()
1017
+ });
1018
+ this.ctx.logger.info("ffmpeg: created session", { meta: {
1019
+ sessionId,
1020
+ codec: config.codec,
1021
+ hwaccelChain,
1022
+ frameSink,
1023
+ nodeId
1024
+ } });
1025
+ return {
1026
+ sessionId,
1027
+ nodeId
1028
+ };
1029
+ }
1030
+ wireCallbackSink(sessionId, session) {
1031
+ const ringBuffer = new RingBuffer(FRAME_BUFFER_CAPACITY);
1032
+ this.frameBuffers.set(sessionId, ringBuffer);
1033
+ return session.onFrame((frame) => {
1034
+ const { format } = frame;
1035
+ if (format !== "jpeg" && format !== "rgb" && format !== "bgr" && format !== "yuv420" && format !== "gray") return;
1036
+ const arrayBuf = new ArrayBuffer(frame.data.byteLength);
1037
+ new Uint8Array(arrayBuf).set(frame.data);
1038
+ const capFrame = {
1039
+ data: new Uint8Array(arrayBuf),
1040
+ width: frame.width,
1041
+ height: frame.height,
1042
+ format,
1043
+ timestamp: frame.timestamp
1044
+ };
1045
+ ringBuffer.push(capFrame);
1046
+ });
1047
+ }
1048
+ wireShmSink(sessionId, session) {
1049
+ const handleRing = new RingBuffer(FRAME_BUFFER_CAPACITY);
1050
+ this.handleBuffers.set(sessionId, handleRing);
1051
+ return session.onFrameHandle((frame) => {
1052
+ handleRing.push(frame.handle);
1053
+ });
1054
+ }
1055
+ async destroySession(input) {
1056
+ const { sessionId } = input;
1057
+ const session = this.sessions.get(sessionId);
1058
+ if (!session) throw new Error(`decoder-ffmpeg: unknown sessionId ${sessionId}`);
1059
+ const unsub = this.unsubscribers.get(sessionId);
1060
+ if (unsub) unsub();
1061
+ await session.destroy();
1062
+ this.sessions.delete(sessionId);
1063
+ this.frameBuffers.delete(sessionId);
1064
+ this.handleBuffers.delete(sessionId);
1065
+ this.unsubscribers.delete(sessionId);
1066
+ this.sessionMeta.delete(sessionId);
1067
+ this.ctx.logger.info("ffmpeg: destroyed session", { meta: { sessionId } });
1068
+ }
1069
+ async listActiveSessions() {
1070
+ const out = [];
1071
+ for (const [sessionId, meta] of this.sessionMeta) out.push({
1072
+ sessionId,
1073
+ codec: meta.codec,
1074
+ outputFormat: meta.outputFormat,
1075
+ createdAtMs: meta.createdAtMs
1076
+ });
1077
+ return out;
1078
+ }
1079
+ async pushPacket(input) {
1080
+ const session = this.sessions.get(input.sessionId);
1081
+ if (!session) throw new Error(`decoder-ffmpeg: unknown sessionId ${input.sessionId}`);
1082
+ const rawData = input.packet.data;
1083
+ const data = Buffer.isBuffer(rawData) ? rawData : rawData instanceof Uint8Array ? Buffer.from(rawData.buffer, rawData.byteOffset, rawData.byteLength) : Buffer.from(rawData);
1084
+ session.pushPacket({
1085
+ ...input.packet,
1086
+ data
1087
+ });
1088
+ }
1089
+ async openStream(input) {
1090
+ if (!this.sessions.get(input.sessionId)) throw new Error(`decoder-ffmpeg: unknown sessionId ${input.sessionId}`);
1091
+ input.url;
1092
+ }
1093
+ async pullFrames(input) {
1094
+ if (!this.sessions.has(input.sessionId)) throw new Error(`decoder-ffmpeg: unknown sessionId ${input.sessionId}`);
1095
+ const ringBuffer = this.frameBuffers.get(input.sessionId);
1096
+ if (!ringBuffer) return [];
1097
+ return ringBuffer.drain(input.maxCount);
1098
+ }
1099
+ async pullHandles(input) {
1100
+ if (!this.sessions.has(input.sessionId)) throw new Error(`decoder-ffmpeg: unknown sessionId ${input.sessionId}`);
1101
+ const handleRing = this.handleBuffers.get(input.sessionId);
1102
+ if (!handleRing) return [];
1103
+ return handleRing.drain(input.maxCount);
1104
+ }
1105
+ async updateConfig(input) {
1106
+ const session = this.sessions.get(input.sessionId);
1107
+ if (!session) throw new Error(`decoder-ffmpeg: unknown sessionId ${input.sessionId}`);
1108
+ session.updateConfig(input.config);
1109
+ }
1110
+ async getStats(input) {
1111
+ const session = this.sessions.get(input.sessionId);
1112
+ if (!session) throw new Error(`decoder-ffmpeg: unknown sessionId ${input.sessionId}`);
1113
+ return session.getStats();
1114
+ }
1115
+ async getFrame(input) {
1116
+ const frame = this.frameReaders?.read(input.handle) ?? null;
1117
+ if (!frame) {
1118
+ this.getFrameMisses += 1;
1119
+ return null;
1120
+ }
1121
+ this.getFrameHits += 1;
1122
+ const arrayBuf = new ArrayBuffer(frame.data.byteLength);
1123
+ new Uint8Array(arrayBuf).set(frame.data);
1124
+ return {
1125
+ data: new Uint8Array(arrayBuf),
1126
+ width: frame.width,
1127
+ height: frame.height,
1128
+ format: frame.format,
1129
+ timestamp: frame.timestamp
1130
+ };
1131
+ }
1132
+ async getShmStats(input) {
1133
+ const stats = this.sessions.get(input.sessionId)?.frameRingSinkOrNull?.getShmStats() ?? null;
1134
+ if (!stats) return null;
1135
+ return {
1136
+ sessionId: input.sessionId,
1137
+ ...stats,
1138
+ budgetMb: RING_BUDGET_MB,
1139
+ getFrameHits: this.getFrameHits,
1140
+ getFrameMisses: this.getFrameMisses
1141
+ };
1142
+ }
1143
+ async onShutdown() {
1144
+ this.ctx.logger.info("ffmpeg decoder addon shutdown — destroying all sessions");
1145
+ const destroyPromises = [];
1146
+ for (const [sessionId, session] of this.sessions) {
1147
+ const unsub = this.unsubscribers.get(sessionId);
1148
+ if (unsub) unsub();
1149
+ destroyPromises.push(session.destroy());
1150
+ }
1151
+ await Promise.all(destroyPromises);
1152
+ this.sessions.clear();
1153
+ this.frameBuffers.clear();
1154
+ this.handleBuffers.clear();
1155
+ this.unsubscribers.clear();
1156
+ this.sessionMeta.clear();
1157
+ this.frameReaders?.close();
1158
+ this.frameReaders = null;
1159
+ }
1160
+ };
1161
+ //#endregion
1162
+ export { DECODE_HWACCEL_RANK, DEFAULT_VAAPI_RENDER_DEVICE, DecoderFfmpegAddon, DecoderFfmpegAddon as default, FfmpegDecoderSession, buildFfmpegDecodeArgs, channelsForPixel, codecToInputFormat, computeOutputGeometry, maxDecodeWidth, parseFfmpegOutputDims, pickDecodeHwAccel, rankDecodeHwAccels, rawPixelForFormat };