@tradalab/mediakit 2.8.0 → 2.9.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
@@ -34,6 +34,17 @@ declare class GpuLostError extends Error {
34
34
  * job (`pipeline.ts`). They are separate because three browsers need three transports but all
35
35
  * three drive this same engine.
36
36
  */
37
+ type PartState = "off" | "loading" | "ready" | "failed";
38
+ interface PartStates {
39
+ person: PartState;
40
+ classes: PartState;
41
+ face: PartState;
42
+ cover: PartState;
43
+ }
44
+ type Part = keyof PartStates;
45
+ type PartErrors = Record<Part, string>;
46
+ declare const NO_PARTS: Readonly<PartStates>;
47
+ declare const NO_PART_ERRORS: Readonly<PartErrors>;
37
48
  interface FrameStats {
38
49
  /** Total time spent on one frame, in milliseconds. */
39
50
  totalMs: number;
@@ -72,6 +83,8 @@ interface FrameStats {
72
83
  maskAgeMs: number;
73
84
  /** Why makeup and teeth are off while the rest runs (their shader failed to link); "" when none. */
74
85
  effectError: string;
86
+ parts: PartStates;
87
+ partErrors: PartErrors;
75
88
  }
76
89
  type EngineCanvas = HTMLCanvasElement | OffscreenCanvas;
77
90
  /** What the Engine skips on a GPU known to fail; a host on the main thread gets it from the GPU guard. */
@@ -143,6 +156,8 @@ declare class Engine {
143
156
  private coverCanvas;
144
157
  private coverCell;
145
158
  private coverOn;
159
+ private coverState;
160
+ private readonly partErr;
146
161
  private faceMisses;
147
162
  private coverHidden;
148
163
  private srcW;
@@ -294,6 +309,9 @@ declare class Engine {
294
309
  private syncing;
295
310
  private hold;
296
311
  private draw;
312
+ private partFailed;
313
+ private parts;
314
+ private partErrors;
297
315
  /**
298
316
  * Wrap the output canvas as a new VideoFrame.
299
317
  *
@@ -356,7 +374,7 @@ interface PipelineOptions {
356
374
  onIssue?: (issue: PipelineIssue) => void;
357
375
  }
358
376
  /** What degraded; each code and what the app should do is in the README, "Handling a weak or failing GPU". */
359
- type IssueCode = "stall" | "slow" | "effect-off" | "worker-moved" | "gpu-lost";
377
+ type IssueCode = "stall" | "slow" | "effect-off" | "part-off" | "worker-moved" | "gpu-lost";
360
378
  interface PipelineIssue {
361
379
  code: IssueCode;
362
380
  message: string;
@@ -385,6 +403,8 @@ interface PipelineHealth {
385
403
  stalled: boolean;
386
404
  /** Why some effects are off while the picture still runs (see `FrameStats.effectError`); "" when none. */
387
405
  effectError: string;
406
+ parts: PartStates;
407
+ partErrors: PartErrors;
388
408
  }
389
409
  /** Whether mediakit can run in this browser, and every reason it cannot. Creates and frees two WebGL contexts. */
390
410
  declare function checkSupport(): SupportReport;
@@ -518,11 +538,17 @@ interface PreloadParts {
518
538
  face?: boolean;
519
539
  cover?: boolean;
520
540
  }
541
+ interface PreloadProgress {
542
+ loaded: number;
543
+ total: number;
544
+ done: number;
545
+ files: number;
546
+ }
521
547
  /**
522
548
  * Warm the HTTP cache with the MediaPipe runtime and the chosen models, at low priority, so the
523
549
  * first recipe that needs them builds without waiting on the network. Never rejects.
524
550
  */
525
- declare function preloadDetectors(parts?: PreloadParts): Promise<void>;
551
+ declare function preloadDetectors(parts?: PreloadParts, onProgress?: (p: PreloadProgress) => void): Promise<void>;
526
552
 
527
553
  /**
528
554
  * Layers several sources onto one output, OBS style: cameras (each with its own mediakit
@@ -669,4 +695,4 @@ declare function renderText(text: string, style?: TextStyle): HTMLCanvasElement;
669
695
  /** Where each of the face landmarker's first 468 landmarks lies on the canonical face texture. */
670
696
  declare const FACE_UV: Float32Array<ArrayBuffer>;
671
697
 
672
- export { BgFilter, Color, DebugView, Effects, Engine, type EngineCanvas, type EngineGuard, FACE_UV, type FrameStats, GpuLostError, type GpuRecord, type IssueCode, type LossPhase, type PipelineHealth, type PipelineIssue, type PipelineOptions, type PreloadParts, Scene, SceneLayer, type SceneOptions, type SceneSource, type SceneStats, type SupportReason, type SupportReport, type TextStyle, TransitionKind, type Transport, VideoPipeline, checkSupport, forgetGpuFailures, gpuRecord, mediakitSupported, preloadDetectors, renderText };
698
+ export { BgFilter, Color, DebugView, Effects, Engine, type EngineCanvas, type EngineGuard, FACE_UV, type FrameStats, GpuLostError, type GpuRecord, type IssueCode, type LossPhase, NO_PARTS, NO_PART_ERRORS, type Part, type PartErrors, type PartState, type PartStates, type PipelineHealth, type PipelineIssue, type PipelineOptions, type PreloadParts, type PreloadProgress, Scene, SceneLayer, type SceneOptions, type SceneSource, type SceneStats, type SupportReason, type SupportReport, type TextStyle, TransitionKind, type Transport, VideoPipeline, checkSupport, forgetGpuFailures, gpuRecord, mediakitSupported, preloadDetectors, renderText };
package/dist/index.js CHANGED
@@ -77,7 +77,8 @@ function withTimeout(p, ms, what, late) {
77
77
  );
78
78
  });
79
79
  }
80
- async function preloadDetectors(parts = { person: true, classes: true, face: true }) {
80
+ var PROGRESS_MS = 100;
81
+ async function preloadDetectors(parts = { person: true, classes: true, face: true }, onProgress) {
81
82
  const urls = [];
82
83
  if (parts.cover) {
83
84
  for (const a of ASSETS) if (a.part === "cover") urls.push(assetUrl(a.path));
@@ -90,10 +91,52 @@ async function preloadDetectors(parts = { person: true, classes: true, face: tru
90
91
  } catch {
91
92
  }
92
93
  }
94
+ const p = { loaded: 0, total: 0, done: 0, files: urls.length };
95
+ const sizes = urls.map(() => void 0);
96
+ let told = 0;
97
+ let broken = false;
98
+ const tell = (force) => {
99
+ if (!onProgress || broken) return;
100
+ const now2 = performance.now();
101
+ if (!force && now2 - told < PROGRESS_MS) return;
102
+ told = now2;
103
+ const known = sizes.every((n) => n !== null && n !== void 0);
104
+ const total = known ? sizes.reduce((a, n) => a + (n ?? 0), 0) : 0;
105
+ try {
106
+ onProgress({ ...p, total, loaded: total ? Math.min(p.loaded, total) : p.loaded });
107
+ } catch (e) {
108
+ broken = true;
109
+ console.error("mediakit: onProgress threw, no more progress from this preload", e);
110
+ }
111
+ };
112
+ tell(true);
93
113
  await Promise.all(
94
- urls.map(
95
- (u) => fetch(u, { priority: "low" }).then((r) => r.arrayBuffer()).catch(() => void 0)
96
- )
114
+ urls.map(async (u, i) => {
115
+ try {
116
+ const r = await fetch(u, { priority: "low" });
117
+ if (!r.ok) {
118
+ sizes[i] = 0;
119
+ await r.body?.cancel();
120
+ } else {
121
+ const encoding = r.headers.get("content-encoding");
122
+ const length = Number(r.headers.get("content-length"));
123
+ sizes[i] = (!encoding || encoding === "identity") && length > 0 ? length : null;
124
+ const reader = r.body?.getReader();
125
+ if (reader) {
126
+ for (; ; ) {
127
+ const { done, value } = await reader.read();
128
+ if (done) break;
129
+ p.loaded += value.byteLength;
130
+ tell(false);
131
+ }
132
+ }
133
+ }
134
+ } catch {
135
+ sizes[i] ??= 0;
136
+ }
137
+ p.done++;
138
+ tell(true);
139
+ })
97
140
  );
98
141
  }
99
142
 
@@ -279,6 +322,9 @@ var DetectWorker = class {
279
322
  this.busy.delete("face");
280
323
  if (this.up.has("face")) this.on.face(m.tsUs, m.n, m.lm, m.ms, m.cover, m.rects);
281
324
  break;
325
+ case "cover":
326
+ this.on.cover(m.ok, m.message);
327
+ break;
282
328
  case "mask":
283
329
  this.busy.delete("mask");
284
330
  if (this.up.has("mask") && m.width > 0) this.on.mask(m.tsUs, m.width, m.height, m.data, m.ms);
@@ -520,6 +566,9 @@ function mergeMasks(person, classes, out, moved = null) {
520
566
  }
521
567
 
522
568
  // src/engine.ts
569
+ var NO_PARTS = Object.freeze({ person: "off", classes: "off", face: "off", cover: "off" });
570
+ var NO_PART_ERRORS = Object.freeze({ person: "", classes: "", face: "", cover: "" });
571
+ var COVER_IN_THREAD = "mediakit: the face cover runs only in the detect worker, and face detection runs in this thread; occluders stays off";
523
572
  var ZERO_STATS = {
524
573
  totalMs: 0,
525
574
  segMs: 0,
@@ -540,7 +589,9 @@ var ZERO_STATS = {
540
589
  heldFrames: 0,
541
590
  faceAgeMs: 0,
542
591
  maskAgeMs: 0,
543
- effectError: ""
592
+ effectError: "",
593
+ parts: { ...NO_PARTS },
594
+ partErrors: { ...NO_PART_ERRORS }
544
595
  };
545
596
  var MAX_HOLD = 3;
546
597
  var COVER_FRAME_W = 256;
@@ -662,6 +713,8 @@ var Engine = class _Engine {
662
713
  coverCanvas = null;
663
714
  coverCell = null;
664
715
  coverOn = false;
716
+ coverState = "loading";
717
+ partErr = /* @__PURE__ */ new Map();
665
718
  faceMisses = 0;
666
719
  coverHidden = false;
667
720
  srcW = 0;
@@ -939,6 +992,7 @@ var Engine = class _Engine {
939
992
  });
940
993
  }).catch((e) => {
941
994
  this.failed.add("face");
995
+ this.partFailed("face", "face detection", "face effects", e);
942
996
  this.gaveUp("face effects", e);
943
997
  if (!(e instanceof LoadTimeout)) console.error("mediakit: face detector failed to load", e);
944
998
  }).finally(() => {
@@ -957,6 +1011,7 @@ var Engine = class _Engine {
957
1011
  }).catch((e) => {
958
1012
  if (!(e instanceof LoadTimeout)) return;
959
1013
  this.failed.add("person");
1014
+ this.partFailed("person", "person segmentation", "background effects", e);
960
1015
  this.gaveUp("background effects", e);
961
1016
  }).finally(() => {
962
1017
  this.personLoading = null;
@@ -1014,6 +1069,11 @@ var Engine = class _Engine {
1014
1069
  this.maskResults.push(r);
1015
1070
  if (this.maskResults.length > MASK_RESULTS_KEPT) this.maskResults.shift();
1016
1071
  },
1072
+ cover: (ok, message) => {
1073
+ if (key !== "face" || this.coverState === "failed") return;
1074
+ this.coverState = ok ? "ready" : "failed";
1075
+ if (!ok) this.partErr.set("cover", `mediakit: ${message}; occluders stays off`);
1076
+ },
1017
1077
  failed: (k, reason) => {
1018
1078
  if (key === "faceExtra") {
1019
1079
  this.faceExtraUp = false;
@@ -1296,6 +1356,7 @@ var Engine = class _Engine {
1296
1356
  });
1297
1357
  }).catch((e) => {
1298
1358
  this.classFailed = true;
1359
+ this.partFailed("classes", "skin segmentation", "skin, hair and product effects use the person model", e);
1299
1360
  if (!(e instanceof LoadTimeout)) console.error("mediakit: multiclass segmenter failed to load", e);
1300
1361
  else console.warn(`${e.message}; the person model stands in`);
1301
1362
  if (needsSegmentation(this.filter, this.effects)) void this.ensureSegmenter();
@@ -1315,6 +1376,7 @@ var Engine = class _Engine {
1315
1376
  this.segmenter = s;
1316
1377
  }).catch((e) => {
1317
1378
  this.failed.add("segmenter");
1379
+ this.partFailed("person", "person segmentation", "background and skin effects", e);
1318
1380
  this.gaveUp("background and skin effects", e);
1319
1381
  if (!(e instanceof LoadTimeout)) console.error("mediakit: segmenter failed to load", e);
1320
1382
  }).finally(() => {
@@ -1651,6 +1713,7 @@ var Engine = class _Engine {
1651
1713
  this.prevSegMs = segMs;
1652
1714
  this.prevTotalMs = performance.now() - t0;
1653
1715
  const s = this.core.stats();
1716
+ const parts = this.parts();
1654
1717
  this.last = {
1655
1718
  totalMs: this.prevTotalMs,
1656
1719
  segMs,
@@ -1671,10 +1734,41 @@ var Engine = class _Engine {
1671
1734
  heldFrames: faceDone ? this.queue.length : 0,
1672
1735
  faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
1673
1736
  maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0,
1674
- effectError: this.programErr || this.loadErr
1737
+ effectError: this.programErr || this.loadErr,
1738
+ parts,
1739
+ partErrors: this.partErrors(parts)
1675
1740
  };
1676
1741
  return glCalls > 0;
1677
1742
  }
1743
+ partFailed(part, what, off, e) {
1744
+ if (this.partErr.has(part)) return;
1745
+ const why = e instanceof LoadTimeout ? e.message : `mediakit: ${what} did not load: ${String(e?.message ?? e)}`;
1746
+ this.partErr.set(part, `${why}; ${off} stay off`);
1747
+ }
1748
+ parts() {
1749
+ const f = this.filter;
1750
+ const e = this.effects;
1751
+ const face = !needsFace(e) ? "off" : this.failed.has("face") ? "failed" : this.face || this.faceRemote ? "ready" : "loading";
1752
+ const classes = !needsSkinClasses(f, e) ? "off" : this.classFailed ? "failed" : this.classSegmenter || this.classRemote ? "ready" : "loading";
1753
+ let person = "off";
1754
+ if (needsSegmentation(f, e)) {
1755
+ if (this.segmenter || this.personRemote && this.personRemoteWanted(f, e)) person = "ready";
1756
+ else if (this.segmenterLoading || this.personLoading) person = "loading";
1757
+ else if (this.failed.has("segmenter") || this.failed.has("person")) person = classes === "ready" ? "ready" : "failed";
1758
+ else person = classes === "off" ? "loading" : classes;
1759
+ }
1760
+ let cover = "off";
1761
+ if (face !== "off" && (e.occluders ?? false)) {
1762
+ cover = face === "loading" ? "loading" : face === "failed" || this.inThread.has("face") ? "failed" : this.coverState;
1763
+ }
1764
+ return { person, classes, face, cover };
1765
+ }
1766
+ partErrors(p) {
1767
+ const why = (part) => p[part] === "failed" ? this.partErr.get(part) ?? "" : "";
1768
+ let cover = why("cover");
1769
+ if (p.cover === "failed" && !cover) cover = p.face === "failed" ? why("face") : COVER_IN_THREAD;
1770
+ return { person: why("person"), classes: why("classes"), face: why("face"), cover };
1771
+ }
1678
1772
  /**
1679
1773
  * Wrap the output canvas as a new VideoFrame.
1680
1774
  *
@@ -1872,7 +1966,9 @@ var VideoPipeline = class {
1872
1966
  frames: this.frames,
1873
1967
  sinceMs: this.lastBeat ? performance.now() - this.lastBeat : 0,
1874
1968
  stalled: this.stalled,
1875
- effectError: this.stats?.effectError ?? ""
1969
+ effectError: this.stats?.effectError ?? "",
1970
+ parts: { ...this.stats?.parts ?? NO_PARTS },
1971
+ partErrors: { ...this.stats?.partErrors ?? NO_PART_ERRORS }
1876
1972
  };
1877
1973
  }
1878
1974
  /** Every processed frame. */
@@ -1898,9 +1994,9 @@ var VideoPipeline = class {
1898
1994
  }
1899
1995
  });
1900
1996
  }
1901
- issue(code, message) {
1902
- if (this.raised.has(code)) return;
1903
- this.raised.add(code);
1997
+ issue(code, message, key = code) {
1998
+ if (this.raised.has(key)) return;
1999
+ this.raised.add(key);
1904
2000
  console.warn(`mediakit: ${code}: ${message}`);
1905
2001
  try {
1906
2002
  this.opts.onIssue?.({ code, message, transport: this.transport });
@@ -1912,6 +2008,12 @@ var VideoPipeline = class {
1912
2008
  const s = this.stats;
1913
2009
  if (!s) return;
1914
2010
  if (s.effectError) this.issue("effect-off", s.effectError);
2011
+ for (const part of Object.keys(s.parts ?? {})) {
2012
+ if (s.parts[part] !== "failed") continue;
2013
+ const why = s.partErrors?.[part] || `mediakit: ${part} failed to load; its effects stay off`;
2014
+ if (s.effectError && s.effectError.includes(why)) continue;
2015
+ this.issue("part-off", why, `part-off:${why}`);
2016
+ }
1915
2017
  const slow = s.totalMs > SLOW_FRAME_MS || s.faceMs > SLOW_FRAME_MS;
1916
2018
  this.slowTicks = slow ? Math.max(1, this.slowTicks + 1) : Math.min(-1, this.slowTicks - 1);
1917
2019
  if (this.slowTicks >= SLOW_TICKS) {
@@ -3797,6 +3899,8 @@ export {
3797
3899
  FACE_UV,
3798
3900
  GpuLostError,
3799
3901
  NO_EFFECTS,
3902
+ NO_PARTS,
3903
+ NO_PART_ERRORS,
3800
3904
  Scene,
3801
3905
  TOUCH_UP,
3802
3906
  TRANSITIONS,