@tradalab/mediakit 2.1.1 → 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,13 +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;
5144
5167
  detectCanvas = null;
5168
+ detectCanvasTs = -1;
5145
5169
  // A kind whose worker failed once stays in-thread.
5146
5170
  inThread = /* @__PURE__ */ new Set();
5147
5171
  faceLoading = null;
@@ -5291,6 +5315,7 @@
5291
5315
  this.core.setRecipe(coreRecipe(filter, effects));
5292
5316
  if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
5293
5317
  if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
5318
+ if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
5294
5319
  if (needsFace(effects)) void this.ensureFace();
5295
5320
  }
5296
5321
  ensureFace() {
@@ -5320,11 +5345,38 @@
5320
5345
  return this.faceLoading;
5321
5346
  }
5322
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
+ }
5323
5361
  async remote(kind, init) {
5324
5362
  if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
5325
5363
  throw new Error("in-thread");
5326
5364
  }
5327
- 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 {
5328
5380
  face: (tsUs, n2, lm, ms2) => {
5329
5381
  if (this.closed || !this.lmBuf) return;
5330
5382
  this.lmBuf.set(lm);
@@ -5332,15 +5384,25 @@
5332
5384
  this.core.setFace(lo2, hi2, n2);
5333
5385
  this.faceWorkerMs = ms2;
5334
5386
  },
5335
- mask: (_tsUs, width, height, data, ms2) => {
5387
+ mask: (tsUs, width, height, data, ms2) => {
5336
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
+ }
5337
5396
  this.uploadClassMask(width, height, data);
5397
+ this.classMaskTs = tsUs;
5338
5398
  this.maskWorkerMs = ms2;
5339
5399
  },
5340
5400
  failed: (k2, reason) => {
5341
- console.warn(`mediakit: ${k2} detection moves into this thread:`, reason);
5342
- this.inThread.add(k2);
5343
- 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") {
5344
5406
  this.faceRemote = false;
5345
5407
  void this.ensureFace();
5346
5408
  } else {
@@ -5348,53 +5410,62 @@
5348
5410
  void this.ensureClassSegmenter();
5349
5411
  }
5350
5412
  }
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");
5413
+ };
5359
5414
  }
5360
- // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
5361
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) {
5362
5421
  const gl = this.gl;
5363
- if (!this.classMaskTex) {
5364
- this.classMaskTex = gl.createTexture();
5365
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
5422
+ if (!tex) {
5423
+ tex = gl.createTexture();
5424
+ gl.bindTexture(gl.TEXTURE_2D, tex);
5366
5425
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
5367
5426
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
5368
5427
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
5369
5428
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
5370
5429
  }
5371
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
5430
+ gl.bindTexture(gl.TEXTURE_2D, tex);
5372
5431
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
5373
5432
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
5374
5433
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
5375
5434
  gl.bindTexture(gl.TEXTURE_2D, null);
5376
- this.classMaskFresh = true;
5435
+ return tex;
5377
5436
  }
5378
5437
  /**
5379
5438
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
5380
5439
  * detection drains Chrome's few capture buffers and throttles the camera itself.
5381
5440
  */
5382
5441
  requestRemote(kind, source, timestampUs) {
5442
+ const detect = this.detects.get(kind);
5443
+ if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
5383
5444
  let frame = null;
5384
5445
  try {
5385
- frame = new VideoFrame(source instanceof VideoFrame ? this.detectCopy(source) : source, {
5446
+ const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
5447
+ frame = new VideoFrame(copyable ? this.detectCopy(source, timestampUs) : source, {
5386
5448
  timestamp: timestampUs
5387
5449
  });
5388
5450
  } catch {
5389
5451
  }
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);
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
+ }
5398
5469
  return this.detectCanvas;
5399
5470
  }
5400
5471
  ensureClassSegmenter() {
@@ -5435,8 +5506,7 @@
5435
5506
  }
5436
5507
  /**
5437
5508
  * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
5438
- * yet, the segmenter is still loading, or the recipe is inactive; the transport must
5439
- * forward the original frame rather than drop it.
5509
+ * yet, the segmenter is still loading, or the recipe is inactive.
5440
5510
  *
5441
5511
  * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
5442
5512
  * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
@@ -5448,16 +5518,69 @@
5448
5518
  */
5449
5519
  render(source, timestampUs) {
5450
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) {
5451
5561
  const t0 = performance.now();
5452
5562
  const [lo2, hi2] = splitMicros(timestampUs);
5453
5563
  const needSeg = this.core.decide(lo2, hi2, this.prevTotalMs, this.prevSegMs) === 1;
5454
5564
  let mask = null;
5455
5565
  let maskKind = 0;
5566
+ let maskTs = timestampUs;
5456
5567
  let segMs = 0;
5457
5568
  let faceMs = 0;
5458
5569
  this.used = null;
5459
5570
  let served = false;
5460
- 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)) {
5461
5584
  this.requestRemote("mask", source, timestampUs);
5462
5585
  if (this.classMaskTex) {
5463
5586
  served = true;
@@ -5465,6 +5588,7 @@
5465
5588
  this.classMaskFresh = false;
5466
5589
  mask = this.classMaskTex;
5467
5590
  maskKind = 1;
5591
+ maskTs = this.classMaskTs;
5468
5592
  segMs = this.maskWorkerMs;
5469
5593
  }
5470
5594
  }
