@tradalab/mediakit 2.2.0 → 2.4.1

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 {
@@ -84,9 +90,18 @@ declare class Engine {
84
90
  private classMaskTs;
85
91
  syncFaces: boolean;
86
92
  renderedTs: number;
87
- private held;
88
- private heldTs;
89
- private heldSlot;
93
+ private queue;
94
+ private spare;
95
+ private holdDepth;
96
+ private depthVotes;
97
+ private gapUs;
98
+ private prevTs;
99
+ private readonly sent;
100
+ private readonly lastSentAt;
101
+ private faceLatencyMs;
102
+ private readonly maskLatencyMs;
103
+ private faceTs;
104
+ private maskUsedTs;
90
105
  private lastHeld;
91
106
  private swallowed;
92
107
  private maskWorkerMs;
@@ -120,6 +135,8 @@ declare class Engine {
120
135
  static on(canvas: EngineCanvas, filter: BgFilter, effects?: Effects, background?: ImageBitmap, alpha?: boolean, maxFaces?: number): Promise<Engine>;
121
136
  get loading(): boolean;
122
137
  get outputCanvas(): EngineCanvas;
138
+ /** Draws an inner layer instead of the picture until set back to "off". */
139
+ setDebug(view: DebugView): void;
123
140
  /**
124
141
  * Change the recipe without rebuilding the pipeline, so dragging a slider does not flash.
125
142
  *
@@ -158,6 +175,11 @@ declare class Engine {
158
175
  * it constructs one only to destroy it again.
159
176
  */
160
177
  render(source: TexImageSource, timestampUs: number): boolean;
178
+ private remoteMaskKind;
179
+ private retuneDepth;
180
+ private dutyAllows;
181
+ private took;
182
+ private releaseHeld;
161
183
  dropped(): boolean;
162
184
  passthrough(): VideoFrame | null;
163
185
  private syncing;
@@ -212,6 +234,8 @@ interface PipelineOptions {
212
234
  */
213
235
  maxFaces?: number;
214
236
  syncFaces?: boolean;
237
+ /** Starts with an inner layer drawn instead of the picture; see `setDebug`. */
238
+ debug?: DebugView;
215
239
  /** No processed frame for 2 s while the camera is live (20 s while a detector loads). */
216
240
  onStall?: (info: {
217
241
  transport: Transport;
@@ -236,6 +260,7 @@ declare class VideoPipeline {
236
260
  private filter;
237
261
  private effects;
238
262
  private opts;
263
+ private debug;
239
264
  private source;
240
265
  private size;
241
266
  private lastBeat;
@@ -274,6 +299,12 @@ declare class VideoPipeline {
274
299
  private startMain;
275
300
  /** Swap the background in place - no pipeline rebuild, so the picture does not flash. */
276
301
  switchTo(filter: BgFilter): Promise<void>;
302
+ /**
303
+ * Draw an inner layer instead of the picture: "skin" (red smoothing, green whitening, blue face
304
+ * mesh), "mask" (the person or class mask) or "face" (tracked outlines and necks). "off" restores it.
305
+ */
306
+ setDebug(view: DebugView): void;
307
+ get debugView(): DebugView;
277
308
  /** Change the effects outside the background. */
278
309
  setEffects(effects: Effects): Promise<void>;
279
310
  private pushRecipe;
@@ -467,4 +498,4 @@ declare function renderText(text: string, style?: TextStyle): HTMLCanvasElement;
467
498
  /** Where each of the face landmarker's first 468 landmarks lies on the canonical face texture. */
468
499
  declare const FACE_UV: Float32Array<ArrayBuffer>;
469
500
 
470
- 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 };
501
+ 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-2AD2GLNR.js";
15
+ } from "./chunk-YW75KJJO.js";
14
16
  import {
15
17
  BLEND_MODES,
16
18
  TRANSITIONS,
@@ -298,8 +300,14 @@ var ZERO_STATS = {
298
300
  faceSize: 0,
299
301
  needsFace: false,
300
302
  autoExposure: 0,
301
- faces: 0
303
+ faces: 0,
304
+ heldFrames: 0,
305
+ faceAgeMs: 0,
306
+ maskAgeMs: 0
302
307
  };
308
+ var MAX_HOLD = 2;
309
+ var DEPTH_VOTES = 15;
310
+ var DETECT_DUTY = 0.6;
303
311
  function sourceSize(source) {
304
312
  if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
305
313
  if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
@@ -353,9 +361,18 @@ var Engine = class _Engine {
353
361
  classMaskTs = 0;
354
362
  syncFaces = false;
355
363
  renderedTs = 0;
356
- held = [null, null];
357
- heldTs = -1;
358
- heldSlot = 0;
364
+ queue = [];
365
+ spare = [];
366
+ holdDepth = 1;
367
+ depthVotes = 0;
368
+ gapUs = 33333;
369
+ prevTs = -1;
370
+ sent = /* @__PURE__ */ new Map();
371
+ lastSentAt = /* @__PURE__ */ new Map();
372
+ faceLatencyMs = 0;
373
+ maskLatencyMs = /* @__PURE__ */ new Map();
374
+ faceTs = -1;
375
+ maskUsedTs = -1;
359
376
  lastHeld = null;
360
377
  swallowed = false;
361
378
  maskWorkerMs = 0;
@@ -437,6 +454,11 @@ var Engine = class _Engine {
437
454
  get outputCanvas() {
438
455
  return this.canvas;
439
456
  }
457
+ /** Draws an inner layer instead of the picture until set back to "off". */
458
+ setDebug(view) {
459
+ if (this.closed) return;
460
+ this.core.setDebug(debugCode(view));
461
+ }
440
462
  /**
441
463
  * Change the recipe without rebuilding the pipeline, so dragging a slider does not flash.
442
464
  *
@@ -585,9 +607,17 @@ var Engine = class _Engine {
585
607
  const [lo, hi] = splitMicros(tsUs);
586
608
  this.core.setFace(lo, hi, n);
587
609
  this.faceWorkerMs = ms;
610
+ this.faceTs = tsUs;
611
+ const took = this.took("face", tsUs);
612
+ if (took !== null) this.faceLatencyMs = this.faceLatencyMs ? this.faceLatencyMs + (took - this.faceLatencyMs) * 0.2 : took;
588
613
  },
589
614
  mask: (tsUs, width, height, data, ms) => {
590
615
  if (this.closed) return;
616
+ const took = this.took(key, tsUs);
617
+ if (took !== null) {
618
+ const was = this.maskLatencyMs.get(key);
619
+ this.maskLatencyMs.set(key, was ? was + (took - was) * 0.2 : took);
620
+ }
591
621
  if (key === "person") {
592
622
  this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, width, height, data);
593
623
  this.personMaskFresh = true;
@@ -643,6 +673,7 @@ var Engine = class _Engine {
643
673
  requestRemote(kind, source, timestampUs) {
644
674
  const detect = this.detects.get(kind);
645
675
  if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
676
+ if (!this.dutyAllows(kind)) return;
646
677
  let frame = null;
647
678
  try {
648
679
  const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
@@ -651,7 +682,11 @@ var Engine = class _Engine {
651
682
  });
652
683
  } catch {
653
684
  }
654
- if (frame) detect.request(kind === "face" ? "face" : "mask", frame, timestampUs);
685
+ if (frame && detect.request(kind === "face" ? "face" : "mask", frame, timestampUs)) {
686
+ const now2 = performance.now();
687
+ this.sent.set(kind, { ts: timestampUs, at: now2 });
688
+ this.lastSentAt.set(kind, now2);
689
+ }
655
690
  }
656
691
  /** Face and mask asked on the same frame share one draw. */
657
692
  detectCopy(source, timestampUs) {
@@ -720,26 +755,66 @@ var Engine = class _Engine {
720
755
  */
721
756
  render(source, timestampUs) {
722
757
  if (this.closed) return false;
758
+ if (this.lastHeld) this.spare.push(this.lastHeld);
723
759
  this.lastHeld = null;
724
760
  this.swallowed = false;
761
+ if (this.prevTs >= 0 && timestampUs > this.prevTs) {
762
+ this.gapUs += (Math.min(timestampUs - this.prevTs, 2e5) - this.gapUs) * 0.1;
763
+ }
764
+ this.prevTs = timestampUs;
725
765
  if (!this.syncing() || typeof ImageData !== "undefined" && source instanceof ImageData) {
726
- this.heldTs = -1;
766
+ this.releaseHeld();
727
767
  this.renderedTs = timestampUs;
728
768
  return this.draw(source, timestampUs, false);
729
769
  }
730
770
  this.requestRemote("face", source, timestampUs);
731
- const prev = this.heldTs >= 0 ? this.held[this.heldSlot] : null;
732
- const prevTs = this.heldTs;
733
- this.heldSlot ^= 1;
734
- this.hold(source, this.heldSlot);
735
- this.heldTs = timestampUs;
736
- if (!prev) {
771
+ const remoteMask = this.remoteMaskKind();
772
+ if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
773
+ this.queue.push({ c: this.hold(source), ts: timestampUs });
774
+ this.retuneDepth();
775
+ if (this.queue.length <= this.holdDepth) {
737
776
  this.swallowed = true;
738
777
  return false;
739
778
  }
740
- this.lastHeld = prev;
741
- this.renderedTs = prevTs;
742
- return this.draw(prev, prevTs, true);
779
+ while (this.queue.length > this.holdDepth + 1) this.spare.push(this.queue.shift().c);
780
+ const front = this.queue.shift();
781
+ this.lastHeld = front.c;
782
+ this.renderedTs = front.ts;
783
+ return this.draw(front.c, front.ts, true);
784
+ }
785
+ remoteMaskKind() {
786
+ if (this.personRemote && this.personRemoteWanted(this.filter, this.effects)) return "person";
787
+ if (this.classRemote && needsSkinClasses(this.filter, this.effects)) return "mask";
788
+ return null;
789
+ }
790
+ retuneDepth() {
791
+ const kind = this.remoteMaskKind();
792
+ const latency = Math.max(this.faceLatencyMs, kind ? this.maskLatencyMs.get(kind) ?? 0 : 0);
793
+ const want = latency > 0 ? Math.min(MAX_HOLD, Math.max(1, Math.ceil(latency * 1e3 / this.gapUs))) : 1;
794
+ if (want === this.holdDepth) {
795
+ this.depthVotes = 0;
796
+ return;
797
+ }
798
+ if (++this.depthVotes >= DEPTH_VOTES) {
799
+ this.holdDepth = want;
800
+ this.depthVotes = 0;
801
+ }
802
+ }
803
+ dutyAllows(kind) {
804
+ const took = kind === "face" ? this.faceLatencyMs : this.maskLatencyMs.get(kind) ?? 0;
805
+ if (took * 1e3 < this.gapUs) return true;
806
+ const last = this.lastSentAt.get(kind);
807
+ return last === void 0 || performance.now() - last >= took / DETECT_DUTY;
808
+ }
809
+ took(kind, tsUs) {
810
+ const s = this.sent.get(kind);
811
+ if (s?.ts !== tsUs) return null;
812
+ this.sent.delete(kind);
813
+ return performance.now() - s.at;
814
+ }
815
+ releaseHeld() {
816
+ for (const h of this.queue) this.spare.push(h.c);
817
+ this.queue = [];
743
818
  }
744
819
  dropped() {
745
820
  return this.swallowed;
@@ -750,14 +825,13 @@ var Engine = class _Engine {
750
825
  syncing() {
751
826
  return this.syncFaces && this.faceRemote && needsFace(this.effects);
752
827
  }
753
- hold(source, slot) {
828
+ hold(source) {
754
829
  const [w, h] = sourceSize(source);
755
- let c = this.held[slot];
756
- if (!c || c.width !== w || c.height !== h) {
757
- c = new OffscreenCanvas(w, h);
758
- this.held[slot] = c;
759
- }
830
+ let c = this.spare.pop();
831
+ while (c && (c.width !== w || c.height !== h)) c = this.spare.pop();
832
+ c ??= new OffscreenCanvas(w, h);
760
833
  c.getContext("2d").drawImage(source, 0, 0, w, h);
834
+ return c;
761
835
  }
762
836
  draw(source, timestampUs, faceDone) {
763
837
  const t0 = performance.now();
@@ -770,8 +844,9 @@ var Engine = class _Engine {
770
844
  let faceMs = 0;
771
845
  this.used = null;
772
846
  let served = false;
773
- if (needSeg && this.personRemote && this.personRemoteWanted(this.filter, this.effects)) {
774
- this.requestRemote("person", source, timestampUs);
847
+ const remoteMask = this.remoteMaskKind();
848
+ if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
849
+ if (remoteMask === "person") {
775
850
  if (this.personMaskTex) {
776
851
  served = true;
777
852
  if (this.personMaskFresh) {
@@ -782,8 +857,7 @@ var Engine = class _Engine {
782
857
  }
783
858
  }
784
859
  }
785
- if (needSeg && !served && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
786
- this.requestRemote("mask", source, timestampUs);
860
+ if (remoteMask === "mask") {
787
861
  if (this.classMaskTex) {
788
862
  served = true;
789
863
  if (this.classMaskFresh) {
@@ -810,9 +884,11 @@ var Engine = class _Engine {
810
884
  }
811
885
  if (faceDone) {
812
886
  faceMs = this.faceWorkerMs;
887
+ } else if (this.faceRemote && needsFace(this.effects)) {
888
+ this.requestRemote("face", source, timestampUs);
889
+ faceMs = this.faceWorkerMs;
813
890
  } else if (this.core.decideFace() === 1) {
814
891
  if (this.faceRemote) {
815
- this.requestRemote("face", source, timestampUs);
816
892
  faceMs = this.faceWorkerMs;
817
893
  } else if (!this.face) {
818
894
  void this.ensureFace();
@@ -821,8 +897,10 @@ var Engine = class _Engine {
821
897
  const n = this.face.detect(source, timestampUs / 1e3, this.lmBuf);
822
898
  faceMs = performance.now() - f0;
823
899
  this.core.setFace(lo, hi, n);
900
+ this.faceTs = timestampUs;
824
901
  }
825
902
  }
903
+ if (mask) this.maskUsedTs = maskTs;
826
904
  const [maskLo, maskHi] = splitMicros(maskTs);
827
905
  const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
828
906
  if (mask) this.used?.release();
@@ -846,7 +924,10 @@ var Engine = class _Engine {
846
924
  faceSize: s ? s[9] : 0,
847
925
  needsFace: s ? s[10] > 0.5 : false,
848
926
  autoExposure: s ? s[11] : 0,
849
- faces: s ? s[12] : 0
927
+ faces: s ? s[12] : 0,
928
+ heldFrames: faceDone ? this.holdDepth : 0,
929
+ faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
930
+ maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0
850
931
  };
851
932
  return glCalls > 0;
852
933
  }
@@ -881,7 +962,8 @@ var Engine = class _Engine {
881
962
  this.personRemote = false;
882
963
  this.classMaskTex = null;
883
964
  this.lmBuf = null;
884
- this.held = [null, null];
965
+ this.queue = [];
966
+ this.spare = [];
885
967
  this.lastHeld = null;
886
968
  this.core.close();
887
969
  this.background?.close();
@@ -962,6 +1044,7 @@ var VideoPipeline = class {
962
1044
  filter;
963
1045
  effects;
964
1046
  opts;
1047
+ debug = "off";
965
1048
  // Health: a beat per frame out.
966
1049
  source = null;
967
1050
  size = { width: 1280, height: 720, fps: 30 };
@@ -991,6 +1074,7 @@ var VideoPipeline = class {
991
1074
  this.filter = filter;
992
1075
  this.effects = effects;
993
1076
  this.opts = opts;
1077
+ this.debug = opts.debug ?? "off";
994
1078
  }
995
1079
  /** Whether frames are coming out, and how long since the last one. */
996
1080
  get health() {
@@ -1116,6 +1200,7 @@ var VideoPipeline = class {
1116
1200
  const { width, height, fps } = this.size;
1117
1201
  this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces);
1118
1202
  this.engine.syncFaces = this.opts.syncFaces ?? false;
1203
+ this.engine.setDebug(this.debug);
1119
1204
  this.transport = hasInsertableStreams() ? "insertable" : "canvas";
1120
1205
  this.frames = 0;
1121
1206
  this.lastBeat = performance.now();
@@ -1131,6 +1216,18 @@ var VideoPipeline = class {
1131
1216
  this.filter = filter;
1132
1217
  await this.pushRecipe();
1133
1218
  }
1219
+ /**
1220
+ * Draw an inner layer instead of the picture: "skin" (red smoothing, green whitening, blue face
1221
+ * mesh), "mask" (the person or class mask) or "face" (tracked outlines and necks). "off" restores it.
1222
+ */
1223
+ setDebug(view) {
1224
+ this.debug = view;
1225
+ if (this.worker) this.send({ t: "debug", view });
1226
+ else this.engine?.setDebug(view);
1227
+ }
1228
+ get debugView() {
1229
+ return this.debug;
1230
+ }
1134
1231
  /** Change the effects outside the background. */
1135
1232
  async setEffects(effects) {
1136
1233
  this.effects = effects;
@@ -1241,7 +1338,8 @@ var VideoPipeline = class {
1241
1338
  background,
1242
1339
  alpha: this.opts.alpha,
1243
1340
  maxFaces: this.opts.maxFaces,
1244
- syncFaces: this.opts.syncFaces
1341
+ syncFaces: this.opts.syncFaces,
1342
+ debug: this.debug
1245
1343
  },
1246
1344
  background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
1247
1345
  )
@@ -1267,7 +1365,8 @@ var VideoPipeline = class {
1267
1365
  background,
1268
1366
  alpha: this.opts.alpha,
1269
1367
  maxFaces: this.opts.maxFaces,
1270
- syncFaces: this.opts.syncFaces
1368
+ syncFaces: this.opts.syncFaces,
1369
+ debug: this.debug
1271
1370
  },
1272
1371
  background ? [clone, background] : [clone]
1273
1372
  )
@@ -2769,6 +2868,7 @@ var FACE_UV = new Float32Array([
2769
2868
  ]);
2770
2869
  export {
2771
2870
  BLEND_MODES,
2871
+ DEBUG_VIEWS,
2772
2872
  EFFECTS_SCHEMA,
2773
2873
  Engine,
2774
2874
  FACE_UV,