@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/worker.js CHANGED
@@ -4675,15 +4675,74 @@
4675
4675
  return ec(zc, t2, e2);
4676
4676
  }, zc.POSE_CONNECTIONS = Lc, r("module$exports$google3$third_party$mediapipe$tasks$web$vision$pose_landmarker$pose_landmarker.PoseLandmarker.POSE_CONNECTIONS", zc.POSE_CONNECTIONS);
4677
4677
 
4678
- // src/segmenter.ts
4679
- var WASM_DIR = "/mediakit/mp";
4678
+ // src/mp.ts
4679
+ var MP_DIR = "/mediakit/mp";
4680
4680
  var MODEL_URL = {
4681
4681
  person: "/mediakit/selfie_segmenter.tflite",
4682
- classes: "/mediakit/selfie_multiclass_256x256.tflite"
4682
+ classes: "/mediakit/selfie_multiclass_256x256.tflite",
4683
+ face: "/mediakit/face_landmarker.task"
4684
+ };
4685
+ var LOAD_MS = 6e4;
4686
+ var fileset = null;
4687
+ function visionFileset() {
4688
+ fileset ??= uh.forVisionTasks(MP_DIR).catch((e2) => {
4689
+ fileset = null;
4690
+ throw e2;
4691
+ });
4692
+ return fileset;
4693
+ }
4694
+ var LoadTimeout = class extends Error {
4695
+ constructor(what, ms2) {
4696
+ super(`mediakit: ${what} did not load within ${Math.round(ms2 / 1e3)} s`);
4697
+ this.name = "LoadTimeout";
4698
+ }
4683
4699
  };
