@tradalab/mediakit 1.0.0
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/chunk-5KXLFDFV.js +62 -0
- package/dist/chunk-5KXLFDFV.js.map +1 -0
- package/dist/index.d.ts +189 -0
- package/dist/index.js +722 -0
- package/dist/index.js.map +1 -0
- package/dist/mediakit.wasm +0 -0
- package/dist/recipe.d.ts +99 -0
- package/dist/recipe.js +21 -0
- package/dist/recipe.js.map +1 -0
- package/dist/wasm_exec.js +575 -0
- package/dist/worker.js +4538 -0
- package/dist/worker.js.map +1 -0
- package/package.json +48 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,722 @@
|
|
|
1
|
+
import {
|
|
2
|
+
NO_EFFECTS,
|
|
3
|
+
coreRecipe,
|
|
4
|
+
needsFace,
|
|
5
|
+
needsMask
|
|
6
|
+
} from "./chunk-5KXLFDFV.js";
|
|
7
|
+
|
|
8
|
+
// src/segmenter.ts
|
|
9
|
+
import { FilesetResolver, ImageSegmenter } from "@mediapipe/tasks-vision";
|
|
10
|
+
var WASM_DIR = "/mediakit/mp";
|
|
11
|
+
var MODEL_URL = "/mediakit/selfie_segmenter.tflite";
|
|
12
|
+
async function createSegmenter(canvas) {
|
|
13
|
+
const fileset = await FilesetResolver.forVisionTasks(WASM_DIR);
|
|
14
|
+
const segmenter = await ImageSegmenter.createFromOptions(fileset, {
|
|
15
|
+
baseOptions: {
|
|
16
|
+
modelAssetPath: MODEL_URL,
|
|
17
|
+
// MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all
|
|
18
|
+
// have. That is why mediakit picked MediaPipe over ONNX Runtime Web at P1: ORT's
|
|
19
|
+
// fast path is WebGPU, which Firefox only has on Windows.
|
|
20
|
+
delegate: "GPU"
|
|
21
|
+
},
|
|
22
|
+
canvas,
|
|
23
|
+
runningMode: "VIDEO",
|
|
24
|
+
// Category mask, not a confidence mask. The values are category INDICES, so they need
|
|
25
|
+
// normalising before they can act as alpha - MaskGain and MaskInvert in `core/graph.go`
|
|
26
|
+
// do that.
|
|
27
|
+
outputCategoryMask: true,
|
|
28
|
+
outputConfidenceMasks: false
|
|
29
|
+
});
|
|
30
|
+
let pending = null;
|
|
31
|
+
const release = () => {
|
|
32
|
+
pending?.close();
|
|
33
|
+
pending = null;
|
|
34
|
+
};
|
|
35
|
+
return {
|
|
36
|
+
segment(frame, timestampMs) {
|
|
37
|
+
release();
|
|
38
|
+
let texture = null;
|
|
39
|
+
segmenter.segmentForVideo(frame, timestampMs, (result) => {
|
|
40
|
+
const mask = result.categoryMask;
|
|
41
|
+
if (mask) texture = mask.getAsWebGLTexture();
|
|
42
|
+
pending = result;
|
|
43
|
+
});
|
|
44
|
+
return texture;
|
|
45
|
+
},
|
|
46
|
+
release,
|
|
47
|
+
close() {
|
|
48
|
+
release();
|
|
49
|
+
segmenter.close();
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/face.ts
|
|
55
|
+
import { FaceLandmarker, FilesetResolver as FilesetResolver2 } from "@mediapipe/tasks-vision";
|
|
56
|
+
var WASM_DIR2 = "/mediakit/mp";
|
|
57
|
+
var MODEL_URL2 = "/mediakit/face_landmarker.task";
|
|
58
|
+
async function createFaceDetector(canvas) {
|
|
59
|
+
const fileset = await FilesetResolver2.forVisionTasks(WASM_DIR2);
|
|
60
|
+
const landmarker = await FaceLandmarker.createFromOptions(fileset, {
|
|
61
|
+
baseOptions: { modelAssetPath: MODEL_URL2, delegate: "GPU" },
|
|
62
|
+
canvas,
|
|
63
|
+
runningMode: "VIDEO",
|
|
64
|
+
// One face: this is the user's own camera. More faces is more inference for a result
|
|
65
|
+
// the layer above can only use one of.
|
|
66
|
+
numFaces: 1,
|
|
67
|
+
// No blendshapes and no transformation matrix - extra work for data nobody reads.
|
|
68
|
+
outputFaceBlendshapes: false,
|
|
69
|
+
outputFacialTransformationMatrixes: false
|
|
70
|
+
});
|
|
71
|
+
return {
|
|
72
|
+
detect(frame, timestampMs, out) {
|
|
73
|
+
const res = landmarker.detectForVideo(frame, timestampMs);
|
|
74
|
+
const lm = res.faceLandmarks?.[0];
|
|
75
|
+
if (!lm || lm.length === 0) return 0;
|
|
76
|
+
const n = Math.min(lm.length * 3, out.length);
|
|
77
|
+
for (let i = 0; i * 3 < n; i++) {
|
|
78
|
+
const p = lm[i];
|
|
79
|
+
out[i * 3] = p.x;
|
|
80
|
+
out[i * 3 + 1] = p.y;
|
|
81
|
+
out[i * 3 + 2] = p.z;
|
|
82
|
+
}
|
|
83
|
+
return n;
|
|
84
|
+
},
|
|
85
|
+
close() {
|
|
86
|
+
landmarker.close();
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/wasm.ts
|
|
92
|
+
var WASM_URL = "/mediakit/mediakit.wasm";
|
|
93
|
+
var EXEC_URL = "/mediakit/wasm_exec.js";
|
|
94
|
+
var execLoaded = null;
|
|
95
|
+
var compiled = null;
|
|
96
|
+
function loadExec() {
|
|
97
|
+
if (execLoaded) return execLoaded;
|
|
98
|
+
execLoaded = (async () => {
|
|
99
|
+
if (globalThis.Go) return;
|
|
100
|
+
const workerLoad = globalThis.importScripts;
|
|
101
|
+
if (typeof workerLoad === "function") {
|
|
102
|
+
workerLoad.call(globalThis, EXEC_URL);
|
|
103
|
+
} else if (typeof document === "undefined") {
|
|
104
|
+
await import(
|
|
105
|
+
/* webpackIgnore: true */
|
|
106
|
+
EXEC_URL
|
|
107
|
+
);
|
|
108
|
+
} else {
|
|
109
|
+
await new Promise((resolve, reject) => {
|
|
110
|
+
const el = document.createElement("script");
|
|
111
|
+
el.src = EXEC_URL;
|
|
112
|
+
el.async = true;
|
|
113
|
+
el.onload = () => resolve();
|
|
114
|
+
el.onerror = () => reject(new Error(`mediakit: cannot load ${EXEC_URL}`));
|
|
115
|
+
document.head.appendChild(el);
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
if (!globalThis.Go) throw new Error("mediakit: wasm_exec.js did not define Go");
|
|
119
|
+
})();
|
|
120
|
+
return execLoaded;
|
|
121
|
+
}
|
|
122
|
+
function compileModule() {
|
|
123
|
+
if (compiled) return compiled;
|
|
124
|
+
compiled = (async () => {
|
|
125
|
+
const res = await fetch(WASM_URL);
|
|
126
|
+
if (!res.ok) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`mediakit: cannot load ${WASM_URL} (HTTP ${res.status}) - the host has to serve this package's dist/ under /mediakit/`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
return WebAssembly.compileStreaming(res);
|
|
132
|
+
})();
|
|
133
|
+
return compiled;
|
|
134
|
+
}
|
|
135
|
+
async function loadCore() {
|
|
136
|
+
await loadExec();
|
|
137
|
+
const mod = await compileModule();
|
|
138
|
+
const Go = globalThis.Go;
|
|
139
|
+
const go = new Go();
|
|
140
|
+
const instance = await WebAssembly.instantiate(mod, go.importObject);
|
|
141
|
+
return new Promise((resolve, reject) => {
|
|
142
|
+
const timer = setTimeout(
|
|
143
|
+
() => reject(new Error("mediakit: core did not attach within 10s")),
|
|
144
|
+
1e4
|
|
145
|
+
);
|
|
146
|
+
globalThis.__mediakitAttach = (core) => {
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
delete globalThis.__mediakitAttach;
|
|
149
|
+
resolve(core);
|
|
150
|
+
};
|
|
151
|
+
void go.run(instance).catch((e) => {
|
|
152
|
+
clearTimeout(timer);
|
|
153
|
+
reject(e instanceof Error ? e : new Error(String(e)));
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
function splitMicros(us) {
|
|
158
|
+
const lo = us >>> 0;
|
|
159
|
+
const hi = Math.floor(us / 2 ** 32);
|
|
160
|
+
return [lo, hi | 0];
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/engine.ts
|
|
164
|
+
var ZERO_STATS = {
|
|
165
|
+
totalMs: 0,
|
|
166
|
+
segMs: 0,
|
|
167
|
+
glCalls: 0,
|
|
168
|
+
segmented: false,
|
|
169
|
+
maskScale: 1,
|
|
170
|
+
workScale: 1,
|
|
171
|
+
cropCX: 0.5,
|
|
172
|
+
cropCY: 0.5,
|
|
173
|
+
cropZoom: 1,
|
|
174
|
+
needsMask: false,
|
|
175
|
+
faceFound: false,
|
|
176
|
+
faceSize: 0,
|
|
177
|
+
needsFace: false
|
|
178
|
+
};
|
|
179
|
+
var Engine = class _Engine {
|
|
180
|
+
canvas;
|
|
181
|
+
gl;
|
|
182
|
+
core;
|
|
183
|
+
background = null;
|
|
184
|
+
// The path the current bitmap came from, so a recipe change that leaves the background
|
|
185
|
+
// alone does not refetch and re-crop it. Without this every slider input event while an
|
|
186
|
+
// image background is on costs a fetch plus two createImageBitmap calls, which is a
|
|
187
|
+
// visible stutter under a dragged finger and the exact case setRecipe exists to make cheap.
|
|
188
|
+
backgroundPath = null;
|
|
189
|
+
closed = false;
|
|
190
|
+
/**
|
|
191
|
+
* The segmenter loads LAZILY - only once a recipe actually needs a person mask.
|
|
192
|
+
*
|
|
193
|
+
* The MediaPipe runtime is ~9 MB of wasm plus a model. Someone who only wants a brighter
|
|
194
|
+
* picture has no reason to download that.
|
|
195
|
+
*/
|
|
196
|
+
segmenter = null;
|
|
197
|
+
segmenterLoading = null;
|
|
198
|
+
/**
|
|
199
|
+
* The landmark detector, also lazy and independent of the segmenter.
|
|
200
|
+
*
|
|
201
|
+
* Its model is ~3.7 MB, fifteen times the segmentation one. Someone who only replaces
|
|
202
|
+
* their background has no reason to download it, and the other way round.
|
|
203
|
+
*/
|
|
204
|
+
face = null;
|
|
205
|
+
faceLoading = null;
|
|
206
|
+
lmBuf = null;
|
|
207
|
+
filter = { kind: "none" };
|
|
208
|
+
effects = NO_EFFECTS;
|
|
209
|
+
// The PREVIOUS frame's measurements, fed to the governor for the next one. The governor
|
|
210
|
+
// steers on past numbers because there is no way to know in advance what a frame will cost.
|
|
211
|
+
prevTotalMs = 0;
|
|
212
|
+
prevSegMs = 0;
|
|
213
|
+
last = { ...ZERO_STATS };
|
|
214
|
+
constructor(canvas, gl, core) {
|
|
215
|
+
this.canvas = canvas;
|
|
216
|
+
this.gl = gl;
|
|
217
|
+
this.core = core;
|
|
218
|
+
}
|
|
219
|
+
/** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */
|
|
220
|
+
static async create(width, height, filter, effects = NO_EFFECTS) {
|
|
221
|
+
const canvas = document.createElement("canvas");
|
|
222
|
+
canvas.width = width;
|
|
223
|
+
canvas.height = height;
|
|
224
|
+
return _Engine.on(canvas, filter, effects);
|
|
225
|
+
}
|
|
226
|
+
static async on(canvas, filter, effects = NO_EFFECTS) {
|
|
227
|
+
const width = canvas.width;
|
|
228
|
+
const height = canvas.height;
|
|
229
|
+
const gl = canvas.getContext("webgl2", {
|
|
230
|
+
alpha: false,
|
|
231
|
+
premultipliedAlpha: false,
|
|
232
|
+
antialias: false,
|
|
233
|
+
depth: false,
|
|
234
|
+
stencil: false
|
|
235
|
+
});
|
|
236
|
+
if (!gl) throw new Error("mediakit: no WebGL2 in this browser");
|
|
237
|
+
let core;
|
|
238
|
+
let engine;
|
|
239
|
+
try {
|
|
240
|
+
core = await loadCore();
|
|
241
|
+
const err = core.init(gl, width, height);
|
|
242
|
+
if (err) throw new Error(`mediakit: ${err}`);
|
|
243
|
+
engine = new _Engine(canvas, gl, core);
|
|
244
|
+
await engine.setRecipe(filter, effects);
|
|
245
|
+
return engine;
|
|
246
|
+
} catch (err) {
|
|
247
|
+
try {
|
|
248
|
+
if (engine) engine.close();
|
|
249
|
+
else {
|
|
250
|
+
core?.close();
|
|
251
|
+
gl.getExtension("WEBGL_lose_context")?.loseContext();
|
|
252
|
+
}
|
|
253
|
+
} catch {
|
|
254
|
+
}
|
|
255
|
+
throw err;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
get outputCanvas() {
|
|
259
|
+
return this.canvas;
|
|
260
|
+
}
|
|
261
|
+
/** Change the recipe without rebuilding the pipeline, so dragging a slider does not flash. */
|
|
262
|
+
async setRecipe(filter, effects = this.effects) {
|
|
263
|
+
if (this.closed) return;
|
|
264
|
+
this.filter = filter;
|
|
265
|
+
this.effects = effects;
|
|
266
|
+
if (filter.kind === "image" && filter.imagePath !== this.backgroundPath) {
|
|
267
|
+
const bmp = await loadBitmap(filter.imagePath, this.canvas.width, this.canvas.height);
|
|
268
|
+
if (this.closed) {
|
|
269
|
+
bmp.close();
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
this.background?.close();
|
|
273
|
+
this.background = bmp;
|
|
274
|
+
this.backgroundPath = filter.imagePath;
|
|
275
|
+
}
|
|
276
|
+
this.core.setRecipe(coreRecipe(filter, effects));
|
|
277
|
+
if (needsMask(filter, effects)) void this.ensureSegmenter();
|
|
278
|
+
if (needsFace(effects)) void this.ensureFace();
|
|
279
|
+
}
|
|
280
|
+
ensureFace() {
|
|
281
|
+
if (this.face || this.closed) return Promise.resolve();
|
|
282
|
+
if (this.faceLoading) return this.faceLoading;
|
|
283
|
+
this.faceLoading = createFaceDetector(this.canvas).then((f) => {
|
|
284
|
+
if (this.closed) {
|
|
285
|
+
f.close();
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
this.face = f;
|
|
289
|
+
this.lmBuf = this.core.faceBuffer();
|
|
290
|
+
}).catch((e) => {
|
|
291
|
+
console.error("mediakit: face detector failed to load", e);
|
|
292
|
+
}).finally(() => {
|
|
293
|
+
this.faceLoading = null;
|
|
294
|
+
});
|
|
295
|
+
return this.faceLoading;
|
|
296
|
+
}
|
|
297
|
+
ensureSegmenter() {
|
|
298
|
+
if (this.segmenter || this.closed) return Promise.resolve();
|
|
299
|
+
if (this.segmenterLoading) return this.segmenterLoading;
|
|
300
|
+
this.segmenterLoading = createSegmenter(this.canvas).then((s) => {
|
|
301
|
+
if (this.closed) {
|
|
302
|
+
s.close();
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
this.segmenter = s;
|
|
306
|
+
}).catch((e) => {
|
|
307
|
+
console.error("mediakit: segmenter failed to load", e);
|
|
308
|
+
}).finally(() => {
|
|
309
|
+
this.segmenterLoading = null;
|
|
310
|
+
});
|
|
311
|
+
return this.segmenterLoading;
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
|
|
315
|
+
* yet, the segmenter is still loading, or the recipe is inactive; the transport must
|
|
316
|
+
* forward the original frame rather than drop it.
|
|
317
|
+
*
|
|
318
|
+
* ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
|
|
319
|
+
* `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
|
|
320
|
+
* MediaPipe. That is what lets the fallback transport (Firefox, and Safari before the
|
|
321
|
+
* worker path) work with NO WebCodecs at all: it passes the `<video>` element straight in.
|
|
322
|
+
*
|
|
323
|
+
* LiveKit's reference implementation requires a `VideoFrame` even on its fallback path, so
|
|
324
|
+
* it constructs one only to destroy it again.
|
|
325
|
+
*/
|
|
326
|
+
render(source, timestampUs) {
|
|
327
|
+
if (this.closed) return false;
|
|
328
|
+
const t0 = performance.now();
|
|
329
|
+
const [lo, hi] = splitMicros(timestampUs);
|
|
330
|
+
const needSeg = this.core.decide(lo, hi, this.prevTotalMs, this.prevSegMs) === 1;
|
|
331
|
+
let mask = null;
|
|
332
|
+
let segMs = 0;
|
|
333
|
+
if (needSeg) {
|
|
334
|
+
if (!this.segmenter) {
|
|
335
|
+
void this.ensureSegmenter();
|
|
336
|
+
} else {
|
|
337
|
+
const s0 = performance.now();
|
|
338
|
+
mask = this.segmenter.segment(source, timestampUs / 1e3);
|
|
339
|
+
segMs = performance.now() - s0;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
if (this.core.decideFace() === 1) {
|
|
343
|
+
if (!this.face) {
|
|
344
|
+
void this.ensureFace();
|
|
345
|
+
} else if (this.lmBuf) {
|
|
346
|
+
const n = this.face.detect(source, timestampUs / 1e3, this.lmBuf);
|
|
347
|
+
this.core.setFace(lo, hi, n);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
const glCalls = this.core.process(source, mask, this.background);
|
|
351
|
+
if (mask) this.segmenter?.release();
|
|
352
|
+
this.prevSegMs = segMs;
|
|
353
|
+
this.prevTotalMs = performance.now() - t0;
|
|
354
|
+
const s = this.core.stats();
|
|
355
|
+
this.last = {
|
|
356
|
+
totalMs: this.prevTotalMs,
|
|
357
|
+
segMs,
|
|
358
|
+
glCalls,
|
|
359
|
+
segmented: needSeg && mask !== null,
|
|
360
|
+
maskScale: s ? s[1] : 1,
|
|
361
|
+
workScale: s ? s[2] : 1,
|
|
362
|
+
cropCX: s ? s[4] : 0.5,
|
|
363
|
+
cropCY: s ? s[5] : 0.5,
|
|
364
|
+
cropZoom: s ? s[6] : 1,
|
|
365
|
+
needsMask: s ? s[7] > 0.5 : false,
|
|
366
|
+
faceFound: s ? s[8] > 0.5 : false,
|
|
367
|
+
faceSize: s ? s[9] : 0,
|
|
368
|
+
needsFace: s ? s[10] > 0.5 : false
|
|
369
|
+
};
|
|
370
|
+
return glCalls > 0;
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* Wrap the output canvas as a new VideoFrame.
|
|
374
|
+
*
|
|
375
|
+
* The timestamp is the SOURCE frame's, carried through unchanged. It is not rebuilt from
|
|
376
|
+
* ticks: whole microseconds cannot represent a frame boundary at 30fps (a frame is
|
|
377
|
+
* 33333.33 us), so every tick-to-microsecond round trip loses information. Ticks are only
|
|
378
|
+
* for the governor and the graph to decide with. See the ToMicros comment in
|
|
379
|
+
* `core/clock.go`.
|
|
380
|
+
*/
|
|
381
|
+
capture(timestampUs) {
|
|
382
|
+
return new VideoFrame(this.canvas, { timestamp: timestampUs, alpha: "discard" });
|
|
383
|
+
}
|
|
384
|
+
close() {
|
|
385
|
+
if (this.closed) return;
|
|
386
|
+
this.closed = true;
|
|
387
|
+
this.segmenter?.close();
|
|
388
|
+
this.segmenter = null;
|
|
389
|
+
this.face?.close();
|
|
390
|
+
this.face = null;
|
|
391
|
+
this.lmBuf = null;
|
|
392
|
+
this.core.close();
|
|
393
|
+
this.background?.close();
|
|
394
|
+
this.background = null;
|
|
395
|
+
this.backgroundPath = null;
|
|
396
|
+
this.gl.getExtension("WEBGL_lose_context")?.loseContext();
|
|
397
|
+
}
|
|
398
|
+
};
|
|
399
|
+
async function decodeImage(path) {
|
|
400
|
+
if (typeof Image === "undefined") {
|
|
401
|
+
const res = await fetch(path);
|
|
402
|
+
if (!res.ok) throw new Error(`mediakit: cannot load background image ${path} (HTTP ${res.status})`);
|
|
403
|
+
const blob = await res.blob();
|
|
404
|
+
try {
|
|
405
|
+
return await createImageBitmap(blob);
|
|
406
|
+
} catch (err) {
|
|
407
|
+
if (blob.type.includes("svg")) {
|
|
408
|
+
throw new Error(
|
|
409
|
+
`mediakit: cannot decode the SVG background ${path} off the main thread - give this transport a raster image`
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
throw err;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
const img = new Image();
|
|
416
|
+
img.crossOrigin = "anonymous";
|
|
417
|
+
await new Promise((resolve, reject) => {
|
|
418
|
+
img.onload = () => resolve();
|
|
419
|
+
img.onerror = () => reject(new Error(`mediakit: cannot load background image ${path}`));
|
|
420
|
+
img.src = path;
|
|
421
|
+
});
|
|
422
|
+
if (!img.naturalWidth || !img.naturalHeight) {
|
|
423
|
+
throw new Error(
|
|
424
|
+
`mediakit: background image ${path} has no intrinsic size - an SVG needs width and height, a viewBox alone is not enough`
|
|
425
|
+
);
|
|
426
|
+
}
|
|
427
|
+
return createImageBitmap(img);
|
|
428
|
+
}
|
|
429
|
+
async function loadBitmap(path, w, h) {
|
|
430
|
+
const src = await decodeImage(path);
|
|
431
|
+
if (src.width * h === src.height * w) return src;
|
|
432
|
+
const scale = Math.max(w / src.width, h / src.height);
|
|
433
|
+
const cw = Math.min(src.width, Math.round(w / scale));
|
|
434
|
+
const ch = Math.min(src.height, Math.round(h / scale));
|
|
435
|
+
const out = await createImageBitmap(
|
|
436
|
+
src,
|
|
437
|
+
Math.round((src.width - cw) / 2),
|
|
438
|
+
Math.round((src.height - ch) / 2),
|
|
439
|
+
cw,
|
|
440
|
+
ch,
|
|
441
|
+
{ resizeWidth: w, resizeHeight: h, resizeQuality: "high" }
|
|
442
|
+
);
|
|
443
|
+
src.close();
|
|
444
|
+
return out;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// src/pipeline.ts
|
|
448
|
+
var WORKER_READY_MS = 8e3;
|
|
449
|
+
function hasInsertableStreams() {
|
|
450
|
+
return typeof window !== "undefined" && "MediaStreamTrackProcessor" in window && "MediaStreamTrackGenerator" in window;
|
|
451
|
+
}
|
|
452
|
+
function mediakitSupported() {
|
|
453
|
+
if (typeof window === "undefined") return false;
|
|
454
|
+
if (typeof WebAssembly === "undefined") return false;
|
|
455
|
+
const probe = document.createElement("canvas");
|
|
456
|
+
if (!probe.getContext("webgl2")) return false;
|
|
457
|
+
return hasInsertableStreams() || "captureStream" in HTMLCanvasElement.prototype;
|
|
458
|
+
}
|
|
459
|
+
var VideoPipeline = class {
|
|
460
|
+
processedTrack;
|
|
461
|
+
filter;
|
|
462
|
+
effects;
|
|
463
|
+
engine = null;
|
|
464
|
+
transport = "insertable";
|
|
465
|
+
// insertable path
|
|
466
|
+
abort = null;
|
|
467
|
+
// worker path
|
|
468
|
+
worker = null;
|
|
469
|
+
workerStats = null;
|
|
470
|
+
// canvas path
|
|
471
|
+
video = null;
|
|
472
|
+
rvfcHandle = 0;
|
|
473
|
+
stopped = false;
|
|
474
|
+
constructor(filter, effects = NO_EFFECTS) {
|
|
475
|
+
this.filter = filter;
|
|
476
|
+
this.effects = effects;
|
|
477
|
+
}
|
|
478
|
+
get stats() {
|
|
479
|
+
return this.transport === "worker" ? this.workerStats : this.engine?.last ?? null;
|
|
480
|
+
}
|
|
481
|
+
get transportName() {
|
|
482
|
+
return this.transport;
|
|
483
|
+
}
|
|
484
|
+
/** Take over `source` and publish the result on {@link processedTrack}. */
|
|
485
|
+
async start(source) {
|
|
486
|
+
const settings = source.getSettings();
|
|
487
|
+
const width = settings.width ?? 1280;
|
|
488
|
+
const height = settings.height ?? 720;
|
|
489
|
+
this.stopped = false;
|
|
490
|
+
if (hasInsertableStreams() && typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
|
|
491
|
+
try {
|
|
492
|
+
await this.startWorker(source, width, height);
|
|
493
|
+
this.transport = "worker";
|
|
494
|
+
return;
|
|
495
|
+
} catch (e) {
|
|
496
|
+
this.teardownWorker();
|
|
497
|
+
console.warn("mediakit: worker unusable, falling back to the main thread", e);
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
this.engine = await Engine.create(width, height, this.filter, this.effects);
|
|
501
|
+
this.transport = hasInsertableStreams() ? "insertable" : "canvas";
|
|
502
|
+
if (this.transport === "insertable") {
|
|
503
|
+
this.startInsertable(source);
|
|
504
|
+
} else {
|
|
505
|
+
await this.startCanvas(source, settings.frameRate ?? 30);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/** Swap the background in place - no pipeline rebuild, so the picture does not flash. */
|
|
509
|
+
async switchTo(filter) {
|
|
510
|
+
this.filter = filter;
|
|
511
|
+
await this.pushRecipe();
|
|
512
|
+
}
|
|
513
|
+
/** Change the effects outside the background. */
|
|
514
|
+
async setEffects(effects) {
|
|
515
|
+
this.effects = effects;
|
|
516
|
+
await this.pushRecipe();
|
|
517
|
+
}
|
|
518
|
+
async pushRecipe() {
|
|
519
|
+
if (this.worker) {
|
|
520
|
+
this.send({ t: "recipe", filter: this.filter, effects: this.effects });
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
await this.engine?.setRecipe(this.filter, this.effects);
|
|
524
|
+
}
|
|
525
|
+
async stop() {
|
|
526
|
+
this.stopped = true;
|
|
527
|
+
this.abort?.abort();
|
|
528
|
+
this.abort = null;
|
|
529
|
+
if (this.rvfcHandle && this.video) {
|
|
530
|
+
this.video.cancelVideoFrameCallback?.(this.rvfcHandle);
|
|
531
|
+
}
|
|
532
|
+
this.rvfcHandle = 0;
|
|
533
|
+
if (this.video) {
|
|
534
|
+
this.video.pause();
|
|
535
|
+
this.video.srcObject = null;
|
|
536
|
+
this.video.remove();
|
|
537
|
+
this.video = null;
|
|
538
|
+
}
|
|
539
|
+
this.teardownWorker();
|
|
540
|
+
this.processedTrack?.stop();
|
|
541
|
+
this.processedTrack = void 0;
|
|
542
|
+
this.engine?.close();
|
|
543
|
+
this.engine = null;
|
|
544
|
+
}
|
|
545
|
+
// ── worker ───────────────────────────────────────────────────────────────────────
|
|
546
|
+
send(m, transfer = []) {
|
|
547
|
+
this.worker?.postMessage(m, transfer);
|
|
548
|
+
}
|
|
549
|
+
teardownWorker() {
|
|
550
|
+
if (!this.worker) return;
|
|
551
|
+
this.send({ t: "stop" });
|
|
552
|
+
this.worker.terminate();
|
|
553
|
+
this.worker = null;
|
|
554
|
+
this.workerStats = null;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Give the worker the frame STREAMS, and keep the track on this thread.
|
|
558
|
+
*
|
|
559
|
+
* ── Why not transfer the track ───────────────────────────────────────────────────
|
|
560
|
+
* The obvious shape is to transfer the camera track into the worker and let it build its
|
|
561
|
+
* own processor and generator there. It does not work, for two independent reasons, and
|
|
562
|
+
* both were measured on 2026-09-26:
|
|
563
|
+
*
|
|
564
|
+
* 1. Chrome 154 does not treat a MediaStreamTrack as transferable at all:
|
|
565
|
+
* `DataCloneError: Value at index 0 does not have a transferable type`. So the whole
|
|
566
|
+
* path fell back to the main thread on every start, on the one browser that has all
|
|
567
|
+
* the APIs it needs.
|
|
568
|
+
* 2. On a browser where the transfer DID succeed it would be worse than useless. A
|
|
569
|
+
* transfer detaches the main-thread object, and a host keeps using it: LiveKit's
|
|
570
|
+
* `setProcessor` calls `attachToElement(_mediaStreamTrack, ...)`, `detachTrack` and
|
|
571
|
+
* registers an `ended` listener on that same object AFTER `init()` returns. Stealing
|
|
572
|
+
* it breaks the camera, not just the effect.
|
|
573
|
+
*
|
|
574
|
+
* A ReadableStream and a WritableStream are both transferable, so the split below moves
|
|
575
|
+
* every frame into the worker with no copy while ownership of the track never leaves this
|
|
576
|
+
* thread. The Engine, MediaPipe and the whole pass chain still run off the main thread,
|
|
577
|
+
* which was the point.
|
|
578
|
+
*
|
|
579
|
+
* The cost: this needs `MediaStreamTrackProcessor` and `MediaStreamTrackGenerator` HERE,
|
|
580
|
+
* so it is the Chrome dialect. A browser that only has them inside a worker (Safari) does
|
|
581
|
+
* not get this path and stays on the canvas transport until someone can test that.
|
|
582
|
+
*/
|
|
583
|
+
startWorker(source, width, height) {
|
|
584
|
+
const processor = new MediaStreamTrackProcessor({ track: source });
|
|
585
|
+
const generator = new MediaStreamTrackGenerator({
|
|
586
|
+
kind: "video",
|
|
587
|
+
signalTarget: source
|
|
588
|
+
});
|
|
589
|
+
const worker = new Worker("/mediakit/worker.js");
|
|
590
|
+
this.worker = worker;
|
|
591
|
+
return new Promise((resolve, reject) => {
|
|
592
|
+
let settled = false;
|
|
593
|
+
const fail = (err) => {
|
|
594
|
+
if (settled) return;
|
|
595
|
+
settled = true;
|
|
596
|
+
clearTimeout(timer);
|
|
597
|
+
generator.stop();
|
|
598
|
+
reject(err);
|
|
599
|
+
};
|
|
600
|
+
const timer = setTimeout(
|
|
601
|
+
() => fail(new Error(`mediakit: worker silent for more than ${WORKER_READY_MS}ms`)),
|
|
602
|
+
WORKER_READY_MS
|
|
603
|
+
);
|
|
604
|
+
worker.onerror = (e) => fail(new Error(e.message || "mediakit: worker failed to load"));
|
|
605
|
+
worker.onmessage = (e) => {
|
|
606
|
+
const m = e.data;
|
|
607
|
+
if (m.t === "stats") {
|
|
608
|
+
this.workerStats = m.stats;
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
if (m.t === "error") {
|
|
612
|
+
if (settled) {
|
|
613
|
+
console.error("mediakit: worker failed after start", m.message);
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
fail(new Error(m.message));
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
settled = true;
|
|
620
|
+
clearTimeout(timer);
|
|
621
|
+
this.processedTrack = generator;
|
|
622
|
+
resolve();
|
|
623
|
+
};
|
|
624
|
+
try {
|
|
625
|
+
this.send(
|
|
626
|
+
{
|
|
627
|
+
t: "start",
|
|
628
|
+
readable: processor.readable,
|
|
629
|
+
writable: generator.writable,
|
|
630
|
+
width,
|
|
631
|
+
height,
|
|
632
|
+
filter: this.filter,
|
|
633
|
+
effects: this.effects
|
|
634
|
+
},
|
|
635
|
+
[processor.readable, generator.writable]
|
|
636
|
+
);
|
|
637
|
+
} catch (err) {
|
|
638
|
+
fail(err instanceof Error ? err : new Error(String(err)));
|
|
639
|
+
}
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
// ── insertable ───────────────────────────────────────────────────────────────────
|
|
643
|
+
startInsertable(source) {
|
|
644
|
+
const engine = this.engine;
|
|
645
|
+
const processor = new MediaStreamTrackProcessor({
|
|
646
|
+
track: source
|
|
647
|
+
});
|
|
648
|
+
const generator = new MediaStreamTrackGenerator({
|
|
649
|
+
kind: "video",
|
|
650
|
+
signalTarget: source
|
|
651
|
+
});
|
|
652
|
+
const transform = new TransformStream({
|
|
653
|
+
transform: (frame, controller) => {
|
|
654
|
+
try {
|
|
655
|
+
if (engine.render(frame, frame.timestamp)) {
|
|
656
|
+
controller.enqueue(engine.capture(frame.timestamp));
|
|
657
|
+
} else {
|
|
658
|
+
controller.enqueue(frame);
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
} catch (e) {
|
|
662
|
+
console.error("mediakit: frame processing failed", e);
|
|
663
|
+
controller.enqueue(frame);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
frame.close();
|
|
667
|
+
}
|
|
668
|
+
});
|
|
669
|
+
this.abort = new AbortController();
|
|
670
|
+
this.processedTrack = generator;
|
|
671
|
+
processor.readable.pipeThrough(transform, { signal: this.abort.signal }).pipeTo(generator.writable, { signal: this.abort.signal }).catch((e) => {
|
|
672
|
+
if (e instanceof DOMException && e.name === "AbortError") return;
|
|
673
|
+
if (!this.stopped) console.error("mediakit: pipe broke", e);
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
// ── canvas ───────────────────────────────────────────────────────────────────────
|
|
677
|
+
async startCanvas(source, fps) {
|
|
678
|
+
const engine = this.engine;
|
|
679
|
+
const video = document.createElement("video");
|
|
680
|
+
video.muted = true;
|
|
681
|
+
video.playsInline = true;
|
|
682
|
+
video.style.position = "fixed";
|
|
683
|
+
video.style.opacity = "0";
|
|
684
|
+
video.style.pointerEvents = "none";
|
|
685
|
+
video.width = 1;
|
|
686
|
+
video.height = 1;
|
|
687
|
+
video.srcObject = new MediaStream([source]);
|
|
688
|
+
document.body.appendChild(video);
|
|
689
|
+
this.video = video;
|
|
690
|
+
await video.play();
|
|
691
|
+
const out = engine.outputCanvas;
|
|
692
|
+
if (!(out instanceof HTMLCanvasElement)) {
|
|
693
|
+
throw new Error("mediakit: the canvas transport needs an HTMLCanvasElement");
|
|
694
|
+
}
|
|
695
|
+
const stream = out.captureStream(fps);
|
|
696
|
+
this.processedTrack = stream.getVideoTracks()[0];
|
|
697
|
+
const pump = (_now, meta) => {
|
|
698
|
+
if (this.stopped || !this.engine) return;
|
|
699
|
+
try {
|
|
700
|
+
this.engine.render(video, Math.round(meta.mediaTime * 1e6));
|
|
701
|
+
} catch (e) {
|
|
702
|
+
console.error("mediakit: frame processing failed", e);
|
|
703
|
+
}
|
|
704
|
+
this.rvfcHandle = video.requestVideoFrameCallback(pump);
|
|
705
|
+
};
|
|
706
|
+
if (typeof video.requestVideoFrameCallback !== "function") {
|
|
707
|
+
throw new Error(
|
|
708
|
+
"mediakit: browser has neither requestVideoFrameCallback nor insertable streams"
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
this.rvfcHandle = video.requestVideoFrameCallback(pump);
|
|
712
|
+
}
|
|
713
|
+
};
|
|
714
|
+
export {
|
|
715
|
+
Engine,
|
|
716
|
+
NO_EFFECTS,
|
|
717
|
+
VideoPipeline,
|
|
718
|
+
mediakitSupported,
|
|
719
|
+
needsFace,
|
|
720
|
+
needsMask
|
|
721
|
+
};
|
|
722
|
+
//# sourceMappingURL=index.js.map
|