@camstack/addon-pipeline 1.1.39 → 1.1.41

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 (38) hide show
  1. package/dist/audio-analyzer/index.js +168 -61
  2. package/dist/audio-analyzer/index.mjs +168 -61
  3. package/dist/detection-pipeline/index.js +2 -2
  4. package/dist/detection-pipeline/index.mjs +2 -2
  5. package/dist/{dist-DbGdZ8Nr.js → dist-BJTPkJFw.js} +247 -3
  6. package/dist/{dist-DvvYzO58.mjs → dist-v6cKLmU3.mjs} +247 -3
  7. package/dist/{frame-handle-plane-B7jMIZc2.js → frame-handle-plane-BP8YV4sF.js} +54 -5
  8. package/dist/{frame-handle-plane-BFzoIfkd.mjs → frame-handle-plane-DKAXTtfn.mjs} +54 -5
  9. package/dist/motion-wasm/index.js +1 -1
  10. package/dist/motion-wasm/index.mjs +1 -1
  11. package/dist/pipeline-runner/index.js +893 -12
  12. package/dist/pipeline-runner/index.mjs +892 -13
  13. package/dist/recorder/index.js +2 -2
  14. package/dist/recorder/index.mjs +2 -2
  15. package/dist/session-decode/decode-worker-child.js +544 -0
  16. package/dist/session-decode/decode-worker-child.mjs +543 -0
  17. package/dist/stream-broker/_stub.js +44 -44
  18. package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-DezFy4Fu.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-C2l0kmD4.mjs} +3 -3
  19. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-DqJvWBKS.mjs +26 -0
  20. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-dGka8yZY.mjs +26 -0
  21. package/dist/stream-broker/{hostInit-BOf0hg9q.mjs → hostInit-DHaCRMjM.mjs} +3 -3
  22. package/dist/stream-broker/index.js +268 -38
  23. package/dist/stream-broker/index.mjs +268 -38
  24. package/dist/stream-broker/remoteEntry.js +1 -1
  25. package/dist/worker-protocol-BCfO8gUF.js +67 -0
  26. package/dist/worker-protocol-pk7qdYXt.mjs +56 -0
  27. package/embed-dist/assets/{MaskShapeCanvas-DI4BY7W2-Br2fqwe7.js → MaskShapeCanvas-DI4BY7W2-B6fza7ic.js} +1 -1
  28. package/embed-dist/assets/{MotionZonesSettings-NcxxQN8r-DYXRf30g.js → MotionZonesSettings-NcxxQN8r-Cy-4iTog.js} +1 -1
  29. package/embed-dist/assets/{PrivacyMaskSettings-APgPLF7p-DLpqLgPo.js → PrivacyMaskSettings-APgPLF7p-CYX33lJb.js} +1 -1
  30. package/embed-dist/assets/index-BPkayx9u.js +81 -0
  31. package/embed-dist/assets/index-CSFtK41z.css +2 -0
  32. package/embed-dist/index.html +2 -2
  33. package/package.json +6 -3
  34. package/python/inference_pool.py +3 -1
  35. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_types__loadShare__.js-DhY3MZ2C.mjs +0 -26
  36. package/dist/stream-broker/_virtual_mf___mfe_internal__addon_stream_broker_widgets__loadShare___mf_0_camstack_mf_1_ui_mf_2_library__loadShare__.js-BsrrdOBU.mjs +0 -26
  37. package/embed-dist/assets/index-C5UpuPr8.css +0 -2
  38. package/embed-dist/assets/index-CR367rYR.js +0 -81
