@tradalab/mediakit 2.4.1 → 2.6.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 +103 -0
- package/dist/{chunk-YW75KJJO.js → chunk-RWUGOTNJ.js} +12 -3
- package/dist/chunk-RWUGOTNJ.js.map +1 -0
- package/dist/detect-worker.js +22 -13
- package/dist/detect-worker.js.map +1 -1
- package/dist/index.d.ts +117 -5
- package/dist/index.js +459 -63
- package/dist/index.js.map +1 -1
- package/dist/mediakit.wasm +0 -0
- package/dist/recipe.d.ts +8 -0
- package/dist/recipe.js +1 -1
- package/dist/worker.js +287 -48
- package/dist/worker.js.map +1 -1
- package/package.json +11 -9
- package/dist/chunk-YW75KJJO.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
normalizeEffects,
|
|
13
13
|
touchUp,
|
|
14
14
|
touchUpAmount
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-RWUGOTNJ.js";
|
|
16
16
|
import {
|
|
17
17
|
BLEND_MODES,
|
|
18
18
|
TRANSITIONS,
|
|
@@ -23,15 +23,76 @@ import {
|
|
|
23
23
|
} from "./chunk-BMIOUOT3.js";
|
|
24
24
|
|
|
25
25
|
// src/segmenter.ts
|
|
26
|
-
import {
|
|
27
|
-
|
|
26
|
+
import { ImageSegmenter } from "@mediapipe/tasks-vision";
|
|
27
|
+
|
|
28
|
+
// src/mp.ts
|
|
29
|
+
import { FilesetResolver } from "@mediapipe/tasks-vision";
|
|
30
|
+
var MP_DIR = "/mediakit/mp";
|
|
28
31
|
var MODEL_URL = {
|
|
29
32
|
person: "/mediakit/selfie_segmenter.tflite",
|
|
30
|
-
classes: "/mediakit/selfie_multiclass_256x256.tflite"
|
|
33
|
+
classes: "/mediakit/selfie_multiclass_256x256.tflite",
|
|
34
|
+
face: "/mediakit/face_landmarker.task"
|
|
31
35
|
};
|
|
36
|
+
var LOAD_MS = 6e4;
|
|
37
|
+
var fileset = null;
|
|
38
|
+
function visionFileset() {
|
|
39
|
+
fileset ??= FilesetResolver.forVisionTasks(MP_DIR).catch((e) => {
|
|
40
|
+
fileset = null;
|
|
41
|
+
throw e;
|
|
42
|
+
});
|
|
43
|
+
return fileset;
|
|
44
|
+
}
|
|
45
|
+
var LoadTimeout = class extends Error {
|
|
46
|
+
constructor(what, ms) {
|
|
47
|
+
super(`mediakit: ${what} did not load within ${Math.round(ms / 1e3)} s`);
|
|
48
|
+
this.name = "LoadTimeout";
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
function withTimeout(p, ms, what, late) {
|
|
52
|
+
return new Promise((resolve, reject) => {
|
|
53
|
+
let done = false;
|
|
54
|
+
const timer = setTimeout(() => {
|
|
55
|
+
done = true;
|
|
56
|
+
reject(new LoadTimeout(what, ms));
|
|
57
|
+
}, ms);
|
|
58
|
+
p.then(
|
|
59
|
+
(v) => {
|
|
60
|
+
if (done) late(v);
|
|
61
|
+
else {
|
|
62
|
+
done = true;
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
resolve(v);
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
(e) => {
|
|
68
|
+
if (done) return;
|
|
69
|
+
done = true;
|
|
70
|
+
clearTimeout(timer);
|
|
71
|
+
reject(e);
|
|
72
|
+
}
|
|
73
|
+
);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async function preloadDetectors(parts = { person: true, classes: true, face: true }) {
|
|
77
|
+
const urls = [];
|
|
78
|
+
try {
|
|
79
|
+
const fs = await visionFileset();
|
|
80
|
+
urls.push(fs.wasmBinaryPath, fs.wasmLoaderPath);
|
|
81
|
+
} catch {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
for (const k of ["person", "classes", "face"]) if (parts[k]) urls.push(MODEL_URL[k]);
|
|
85
|
+
await Promise.all(
|
|
86
|
+
urls.map(
|
|
87
|
+
(u) => fetch(u, { priority: "low" }).then((r) => r.arrayBuffer()).catch(() => void 0)
|
|
88
|
+
)
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// src/segmenter.ts
|
|
32
93
|
async function createSegmenter(canvas, model = "person") {
|
|
33
|
-
const
|
|
34
|
-
const segmenter = await ImageSegmenter.createFromOptions(
|
|
94
|
+
const fileset2 = await visionFileset();
|
|
95
|
+
const segmenter = await ImageSegmenter.createFromOptions(fileset2, {
|
|
35
96
|
baseOptions: {
|
|
36
97
|
modelAssetPath: MODEL_URL[model],
|
|
37
98
|
// MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all
|
|
@@ -72,14 +133,12 @@ async function createSegmenter(canvas, model = "person") {
|
|
|
72
133
|
}
|
|
73
134
|
|
|
74
135
|
// src/face.ts
|
|
75
|
-
import { FaceLandmarker
|
|
76
|
-
var WASM_DIR2 = "/mediakit/mp";
|
|
77
|
-
var MODEL_URL2 = "/mediakit/face_landmarker.task";
|
|
136
|
+
import { FaceLandmarker } from "@mediapipe/tasks-vision";
|
|
78
137
|
var FACE_FLOATS = 478 * 3;
|
|
79
138
|
async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
|
|
80
|
-
const
|
|
81
|
-
const landmarker = await FaceLandmarker.createFromOptions(
|
|
82
|
-
baseOptions: { modelAssetPath:
|
|
139
|
+
const fileset2 = await visionFileset();
|
|
140
|
+
const landmarker = await FaceLandmarker.createFromOptions(fileset2, {
|
|
141
|
+
baseOptions: { modelAssetPath: MODEL_URL.face, delegate },
|
|
83
142
|
canvas,
|
|
84
143
|
runningMode: "VIDEO",
|
|
85
144
|
// As many as the core tracks: one landmark pass returns them all, so the cost of a second
|
|
@@ -113,7 +172,6 @@ async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
|
|
|
113
172
|
|
|
114
173
|
// src/detect-remote.ts
|
|
115
174
|
var DETECT_WORKER_URL = "/mediakit/detect-worker.js";
|
|
116
|
-
var READY_MS = 2e4;
|
|
117
175
|
var DetectWorker = class {
|
|
118
176
|
constructor(on) {
|
|
119
177
|
this.on = on;
|
|
@@ -162,7 +220,7 @@ var DetectWorker = class {
|
|
|
162
220
|
reject(new Error("detect worker gone"));
|
|
163
221
|
return;
|
|
164
222
|
}
|
|
165
|
-
const timer = setTimeout(() => this.settle(kind, new
|
|
223
|
+
const timer = setTimeout(() => this.settle(kind, new LoadTimeout(`${kind} detection`, LOAD_MS)), LOAD_MS);
|
|
166
224
|
this.ready.set(kind, { resolve, reject, timer });
|
|
167
225
|
this.send(m);
|
|
168
226
|
});
|
|
@@ -283,6 +341,75 @@ function splitMicros(us) {
|
|
|
283
341
|
return [lo, hi | 0];
|
|
284
342
|
}
|
|
285
343
|
|
|
344
|
+
// src/gpu-guard.ts
|
|
345
|
+
var KEY = "mediakit-gpu-guard";
|
|
346
|
+
var TTL_MS = 3 * 24 * 3600 * 1e3;
|
|
347
|
+
function storage() {
|
|
348
|
+
try {
|
|
349
|
+
return typeof localStorage === "undefined" ? null : localStorage;
|
|
350
|
+
} catch {
|
|
351
|
+
return null;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
function load() {
|
|
355
|
+
const s = storage();
|
|
356
|
+
if (!s) return {};
|
|
357
|
+
try {
|
|
358
|
+
const parsed = JSON.parse(s.getItem(KEY) ?? "{}");
|
|
359
|
+
return parsed && typeof parsed === "object" ? parsed : {};
|
|
360
|
+
} catch {
|
|
361
|
+
return {};
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
function save(store) {
|
|
365
|
+
try {
|
|
366
|
+
storage()?.setItem(KEY, JSON.stringify(store));
|
|
367
|
+
} catch {
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
function gpuRecord(gpu) {
|
|
372
|
+
if (!gpu) return null;
|
|
373
|
+
const r = load()[gpu];
|
|
374
|
+
if (!r || typeof r.at !== "number" || Date.now() - r.at > TTL_MS) return null;
|
|
375
|
+
return { init: r.init === true, faceColor: r.faceColor === true, at: r.at };
|
|
376
|
+
}
|
|
377
|
+
function recordLoss(gpu, phase) {
|
|
378
|
+
if (!gpu || phase === "run" || !storage()) return;
|
|
379
|
+
const store = load();
|
|
380
|
+
const was = gpuRecord(gpu);
|
|
381
|
+
store[gpu] = {
|
|
382
|
+
init: phase === "init" || (was?.init ?? false),
|
|
383
|
+
faceColor: phase === "link" || (was?.faceColor ?? false),
|
|
384
|
+
at: Date.now()
|
|
385
|
+
};
|
|
386
|
+
save(store);
|
|
387
|
+
}
|
|
388
|
+
function forgetGpuFailures() {
|
|
389
|
+
try {
|
|
390
|
+
storage()?.removeItem(KEY);
|
|
391
|
+
} catch {
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
function rendererOf(gl) {
|
|
396
|
+
if (gl.isContextLost()) return "";
|
|
397
|
+
const info = gl.getExtension("WEBGL_debug_renderer_info");
|
|
398
|
+
return String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "");
|
|
399
|
+
}
|
|
400
|
+
var GpuLostError = class extends Error {
|
|
401
|
+
constructor(phase, gpu, detail = "") {
|
|
402
|
+
super(`mediakit: the WebGL context was lost ${phase === "init" ? "building the shaders" : phase === "link" ? "linking a makeup shader" : "while running"}${detail ? ` (${detail})` : ""} [GPU: ${gpu || "unknown"}]`);
|
|
403
|
+
this.phase = phase;
|
|
404
|
+
this.gpu = gpu;
|
|
405
|
+
this.detail = detail;
|
|
406
|
+
this.name = "GpuLostError";
|
|
407
|
+
}
|
|
408
|
+
phase;
|
|
409
|
+
gpu;
|
|
410
|
+
detail;
|
|
411
|
+
};
|
|
412
|
+
|
|
286
413
|
// src/engine.ts
|
|
287
414
|
var ZERO_STATS = {
|
|
288
415
|
totalMs: 0,
|
|
@@ -303,17 +430,25 @@ var ZERO_STATS = {
|
|
|
303
430
|
faces: 0,
|
|
304
431
|
heldFrames: 0,
|
|
305
432
|
faceAgeMs: 0,
|
|
306
|
-
maskAgeMs: 0
|
|
433
|
+
maskAgeMs: 0,
|
|
434
|
+
effectError: ""
|
|
307
435
|
};
|
|
308
436
|
var MAX_HOLD = 2;
|
|
437
|
+
var LINK_LOSS_WINDOW_MS = 3e3;
|
|
309
438
|
var DEPTH_VOTES = 15;
|
|
310
439
|
var DETECT_DUTY = 0.6;
|
|
440
|
+
function gpuName(gl) {
|
|
441
|
+
const info = gl.getExtension("WEBGL_debug_renderer_info");
|
|
442
|
+
const name = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "unknown");
|
|
443
|
+
return gl.isContextLost() ? `${name}, context lost` : name;
|
|
444
|
+
}
|
|
311
445
|
function sourceSize(source) {
|
|
312
446
|
if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
|
|
313
447
|
if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
|
|
314
448
|
const s = source;
|
|
315
449
|
return [s.width, s.height];
|
|
316
450
|
}
|
|
451
|
+
var FACE_COLOR_SKIPPED = "face colour shaders skipped: linking one lost the WebGL context on this GPU before";
|
|
317
452
|
var Engine = class _Engine {
|
|
318
453
|
canvas;
|
|
319
454
|
gl;
|
|
@@ -344,6 +479,14 @@ var Engine = class _Engine {
|
|
|
344
479
|
classLoading = null;
|
|
345
480
|
/** The segmenter whose result this frame borrowed, to give it back after process(). */
|
|
346
481
|
used = null;
|
|
482
|
+
programErr = "";
|
|
483
|
+
loadErr = "";
|
|
484
|
+
gpu = "";
|
|
485
|
+
linkSeenAt = -Infinity;
|
|
486
|
+
links = 0;
|
|
487
|
+
lostPhase = null;
|
|
488
|
+
classFailed = false;
|
|
489
|
+
failed = /* @__PURE__ */ new Set();
|
|
347
490
|
/**
|
|
348
491
|
* The landmark detector, also lazy and independent of the segmenter.
|
|
349
492
|
*
|
|
@@ -403,19 +546,20 @@ var Engine = class _Engine {
|
|
|
403
546
|
this.core = core;
|
|
404
547
|
}
|
|
405
548
|
/** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */
|
|
406
|
-
static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3) {
|
|
549
|
+
static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3, guard = {}) {
|
|
407
550
|
const canvas = document.createElement("canvas");
|
|
408
551
|
canvas.width = width;
|
|
409
552
|
canvas.height = height;
|
|
410
|
-
return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces);
|
|
553
|
+
return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces, guard);
|
|
411
554
|
}
|
|
412
555
|
/**
|
|
413
556
|
* `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
|
|
414
557
|
* only a `cutout` background writes; it is fixed for the life of the context, so a host that
|
|
415
558
|
* may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
|
|
416
|
-
* landmarker looks for: below 3 it skips re-running its face detector on every call.
|
|
559
|
+
* landmarker looks for: below 3 it skips re-running its face detector on every call. Throws
|
|
560
|
+
* GpuLostError when the context is lost building the shaders, or this GPU is remembered for it.
|
|
417
561
|
*/
|
|
418
|
-
static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3) {
|
|
562
|
+
static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3, guard = {}) {
|
|
419
563
|
const width = canvas.width;
|
|
420
564
|
const height = canvas.height;
|
|
421
565
|
const gl = canvas.getContext("webgl2", {
|
|
@@ -425,14 +569,26 @@ var Engine = class _Engine {
|
|
|
425
569
|
depth: false,
|
|
426
570
|
stencil: false
|
|
427
571
|
});
|
|
428
|
-
if (!gl) throw new Error("mediakit: no WebGL2 in this browser");
|
|
572
|
+
if (!gl) throw new Error("mediakit: no WebGL2 in this browser (none available, blocked, or the GPU process was reset)");
|
|
573
|
+
const gpu = rendererOf(gl);
|
|
574
|
+
const known = gpuRecord(gpu);
|
|
575
|
+
if (known?.init) {
|
|
576
|
+
gl.getExtension("WEBGL_lose_context")?.loseContext();
|
|
577
|
+
throw new GpuLostError("init", gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`);
|
|
578
|
+
}
|
|
429
579
|
let core;
|
|
430
580
|
let engine;
|
|
431
581
|
try {
|
|
432
582
|
core = await loadCore();
|
|
433
583
|
const err = core.init(gl, width, height);
|
|
434
|
-
if (err
|
|
584
|
+
if (err && gl.isContextLost()) {
|
|
585
|
+
recordLoss(gpu, "init");
|
|
586
|
+
throw new GpuLostError("init", gpu, err);
|
|
587
|
+
}
|
|
588
|
+
if (err) throw new Error(`mediakit: ${err} [GPU: ${gpuName(gl)}]`);
|
|
435
589
|
engine = new _Engine(canvas, gl, core);
|
|
590
|
+
engine.gpu = gpu;
|
|
591
|
+
if (guard.noFaceColor || known?.faceColor) core.disableFaceColor?.(FACE_COLOR_SKIPPED);
|
|
436
592
|
engine.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3));
|
|
437
593
|
await engine.setRecipe(filter, effects, background);
|
|
438
594
|
return engine;
|
|
@@ -448,9 +604,29 @@ var Engine = class _Engine {
|
|
|
448
604
|
throw err;
|
|
449
605
|
}
|
|
450
606
|
}
|
|
607
|
+
/** The GPU the context reported at creation, "" when the browser hides it. */
|
|
608
|
+
get gpuName() {
|
|
609
|
+
return this.gpu;
|
|
610
|
+
}
|
|
451
611
|
get loading() {
|
|
452
612
|
return this.segmenterLoading !== null || this.classLoading !== null || this.faceLoading !== null;
|
|
453
613
|
}
|
|
614
|
+
/** The browser took the WebGL context away (GPU process reset or reclaimed); this Engine is done. */
|
|
615
|
+
get lost() {
|
|
616
|
+
return this.gl.isContextLost();
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* When the context was lost: "link" within 3 s of a face colour shader starting or still linking, else "run";
|
|
620
|
+
* null while it is not. The first read decides, and on the main thread it is remembered per GPU.
|
|
621
|
+
*/
|
|
622
|
+
get lostDuring() {
|
|
623
|
+
if (this.closed || !this.gl.isContextLost()) return null;
|
|
624
|
+
if (!this.lostPhase) {
|
|
625
|
+
this.lostPhase = performance.now() - this.linkSeenAt < LINK_LOSS_WINDOW_MS ? "link" : "run";
|
|
626
|
+
recordLoss(this.gpu, this.lostPhase);
|
|
627
|
+
}
|
|
628
|
+
return this.lostPhase;
|
|
629
|
+
}
|
|
454
630
|
get outputCanvas() {
|
|
455
631
|
return this.canvas;
|
|
456
632
|
}
|
|
@@ -537,13 +713,29 @@ var Engine = class _Engine {
|
|
|
537
713
|
this.makeupPath = makeupTexture;
|
|
538
714
|
}
|
|
539
715
|
this.core.setRecipe(coreRecipe(filter, effects));
|
|
540
|
-
|
|
716
|
+
this.noteLinking();
|
|
717
|
+
if (needsSegmentation(filter, effects) && !this.remoteMaskComing(filter, effects)) void this.ensureSegmenter();
|
|
541
718
|
if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
|
|
542
719
|
if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
|
|
543
720
|
if (needsFace(effects)) void this.ensureFace();
|
|
544
721
|
}
|
|
722
|
+
noteLinking() {
|
|
723
|
+
const links = this.core.links?.() ?? 0;
|
|
724
|
+
if (links !== this.links || (this.core.linking?.() ?? 0) > 0) this.linkSeenAt = performance.now();
|
|
725
|
+
this.links = links;
|
|
726
|
+
}
|
|
727
|
+
/** A worker, or the multiclass model, will bring the mask: no in-thread person model for it. */
|
|
728
|
+
remoteMaskComing(filter, effects) {
|
|
729
|
+
if (needsSkinClasses(filter, effects) && !this.classFailed) return true;
|
|
730
|
+
return this.personRemoteWanted(filter, effects) && !this.inThread.has("person");
|
|
731
|
+
}
|
|
732
|
+
gaveUp(what, e) {
|
|
733
|
+
if (!(e instanceof LoadTimeout)) return;
|
|
734
|
+
this.loadErr ||= `${e.message}; ${what} stay off`;
|
|
735
|
+
console.warn(this.loadErr);
|
|
736
|
+
}
|
|
545
737
|
ensureFace() {
|
|
546
|
-
if (this.face || this.faceRemote || this.closed) return Promise.resolve();
|
|
738
|
+
if (this.face || this.faceRemote || this.failed.has("face") || this.closed) return Promise.resolve();
|
|
547
739
|
if (this.faceLoading) return this.faceLoading;
|
|
548
740
|
const buf = this.core.faceBuffer();
|
|
549
741
|
if (!buf) return Promise.resolve();
|
|
@@ -552,8 +744,9 @@ var Engine = class _Engine {
|
|
|
552
744
|
this.faceRemote = true;
|
|
553
745
|
this.lmBuf = buf;
|
|
554
746
|
}).catch((e) => {
|
|
747
|
+
if (e instanceof LoadTimeout) throw e;
|
|
555
748
|
if (!this.inThread.has("face")) console.warn("mediakit: no detect worker for faces, detecting in this thread", e);
|
|
556
|
-
return createFaceDetector(this.canvas, n).then((f) => {
|
|
749
|
+
return withTimeout(createFaceDetector(this.canvas, n), LOAD_MS, "face detection", (f) => f.close()).then((f) => {
|
|
557
750
|
if (this.closed) {
|
|
558
751
|
f.close();
|
|
559
752
|
return;
|
|
@@ -562,7 +755,9 @@ var Engine = class _Engine {
|
|
|
562
755
|
this.lmBuf = buf;
|
|
563
756
|
});
|
|
564
757
|
}).catch((e) => {
|
|
565
|
-
|
|
758
|
+
this.failed.add("face");
|
|
759
|
+
this.gaveUp("face effects", e);
|
|
760
|
+
if (!(e instanceof LoadTimeout)) console.error("mediakit: face detector failed to load", e);
|
|
566
761
|
}).finally(() => {
|
|
567
762
|
this.faceLoading = null;
|
|
568
763
|
});
|
|
@@ -573,10 +768,13 @@ var Engine = class _Engine {
|
|
|
573
768
|
return filter.kind === "none" && needsSegmentation(filter, effects) && !needsSkinClasses(filter, effects);
|
|
574
769
|
}
|
|
575
770
|
ensurePersonRemote() {
|
|
576
|
-
if (this.personRemote || this.closed) return Promise.resolve();
|
|
771
|
+
if (this.personRemote || this.failed.has("person") || this.closed) return Promise.resolve();
|
|
577
772
|
this.personLoading ??= this.remote("person", (d) => d.initMask("person")).then(() => {
|
|
578
773
|
this.personRemote = true;
|
|
579
|
-
}).catch(() => {
|
|
774
|
+
}).catch((e) => {
|
|
775
|
+
if (!(e instanceof LoadTimeout)) return;
|
|
776
|
+
this.failed.add("person");
|
|
777
|
+
this.gaveUp("background effects", e);
|
|
580
778
|
}).finally(() => {
|
|
581
779
|
this.personLoading = null;
|
|
582
780
|
});
|
|
@@ -584,6 +782,7 @@ var Engine = class _Engine {
|
|
|
584
782
|
}
|
|
585
783
|
async remote(kind, init) {
|
|
586
784
|
if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
|
|
785
|
+
this.inThread.add(kind);
|
|
587
786
|
throw new Error("in-thread");
|
|
588
787
|
}
|
|
589
788
|
let detect = this.detects.get(kind);
|
|
@@ -594,7 +793,10 @@ var Engine = class _Engine {
|
|
|
594
793
|
try {
|
|
595
794
|
await init(detect);
|
|
596
795
|
} catch (e) {
|
|
597
|
-
|
|
796
|
+
if (e instanceof LoadTimeout) {
|
|
797
|
+
detect.close();
|
|
798
|
+
this.detects.delete(kind);
|
|
799
|
+
} else this.inThread.add(kind);
|
|
598
800
|
throw e;
|
|
599
801
|
}
|
|
600
802
|
if (this.closed) throw new Error("closed");
|
|
@@ -706,36 +908,42 @@ var Engine = class _Engine {
|
|
|
706
908
|
return this.detectCanvas;
|
|
707
909
|
}
|
|
708
910
|
ensureClassSegmenter() {
|
|
709
|
-
if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
|
|
911
|
+
if (this.classSegmenter || this.classRemote || this.classFailed || this.closed) return Promise.resolve();
|
|
710
912
|
if (this.classLoading) return this.classLoading;
|
|
711
913
|
this.classLoading = this.remote("mask", (d) => d.initMask("classes")).then(() => {
|
|
712
914
|
this.classRemote = true;
|
|
713
|
-
}).catch(
|
|
714
|
-
(
|
|
915
|
+
}).catch((e) => {
|
|
916
|
+
if (e instanceof LoadTimeout) throw e;
|
|
917
|
+
return withTimeout(createSegmenter(this.canvas, "classes"), LOAD_MS, "skin segmentation", (s) => s.close()).then((s) => {
|
|
715
918
|
if (this.closed) {
|
|
716
919
|
s.close();
|
|
717
920
|
return;
|
|
718
921
|
}
|
|
719
922
|
this.classSegmenter = s;
|
|
720
|
-
})
|
|
721
|
-
).catch((e) => {
|
|
722
|
-
|
|
923
|
+
});
|
|
924
|
+
}).catch((e) => {
|
|
925
|
+
this.classFailed = true;
|
|
926
|
+
if (!(e instanceof LoadTimeout)) console.error("mediakit: multiclass segmenter failed to load", e);
|
|
927
|
+
else console.warn(`${e.message}; the person model stands in`);
|
|
928
|
+
if (needsSegmentation(this.filter, this.effects)) void this.ensureSegmenter();
|
|
723
929
|
}).finally(() => {
|
|
724
930
|
this.classLoading = null;
|
|
725
931
|
});
|
|
726
932
|
return this.classLoading;
|
|
727
933
|
}
|
|
728
934
|
ensureSegmenter() {
|
|
729
|
-
if (this.segmenter || this.closed) return Promise.resolve();
|
|
935
|
+
if (this.segmenter || this.failed.has("segmenter") || this.closed) return Promise.resolve();
|
|
730
936
|
if (this.segmenterLoading) return this.segmenterLoading;
|
|
731
|
-
this.segmenterLoading = createSegmenter(this.canvas).then((s) => {
|
|
937
|
+
this.segmenterLoading = withTimeout(createSegmenter(this.canvas), LOAD_MS, "person segmentation", (s) => s.close()).then((s) => {
|
|
732
938
|
if (this.closed) {
|
|
733
939
|
s.close();
|
|
734
940
|
return;
|
|
735
941
|
}
|
|
736
942
|
this.segmenter = s;
|
|
737
943
|
}).catch((e) => {
|
|
738
|
-
|
|
944
|
+
this.failed.add("segmenter");
|
|
945
|
+
this.gaveUp("background and skin effects", e);
|
|
946
|
+
if (!(e instanceof LoadTimeout)) console.error("mediakit: segmenter failed to load", e);
|
|
739
947
|
}).finally(() => {
|
|
740
948
|
this.segmenterLoading = null;
|
|
741
949
|
});
|
|
@@ -754,7 +962,7 @@ var Engine = class _Engine {
|
|
|
754
962
|
* it constructs one only to destroy it again.
|
|
755
963
|
*/
|
|
756
964
|
render(source, timestampUs) {
|
|
757
|
-
if (this.closed) return false;
|
|
965
|
+
if (this.closed || this.lostDuring) return false;
|
|
758
966
|
if (this.lastHeld) this.spare.push(this.lastHeld);
|
|
759
967
|
this.lastHeld = null;
|
|
760
968
|
this.swallowed = false;
|
|
@@ -873,7 +1081,7 @@ var Engine = class _Engine {
|
|
|
873
1081
|
const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
|
|
874
1082
|
const seg = classes ? this.classSegmenter : this.segmenter;
|
|
875
1083
|
if (!seg) {
|
|
876
|
-
void this.ensureSegmenter();
|
|
1084
|
+
if (!this.remoteMaskComing(this.filter, this.effects)) void this.ensureSegmenter();
|
|
877
1085
|
} else {
|
|
878
1086
|
const s0 = performance.now();
|
|
879
1087
|
mask = seg.segment(source, timestampUs / 1e3);
|
|
@@ -905,6 +1113,14 @@ var Engine = class _Engine {
|
|
|
905
1113
|
const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
|
|
906
1114
|
if (mask) this.used?.release();
|
|
907
1115
|
this.used = null;
|
|
1116
|
+
this.noteLinking();
|
|
1117
|
+
if (!this.programErr) {
|
|
1118
|
+
const err = this.core.programError?.() ?? "";
|
|
1119
|
+
if (err) {
|
|
1120
|
+
this.programErr = `mediakit: ${err}; makeup and teeth stay off, the rest runs [GPU: ${gpuName(this.gl)}]`;
|
|
1121
|
+
console.warn(this.programErr);
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
908
1124
|
this.prevSegMs = segMs;
|
|
909
1125
|
this.prevTotalMs = performance.now() - t0;
|
|
910
1126
|
const s = this.core.stats();
|
|
@@ -927,7 +1143,8 @@ var Engine = class _Engine {
|
|
|
927
1143
|
faces: s ? s[12] : 0,
|
|
928
1144
|
heldFrames: faceDone ? this.holdDepth : 0,
|
|
929
1145
|
faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
|
|
930
|
-
maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0
|
|
1146
|
+
maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0,
|
|
1147
|
+
effectError: this.programErr || this.loadErr
|
|
931
1148
|
};
|
|
932
1149
|
return glCalls > 0;
|
|
933
1150
|
}
|
|
@@ -1025,6 +1242,9 @@ async function coverCrop(src, w, h) {
|
|
|
1025
1242
|
}
|
|
1026
1243
|
|
|
1027
1244
|
// src/pipeline.ts
|
|
1245
|
+
var SLOW_FRAME_MS = 150;
|
|
1246
|
+
var SLOW_TICKS = 3;
|
|
1247
|
+
var MAX_GPU_RECOVERIES = 2;
|
|
1028
1248
|
var WORKER_READY_MS = 8e3;
|
|
1029
1249
|
var STALL_MS = 2e3;
|
|
1030
1250
|
var LOADING_STALL_MS = 2e4;
|
|
@@ -1032,12 +1252,40 @@ var WORKER_DEAD_MS = 8e3;
|
|
|
1032
1252
|
function hasInsertableStreams() {
|
|
1033
1253
|
return typeof window !== "undefined" && "MediaStreamTrackProcessor" in window && "MediaStreamTrackGenerator" in window;
|
|
1034
1254
|
}
|
|
1255
|
+
function checkSupport() {
|
|
1256
|
+
if (typeof window === "undefined") return { supported: false, reasons: ["no-window"], softwareRenderer: false, gpu: "", remembered: null };
|
|
1257
|
+
const reasons = [];
|
|
1258
|
+
if (typeof WebAssembly === "undefined") reasons.push("no-wasm");
|
|
1259
|
+
const gl = document.createElement("canvas").getContext("webgl2");
|
|
1260
|
+
let gpu = "";
|
|
1261
|
+
let softwareRenderer = false;
|
|
1262
|
+
if (!gl) reasons.push("no-webgl2");
|
|
1263
|
+
else {
|
|
1264
|
+
const info = gl.getExtension("WEBGL_debug_renderer_info");
|
|
1265
|
+
gpu = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "");
|
|
1266
|
+
const fast = document.createElement("canvas").getContext("webgl2", { failIfMajorPerformanceCaveat: true });
|
|
1267
|
+
softwareRenderer = !fast || /swiftshader|llvmpipe|software|basic render/i.test(gpu);
|
|
1268
|
+
fast?.getExtension("WEBGL_lose_context")?.loseContext();
|
|
1269
|
+
gl.getExtension("WEBGL_lose_context")?.loseContext();
|
|
1270
|
+
}
|
|
1271
|
+
if (!hasInsertableStreams() && !("captureStream" in HTMLCanvasElement.prototype)) reasons.push("no-transport");
|
|
1272
|
+
const remembered = gpuRecord(gpu);
|
|
1273
|
+
if (remembered?.init) reasons.push("gpu-blocked");
|
|
1274
|
+
probedGpu = gpu;
|
|
1275
|
+
return { supported: reasons.length === 0, reasons, softwareRenderer, gpu, remembered };
|
|
1276
|
+
}
|
|
1277
|
+
var probedGpu = null;
|
|
1278
|
+
function probeGpu() {
|
|
1279
|
+
if (probedGpu !== null) return probedGpu;
|
|
1280
|
+
const gl = typeof document === "undefined" ? null : document.createElement("canvas").getContext("webgl2");
|
|
1281
|
+
if (!gl) return "";
|
|
1282
|
+
const info = gl.getExtension("WEBGL_debug_renderer_info");
|
|
1283
|
+
probedGpu = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "");
|
|
1284
|
+
gl.getExtension("WEBGL_lose_context")?.loseContext();
|
|
1285
|
+
return probedGpu;
|
|
1286
|
+
}
|
|
1035
1287
|
function mediakitSupported() {
|
|
1036
|
-
|
|
1037
|
-
if (typeof WebAssembly === "undefined") return false;
|
|
1038
|
-
const probe = document.createElement("canvas");
|
|
1039
|
-
if (!probe.getContext("webgl2")) return false;
|
|
1040
|
-
return hasInsertableStreams() || "captureStream" in HTMLCanvasElement.prototype;
|
|
1288
|
+
return checkSupport().supported;
|
|
1041
1289
|
}
|
|
1042
1290
|
var VideoPipeline = class {
|
|
1043
1291
|
processedTrack;
|
|
@@ -1053,6 +1301,15 @@ var VideoPipeline = class {
|
|
|
1053
1301
|
stalled = false;
|
|
1054
1302
|
watchdog = null;
|
|
1055
1303
|
movedOff = false;
|
|
1304
|
+
raised = /* @__PURE__ */ new Set();
|
|
1305
|
+
slowTicks = 0;
|
|
1306
|
+
gpuRecoveries = 0;
|
|
1307
|
+
gpu = "";
|
|
1308
|
+
faceColorLost = false;
|
|
1309
|
+
recovering = false;
|
|
1310
|
+
workerDialect = null;
|
|
1311
|
+
generator = null;
|
|
1312
|
+
piping = Promise.resolve();
|
|
1056
1313
|
/** What the worker last said about loading detectors. */
|
|
1057
1314
|
workerLoading = false;
|
|
1058
1315
|
// Frames handed out alongside the track - see subscribeFrames.
|
|
@@ -1082,7 +1339,8 @@ var VideoPipeline = class {
|
|
|
1082
1339
|
transport: this.transport,
|
|
1083
1340
|
frames: this.frames,
|
|
1084
1341
|
sinceMs: this.lastBeat ? performance.now() - this.lastBeat : 0,
|
|
1085
|
-
stalled: this.stalled
|
|
1342
|
+
stalled: this.stalled,
|
|
1343
|
+
effectError: this.stats?.effectError ?? ""
|
|
1086
1344
|
};
|
|
1087
1345
|
}
|
|
1088
1346
|
/** Every processed frame. */
|
|
@@ -1108,6 +1366,55 @@ var VideoPipeline = class {
|
|
|
1108
1366
|
}
|
|
1109
1367
|
});
|
|
1110
1368
|
}
|
|
1369
|
+
issue(code, message) {
|
|
1370
|
+
if (this.raised.has(code)) return;
|
|
1371
|
+
this.raised.add(code);
|
|
1372
|
+
console.warn(`mediakit: ${code}: ${message}`);
|
|
1373
|
+
try {
|
|
1374
|
+
this.opts.onIssue?.({ code, message, transport: this.transport });
|
|
1375
|
+
} catch (e) {
|
|
1376
|
+
console.error("mediakit: onIssue threw", e);
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
watchQuality() {
|
|
1380
|
+
const s = this.stats;
|
|
1381
|
+
if (!s) return;
|
|
1382
|
+
if (s.effectError) this.issue("effect-off", s.effectError);
|
|
1383
|
+
const slow = s.totalMs > SLOW_FRAME_MS || s.faceMs > SLOW_FRAME_MS;
|
|
1384
|
+
this.slowTicks = slow ? Math.max(1, this.slowTicks + 1) : Math.min(-1, this.slowTicks - 1);
|
|
1385
|
+
if (this.slowTicks >= SLOW_TICKS) {
|
|
1386
|
+
this.issue("slow", `frames take ${Math.round(s.totalMs)}ms, face detection ${Math.round(s.faceMs)}ms`);
|
|
1387
|
+
} else if (this.slowTicks <= -SLOW_TICKS) {
|
|
1388
|
+
this.raised.delete("slow");
|
|
1389
|
+
}
|
|
1390
|
+
const phase = this.engine?.lostDuring;
|
|
1391
|
+
if (phase) void this.recoverGpu("the main-thread WebGL context was lost", phase);
|
|
1392
|
+
}
|
|
1393
|
+
noFaceColor() {
|
|
1394
|
+
return this.faceColorLost || (gpuRecord(this.gpu)?.faceColor ?? false);
|
|
1395
|
+
}
|
|
1396
|
+
/** A "link" loss rebuilds without face colour, a "run" loss as before; an "init" loss would only repeat. */
|
|
1397
|
+
async recoverGpu(why, phase, gpu = this.gpu) {
|
|
1398
|
+
if (this.recovering || this.stopped || !this.source || this.raised.has("gpu-lost")) return;
|
|
1399
|
+
recordLoss(gpu, phase);
|
|
1400
|
+
if (phase === "link") this.faceColorLost = true;
|
|
1401
|
+
const retry = phase !== "init" && this.gpuRecoveries < MAX_GPU_RECOVERIES;
|
|
1402
|
+
const during = phase === "link" ? "linking a makeup shader" : phase === "init" ? "building the shaders" : "while running";
|
|
1403
|
+
const next = !retry ? "not rebuilding" : phase === "link" ? "rebuilding without makeup" : "rebuilding";
|
|
1404
|
+
this.issue("gpu-lost", `${why} (${during}, ${next})`);
|
|
1405
|
+
if (!retry) return;
|
|
1406
|
+
this.gpuRecoveries++;
|
|
1407
|
+
this.recovering = true;
|
|
1408
|
+
try {
|
|
1409
|
+
if (this.transport === "worker" && phase === "run") await this.moveOffWorker("lost its WebGL context");
|
|
1410
|
+
else await this.rebuild(this.source);
|
|
1411
|
+
this.raised.delete("gpu-lost");
|
|
1412
|
+
} catch (e) {
|
|
1413
|
+
console.error("mediakit: rebuilding after a lost WebGL context failed", e);
|
|
1414
|
+
} finally {
|
|
1415
|
+
this.recovering = false;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1111
1418
|
beat() {
|
|
1112
1419
|
this.lastBeat = performance.now();
|
|
1113
1420
|
this.frames++;
|
|
@@ -1131,9 +1438,11 @@ var VideoPipeline = class {
|
|
|
1131
1438
|
const transport = this.transport;
|
|
1132
1439
|
if (since >= (loading ? LOADING_STALL_MS : STALL_MS) && !this.stalled) {
|
|
1133
1440
|
this.stalled = true;
|
|
1134
|
-
|
|
1441
|
+
this.issue("stall", `no frame out for ${Math.round(since)}ms on the ${transport} transport`);
|
|
1135
1442
|
this.opts.onStall?.({ transport, sinceMs: since });
|
|
1136
1443
|
}
|
|
1444
|
+
if (!this.stalled) this.raised.delete("stall");
|
|
1445
|
+
this.watchQuality();
|
|
1137
1446
|
if (transport === "worker" && since >= (loading ? LOADING_STALL_MS : WORKER_DEAD_MS)) {
|
|
1138
1447
|
void this.moveOffWorker("silent");
|
|
1139
1448
|
}
|
|
@@ -1147,7 +1456,7 @@ var VideoPipeline = class {
|
|
|
1147
1456
|
async moveOffWorker(reason) {
|
|
1148
1457
|
if (this.movedOff || this.stopped || !this.source) return;
|
|
1149
1458
|
this.movedOff = true;
|
|
1150
|
-
|
|
1459
|
+
this.issue("worker-moved", `worker ${reason} after start, moving to the main thread`);
|
|
1151
1460
|
const previous = this.processedTrack;
|
|
1152
1461
|
this.teardownWorker();
|
|
1153
1462
|
try {
|
|
@@ -1167,6 +1476,11 @@ var VideoPipeline = class {
|
|
|
1167
1476
|
}
|
|
1168
1477
|
/** Take over `source` and publish the result on {@link processedTrack}. */
|
|
1169
1478
|
async start(source) {
|
|
1479
|
+
this.gpu ||= probeGpu();
|
|
1480
|
+
const known = gpuRecord(this.gpu);
|
|
1481
|
+
if (known?.init) {
|
|
1482
|
+
throw new GpuLostError("init", this.gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`);
|
|
1483
|
+
}
|
|
1170
1484
|
const settings = source.getSettings();
|
|
1171
1485
|
const width = settings.width ?? 1280;
|
|
1172
1486
|
const height = settings.height ?? 720;
|
|
@@ -1174,23 +1488,28 @@ var VideoPipeline = class {
|
|
|
1174
1488
|
this.source = source;
|
|
1175
1489
|
this.size = { width, height, fps: settings.frameRate ?? 30 };
|
|
1176
1490
|
this.frames = 0;
|
|
1491
|
+
this.movedOff = false;
|
|
1177
1492
|
this.startWatchdog();
|
|
1178
1493
|
if (hasInsertableStreams() && typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
|
|
1179
1494
|
try {
|
|
1180
1495
|
await this.startWorker(source, width, height, await this.backgroundForWorker(this.filter));
|
|
1181
1496
|
this.transport = "worker";
|
|
1497
|
+
this.workerDialect = "streams";
|
|
1182
1498
|
return;
|
|
1183
1499
|
} catch (e) {
|
|
1184
1500
|
this.teardownWorker();
|
|
1501
|
+
if (e instanceof GpuLostError) throw e;
|
|
1185
1502
|
console.warn("mediakit: worker unusable, falling back to the main thread", e);
|
|
1186
1503
|
}
|
|
1187
1504
|
} else if (typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
|
|
1188
1505
|
try {
|
|
1189
1506
|
await this.startWorkerWithTrack(source, width, height, await this.backgroundForWorker(this.filter));
|
|
1190
1507
|
this.transport = "worker";
|
|
1508
|
+
this.workerDialect = "track";
|
|
1191
1509
|
return;
|
|
1192
1510
|
} catch (e) {
|
|
1193
1511
|
this.teardownWorker();
|
|
1512
|
+
if (e instanceof GpuLostError) throw e;
|
|
1194
1513
|
console.warn("mediakit: no worker transport in this browser, staying on the main thread", e);
|
|
1195
1514
|
}
|
|
1196
1515
|
}
|
|
@@ -1198,7 +1517,9 @@ var VideoPipeline = class {
|
|
|
1198
1517
|
}
|
|
1199
1518
|
async startMain(source) {
|
|
1200
1519
|
const { width, height, fps } = this.size;
|
|
1201
|
-
this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces
|
|
1520
|
+
this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces, {
|
|
1521
|
+
noFaceColor: this.noFaceColor()
|
|
1522
|
+
});
|
|
1202
1523
|
this.engine.syncFaces = this.opts.syncFaces ?? false;
|
|
1203
1524
|
this.engine.setDebug(this.debug);
|
|
1204
1525
|
this.transport = hasInsertableStreams() ? "insertable" : "canvas";
|
|
@@ -1211,6 +1532,45 @@ var VideoPipeline = class {
|
|
|
1211
1532
|
await this.startCanvas(source, fps);
|
|
1212
1533
|
}
|
|
1213
1534
|
}
|
|
1535
|
+
/**
|
|
1536
|
+
* Feed a different camera into the running pipeline, as Tencent's `resetCore(input)`. At the
|
|
1537
|
+
* same resolution {@link processedTrack} stays the same track; otherwise the pipeline rebuilds
|
|
1538
|
+
* and `onTrackReplaced` fires. The caller still owns both sources: neither is stopped here.
|
|
1539
|
+
*/
|
|
1540
|
+
async replaceSource(next) {
|
|
1541
|
+
if (this.stopped || !this.source) throw new Error("mediakit: replaceSource before start");
|
|
1542
|
+
const settings = next.getSettings();
|
|
1543
|
+
const width = settings.width ?? 1280;
|
|
1544
|
+
const height = settings.height ?? 720;
|
|
1545
|
+
if (width !== this.size.width || height !== this.size.height) {
|
|
1546
|
+
await this.rebuild(next);
|
|
1547
|
+
return this.processedTrack;
|
|
1548
|
+
}
|
|
1549
|
+
if (this.transport === "worker" && this.workerDialect === "streams") {
|
|
1550
|
+
const processor = new MediaStreamTrackProcessor({ track: next });
|
|
1551
|
+
this.send({ t: "source", readable: processor.readable }, [processor.readable]);
|
|
1552
|
+
} else if (this.transport === "worker") {
|
|
1553
|
+
const clone = next.clone();
|
|
1554
|
+
this.send({ t: "sourceTrack", track: clone }, [clone]);
|
|
1555
|
+
} else if (this.transport === "insertable") {
|
|
1556
|
+
this.pipeInsertable(next);
|
|
1557
|
+
} else if (this.video) {
|
|
1558
|
+
this.video.srcObject = new MediaStream([next]);
|
|
1559
|
+
await this.video.play();
|
|
1560
|
+
}
|
|
1561
|
+
this.source = next;
|
|
1562
|
+
this.size.fps = settings.frameRate ?? this.size.fps;
|
|
1563
|
+
this.lastBeat = performance.now();
|
|
1564
|
+
return this.processedTrack;
|
|
1565
|
+
}
|
|
1566
|
+
async rebuild(source) {
|
|
1567
|
+
const previous = this.processedTrack;
|
|
1568
|
+
this.processedTrack = void 0;
|
|
1569
|
+
this.teardownTransports();
|
|
1570
|
+
await this.start(source);
|
|
1571
|
+
previous?.stop();
|
|
1572
|
+
if (this.processedTrack) this.opts.onTrackReplaced?.(this.processedTrack, previous);
|
|
1573
|
+
}
|
|
1214
1574
|
/** Swap the background in place - no pipeline rebuild, so the picture does not flash. */
|
|
1215
1575
|
async switchTo(filter) {
|
|
1216
1576
|
this.filter = filter;
|
|
@@ -1246,8 +1606,14 @@ var VideoPipeline = class {
|
|
|
1246
1606
|
this.stopped = true;
|
|
1247
1607
|
this.stopWatchdog();
|
|
1248
1608
|
this.source = null;
|
|
1609
|
+
this.teardownTransports();
|
|
1610
|
+
this.processedTrack?.stop();
|
|
1611
|
+
this.processedTrack = void 0;
|
|
1612
|
+
}
|
|
1613
|
+
teardownTransports() {
|
|
1249
1614
|
this.abort?.abort();
|
|
1250
1615
|
this.abort = null;
|
|
1616
|
+
this.generator = null;
|
|
1251
1617
|
if (this.rvfcHandle && this.video) {
|
|
1252
1618
|
this.video.cancelVideoFrameCallback?.(this.rvfcHandle);
|
|
1253
1619
|
}
|
|
@@ -1259,8 +1625,6 @@ var VideoPipeline = class {
|
|
|
1259
1625
|
this.video = null;
|
|
1260
1626
|
}
|
|
1261
1627
|
this.teardownWorker();
|
|
1262
|
-
this.processedTrack?.stop();
|
|
1263
|
-
this.processedTrack = void 0;
|
|
1264
1628
|
this.engine?.close();
|
|
1265
1629
|
this.engine = null;
|
|
1266
1630
|
}
|
|
@@ -1284,6 +1648,7 @@ var VideoPipeline = class {
|
|
|
1284
1648
|
this.send({ t: "stop" });
|
|
1285
1649
|
this.worker.terminate();
|
|
1286
1650
|
this.worker = null;
|
|
1651
|
+
this.workerDialect = null;
|
|
1287
1652
|
this.workerStats = null;
|
|
1288
1653
|
this.workerLoading = false;
|
|
1289
1654
|
this.workerBackgroundPath = null;
|
|
@@ -1339,7 +1704,8 @@ var VideoPipeline = class {
|
|
|
1339
1704
|
alpha: this.opts.alpha,
|
|
1340
1705
|
maxFaces: this.opts.maxFaces,
|
|
1341
1706
|
syncFaces: this.opts.syncFaces,
|
|
1342
|
-
debug: this.debug
|
|
1707
|
+
debug: this.debug,
|
|
1708
|
+
noFaceColor: this.noFaceColor()
|
|
1343
1709
|
},
|
|
1344
1710
|
background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
|
|
1345
1711
|
)
|
|
@@ -1366,7 +1732,8 @@ var VideoPipeline = class {
|
|
|
1366
1732
|
alpha: this.opts.alpha,
|
|
1367
1733
|
maxFaces: this.opts.maxFaces,
|
|
1368
1734
|
syncFaces: this.opts.syncFaces,
|
|
1369
|
-
debug: this.debug
|
|
1735
|
+
debug: this.debug,
|
|
1736
|
+
noFaceColor: this.noFaceColor()
|
|
1370
1737
|
},
|
|
1371
1738
|
background ? [clone, background] : [clone]
|
|
1372
1739
|
)
|
|
@@ -1410,6 +1777,15 @@ var VideoPipeline = class {
|
|
|
1410
1777
|
this.deliver(m.frame);
|
|
1411
1778
|
return;
|
|
1412
1779
|
}
|
|
1780
|
+
if (m.t === "lost") {
|
|
1781
|
+
const gpu = m.gpu || this.gpu;
|
|
1782
|
+
if (settled) void this.recoverGpu("the worker's WebGL context was lost", m.phase, gpu);
|
|
1783
|
+
else {
|
|
1784
|
+
recordLoss(gpu, m.phase);
|
|
1785
|
+
fail(m.phase === "init" ? new GpuLostError("init", gpu, m.message) : new Error("mediakit: the worker's WebGL context was lost"));
|
|
1786
|
+
}
|
|
1787
|
+
return;
|
|
1788
|
+
}
|
|
1413
1789
|
if (m.t === "error") {
|
|
1414
1790
|
if (settled) {
|
|
1415
1791
|
console.error("mediakit: worker failed after start", m.message);
|
|
@@ -1440,17 +1816,27 @@ var VideoPipeline = class {
|
|
|
1440
1816
|
}
|
|
1441
1817
|
// ── insertable ───────────────────────────────────────────────────────────────────
|
|
1442
1818
|
startInsertable(source) {
|
|
1443
|
-
|
|
1444
|
-
const processor = new MediaStreamTrackProcessor({
|
|
1445
|
-
track: source
|
|
1446
|
-
});
|
|
1447
|
-
const generator = new MediaStreamTrackGenerator({
|
|
1819
|
+
this.generator = new MediaStreamTrackGenerator({
|
|
1448
1820
|
kind: "video",
|
|
1449
1821
|
signalTarget: source
|
|
1450
1822
|
});
|
|
1823
|
+
this.processedTrack = this.generator;
|
|
1824
|
+
this.pipeInsertable(source);
|
|
1825
|
+
}
|
|
1826
|
+
pipeInsertable(source) {
|
|
1827
|
+
const generator = this.generator;
|
|
1828
|
+
if (!generator) return;
|
|
1829
|
+
const processor = new MediaStreamTrackProcessor({
|
|
1830
|
+
track: source
|
|
1831
|
+
});
|
|
1451
1832
|
const transform = new TransformStream({
|
|
1452
1833
|
transform: (frame, controller) => {
|
|
1453
1834
|
this.beat();
|
|
1835
|
+
const engine = this.engine;
|
|
1836
|
+
if (!engine) {
|
|
1837
|
+
controller.enqueue(frame);
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1454
1840
|
try {
|
|
1455
1841
|
const drew = engine.render(frame, frame.timestamp);
|
|
1456
1842
|
const held = drew ? null : engine.passthrough();
|
|
@@ -1473,11 +1859,16 @@ var VideoPipeline = class {
|
|
|
1473
1859
|
frame.close();
|
|
1474
1860
|
}
|
|
1475
1861
|
});
|
|
1476
|
-
this.abort
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1862
|
+
this.abort?.abort();
|
|
1863
|
+
const abort = new AbortController();
|
|
1864
|
+
this.abort = abort;
|
|
1865
|
+
const previous = this.piping;
|
|
1866
|
+
this.piping = previous.then(() => {
|
|
1867
|
+
if (abort.signal.aborted) return;
|
|
1868
|
+
return processor.readable.pipeThrough(transform, { signal: abort.signal }).pipeTo(generator.writable, { signal: abort.signal, preventAbort: true, preventClose: true }).catch((e) => {
|
|
1869
|
+
if (abort.signal.aborted) return;
|
|
1870
|
+
if (!this.stopped) console.error("mediakit: pipe broke", e);
|
|
1871
|
+
});
|
|
1481
1872
|
});
|
|
1482
1873
|
}
|
|
1483
1874
|
// ── canvas ───────────────────────────────────────────────────────────────────────
|
|
@@ -2872,11 +3263,15 @@ export {
|
|
|
2872
3263
|
EFFECTS_SCHEMA,
|
|
2873
3264
|
Engine,
|
|
2874
3265
|
FACE_UV,
|
|
3266
|
+
GpuLostError,
|
|
2875
3267
|
NO_EFFECTS,
|
|
2876
3268
|
Scene,
|
|
2877
3269
|
TOUCH_UP,
|
|
2878
3270
|
TRANSITIONS,
|
|
2879
3271
|
VideoPipeline,
|
|
3272
|
+
checkSupport,
|
|
3273
|
+
forgetGpuFailures,
|
|
3274
|
+
gpuRecord,
|
|
2880
3275
|
hitTest,
|
|
2881
3276
|
layouts,
|
|
2882
3277
|
mediakitSupported,
|
|
@@ -2885,6 +3280,7 @@ export {
|
|
|
2885
3280
|
needsSegmentation,
|
|
2886
3281
|
normalizeEffects,
|
|
2887
3282
|
parseColor,
|
|
3283
|
+
preloadDetectors,
|
|
2888
3284
|
renderText,
|
|
2889
3285
|
touchUp,
|
|
2890
3286
|
touchUpAmount
|