@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.
package/dist/index.d.ts CHANGED
@@ -81,8 +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;
100
+ private detectCanvas;
101
+ private detectCanvasTs;
86
102
  private readonly inThread;
87
103
  private faceLoading;
88
104
  private maxFaces;
@@ -114,16 +130,24 @@ declare class Engine {
114
130
  setRecipe(filter: BgFilter, effects?: Effects, background?: ImageBitmap): Promise<void>;
115
131
  private ensureFace;
116
132
  /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */
133
+ private personRemoteWanted;
134
+ private ensurePersonRemote;
117
135
  private remote;
136
+ private detectHandlers;
118
137
  private uploadClassMask;
119
- /** Hands a copy of this frame to the detect worker; the caller's frame stays its own. */
138
+ private uploadMaskBytes;
139
+ /**
140
+ * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
141
+ * detection drains Chrome's few capture buffers and throttles the camera itself.
142
+ */
120
143
  private requestRemote;
144
+ /** Face and mask asked on the same frame share one draw. */
145
+ private detectCopy;
121
146
  private ensureClassSegmenter;
122
147
  private ensureSegmenter;
123
148
  /**
124
149
  * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
125
- * yet, the segmenter is still loading, or the recipe is inactive; the transport must
126
- * forward the original frame rather than drop it.
150
+ * yet, the segmenter is still loading, or the recipe is inactive.
127
151
  *
128
152
  * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
129
153
  * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
@@ -134,6 +158,11 @@ declare class Engine {
134
158
  * it constructs one only to destroy it again.
135
159
  */
136
160
  render(source: TexImageSource, timestampUs: number): boolean;
161
+ dropped(): boolean;
162
+ passthrough(): VideoFrame | null;
163
+ private syncing;
164
+ private hold;
165
+ private draw;
137
166
  /**
138
167
  * Wrap the output canvas as a new VideoFrame.
139
168
  *
@@ -182,6 +211,7 @@ interface PipelineOptions {
182
211
  * the face detector on every call, about a third of the landmark cost.
183
212
  */
184
213
  maxFaces?: number;
214
+ syncFaces?: boolean;
185
215
  /** No processed frame for 2 s while the camera is live (20 s while a detector loads). */
186
216
  onStall?: (info: {
187
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,12 +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;
369
+ detectCanvas = null;
370
+ detectCanvasTs = -1;
346
371
  // A kind whose worker failed once stays in-thread.
347
372
  inThread = /* @__PURE__ */ new Set();
348
373
  faceLoading = null;
@@ -492,6 +517,7 @@ var Engine = class _Engine {
492
517
  this.core.setRecipe(coreRecipe(filter, effects));
493
518
  if (needsSegmentation(filter, effects)) void this.ensureSegmenter();
494
519
  if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter();
520
+ if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote();
495
521
  if (needsFace(effects)) void this.ensureFace();
496
522
  }
497
523
  ensureFace() {
@@ -521,11 +547,38 @@ var Engine = class _Engine {
521
547
  return this.faceLoading;
522
548
  }
523
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
+ }
524
563
  async remote(kind, init) {
525
564
  if (this.inThread.has(kind) || typeof Worker === "undefined" || typeof VideoFrame === "undefined") {
526
565
  throw new Error("in-thread");
527
566
  }
528
- 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 {
529
582
  face: (tsUs, n, lm, ms) => {
530
583
  if (this.closed || !this.lmBuf) return;
531
584
  this.lmBuf.set(lm);
@@ -533,15 +586,25 @@ var Engine = class _Engine {
533
586
  this.core.setFace(lo, hi, n);
534
587
  this.faceWorkerMs = ms;
535
588
  },
536
- mask: (_tsUs, width, height, data, ms) => {
589
+ mask: (tsUs, width, height, data, ms) => {
537
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
+ }
538
598
  this.uploadClassMask(width, height, data);
599
+ this.classMaskTs = tsUs;
539
600
  this.maskWorkerMs = ms;
540
601
  },
541
602
  failed: (k, reason) => {
542
- console.warn(`mediakit: ${k} detection moves into this thread:`, reason);
543
- this.inThread.add(k);
544
- 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") {
545
608
  this.faceRemote = false;
546
609
  void this.ensureFace();
547
610
  } else {
@@ -549,41 +612,63 @@ var Engine = class _Engine {
549
612
  void this.ensureClassSegmenter();
550
613
  }
551
614
  }
552
- });
553
- try {
554
- await init(this.detect);
555
- } catch (e) {
556
- this.inThread.add(kind);
557
- throw e;
558
- }
559
- if (this.closed) throw new Error("closed");
615
+ };
560
616
  }
561
- // Category indices: NEAREST, since a blend of two indices is a third, wrong category.
562
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) {
563
623
  const gl = this.gl;
564
- if (!this.classMaskTex) {
565
- this.classMaskTex = gl.createTexture();
566
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
624
+ if (!tex) {
625
+ tex = gl.createTexture();
626
+ gl.bindTexture(gl.TEXTURE_2D, tex);
567
627
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
568
628
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
569
629
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
570
630
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
571
631
  }
572
- gl.bindTexture(gl.TEXTURE_2D, this.classMaskTex);
632
+ gl.bindTexture(gl.TEXTURE_2D, tex);
573
633
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
574
634
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data);
575
635
  gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
576
636
  gl.bindTexture(gl.TEXTURE_2D, null);
577
- this.classMaskFresh = true;
637
+ return tex;
578
638
  }
579
- /** Hands a copy of this frame to the detect worker; the caller's frame stays its own. */
639
+ /**
640
+ * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
641
+ * detection drains Chrome's few capture buffers and throttles the camera itself.
642
+ */
580
643
  requestRemote(kind, source, timestampUs) {
644
+ const detect = this.detects.get(kind);
645
+ if (!detect?.accepts(kind === "face" ? "face" : "mask")) return;
581
646
  let frame = null;
582
647
  try {
583
- frame = source instanceof VideoFrame ? source.clone() : new VideoFrame(source, { timestamp: timestampUs });
648
+ const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
649
+ frame = new VideoFrame(copyable ? this.detectCopy(source, timestampUs) : source, {
650
+ timestamp: timestampUs
651
+ });
584
652
  } catch {
585
653
  }
586
- if (frame) this.detect?.request(kind, frame, timestampUs);
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
+ }
671
+ return this.detectCanvas;
587
672
  }
