@tradalab/mediakit 2.0.0 → 2.1.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
@@ -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,16 @@ 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 readonly inThread;
77
87
  private faceLoading;
88
+ private maxFaces;
78
89
  private lmBuf;
79
90
  private filter;
80
91
  private effects;
@@ -83,13 +94,14 @@ declare class Engine {
83
94
  last: FrameStats;
84
95
  private constructor();
85
96
  /** 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>;
97
+ static create(width: number, height: number, filter: BgFilter, effects?: Effects, alpha?: boolean, maxFaces?: number): Promise<Engine>;
87
98
  /**
88
99
  * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
89
100
  * 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.
101
+ * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
102
+ * landmarker looks for: below 3 it skips re-running its face detector on every call.
91
103
  */
92
- static on(canvas: EngineCanvas, filter: BgFilter, effects?: Effects, background?: ImageBitmap, alpha?: boolean): Promise<Engine>;
104
+ static on(canvas: EngineCanvas, filter: BgFilter, effects?: Effects, background?: ImageBitmap, alpha?: boolean, maxFaces?: number): Promise<Engine>;
93
105
  get loading(): boolean;
94
106
  get outputCanvas(): EngineCanvas;
95
107
  /**
@@ -101,6 +113,11 @@ declare class Engine {
101
113
  */
102
114
  setRecipe(filter: BgFilter, effects?: Effects, background?: ImageBitmap): Promise<void>;
103
115
  private ensureFace;
116
+ /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
117
+ private remote;
118
+ private uploadClassMask;
119
+ /** Hands a copy of this frame to the detect worker; the caller's frame stays its own. */
120
+ private requestRemote;
104
121
  private ensureClassSegmenter;
105
122
  private ensureSegmenter;
106
123
  /**
@@ -160,6 +177,11 @@ type Transport = "worker" | "insertable" | "canvas";
160
177
  interface PipelineOptions {
161
178
  /** Keep the output's alpha channel, for `subscribeFrames` with a `cutout` background. */
162
179
  alpha?: boolean;
180
+ /**
181
+ * Faces to track, 1-3, default 3. One person per camera should say 1: looking for more re-runs
182
+ * the face detector on every call, about a third of the landmark cost.
183
+ */
184
+ maxFaces?: number;
163
185
  /** No processed frame for 2 s while the camera is live (20 s while a detector loads). */
164
186
  onStall?: (info: {
165
187
  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,20 @@ 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
+ // A kind whose worker failed once stays in-thread.
347
+ inThread = /* @__PURE__ */ new Set();
239
348
  faceLoading = null;
349
+ maxFaces = 3;
240
350
  lmBuf = null;
241
351
  filter = { kind: "none" };
242
352
  effects = NO_EFFECTS;
@@ -251,18 +361,19 @@ var Engine = class _Engine {
251
361
  this.core = core;
252
362
  }
253
363
  /** 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) {
364
+ static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3) {
255
365
  const canvas = document.createElement("canvas");
256
366
  canvas.width = width;
257
367
  canvas.height = height;
258
- return _Engine.on(canvas, filter, effects, void 0, alpha);
368
+ return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces);
259
369
  }
260
370
  /**
261
371
  * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
262
372
  * 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.
373
+ * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
374
+ * landmarker looks for: below 3 it skips re-running its face detector on every call.
264
375
  */
265
- static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false) {
376
+ static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3) {
266
377
  const width = canvas.width;
267
378
  const height = canvas.height;
268
379
  const gl = canvas.getContext("webgl2", {
@@ -280,6 +391,7 @@ var Engine = class _Engine {
280
391
  const err = core.init(gl, width, height);
281
392
  if (err) throw new Error(`mediakit: ${err}`);
282
393
  engine = new _Engine(canvas, gl, core);
394
+ engine.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3));
283
395
  await engine.setRecipe(filter, effects, background);
284
396
  return engine;
285
397
  } catch (err) {
@@ -383,17 +495,24 @@ var Engine = class _Engine {
383
495
  if (needsFace(effects)) void this.ensureFace();
384
496
  }
385
497
  ensureFace() {
386
- if (this.face || this.closed) return Promise.resolve();
498
+ if (this.face || this.faceRemote || this.closed) return Promise.resolve();
387
499
  if (this.faceLoading) return this.faceLoading;
388
500
  const buf = this.core.faceBuffer();
389
501
  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;
502
+ const n = Math.min(Math.max(1, Math.floor(buf.length / FACE_FLOATS)), this.maxFaces);
503
+ this.faceLoading = this.remote("face", (d) => d.initFace(n)).then(() => {
504
+ this.faceRemote = true;
396
505
  this.lmBuf = buf;
506
+ }).catch((e) => {
507
+ if (!this.inThread.has("face")) console.warn("mediakit: no detect worker for faces, detecting in this thread", e);
508
+ return createFaceDetector(this.canvas, n).then((f) => {
509
+ if (this.closed) {
510
+ f.close();
511
+ return;
512
+ }
513
+ this.face = f;
514
+ this.lmBuf = buf;
515
+ });
397
516
  }).catch((e) => {
398
517
  console.error("mediakit: face detector failed to load", e);
399
518
  }).finally(() => {
@@ -401,16 +520,85 @@ var Engine = class _Engine {
401
520
  });
402
521
  return this.faceLoading;
403
522
  }
523
+ /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
524
+ async remote(kind, init) {
525
+ if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
526
+ throw new Error("in-thread");
527
+ }
528
+ this.detect ??= new DetectWorker({
529
+ face: (tsUs, n, lm, ms) => {
530
+ if (this.closed || !this.lmBuf) return;
531
+ this.lmBuf.set(lm);
532
+ const [lo, hi] = splitMicros(tsUs);
533
+ this.core.setFace(lo, hi, n);
534
+ this.faceWorkerMs = ms;
535
+ },
536
+ mask: (_tsUs, width, height, data, ms) => {
537
+ if (this.closed) return;
538
+ this.uploadClassMask(width, height, data);
539
+ this.maskWorkerMs = ms;
540
+ },
541
+ failed: (k, reason) => {
542
+ console.warn(`mediakit: ${k} detection moves into this thread:`, reason);
543
+ this.inThread.add(k);
544
+ if (k === "face") {
545
+ this.faceRemote = false;
546
+ void this.ensureFace();
547
+ } else {
548
+ this.classRemote = false;
549
+ void this.ensureClassSegmenter();
550
+ }
551
+ }
552
+ });
553
+ try {
554
+ await init(this.detect);
555
+ } catch (e) {
556
+ this.inThread.add(kind);
557
+ throw e;
558
+ }
559
+ if (this.closed) throw new Error("closed");
560
+ }
561
+ // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
562
+ uploadClassMask(width, height, data) {
563
+ const gl = this.gl;
564
+ if (!this.classMaskTex) {
565
+ this.classMaskTex = gl.createTexture();
566
+ gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
567
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
568
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
569
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
570
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
571
+ }
572
+ gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
573
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
574
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
575
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
576
+ gl.bindTexture(gl.TEXTURE_2D, null);
577
+ this.classMaskFresh = true;
578
+ }
579
+ /** Hands a copy of this frame to the detect worker; the caller's frame stays its own. */
580
+ requestRemote(kind, source, timestampUs) {
581
+ let frame = null;
582
+ try {
583
+ frame = source instanceof VideoFrame ? source.clone() : new VideoFrame(source, { timestamp: timestampUs });
584
+ } catch {
585
+ }
586
+ if (frame) this.detect?.request(kind, frame, timestampUs);
587
+ }
404
588
  ensureClassSegmenter() {
405
- if (this.classSegmenter || this.closed) return Promise.resolve();
589
+ if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
406
590
  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) => {
591
+ this.classLoading = this.remote("mask", (d) => d.initMask("classes")).then(() => {
592
+ this.classRemote = true;
593
+ }).catch(
594
+ () => createSegmenter(this.canvas, "classes").then((s) => {
595
+ if (this.closed) {
596
+ s.close();
597
+ return;
598
+ }
599
+ this.classSegmenter = s;
600
+ })
601
+ ).catch((e) => {
414
602
  console.error("mediakit: multiclass segmenter failed to load", e);
415
603
  }).finally(() => {
416
604
  this.classLoading = null;
@@ -454,8 +642,22 @@ var Engine = class _Engine {
454
642
  let mask = null;
455
643
  let maskKind = 0;
456
644
  let segMs = 0;
645
+ let faceMs = 0;
457
646
  this.used = null;
458
- if (needSeg) {
647
+ let served = false;
648
+ if (needSeg && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
649
+ this.requestRemote("mask", source, timestampUs);
650
+ if (this.classMaskTex) {
651
+ served = true;
652
+ if (this.classMaskFresh) {
653
+ this.classMaskFresh = false;
654
+ mask = this.classMaskTex;
655
+ maskKind = 1;
656
+ segMs = this.maskWorkerMs;
657
+ }
658
+ }
659
+ }
660
+ if (needSeg && !served) {
459
661
  const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
460
662
  const seg = classes ? this.classSegmenter : this.segmenter;
461
663
  if (!seg) {
@@ -469,10 +671,15 @@ var Engine = class _Engine {
469
671
  }
470
672
  }
471
673
  if (this.core.decideFace() === 1) {
472
- if (!this.face) {
674
+ if (this.faceRemote) {
675
+ this.requestRemote("face", source, timestampUs);
676
+ faceMs = this.faceWorkerMs;
677
+ } else if (!this.face) {
473
678
  void this.ensureFace();
474
679
  } else if (this.lmBuf) {
680
+ const f0 = performance.now();
475
681
  const n = this.face.detect(source, timestampUs / 1e3, this.lmBuf);
682
+ faceMs = performance.now() - f0;
476
683
  this.core.setFace(lo, hi, n);
477
684
  }
478
685
  }
@@ -485,6 +692,7 @@ var Engine = class _Engine {
485
692
  this.last = {
486
693
  totalMs: this.prevTotalMs,
487
694
  segMs,
695
+ faceMs,
488
696
  glCalls,
489
697
  segmented: needSeg && mask !== null,
490
698
  maskScale: s ? s[1] : 1,
@@ -522,6 +730,12 @@ var Engine = class _Engine {
522
730
  this.classSegmenter = null;
523
731
  this.face?.close();
524
732
  this.face = null;
733
+ this.detect?.close();
734
+ this.detect = null;
735
+ this.faceRemote = false;
736
+ this.classRemote = false;
737
+ if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
738
+ this.classMaskTex = null;
525
739
  this.lmBuf = null;
526
740
  this.core.close();
527
741
  this.background?.close();
@@ -754,7 +968,7 @@ var VideoPipeline = class {
754
968
  }
755
969
  async startMain(source) {
756
970
  const { width, height, fps } = this.size;
757
- this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false);
971
+ this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces);
758
972
  this.transport = hasInsertableStreams() ? "insertable" : "canvas";
759
973
  this.frames = 0;
760
974
  this.lastBeat = performance.now();
@@ -878,7 +1092,8 @@ var VideoPipeline = class {
878
1092
  filter: this.filter,
879
1093
  effects: this.effects,
880
1094
  background,
881
- alpha: this.opts.alpha
1095
+ alpha: this.opts.alpha,
1096
+ maxFaces: this.opts.maxFaces
882
1097
  },
883
1098
  background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
884
1099
  )
@@ -902,7 +1117,8 @@ var VideoPipeline = class {
902
1117
  filter: this.filter,
903
1118
  effects: this.effects,
904
1119
  background,
905
- alpha: this.opts.alpha
1120
+ alpha: this.opts.alpha,
1121
+ maxFaces: this.opts.maxFaces
906
1122
  },
907
1123
  background ? [clone, background] : [clone]
908
1124
  )