@tradalab/mediakit 2.6.0 → 2.8.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-RWUGOTNJ.js";
15
+ } from "./chunk-4YCBTZRB.js";
16
16
  import {
17
17
  BLEND_MODES,
18
18
  TRANSITIONS,
@@ -21,17 +21,21 @@ import {
21
21
  layouts,
22
22
  parseColor
23
23
  } from "./chunk-BMIOUOT3.js";
24
+ import {
25
+ ASSETS,
26
+ assetUrl
27
+ } from "./chunk-T7YS2EQE.js";
24
28
 
25
29
  // src/segmenter.ts
26
30
  import { ImageSegmenter } from "@mediapipe/tasks-vision";
27
31
 
28
32
  // src/mp.ts
29
33
  import { FilesetResolver } from "@mediapipe/tasks-vision";
30
- var MP_DIR = "/mediakit/mp";
34
+ var MP_DIR = assetUrl("mp");
31
35
  var MODEL_URL = {
32
- person: "/mediakit/selfie_segmenter.tflite",
33
- classes: "/mediakit/selfie_multiclass_256x256.tflite",
34
- face: "/mediakit/face_landmarker.task"
36
+ person: assetUrl("selfie_segmenter.tflite"),
37
+ classes: assetUrl("selfie_multiclass_256x256.tflite"),
38
+ face: assetUrl("face_landmarker.task")
35
39
  };
36
40
  var LOAD_MS = 6e4;
37
41
  var fileset = null;
@@ -75,13 +79,17 @@ function withTimeout(p, ms, what, late) {
75
79
  }
76
80
  async function preloadDetectors(parts = { person: true, classes: true, face: true }) {
77
81
  const urls = [];
78
- try {
79
- const fs = await visionFileset();
80
- urls.push(fs.wasmBinaryPath, fs.wasmLoaderPath);
81
- } catch {
82
- return;
82
+ if (parts.cover) {
83
+ for (const a of ASSETS) if (a.part === "cover") urls.push(assetUrl(a.path));
84
+ }
85
+ if (parts.person || parts.classes || parts.face) {
86
+ try {
87
+ const fs = await visionFileset();
88
+ urls.push(fs.wasmBinaryPath, fs.wasmLoaderPath);
89
+ for (const k of ["person", "classes", "face"]) if (parts[k]) urls.push(MODEL_URL[k]);
90
+ } catch {
91
+ }
83
92
  }
84
- for (const k of ["person", "classes", "face"]) if (parts[k]) urls.push(MODEL_URL[k]);
85
93
  await Promise.all(
86
94
  urls.map(
87
95
  (u) => fetch(u, { priority: "low" }).then((r) => r.arrayBuffer()).catch(() => void 0)
@@ -89,6 +97,22 @@ async function preloadDetectors(parts = { person: true, classes: true, face: tru
89
97
  );
90
98
  }
91
99
 
100
+ // src/mp-clock.ts
101
+ var SOURCE_SWITCH_GAP_MS = 33;
102
+ function monotonicClock() {
103
+ let offset = 0;
104
+ let last = -Infinity;
105
+ return (timestampMs) => {
106
+ let t = timestampMs + offset;
107
+ if (t <= last) {
108
+ offset += last + SOURCE_SWITCH_GAP_MS - t;
109
+ t = last + SOURCE_SWITCH_GAP_MS;
110
+ }
111
+ last = t;
112
+ return t;
113
+ };
114
+ }
115
+
92
116
  // src/segmenter.ts
93
117
  async function createSegmenter(canvas, model = "person") {
94
118
  const fileset2 = await visionFileset();
@@ -108,6 +132,7 @@ async function createSegmenter(canvas, model = "person") {
108
132
  outputCategoryMask: true,
109
133
  outputConfidenceMasks: false
110
134
  });
135
+ const clock = monotonicClock();
111
136
  let pending = null;
112
137
  const release = () => {
113
138
  pending?.close();
@@ -117,7 +142,7 @@ async function createSegmenter(canvas, model = "person") {
117
142
  segment(frame, timestampMs) {
118
143
  release();
119
144
  let texture = null;
120
- segmenter.segmentForVideo(frame, timestampMs, (result) => {
145
+ segmenter.segmentForVideo(frame, clock(timestampMs), (result) => {
121
146
  const mask = result.categoryMask;
122
147
  if (mask) texture = mask.getAsWebGLTexture();
123
148
  pending = result;
@@ -135,12 +160,26 @@ async function createSegmenter(canvas, model = "person") {
135
160
  // src/face.ts
136
161
  import { FaceLandmarker } from "@mediapipe/tasks-vision";
137
162
  var FACE_FLOATS = 478 * 3;
138
- async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
163
+ var COVER_SIZE = 96;
164
+ function faceBox(lm, at) {
165
+ let x0 = 1;
166
+ let y0 = 1;
167
+ let x1 = 0;
168
+ let y1 = 0;
169
+ for (let i = at; i < at + FACE_FLOATS; i += 3) {
170
+ x0 = Math.min(x0, lm[i]);
171
+ x1 = Math.max(x1, lm[i]);
172
+ y0 = Math.min(y0, lm[i + 1]);
173
+ y1 = Math.max(y1, lm[i + 1]);
174
+ }
175
+ return [x0, y0, x1 - x0, y1 - y0];
176
+ }
177
+ async function createFaceDetector(canvas, maxFaces, delegate = "GPU", mode = "VIDEO") {
139
178
  const fileset2 = await visionFileset();
140
179
  const landmarker = await FaceLandmarker.createFromOptions(fileset2, {
141
180
  baseOptions: { modelAssetPath: MODEL_URL.face, delegate },
142
181
  canvas,
143
- runningMode: "VIDEO",
182
+ runningMode: mode,
144
183
  // As many as the core tracks: one landmark pass returns them all, so the cost of a second
145
184
  // face is the copy below and its own shader passes, not a second inference.
146
185
  numFaces: maxFaces,
@@ -148,9 +187,10 @@ async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
148
187
  outputFaceBlendshapes: false,
149
188
  outputFacialTransformationMatrixes: false
150
189
  });
190
+ const clock = monotonicClock();
151
191
  return {
152
192
  detect(frame, timestampMs, out) {
153
- const res = landmarker.detectForVideo(frame, timestampMs);
193
+ const res = mode === "VIDEO" ? landmarker.detectForVideo(frame, clock(timestampMs)) : landmarker.detect(frame);
154
194
  let n = 0;
155
195
  for (const lm of res.faceLandmarks ?? []) {
156
196
  if (lm.length * 3 !== FACE_FLOATS || n + FACE_FLOATS > out.length) break;
@@ -171,7 +211,7 @@ async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
171
211
  }
172
212
 
173
213
  // src/detect-remote.ts
174
- var DETECT_WORKER_URL = "/mediakit/detect-worker.js";
214
+ var DETECT_WORKER_URL = assetUrl("detect-worker.js");
175
215
  var DetectWorker = class {
176
216
  constructor(on) {
177
217
  this.on = on;
@@ -195,13 +235,13 @@ var DetectWorker = class {
195
235
  return this.worker !== null && this.up.has(kind) && !this.busy.has(kind);
196
236
  }
197
237
  /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */
198
- request(kind, frame, tsUs) {
238
+ request(kind, frame, tsUs, cover = false, retry = null) {
199
239
  if (!this.accepts(kind)) {
200
240
  frame.close();
201
241
  return false;
202
242
  }
203
243
  this.busy.add(kind);
204
- this.send({ t: kind, frame, tsUs }, [frame]);
244
+ this.send(kind === "face" ? { t: kind, frame, tsUs, cover, retry } : { t: kind, frame, tsUs }, [frame]);
205
245
  return true;
206
246
  }
207
247
  isUp(kind) {
@@ -237,7 +277,7 @@ var DetectWorker = class {
237
277
  break;
238
278
  case "face":
239
279
  this.busy.delete("face");
240
- if (this.up.has("face")) this.on.face(m.tsUs, m.n, m.lm, m.ms);
280
+ if (this.up.has("face")) this.on.face(m.tsUs, m.n, m.lm, m.ms, m.cover, m.rects);
241
281
  break;
242
282
  case "mask":
243
283
  this.busy.delete("mask");
@@ -270,8 +310,8 @@ var DetectWorker = class {
270
310
  };
271
311
 
272
312
  // src/wasm.ts
273
- var WASM_URL = "/mediakit/mediakit.wasm";
274
- var EXEC_URL = "/mediakit/wasm_exec.js";
313
+ var WASM_URL = assetUrl("mediakit.wasm");
314
+ var EXEC_URL = assetUrl("wasm_exec.js");
275
315
  var execLoaded = null;
276
316
  var compiled = null;
277
317
  function loadExec() {
@@ -410,6 +450,75 @@ var GpuLostError = class extends Error {
410
450
  detail;
411
451
  };
412
452
 
453
+ // src/mask-merge.ts
454
+ var CLASS_BACKGROUND = 0;
455
+ var CLASS_BODY_SKIN = 2;
456
+ var CLASS_CLOTHES = 4;
457
+ var CLASS_OTHERS = 5;
458
+ var CLASS_STALE_OCCLUDER = 6;
459
+ var THUMB_W = 64;
460
+ var THUMB_H = 36;
461
+ var MOVED_LUMA = 12;
462
+ function lumaThumb(rgba) {
463
+ const y = new Uint8Array(THUMB_W * THUMB_H);
464
+ 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;
465
+ return y;
466
+ }
467
+ function movedBetween(a, b) {
468
+ const w = THUMB_W;
469
+ const h = THUMB_H;
470
+ const hit = new Uint8Array(w * h);
471
+ for (let i = 0; i < hit.length; i++) hit[i] = Math.abs(a[i] - b[i]) > MOVED_LUMA ? 1 : 0;
472
+ const data = new Uint8Array(w * h);
473
+ for (let y = 0; y < h; y++) {
474
+ for (let x = 0; x < w; x++) {
475
+ let v = 0;
476
+ for (let dy = -1; dy <= 1 && !v; dy++) {
477
+ const yy = y + dy;
478
+ if (yy < 0 || yy >= h) continue;
479
+ for (let dx = -1; dx <= 1; dx++) {
480
+ const xx = x + dx;
481
+ if (xx >= 0 && xx < w && hit[yy * w + xx]) {
482
+ v = 1;
483
+ break;
484
+ }
485
+ }
486
+ }
487
+ data[y * w + x] = v;
488
+ }
489
+ }
490
+ return { width: w, height: h, data };
491
+ }
492
+ function mergeMasks(person, classes, out, moved = null) {
493
+ const { width: w, height: h } = person;
494
+ const merged = out && out.length === w * h ? out : new Uint8Array(w * h);
495
+ const cw = classes.width;
496
+ const ch = classes.height;
497
+ const sx = cw / w;
498
+ const sy = ch / h;
499
+ const mw = moved?.width ?? 0;
500
+ const mh = moved?.height ?? 0;
501
+ for (let y = 0; y < h; y++) {
502
+ const crow = Math.min(ch - 1, Math.floor((y + 0.5) * sy)) * cw;
503
+ const mrow = moved ? Math.min(mh - 1, Math.floor((y + 0.5) * mh / h)) * mw : 0;
504
+ const prow = y * w;
505
+ for (let x = 0; x < w; x++) {
506
+ if (person.data[prow + x] !== 0) {
507
+ merged[prow + x] = CLASS_BACKGROUND;
508
+ continue;
509
+ }
510
+ const c = classes.data[crow + Math.min(cw - 1, Math.floor((x + 0.5) * sx))];
511
+ if (c === CLASS_BACKGROUND) {
512
+ merged[prow + x] = CLASS_CLOTHES;
513
+ continue;
514
+ }
515
+ 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;
516
+ merged[prow + x] = stale ? CLASS_STALE_OCCLUDER : c;
517
+ }
518
+ }
519
+ return merged;
520
+ }
521
+
413
522
  // src/engine.ts
414
523
  var ZERO_STATS = {
415
524
  totalMs: 0,
@@ -433,9 +542,30 @@ var ZERO_STATS = {
433
542
  maskAgeMs: 0,
434
543
  effectError: ""
435
544
  };
436
- var MAX_HOLD = 2;
545
+ var MAX_HOLD = 3;
546
+ var COVER_FRAME_W = 256;
547
+ var COVER_HOLD = 0.6;
548
+ var COVER_MISSES = 2;
549
+ var FOLLOW_SIDE = 384;
550
+ var FOLLOW_MARGIN = 2.6;
551
+ var FOLLOW_RETRY = 2;
552
+ var FOLLOW_MIN_SIDE = 64;
553
+ var FOLLOW_SHIFT = 0.06;
554
+ var FOLLOW_RESIZE = 0.12;
555
+ var FOLLOW_STALE_US = 5e5;
556
+ var FOLLOW_KEPT_US = 1e6;
557
+ var SCAN_SHARE = 0.5;
558
+ var SCAN_STEP = 0.75;
559
+ var FOLLOW_REFRESH = 30;
560
+ var FOLLOW_WIDEN = 2;
561
+ var FOLLOW_GROW = 3;
562
+ var SAME_FACE = 0.3;
563
+ var FACE_RESULTS_KEPT = 8;
564
+ var THUMBS_KEPT = 12;
437
565
  var LINK_LOSS_WINDOW_MS = 3e3;
438
- var DEPTH_VOTES = 15;
566
+ var FACE_JUMP = 0.15;
567
+ var CATCH_UP_EVERY_US = 1e6;
568
+ var MASK_RESULTS_KEPT = 8;
439
569
  var DETECT_DUTY = 0.6;
440
570
  function gpuName(gl) {
441
571
  const info = gl.getExtension("WEBGL_debug_renderer_info");
@@ -448,6 +578,18 @@ function sourceSize(source) {
448
578
  const s = source;
449
579
  return [s.width, s.height];
450
580
  }
581
+ function tileGrid(sw, sh) {
582
+ const side = Math.max(FOLLOW_MIN_SIDE, Math.round(Math.min(sw, sh) * SCAN_SHARE));
583
+ const step = side * SCAN_STEP;
584
+ return { side, step, nx: Math.max(1, Math.ceil((sw - side) / step) + 1), ny: Math.max(1, Math.ceil((sh - side) / step) + 1) };
585
+ }
586
+ function overlap(a, b) {
587
+ const w = Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]);
588
+ const h = Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]);
589
+ if (w <= 0 || h <= 0) return 0;
590
+ const i = w * h;
591
+ return i / (a[2] * a[3] + b[2] * b[3] - i);
592
+ }
451
593
  var FACE_COLOR_SKIPPED = "face colour shaders skipped: linking one lost the WebGL context on this GPU before";
452
594
  var Engine = class _Engine {
453
595
  canvas;
@@ -501,13 +643,14 @@ var Engine = class _Engine {
501
643
  classRemote = false;
502
644
  classMaskTex = null;
503
645
  classMaskFresh = false;
504
- classMaskTs = 0;
646
+ classMaskTs = -1;
505
647
  syncFaces = false;
506
648
  renderedTs = 0;
507
649
  queue = [];
508
650
  spare = [];
509
- holdDepth = 1;
510
- depthVotes = 0;
651
+ faceExtraUp = false;
652
+ faceExtraTried = false;
653
+ lerpBuf = null;
511
654
  gapUs = 33333;
512
655
  prevTs = -1;
513
656
  sent = /* @__PURE__ */ new Map();
@@ -515,6 +658,35 @@ var Engine = class _Engine {
515
658
  faceLatencyMs = 0;
516
659
  maskLatencyMs = /* @__PURE__ */ new Map();
517
660
  faceTs = -1;
661
+ faceResults = [];
662
+ coverCanvas = null;
663
+ coverCell = null;
664
+ coverOn = false;
665
+ faceMisses = 0;
666
+ coverHidden = false;
667
+ srcW = 0;
668
+ srcH = 0;
669
+ coverLast = null;
670
+ coverShown = null;
671
+ coverImg = null;
672
+ faceAsked = /* @__PURE__ */ new Set();
673
+ faceCrops = /* @__PURE__ */ new Map();
674
+ followBox = null;
675
+ followTs = -Infinity;
676
+ followCrop = null;
677
+ followCanvas = null;
678
+ followRetry = null;
679
+ faceSeen = false;
680
+ followFloats = 0;
681
+ followAll = false;
682
+ followTurn = 0;
683
+ followMiss = 0;
684
+ followGrow = 0;
685
+ boxFloats = 0;
686
+ scanFrom = 0;
687
+ scanTurn = 0;
688
+ probes = /* @__PURE__ */ new Set();
689
+ maskResults = [];
518
690
  maskUsedTs = -1;
519
691
  lastHeld = null;
520
692
  swallowed = false;
@@ -524,13 +696,23 @@ var Engine = class _Engine {
524
696
  personLoading = null;
525
697
  personMaskTex = null;
526
698
  personMaskFresh = false;
527
- personMaskTs = 0;
699
+ personMaskTs = -1;
528
700
  personWorkerMs = 0;
701
+ personBytes = null;
702
+ classBytes = null;
703
+ mergedBytes = null;
704
+ mergedTex = null;
705
+ mergedFresh = false;
706
+ mergedTs = 0;
529
707
  detectCanvas = null;
530
708
  detectCanvasTs = -1;
709
+ thumbCanvas = null;
710
+ thumbs = /* @__PURE__ */ new Map();
531
711
  // A kind whose worker failed once stays in-thread.
532
712
  inThread = /* @__PURE__ */ new Set();
533
713
  faceLoading = null;
714
+ faceCount = 1;
715
+ caughtUpTs = -Infinity;
534
716
  maxFaces = 3;
535
717
  lmBuf = null;
536
718
  filter = { kind: "none" };
@@ -679,7 +861,7 @@ var Engine = class _Engine {
679
861
  }
680
862
  if (effects.whitenStyle === "pink" && this.skinLutState === "none") {
681
863
  this.skinLutState = "loading";
682
- decodeImage("/mediakit/whiten_pink.png", { colorSpaceConversion: "none", premultiplyAlpha: "none" }).then((bmp) => {
864
+ decodeImage(assetUrl("whiten_pink.png"), { colorSpaceConversion: "none", premultiplyAlpha: "none" }).then((bmp) => {
683
865
  if (this.closed) {
684
866
  bmp.close();
685
867
  return;
@@ -743,6 +925,7 @@ var Engine = class _Engine {
743
925
  this.faceLoading = this.remote("face", (d) => d.initFace(n)).then(() => {
744
926
  this.faceRemote = true;
745
927
  this.lmBuf = buf;
928
+ this.faceCount = n;
746
929
  }).catch((e) => {
747
930
  if (e instanceof LoadTimeout) throw e;
748
931
  if (!this.inThread.has("face")) console.warn("mediakit: no detect worker for faces, detecting in this thread", e);
@@ -765,7 +948,7 @@ var Engine = class _Engine {
765
948
  }
766
949
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
767
950
  personRemoteWanted(filter, effects) {
768
- return filter.kind === "none" && needsSegmentation(filter, effects) && !needsSkinClasses(filter, effects);
951
+ return filter.kind === "none" && needsSegmentation(filter, effects);
769
952
  }
770
953
  ensurePersonRemote() {
771
954
  if (this.personRemote || this.failed.has("person") || this.closed) return Promise.resolve();
@@ -803,14 +986,17 @@ var Engine = class _Engine {
803
986
  }
804
987
  detectHandlers(key) {
805
988
  return {
806
- face: (tsUs, n, lm, ms) => {
807
- if (this.closed || !this.lmBuf) return;
808
- this.lmBuf.set(lm);
809
- const [lo, hi] = splitMicros(tsUs);
810
- this.core.setFace(lo, hi, n);
989
+ face: (tsUs, found, lm, ms, foundCover, foundRects) => {
990
+ if (this.closed || !this.lmBuf || tsUs > this.prevTs) return;
811
991
  this.faceWorkerMs = ms;
812
- this.faceTs = tsUs;
813
- const took = this.took("face", tsUs);
992
+ this.uncrop(tsUs, found, lm, foundRects);
993
+ const { n, cover, rects } = this.dedupe(found, lm, foundCover, foundRects);
994
+ this.follow(tsUs, n, lm, this.probes.delete(tsUs));
995
+ if (this.syncing()) {
996
+ this.faceResults.push({ ts: tsUs, n, lm: lm.slice(), cover, rects });
997
+ if (this.faceResults.length > FACE_RESULTS_KEPT) this.faceResults.shift();
998
+ } else this.applyFace(tsUs, n, lm, cover, rects);
999
+ const took = this.took(key === "faceExtra" ? "faceExtra" : "face", tsUs);
814
1000
  if (took !== null) this.faceLatencyMs = this.faceLatencyMs ? this.faceLatencyMs + (took - this.faceLatencyMs) * 0.2 : took;
815
1001
  },
816
1002
  mask: (tsUs, width, height, data, ms) => {
@@ -820,24 +1006,30 @@ var Engine = class _Engine {
820
1006
  const was = this.maskLatencyMs.get(key);
821
1007
  this.maskLatencyMs.set(key, was ? was + (took - was) * 0.2 : took);
822
1008
  }
823
- if (key === "person") {
824
- this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, width, height, data);
825
- this.personMaskFresh = true;
826
- this.personMaskTs = tsUs;
827
- this.personWorkerMs = ms;
1009
+ const r = { person: key === "person", ts: tsUs, width, height, data, ms };
1010
+ if (!this.syncing()) {
1011
+ this.applyMask(r);
828
1012
  return;
829
1013
  }
830
- this.uploadClassMask(width, height, data);
831
- this.classMaskTs = tsUs;
832
- this.maskWorkerMs = ms;
1014
+ this.maskResults.push(r);
1015
+ if (this.maskResults.length > MASK_RESULTS_KEPT) this.maskResults.shift();
833
1016
  },
834
1017
  failed: (k, reason) => {
1018
+ if (key === "faceExtra") {
1019
+ this.faceExtraUp = false;
1020
+ this.detects.get(key)?.close();
1021
+ this.detects.delete(key);
1022
+ return;
1023
+ }
835
1024
  console.warn(`mediakit: ${key} detection moves into this thread:`, reason);
836
1025
  this.inThread.add(key);
837
1026
  if (key === "person") {
838
1027
  this.personRemote = false;
839
1028
  } else if (k === "face") {
840
1029
  this.faceRemote = false;
1030
+ if (this.coverOn) this.core.setFaceCover(null);
1031
+ this.coverOn = false;
1032
+ this.coverShown = null;
841
1033
  void this.ensureFace();
842
1034
  } else {
843
1035
  this.classRemote = false;
@@ -846,6 +1038,24 @@ var Engine = class _Engine {
846
1038
  }
847
1039
  };
848
1040
  }
1041
+ noteThumb(timestampUs) {
1042
+ if (this.thumbs.has(timestampUs) || !this.detectCanvas || this.detectCanvasTs !== timestampUs) return;
1043
+ this.thumbCanvas ??= new OffscreenCanvas(THUMB_W, THUMB_H);
1044
+ const ctx = this.thumbCanvas.getContext("2d", { willReadFrequently: true });
1045
+ ctx.drawImage(this.detectCanvas, 0, 0, THUMB_W, THUMB_H);
1046
+ this.thumbs.set(timestampUs, lumaThumb(ctx.getImageData(0, 0, THUMB_W, THUMB_H).data));
1047
+ if (this.thumbs.size > THUMBS_KEPT) this.thumbs.delete(this.thumbs.keys().next().value);
1048
+ }
1049
+ merge(tsUs) {
1050
+ if (!this.personBytes || !this.classBytes || !needsSkinClasses(this.filter, this.effects)) return;
1051
+ const then = this.thumbs.get(this.classMaskTs);
1052
+ const now2 = this.thumbs.get(this.personMaskTs);
1053
+ const moved = then && now2 && this.classMaskTs !== this.personMaskTs ? movedBetween(then, now2) : null;
1054
+ this.mergedBytes = mergeMasks(this.personBytes, this.classBytes, this.mergedBytes, moved);
1055
+ this.mergedTex = this.uploadMaskBytes(this.mergedTex, this.personBytes.width, this.personBytes.height, this.mergedBytes);
1056
+ this.mergedFresh = true;
1057
+ this.mergedTs = tsUs;
1058
+ }
849
1059
  uploadClassMask(width, height, data) {
850
1060
  this.classMaskTex = this.uploadMaskBytes(this.classMaskTex, width, height, data);
851
1061
  this.classMaskFresh = true;
@@ -872,24 +1082,187 @@ var Engine = class _Engine {
872
1082
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
873
1083
  * detection drains Chrome's few capture buffers and throttles the camera itself.
874
1084
  */
875
- requestRemote(kind, source, timestampUs) {
1085
+ requestRemote(want, source, timestampUs) {
1086
+ const lockstep = want === "face" && this.syncing();
1087
+ const kind = lockstep ? this.freeFaceWorker() : want;
1088
+ if (!kind) return;
876
1089
  const detect = this.detects.get(kind);
877
- if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
878
- if (!this.dutyAllows(kind)) return;
1090
+ if (!detect?.accepts(kind === "face" || kind === "faceExtra" ? "face" : "mask")) return;
1091
+ if (!lockstep && !this.dutyAllows(kind)) return;
879
1092
  let frame = null;
1093
+ let followed = null;
1094
+ let scanned = null;
880
1095
  try {
881
1096
  const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
882
- frame = new VideoFrame(copyable ? this.detectCopy(source, timestampUs) : source, {
1097
+ if (copyable) {
1098
+ this.srcW = source instanceof VideoFrame ? source.displayWidth : source.width;
1099
+ this.srcH = source instanceof VideoFrame ? source.displayHeight : source.height;
1100
+ }
1101
+ if (copyable && (kind === "face" || kind === "faceExtra")) {
1102
+ followed = this.followCopy(source, timestampUs);
1103
+ if (!followed) scanned = this.scanCopy(source, timestampUs);
1104
+ }
1105
+ frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(source, timestampUs) : source), {
883
1106
  timestamp: timestampUs
884
1107
  });
885
1108
  } catch {
886
1109
  }
887
- if (frame && detect.request(kind === "face" ? "face" : "mask", frame, timestampUs)) {
1110
+ if (frame && detect.request(kind === "face" || kind === "faceExtra" ? "face" : "mask", frame, timestampUs, this.effects.occluders ?? false, followed ? this.followRetry : null)) {
888
1111
  const now2 = performance.now();
889
1112
  this.sent.set(kind, { ts: timestampUs, at: now2 });
890
1113
  this.lastSentAt.set(kind, now2);
1114
+ if (lockstep) this.faceAsked.add(timestampUs);
1115
+ if (kind !== "face" && kind !== "faceExtra" && this.remoteMaskKind() === "merged") this.noteThumb(timestampUs);
1116
+ } else if (followed || scanned) this.faceCrops.delete(timestampUs);
1117
+ }
1118
+ followCopy(source, timestampUs) {
1119
+ const box = this.followBox;
1120
+ if (!box || timestampUs - this.followTs > FOLLOW_STALE_US) return null;
1121
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
1122
+ const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
1123
+ const want = Math.max(FOLLOW_MIN_SIDE, FOLLOW_MARGIN * (1 + this.followMiss) * Math.max(box[2] * sw, box[3] * sh));
1124
+ if (want > Math.min(sw, sh) && this.followFloats > FACE_FLOATS) return null;
1125
+ if (!this.followAll && this.followTurn++ % FOLLOW_REFRESH === FOLLOW_REFRESH - 1) {
1126
+ this.probes.add(timestampUs);
1127
+ return null;
1128
+ }
1129
+ let side = Math.round(Math.min(sw, sh, want));
1130
+ let x = Math.round(Math.min(sw - side, Math.max(0, (box[0] + box[2] / 2) * sw - side / 2)));
1131
+ let y = Math.round(Math.min(sh - side, Math.max(0, (box[1] + box[3] / 2) * sh - side / 2)));
1132
+ const kept = this.followCrop;
1133
+ 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) {
1134
+ ;
1135
+ [x, y, side] = kept;
1136
+ } else this.followCrop = [x, y, side];
1137
+ this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
1138
+ this.followCanvas.getContext("2d").drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
1139
+ const tight = Math.min(side, Math.max(FOLLOW_MIN_SIDE, FOLLOW_RETRY * Math.max(box[2] * sw, box[3] * sh)));
1140
+ this.followRetry = [((box[0] + box[2] / 2) * sw - x) / side, ((box[1] + box[3] / 2) * sh - y) / side, tight / side];
1141
+ this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh]);
1142
+ return this.followCanvas;
1143
+ }
1144
+ scanCopy(source, timestampUs) {
1145
+ if (this.faceSeen) return null;
1146
+ const turn = this.scanTurn++;
1147
+ if (turn % 2 === 0) return null;
1148
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
1149
+ const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
1150
+ const { side, step, nx, ny } = tileGrid(sw, sh);
1151
+ const at = (this.scanFrom + (turn >> 1)) % (nx * ny);
1152
+ const x = Math.max(0, Math.min(sw - side, Math.round(at % nx * step)));
1153
+ const y = Math.max(0, Math.min(sh - side, Math.round(Math.floor(at / nx) * step)));
1154
+ this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
1155
+ this.followCanvas.getContext("2d").drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
1156
+ this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh]);
1157
+ this.probes.add(timestampUs);
1158
+ return this.followCanvas;
1159
+ }
1160
+ scanTile(cx, cy) {
1161
+ const sw = this.srcW || this.canvas.width;
1162
+ const sh = this.srcH || this.canvas.height;
1163
+ const { side, step, nx, ny } = tileGrid(sw, sh);
1164
+ const ix = Math.min(nx - 1, Math.max(0, Math.round((cx * sw - side / 2) / step)));
1165
+ const iy = Math.min(ny - 1, Math.max(0, Math.round((cy * sh - side / 2) / step)));
1166
+ return iy * nx + ix;
1167
+ }
1168
+ uncrop(tsUs, n, lm, rects) {
1169
+ const crop = this.faceCrops.get(tsUs);
1170
+ for (const ts of this.faceCrops.keys()) if (ts === tsUs || ts < tsUs - FOLLOW_KEPT_US) this.faceCrops.delete(ts);
1171
+ if (!crop) return;
1172
+ for (let i = 0; i < n; i += 3) {
1173
+ lm[i] = crop[0] + lm[i] * crop[2];
1174
+ lm[i + 1] = crop[1] + lm[i + 1] * crop[3];
1175
+ lm[i + 2] = lm[i + 2] * crop[2];
1176
+ }
1177
+ for (let i = 0; rects && i < rects.length; i += 3) {
1178
+ rects[i] = crop[0] + rects[i] * crop[2];
1179
+ rects[i + 1] = crop[1] + rects[i + 1] * crop[3];
1180
+ rects[i + 2] = rects[i + 2] * crop[2];
891
1181
  }
892
1182
  }
1183
+ dedupe(n, lm, cover, rects) {
1184
+ const faces = n / FACE_FLOATS;
1185
+ if (faces < 2) return { n, cover, rects };
1186
+ const boxes = Array.from({ length: faces }, (_, f) => faceBox(lm, f * FACE_FLOATS));
1187
+ const ref = this.followBox;
1188
+ const score = (b) => (ref ? overlap(b, ref) : 0) + b[2] * b[3] * 1e-3;
1189
+ const keep = boxes.map(() => true);
1190
+ for (let a = 0; a < faces; a++) {
1191
+ for (let b = a + 1; b < faces; b++) {
1192
+ if (!keep[a] || !keep[b] || overlap(boxes[a], boxes[b]) <= SAME_FACE) continue;
1193
+ keep[score(boxes[a]) >= score(boxes[b]) ? b : a] = false;
1194
+ }
1195
+ }
1196
+ if (keep.every(Boolean)) return { n, cover, rects };
1197
+ const cells = COVER_SIZE * COVER_SIZE;
1198
+ const outCover = cover ? new Uint8Array(cover.length) : null;
1199
+ const outRects = rects ? new Float32Array(rects.length) : null;
1200
+ let k = 0;
1201
+ for (let f = 0; f < faces; f++) {
1202
+ if (!keep[f]) continue;
1203
+ if (k !== f) lm.copyWithin(k * FACE_FLOATS, f * FACE_FLOATS, (f + 1) * FACE_FLOATS);
1204
+ if (cover && outCover) outCover.set(cover.subarray(f * cells, (f + 1) * cells), k * cells);
1205
+ if (rects && outRects) outRects.set(rects.subarray(f * 3, f * 3 + 3), k * 3);
1206
+ k++;
1207
+ }
1208
+ return { n: k * FACE_FLOATS, cover: outCover ? outCover.slice(0, k * cells) : null, rects: outRects ? outRects.slice(0, k * 3) : null };
1209
+ }
1210
+ follow(tsUs, n, lm, probe) {
1211
+ for (const ts of this.probes) if (ts < tsUs - FOLLOW_KEPT_US) this.probes.delete(ts);
1212
+ if (tsUs <= this.followTs || probe && (n === 0 || n < this.followFloats)) return;
1213
+ this.followTs = tsUs;
1214
+ this.faceSeen = n > 0;
1215
+ if (n === 0) {
1216
+ this.followGrow = 0;
1217
+ this.followFloats = 0;
1218
+ this.followAll = false;
1219
+ const box = this.followBox;
1220
+ if (box && this.followMiss < FOLLOW_WIDEN) {
1221
+ this.followMiss++;
1222
+ return;
1223
+ }
1224
+ this.followMiss = 0;
1225
+ if (box) this.scanFrom = this.scanTile(box[0] + box[2] / 2, box[1] + box[3] / 2);
1226
+ this.scanTurn = 1;
1227
+ this.followBox = null;
1228
+ this.followCrop = null;
1229
+ this.boxFloats = 0;
1230
+ return;
1231
+ }
1232
+ this.followMiss = 0;
1233
+ const old = this.followBox;
1234
+ const grow = old !== null && this.boxFloats > 0 && n > this.boxFloats && !probe;
1235
+ this.followGrow = grow ? this.followGrow + 1 : 0;
1236
+ const take = grow && this.followGrow < FOLLOW_GROW ? this.boxFloats : n;
1237
+ const boxes = [];
1238
+ for (let f = 0; f < n; f += FACE_FLOATS) boxes.push(faceBox(lm, f));
1239
+ if (take < n && old) boxes.sort((a, b) => overlap(b, old) - overlap(a, old));
1240
+ const kept = boxes.slice(0, take / FACE_FLOATS);
1241
+ const x0 = Math.min(...kept.map((b) => b[0]));
1242
+ const y0 = Math.min(...kept.map((b) => b[1]));
1243
+ const x1 = Math.max(...kept.map((b) => b[0] + b[2]));
1244
+ const y1 = Math.max(...kept.map((b) => b[1] + b[3]));
1245
+ this.followBox = [x0, y0, x1 - x0, y1 - y0];
1246
+ this.boxFloats = take;
1247
+ this.followFloats = take;
1248
+ this.followAll = take >= this.faceCount * FACE_FLOATS;
1249
+ }
1250
+ freeFaceWorker() {
1251
+ if (this.detects.get("face")?.accepts("face")) return "face";
1252
+ if (this.faceExtraUp && this.detects.get("faceExtra")?.accepts("face")) return "faceExtra";
1253
+ return null;
1254
+ }
1255
+ ensureFaceExtra() {
1256
+ if (this.faceExtraTried || this.closed) return;
1257
+ this.faceExtraTried = true;
1258
+ const n = this.faceCount;
1259
+ this.remote("faceExtra", (d) => d.initFace(n)).then(() => {
1260
+ this.faceExtraUp = true;
1261
+ }).catch(() => {
1262
+ this.detects.get("faceExtra")?.close();
1263
+ this.detects.delete("faceExtra");
1264
+ });
1265
+ }
893
1266
  /** Face and mask asked on the same frame share one draw. */
894
1267
  detectCopy(source, timestampUs) {
895
1268
  const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
@@ -969,45 +1342,99 @@ var Engine = class _Engine {
969
1342
  if (this.prevTs >= 0 && timestampUs > this.prevTs) {
970
1343
  this.gapUs += (Math.min(timestampUs - this.prevTs, 2e5) - this.gapUs) * 0.1;
971
1344
  }
1345
+ if (timestampUs < this.prevTs) {
1346
+ this.faceResults = [];
1347
+ this.maskResults = [];
1348
+ this.faceAsked.clear();
1349
+ this.faceCrops.clear();
1350
+ this.followBox = null;
1351
+ this.followCrop = null;
1352
+ this.followTs = -Infinity;
1353
+ this.faceSeen = false;
1354
+ this.followFloats = 0;
1355
+ this.followAll = false;
1356
+ this.followTurn = 0;
1357
+ this.followMiss = 0;
1358
+ this.followGrow = 0;
1359
+ this.boxFloats = 0;
1360
+ this.scanFrom = 0;
1361
+ this.scanTurn = 0;
1362
+ this.probes.clear();
1363
+ this.caughtUpTs = -Infinity;
1364
+ this.thumbs.clear();
1365
+ }
972
1366
  this.prevTs = timestampUs;
973
1367
  if (!this.syncing() || typeof ImageData !== "undefined" && source instanceof ImageData) {
974
1368
  this.releaseHeld();
975
1369
  this.renderedTs = timestampUs;
976
1370
  return this.draw(source, timestampUs, false);
977
1371
  }
1372
+ this.ensureFaceExtra();
978
1373
  this.requestRemote("face", source, timestampUs);
979
1374
  const remoteMask = this.remoteMaskKind();
980
- if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
1375
+ if (remoteMask === "merged") {
1376
+ this.requestRemote("person", source, timestampUs);
1377
+ this.requestRemote("mask", source, timestampUs);
1378
+ } else if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
981
1379
  this.queue.push({ c: this.hold(source), ts: timestampUs });
982
- this.retuneDepth();
983
- if (this.queue.length <= this.holdDepth) {
1380
+ while (this.queue.length > MAX_HOLD + 1) this.faceAsked.delete(this.spareFront());
1381
+ if (this.queue.length <= MAX_HOLD && !this.faceReady(this.queue[0].ts)) {
984
1382
  this.swallowed = true;
985
1383
  return false;
986
1384
  }
987
- while (this.queue.length > this.holdDepth + 1) this.spare.push(this.queue.shift().c);
1385
+ if (this.queue.length > 2 && this.faceReady(this.queue[1].ts) && timestampUs - this.caughtUpTs >= CATCH_UP_EVERY_US) {
1386
+ this.caughtUpTs = timestampUs;
1387
+ this.faceAsked.delete(this.spareFront());
1388
+ }
988
1389
  const front = this.queue.shift();
1390
+ this.faceAsked.delete(front.ts);
1391
+ this.faceFor(front.ts);
1392
+ this.masksFor(front.ts);
989
1393
  this.lastHeld = front.c;
990
1394
  this.renderedTs = front.ts;
991
1395
  return this.draw(front.c, front.ts, true);
992
1396
  }
993
1397
  remoteMaskKind() {
994
- if (this.personRemote && this.personRemoteWanted(this.filter, this.effects)) return "person";
995
- if (this.classRemote && needsSkinClasses(this.filter, this.effects)) return "mask";
996
- return null;
997
- }
998
- retuneDepth() {
999
- const kind = this.remoteMaskKind();
1000
- const latency = Math.max(this.faceLatencyMs, kind ? this.maskLatencyMs.get(kind) ?? 0 : 0);
1001
- const want = latency > 0 ? Math.min(MAX_HOLD, Math.max(1, Math.ceil(latency * 1e3 / this.gapUs))) : 1;
1002
- if (want === this.holdDepth) {
1003
- this.depthVotes = 0;
1398
+ const person = this.personRemote && this.personRemoteWanted(this.filter, this.effects);
1399
+ if (!needsSkinClasses(this.filter, this.effects)) return person ? "person" : null;
1400
+ if (this.classRemote) return person ? "merged" : "mask";
1401
+ return person && !this.inThread.has("mask") ? "person" : null;
1402
+ }
1403
+ spareFront() {
1404
+ const h = this.queue.shift();
1405
+ this.spare.push(h.c);
1406
+ return h.ts;
1407
+ }
1408
+ applyMask(r) {
1409
+ if (r.person) {
1410
+ this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, r.width, r.height, r.data);
1411
+ this.personMaskFresh = true;
1412
+ this.personMaskTs = r.ts;
1413
+ this.personWorkerMs = r.ms;
1414
+ this.personBytes = { width: r.width, height: r.height, data: r.data };
1415
+ this.merge(r.ts);
1004
1416
  return;
1005
1417
  }
1006
- if (++this.depthVotes >= DEPTH_VOTES) {
1007
- this.holdDepth = want;
1008
- this.depthVotes = 0;
1418
+ this.uploadClassMask(r.width, r.height, r.data);
1419
+ this.classMaskTs = r.ts;
1420
+ this.maskWorkerMs = r.ms;
1421
+ this.classBytes = { width: r.width, height: r.height, data: r.data };
1422
+ this.merge(this.personMaskTs);
1423
+ }
1424
+ masksFor(tsUs) {
1425
+ for (const person of [false, true]) {
1426
+ let pick = null;
1427
+ for (const r of this.maskResults) if (r.person === person && (!pick || Math.abs(r.ts - tsUs) < Math.abs(pick.ts - tsUs))) pick = r;
1428
+ if (!pick) continue;
1429
+ const chosen = pick;
1430
+ this.maskResults = this.maskResults.filter((r) => r.person !== person || r.ts >= chosen.ts);
1431
+ if (chosen.ts !== (person ? this.personMaskTs : this.classMaskTs)) this.applyMask(chosen);
1009
1432
  }
1010
1433
  }
1434
+ faceReady(tsUs) {
1435
+ const asked = this.faceAsked.has(tsUs);
1436
+ return this.faceResults.some((r) => asked ? r.ts === tsUs : r.ts > tsUs);
1437
+ }
1011
1438
  dutyAllows(kind) {
1012
1439
  const took = kind === "face" ? this.faceLatencyMs : this.maskLatencyMs.get(kind) ?? 0;
1013
1440
  if (took * 1e3 < this.gapUs) return true;
@@ -1020,6 +1447,89 @@ var Engine = class _Engine {
1020
1447
  this.sent.delete(kind);
1021
1448
  return performance.now() - s.at;
1022
1449
  }
1450
+ applyFace(tsUs, n, lm, cover, rects) {
1451
+ this.faceMisses = n === 0 ? this.faceMisses + 1 : 0;
1452
+ if (n > 0) this.showCover(cover, rects);
1453
+ else if (this.faceMisses >= COVER_MISSES) this.hideCover();
1454
+ this.lmBuf.set(lm);
1455
+ const [lo, hi] = splitMicros(tsUs);
1456
+ this.core.setFace(lo, hi, n);
1457
+ this.faceTs = tsUs;
1458
+ }
1459
+ faceFor(tsUs) {
1460
+ this.faceResults.sort((a2, b) => a2.ts - b.ts);
1461
+ let pick = -1;
1462
+ for (let i = 0; i < this.faceResults.length; i++) if (this.faceResults[i].ts <= tsUs) pick = i;
1463
+ if (pick < 0) return;
1464
+ const r = this.faceResults[pick];
1465
+ const next = this.faceResults[pick + 1];
1466
+ this.faceResults.splice(0, pick);
1467
+ if (r.ts === tsUs || !next || !this.sameFaces(r, next)) {
1468
+ if (r.ts !== this.faceTs) this.applyFace(r.ts, r.n, r.lm, r.cover, r.rects);
1469
+ return;
1470
+ }
1471
+ const a = (tsUs - r.ts) / (next.ts - r.ts);
1472
+ if (!this.lerpBuf || this.lerpBuf.length !== r.lm.length) this.lerpBuf = new Float32Array(r.lm.length);
1473
+ for (let i = 0; i < r.n; i++) this.lerpBuf[i] = r.lm[i] + (next.lm[i] - r.lm[i]) * a;
1474
+ const near = a < 0.5 ? r : next;
1475
+ this.applyFace(tsUs, r.n, this.lerpBuf, near.cover, near.rects);
1476
+ }
1477
+ hideCover() {
1478
+ if (!this.coverOn || !this.coverCanvas || this.coverHidden) return;
1479
+ const ctx = this.coverCanvas.getContext("2d");
1480
+ ctx.fillStyle = "#000";
1481
+ ctx.fillRect(0, 0, this.coverCanvas.width, this.coverCanvas.height);
1482
+ this.core.setFaceCover(this.coverCanvas);
1483
+ this.coverShown = null;
1484
+ this.coverHidden = true;
1485
+ }
1486
+ showCover(cover, rects) {
1487
+ this.coverHidden = false;
1488
+ if (!cover || !rects || !(this.effects.occluders ?? false)) {
1489
+ if (this.coverOn) this.core.setFaceCover(null);
1490
+ this.coverOn = false;
1491
+ this.coverShown = null;
1492
+ return;
1493
+ }
1494
+ if (cover === this.coverShown && this.coverOn) return;
1495
+ const w = COVER_FRAME_W;
1496
+ const h = Math.max(1, Math.round(w * (this.srcH || this.canvas.height) / (this.srcW || this.canvas.width)));
1497
+ if (!this.coverCanvas || this.coverCanvas.height !== h) this.coverCanvas = new OffscreenCanvas(w, h);
1498
+ this.coverCell ??= new OffscreenCanvas(COVER_SIZE, COVER_SIZE);
1499
+ const ctx = this.coverCanvas.getContext("2d");
1500
+ const cell = this.coverCell.getContext("2d");
1501
+ ctx.fillStyle = "#fff";
1502
+ ctx.fillRect(0, 0, w, h);
1503
+ this.coverImg ??= cell.createImageData(COVER_SIZE, COVER_SIZE);
1504
+ const img = this.coverImg;
1505
+ const cells = COVER_SIZE * COVER_SIZE;
1506
+ const held = this.coverLast && this.coverLast !== cover && this.coverLast.length === cover.length ? this.coverLast : null;
1507
+ for (let f = 0; f * 3 < rects.length; f++) {
1508
+ for (let i = 0; i < cells; i++) {
1509
+ const now2 = cover[f * cells + i];
1510
+ const v = held ? Math.min(now2, now2 * (1 - COVER_HOLD) + held[f * cells + i] * COVER_HOLD) : now2;
1511
+ img.data[i * 4] = v;
1512
+ img.data[i * 4 + 1] = v;
1513
+ img.data[i * 4 + 2] = v;
1514
+ img.data[i * 4 + 3] = 255;
1515
+ }
1516
+ cell.putImageData(img, 0, 0);
1517
+ const side = rects[f * 3 + 2] * w;
1518
+ ctx.drawImage(this.coverCell, rects[f * 3] * w - side / 2, rects[f * 3 + 1] * h - side / 2, side, side);
1519
+ }
1520
+ this.core.setFaceCover(this.coverCanvas);
1521
+ this.coverOn = true;
1522
+ this.coverLast = cover;
1523
+ this.coverShown = cover;
1524
+ }
1525
+ sameFaces(a, b) {
1526
+ if (a.n === 0 || a.n !== b.n) return false;
1527
+ for (let k = 0; k < a.n; k += FACE_FLOATS) {
1528
+ const nose = k + 3;
1529
+ 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;
1530
+ }
1531
+ return true;
1532
+ }
1023
1533
  releaseHeld() {
1024
1534
  for (const h of this.queue) this.spare.push(h.c);
1025
1535
  this.queue = [];
@@ -1053,7 +1563,24 @@ var Engine = class _Engine {
1053
1563
  this.used = null;
1054
1564
  let served = false;
1055
1565
  const remoteMask = this.remoteMaskKind();
1056
- if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
1566
+ if (remoteMask === "merged") {
1567
+ if (!faceDone) {
1568
+ this.requestRemote("person", source, timestampUs);
1569
+ this.requestRemote("mask", source, timestampUs);
1570
+ }
1571
+ const tex = this.mergedTex ?? this.personMaskTex;
1572
+ if (tex) {
1573
+ served = true;
1574
+ if (this.mergedTex ? this.mergedFresh : this.personMaskFresh) {
1575
+ this.mergedFresh = false;
1576
+ this.personMaskFresh = false;
1577
+ mask = tex;
1578
+ maskKind = this.mergedTex ? 1 : 0;
1579
+ maskTs = this.mergedTex ? this.mergedTs : this.personMaskTs;
1580
+ segMs = this.personWorkerMs;
1581
+ }
1582
+ }
1583
+ } else if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
1057
1584
  if (remoteMask === "person") {
1058
1585
  if (this.personMaskTex) {
1059
1586
  served = true;
@@ -1141,7 +1668,7 @@ var Engine = class _Engine {
1141
1668
  needsFace: s ? s[10] > 0.5 : false,
1142
1669
  autoExposure: s ? s[11] : 0,
1143
1670
  faces: s ? s[12] : 0,
1144
- heldFrames: faceDone ? this.holdDepth : 0,
1671
+ heldFrames: faceDone ? this.queue.length : 0,
1145
1672
  faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
1146
1673
  maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0,
1147
1674
  effectError: this.programErr || this.loadErr
@@ -1176,6 +1703,11 @@ var Engine = class _Engine {
1176
1703
  if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
1177
1704
  if (this.personMaskTex) this.gl.deleteTexture(this.personMaskTex);
1178
1705
  this.personMaskTex = null;
1706
+ if (this.mergedTex) this.gl.deleteTexture(this.mergedTex);
1707
+ this.mergedTex = null;
1708
+ this.personBytes = null;
1709
+ this.classBytes = null;
1710
+ this.mergedBytes = null;
1179
1711
  this.personRemote = false;
1180
1712
  this.classMaskTex = null;
1181
1713
  this.lmBuf = null;
@@ -1741,7 +2273,7 @@ var VideoPipeline = class {
1741
2273
  }
1742
2274
  /** Starts the worker and waits for its "ready". */
1743
2275
  attachWorker(onReady, cleanup, post) {
1744
- const worker = new Worker("/mediakit/worker.js");
2276
+ const worker = new Worker(assetUrl("worker.js"));
1745
2277
  this.worker = worker;
1746
2278
  return new Promise((resolve, reject) => {
1747
2279
  let settled = false;