@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.
package/dist/index.d.ts CHANGED
@@ -81,9 +81,24 @@ declare class Engine {
81
81
  private classRemote;
82
82
  private classMaskTex;
83
83
  private classMaskFresh;
84
+ private classMaskTs;
85
+ syncFaces: boolean;
86
+ renderedTs: number;
87
+ private held;
88
+ private heldTs;
89
+ private heldSlot;
90
+ private lastHeld;
91
+ private swallowed;
84
92
  private maskWorkerMs;
85
- private detect;
93
+ private readonly detects;
94
+ private personRemote;
95
+ private personLoading;
96
+ private personMaskTex;
97
+ private personMaskFresh;
98
+ private personMaskTs;
99
+ private personWorkerMs;
86
100
  private detectCanvas;
101
+ private detectCanvasTs;
87
102
  private readonly inThread;
88
103
  private faceLoading;
89
104
  private maxFaces;
@@ -115,20 +130,24 @@ declare class Engine {
115
130
  setRecipe(filter: BgFilter, effects?: Effects, background?: ImageBitmap): Promise<void>;
116
131
  private ensureFace;
117
132
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
133
+ private personRemoteWanted;
134
+ private ensurePersonRemote;
118
135
  private remote;
136
+ private detectHandlers;
119
137
  private uploadClassMask;
138
+ private uploadMaskBytes;
120
139
  /**
121
140
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
122
141
  * detection drains Chrome's few capture buffers and throttles the camera itself.
123
142
  */
124
143
  private requestRemote;
144
+ /** Face and mask asked on the same frame share one draw. */
125
145
  private detectCopy;
126
146
  private ensureClassSegmenter;
127
147
  private ensureSegmenter;
128
148
  /**
129
149
  * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
130
- * yet, the segmenter is still loading, or the recipe is inactive; the transport must
131
- * forward the original frame rather than drop it.
150
+ * yet, the segmenter is still loading, or the recipe is inactive.
132
151
  *
133
152
  * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
134
153
  * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
@@ -139,6 +158,11 @@ declare class Engine {
139
158
  * it constructs one only to destroy it again.
140
159
  */
141
160
  render(source: TexImageSource, timestampUs: number): boolean;
161
+ dropped(): boolean;
162
+ passthrough(): VideoFrame | null;
163
+ private syncing;
164
+ private hold;
165
+ private draw;
142
166
  /**
143
167
  * Wrap the output canvas as a new VideoFrame.
144
168
  *
@@ -187,6 +211,7 @@ interface PipelineOptions {
187
211
  * the face detector on every call, about a third of the landmark cost.
188
212
  */
189
213
  maxFaces?: number;
214
+ syncFaces?: boolean;
190
215
  /** No processed frame for 2 s while the camera is live (20 s while a detector loads). */
191
216
  onStall?: (info: {
192
217
  transport: Transport;
package/dist/index.js CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  normalizeEffects,
11
11
  touchUp,
12
12
  touchUpAmount
13
- } from "./chunk-TBMYRKXR.js";
13
+ } from "./chunk-2AD2GLNR.js";
14
14
  import {
15
15
  BLEND_MODES,
16
16
  TRANSITIONS,
@@ -130,9 +130,13 @@ var DetectWorker = class {
130
130
  initMask(model) {
131
131
  return this.init("mask", { t: "initMask", model });
132
132
  }
133
+ /** Whether `request` would take a frame of this kind now. */
134
+ accepts(kind) {
135
+ return this.worker !== null && this.up.has(kind) && !this.busy.has(kind);
136
+ }
133
137
  /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */
134
138
  request(kind, frame, tsUs) {
135
- if (!this.worker || !this.up.has(kind) || this.busy.has(kind)) {
139
+ if (!this.accepts(kind)) {
136
140
  frame.close();
137
141
  return false;
138
142
  }
@@ -296,6 +300,12 @@ var ZERO_STATS = {
296
300
  autoExposure: 0,
297
301
  faces: 0
298
302
  };
303
+ function sourceSize(source) {
304
+ if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
305
+ if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
306
+ const s = source;
307
+ return [s.width, s.height];
308
+ }
299
309
  var Engine = class _Engine {
300
310
  canvas;
301
311
  gl;
@@ -337,13 +347,27 @@ var Engine = class _Engine {
337
347
  // stalls the picture for that long. `face` is the fallback when no worker can be made.
338
348
  faceRemote = false;
339
349
  faceWorkerMs = 0;
340
- // The multiclass segmenter in that same worker: its mask comes back as bytes, uploaded here.
341
350
  classRemote = false;
342
351
  classMaskTex = null;
343
352
  classMaskFresh = false;
353
+ classMaskTs = 0;
354
+ syncFaces = false;
355
+ renderedTs = 0;
356
+ held = [null, null];
357
+ heldTs = -1;
358
+ heldSlot = 0;
359
+ lastHeld = null;
360
+ swallowed = false;
344
361
  maskWorkerMs = 0;
345
- detect = null;
362
+ detects = /* @__PURE__ */ new Map();
363
+ personRemote = false;
364
+ personLoading = null;
365
+ personMaskTex = null;
366
+ personMaskFresh = false;
367
+ personMaskTs = 0;
368
+ personWorkerMs = 0;
346
369
  detectCanvas = null;
370
+ detectCanvasTs = -1;
347
371
  // A kind whose worker failed once stays in-thread.
348
372
  inThread = /* @__PURE__ */ new Set();
349
373
  faceLoading = null;
@@ -493,6 +517,7 @@ var Engine = class _Engine {
493
517
  this.core.setRecipe(coreRecipe(filter, effects));
494
518
  if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
495
519
  if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
520
+ if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
496
521
  if (needsFace(effects)) void this.ensureFace();
497
522
  }
498
523
  ensureFace() {
@@ -522,11 +547,38 @@ var Engine = class _Engine {
522
547
  return this.faceLoading;
523
548
  }
524
549
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
550
+ personRemoteWanted(filter, effects) {
551
+ return filter.kind === "none" && needsSegmentation(filter, effects) && !needsSkinClasses(filter, effects);
552
+ }
553
+ ensurePersonRemote() {
554
+ if (this.personRemote || this.closed) return Promise.resolve();
555
+ this.personLoading ??= this.remote("person", (d) => d.initMask("person")).then(() => {
556
+ this.personRemote = true;
557
+ }).catch(() => {
558
+ }).finally(() => {
559
+ this.personLoading = null;
560
+ });
561
+ return this.personLoading;
562
+ }
525
563
  async remote(kind, init) {
526
564
  if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
527
565
  throw new Error("in-thread");
528
566
  }
529
- this.detect ??= new DetectWorker({
567
+ let detect = this.detects.get(kind);
568
+ if (!detect) {
569
+ detect = new DetectWorker(this.detectHandlers(kind));
570
+ this.detects.set(kind, detect);
571
+ }
572
+ try {
573
+ await init(detect);
574
+ } catch (e) {
575
+ this.inThread.add(kind);
576
+ throw e;
577
+ }
578
+ if (this.closed) throw new Error("closed");
579
+ }
580
+ detectHandlers(key) {
581
+ return {
530
582
  face: (tsUs, n, lm, ms) => {
531
583
  if (this.closed || !this.lmBuf) return;
532
584
  this.lmBuf.set(lm);
@@ -534,15 +586,25 @@ var Engine = class _Engine {
534
586
  this.core.setFace(lo, hi, n);
535
587
  this.faceWorkerMs = ms;
536
588
  },
537
- mask: (_tsUs, width, height, data, ms) => {
589
+ mask: (tsUs, width, height, data, ms) => {
538
590
  if (this.closed) return;
591
+ if (key === "person") {
592
+ this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, width, height, data);
593
+ this.personMaskFresh = true;
594
+ this.personMaskTs = tsUs;
595
+ this.personWorkerMs = ms;
596
+ return;
597
+ }
539
598
  this.uploadClassMask(width, height, data);
599
+ this.classMaskTs = tsUs;
540
600
  this.maskWorkerMs = ms;
541
601
  },
542
602
  failed: (k, reason) => {
543
- console.warn(`mediakit: ${k} detection moves into this thread:`, reason);
544
- this.inThread.add(k);
545
- if (k === "face") {
603
+ console.warn(`mediakit: ${key} detection moves into this thread:`, reason);
604
+ this.inThread.add(key);
605
+ if (key === "person") {
606
+ this.personRemote = false;
607
+ } else if (k === "face") {
546
608
  this.faceRemote = false;
547
609
  void this.ensureFace();
548
610
  } else {
@@ -550,53 +612,62 @@ var Engine = class _Engine {
550
612
  void this.ensureClassSegmenter();
551
613
  }
552
614
  }
553
- });
554
- try {
555
- await init(this.detect);
556
- } catch (e) {
557
- this.inThread.add(kind);
558
- throw e;
559
- }
560
- if (this.closed) throw new Error("closed");
615
+ };
561
616
  }
562
- // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
563
617
  uploadClassMask(width, height, data) {
618
+ this.classMaskTex = this.uploadMaskBytes(this.classMaskTex, width, height, data);
619
+ this.classMaskFresh = true;
620
+ }
621
+ // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
622
+ uploadMaskBytes(tex, width, height, data) {
564
623
  const gl = this.gl;
565
- if (!this.classMaskTex) {
566
- this.classMaskTex = gl.createTexture();
567
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
624
+ if (!tex) {
625
+ tex = gl.createTexture();
626
+ gl.bindTexture(gl.TEXTURE_2D, tex);
568
627
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
569
628
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
570
629
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
571
630
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
572
631
  }
573
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
632
+ gl.bindTexture(gl.TEXTURE_2D, tex);
574
633
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
575
634
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
576
635
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
577
636
  gl.bindTexture(gl.TEXTURE_2D, null);
578
- this.classMaskFresh = true;
637
+ return tex;
579
638
  }
580
639
  /**
581
640
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
582
641
  * detection drains Chrome's few capture buffers and throttles the camera itself.
583
642
  */
584
643
  requestRemote(kind, source, timestampUs) {
644
+ const detect = this.detects.get(kind);
645
+ if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
585
646
  let frame = null;
586
647
  try {
587
- frame = new VideoFrame(source instanceof VideoFrame ? this.detectCopy(source) : source, {
648
+ const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
649
+ frame = new VideoFrame(copyable ? this.detectCopy(source, timestampUs) : source, {
588
650
  timestamp: timestampUs
589
651
  });
590
652
  } catch {
591
653
  }
592
- if (frame) this.detect?.request(kind, frame, timestampUs);
593
- }
594
- detectCopy(source) {
595
- const s = Math.min(1, 512 / Math.max(source.displayWidth, source.displayHeight));
596
- const w = Math.max(1, Math.round(source.displayWidth * s));
597
- const h = Math.max(1, Math.round(source.displayHeight * s));
598
- if (!this.detectCanvas || this.detectCanvas.width !== w || this.detectCanvas.height !== h) this.detectCanvas = new OffscreenCanvas(w, h);
599
- this.detectCanvas.getContext("2d").drawImage(source, 0, 0, w, h);
654
+ if (frame) detect.request(kind === "face" ? "face" : "mask", frame, timestampUs);
655
+ }
656
+ /** Face and mask asked on the same frame share one draw. */
657
+ detectCopy(source, timestampUs) {
658
+ const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
659
+ const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
660
+ const s = Math.min(1, 512 / Math.max(sw, sh));
661
+ const w = Math.max(1, Math.round(sw * s));
662
+ const h = Math.max(1, Math.round(sh * s));
663
+ if (!this.detectCanvas || this.detectCanvas.width !== w || this.detectCanvas.height !== h) {
664
+ this.detectCanvas = new OffscreenCanvas(w, h);
665
+ this.detectCanvasTs = -1;
666
+ }
667
+ if (this.detectCanvasTs !== timestampUs) {
668
+ this.detectCanvas.getContext("2d").drawImage(source, 0, 0, w, h);
669
+ this.detectCanvasTs = timestampUs;
670
+ }
600
671
  return this.detectCanvas;
601
672
  }
602
673
  ensureClassSegmenter() {
@@ -637,8 +708,7 @@ var Engine = class _Engine {
637
708
  }
638
709
  /**
639
710
  * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
640
- * yet, the segmenter is still loading, or the recipe is inactive; the transport must
641
- * forward the original frame rather than drop it.
711
+ * yet, the segmenter is still loading, or the recipe is inactive.
642
712
  *
643
713
  * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
644
714
  * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
@@ -650,16 +720,69 @@ var Engine = class _Engine {
650
720
  */
651
721
  render(source, timestampUs) {
652
722
  if (this.closed) return false;
723
+ this.lastHeld = null;
724
+ this.swallowed = false;
725
+ if (!this.syncing() || typeof ImageData !== "undefined" && source instanceof ImageData) {
726
+ this.heldTs = -1;
727
+ this.renderedTs = timestampUs;
728
+ return this.draw(source, timestampUs, false);
729
+ }
730
+ this.requestRemote("face", source, timestampUs);
731
+ const prev = this.heldTs >= 0 ? this.held[this.heldSlot] : null;
732
+ const prevTs = this.heldTs;
733
+ this.heldSlot ^= 1;
734
+ this.hold(source, this.heldSlot);
735
+ this.heldTs = timestampUs;
736
+ if (!prev) {
737
+ this.swallowed = true;
738
+ return false;
739
+ }
740
+ this.lastHeld = prev;
741
+ this.renderedTs = prevTs;
742
+ return this.draw(prev, prevTs, true);
743
+ }
744
+ dropped() {
745
+ return this.swallowed;
746
+ }
747
+ passthrough() {
748
+ return this.lastHeld ? new VideoFrame(this.lastHeld, { timestamp: this.renderedTs }) : null;
749
+ }
750
+ syncing() {
751
+ return this.syncFaces && this.faceRemote && needsFace(this.effects);
752
+ }
753
+ hold(source, slot) {
754
+ const [w, h] = sourceSize(source);
755
+ let c = this.held[slot];
756
+ if (!c || c.width !== w || c.height !== h) {
757
+ c = new OffscreenCanvas(w, h);
758
+ this.held[slot] = c;
759
+ }
760
+ c.getContext("2d").drawImage(source, 0, 0, w, h);
761
+ }
762
+ draw(source, timestampUs, faceDone) {
653
763
  const t0 = performance.now();
654
764
  const [lo, hi] = splitMicros(timestampUs);
655
765
  const needSeg = this.core.decide(lo, hi, this.prevTotalMs, this.prevSegMs) === 1;
656
766
  let mask = null;
657
767
  let maskKind = 0;
768
+ let maskTs = timestampUs;
658
769
  let segMs = 0;
659
770
  let faceMs = 0;
660
771
  this.used = null;
661
772
  let served = false;
662
- if (needSeg && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
773
+ if (needSeg && this.personRemote && this.personRemoteWanted(this.filter, this.effects)) {
774
+ this.requestRemote("person", source, timestampUs);
775
+ if (this.personMaskTex) {
776
+ served = true;
777
+ if (this.personMaskFresh) {
778
+ this.personMaskFresh = false;
779
+ mask = this.personMaskTex;
780
+ maskTs = this.personMaskTs;
781
+ segMs = this.personWorkerMs;
782
+ }
783
+ }
784
+ }
785
+ if (needSeg && !served && this.classRemote && needsSkinClasses(this.filter, this.effects)) {
663
786
  this.requestRemote("mask", source, timestampUs);
664
787
  if (this.classMaskTex) {
665
788
  served = true;
@@ -667,6 +790,7 @@ var Engine = class _Engine {
667
790
  this.classMaskFresh = false;
668
791
  mask = this.classMaskTex;
669
792
  maskKind = 1;
793
+ maskTs = this.classMaskTs;
670
794
  segMs = this.maskWorkerMs;
671
795
  }
672
796
  }
@@ -684,7 +808,9 @@ var Engine = class _Engine {
684
808
  maskKind = classes ? 1 : 0;
685
809
  }
686
810
  }
687
- if (this.core.decideFace() === 1) {
811
+ if (faceDone) {
812
+ faceMs = this.faceWorkerMs;
813
+ } else if (this.core.decideFace() === 1) {
688
814
  if (this.faceRemote) {
689
815
  this.requestRemote("face", source, timestampUs);
690
816
  faceMs = this.faceWorkerMs;
@@ -697,7 +823,8 @@ var Engine = class _Engine {
697
823
  this.core.setFace(lo, hi, n);
698
824
  }
699
825
  }
700
- const glCalls = this.core.process(source, mask, this.background, maskKind);
826
+ const [maskLo, maskHi] = splitMicros(maskTs);
827
+ const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
701
828
  if (mask) this.used?.release();
702
829
  this.used = null;
703
830
  this.prevSegMs = segMs;
@@ -744,13 +871,18 @@ var Engine = class _Engine {
744
871
  this.classSegmenter = null;
745
872
  this.face?.close();
746
873
  this.face = null;
747
- this.detect?.close();
748
- this.detect = null;
874
+ for (const detect of this.detects.values()) detect.close();
875
+ this.detects.clear();
749
876
  this.faceRemote = false;
750
877
  this.classRemote = false;
751
878
  if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex);
879
+ if (this.personMaskTex) this.gl.deleteTexture(this.personMaskTex);
880
+ this.personMaskTex = null;
881
+ this.personRemote = false;
752
882
  this.classMaskTex = null;
753
883
  this.lmBuf = null;
884
+ this.held = [null, null];
885
+ this.lastHeld = null;
754
886
  this.core.close();
755
887
  this.background?.close();
756
888
  this.background = null;
@@ -983,6 +1115,7 @@ var VideoPipeline = class {
983
1115
  async startMain(source) {
984
1116
  const { width, height, fps } = this.size;
985
1117
  this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces);
1118
+ this.engine.syncFaces = this.opts.syncFaces ?? false;
986
1119
  this.transport = hasInsertableStreams() ? "insertable" : "canvas";
987
1120
  this.frames = 0;
988
1121
  this.lastBeat = performance.now();
@@ -1107,7 +1240,8 @@ var VideoPipeline = class {
1107
1240
  effects: this.effects,
1108
1241
  background,
1109
1242
  alpha: this.opts.alpha,
1110
- maxFaces: this.opts.maxFaces
1243
+ maxFaces: this.opts.maxFaces,
1244
+ syncFaces: this.opts.syncFaces
1111
1245
  },
1112
1246
  background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
1113
1247
  )
@@ -1132,7 +1266,8 @@ var VideoPipeline = class {
1132
1266
  effects: this.effects,
1133
1267
  background,
1134
1268
  alpha: this.opts.alpha,
1135
- maxFaces: this.opts.maxFaces
1269
+ maxFaces: this.opts.maxFaces,
1270
+ syncFaces: this.opts.syncFaces
1136
1271
  },
1137
1272
  background ? [clone, background] : [clone]
1138
1273
  )
@@ -1218,10 +1353,15 @@ var VideoPipeline = class {
1218
1353
  transform: (frame, controller) => {
1219
1354
  this.beat();
1220
1355
  try {
1221
- if (engine.render(frame, frame.timestamp)) {
1222
- controller.enqueue(engine.capture(frame.timestamp));
1223
- if (this.frameSubs.size > 0) this.deliver(engine.capture(frame.timestamp, true));
1224
- } else {
1356
+ const drew = engine.render(frame, frame.timestamp);
1357
+ const held = drew ? null : engine.passthrough();
1358
+ if (drew) {
1359
+ controller.enqueue(engine.capture(engine.renderedTs));
1360
+ if (this.frameSubs.size > 0) this.deliver(engine.capture(engine.renderedTs, true));
1361
+ } else if (held) {
1362
+ if (this.frameSubs.size > 0) this.deliver(held.clone());
1363
+ controller.enqueue(held);
1364
+ } else if (!engine.dropped()) {
1225
1365
  if (this.frameSubs.size > 0) this.deliver(frame.clone());
1226
1366
  controller.enqueue(frame);
1227
1367
  return;