@tradalab/mediakit 2.8.0 → 2.9.1

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;
@@ -404,6 +424,7 @@ declare class VideoPipeline {
404
424
  private watchdog;
405
425
  private movedOff;
406
426
  private raised;
427
+ private effectOff;
407
428
  private slowTicks;
408
429
  private gpuRecoveries;
409
430
  private gpu;
@@ -518,11 +539,17 @@ interface PreloadParts {
518
539
  face?: boolean;
519
540
  cover?: boolean;
520
541
  }
542
+ interface PreloadProgress {
543
+ loaded: number;
544
+ total: number;
545
+ done: number;
546
+ files: number;
547
+ }
521
548
  /**
522
549
  * Warm the HTTP cache with the MediaPipe runtime and the chosen models, at low priority, so the
523
550
  * first recipe that needs them builds without waiting on the network. Never rejects.
524
551
  */
525
- declare function preloadDetectors(parts?: PreloadParts): Promise<void>;
552
+ declare function preloadDetectors(parts?: PreloadParts, onProgress?: (p: PreloadProgress) => void): Promise<void>;
526
553
 
527
554
  /**
528
555
  * Layers several sources onto one output, OBS style: cameras (each with its own mediakit
@@ -669,4 +696,4 @@ declare function renderText(text: string, style?: TextStyle): HTMLCanvasElement;
669
696
  /** Where each of the face landmarker's first 468 landmarks lies on the canonical face texture. */
670
697
  declare const FACE_UV: Float32Array<ArrayBuffer>;
671
698
 
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 };
699
+ 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,55 @@ 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
+ let got = 0;
116
+ try {
117
+ const r = await fetch(u, { priority: "low" });
118
+ if (!r.ok) {
119
+ sizes[i] = 0;
120
+ await r.body?.cancel();
121
+ } else {
122
+ const encoding = r.headers.get("content-encoding");
123
+ const length = Number(r.headers.get("content-length"));
124
+ sizes[i] = (!encoding || encoding === "identity") && length > 0 ? length : null;
125
+ const reader = r.body?.getReader();
126
+ if (reader) {
127
+ for (; ; ) {
128
+ const { done, value } = await reader.read();
129
+ if (done) break;
130
+ got += value.byteLength;
131
+ p.loaded += value.byteLength;
132
+ tell(false);
133
+ }
134
+ }
135
+ }
136
+ } catch {
137
+ p.loaded -= got;
138
+ sizes[i] = 0;
139
+ }
140
+ p.done++;
141
+ tell(true);
142
+ })
97
143
  );
98
144
  }
99
145
 
