@tradalab/mediakit 2.1.1 → 2.4.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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { BgFilter, Effects } from './recipe.js';
2
- export { EFFECTS_SCHEMA, FieldSpec, NO_EFFECTS, Rgb, TOUCH_UP, needsFace, needsMask, needsSegmentation, normalizeEffects, touchUp, touchUpAmount } from './recipe.js';
1
+ import { BgFilter, Effects, DebugView } from './recipe.js';
2
+ export { DEBUG_VIEWS, EFFECTS_SCHEMA, FieldSpec, NO_EFFECTS, Rgb, TOUCH_UP, needsFace, needsMask, needsSegmentation, normalizeEffects, touchUp, touchUpAmount } from './recipe.js';
3
3
  import { Color, SceneLayer, TransitionKind } from './layout.js';
4
4
  export { BLEND_MODES, BlendMode, Rect, TRANSITIONS, hitTest, layouts, parseColor } from './layout.js';
5
5
 
@@ -41,6 +41,12 @@ interface FrameStats {
41
41
  autoExposure: number;
42
42
  /** How many faces are being tracked. */
43
43
  faces: number;
44
+ /** Frames `syncFaces` holds back right now, sized to how long landmarks take; 0 when off. */
45
+ heldFrames: number;
46
+ /** How old the landmarks behind this frame are, from the frame they were found on; 0 without landmarks. */
47
+ faceAgeMs: number;
48
+ /** How old the segmentation mask behind this frame is; 0 without one. */
49
+ maskAgeMs: number;
44
50
  }
45
51
  type EngineCanvas = HTMLCanvasElement | OffscreenCanvas;
