@tradalab/mediakit 2.9.0 → 2.10.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.js CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  } from "./chunk-BMIOUOT3.js";
24
24
  import {
25
25
  ASSETS,
26
+ ASSET_BASE,
26
27
  assetUrl
27
28
  } from "./chunk-T7YS2EQE.js";
28
29
 
@@ -31,16 +32,92 @@ import { ImageSegmenter } from "@mediapipe/tasks-vision";
31
32
 
32
33
  // src/mp.ts
33
34
  import { FilesetResolver } from "@mediapipe/tasks-vision";
34
- var MP_DIR = assetUrl("mp");
35
- var MODEL_URL = {
36
- person: assetUrl("selfie_segmenter.tflite"),
37
- classes: assetUrl("selfie_multiclass_256x256.tflite"),
38
- face: assetUrl("face_landmarker.task")
35
+
36
+ // src/res.ts
37
+ import { connectAssets, createAssets, isAssetsMessage } from "@tradalab/tskit/assets";
38
+ var RES_NAME = "mediakit";
39
+ var RES_VERSION = true ? "2.10.0" : "dev";
40
+ var MP_RUNTIME = ["vision_wasm_internal.js", "vision_wasm_internal.wasm", "vision_wasm_nosimd_internal.js", "vision_wasm_nosimd_internal.wasm"];
41
+ var NOT_FETCHED = /* @__PURE__ */ new Set(["worker.js", "detect-worker.js", "NOTICE"]);
42
+ var TYPES = {
43
+ js: "text/javascript",
44
+ mjs: "text/javascript",
45
+ wasm: "application/wasm",
46
+ png: "image/png"
39
47
  };
48
+ function typeOf(path) {
49
+ return TYPES[path.slice(path.lastIndexOf(".") + 1)] ?? "application/octet-stream";
50
+ }
51
+ function resourceManifest() {
52
+ const specs = [];
53
+ for (const a of ASSETS) {
54
+ if (a.debug || a.path.endsWith("/") || NOT_FETCHED.has(a.path)) continue;
55
+ specs.push({ id: a.path, url: assetUrl(a.path), type: typeOf(a.path), group: a.part });
56
+ }
57
+ for (const f of MP_RUNTIME) specs.push({ id: `mp/${f}`, url: assetUrl(`mp/${f}`), type: typeOf(f), group: "mp" });
58
+ return specs;
59
+ }
60
+ var source = null;
61
+ var urls = /* @__PURE__ */ new Map();
62
+ function resources() {
63
+ if (!source) {
64
+ const owner = createAssets({ manifest: resourceManifest(), name: RES_NAME, version: RES_VERSION, fetch: (u, i) => fetch(u, i) });
65
+ owner.purgeOld().catch((err) => console.warn("mediakit: could not delete the files of older versions", err));
66
+ source = owner;
67
+ }
68
+ return source;
69
+ }
70
+ function serveResources(port) {
71
+ return resources().serve(port);
72
+ }
73
+ function resourceId(pathOrUrl) {
74
+ return pathOrUrl.startsWith(ASSET_BASE) ? pathOrUrl.slice(ASSET_BASE.length) : pathOrUrl;
75
+ }
76
+ function resourceBytes(id, signal) {
77
+ return resources().bytes(id, signal);
78
+ }
79
+ function resourceUrl(id) {
80
+ let p = urls.get(id);
81
+ if (!p) {
82
+ p = resourceBytes(id).then((b) => URL.createObjectURL(new Blob([b], { type: typeOf(id) })));
83
+ p.catch(() => urls.delete(id));
84
+ urls.set(id, p);
85
+ }
86
+ return p;
87
+ }
88
+ async function preloadResources(ids, onProgress) {
89
+ const src = resources();
90
+ if ("preload" in src) return src.preload(ids, onProgress);
91
+ await Promise.all(ids.map((id) => src.bytes(id).catch(() => void 0)));
92
+ return null;
93
+ }
94
+ async function clearCachedAssets() {
95
+ const src = resources();
96
+ if ("clear" in src) await src.clear();
97
+ }
98
+
99
+ // src/mp.ts
100
+ var MP_DIR = assetUrl("mp");
40
101
  var LOAD_MS = 6e4;
41
102
  var fileset = null;
103
+ var MODEL_ID = {
104
+ person: "selfie_segmenter.tflite",
105
+ classes: "selfie_multiclass_256x256.tflite",
106
+ face: "face_landmarker.task"
107
+ };
108
+ function modelBytes(model) {
109
+ return resourceBytes(MODEL_ID[model]);
110
+ }
111
+ async function runtimeIds() {
112
+ const base = await FilesetResolver.forVisionTasks(MP_DIR);
113
+ return [resourceId(base.wasmLoaderPath), resourceId(base.wasmBinaryPath)];
114
+ }
42
115
  function visionFileset() {
43
- fileset ??= FilesetResolver.forVisionTasks(MP_DIR).catch((e) => {
116
+ fileset ??= (async () => {
117
+ const base = await FilesetResolver.forVisionTasks(MP_DIR);
118
+ const [loader, binary] = await Promise.all([resourceUrl(resourceId(base.wasmLoaderPath)), resourceUrl(resourceId(base.wasmBinaryPath))]);
119
+ return { ...base, wasmLoaderPath: loader, wasmBinaryPath: binary };
120
+ })().catch((e) => {
44
121
  fileset = null;
45
122
  throw e;
46
123
  });
@@ -77,67 +154,32 @@ function withTimeout(p, ms, what, late) {
77
154
  );
78
155
  });
79
156
  }
80
- var PROGRESS_MS = 100;
81
157
  async function preloadDetectors(parts = { person: true, classes: true, face: true }, onProgress) {
82
- const urls = [];
158
+ const ids = [];
83
159
  if (parts.cover) {
84
- for (const a of ASSETS) if (a.part === "cover") urls.push(assetUrl(a.path));
160
+ for (const a of ASSETS) if (a.part === "cover") ids.push(a.path);
85
161
  }
86
162
  if (parts.person || parts.classes || parts.face) {
87
163
  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]);
164
+ ids.push(...await runtimeIds());
91
165
  } catch {
92
166
  }