@@ -279,6 +325,9 @@ var DetectWorker = class {
279
325
  this.busy.delete("face");
280
326
  if (this.up.has("face")) this.on.face(m.tsUs, m.n, m.lm, m.ms, m.cover, m.rects);
281
327
  break;
328
+ case "cover":
329
+ this.on.cover(m.ok, m.message);
330
+ break;
282
331
  case "mask":
283
332
  this.busy.delete("mask");
284
333
  if (this.up.has("mask") && m.width > 0) this.on.mask(m.tsUs, m.width, m.height, m.data, m.ms);
@@ -520,6 +569,9 @@ function mergeMasks(person, classes, out, moved = null) {
520
569
  }
521
570
 
522
571
  // src/engine.ts
572
+ var NO_PARTS = Object.freeze({ person: "off", classes: "off", face: "off", cover: "off" });
573
+ var NO_PART_ERRORS = Object.freeze({ person: "", classes: "", face: "", cover: "" });
574
+ 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
575
  var ZERO_STATS = {
524
576
  totalMs: 0,
525
577
  segMs: 0,
@@ -540,7 +592,9 @@ var ZERO_STATS = {
540
592
  heldFrames: 0,
541
593
  faceAgeMs: 0,
542
594
  maskAgeMs: 0,
543
- effectError: ""
595
+ effectError: "",
596
+ parts: { ...NO_PARTS },
597
+ partErrors: { ...NO_PART_ERRORS }
544
598
  };
545
599
  var MAX_HOLD = 3;
546
600
  var COVER_FRAME_W = 256;
@@ -662,6 +716,8 @@ var Engine = class _Engine {
662
716
  coverCanvas = null;
663
717
  coverCell = null;
664
718
  coverOn = false;
719
+ coverState = "loading";
720
+ partErr = /* @__PURE__ */ new Map();
665
721
  faceMisses = 0;
666
722
  coverHidden = false;
667
723
  srcW = 0;
@@ -721,7 +777,7 @@ var Engine = class _Engine {
721
777
  // steers on past numbers because there is no way to know in advance what a frame will cost.
722
778
  prevTotalMs = 0;
723
779
  prevSegMs = 0;
724
- last = { ...ZERO_STATS };
780
+ last = { ...ZERO_STATS, parts: { ...NO_PARTS }, partErrors: { ...NO_PART_ERRORS } };
725
781
  constructor(canvas, gl, core) {
726
782
  this.canvas = canvas;
727
783
  this.gl = gl;
@@ -939,6 +995,7 @@ var Engine = class _Engine {
939
995
  });
940
996
  }).catch((e) => {
941
997
  this.failed.add("face");
998
+ this.partFailed("face", "face detection", "face effects stay off", e);
942
999
  this.gaveUp("face effects", e);
943
1000
  if (!(e instanceof LoadTimeout)) console.error("mediakit: face detector failed to load", e);
944
1001
  }).finally(() => {
@@ -957,6 +1014,7 @@ var Engine = class _Engine {
957
1014
  }).catch((e) => {
958
1015
  if (!(e instanceof LoadTimeout)) return;
959
1016
  this.failed.add("person");
1017
+ this.partFailed("person", "person segmentation", "background effects stay off", e);
960
1018
  this.gaveUp("background effects", e);
961
1019
  }).finally(() => {
962
1020
  this.personLoading = null;
@@ -1014,6 +1072,11 @@ var Engine = class _Engine {
1014
1072
  this.maskResults.push(r);
1015
1073
  if (this.maskResults.length > MASK_RESULTS_KEPT) this.maskResults.shift();
1016
1074
  },
1075
+ cover: (ok, message) => {
1076
+ if (key !== "face" || this.coverState === "failed") return;
1077
+ this.coverState = ok ? "ready" : "failed";
1078
+ if (!ok) this.partErr.set("cover", `${message}; occluders stays off`);
1079
+ },
1017
1080
  failed: (k, reason) => {
1018
1081
  if (key === "faceExtra") {
1019
1082
  this.faceExtraUp = false;
@@ -1296,6 +1359,7 @@ var Engine = class _Engine {
1296
1359
  });
1297
1360
  }).catch((e) => {
1298
1361
  this.classFailed = true;
1362
+ this.partFailed("classes", "skin segmentation", "skin, hair and product effects use the person model", e);
1299
1363
  if (!(e instanceof LoadTimeout)) console.error("mediakit: multiclass segmenter failed to load", e);
1300
1364
  else console.warn(`${e.message}; the person model stands in`);
1301
1365
  if (needsSegmentation(this.filter, this.effects)) void this.ensureSegmenter();
@@ -1315,6 +1379,7 @@ var Engine = class _Engine {
1315
1379
  this.segmenter = s;
1316
1380
  }).catch((e) => {
1317
1381
  this.failed.add("segmenter");
1382
+ this.partFailed("person", "person segmentation", "background and skin effects stay off", e);
1318
1383
  this.gaveUp("background and skin effects", e);
1319
1384
  if (!(e instanceof LoadTimeout)) console.error("mediakit: segmenter failed to load", e);
1320
1385
  }).finally(() => {
@@ -1651,6 +1716,7 @@ var Engine = class _Engine {
1651
1716
  this.prevSegMs = segMs;
1652
1717
  this.prevTotalMs = performance.now() - t0;
1653
1718
  const s = this.core.stats();
1719
+ const parts = this.parts();
1654
1720
  this.last = {
1655
1721
  totalMs: this.prevTotalMs,
1656
1722
  segMs,
@@ -1671,10 +1737,41 @@ var Engine = class _Engine {
1671
1737
  heldFrames: faceDone ? this.queue.length : 0,
1672
1738
  faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
1673
1739
  maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0,
1674
- effectError: this.programErr || this.loadErr
1740
+ effectError: this.programErr || this.loadErr,
1741
+ parts,
1742
+ partErrors: this.partErrors(parts)
1675
1743
  };
1676
1744
  return glCalls > 0;
1677
1745
  }
1746
+ partFailed(part, what, then, e) {
1747
+ if (this.partErr.has(part)) return;
1748
+ const why = e instanceof LoadTimeout ? e.message : `mediakit: ${what} did not load: ${String(e?.message ?? e)}`;
1749
+ this.partErr.set(part, `${why}; ${then}`);
1750
+ }
1751
+ parts() {
1752
+ const f = this.filter;
1753
+ const e = this.effects;
1754
+ const face = !needsFace(e) ? "off" : this.failed.has("face") ? "failed" : this.face || this.faceRemote ? "ready" : "loading";
1755
+ const classes = !needsSkinClasses(f, e) ? "off" : this.classFailed ? "failed" : this.classSegmenter || this.classRemote ? "ready" : "loading";
1756
+ let person = "off";
1757
+ if (needsSegmentation(f, e)) {
1758
+ if (this.segmenter || this.personRemote && this.personRemoteWanted(f, e)) person = "ready";
1759
+ else if (this.segmenterLoading || this.personLoading) person = "loading";
1760
+ else if (this.failed.has("segmenter") || this.failed.has("person")) person = classes === "ready" ? "ready" : "failed";
1761
+ else person = classes === "off" ? "loading" : classes;
1762
+ }
1763
+ let cover = "off";
1764
+ if (face !== "off" && (e.occluders ?? false)) {
1765
+ cover = face === "loading" ? "loading" : face === "failed" || this.inThread.has("face") ? "failed" : this.coverState;
1766
+ }
1767
+ return { person, classes, face, cover };
1768
+ }
1769
+ partErrors(p) {
1770
+ const why = (part) => p[part] === "failed" ? this.partErr.get(part) ?? "" : "";
1771
+ let cover = why("cover");
1772
+ if (p.cover === "failed" && !cover) cover = p.face === "failed" ? why("face") : COVER_IN_THREAD;
1773
+ return { person: why("person"), classes: why("classes"), face: why("face"), cover };
1774
+ }
1678
1775
  /**
1679
1776
  * Wrap the output canvas as a new VideoFrame.
1680
1777
  *
@@ -1834,6 +1931,7 @@ var VideoPipeline = class {
1834
1931
  watchdog = null;
1835
1932
  movedOff = false;
1836
1933
  raised = /* @__PURE__ */ new Set();
1934
+ effectOff = "";
1837
1935
  slowTicks = 0;
1838
1936
  gpuRecoveries = 0;
1839
1937
  gpu = "";
@@ -1872,7 +1970,9 @@ var VideoPipeline = class {
1872
1970
  frames: this.frames,
1873
1971
  sinceMs: this.lastBeat ? performance.now() - this.lastBeat : 0,
1874
1972
  stalled: this.stalled,
1875
- effectError: this.stats?.effectError ?? ""
1973
+ effectError: this.stats?.effectError ?? "",
1974
+ parts: { ...this.stats?.parts ?? NO_PARTS },
1975
+ partErrors: { ...this.stats?.partErrors ?? NO_PART_ERRORS }
1876
1976
  };
1877
1977
  }
1878
1978
  /** Every processed frame. */
@@ -1898,20 +1998,27 @@ var VideoPipeline = class {
1898
1998
  }
1899
1999
  });
1900
2000
  }
1901
- issue(code, message) {
1902
- if (this.raised.has(code)) return;
1903
- this.raised.add(code);
2001
+ issue(code, message, key = code) {
2002
+ if (this.raised.has(key)) return false;
2003
+ this.raised.add(key);
1904
2004
  console.warn(`mediakit: ${code}: ${message}`);
1905
2005
  try {
1906
2006
  this.opts.onIssue?.({ code, message, transport: this.transport });
1907
2007
  } catch (e) {
1908
2008
  console.error("mediakit: onIssue threw", e);
1909
2009
  }
2010
+ return true;
1910
2011
  }
1911
2012
  watchQuality() {
1912
2013
  const s = this.stats;
1913
2014
  if (!s) return;
1914
- if (s.effectError) this.issue("effect-off", s.effectError);
2015
+ if (s.effectError && this.issue("effect-off", s.effectError)) this.effectOff = s.effectError;
2016
+ for (const part of Object.keys(s.parts ?? {})) {
2017
+ if (s.parts[part] !== "failed") continue;
2018
+ const why = s.partErrors?.[part] || `mediakit: ${part} failed to load; its effects stay off`;
2019
+ if (this.effectOff.includes(why)) continue;
2020
+ this.issue("part-off", why, `part-off:${why}`);
2021
+ }
1915
2022
  const slow = s.totalMs > SLOW_FRAME_MS || s.faceMs > SLOW_FRAME_MS;
1916
2023
  this.slowTicks = slow ? Math.max(1, this.slowTicks + 1) : Math.min(-1, this.slowTicks - 1);
1917
2024
  if (this.slowTicks >= SLOW_TICKS) {
@@ -3797,6 +3904,8 @@ export {
3797
3904
  FACE_UV,
3798
3905
  GpuLostError,
3799
3906
  NO_EFFECTS,
3907
+ NO_PARTS,
3908
+ NO_PART_ERRORS,
3800
3909
  Scene,
3801
3910
  TOUCH_UP,
3802
3911
  TRANSITIONS,