@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.
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,20 @@
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
+ // A kind whose worker failed once stays in-thread.
5145
+ inThread = /* @__PURE__ */ new Set();
5037
5146
  faceLoading = null;
5147
+ maxFaces = 3;
5038
5148
  lmBuf = null;
5039
5149
  filter = { kind: "none" };
5040
5150
  effects = NO_EFFECTS;
@@ -5049,18 +5159,19 @@
5049
5159
  this.core = core;
5050
5160
  }
5051
5161
  /** 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) {
5162
+ static async create(width, height, filter, effects = NO_EFFECTS, alpha = false, maxFaces = 3) {
5053
5163
  const canvas = document.createElement("canvas");
5054
5164
  canvas.width = width;
5055
5165
  canvas.height = height;
5056
- return _Engine.on(canvas, filter, effects, void 0, alpha);
5166
+ return _Engine.on(canvas, filter, effects, void 0, alpha, maxFaces);
5057
5167
  }
5058
5168
  /**
5059
5169
  * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which
5060
5170
  * 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.
5171
+ * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the
5172
+ * landmarker looks for: below 3 it skips re-running its face detector on every call.
5062
5173
  */
5063
- static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false) {
5174
+ static async on(canvas, filter, effects = NO_EFFECTS, background, alpha = false, maxFaces = 3) {
5064
5175
  const width = canvas.width;
5065
5176
  const height = canvas.height;
5066
5177
  const gl = canvas.getContext("webgl2", {
@@ -5078,6 +5189,7 @@
5078
5189
  const err = core.init(gl, width, height);
5079
5190
  if (err) throw new Error(`mediakit: ${err}`);
5080
5191
  engine2 = new _Engine(canvas, gl, core);
5192
+ engine2.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3));
5081
5193
  await engine2.setRecipe(filter, effects, background);
5082
5194
  return engine2;
5083
5195
  } catch (err) {
@@ -5181,17 +5293,24 @@
5181
5293
  if (needsFace(effects)) void this.ensureFace();
5182
5294
  }
5183
5295
  ensureFace() {
5184
- if (this.face || this.closed) return Promise.resolve();
5296
+ if (this.face || this.faceRemote || this.closed) return Promise.resolve();
5185
5297
  if (this.faceLoading) return this.faceLoading;
5186
5298
  const buf = this.core.faceBuffer();
5187
5299
  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;
5300
+ const n2 = Math.min(Math.max(1, Math.floor(buf.length / FACE_FLOATS)), this.maxFaces);
5301
+ this.faceLoading = this.remote("face", (d2) => d2.initFace(n2)).then(() => {
5302
+ this.faceRemote = true;
5194
5303
  this.lmBuf = buf;
5304
+ }).catch((e2) => {
5305
+ if (!this.inThread.has("face")) console.warn("mediakit: no detect worker for faces, detecting in this thread", e2);
5306
+ return createFaceDetector(this.canvas, n2).then((f2) => {
5307
+ if (this.closed) {
5308
+ f2.close();
5309
+ return;
5310
+ }
5311
+ this.face = f2;
5312
+ this.lmBuf = buf;
5313
+ });
5195
5314
  }).catch((e2) => {
5196
5315
  console.error("mediakit: face detector failed to load", e2);
5197
5316
  }).finally(() => {
@@ -5199,16 +5318,85 @@
5199
5318
  });
5200
5319
  return this.faceLoading;
5201
5320
  }
5321
+ /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
5322
+ async remote(kind, init) {
5323
+ if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
5324
+ throw new Error("in-thread");
5325
+ }
5326
+ this.detect ??= new DetectWorker({
5327
+ face: (tsUs, n2, lm, ms2) => {
5328
+ if (this.closed || !this.lmBuf) return;
5329
+ this.lmBuf.set(lm);
5330
+ const [lo2, hi2] = splitMicros(tsUs);
5331
+ this.core.setFace(lo2, hi2, n2);
5332
+ this.faceWorkerMs = ms2;
5333
+ },
5334
+ mask: (_tsUs, width, height, data, ms2) => {
5335
+ if (this.closed) return;
5336
+ this.uploadClassMask(width, height, data);
5337
+ this.maskWorkerMs = ms2;
5338
+ },
5339
+ failed: (k2, reason) => {
5340
+ console.warn(`mediakit: ${k2} detection moves into this thread:`, reason);
5341
+ this.inThread.add(k2);
5342
+ if (k2 === "face") {
5343
+ this.faceRemote = false;
5344
+ void this.ensureFace();
5345
+ } else {
5346
+ this.classRemote = false;
5347
+ void this.ensureClassSegmenter();
5348
+ }
5349
+ }
5350
+ });
5351
+ try {
5352
+ await init(this.detect);
5353
+ } catch (e2) {
5354
+ this.inThread.add(kind);
5355
+ throw e2;
5356
+ }
5357
+ if (this.closed) throw new Error("closed");
5358
+ }
5359
+ // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
5360
+ uploadClassMask(width, height, data) {
5361
+ const gl = this.gl;
5362
+ if (!this.classMaskTex) {
5363
+ this.classMaskTex = gl.createTexture();
5364
+ gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
5365
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
5366
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
5367
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
5368
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
5369
+ }
5370
+ gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
5371
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
5372
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
5373
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
5374
+ gl.bindTexture(gl.TEXTURE_2D, null);
5375
+ this.classMaskFresh = true;
5376
+ }
5377
+ /** Hands a copy of this frame to the detect worker; the caller's frame stays its own. */
5378
+ requestRemote(kind, source, timestampUs) {
5379
+ let frame = null;
5380
+ try {
5381
+ frame = source instanceof VideoFrame ? source.clone() : new VideoFrame(source, { timestamp: timestampUs });
5382
+ } catch {
5383
+ }
5384
+ if (frame) this.detect?.request(kind, frame, timestampUs);
5385
+ }
5202
5386
  ensureClassSegmenter() {
5203
- if (this.classSegmenter || this.closed) return Promise.resolve();
5387
+ if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
5204
5388
  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) => {
5389
+ this.classLoading = this.remote("mask", (d2) => d2.initMask("classes")).then(() => {
5390
+ this.classRemote = true;
5391
+ }).catch(
5392
+ () => createSegmenter(this.canvas, "classes").then((s2) => {
5393
+ if (this.closed) {
5394
+ s2.close();
5395
+ return;
5396
+ }
5397
+ this.classSegmenter = s2;
5398
+ })
5399
+ ).catch((e2) => {
5212
5400
  console.error("mediakit: multiclass segmenter failed to load", e2);
5213
5401
  }).finally(() => {
5214
5402
  this.classLoading = null;
@@ -5252,8 +5440,22 @@
5252
5440
  let mask = null;
5253
5441
  let maskKind = 0;
5254
5442
  let segMs = 0;
5443
+ let faceMs = 0;
5255
5444
  this.used = null;
5256
- if (needSeg) {
5445
+ let served = false;
5446
+ if (needSeg && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
5447
+ this.requestRemote("mask", source, timestampUs);
5448
+ if (this.classMaskTex) {
5449
+ served = true;
5450
+ if (this.classMaskFresh) {
5451
+ this.classMaskFresh = false;
5452
+ mask = this.classMaskTex;
5453
+ maskKind = 1;
5454
+ segMs = this.maskWorkerMs;
5455
+ }
5456
+ }
5457
+ }
5458
+ if (needSeg && !served) {
5257
5459
  const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects);
5258
5460
  const seg = classes ? this.classSegmenter : this.segmenter;
5259
5461
  if (!seg) {
@@ -5267,10 +5469,15 @@
5267
5469
  }
5268
5470
  }
5269
5471
  if (this.core.decideFace() === 1) {
5270
- if (!this.face) {
5472
+ if (this.faceRemote) {
5473
+ this.requestRemote("face", source, timestampUs);
5474
+ faceMs = this.faceWorkerMs;
5475
+ } else if (!this.face) {
5271
5476
  void this.ensureFace();
5272
5477
  } else if (this.lmBuf) {
5478
+ const f0 = performance.now();
5273
5479
  const n2 = this.face.detect(source, timestampUs / 1e3, this.lmBuf);
5480
+ faceMs = performance.now() - f0;
5274
5481
  this.core.setFace(lo2, hi2, n2);
5275
5482
  }
5276
5483
  }
@@ -5283,6 +5490,7 @@
5283
5490
  this.last = {
5284
5491
  totalMs: this.prevTotalMs,
5285
5492
  segMs,
5493
+ faceMs,
5286
5494
  glCalls,
5287
5495
  segmented: needSeg && mask !== null,
5288
5496
  maskScale: s2 ? s2[1] : 1,
@@ -5320,6 +5528,12 @@
5320
5528
  this.classSegmenter = null;
5321
5529
  this.face?.close();
5322
5530
  this.face = null;
5531
+ this.detect?.close();
5532
+ this.detect = null;
5533
+ this.faceRemote = false;
5534
+ this.classRemote = false;
5535
+ if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
5536
+ this.classMaskTex = null;
5323
5537
  this.lmBuf = null;
5324
5538
  this.core.close();
5325
5539
  this.background?.close();
@@ -5400,7 +5614,7 @@
5400
5614
  }
5401
5615
  async function run(m2, readable, writable, outTrack) {
5402
5616
  const canvas = new OffscreenCanvas(m2.width, m2.height);
5403
- engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false);
5617
+ engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false, m2.maxFaces);
5404
5618
  abort = new AbortController();
5405
5619
  let n2 = 0;
5406
5620
  let lastPost = performance.now();