@tradalab/mediakit 2.7.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;
@@ -516,12 +536,19 @@ interface PreloadParts {
516
536
  person?: boolean;
517
537
  classes?: boolean;
518
538
  face?: boolean;
539
+ cover?: boolean;
540
+ }
541
+ interface PreloadProgress {
542
+ loaded: number;
543
+ total: number;
544
+ done: number;
545
+ files: number;
519
546
  }
520
547
  /**
521
548
  * Warm the HTTP cache with the MediaPipe runtime and the chosen models, at low priority, so the
522
549
  * first recipe that needs them builds without waiting on the network. Never rejects.
523
550
  */
524
- declare function preloadDetectors(parts?: PreloadParts): Promise<void>;
551
+ declare function preloadDetectors(parts?: PreloadParts, onProgress?: (p: PreloadProgress) => void): Promise<void>;
525
552
 
526
553
  /**
527
554
  * Layers several sources onto one output, OBS style: cameras (each with its own mediakit
@@ -668,4 +695,4 @@ declare function renderText(text: string, style?: TextStyle): HTMLCanvasElement;
668
695
  /** Where each of the face landmarker's first 468 landmarks lies on the canonical face texture. */
669
696
  declare const FACE_UV: Float32Array<ArrayBuffer>;
670
697
 
671
- 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
@@ -21,17 +21,21 @@ import {
21
21
  layouts,
22
22
  parseColor
23
23
  } from "./chunk-BMIOUOT3.js";
24
+ import {
25
+ ASSETS,
26
+ assetUrl
27
+ } from "./chunk-T7YS2EQE.js";
24
28
 
25
29
  // src/segmenter.ts
26
30
  import { ImageSegmenter } from "@mediapipe/tasks-vision";
27
31
 
28
32
  // src/mp.ts
29
33
  import { FilesetResolver } from "@mediapipe/tasks-vision";
30
- var MP_DIR = "/mediakit/mp";
34
+ var MP_DIR = assetUrl("mp");
31
35
  var MODEL_URL = {
32
- person: "/mediakit/selfie_segmenter.tflite",
33
- classes: "/mediakit/selfie_multiclass_256x256.tflite",
34
- face: "/mediakit/face_landmarker.task"
36
+ person: assetUrl("selfie_segmenter.tflite"),
37
+ classes: assetUrl("selfie_multiclass_256x256.tflite"),
38
+ face: assetUrl("face_landmarker.task")
35
39
  };
36
40
  var LOAD_MS = 6e4;
37
41
  var fileset = null;
@@ -73,19 +77,66 @@ function withTimeout(p, ms, what, late) {
73
77
  );
74
78
  });
75
79
  }
76
- 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) {
77
82
  const urls = [];
78
- try {
79
- const fs = await visionFileset();
80
- urls.push(fs.wasmBinaryPath, fs.wasmLoaderPath);
81
- } catch {
82
- return;
83
+ if (parts.cover) {
84
+ for (const a of ASSETS) if (a.part === "cover") urls.push(assetUrl(a.path));
83
85
  }
84
- for (const k of ["person", "classes", "face"]) if (parts[k]) urls.push(MODEL_URL[k]);
86
+ if (parts.person || parts.classes || parts.face) {
87
+ try {
88
+ const fs = await visionFileset();
89
+ urls.push(fs.wasmBinaryPath, fs.wasmLoaderPath);
90
+ for (const k of ["person", "classes", "face"]) if (parts[k]) urls.push(MODEL_URL[k]);
91
+ } catch {
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);
85
113
  await Promise.all(
86
- urls.map(
87
- (u) => fetch(u, { priority: "low" }).then((r) => r.arrayBuffer()).catch(() => void 0)
88
- )
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
+ })
89
140
  );
90
141
  }
91
142
 
@@ -203,7 +254,7 @@ async function createFaceDetector(canvas, maxFaces, delegate = "GPU", mode = "VI
203
254
  }
204
255
 
205
256
  // src/detect-remote.ts