4700
+ function withTimeout(p2, ms2, what, late) {
4701
+ return new Promise((resolve, reject) => {
4702
+ let done = false;
4703
+ const timer = setTimeout(() => {
4704
+ done = true;
4705
+ reject(new LoadTimeout(what, ms2));
4706
+ }, ms2);
4707
+ p2.then(
4708
+ (v2) => {
4709
+ if (done) late(v2);
4710
+ else {
4711
+ done = true;
4712
+ clearTimeout(timer);
4713
+ resolve(v2);
4714
+ }
4715
+ },
4716
+ (e2) => {
4717
+ if (done) return;
4718
+ done = true;
4719
+ clearTimeout(timer);
4720
+ reject(e2);
4721
+ }
4722
+ );
4723
+ });
4724
+ }
4725
+
4726
+ // src/mp-clock.ts
4727
+ var SOURCE_SWITCH_GAP_MS = 33;
4728
+ function monotonicClock() {
4729
+ let offset = 0;
4730
+ let last = -Infinity;
4731
+ return (timestampMs) => {
4732
+ let t2 = timestampMs + offset;
4733
+ if (t2 <= last) {
4734
+ offset += last + SOURCE_SWITCH_GAP_MS - t2;
4735
+ t2 = last + SOURCE_SWITCH_GAP_MS;
4736
+ }
4737
+ last = t2;
4738
+ return t2;
4739
+ };
4740
+ }
4741
+
4742
+ // src/segmenter.ts
4684
4743
  async function createSegmenter(canvas, model = "person") {
4685
- const fileset = await uh.forVisionTasks(WASM_DIR);
4686
- const segmenter = await $c.createFromOptions(fileset, {
4744
+ const fileset2 = await visionFileset();
4745
+ const segmenter = await $c.createFromOptions(fileset2, {
4687
4746
  baseOptions: {
4688
4747
  modelAssetPath: MODEL_URL[model],
4689
4748
  // MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all
@@ -4699,6 +4758,7 @@
4699
4758
  outputCategoryMask: true,
4700
4759
  outputConfidenceMasks: false
4701
4760
  });
4761
+ const clock = monotonicClock();
4702
4762
  let pending = null;
4703
4763
  const release = () => {
4704
4764
  pending?.close();
@@ -4708,7 +4768,7 @@
4708
4768
  segment(frame, timestampMs) {
4709
4769
  release();
4710
4770
  let texture = null;
4711
- segmenter.segmentForVideo(frame, timestampMs, (result) => {
4771
+ segmenter.segmentForVideo(frame, clock(timestampMs), (result) => {
4712
4772
  const mask = result.categoryMask;
4713
4773
  if (mask) texture = mask.getAsWebGLTexture();
4714
4774
  pending = result;
@@ -4724,15 +4784,27 @@
4724
4784
  }
4725
4785
 
4726
4786
  // src/face.ts
4727
- var WASM_DIR2 = "/mediakit/mp";
4728
- var MODEL_URL2 = "/mediakit/face_landmarker.task";
4729
4787
  var FACE_FLOATS = 478 * 3;
4730
- async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
4731
- const fileset = await uh.forVisionTasks(WASM_DIR2);
4732
- const landmarker = await yc.createFromOptions(fileset, {
4733
- baseOptions: { modelAssetPath: MODEL_URL2, delegate },
4788
+ var COVER_SIZE = 96;
4789
+ function faceBox(lm, at2) {
4790
+ let x0 = 1;
4791
+ let y0 = 1;
4792
+ let x1 = 0;
4793
+ let y1 = 0;
4794
+ for (let i2 = at2; i2 < at2 + FACE_FLOATS; i2 += 3) {
4795
+ x0 = Math.min(x0, lm[i2]);
4796
+ x1 = Math.max(x1, lm[i2]);
4797
+ y0 = Math.min(y0, lm[i2 + 1]);
4798
+ y1 = Math.max(y1, lm[i2 + 1]);
4799
+ }
4800
+ return [x0, y0, x1 - x0, y1 - y0];
4801
+ }
4802
+ async function createFaceDetector(canvas, maxFaces, delegate = "GPU", mode = "VIDEO") {
4803
+ const fileset2 = await visionFileset();
4804
+ const landmarker = await yc.createFromOptions(fileset2, {
4805
+ baseOptions: { modelAssetPath: MODEL_URL.face, delegate },
4734
4806
  canvas,
4735
- runningMode: "VIDEO",
4807
+ runningMode: mode,
4736
4808
  // As many as the core tracks: one landmark pass returns them all, so the cost of a second
4737
4809
  // face is the copy below and its own shader passes, not a second inference.
4738
4810
  numFaces: maxFaces,
@@ -4740,9 +4812,10 @@
4740
4812
  outputFaceBlendshapes: false,
4741
4813
  outputFacialTransformationMatrixes: false
4742
4814
  });
4815
+ const clock = monotonicClock();
4743
4816
  return {
4744
4817
  detect(frame, timestampMs, out) {
4745
- const res = landmarker.detectForVideo(frame, timestampMs);
4818
+ const res = mode === "VIDEO" ? landmarker.detectForVideo(frame, clock(timestampMs)) : landmarker.detect(frame);
4746
4819
  let n2 = 0;
4747
4820
  for (const lm of res.faceLandmarks ?? []) {
4748
4821
  if (lm.length * 3 !== FACE_FLOATS || n2 + FACE_FLOATS > out.length) break;
@@ -4764,7 +4837,6 @@
4764
4837
 
4765
4838
  // src/detect-remote.ts
4766
4839
  var DETECT_WORKER_URL = "/mediakit/detect-worker.js";
4767
- var READY_MS = 2e4;
4768
4840
  var DetectWorker = class {
4769
4841
  constructor(on2) {
4770
4842
  this.on = on2;
@@ -4788,13 +4860,13 @@
4788
4860
  return this.worker !== null && this.up.has(kind) && !this.busy.has(kind);
4789
4861
  }
4790
4862
  /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */
4791
- request(kind, frame, tsUs) {
4863
+ request(kind, frame, tsUs, cover = false, retry = null) {
4792
4864
  if (!this.accepts(kind)) {
4793
4865
  frame.close();
4794
4866
  return false;
4795
4867
  }
4796
4868
  this.busy.add(kind);
4797
- this.send({ t: kind, frame, tsUs }, [frame]);
4869
+ this.send(kind === "face" ? { t: kind, frame, tsUs, cover, retry } : { t: kind, frame, tsUs }, [frame]);
4798
4870
  return true;
4799
4871
  }
4800
4872
  isUp(kind) {
@@ -4813,7 +4885,7 @@
4813
4885
  reject(new Error("detect worker gone"));
4814
4886
  return;
4815
4887
  }
4816
- const timer = setTimeout(() => this.settle(kind, new Error(`${kind}: no ready after ${READY_MS} ms`)), READY_MS);
4888
+ const timer = setTimeout(() => this.settle(kind, new LoadTimeout(`${kind} detection`, LOAD_MS)), LOAD_MS);
4817
4889
  this.ready.set(kind, { resolve, reject, timer });
4818
4890
  this.send(m2);
4819
4891
  });
@@ -4830,7 +4902,7 @@
4830
4902
  break;
4831
4903
  case "face":
4832
4904
  this.busy.delete("face");
4833
- if (this.up.has("face")) this.on.face(m2.tsUs, m2.n, m2.lm, m2.ms);
4905
+ if (this.up.has("face")) this.on.face(m2.tsUs, m2.n, m2.lm, m2.ms, m2.cover, m2.rects);
4834
4906
  break;
4835
4907
  case "mask":
4836
4908
  this.busy.delete("mask");
@@ -4934,6 +5006,137 @@
4934
5006
  return [lo2, hi2 | 0];
4935
5007
  }
4936
5008
 
5009
+ // src/gpu-guard.ts
5010
+ var KEY = "mediakit-gpu-guard";
5011
+ var TTL_MS = 3 * 24 * 3600 * 1e3;
5012
+ function storage() {
5013
+ try {
5014
+ return typeof localStorage === "undefined" ? null : localStorage;
5015
+ } catch {
5016
+ return null;
5017
+ }
5018
+ }
5019
+ function load() {
5020
+ const s2 = storage();
5021
+ if (!s2) return {};
5022
+ try {
5023
+ const parsed = JSON.parse(s2.getItem(KEY) ?? "{}");
5024
+ return parsed && typeof parsed === "object" ? parsed : {};
5025
+ } catch {
5026
+ return {};
5027
+ }
5028
+ }
5029
+ function save(store) {
5030
+ try {
5031
+ storage()?.setItem(KEY, JSON.stringify(store));
5032
+ } catch {
5033
+ return;
5034
+ }
5035
+ }
5036
+ function gpuRecord(gpu) {
5037
+ if (!gpu) return null;
5038
+ const r2 = load()[gpu];
5039
+ if (!r2 || typeof r2.at !== "number" || Date.now() - r2.at > TTL_MS) return null;
5040
+ return { init: r2.init === true, faceColor: r2.faceColor === true, at: r2.at };
5041
+ }
5042
+ function recordLoss(gpu, phase) {
5043
+ if (!gpu || phase === "run" || !storage()) return;
5044
+ const store = load();
5045
+ const was = gpuRecord(gpu);
5046
+ store[gpu] = {
5047
+ init: phase === "init" || (was?.init ?? false),
5048
+ faceColor: phase === "link" || (was?.faceColor ?? false),
5049
+ at: Date.now()
5050
+ };
5051
+ save(store);
5052
+ }
5053
+ function rendererOf(gl) {
5054
+ if (gl.isContextLost()) return "";
5055
+ const info = gl.getExtension("WEBGL_debug_renderer_info");
5056
+ return String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "");
5057
+ }
5058
+ var GpuLostError = class extends Error {
5059
+ constructor(phase, gpu, detail = "") {
5060
+ 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"}]`);
5061
+ this.phase = phase;
5062
+ this.gpu = gpu;
5063
+ this.detail = detail;
5064
+ this.name = "GpuLostError";
5065
+ }
5066
+ phase;
5067
+ gpu;
5068
+ detail;
5069
+ };
5070
+
5071
+ // src/mask-merge.ts
5072
+ var CLASS_BACKGROUND = 0;
5073
+ var CLASS_BODY_SKIN = 2;
5074
+ var CLASS_CLOTHES = 4;
5075
+ var CLASS_OTHERS = 5;
5076
+ var CLASS_STALE_OCCLUDER = 6;
5077
+ var THUMB_W = 64;
5078
+ var THUMB_H = 36;
5079
+ var MOVED_LUMA = 12;
5080
+ function lumaThumb(rgba) {
5081
+ const y2 = new Uint8Array(THUMB_W * THUMB_H);
5082
+ for (let i2 = 0; i2 < y2.length; i2++) y2[i2] = rgba[i2 * 4] * 77 + rgba[i2 * 4 + 1] * 150 + rgba[i2 * 4 + 2] * 29 >> 8;
5083
+ return y2;
5084
+ }
5085
+ function movedBetween(a2, b2) {
5086
+ const w2 = THUMB_W;
5087
+ const h2 = THUMB_H;
5088
+ const hit = new Uint8Array(w2 * h2);
5089
+ for (let i2 = 0; i2 < hit.length; i2++) hit[i2] = Math.abs(a2[i2] - b2[i2]) > MOVED_LUMA ? 1 : 0;
5090
+ const data = new Uint8Array(w2 * h2);
5091
+ for (let y2 = 0; y2 < h2; y2++) {
5092
+ for (let x2 = 0; x2 < w2; x2++) {
5093
+ let v2 = 0;
5094
+ for (let dy = -1; dy <= 1 && !v2; dy++) {
5095
+ const yy = y2 + dy;
5096
+ if (yy < 0 || yy >= h2) continue;
5097
+ for (let dx = -1; dx <= 1; dx++) {
5098
+ const xx = x2 + dx;
5099
+ if (xx >= 0 && xx < w2 && hit[yy * w2 + xx]) {
5100
+ v2 = 1;
5101
+ break;
5102
+ }
5103
+ }
5104
+ }
5105
+ data[y2 * w2 + x2] = v2;
5106
+ }
5107
+ }
5108
+ return { width: w2, height: h2, data };
5109
+ }
5110
+ function mergeMasks(person, classes, out, moved = null) {
5111
+ const { width: w2, height: h2 } = person;
5112
+ const merged = out && out.length === w2 * h2 ? out : new Uint8Array(w2 * h2);
5113
+ const cw = classes.width;
5114
+ const ch2 = classes.height;
5115
+ const sx = cw / w2;
5116
+ const sy = ch2 / h2;
5117
+ const mw = moved?.width ?? 0;
5118
+ const mh2 = moved?.height ?? 0;
5119
+ for (let y2 = 0; y2 < h2; y2++) {
5120
+ const crow = Math.min(ch2 - 1, Math.floor((y2 + 0.5) * sy)) * cw;
5121
+ const mrow = moved ? Math.min(mh2 - 1, Math.floor((y2 + 0.5) * mh2 / h2)) * mw : 0;
5122
+ const prow = y2 * w2;
5123
+ for (let x2 = 0; x2 < w2; x2++) {
5124
+ if (person.data[prow + x2] !== 0) {
5125
+ merged[prow + x2] = CLASS_BACKGROUND;
5126
+ continue;
5127
+ }
5128
+ const c2 = classes.data[crow + Math.min(cw - 1, Math.floor((x2 + 0.5) * sx))];
5129
+ if (c2 === CLASS_BACKGROUND) {
5130
+ merged[prow + x2] = CLASS_CLOTHES;
5131
+ continue;
5132
+ }
5133
+ const stale = moved !== null && (c2 === CLASS_BODY_SKIN || c2 === CLASS_OTHERS) && moved.data[mrow + Math.min(mw - 1, Math.floor((x2 + 0.5) * mw / w2))] !== 0;
5134
+ merged[prow + x2] = stale ? CLASS_STALE_OCCLUDER : c2;
5135
+ }
5136
+ }
5137
+ return merged;
5138
+ }
5139
+
4937
5140
  // src/recipe.ts
4938
5141
  var DEBUG_VIEWS = ["off", "skin", "mask", "face"];
4939
5142
  function debugCode(view) {
@@ -4948,6 +5151,7 @@
4948
5151
  tint: 0,
4949
5152
  vibrance: 0,
4950
5153
  grain: 0,
5154
+ sharpen: 0,
4951
5155
  autoframe: false,
4952
5156
  teeth: 0,
4953
5157
  eyeBright: 0,
@@ -4967,6 +5171,8 @@
4967
5171
  whiten: 0,
4968
5172
  skinLight: 0,
4969
5173
  clarity: 0,
5174
+ hair: 0,
5175
+ hairColor: [0.45, 0.22, 0.12],
4970
5176
  skinScope: "person",
4971
5177
  lut: "",
4972
5178
  grade: 0,
@@ -4975,6 +5181,7 @@
4975
5181
  keyColor: [0, 0, 0],
4976
5182
  keyTolerance: 0,
4977
5183
  autoLight: false,
5184
+ occluders: false,
4978
5185
  mirror: false,
4979
5186
  slimFace: 0,
4980
5187
  enlargeEyes: 0,
@@ -5012,7 +5219,7 @@
5012
5219
  }
5013
5220
  }
5014
5221
  function needsMask(f2, e2) {
5015
- return f2.kind !== "none" || e2.beautify > 0 || e2.autoframe || hasSkin(e2) || e2.grade > 0 && (e2.gradeScope ?? "frame") !== "frame";
5222
+ return f2.kind !== "none" || e2.beautify > 0 || e2.autoframe || hasSkin(e2) || e2.grade > 0 && (e2.gradeScope ?? "frame") !== "frame" || (e2.hair ?? 0) > 0;
5016
5223
  }
5017
5224
  function hasSkin(e2) {
5018
5225
  return (e2.whiten ?? 0) > 0 || (e2.skinLight ?? 0) > 0 || (e2.clarity ?? 0) > 0;
@@ -5021,7 +5228,7 @@
5021
5228
  return needsMask(f2, e2) && !e2.chromaKey;
5022
5229
  }
5023
5230
  function needsSkinClasses(_f, e2) {
5024
- return e2.grade > 0 && (e2.gradeScope ?? "frame") !== "frame";
5231
+ return e2.grade > 0 && (e2.gradeScope ?? "frame") !== "frame" || (e2.hair ?? 0) > 0;
5025
5232
  }
5026
5233
  function needsFace(e2) {
5027
5234
  return e2.teeth > 0 || e2.eyeBright > 0 || e2.underEye > 0 || e2.smileLines > 0 || e2.lips > 0 || e2.blush > 0 || e2.iris > 0 || (e2.eyeShadow ?? 0) > 0 || (e2.lipGloss ?? 0) > 0 || (e2.rosy ?? 0) > 0 || e2.skinScope === "face" && (e2.beautify > 0 || hasSkin(e2)) || // Whitening and skin light measure skin on the face; clarity is held to it.
@@ -5039,6 +5246,7 @@
5039
5246
  tint: e2.tint ?? 0,
5040
5247
  vibrance: e2.vibrance ?? 0,
5041
5248
  grain: e2.grain ?? 0,
5249
+ sharpen: e2.sharpen ?? 0,
5042
5250
  autoframe: e2.autoframe,
5043
5251
  teeth: e2.teeth,
5044
5252
  eyeBright: e2.eyeBright,
@@ -5058,6 +5266,8 @@
5058
5266
  whiten: e2.whiten ?? 0,
5059
5267
  skinLight: e2.skinLight ?? 0,
5060
5268
  clarity: e2.clarity ?? 0,
5269
+ hair: e2.hair ?? 0,
5270
+ hairColor: e2.hairColor ?? NO_EFFECTS.hairColor,
5061
5271
  skinScope: SKIN_SCOPE[e2.skinScope] ?? 0,
5062
5272
  grade: e2.grade,
5063
5273
  gradeScope: GRADE_SCOPE[e2.gradeScope] ?? 0,
@@ -5065,6 +5275,7 @@
5065
5275
  keyColor: e2.keyColor,
5066
5276
  keyTolerance: e2.keyTolerance,
5067
5277
  autoLight: e2.autoLight,
5278
+ occluders: e2.occluders ?? false,
5068
5279
  mirror: e2.mirror,
5069
5280
  slimFace: e2.slimFace,
5070
5281
  enlargeEyes: e2.enlargeEyes,
@@ -5103,17 +5314,58 @@
5103
5314
  faces: 0,
5104
5315
  heldFrames: 0,
5105
5316
  faceAgeMs: 0,
5106
- maskAgeMs: 0
5107
- };
5108
- var MAX_HOLD = 2;
5109
- var DEPTH_VOTES = 15;
5317
+ maskAgeMs: 0,
5318
+ effectError: ""
5319
+ };
5320
+ var MAX_HOLD = 3;
5321
+ var COVER_FRAME_W = 256;
5322
+ var COVER_HOLD = 0.6;
5323
+ var COVER_MISSES = 2;
5324
+ var FOLLOW_SIDE = 384;
5325
+ var FOLLOW_MARGIN = 2.6;
5326
+ var FOLLOW_RETRY = 2;
5327
+ var FOLLOW_MIN_SIDE = 64;
5328
+ var FOLLOW_SHIFT = 0.06;
5329
+ var FOLLOW_RESIZE = 0.12;
5330
+ var FOLLOW_STALE_US = 5e5;
5331
+ var FOLLOW_KEPT_US = 1e6;
5332
+ var SCAN_SHARE = 0.5;
5333
+ var SCAN_STEP = 0.75;
5334
+ var FOLLOW_REFRESH = 30;
5335
+ var FOLLOW_WIDEN = 2;
5336
+ var FOLLOW_GROW = 3;
5337
+ var SAME_FACE = 0.3;
5338
+ var FACE_RESULTS_KEPT = 8;
5339
+ var THUMBS_KEPT = 12;
5340
+ var LINK_LOSS_WINDOW_MS = 3e3;
5341
+ var FACE_JUMP = 0.15;
5342
+ var CATCH_UP_EVERY_US = 1e6;
5343
+ var MASK_RESULTS_KEPT = 8;
5110
5344
  var DETECT_DUTY = 0.6;
5345
+ function gpuName(gl) {
5346
+ const info = gl.getExtension("WEBGL_debug_renderer_info");
5347
+ const name = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "unknown");
5348
+ return gl.isContextLost() ? `${name}, context lost` : name;
5349
+ }
5111
5350
  function sourceSize(source) {
5112
5351
  if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
5113
5352
  if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
5114
5353
  const s2 = source;
5115
5354
  return [s2.width, s2.height];
5116
5355
  }
5356
+ function tileGrid(sw, sh2) {
5357
+ const side = Math.max(FOLLOW_MIN_SIDE, Math.round(Math.min(sw, sh2) * SCAN_SHARE));
5358
+ const step = side * SCAN_STEP;
5359
+ return { side, step, nx: Math.max(1, Math.ceil((sw - side) / step) + 1), ny: Math.max(1, Math.ceil((sh2 - side) / step) + 1) };
5360
+ }
5361
+ function overlap(a2, b2) {
5362
+ const w2 = Math.min(a2[0] + a2[2], b2[0] + b2[2]) - Math.max(a2[0], b2[0]);
5363
+ const h2 = Math.min(a2[1] + a2[3], b2[1] + b2[3]) - Math.max(a2[1], b2[1]);
5364
+ if (w2 <= 0 || h2 <= 0) return 0;
5365
+ const i2 = w2 * h2;
5366
+ return i2 / (a2[2] * a2[3] + b2[2] * b2[3] - i2);
5367
+ }
5368
+ var FACE_COLOR_SKIPPED = "face colour shaders skipped: linking one lost the WebGL context on this GPU before";
5117
5369
  var Engine = class _Engine {
5118
5370
  canvas;
5119
5371
  gl;
@@ -5144,6 +5396,14 @@
5144
5396
  classLoading = null;
5145
5397
  /** The segmenter whose result this frame borrowed, to give it back after process(). */
5146
5398
  used = null;
5399
+ programErr = "";
5400
+ loadErr = "";
5401
+ gpu = "";
5402
+ linkSeenAt = -Infinity;
5403
+ links = 0;
5404
+ lostPhase = null;
5405
+ classFailed = false;
5406
+ failed = /* @__PURE__ */ new Set();
5147
5407
  /**
5148
5408
  * The landmark detector, also lazy and independent of the segmenter.
5149
5409
  *
@@ -5158,13 +5418,14 @@
5158
5418
  classRemote = false;
5159
5419
  classMaskTex = null;
5160
5420
  classMaskFresh = false;
5161
- classMaskTs = 0;
5421
+ classMaskTs = -1;
5162
5422
  syncFaces = false;
5163
5423
  renderedTs = 0;
5164
5424
  queue = [];
5165
5425
  spare = [];
5166
- holdDepth = 1;
5167
- depthVotes = 0;
5426
+ faceExtraUp = false;
5427
+ faceExtraTried = false;
5428
+ lerpBuf = null;
5168
5429
  gapUs = 33333;
5169
5430
  prevTs = -1;
5170
5431
  sent = /* @__PURE__ */ new Map();
@@ -5172,6 +5433,35 @@
5172
5433
  faceLatencyMs = 0;
5173
5434
  maskLatencyMs = /* @__PURE__ */ new Map();
5174
5435
  faceTs = -1;
5436
+ faceResults = [];
5437
+ coverCanvas = null;
5438
+ coverCell = null;
5439
+ coverOn = false;
5440
+ faceMisses = 0;
5441
+ coverHidden = false;
5442
+ srcW = 0;
5443
+ srcH = 0;
5444
+ coverLast = null;
5445
+ coverShown = null;
5446
+ coverImg = null;
5447
+ faceAsked = /* @__PURE__ */ new Set();
5448
+ faceCrops = /* @__PURE__ */ new Map();
5449
+ followBox = null;
5450
+ followTs = -Infinity;
5451
+ followCrop = null;
5452
+ followCanvas = null;
5453
+ followRetry = null;
5454
+ faceSeen = false;
5455
+ followFloats = 0;
5456
+ followAll = false;
5457
+ followTurn = 0;
5458
+ followMiss = 0;
5459
+ followGrow = 0;
5460
+ boxFloats = 0;
5461
+ scanFrom = 0;
5462
+ scanTurn = 0;
5463
+ probes = /* @__PURE__ */ new Set();
5464
+ maskResults = [];
5175
5465
  maskUsedTs = -1;
5176
5466
  lastHeld = null;
5177
5467
  swallowed = false;
@@ -5181,13 +5471,23 @@
5181
5471
  personLoading = null;
5182
5472
  personMaskTex = null;
5183
5473
  personMaskFresh = false;
5184
- personMaskTs = 0;
5474
+ personMaskTs = -1;
5185
5475
  personWorkerMs = 0;
5476
+ personBytes = null;
5477
+ classBytes = null;
5478
+ mergedBytes = null;
5479
+ mergedTex = null;
5480
+ mergedFresh = false;
5481
+ mergedTs = 0;
5186
5482
  detectCanvas = null;
5187
5483
  detectCanvasTs = -1;
5484
+ thumbCanvas = null;
5485
+ thumbs = /* @__PURE__ */ new Map();
5188
5486
  // A kind whose worker failed once stays in-thread.
5189
5487
  inThread = /* @__PURE__ */ new Set();
5190
5488
  faceLoading = null;
5489
+ faceCount = 1;
5490
+ caughtUpTs = -Infinity;
5191
5491
  maxFaces = 3;
5192
5492
  lmBuf = null;
5193
5493
  filter = { kind: "none" };
@@ -5203,19 +5503,20 @@
5203
5503
  this.core = core;
5204
5504
  }
5205
5505
  /** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */
5206
- static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3) {
5506
+ static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3, guard = {}) {
5207
5507
  const canvas = document.createElement("canvas");
5208
5508
  canvas.width = width;
5209
5509
  canvas.height = height;
5210
- return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces);
5510
+ return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces, guard);
5211
5511
  }
5212
5512
  /**
5213
5513
  * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
5214
5514
  * only a `cutout` background writes; it is fixed for the life of the context, so a host that
5215
5515
  * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
5216
- * landmarker looks for: below 3 it skips re-running its face detector on every call.
5516
+ * landmarker looks for: below 3 it skips re-running its face detector on every call. Throws
5517
+ * GpuLostError when the context is lost building the shaders, or this GPU is remembered for it.
5217
5518
  */
5218
- static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3) {
5519
+ static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3, guard = {}) {
5219
5520
  const width = canvas.width;
5220
5521
  const height = canvas.height;
5221
5522
  const gl = canvas.getContext("webgl2", {
@@ -5225,14 +5526,26 @@
5225
5526
  depth: false,
5226
5527
  stencil: false
5227
5528
  });
5228
- if (!gl) throw new Error("mediakit: no WebGL2 in this browser");
5529
+ if (!gl) throw new Error("mediakit: no WebGL2 in this browser (none available, blocked, or the GPU process was reset)");
5530
+ const gpu = rendererOf(gl);
5531
+ const known = gpuRecord(gpu);
5532
+ if (known?.init) {
5533
+ gl.getExtension("WEBGL_lose_context")?.loseContext();
5534
+ throw new GpuLostError("init", gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`);
5535
+ }
5229
5536
  let core;
5230
5537
  let engine2;
5231
5538
  try {
5232
5539
  core = await loadCore();
5233
5540
  const err = core.init(gl, width, height);
5234
- if (err) throw new Error(`mediakit: ${err}`);
5541
+ if (err && gl.isContextLost()) {
5542
+ recordLoss(gpu, "init");
5543
+ throw new GpuLostError("init", gpu, err);
5544
+ }
5545
+ if (err) throw new Error(`mediakit: ${err} [GPU: ${gpuName(gl)}]`);
5235
5546
  engine2 = new _Engine(canvas, gl, core);
5547
+ engine2.gpu = gpu;
5548
+ if (guard.noFaceColor || known?.faceColor) core.disableFaceColor?.(FACE_COLOR_SKIPPED);
5236
5549
  engine2.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3));
5237
5550
  await engine2.setRecipe(filter, effects, background);
5238
5551
  return engine2;
@@ -5248,9 +5561,29 @@
5248
5561
  throw err;
5249
5562
  }
5250
5563
  }
5564
+ /** The GPU the context reported at creation, "" when the browser hides it. */
5565
+ get gpuName() {
5566
+ return this.gpu;
5567
+ }
5251
5568
  get loading() {
5252
5569
  return this.segmenterLoading !== null || this.classLoading !== null || this.faceLoading !== null;
5253
5570
  }
5571
+ /** The browser took the WebGL context away (GPU process reset or reclaimed); this Engine is done. */
5572
+ get lost() {
5573
+ return this.gl.isContextLost();
5574
+ }
5575
+ /**
5576
+ * When the context was lost: "link" within 3 s of a face colour shader starting or still linking, else "run";
5577
+ * null while it is not. The first read decides, and on the main thread it is remembered per GPU.
5578
+ */
5579
+ get lostDuring() {
5580
+ if (this.closed || !this.gl.isContextLost()) return null;
5581
+ if (!this.lostPhase) {
5582
+ this.lostPhase = performance.now() - this.linkSeenAt < LINK_LOSS_WINDOW_MS ? "link" : "run";
5583
+ recordLoss(this.gpu, this.lostPhase);
5584
+ }
5585
+ return this.lostPhase;
5586
+ }
5254
5587
  get outputCanvas() {
5255
5588
  return this.canvas;
5256
5589
  }
@@ -5337,13 +5670,29 @@
5337
5670
  this.makeupPath = makeupTexture;
5338
5671
  }
5339
5672
  this.core.setRecipe(coreRecipe(filter, effects));
5340
- if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
5673
+ this.noteLinking();
5674
+ if (needsSegmentation(filter, effects) && !this.remoteMaskComing(filter, effects)) void this.ensureSegmenter();
5341
5675
  if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
5342
5676
  if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
5343
5677
  if (needsFace(effects)) void this.ensureFace();
5344
5678
  }
5679
+ noteLinking() {
5680
+ const links = this.core.links?.() ?? 0;
5681
+ if (links !== this.links || (this.core.linking?.() ?? 0) > 0) this.linkSeenAt = performance.now();
5682
+ this.links = links;
5683
+ }
5684
+ /** A worker, or the multiclass model, will bring the mask: no in-thread person model for it. */
5685
+ remoteMaskComing(filter, effects) {
5686
+ if (needsSkinClasses(filter, effects) && !this.classFailed) return true;
5687
+ return this.personRemoteWanted(filter, effects) && !this.inThread.has("person");
5688
+ }
5689
+ gaveUp(what, e2) {
5690
+ if (!(e2 instanceof LoadTimeout)) return;
5691
+ this.loadErr ||= `${e2.message}; ${what} stay off`;
5692
+ console.warn(this.loadErr);
5693
+ }
5345
5694
  ensureFace() {
5346
- if (this.face || this.faceRemote || this.closed) return Promise.resolve();
5695
+ if (this.face || this.faceRemote || this.failed.has("face") || this.closed) return Promise.resolve();
5347
5696
  if (this.faceLoading) return this.faceLoading;
5348
5697
  const buf = this.core.faceBuffer();
5349
5698
  if (!buf) return Promise.resolve();
@@ -5351,9 +5700,11 @@
5351
5700
  this.faceLoading = this.remote("face", (d2) => d2.initFace(n2)).then(() => {
5352
5701
  this.faceRemote = true;
5353
5702
  this.lmBuf = buf;
5703
+ this.faceCount = n2;
5354
5704
  }).catch((e2) => {
5705
+ if (e2 instanceof LoadTimeout) throw e2;
5355
5706
  if (!this.inThread.has("face")) console.warn("mediakit: no detect worker for faces, detecting in this thread", e2);
5356
- return createFaceDetector(this.canvas, n2).then((f2) => {
5707
+ return withTimeout(createFaceDetector(this.canvas, n2), LOAD_MS, "face detection", (f2) => f2.close()).then((f2) => {
5357
5708
  if (this.closed) {
5358
5709
  f2.close();
5359
5710
  return;
@@ -5362,7 +5713,9 @@
5362
5713
  this.lmBuf = buf;
5363
5714
  });
5364
5715
  }).catch((e2) => {
5365
- console.error("mediakit: face detector failed to load", e2);
5716
+ this.failed.add("face");
5717
+ this.gaveUp("face effects", e2);
5718
+ if (!(e2 instanceof LoadTimeout)) console.error("mediakit: face detector failed to load", e2);
5366
5719
  }).finally(() => {
5367
5720
  this.faceLoading = null;
5368
5721
  });
@@ -5370,13 +5723,16 @@
5370
5723
  }
5371
5724
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
5372
5725
  personRemoteWanted(filter, effects) {
5373
- return filter.kind === "none" && needsSegmentation(filter, effects) && !needsSkinClasses(filter, effects);
5726
+ return filter.kind === "none" && needsSegmentation(filter, effects);
5374
5727
  }
5375
5728
  ensurePersonRemote() {
5376
- if (this.personRemote || this.closed) return Promise.resolve();
5729
+ if (this.personRemote || this.failed.has("person") || this.closed) return Promise.resolve();
5377
5730
  this.personLoading ??= this.remote("person", (d2) => d2.initMask("person")).then(() => {
5378
5731
  this.personRemote = true;
5379
- }).catch(() => {
5732
+ }).catch((e2) => {
5733
+ if (!(e2 instanceof LoadTimeout)) return;
5734
+ this.failed.add("person");
5735
+ this.gaveUp("background effects", e2);
5380
5736
  }).finally(() => {
5381
5737
  this.personLoading = null;
5382
5738
  });
@@ -5384,6 +5740,7 @@
5384
5740
  }
5385
5741
  async remote(kind, init) {
5386
5742
  if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
5743
+ this.inThread.add(kind);
5387
5744
  throw new Error("in-thread");
5388
5745
  }
5389
5746
  let detect = this.detects.get(kind);
@@ -5394,21 +5751,27 @@
5394
5751
  try {
5395
5752
  await init(detect);
5396
5753
  } catch (e2) {
5397
- this.inThread.add(kind);
5754
+ if (e2 instanceof LoadTimeout) {
5755
+ detect.close();
5756
+ this.detects.delete(kind);
5757
+ } else this.inThread.add(kind);
5398
5758
  throw e2;
5399
5759
  }
5400
5760
  if (this.closed) throw new Error("closed");
5401
5761
  }
5402
5762
  detectHandlers(key) {
5403
5763
  return {
5404
- face: (tsUs, n2, lm, ms2) => {
5405
- if (this.closed || !this.lmBuf) return;
5406
- this.lmBuf.set(lm);
5407
- const [lo2, hi2] = splitMicros(tsUs);
5408
- this.core.setFace(lo2, hi2, n2);
5764
+ face: (tsUs, found, lm, ms2, foundCover, foundRects) => {
5765
+ if (this.closed || !this.lmBuf || tsUs > this.prevTs) return;
5409
5766
  this.faceWorkerMs = ms2;
5410
- this.faceTs = tsUs;
5411
- const took = this.took("face", tsUs);
5767
+ this.uncrop(tsUs, found, lm, foundRects);
5768
+ const { n: n2, cover, rects } = this.dedupe(found, lm, foundCover, foundRects);
5769
+ this.follow(tsUs, n2, lm, this.probes.delete(tsUs));
5770
+ if (this.syncing()) {
5771
+ this.faceResults.push({ ts: tsUs, n: n2, lm: lm.slice(), cover, rects });
5772
+ if (this.faceResults.length > FACE_RESULTS_KEPT) this.faceResults.shift();
5773
+ } else this.applyFace(tsUs, n2, lm, cover, rects);
5774
+ const took = this.took(key === "faceExtra" ? "faceExtra" : "face", tsUs);
5412
5775
  if (took !== null) this.faceLatencyMs = this.faceLatencyMs ? this.faceLatencyMs + (took - this.faceLatencyMs) * 0.2 : took;
5413
5776
  },
5414
5777
  mask: (tsUs, width, height, data, ms2) => {
@@ -5418,24 +5781,30 @@
5418
5781
  const was = this.maskLatencyMs.get(key);
5419
5782
  this.maskLatencyMs.set(key, was ? was + (took - was) * 0.2 : took);
5420
5783
  }
5421
- if (key === "person") {
5422
- this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, width, height, data);
5423
- this.personMaskFresh = true;
5424
- this.personMaskTs = tsUs;
5425
- this.personWorkerMs = ms2;
5784
+ const r2 = { person: key === "person", ts: tsUs, width, height, data, ms: ms2 };
5785
+ if (!this.syncing()) {
5786
+ this.applyMask(r2);
5426
5787
  return;
5427
5788
  }
5428
- this.uploadClassMask(width, height, data);
5429
- this.classMaskTs = tsUs;
5430
- this.maskWorkerMs = ms2;
5789
+ this.maskResults.push(r2);
5790
+ if (this.maskResults.length > MASK_RESULTS_KEPT) this.maskResults.shift();
5431
5791
  },
5432
5792
  failed: (k2, reason) => {
5793
+ if (key === "faceExtra") {
5794
+ this.faceExtraUp = false;
5795
+ this.detects.get(key)?.close();
5796
+ this.detects.delete(key);
5797
+ return;
5798
+ }
5433
5799
  console.warn(`mediakit: ${key} detection moves into this thread:`, reason);
5434
5800
  this.inThread.add(key);
5435
5801
  if (key === "person") {
5436
5802
  this.personRemote = false;
5437
5803
  } else if (k2 === "face") {
5438
5804
  this.faceRemote = false;
5805
+ if (this.coverOn) this.core.setFaceCover(null);
5806
+ this.coverOn = false;
5807
+ this.coverShown = null;
5439
5808
  void this.ensureFace();
5440
5809
  } else {
5441
5810
  this.classRemote = false;
@@ -5444,6 +5813,24 @@
5444
5813
  }
5445
5814
  };
5446
5815
  }
5816
+ noteThumb(timestampUs) {
5817
+ if (this.thumbs.has(timestampUs) || !this.detectCanvas || this.detectCanvasTs !== timestampUs) return;
5818
+ this.thumbCanvas ??= new OffscreenCanvas(THUMB_W, THUMB_H);
5819
+ const ctx = this.thumbCanvas.getContext("2d", { willReadFrequently: true });
5820
+ ctx.drawImage(this.detectCanvas, 0, 0, THUMB_W, THUMB_H);
5821
+ this.thumbs.set(timestampUs, lumaThumb(ctx.getImageData(0, 0, THUMB_W, THUMB_H).data));
5822
+ if (this.thumbs.size > THUMBS_KEPT) this.thumbs.delete(this.thumbs.keys().next().value);
5823
+ }
5824
+ merge(tsUs) {
5825
+ if (!this.personBytes || !this.classBytes || !needsSkinClasses(this.filter, this.effects)) return;
5826
+ const then = this.thumbs.get(this.classMaskTs);
5827
+ const now = this.thumbs.get(this.personMaskTs);
5828
+ const moved = then && now && this.classMaskTs !== this.personMaskTs ? movedBetween(then, now) : null;
5829
+ this.mergedBytes = mergeMasks(this.personBytes, this.classBytes, this.mergedBytes, moved);
5830
+ this.mergedTex = this.uploadMaskBytes(this.mergedTex, this.personBytes.width, this.personBytes.height, this.mergedBytes);
5831
+ this.mergedFresh = true;
5832
+ this.mergedTs = tsUs;
5833
+ }
5447
5834
  uploadClassMask(width, height, data) {
5448
5835
  this.classMaskTex = this.uploadMaskBytes(this.classMaskTex, width, height, data);
5449
5836
  this.classMaskFresh = true;
@@ -5470,24 +5857,187 @@
5470
5857
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
5471
5858
  * detection drains Chrome's few capture buffers and throttles the camera itself.
5472
5859
  */
5473
- requestRemote(kind, source, timestampUs) {
5860
+ requestRemote(want, source, timestampUs) {
5861
+ const lockstep = want === "face" && this.syncing();
5862
+ const kind = lockstep ? this.freeFaceWorker() : want;
5863
+ if (!kind) return;
5474
5864
  const detect = this.detects.get(kind);
5475
- if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
5476
- if (!this.dutyAllows(kind)) return;
5865
+ if (!detect?.accepts(kind === "face" || kind === "faceExtra" ? "face" : "mask")) return;
5866
+ if (!lockstep && !this.dutyAllows(kind)) return;
5477
5867
  let frame = null;
5868
+ let followed = null;
5869
+ let scanned = null;
5478
5870
  try {
5479
5871
  const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
5480
- frame = new VideoFrame(copyable ? this.detectCopy(source, timestampUs) : source, {
5872
+ if (copyable) {
5873
+ this.srcW = source instanceof VideoFrame ? source.displayWidth : source.width;
5874
+ this.srcH = source instanceof VideoFrame ? source.displayHeight : source.height;
5875
+ }
5876
+ if (copyable && (kind === "face" || kind === "faceExtra")) {
5877
+ followed = this.followCopy(source, timestampUs);
5878
+ if (!followed) scanned = this.scanCopy(source, timestampUs);
5879
+ }
5880
+ frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(source, timestampUs) : source), {
5481
5881
  timestamp: timestampUs
5482
5882
  });
5483
5883
  } catch {
5484
5884
  }
5485
- if (frame && detect.request(kind === "face" ? "face" : "mask", frame, timestampUs)) {
5885
+ if (frame && detect.request(kind === "face" || kind === "faceExtra" ? "face" : "mask", frame, timestampUs, this.effects.occluders ?? false, followed ? this.followRetry : null)) {
5486
5886
  const now = performance.now();
5487
5887
  this.sent.set(kind, { ts: timestampUs, at: now });
5488
5888
  this.lastSentAt.set(kind, now);
5889
+ if (lockstep) this.faceAsked.add(timestampUs);
5890
+ if (kind !== "face" && kind !== "faceExtra" && this.remoteMaskKind() === "merged") this.noteThumb(timestampUs);
5891
+ } else if (followed || scanned) this.faceCrops.delete(timestampUs);
5892
+ }
5893
+ followCopy(source, timestampUs) {
5894
+ const box = this.followBox;
5895
+ if (!box || timestampUs - this.followTs > FOLLOW_STALE_US) return null;
5896
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
5897
+ const sh2 = source instanceof VideoFrame ? source.displayHeight : source.height;
5898
+ const want = Math.max(FOLLOW_MIN_SIDE, FOLLOW_MARGIN * (1 + this.followMiss) * Math.max(box[2] * sw, box[3] * sh2));
5899
+ if (want > Math.min(sw, sh2) && this.followFloats > FACE_FLOATS) return null;
5900
+ if (!this.followAll && this.followTurn++ % FOLLOW_REFRESH === FOLLOW_REFRESH - 1) {
5901
+ this.probes.add(timestampUs);
5902
+ return null;
5903
+ }
5904
+ let side = Math.round(Math.min(sw, sh2, want));
5905
+ let x2 = Math.round(Math.min(sw - side, Math.max(0, (box[0] + box[2] / 2) * sw - side / 2)));
5906
+ let y2 = Math.round(Math.min(sh2 - side, Math.max(0, (box[1] + box[3] / 2) * sh2 - side / 2)));
5907
+ const kept = this.followCrop;
5908
+ if (kept && kept[0] + kept[2] <= sw && kept[1] + kept[2] <= sh2 && Math.abs(kept[2] - side) < FOLLOW_RESIZE * side && Math.abs(kept[0] - x2) < FOLLOW_SHIFT * side && Math.abs(kept[1] - y2) < FOLLOW_SHIFT * side) {
5909
+ ;
5910
+ [x2, y2, side] = kept;
5911
+ } else this.followCrop = [x2, y2, side];
5912
+ this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
5913
+ this.followCanvas.getContext("2d").drawImage(source, x2, y2, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
5914
+ const tight = Math.min(side, Math.max(FOLLOW_MIN_SIDE, FOLLOW_RETRY * Math.max(box[2] * sw, box[3] * sh2)));
5915
+ this.followRetry = [((box[0] + box[2] / 2) * sw - x2) / side, ((box[1] + box[3] / 2) * sh2 - y2) / side, tight / side];
5916
+ this.faceCrops.set(timestampUs, [x2 / sw, y2 / sh2, side / sw, side / sh2]);
5917
+ return this.followCanvas;
5918
+ }
5919
+ scanCopy(source, timestampUs) {
5920
+ if (this.faceSeen) return null;
5921
+ const turn = this.scanTurn++;
5922
+ if (turn % 2 === 0) return null;
5923
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
5924
+ const sh2 = source instanceof VideoFrame ? source.displayHeight : source.height;
5925
+ const { side, step, nx, ny } = tileGrid(sw, sh2);
5926
+ const at2 = (this.scanFrom + (turn >> 1)) % (nx * ny);
5927
+ const x2 = Math.max(0, Math.min(sw - side, Math.round(at2 % nx * step)));
5928
+ const y2 = Math.max(0, Math.min(sh2 - side, Math.round(Math.floor(at2 / nx) * step)));
5929
+ this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
5930
+ this.followCanvas.getContext("2d").drawImage(source, x2, y2, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
5931
+ this.faceCrops.set(timestampUs, [x2 / sw, y2 / sh2, side / sw, side / sh2]);
5932
+ this.probes.add(timestampUs);
5933
+ return this.followCanvas;
5934
+ }
5935
+ scanTile(cx, cy) {
5936
+ const sw = this.srcW || this.canvas.width;
5937
+ const sh2 = this.srcH || this.canvas.height;
5938
+ const { side, step, nx, ny } = tileGrid(sw, sh2);
5939
+ const ix = Math.min(nx - 1, Math.max(0, Math.round((cx * sw - side / 2) / step)));
5940
+ const iy = Math.min(ny - 1, Math.max(0, Math.round((cy * sh2 - side / 2) / step)));
5941
+ return iy * nx + ix;
5942
+ }
5943
+ uncrop(tsUs, n2, lm, rects) {
5944
+ const crop = this.faceCrops.get(tsUs);
5945
+ for (const ts2 of this.faceCrops.keys()) if (ts2 === tsUs || ts2 < tsUs - FOLLOW_KEPT_US) this.faceCrops.delete(ts2);
5946
+ if (!crop) return;
5947
+ for (let i2 = 0; i2 < n2; i2 += 3) {
5948
+ lm[i2] = crop[0] + lm[i2] * crop[2];
5949
+ lm[i2 + 1] = crop[1] + lm[i2 + 1] * crop[3];
5950
+ lm[i2 + 2] = lm[i2 + 2] * crop[2];
5951
+ }
5952
+ for (let i2 = 0; rects && i2 < rects.length; i2 += 3) {
5953
+ rects[i2] = crop[0] + rects[i2] * crop[2];
5954
+ rects[i2 + 1] = crop[1] + rects[i2 + 1] * crop[3];
5955
+ rects[i2 + 2] = rects[i2 + 2] * crop[2];
5489
5956
  }
5490
5957
  }
5958
+ dedupe(n2, lm, cover, rects) {
5959
+ const faces = n2 / FACE_FLOATS;
5960
+ if (faces < 2) return { n: n2, cover, rects };
5961
+ const boxes = Array.from({ length: faces }, (_2, f2) => faceBox(lm, f2 * FACE_FLOATS));
5962
+ const ref = this.followBox;
5963
+ const score = (b2) => (ref ? overlap(b2, ref) : 0) + b2[2] * b2[3] * 1e-3;
5964
+ const keep = boxes.map(() => true);
5965
+ for (let a2 = 0; a2 < faces; a2++) {
5966
+ for (let b2 = a2 + 1; b2 < faces; b2++) {
5967
+ if (!keep[a2] || !keep[b2] || overlap(boxes[a2], boxes[b2]) <= SAME_FACE) continue;
5968
+ keep[score(boxes[a2]) >= score(boxes[b2]) ? b2 : a2] = false;
5969
+ }
5970
+ }
5971
+ if (keep.every(Boolean)) return { n: n2, cover, rects };
5972
+ const cells = COVER_SIZE * COVER_SIZE;
5973
+ const outCover = cover ? new Uint8Array(cover.length) : null;
5974
+ const outRects = rects ? new Float32Array(rects.length) : null;
5975
+ let k2 = 0;
5976
+ for (let f2 = 0; f2 < faces; f2++) {
5977
+ if (!keep[f2]) continue;
5978
+ if (k2 !== f2) lm.copyWithin(k2 * FACE_FLOATS, f2 * FACE_FLOATS, (f2 + 1) * FACE_FLOATS);
5979
+ if (cover && outCover) outCover.set(cover.subarray(f2 * cells, (f2 + 1) * cells), k2 * cells);
5980
+ if (rects && outRects) outRects.set(rects.subarray(f2 * 3, f2 * 3 + 3), k2 * 3);
5981
+ k2++;
5982
+ }
5983
+ return { n: k2 * FACE_FLOATS, cover: outCover ? outCover.slice(0, k2 * cells) : null, rects: outRects ? outRects.slice(0, k2 * 3) : null };
5984
+ }
5985
+ follow(tsUs, n2, lm, probe) {
5986
+ for (const ts2 of this.probes) if (ts2 < tsUs - FOLLOW_KEPT_US) this.probes.delete(ts2);
5987
+ if (tsUs <= this.followTs || probe && (n2 === 0 || n2 < this.followFloats)) return;
5988
+ this.followTs = tsUs;
5989
+ this.faceSeen = n2 > 0;
5990
+ if (n2 === 0) {
5991
+ this.followGrow = 0;
5992
+ this.followFloats = 0;
5993
+ this.followAll = false;
5994
+ const box = this.followBox;
5995
+ if (box && this.followMiss < FOLLOW_WIDEN) {
5996
+ this.followMiss++;
5997
+ return;
5998
+ }
5999
+ this.followMiss = 0;
6000
+ if (box) this.scanFrom = this.scanTile(box[0] + box[2] / 2, box[1] + box[3] / 2);
6001
+ this.scanTurn = 1;
6002
+ this.followBox = null;
6003
+ this.followCrop = null;
6004
+ this.boxFloats = 0;
6005
+ return;
6006
+ }
6007
+ this.followMiss = 0;
6008
+ const old = this.followBox;
6009
+ const grow = old !== null && this.boxFloats > 0 && n2 > this.boxFloats && !probe;
6010
+ this.followGrow = grow ? this.followGrow + 1 : 0;
6011
+ const take = grow && this.followGrow < FOLLOW_GROW ? this.boxFloats : n2;
6012
+ const boxes = [];
6013
+ for (let f2 = 0; f2 < n2; f2 += FACE_FLOATS) boxes.push(faceBox(lm, f2));
6014
+ if (take < n2 && old) boxes.sort((a2, b2) => overlap(b2, old) - overlap(a2, old));
6015
+ const kept = boxes.slice(0, take / FACE_FLOATS);
6016
+ const x0 = Math.min(...kept.map((b2) => b2[0]));
6017
+ const y0 = Math.min(...kept.map((b2) => b2[1]));
6018
+ const x1 = Math.max(...kept.map((b2) => b2[0] + b2[2]));
6019
+ const y1 = Math.max(...kept.map((b2) => b2[1] + b2[3]));
6020
+ this.followBox = [x0, y0, x1 - x0, y1 - y0];
6021
+ this.boxFloats = take;
6022
+ this.followFloats = take;
6023
+ this.followAll = take >= this.faceCount * FACE_FLOATS;
6024
+ }
6025
+ freeFaceWorker() {
6026
+ if (this.detects.get("face")?.accepts("face")) return "face";
6027
+ if (this.faceExtraUp && this.detects.get("faceExtra")?.accepts("face")) return "faceExtra";
6028
+ return null;
6029
+ }
6030
+ ensureFaceExtra() {
6031
+ if (this.faceExtraTried || this.closed) return;
6032
+ this.faceExtraTried = true;
6033
+ const n2 = this.faceCount;
6034
+ this.remote("faceExtra", (d2) => d2.initFace(n2)).then(() => {
6035
+ this.faceExtraUp = true;
6036
+ }).catch(() => {
6037
+ this.detects.get("faceExtra")?.close();
6038
+ this.detects.delete("faceExtra");
6039
+ });
6040
+ }
5491
6041
  /** Face and mask asked on the same frame share one draw. */
5492
6042
  detectCopy(source, timestampUs) {
5493
6043
  const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
@@ -5506,36 +6056,42 @@
5506
6056
  return this.detectCanvas;
5507
6057
  }
5508
6058
  ensureClassSegmenter() {
5509
- if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
6059
+ if (this.classSegmenter || this.classRemote || this.classFailed || this.closed) return Promise.resolve();
5510
6060
  if (this.classLoading) return this.classLoading;
5511
6061
  this.classLoading = this.remote("mask", (d2) => d2.initMask("classes")).then(() => {
5512
6062
  this.classRemote = true;
5513
- }).catch(
5514
- () => createSegmenter(this.canvas, "classes").then((s2) => {
6063
+ }).catch((e2) => {
6064
+ if (e2 instanceof LoadTimeout) throw e2;
6065
+ return withTimeout(createSegmenter(this.canvas, "classes"), LOAD_MS, "skin segmentation", (s2) => s2.close()).then((s2) => {
5515
6066
  if (this.closed) {
5516
6067
  s2.close();
5517
6068
  return;
5518
6069
  }
5519
6070
  this.classSegmenter = s2;
5520
- })
5521
- ).catch((e2) => {
5522
- console.error("mediakit: multiclass segmenter failed to load", e2);
6071
+ });
6072
+ }).catch((e2) => {
6073
+ this.classFailed = true;
6074
+ if (!(e2 instanceof LoadTimeout)) console.error("mediakit: multiclass segmenter failed to load", e2);
6075
+ else console.warn(`${e2.message}; the person model stands in`);
6076
+ if (needsSegmentation(this.filter, this.effects)) void this.ensureSegmenter();
5523
6077
  }).finally(() => {
5524
6078
  this.classLoading = null;
5525
6079
  });
5526
6080
  return this.classLoading;
5527
6081
  }
5528
6082
  ensureSegmenter() {
5529
- if (this.segmenter || this.closed) return Promise.resolve();
6083
+ if (this.segmenter || this.failed.has("segmenter") || this.closed) return Promise.resolve();
5530
6084
  if (this.segmenterLoading) return this.segmenterLoading;
5531
- this.segmenterLoading = createSegmenter(this.canvas).then((s2) => {
6085
+ this.segmenterLoading = withTimeout(createSegmenter(this.canvas), LOAD_MS, "person segmentation", (s2) => s2.close()).then((s2) => {
5532
6086
  if (this.closed) {
5533
6087
  s2.close();
5534
6088
  return;
5535
6089
  }
5536
6090
  this.segmenter = s2;
5537
6091
  }).catch((e2) => {
5538
- console.error("mediakit: segmenter failed to load", e2);
6092
+ this.failed.add("segmenter");
6093
+ this.gaveUp("background and skin effects", e2);
6094
+ if (!(e2 instanceof LoadTimeout)) console.error("mediakit: segmenter failed to load", e2);
5539
6095
  }).finally(() => {
5540
6096
  this.segmenterLoading = null;
5541
6097
  });
@@ -5554,52 +6110,106 @@
5554
6110
  * it constructs one only to destroy it again.
5555
6111
  */
5556
6112
  render(source, timestampUs) {
5557
- if (this.closed) return false;
6113
+ if (this.closed || this.lostDuring) return false;
5558
6114
  if (this.lastHeld) this.spare.push(this.lastHeld);
5559
6115
  this.lastHeld = null;
5560
6116
  this.swallowed = false;
5561
6117
  if (this.prevTs >= 0 && timestampUs > this.prevTs) {
5562
6118
  this.gapUs += (Math.min(timestampUs - this.prevTs, 2e5) - this.gapUs) * 0.1;
5563
6119
  }
6120
+ if (timestampUs < this.prevTs) {
6121
+ this.faceResults = [];
6122
+ this.maskResults = [];
6123
+ this.faceAsked.clear();
6124
+ this.faceCrops.clear();
6125
+ this.followBox = null;
6126
+ this.followCrop = null;
6127
+ this.followTs = -Infinity;
6128
+ this.faceSeen = false;
6129
+ this.followFloats = 0;
6130
+ this.followAll = false;
6131
+ this.followTurn = 0;
6132
+ this.followMiss = 0;
6133
+ this.followGrow = 0;
6134
+ this.boxFloats = 0;
6135
+ this.scanFrom = 0;
6136
+ this.scanTurn = 0;
6137
+ this.probes.clear();
6138
+ this.caughtUpTs = -Infinity;
6139
+ this.thumbs.clear();
6140
+ }
5564
6141
  this.prevTs = timestampUs;
5565
6142
  if (!this.syncing() || typeof ImageData !== "undefined" && source instanceof ImageData) {
5566
6143
  this.releaseHeld();
5567
6144
  this.renderedTs = timestampUs;
5568
6145
  return this.draw(source, timestampUs, false);
5569
6146
  }
6147
+ this.ensureFaceExtra();
5570
6148
  this.requestRemote("face", source, timestampUs);
5571
6149
  const remoteMask = this.remoteMaskKind();
5572
- if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
6150
+ if (remoteMask === "merged") {
6151
+ this.requestRemote("person", source, timestampUs);
6152
+ this.requestRemote("mask", source, timestampUs);
6153
+ } else if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
5573
6154
  this.queue.push({ c: this.hold(source), ts: timestampUs });
5574
- this.retuneDepth();
5575
- if (this.queue.length <= this.holdDepth) {
6155
+ while (this.queue.length > MAX_HOLD + 1) this.faceAsked.delete(this.spareFront());
6156
+ if (this.queue.length <= MAX_HOLD && !this.faceReady(this.queue[0].ts)) {
5576
6157
  this.swallowed = true;
5577
6158
  return false;
5578
6159
  }
5579
- while (this.queue.length > this.holdDepth + 1) this.spare.push(this.queue.shift().c);
6160
+ if (this.queue.length > 2 && this.faceReady(this.queue[1].ts) && timestampUs - this.caughtUpTs >= CATCH_UP_EVERY_US) {
6161
+ this.caughtUpTs = timestampUs;
6162
+ this.faceAsked.delete(this.spareFront());
6163
+ }
5580
6164
  const front = this.queue.shift();
6165
+ this.faceAsked.delete(front.ts);
6166
+ this.faceFor(front.ts);
6167
+ this.masksFor(front.ts);
5581
6168
  this.lastHeld = front.c;
5582
6169
  this.renderedTs = front.ts;
5583
6170
  return this.draw(front.c, front.ts, true);
5584
6171
  }
5585
6172
  remoteMaskKind() {
5586
- if (this.personRemote && this.personRemoteWanted(this.filter, this.effects)) return "person";
5587
- if (this.classRemote && needsSkinClasses(this.filter, this.effects)) return "mask";
5588
- return null;
5589
- }
5590
- retuneDepth() {
5591
- const kind = this.remoteMaskKind();
5592
- const latency = Math.max(this.faceLatencyMs, kind ? this.maskLatencyMs.get(kind) ?? 0 : 0);
5593
- const want = latency > 0 ? Math.min(MAX_HOLD, Math.max(1, Math.ceil(latency * 1e3 / this.gapUs))) : 1;
5594
- if (want === this.holdDepth) {
5595
- this.depthVotes = 0;
6173
+ const person = this.personRemote && this.personRemoteWanted(this.filter, this.effects);
6174
+ if (!needsSkinClasses(this.filter, this.effects)) return person ? "person" : null;
6175
+ if (this.classRemote) return person ? "merged" : "mask";
6176
+ return person && !this.inThread.has("mask") ? "person" : null;
6177
+ }
6178
+ spareFront() {
6179
+ const h2 = this.queue.shift();
6180
+ this.spare.push(h2.c);
6181
+ return h2.ts;
6182
+ }
6183
+ applyMask(r2) {
6184
+ if (r2.person) {
6185
+ this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, r2.width, r2.height, r2.data);
6186
+ this.personMaskFresh = true;
6187
+ this.personMaskTs = r2.ts;
6188
+ this.personWorkerMs = r2.ms;
6189
+ this.personBytes = { width: r2.width, height: r2.height, data: r2.data };
6190
+ this.merge(r2.ts);
5596
6191
  return;
5597
6192
  }
5598
- if (++this.depthVotes >= DEPTH_VOTES) {
5599
- this.holdDepth = want;
5600
- this.depthVotes = 0;
6193
+ this.uploadClassMask(r2.width, r2.height, r2.data);
6194
+ this.classMaskTs = r2.ts;
6195
+ this.maskWorkerMs = r2.ms;
6196
+ this.classBytes = { width: r2.width, height: r2.height, data: r2.data };
6197
+ this.merge(this.personMaskTs);
6198
+ }
6199
+ masksFor(tsUs) {
6200
+ for (const person of [false, true]) {
6201
+ let pick = null;
6202
+ for (const r2 of this.maskResults) if (r2.person === person && (!pick || Math.abs(r2.ts - tsUs) < Math.abs(pick.ts - tsUs))) pick = r2;
6203
+ if (!pick) continue;
6204
+ const chosen = pick;
6205
+ this.maskResults = this.maskResults.filter((r2) => r2.person !== person || r2.ts >= chosen.ts);
6206
+ if (chosen.ts !== (person ? this.personMaskTs : this.classMaskTs)) this.applyMask(chosen);
5601
6207
  }
5602
6208
  }
6209
+ faceReady(tsUs) {
6210
+ const asked = this.faceAsked.has(tsUs);
6211
+ return this.faceResults.some((r2) => asked ? r2.ts === tsUs : r2.ts > tsUs);
6212
+ }
5603
6213
  dutyAllows(kind) {
5604
6214
  const took = kind === "face" ? this.faceLatencyMs : this.maskLatencyMs.get(kind) ?? 0;
5605
6215
  if (took * 1e3 < this.gapUs) return true;
@@ -5612,6 +6222,89 @@
5612
6222
  this.sent.delete(kind);
5613
6223
  return performance.now() - s2.at;
5614
6224
  }
6225
+ applyFace(tsUs, n2, lm, cover, rects) {
6226
+ this.faceMisses = n2 === 0 ? this.faceMisses + 1 : 0;
6227
+ if (n2 > 0) this.showCover(cover, rects);
6228
+ else if (this.faceMisses >= COVER_MISSES) this.hideCover();
6229
+ this.lmBuf.set(lm);
6230
+ const [lo2, hi2] = splitMicros(tsUs);
6231
+ this.core.setFace(lo2, hi2, n2);
6232
+ this.faceTs = tsUs;
6233
+ }
6234
+ faceFor(tsUs) {
6235
+ this.faceResults.sort((a3, b2) => a3.ts - b2.ts);
6236
+ let pick = -1;
6237
+ for (let i2 = 0; i2 < this.faceResults.length; i2++) if (this.faceResults[i2].ts <= tsUs) pick = i2;
6238
+ if (pick < 0) return;
6239
+ const r2 = this.faceResults[pick];
6240
+ const next = this.faceResults[pick + 1];
6241
+ this.faceResults.splice(0, pick);
6242
+ if (r2.ts === tsUs || !next || !this.sameFaces(r2, next)) {
6243
+ if (r2.ts !== this.faceTs) this.applyFace(r2.ts, r2.n, r2.lm, r2.cover, r2.rects);
6244
+ return;
6245
+ }
6246
+ const a2 = (tsUs - r2.ts) / (next.ts - r2.ts);
6247
+ if (!this.lerpBuf || this.lerpBuf.length !== r2.lm.length) this.lerpBuf = new Float32Array(r2.lm.length);
6248
+ for (let i2 = 0; i2 < r2.n; i2++) this.lerpBuf[i2] = r2.lm[i2] + (next.lm[i2] - r2.lm[i2]) * a2;
6249
+ const near = a2 < 0.5 ? r2 : next;
6250
+ this.applyFace(tsUs, r2.n, this.lerpBuf, near.cover, near.rects);
6251
+ }
6252
+ hideCover() {
6253
+ if (!this.coverOn || !this.coverCanvas || this.coverHidden) return;
6254
+ const ctx = this.coverCanvas.getContext("2d");
6255
+ ctx.fillStyle = "#000";
6256
+ ctx.fillRect(0, 0, this.coverCanvas.width, this.coverCanvas.height);
6257
+ this.core.setFaceCover(this.coverCanvas);
6258
+ this.coverShown = null;
6259
+ this.coverHidden = true;
6260
+ }
6261
+ showCover(cover, rects) {
6262
+ this.coverHidden = false;
6263
+ if (!cover || !rects || !(this.effects.occluders ?? false)) {
6264
+ if (this.coverOn) this.core.setFaceCover(null);
6265
+ this.coverOn = false;
6266
+ this.coverShown = null;
6267
+ return;
6268
+ }
6269
+ if (cover === this.coverShown && this.coverOn) return;
6270
+ const w2 = COVER_FRAME_W;
6271
+ const h2 = Math.max(1, Math.round(w2 * (this.srcH || this.canvas.height) / (this.srcW || this.canvas.width)));
6272
+ if (!this.coverCanvas || this.coverCanvas.height !== h2) this.coverCanvas = new OffscreenCanvas(w2, h2);
6273
+ this.coverCell ??= new OffscreenCanvas(COVER_SIZE, COVER_SIZE);
6274
+ const ctx = this.coverCanvas.getContext("2d");
6275
+ const cell = this.coverCell.getContext("2d");
6276
+ ctx.fillStyle = "#fff";
6277
+ ctx.fillRect(0, 0, w2, h2);
6278
+ this.coverImg ??= cell.createImageData(COVER_SIZE, COVER_SIZE);
6279
+ const img = this.coverImg;
6280
+ const cells = COVER_SIZE * COVER_SIZE;
6281
+ const held = this.coverLast && this.coverLast !== cover && this.coverLast.length === cover.length ? this.coverLast : null;
6282
+ for (let f2 = 0; f2 * 3 < rects.length; f2++) {
6283
+ for (let i2 = 0; i2 < cells; i2++) {
6284
+ const now = cover[f2 * cells + i2];
6285
+ const v2 = held ? Math.min(now, now * (1 - COVER_HOLD) + held[f2 * cells + i2] * COVER_HOLD) : now;
6286
+ img.data[i2 * 4] = v2;
6287
+ img.data[i2 * 4 + 1] = v2;
6288
+ img.data[i2 * 4 + 2] = v2;
6289
+ img.data[i2 * 4 + 3] = 255;
6290
+ }
6291
+ cell.putImageData(img, 0, 0);
6292
+ const side = rects[f2 * 3 + 2] * w2;
6293
+ ctx.drawImage(this.coverCell, rects[f2 * 3] * w2 - side / 2, rects[f2 * 3 + 1] * h2 - side / 2, side, side);
6294
+ }
6295
+ this.core.setFaceCover(this.coverCanvas);
6296
+ this.coverOn = true;
6297
+ this.coverLast = cover;
6298
+ this.coverShown = cover;
6299
+ }
6300
+ sameFaces(a2, b2) {
6301
+ if (a2.n === 0 || a2.n !== b2.n) return false;
6302
+ for (let k2 = 0; k2 < a2.n; k2 += FACE_FLOATS) {
6303
+ const nose = k2 + 3;
6304
+ if (Math.abs(a2.lm[nose] - b2.lm[nose]) > FACE_JUMP || Math.abs(a2.lm[nose + 1] - b2.lm[nose + 1]) > FACE_JUMP) return false;
6305
+ }
6306
+ return true;
6307
+ }
5615
6308
  releaseHeld() {
5616
6309
  for (const h2 of this.queue) this.spare.push(h2.c);
5617
6310
  this.queue = [];
@@ -5645,7 +6338,24 @@
5645
6338
  this.used = null;
5646
6339
  let served = false;
5647
6340
  const remoteMask = this.remoteMaskKind();
5648
- if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
6341
+ if (remoteMask === "merged") {
6342
+ if (!faceDone) {
6343
+ this.requestRemote("person", source, timestampUs);
6344
+ this.requestRemote("mask", source, timestampUs);
6345
+ }
6346
+ const tex = this.mergedTex ?? this.personMaskTex;
6347
+ if (tex) {
6348
+ served = true;
6349
+ if (this.mergedTex ? this.mergedFresh : this.personMaskFresh) {
6350
+ this.mergedFresh = false;
6351
+ this.personMaskFresh = false;
6352
+ mask = tex;
6353
+ maskKind = this.mergedTex ? 1 : 0;
6354
+ maskTs = this.mergedTex ? this.mergedTs : this.personMaskTs;
6355
+ segMs = this.personWorkerMs;
6356
+ }
6357
+ }
6358
+ } else if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
5649
6359
  if (remoteMask === "person") {
5650
6360
  if (this.personMaskTex) {
5651
6361
  served = true;
@@ -5673,7 +6383,7 @@
5673
6383
  const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
5674
6384
  const seg = classes ? this.classSegmenter : this.segmenter;
5675
6385
  if (!seg) {
5676
- void this.ensureSegmenter();
6386
+ if (!this.remoteMaskComing(this.filter, this.effects)) void this.ensureSegmenter();
5677
6387
  } else {
5678
6388
  const s0 = performance.now();
5679
6389
  mask = seg.segment(source, timestampUs / 1e3);
@@ -5705,6 +6415,14 @@
5705
6415
  const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
5706
6416
  if (mask) this.used?.release();
5707
6417
  this.used = null;
6418
+ this.noteLinking();
6419
+ if (!this.programErr) {
6420
+ const err = this.core.programError?.() ?? "";
6421
+ if (err) {
6422
+ this.programErr = `mediakit: ${err}; makeup and teeth stay off, the rest runs [GPU: ${gpuName(this.gl)}]`;
6423
+ console.warn(this.programErr);
6424
+ }
6425
+ }
5708
6426
  this.prevSegMs = segMs;
5709
6427
  this.prevTotalMs = performance.now() - t0;
5710
6428
  const s2 = this.core.stats();
@@ -5725,9 +6443,10 @@
5725
6443
  needsFace: s2 ? s2[10] > 0.5 : false,
5726
6444
  autoExposure: s2 ? s2[11] : 0,
5727
6445
  faces: s2 ? s2[12] : 0,
5728
- heldFrames: faceDone ? this.holdDepth : 0,
6446
+ heldFrames: faceDone ? this.queue.length : 0,
5729
6447
  faceAgeMs: s2 && s2[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
5730
- maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0
6448
+ maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0,
6449
+ effectError: this.programErr || this.loadErr
5731
6450
  };
5732
6451
  return glCalls > 0;
5733
6452
  }
@@ -5759,6 +6478,11 @@
5759
6478
  if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
5760
6479
  if (this.personMaskTex) this.gl.deleteTexture(this.personMaskTex);
5761
6480
  this.personMaskTex = null;
6481
+ if (this.mergedTex) this.gl.deleteTexture(this.mergedTex);
6482
+ this.mergedTex = null;
6483
+ this.personBytes = null;
6484
+ this.classBytes = null;
6485
+ this.mergedBytes = null;
5762
6486
  this.personRemote = false;
5763
6487
  this.classMaskTex = null;
5764
6488
  this.lmBuf = null;
@@ -5828,6 +6552,8 @@
5828
6552
  var post = (m2) => self.postMessage(m2);
5829
6553
  var engine = null;
5830
6554
  var abort = null;
6555
+ var repipe = null;
6556
+ var inTrack = null;
5831
6557
  var framesOn = false;
5832
6558
  async function start(m2) {
5833
6559
  await run(m2, m2.readable, m2.writable);
@@ -5838,21 +6564,27 @@
5838
6564
  m2.track.stop();
5839
6565
  throw new Error("mediakit: this worker has no MediaStreamTrackProcessor / VideoTrackGenerator");
5840
6566
  }
6567
+ inTrack = m2.track;
5841
6568
  const processor = new g2.MediaStreamTrackProcessor({ track: m2.track });
5842
6569
  const generator = new g2.VideoTrackGenerator();
5843
6570
  await run(m2, processor.readable, generator.writable, generator.track);
5844
6571
  }
5845
6572
  async function run(m2, readable, writable, outTrack) {
5846
6573
  const canvas = new OffscreenCanvas(m2.width, m2.height);
5847
- engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false, m2.maxFaces);
6574
+ engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false, m2.maxFaces, { noFaceColor: m2.noFaceColor });
5848
6575
  engine.syncFaces = m2.syncFaces ?? false;
5849
6576
  engine.setDebug(m2.debug ?? "off");
5850
- abort = new AbortController();
5851
6577
  let n2 = 0;
5852
6578
  let lastPost = performance.now();
5853
6579
  let lastLoading = engine.loading;
5854
- const transform = new TransformStream({
6580
+ let lostSent = false;
6581
+ const makeTransform = () => new TransformStream({
5855
6582
  transform: (frame, controller) => {
6583
+ const phase = engine?.lostDuring;
6584
+ if (phase && !lostSent) {
6585
+ lostSent = true;
6586
+ post({ t: "lost", phase, gpu: engine?.gpuName ?? "" });
6587
+ }
5856
6588
  const ts2 = frame.timestamp ?? 0;
5857
6589
  n2++;
5858
6590
  const now = performance.now();
@@ -5904,14 +6636,41 @@
5904
6636
  } else {
5905
6637
  post({ t: "ready", loading: engine.loading });
5906
6638
  }
5907
- void readable.pipeThrough(transform, { signal: abort.signal }).pipeTo(writable, { signal: abort.signal }).catch((e2) => {
5908
- if (abort?.signal.aborted) return;
5909
- post({ t: "error", message: e2 instanceof Error ? e2.message : String(e2) });
5910
- });
6639
+ let piping = Promise.resolve();
6640
+ repipe = (input) => {
6641
+ abort?.abort();
6642
+ const mine = new AbortController();
6643
+ abort = mine;
6644
+ piping = piping.then(() => {
6645
+ if (mine.signal.aborted) {
6646
+ void input.cancel();
6647
+ return;
6648
+ }
6649
+ return input.pipeThrough(makeTransform(), { signal: mine.signal }).pipeTo(writable, { signal: mine.signal, preventAbort: true, preventClose: true }).catch((e2) => {
6650
+ if (mine.signal.aborted) return;
6651
+ post({ t: "error", message: e2 instanceof Error ? e2.message : String(e2) });
6652
+ });
6653
+ });
6654
+ };
6655
+ repipe(readable);
6656
+ }
6657
+ function switchTrack(track) {
6658
+ const g2 = globalThis;
6659
+ if (!g2.MediaStreamTrackProcessor || !repipe) {
6660
+ track.stop();
6661
+ return;
6662
+ }
6663
+ const previous = inTrack;
6664
+ inTrack = track;
6665
+ repipe(new g2.MediaStreamTrackProcessor({ track }).readable);
6666
+ previous?.stop();
5911
6667
  }
5912
6668
  function stop() {
5913
6669
  abort?.abort();
5914
6670
  abort = null;
6671
+ repipe = null;
6672
+ inTrack?.stop();
6673
+ inTrack = null;
5915
6674
  engine?.close();
5916
6675
  engine = null;
5917
6676
  }
@@ -5920,10 +6679,16 @@
5920
6679
  try {
5921
6680
  if (m2.t === "start" || m2.t === "startTrack") {
5922
6681
  void (m2.t === "start" ? start(m2) : startTrack(m2)).catch((err) => {
5923
- post({ t: "error", message: err instanceof Error ? err.message : String(err) });
6682
+ if (err instanceof GpuLostError) post({ t: "lost", phase: err.phase, gpu: err.gpu, message: err.detail });
6683
+ else post({ t: "error", message: err instanceof Error ? err.message : String(err) });
5924
6684
  });
5925
6685
  } else if (m2.t === "frames") {
5926
6686
  framesOn = m2.on;
6687
+ } else if (m2.t === "source") {
6688
+ if (repipe) repipe(m2.readable);
6689
+ else void m2.readable.cancel();
6690
+ } else if (m2.t === "sourceTrack") {
6691
+ switchTrack(m2.track);
5927
6692
  } else if (m2.t === "debug") {
5928
6693
  engine?.setDebug(m2.view);
5929
6694
  } else if (m2.t === "recipe") {