@tradalab/mediakit 2.1.0 → 2.2.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/recipe.js CHANGED
@@ -18,7 +18,7 @@ import {
18
18
  normalizeEffects,
19
19
  touchUp,
20
20
  touchUpAmount
21
- } from "./chunk-TBMYRKXR.js";
21
+ } from "./chunk-2AD2GLNR.js";
22
22
  export {
23
23
  EFFECTS_SCHEMA,
24
24
  GRADE_SCOPE,
package/dist/worker.js CHANGED
@@ -4783,9 +4783,13 @@
4783
4783
  initMask(model) {
4784
4784
  return this.init("mask", { t: "initMask", model });
4785
4785
  }
4786
+ /** Whether `request` would take a frame of this kind now. */
4787
+ accepts(kind) {
4788
+ return this.worker !== null && this.up.has(kind) && !this.busy.has(kind);
4789
+ }
4786
4790
  /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */
4787
4791
  request(kind, frame, tsUs) {
4788
- if (!this.worker || !this.up.has(kind) || this.busy.has(kind)) {
4792
+ if (!this.accepts(kind)) {
4789
4793
  frame.close();
4790
4794
  return false;
4791
4795
  }
@@ -5013,7 +5017,7 @@
5013
5017
  return needsMask(f2, e2) && !e2.chromaKey;
5014
5018
  }
5015
5019
  function needsSkinClasses(_f, e2) {
5016
- return (e2.whiten ?? 0) > 0 || (e2.skinLight ?? 0) > 0 || e2.grade > 0 && (e2.gradeScope ?? "frame") !== "frame";
5020
+ return e2.grade > 0 && (e2.gradeScope ?? "frame") !== "frame";
5017
5021
  }
5018
5022
  function needsFace(e2) {
5019
5023
  return e2.teeth > 0 || e2.eyeBright > 0 || e2.underEye > 0 || e2.smileLines > 0 || e2.lips > 0 || e2.blush > 0 || e2.iris > 0 || (e2.eyeShadow ?? 0) > 0 || (e2.lipGloss ?? 0) > 0 || (e2.rosy ?? 0) > 0 || e2.skinScope === "face" && (e2.beautify > 0 || hasSkin(e2)) || // Whitening and skin light measure skin on the face; clarity is held to it.
@@ -5094,6 +5098,12 @@
5094
5098
  autoExposure: 0,
5095
5099
  faces: 0
5096
5100
  };
5101
+ function sourceSize(source) {
5102
+ if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
5103
+ if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
5104
+ const s2 = source;
5105
+ return [s2.width, s2.height];
5106
+ }
5097
5107
  var Engine = class _Engine {
5098
5108
  canvas;
5099
5109
  gl;
@@ -5135,12 +5145,27 @@
5135
5145
  // stalls the picture for that long. `face` is the fallback when no worker can be made.
5136
5146
  faceRemote = false;
5137
5147
  faceWorkerMs = 0;
5138
- // The multiclass segmenter in that same worker: its mask comes back as bytes, uploaded here.
5139
5148
  classRemote = false;
5140
5149
  classMaskTex = null;
5141
5150
  classMaskFresh = false;
5151
+ classMaskTs = 0;
5152
+ syncFaces = false;
5153
+ renderedTs = 0;
5154
+ held = [null, null];
5155
+ heldTs = -1;
5156
+ heldSlot = 0;
5157
+ lastHeld = null;
5158
+ swallowed = false;
5142
5159
  maskWorkerMs = 0;
5143
- detect = null;
5160
+ detects = /* @__PURE__ */ new Map();
5161
+ personRemote = false;
5162
+ personLoading = null;
5163
+ personMaskTex = null;
5164
+ personMaskFresh = false;
5165
+ personMaskTs = 0;
5166
+ personWorkerMs = 0;
5167
+ detectCanvas = null;
5168
+ detectCanvasTs = -1;
5144
5169
  // A kind whose worker failed once stays in-thread.
5145
5170
  inThread = /* @__PURE__ */ new Set();
5146
5171
  faceLoading = null;
@@ -5290,6 +5315,7 @@
5290
5315
  this.core.setRecipe(coreRecipe(filter, effects));
5291
5316
  if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
5292
5317
  if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
5318
+ if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
5293
5319
  if (needsFace(effects)) void this.ensureFace();
5294
5320
  }
5295
5321
  ensureFace() {
@@ -5319,11 +5345,38 @@
5319
5345
  return this.faceLoading;
5320
5346
  }
5321
5347
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
5348
+ personRemoteWanted(filter, effects) {
5349
+ return filter.kind === "none" && needsSegmentation(filter, effects) && !needsSkinClasses(filter, effects);
5350
+ }
5351
+ ensurePersonRemote() {
5352
+ if (this.personRemote || this.closed) return Promise.resolve();
5353
+ this.personLoading ??= this.remote("person", (d2) => d2.initMask("person")).then(() => {
5354
+ this.personRemote = true;
5355
+ }).catch(() => {
5356
+ }).finally(() => {
5357
+ this.personLoading = null;
5358
+ });
5359
+ return this.personLoading;
5360
+ }
5322
5361
  async remote(kind, init) {
5323
5362
  if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
5324
5363
  throw new Error("in-thread");
5325
5364
  }
5326
- this.detect ??= new DetectWorker({
5365
+ let detect = this.detects.get(kind);
5366
+ if (!detect) {
5367
+ detect = new DetectWorker(this.detectHandlers(kind));
5368
+ this.detects.set(kind, detect);
5369
+ }
5370
+ try {
5371
+ await init(detect);
5372
+ } catch (e2) {
5373
+ this.inThread.add(kind);
5374
+ throw e2;
5375
+ }
5376
+ if (this.closed) throw new Error("closed");
5377
+ }
5378
+ detectHandlers(key) {
5379
+ return {
5327
5380
  face: (tsUs, n2, lm, ms2) => {
5328
5381
  if (this.closed || !this.lmBuf) return;
5329
5382
  this.lmBuf.set(lm);
@@ -5331,15 +5384,25 @@
5331
5384
  this.core.setFace(lo2, hi2, n2);
5332
5385
  this.faceWorkerMs = ms2;
5333
5386
  },
5334
- mask: (_tsUs, width, height, data, ms2) => {
5387
+ mask: (tsUs, width, height, data, ms2) => {
5335
5388
  if (this.closed) return;
5389
+ if (key === "person") {
5390
+ this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, width, height, data);
5391
+ this.personMaskFresh = true;
5392
+ this.personMaskTs = tsUs;
5393
+ this.personWorkerMs = ms2;
5394
+ return;
5395
+ }
5336
5396
  this.uploadClassMask(width, height, data);
5397
+ this.classMaskTs = tsUs;
5337
5398
  this.maskWorkerMs = ms2;
5338
5399
  },
5339
5400
  failed: (k2, reason) => {
5340
- console.warn(`mediakit: ${k2} detection moves into this thread:`, reason);
5341
- this.inThread.add(k2);
5342
- if (k2 === "face") {
5401
+ console.warn(`mediakit: ${key} detection moves into this thread:`, reason);
5402
+ this.inThread.add(key);
5403
+ if (key === "person") {
5404
+ this.personRemote = false;
5405
+ } else if (k2 === "face") {
5343
5406
  this.faceRemote = false;
5344
5407
  void this.ensureFace();
5345
5408
  } else {
@@ -5347,41 +5410,63 @@
5347
5410
  void this.ensureClassSegmenter();
5348
5411
  }
5349
5412
  }
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");
5413
+ };
5358
5414
  }
5359
- // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
5360
5415
  uploadClassMask(width, height, data) {
5416
+ this.classMaskTex = this.uploadMaskBytes(this.classMaskTex, width, height, data);
5417
+ this.classMaskFresh = true;
5418
+ }
5419
+ // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
5420
+ uploadMaskBytes(tex, width, height, data) {
5361
5421
  const gl = this.gl;
5362
- if (!this.classMaskTex) {
5363
- this.classMaskTex = gl.createTexture();
5364
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
5422
+ if (!tex) {
5423
+ tex = gl.createTexture();
5424
+ gl.bindTexture(gl.TEXTURE_2D, tex);
5365
5425
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
5366
5426
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
5367
5427
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
5368
5428
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
5369
5429
  }
5370
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
5430
+ gl.bindTexture(gl.TEXTURE_2D, tex);
5371
5431
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
5372
5432
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
5373
5433
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
5374
5434
  gl.bindTexture(gl.TEXTURE_2D, null);
5375
- this.classMaskFresh = true;
5435
+ return tex;
5376
5436
  }
5377
- /** Hands a copy of this frame to the detect worker; the caller's frame stays its own. */
5437
+ /**
5438
+ * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
5439
+ * detection drains Chrome's few capture buffers and throttles the camera itself.
5440
+ */
5378
5441
  requestRemote(kind, source, timestampUs) {
5442
+ const detect = this.detects.get(kind);
5443
+ if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
5379
5444
  let frame = null;
5380
5445
  try {
5381
- frame = source instanceof VideoFrame ? source.clone() : new VideoFrame(source, { timestamp: timestampUs });
5446
+ const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
5447
+ frame = new VideoFrame(copyable ? this.detectCopy(source, timestampUs) : source, {
5448
+ timestamp: timestampUs
5449
+ });
5382
5450
  } catch {
5383
5451
  }
5384
- if (frame) this.detect?.request(kind, frame, timestampUs);
5452
+ if (frame) detect.request(kind === "face" ? "face" : "mask", frame, timestampUs);
5453
+ }
5454
+ /** Face and mask asked on the same frame share one draw. */
5455
+ detectCopy(source, timestampUs) {
5456
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
5457
+ const sh2 = source instanceof VideoFrame ? source.displayHeight : source.height;
5458
+ const s2 = Math.min(1, 512 / Math.max(sw, sh2));
5459
+ const w2 = Math.max(1, Math.round(sw * s2));
5460
+ const h2 = Math.max(1, Math.round(sh2 * s2));
5461
+ if (!this.detectCanvas || this.detectCanvas.width !== w2 || this.detectCanvas.height !== h2) {
5462
+ this.detectCanvas = new OffscreenCanvas(w2, h2);
5463
+ this.detectCanvasTs = -1;
5464
+ }
5465
+ if (this.detectCanvasTs !== timestampUs) {
5466
+ this.detectCanvas.getContext("2d").drawImage(source, 0, 0, w2, h2);
5467
+ this.detectCanvasTs = timestampUs;
5468
+ }
5469
+ return this.detectCanvas;
5385
5470
  }
5386
5471
  ensureClassSegmenter() {
5387
5472
  if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
@@ -5421,8 +5506,7 @@
5421
5506
  }
5422
5507
  /**
5423
5508
  * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
5424
- * yet, the segmenter is still loading, or the recipe is inactive; the transport must
5425
- * forward the original frame rather than drop it.
5509
+ * yet, the segmenter is still loading, or the recipe is inactive.
5426
5510
  *
5427
5511
  * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
5428
5512
  * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
@@ -5434,16 +5518,69 @@
5434
5518
  */
5435
5519
  render(source, timestampUs) {
5436
5520
  if (this.closed) return false;
5521
+ this.lastHeld = null;
5522
+ this.swallowed = false;
5523
+ if (!this.syncing() || typeof ImageData !== "undefined" && source instanceof ImageData) {
5524
+ this.heldTs = -1;
5525
+ this.renderedTs = timestampUs;
5526
+ return this.draw(source, timestampUs, false);
5527
+ }
5528
+ this.requestRemote("face", source, timestampUs);
5529
+ const prev = this.heldTs >= 0 ? this.held[this.heldSlot] : null;
5530
+ const prevTs = this.heldTs;
5531
+ this.heldSlot ^= 1;
5532
+ this.hold(source, this.heldSlot);
5533
+ this.heldTs = timestampUs;
5534
+ if (!prev) {
5535
+ this.swallowed = true;
5536
+ return false;
5537
+ }
5538
+ this.lastHeld = prev;
5539
+ this.renderedTs = prevTs;
5540
+ return this.draw(prev, prevTs, true);
5541
+ }
5542
+ dropped() {
5543
+ return this.swallowed;
5544
+ }
5545
+ passthrough() {
5546
+ return this.lastHeld ? new VideoFrame(this.lastHeld, { timestamp: this.renderedTs }) : null;
5547
+ }
5548
+ syncing() {
5549
+ return this.syncFaces && this.faceRemote && needsFace(this.effects);
5550
+ }
5551
+ hold(source, slot) {
5552
+ const [w2, h2] = sourceSize(source);
5553
+ let c2 = this.held[slot];
5554
+ if (!c2 || c2.width !== w2 || c2.height !== h2) {
5555
+ c2 = new OffscreenCanvas(w2, h2);
5556
+ this.held[slot] = c2;
5557
+ }
5558
+ c2.getContext("2d").drawImage(source, 0, 0, w2, h2);
5559
+ }
5560
+ draw(source, timestampUs, faceDone) {
5437
5561
  const t0 = performance.now();
5438
5562
  const [lo2, hi2] = splitMicros(timestampUs);
5439
5563
  const needSeg = this.core.decide(lo2, hi2, this.prevTotalMs, this.prevSegMs) === 1;
5440
5564
  let mask = null;
5441
5565
  let maskKind = 0;
5566
+ let maskTs = timestampUs;
5442
5567
  let segMs = 0;
5443
5568
  let faceMs = 0;
5444
5569
  this.used = null;
5445
5570
  let served = false;
5446
- if (needSeg && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
5571
+ if (needSeg && this.personRemote && this.personRemoteWanted(this.filter, this.effects)) {
5572
+ this.requestRemote("person", source, timestampUs);
5573
+ if (this.personMaskTex) {
5574
+ served = true;
5575
+ if (this.personMaskFresh) {
5576
+ this.personMaskFresh = false;
5577
+ mask = this.personMaskTex;
5578
+ maskTs = this.personMaskTs;
5579
+ segMs = this.personWorkerMs;
5580
+ }
5581
+ }
5582
+ }
5583
+ if (needSeg && !served && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
5447
5584
  this.requestRemote("mask", source, timestampUs);
5448
5585
  if (this.classMaskTex) {
5449
5586
  served = true;
@@ -5451,6 +5588,7 @@
5451
5588
  this.classMaskFresh = false;
5452
5589
  mask = this.classMaskTex;
5453
5590
  maskKind = 1;
5591
+ maskTs = this.classMaskTs;
5454
5592
  segMs = this.maskWorkerMs;
5455
5593
  }
5456
5594
  }
@@ -5468,7 +5606,9 @@
5468
5606
  maskKind = classes ? 1 : 0;
5469
5607
  }
5470
5608
  }
5471
- if (this.core.decideFace() === 1) {
5609
+ if (faceDone) {
5610
+ faceMs = this.faceWorkerMs;
5611
+ } else if (this.core.decideFace() === 1) {
5472
5612
  if (this.faceRemote) {
5473
5613
  this.requestRemote("face", source, timestampUs);
5474
5614
  faceMs = this.faceWorkerMs;
@@ -5481,7 +5621,8 @@
5481
5621
  this.core.setFace(lo2, hi2, n2);
5482
5622
  }
5483
5623
  }
5484
- const glCalls = this.core.process(source, mask, this.background, maskKind);
5624
+ const [maskLo, maskHi] = splitMicros(maskTs);
5625
+ const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
5485
5626
  if (mask) this.used?.release();
5486
5627
  this.used = null;
5487
5628
  this.prevSegMs = segMs;
@@ -5528,13 +5669,18 @@
5528
5669
  this.classSegmenter = null;
5529
5670
  this.face?.close();
5530
5671
  this.face = null;
5531
- this.detect?.close();
5532
- this.detect = null;
5672
+ for (const detect of this.detects.values()) detect.close();
5673
+ this.detects.clear();
5533
5674
  this.faceRemote = false;
5534
5675
  this.classRemote = false;
5535
5676
  if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
5677
+ if (this.personMaskTex) this.gl.deleteTexture(this.personMaskTex);
5678
+ this.personMaskTex = null;
5679
+ this.personRemote = false;
5536
5680
  this.classMaskTex = null;
5537
5681
  this.lmBuf = null;
5682
+ this.held = [null, null];
5683
+ this.lastHeld = null;
5538
5684
  this.core.close();
5539
5685
  this.background?.close();
5540
5686
  this.background = null;
@@ -5615,6 +5761,7 @@
5615
5761
  async function run(m2, readable, writable, outTrack) {
5616
5762
  const canvas = new OffscreenCanvas(m2.width, m2.height);
5617
5763
  engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false, m2.maxFaces);
5764
+ engine.syncFaces = m2.syncFaces ?? false;
5618
5765
  abort = new AbortController();
5619
5766
  let n2 = 0;
5620
5767
  let lastPost = performance.now();
@@ -5636,6 +5783,20 @@
5636
5783
  } catch (e2) {
5637
5784
  post({ t: "error", message: e2 instanceof Error ? e2.message : String(e2) });
5638
5785
  }
5786
+ if (!drew && engine?.dropped()) {
5787
+ frame.close();
5788
+ return;
5789
+ }
5790
+ const held = !drew && engine ? engine.passthrough() : null;
5791
+ if (held) {
5792
+ if (framesOn) {
5793
+ const copy = held.clone();
5794
+ self.postMessage({ t: "frame", frame: copy }, [copy]);
5795
+ }
5796
+ controller.enqueue(held);
5797
+ frame.close();
5798
+ return;
5799
+ }
5639
5800
  if (!drew || !engine) {
5640
5801
  if (framesOn) {
5641
5802
  const copy = frame.clone();
@@ -5644,9 +5805,9 @@
5644
5805
  controller.enqueue(frame);
5645
5806
  return;
5646
5807
  }
5647
- controller.enqueue(engine.capture(ts2));
5808
+ controller.enqueue(engine.capture(engine.renderedTs));
5648
5809
  if (framesOn) {
5649
- const copy = engine.capture(ts2, true);
5810
+ const copy = engine.capture(engine.renderedTs, true);
5650
5811
  self.postMessage({ t: "frame", frame: copy }, [copy]);
5651
5812
  }
5652
5813
  frame.close();