46
52
  declare class Engine {
@@ -81,9 +87,32 @@ declare class Engine {
81
87
  private classRemote;
82
88
  private classMaskTex;
83
89
  private classMaskFresh;
90
+ private classMaskTs;
91
+ syncFaces: boolean;
92
+ renderedTs: number;
93
+ private queue;
94
+ private spare;
95
+ private holdDepth;
96
+ private depthVotes;
97
+ private gapUs;
98
+ private prevTs;
99
+ private readonly sent;
100
+ private faceLatencyMs;
101
+ private readonly maskLatencyMs;
102
+ private faceTs;
103
+ private maskUsedTs;
104
+ private lastHeld;
105
+ private swallowed;
84
106
  private maskWorkerMs;
85
- private detect;
107
+ private readonly detects;
108
+ private personRemote;
109
+ private personLoading;
110
+ private personMaskTex;
111
+ private personMaskFresh;
112
+ private personMaskTs;
113
+ private personWorkerMs;
86
114
  private detectCanvas;
115
+ private detectCanvasTs;
87
116
  private readonly inThread;
88
117
  private faceLoading;
89
118
  private maxFaces;
@@ -105,6 +134,8 @@ declare class Engine {
105
134
  static on(canvas: EngineCanvas, filter: BgFilter, effects?: Effects, background?: ImageBitmap, alpha?: boolean, maxFaces?: number): Promise<Engine>;
106
135
  get loading(): boolean;
107
136
  get outputCanvas(): EngineCanvas;
137
+ /** Draws an inner layer instead of the picture until set back to "off". */
138
+ setDebug(view: DebugView): void;
108
139
  /**
109
140
  * Change the recipe without rebuilding the pipeline, so dragging a slider does not flash.
110
141
  *
@@ -115,20 +146,24 @@ declare class Engine {
115
146
  setRecipe(filter: BgFilter, effects?: Effects, background?: ImageBitmap): Promise<void>;
116
147
  private ensureFace;
117
148
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
149
+ private personRemoteWanted;
150
+ private ensurePersonRemote;
118
151
  private remote;
152
+ private detectHandlers;
119
153
  private uploadClassMask;
154
+ private uploadMaskBytes;
120
155
  /**
121
156
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
122
157
  * detection drains Chrome's few capture buffers and throttles the camera itself.
123
158
  */
124
159
  private requestRemote;
160
+ /** Face and mask asked on the same frame share one draw. */
125
161
  private detectCopy;
126
162
  private ensureClassSegmenter;
127
163
  private ensureSegmenter;
128
164
  /**
129
165
  * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
130
- * yet, the segmenter is still loading, or the recipe is inactive; the transport must
131
- * forward the original frame rather than drop it.
166
+ * yet, the segmenter is still loading, or the recipe is inactive.
132
167
  *
133
168
  * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
134
169
  * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
@@ -139,6 +174,15 @@ declare class Engine {
139
174
  * it constructs one only to destroy it again.
140
175
  */
141
176
  render(source: TexImageSource, timestampUs: number): boolean;
177
+ private remoteMaskKind;
178
+ private retuneDepth;
179
+ private took;
180
+ private releaseHeld;
181
+ dropped(): boolean;
182
+ passthrough(): VideoFrame | null;
183
+ private syncing;
184
+ private hold;
185
+ private draw;
142
186
  /**
143
187
  * Wrap the output canvas as a new VideoFrame.
144
188
  *
@@ -187,6 +231,9 @@ interface PipelineOptions {
187
231
  * the face detector on every call, about a third of the landmark cost.
188
232
  */
189
233
  maxFaces?: number;
234
+ syncFaces?: boolean;
235
+ /** Starts with an inner layer drawn instead of the picture; see `setDebug`. */
236
+ debug?: DebugView;
190
237
  /** No processed frame for 2 s while the camera is live (20 s while a detector loads). */
191
238
  onStall?: (info: {
192
239
  transport: Transport;
@@ -211,6 +258,7 @@ declare class VideoPipeline {
211
258
  private filter;
212
259
  private effects;
213
260
  private opts;
261
+ private debug;
214
262
  private source;
215
263
  private size;
216
264
  private lastBeat;
@@ -249,6 +297,12 @@ declare class VideoPipeline {
249
297
  private startMain;
250
298
  /** Swap the background in place - no pipeline rebuild, so the picture does not flash. */
251
299
  switchTo(filter: BgFilter): Promise<void>;
300
+ /**
301
+ * Draw an inner layer instead of the picture: "skin" (red smoothing, green whitening, blue face
302
+ * mesh), "mask" (the person or class mask) or "face" (tracked outlines and necks). "off" restores it.
303
+ */
304
+ setDebug(view: DebugView): void;
305
+ get debugView(): DebugView;
252
306
  /** Change the effects outside the background. */
253
307
  setEffects(effects: Effects): Promise<void>;
254
308
  private pushRecipe;
@@ -442,4 +496,4 @@ declare function renderText(text: string, style?: TextStyle): HTMLCanvasElement;
442
496
  /** Where each of the face landmarker's first 468 landmarks lies on the canonical face texture. */
443
497
  declare const FACE_UV: Float32Array<ArrayBuffer>;
444
498
 
445
- export { BgFilter, Color, Effects, Engine, type EngineCanvas, FACE_UV, type FrameStats, type PipelineHealth, type PipelineOptions, Scene, SceneLayer, type SceneOptions, type SceneSource, type SceneStats, type TextStyle, TransitionKind, type Transport, VideoPipeline, mediakitSupported, renderText };
499
+ export { BgFilter, Color, DebugView, Effects, Engine, type EngineCanvas, FACE_UV, type FrameStats, type PipelineHealth, type PipelineOptions, Scene, SceneLayer, type SceneOptions, type SceneSource, type SceneStats, type TextStyle, TransitionKind, type Transport, VideoPipeline, mediakitSupported, renderText };
package/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
1
  import {
2
+ DEBUG_VIEWS,
2
3
  EFFECTS_SCHEMA,
3
4
  NO_EFFECTS,
4
5
  TOUCH_UP,
5
6
  coreRecipe,
7
+ debugCode,
6
8
  needsFace,
7
9
  needsMask,
8
10
  needsSegmentation,
@@ -10,7 +12,7 @@ import {
10
12
  normalizeEffects,
11
13
  touchUp,
12
14
  touchUpAmount
13
- } from "./chunk-TBMYRKXR.js";
15
+ } from "./chunk-YW75KJJO.js";
14
16
  import {
15
17
  BLEND_MODES,
16
18
  TRANSITIONS,
@@ -130,9 +132,13 @@ var DetectWorker = class {
130
132
  initMask(model) {
131
133
  return this.init("mask", { t: "initMask", model });
132
134
  }
135
+ /** Whether `request` would take a frame of this kind now. */
136
+ accepts(kind) {
137
+ return this.worker !== null && this.up.has(kind) && !this.busy.has(kind);
138
+ }
133
139
  /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */
134
140
  request(kind, frame, tsUs) {
135
- if (!this.worker || !this.up.has(kind) || this.busy.has(kind)) {
141
+ if (!this.accepts(kind)) {
136
142
  frame.close();
137
143
  return false;
138
144
  }
@@ -294,8 +300,19 @@ var ZERO_STATS = {
294
300
  faceSize: 0,
295
301
  needsFace: false,
296
302
  autoExposure: 0,
297
- faces: 0
303
+ faces: 0,
304
+ heldFrames: 0,
305
+ faceAgeMs: 0,
306
+ maskAgeMs: 0
298
307
  };
308
+ var MAX_HOLD = 2;
309
+ var DEPTH_VOTES = 15;
310
+ function sourceSize(source) {
311
+ if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
312
+ if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
313
+ const s = source;
314
+ return [s.width, s.height];
315
+ }
299
316
  var Engine = class _Engine {
300
317
  canvas;
301
318
  gl;
@@ -337,13 +354,35 @@ var Engine = class _Engine {
337
354
  // stalls the picture for that long. `face` is the fallback when no worker can be made.
338
355
  faceRemote = false;
339
356
  faceWorkerMs = 0;
340
- // The multiclass segmenter in that same worker: its mask comes back as bytes, uploaded here.
341
357
  classRemote = false;
342
358
  classMaskTex = null;
343
359
  classMaskFresh = false;
360
+ classMaskTs = 0;
361
+ syncFaces = false;
362
+ renderedTs = 0;
363
+ queue = [];
364
+ spare = [];
365
+ holdDepth = 1;
366
+ depthVotes = 0;
367
+ gapUs = 33333;
368
+ prevTs = -1;
369
+ sent = /* @__PURE__ */ new Map();
370
+ faceLatencyMs = 0;
371
+ maskLatencyMs = /* @__PURE__ */ new Map();
372
+ faceTs = -1;
373
+ maskUsedTs = -1;
374
+ lastHeld = null;
375
+ swallowed = false;
344
376
  maskWorkerMs = 0;
345
- detect = null;
377
+ detects = /* @__PURE__ */ new Map();
378
+ personRemote = false;
379
+ personLoading = null;
380
+ personMaskTex = null;
381
+ personMaskFresh = false;
382
+ personMaskTs = 0;
383
+ personWorkerMs = 0;
346
384
  detectCanvas = null;
385
+ detectCanvasTs = -1;
347
386
  // A kind whose worker failed once stays in-thread.
348
387
  inThread = /* @__PURE__ */ new Set();
349
388
  faceLoading = null;
@@ -413,6 +452,11 @@ var Engine = class _Engine {
413
452
  get outputCanvas() {
414
453
  return this.canvas;
415
454
  }
455
+ /** Draws an inner layer instead of the picture until set back to "off". */
456
+ setDebug(view) {
457
+ if (this.closed) return;
458
+ this.core.setDebug(debugCode(view));
459
+ }
416
460
  /**
417
461
  * Change the recipe without rebuilding the pipeline, so dragging a slider does not flash.
418
462
  *
@@ -493,6 +537,7 @@ var Engine = class _Engine {
493
537
  this.core.setRecipe(coreRecipe(filter, effects));
494
538
  if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
495
539
  if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
540
+ if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
496
541
  if (needsFace(effects)) void this.ensureFace();
497
542
  }
498
543
  ensureFace() {
@@ -522,27 +567,72 @@ var Engine = class _Engine {
522
567
  return this.faceLoading;
523
568
  }
524
569
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
570
+ personRemoteWanted(filter, effects) {
571
+ return filter.kind === "none" && needsSegmentation(filter, effects) && !needsSkinClasses(filter, effects);
572
+ }
573
+ ensurePersonRemote() {
574
+ if (this.personRemote || this.closed) return Promise.resolve();
575
+ this.personLoading ??= this.remote("person", (d) => d.initMask("person")).then(() => {
576
+ this.personRemote = true;
577
+ }).catch(() => {
578
+ }).finally(() => {
579
+ this.personLoading = null;
580
+ });
581
+ return this.personLoading;
582
+ }
525
583
  async remote(kind, init) {
526
584
  if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
527
585
  throw new Error("in-thread");
528
586
  }
529
- this.detect ??= new DetectWorker({
587
+ let detect = this.detects.get(kind);
588
+ if (!detect) {
589
+ detect = new DetectWorker(this.detectHandlers(kind));
590
+ this.detects.set(kind, detect);
591
+ }
592
+ try {
593
+ await init(detect);
594
+ } catch (e) {
595
+ this.inThread.add(kind);
596
+ throw e;
597
+ }
598
+ if (this.closed) throw new Error("closed");
599
+ }
600
+ detectHandlers(key) {
601
+ return {
530
602
  face: (tsUs, n, lm, ms) => {
531
603
  if (this.closed || !this.lmBuf) return;
532
604
  this.lmBuf.set(lm);
533
605
  const [lo, hi] = splitMicros(tsUs);
534
606
  this.core.setFace(lo, hi, n);
535
607
  this.faceWorkerMs = ms;
608
+ this.faceTs = tsUs;
609
+ const took = this.took("face", tsUs);
610
+ if (took !== null) this.faceLatencyMs = this.faceLatencyMs ? this.faceLatencyMs + (took - this.faceLatencyMs) * 0.2 : took;
536
611
  },
537
- mask: (_tsUs, width, height, data, ms) => {
612
+ mask: (tsUs, width, height, data, ms) => {
538
613
  if (this.closed) return;
614
+ const took = this.took(key, tsUs);
615
+ if (took !== null) {
616
+ const was = this.maskLatencyMs.get(key);
617
+ this.maskLatencyMs.set(key, was ? was + (took - was) * 0.2 : took);
618
+ }
619
+ if (key === "person") {
620
+ this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, width, height, data);
621
+ this.personMaskFresh = true;
622
+ this.personMaskTs = tsUs;
623
+ this.personWorkerMs = ms;
624
+ return;
625
+ }
539
626
  this.uploadClassMask(width, height, data);
627
+ this.classMaskTs = tsUs;
540
628
  this.maskWorkerMs = ms;
541
629
  },
542
630
  failed: (k, reason) => {
543
- console.warn(`mediakit: ${k} detection moves into this thread:`, reason);
544
- this.inThread.add(k);
545
- if (k === "face") {
631
+ console.warn(`mediakit: ${key} detection moves into this thread:`, reason);
632
+ this.inThread.add(key);
633
+ if (key === "person") {
634
+ this.personRemote = false;
635
+ } else if (k === "face") {
546
636
  this.faceRemote = false;
547
637
  void this.ensureFace();
548
638
  } else {
@@ -550,53 +640,64 @@ var Engine = class _Engine {
550
640
  void this.ensureClassSegmenter();
551
641
  }
552
642
  }
553
- });
554
- try {
555
- await init(this.detect);
556
- } catch (e) {
557
- this.inThread.add(kind);
558
- throw e;
559
- }
560
- if (this.closed) throw new Error("closed");
643
+ };
561
644
  }
562
- // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
563
645
  uploadClassMask(width, height, data) {
646
+ this.classMaskTex = this.uploadMaskBytes(this.classMaskTex, width, height, data);
647
+ this.classMaskFresh = true;
648
+ }
649
+ // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
650
+ uploadMaskBytes(tex, width, height, data) {
564
651
  const gl = this.gl;
565
- if (!this.classMaskTex) {
566
- this.classMaskTex = gl.createTexture();
567
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
652
+ if (!tex) {
653
+ tex = gl.createTexture();
654
+ gl.bindTexture(gl.TEXTURE_2D, tex);
568
655
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
569
656
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
570
657
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
571
658
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
572
659
  }
573
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
660
+ gl.bindTexture(gl.TEXTURE_2D, tex);
574
661
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
575
662
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
576
663
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
577
664
  gl.bindTexture(gl.TEXTURE_2D, null);
578
- this.classMaskFresh = true;
665
+ return tex;
579
666
  }
580
667
  /**
581
668
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
582
669
  * detection drains Chrome's few capture buffers and throttles the camera itself.
583
670
  */
584
671
  requestRemote(kind, source, timestampUs) {
672
+ const detect = this.detects.get(kind);
673
+ if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
585
674
  let frame = null;
586
675
  try {
587
- frame = new VideoFrame(source instanceof VideoFrame ? this.detectCopy(source) : source, {
676
+ const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
677
+ frame = new VideoFrame(copyable ? this.detectCopy(source, timestampUs) : source, {
588
678
  timestamp: timestampUs
589
679
  });
590
680
  } catch {
591
681
  }
592
- if (frame) this.detect?.request(kind, frame, timestampUs);
593
- }
594
- detectCopy(source) {
595
- const s = Math.min(1, 512 / Math.max(source.displayWidth, source.displayHeight));
596
- const w = Math.max(1, Math.round(source.displayWidth * s));
597
- const h = Math.max(1, Math.round(source.displayHeight * s));
598
- if (!this.detectCanvas || this.detectCanvas.width !== w || this.detectCanvas.height !== h) this.detectCanvas = new OffscreenCanvas(w, h);
599
- this.detectCanvas.getContext("2d").drawImage(source, 0, 0, w, h);
682
+ if (frame && detect.request(kind === "face" ? "face" : "mask", frame, timestampUs)) {
683
+ this.sent.set(kind, { ts: timestampUs, at: performance.now() });
684
+ }
685
+ }
686
+ /** Face and mask asked on the same frame share one draw. */
687
+ detectCopy(source, timestampUs) {
688
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
689
+ const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
690
+ const s = Math.min(1, 512 / Math.max(sw, sh));
691
+ const w = Math.max(1, Math.round(sw * s));
692
+ const h = Math.max(1, Math.round(sh * s));
693
+ if (!this.detectCanvas || this.detectCanvas.width !== w || this.detectCanvas.height !== h) {
694
+ this.detectCanvas = new OffscreenCanvas(w, h);
695
+ this.detectCanvasTs = -1;
696
+ }
697
+ if (this.detectCanvasTs !== timestampUs) {
698
+ this.detectCanvas.getContext("2d").drawImage(source, 0, 0, w, h);
699
+ this.detectCanvasTs = timestampUs;
700
+ }
600
701
  return this.detectCanvas;
601
702
  }
602
703
  ensureClassSegmenter() {
@@ -637,8 +738,7 @@ var Engine = class _Engine {
637
738
  }
638
739
  /**
639
740
  * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
640
- * yet, the segmenter is still loading, or the recipe is inactive; the transport must
641
- * forward the original frame rather than drop it.
741
+ * yet, the segmenter is still loading, or the recipe is inactive.
642
742
  *
643
743
  * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
644
744
  * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
@@ -650,23 +750,110 @@ var Engine = class _Engine {
650
750
  */
651
751
  render(source, timestampUs) {
652
752
  if (this.closed) return false;
753
+ if (this.lastHeld) this.spare.push(this.lastHeld);
754
+ this.lastHeld = null;
755
+ this.swallowed = false;
756
+ if (this.prevTs >= 0 && timestampUs > this.prevTs) {
757
+ this.gapUs += (Math.min(timestampUs - this.prevTs, 2e5) - this.gapUs) * 0.1;
758
+ }
759
+ this.prevTs = timestampUs;
760
+ if (!this.syncing() || typeof ImageData !== "undefined" && source instanceof ImageData) {
761
+ this.releaseHeld();
762
+ this.renderedTs = timestampUs;
763
+ return this.draw(source, timestampUs, false);
764
+ }
765
+ this.requestRemote("face", source, timestampUs);
766
+ const remoteMask = this.remoteMaskKind();
767
+ if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
768
+ this.queue.push({ c: this.hold(source), ts: timestampUs });
769
+ this.retuneDepth();
770
+ if (this.queue.length <= this.holdDepth) {
771
+ this.swallowed = true;
772
+ return false;
773
+ }
774
+ while (this.queue.length > this.holdDepth + 1) this.spare.push(this.queue.shift().c);
775
+ const front = this.queue.shift();
776
+ this.lastHeld = front.c;
777
+ this.renderedTs = front.ts;
778
+ return this.draw(front.c, front.ts, true);
779
+ }
780
+ remoteMaskKind() {
781
+ if (this.personRemote && this.personRemoteWanted(this.filter, this.effects)) return "person";
782
+ if (this.classRemote && needsSkinClasses(this.filter, this.effects)) return "mask";
783
+ return null;
784
+ }
785
+ retuneDepth() {
786
+ const kind = this.remoteMaskKind();
787
+ const latency = Math.max(this.faceLatencyMs, kind ? this.maskLatencyMs.get(kind) ?? 0 : 0);
788
+ const want = latency > 0 ? Math.min(MAX_HOLD, Math.max(1, Math.ceil(latency * 1e3 / this.gapUs))) : 1;
789
+ if (want === this.holdDepth) {
790
+ this.depthVotes = 0;
791
+ return;
792
+ }
793
+ if (++this.depthVotes >= DEPTH_VOTES) {
794
+ this.holdDepth = want;
795
+ this.depthVotes = 0;
796
+ }
797
+ }
798
+ took(kind, tsUs) {
799
+ const s = this.sent.get(kind);
800
+ if (s?.ts !== tsUs) return null;
801
+ this.sent.delete(kind);
802
+ return performance.now() - s.at;
803
+ }
804
+ releaseHeld() {
805
+ for (const h of this.queue) this.spare.push(h.c);
806
+ this.queue = [];
807
+ }
808
+ dropped() {
809
+ return this.swallowed;
810
+ }
811
+ passthrough() {
812
+ return this.lastHeld ? new VideoFrame(this.lastHeld, { timestamp: this.renderedTs }) : null;
813
+ }
814
+ syncing() {
815
+ return this.syncFaces && this.faceRemote && needsFace(this.effects);
816
+ }
817
+ hold(source) {
818
+ const [w, h] = sourceSize(source);
819
+ let c = this.spare.pop();
820
+ while (c && (c.width !== w || c.height !== h)) c = this.spare.pop();
821
+ c ??= new OffscreenCanvas(w, h);
822
+ c.getContext("2d").drawImage(source, 0, 0, w, h);
823
+ return c;
824
+ }
825
+ draw(source, timestampUs, faceDone) {
653
826
  const t0 = performance.now();
654
827
  const [lo, hi] = splitMicros(timestampUs);
655
828
  const needSeg = this.core.decide(lo, hi, this.prevTotalMs, this.prevSegMs) === 1;
656
829
  let mask = null;
657
830
  let maskKind = 0;
831
+ let maskTs = timestampUs;
658
832
  let segMs = 0;
659
833
  let faceMs = 0;
660
834
  this.used = null;
661
835
  let served = false;
662
- if (needSeg && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
663
- this.requestRemote("mask", source, timestampUs);
836
+ const remoteMask = this.remoteMaskKind();
837
+ if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
838
+ if (remoteMask === "person") {
839
+ if (this.personMaskTex) {
840
+ served = true;
841
+ if (this.personMaskFresh) {
842
+ this.personMaskFresh = false;
843
+ mask = this.personMaskTex;
844
+ maskTs = this.personMaskTs;
845
+ segMs = this.personWorkerMs;
846
+ }
847
+ }
848
+ }
849
+ if (remoteMask === "mask") {
664
850
  if (this.classMaskTex) {
665
851
  served = true;
666
852
  if (this.classMaskFresh) {
667
853
  this.classMaskFresh = false;
668
854
  mask = this.classMaskTex;
669
855
  maskKind = 1;
856
+ maskTs = this.classMaskTs;
670
857
  segMs = this.maskWorkerMs;
671
858
  }
672
859
  }
@@ -684,9 +871,13 @@ var Engine = class _Engine {
684
871
  maskKind = classes ? 1 : 0;
685
872
  }
686
873
  }
687
- if (this.core.decideFace() === 1) {
874
+ if (faceDone) {
875
+ faceMs = this.faceWorkerMs;
876
+ } else if (this.faceRemote && needsFace(this.effects)) {
877
+ this.requestRemote("face", source, timestampUs);
878
+ faceMs = this.faceWorkerMs;
879
+ } else if (this.core.decideFace() === 1) {
688
880
  if (this.faceRemote) {
689
- this.requestRemote("face", source, timestampUs);
690
881
  faceMs = this.faceWorkerMs;
691
882
  } else if (!this.face) {
692
883
  void this.ensureFace();
@@ -695,9 +886,12 @@ var Engine = class _Engine {
695
886
  const n = this.face.detect(source, timestampUs / 1e3, this.lmBuf);
696
887
  faceMs = performance.now() - f0;
697
888
  this.core.setFace(lo, hi, n);
889
+ this.faceTs = timestampUs;
698
890
  }
699
891
  }
700
- const glCalls = this.core.process(source, mask, this.background, maskKind);
892
+ if (mask) this.maskUsedTs = maskTs;
893
+ const [maskLo, maskHi] = splitMicros(maskTs);
894
+ const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
701
895
  if (mask) this.used?.release();
702
896
  this.used = null;
703
897
  this.prevSegMs = segMs;
@@ -719,7 +913,10 @@ var Engine = class _Engine {
719
913
  faceSize: s ? s[9] : 0,
720
914
  needsFace: s ? s[10] > 0.5 : false,
721
915
  autoExposure: s ? s[11] : 0,
722
- faces: s ? s[12] : 0
916
+ faces: s ? s[12] : 0,
917
+ heldFrames: faceDone ? this.holdDepth : 0,
918
+ faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
919
+ maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0
723
920
  };
724
921
  return glCalls > 0;
725
922
  }
@@ -744,13 +941,19 @@ var Engine = class _Engine {
744
941
  this.classSegmenter = null;
745
942
  this.face?.close();
746
943
  this.face = null;
747
- this.detect?.close();
748
- this.detect = null;
944
+ for (const detect of this.detects.values()) detect.close();
945
+ this.detects.clear();
749
946
  this.faceRemote = false;
750
947
  this.classRemote = false;
751
948
  if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
949
+ if (this.personMaskTex) this.gl.deleteTexture(this.personMaskTex);
950
+ this.personMaskTex = null;
951
+ this.personRemote = false;
752
952
  this.classMaskTex = null;
753
953
  this.lmBuf = null;
954
+ this.queue = [];
955
+ this.spare = [];
956
+ this.lastHeld = null;
754
957
  this.core.close();
755
958
  this.background?.close();
756
959
  this.background = null;
@@ -830,6 +1033,7 @@ var VideoPipeline = class {
830
1033
  filter;
831
1034
  effects;
832
1035
  opts;
1036
+ debug = "off";
833
1037
  // Health: a beat per frame out.
834
1038
  source = null;
835
1039
  size = { width: 1280, height: 720, fps: 30 };
@@ -859,6 +1063,7 @@ var VideoPipeline = class {
859
1063
  this.filter = filter;
860
1064
  this.effects = effects;
861
1065
  this.opts = opts;
1066
+ this.debug = opts.debug ?? "off";
862
1067
  }
863
1068
  /** Whether frames are coming out, and how long since the last one. */
864
1069
  get health() {
@@ -983,6 +1188,8 @@ var VideoPipeline = class {
983
1188
  async startMain(source) {
984
1189
  const { width, height, fps } = this.size;
985
1190
  this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces);
1191
+ this.engine.syncFaces = this.opts.syncFaces ?? false;
1192
+ this.engine.setDebug(this.debug);
986
1193
  this.transport = hasInsertableStreams() ? "insertable" : "canvas";
987
1194
  this.frames = 0;
988
1195
  this.lastBeat = performance.now();
@@ -998,6 +1205,18 @@ var VideoPipeline = class {
998
1205
  this.filter = filter;
999
1206
  await this.pushRecipe();
1000
1207
  }
1208
+ /**
1209
+ * Draw an inner layer instead of the picture: "skin" (red smoothing, green whitening, blue face
1210
+ * mesh), "mask" (the person or class mask) or "face" (tracked outlines and necks). "off" restores it.
1211
+ */
1212
+ setDebug(view) {
1213
+ this.debug = view;
1214
+ if (this.worker) this.send({ t: "debug", view });
1215
+ else this.engine?.setDebug(view);
1216
+ }
1217
+ get debugView() {
1218
+ return this.debug;
1219
+ }
1001
1220
  /** Change the effects outside the background. */
1002
1221
  async setEffects(effects) {
1003
1222
  this.effects = effects;
@@ -1107,7 +1326,9 @@ var VideoPipeline = class {
1107
1326
  effects: this.effects,
1108
1327
  background,
1109
1328
  alpha: this.opts.alpha,
1110
- maxFaces: this.opts.maxFaces
1329
+ maxFaces: this.opts.maxFaces,
1330
+ syncFaces: this.opts.syncFaces,
1331
+ debug: this.debug
1111
1332
  },
1112
1333
  background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
1113
1334
  )
@@ -1132,7 +1353,9 @@ var VideoPipeline = class {
1132
1353
  effects: this.effects,
1133
1354
  background,
1134
1355
  alpha: this.opts.alpha,
1135
- maxFaces: this.opts.maxFaces
1356
+ maxFaces: this.opts.maxFaces,
1357
+ syncFaces: this.opts.syncFaces,
1358
+ debug: this.debug
1136
1359
  },
1137
1360
  background ? [clone, background] : [clone]
1138
1361
  )
@@ -1218,10 +1441,15 @@ var VideoPipeline = class {
1218
1441
  transform: (frame, controller) => {
1219
1442
  this.beat();
1220
1443
  try {
1221
- if (engine.render(frame, frame.timestamp)) {
1222
- controller.enqueue(engine.capture(frame.timestamp));
1223
- if (this.frameSubs.size > 0) this.deliver(engine.capture(frame.timestamp, true));
1224
- } else {
1444
+ const drew = engine.render(frame, frame.timestamp);
1445
+ const held = drew ? null : engine.passthrough();
1446
+ if (drew) {
1447
+ controller.enqueue(engine.capture(engine.renderedTs));
1448
+ if (this.frameSubs.size > 0) this.deliver(engine.capture(engine.renderedTs, true));
1449
+ } else if (held) {
1450
+ if (this.frameSubs.size > 0) this.deliver(held.clone());
1451
+ controller.enqueue(held);
1452
+ } else if (!engine.dropped()) {
1225
1453
  if (this.frameSubs.size > 0) this.deliver(frame.clone());
1226
1454
  controller.enqueue(frame);
1227
1455
  return;
@@ -2629,6 +2857,7 @@ var FACE_UV = new Float32Array([
2629
2857
  ]);
2630
2858
  export {
2631
2859
  BLEND_MODES,
2860
+ DEBUG_VIEWS,
2632
2861
  EFFECTS_SCHEMA,
2633
2862
  Engine,
2634
2863
  FACE_UV,