206
- var DETECT_WORKER_URL = "/mediakit/detect-worker.js";
257
+ var DETECT_WORKER_URL = assetUrl("detect-worker.js");
207
258
  var DetectWorker = class {
208
259
  constructor(on) {
209
260
  this.on = on;
@@ -271,6 +322,9 @@ var DetectWorker = class {
271
322
  this.busy.delete("face");
272
323
  if (this.up.has("face")) this.on.face(m.tsUs, m.n, m.lm, m.ms, m.cover, m.rects);
273
324
  break;
325
+ case "cover":
326
+ this.on.cover(m.ok, m.message);
327
+ break;
274
328
  case "mask":
275
329
  this.busy.delete("mask");
276
330
  if (this.up.has("mask") && m.width > 0) this.on.mask(m.tsUs, m.width, m.height, m.data, m.ms);
@@ -302,8 +356,8 @@ var DetectWorker = class {
302
356
  };
303
357
 
304
358
  // src/wasm.ts
305
- var WASM_URL = "/mediakit/mediakit.wasm";
306
- var EXEC_URL = "/mediakit/wasm_exec.js";
359
+ var WASM_URL = assetUrl("mediakit.wasm");
360
+ var EXEC_URL = assetUrl("wasm_exec.js");
307
361
  var execLoaded = null;
308
362
  var compiled = null;
309
363
  function loadExec() {
@@ -512,6 +566,9 @@ function mergeMasks(person, classes, out, moved = null) {
512
566
  }
513
567
 
514
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";
515
572
  var ZERO_STATS = {
516
573
  totalMs: 0,
517
574
  segMs: 0,
@@ -532,7 +589,9 @@ var ZERO_STATS = {
532
589
  heldFrames: 0,
533
590
  faceAgeMs: 0,
534
591
  maskAgeMs: 0,
535
- effectError: ""
592
+ effectError: "",
593
+ parts: { ...NO_PARTS },
594
+ partErrors: { ...NO_PART_ERRORS }
536
595
  };
537
596
  var MAX_HOLD = 3;
538
597
  var COVER_FRAME_W = 256;
@@ -654,6 +713,8 @@ var Engine = class _Engine {
654
713
  coverCanvas = null;
655
714
  coverCell = null;
656
715
  coverOn = false;
716
+ coverState = "loading";
717
+ partErr = /* @__PURE__ */ new Map();
657
718
  faceMisses = 0;
658
719
  coverHidden = false;
659
720
  srcW = 0;
@@ -853,7 +914,7 @@ var Engine = class _Engine {
853
914
  }
854
915
  if (effects.whitenStyle === "pink" && this.skinLutState === "none") {
855
916
  this.skinLutState = "loading";
856
- decodeImage("/mediakit/whiten_pink.png", { colorSpaceConversion: "none", premultiplyAlpha: "none" }).then((bmp) => {
917
+ decodeImage(assetUrl("whiten_pink.png"), { colorSpaceConversion: "none", premultiplyAlpha: "none" }).then((bmp) => {
857
918
  if (this.closed) {
858
919
  bmp.close();
859
920
  return;
@@ -931,6 +992,7 @@ var Engine = class _Engine {
931
992
  });
932
993
  }).catch((e) => {
933
994
  this.failed.add("face");
995
+ this.partFailed("face", "face detection", "face effects", e);
934
996
  this.gaveUp("face effects", e);
935
997
  if (!(e instanceof LoadTimeout)) console.error("mediakit: face detector failed to load", e);
936
998
  }).finally(() => {
@@ -949,6 +1011,7 @@ var Engine = class _Engine {
949
1011
  }).catch((e) => {
950
1012
  if (!(e instanceof LoadTimeout)) return;
951
1013
  this.failed.add("person");
1014
+ this.partFailed("person", "person segmentation", "background effects", e);
952
1015
  this.gaveUp("background effects", e);
953
1016
  }).finally(() => {
954
1017
  this.personLoading = null;
@@ -1006,6 +1069,11 @@ var Engine = class _Engine {
1006
1069
  this.maskResults.push(r);
1007
1070
  if (this.maskResults.length > MASK_RESULTS_KEPT) this.maskResults.shift();
1008
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
+ },
1009
1077
  failed: (k, reason) => {
1010
1078
  if (key === "faceExtra") {
1011
1079
  this.faceExtraUp = false;
@@ -1288,6 +1356,7 @@ var Engine = class _Engine {
1288
1356
  });
1289
1357
  }).catch((e) => {
1290
1358
  this.classFailed = true;
1359
+ this.partFailed("classes", "skin segmentation", "skin, hair and product effects use the person model", e);
1291
1360
  if (!(e instanceof LoadTimeout)) console.error("mediakit: multiclass segmenter failed to load", e);
1292
1361
  else console.warn(`${e.message}; the person model stands in`);
1293
1362
  if (needsSegmentation(this.filter, this.effects)) void this.ensureSegmenter();
@@ -1307,6 +1376,7 @@ var Engine = class _Engine {
1307
1376
  this.segmenter = s;
1308
1377
  }).catch((e) => {
1309
1378
  this.failed.add("segmenter");
1379
+ this.partFailed("person", "person segmentation", "background and skin effects", e);
1310
1380
  this.gaveUp("background and skin effects", e);
1311
1381
  if (!(e instanceof LoadTimeout)) console.error("mediakit: segmenter failed to load", e);
1312
1382
  }).finally(() => {
@@ -1643,6 +1713,7 @@ var Engine = class _Engine {
1643
1713
  this.prevSegMs = segMs;
1644
1714
  this.prevTotalMs = performance.now() - t0;
1645
1715
  const s = this.core.stats();
1716
+ const parts = this.parts();
1646
1717
  this.last = {
1647
1718
  totalMs: this.prevTotalMs,
1648
1719
  segMs,
@@ -1663,10 +1734,41 @@ var Engine = class _Engine {
1663
1734
  heldFrames: faceDone ? this.queue.length : 0,
1664
1735
  faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1e3 : 0,
1665
1736
  maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1e3 : 0,
1666
- effectError: this.programErr || this.loadErr
1737
+ effectError: this.programErr || this.loadErr,
1738
+ parts,
1739
+ partErrors: this.partErrors(parts)
1667
1740
  };
1668
1741
  return glCalls > 0;
1669
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
+ }
1670
1772
  /**
1671
1773
  * Wrap the output canvas as a new VideoFrame.
1672
1774
  *
@@ -1864,7 +1966,9 @@ var VideoPipeline = class {
1864
1966
  frames: this.frames,
1865
1967
  sinceMs: this.lastBeat ? performance.now() - this.lastBeat : 0,
1866
1968
  stalled: this.stalled,
1867
- effectError: this.stats?.effectError ?? ""
1969
+ effectError: this.stats?.effectError ?? "",
1970
+ parts: { ...this.stats?.parts ?? NO_PARTS },
1971
+ partErrors: { ...this.stats?.partErrors ?? NO_PART_ERRORS }
1868
1972
  };
1869
1973
  }
1870
1974
  /** Every processed frame. */
@@ -1890,9 +1994,9 @@ var VideoPipeline = class {
1890
1994
  }
1891
1995
  });
1892
1996
  }
1893
- issue(code, message) {
1894
- if (this.raised.has(code)) return;
1895
- this.raised.add(code);
1997
+ issue(code, message, key = code) {
1998
+ if (this.raised.has(key)) return;
1999
+ this.raised.add(key);
1896
2000
  console.warn(`mediakit: ${code}: ${message}`);
1897
2001
  try {
1898
2002
  this.opts.onIssue?.({ code, message, transport: this.transport });
@@ -1904,6 +2008,12 @@ var VideoPipeline = class {
1904
2008
  const s = this.stats;
1905
2009
  if (!s) return;
1906
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
+ }
1907
2017
  const slow = s.totalMs > SLOW_FRAME_MS || s.faceMs > SLOW_FRAME_MS;
1908
2018
  this.slowTicks = slow ? Math.max(1, this.slowTicks + 1) : Math.min(-1, this.slowTicks - 1);
1909
2019
  if (this.slowTicks >= SLOW_TICKS) {
@@ -2265,7 +2375,7 @@ var VideoPipeline = class {
2265
2375
  }
2266
2376
  /** Starts the worker and waits for its "ready". */
2267
2377
  attachWorker(onReady, cleanup, post) {
2268
- const worker = new Worker("/mediakit/worker.js");
2378
+ const worker = new Worker(assetUrl("worker.js"));
2269
2379
  this.worker = worker;
2270
2380
  return new Promise((resolve, reject) => {
2271
2381
  let settled = false;
@@ -3789,6 +3899,8 @@ export {
3789
3899
  FACE_UV,
3790
3900
  GpuLostError,
3791
3901
  NO_EFFECTS,
3902
+ NO_PARTS,
3903
+ NO_PART_ERRORS,
3792
3904
  Scene,
3793
3905
  TOUCH_UP,
3794
3906
  TRANSITIONS,