167
+ for (const k of ["person", "classes", "face"]) if (parts[k]) ids.push(MODEL_ID[k]);
93
168
  }
94
- const p = { loaded: 0, total: 0, done: 0, files: urls.length };
95
- const sizes = urls.map(() => void 0);
96
- let told = 0;
97
169
  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;
170
+ const tell = onProgress ? (p) => {
171
+ if (broken) return;
105
172
  try {
106
- onProgress({ ...p, total, loaded: total ? Math.min(p.loaded, total) : p.loaded });
173
+ onProgress({ loaded: p.loaded, total: p.total, done: p.done, files: p.items });
107
174
  } catch (e) {
108
175
  broken = true;
109
176
  console.error("mediakit: onProgress threw, no more progress from this preload", e);
110
177
  }
111
- };
112
- tell(true);
113
- await Promise.all(
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
- })
140
- );
178
+ } : void 0;
179
+ try {
180
+ await preloadResources(ids, tell);
181
+ } catch {
182
+ }
141
183
  }
142
184
 
143
185
  // src/mp-clock.ts
@@ -161,7 +203,7 @@ async function createSegmenter(canvas, model = "person") {
161
203
  const fileset2 = await visionFileset();
162
204
  const segmenter = await ImageSegmenter.createFromOptions(fileset2, {
163
205
  baseOptions: {
164
- modelAssetPath: MODEL_URL[model],
206
+ modelAssetBuffer: await modelBytes(model),
165
207
  // MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all
166
208
  // have. That is why mediakit picked MediaPipe over ONNX Runtime Web at P1: ORT's
167
209
  // fast path is WebGPU, which Firefox only has on Windows.
@@ -220,7 +262,7 @@ function faceBox(lm, at) {
220
262
  async function createFaceDetector(canvas, maxFaces, delegate = "GPU", mode = "VIDEO") {
221
263
  const fileset2 = await visionFileset();
222
264
  const landmarker = await FaceLandmarker.createFromOptions(fileset2, {
223
- baseOptions: { modelAssetPath: MODEL_URL.face, delegate },
265
+ baseOptions: { modelAssetBuffer: await modelBytes("face"), delegate },
224
266
  canvas,
225
267
  runningMode: mode,
226
268
  // As many as the core tracks: one landmark pass returns them all, so the cost of a second
@@ -259,11 +301,15 @@ var DetectWorker = class {
259
301
  constructor(on) {
260
302
  this.on = on;
261
303
  this.worker = new Worker(DETECT_WORKER_URL);
304
+ this.unserve = serveResources(this.worker);
262
305
  this.worker.onerror = (e) => this.failAll(e.message || "detect worker failed to load");
263
- this.worker.onmessage = (e) => this.receive(e.data);
306
+ this.worker.onmessage = (e) => {
307
+ if (!isAssetsMessage(e.data)) this.receive(e.data);
308
+ };
264
309
  }
265
310
  on;
266
311
  worker;
312
+ unserve;
267
313
  ready = /* @__PURE__ */ new Map();
268
314
  up = /* @__PURE__ */ new Set();
269
315
  busy = /* @__PURE__ */ new Set();
@@ -292,6 +338,7 @@ var DetectWorker = class {
292
338
  }
293
339
  close() {
294
340
  this.send({ t: "close" });
341
+ this.unserve();
295
342
  this.worker = null;
296
343
  for (const kind of [...this.ready.keys()]) this.settle(kind, new Error("closed"));
297
344
  this.up.clear();
@@ -346,6 +393,7 @@ var DetectWorker = class {
346
393
  }
347
394
  failAll(reason) {
348
395
  this.worker?.terminate();
396
+ this.unserve();
349
397
  this.worker = null;
350
398
  for (const kind of [...this.ready.keys()]) this.settle(kind, new Error(reason));
351
399
  for (const kind of [...this.up]) this.fail(kind, reason);
@@ -364,18 +412,21 @@ function loadExec() {
364
412
  if (execLoaded) return execLoaded;
365
413
  execLoaded = (async () => {
366
414
  if (globalThis.Go) return;
415
+ const execUrl = await resourceUrl("wasm_exec.js").catch((err) => {
416
+ throw new Error(`mediakit: cannot load ${EXEC_URL} (${err instanceof Error ? err.message : String(err)})`);
417
+ });
367
418
  const workerLoad = globalThis.importScripts;
368
419
  if (typeof workerLoad === "function") {
369
- workerLoad.call(globalThis, EXEC_URL);
420
+ workerLoad.call(globalThis, execUrl);
370
421
  } else if (typeof document === "undefined") {
371
422
  await import(
372
423
  /* webpackIgnore: true */
373
- EXEC_URL
424
+ execUrl
374
425
  );
375
426
  } else {
376
427
  await new Promise((resolve, reject) => {
377
428
  const el = document.createElement("script");
378
- el.src = EXEC_URL;
429
+ el.src = execUrl;
379
430
  el.async = true;
380
431
  el.onload = () => resolve();
381
432
  el.onerror = () => reject(new Error(`mediakit: cannot load ${EXEC_URL}`));
@@ -389,13 +440,12 @@ function loadExec() {
389
440
  function compileModule() {
390
441
  if (compiled) return compiled;
391
442
  compiled = (async () => {
392
- const res = await fetch(WASM_URL);
393
- if (!res.ok) {
443
+ const bytes = await resourceBytes("mediakit.wasm").catch((err) => {
394
444
  throw new Error(
395
- `mediakit: cannot load ${WASM_URL} (HTTP ${res.status}) - the host has to serve this package's dist/ under /mediakit/`
445
+ `mediakit: cannot load ${WASM_URL} (${err instanceof Error ? err.message : String(err)}) - the host has to serve this package's dist/ under /mediakit/`
396
446
  );
397
- }
398
- return WebAssembly.compileStreaming(res);
447
+ });
448
+ return WebAssembly.compile(bytes);
399
449
  })();
400
450
  return compiled;
401
451
  }
@@ -623,10 +673,10 @@ function gpuName(gl) {
623
673
  const name = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? "unknown");
624
674
  return gl.isContextLost() ? `${name}, context lost` : name;
625
675
  }
626
- function sourceSize(source) {
627
- if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight];
628
- if (typeof HTMLVideoElement !== "undefined" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight];
629
- const s = source;
676
+ function sourceSize(source2) {
677
+ if (source2 instanceof VideoFrame) return [source2.displayWidth, source2.displayHeight];
678
+ if (typeof HTMLVideoElement !== "undefined" && source2 instanceof HTMLVideoElement) return [source2.videoWidth, source2.videoHeight];
679
+ const s = source2;
630
680
  return [s.width, s.height];
631
681
  }
632
682
  function tileGrid(sw, sh) {
@@ -774,7 +824,7 @@ var Engine = class _Engine {
774
824
  // steers on past numbers because there is no way to know in advance what a frame will cost.
775
825
  prevTotalMs = 0;
776
826
  prevSegMs = 0;
777
- last = { ...ZERO_STATS };
827
+ last = { ...ZERO_STATS, parts: { ...NO_PARTS }, partErrors: { ...NO_PART_ERRORS } };
778
828
  constructor(canvas, gl, core) {
779
829
  this.canvas = canvas;
780
830
  this.gl = gl;
@@ -914,7 +964,7 @@ var Engine = class _Engine {
914
964
  }
915
965
  if (effects.whitenStyle === "pink" && this.skinLutState === "none") {
916
966
  this.skinLutState = "loading";
917
- decodeImage(assetUrl("whiten_pink.png"), { colorSpaceConversion: "none", premultiplyAlpha: "none" }).then((bmp) => {
967
+ resourceBytes("whiten_pink.png").then((b) => createImageBitmap(new Blob([b], { type: "image/png" }), { colorSpaceConversion: "none", premultiplyAlpha: "none" })).then((bmp) => {
918
968
  if (this.closed) {
919
969
  bmp.close();
920
970
  return;
@@ -992,7 +1042,7 @@ var Engine = class _Engine {
992
1042
  });
993
1043
  }).catch((e) => {
994
1044
  this.failed.add("face");
995
- this.partFailed("face", "face detection", "face effects", e);
1045
+ this.partFailed("face", "face detection", "face effects stay off", e);
996
1046
  this.gaveUp("face effects", e);
997
1047
  if (!(e instanceof LoadTimeout)) console.error("mediakit: face detector failed to load", e);
998
1048
  }).finally(() => {
@@ -1011,7 +1061,7 @@ var Engine = class _Engine {
1011
1061
  }).catch((e) => {
1012
1062
  if (!(e instanceof LoadTimeout)) return;
1013
1063
  this.failed.add("person");
1014
- this.partFailed("person", "person segmentation", "background effects", e);
1064
+ this.partFailed("person", "person segmentation", "background effects stay off", e);
1015
1065
  this.gaveUp("background effects", e);
1016
1066
  }).finally(() => {
1017
1067
  this.personLoading = null;
@@ -1072,7 +1122,7 @@ var Engine = class _Engine {
1072
1122
  cover: (ok, message) => {
1073
1123
  if (key !== "face" || this.coverState === "failed") return;
1074
1124
  this.coverState = ok ? "ready" : "failed";
1075
- if (!ok) this.partErr.set("cover", `mediakit: ${message}; occluders stays off`);
1125
+ if (!ok) this.partErr.set("cover", `${message}; occluders stays off`);
1076
1126
  },
1077
1127
  failed: (k, reason) => {
1078
1128
  if (key === "faceExtra") {
@@ -1142,7 +1192,7 @@ var Engine = class _Engine {
1142
1192
  * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow
1143
1193
  * detection drains Chrome's few capture buffers and throttles the camera itself.
1144
1194
  */
1145
- requestRemote(want, source, timestampUs) {
1195
+ requestRemote(want, source2, timestampUs) {
1146
1196
  const lockstep = want === "face" && this.syncing();
1147
1197
  const kind = lockstep ? this.freeFaceWorker() : want;
1148
1198
  if (!kind) return;
@@ -1153,16 +1203,16 @@ var Engine = class _Engine {
1153
1203
  let followed = null;
1154
1204
  let scanned = null;
1155
1205
  try {
1156
- const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas;
1206
+ const copyable = source2 instanceof VideoFrame || source2 instanceof OffscreenCanvas;
1157
1207
  if (copyable) {
1158
- this.srcW = source instanceof VideoFrame ? source.displayWidth : source.width;
1159
- this.srcH = source instanceof VideoFrame ? source.displayHeight : source.height;
1208
+ this.srcW = source2 instanceof VideoFrame ? source2.displayWidth : source2.width;
1209
+ this.srcH = source2 instanceof VideoFrame ? source2.displayHeight : source2.height;
1160
1210
  }
1161
1211
  if (copyable && (kind === "face" || kind === "faceExtra")) {
1162
- followed = this.followCopy(source, timestampUs);
1163
- if (!followed) scanned = this.scanCopy(source, timestampUs);
1212
+ followed = this.followCopy(source2, timestampUs);
1213
+ if (!followed) scanned = this.scanCopy(source2, timestampUs);
1164
1214
  }
1165
- frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(source, timestampUs) : source), {
1215
+ frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(source2, timestampUs) : source2), {
1166
1216
  timestamp: timestampUs
1167
1217
  });
1168
1218
  } catch {
@@ -1175,11 +1225,11 @@ var Engine = class _Engine {
1175
1225
  if (kind !== "face" && kind !== "faceExtra" && this.remoteMaskKind() === "merged") this.noteThumb(timestampUs);
1176
1226
  } else if (followed || scanned) this.faceCrops.delete(timestampUs);
1177
1227
  }
1178
- followCopy(source, timestampUs) {
1228
+ followCopy(source2, timestampUs) {
1179
1229
  const box = this.followBox;
1180
1230
  if (!box || timestampUs - this.followTs > FOLLOW_STALE_US) return null;
1181
- const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
1182
- const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
1231
+ const sw = source2 instanceof VideoFrame ? source2.displayWidth : source2.width;
1232
+ const sh = source2 instanceof VideoFrame ? source2.displayHeight : source2.height;
1183
1233
  const want = Math.max(FOLLOW_MIN_SIDE, FOLLOW_MARGIN * (1 + this.followMiss) * Math.max(box[2] * sw, box[3] * sh));
1184
1234
  if (want > Math.min(sw, sh) && this.followFloats > FACE_FLOATS) return null;
1185
1235
  if (!this.followAll && this.followTurn++ % FOLLOW_REFRESH === FOLLOW_REFRESH - 1) {
@@ -1195,24 +1245,24 @@ var Engine = class _Engine {
1195
1245
  [x, y, side] = kept;
1196
1246
  } else this.followCrop = [x, y, side];
1197
1247
  this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
1198
- this.followCanvas.getContext("2d").drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
1248
+ this.followCanvas.getContext("2d").drawImage(source2, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
1199
1249
  const tight = Math.min(side, Math.max(FOLLOW_MIN_SIDE, FOLLOW_RETRY * Math.max(box[2] * sw, box[3] * sh)));
1200
1250
  this.followRetry = [((box[0] + box[2] / 2) * sw - x) / side, ((box[1] + box[3] / 2) * sh - y) / side, tight / side];
1201
1251
  this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh]);
1202
1252
  return this.followCanvas;
1203
1253
  }
1204
- scanCopy(source, timestampUs) {
1254
+ scanCopy(source2, timestampUs) {
1205
1255
  if (this.faceSeen) return null;
1206
1256
  const turn = this.scanTurn++;
1207
1257
  if (turn % 2 === 0) return null;
1208
- const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
1209
- const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
1258
+ const sw = source2 instanceof VideoFrame ? source2.displayWidth : source2.width;
1259
+ const sh = source2 instanceof VideoFrame ? source2.displayHeight : source2.height;
1210
1260
  const { side, step, nx, ny } = tileGrid(sw, sh);
1211
1261
  const at = (this.scanFrom + (turn >> 1)) % (nx * ny);
1212
1262
  const x = Math.max(0, Math.min(sw - side, Math.round(at % nx * step)));
1213
1263
  const y = Math.max(0, Math.min(sh - side, Math.round(Math.floor(at / nx) * step)));
1214
1264
  this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE);
1215
- this.followCanvas.getContext("2d").drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
1265
+ this.followCanvas.getContext("2d").drawImage(source2, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE);
1216
1266
  this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh]);
1217
1267
  this.probes.add(timestampUs);
1218
1268
  return this.followCanvas;
@@ -1324,9 +1374,9 @@ var Engine = class _Engine {
1324
1374
  });
1325
1375
  }
1326
1376
  /** Face and mask asked on the same frame share one draw. */
1327
- detectCopy(source, timestampUs) {
1328
- const sw = source instanceof VideoFrame ? source.displayWidth : source.width;
1329
- const sh = source instanceof VideoFrame ? source.displayHeight : source.height;
1377
+ detectCopy(source2, timestampUs) {
1378
+ const sw = source2 instanceof VideoFrame ? source2.displayWidth : source2.width;
1379
+ const sh = source2 instanceof VideoFrame ? source2.displayHeight : source2.height;
1330
1380
  const s = Math.min(1, 512 / Math.max(sw, sh));
1331
1381
  const w = Math.max(1, Math.round(sw * s));
1332
1382
  const h = Math.max(1, Math.round(sh * s));
@@ -1335,7 +1385,7 @@ var Engine = class _Engine {
1335
1385
  this.detectCanvasTs = -1;
1336
1386
  }
1337
1387
  if (this.detectCanvasTs !== timestampUs) {
1338
- this.detectCanvas.getContext("2d").drawImage(source, 0, 0, w, h);
1388
+ this.detectCanvas.getContext("2d").drawImage(source2, 0, 0, w, h);
1339
1389
  this.detectCanvasTs = timestampUs;
1340
1390
  }
1341
1391
  return this.detectCanvas;
@@ -1376,7 +1426,7 @@ var Engine = class _Engine {
1376
1426
  this.segmenter = s;
1377
1427
  }).catch((e) => {
1378
1428
  this.failed.add("segmenter");
1379
- this.partFailed("person", "person segmentation", "background and skin effects", e);
1429
+ this.partFailed("person", "person segmentation", "background and skin effects stay off", e);
1380
1430
  this.gaveUp("background and skin effects", e);
1381
1431
  if (!(e instanceof LoadTimeout)) console.error("mediakit: segmenter failed to load", e);
1382
1432
  }).finally(() => {
@@ -1396,7 +1446,7 @@ var Engine = class _Engine {
1396
1446
  * LiveKit's reference implementation requires a `VideoFrame` even on its fallback path, so
1397
1447
  * it constructs one only to destroy it again.
1398
1448
  */
1399
- render(source, timestampUs) {
1449
+ render(source2, timestampUs) {
1400
1450
  if (this.closed || this.lostDuring) return false;
1401
1451
  if (this.lastHeld) this.spare.push(this.lastHeld);
1402
1452
  this.lastHeld = null;
@@ -1426,19 +1476,19 @@ var Engine = class _Engine {
1426
1476
  this.thumbs.clear();
1427
1477
  }
1428
1478
  this.prevTs = timestampUs;
1429
- if (!this.syncing() || typeof ImageData !== "undefined" && source instanceof ImageData) {
1479
+ if (!this.syncing() || typeof ImageData !== "undefined" && source2 instanceof ImageData) {
1430
1480
  this.releaseHeld();
1431
1481
  this.renderedTs = timestampUs;
1432
- return this.draw(source, timestampUs, false);
1482
+ return this.draw(source2, timestampUs, false);
1433
1483
  }
1434
1484
  this.ensureFaceExtra();
1435
- this.requestRemote("face", source, timestampUs);
1485
+ this.requestRemote("face", source2, timestampUs);
1436
1486
  const remoteMask = this.remoteMaskKind();
1437
1487
  if (remoteMask === "merged") {
1438
- this.requestRemote("person", source, timestampUs);
1439
- this.requestRemote("mask", source, timestampUs);
1440
- } else if (remoteMask) this.requestRemote(remoteMask, source, timestampUs);
1441
- this.queue.push({ c: this.hold(source), ts: timestampUs });
1488
+ this.requestRemote("person", source2, timestampUs);
1489
+ this.requestRemote("mask", source2, timestampUs);
1490
+ } else if (remoteMask) this.requestRemote(remoteMask, source2, timestampUs);
1491
+ this.queue.push({ c: this.hold(source2), ts: timestampUs });
1442
1492
  while (this.queue.length > MAX_HOLD + 1) this.faceAsked.delete(this.spareFront());
1443
1493
  if (this.queue.length <= MAX_HOLD && !this.faceReady(this.queue[0].ts)) {
1444
1494
  this.swallowed = true;
@@ -1605,15 +1655,15 @@ var Engine = class _Engine {
1605
1655
  syncing() {
1606
1656
  return this.syncFaces && this.faceRemote && needsFace(this.effects);
1607
1657
  }
1608
- hold(source) {
1609
- const [w, h] = sourceSize(source);
1658
+ hold(source2) {
1659
+ const [w, h] = sourceSize(source2);
1610
1660
  let c = this.spare.pop();
1611
1661
  while (c && (c.width !== w || c.height !== h)) c = this.spare.pop();
1612
1662
  c ??= new OffscreenCanvas(w, h);
1613
- c.getContext("2d").drawImage(source, 0, 0, w, h);
1663
+ c.getContext("2d").drawImage(source2, 0, 0, w, h);
1614
1664
  return c;
1615
1665
  }
1616
- draw(source, timestampUs, faceDone) {
1666
+ draw(source2, timestampUs, faceDone) {
1617
1667
  const t0 = performance.now();
1618
1668
  const [lo, hi] = splitMicros(timestampUs);
1619
1669
  const needSeg = this.core.decide(lo, hi, this.prevTotalMs, this.prevSegMs) === 1;
@@ -1627,8 +1677,8 @@ var Engine = class _Engine {
1627
1677
  const remoteMask = this.remoteMaskKind();
1628
1678
  if (remoteMask === "merged") {
1629
1679
  if (!faceDone) {
1630
- this.requestRemote("person", source, timestampUs);
1631
- this.requestRemote("mask", source, timestampUs);
1680
+ this.requestRemote("person", source2, timestampUs);
1681
+ this.requestRemote("mask", source2, timestampUs);
1632
1682
  }
1633
1683
  const tex = this.mergedTex ?? this.personMaskTex;
1634
1684
  if (tex) {
@@ -1642,7 +1692,7 @@ var Engine = class _Engine {
1642
1692
  segMs = this.personWorkerMs;
1643
1693
  }
1644
1694
  }
1645
- } else if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs);
1695
+ } else if (remoteMask && !faceDone) this.requestRemote(remoteMask, source2, timestampUs);
1646
1696
  if (remoteMask === "person") {
1647
1697
  if (this.personMaskTex) {
1648
1698
  served = true;
@@ -1673,7 +1723,7 @@ var Engine = class _Engine {
1673
1723
  if (!this.remoteMaskComing(this.filter, this.effects)) void this.ensureSegmenter();
1674
1724
  } else {
1675
1725
  const s0 = performance.now();
1676
- mask = seg.segment(source, timestampUs / 1e3);
1726
+ mask = seg.segment(source2, timestampUs / 1e3);
1677
1727
  segMs = performance.now() - s0;
1678
1728
  this.used = seg;
1679
1729
  maskKind = classes ? 1 : 0;
@@ -1682,7 +1732,7 @@ var Engine = class _Engine {
1682
1732
  if (faceDone) {
1683
1733
  faceMs = this.faceWorkerMs;
1684
1734
  } else if (this.faceRemote && needsFace(this.effects)) {
1685
- this.requestRemote("face", source, timestampUs);
1735
+ this.requestRemote("face", source2, timestampUs);
1686
1736
  faceMs = this.faceWorkerMs;
1687
1737
  } else if (this.core.decideFace() === 1) {
1688
1738
  if (this.faceRemote) {
@@ -1691,7 +1741,7 @@ var Engine = class _Engine {
1691
1741
  void this.ensureFace();
1692
1742
  } else if (this.lmBuf) {
1693
1743
  const f0 = performance.now();
1694
- const n = this.face.detect(source, timestampUs / 1e3, this.lmBuf);
1744
+ const n = this.face.detect(source2, timestampUs / 1e3, this.lmBuf);
1695
1745
  faceMs = performance.now() - f0;
1696
1746
  this.core.setFace(lo, hi, n);
1697
1747
  this.faceTs = timestampUs;
@@ -1699,7 +1749,7 @@ var Engine = class _Engine {
1699
1749
  }
1700
1750
  if (mask) this.maskUsedTs = maskTs;
1701
1751
  const [maskLo, maskHi] = splitMicros(maskTs);
1702
- const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi);
1752
+ const glCalls = this.core.process(source2, mask, this.background, maskKind, maskLo, maskHi);
1703
1753
  if (mask) this.used?.release();
1704
1754
  this.used = null;
1705
1755
  this.noteLinking();
@@ -1740,10 +1790,10 @@ var Engine = class _Engine {
1740
1790
  };
1741
1791
  return glCalls > 0;
1742
1792
  }
1743
- partFailed(part, what, off, e) {
1793
+ partFailed(part, what, then, e) {
1744
1794
  if (this.partErr.has(part)) return;
1745
1795
  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`);
1796
+ this.partErr.set(part, `${why}; ${then}`);
1747
1797
  }
1748
1798
  parts() {
1749
1799
  const f = this.filter;
@@ -1928,6 +1978,7 @@ var VideoPipeline = class {
1928
1978
  watchdog = null;
1929
1979
  movedOff = false;
1930
1980
  raised = /* @__PURE__ */ new Set();
1981
+ effectOff = "";
1931
1982
  slowTicks = 0;
1932
1983
  gpuRecoveries = 0;
1933
1984
  gpu = "";
@@ -1946,6 +1997,7 @@ var VideoPipeline = class {
1946
1997
  abort = null;
1947
1998
  // worker path
1948
1999
  worker = null;
2000
+ unserveWorker = null;
1949
2001
  workerStats = null;
1950
2002
  /** The background path the worker already holds; see backgroundForWorker. */
1951
2003
  workerBackgroundPath = null;
@@ -1995,7 +2047,7 @@ var VideoPipeline = class {
1995
2047
  });
1996
2048
  }
1997
2049
  issue(code, message, key = code) {
1998
- if (this.raised.has(key)) return;
2050
+ if (this.raised.has(key)) return false;
1999
2051
  this.raised.add(key);
2000
2052
  console.warn(`mediakit: ${code}: ${message}`);
2001
2053
  try {
@@ -2003,15 +2055,16 @@ var VideoPipeline = class {
2003
2055
  } catch (e) {
2004
2056
  console.error("mediakit: onIssue threw", e);
2005
2057
  }
2058
+ return true;
2006
2059
  }
2007
2060
  watchQuality() {
2008
2061
  const s = this.stats;
2009
2062
  if (!s) return;
2010
- if (s.effectError) this.issue("effect-off", s.effectError);
2063
+ if (s.effectError && this.issue("effect-off", s.effectError)) this.effectOff = s.effectError;
2011
2064
  for (const part of Object.keys(s.parts ?? {})) {
2012
2065
  if (s.parts[part] !== "failed") continue;
2013
2066
  const why = s.partErrors?.[part] || `mediakit: ${part} failed to load; its effects stay off`;
2014
- if (s.effectError && s.effectError.includes(why)) continue;
2067
+ if (this.effectOff.includes(why)) continue;
2015
2068
  this.issue("part-off", why, `part-off:${why}`);
2016
2069
  }
2017
2070
  const slow = s.totalMs > SLOW_FRAME_MS || s.faceMs > SLOW_FRAME_MS;
@@ -2109,24 +2162,24 @@ var VideoPipeline = class {
2109
2162
  return this.transport;
2110
2163
  }
2111
2164
  /** Take over `source` and publish the result on {@link processedTrack}. */
2112
- async start(source) {
2165
+ async start(source2) {
2113
2166
  this.gpu ||= probeGpu();
2114
2167
  const known = gpuRecord(this.gpu);
2115
2168
  if (known?.init) {
2116
2169
  throw new GpuLostError("init", this.gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`);
2117
2170
  }
2118
- const settings = source.getSettings();
2171
+ const settings = source2.getSettings();
2119
2172
  const width = settings.width ?? 1280;
2120
2173
  const height = settings.height ?? 720;
2121
2174
  this.stopped = false;
2122
- this.source = source;
2175
+ this.source = source2;
2123
2176
  this.size = { width, height, fps: settings.frameRate ?? 30 };
2124
2177
  this.frames = 0;
2125
2178
  this.movedOff = false;
2126
2179
  this.startWatchdog();
2127
2180
  if (hasInsertableStreams() && typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
2128
2181
  try {
2129
- await this.startWorker(source, width, height, await this.backgroundForWorker(this.filter));
2182
+ await this.startWorker(source2, width, height, await this.backgroundForWorker(this.filter));
2130
2183
  this.transport = "worker";
2131
2184
  this.workerDialect = "streams";
2132
2185
  return;
@@ -2137,7 +2190,7 @@ var VideoPipeline = class {
2137
2190
  }
2138
2191
  } else if (typeof Worker !== "undefined" && typeof OffscreenCanvas !== "undefined") {
2139
2192
  try {
2140
- await this.startWorkerWithTrack(source, width, height, await this.backgroundForWorker(this.filter));
2193
+ await this.startWorkerWithTrack(source2, width, height, await this.backgroundForWorker(this.filter));
2141
2194
  this.transport = "worker";
2142
2195
  this.workerDialect = "track";
2143
2196
  return;
@@ -2147,9 +2200,9 @@ var VideoPipeline = class {
2147
2200
  console.warn("mediakit: no worker transport in this browser, staying on the main thread", e);
2148
2201
  }
2149
2202
  }
2150
- await this.startMain(source);
2203
+ await this.startMain(source2);
2151
2204
  }
2152
- async startMain(source) {
2205
+ async startMain(source2) {
2153
2206
  const { width, height, fps } = this.size;
2154
2207
  this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces, {
2155
2208
  noFaceColor: this.noFaceColor()
@@ -2161,9 +2214,9 @@ var VideoPipeline = class {
2161
2214
  this.lastBeat = performance.now();
2162
2215
  this.stalled = false;
2163
2216
  if (this.transport === "insertable") {
2164
- this.startInsertable(source);
2217
+ this.startInsertable(source2);
2165
2218
  } else {
2166
- await this.startCanvas(source, fps);
2219
+ await this.startCanvas(source2, fps);
2167
2220
  }
2168
2221
  }
2169
2222
  /**
@@ -2197,11 +2250,11 @@ var VideoPipeline = class {
2197
2250
  this.lastBeat = performance.now();
2198
2251
  return this.processedTrack;
2199
2252
  }
2200
- async rebuild(source) {
2253
+ async rebuild(source2) {
2201
2254
  const previous = this.processedTrack;
2202
2255
  this.processedTrack = void 0;
2203
2256
  this.teardownTransports();
2204
- await this.start(source);
2257
+ await this.start(source2);
2205
2258
  previous?.stop();
2206
2259
  if (this.processedTrack) this.opts.onTrackReplaced?.(this.processedTrack, previous);
2207
2260
  }
@@ -2281,6 +2334,8 @@ var VideoPipeline = class {
2281
2334
  if (!this.worker) return;
2282
2335
  this.send({ t: "stop" });
2283
2336
  this.worker.terminate();
2337
+ this.unserveWorker?.();
2338
+ this.unserveWorker = null;
2284
2339
  this.worker = null;
2285
2340
  this.workerDialect = null;
2286
2341
  this.workerStats = null;
@@ -2314,11 +2369,11 @@ var VideoPipeline = class {
2314
2369
  * so it is the Chrome dialect. A browser that only has them inside a worker (Safari) does
2315
2370
  * not get this path and stays on the canvas transport until someone can test that.
2316
2371
  */
2317
- startWorker(source, width, height, background) {
2318
- const processor = new MediaStreamTrackProcessor({ track: source });
2372
+ startWorker(source2, width, height, background) {
2373
+ const processor = new MediaStreamTrackProcessor({ track: source2 });
2319
2374
  const generator = new MediaStreamTrackGenerator({
2320
2375
  kind: "video",
2321
- signalTarget: source
2376
+ signalTarget: source2
2322
2377
  });
2323
2378
  return this.attachWorker(
2324
2379
  (ready) => {
@@ -2346,8 +2401,8 @@ var VideoPipeline = class {
2346
2401
  );
2347
2402
  }
2348
2403
  /** Safari's dialect (see `startTrack` in worker/entry.ts). */
2349
- startWorkerWithTrack(source, width, height, background) {
2350
- const clone = source.clone();
2404
+ startWorkerWithTrack(source2, width, height, background) {
2405
+ const clone = source2.clone();
2351
2406
  return this.attachWorker(
2352
2407
  (ready) => {
2353
2408
  if (!ready.track) throw new Error("mediakit: the worker sent no track");
@@ -2377,6 +2432,7 @@ var VideoPipeline = class {
2377
2432
  attachWorker(onReady, cleanup, post) {
2378
2433
  const worker = new Worker(assetUrl("worker.js"));
2379
2434
  this.worker = worker;
2435
+ this.unserveWorker = serveResources(worker);
2380
2436
  return new Promise((resolve, reject) => {
2381
2437
  let settled = false;
2382
2438
  const fail = (err) => {
@@ -2398,6 +2454,7 @@ var VideoPipeline = class {
2398
2454
  fail(new Error(e.message || "mediakit: worker failed to load"));
2399
2455
  };
2400
2456
  worker.onmessage = (e) => {
2457
+ if (isAssetsMessage(e.data)) return;
2401
2458
  const m = e.data;
2402
2459
  if (m.t === "stats") {
2403
2460
  this.workerStats = m.stats;
@@ -2449,19 +2506,19 @@ var VideoPipeline = class {
2449
2506
  });
2450
2507
  }
2451
2508
  // ── insertable ───────────────────────────────────────────────────────────────────
2452
- startInsertable(source) {
2509
+ startInsertable(source2) {
2453
2510
  this.generator = new MediaStreamTrackGenerator({
2454
2511
  kind: "video",
2455
- signalTarget: source
2512
+ signalTarget: source2
2456
2513
  });
2457
2514
  this.processedTrack = this.generator;
2458
- this.pipeInsertable(source);
2515
+ this.pipeInsertable(source2);
2459
2516
  }
2460
- pipeInsertable(source) {
2517
+ pipeInsertable(source2) {
2461
2518
  const generator = this.generator;
2462
2519
  if (!generator) return;
2463
2520
  const processor = new MediaStreamTrackProcessor({
2464
- track: source
2521
+ track: source2
2465
2522
  });
2466
2523
  const transform = new TransformStream({
2467
2524
  transform: (frame, controller) => {
@@ -2506,7 +2563,7 @@ var VideoPipeline = class {
2506
2563
  });
2507
2564
  }
2508
2565
  // ── canvas ───────────────────────────────────────────────────────────────────────
2509
- async startCanvas(source, fps) {
2566
+ async startCanvas(source2, fps) {
2510
2567
  const engine = this.engine;
2511
2568
  const video = document.createElement("video");
2512
2569
  video.muted = true;
@@ -2516,7 +2573,7 @@ var VideoPipeline = class {
2516
2573
  video.style.pointerEvents = "none";
2517
2574
  video.width = 1;
2518
2575
  video.height = 1;
2519
- video.srcObject = new MediaStream([source]);
2576
+ video.srcObject = new MediaStream([source2]);
2520
2577
  document.body.appendChild(video);
2521
2578
  this.video = video;
2522
2579
  await video.play();
@@ -3906,6 +3963,7 @@ export {
3906
3963
  TRANSITIONS,
3907
3964
  VideoPipeline,
3908
3965
  checkSupport,
3966
+ clearCachedAssets,
3909
3967
  forgetGpuFailures,
3910
3968
  gpuRecord,
3911
3969
  hitTest,