@tradalab/mediakit 2.4.1 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ import {
12
12
  normalizeEffects,
13
13
  touchUp,
14
14
  touchUpAmount
15
- } from "./chunk-YW75KJJO.js";
15
+ } from "./chunk-4YCBTZRB.js";
16
16
  import {
17
17
  BLEND_MODES,
18
18
  TRANSITIONS,
@@ -23,15 +23,92 @@ import {
23
23
  } from "./chunk-BMIOUOT3.js";
24
24
 
25
25
  // src/segmenter.ts
26
- import { FilesetResolver, ImageSegmenter } from "@mediapipe/tasks-vision";
27
- var WASM_DIR = "/mediakit/mp";
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"
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
+ }
31
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/mp-clock.ts
93
+ var SOURCE_SWITCH_GAP_MS = 33;
94
+ function monotonicClock() {
95
+ let offset = 0;
96
+ let last = -Infinity;
97
+ return (timestampMs) => {
98
+ let t = timestampMs + offset;
99
+ if (t <= last) {
100
+ offset += last + SOURCE_SWITCH_GAP_MS - t;
101
+ t = last + SOURCE_SWITCH_GAP_MS;
102
+ }
103
+ last = t;
104
+ return t;
105
+ };
106
+ }
107
+
108
+ // src/segmenter.ts
32
109
  async function createSegmenter(canvas, model = "person") {
33
- const fileset = await FilesetResolver.forVisionTasks(WASM_DIR);
34
- const segmenter = await ImageSegmenter.createFromOptions(fileset, {
110
+ const fileset2 = await visionFileset();
111
+ const segmenter = await ImageSegmenter.createFromOptions(fileset2, {
35
112
  baseOptions: {
36
113
  modelAssetPath: MODEL_URL[model],
37
114
  // MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all
@@ -47,6 +124,7 @@ async function createSegmenter(canvas, model = "person") {
47
124
  outputCategoryMask: true,
48
125
  outputConfidenceMasks: false
49
126
  });
127
+ const clock = monotonicClock();
50
128
  let pending = null;
51
129
  const release = () => {
52
130
  pending?.close();
@@ -56,7 +134,7 @@ async function createSegmenter(canvas, model = "person") {
56
134
  segment(frame, timestampMs) {
57
135
  release();
58
136
  let texture = null;
59
- segmenter.segmentForVideo(frame, timestampMs, (result) => {
137
+ segmenter.segmentForVideo(frame, clock(timestampMs), (result) => {
60
138
  const mask = result.categoryMask;
61
139
  if (mask) texture = mask.getAsWebGLTexture();
62
140
  pending = result;
@@ -72,16 +150,28 @@ async function createSegmenter(canvas, model = "person") {
72
150
  }
73
151
 
74
152
  // src/face.ts
75
- import { FaceLandmarker, FilesetResolver as FilesetResolver2 } from "@mediapipe/tasks-vision";
76
- var WASM_DIR2 = "/mediakit/mp";
77
- var MODEL_URL2 = "/mediakit/face_landmarker.task";
153
+ import { FaceLandmarker } from "@mediapipe/tasks-vision";
78
154
  var FACE_FLOATS = 478 * 3;
79
- async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
80
- const fileset = await FilesetResolver2.forVisionTasks(WASM_DIR2);
81
- const landmarker = await FaceLandmarker.createFromOptions(fileset, {
82
- baseOptions: { modelAssetPath: MODEL_URL2, delegate },
155
+ var COVER_SIZE = 96;
156
+ function faceBox(lm, at) {
157
+ let x0 = 1;
158
+ let y0 = 1;
159
+ let x1 = 0;
160
+ let y1 = 0;
161
+ for (let i = at; i < at + FACE_FLOATS; i += 3) {
162
+ x0 = Math.min(x0, lm[i]);
163
+ x1 = Math.max(x1, lm[i]);
164
+ y0 = Math.min(y0, lm[i + 1]);
165
+ y1 = Math.max(y1, lm[i + 1]);
166
+ }
167
+ return [x0, y0, x1 - x0, y1 - y0];
168
+ }
169
+ async function createFaceDetector(canvas, maxFaces, delegate = "GPU", mode = "VIDEO") {
170
+ const fileset2 = await visionFileset();
171
+ const landmarker = await FaceLandmarker.createFromOptions(fileset2, {
172
+ baseOptions: { modelAssetPath: MODEL_URL.face, delegate },
83
173
  canvas,
84
- runningMode: "VIDEO",
174
+ runningMode: mode,
85
175
  // As many as the core tracks: one landmark pass returns them all, so the cost of a second
86
176
  // face is the copy below and its own shader passes, not a second inference.
87
177
  numFaces: maxFaces,
@@ -89,9 +179,10 @@ async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
89
179
  outputFaceBlendshapes: false,
90
180
  outputFacialTransformationMatrixes: false
91
181
  });
182
+ const clock = monotonicClock();
92
183
  return {
93
184
  detect(frame, timestampMs, out) {
94
- const res = landmarker.detectForVideo(frame, timestampMs);
185
+ const res = mode === "VIDEO" ? landmarker.detectForVideo(frame, clock(timestampMs)) : landmarker.detect(frame);
95
186
  let n = 0;
96
187
  for (const lm of res.faceLandmarks ?? []) {
97
188
  if (lm.length * 3 !== FACE_FLOATS || n + FACE_FLOATS > out.length) break;
@@ -113,7 +204,6 @@ async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
113
204
 
114
205
  // src/detect-remote.ts
115
206
  var DETECT_WORKER_URL = "/mediakit/detect-worker.js";
116
- var READY_MS = 2e4;
117
207
  var DetectWorker = class {
118
208
  constructor(on) {
119
209
  this.on = on;
@@ -137,13 +227,13 @@ var DetectWorker = class {
137
227
  return this.worker !== null && this.up.has(kind) && !this.busy.has(kind);
138
228
  }
139
229
  /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */
140
- request(kind, frame, tsUs) {
230
+ request(kind, frame, tsUs, cover = false, retry = null) {
141
231
  if (!this.accepts(kind)) {
142
232
  frame.close();
143
233
  return false;
144
234
  }
145
235
  this.busy.add(kind);
146
- this.send({ t: kind, frame, tsUs }, [frame]);
236
+ this.send(kind === "face" ? { t: kind, frame, tsUs, cover, retry } : { t: kind, frame, tsUs }, [frame]);
147
237
  return true;
148
238
  }
149
239
  isUp(kind) {
@@ -162,7 +252,7 @@ var DetectWorker = class {
162
252
  reject(new Error("detect worker gone"));
163
253
  return;
164
254
  }
165
- const timer = setTimeout(() => this.settle(kind, new Error(`${kind}: no ready after ${READY_MS} ms`)), READY_MS);
255
+ const timer = setTimeout(() => this.settle(kind, new LoadTimeout(`${kind} detection`, LOAD_MS)), LOAD_MS);
166
256
  this.ready.set(kind, { resolve, reject, timer });
167
257
  this.send(m);
168
258
  });
@@ -179,7 +269,7 @@ var DetectWorker = class {
179
269
  break;
180
270
  case "face":
181
271
  this.busy.delete("face");
182
- if (this.up.has("face")) this.on.face(m.tsUs, m.n, m.lm, m.ms);
272
+ if (this.up.has("face")) this.on.face(m.tsUs, m.n, m.lm, m.ms, m.cover, m.rects);
183
273
  break;
184
274
  case "mask":
185
275
  this.busy.delete("mask");
@@ -283,6 +373,144 @@ function splitMicros(us) {
283
373
  return [lo, hi | 0];
284
374
  }
285
375
 
376
+ // src/gpu-guard.ts
377
+ var KEY = "mediakit-gpu-guard";
378
+ var TTL_MS = 3 * 24 * 3600 * 1e3;
379
+ function storage() {
380
+ try {
381
+ return typeof localStorage === "undefined" ? null : localStorage;
382
+ } catch {
383
+ return null;
384
+ }
385
+ }
386
+ function load() {
387
+ const s = storage();
388
+ if (!s) return {};
389
+ try {
390
+ const parsed = JSON.parse(s.getItem(KEY) ?? "{}");
391
+ return parsed && typeof parsed === "object" ? parsed : {};
392
+ } catch {
393
+ return {};
394
+ }
395
+ }
396
+ function save(store) {
397
+ try {
398
+ storage()?.setItem(KEY, JSON.stringify(store));
399
+ } catch {
400
+ return;
401
+ }
402
+ }
403
+ function gpuRecord(gpu) {
404
+ if (!gpu) return null;
405
+ const r = load()[gpu];
406
+ if (!r || typeof r.at !== "number" || Date.now() - r.at > TTL_MS) return null;
407
+ return { init: r.init === true, faceColor: r.faceColor === true, at: r.at };
408
+ }
409
+ function recordLoss(gpu, phase) {
410
+ if (!gpu || phase === "run" || !storage()) return;
411
+ const store = load();
412
+ const was = gpuRecord(gpu);
413
+ store[gpu] = {
414
+ init: phase === "init" || (was?.init ?? false),
415
+ faceColor: phase === "link" || (was?.faceColor ?? false),
416
+ at: Date.now()
417
+ };
418
+ save(store);
419
+ }
420
+ function forgetGpuFailures() {
421
+ try {
422
+ storage()?.removeItem(KEY);
423
+ } catch {
424
+ return;
425
+ }
426
+ }
427
+ function rendererOf(gl) {
428
+ if (gl.isContextLost()) return "";
429
+ const info = gl.getExtension("WEBGL_debug_renderer_info");
430
+ return String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "");
431
+ }
432
+ var GpuLostError = class extends Error {
433
+ constructor(phase, gpu, detail = "") {
434
+ 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"}]`);
435
+ this.phase = phase;
436
+ this.gpu = gpu;
437
+ this.detail = detail;
438
+ this.name = "GpuLostError";
439
+ }
440
+ phase;
441
+ gpu;
442
+ detail;
443
+ };
444
+
445
+ // src/mask-merge.ts
446
+ var CLASS_BACKGROUND = 0;
447
+ var CLASS_BODY_SKIN = 2;
448
+ var CLASS_CLOTHES = 4;
449
+ var CLASS_OTHERS = 5;
450
+ var CLASS_STALE_OCCLUDER = 6;
451
+ var THUMB_W = 64;
452
+ var THUMB_H = 36;
453
+ var MOVED_LUMA = 12;
454
+ function lumaThumb(rgba) {
455
+ const y = new Uint8Array(THUMB_W * THUMB_H);
456
+ for (let i = 0; i < y.length; i++) y[i] = rgba[i * 4] * 77 + rgba[i * 4 + 1] * 150 + rgba[i * 4 + 2] * 29 >> 8;
457
+ return y;
458
+ }
459
+ function movedBetween(a, b) {
460
+ const w = THUMB_W;
461
+ const h = THUMB_H;
462
+ const hit = new Uint8Array(w * h);
463
+ for (let i = 0; i < hit.length; i++) hit[i] = Math.abs(a[i] - b[i]) > MOVED_LUMA ? 1 : 0;
464
+ const data = new Uint8Array(w * h);
465
+ for (let y = 0; y < h; y++) {
466
+ for (let x = 0; x < w; x++) {
467
+ let v = 0;
468
+ for (let dy = -1; dy <= 1 && !v; dy++) {
469
+ const yy = y + dy;
470
+ if (yy < 0 || yy >= h) continue;
471
+ for (let dx = -1; dx <= 1; dx++) {
472
+ const xx = x + dx;
473
+ if (xx >= 0 && xx < w && hit[yy * w + xx]) {
474
+ v = 1;
475
+ break;
476
+ }
477
+ }
478
+ }
479
+ data[y * w + x] = v;
480
+ }
481
+ }
482
+ return { width: w, height: h, data };
483
+ }
484
+ function mergeMasks(person, classes, out, moved = null) {
485
+ const { width: w, height: h } = person;
486
+ const merged = out && out.length === w * h ? out : new Uint8Array(w * h);
487
+ const cw = classes.width;
488
+ const ch = classes.height;
489
+ const sx = cw / w;
490
+ const sy = ch / h;
491
+ const mw = moved?.width ?? 0;
492
+ const mh = moved?.height ?? 0;
493
+ for (let y = 0; y < h; y++) {
494
+ const crow = Math.min(ch - 1, Math.floor((y + 0.5) * sy)) * cw;
495
+ const mrow = moved ? Math.min(mh - 1, Math.floor((y + 0.5) * mh / h)) * mw : 0;
496
+ const prow = y * w;
497
+ for (let x = 0; x < w; x++) {
498
+ if (person.data[prow + x] !== 0) {
499
+ merged[prow + x] = CLASS_BACKGROUND;
500
+ continue;
501
+ }
502
+ const c = classes.data[crow + Math.min(cw - 1, Math.floor((x + 0.5) * sx))];
503
+ if (c === CLASS_BACKGROUND) {
504
+ merged[prow + x] = CLASS_CLOTHES;
505
+ continue;
506
+ }
507
+ const stale = moved !== null && (c === CLASS_BODY_SKIN || c === CLASS_OTHERS) && moved.data[mrow + Math.min(mw - 1, Math.floor((x + 0.5) * mw / w))] !== 0;
508
+ merged[prow + x] = stale ? CLASS_STALE_OCCLUDER : c;
509
+ }
510
+ }
511
+ return merged;
512
+ }
513
+
286
514
  // src/engine.ts
287
515
  var ZERO_STATS = {
288
516
  totalMs: 0,
@@ -303,17 +531,58 @@ var ZERO_STATS = {
303
531
  faces: 0,
304
532
  heldFrames: 0,
305
533
  faceAgeMs: 0,
306
- maskAgeMs: 0
534
+ maskAgeMs: 0,
535
+ effectError: ""
307
536
  };
308
- var MAX_HOLD = 2;
309
- var DEPTH_VOTES = 15;
537
+ var MAX_HOLD = 3;
538
+ var COVER_FRAME_W = 256;
539
+ var COVER_HOLD = 0.6;
540
+ var COVER_MISSES = 2;
541
+ var FOLLOW_SIDE = 384;
542
+ var FOLLOW_MARGIN = 2.6;
543
+ var FOLLOW_RETRY = 2;
544
+ var FOLLOW_MIN_SIDE = 64;
545
+ var FOLLOW_SHIFT = 0.06;
546
+ var FOLLOW_RESIZE = 0.12;
547
+ var FOLLOW_STALE_US = 5e5;
548
+ var FOLLOW_KEPT_US = 1e6;
549
+ var SCAN_SHARE = 0.5;
550
+ var SCAN_STEP = 0.75;
551
+ var FOLLOW_REFRESH = 30;
552
+ var FOLLOW_WIDEN = 2;
553
+ var FOLLOW_GROW = 3;
554
+ var SAME_FACE = 0.3;
555
+ var FACE_RESULTS_KEPT = 8;
556
+ var THUMBS_KEPT = 12;
557
+ var LINK_LOSS_WINDOW_MS = 3e3;
558
+ var FACE_JUMP = 0.15;
559
+ var CATCH_UP_EVERY_US = 1e6;
560
+ var MASK_RESULTS_KEPT = 8;
310
561
  var DETECT_DUTY = 0.6;
562
+ function gpuName(gl) {
563
+ const info = gl.getExtension("WEBGL_debug_renderer_info");
564
+ const name = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "unknown");
565
+ return gl.isContextLost() ? `${name}, context lost` : name;
566
+ }
311
567
  function sourceSize(source) {
312
568
  if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
313
569
  if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
314
570
  const s = source;
315
571
  return [s.width, s.height];
316
572
  }
573
+ function tileGrid(sw, sh) {
574
+ const side = Math.max(FOLLOW_MIN_SIDE, Math.round(Math.min(sw, sh) * SCAN_SHARE));
575
+ const step = side * SCAN_STEP;
576
+ return { side, step, nx: Math.max(1, Math.ceil((sw - side) / step) + 1), ny: Math.max(1, Math.ceil((sh - side) / step) + 1) };
577
+ }
578
+ function overlap(a, b) {
579
+ const w = Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]);
580
+ const h = Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]);
581
+ if (w <= 0 || h <= 0) return 0;
582
+ const i = w * h;
583
+ return i / (a[2] * a[3] + b[2] * b[3] - i);
584
+ }
585
+ var FACE_COLOR_SKIPPED = "face colour shaders skipped: linking one lost the WebGL context on this GPU before";
317
586
  var Engine = class _Engine {
318
587
  canvas;
319
588
  gl;
@@ -344,6 +613,14 @@ var Engine = class _Engine {
344
613
  classLoading = null;
345
614
  /** The segmenter whose result this frame borrowed, to give it back after process(). */
346
615
  used = null;
616
+ programErr = "";
617
+ loadErr = "";
618
+ gpu = "";
619
+ linkSeenAt = -Infinity;
620
+ links = 0;
621
+ lostPhase = null;
622
+ classFailed = false;
623
+ failed = /* @__PURE__ */ new Set();
347
624
  /**
348
625
  * The landmark detector, also lazy and independent of the segmenter.
349
626
  *
@@ -358,13 +635,14 @@ var Engine = class _Engine {
358
635
  classRemote = false;
359
636
  classMaskTex = null;
360
637
  classMaskFresh = false;
361
- classMaskTs = 0;
638
+ classMaskTs = -1;
362
639
  syncFaces = false;
363
640
  renderedTs = 0;
364
641
  queue = [];
365
642
  spare = [];
366
- holdDepth = 1;
367
- depthVotes = 0;
643
+ faceExtraUp = false;
644
+ faceExtraTried = false;
645
+ lerpBuf = null;
368
646
  gapUs = 33333;
369
647
  prevTs = -1;
370
648
  sent = /* @__PURE__ */ new Map();
@@ -372,6 +650,35 @@ var Engine = class _Engine {
372
650
  faceLatencyMs = 0;
373
651
  maskLatencyMs = /* @__PURE__ */ new Map();
374
652
  faceTs = -1;
653
+ faceResults = [];
654
+ coverCanvas = null;
655
+ coverCell = null;
656
+ coverOn = false;
657
+ faceMisses = 0;
658
+ coverHidden = false;
659
+ srcW = 0;
660
+ srcH = 0;
661
+ coverLast = null;
662
+ coverShown = null;
663
+ coverImg = null;
664
+ faceAsked = /* @__PURE__ */ new Set();
665
+ faceCrops = /* @__PURE__ */ new Map();
666
+ followBox = null;
667
+ followTs = -Infinity;
668
+ followCrop = null;
669
+ followCanvas = null;
670
+ followRetry = null;
671
+ faceSeen = false;
672
+ followFloats = 0;
673
+ followAll = false;
674
+ followTurn = 0;
675
+ followMiss = 0;
676
+ followGrow = 0;
677
+ boxFloats = 0;
678
+ scanFrom = 0;
679
+ scanTurn = 0;
680
+ probes = /* @__PURE__ */ new Set();
681
+ maskResults = [];
375
682
  maskUsedTs = -1;
376
683
  lastHeld = null;
377
684
  swallowed = false;
@@ -381,13 +688,23 @@ var Engine = class _Engine {
381
688
  personLoading = null;
382
689
  personMaskTex = null;
383
690
  personMaskFresh = false;
384
- personMaskTs = 0;
691
+ personMaskTs = -1;
385
692
  personWorkerMs = 0;
693
+ personBytes = null;
694
+ classBytes = null;
695
+ mergedBytes = null;
696
+ mergedTex = null;
697
+ mergedFresh = false;
698
+ mergedTs = 0;
386
699
  detectCanvas = null;
387
700
  detectCanvasTs = -1;
701
+ thumbCanvas = null;
702
+ thumbs = /* @__PURE__ */ new Map();
388
703
  // A kind whose worker failed once stays in-thread.
389
704
  inThread = /* @__PURE__ */ new Set();
390
705
  faceLoading = null;
706
+ faceCount = 1;
707
+ caughtUpTs = -Infinity;
391
708
  maxFaces = 3;
392
709
  lmBuf = null;
393
710
  filter = { kind: "none" };
@@ -403,19 +720,20 @@ var Engine = class _Engine {
403
720
  this.core = core;
404
721
  }
405
722
  /** 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) {
723
+ static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3, guard = {}) {
407
724
  const canvas = document.createElement("canvas");
408
725
  canvas.width = width;
409
726
  canvas.height = height;
410
- return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces);
727
+ return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces, guard);
411
728
  }
412
729
  /**
413
730
  * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
414
731
  * only a `cutout` background writes; it is fixed for the life of the context, so a host that
415
732
  * 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.
733
+ * landmarker looks for: below 3 it skips re-running its face detector on every call. Throws
734
+ * GpuLostError when the context is lost building the shaders, or this GPU is remembered for it.
417
735
  */
418
- static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3) {
736
+ static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3, guard = {}) {
419
737
  const width = canvas.width;
420
738
  const height = canvas.height;
421
739
  const gl = canvas.getContext("webgl2", {
@@ -425,14 +743,26 @@ var Engine = class _Engine {
425
743
  depth: false,
426
744
  stencil: false
427
745
  });
428
- if (!gl) throw new Error("mediakit: no WebGL2 in this browser");
746
+ if (!gl) throw new Error("mediakit: no WebGL2 in this browser (none available, blocked, or the GPU process was reset)");
747
+ const gpu = rendererOf(gl);
748
+ const known = gpuRecord(gpu);
749
+ if (known?.init) {
750
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
751
+ throw new GpuLostError("init", gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`);
752
+ }
429
753
  let core;
430
754
  let engine;
431
755
  try {
432
756
  core = await loadCore();
433
757
  const err = core.init(gl, width, height);
434
- if (err) throw new Error(`mediakit: ${err}`);
758
+ if (err && gl.isContextLost()) {
759
+ recordLoss(gpu, "init");
760
+ throw new GpuLostError("init", gpu, err);
761
+ }
762
+ if (err) throw new Error(`mediakit: ${err} [GPU: ${gpuName(gl)}]`);
435
763
  engine = new _Engine(canvas, gl, core);
764
+ engine.gpu = gpu;
765
+ if (guard.noFaceColor || known?.faceColor) core.disableFaceColor?.(FACE_COLOR_SKIPPED);
436
766
  engine.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3));
437
767
  await engine.setRecipe(filter, effects, background);
438
768
  return engine;
@@ -448,9 +778,29 @@ var Engine = class _Engine {
448
778
  throw err;
449
779
  }
450
780
  }
781
+ /** The GPU the context reported at creation, "" when the browser hides it. */
782
+ get gpuName() {
783
+ return this.gpu;
784
+ }
451
785
  get loading() {
452
786
  return this.segmenterLoading !== null || this.classLoading !== null || this.faceLoading !== null;
453
787
  }
788
+ /** The browser took the WebGL context away (GPU process reset or reclaimed); this Engine is done. */
789
+ get lost() {
790
+ return this.gl.isContextLost();
791
+ }
792
+ /**
793
+ * When the context was lost: "link" within 3 s of a face colour shader starting or still linking, else "run";
794
+ * null while it is not. The first read decides, and on the main thread it is remembered per GPU.
795
+ */
796
+ get lostDuring() {
797
+ if (this.closed || !this.gl.isContextLost()) return null;
798
+ if (!this.lostPhase) {
799
+ this.lostPhase = performance.now() - this.linkSeenAt < LINK_LOSS_WINDOW_MS ? "link" : "run";
800
+ recordLoss(this.gpu, this.lostPhase);
801
+ }
802
+ return this.lostPhase;
803
+ }
454
804
  get outputCanvas() {
455
805
  return this.canvas;
456
806
  }
@@ -537,13 +887,29 @@ var Engine = class _Engine {
537
887
  this.makeupPath = makeupTexture;
538
888
  }
539
889
  this.core.setRecipe(coreRecipe(filter, effects));
540
- if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
890
+ this.noteLinking();
891
+ if (needsSegmentation(filter, effects) && !this.remoteMaskComing(filter, effects)) void this.ensureSegmenter();
541
892
  if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
542
893
  if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
543
894
  if (needsFace(effects)) void this.ensureFace();
544
895
  }
896
+ noteLinking() {
897
+ const links = this.core.links?.() ?? 0;
898
+ if (links !== this.links || (this.core.linking?.() ?? 0) > 0) this.linkSeenAt = performance.now();
899
+ this.links = links;
900
+ }
901
+ /** A worker, or the multiclass model, will bring the mask: no in-thread person model for it. */
902
+ remoteMaskComing(filter, effects) {
903
+ if (needsSkinClasses(filter, effects) && !this.classFailed) return true;
904
+ return this.personRemoteWanted(filter, effects) && !this.inThread.has("person");
905
+ }
906
+ gaveUp(what, e) {
907
+ if (!(e instanceof LoadTimeout)) return;
908
+ this.loadErr ||= `${e.message}; ${what} stay off`;
909
+ console.warn(this.loadErr);
910
+ }
545
911
  ensureFace() {
546
- if (this.face || this.faceRemote || this.closed) return Promise.resolve();
912
+ if (this.face || this.faceRemote || this.failed.has("face") || this.closed) return Promise.resolve();
547
913
  if (this.faceLoading) return this.faceLoading;
548
914
  const buf = this.core.faceBuffer();
549
915
  if (!buf) return Promise.resolve();
@@ -551,9 +917,11 @@ var Engine = class _Engine {
551
917
  this.faceLoading = this.remote("face", (d) => d.initFace(n)).then(() => {
552
918
  this.faceRemote = true;
553
919
  this.lmBuf = buf;
920
+ this.faceCount = n;
554
921
  }).catch((e) => {
922
+ if (e instanceof LoadTimeout) throw e;
555
923
  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) => {
924
+ return withTimeout(createFaceDetector(this.canvas, n), LOAD_MS, "face detection", (f) => f.close()).then((f) => {
557
925
  if (this.closed) {
558
926
  f.close();
559
927
  return;
@@ -562,7 +930,9 @@ var Engine = class _Engine {
562
930
  this.lmBuf = buf;
563
931
  });
564
932
  }).catch((e) => {
565
- console.error("mediakit: face detector failed to load", e);
933
+ this.failed.add("face");
934
+ this.gaveUp("face effects", e);
935
+ if (!(e instanceof LoadTimeout)) console.error("mediakit: face detector failed to load", e);
566
936
  }).finally(() => {
567
937
  this.faceLoading = null;
568
938
  });
@@ -570,13 +940,16 @@ var Engine = class _Engine {
570
940
  }
571
941
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
572
942
  personRemoteWanted(filter, effects) {
573
- return filter.kind === "none" && needsSegmentation(filter, effects) && !needsSkinClasses(filter, effects);
943
+ return filter.kind === "none" && needsSegmentation(filter, effects);
574
944
  }
575
945
  ensurePersonRemote() {
576
- if (this.personRemote || this.closed) return Promise.resolve();
946
+ if (this.personRemote || this.failed.has("person") || this.closed) return Promise.resolve();
577
947
  this.personLoading ??= this.remote("person", (d) => d.initMask("person")).then(() => {
578
948
  this.personRemote = true;
579
- }).catch(() => {
949
+ }).catch((e) => {
950
+ if (!(e instanceof LoadTimeout)) return;
951
+ this.failed.add("person");
952
+ this.gaveUp("background effects", e);
580
953
  }).finally(() => {
581
954
  this.personLoading = null;
582
955
  });
@@ -584,6 +957,7 @@ var Engine = class _Engine {
584
957
  }
585
958
  async remote(kind, init) {
586
959
  if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
960
+ this.inThread.add(kind);
587
961
  throw new Error("in-thread");
588
962
  }
589
963
  let detect = this.detects.get(kind);
@@ -594,21 +968,27 @@ var Engine = class _Engine {
594
968
  try {
595
969
  await init(detect);
596
970
  } catch (e) {
597
- this.inThread.add(kind);
971
+ if (e instanceof LoadTimeout) {
972
+ detect.close();
973
+ this.detects.delete(kind);
974
+ } else this.inThread.add(kind);
598
975
  throw e;
599
976
  }
600
977
  if (this.closed) throw new Error("closed");
601
978
  }
602
979
  detectHandlers(key) {
603
980
  return {
604
- face: (tsUs, n, lm, ms) => {
605
- if (this.closed || !this.lmBuf) return;
606
- this.lmBuf.set(lm);
607
- const [lo, hi] = splitMicros(tsUs);
608
- this.core.setFace(lo, hi, n);
981
+ face: (tsUs, found, lm, ms, foundCover, foundRects) => {
982
+ if (this.closed || !this.lmBuf || tsUs > this.prevTs) return;
609
983
  this.faceWorkerMs = ms;
610
- this.faceTs = tsUs;
611
- const took = this.took("face", tsUs);
984
+ this.uncrop(tsUs, found, lm, foundRects);
985
+ const { n, cover, rects } = this.dedupe(found, lm, foundCover, foundRects);
986
+ this.follow(tsUs, n, lm, this.probes.delete(tsUs));
987
+ if (this.syncing()) {
988
+ this.faceResults.push({ ts: tsUs, n, lm: lm.slice(), cover, rects });
989
+ if (this.faceResults.length > FACE_RESULTS_KEPT) this.faceResults.shift();
990
+ } else this.applyFace(tsUs, n, lm, cover, rects);
991
+ const took = this.took(key === "faceExtra" ? "faceExtra" : "face", tsUs);
612
992
  if (took !== null) this.faceLatencyMs = this.faceLatencyMs ? this.faceLatencyMs + (took - this.faceLatencyMs) * 0.2 : took;
613
993
  },
614
994
  mask: (tsUs, width, height, data, ms) => {
@@ -618,24 +998,30 @@ var Engine = class _Engine {
618
998
  const was = this.maskLatencyMs.get(key);
619
999
  this.maskLatencyMs.set(key, was ? was + (took - was) * 0.2 : took);
620
1000
  }
621
- if (key === "person") {
622
- this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, width, height, data);
623
- this.personMaskFresh = true;
624
- this.personMaskTs = tsUs;
625
- this.personWorkerMs = ms;
1001
+ const r = { person: key === "person", ts: tsUs, width, height, data, ms };
1002
+ if (!this.syncing()) {
1003
+ this.applyMask(r);
626
1004
  return;
627
1005
  }
628
- this.uploadClassMask(width, height, data);
629
- this.classMaskTs = tsUs;
630
- this.maskWorkerMs = ms;
1006
+ this.maskResults.push(r);
1007
+ if (this.maskResults.length > MASK_RESULTS_KEPT) this.maskResults.shift();
631
1008
  },
632
1009
  failed: (k, reason) => {
1010
+ if (key === "faceExtra") {
1011
+ this.faceExtraUp = false;
1012
+ this.detects.get(key)?.close();
1013
+ this.detects.delete(key);
1014
+ return;
1015
+ }
633
1016
  console.warn(`mediakit: ${key} detection moves into this thread:`, reason);
634
1017
  this.inThread.add(key);
635
1018
  if (key === "person") {
636
1019
  this.personRemote = false;
637
1020
  } else if (k === "face") {
638
1021
  this.faceRemote = false;
1022
+ if (this.coverOn) this.core.setFaceCover(null);
1023
+ this.coverOn = false;
1024
+ this.coverShown = null;
639
1025
  void this.ensureFace();
640
1026
  } else {
641
1027
  this.classRemote = false;
@@ -644,6 +1030,24 @@ var Engine = class _Engine {
644
1030
  }
645
1031
  };
646
1032
  }
1033
+ noteThumb(timestampUs) {
1034
+ if (this.thumbs.has(timestampUs) || !this.detectCanvas || this.detectCanvasTs !== timestampUs) return;
1035
+ this.thumbCanvas ??= new OffscreenCanvas(THUMB_W, THUMB_H);
1036
+ const ctx = this.thumbCanvas.getContext("2d", { willReadFrequently: true });
1037
+ ctx.drawImage(this.detectCanvas, 0, 0, THUMB_W, THUMB_H);
1038
+ this.thumbs.set(timestampUs, lumaThumb(ctx.getImageData(0, 0, THUMB_W, THUMB_H).data));
1039
+ if (this.thumbs.size > THUMBS_KEPT) this.thumbs.delete(this.thumbs.keys().next().value);
1040
+ }
1041
+ merge(tsUs) {
1042
+ if (!this.personBytes || !this.classBytes || !needsSkinClasses(this.filter, this.effects)) return;
1043
+ const then = this.thumbs.get(this.classMaskTs);
1044
+ const now2 = this.thumbs.get(this.personMaskTs);
1045
+ const moved = then && now2 && this.classMaskTs !== this.personMaskTs ? movedBetween(then, now2) : null;
1046
+ this.mergedBytes = mergeMasks(this.personBytes, this.classBytes, this.mergedBytes, moved);
1047
+ this.mergedTex = this.uploadMaskBytes(this.mergedTex, this.personBytes.width, this.personBytes.height, this.mergedBytes);
1048
+ this.mergedFresh = true;
1049
+ this.mergedTs = tsUs;
1050
+ }
647
1051
  uploadClassMask(width, height, data) {
648
1052
  this.classMaskTex = this.uploadMaskBytes(this.classMaskTex, width, height, data);
649
1053
  this.classMaskFresh = true;
@@ -670,24 +1074,187 @@ var Engine = class _Engine {
670
1074
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
671
1075
  * detection drains Chrome's few capture buffers and throttles the camera itself.
672
1076
  */
673
- requestRemote(kind, source, timestampUs) {
1077
+ requestRemote(want, source, timestampUs) {
1078
+ const lockstep = want === "face" && this.syncing();
1079
+ const kind = lockstep ? this.freeFaceWorker() : want;
1080
+ if (!kind) return;
674
1081
  const detect = this.detects.get(kind);
675
- if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
676
- if (!this.dutyAllows(kind)) return;
1082
+ if (!detect?.accepts(kind === "face" || kind === "faceExtra" ? "face" : "mask")) return;
1083
+ if (!lockstep && !this.dutyAllows(kind)) return;
677
1084
  let frame = null;
1085
+ let followed = null;
1086
+ let scanned = null;
678
1087
  try {
679
1088
  const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
680
- frame = new VideoFrame(copyable ? this.detectCopy(source, timestampUs) : source, {
1089
+ if (copyable) {
1090
+ this.srcW = source instanceof VideoFrame ? source.displayWidth : source.width;
1091
+ this.srcH = source instanceof VideoFrame ? source.displayHeight : source.height;
1092
+ }
1093
+ if (copyable && (kind === "face" || kind === "faceExtra")) {
1094
+ followed = this.followCopy(source, timestampUs);
1095
+ if (!followed) scanned = this.scanCopy(source, timestampUs);
1096
+ }
1097
+ frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(source, timestampUs) : source), {
681
1098
  timestamp: timestampUs
682
1099
  });
683
1100
  } catch {
684
1101
  }
685
- if (frame && detect.request(kind === "face" ? "face" : "mask", frame, timestampUs)) {
1102
+ if (frame && detect.request(kind === "face" || kind === "faceExtra" ? "face" : "mask", frame, timestampUs, this.effects.occluders ?? false, followed ? this.followRetry : null)) {
686
1103
  const now2 = performance.now();
687
1104
  this.sent.set(kind, { ts: timestampUs, at: now2 });
688
1105
  this.lastSentAt.set(kind, now2);
1106
+ if (lockstep) this.faceAsked.add(timestampUs);
1107
+ if (kind !== "face" && kind !== "faceExtra" && this.remoteMaskKind() === "merged") this.noteThumb(timestampUs);
1108
+ } else if (followed || scanned) this.faceCrops.delete(timestampUs);
1109
+ }
1110
+ followCopy(source, timestampUs) {
1111
+ const box = this.followBox;
1112
+ if (!box || timestampUs - this.followTs > FOLLOW_STALE_US) return null;
1113
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
1114
+ const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
1115
+ const want = Math.max(FOLLOW_MIN_SIDE, FOLLOW_MARGIN * (1 + this.followMiss) * Math.max(box[2] * sw, box[3] * sh));
1116
+ if (want > Math.min(sw, sh) && this.followFloats > FACE_FLOATS) return null;
1117
+ if (!this.followAll && this.followTurn++ % FOLLOW_REFRESH === FOLLOW_REFRESH - 1) {
1118
+ this.probes.add(timestampUs);
1119
+ return null;
1120
+ }
1121
+ let side = Math.round(Math.min(sw, sh, want));
1122
+ let x = Math.round(Math.min(sw - side, Math.max(0, (box[0] + box[2] / 2) * sw - side / 2)));
1123
+ let y = Math.round(Math.min(sh - side, Math.max(0, (box[1] + box[3] / 2) * sh - side / 2)));
1124
+ const kept = this.followCrop;
1125
+ if (kept && kept[0] + kept[2] <= sw && kept[1] + kept[2] <= sh && Math.abs(kept[2] - side) < FOLLOW_RESIZE * side && Math.abs(kept[0] - x) < FOLLOW_SHIFT * side && Math.abs(kept[1] - y) < FOLLOW_SHIFT * side) {
1126
+ ;
1127
+ [x, y, side] = kept;
1128
+ } else this.followCrop = [x, y, side];
1129
+ this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
1130
+ this.followCanvas.getContext("2d").drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
1131
+ const tight = Math.min(side, Math.max(FOLLOW_MIN_SIDE, FOLLOW_RETRY * Math.max(box[2] * sw, box[3] * sh)));
1132
+ this.followRetry = [((box[0] + box[2] / 2) * sw - x) / side, ((box[1] + box[3] / 2) * sh - y) / side, tight / side];
1133
+ this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh]);
1134
+ return this.followCanvas;
1135
+ }
1136
+ scanCopy(source, timestampUs) {
1137
+ if (this.faceSeen) return null;
1138
+ const turn = this.scanTurn++;
1139
+ if (turn % 2 === 0) return null;
1140
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
1141
+ const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
1142
+ const { side, step, nx, ny } = tileGrid(sw, sh);
1143
+ const at = (this.scanFrom + (turn >> 1)) % (nx * ny);
1144
+ const x = Math.max(0, Math.min(sw - side, Math.round(at % nx * step)));
1145
+ const y = Math.max(0, Math.min(sh - side, Math.round(Math.floor(at / nx) * step)));
1146
+ this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
1147
+ this.followCanvas.getContext("2d").drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
1148
+ this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh]);
1149
+ this.probes.add(timestampUs);
1150
+ return this.followCanvas;
1151
+ }
1152
+ scanTile(cx, cy) {
1153
+ const sw = this.srcW || this.canvas.width;
1154
+ const sh = this.srcH || this.canvas.height;
1155
+ const { side, step, nx, ny } = tileGrid(sw, sh);
1156
+ const ix = Math.min(nx - 1, Math.max(0, Math.round((cx * sw - side / 2) / step)));
1157
+ const iy = Math.min(ny - 1, Math.max(0, Math.round((cy * sh - side / 2) / step)));
1158
+ return iy * nx + ix;
1159
+ }
1160
+ uncrop(tsUs, n, lm, rects) {
1161
+ const crop = this.faceCrops.get(tsUs);
1162
+ for (const ts of this.faceCrops.keys()) if (ts === tsUs || ts < tsUs - FOLLOW_KEPT_US) this.faceCrops.delete(ts);
1163
+ if (!crop) return;
1164
+ for (let i = 0; i < n; i += 3) {
1165
+ lm[i] = crop[0] + lm[i] * crop[2];
1166
+ lm[i + 1] = crop[1] + lm[i + 1] * crop[3];
1167
+ lm[i + 2] = lm[i + 2] * crop[2];
1168
+ }
1169
+ for (let i = 0; rects && i < rects.length; i += 3) {
1170
+ rects[i] = crop[0] + rects[i] * crop[2];
1171
+ rects[i + 1] = crop[1] + rects[i + 1] * crop[3];
1172
+ rects[i + 2] = rects[i + 2] * crop[2];
689
1173
  }
690
1174
  }
1175
+ dedupe(n, lm, cover, rects) {
1176
+ const faces = n / FACE_FLOATS;
1177
+ if (faces < 2) return { n, cover, rects };
1178
+ const boxes = Array.from({ length: faces }, (_, f) => faceBox(lm, f * FACE_FLOATS));
1179
+ const ref = this.followBox;
1180
+ const score = (b) => (ref ? overlap(b, ref) : 0) + b[2] * b[3] * 1e-3;
1181
+ const keep = boxes.map(() => true);
1182
+ for (let a = 0; a < faces; a++) {
1183
+ for (let b = a + 1; b < faces; b++) {
1184
+ if (!keep[a] || !keep[b] || overlap(boxes[a], boxes[b]) <= SAME_FACE) continue;
1185
+ keep[score(boxes[a]) >= score(boxes[b]) ? b : a] = false;
1186
+ }
1187
+ }
1188
+ if (keep.every(Boolean)) return { n, cover, rects };
1189
+ const cells = COVER_SIZE * COVER_SIZE;
1190
+ const outCover = cover ? new Uint8Array(cover.length) : null;
1191
+ const outRects = rects ? new Float32Array(rects.length) : null;
1192
+ let k = 0;
1193
+ for (let f = 0; f < faces; f++) {
1194
+ if (!keep[f]) continue;
1195
+ if (k !== f) lm.copyWithin(k * FACE_FLOATS, f * FACE_FLOATS, (f + 1) * FACE_FLOATS);
1196
+ if (cover && outCover) outCover.set(cover.subarray(f * cells, (f + 1) * cells), k * cells);
1197
+ if (rects && outRects) outRects.set(rects.subarray(f * 3, f * 3 + 3), k * 3);
1198
+ k++;
1199
+ }
1200
+ return { n: k * FACE_FLOATS, cover: outCover ? outCover.slice(0, k * cells) : null, rects: outRects ? outRects.slice(0, k * 3) : null };
1201
+ }
1202
+ follow(tsUs, n, lm, probe) {
1203
+ for (const ts of this.probes) if (ts < tsUs - FOLLOW_KEPT_US) this.probes.delete(ts);
1204
+ if (tsUs <= this.followTs || probe && (n === 0 || n < this.followFloats)) return;
1205
+ this.followTs = tsUs;
1206
+ this.faceSeen = n > 0;
1207
+ if (n === 0) {
1208
+ this.followGrow = 0;
1209
+ this.followFloats = 0;
1210
+ this.followAll = false;
1211
+ const box = this.followBox;
1212
+ if (box && this.followMiss < FOLLOW_WIDEN) {
1213
+ this.followMiss++;
1214
+ return;
1215
+ }
1216
+ this.followMiss = 0;
1217
+ if (box) this.scanFrom = this.scanTile(box[0] + box[2] / 2, box[1] + box[3] / 2);
1218
+ this.scanTurn = 1;
1219
+ this.followBox = null;
1220
+ this.followCrop = null;
1221
+ this.boxFloats = 0;
1222
+ return;
1223
+ }
1224
+ this.followMiss = 0;
1225
+ const old = this.followBox;
1226
+ const grow = old !== null && this.boxFloats > 0 && n > this.boxFloats && !probe;
1227
+ this.followGrow = grow ? this.followGrow + 1 : 0;
1228
+ const take = grow && this.followGrow < FOLLOW_GROW ? this.boxFloats : n;
1229
+ const boxes = [];
1230
+ for (let f = 0; f < n; f += FACE_FLOATS) boxes.push(faceBox(lm, f));
1231
+ if (take < n && old) boxes.sort((a, b) => overlap(b, old) - overlap(a, old));
1232
+ const kept = boxes.slice(0, take / FACE_FLOATS);
1233
+ const x0 = Math.min(...kept.map((b) => b[0]));
1234
+ const y0 = Math.min(...kept.map((b) => b[1]));
1235
+ const x1 = Math.max(...kept.map((b) => b[0] + b[2]));
1236
+ const y1 = Math.max(...kept.map((b) => b[1] + b[3]));
1237
+ this.followBox = [x0, y0, x1 - x0, y1 - y0];
1238
+ this.boxFloats = take;
1239
+ this.followFloats = take;
1240
+ this.followAll = take >= this.faceCount * FACE_FLOATS;
1241
+ }
1242
+ freeFaceWorker() {
1243
+ if (this.detects.get("face")?.accepts("face")) return "face";
1244
+ if (this.faceExtraUp && this.detects.get("faceExtra")?.accepts("face")) return "faceExtra";
1245
+ return null;
1246
+ }
1247
+ ensureFaceExtra() {
1248
+ if (this.faceExtraTried || this.closed) return;
1249
+ this.faceExtraTried = true;
1250
+ const n = this.faceCount;
1251
+ this.remote("faceExtra", (d) => d.initFace(n)).then(() => {
1252
+ this.faceExtraUp = true;
1253
+ }).catch(() => {
1254
+ this.detects.get("faceExtra")?.close();
1255
+ this.detects.delete("faceExtra");
1256
+ });
1257
+ }
691
1258
  /** Face and mask asked on the same frame share one draw. */
692
1259
  detectCopy(source, timestampUs) {
693
1260
  const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
@@ -706,36 +1273,42 @@ var Engine = class _Engine {
706
1273
  return this.detectCanvas;
707
1274
  }
708
1275
  ensureClassSegmenter() {
709
- if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
1276
+ if (this.classSegmenter || this.classRemote || this.classFailed || this.closed) return Promise.resolve();
710
1277
  if (this.classLoading) return this.classLoading;
711
1278
  this.classLoading = this.remote("mask", (d) => d.initMask("classes")).then(() => {
712
1279
  this.classRemote = true;
713
- }).catch(
714
- () => createSegmenter(this.canvas, "classes").then((s) => {
1280
+ }).catch((e) => {
1281
+ if (e instanceof LoadTimeout) throw e;
1282
+ return withTimeout(createSegmenter(this.canvas, "classes"), LOAD_MS, "skin segmentation", (s) => s.close()).then((s) => {
715
1283
  if (this.closed) {
716
1284
  s.close();
717
1285
  return;
718
1286
  }
719
1287
  this.classSegmenter = s;
720
- })
721
- ).catch((e) => {
722
- console.error("mediakit: multiclass segmenter failed to load", e);
1288
+ });
1289
+ }).catch((e) => {
1290
+ this.classFailed = true;
1291
+ if (!(e instanceof LoadTimeout)) console.error("mediakit: multiclass segmenter failed to load", e);
1292
+ else console.warn(`${e.message}; the person model stands in`);
1293
+ if (needsSegmentation(this.filter, this.effects)) void this.ensureSegmenter();
723
1294
  }).finally(() => {
724
1295
  this.classLoading = null;
725
1296
  });
726
1297
  return this.classLoading;
727
1298
  }
728
1299
  ensureSegmenter() {
729
- if (this.segmenter || this.closed) return Promise.resolve();
1300
+ if (this.segmenter || this.failed.has("segmenter") || this.closed) return Promise.resolve();
730
1301
  if (this.segmenterLoading) return this.segmenterLoading;
731
- this.segmenterLoading = createSegmenter(this.canvas).then((s) => {
1302
+ this.segmenterLoading = withTimeout(createSegmenter(this.canvas), LOAD_MS, "person segmentation", (s) => s.close()).then((s) => {
732
1303
  if (this.closed) {
733
1304
  s.close();
734
1305
  return;
735
1306
  }
736
1307
  this.segmenter = s;
737
1308
  }).catch((e) => {
738
- console.error("mediakit: segmenter failed to load", e);
1309
+ this.failed.add("segmenter");
1310
+ this.gaveUp("background and skin effects", e);
1311
+ if (!(e instanceof LoadTimeout)) console.error("mediakit: segmenter failed to load", e);
739
1312
  }).finally(() => {
740
1313
  this.segmenterLoading = null;
741
1314
  });
@@ -754,52 +1327,106 @@ var Engine = class _Engine {
754
1327
  * it constructs one only to destroy it again.
755
1328
  */
756
1329
  render(source, timestampUs) {
757
- if (this.closed) return false;
1330
+ if (this.closed || this.lostDuring) return false;
758
1331
  if (this.lastHeld) this.spare.push(this.lastHeld);
759
1332
  this.lastHeld = null;
760
1333
  this.swallowed = false;
761
1334
  if (this.prevTs >= 0 && timestampUs > this.prevTs) {
762
1335
  this.gapUs += (Math.min(timestampUs - this.prevTs, 2e5) - this.gapUs) * 0.1;
763
1336
  }
1337
+ if (timestampUs < this.prevTs) {
1338
+ this.faceResults = [];
1339
+ this.maskResults = [];
1340
+ this.faceAsked.clear();
1341
+ this.faceCrops.clear();
1342
+ this.followBox = null;
1343
+ this.followCrop = null;
1344
+ this.followTs = -Infinity;
1345
+ this.faceSeen = false;
1346
+ this.followFloats = 0;
1347
+ this.followAll = false;
1348
+ this.followTurn = 0;
1349
+ this.followMiss = 0;
1350
+ this.followGrow = 0;
1351
+ this.boxFloats = 0;
1352
+ this.scanFrom = 0;
1353
+ this.scanTurn = 0;
1354
+ this.probes.clear();
1355
+ this.caughtUpTs = -Infinity;
1356
+ this.thumbs.clear();
1357
+ }
764
1358
  this.prevTs = timestampUs;
765
1359
  if (!this.syncing() || typeof ImageData !== "undefined" && source instanceof ImageData) {
766
1360
  this.releaseHeld();
767
1361
  this.renderedTs = timestampUs;
768
1362
  return this.draw(source, timestampUs, false);
769
1363
  }
1364
+ this.ensureFaceExtra();
770
1365
  this.requestRemote("face", source, timestampUs);
771
1366
  const remoteMask = this.remoteMaskKind();
772
- if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
1367
+ if (remoteMask === "merged") {
1368
+ this.requestRemote("person", source, timestampUs);
1369
+ this.requestRemote("mask", source, timestampUs);
1370
+ } else if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
773
1371
  this.queue.push({ c: this.hold(source), ts: timestampUs });
774
- this.retuneDepth();
775
- if (this.queue.length <= this.holdDepth) {
1372
+ while (this.queue.length > MAX_HOLD + 1) this.faceAsked.delete(this.spareFront());
1373
+ if (this.queue.length <= MAX_HOLD && !this.faceReady(this.queue[0].ts)) {
776
1374
  this.swallowed = true;
777
1375
  return false;
778
1376
  }
779
- while (this.queue.length > this.holdDepth + 1) this.spare.push(this.queue.shift().c);
1377
+ if (this.queue.length > 2 && this.faceReady(this.queue[1].ts) && timestampUs - this.caughtUpTs >= CATCH_UP_EVERY_US) {
1378
+ this.caughtUpTs = timestampUs;
1379
+ this.faceAsked.delete(this.spareFront());
1380
+ }
780
1381
  const front = this.queue.shift();
1382
+ this.faceAsked.delete(front.ts);
1383
+ this.faceFor(front.ts);
1384
+ this.masksFor(front.ts);
781
1385
  this.lastHeld = front.c;
782
1386
  this.renderedTs = front.ts;
783
1387
  return this.draw(front.c, front.ts, true);
784
1388
  }
785
1389
  remoteMaskKind() {
786
- if (this.personRemote && this.personRemoteWanted(this.filter, this.effects)) return "person";
787
- if (this.classRemote && needsSkinClasses(this.filter, this.effects)) return "mask";
788
- return null;
789
- }
790
- retuneDepth() {
791
- const kind = this.remoteMaskKind();
792
- const latency = Math.max(this.faceLatencyMs, kind ? this.maskLatencyMs.get(kind) ?? 0 : 0);
793
- const want = latency > 0 ? Math.min(MAX_HOLD, Math.max(1, Math.ceil(latency * 1e3 / this.gapUs))) : 1;
794
- if (want === this.holdDepth) {
795
- this.depthVotes = 0;
1390
+ const person = this.personRemote && this.personRemoteWanted(this.filter, this.effects);
1391
+ if (!needsSkinClasses(this.filter, this.effects)) return person ? "person" : null;
1392
+ if (this.classRemote) return person ? "merged" : "mask";
1393
+ return person && !this.inThread.has("mask") ? "person" : null;
1394
+ }
1395
+ spareFront() {
1396
+ const h = this.queue.shift();
1397
+ this.spare.push(h.c);
1398
+ return h.ts;
1399
+ }
1400
+ applyMask(r) {
1401
+ if (r.person) {
1402
+ this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, r.width, r.height, r.data);
1403
+ this.personMaskFresh = true;
1404
+ this.personMaskTs = r.ts;
1405
+ this.personWorkerMs = r.ms;
1406
+ this.personBytes = { width: r.width, height: r.height, data: r.data };
1407
+ this.merge(r.ts);
796
1408
  return;
797
1409
  }
798
- if (++this.depthVotes >= DEPTH_VOTES) {
799
- this.holdDepth = want;
800
- this.depthVotes = 0;
1410
+ this.uploadClassMask(r.width, r.height, r.data);
1411
+ this.classMaskTs = r.ts;
1412
+ this.maskWorkerMs = r.ms;
1413
+ this.classBytes = { width: r.width, height: r.height, data: r.data };
1414
+ this.merge(this.personMaskTs);
1415
+ }
1416
+ masksFor(tsUs) {
1417
+ for (const person of [false, true]) {
1418
+ let pick = null;
1419
+ for (const r of this.maskResults) if (r.person === person && (!pick || Math.abs(r.ts - tsUs) < Math.abs(pick.ts - tsUs))) pick = r;
1420
+ if (!pick) continue;
1421
+ const chosen = pick;
1422
+ this.maskResults = this.maskResults.filter((r) => r.person !== person || r.ts >= chosen.ts);
1423
+ if (chosen.ts !== (person ? this.personMaskTs : this.classMaskTs)) this.applyMask(chosen);
801
1424
  }
802
1425
  }
1426
+ faceReady(tsUs) {
1427
+ const asked = this.faceAsked.has(tsUs);
1428
+ return this.faceResults.some((r) => asked ? r.ts === tsUs : r.ts > tsUs);
1429
+ }
803
1430
  dutyAllows(kind) {
804
1431
  const took = kind === "face" ? this.faceLatencyMs : this.maskLatencyMs.get(kind) ?? 0;
805
1432
  if (took * 1e3 < this.gapUs) return true;
@@ -812,6 +1439,89 @@ var Engine = class _Engine {
812
1439
  this.sent.delete(kind);
813
1440
  return performance.now() - s.at;
814
1441
  }
1442
+ applyFace(tsUs, n, lm, cover, rects) {
1443
+ this.faceMisses = n === 0 ? this.faceMisses + 1 : 0;
1444
+ if (n > 0) this.showCover(cover, rects);
1445
+ else if (this.faceMisses >= COVER_MISSES) this.hideCover();
1446
+ this.lmBuf.set(lm);
1447
+ const [lo, hi] = splitMicros(tsUs);
1448
+ this.core.setFace(lo, hi, n);
1449
+ this.faceTs = tsUs;
1450
+ }
1451
+ faceFor(tsUs) {
1452
+ this.faceResults.sort((a2, b) => a2.ts - b.ts);
1453
+ let pick = -1;
1454
+ for (let i = 0; i < this.faceResults.length; i++) if (this.faceResults[i].ts <= tsUs) pick = i;
1455
+ if (pick < 0) return;
1456
+ const r = this.faceResults[pick];
1457
+ const next = this.faceResults[pick + 1];
1458
+ this.faceResults.splice(0, pick);
1459
+ if (r.ts === tsUs || !next || !this.sameFaces(r, next)) {
1460
+ if (r.ts !== this.faceTs) this.applyFace(r.ts, r.n, r.lm, r.cover, r.rects);
1461
+ return;
1462
+ }
1463
+ const a = (tsUs - r.ts) / (next.ts - r.ts);
1464
+ if (!this.lerpBuf || this.lerpBuf.length !== r.lm.length) this.lerpBuf = new Float32Array(r.lm.length);
1465
+ for (let i = 0; i < r.n; i++) this.lerpBuf[i] = r.lm[i] + (next.lm[i] - r.lm[i]) * a;
1466
+ const near = a < 0.5 ? r : next;
1467
+ this.applyFace(tsUs, r.n, this.lerpBuf, near.cover, near.rects);
1468
+ }
1469
+ hideCover() {
1470
+ if (!this.coverOn || !this.coverCanvas || this.coverHidden) return;
1471
+ const ctx = this.coverCanvas.getContext("2d");
1472
+ ctx.fillStyle = "#000";
1473
+ ctx.fillRect(0, 0, this.coverCanvas.width, this.coverCanvas.height);
1474
+ this.core.setFaceCover(this.coverCanvas);
1475
+ this.coverShown = null;
1476
+ this.coverHidden = true;
1477
+ }
1478
+ showCover(cover, rects) {
1479
+ this.coverHidden = false;
1480
+ if (!cover || !rects || !(this.effects.occluders ?? false)) {
1481
+ if (this.coverOn) this.core.setFaceCover(null);
1482
+ this.coverOn = false;
1483
+ this.coverShown = null;
1484
+ return;
1485
+ }
1486
+ if (cover === this.coverShown && this.coverOn) return;
1487
+ const w = COVER_FRAME_W;
1488
+ const h = Math.max(1, Math.round(w * (this.srcH || this.canvas.height) / (this.srcW || this.canvas.width)));
1489
+ if (!this.coverCanvas || this.coverCanvas.height !== h) this.coverCanvas = new OffscreenCanvas(w, h);
1490
+ this.coverCell ??= new OffscreenCanvas(COVER_SIZE, COVER_SIZE);
1491
+ const ctx = this.coverCanvas.getContext("2d");
1492
+ const cell = this.coverCell.getContext("2d");
1493
+ ctx.fillStyle = "#fff";
1494
+ ctx.fillRect(0, 0, w, h);
1495
+ this.coverImg ??= cell.createImageData(COVER_SIZE, COVER_SIZE);
1496
+ const img = this.coverImg;
1497
+ const cells = COVER_SIZE * COVER_SIZE;
1498
+ const held = this.coverLast && this.coverLast !== cover && this.coverLast.length === cover.length ? this.coverLast : null;
1499
+ for (let f = 0; f * 3 < rects.length; f++) {
1500
+ for (let i = 0; i < cells; i++) {
1501
+ const now2 = cover[f * cells + i];
1502
+ const v = held ? Math.min(now2, now2 * (1 - COVER_HOLD) + held[f * cells + i] * COVER_HOLD) : now2;
1503
+ img.data[i * 4] = v;
1504
+ img.data[i * 4 + 1] = v;
1505
+ img.data[i * 4 + 2] = v;
1506
+ img.data[i * 4 + 3] = 255;
1507
+ }
1508
+ cell.putImageData(img, 0, 0);
1509
+ const side = rects[f * 3 + 2] * w;
1510
+ ctx.drawImage(this.coverCell, rects[f * 3] * w - side / 2, rects[f * 3 + 1] * h - side / 2, side, side);
1511
+ }
1512
+ this.core.setFaceCover(this.coverCanvas);
1513
+ this.coverOn = true;
1514
+ this.coverLast = cover;
1515
+ this.coverShown = cover;
1516
+ }
1517
+ sameFaces(a, b) {
1518
+ if (a.n === 0 || a.n !== b.n) return false;
1519
+ for (let k = 0; k < a.n; k += FACE_FLOATS) {
1520
+ const nose = k + 3;
1521
+ if (Math.abs(a.lm[nose] - b.lm[nose]) > FACE_JUMP || Math.abs(a.lm[nose + 1] - b.lm[nose + 1]) > FACE_JUMP) return false;
1522
+ }
1523
+ return true;
1524
+ }
815
1525
  releaseHeld() {
816
1526
  for (const h of this.queue) this.spare.push(h.c);
817
1527
  this.queue = [];
@@ -845,7 +1555,24 @@ var Engine = class _Engine {
845
1555
  this.used = null;
846
1556
  let served = false;
847
1557
  const remoteMask = this.remoteMaskKind();
848
- if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
1558
+ if (remoteMask === "merged") {
1559
+ if (!faceDone) {
1560
+ this.requestRemote("person", source, timestampUs);
1561
+ this.requestRemote("mask", source, timestampUs);
1562
+ }
1563
+ const tex = this.mergedTex ?? this.personMaskTex;
1564
+ if (tex) {
1565
+ served = true;
1566
+ if (this.mergedTex ? this.mergedFresh : this.personMaskFresh) {
1567
+ this.mergedFresh = false;
1568
+ this.personMaskFresh = false;
1569
+ mask = tex;
1570
+ maskKind = this.mergedTex ? 1 : 0;
1571
+ maskTs = this.mergedTex ? this.mergedTs : this.personMaskTs;
1572
+ segMs = this.personWorkerMs;
1573
+ }
1574
+ }
1575
+ } else if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
849
1576
  if (remoteMask === "person") {
850
1577
  if (this.personMaskTex) {
851
1578
  served = true;
@@ -873,7 +1600,7 @@ var Engine = class _Engine {
873
1600
  const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
874
1601
  const seg = classes ? this.classSegmenter : this.segmenter;
875
1602
  if (!seg) {
876
- void this.ensureSegmenter();
1603
+ if (!this.remoteMaskComing(this.filter, this.effects)) void this.ensureSegmenter();
877
1604
  } else {
878
1605
  const s0 = performance.now();
879
1606
  mask = seg.segment(source, timestampUs / 1e3);
@@ -905,6 +1632,14 @@ var Engine = class _Engine {
905
1632
  const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
906
1633
  if (mask) this.used?.release();
907
1634
  this.used = null;
1635
+ this.noteLinking();
1636
+ if (!this.programErr) {
1637
+ const err = this.core.programError?.() ?? "";
1638
+ if (err) {
1639
+ this.programErr = `mediakit: ${err}; makeup and teeth stay off, the rest runs [GPU: ${gpuName(this.gl)}]`;
1640
+ console.warn(this.programErr);
1641
+ }
1642
+ }
908
1643
  this.prevSegMs = segMs;
909
1644
  this.prevTotalMs = performance.now() - t0;
910
1645
  const s = this.core.stats();
@@ -925,9 +1660,10 @@ var Engine = class _Engine {
925
1660
  needsFace: s ? s[10] > 0.5 : false,
926
1661
  autoExposure: s ? s[11] : 0,
927
1662
  faces: s ? s[12] : 0,
928
- heldFrames: faceDone ? this.holdDepth : 0,
1663
+ heldFrames: faceDone ? this.queue.length : 0,
929
1664
  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
1665
+ maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0,
1666
+ effectError: this.programErr || this.loadErr
931
1667
  };
932
1668
  return glCalls > 0;
933
1669
  }
@@ -959,6 +1695,11 @@ var Engine = class _Engine {
959
1695
  if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
960
1696
  if (this.personMaskTex) this.gl.deleteTexture(this.personMaskTex);
961
1697
  this.personMaskTex = null;
1698
+ if (this.mergedTex) this.gl.deleteTexture(this.mergedTex);
1699
+ this.mergedTex = null;
1700
+ this.personBytes = null;
1701
+ this.classBytes = null;
1702
+ this.mergedBytes = null;
962
1703
  this.personRemote = false;
963
1704
  this.classMaskTex = null;
964
1705
  this.lmBuf = null;
@@ -1025,6 +1766,9 @@ async function coverCrop(src, w, h) {
1025
1766
  }
1026
1767
 
1027
1768
  // src/pipeline.ts
1769
+ var SLOW_FRAME_MS = 150;
1770
+ var SLOW_TICKS = 3;
1771
+ var MAX_GPU_RECOVERIES = 2;
1028
1772
  var WORKER_READY_MS = 8e3;
1029
1773
  var STALL_MS = 2e3;
1030
1774
  var LOADING_STALL_MS = 2e4;
@@ -1032,12 +1776,40 @@ var WORKER_DEAD_MS = 8e3;
1032
1776
  function hasInsertableStreams() {
1033
1777
  return typeof window !== "undefined" && "MediaStreamTrackProcessor" in window && "MediaStreamTrackGenerator" in window;
1034
1778
  }
1779
+ function checkSupport() {
1780
+ if (typeof window === "undefined") return { supported: false, reasons: ["no-window"], softwareRenderer: false, gpu: "", remembered: null };
1781
+ const reasons = [];
1782
+ if (typeof WebAssembly === "undefined") reasons.push("no-wasm");
1783
+ const gl = document.createElement("canvas").getContext("webgl2");
1784
+ let gpu = "";
1785
+ let softwareRenderer = false;
1786
+ if (!gl) reasons.push("no-webgl2");
1787
+ else {
1788
+ const info = gl.getExtension("WEBGL_debug_renderer_info");
1789
+ gpu = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "");
1790
+ const fast = document.createElement("canvas").getContext("webgl2", { failIfMajorPerformanceCaveat: true });
1791
+ softwareRenderer = !fast || /swiftshader|llvmpipe|software|basic render/i.test(gpu);
1792
+ fast?.getExtension("WEBGL_lose_context")?.loseContext();
1793
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
1794
+ }
1795
+ if (!hasInsertableStreams() && !("captureStream" in HTMLCanvasElement.prototype)) reasons.push("no-transport");
1796
+ const remembered = gpuRecord(gpu);
1797
+ if (remembered?.init) reasons.push("gpu-blocked");
1798
+ probedGpu = gpu;
1799
+ return { supported: reasons.length === 0, reasons, softwareRenderer, gpu, remembered };
1800
+ }
1801
+ var probedGpu = null;
1802
+ function probeGpu() {
1803
+ if (probedGpu !== null) return probedGpu;
1804
+ const gl = typeof document === "undefined" ? null : document.createElement("canvas").getContext("webgl2");
1805
+ if (!gl) return "";
1806
+ const info = gl.getExtension("WEBGL_debug_renderer_info");
1807
+ probedGpu = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "");
1808
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
1809
+ return probedGpu;
1810
+ }
1035
1811
  function mediakitSupported() {
1036
- if (typeof window === "undefined") return false;
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;
1812
+ return checkSupport().supported;
1041
1813
  }
1042
1814
  var VideoPipeline = class {
1043
1815
  processedTrack;
@@ -1053,6 +1825,15 @@ var VideoPipeline = class {
1053
1825
  stalled = false;
1054
1826
  watchdog = null;
1055
1827
  movedOff = false;
1828
+ raised = /* @__PURE__ */ new Set();
1829
+ slowTicks = 0;
1830
+ gpuRecoveries = 0;
1831
+ gpu = "";
1832
+ faceColorLost = false;
1833
+ recovering = false;
1834
+ workerDialect = null;
1835
+ generator = null;
1836
+ piping = Promise.resolve();
1056
1837
  /** What the worker last said about loading detectors. */
1057
1838
  workerLoading = false;
1058
1839
  // Frames handed out alongside the track - see subscribeFrames.
@@ -1082,7 +1863,8 @@ var VideoPipeline = class {
1082
1863
  transport: this.transport,
1083
1864
  frames: this.frames,
1084
1865
  sinceMs: this.lastBeat ? performance.now() - this.lastBeat : 0,
1085
- stalled: this.stalled
1866
+ stalled: this.stalled,
1867
+ effectError: this.stats?.effectError ?? ""
1086
1868
  };
1087
1869
  }
1088
1870
  /** Every processed frame. */
@@ -1108,6 +1890,55 @@ var VideoPipeline = class {
1108
1890
  }
1109
1891
  });
1110
1892
  }
1893
+ issue(code, message) {
1894
+ if (this.raised.has(code)) return;
1895
+ this.raised.add(code);
1896
+ console.warn(`mediakit: ${code}: ${message}`);
1897
+ try {
1898
+ this.opts.onIssue?.({ code, message, transport: this.transport });
1899
+ } catch (e) {
1900
+ console.error("mediakit: onIssue threw", e);
1901
+ }
1902
+ }
1903
+ watchQuality() {
1904
+ const s = this.stats;
1905
+ if (!s) return;
1906
+ if (s.effectError) this.issue("effect-off", s.effectError);
1907
+ const slow = s.totalMs > SLOW_FRAME_MS || s.faceMs > SLOW_FRAME_MS;
1908
+ this.slowTicks = slow ? Math.max(1, this.slowTicks + 1) : Math.min(-1, this.slowTicks - 1);
1909
+ if (this.slowTicks >= SLOW_TICKS) {
1910
+ this.issue("slow", `frames take ${Math.round(s.totalMs)}ms, face detection ${Math.round(s.faceMs)}ms`);
1911
+ } else if (this.slowTicks <= -SLOW_TICKS) {
1912
+ this.raised.delete("slow");
1913
+ }
1914
+ const phase = this.engine?.lostDuring;
1915
+ if (phase) void this.recoverGpu("the main-thread WebGL context was lost", phase);
1916
+ }
1917
+ noFaceColor() {
1918
+ return this.faceColorLost || (gpuRecord(this.gpu)?.faceColor ?? false);
1919
+ }
1920
+ /** A "link" loss rebuilds without face colour, a "run" loss as before; an "init" loss would only repeat. */
1921
+ async recoverGpu(why, phase, gpu = this.gpu) {
1922
+ if (this.recovering || this.stopped || !this.source || this.raised.has("gpu-lost")) return;
1923
+ recordLoss(gpu, phase);
1924
+ if (phase === "link") this.faceColorLost = true;
1925
+ const retry = phase !== "init" && this.gpuRecoveries < MAX_GPU_RECOVERIES;
1926
+ const during = phase === "link" ? "linking a makeup shader" : phase === "init" ? "building the shaders" : "while running";
1927
+ const next = !retry ? "not rebuilding" : phase === "link" ? "rebuilding without makeup" : "rebuilding";
1928
+ this.issue("gpu-lost", `${why} (${during}, ${next})`);
1929
+ if (!retry) return;
1930
+ this.gpuRecoveries++;
1931
+ this.recovering = true;
1932
+ try {
1933
+ if (this.transport === "worker" && phase === "run") await this.moveOffWorker("lost its WebGL context");
1934
+ else await this.rebuild(this.source);
1935
+ this.raised.delete("gpu-lost");
1936
+ } catch (e) {
1937
+ console.error("mediakit: rebuilding after a lost WebGL context failed", e);
1938
+ } finally {
1939
+ this.recovering = false;
1940
+ }
1941
+ }
1111
1942
  beat() {
1112
1943
  this.lastBeat = performance.now();
1113
1944
  this.frames++;
@@ -1131,9 +1962,11 @@ var VideoPipeline = class {
1131
1962
  const transport = this.transport;
1132
1963
  if (since >= (loading ? LOADING_STALL_MS : STALL_MS) && !this.stalled) {
1133
1964
  this.stalled = true;
1134
- console.warn(`mediakit: no frame out for ${Math.round(since)}ms on the ${transport} transport`);
1965
+ this.issue("stall", `no frame out for ${Math.round(since)}ms on the ${transport} transport`);
1135
1966
  this.opts.onStall?.({ transport, sinceMs: since });
1136
1967
  }
1968
+ if (!this.stalled) this.raised.delete("stall");
1969
+ this.watchQuality();
1137
1970
  if (transport === "worker" && since >= (loading ? LOADING_STALL_MS : WORKER_DEAD_MS)) {
1138
1971
  void this.moveOffWorker("silent");
1139
1972
  }
@@ -1147,7 +1980,7 @@ var VideoPipeline = class {
1147
1980
  async moveOffWorker(reason) {
1148
1981
  if (this.movedOff || this.stopped || !this.source) return;
1149
1982
  this.movedOff = true;
1150
- console.warn(`mediakit: worker ${reason} after start, moving to the main thread`);
1983
+ this.issue("worker-moved", `worker ${reason} after start, moving to the main thread`);
1151
1984
  const previous = this.processedTrack;
1152
1985
  this.teardownWorker();
1153
1986
  try {
@@ -1167,6 +2000,11 @@ var VideoPipeline = class {
1167
2000
  }
1168
2001
  /** Take over `source` and publish the result on {@link processedTrack}. */
1169
2002
  async start(source) {
2003
+ this.gpu ||= probeGpu();
2004
+ const known = gpuRecord(this.gpu);
2005
+ if (known?.init) {
2006
+ throw new GpuLostError("init", this.gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`);
2007
+ }
1170
2008
  const settings = source.getSettings();
1171
2009
  const width = settings.width ?? 1280;
1172
2010
  const height = settings.height ?? 720;
@@ -1174,23 +2012,28 @@ var VideoPipeline = class {
1174
2012
  this.source = source;
1175
2013
  this.size = { width, height, fps: settings.frameRate ?? 30 };
1176
2014
  this.frames = 0;
2015
+ this.movedOff = false;
1177
2016
  this.startWatchdog();
1178
2017
  if (hasInsertableStreams() && typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
1179
2018
  try {
1180
2019
  await this.startWorker(source, width, height, await this.backgroundForWorker(this.filter));
1181
2020
  this.transport = "worker";
2021
+ this.workerDialect = "streams";
1182
2022
  return;
1183
2023
  } catch (e) {
1184
2024
  this.teardownWorker();
2025
+ if (e instanceof GpuLostError) throw e;
1185
2026
  console.warn("mediakit: worker unusable, falling back to the main thread", e);
1186
2027
  }
1187
2028
  } else if (typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
1188
2029
  try {
1189
2030
  await this.startWorkerWithTrack(source, width, height, await this.backgroundForWorker(this.filter));
1190
2031
  this.transport = "worker";
2032
+ this.workerDialect = "track";
1191
2033
  return;
1192
2034
  } catch (e) {
1193
2035
  this.teardownWorker();
2036
+ if (e instanceof GpuLostError) throw e;
1194
2037
  console.warn("mediakit: no worker transport in this browser, staying on the main thread", e);
1195
2038
  }
1196
2039
  }
@@ -1198,7 +2041,9 @@ var VideoPipeline = class {
1198
2041
  }
1199
2042
  async startMain(source) {
1200
2043
  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);
2044
+ this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces, {
2045
+ noFaceColor: this.noFaceColor()
2046
+ });
1202
2047
  this.engine.syncFaces = this.opts.syncFaces ?? false;
1203
2048
  this.engine.setDebug(this.debug);
1204
2049
  this.transport = hasInsertableStreams() ? "insertable" : "canvas";
@@ -1211,6 +2056,45 @@ var VideoPipeline = class {
1211
2056
  await this.startCanvas(source, fps);
1212
2057
  }
1213
2058
  }
2059
+ /**
2060
+ * Feed a different camera into the running pipeline, as Tencent's `resetCore(input)`. At the
2061
+ * same resolution {@link processedTrack} stays the same track; otherwise the pipeline rebuilds
2062
+ * and `onTrackReplaced` fires. The caller still owns both sources: neither is stopped here.
2063
+ */
2064
+ async replaceSource(next) {
2065
+ if (this.stopped || !this.source) throw new Error("mediakit: replaceSource before start");
2066
+ const settings = next.getSettings();
2067
+ const width = settings.width ?? 1280;
2068
+ const height = settings.height ?? 720;
2069
+ if (width !== this.size.width || height !== this.size.height) {
2070
+ await this.rebuild(next);
2071
+ return this.processedTrack;
2072
+ }
2073
+ if (this.transport === "worker" && this.workerDialect === "streams") {
2074
+ const processor = new MediaStreamTrackProcessor({ track: next });
2075
+ this.send({ t: "source", readable: processor.readable }, [processor.readable]);
2076
+ } else if (this.transport === "worker") {
2077
+ const clone = next.clone();
2078
+ this.send({ t: "sourceTrack", track: clone }, [clone]);
2079
+ } else if (this.transport === "insertable") {
2080
+ this.pipeInsertable(next);
2081
+ } else if (this.video) {
2082
+ this.video.srcObject = new MediaStream([next]);
2083
+ await this.video.play();
2084
+ }
2085
+ this.source = next;
2086
+ this.size.fps = settings.frameRate ?? this.size.fps;
2087
+ this.lastBeat = performance.now();
2088
+ return this.processedTrack;
2089
+ }
2090
+ async rebuild(source) {
2091
+ const previous = this.processedTrack;
2092
+ this.processedTrack = void 0;
2093
+ this.teardownTransports();
2094
+ await this.start(source);
2095
+ previous?.stop();
2096
+ if (this.processedTrack) this.opts.onTrackReplaced?.(this.processedTrack, previous);
2097
+ }
1214
2098
  /** Swap the background in place - no pipeline rebuild, so the picture does not flash. */
1215
2099
  async switchTo(filter) {
1216
2100
  this.filter = filter;
@@ -1246,8 +2130,14 @@ var VideoPipeline = class {
1246
2130
  this.stopped = true;
1247
2131
  this.stopWatchdog();
1248
2132
  this.source = null;
2133
+ this.teardownTransports();
2134
+ this.processedTrack?.stop();
2135
+ this.processedTrack = void 0;
2136
+ }
2137
+ teardownTransports() {
1249
2138
  this.abort?.abort();
1250
2139
  this.abort = null;
2140
+ this.generator = null;
1251
2141
  if (this.rvfcHandle && this.video) {
1252
2142
  this.video.cancelVideoFrameCallback?.(this.rvfcHandle);
1253
2143
  }
@@ -1259,8 +2149,6 @@ var VideoPipeline = class {
1259
2149
  this.video = null;
1260
2150
  }
1261
2151
  this.teardownWorker();
1262
- this.processedTrack?.stop();
1263
- this.processedTrack = void 0;
1264
2152
  this.engine?.close();
1265
2153
  this.engine = null;
1266
2154
  }
@@ -1284,6 +2172,7 @@ var VideoPipeline = class {
1284
2172
  this.send({ t: "stop" });
1285
2173
  this.worker.terminate();
1286
2174
  this.worker = null;
2175
+ this.workerDialect = null;
1287
2176
  this.workerStats = null;
1288
2177
  this.workerLoading = false;
1289
2178
  this.workerBackgroundPath = null;
@@ -1339,7 +2228,8 @@ var VideoPipeline = class {
1339
2228
  alpha: this.opts.alpha,
1340
2229
  maxFaces: this.opts.maxFaces,
1341
2230
  syncFaces: this.opts.syncFaces,
1342
- debug: this.debug
2231
+ debug: this.debug,
2232
+ noFaceColor: this.noFaceColor()
1343
2233
  },
1344
2234
  background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
1345
2235
  )
@@ -1366,7 +2256,8 @@ var VideoPipeline = class {
1366
2256
  alpha: this.opts.alpha,
1367
2257
  maxFaces: this.opts.maxFaces,
1368
2258
  syncFaces: this.opts.syncFaces,
1369
- debug: this.debug
2259
+ debug: this.debug,
2260
+ noFaceColor: this.noFaceColor()
1370
2261
  },
1371
2262
  background ? [clone, background] : [clone]
1372
2263
  )
@@ -1410,6 +2301,15 @@ var VideoPipeline = class {
1410
2301
  this.deliver(m.frame);
1411
2302
  return;
1412
2303
  }
2304
+ if (m.t === "lost") {
2305
+ const gpu = m.gpu || this.gpu;
2306
+ if (settled) void this.recoverGpu("the worker's WebGL context was lost", m.phase, gpu);
2307
+ else {
2308
+ recordLoss(gpu, m.phase);
2309
+ fail(m.phase === "init" ? new GpuLostError("init", gpu, m.message) : new Error("mediakit: the worker's WebGL context was lost"));
2310
+ }
2311
+ return;
2312
+ }
1413
2313
  if (m.t === "error") {
1414
2314
  if (settled) {
1415
2315
  console.error("mediakit: worker failed after start", m.message);
@@ -1440,17 +2340,27 @@ var VideoPipeline = class {
1440
2340
  }
1441
2341
  // ── insertable ───────────────────────────────────────────────────────────────────
1442
2342
  startInsertable(source) {
1443
- const engine = this.engine;
1444
- const processor = new MediaStreamTrackProcessor({
1445
- track: source
1446
- });
1447
- const generator = new MediaStreamTrackGenerator({
2343
+ this.generator = new MediaStreamTrackGenerator({
1448
2344
  kind: "video",
1449
2345
  signalTarget: source
1450
2346
  });
2347
+ this.processedTrack = this.generator;
2348
+ this.pipeInsertable(source);
2349
+ }
2350
+ pipeInsertable(source) {
2351
+ const generator = this.generator;
2352
+ if (!generator) return;
2353
+ const processor = new MediaStreamTrackProcessor({
2354
+ track: source
2355
+ });
1451
2356
  const transform = new TransformStream({
1452
2357
  transform: (frame, controller) => {
1453
2358
  this.beat();
2359
+ const engine = this.engine;
2360
+ if (!engine) {
2361
+ controller.enqueue(frame);
2362
+ return;
2363
+ }
1454
2364
  try {
1455
2365
  const drew = engine.render(frame, frame.timestamp);
1456
2366
  const held = drew ? null : engine.passthrough();
@@ -1473,11 +2383,16 @@ var VideoPipeline = class {
1473
2383
  frame.close();
1474
2384
  }
1475
2385
  });
1476
- this.abort = new AbortController();
1477
- this.processedTrack = generator;
1478
- processor.readable.pipeThrough(transform, { signal: this.abort.signal }).pipeTo(generator.writable, { signal: this.abort.signal }).catch((e) => {
1479
- if (e instanceof DOMException && e.name === "AbortError") return;
1480
- if (!this.stopped) console.error("mediakit: pipe broke", e);
2386
+ this.abort?.abort();
2387
+ const abort = new AbortController();
2388
+ this.abort = abort;
2389
+ const previous = this.piping;
2390
+ this.piping = previous.then(() => {
2391
+ if (abort.signal.aborted) return;
2392
+ return processor.readable.pipeThrough(transform, { signal: abort.signal }).pipeTo(generator.writable, { signal: abort.signal, preventAbort: true, preventClose: true }).catch((e) => {
2393
+ if (abort.signal.aborted) return;
2394
+ if (!this.stopped) console.error("mediakit: pipe broke", e);
2395
+ });
1481
2396
  });
1482
2397
  }
1483
2398
  // ── canvas ───────────────────────────────────────────────────────────────────────
@@ -2872,11 +3787,15 @@ export {
2872
3787
  EFFECTS_SCHEMA,
2873
3788
  Engine,
2874
3789
  FACE_UV,
3790
+ GpuLostError,
2875
3791
  NO_EFFECTS,
2876
3792
  Scene,
2877
3793
  TOUCH_UP,
2878
3794
  TRANSITIONS,
2879
3795
  VideoPipeline,
3796
+ checkSupport,
3797
+ forgetGpuFailures,
3798
+ gpuRecord,
2880
3799
  hitTest,
2881
3800
  layouts,
2882
3801
  mediakitSupported,
@@ -2885,6 +3804,7 @@ export {
2885
3804
  needsSegmentation,
2886
3805
  normalizeEffects,
2887
3806
  parseColor,
3807
+ preloadDetectors,
2888
3808
  renderText,
2889
3809
  touchUp,
2890
3810
  touchUpAmount