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