@tradalab/mediakit 2.4.0 → 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 +116 -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 +119 -5
- package/dist/index.js +471 -64
- 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 +299 -49
- 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,16 +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;
|
|
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
|
+
}
|
|
310
445
|
function sourceSize(source) {
|
|
311
446
|
if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
|
|
312
447
|
if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
|
|
313
448
|
const s = source;
|
|
314
449
|
return [s.width, s.height];
|
|
315
450
|
}
|
|
451
|
+
var FACE_COLOR_SKIPPED = "face colour shaders skipped: linking one lost the WebGL context on this GPU before";
|
|
316
452
|
var Engine = class _Engine {
|
|
317
453
|
canvas;
|
|
318
454
|
gl;
|
|
@@ -343,6 +479,14 @@ var Engine = class _Engine {
|
|
|
343
479
|
classLoading = null;
|
|
344
480
|
/** The segmenter whose result this frame borrowed, to give it back after process(). */
|
|
345
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();
|
|
346
490
|
/**
|
|
347
491
|
* The landmark detector, also lazy and independent of the segmenter.
|
|
348
492
|
*
|
|
@@ -367,6 +511,7 @@ var Engine = class _Engine {
|
|
|
367
511
|
gapUs = 33333;
|
|
368
512
|
prevTs = -1;
|
|
369
513
|
sent = /* @__PURE__ */ new Map();
|
|
514
|
+
lastSentAt = /* @__PURE__ */ new Map();
|
|
370
515
|
faceLatencyMs = 0;
|
|
371
516
|
maskLatencyMs = /* @__PURE__ */ new Map();
|
|
372
517
|
faceTs = -1;
|
|
@@ -401,19 +546,20 @@ var Engine = class _Engine {
|
|
|
401
546
|
this.core = core;
|
|
402
547
|
}
|
|
403
548
|
/** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */
|
|
404
|
-
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 = {}) {
|
|
405
550
|
const canvas = document.createElement("canvas");
|
|
406
551
|
canvas.width = width;
|
|
407
552
|
canvas.height = height;
|
|
408
|
-
return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces);
|
|
553
|
+
return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces, guard);
|
|
409
554
|
}
|
|
410
555
|
/**
|
|
411
556
|
* `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
|
|
412
557
|
* only a `cutout` background writes; it is fixed for the life of the context, so a host that
|
|
413
558
|
* may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
|
|
414
|
-
* 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.
|
|
415
561
|
*/
|
|
416
|
-
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 = {}) {
|
|
417
563
|
const width = canvas.width;
|
|
418
564
|
const height = canvas.height;
|
|
419
565
|
const gl = canvas.getContext("webgl2", {
|
|
@@ -423,14 +569,26 @@ var Engine = class _Engine {
|
|
|
423
569
|
depth: false,
|
|
424
570
|
stencil: false
|
|
425
571
|
});
|
|
426
|
-
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
|
+
}
|
|
427
579
|
let core;
|
|
428
580
|
let engine;
|
|
429
581
|
try {
|
|
430
582
|
core = await loadCore();
|
|
431
583
|
const err = core.init(gl, width, height);
|
|
432
|
-
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)}]`);
|
|
433
589
|
engine = new _Engine(canvas, gl, core);
|
|
590
|
+
engine.gpu = gpu;
|
|
591
|
+
if (guard.noFaceColor || known?.faceColor) core.disableFaceColor?.(FACE_COLOR_SKIPPED);
|
|
434
592
|
engine.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3));
|
|
435
593
|
await engine.setRecipe(filter, effects, background);
|
|
436
594
|
return engine;
|
|
@@ -446,9 +604,29 @@ var Engine = class _Engine {
|
|
|
446
604
|
throw err;
|
|
447
605
|
}
|
|
448
606
|
}
|
|
607
|
+
/** The GPU the context reported at creation, "" when the browser hides it. */
|
|
608
|
+
get gpuName() {
|
|
609
|
+
return this.gpu;
|
|
610
|
+
}
|
|
449
611
|
get loading() {
|
|
450
612
|
return this.segmenterLoading !== null || this.classLoading !== null || this.faceLoading !== null;
|
|
451
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
|
+
}
|
|
452
630
|
get outputCanvas() {
|
|
453
631
|
return this.canvas;
|
|
454
632
|
}
|
|
@@ -535,13 +713,29 @@ var Engine = class _Engine {
|
|
|
535
713
|
this.makeupPath = makeupTexture;
|
|
536
714
|
}
|
|
537
715
|
this.core.setRecipe(coreRecipe(filter, effects));
|
|
538
|
-
|
|
716
|
+
this.noteLinking();
|
|
717
|
+
if (needsSegmentation(filter, effects) && !this.remoteMaskComing(filter, effects)) void this.ensureSegmenter();
|
|
539
718
|
if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
|
|
540
719
|
if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
|
|
541
720
|
if (needsFace(effects)) void this.ensureFace();
|
|
542
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
|
+
}
|
|
543
737
|
ensureFace() {
|
|
544
|
-
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();
|
|
545
739
|
if (this.faceLoading) return this.faceLoading;
|
|
546
740
|
const buf = this.core.faceBuffer();
|
|
547
741
|
if (!buf) return Promise.resolve();
|
|
@@ -550,8 +744,9 @@ var Engine = class _Engine {
|
|
|
550
744
|
this.faceRemote = true;
|
|
551
745
|
this.lmBuf = buf;
|
|
552
746
|
}).catch((e) => {
|
|
747
|
+
if (e instanceof LoadTimeout) throw e;
|
|
553
748
|
if (!this.inThread.has("face")) console.warn("mediakit: no detect worker for faces, detecting in this thread", e);
|
|
554
|
-
return createFaceDetector(this.canvas, n).then((f) => {
|
|
749
|
+
return withTimeout(createFaceDetector(this.canvas, n), LOAD_MS, "face detection", (f) => f.close()).then((f) => {
|
|
555
750
|
if (this.closed) {
|
|
556
751
|
f.close();
|
|
557
752
|
return;
|
|
@@ -560,7 +755,9 @@ var Engine = class _Engine {
|
|
|
560
755
|
this.lmBuf = buf;
|
|
561
756
|
});
|
|
562
757
|
}).catch((e) => {
|
|
563
|
-
|
|
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);
|
|
564
761
|
}).finally(() => {
|
|
565
762
|
this.faceLoading = null;
|
|
566
763
|
});
|
|
@@ -571,10 +768,13 @@ var Engine = class _Engine {
|
|
|
571
768
|
return filter.kind === "none" && needsSegmentation(filter, effects) && !needsSkinClasses(filter, effects);
|
|
572
769
|
}
|
|
573
770
|
ensurePersonRemote() {
|
|
574
|
-
if (this.personRemote || this.closed) return Promise.resolve();
|
|
771
|
+
if (this.personRemote || this.failed.has("person") || this.closed) return Promise.resolve();
|
|
575
772
|
this.personLoading ??= this.remote("person", (d) => d.initMask("person")).then(() => {
|
|
576
773
|
this.personRemote = true;
|
|
577
|
-
}).catch(() => {
|
|
774
|
+
}).catch((e) => {
|
|
775
|
+
if (!(e instanceof LoadTimeout)) return;
|
|
776
|
+
this.failed.add("person");
|
|
777
|
+
this.gaveUp("background effects", e);
|
|
578
778
|
}).finally(() => {
|
|
579
779
|
this.personLoading = null;
|
|
580
780
|
});
|
|
@@ -582,6 +782,7 @@ var Engine = class _Engine {
|
|
|
582
782
|
}
|
|
583
783
|
async remote(kind, init) {
|
|
584
784
|
if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
|
|
785
|
+
this.inThread.add(kind);
|
|
585
786
|
throw new Error("in-thread");
|
|
586
787
|
}
|
|
587
788
|
let detect = this.detects.get(kind);
|
|
@@ -592,7 +793,10 @@ var Engine = class _Engine {
|
|
|
592
793
|
try {
|
|
593
794
|
await init(detect);
|
|
594
795
|
} catch (e) {
|
|
595
|
-
|
|
796
|
+
if (e instanceof LoadTimeout) {
|
|
797
|
+
detect.close();
|
|
798
|
+
this.detects.delete(kind);
|
|
799
|
+
} else this.inThread.add(kind);
|
|
596
800
|
throw e;
|
|
597
801
|
}
|
|
598
802
|
if (this.closed) throw new Error("closed");
|
|
@@ -671,6 +875,7 @@ var Engine = class _Engine {
|
|
|
671
875
|
requestRemote(kind, source, timestampUs) {
|
|
672
876
|
const detect = this.detects.get(kind);
|
|
673
877
|
if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
|
|
878
|
+
if (!this.dutyAllows(kind)) return;
|
|
674
879
|
let frame = null;
|
|
675
880
|
try {
|
|
676
881
|
const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
|
|
@@ -680,7 +885,9 @@ var Engine = class _Engine {
|
|
|
680
885
|
} catch {
|
|
681
886
|
}
|
|
682
887
|
if (frame && detect.request(kind === "face" ? "face" : "mask", frame, timestampUs)) {
|
|
683
|
-
|
|
888
|
+
const now2 = performance.now();
|
|
889
|
+
this.sent.set(kind, { ts: timestampUs, at: now2 });
|
|
890
|
+
this.lastSentAt.set(kind, now2);
|
|
684
891
|
}
|
|
685
892
|
}
|
|
686
893
|
/** Face and mask asked on the same frame share one draw. */
|
|
@@ -701,36 +908,42 @@ var Engine = class _Engine {
|
|
|
701
908
|
return this.detectCanvas;
|
|
702
909
|
}
|
|
703
910
|
ensureClassSegmenter() {
|
|
704
|
-
if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
|
|
911
|
+
if (this.classSegmenter || this.classRemote || this.classFailed || this.closed) return Promise.resolve();
|
|
705
912
|
if (this.classLoading) return this.classLoading;
|
|
706
913
|
this.classLoading = this.remote("mask", (d) => d.initMask("classes")).then(() => {
|
|
707
914
|
this.classRemote = true;
|
|
708
|
-
}).catch(
|
|
709
|
-
(
|
|
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) => {
|
|
710
918
|
if (this.closed) {
|
|
711
919
|
s.close();
|
|
712
920
|
return;
|
|
713
921
|
}
|
|
714
922
|
this.classSegmenter = s;
|
|
715
|
-
})
|
|
716
|
-
).catch((e) => {
|
|
717
|
-
|
|
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();
|
|
718
929
|
}).finally(() => {
|
|
719
930
|
this.classLoading = null;
|
|
720
931
|
});
|
|
721
932
|
return this.classLoading;
|
|
722
933
|
}
|
|
723
934
|
ensureSegmenter() {
|
|
724
|
-
if (this.segmenter || this.closed) return Promise.resolve();
|
|
935
|
+
if (this.segmenter || this.failed.has("segmenter") || this.closed) return Promise.resolve();
|
|
725
936
|
if (this.segmenterLoading) return this.segmenterLoading;
|
|
726
|
-
this.segmenterLoading = createSegmenter(this.canvas).then((s) => {
|
|
937
|
+
this.segmenterLoading = withTimeout(createSegmenter(this.canvas), LOAD_MS, "person segmentation", (s) => s.close()).then((s) => {
|
|
727
938
|
if (this.closed) {
|
|
728
939
|
s.close();
|
|
729
940
|
return;
|
|
730
941
|
}
|
|
731
942
|
this.segmenter = s;
|
|
732
943
|
}).catch((e) => {
|
|
733
|
-
|
|
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);
|
|
734
947
|
}).finally(() => {
|
|
735
948
|
this.segmenterLoading = null;
|
|
736
949
|
});
|
|
@@ -749,7 +962,7 @@ var Engine = class _Engine {
|
|
|
749
962
|
* it constructs one only to destroy it again.
|
|
750
963
|
*/
|
|
751
964
|
render(source, timestampUs) {
|
|
752
|
-
if (this.closed) return false;
|
|
965
|
+
if (this.closed || this.lostDuring) return false;
|
|
753
966
|
if (this.lastHeld) this.spare.push(this.lastHeld);
|
|
754
967
|
this.lastHeld = null;
|
|
755
968
|
this.swallowed = false;
|
|
@@ -795,6 +1008,12 @@ var Engine = class _Engine {
|
|
|
795
1008
|
this.depthVotes = 0;
|
|
796
1009
|
}
|
|
797
1010
|
}
|
|
1011
|
+
dutyAllows(kind) {
|
|
1012
|
+
const took = kind === "face" ? this.faceLatencyMs : this.maskLatencyMs.get(kind) ?? 0;
|
|
1013
|
+
if (took * 1e3 < this.gapUs) return true;
|
|
1014
|
+
const last = this.lastSentAt.get(kind);
|
|
1015
|
+
return last === void 0 || performance.now() - last >= took / DETECT_DUTY;
|
|
1016
|
+
}
|
|
798
1017
|
took(kind, tsUs) {
|
|
799
1018
|
const s = this.sent.get(kind);
|
|
800
1019
|
if (s?.ts !== tsUs) return null;
|
|
@@ -862,7 +1081,7 @@ var Engine = class _Engine {
|
|
|
862
1081
|
const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
|
|
863
1082
|
const seg = classes ? this.classSegmenter : this.segmenter;
|
|
864
1083
|
if (!seg) {
|
|
865
|
-
void this.ensureSegmenter();
|
|
1084
|
+
if (!this.remoteMaskComing(this.filter, this.effects)) void this.ensureSegmenter();
|
|
866
1085
|
} else {
|
|
867
1086
|
const s0 = performance.now();
|
|
868
1087
|
mask = seg.segment(source, timestampUs / 1e3);
|
|
@@ -894,6 +1113,14 @@ var Engine = class _Engine {
|
|
|
894
1113
|
const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
|
|
895
1114
|
if (mask) this.used?.release();
|
|
896
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
|
+
}
|
|
897
1124
|
this.prevSegMs = segMs;
|
|
898
1125
|
this.prevTotalMs = performance.now() - t0;
|
|
899
1126
|
const s = this.core.stats();
|
|
@@ -916,7 +1143,8 @@ var Engine = class _Engine {
|
|
|
916
1143
|
faces: s ? s[12] : 0,
|
|
917
1144
|
heldFrames: faceDone ? this.holdDepth : 0,
|
|
918
1145
|
faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
|
|
919
|
-
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
|
|
920
1148
|
};
|
|
921
1149
|
return glCalls > 0;
|
|
922
1150
|
}
|
|
@@ -1014,6 +1242,9 @@ async function coverCrop(src, w, h) {
|
|
|
1014
1242
|
}
|
|
1015
1243
|
|
|
1016
1244
|
// src/pipeline.ts
|
|
1245
|
+
var SLOW_FRAME_MS = 150;
|
|
1246
|
+
var SLOW_TICKS = 3;
|
|
1247
|
+
var MAX_GPU_RECOVERIES = 2;
|
|
1017
1248
|
var WORKER_READY_MS = 8e3;
|
|
1018
1249
|
var STALL_MS = 2e3;
|
|
1019
1250
|
var LOADING_STALL_MS = 2e4;
|
|
@@ -1021,12 +1252,40 @@ var WORKER_DEAD_MS = 8e3;
|
|
|
1021
1252
|
function hasInsertableStreams() {
|
|
1022
1253
|
return typeof window !== "undefined" && "MediaStreamTrackProcessor" in window && "MediaStreamTrackGenerator" in window;
|
|
1023
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
|
+
}
|
|
1024
1287
|
function mediakitSupported() {
|
|
1025
|
-
|
|
1026
|
-
if (typeof WebAssembly === "undefined") return false;
|
|
1027
|
-
const probe = document.createElement("canvas");
|
|
1028
|
-
if (!probe.getContext("webgl2")) return false;
|
|
1029
|
-
return hasInsertableStreams() || "captureStream" in HTMLCanvasElement.prototype;
|
|
1288
|
+
return checkSupport().supported;
|
|
1030
1289
|
}
|
|
1031
1290
|
var VideoPipeline = class {
|
|
1032
1291
|
processedTrack;
|
|
@@ -1042,6 +1301,15 @@ var VideoPipeline = class {
|
|
|
1042
1301
|
stalled = false;
|
|
1043
1302
|
watchdog = null;
|
|
1044
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();
|
|
1045
1313
|
/** What the worker last said about loading detectors. */
|
|
1046
1314
|
workerLoading = false;
|
|
1047
1315
|
// Frames handed out alongside the track - see subscribeFrames.
|
|
@@ -1071,7 +1339,8 @@ var VideoPipeline = class {
|
|
|
1071
1339
|
transport: this.transport,
|
|
1072
1340
|
frames: this.frames,
|
|
1073
1341
|
sinceMs: this.lastBeat ? performance.now() - this.lastBeat : 0,
|
|
1074
|
-
stalled: this.stalled
|
|
1342
|
+
stalled: this.stalled,
|
|
1343
|
+
effectError: this.stats?.effectError ?? ""
|
|
1075
1344
|
};
|
|
1076
1345
|
}
|
|
1077
1346
|
/** Every processed frame. */
|
|
@@ -1097,6 +1366,55 @@ var VideoPipeline = class {
|
|
|
1097
1366
|
}
|
|
1098
1367
|
});
|
|
1099
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
|
+
}
|
|
1100
1418
|
beat() {
|
|
1101
1419
|
this.lastBeat = performance.now();
|
|
1102
1420
|
this.frames++;
|
|
@@ -1120,9 +1438,11 @@ var VideoPipeline = class {
|
|
|
1120
1438
|
const transport = this.transport;
|
|
1121
1439
|
if (since >= (loading ? LOADING_STALL_MS : STALL_MS) && !this.stalled) {
|
|
1122
1440
|
this.stalled = true;
|
|
1123
|
-
|
|
1441
|
+
this.issue("stall", `no frame out for ${Math.round(since)}ms on the ${transport} transport`);
|
|
1124
1442
|
this.opts.onStall?.({ transport, sinceMs: since });
|
|
1125
1443
|
}
|
|
1444
|
+
if (!this.stalled) this.raised.delete("stall");
|
|
1445
|
+
this.watchQuality();
|
|
1126
1446
|
if (transport === "worker" && since >= (loading ? LOADING_STALL_MS : WORKER_DEAD_MS)) {
|
|
1127
1447
|
void this.moveOffWorker("silent");
|
|
1128
1448
|
}
|
|
@@ -1136,7 +1456,7 @@ var VideoPipeline = class {
|
|
|
1136
1456
|
async moveOffWorker(reason) {
|
|
1137
1457
|
if (this.movedOff || this.stopped || !this.source) return;
|
|
1138
1458
|
this.movedOff = true;
|
|
1139
|
-
|
|
1459
|
+
this.issue("worker-moved", `worker ${reason} after start, moving to the main thread`);
|
|
1140
1460
|
const previous = this.processedTrack;
|
|
1141
1461
|
this.teardownWorker();
|
|
1142
1462
|
try {
|
|
@@ -1156,6 +1476,11 @@ var VideoPipeline = class {
|
|
|
1156
1476
|
}
|
|
1157
1477
|
/** Take over `source` and publish the result on {@link processedTrack}. */
|
|
1158
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
|
+
}
|
|
1159
1484
|
const settings = source.getSettings();
|
|
1160
1485
|
const width = settings.width ?? 1280;
|
|
1161
1486
|
const height = settings.height ?? 720;
|
|
@@ -1163,23 +1488,28 @@ var VideoPipeline = class {
|
|
|
1163
1488
|
this.source = source;
|
|
1164
1489
|
this.size = { width, height, fps: settings.frameRate ?? 30 };
|
|
1165
1490
|
this.frames = 0;
|
|
1491
|
+
this.movedOff = false;
|
|
1166
1492
|
this.startWatchdog();
|
|
1167
1493
|
if (hasInsertableStreams() && typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
|
|
1168
1494
|
try {
|
|
1169
1495
|
await this.startWorker(source, width, height, await this.backgroundForWorker(this.filter));
|
|
1170
1496
|
this.transport = "worker";
|
|
1497
|
+
this.workerDialect = "streams";
|
|
1171
1498
|
return;
|
|
1172
1499
|
} catch (e) {
|
|
1173
1500
|
this.teardownWorker();
|
|
1501
|
+
if (e instanceof GpuLostError) throw e;
|
|
1174
1502
|
console.warn("mediakit: worker unusable, falling back to the main thread", e);
|
|
1175
1503
|
}
|
|
1176
1504
|
} else if (typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
|
|
1177
1505
|
try {
|
|
1178
1506
|
await this.startWorkerWithTrack(source, width, height, await this.backgroundForWorker(this.filter));
|
|
1179
1507
|
this.transport = "worker";
|
|
1508
|
+
this.workerDialect = "track";
|
|
1180
1509
|
return;
|
|
1181
1510
|
} catch (e) {
|
|
1182
1511
|
this.teardownWorker();
|
|
1512
|
+
if (e instanceof GpuLostError) throw e;
|
|
1183
1513
|
console.warn("mediakit: no worker transport in this browser, staying on the main thread", e);
|
|
1184
1514
|
}
|
|
1185
1515
|
}
|
|
@@ -1187,7 +1517,9 @@ var VideoPipeline = class {
|
|
|
1187
1517
|
}
|
|
1188
1518
|
async startMain(source) {
|
|
1189
1519
|
const { width, height, fps } = this.size;
|
|
1190
|
-
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
|
+
});
|
|
1191
1523
|
this.engine.syncFaces = this.opts.syncFaces ?? false;
|
|
1192
1524
|
this.engine.setDebug(this.debug);
|
|
1193
1525
|
this.transport = hasInsertableStreams() ? "insertable" : "canvas";
|
|
@@ -1200,6 +1532,45 @@ var VideoPipeline = class {
|
|
|
1200
1532
|
await this.startCanvas(source, fps);
|
|
1201
1533
|
}
|
|
1202
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
|
+
}
|
|
1203
1574
|
/** Swap the background in place - no pipeline rebuild, so the picture does not flash. */
|
|
1204
1575
|
async switchTo(filter) {
|
|
1205
1576
|
this.filter = filter;
|
|
@@ -1235,8 +1606,14 @@ var VideoPipeline = class {
|
|
|
1235
1606
|
this.stopped = true;
|
|
1236
1607
|
this.stopWatchdog();
|
|
1237
1608
|
this.source = null;
|
|
1609
|
+
this.teardownTransports();
|
|
1610
|
+
this.processedTrack?.stop();
|
|
1611
|
+
this.processedTrack = void 0;
|
|
1612
|
+
}
|
|
1613
|
+
teardownTransports() {
|
|
1238
1614
|
this.abort?.abort();
|
|
1239
1615
|
this.abort = null;
|
|
1616
|
+
this.generator = null;
|
|
1240
1617
|
if (this.rvfcHandle && this.video) {
|
|
1241
1618
|
this.video.cancelVideoFrameCallback?.(this.rvfcHandle);
|
|
1242
1619
|
}
|
|
@@ -1248,8 +1625,6 @@ var VideoPipeline = class {
|
|
|
1248
1625
|
this.video = null;
|
|
1249
1626
|
}
|
|
1250
1627
|
this.teardownWorker();
|
|
1251
|
-
this.processedTrack?.stop();
|
|
1252
|
-
this.processedTrack = void 0;
|
|
1253
1628
|
this.engine?.close();
|
|
1254
1629
|
this.engine = null;
|
|
1255
1630
|
}
|
|
@@ -1273,6 +1648,7 @@ var VideoPipeline = class {
|
|
|
1273
1648
|
this.send({ t: "stop" });
|
|
1274
1649
|
this.worker.terminate();
|
|
1275
1650
|
this.worker = null;
|
|
1651
|
+
this.workerDialect = null;
|
|
1276
1652
|
this.workerStats = null;
|
|
1277
1653
|
this.workerLoading = false;
|
|
1278
1654
|
this.workerBackgroundPath = null;
|
|
@@ -1328,7 +1704,8 @@ var VideoPipeline = class {
|
|
|
1328
1704
|
alpha: this.opts.alpha,
|
|
1329
1705
|
maxFaces: this.opts.maxFaces,
|
|
1330
1706
|
syncFaces: this.opts.syncFaces,
|
|
1331
|
-
debug: this.debug
|
|
1707
|
+
debug: this.debug,
|
|
1708
|
+
noFaceColor: this.noFaceColor()
|
|
1332
1709
|
},
|
|
1333
1710
|
background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
|
|
1334
1711
|
)
|
|
@@ -1355,7 +1732,8 @@ var VideoPipeline = class {
|
|
|
1355
1732
|
alpha: this.opts.alpha,
|
|
1356
1733
|
maxFaces: this.opts.maxFaces,
|
|
1357
1734
|
syncFaces: this.opts.syncFaces,
|
|
1358
|
-
debug: this.debug
|
|
1735
|
+
debug: this.debug,
|
|
1736
|
+
noFaceColor: this.noFaceColor()
|
|
1359
1737
|
},
|
|
1360
1738
|
background ? [clone, background] : [clone]
|
|
1361
1739
|
)
|
|
@@ -1399,6 +1777,15 @@ var VideoPipeline = class {
|
|
|
1399
1777
|
this.deliver(m.frame);
|
|
1400
1778
|
return;
|
|
1401
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
|
+
}
|
|
1402
1789
|
if (m.t === "error") {
|
|
1403
1790
|
if (settled) {
|
|
1404
1791
|
console.error("mediakit: worker failed after start", m.message);
|
|
@@ -1429,17 +1816,27 @@ var VideoPipeline = class {
|
|
|
1429
1816
|
}
|
|
1430
1817
|
// ── insertable ───────────────────────────────────────────────────────────────────
|
|
1431
1818
|
startInsertable(source) {
|
|
1432
|
-
|
|
1433
|
-
const processor = new MediaStreamTrackProcessor({
|
|
1434
|
-
track: source
|
|
1435
|
-
});
|
|
1436
|
-
const generator = new MediaStreamTrackGenerator({
|
|
1819
|
+
this.generator = new MediaStreamTrackGenerator({
|
|
1437
1820
|
kind: "video",
|
|
1438
1821
|
signalTarget: source
|
|
1439
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
|
+
});
|
|
1440
1832
|
const transform = new TransformStream({
|
|
1441
1833
|
transform: (frame, controller) => {
|
|
1442
1834
|
this.beat();
|
|
1835
|
+
const engine = this.engine;
|
|
1836
|
+
if (!engine) {
|
|
1837
|
+
controller.enqueue(frame);
|
|
1838
|
+
return;
|
|
1839
|
+
}
|
|
1443
1840
|
try {
|
|
1444
1841
|
const drew = engine.render(frame, frame.timestamp);
|
|
1445
1842
|
const held = drew ? null : engine.passthrough();
|
|
@@ -1462,11 +1859,16 @@ var VideoPipeline = class {
|
|
|
1462
1859
|
frame.close();
|
|
1463
1860
|
}
|
|
1464
1861
|
});
|
|
1465
|
-
this.abort
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
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
|
+
});
|
|
1470
1872
|
});
|
|
1471
1873
|
}
|
|
1472
1874
|
// ── canvas ───────────────────────────────────────────────────────────────────────
|
|
@@ -2861,11 +3263,15 @@ export {
|
|
|
2861
3263
|
EFFECTS_SCHEMA,
|
|
2862
3264
|
Engine,
|
|
2863
3265
|
FACE_UV,
|
|
3266
|
+
GpuLostError,
|
|
2864
3267
|
NO_EFFECTS,
|
|
2865
3268
|
Scene,
|
|
2866
3269
|
TOUCH_UP,
|
|
2867
3270
|
TRANSITIONS,
|
|
2868
3271
|
VideoPipeline,
|
|
3272
|
+
checkSupport,
|
|
3273
|
+
forgetGpuFailures,
|
|
3274
|
+
gpuRecord,
|
|
2869
3275
|
hitTest,
|
|
2870
3276
|
layouts,
|
|
2871
3277
|
mediakitSupported,
|
|
@@ -2874,6 +3280,7 @@ export {
|
|
|
2874
3280
|
needsSegmentation,
|
|
2875
3281
|
normalizeEffects,
|
|
2876
3282
|
parseColor,
|
|
3283
|
+
preloadDetectors,
|
|
2877
3284
|
renderText,
|
|
2878
3285
|
touchUp,
|
|
2879
3286
|
touchUpAmount
|