@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.
Binary file
package/dist/worker.js CHANGED
@@ -4727,10 +4727,10 @@
4727
4727
  var WASM_DIR2 = "/mediakit/mp";
4728
4728
  var MODEL_URL2 = "/mediakit/face_landmarker.task";
4729
4729
  var FACE_FLOATS = 478 * 3;
4730
- async function createFaceDetector(canvas, maxFaces) {
4730
+ async function createFaceDetector(canvas, maxFaces, delegate = "GPU") {
4731
4731
  const fileset = await uh.forVisionTasks(WASM_DIR2);
4732
4732
  const landmarker = await yc.createFromOptions(fileset, {
4733
- baseOptions: { modelAssetPath: MODEL_URL2, delegate: "GPU" },
4733
+ baseOptions: { modelAssetPath: MODEL_URL2, delegate },
4734
4734
  canvas,
4735
4735
  runningMode: "VIDEO",
4736
4736
  // As many as the core tracks: one landmark pass returns them all, so the cost of a second
@@ -4762,6 +4762,102 @@
4762
4762
  };
4763
4763
  }
4764
4764
 
4765
+ // src/detect-remote.ts
4766
+ var DETECT_WORKER_URL = "/mediakit/detect-worker.js";
4767
+ var READY_MS = 2e4;
4768
+ var DetectWorker = class {
4769
+ constructor(on2) {
4770
+ this.on = on2;
4771
+ this.worker = new Worker(DETECT_WORKER_URL);
4772
+ this.worker.onerror = (e2) => this.failAll(e2.message || "detect worker failed to load");
4773
+ this.worker.onmessage = (e2) => this.receive(e2.data);
4774
+ }
4775
+ on;
4776
+ worker;
4777
+ ready = /* @__PURE__ */ new Map();
4778
+ up = /* @__PURE__ */ new Set();
4779
+ busy = /* @__PURE__ */ new Set();
4780
+ initFace(maxFaces) {
4781
+ return this.init("face", { t: "initFace", maxFaces });
4782
+ }
4783
+ initMask(model) {
4784
+ return this.init("mask", { t: "initMask", model });
4785
+ }
4786
+ /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */
4787
+ request(kind, frame, tsUs) {
4788
+ if (!this.worker || !this.up.has(kind) || this.busy.has(kind)) {
4789
+ frame.close();
4790
+ return false;
4791
+ }
4792
+ this.busy.add(kind);
4793
+ this.send({ t: kind, frame, tsUs }, [frame]);
4794
+ return true;
4795
+ }
4796
+ isUp(kind) {
4797
+ return this.up.has(kind);
4798
+ }
4799
+ close() {
4800
+ this.send({ t: "close" });
4801
+ this.worker = null;
4802
+ for (const kind of [...this.ready.keys()]) this.settle(kind, new Error("closed"));
4803
+ this.up.clear();
4804
+ }
4805
+ init(kind, m2) {
4806
+ if (this.up.has(kind)) return Promise.resolve();
4807
+ return new Promise((resolve, reject) => {
4808
+ if (!this.worker) {
4809
+ reject(new Error("detect worker gone"));
4810
+ return;
4811
+ }
4812
+ const timer = setTimeout(() => this.settle(kind, new Error(`${kind}: no ready after ${READY_MS} ms`)), READY_MS);
4813
+ this.ready.set(kind, { resolve, reject, timer });
4814
+ this.send(m2);
4815
+ });
4816
+ }
4817
+ receive(m2) {
4818
+ switch (m2.t) {
4819
+ case "ready":
4820
+ this.up.add(m2.kind);
4821
+ this.settle(m2.kind);
4822
+ break;
4823
+ case "error":
4824
+ if (this.ready.has(m2.kind)) this.settle(m2.kind, new Error(m2.message));
4825
+ else this.fail(m2.kind, m2.message);
4826
+ break;
4827
+ case "face":
4828
+ this.busy.delete("face");
4829
+ if (this.up.has("face")) this.on.face(m2.tsUs, m2.n, m2.lm, m2.ms);
4830
+ break;
4831
+ case "mask":
4832
+ this.busy.delete("mask");
4833
+ if (this.up.has("mask") && m2.width > 0) this.on.mask(m2.tsUs, m2.width, m2.height, m2.data, m2.ms);
4834
+ break;
4835
+ }
4836
+ }
4837
+ settle(kind, err) {
4838
+ const r2 = this.ready.get(kind);
4839
+ if (!r2) return;
4840
+ this.ready.delete(kind);
4841
+ clearTimeout(r2.timer);
4842
+ if (err) r2.reject(err);
4843
+ else r2.resolve();
4844
+ }
4845
+ fail(kind, reason) {
4846
+ if (!this.up.delete(kind)) return;
4847
+ this.busy.delete(kind);
4848
+ this.on.failed(kind, reason);
4849
+ }
4850
+ failAll(reason) {
4851
+ this.worker?.terminate();
4852
+ this.worker = null;
4853
+ for (const kind of [...this.ready.keys()]) this.settle(kind, new Error(reason));
4854
+ for (const kind of [...this.up]) this.fail(kind, reason);
4855
+ }
4856
+ send(m2, transfer = []) {
4857
+ this.worker?.postMessage(m2, transfer);
4858
+ }
4859
+ };
4860
+
4765
4861
  // src/wasm.ts
4766
4862
  var WASM_URL = "/mediakit/mediakit.wasm";
4767
4863
  var EXEC_URL = "/mediakit/wasm_exec.js";
@@ -4983,6 +5079,7 @@
4983
5079
  var ZERO_STATS = {
4984
5080
  totalMs: 0,
4985
5081
  segMs: 0,
5082
+ faceMs: 0,
4986
5083
  glCalls: 0,
4987
5084
  segmented: false,
4988
5085
  maskScale: 1,
@@ -5034,7 +5131,21 @@
5034
5131
  * their background has no reason to download it, and the other way round.
5035
5132
  */
5036
5133
  face = null;
5134
+ // Preferred over `face`: a landmarker call can take longer than a frame, and in-thread it
5135
+ // stalls the picture for that long. `face` is the fallback when no worker can be made.
5136
+ faceRemote = false;
5137
+ faceWorkerMs = 0;
5138
+ // The multiclass segmenter in that same worker: its mask comes back as bytes, uploaded here.
5139
+ classRemote = false;
5140
+ classMaskTex = null;
5141
+ classMaskFresh = false;
5142
+ maskWorkerMs = 0;
5143
+ detect = null;
5144
+ detectCanvas = null;
5145
+ // A kind whose worker failed once stays in-thread.
5146
+ inThread = /* @__PURE__ */ new Set();
5037
5147
  faceLoading = null;
5148
+ maxFaces = 3;
5038
5149
  lmBuf = null;
5039
5150
  filter = { kind: "none" };
5040
5151
  effects = NO_EFFECTS;
@@ -5049,18 +5160,19 @@
5049
5160
  this.core = core;
5050
5161
  }
5051
5162
  /** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */
5052
- static async create(width, height, filter, effects = NO_EFFECTS, alpha = false) {
5163
+ static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3) {
5053
5164
  const canvas = document.createElement("canvas");
5054
5165
  canvas.width = width;
5055
5166
  canvas.height = height;
5056
- return _Engine.on(canvas, filter, effects, void 0, alpha);
5167
+ return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces);
5057
5168
  }
5058
5169
  /**
5059
5170
  * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
5060
5171
  * only a `cutout` background writes; it is fixed for the life of the context, so a host that
5061
- * may switch to `cutout` later has to ask for it here.
5172
+ * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
5173
+ * landmarker looks for: below 3 it skips re-running its face detector on every call.
5062
5174
  */
5063
- static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false) {
5175
+ static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3) {
5064
5176
  const width = canvas.width;
5065
5177
  const height = canvas.height;
5066
5178
  const gl = canvas.getContext("webgl2", {
@@ -5078,6 +5190,7 @@
5078
5190
  const err = core.init(gl, width, height);
5079
5191
  if (err) throw new Error(`mediakit: ${err}`);
5080
5192
  engine2 = new _Engine(canvas, gl, core);
5193
+ engine2.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3));
5081
5194
  await engine2.setRecipe(filter, effects, background);
5082
5195
  return engine2;
5083
5196
  } catch (err) {
@@ -5181,17 +5294,24 @@
5181
5294
  if (needsFace(effects)) void this.ensureFace();
5182
5295
  }