588
673
  ensureClassSegmenter() {
589
674
  if (this.classSegmenter || this.classRemote || this.closed) return Promise.resolve();
@@ -623,8 +708,7 @@ var Engine = class _Engine {
623
708
  }
624
709
  /**
625
710
  * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask
626
- * yet, the segmenter is still loading, or the recipe is inactive; the transport must
627
- * forward the original frame rather than drop it.
711
+ * yet, the segmenter is still loading, or the recipe is inactive.
628
712
  *
629
713
  * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────
630
714
  * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does
@@ -636,16 +720,69 @@ var Engine = class _Engine {
636
720
  */
637
721
  render(source, timestampUs) {
638
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) {
639
763
  const t0 = performance.now();
640
764
  const [lo, hi] = splitMicros(timestampUs);
641
765
  const needSeg = this.core.decide(lo, hi, this.prevTotalMs, this.prevSegMs) === 1;
642
766
  let mask = null;
643
767
  let maskKind = 0;
768
+ let maskTs = timestampUs;
644
769
  let segMs = 0;
645
770
  let faceMs = 0;
646
771
  this.used = null;
647
772
  let served = false;
648
- 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)) {
649
786
  this.requestRemote("mask", source, timestampUs);
650
787
  if (this.classMaskTex) {
651
788
  served = true;
@@ -653,6 +790,7 @@ var Engine = class _Engine {
653
790
  this.classMaskFresh = false;
654
791
  mask = this.classMaskTex;
655
792
  maskKind = 1;
793
+ maskTs = this.classMaskTs;
656
794
  segMs = this.maskWorkerMs;
657
795
  }
658
796
  }
@@ -670,7 +808,9 @@ var Engine = class _Engine {
670
808
  maskKind = classes ? 1 : 0;
671
809
  }
672
810
  }
673
- if (this.core.decideFace() === 1) {
811
+ if (faceDone) {
812
+ faceMs = this.faceWorkerMs;
813
+ } else if (this.core.decideFace() === 1) {
674
814
  if (this.faceRemote) {
675
815
  this.requestRemote("face", source, timestampUs);
676
816
  faceMs = this.faceWorkerMs;
@@ -683,7 +823,8 @@ var Engine = class _Engine {
683
823
  this.core.setFace(lo, hi, n);
684
824
  }
685
825
  }
686
- 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);
687
828
  if (mask) this.used?.release();
688
829
  this.used = null;
689
830
  this.prevSegMs = segMs;
@@ -730,13 +871,18 @@ var Engine = class _Engine {
730
871
  this.classSegmenter = null;
731
872
  this.face?.close();
732
873
  this.face = null;
733
- this.detect?.close();
734
- this.detect = null;
874
+ for (const detect of this.detects.values()) detect.close();
875
+ this.detects.clear();
735
876
  this.faceRemote = false;
736
877
  this.classRemote = false;
737
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;
738
882
  this.classMaskTex = null;
739
883
  this.lmBuf = null;
884
+ this.held = [null, null];
885
+ this.lastHeld = null;
740
886
  this.core.close();
741
887
  this.background?.close();
742
888
  this.background = null;
@@ -969,6 +1115,7 @@ var VideoPipeline = class {
969
1115
  async startMain(source) {
970
1116
  const { width, height, fps } = this.size;
971
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;
972
1119
  this.transport = hasInsertableStreams() ? "insertable" : "canvas";
973
1120
  this.frames = 0;
974
1121
  this.lastBeat = performance.now();
@@ -1093,7 +1240,8 @@ var VideoPipeline = class {
1093
1240
  effects: this.effects,
1094
1241
  background,
1095
1242
  alpha: this.opts.alpha,
1096
- maxFaces: this.opts.maxFaces
1243
+ maxFaces: this.opts.maxFaces,
1244
+ syncFaces: this.opts.syncFaces
1097
1245
  },
1098
1246
  background ? [processor.readable, generator.writable, background] : [processor.readable, generator.writable]
1099
1247
  )
@@ -1118,7 +1266,8 @@ var VideoPipeline = class {
1118
1266
  effects: this.effects,
1119
1267
  background,
1120
1268
  alpha: this.opts.alpha,
1121
- maxFaces: this.opts.maxFaces
1269
+ maxFaces: this.opts.maxFaces,
1270
+ syncFaces: this.opts.syncFaces
1122
1271
  },
1123
1272
  background ? [clone, background] : [clone]
1124
1273
  )
@@ -1204,10 +1353,15 @@ var VideoPipeline = class {
1204
1353
  transform: (frame, controller) => {
1205
1354
  this.beat();
1206
1355
  try {
1207
- if (engine.render(frame, frame.timestamp)) {
1208
- controller.enqueue(engine.capture(frame.timestamp));
1209
- if (this.frameSubs.size > 0) this.deliver(engine.capture(frame.timestamp, true));
1210
- } 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()) {
1211
1365
  if (this.frameSubs.size > 0) this.deliver(frame.clone());
1212
1366
  controller.enqueue(frame);
1213
1367
  return;