@tradalab/mediakit 2.9.1 → 2.10.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/README.md +29 -0
- package/dist/detect-worker.js +1138 -12
- package/dist/detect-worker.js.map +1 -1
- package/dist/index.d.ts +4 -5
- package/dist/index.js +186 -133
- package/dist/index.js.map +1 -1
- package/dist/worker.js +1193 -60
- package/dist/worker.js.map +1 -1
- package/package.json +4 -1
package/dist/index.js
CHANGED
|
@@ -23,6 +23,7 @@ import {
|
|
|
23
23
|
} from "./chunk-BMIOUOT3.js";
|
|
24
24
|
import {
|
|
25
25
|
ASSETS,
|
|
26
|
+
ASSET_BASE,
|
|
26
27
|
assetUrl
|
|
27
28
|
} from "./chunk-T7YS2EQE.js";
|
|
28
29
|
|
|
@@ -31,16 +32,92 @@ import { ImageSegmenter } from "@mediapipe/tasks-vision";
|
|
|
31
32
|
|
|
32
33
|
// src/mp.ts
|
|
33
34
|
import { FilesetResolver } from "@mediapipe/tasks-vision";
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
35
|
+
|
|
36
|
+
// src/res.ts
|
|
37
|
+
import { connectAssets, createAssets, isAssetsMessage } from "@tradalab/tskit/assets";
|
|
38
|
+
var RES_NAME = "mediakit";
|
|
39
|
+
var RES_VERSION = true ? "2.10.0" : "dev";
|
|
40
|
+
var MP_RUNTIME = ["vision_wasm_internal.js", "vision_wasm_internal.wasm", "vision_wasm_nosimd_internal.js", "vision_wasm_nosimd_internal.wasm"];
|
|
41
|
+
var NOT_FETCHED = /* @__PURE__ */ new Set(["worker.js", "detect-worker.js", "NOTICE"]);
|
|
42
|
+
var TYPES = {
|
|
43
|
+
js: "text/javascript",
|
|
44
|
+
mjs: "text/javascript",
|
|
45
|
+
wasm: "application/wasm",
|
|
46
|
+
png: "image/png"
|
|
39
47
|
};
|
|
48
|
+
function typeOf(path) {
|
|
49
|
+
return TYPES[path.slice(path.lastIndexOf(".") + 1)] ?? "application/octet-stream";
|
|
50
|
+
}
|
|
51
|
+
function resourceManifest() {
|
|
52
|
+
const specs = [];
|
|
53
|
+
for (const a of ASSETS) {
|
|
54
|
+
if (a.debug || a.path.endsWith("/") || NOT_FETCHED.has(a.path)) continue;
|
|
55
|
+
specs.push({ id: a.path, url: assetUrl(a.path), type: typeOf(a.path), group: a.part });
|
|
56
|
+
}
|
|
57
|
+
for (const f of MP_RUNTIME) specs.push({ id: `mp/${f}`, url: assetUrl(`mp/${f}`), type: typeOf(f), group: "mp" });
|
|
58
|
+
return specs;
|
|
59
|
+
}
|
|
60
|
+
var source = null;
|
|
61
|
+
var urls = /* @__PURE__ */ new Map();
|
|
62
|
+
function resources() {
|
|
63
|
+
if (!source) {
|
|
64
|
+
const owner = createAssets({ manifest: resourceManifest(), name: RES_NAME, version: RES_VERSION, fetch: (u, i) => fetch(u, i) });
|
|
65
|
+
owner.purgeOld().catch((err) => console.warn("mediakit: could not delete the files of older versions", err));
|
|
66
|
+
source = owner;
|
|
67
|
+
}
|
|
68
|
+
return source;
|
|
69
|
+
}
|
|
70
|
+
function serveResources(port) {
|
|
71
|
+
return resources().serve(port);
|
|
72
|
+
}
|
|
73
|
+
function resourceId(pathOrUrl) {
|
|
74
|
+
return pathOrUrl.startsWith(ASSET_BASE) ? pathOrUrl.slice(ASSET_BASE.length) : pathOrUrl;
|
|
75
|
+
}
|
|
76
|
+
function resourceBytes(id, signal) {
|
|
77
|
+
return resources().bytes(id, signal);
|
|
78
|
+
}
|
|
79
|
+
function resourceUrl(id) {
|
|
80
|
+
let p = urls.get(id);
|
|
81
|
+
if (!p) {
|
|
82
|
+
p = resourceBytes(id).then((b) => URL.createObjectURL(new Blob([b], { type: typeOf(id) })));
|
|
83
|
+
p.catch(() => urls.delete(id));
|
|
84
|
+
urls.set(id, p);
|
|
85
|
+
}
|
|
86
|
+
return p;
|
|
87
|
+
}
|
|
88
|
+
async function preloadResources(ids, onProgress) {
|
|
89
|
+
const src = resources();
|
|
90
|
+
if ("preload" in src) return src.preload(ids, onProgress);
|
|
91
|
+
await Promise.all(ids.map((id) => src.bytes(id).catch(() => void 0)));
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
async function clearCachedAssets() {
|
|
95
|
+
const src = resources();
|
|
96
|
+
if ("clear" in src) await src.clear();
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/mp.ts
|
|
100
|
+
var MP_DIR = assetUrl("mp");
|
|
40
101
|
var LOAD_MS = 6e4;
|
|
41
102
|
var fileset = null;
|
|
103
|
+
var MODEL_ID = {
|
|
104
|
+
person: "selfie_segmenter.tflite",
|
|
105
|
+
classes: "selfie_multiclass_256x256.tflite",
|
|
106
|
+
face: "face_landmarker.task"
|
|
107
|
+
};
|
|
108
|
+
function modelBytes(model) {
|
|
109
|
+
return resourceBytes(MODEL_ID[model]);
|
|
110
|
+
}
|
|
111
|
+
async function runtimeIds() {
|
|
112
|
+
const base = await FilesetResolver.forVisionTasks(MP_DIR);
|
|
113
|
+
return [resourceId(base.wasmLoaderPath), resourceId(base.wasmBinaryPath)];
|
|
114
|
+
}
|
|
42
115
|
function visionFileset() {
|
|
43
|
-
fileset ??=
|
|
116
|
+
fileset ??= (async () => {
|
|
117
|
+
const base = await FilesetResolver.forVisionTasks(MP_DIR);
|
|
118
|
+
const [loader, binary] = await Promise.all([resourceUrl(resourceId(base.wasmLoaderPath)), resourceUrl(resourceId(base.wasmBinaryPath))]);
|
|
119
|
+
return { ...base, wasmLoaderPath: loader, wasmBinaryPath: binary };
|
|
120
|
+
})().catch((e) => {
|
|
44
121
|
fileset = null;
|
|
45
122
|
throw e;
|
|
46
123
|
});
|
|
@@ -77,70 +154,32 @@ function withTimeout(p, ms, what, late) {
|
|
|
77
154
|
);
|
|
78
155
|
});
|
|
79
156
|
}
|
|
80
|
-
var PROGRESS_MS = 100;
|
|
81
157
|
async function preloadDetectors(parts = { person: true, classes: true, face: true }, onProgress) {
|
|
82
|
-
const
|
|
158
|
+
const ids = [];
|
|
83
159
|
if (parts.cover) {
|
|
84
|
-
for (const a of ASSETS) if (a.part === "cover")
|
|
160
|
+
for (const a of ASSETS) if (a.part === "cover") ids.push(a.path);
|
|
85
161
|
}
|
|
86
162
|
if (parts.person || parts.classes || parts.face) {
|
|
87
163
|
try {
|
|
88
|
-
|
|
89
|
-
urls.push(fs.wasmBinaryPath, fs.wasmLoaderPath);
|
|
90
|
-
for (const k of ["person", "classes", "face"]) if (parts[k]) urls.push(MODEL_URL[k]);
|
|
164
|
+
ids.push(...await runtimeIds());
|
|
91
165
|
} catch {
|
|
92
166
|
}
|
|
167
|
+
for (const k of ["person", "classes", "face"]) if (parts[k]) ids.push(MODEL_ID[k]);
|
|
93
168
|
}
|
|
94
|
-
const p = { loaded: 0, total: 0, done: 0, files: urls.length };
|
|
95
|
-
const sizes = urls.map(() => void 0);
|
|
96
|
-
let told = 0;
|
|
97
169
|
let broken = false;
|
|
98
|
-
const tell = (
|
|
99
|
-
if (
|
|
100
|
-
const now2 = performance.now();
|
|
101
|
-
if (!force && now2 - told < PROGRESS_MS) return;
|
|
102
|
-
told = now2;
|
|
103
|
-
const known = sizes.every((n) => n !== null && n !== void 0);
|
|
104
|
-
const total = known ? sizes.reduce((a, n) => a + (n ?? 0), 0) : 0;
|
|
170
|
+
const tell = onProgress ? (p) => {
|
|
171
|
+
if (broken) return;
|
|
105
172
|
try {
|
|
106
|
-
onProgress({
|
|
173
|
+
onProgress({ loaded: p.loaded, total: p.total, done: p.done, files: p.items });
|
|
107
174
|
} catch (e) {
|
|
108
175
|
broken = true;
|
|
109
176
|
console.error("mediakit: onProgress threw, no more progress from this preload", e);
|
|
110
177
|
}
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
try {
|
|
117
|
-
const r = await fetch(u, { priority: "low" });
|
|
118
|
-
if (!r.ok) {
|
|
119
|
-
sizes[i] = 0;
|
|
120
|
-
await r.body?.cancel();
|
|
121
|
-
} else {
|
|
122
|
-
const encoding = r.headers.get("content-encoding");
|
|
123
|
-
const length = Number(r.headers.get("content-length"));
|
|
124
|
-
sizes[i] = (!encoding || encoding === "identity") && length > 0 ? length : null;
|
|
125
|
-
const reader = r.body?.getReader();
|
|
126
|
-
if (reader) {
|
|
127
|
-
for (; ; ) {
|
|
128
|
-
const { done, value } = await reader.read();
|
|
129
|
-
if (done) break;
|
|
130
|
-
got += value.byteLength;
|
|
131
|
-
p.loaded += value.byteLength;
|
|
132
|
-
tell(false);
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
} catch {
|
|
137
|
-
p.loaded -= got;
|
|
138
|
-
sizes[i] = 0;
|
|
139
|
-
}
|
|
140
|
-
p.done++;
|
|
141
|
-
tell(true);
|
|
142
|
-
})
|
|
143
|
-
);
|
|
178
|
+
} : void 0;
|
|
179
|
+
try {
|
|
180
|
+
await preloadResources(ids, tell);
|
|
181
|
+
} catch {
|
|
182
|
+
}
|
|
144
183
|
}
|
|
145
184
|
|
|
146
185
|
// src/mp-clock.ts
|
|
@@ -164,7 +203,7 @@ async function createSegmenter(canvas, model = "person") {
|
|
|
164
203
|
const fileset2 = await visionFileset();
|
|
165
204
|
const segmenter = await ImageSegmenter.createFromOptions(fileset2, {
|
|
166
205
|
baseOptions: {
|
|
167
|
-
|
|
206
|
+
modelAssetBuffer: await modelBytes(model),
|
|
168
207
|
// MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all
|
|
169
208
|
// have. That is why mediakit picked MediaPipe over ONNX Runtime Web at P1: ORT's
|
|
170
209
|
// fast path is WebGPU, which Firefox only has on Windows.
|
|
@@ -223,7 +262,7 @@ function faceBox(lm, at) {
|
|
|
223
262
|
async function createFaceDetector(canvas, maxFaces, delegate = "GPU", mode = "VIDEO") {
|
|
224
263
|
const fileset2 = await visionFileset();
|
|
225
264
|
const landmarker = await FaceLandmarker.createFromOptions(fileset2, {
|
|
226
|
-
baseOptions: {
|
|
265
|
+
baseOptions: { modelAssetBuffer: await modelBytes("face"), delegate },
|
|
227
266
|
canvas,
|
|
228
267
|
runningMode: mode,
|
|
229
268
|
// As many as the core tracks: one landmark pass returns them all, so the cost of a second
|
|
@@ -262,11 +301,15 @@ var DetectWorker = class {
|
|
|
262
301
|
constructor(on) {
|
|
263
302
|
this.on = on;
|
|
264
303
|
this.worker = new Worker(DETECT_WORKER_URL);
|
|
304
|
+
this.unserve = serveResources(this.worker);
|
|
265
305
|
this.worker.onerror = (e) => this.failAll(e.message || "detect worker failed to load");
|
|
266
|
-
this.worker.onmessage = (e) =>
|
|
306
|
+
this.worker.onmessage = (e) => {
|
|
307
|
+
if (!isAssetsMessage(e.data)) this.receive(e.data);
|
|
308
|
+
};
|
|
267
309
|
}
|
|
268
310
|
on;
|
|
269
311
|
worker;
|
|
312
|
+
unserve;
|
|
270
313
|
ready = /* @__PURE__ */ new Map();
|
|
271
314
|
up = /* @__PURE__ */ new Set();
|
|
272
315
|
busy = /* @__PURE__ */ new Set();
|
|
@@ -295,6 +338,7 @@ var DetectWorker = class {
|
|
|
295
338
|
}
|
|
296
339
|
close() {
|
|
297
340
|
this.send({ t: "close" });
|
|
341
|
+
this.unserve();
|
|
298
342
|
this.worker = null;
|
|
299
343
|
for (const kind of [...this.ready.keys()]) this.settle(kind, new Error("closed"));
|
|
300
344
|
this.up.clear();
|
|
@@ -349,6 +393,7 @@ var DetectWorker = class {
|
|
|
349
393
|
}
|
|
350
394
|
failAll(reason) {
|
|
351
395
|
this.worker?.terminate();
|
|
396
|
+
this.unserve();
|
|
352
397
|
this.worker = null;
|
|
353
398
|
for (const kind of [...this.ready.keys()]) this.settle(kind, new Error(reason));
|
|
354
399
|
for (const kind of [...this.up]) this.fail(kind, reason);
|
|
@@ -367,18 +412,21 @@ function loadExec() {
|
|
|
367
412
|
if (execLoaded) return execLoaded;
|
|
368
413
|
execLoaded = (async () => {
|
|
369
414
|
if (globalThis.Go) return;
|
|
415
|
+
const execUrl = await resourceUrl("wasm_exec.js").catch((err) => {
|
|
416
|
+
throw new Error(`mediakit: cannot load ${EXEC_URL} (${err instanceof Error ? err.message : String(err)})`);
|
|
417
|
+
});
|
|
370
418
|
const workerLoad = globalThis.importScripts;
|
|
371
419
|
if (typeof workerLoad === "function") {
|
|
372
|
-
workerLoad.call(globalThis,
|
|
420
|
+
workerLoad.call(globalThis, execUrl);
|
|
373
421
|
} else if (typeof document === "undefined") {
|
|
374
422
|
await import(
|
|
375
423
|
/* webpackIgnore: true */
|
|
376
|
-
|
|
424
|
+
execUrl
|
|
377
425
|
);
|
|
378
426
|
} else {
|
|
379
427
|
await new Promise((resolve, reject) => {
|
|
380
428
|
const el = document.createElement("script");
|
|
381
|
-
el.src =
|
|
429
|
+
el.src = execUrl;
|
|
382
430
|
el.async = true;
|
|
383
431
|
el.onload = () => resolve();
|
|
384
432
|
el.onerror = () => reject(new Error(`mediakit: cannot load ${EXEC_URL}`));
|
|
@@ -392,13 +440,12 @@ function loadExec() {
|
|
|
392
440
|
function compileModule() {
|
|
393
441
|
if (compiled) return compiled;
|
|
394
442
|
compiled = (async () => {
|
|
395
|
-
const
|
|
396
|
-
if (!res.ok) {
|
|
443
|
+
const bytes = await resourceBytes("mediakit.wasm").catch((err) => {
|
|
397
444
|
throw new Error(
|
|
398
|
-
`mediakit: cannot load ${WASM_URL} (
|
|
445
|
+
`mediakit: cannot load ${WASM_URL} (${err instanceof Error ? err.message : String(err)}) - the host has to serve this package's dist/ under /mediakit/`
|
|
399
446
|
);
|
|
400
|
-
}
|
|
401
|
-
return WebAssembly.
|
|
447
|
+
});
|
|
448
|
+
return WebAssembly.compile(bytes);
|
|
402
449
|
})();
|
|
403
450
|
return compiled;
|
|
404
451
|
}
|
|
@@ -626,10 +673,10 @@ function gpuName(gl) {
|
|
|
626
673
|
const name = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "unknown");
|
|
627
674
|
return gl.isContextLost() ? `${name}, context lost` : name;
|
|
628
675
|
}
|
|
629
|
-
function sourceSize(
|
|
630
|
-
if (
|
|
631
|
-
if (typeof HTMLVideoElement !== "undefined" &&
|
|
632
|
-
const s =
|
|
676
|
+
function sourceSize(source2) {
|
|
677
|
+
if (source2 instanceof VideoFrame) return [source2.displayWidth, source2.displayHeight];
|
|
678
|
+
if (typeof HTMLVideoElement !== "undefined" && source2 instanceof HTMLVideoElement) return [source2.videoWidth, source2.videoHeight];
|
|
679
|
+
const s = source2;
|
|
633
680
|
return [s.width, s.height];
|
|
634
681
|
}
|
|
635
682
|
function tileGrid(sw, sh) {
|
|
@@ -917,7 +964,7 @@ var Engine = class _Engine {
|
|
|
917
964
|
}
|
|
918
965
|
if (effects.whitenStyle === "pink" && this.skinLutState === "none") {
|
|
919
966
|
this.skinLutState = "loading";
|
|
920
|
-
|
|
967
|
+
resourceBytes("whiten_pink.png").then((b) => createImageBitmap(new Blob([b], { type: "image/png" }), { colorSpaceConversion: "none", premultiplyAlpha: "none" })).then((bmp) => {
|
|
921
968
|
if (this.closed) {
|
|
922
969
|
bmp.close();
|
|
923
970
|
return;
|
|
@@ -1145,7 +1192,7 @@ var Engine = class _Engine {
|
|
|
1145
1192
|
* Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
|
|
1146
1193
|
* detection drains Chrome's few capture buffers and throttles the camera itself.
|
|
1147
1194
|
*/
|
|
1148
|
-
requestRemote(want,
|
|
1195
|
+
requestRemote(want, source2, timestampUs) {
|
|
1149
1196
|
const lockstep = want === "face" && this.syncing();
|
|
1150
1197
|
const kind = lockstep ? this.freeFaceWorker() : want;
|
|
1151
1198
|
if (!kind) return;
|
|
@@ -1156,16 +1203,16 @@ var Engine = class _Engine {
|
|
|
1156
1203
|
let followed = null;
|
|
1157
1204
|
let scanned = null;
|
|
1158
1205
|
try {
|
|
1159
|
-
const copyable =
|
|
1206
|
+
const copyable = source2 instanceof VideoFrame || source2 instanceof OffscreenCanvas;
|
|
1160
1207
|
if (copyable) {
|
|
1161
|
-
this.srcW =
|
|
1162
|
-
this.srcH =
|
|
1208
|
+
this.srcW = source2 instanceof VideoFrame ? source2.displayWidth : source2.width;
|
|
1209
|
+
this.srcH = source2 instanceof VideoFrame ? source2.displayHeight : source2.height;
|
|
1163
1210
|
}
|
|
1164
1211
|
if (copyable && (kind === "face" || kind === "faceExtra")) {
|
|
1165
|
-
followed = this.followCopy(
|
|
1166
|
-
if (!followed) scanned = this.scanCopy(
|
|
1212
|
+
followed = this.followCopy(source2, timestampUs);
|
|
1213
|
+
if (!followed) scanned = this.scanCopy(source2, timestampUs);
|
|
1167
1214
|
}
|
|
1168
|
-
frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(
|
|
1215
|
+
frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(source2, timestampUs) : source2), {
|
|
1169
1216
|
timestamp: timestampUs
|
|
1170
1217
|
});
|
|
1171
1218
|
} catch {
|
|
@@ -1178,11 +1225,11 @@ var Engine = class _Engine {
|
|
|
1178
1225
|
if (kind !== "face" && kind !== "faceExtra" && this.remoteMaskKind() === "merged") this.noteThumb(timestampUs);
|
|
1179
1226
|
} else if (followed || scanned) this.faceCrops.delete(timestampUs);
|
|
1180
1227
|
}
|
|
1181
|
-
followCopy(
|
|
1228
|
+
followCopy(source2, timestampUs) {
|
|
1182
1229
|
const box = this.followBox;
|
|
1183
1230
|
if (!box || timestampUs - this.followTs > FOLLOW_STALE_US) return null;
|
|
1184
|
-
const sw =
|
|
1185
|
-
const sh =
|
|
1231
|
+
const sw = source2 instanceof VideoFrame ? source2.displayWidth : source2.width;
|
|
1232
|
+
const sh = source2 instanceof VideoFrame ? source2.displayHeight : source2.height;
|
|
1186
1233
|
const want = Math.max(FOLLOW_MIN_SIDE, FOLLOW_MARGIN * (1 + this.followMiss) * Math.max(box[2] * sw, box[3] * sh));
|
|
1187
1234
|
if (want > Math.min(sw, sh) && this.followFloats > FACE_FLOATS) return null;
|
|
1188
1235
|
if (!this.followAll && this.followTurn++ % FOLLOW_REFRESH === FOLLOW_REFRESH - 1) {
|
|
@@ -1198,24 +1245,24 @@ var Engine = class _Engine {
|
|
|
1198
1245
|
[x, y, side] = kept;
|
|
1199
1246
|
} else this.followCrop = [x, y, side];
|
|
1200
1247
|
this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
|
|
1201
|
-
this.followCanvas.getContext("2d").drawImage(
|
|
1248
|
+
this.followCanvas.getContext("2d").drawImage(source2, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
|
|
1202
1249
|
const tight = Math.min(side, Math.max(FOLLOW_MIN_SIDE, FOLLOW_RETRY * Math.max(box[2] * sw, box[3] * sh)));
|
|
1203
1250
|
this.followRetry = [((box[0] + box[2] / 2) * sw - x) / side, ((box[1] + box[3] / 2) * sh - y) / side, tight / side];
|
|
1204
1251
|
this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh]);
|
|
1205
1252
|
return this.followCanvas;
|
|
1206
1253
|
}
|
|
1207
|
-
scanCopy(
|
|
1254
|
+
scanCopy(source2, timestampUs) {
|
|
1208
1255
|
if (this.faceSeen) return null;
|
|
1209
1256
|
const turn = this.scanTurn++;
|
|
1210
1257
|
if (turn % 2 === 0) return null;
|
|
1211
|
-
const sw =
|
|
1212
|
-
const sh =
|
|
1258
|
+
const sw = source2 instanceof VideoFrame ? source2.displayWidth : source2.width;
|
|
1259
|
+
const sh = source2 instanceof VideoFrame ? source2.displayHeight : source2.height;
|
|
1213
1260
|
const { side, step, nx, ny } = tileGrid(sw, sh);
|
|
1214
1261
|
const at = (this.scanFrom + (turn >> 1)) % (nx * ny);
|
|
1215
1262
|
const x = Math.max(0, Math.min(sw - side, Math.round(at % nx * step)));
|
|
1216
1263
|
const y = Math.max(0, Math.min(sh - side, Math.round(Math.floor(at / nx) * step)));
|
|
1217
1264
|
this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
|
|
1218
|
-
this.followCanvas.getContext("2d").drawImage(
|
|
1265
|
+
this.followCanvas.getContext("2d").drawImage(source2, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
|
|
1219
1266
|
this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh]);
|
|
1220
1267
|
this.probes.add(timestampUs);
|
|
1221
1268
|
return this.followCanvas;
|
|
@@ -1327,9 +1374,9 @@ var Engine = class _Engine {
|
|
|
1327
1374
|
});
|
|
1328
1375
|
}
|
|
1329
1376
|
/** Face and mask asked on the same frame share one draw. */
|
|
1330
|
-
detectCopy(
|
|
1331
|
-
const sw =
|
|
1332
|
-
const sh =
|
|
1377
|
+
detectCopy(source2, timestampUs) {
|
|
1378
|
+
const sw = source2 instanceof VideoFrame ? source2.displayWidth : source2.width;
|
|
1379
|
+
const sh = source2 instanceof VideoFrame ? source2.displayHeight : source2.height;
|
|
1333
1380
|
const s = Math.min(1, 512 / Math.max(sw, sh));
|
|
1334
1381
|
const w = Math.max(1, Math.round(sw * s));
|
|
1335
1382
|
const h = Math.max(1, Math.round(sh * s));
|
|
@@ -1338,7 +1385,7 @@ var Engine = class _Engine {
|
|
|
1338
1385
|
this.detectCanvasTs = -1;
|
|
1339
1386
|
}
|
|
1340
1387
|
if (this.detectCanvasTs !== timestampUs) {
|
|
1341
|
-
this.detectCanvas.getContext("2d").drawImage(
|
|
1388
|
+
this.detectCanvas.getContext("2d").drawImage(source2, 0, 0, w, h);
|
|
1342
1389
|
this.detectCanvasTs = timestampUs;
|
|
1343
1390
|
}
|
|
1344
1391
|
return this.detectCanvas;
|
|
@@ -1399,7 +1446,7 @@ var Engine = class _Engine {
|
|
|
1399
1446
|
* LiveKit's reference implementation requires a `VideoFrame` even on its fallback path, so
|
|
1400
1447
|
* it constructs one only to destroy it again.
|
|
1401
1448
|
*/
|
|
1402
|
-
render(
|
|
1449
|
+
render(source2, timestampUs) {
|
|
1403
1450
|
if (this.closed || this.lostDuring) return false;
|
|
1404
1451
|
if (this.lastHeld) this.spare.push(this.lastHeld);
|
|
1405
1452
|
this.lastHeld = null;
|
|
@@ -1429,19 +1476,19 @@ var Engine = class _Engine {
|
|
|
1429
1476
|
this.thumbs.clear();
|
|
1430
1477
|
}
|
|
1431
1478
|
this.prevTs = timestampUs;
|
|
1432
|
-
if (!this.syncing() || typeof ImageData !== "undefined" &&
|
|
1479
|
+
if (!this.syncing() || typeof ImageData !== "undefined" && source2 instanceof ImageData) {
|
|
1433
1480
|
this.releaseHeld();
|
|
1434
1481
|
this.renderedTs = timestampUs;
|
|
1435
|
-
return this.draw(
|
|
1482
|
+
return this.draw(source2, timestampUs, false);
|
|
1436
1483
|
}
|
|
1437
1484
|
this.ensureFaceExtra();
|
|
1438
|
-
this.requestRemote("face",
|
|
1485
|
+
this.requestRemote("face", source2, timestampUs);
|
|
1439
1486
|
const remoteMask = this.remoteMaskKind();
|
|
1440
1487
|
if (remoteMask === "merged") {
|
|
1441
|
-
this.requestRemote("person",
|
|
1442
|
-
this.requestRemote("mask",
|
|
1443
|
-
} else if (remoteMask) this.requestRemote(remoteMask,
|
|
1444
|
-
this.queue.push({ c: this.hold(
|
|
1488
|
+
this.requestRemote("person", source2, timestampUs);
|
|
1489
|
+
this.requestRemote("mask", source2, timestampUs);
|
|
1490
|
+
} else if (remoteMask) this.requestRemote(remoteMask, source2, timestampUs);
|
|
1491
|
+
this.queue.push({ c: this.hold(source2), ts: timestampUs });
|
|
1445
1492
|
while (this.queue.length > MAX_HOLD + 1) this.faceAsked.delete(this.spareFront());
|
|
1446
1493
|
if (this.queue.length <= MAX_HOLD && !this.faceReady(this.queue[0].ts)) {
|
|
1447
1494
|
this.swallowed = true;
|
|
@@ -1608,15 +1655,15 @@ var Engine = class _Engine {
|
|
|
1608
1655
|
syncing() {
|
|
1609
1656
|
return this.syncFaces && this.faceRemote && needsFace(this.effects);
|
|
1610
1657
|
}
|
|
1611
|
-
hold(
|
|
1612
|
-
const [w, h] = sourceSize(
|
|
1658
|
+
hold(source2) {
|
|
1659
|
+
const [w, h] = sourceSize(source2);
|
|
1613
1660
|
let c = this.spare.pop();
|
|
1614
1661
|
while (c && (c.width !== w || c.height !== h)) c = this.spare.pop();
|
|
1615
1662
|
c ??= new OffscreenCanvas(w, h);
|
|
1616
|
-
c.getContext("2d").drawImage(
|
|
1663
|
+
c.getContext("2d").drawImage(source2, 0, 0, w, h);
|
|
1617
1664
|
return c;
|
|
1618
1665
|
}
|
|
1619
|
-
draw(
|
|
1666
|
+
draw(source2, timestampUs, faceDone) {
|
|
1620
1667
|
const t0 = performance.now();
|
|
1621
1668
|
const [lo, hi] = splitMicros(timestampUs);
|
|
1622
1669
|
const needSeg = this.core.decide(lo, hi, this.prevTotalMs, this.prevSegMs) === 1;
|
|
@@ -1630,8 +1677,8 @@ var Engine = class _Engine {
|
|
|
1630
1677
|
const remoteMask = this.remoteMaskKind();
|
|
1631
1678
|
if (remoteMask === "merged") {
|
|
1632
1679
|
if (!faceDone) {
|
|
1633
|
-
this.requestRemote("person",
|
|
1634
|
-
this.requestRemote("mask",
|
|
1680
|
+
this.requestRemote("person", source2, timestampUs);
|
|
1681
|
+
this.requestRemote("mask", source2, timestampUs);
|
|
1635
1682
|
}
|
|
1636
1683
|
const tex = this.mergedTex ?? this.personMaskTex;
|
|
1637
1684
|
if (tex) {
|
|
@@ -1645,7 +1692,7 @@ var Engine = class _Engine {
|
|
|
1645
1692
|
segMs = this.personWorkerMs;
|
|
1646
1693
|
}
|
|
1647
1694
|
}
|
|
1648
|
-
} else if (remoteMask && !faceDone) this.requestRemote(remoteMask,
|
|
1695
|
+
} else if (remoteMask && !faceDone) this.requestRemote(remoteMask, source2, timestampUs);
|
|
1649
1696
|
if (remoteMask === "person") {
|
|
1650
1697
|
if (this.personMaskTex) {
|
|
1651
1698
|
served = true;
|
|
@@ -1676,7 +1723,7 @@ var Engine = class _Engine {
|
|
|
1676
1723
|
if (!this.remoteMaskComing(this.filter, this.effects)) void this.ensureSegmenter();
|
|
1677
1724
|
} else {
|
|
1678
1725
|
const s0 = performance.now();
|
|
1679
|
-
mask = seg.segment(
|
|
1726
|
+
mask = seg.segment(source2, timestampUs / 1e3);
|
|
1680
1727
|
segMs = performance.now() - s0;
|
|
1681
1728
|
this.used = seg;
|
|
1682
1729
|
maskKind = classes ? 1 : 0;
|
|
@@ -1685,7 +1732,7 @@ var Engine = class _Engine {
|
|
|
1685
1732
|
if (faceDone) {
|
|
1686
1733
|
faceMs = this.faceWorkerMs;
|
|
1687
1734
|
} else if (this.faceRemote && needsFace(this.effects)) {
|
|
1688
|
-
this.requestRemote("face",
|
|
1735
|
+
this.requestRemote("face", source2, timestampUs);
|
|
1689
1736
|
faceMs = this.faceWorkerMs;
|
|
1690
1737
|
} else if (this.core.decideFace() === 1) {
|
|
1691
1738
|
if (this.faceRemote) {
|
|
@@ -1694,7 +1741,7 @@ var Engine = class _Engine {
|
|
|
1694
1741
|
void this.ensureFace();
|
|
1695
1742
|
} else if (this.lmBuf) {
|
|
1696
1743
|
const f0 = performance.now();
|
|
1697
|
-
const n = this.face.detect(
|
|
1744
|
+
const n = this.face.detect(source2, timestampUs / 1e3, this.lmBuf);
|
|
1698
1745
|
faceMs = performance.now() - f0;
|
|
1699
1746
|
this.core.setFace(lo, hi, n);
|
|
1700
1747
|
this.faceTs = timestampUs;
|
|
@@ -1702,7 +1749,7 @@ var Engine = class _Engine {
|
|
|
1702
1749
|
}
|
|
1703
1750
|
if (mask) this.maskUsedTs = maskTs;
|
|
1704
1751
|
const [maskLo, maskHi] = splitMicros(maskTs);
|
|
1705
|
-
const glCalls = this.core.process(
|
|
1752
|
+
const glCalls = this.core.process(source2, mask, this.background, maskKind, maskLo, maskHi);
|
|
1706
1753
|
if (mask) this.used?.release();
|
|
1707
1754
|
this.used = null;
|
|
1708
1755
|
this.noteLinking();
|
|
@@ -1950,6 +1997,7 @@ var VideoPipeline = class {
|
|
|
1950
1997
|
abort = null;
|
|
1951
1998
|
// worker path
|
|
1952
1999
|
worker = null;
|
|
2000
|
+
unserveWorker = null;
|
|
1953
2001
|
workerStats = null;
|
|
1954
2002
|
/** The background path the worker already holds; see backgroundForWorker. */
|
|
1955
2003
|
workerBackgroundPath = null;
|
|
@@ -2114,24 +2162,24 @@ var VideoPipeline = class {
|
|
|
2114
2162
|
return this.transport;
|
|
2115
2163
|
}
|
|
2116
2164
|
/** Take over `source` and publish the result on {@link processedTrack}. */
|
|
2117
|
-
async start(
|
|
2165
|
+
async start(source2) {
|
|
2118
2166
|
this.gpu ||= probeGpu();
|
|
2119
2167
|
const known = gpuRecord(this.gpu);
|
|
2120
2168
|
if (known?.init) {
|
|
2121
2169
|
throw new GpuLostError("init", this.gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`);
|
|
2122
2170
|
}
|
|
2123
|
-
const settings =
|
|
2171
|
+
const settings = source2.getSettings();
|
|
2124
2172
|
const width = settings.width ?? 1280;
|
|
2125
2173
|
const height = settings.height ?? 720;
|
|
2126
2174
|
this.stopped = false;
|
|
2127
|
-
this.source =
|
|
2175
|
+
this.source = source2;
|
|
2128
2176
|
this.size = { width, height, fps: settings.frameRate ?? 30 };
|
|
2129
2177
|
this.frames = 0;
|
|
2130
2178
|
this.movedOff = false;
|
|
2131
2179
|
this.startWatchdog();
|
|
2132
2180
|
if (hasInsertableStreams() && typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
|
|
2133
2181
|
try {
|
|
2134
|
-
await this.startWorker(
|
|
2182
|
+
await this.startWorker(source2, width, height, await this.backgroundForWorker(this.filter));
|
|
2135
2183
|
this.transport = "worker";
|
|
2136
2184
|
this.workerDialect = "streams";
|
|
2137
2185
|
return;
|
|
@@ -2142,7 +2190,7 @@ var VideoPipeline = class {
|
|
|
2142
2190
|
}
|
|
2143
2191
|
} else if (typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
|
|
2144
2192
|
try {
|
|
2145
|
-
await this.startWorkerWithTrack(
|
|
2193
|
+
await this.startWorkerWithTrack(source2, width, height, await this.backgroundForWorker(this.filter));
|
|
2146
2194
|
this.transport = "worker";
|
|
2147
2195
|
this.workerDialect = "track";
|
|
2148
2196
|
return;
|
|
@@ -2152,9 +2200,9 @@ var VideoPipeline = class {
|
|
|
2152
2200
|
console.warn("mediakit: no worker transport in this browser, staying on the main thread", e);
|
|
2153
2201
|
}
|
|
2154
2202
|
}
|
|
2155
|
-
await this.startMain(
|
|
2203
|
+
await this.startMain(source2);
|
|
2156
2204
|
}
|
|
2157
|
-
async startMain(
|
|
2205
|
+
async startMain(source2) {
|
|
2158
2206
|
const { width, height, fps } = this.size;
|
|
2159
2207
|
this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces, {
|
|
2160
2208
|
noFaceColor: this.noFaceColor()
|
|
@@ -2166,9 +2214,9 @@ var VideoPipeline = class {
|
|
|
2166
2214
|
this.lastBeat = performance.now();
|
|
2167
2215
|
this.stalled = false;
|
|
2168
2216
|
if (this.transport === "insertable") {
|
|
2169
|
-
this.startInsertable(
|
|
2217
|
+
this.startInsertable(source2);
|
|
2170
2218
|
} else {
|
|
2171
|
-
await this.startCanvas(
|
|
2219
|
+
await this.startCanvas(source2, fps);
|
|
2172
2220
|
}
|
|
2173
2221
|
}
|
|
2174
2222
|
/**
|
|
@@ -2202,11 +2250,11 @@ var VideoPipeline = class {
|
|
|
2202
2250
|
this.lastBeat = performance.now();
|
|
2203
2251
|
return this.processedTrack;
|
|
2204
2252
|
}
|
|
2205
|
-
async rebuild(
|
|
2253
|
+
async rebuild(source2) {
|
|
2206
2254
|
const previous = this.processedTrack;
|
|
2207
2255
|
this.processedTrack = void 0;
|
|
2208
2256
|
this.teardownTransports();
|
|
2209
|
-
await this.start(
|
|
2257
|
+
await this.start(source2);
|
|
2210
2258
|
previous?.stop();
|
|
2211
2259
|
if (this.processedTrack) this.opts.onTrackReplaced?.(this.processedTrack, previous);
|
|
2212
2260
|
}
|
|
@@ -2286,6 +2334,8 @@ var VideoPipeline = class {
|
|
|
2286
2334
|
if (!this.worker) return;
|
|
2287
2335
|
this.send({ t: "stop" });
|
|
2288
2336
|
this.worker.terminate();
|
|
2337
|
+
this.unserveWorker?.();
|
|
2338
|
+
this.unserveWorker = null;
|
|
2289
2339
|
this.worker = null;
|
|
2290
2340
|
this.workerDialect = null;
|
|
2291
2341
|
this.workerStats = null;
|
|
@@ -2319,11 +2369,11 @@ var VideoPipeline = class {
|
|
|
2319
2369
|
* so it is the Chrome dialect. A browser that only has them inside a worker (Safari) does
|
|
2320
2370
|
* not get this path and stays on the canvas transport until someone can test that.
|
|
2321
2371
|
*/
|
|
2322
|
-
startWorker(
|
|
2323
|
-
const processor = new MediaStreamTrackProcessor({ track:
|
|
2372
|
+
startWorker(source2, width, height, background) {
|
|
2373
|
+
const processor = new MediaStreamTrackProcessor({ track: source2 });
|
|
2324
2374
|
const generator = new MediaStreamTrackGenerator({
|
|
2325
2375
|
kind: "video",
|
|
2326
|
-
signalTarget:
|
|
2376
|
+
signalTarget: source2
|
|
2327
2377
|
});
|
|
2328
2378
|
return this.attachWorker(
|
|
2329
2379
|
(ready) => {
|
|
@@ -2351,8 +2401,8 @@ var VideoPipeline = class {
|
|
|
2351
2401
|
);
|
|
2352
2402
|
}
|
|
2353
2403
|
/** Safari's dialect (see `startTrack` in worker/entry.ts). */
|
|
2354
|
-
startWorkerWithTrack(
|
|
2355
|
-
const clone =
|
|
2404
|
+
startWorkerWithTrack(source2, width, height, background) {
|
|
2405
|
+
const clone = source2.clone();
|
|
2356
2406
|
return this.attachWorker(
|
|
2357
2407
|
(ready) => {
|
|
2358
2408
|
if (!ready.track) throw new Error("mediakit: the worker sent no track");
|
|
@@ -2382,6 +2432,7 @@ var VideoPipeline = class {
|
|
|
2382
2432
|
attachWorker(onReady, cleanup, post) {
|
|
2383
2433
|
const worker = new Worker(assetUrl("worker.js"));
|
|
2384
2434
|
this.worker = worker;
|
|
2435
|
+
this.unserveWorker = serveResources(worker);
|
|
2385
2436
|
return new Promise((resolve, reject) => {
|
|
2386
2437
|
let settled = false;
|
|
2387
2438
|
const fail = (err) => {
|
|
@@ -2403,6 +2454,7 @@ var VideoPipeline = class {
|
|
|
2403
2454
|
fail(new Error(e.message || "mediakit: worker failed to load"));
|
|
2404
2455
|
};
|
|
2405
2456
|
worker.onmessage = (e) => {
|
|
2457
|
+
if (isAssetsMessage(e.data)) return;
|
|
2406
2458
|
const m = e.data;
|
|
2407
2459
|
if (m.t === "stats") {
|
|
2408
2460
|
this.workerStats = m.stats;
|
|
@@ -2454,19 +2506,19 @@ var VideoPipeline = class {
|
|
|
2454
2506
|
});
|
|
2455
2507
|
}
|
|
2456
2508
|
// ── insertable ───────────────────────────────────────────────────────────────────
|
|
2457
|
-
startInsertable(
|
|
2509
|
+
startInsertable(source2) {
|
|
2458
2510
|
this.generator = new MediaStreamTrackGenerator({
|
|
2459
2511
|
kind: "video",
|
|
2460
|
-
signalTarget:
|
|
2512
|
+
signalTarget: source2
|
|
2461
2513
|
});
|
|
2462
2514
|
this.processedTrack = this.generator;
|
|
2463
|
-
this.pipeInsertable(
|
|
2515
|
+
this.pipeInsertable(source2);
|
|
2464
2516
|
}
|
|
2465
|
-
pipeInsertable(
|
|
2517
|
+
pipeInsertable(source2) {
|
|
2466
2518
|
const generator = this.generator;
|
|
2467
2519
|
if (!generator) return;
|
|
2468
2520
|
const processor = new MediaStreamTrackProcessor({
|
|
2469
|
-
track:
|
|
2521
|
+
track: source2
|
|
2470
2522
|
});
|
|
2471
2523
|
const transform = new TransformStream({
|
|
2472
2524
|
transform: (frame, controller) => {
|
|
@@ -2511,7 +2563,7 @@ var VideoPipeline = class {
|
|
|
2511
2563
|
});
|
|
2512
2564
|
}
|
|
2513
2565
|
// ── canvas ───────────────────────────────────────────────────────────────────────
|
|
2514
|
-
async startCanvas(
|
|
2566
|
+
async startCanvas(source2, fps) {
|
|
2515
2567
|
const engine = this.engine;
|
|
2516
2568
|
const video = document.createElement("video");
|
|
2517
2569
|
video.muted = true;
|
|
@@ -2521,7 +2573,7 @@ var VideoPipeline = class {
|
|
|
2521
2573
|
video.style.pointerEvents = "none";
|
|
2522
2574
|
video.width = 1;
|
|
2523
2575
|
video.height = 1;
|
|
2524
|
-
video.srcObject = new MediaStream([
|
|
2576
|
+
video.srcObject = new MediaStream([source2]);
|
|
2525
2577
|
document.body.appendChild(video);
|
|
2526
2578
|
this.video = video;
|
|
2527
2579
|
await video.play();
|
|
@@ -3911,6 +3963,7 @@ export {
|
|
|
3911
3963
|
TRANSITIONS,
|
|
3912
3964
|
VideoPipeline,
|
|
3913
3965
|
checkSupport,
|
|
3966
|
+
clearCachedAssets,
|
|
3914
3967
|
forgetGpuFailures,
|
|
3915
3968
|
gpuRecord,
|
|
3916
3969
|
hitTest,
|