5183
5296
  ensureFace() {
5184
- if (this.face || this.closed) return Promise.resolve();
5297
+ if (this.face || this.faceRemote || this.closed) return Promise.resolve();
5185
5298
  if (this.faceLoading) return this.faceLoading;
5186
5299
  const buf = this.core.faceBuffer();
5187
5300
  if (!buf) return Promise.resolve();
5188
- this.faceLoading = createFaceDetector(this.canvas, Math.max(1, Math.floor(buf.length / FACE_FLOATS))).then((f2) => {
5189
- if (this.closed) {
5190
- f2.close();
5191
- return;
5192
- }
5193
- this.face = f2;
5301
+ const n2 = Math.min(Math.max(1, Math.floor(buf.length / FACE_FLOATS)), this.maxFaces);
5302
+ this.faceLoading = this.remote("face", (d2) => d2.initFace(n2)).then(() => {
5303
+ this.faceRemote = true;
5194
5304
  this.lmBuf = buf;
5305
+ }).catch((e2) => {
5306
+ if (!this.inThread.has("face")) console.warn("mediakit: no detect worker for faces, detecting in this thread", e2);
5307
+ return createFaceDetector(this.canvas, n2).then((f2) => {
5308
+ if (this.closed) {
5309
+ f2.close();
5310
+ return;
5311
+ }
5312
+ this.face = f2;
5313
+ this.lmBuf = buf;
5314
+ });
5195
5315
  }).catch((e2) => {
5196
5316
  console.error("mediakit: face detector failed to load", e2);
5197
5317
  }).finally(() => {
@@ -5199,16 +5319,98 @@
5199
5319
  });
5200
5320
  return this.faceLoading;
5201
5321
  }
5322
+ /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
5323
+ async remote(kind, init) {
5324
+ if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
5325
+ throw new Error("in-thread");
5326
+ }
5327
+ this.detect ??= new DetectWorker({
5328
+ face: (tsUs, n2, lm, ms2) => {
5329
+ if (this.closed || !this.lmBuf) return;
5330
+ this.lmBuf.set(lm);
5331
+ const [lo2, hi2] = splitMicros(tsUs);
5332
+ this.core.setFace(lo2, hi2, n2);
5333
+ this.faceWorkerMs = ms2;
5334
+ },
5335
+ mask: (_tsUs, width, height, data, ms2) => {
5336
+ if (this.closed) return;
5337
+ this.uploadClassMask(width, height, data);
5338
+ this.maskWorkerMs = ms2;
5339
+ },
5340
+ failed: (k2, reason) => {
5341
+ console.warn(`mediakit: ${k2} detection moves into this thread:`, reason);
5342
+ this.inThread.add(k2);
5343
+ if (k2 === "face") {
5344
+ this.faceRemote = false;
5345
+ void this.ensureFace();
5346
+ } else {
5347
+ this.classRemote = false;
5348
+ void this.ensureClassSegmenter();
5349
+ }
5350
+ }
5351
+ });
5352
+ try {
5353
+ await init(this.detect);
5354
+ } catch (e2) {
5355
+ this.inThread.add(kind);
5356
+ throw e2;
5357
+ }
5358
+ if (this.closed) throw new Error("closed");
5359
+ }
5360
+ // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
5361
+ uploadClassMask(width, height, data) {
5362
+ const gl = this.gl;
5363
+ if (!this.classMaskTex) {
5364
+ this.classMaskTex = gl.createTexture();
5365
+ gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
5366
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
5367
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
5368
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
5369
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
5370
+ }
5371
+ gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
5372
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
5373
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
5374
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
5375
+ gl.bindTexture(gl.TEXTURE_2D, null);
5376
+ this.classMaskFresh = true;
5377
+ }
5378
+ /**
5379
+ * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
5380
+ * detection drains Chrome's few capture buffers and throttles the camera itself.
5381
+ */
5382
+ requestRemote(kind, source, timestampUs) {
5383
+ let frame = null;
5384
+ try {
5385
+ frame = new VideoFrame(source instanceof VideoFrame ? this.detectCopy(source) : source, {
5386
+ timestamp: timestampUs
5387
+ });
5388
+ } catch {
5389
+ }
5390
+ if (frame) this.detect?.request(kind, frame, timestampUs);
5391
+ }
5392
+ detectCopy(source) {
5393
+ const s2 = Math.min(1, 512 / Math.max(source.displayWidth, source.displayHeight));
5394
+ const w2 = Math.max(1, Math.round(source.displayWidth * s2));
5395
+ const h2 = Math.max(1, Math.round(source.displayHeight * s2));
5396
+ if (!this.detectCanvas || this.detectCanvas.width !== w2 || this.detectCanvas.height !== h2) this.detectCanvas = new OffscreenCanvas(w2, h2);
5397
+ this.detectCanvas.getContext("2d").drawImage(source, 0, 0, w2, h2);
5398
+ return this.detectCanvas;
5399
+ }
5202
5400
  ensureClassSegmenter() {
5203
- if (this.classSegmenter || this.closed) return Promise.resolve();
5401
+ if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
5204
5402
  if (this.classLoading) return this.classLoading;
5205
- this.classLoading = createSegmenter(this.canvas, "classes").then((s2) => {
5206
- if (this.closed) {
5207
- s2.close();
5208
- return;
5209
- }
5210
- this.classSegmenter = s2;
5211
- }).catch((e2) => {
5403
+ this.classLoading = this.remote("mask", (d2) => d2.initMask("classes")).then(() => {
5404
+ this.classRemote = true;
5405
+ }).catch(
5406
+ () => createSegmenter(this.canvas, "classes").then((s2) => {
5407
+ if (this.closed) {
5408
+ s2.close();
5409
+ return;
5410
+ }
5411
+ this.classSegmenter = s2;
5412
+ })
5413
+ ).catch((e2) => {
5212
5414
  console.error("mediakit: multiclass segmenter failed to load", e2);
5213
5415
  }).finally(() => {
5214
5416
  this.classLoading = null;
@@ -5252,8 +5454,22 @@
5252
5454
  let mask = null;
5253
5455
  let maskKind = 0;
5254
5456
  let segMs = 0;
5457
+ let faceMs = 0;
5255
5458
  this.used = null;
5256
- if (needSeg) {
5459
+ let served = false;
5460
+ if (needSeg && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
5461
+ this.requestRemote("mask", source, timestampUs);
5462
+ if (this.classMaskTex) {
5463
+ served = true;
5464
+ if (this.classMaskFresh) {
5465
+ this.classMaskFresh = false;
5466
+ mask = this.classMaskTex;
5467
+ maskKind = 1;
5468
+ segMs = this.maskWorkerMs;
5469
+ }
5470
+ }
5471
+ }
5472
+ if (needSeg && !served) {
5257
5473
  const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
5258
5474
  const seg = classes ? this.classSegmenter : this.segmenter;
5259
5475
  if (!seg) {
@@ -5267,10 +5483,15 @@
5267
5483
  }
5268
5484
  }
5269
5485
  if (this.core.decideFace() === 1) {
5270
- if (!this.face) {
5486
+ if (this.faceRemote) {
5487
+ this.requestRemote("face", source, timestampUs);
5488
+ faceMs = this.faceWorkerMs;
5489
+ } else if (!this.face) {
5271
5490
  void this.ensureFace();
5272
5491
  } else if (this.lmBuf) {
5492
+ const f0 = performance.now();
5273
5493
  const n2 = this.face.detect(source, timestampUs / 1e3, this.lmBuf);
5494
+ faceMs = performance.now() - f0;
5274
5495
  this.core.setFace(lo2, hi2, n2);
5275
5496
  }
5276
5497
  }
@@ -5283,6 +5504,7 @@
5283
5504
  this.last = {
5284
5505
  totalMs: this.prevTotalMs,
5285
5506
  segMs,
5507
+ faceMs,
5286
5508
  glCalls,
5287
5509
  segmented: needSeg && mask !== null,
5288
5510
  maskScale: s2 ? s2[1] : 1,
@@ -5320,6 +5542,12 @@
5320
5542
  this.classSegmenter = null;
5321
5543
  this.face?.close();
5322
5544
  this.face = null;
5545
+ this.detect?.close();
5546
+ this.detect = null;
5547
+ this.faceRemote = false;
5548
+ this.classRemote = false;
5549
+ if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
5550
+ this.classMaskTex = null;
5323
5551
  this.lmBuf = null;
5324
5552
  this.core.close();
5325
5553
  this.background?.close();
@@ -5400,7 +5628,7 @@
5400
5628
  }
5401
5629
  async function run(m2, readable, writable, outTrack) {
5402
5630
  const canvas = new OffscreenCanvas(m2.width, m2.height);
5403
- engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false);
5631
+ engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false, m2.maxFaces);
5404
5632
  abort = new AbortController();
5405
5633
  let n2 = 0;
5406
5634
  let lastPost = performance.now();