@@ -5482,7 +5606,9 @@
5482
5606
  maskKind = classes ? 1 : 0;
5483
5607
  }
5484
5608
  }
5485
- if (this.core.decideFace() === 1) {
5609
+ if (faceDone) {
5610
+ faceMs = this.faceWorkerMs;
5611
+ } else if (this.core.decideFace() === 1) {
5486
5612
  if (this.faceRemote) {
5487
5613
  this.requestRemote("face", source, timestampUs);
5488
5614
  faceMs = this.faceWorkerMs;
@@ -5495,7 +5621,8 @@
5495
5621
  this.core.setFace(lo2, hi2, n2);
5496
5622
  }
5497
5623
  }
5498
- 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);
5499
5626
  if (mask) this.used?.release();
5500
5627
  this.used = null;
5501
5628
  this.prevSegMs = segMs;
@@ -5542,13 +5669,18 @@
5542
5669
  this.classSegmenter = null;
5543
5670
  this.face?.close();
5544
5671
  this.face = null;
5545
- this.detect?.close();
5546
- this.detect = null;
5672
+ for (const detect of this.detects.values()) detect.close();
5673
+ this.detects.clear();
5547
5674
  this.faceRemote = false;
5548
5675
  this.classRemote = false;
5549
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;
5550
5680
  this.classMaskTex = null;
5551
5681
  this.lmBuf = null;
5682
+ this.held = [null, null];
5683
+ this.lastHeld = null;
5552
5684
  this.core.close();
5553
5685
  this.background?.close();
5554
5686
  this.background = null;
@@ -5629,6 +5761,7 @@
5629
5761
  async function run(m2, readable, writable, outTrack) {
5630
5762
  const canvas = new OffscreenCanvas(m2.width, m2.height);
5631
5763
  engine = await Engine.on(canvas, m2.filter, m2.effects, m2.background, m2.alpha ?? false, m2.maxFaces);
5764
+ engine.syncFaces = m2.syncFaces ?? false;
5632
5765
  abort = new AbortController();
5633
5766
  let n2 = 0;
5634
5767
  let lastPost = performance.now();
@@ -5650,6 +5783,20 @@
5650
5783
  } catch (e2) {
5651
5784
  post({ t: "error", message: e2 instanceof Error ? e2.message : String(e2) });
5652
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
+ }
5653
5800
  if (!drew || !engine) {
5654
5801
  if (framesOn) {
5655
5802
  const copy = frame.clone();
@@ -5658,9 +5805,9 @@
5658
5805
  controller.enqueue(frame);
5659
5806
  return;
5660
5807
  }
5661
- controller.enqueue(engine.capture(ts2));
5808
+ controller.enqueue(engine.capture(engine.renderedTs));
5662
5809
  if (framesOn) {
5663
- const copy = engine.capture(ts2, true);
5810
+ const copy = engine.capture(engine.renderedTs, true);
5664
5811
  self.postMessage({ t: "frame", frame: copy }, [copy]);
5665
5812
  }
5666
5813
  frame.close();