@@ -0,0 +1,543 @@
1
+ import { n as isWorkerRequest } from "../worker-protocol-pk7qdYXt.mjs";
2
+ //#region src/session-decode/frame-slot.ts
3
+ function toReply(held) {
4
+ return {
5
+ frameId: held.frameId,
6
+ timestamp: held.timestamp,
7
+ width: held.width,
8
+ height: held.height
9
+ };
10
+ }
11
+ /**
12
+ * Latest-wins decoded-frame slot + reserved-for-`toBuffer` holder +
13
+ * pending-pull flag. One instance per decode-worker child session.
14
+ */
15
+ var FrameSlot = class {
16
+ nextFrameId = 1;
17
+ slot = null;
18
+ /**
19
+ * The frame handed to the MOST RECENT `pull`, retained so a following
20
+ * `toBuffer(frameId)` still resolves even though `publish` keeps advancing
21
+ * the latest-wins `slot`. Freed when the next `pull` supersedes it (or on
22
+ * `free()`).
23
+ */
24
+ reserved = null;
25
+ pendingPull = false;
26
+ /**
27
+ * Publish a newly decoded frame into the latest-wins slot, freeing
28
+ * whatever the slot held before (the drop-older half of "latest-wins").
29
+ * Returns the reply to send if a `pull` was pending (resolving it
30
+ * immediately and reserving the frame); otherwise returns `null` and the
31
+ * frame simply waits in the slot for the next `pull`.
32
+ */
33
+ publish(frame, timestamp, minIntervalMs) {
34
+ if (minIntervalMs > 0 && this.slot && timestamp - this.slot.timestamp < minIntervalMs) {
35
+ frame.free();
36
+ return null;
37
+ }
38
+ const previous = this.slot;
39
+ const frameId = this.nextFrameId++;
40
+ this.slot = {
41
+ frameId,
42
+ frame,
43
+ timestamp,
44
+ width: frame.width,
45
+ height: frame.height
46
+ };
47
+ previous?.frame.free();
48
+ if (this.pendingPull) {
49
+ this.pendingPull = false;
50
+ return this.reserveSlot();
51
+ }
52
+ return null;
53
+ }
54
+ /**
55
+ * Hand out the newest slot frame and RESERVE it (freeing the previously
56
+ * reserved frame), clearing the slot. Returns `null` if no frame has been
57
+ * decoded yet — the caller should then call `markPendingPull()`.
58
+ */
59
+ pull() {
60
+ if (!this.slot) return null;
61
+ return this.reserveSlot();
62
+ }
63
+ /** Record that a pull is waiting for the next `publish` to resolve it. */
64
+ markPendingPull() {
65
+ this.pendingPull = true;
66
+ }
67
+ /** The reserved frame for `frameId`, or `null` if unknown/stale. */
68
+ toBuffer(frameId) {
69
+ if (!this.reserved || this.reserved.frameId !== frameId) return null;
70
+ return this.reserved.frame;
71
+ }
72
+ /** Free both the slot and the reserved frame (teardown). */
73
+ free() {
74
+ this.slot?.frame.free();
75
+ this.slot = null;
76
+ this.reserved?.frame.free();
77
+ this.reserved = null;
78
+ }
79
+ reserveSlot() {
80
+ const held = this.slot;
81
+ if (!held) throw new Error("frame-slot: reserveSlot called with no slot held");
82
+ const previousReserved = this.reserved;
83
+ this.reserved = held;
84
+ this.slot = null;
85
+ previousReserved?.frame.free();
86
+ return toReply(held);
87
+ }
88
+ };
89
+ //#endregion
90
+ //#region src/session-decode/decode-worker-child.ts
91
+ /** Re-dial backoff on a transient dial error/EOF (mirrors the decoder's PULL_REDIAL_MS). */
92
+ var REDIAL_MS = 3e3;
93
+ var _nav = null;
94
+ var _consts = null;
95
+ async function getNodeAv() {
96
+ if (!_nav) _nav = await import("node-av");
97
+ return _nav;
98
+ }
99
+ async function getConstants() {
100
+ if (!_consts) _consts = await import("node-av/constants");
101
+ return _consts;
102
+ }
103
+ function errMessage(err) {
104
+ if (err instanceof Error) return err.message;
105
+ return String(err);
106
+ }
107
+ /**
108
+ * RTSP low-latency demuxer options — mirrors
109
+ * `addon-decoder-nodeav/src/pull-demuxer-options.ts` (duplicated here rather
110
+ * than cross-imported: this file is a standalone forked entry point, not an
111
+ * addon consumer of that package). `analyzeduration`/`probesize` stay small
112
+ * but non-zero — zeroing them starves the Reolink rfc4571 restream demuxer.
113
+ */
114
+ function buildDemuxerOptions() {
115
+ return {
116
+ rtsp_transport: "tcp",
117
+ fflags: "nobuffer",
118
+ analyzeduration: "1000000",
119
+ probesize: "1000000",
120
+ max_delay: "0",
121
+ reorder_queue_size: "0",
122
+ user_agent: "decode-worker"
123
+ };
124
+ }
125
+ /** Ordered hwaccel candidates per platform — first successful create() wins, else software. */
126
+ function candidateBackends() {
127
+ switch (process.platform) {
128
+ case "darwin": return ["videotoolbox"];
129
+ case "linux": return [
130
+ "vaapi",
131
+ "qsv",
132
+ "cuda"
133
+ ];
134
+ case "win32": return [
135
+ "d3d11va",
136
+ "dxva2",
137
+ "cuda"
138
+ ];
139
+ default: return [];
140
+ }
141
+ }
142
+ /** Map a canonical backend name to the node-av `AV_HWDEVICE_TYPE_*` constant. */
143
+ function backendToHwDeviceConst(backend, consts) {
144
+ switch (backend) {
145
+ case "videotoolbox": return consts.AV_HWDEVICE_TYPE_VIDEOTOOLBOX;
146
+ case "cuda":
147
+ case "nvdec": return consts.AV_HWDEVICE_TYPE_CUDA;
148
+ case "vaapi": return consts.AV_HWDEVICE_TYPE_VAAPI;
149
+ case "qsv": return consts.AV_HWDEVICE_TYPE_QSV;
150
+ case "d3d11va": return consts.AV_HWDEVICE_TYPE_D3D11VA;
151
+ case "dxva2": return consts.AV_HWDEVICE_TYPE_DXVA2;
152
+ case "amf": return consts.AV_HWDEVICE_TYPE_AMF;
153
+ case "vdpau": return consts.AV_HWDEVICE_TYPE_VDPAU;
154
+ case "drm": return consts.AV_HWDEVICE_TYPE_DRM;
155
+ default: return null;
156
+ }
157
+ }
158
+ /** Clamp to [min,max] then floor to the nearest even number (YUV420P chroma is 2x2 subsampled). */
159
+ function clampEven(value, min, max) {
160
+ const bounded = Math.min(Math.max(value, min), max);
161
+ return bounded - bounded % 2;
162
+ }
163
+ /** Resolve `FrameImageOptions.crop` against the decoded frame's dimensions, defaulting to the full frame. */
164
+ function resolveCropRegion(frameWidth, frameHeight, crop) {
165
+ const left = clampEven(crop?.left ?? 0, 0, Math.max(0, frameWidth - 2));
166
+ const top = clampEven(crop?.top ?? 0, 0, Math.max(0, frameHeight - 2));
167
+ return {
168
+ left,
169
+ top,
170
+ width: clampEven(crop?.width ?? frameWidth - left, 2, frameWidth - left),
171
+ height: clampEven(crop?.height ?? frameHeight - top, 2, frameHeight - top)
172
+ };
173
+ }
174
+ /** Resolve `FrameImageOptions.resize`, defaulting to the (already cropped) source dimensions. */
175
+ function resolveResizeTarget(cropWidth, cropHeight, resize) {
176
+ if (!resize) return {
177
+ width: cropWidth,
178
+ height: cropHeight
179
+ };
180
+ return {
181
+ width: Math.max(1, Math.round(resize.width)),
182
+ height: Math.max(1, Math.round(resize.height))
183
+ };
184
+ }
185
+ /**
186
+ * The forked child's whole runtime: decode-loop lifecycle, the latest-wins
187
+ * frame slot, and the ROI scaler for `toBuffer`. One instance per process.
188
+ */
189
+ var DecodeWorkerChild = class {
190
+ nav = null;
191
+ consts = null;
192
+ hwContext = null;
193
+ /**
194
+ * Reused software scaler + the geometry/format key it was built for.
195
+ * Building a fresh `SoftwareScaleContext` on EVERY `toBuffer` (24fps)
196
+ * churned native libav memory unboundedly (a persistent worker grew to
197
+ * ~10GB/h). Detection uses a stable ROI + resize target, so the scaler is
198
+ * built once and reused, rebuilt only when the key changes — mirroring the
199
+ * shared decoder session (`nodeav-decoder-session.ts`, which reuses one
200
+ * `this.scaler` for the same reason). Disposed in `teardown`.
201
+ */
202
+ scaler = null;
203
+ scalerKey = "";
204
+ demuxer = null;
205
+ decoder = null;
206
+ abortController = null;
207
+ started = false;
208
+ stopped = false;
209
+ sessionFormat = "rgb";
210
+ minIntervalMs = 0;
211
+ /**
212
+ * The latest-wins decoded-frame slot + reserved-for-`toBuffer` holder +
213
+ * pending-pull flag — extracted to `FrameSlot` (Epic C P2 Task 2 / I2) so
214
+ * the reserve-on-pull invariant (`e3c78a9b`) is unit-tested without
215
+ * node-av. See that file's doc comment for the full semantics.
216
+ */
217
+ frames = new FrameSlot();
218
+ /**
219
+ * Mirrors whether `this.frames` currently has a pull waiting, so
220
+ * `teardown` knows to resolve it with `{kind:'ended'}` — `FrameSlot`
221
+ * intentionally exposes no pending-pull query, only `markPendingPull()`,
222
+ * so the child tracks this in lockstep (set in `handlePull`, cleared
223
+ * whenever `consumeDecodedFrame`'s `publish` resolves it).
224
+ */
225
+ pendingPull = false;
226
+ ended = false;
227
+ redialTimer = null;
228
+ handleMessage(message) {
229
+ if (!isWorkerRequest(message)) {
230
+ this.sendError("decode-worker-child: malformed request");
231
+ return;
232
+ }
233
+ switch (message.kind) {
234
+ case "start":
235
+ this.handleStart(message.source, message.opts);
236
+ return;
237
+ case "pull":
238
+ this.handlePull();
239
+ return;
240
+ case "toBuffer":
241
+ this.handleToBuffer(message.frameId, message.opts);
242
+ return;
243
+ case "stop":
244
+ this.handleStop();
245
+ return;
246
+ }
247
+ }
248
+ /** Channel teardown (explicit `stop` or the parent disconnecting) — dispose, then exit. */
249
+ teardown() {
250
+ this.stopped = true;
251
+ this.ended = true;
252
+ if (this.redialTimer) {
253
+ clearTimeout(this.redialTimer);
254
+ this.redialTimer = null;
255
+ }
256
+ this.abortController?.abort();
257
+ this.closeInput();
258
+ this.frames.free();
259
+ this.scaler?.[Symbol.dispose]?.();
260
+ this.scaler = null;
261
+ this.scalerKey = "";
262
+ this.hwContext?.[Symbol.dispose]?.();
263
+ this.hwContext = null;
264
+ if (this.pendingPull) {
265
+ this.pendingPull = false;
266
+ this.send({ kind: "ended" });
267
+ }
268
+ }
269
+ handleStart(source, opts) {
270
+ if (this.started) {
271
+ process.stderr.write("decode-worker-child: duplicate start ignored\n");
272
+ return;
273
+ }
274
+ this.started = true;
275
+ this.sessionFormat = opts.format ?? "rgb";
276
+ this.minIntervalMs = opts.fps && opts.fps > 0 ? 1e3 / opts.fps : 0;
277
+ this.runDecodeLoop(source.restreamUrl).catch((err) => {
278
+ this.sendError(`decode-worker-child: decode loop crashed — ${errMessage(err)}`);
279
+ });
280
+ }
281
+ handlePull() {
282
+ if (this.ended) {
283
+ this.send({ kind: "ended" });
284
+ return;
285
+ }
286
+ const reply = this.frames.pull();
287
+ if (reply) {
288
+ this.send(this.toFrameReply(reply));
289
+ return;
290
+ }
291
+ this.pendingPull = true;
292
+ this.frames.markPendingPull();
293
+ }
294
+ handleToBuffer(frameId, opts) {
295
+ const frame = this.frames.toBuffer(frameId);
296
+ if (!frame) {
297
+ this.sendError(`decode-worker-child: toBuffer for unknown or stale frameId ${frameId}`, frameId);
298
+ return;
299
+ }
300
+ try {
301
+ const bytes = this.scaleRoiToBuffer(frame, opts);
302
+ this.send({
303
+ kind: "buffer",
304
+ frameId,
305
+ bytes
306
+ });
307
+ } catch (err) {
308
+ this.sendError(`decode-worker-child: toBuffer failed — ${errMessage(err)}`, frameId);
309
+ }
310
+ }
311
+ handleStop() {
312
+ this.teardown();
313
+ process.exit(0);
314
+ }
315
+ async runDecodeLoop(url) {
316
+ const nav = await getNodeAv();
317
+ const C = await getConstants();
318
+ if (this.stopped) return;
319
+ this.nav = nav;
320
+ this.consts = C;
321
+ nav.Log.setLevel(C.AV_LOG_FATAL);
322
+ await this.ensureHwContext(nav, C);
323
+ while (!this.stopped) {
324
+ try {
325
+ await this.dialAndDecode(nav, C, url);
326
+ } catch (err) {
327
+ if (this.stopped) break;
328
+ process.stderr.write(`decode-worker-child: dial ended — re-dial scheduled: ${errMessage(err)}\n`);
329
+ } finally {
330
+ this.closeInput();
331
+ }
332
+ if (this.stopped) break;
333
+ await this.sleep(REDIAL_MS);
334
+ }
335
+ }
336
+ /**
337
+ * One dial: open the demuxer, pick the video stream, build a HW/SW decoder
338
+ * that downloads + normalises frames to YUV420P system memory (so the ROI
339
+ * scaler always reads plain software planes regardless of hwaccel), and
340
+ * pump `demuxer.packets → decoder.frames → consumeDecodedFrame` until the
341
+ * stream ends, errors, or teardown aborts it.
342
+ *
343
+ * Copied from `nodeav-decoder-session.ts` `pullDialAndDecode` (lines
344
+ * ~916-996): same demuxer options, same `rescale.pixelFormat: YUV420P`
345
+ * download-always contract (keeping decoded frames on the GPU leaked the
346
+ * VAAPI surface pool on every re-dial — see that file's comment), same
347
+ * `exitOnError: false` bad-frame tolerance.
348
+ */
349
+ async dialAndDecode(nav, C, url) {
350
+ this.abortController = new AbortController();
351
+ const demuxer = await nav.Demuxer.open(url, {
352
+ options: buildDemuxerOptions(),
353
+ signal: this.abortController.signal
354
+ });
355
+ if (this.stopped) {
356
+ demuxer[Symbol.dispose]?.();
357
+ return;
358
+ }
359
+ this.demuxer = demuxer;
360
+ const videoStream = demuxer.video();
361
+ if (!videoStream) throw new Error("decode-worker-child: pull input has no video stream");
362
+ const decoder = await nav.Decoder.create(videoStream, {
363
+ ...this.hwContext ? { hardware: this.hwContext } : {},
364
+ rescale: { pixelFormat: C.AV_PIX_FMT_YUV420P },
365
+ exitOnError: false
366
+ });
367
+ if (this.stopped) {
368
+ decoder[Symbol.dispose]?.();
369
+ return;
370
+ }
371
+ this.decoder = decoder;
372
+ for await (const frame of decoder.frames(demuxer.packets(videoStream.index))) {
373
+ if (this.stopped) break;
374
+ if (!frame) continue;
375
+ this.consumeDecodedFrame(frame);
376
+ }
377
+ }
378
+ /**
379
+ * Publish a decoded frame into the latest-wins slot (mirrors Scrypted's
380
+ * `libav.py:32,50-53` single-slot queue) via `FrameSlot`, which handles
381
+ * drop-older, the `minIntervalMs` throttle, and resolving a pending `pull`.
382
+ */
383
+ consumeDecodedFrame(frame) {
384
+ if (frame.isHwFrame()) {
385
+ frame.free();
386
+ return;
387
+ }
388
+ const reply = this.frames.publish(frame, Date.now(), this.minIntervalMs);
389
+ if (reply) {
390
+ this.pendingPull = false;
391
+ this.send(this.toFrameReply(reply));
392
+ }
393
+ }
394
+ toFrameReply(reply) {
395
+ return {
396
+ kind: "frame",
397
+ frameId: reply.frameId,
398
+ timestamp: reply.timestamp,
399
+ width: reply.width,
400
+ height: reply.height,
401
+ format: this.sessionFormat
402
+ };
403
+ }
404
+ /**
405
+ * ROI `toBuffer`: crop (via plane-pointer offset, not a re-decode) + resize
406
+ * + format-convert a retained decoded frame with `SoftwareScaleContext`.
407
+ * Writes straight into a tightly-packed destination buffer via the
408
+ * low-level `scaleSync` (no `dstFrame` + row-strip step needed — the same
409
+ * zero-copy destination technique as `scaleIntoRingSlot` in
410
+ * `nodeav-decoder-session.ts`, adapted to also OFFSET the source planes so
411
+ * a single scaler call handles the crop.
412
+ */
413
+ scaleRoiToBuffer(frame, opts) {
414
+ const nav = this.nav;
415
+ const C = this.consts;
416
+ if (!nav || !C) throw new Error("node-av not initialized");
417
+ const region = resolveCropRegion(frame.width, frame.height, opts?.crop);
418
+ const target = resolveResizeTarget(region.width, region.height, opts?.resize);
419
+ const format = opts?.format ?? this.sessionFormat;
420
+ const dstFmt = format === "gray" ? C.AV_PIX_FMT_GRAY8 : C.AV_PIX_FMT_RGB24;
421
+ const channels = format === "gray" ? 1 : 3;
422
+ const planes = frame.data;
423
+ const strides = frame.linesize;
424
+ const yPlane = planes?.[0];
425
+ const uPlane = planes?.[1];
426
+ const vPlane = planes?.[2];
427
+ if (!yPlane || !uPlane || !vPlane) throw new Error("decode-worker-child: decoded frame missing planar YUV420P data");
428
+ const yStride = strides[0] ?? 0;
429
+ const cStride = strides[1] ?? 0;
430
+ const ySlice = yPlane.subarray(region.top * yStride + region.left);
431
+ const uSlice = uPlane.subarray(region.top / 2 * cStride + region.left / 2);
432
+ const vSlice = vPlane.subarray(region.top / 2 * cStride + region.left / 2);
433
+ const scaler = this.ensureScaler(nav, C, region.width, region.height, target.width, target.height, dstFmt);
434
+ const dstStride = target.width * channels;
435
+ const dstBuffer = Buffer.allocUnsafe(dstStride * target.height);
436
+ const scaledHeight = scaler.scaleSync([
437
+ ySlice,
438
+ uSlice,
439
+ vSlice
440
+ ], [
441
+ yStride,
442
+ cStride,
443
+ cStride
444
+ ], 0, region.height, [dstBuffer], [dstStride]);
445
+ if (scaledHeight < 0) throw new Error(`sws_scale failed: ${scaledHeight}`);
446
+ if (scaledHeight !== target.height) throw new Error(`scaler produced ${scaledHeight} of ${target.height} rows`);
447
+ return dstBuffer;
448
+ }
449
+ /**
450
+ * Build-once / reuse the {@link NavScaler} for a given src+dst geometry and
451
+ * dst format. Rebuilt (old disposed) only when the key changes — detection's
452
+ * ROI + resize target are stable, so this is a per-worker singleton in the
453
+ * steady state. Replaces the previous per-frame `new SoftwareScaleContext()`
454
+ * that leaked native libav memory at frame rate. Synchronous + single-thread
455
+ * (Node), so no epoch/race guard is needed (unlike the async shared session).
456
+ */
457
+ ensureScaler(nav, C, srcW, srcH, dstW, dstH, dstFmt) {
458
+ const key = `${srcW}x${srcH}->${dstW}x${dstH}:${dstFmt}`;
459
+ const cached = this.scaler;
460
+ if (cached && key === this.scalerKey) return cached;
461
+ this.scaler?.[Symbol.dispose]?.();
462
+ this.scaler = null;
463
+ this.scalerKey = "";
464
+ const scaler = new nav.SoftwareScaleContext();
465
+ scaler.getContext(srcW, srcH, C.AV_PIX_FMT_YUV420P, dstW, dstH, dstFmt, C.SWS_FAST_BILINEAR);
466
+ const initRet = scaler.initContext();
467
+ if (initRet < 0) {
468
+ scaler[Symbol.dispose]?.();
469
+ throw new Error(`sws_init_context failed: ${initRet}`);
470
+ }
471
+ this.scaler = scaler;
472
+ this.scalerKey = key;
473
+ return scaler;
474
+ }
475
+ /**
476
+ * Resolve the HW context ONCE (reused across every re-dial, freed in
477
+ * `teardown`). Tries the platform's ordered candidate list; the first
478
+ * `HardwareContext.create` that succeeds wins; every failure falls through
479
+ * to software decode (`hardware` omitted from `Decoder.create`).
480
+ */
481
+ async ensureHwContext(nav, C) {
482
+ for (const backend of candidateBackends()) {
483
+ const deviceType = backendToHwDeviceConst(backend, C);
484
+ if (deviceType === null) continue;
485
+ const hw = nav.HardwareContext.create(deviceType);
486
+ if (!hw) {
487
+ process.stderr.write(`decode-worker-child: hwaccel candidate '${backend}' failed — trying next\n`);
488
+ continue;
489
+ }
490
+ this.hwContext = hw;
491
+ return;
492
+ }
493
+ process.stderr.write("decode-worker-child: no hwaccel backend available — using software decode\n");
494
+ }
495
+ /** Interruptible re-dial backoff — `teardown` clears the pending timer. */
496
+ sleep(ms) {
497
+ return new Promise((resolve) => {
498
+ this.redialTimer = setTimeout(() => {
499
+ this.redialTimer = null;
500
+ resolve();
501
+ }, ms);
502
+ });
503
+ }
504
+ /** Dispose the CURRENT dial's demuxer + decoder (the HW context is reused across dials). */
505
+ closeInput() {
506
+ this.decoder?.[Symbol.dispose]?.();
507
+ this.decoder = null;
508
+ this.demuxer?.[Symbol.dispose]?.();
509
+ this.demuxer = null;
510
+ }
511
+ send(reply) {
512
+ process.send?.(reply);
513
+ }
514
+ sendError(message, frameId) {
515
+ process.stderr.write(`${message}\n`);
516
+ this.send(frameId === void 0 ? {
517
+ kind: "error",
518
+ message
519
+ } : {
520
+ kind: "error",
521
+ message,
522
+ frameId
523
+ });
524
+ }
525
+ };
526
+ var worker = new DecodeWorkerChild();
527
+ process.on("message", (message) => {
528
+ worker.handleMessage(message);
529
+ });
530
+ process.on("disconnect", () => {
531
+ worker.teardown();
532
+ process.exit(0);
533
+ });
534
+ process.on("uncaughtException", (err) => {
535
+ process.stderr.write(`decode-worker-child: uncaught exception — ${errMessage(err)}\n`);
536
+ worker.teardown();
537
+ process.exit(1);
538
+ });
539
+ process.on("unhandledRejection", (reason) => {
540
+ process.stderr.write(`decode-worker-child: unhandled rejection — ${errMessage(reason)}\n`);
541
+ });
542
+ //#endregion
543
+ export { DecodeWorkerChild };