@tradalab/mediakit 2.0.0 → 2.1.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
@@ -16,6 +16,8 @@ interface FrameStats {
16
16
  totalMs: number;
17
17
  /** How much of that was segmentation. */
18
18
  segMs: number;
19
+ /** The last landmark detection; in its worker it no longer holds up the frame. */
20
+ faceMs: number;
19
21
  /** WebGL call count - the P0.2 gate in doc/apps/mediakit/PLAN.md. */
20
22
  glCalls: number;
21
23
  /** Whether this frame ran segmentation or reused the previous mask. */
@@ -74,7 +76,17 @@ declare class Engine {
74
76
  * their background has no reason to download it, and the other way round.
75
77
  */
76
78
  private face;
79
+ private faceRemote;
80
+ private faceWorkerMs;
81
+ private classRemote;
82
+ private classMaskTex;
83
+ private classMaskFresh;
84
+ private maskWorkerMs;
85
+ private detect;
86
+ private detectCanvas;
87
+ private readonly inThread;
77
88
  private faceLoading;
89
+ private maxFaces;
78
90
  private lmBuf;
79
91
  private filter;
80
92
  private effects;
@@ -83,13 +95,14 @@ declare class Engine {
83
95
  last: FrameStats;
84
96
  private constructor();
85
97
  /** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */
86
- static create(width: number, height: number, filter: BgFilter, effects?: Effects, alpha?: boolean): Promise<Engine>;
98
+ static create(width: number, height: number, filter: BgFilter, effects?: Effects, alpha?: boolean, maxFaces?: number): Promise<Engine>;
87
99
  /**
88
100
  * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
89
101
  * only a `cutout` background writes; it is fixed for the life of the context, so a host that
90
- * may switch to `cutout` later has to ask for it here.
102
+ * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
103
+ * landmarker looks for: below 3 it skips re-running its face detector on every call.
91
104
  */
92
- static on(canvas: EngineCanvas, filter: BgFilter, effects?: Effects, background?: ImageBitmap, alpha?: boolean): Promise<Engine>;
105
+ static on(canvas: EngineCanvas, filter: BgFilter, effects?: Effects, background?: ImageBitmap, alpha?: boolean, maxFaces?: number): Promise<Engine>;
93
106
  get loading(): boolean;
94
107
  get outputCanvas(): EngineCanvas;
95
108
  /**
@@ -101,6 +114,15 @@ declare class Engine {
101
114
  */
102
115
  setRecipe(filter: BgFilter, effects?: Effects, background?: ImageBitmap): Promise<void>;
103
116
  private ensureFace;
117
+ /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
118
+ private remote;
119
+ private uploadClassMask;
120
+ /**
121
+ * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
122
+ * detection drains Chrome's few capture buffers and throttles the camera itself.
123
+ */
124
+ private requestRemote;
125
+ private detectCopy;
104
126
  private ensureClassSegmenter;
105
127
  private ensureSegmenter;
106
128
  /**
@@ -160,6 +182,11 @@ type Transport = "worker" | "insertable" | "canvas";
160
182
  interface PipelineOptions {
161
183
  /** Keep the output's alpha channel, for `subscribeFrames` with a `cutout` background. */
162
184
  alpha?: boolean;
185
+ /**
186
+ * Faces to track, 1-3, default 3. One person per camera should say 1: looking for more re-runs
187
+ * the face detector on every call, about a third of the landmark cost.
188
+ */
189
+ maxFaces?: number;
163
190
  /** No processed frame for 2 s while the camera is live (20 s while a detector loads). */
164
191
  onStall?: (info: {
165
192
  transport: Transport;
package/dist/index.js CHANGED
@@ -74,10 +74,10 @@ import { FaceLandmarker, FilesetResolver as FilesetResolver2 } from "@mediapipe/
74
74
  var WASM_DIR2 = "/mediakit/mp";
75
75
  var MODEL_URL2 = "/mediakit/face_landmarker.task";
76
76
  var FACE_FLOATS = 478 * 3;
77
- async function createFaceDetector(canvas, maxFaces) {
77
+ async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
78
78
  const fileset = await FilesetResolver2.forVisionTasks(WASM_DIR2);
79
79
  const landmarker = await FaceLandmarker.createFromOptions(fileset, {
80
- baseOptions: { modelAssetPath: MODEL_URL2, delegate: "GPU" },
80
+ baseOptions: { modelAssetPath: MODEL_URL2, delegate },
81
81
  canvas,
82
82
  runningMode: "VIDEO",
83
83
  // As many as the core tracks: one landmark pass returns them all, so the cost of a second
@@ -109,6 +109,102 @@ async function createFaceDetector(canvas, maxFaces) {
109
109
  };
110
110
  }
111
111
 
112
+ // src/detect-remote.ts
113
+ var DETECT_WORKER_URL = "/mediakit/detect-worker.js";
114
+ var READY_MS = 2e4;
115
+ var DetectWorker = class {
116
+ constructor(on) {
117
+ this.on = on;
118
+ this.worker = new Worker(DETECT_WORKER_URL);
119
+ this.worker.onerror = (e) => this.failAll(e.message || "detect worker failed to load");
120
+ this.worker.onmessage = (e) => this.receive(e.data);
121
+ }
122
+ on;
123
+ worker;
124
+ ready = /* @__PURE__ */ new Map();
125
+ up = /* @__PURE__ */ new Set();
126
+ busy = /* @__PURE__ */ new Set();
127
+ initFace(maxFaces) {
128
+ return this.init("face", { t: "initFace", maxFaces });
129
+ }
130
+ initMask(model) {
131
+ return this.init("mask", { t: "initMask", model });
132
+ }
133
+ /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */
134
+ request(kind, frame, tsUs) {
135
+ if (!this.worker || !this.up.has(kind) || this.busy.has(kind)) {
136
+ frame.close();
137
+ return false;
138
+ }
139
+ this.busy.add(kind);
140
+ this.send({ t: kind, frame, tsUs }, [frame]);
141
+ return true;
142
+ }
143
+ isUp(kind) {
144
+ return this.up.has(kind);
145
+ }
146
+ close() {
147
+ this.send({ t: "close" });
148
+ this.worker = null;
149
+ for (const kind of [...this.ready.keys()]) this.settle(kind, new Error("closed"));
150
+ this.up.clear();
151
+ }
152
+ init(kind, m) {
153
+ if (this.up.has(kind)) return Promise.resolve();
154
+ return new Promise((resolve, reject) => {
155
+ if (!this.worker) {
156
+ reject(new Error("detect worker gone"));
157
+ return;
158
+ }
159
+ const timer = setTimeout(() => this.settle(kind, new Error(`${kind}: no ready after ${READY_MS} ms`)), READY_MS);
160
+ this.ready.set(kind, { resolve, reject, timer });
161
+ this.send(m);
162
+ });
163
+ }
164
+ receive(m) {
165
+ switch (m.t) {
166
+ case "ready":
167
+ this.up.add(m.kind);
168
+ this.settle(m.kind);
169
+ break;
170
+ case "error":
171
+ if (this.ready.has(m.kind)) this.settle(m.kind, new Error(m.message));
172
+ else this.fail(m.kind, m.message);
173
+ break;
174
+ case "face":
175
+ this.busy.delete("face");
176
+ if (this.up.has("face")) this.on.face(m.tsUs, m.n, m.lm, m.ms);
177
+ break;
178
+ case "mask":
179
+ this.busy.delete("mask");
180
+ if (this.up.has("mask") && m.width > 0) this.on.mask(m.tsUs, m.width, m.height, m.data, m.ms);
181
+ break;
182
+ }
183
+ }
184
+ settle(kind, err) {
185
+ const r = this.ready.get(kind);
186
+ if (!r) return;
187
+ this.ready.delete(kind);
188
+ clearTimeout(r.timer);
189
+ if (err) r.reject(err);
190
+ else r.resolve();
191
+ }
192
+ fail(kind, reason) {
193
+ if (!this.up.delete(kind)) return;
194
+ this.busy.delete(kind);
195
+ this.on.failed(kind, reason);
196
+ }
197
+ failAll(reason) {
198
+ this.worker?.terminate();
199
+ this.worker = null;
200
+ for (const kind of [...this.ready.keys()]) this.settle(kind, new Error(reason));
201
+ for (const kind of [...this.up]) this.fail(kind, reason);
202
+ }
203
+ send(m, transfer = []) {
204
+ this.worker?.postMessage(m, transfer);
205
+ }
206
+ };
207
+
112
208
  // src/wasm.ts
113
209
  var WASM_URL = "/mediakit/mediakit.wasm";
114
210
  var EXEC_URL = "/mediakit/wasm_exec.js";
@@ -185,6 +281,7 @@ function splitMicros(us) {
185
281
  var ZERO_STATS = {
186
282
  totalMs: 0,
187
283
  segMs: 0,
284
+ faceMs: 0,
188
285
  glCalls: 0,
189
286
  segmented: false,
190
287
  maskScale: 1,
@@ -236,7 +333,21 @@ var Engine = class _Engine {
236
333
  * their background has no reason to download it, and the other way round.
237
334
  */
238
335
  face = null;
336
+ // Preferred over `face`: a landmarker call can take longer than a frame, and in-thread it
337
+ // stalls the picture for that long. `face` is the fallback when no worker can be made.
338
+ faceRemote = false;
339
+ faceWorkerMs = 0;
340
+ // The multiclass segmenter in that same worker: its mask comes back as bytes, uploaded here.
341
+ classRemote = false;
342
+ classMaskTex = null;
343
+ classMaskFresh = false;
344
+ maskWorkerMs = 0;
345
+ detect = null;
346
+ detectCanvas = null;
347
+ // A kind whose worker failed once stays in-thread.
348
+ inThread = /* @__PURE__ */ new Set();
239
349
  faceLoading = null;
350
+ maxFaces = 3;
240
351
  lmBuf = null;
241
352
  filter = { kind: "none" };
242
353
  effects = NO_EFFECTS;
@@ -251,18 +362,19 @@ var Engine = class _Engine {
251
362
  this.core = core;
252
363
  }
253
364
  /** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */
254
- static async create(width, height, filter, effects = NO_EFFECTS, alpha = false) {
365
+ static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3) {
255
366
  const canvas = document.createElement("canvas");
256
367
  canvas.width = width;
257
368
  canvas.height = height;
258
- return _Engine.on(canvas, filter, effects, void 0, alpha);
369
+ return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces);
259
370
  }
260
371
  /**
261
372
  * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
262
373
  * only a `cutout` background writes; it is fixed for the life of the context, so a host that
263
- * may switch to `cutout` later has to ask for it here.
374
+ * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
375
+ * landmarker looks for: below 3 it skips re-running its face detector on every call.
264
376
  */
265
- static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false) {
377
+ static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3) {
266
378
  const width = canvas.width;
267
379
  const height = canvas.height;
268
380
  const gl = canvas.getContext("webgl2", {
@@ -280,6 +392,7 @@ var Engine = class _Engine {
280
392
  const err = core.init(gl, width, height);
281
393
  if (err) throw new Error(`mediakit: ${err}`);
282
394
  engine = new _Engine(canvas, gl, core);
395
+ engine.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3));
283
396
  await engine.setRecipe(filter, effects, background);
284
397
  return engine;
285
398
  } catch (err) {
@@ -383,17 +496,24 @@ var Engine = class _Engine {
383
496
  if (needsFace(effects)) void this.ensureFace();
384
497
  }
385
498
  ensureFace() {
386
- if (this.face || this.closed) return Promise.resolve();
499
+ if (this.face || this.faceRemote || this.closed) return Promise.resolve();
387
500
  if (this.faceLoading) return this.faceLoading;
388
501
  const buf = this.core.faceBuffer();
389
502
  if (!buf) return Promise.resolve();
390
- this.faceLoading = createFaceDetector(this.canvas, Math.max(1, Math.floor(buf.length / FACE_FLOATS))).then((f) => {
391
- if (this.closed) {
392
- f.close();
393
- return;
394
- }
395
- this.face = f;
503
+ const n = Math.min(Math.max(1, Math.floor(buf.length / FACE_FLOATS)), this.maxFaces);
504
+ this.faceLoading = this.remote("face", (d) => d.initFace(n)).then(() => {
505
+ this.faceRemote = true;
396
506
  this.lmBuf = buf;
507
+ }).catch((e) => {
508
+ if (!this.inThread.has("face")) console.warn("mediakit: no detect worker for faces, detecting in this thread", e);
509
+ return createFaceDetector(this.canvas, n).then((f) => {
510
+ if (this.closed) {
511
+ f.close();
512
+ return;
513
+ }
514
+ this.face = f;
515
+ this.lmBuf = buf;
516
+ });
397
517
  }).catch((e) => {
398
518
  console.error("mediakit: face detector failed to load", e);
399
519
  }).finally(() => {
@@ -401,16 +521,98 @@ var Engine = class _Engine {
401
521
  });
402
522
  return this.faceLoading;
403
523
  }
524
+ /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
525
+ async remote(kind, init) {
526
+ if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
527
+ throw new Error("in-thread");
528
+ }
529
+ this.detect ??= new DetectWorker({
530
+ face: (tsUs, n, lm, ms) => {
531
+ if (this.closed || !this.lmBuf) return;
532
+ this.lmBuf.set(lm);
533
+ const [lo, hi] = splitMicros(tsUs);
534
+ this.core.setFace(lo, hi, n);
535
+ this.faceWorkerMs = ms;
536
+ },
537
+ mask: (_tsUs, width, height, data, ms) => {
538
+ if (this.closed) return;
539
+ this.uploadClassMask(width, height, data);
540
+ this.maskWorkerMs = ms;
541
+ },
542
+ failed: (k, reason) => {
543
+ console.warn(`mediakit: ${k} detection moves into this thread:`, reason);
544
+ this.inThread.add(k);
545
+ if (k === "face") {
546
+ this.faceRemote = false;
547
+ void this.ensureFace();
548
+ } else {
549
+ this.classRemote = false;
550
+ void this.ensureClassSegmenter();
551
+ }
552
+ }
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");
561
+ }
562
+ // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
563
+ uploadClassMask(width, height, data) {
564
+ const gl = this.gl;
565
+ if (!this.classMaskTex) {
566
+ this.classMaskTex = gl.createTexture();
567
+ gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
568
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
569
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
570
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
571
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
572
+ }
573
+ gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
574
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
575
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
576
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
577
+ gl.bindTexture(gl.TEXTURE_2D, null);
578
+ this.classMaskFresh = true;
579
+ }
580
+ /**
581
+ * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
582
+ * detection drains Chrome's few capture buffers and throttles the camera itself.
583
+ */
584
+ requestRemote(kind, source, timestampUs) {
585
+ let frame = null;
586
+ try {
587
+ frame = new VideoFrame(source instanceof VideoFrame ? this.detectCopy(source) : source, {
588
+ timestamp: timestampUs
589
+ });
590
+ } catch {
591
+ }
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);
600
+ return this.detectCanvas;
601
+ }
404
602
  ensureClassSegmenter() {
405
- if (this.classSegmenter || this.closed) return Promise.resolve();
603
+ if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
406
604
  if (this.classLoading) return this.classLoading;
407
- this.classLoading = createSegmenter(this.canvas, "classes").then((s) => {
408
- if (this.closed) {
409
- s.close();
410
- return;
411
- }
412
- this.classSegmenter = s;
413
- }).catch((e) => {
605
+ this.classLoading = this.remote("mask", (d) => d.initMask("classes")).then(() => {
606
+ this.classRemote = true;
607
+ }).catch(
608
+ () => createSegmenter(this.canvas, "classes").then((s) => {
609
+ if (this.closed) {
610
+ s.close();
611
+ return;
612
+ }
613
+ this.classSegmenter = s;
614
+ })
615
+ ).catch((e) => {
414
616
  console.error("mediakit: multiclass segmenter failed to load", e);
415
617
  }).finally(() => {
416
618
  this.classLoading = null;
@@ -454,8 +656,22 @@ var Engine = class _Engine {
454
656
  let mask = null;
455
657
  let maskKind = 0;
456
658
  let segMs = 0;
659
+ let faceMs = 0;
457
660
  this.used = null;
458
- if (needSeg) {
661
+ let served = false;
662
+ if (needSeg && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
663
+ this.requestRemote("mask", source, timestampUs);
664
+ if (this.classMaskTex) {
665
+ served = true;
666
+ if (this.classMaskFresh) {
667
+ this.classMaskFresh = false;
668
+ mask = this.classMaskTex;
669
+ maskKind = 1;
670
+ segMs = this.maskWorkerMs;
671
+ }
672
+ }
673
+ }
674
+ if (needSeg && !served) {
459
675
  const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
460
676
  const seg = classes ? this.classSegmenter : this.segmenter;
461
677
  if (!seg) {
@@ -469,10 +685,15 @@ var Engine = class _Engine {
469
685
  }
470
686
  }
471
687
  if (this.core.decideFace() === 1) {
472
- if (!this.face) {
688
+ if (this.faceRemote) {
689
+ this.requestRemote("face", source, timestampUs);
690
+ faceMs = this.faceWorkerMs;
691
+ } else if (!this.face) {
473
692
  void this.ensureFace();
474
693
  } else if (this.lmBuf) {
694
+ const f0 = performance.now();
475
695
  const n = this.face.detect(source, timestampUs / 1e3, this.lmBuf);
696
+ faceMs = performance.now() - f0;
476
697
  this.core.setFace(lo, hi, n);
477
698
  }
478
699
  }
@@ -485,6 +706,7 @@ var Engine = class _Engine {
485
706
  this.last = {
486
707
  totalMs: this.prevTotalMs,
487
708
  segMs,
709
+ faceMs,
488
710
  glCalls,
489
711
  segmented: needSeg && mask !== null,
490
712
  maskScale: s ? s[1] : 1,
@@ -522,6 +744,12 @@ var Engine = class _Engine {
522
744
  this.classSegmenter = null;
523
745
  this.face?.close();
524
746
  this.face = null;
747
+ this.detect?.close();
748
+ this.detect = null;
749
+ this.faceRemote = false;
750
+ this.classRemote = false;
751
+ if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
752
+ this.classMaskTex = null;
525
753
  this.lmBuf = null;
526
754
  this.core.close();
527
755
  this.background?.close();
@@ -754,7 +982,7 @@ var VideoPipeline = class {
754
982
  }
755
983
  async startMain(source) {
756
984
  const { width, height, fps } = this.size;
757
- this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false);
985
+ this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces);
758
986
  this.transport = hasInsertableStreams() ? "insertable" : "canvas";
759
987
  this.frames = 0;
760
988
  this.lastBeat = performance.now();
@@ -878,7 +1106,8 @@ var VideoPipeline = class {
878
1106
  filter: this.filter,
879
1107
  effects: this.effects,
880
1108
  background,
881
- alpha: this.opts.alpha
1109
+ alpha: this.opts.alpha,
1110
+ maxFaces: this.opts.maxFaces
882
1111
  },
883
1112
  background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
884
1113
  )
@@ -902,7 +1131,8 @@ var VideoPipeline = class {
902
1131
  filter: this.filter,
903
1132
  effects: this.effects,
904
1133
  background,
905
- alpha: this.opts.alpha
1134
+ alpha: this.opts.alpha,
1135
+ maxFaces: this.opts.maxFaces
906
1136
  },
907
1137
  background ? [clone, background] : [clone]
908
1138
  )