@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/README.md +40 -1
- package/dist/detect-worker.js +39 -2
- package/dist/detect-worker.js.map +1 -1
- package/dist/index.d.ts +29 -3
- package/dist/index.js +114 -10
- package/dist/index.js.map +1 -1
- package/dist/worker.js +53 -2
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/segmenter.ts","../src/mp.ts","../src/mp-clock.ts","../src/face.ts","../src/detect-remote.ts","../src/wasm.ts","../src/gpu-guard.ts","../src/mask-merge.ts","../src/engine.ts","../src/pipeline.ts","../src/scene.ts","../src/facemesh.ts"],"sourcesContent":["import { ImageSegmenter } from \"@mediapipe/tasks-vision\"\nimport { MODEL_URL, visionFileset } from \"./mp\"\nimport { monotonicClock } from \"./mp-clock\"\n\n/**\n * Person segmentation, on the GPU, with the mask staying on the GPU.\n *\n * ── The two facts that decide the whole design ───────────────────────────────────────\n *\n * 1. **It shares the WebGL context with mediakit.** `createFromOptions` is given the very\n * canvas the Device took its context from, so `getAsWebGLTexture()` returns a texture\n * mediakit can sample directly. With separate contexts the mask would have to be read back\n * to the CPU and uploaded again - the most expensive round trip in the pipeline, for data\n * that was already in the right place.\n *\n * The price is that MediaPipe changes GL state behind mediakit's back. That is handled in\n * `ResetState` in `gpu/webgl/device.go` - read the comment there before changing anything\n * here.\n *\n * 2. **Assets are served from the consuming origin.** Everything lives under `/mediakit/`,\n * which the host app copies out of this package's `dist/`. Nothing is fetched from a third\n * party while a frame is being processed - that is gate P0.8.\n */\n\n/** Which model: `person` is the selfie segmenter, person against background, 244 kB. */\nexport type SegmenterModel = \"person\" | \"classes\"\n\nexport interface Segmenter {\n /** The raw mask as a WebGLTexture, or null when this frame produced no result. */\n segment(frame: VideoFrame, timestampMs: number): WebGLTexture | null\n /**\n * Hand the last result's buffer back to MediaPipe.\n *\n * Call it AFTER mediakit is done with the texture, not before. Closing the result and then\n * sampling the texture reads a buffer that has gone back to the shared pool - it may still\n * hold the same mask, or it may hold another frame's. Neither reports anything.\n *\n * Not calling it breaks differently: MediaPipe runs out of buffers after a few dozen\n * frames, quietly stops returning masks, and the effect freezes on the last one it managed.\n */\n release(): void\n close(): void\n}\n\n/**\n * Build a segmenter on the canvas mediakit is drawing to.\n *\n * `canvas` must be the EXACT canvas whose `WebGL2RenderingContext` was passed to `core.init` -\n * see reason 1 above.\n */\nexport async function createSegmenter(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n model: SegmenterModel = \"person\",\n): Promise<Segmenter> {\n const fileset = await visionFileset()\n\n const segmenter = await ImageSegmenter.createFromOptions(fileset, {\n baseOptions: {\n modelAssetPath: MODEL_URL[model],\n // MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all\n // have. That is why mediakit picked MediaPipe over ONNX Runtime Web at P1: ORT's\n // fast path is WebGPU, which Firefox only has on Windows.\n delegate: \"GPU\",\n },\n canvas,\n runningMode: \"VIDEO\",\n // Category mask, not a confidence mask. The values are category INDICES, so they need\n // normalising before they can act as alpha - MaskGain and MaskInvert in `core/graph.go`\n // do that.\n outputCategoryMask: true,\n outputConfidenceMasks: false,\n })\n\n const clock = monotonicClock()\n // The open result, held until mediakit is done with its texture.\n let pending: { close(): void } | null = null\n\n const release = () => {\n pending?.close()\n pending = null\n }\n\n return {\n segment(frame, timestampMs) {\n // The previous result was never given back - the caller forgot to release, or the\n // frame before threw part way through. Give it back now rather than leak until the\n // pool runs dry.\n release()\n\n let texture: WebGLTexture | null = null\n // This callback is SYNCHRONOUS - it finishes before segmentForVideo returns. That\n // is also why the call blocks the event loop for tens of milliseconds, and why\n // mediakit has a governor at all: the cheapest way to make it faster is to call it\n // less often.\n segmenter.segmentForVideo(frame, clock(timestampMs), (result) => {\n const mask = result.categoryMask\n if (mask) texture = mask.getAsWebGLTexture()\n // NOT closed here - the texture has to outlive core.process(). See release().\n pending = result\n })\n return texture\n },\n release,\n close() {\n release()\n segmenter.close()\n },\n }\n}\n\n/** A category mask read back to bytes: one category index per pixel, row 0 at the top. */\nexport interface MaskBytes {\n width: number\n height: number\n data: Uint8Array\n}\n\n/**\n * A segmenter for a worker of its own: it reads the mask back instead of lending a texture, since\n * a texture cannot leave its context. The read happens there, off the frame path.\n */\nexport async function createMaskReader(\n canvas: OffscreenCanvas,\n model: SegmenterModel,\n delegate: \"GPU\" | \"CPU\",\n): Promise<{ read(frame: OffscreenCanvas, timestampMs: number): MaskBytes | null; close(): void }> {\n const fileset = await visionFileset()\n const segmenter = await ImageSegmenter.createFromOptions(fileset, {\n baseOptions: { modelAssetPath: MODEL_URL[model], delegate },\n canvas,\n runningMode: \"VIDEO\",\n outputCategoryMask: true,\n outputConfidenceMasks: false,\n })\n const clock = monotonicClock()\n return {\n read(frame, timestampMs) {\n let out: MaskBytes | null = null\n segmenter.segmentForVideo(frame, clock(timestampMs), (result) => {\n const mask = result.categoryMask\n if (mask) out = { width: mask.width, height: mask.height, data: mask.getAsUint8Array().slice() }\n result.close()\n })\n return out\n },\n close() {\n segmenter.close()\n },\n }\n}\n","import { FilesetResolver } from \"@mediapipe/tasks-vision\"\nimport { ASSETS, assetUrl } from \"./assets\"\n\nexport const MP_DIR = assetUrl(\"mp\")\n\nexport const MODEL_URL = {\n person: assetUrl(\"selfie_segmenter.tflite\"),\n classes: assetUrl(\"selfie_multiclass_256x256.tflite\"),\n face: assetUrl(\"face_landmarker.task\"),\n} as const\n\n/** How long one detector may take to download and build before its effects are given up on. */\nexport const LOAD_MS = 60_000\n\ntype Fileset = Awaited<ReturnType<typeof FilesetResolver.forVisionTasks>>\n\nlet fileset: Promise<Fileset> | null = null\n\n/** The MediaPipe runtime paths, resolved once per realm. */\nexport function visionFileset(): Promise<Fileset> {\n fileset ??= FilesetResolver.forVisionTasks(MP_DIR).catch((e: unknown) => {\n fileset = null\n throw e\n })\n return fileset\n}\n\n/** A detector that did not come up within {@link LOAD_MS}. */\nexport class LoadTimeout extends Error {\n constructor(what: string, ms: number) {\n super(`mediakit: ${what} did not load within ${Math.round(ms / 1000)} s`)\n this.name = \"LoadTimeout\"\n }\n}\n\n/** `p`, or a LoadTimeout after `ms`; what `p` brings after that goes to `late`. */\nexport function withTimeout<T>(p: Promise<T>, ms: number, what: string, late: (v: T) => void): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let done = false\n const timer = setTimeout(() => {\n done = true\n reject(new LoadTimeout(what, ms))\n }, ms)\n p.then(\n (v) => {\n if (done) late(v)\n else {\n done = true\n clearTimeout(timer)\n resolve(v)\n }\n },\n (e: unknown) => {\n if (done) return\n done = true\n clearTimeout(timer)\n reject(e)\n },\n )\n })\n}\n\n/** Which detectors {@link preloadDetectors} fetches; the MediaPipe runtime comes with any of them. */\nexport interface PreloadParts {\n person?: boolean\n classes?: boolean\n face?: boolean\n cover?: boolean\n}\n\n/**\n * Warm the HTTP cache with the MediaPipe runtime and the chosen models, at low priority, so the\n * first recipe that needs them builds without waiting on the network. Never rejects.\n */\nexport async function preloadDetectors(parts: PreloadParts = { person: true, classes: true, face: true }): Promise<void> {\n const urls: string[] = []\n if (parts.cover) for (const a of ASSETS) if (a.part === \"cover\") urls.push(assetUrl(a.path))\n if (parts.person || parts.classes || parts.face) {\n try {\n const fs = await visionFileset()\n urls.push(fs.wasmBinaryPath, fs.wasmLoaderPath)\n for (const k of [\"person\", \"classes\", \"face\"] as const) if (parts[k]) urls.push(MODEL_URL[k])\n } catch {}\n }\n await Promise.all(\n urls.map((u) =>\n fetch(u, { priority: \"low\" } as RequestInit)\n .then((r) => r.arrayBuffer())\n .catch(() => undefined),\n ),\n )\n}\n","const SOURCE_SWITCH_GAP_MS = 33\n\nexport function monotonicClock(): (timestampMs: number) => number {\n let offset = 0\n let last = -Infinity\n return (timestampMs) => {\n let t = timestampMs + offset\n if (t <= last) {\n offset += last + SOURCE_SWITCH_GAP_MS - t\n t = last + SOURCE_SWITCH_GAP_MS\n }\n last = t\n return t\n }\n}\n","import { FaceLandmarker } from \"@mediapipe/tasks-vision\"\nimport { monotonicClock } from \"./mp-clock\"\nimport { MODEL_URL, visionFileset } from \"./mp\"\n\n/**\n * Face landmark detection.\n *\n * Separate from `segmenter.ts` because the two detectors are INDEPENDENT costs: whitening\n * teeth does not need a person mask, replacing a background does not need to know where the\n * eyes are. This one loads only when the recipe actually asks for it - the model is ~3.7 MB,\n * fifteen times the segmentation one.\n *\n * Landmarks are NOT interpreted here. They are written straight into the Go core's buffer, and\n * every region derivation and all the smoothing live in `core/face`. The reason is in that\n * package's header: the hard part is not the coordinate transform, it is deciding when a\n * region is allowed to move - a control problem, not a geometry one.\n */\n\n\nexport interface FaceDetector {\n /**\n * Write every face's landmarks into `out`, back to back, and return how many cells were\n * written. 0 means no face.\n *\n * `out` is allocated by the Go core - writing straight into it avoids one new array per\n * frame - and its length is what bounds how many faces fit.\n */\n detect(frame: TexImageSource | OffscreenCanvas, timestampMs: number, out: Float32Array): number\n close(): void\n}\n\n/** Floats per face: FaceLandmarker's 478 points times x, y, z. Mirrors `face.Floats` in Go. */\nexport const FACE_FLOATS = 478 * 3\n\nexport const COVER_SIZE = 96\n\nexport type Box = [number, number, number, number]\n\nexport function faceBox(lm: Float32Array, at: number): Box {\n let x0 = 1\n let y0 = 1\n let x1 = 0\n let y1 = 0\n for (let i = at; i < at + FACE_FLOATS; i += 3) {\n x0 = Math.min(x0, lm[i]!)\n x1 = Math.max(x1, lm[i]!)\n y0 = Math.min(y0, lm[i + 1]!)\n y1 = Math.max(y1, lm[i + 1]!)\n }\n return [x0, y0, x1 - x0, y1 - y0]\n}\n\n/**\n * `maxFaces` comes from the Go core's buffer (its length over FACE_FLOATS), so the number of\n * faces tracked is decided in one place.\n */\nexport async function createFaceDetector(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n maxFaces: number,\n delegate: \"GPU\" | \"CPU\" = \"GPU\",\n mode: \"VIDEO\" | \"IMAGE\" = \"VIDEO\",\n): Promise<FaceDetector> {\n const fileset = await visionFileset()\n\n const landmarker = await FaceLandmarker.createFromOptions(fileset, {\n baseOptions: { modelAssetPath: MODEL_URL.face, delegate },\n canvas,\n runningMode: mode,\n // As many as the core tracks: one landmark pass returns them all, so the cost of a second\n // face is the copy below and its own shader passes, not a second inference.\n numFaces: maxFaces,\n // No blendshapes and no transformation matrix - extra work for data nobody reads.\n outputFaceBlendshapes: false,\n outputFacialTransformationMatrixes: false,\n })\n\n const clock = monotonicClock()\n return {\n detect(frame, timestampMs, out) {\n const res = mode === \"VIDEO\" ? landmarker.detectForVideo(frame, clock(timestampMs)) : landmarker.detect(frame)\n let n = 0\n for (const lm of res.faceLandmarks ?? []) {\n // Whole faces only: a face cut off by the end of the buffer would parse as garbage.\n if (lm.length * 3 !== FACE_FLOATS || n + FACE_FLOATS > out.length) break\n for (let i = 0; i < lm.length; i++) {\n const p = lm[i]\n out[n + i * 3] = p.x\n out[n + i * 3 + 1] = p.y\n out[n + i * 3 + 2] = p.z\n }\n n += FACE_FLOATS\n }\n return n\n },\n close() {\n landmarker.close()\n },\n }\n}\n","import type { DetectReply, DetectRequest } from \"./detect-worker/entry\"\nimport { LOAD_MS, LoadTimeout } from \"./mp\"\nimport type { SegmenterModel } from \"./segmenter\"\nimport { assetUrl } from \"./assets\"\n\nconst DETECT_WORKER_URL = assetUrl(\"detect-worker.js\")\n\ntype Kind = \"face\" | \"mask\"\n\nexport interface DetectHandlers {\n face(tsUs: number, n: number, lm: Float32Array, ms: number, cover: Uint8Array | null, rects: Float32Array | null): void\n mask(tsUs: number, width: number, height: number, data: Uint8Array, ms: number): void\n /** That kind stopped working after it was ready; the caller detects in-thread from now on. */\n failed(kind: Kind, reason: string): void\n}\n\n/**\n * Detection in a worker of its own. At most one frame in flight per kind: a request while one is\n * pending is dropped, and the regions or the last mask carry on until the answer lands.\n */\nexport class DetectWorker {\n private worker: Worker | null\n private readonly ready = new Map<Kind, { resolve(): void; reject(e: Error): void; timer: ReturnType<typeof setTimeout> }>()\n private readonly up = new Set<Kind>()\n private readonly busy = new Set<Kind>()\n\n constructor(private readonly on: DetectHandlers) {\n this.worker = new Worker(DETECT_WORKER_URL)\n this.worker.onerror = (e) => this.failAll(e.message || \"detect worker failed to load\")\n this.worker.onmessage = (e: MessageEvent<DetectReply>) => this.receive(e.data)\n }\n\n initFace(maxFaces: number): Promise<void> {\n return this.init(\"face\", { t: \"initFace\", maxFaces })\n }\n\n initMask(model: SegmenterModel): Promise<void> {\n return this.init(\"mask\", { t: \"initMask\", model })\n }\n\n /** Whether `request` would take a frame of this kind now. */\n accepts(kind: Kind): boolean {\n return this.worker !== null && this.up.has(kind) && !this.busy.has(kind)\n }\n\n /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */\n request(kind: Kind, frame: VideoFrame, tsUs: number, cover = false, retry: [number, number, number] | null = null): boolean {\n if (!this.accepts(kind)) {\n frame.close()\n return false\n }\n this.busy.add(kind)\n this.send(kind === \"face\" ? { t: kind, frame, tsUs, cover, retry } : { t: kind, frame, tsUs }, [frame])\n return true\n }\n\n isUp(kind: Kind): boolean {\n return this.up.has(kind)\n }\n\n close(): void {\n this.send({ t: \"close\" })\n this.worker = null\n for (const kind of [...this.ready.keys()]) this.settle(kind, new Error(\"closed\"))\n this.up.clear()\n }\n\n private init(kind: Kind, m: DetectRequest): Promise<void> {\n if (this.up.has(kind)) return Promise.resolve()\n return new Promise((resolve, reject) => {\n if (!this.worker) {\n reject(new Error(\"detect worker gone\"))\n return\n }\n const timer = setTimeout(() => this.settle(kind, new LoadTimeout(`${kind} detection`, LOAD_MS)), LOAD_MS)\n this.ready.set(kind, { resolve, reject, timer })\n this.send(m)\n })\n }\n\n private receive(m: DetectReply): void {\n switch (m.t) {\n case \"ready\":\n this.up.add(m.kind)\n this.settle(m.kind)\n break\n case \"error\":\n if (this.ready.has(m.kind)) this.settle(m.kind, new Error(m.message))\n else this.fail(m.kind, m.message)\n break\n case \"face\":\n this.busy.delete(\"face\")\n if (this.up.has(\"face\")) this.on.face(m.tsUs, m.n, m.lm, m.ms, m.cover, m.rects)\n break\n case \"mask\":\n this.busy.delete(\"mask\")\n if (this.up.has(\"mask\") && m.width > 0) this.on.mask(m.tsUs, m.width, m.height, m.data, m.ms)\n break\n }\n }\n\n private settle(kind: Kind, err?: Error): void {\n const r = this.ready.get(kind)\n if (!r) return\n this.ready.delete(kind)\n clearTimeout(r.timer)\n if (err) r.reject(err)\n else r.resolve()\n }\n\n private fail(kind: Kind, reason: string): void {\n if (!this.up.delete(kind)) return\n this.busy.delete(kind)\n this.on.failed(kind, reason)\n }\n\n private failAll(reason: string): void {\n this.worker?.terminate()\n this.worker = null\n for (const kind of [...this.ready.keys()]) this.settle(kind, new Error(reason))\n for (const kind of [...this.up]) this.fail(kind, reason)\n }\n\n private send(m: DetectRequest, transfer: Transferable[] = []): void {\n this.worker?.postMessage(m, transfer)\n }\n}\n","/**\n * Loads the Go core.\n *\n * The core is built from this repo for `GOOS=js GOARCH=wasm`. It never touches a pixel: every\n * frame, mask and texture crosses into it as a handle, and the per-pixel work happens in the\n * WebGL2 shaders it drives. See `doc/apps/mediakit/PLAN.md` section 2.\n */\n\nimport type { CoreRecipe } from \"./recipe\"\nimport type { CoreLayer } from \"./layout\"\nimport { assetUrl } from \"./assets\"\n\n/** The surface the Go core exports. Matches `wasmjs/main.go`. */\nexport interface MediakitCore {\n /** Empty string on success, an error message otherwise. */\n init(gl: WebGL2RenderingContext, width: number, height: number): string\n /** Takes an object with NAMED fields - see `setRecipe` in wasmjs/main.go. */\n setRecipe(recipe: CoreRecipe): string\n /** Shared array to write landmarks into. Allocated once, by the core. */\n faceBuffer(): Float32Array | null\n /** Commit the landmarks just written. n = cell count; 0 means no face this frame. */\n setFace(usLo: number, usHi: number, n: number): string\n setDebug(view: number): string\n /** The first background shader link that failed, empty while none has. */\n programError?(): string\n /** Never link a face colour shader again; `reason` becomes the programError. */\n disableFaceColor?(reason: string): void\n /** How many face colour shaders the driver is still linking. */\n linking?(): number\n /** How many face colour links were started, failed ones included. */\n links?(): number\n /** Returns 1 when the coming frame NEEDS segmentation. */\n decide(usLo: number, usHi: number, prevTotalMs: number, prevSegMs: number): number\n /** Returns 1 when the coming frame needs landmark detection. Reads back decide's verdict. */\n decideFace(): number\n /**\n * Returns the GL call count for this frame - the P0.2 gate is measured from it - or 0 when\n * nothing was drawn and the source frame has to be shown instead.\n */\n /** `maskKind` is what `mask` carries: 0 a person mask, 1 the multiclass categories. */\n process(frame: unknown, mask: unknown, background: unknown, maskKind?: number, maskUsLo?: number, maskUsHi?: number): number\n /** Hand the colour LUT image over once; null clears it. Not per frame - see Pipeline.SetLut. */\n setLut(image: unknown): string\n /** Hand the makeup texture over once; null clears it. See Pipeline.SetMakeup. */\n setMakeup(image: unknown): string\n setFaceCover(image: unknown): string\n /** Hand the pink whitening table over once; null clears it. See Pipeline.SetSkinLut. */\n setSkinLut(image: unknown): string\n /** 16 cells - layout in `statsFloats` in wasmjs/main.go. */\n stats(): Float32Array | null\n close(): void\n\n // The scene compositor - `sceneState` in wasmjs/main.go. One core runs either a camera\n // pipeline or a scene in practice, but the two do not share state.\n sceneInit(gl: WebGL2RenderingContext, width: number, height: number): string\n sceneBackground(r: number, g: number, b: number): string\n /** Copy one source's picture into its slot; null empties the slot. */\n sceneUpload(slot: number, image: unknown, width: number, height: number): string\n sceneSet(layers: CoreLayer[], usLo: number, usHi: number, animateMs: number): string\n sceneSwitch(layers: CoreLayer[], usLo: number, usHi: number, transition: number, durationMs: number): string\n /** GL call count of the frame, 0 once closed. */\n sceneRender(usLo: number, usHi: number): number\n sceneClose(): string\n}\n\n// Declared on globalThis rather than Window: the same two names have to be reachable from a\n// DedicatedWorker, where Window does not exist.\ndeclare global {\n var Go:\n | (new () => {\n importObject: WebAssembly.Imports\n run(instance: WebAssembly.Instance): Promise<void>\n })\n | undefined\n var __mediakitAttach: ((core: MediakitCore) => void) | undefined\n}\n\nconst WASM_URL = assetUrl(\"mediakit.wasm\")\nconst EXEC_URL = assetUrl(\"wasm_exec.js\")\n\nlet execLoaded: Promise<void> | null = null\nlet compiled: Promise<WebAssembly.Module> | null = null\n\n/**\n * `wasm_exec.js` is the shim Go ships, and it MUST come from the same Go release that built\n * the `.wasm`. A skew between them is not a compile error: it surfaces at runtime, with a\n * message that points nowhere near the cause. Both files travel in this package's `dist/` and\n * the consumer copies them in one step, so never update one alone.\n */\n//\n// Two ways in, because a worker has no document. The script tag stays the main-thread path\n// because it is the one that has been running; a worker takes the dynamic import instead.\n// wasm_exec.js is an IIFE that assigns globalThis.Go, so importing it for its side effect is\n// enough - it exports nothing.\nfunction loadExec(): Promise<void> {\n if (execLoaded) return execLoaded\n execLoaded = (async () => {\n if (globalThis.Go) return\n const workerLoad = (globalThis as { importScripts?: (url: string) => void }).importScripts\n if (typeof workerLoad === \"function\") {\n // A CLASSIC worker. It has to be classic, because MediaPipe loads its own wasm glue\n // with importScripts() and a module worker forbids that - so the Go shim comes in\n // the same way rather than through a dynamic import.\n workerLoad.call(globalThis, EXEC_URL)\n } else if (typeof document === \"undefined\") {\n await import(/* webpackIgnore: true */ EXEC_URL)\n } else {\n await new Promise<void>((resolve, reject) => {\n const el = document.createElement(\"script\")\n el.src = EXEC_URL\n el.async = true\n el.onload = () => resolve()\n el.onerror = () => reject(new Error(`mediakit: cannot load ${EXEC_URL}`))\n document.head.appendChild(el)\n })\n }\n if (!globalThis.Go) throw new Error(\"mediakit: wasm_exec.js did not define Go\")\n })()\n return execLoaded\n}\n\n/**\n * Compile the module ONCE, then instantiate it as often as needed.\n *\n * Compiling is the expensive half; instantiating is cheap. Each instance gets its own memory\n * and its own globals, so two pipelines running side by side cannot tread on each other.\n */\nfunction compileModule(): Promise<WebAssembly.Module> {\n if (compiled) return compiled\n compiled = (async () => {\n const res = await fetch(WASM_URL)\n if (!res.ok) {\n throw new Error(\n `mediakit: cannot load ${WASM_URL} (HTTP ${res.status}) - ` +\n \"the host has to serve this package's dist/ under /mediakit/\",\n )\n }\n return WebAssembly.compileStreaming(res)\n })()\n return compiled\n}\n\n/**\n * Bring up one independent mediakit core.\n *\n * `go.run()` NEVER resolves: the core's `main()` ends in `select{}` to keep the runtime alive,\n * because a Go/wasm program exits when main returns and exiting turns every registered\n * function into a call into a dead runtime. So wait for the attach callback rather than\n * awaiting `go.run()`.\n */\nexport async function loadCore(): Promise<MediakitCore> {\n await loadExec()\n const mod = await compileModule()\n\n const Go = globalThis.Go!\n const go = new Go()\n const instance = await WebAssembly.instantiate(mod, go.importObject)\n\n return new Promise<MediakitCore>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(\"mediakit: core did not attach within 10s\")),\n 10_000,\n )\n globalThis.__mediakitAttach = (core) => {\n clearTimeout(timer)\n delete globalThis.__mediakitAttach\n resolve(core)\n }\n void go.run(instance).catch((e: unknown) => {\n clearTimeout(timer)\n reject(e instanceof Error ? e : new Error(String(e)))\n })\n })\n}\n\n/** Split a microsecond count into the two 32-bit halves `decide` takes. */\nexport function splitMicros(us: number): [number, number] {\n const lo = us >>> 0\n const hi = Math.floor(us / 2 ** 32)\n return [lo, hi | 0]\n}\n","/** When a lost WebGL context happened: building the core's shaders, linking a face colour shader, or later. */\nexport type LossPhase = \"init\" | \"link\" | \"run\"\n\n/** What this browser remembers about a GPU that lost its context under mediakit. */\nexport interface GpuRecord {\n /** Lost the context building the core's shaders: mediakit does not start on it. */\n init: boolean\n /** Lost the context linking a face colour shader: makeup and teeth stay off on it. */\n faceColor: boolean\n /** When the last loss was recorded, ms since the epoch. */\n at: number\n}\n\nconst KEY = \"mediakit-gpu-guard\"\nconst TTL_MS = 3 * 24 * 3600 * 1000\n\ntype Store = Record<string, GpuRecord>\n\nfunction storage(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage\n } catch {\n return null\n }\n}\n\nfunction load(): Store {\n const s = storage()\n if (!s) return {}\n try {\n const parsed: unknown = JSON.parse(s.getItem(KEY) ?? \"{}\")\n return parsed && typeof parsed === \"object\" ? (parsed as Store) : {}\n } catch {\n return {}\n }\n}\n\nfunction save(store: Store): void {\n try {\n storage()?.setItem(KEY, JSON.stringify(store))\n } catch {\n return\n }\n}\n\n/** The record for `gpu`, null when there is none, it expired, or this realm has no localStorage. */\nexport function gpuRecord(gpu: string): GpuRecord | null {\n if (!gpu) return null\n const r = load()[gpu]\n if (!r || typeof r.at !== \"number\" || Date.now() - r.at > TTL_MS) return null\n return { init: r.init === true, faceColor: r.faceColor === true, at: r.at }\n}\n\n/** Remember a loss on `gpu`; a \"run\" loss is a reset or a reclaim, not a shader, and is not kept. */\nexport function recordLoss(gpu: string, phase: LossPhase): void {\n if (!gpu || phase === \"run\" || !storage()) return\n const store = load()\n const was = gpuRecord(gpu)\n store[gpu] = {\n init: phase === \"init\" || (was?.init ?? false),\n faceColor: phase === \"link\" || (was?.faceColor ?? false),\n at: Date.now(),\n }\n save(store)\n}\n\n/** Forget every GPU failure this browser remembers - for a \"try again\" after a driver update. */\nexport function forgetGpuFailures(): void {\n try {\n storage()?.removeItem(KEY)\n } catch {\n return\n }\n}\n\n/** The renderer name a WebGL2 context reports, \"\" when the browser hides it or the context is gone. */\nexport function rendererOf(gl: WebGL2RenderingContext): string {\n if (gl.isContextLost()) return \"\"\n const info = gl.getExtension(\"WEBGL_debug_renderer_info\")\n return String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? \"\")\n}\n\n/** A WebGL context lost while mediakit was building or linking its shaders. */\nexport class GpuLostError extends Error {\n constructor(\n readonly phase: LossPhase,\n readonly gpu: string,\n readonly detail = \"\",\n ) {\n super(`mediakit: the WebGL context was lost ${phase === \"init\" ? \"building the shaders\" : phase === \"link\" ? \"linking a makeup shader\" : \"while running\"}${detail ? ` (${detail})` : \"\"} [GPU: ${gpu || \"unknown\"}]`)\n this.name = \"GpuLostError\"\n }\n}\n","import type { MaskBytes } from \"./segmenter\"\n\nexport const CLASS_BACKGROUND = 0\nexport const CLASS_BODY_SKIN = 2\nexport const CLASS_CLOTHES = 4\nexport const CLASS_OTHERS = 5\nexport const CLASS_STALE_OCCLUDER = 6\n\nexport const THUMB_W = 64\nexport const THUMB_H = 36\nconst MOVED_LUMA = 12\n\nexport function lumaThumb(rgba: Uint8ClampedArray): Uint8Array {\n const y = new Uint8Array(THUMB_W * THUMB_H)\n for (let i = 0; i < y.length; i++) y[i] = (rgba[i * 4]! * 77 + rgba[i * 4 + 1]! * 150 + rgba[i * 4 + 2]! * 29) >> 8\n return y\n}\n\nexport function movedBetween(a: Uint8Array, b: Uint8Array): MaskBytes {\n const w = THUMB_W\n const h = THUMB_H\n const hit = new Uint8Array(w * h)\n for (let i = 0; i < hit.length; i++) hit[i] = Math.abs(a[i]! - b[i]!) > MOVED_LUMA ? 1 : 0\n const data = new Uint8Array(w * h)\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n let v = 0\n for (let dy = -1; dy <= 1 && !v; dy++) {\n const yy = y + dy\n if (yy < 0 || yy >= h) continue\n for (let dx = -1; dx <= 1; dx++) {\n const xx = x + dx\n if (xx >= 0 && xx < w && hit[yy * w + xx]) {\n v = 1\n break\n }\n }\n }\n data[y * w + x] = v\n }\n }\n return { width: w, height: h, data }\n}\n\nexport function mergeMasks(person: MaskBytes, classes: MaskBytes, out: Uint8Array | null, moved: MaskBytes | null = null): Uint8Array {\n const { width: w, height: h } = person\n const merged = out && out.length === w * h ? out : new Uint8Array(w * h)\n const cw = classes.width\n const ch = classes.height\n const sx = cw / w\n const sy = ch / h\n const mw = moved?.width ?? 0\n const mh = moved?.height ?? 0\n for (let y = 0; y < h; y++) {\n const crow = Math.min(ch - 1, Math.floor((y + 0.5) * sy)) * cw\n const mrow = moved ? Math.min(mh - 1, Math.floor(((y + 0.5) * mh) / h)) * mw : 0\n const prow = y * w\n for (let x = 0; x < w; x++) {\n if (person.data[prow + x] !== 0) {\n merged[prow + x] = CLASS_BACKGROUND\n continue\n }\n const c = classes.data[crow + Math.min(cw - 1, Math.floor((x + 0.5) * sx))]!\n if (c === CLASS_BACKGROUND) {\n merged[prow + x] = CLASS_CLOTHES\n continue\n }\n const stale = moved !== null && (c === CLASS_BODY_SKIN || c === CLASS_OTHERS) && moved.data[mrow + Math.min(mw - 1, Math.floor(((x + 0.5) * mw) / w))] !== 0\n merged[prow + x] = stale ? CLASS_STALE_OCCLUDER : c\n }\n }\n return merged\n}\n","import { createSegmenter, type MaskBytes, type Segmenter, type SegmenterModel } from \"./segmenter\"\nimport { COVER_SIZE, FACE_FLOATS, createFaceDetector, faceBox, type Box, type FaceDetector } from \"./face\"\nimport { DetectWorker, type DetectHandlers } from \"./detect-remote\"\nimport { loadCore, splitMicros, type MediakitCore } from \"./wasm\"\nimport { GpuLostError, gpuRecord, recordLoss, rendererOf, type LossPhase } from \"./gpu-guard\"\nimport { LOAD_MS, LoadTimeout, withTimeout } from \"./mp\"\nimport { lumaThumb, mergeMasks, movedBetween, THUMB_H, THUMB_W } from \"./mask-merge\"\nimport {\n NO_EFFECTS,\n coreRecipe,\n debugCode,\n needsFace,\n needsSegmentation,\n needsSkinClasses,\n type BgFilter,\n type DebugView,\n type Effects,\n} from \"./recipe\"\nimport { assetUrl } from \"./assets\"\n\n/**\n * One mediakit pipeline: canvas plus WebGL2 plus the Go core plus the detectors, which is\n * everything needed to turn a source frame into a processed one.\n *\n * The Engine does NOT know where a frame came from or where it goes - that is the transport's\n * job (`pipeline.ts`). They are separate because three browsers need three transports but all\n * three drive this same engine.\n */\n\nexport interface FrameStats {\n /** Total time spent on one frame, in milliseconds. */\n totalMs: number\n /** How much of that was segmentation. */\n segMs: number\n /** The last landmark detection; in its worker it no longer holds up the frame. */\n faceMs: number\n /** WebGL call count - the P0.2 gate in doc/apps/mediakit/PLAN.md. */\n glCalls: number\n /** Whether this frame ran segmentation or reused the previous mask. */\n segmented: boolean\n /** The resolution ratios the governor settled on. */\n maskScale: number\n workScale: number\n /** The autoframe window: centre and zoom, in UV coordinates. */\n cropCX: number\n cropCY: number\n cropZoom: number\n /** Whether the current recipe needs a person mask. */\n needsMask: boolean\n /** Whether a face is currently being tracked. */\n faceFound: boolean\n /** Face size as a fraction of frame height. */\n faceSize: number\n /** Whether the current recipe needs face landmarks. */\n needsFace: boolean\n /** The exposure lift auto light is applying, 0 when it is off or the room is bright. */\n autoExposure: number\n /** How many faces are being tracked. */\n faces: number\n /** Frames `syncFaces` holds back right now, sized to how long landmarks take; 0 when off. */\n heldFrames: number\n /** How old the landmarks behind this frame are, from the frame they were found on; 0 without landmarks. */\n faceAgeMs: number\n /** How old the segmentation mask behind this frame is; 0 without one. */\n maskAgeMs: number\n /** Why makeup and teeth are off while the rest runs (their shader failed to link); \"\" when none. */\n effectError: string\n}\n\nconst ZERO_STATS: FrameStats = {\n totalMs: 0,\n segMs: 0,\n faceMs: 0,\n glCalls: 0,\n segmented: false,\n maskScale: 1,\n workScale: 1,\n cropCX: 0.5,\n cropCY: 0.5,\n cropZoom: 1,\n needsMask: false,\n faceFound: false,\n faceSize: 0,\n needsFace: false,\n autoExposure: 0,\n faces: 0,\n heldFrames: 0,\n faceAgeMs: 0,\n maskAgeMs: 0,\n effectError: \"\",\n}\n\nconst MAX_HOLD = 3\nconst COVER_FRAME_W = 256\nconst COVER_HOLD = 0.6\nconst COVER_MISSES = 2\nconst FOLLOW_SIDE = 384\nconst FOLLOW_MARGIN = 2.6\nconst FOLLOW_RETRY = 2\nconst FOLLOW_MIN_SIDE = 64\nconst FOLLOW_SHIFT = 0.06\nconst FOLLOW_RESIZE = 0.12\nconst FOLLOW_STALE_US = 500_000\nconst FOLLOW_KEPT_US = 1_000_000\nconst SCAN_SHARE = 0.5\nconst SCAN_STEP = 0.75\nconst FOLLOW_REFRESH = 30\nconst FOLLOW_WIDEN = 2\nconst FOLLOW_GROW = 3\nconst SAME_FACE = 0.3\nconst FACE_RESULTS_KEPT = 8\nconst THUMBS_KEPT = 12\nconst LINK_LOSS_WINDOW_MS = 3_000\nconst FACE_JUMP = 0.15\nconst CATCH_UP_EVERY_US = 1_000_000\nconst MASK_RESULTS_KEPT = 8\n\ntype MaskResult = { person: boolean; ts: number; width: number; height: number; data: Uint8Array; ms: number }\nconst DETECT_DUTY = 0.6\n\nfunction gpuName(gl: WebGL2RenderingContext): string {\n const info = gl.getExtension(\"WEBGL_debug_renderer_info\")\n const name = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? \"unknown\")\n return gl.isContextLost() ? `${name}, context lost` : name\n}\n\n// A worker has no document, so the Engine has to accept the canvas it is handed rather than\n// make one. segmenter.ts and face.ts already took this union - this is the last place that did\n// not.\nexport type EngineCanvas = HTMLCanvasElement | OffscreenCanvas\n\nfunction sourceSize(source: TexImageSource): [number, number] {\n if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight]\n if (typeof HTMLVideoElement !== \"undefined\" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight]\n const s = source as { width: number; height: number }\n return [s.width, s.height]\n}\n\nfunction tileGrid(sw: number, sh: number): { side: number; step: number; nx: number; ny: number } {\n const side = Math.max(FOLLOW_MIN_SIDE, Math.round(Math.min(sw, sh) * SCAN_SHARE))\n const step = side * SCAN_STEP\n return { side, step, nx: Math.max(1, Math.ceil((sw - side) / step) + 1), ny: Math.max(1, Math.ceil((sh - side) / step) + 1) }\n}\n\nfunction overlap(a: Box, b: Box): number {\n const w = Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0])\n const h = Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1])\n if (w <= 0 || h <= 0) return 0\n const i = w * h\n return i / (a[2] * a[3] + b[2] * b[3] - i)\n}\n\ntype FaceResult = { ts: number; n: number; lm: Float32Array; cover: Uint8Array | null; rects: Float32Array | null }\ntype RemoteKind = \"face\" | \"faceExtra\" | \"mask\" | \"person\"\n\n/** What the Engine skips on a GPU known to fail; a host on the main thread gets it from the GPU guard. */\nexport interface EngineGuard {\n noFaceColor?: boolean\n}\n\nconst FACE_COLOR_SKIPPED = \"face colour shaders skipped: linking one lost the WebGL context on this GPU before\"\n\nexport class Engine {\n private canvas: EngineCanvas\n private gl: WebGL2RenderingContext\n private core: MediakitCore\n private background: ImageBitmap | null = null\n // The path the current bitmap came from, so a recipe change that leaves the background\n // alone does not refetch and re-crop it. Without this every slider input event while an\n // image background is on costs a fetch plus two createImageBitmap calls, which is a\n // visible stutter under a dragged finger and the exact case setRecipe exists to make cheap.\n private backgroundPath: string | null = null\n /** The LUT the core holds, by path, so a slider drag does not decode it again. */\n private lutPath = \"\"\n /** The makeup texture the core holds, by path - see setRecipe. */\n private makeupPath = \"\"\n /** Whether the core holds the pink whitening table. */\n private skinLutState: \"none\" | \"loading\" | \"ready\" | \"failed\" = \"none\"\n private closed = false\n\n /**\n * The segmenter loads LAZILY - only once a recipe actually needs a person mask.\n *\n * The MediaPipe runtime is ~9 MB of wasm plus a model. Someone who only wants a brighter\n * picture has no reason to download that.\n */\n private segmenter: Segmenter | null = null\n private segmenterLoading: Promise<void> | null = null\n /** The multiclass segmenter, for recipes that tell skin from clothes (`needsSkinClasses`). */\n private classSegmenter: Segmenter | null = null\n private classLoading: Promise<void> | null = null\n /** The segmenter whose result this frame borrowed, to give it back after process(). */\n private used: Segmenter | null = null\n private programErr = \"\"\n private loadErr = \"\"\n private gpu = \"\"\n private linkSeenAt = -Infinity\n private links = 0\n private lostPhase: LossPhase | null = null\n private classFailed = false\n private readonly failed = new Set<\"face\" | \"person\" | \"segmenter\">()\n\n /**\n * The landmark detector, also lazy and independent of the segmenter.\n *\n * Its model is ~3.7 MB, fifteen times the segmentation one. Someone who only replaces\n * their background has no reason to download it, and the other way round.\n */\n private face: FaceDetector | null = null\n // Preferred over `face`: a landmarker call can take longer than a frame, and in-thread it\n // stalls the picture for that long. `face` is the fallback when no worker can be made.\n private faceRemote = false\n private faceWorkerMs = 0\n private classRemote = false\n private classMaskTex: WebGLTexture | null = null\n private classMaskFresh = false\n private classMaskTs = -1\n syncFaces = false\n renderedTs = 0\n private queue: { c: OffscreenCanvas; ts: number }[] = []\n private spare: OffscreenCanvas[] = []\n private faceExtraUp = false\n private faceExtraTried = false\n private lerpBuf: Float32Array | null = null\n private gapUs = 33_333\n private prevTs = -1\n private readonly sent = new Map<RemoteKind, { ts: number; at: number }>()\n private readonly lastSentAt = new Map<RemoteKind, number>()\n private faceLatencyMs = 0\n private readonly maskLatencyMs = new Map<RemoteKind, number>()\n private faceTs = -1\n private faceResults: FaceResult[] = []\n private coverCanvas: OffscreenCanvas | null = null\n private coverCell: OffscreenCanvas | null = null\n private coverOn = false\n private faceMisses = 0\n private coverHidden = false\n private srcW = 0\n private srcH = 0\n private coverLast: Uint8Array | null = null\n private coverShown: Uint8Array | null = null\n private coverImg: ImageData | null = null\n private readonly faceAsked = new Set<number>()\n private readonly faceCrops = new Map<number, Box>()\n private followBox: Box | null = null\n private followTs = -Infinity\n private followCrop: [number, number, number] | null = null\n private followCanvas: OffscreenCanvas | null = null\n private followRetry: [number, number, number] | null = null\n private faceSeen = false\n private followFloats = 0\n private followAll = false\n private followTurn = 0\n private followMiss = 0\n private followGrow = 0\n private boxFloats = 0\n private scanFrom = 0\n private scanTurn = 0\n private readonly probes = new Set<number>()\n private maskResults: MaskResult[] = []\n private maskUsedTs = -1\n private lastHeld: OffscreenCanvas | null = null\n private swallowed = false\n private maskWorkerMs = 0\n private readonly detects = new Map<RemoteKind, DetectWorker>()\n private personRemote = false\n private personLoading: Promise<void> | null = null\n private personMaskTex: WebGLTexture | null = null\n private personMaskFresh = false\n private personMaskTs = -1\n private personWorkerMs = 0\n private personBytes: MaskBytes | null = null\n private classBytes: MaskBytes | null = null\n private mergedBytes: Uint8Array | null = null\n private mergedTex: WebGLTexture | null = null\n private mergedFresh = false\n private mergedTs = 0\n private detectCanvas: OffscreenCanvas | null = null\n private detectCanvasTs = -1\n private thumbCanvas: OffscreenCanvas | null = null\n private readonly thumbs = new Map<number, Uint8Array>()\n // A kind whose worker failed once stays in-thread.\n private readonly inThread = new Set<RemoteKind>()\n private faceLoading: Promise<void> | null = null\n private faceCount = 1\n private caughtUpTs = -Infinity\n private maxFaces = 3\n private lmBuf: Float32Array | null = null\n\n private filter: BgFilter = { kind: \"none\" }\n private effects: Effects = NO_EFFECTS\n\n // The PREVIOUS frame's measurements, fed to the governor for the next one. The governor\n // steers on past numbers because there is no way to know in advance what a frame will cost.\n private prevTotalMs = 0\n private prevSegMs = 0\n\n last: FrameStats = { ...ZERO_STATS }\n\n private constructor(canvas: EngineCanvas, gl: WebGL2RenderingContext, core: MediakitCore) {\n this.canvas = canvas\n this.gl = gl\n this.core = core\n }\n\n /** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */\n static async create(\n width: number,\n height: number,\n filter: BgFilter,\n effects: Effects = NO_EFFECTS,\n alpha = false,\n maxFaces = 3,\n guard: EngineGuard = {},\n ): Promise<Engine> {\n const canvas = document.createElement(\"canvas\")\n canvas.width = width\n canvas.height = height\n return Engine.on(canvas, filter, effects, undefined, alpha, maxFaces, guard)\n }\n\n /**\n * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which\n * only a `cutout` background writes; it is fixed for the life of the context, so a host that\n * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the\n * landmarker looks for: below 3 it skips re-running its face detector on every call. Throws\n * GpuLostError when the context is lost building the shaders, or this GPU is remembered for it.\n */\n static async on(\n canvas: EngineCanvas,\n filter: BgFilter,\n effects: Effects = NO_EFFECTS,\n background?: ImageBitmap,\n alpha = false,\n maxFaces = 3,\n guard: EngineGuard = {},\n ): Promise<Engine> {\n const width = canvas.width\n const height = canvas.height\n\n // `premultipliedAlpha: false` because the shaders blend themselves; `alpha` off unless\n // asked because an opaque output makes the alpha channel pure bandwidth;\n // depth/stencil/antialias off because no pass uses them.\n //\n // `desynchronized` is DELIBERATELY not set. It decouples the canvas from the page's\n // paint rhythm to get pixels on screen sooner - but the destination here is\n // `new VideoFrame(canvas)`, which READS the canvas back inside the same task.\n // Decoupling at exactly that point opens the door to reading a buffer that is still\n // being drawn, and the symptom would be occasional torn frames: not reproducible, and\n // with no error anywhere.\n // Typed by hand: on the HTMLCanvasElement | OffscreenCanvas union, TS resolves the\n // getContext overload differently depending on what else it checked first.\n const gl = canvas.getContext(\"webgl2\", {\n alpha,\n premultipliedAlpha: false,\n antialias: false,\n depth: false,\n stencil: false,\n }) as WebGL2RenderingContext | null\n if (!gl) throw new Error(\"mediakit: no WebGL2 in this browser (none available, blocked, or the GPU process was reset)\")\n const gpu = rendererOf(gl)\n const known = gpuRecord(gpu)\n if (known?.init) {\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n throw new GpuLostError(\"init\", gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`)\n }\n\n // From here on a context exists, and every failure below has to give it back.\n //\n // Browsers cap how many WebGL contexts live at once, usually 8-16, and when the cap is\n // hit the OLDEST one is reclaimed - the meeting that is running, not the attempt that\n // just failed. So a caller retrying create() walks that cap and kills the call it is\n // trying to fix. Nothing reports it: the reclaimed context just stops drawing.\n let core: MediakitCore | undefined\n let engine: Engine | undefined\n try {\n core = await loadCore()\n const err = core.init(gl, width, height)\n if (err && gl.isContextLost()) {\n recordLoss(gpu, \"init\")\n throw new GpuLostError(\"init\", gpu, err)\n }\n if (err) throw new Error(`mediakit: ${err} [GPU: ${gpuName(gl)}]`)\n\n engine = new Engine(canvas, gl, core)\n engine.gpu = gpu\n if (guard.noFaceColor || known?.faceColor) core.disableFaceColor?.(FACE_COLOR_SKIPPED)\n engine.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3))\n await engine.setRecipe(filter, effects, background)\n return engine\n } catch (err) {\n // Teardown must never replace the diagnosis. Closing a half-built segmenter can\n // throw, and then the caller reads a cleanup error instead of the reason create()\n // actually failed - pointing the search at the wrong layer.\n try {\n // Once the Engine exists its own close() is the complete teardown - segmenter,\n // face detector, core and context. Before that there is only the core and the\n // context to undo, and running both paths would tear down twice.\n if (engine) engine.close()\n else {\n core?.close()\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n }\n } catch {\n // Nothing useful to do: the context is going away with the page anyway, and the\n // error below is the one worth reading.\n }\n throw err\n }\n }\n\n /** The GPU the context reported at creation, \"\" when the browser hides it. */\n get gpuName(): string {\n return this.gpu\n }\n\n get loading(): boolean {\n return this.segmenterLoading !== null || this.classLoading !== null || this.faceLoading !== null\n }\n\n /** The browser took the WebGL context away (GPU process reset or reclaimed); this Engine is done. */\n get lost(): boolean {\n return this.gl.isContextLost()\n }\n\n /**\n * When the context was lost: \"link\" within 3 s of a face colour shader starting or still linking, else \"run\";\n * null while it is not. The first read decides, and on the main thread it is remembered per GPU.\n */\n get lostDuring(): LossPhase | null {\n if (this.closed || !this.gl.isContextLost()) return null\n if (!this.lostPhase) {\n this.lostPhase = performance.now() - this.linkSeenAt < LINK_LOSS_WINDOW_MS ? \"link\" : \"run\"\n recordLoss(this.gpu, this.lostPhase)\n }\n return this.lostPhase\n }\n\n get outputCanvas(): EngineCanvas {\n return this.canvas\n }\n\n /** Draws an inner layer instead of the picture until set back to \"off\". */\n setDebug(view: DebugView): void {\n if (this.closed) return\n this.core.setDebug(debugCode(view))\n }\n\n /**\n * Change the recipe without rebuilding the pipeline, so dragging a slider does not flash.\n *\n * `background` is `filter.imagePath` already decoded, and the Engine takes ownership of it.\n * A worker needs it: there is no `Image` there, so an SVG - every background meet bundles -\n * cannot be decoded at all, and the main thread has to do it and transfer the bitmap.\n */\n async setRecipe(filter: BgFilter, effects: Effects = this.effects, background?: ImageBitmap): Promise<void> {\n if (this.closed) return\n this.filter = filter\n this.effects = effects\n\n if (filter.kind === \"image\" && (background || filter.imagePath !== this.backgroundPath)) {\n const w = this.canvas.width\n const h = this.canvas.height\n const bmp = background ? await coverCrop(background, w, h) : await loadBitmap(filter.imagePath, w, h)\n if (this.closed) {\n bmp.close()\n return\n }\n this.background?.close()\n this.background = bmp\n this.backgroundPath = filter.imagePath\n }\n\n if (effects.lut !== this.lutPath) {\n if (effects.lut) {\n // Not cover-cropped like a background: a LUT is data laid out on a fixed grid,\n // and resampling it would mix neighbouring colours into each other. No colour-space\n // conversion either: an embedded gamma or ICC profile would shift every entry.\n let bmp: ImageBitmap | null = null\n try {\n bmp = await decodeImage(effects.lut, { colorSpaceConversion: \"none\", premultiplyAlpha: \"none\" })\n } catch (e: unknown) {\n // A broken LUT must not hold back the rest of the recipe, nor be fetched again\n // on every slider event after it.\n console.error(\"mediakit: LUT failed to load\", e)\n }\n // A newer setRecipe ran during the decode and already owns the core's state;\n // applying this one now would put an older LUT and recipe back over it.\n if (this.closed || this.filter !== filter || this.effects !== effects) {\n bmp?.close()\n return\n }\n this.core.setLut(bmp)\n bmp?.close()\n } else {\n this.core.setLut(null)\n }\n this.lutPath = effects.lut\n }\n\n if (effects.whitenStyle === \"pink\" && this.skinLutState === \"none\") {\n // Not awaited: until it is in, the core whitens the natural way.\n this.skinLutState = \"loading\"\n decodeImage(assetUrl(\"whiten_pink.png\"), { colorSpaceConversion: \"none\", premultiplyAlpha: \"none\" })\n .then((bmp) => {\n if (this.closed) {\n bmp.close()\n return\n }\n this.core.setSkinLut(bmp)\n bmp.close()\n this.skinLutState = \"ready\"\n })\n .catch((err: unknown) => {\n // Not retried on every recipe change.\n console.error(\"mediakit: pink whitening table failed to load\", err)\n this.skinLutState = \"failed\"\n })\n }\n\n const makeupTexture = effects.makeupTexture ?? \"\"\n if (makeupTexture !== this.makeupPath) {\n if (makeupTexture) {\n // Decoded as it is, like a LUT.\n let bmp: ImageBitmap | null = null\n try {\n bmp = await decodeImage(makeupTexture, { premultiplyAlpha: \"none\" })\n } catch (e: unknown) {\n console.error(\"mediakit: makeup texture failed to load\", e)\n }\n if (this.closed || this.filter !== filter || this.effects !== effects) {\n bmp?.close()\n return\n }\n this.core.setMakeup(bmp)\n bmp?.close()\n } else {\n this.core.setMakeup(null)\n }\n this.makeupPath = makeupTexture\n }\n\n this.core.setRecipe(coreRecipe(filter, effects))\n this.noteLinking()\n\n // Start a detector the moment a recipe begins to need it. Not awaited: the frames in\n // the meantime pass through unprocessed, exactly like the first frames before any mask\n // exists.\n if (needsSegmentation(filter, effects) && !this.remoteMaskComing(filter, effects)) void this.ensureSegmenter()\n if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter()\n if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote()\n if (needsFace(effects)) void this.ensureFace()\n }\n\n private noteLinking(): void {\n const links = this.core.links?.() ?? 0\n if (links !== this.links || (this.core.linking?.() ?? 0) > 0) this.linkSeenAt = performance.now()\n this.links = links\n }\n\n /** A worker, or the multiclass model, will bring the mask: no in-thread person model for it. */\n private remoteMaskComing(filter: BgFilter, effects: Effects): boolean {\n if (needsSkinClasses(filter, effects) && !this.classFailed) return true\n return this.personRemoteWanted(filter, effects) && !this.inThread.has(\"person\")\n }\n\n private gaveUp(what: string, e: unknown): void {\n if (!(e instanceof LoadTimeout)) return\n this.loadErr ||= `${e.message}; ${what} stay off`\n console.warn(this.loadErr)\n }\n\n private ensureFace(): Promise<void> {\n if (this.face || this.faceRemote || this.failed.has(\"face\") || this.closed) return Promise.resolve()\n if (this.faceLoading) return this.faceLoading\n\n // The buffer first: its length is how many faces the core tracks, and the detector has to\n // be built for that many.\n const buf = this.core.faceBuffer()\n if (!buf) return Promise.resolve()\n const n = Math.min(Math.max(1, Math.floor(buf.length / FACE_FLOATS)), this.maxFaces)\n this.faceLoading = this.remote(\"face\", (d) => d.initFace(n))\n .then(() => {\n this.faceRemote = true\n this.lmBuf = buf\n this.faceCount = n\n })\n .catch((e: unknown) => {\n if (e instanceof LoadTimeout) throw e\n if (!this.inThread.has(\"face\")) console.warn(\"mediakit: no detect worker for faces, detecting in this thread\", e)\n return withTimeout(createFaceDetector(this.canvas, n), LOAD_MS, \"face detection\", (f) => f.close()).then((f) => {\n if (this.closed) {\n f.close()\n return\n }\n this.face = f\n this.lmBuf = buf\n })\n })\n .catch((e: unknown) => {\n this.failed.add(\"face\")\n this.gaveUp(\"face effects\", e)\n if (!(e instanceof LoadTimeout)) console.error(\"mediakit: face detector failed to load\", e)\n })\n .finally(() => {\n this.faceLoading = null\n })\n return this.faceLoading\n }\n\n /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */\n private personRemoteWanted(filter: BgFilter, effects: Effects): boolean {\n return filter.kind === \"none\" && needsSegmentation(filter, effects)\n }\n\n private ensurePersonRemote(): Promise<void> {\n if (this.personRemote || this.failed.has(\"person\") || this.closed) return Promise.resolve()\n this.personLoading ??= this.remote(\"person\", (d) => d.initMask(\"person\"))\n .then(() => {\n this.personRemote = true\n })\n .catch((e: unknown) => {\n if (!(e instanceof LoadTimeout)) return\n this.failed.add(\"person\")\n this.gaveUp(\"background effects\", e)\n })\n .finally(() => {\n this.personLoading = null\n })\n return this.personLoading\n }\n\n private async remote(kind: RemoteKind, init: (d: DetectWorker) => Promise<void>): Promise<void> {\n if (this.inThread.has(kind) || typeof Worker === \"undefined\" || typeof VideoFrame === \"undefined\") {\n this.inThread.add(kind)\n throw new Error(\"in-thread\")\n }\n let detect = this.detects.get(kind)\n if (!detect) {\n detect = new DetectWorker(this.detectHandlers(kind))\n this.detects.set(kind, detect)\n }\n try {\n await init(detect)\n } catch (e) {\n if (e instanceof LoadTimeout) {\n detect.close()\n this.detects.delete(kind)\n } else this.inThread.add(kind)\n throw e\n }\n if (this.closed) throw new Error(\"closed\")\n }\n\n private detectHandlers(key: RemoteKind): DetectHandlers {\n return {\n face: (tsUs, found, lm, ms, foundCover, foundRects) => {\n if (this.closed || !this.lmBuf || tsUs > this.prevTs) return\n this.faceWorkerMs = ms\n this.uncrop(tsUs, found, lm, foundRects)\n const { n, cover, rects } = this.dedupe(found, lm, foundCover, foundRects)\n this.follow(tsUs, n, lm, this.probes.delete(tsUs))\n if (this.syncing()) {\n this.faceResults.push({ ts: tsUs, n, lm: lm.slice(), cover, rects })\n if (this.faceResults.length > FACE_RESULTS_KEPT) this.faceResults.shift()\n } else this.applyFace(tsUs, n, lm, cover, rects)\n const took = this.took(key === \"faceExtra\" ? \"faceExtra\" : \"face\", tsUs)\n if (took !== null) this.faceLatencyMs = this.faceLatencyMs ? this.faceLatencyMs + (took - this.faceLatencyMs) * 0.2 : took\n },\n mask: (tsUs, width, height, data, ms) => {\n if (this.closed) return\n const took = this.took(key, tsUs)\n if (took !== null) {\n const was = this.maskLatencyMs.get(key)\n this.maskLatencyMs.set(key, was ? was + (took - was) * 0.2 : took)\n }\n const r = { person: key === \"person\", ts: tsUs, width, height, data, ms }\n if (!this.syncing()) {\n this.applyMask(r)\n return\n }\n this.maskResults.push(r)\n if (this.maskResults.length > MASK_RESULTS_KEPT) this.maskResults.shift()\n },\n failed: (k, reason) => {\n if (key === \"faceExtra\") {\n this.faceExtraUp = false\n this.detects.get(key)?.close()\n this.detects.delete(key)\n return\n }\n console.warn(`mediakit: ${key} detection moves into this thread:`, reason)\n this.inThread.add(key)\n if (key === \"person\") {\n this.personRemote = false\n } else if (k === \"face\") {\n this.faceRemote = false\n if (this.coverOn) this.core.setFaceCover(null)\n this.coverOn = false\n this.coverShown = null\n void this.ensureFace()\n } else {\n this.classRemote = false\n void this.ensureClassSegmenter()\n }\n },\n }\n }\n\n private noteThumb(timestampUs: number): void {\n if (this.thumbs.has(timestampUs) || !this.detectCanvas || this.detectCanvasTs !== timestampUs) return\n this.thumbCanvas ??= new OffscreenCanvas(THUMB_W, THUMB_H)\n const ctx = this.thumbCanvas.getContext(\"2d\", { willReadFrequently: true })!\n ctx.drawImage(this.detectCanvas, 0, 0, THUMB_W, THUMB_H)\n this.thumbs.set(timestampUs, lumaThumb(ctx.getImageData(0, 0, THUMB_W, THUMB_H).data))\n if (this.thumbs.size > THUMBS_KEPT) this.thumbs.delete(this.thumbs.keys().next().value!)\n }\n\n private merge(tsUs: number): void {\n if (!this.personBytes || !this.classBytes || !needsSkinClasses(this.filter, this.effects)) return\n const then = this.thumbs.get(this.classMaskTs)\n const now = this.thumbs.get(this.personMaskTs)\n const moved = then && now && this.classMaskTs !== this.personMaskTs ? movedBetween(then, now) : null\n this.mergedBytes = mergeMasks(this.personBytes, this.classBytes, this.mergedBytes, moved)\n this.mergedTex = this.uploadMaskBytes(this.mergedTex, this.personBytes.width, this.personBytes.height, this.mergedBytes)\n this.mergedFresh = true\n this.mergedTs = tsUs\n }\n\n private uploadClassMask(width: number, height: number, data: Uint8Array): void {\n this.classMaskTex = this.uploadMaskBytes(this.classMaskTex, width, height, data)\n this.classMaskFresh = true\n }\n\n // Category indices: NEAREST, since a blend of two indices is a third, wrong category.\n private uploadMaskBytes(tex: WebGLTexture | null, width: number, height: number, data: Uint8Array): WebGLTexture | null {\n const gl = this.gl\n if (!tex) {\n tex = gl.createTexture()\n gl.bindTexture(gl.TEXTURE_2D, tex)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)\n }\n gl.bindTexture(gl.TEXTURE_2D, tex)\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data)\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4)\n gl.bindTexture(gl.TEXTURE_2D, null)\n return tex\n }\n\n /**\n * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow\n * detection drains Chrome's few capture buffers and throttles the camera itself.\n */\n private requestRemote(want: RemoteKind, source: TexImageSource, timestampUs: number): void {\n const lockstep = want === \"face\" && this.syncing()\n const kind = lockstep ? this.freeFaceWorker() : want\n if (!kind) return\n const detect = this.detects.get(kind)\n if (!detect?.accepts(kind === \"face\" || kind === \"faceExtra\" ? \"face\" : \"mask\")) return\n if (!lockstep && !this.dutyAllows(kind)) return\n let frame: VideoFrame | null = null\n let followed: OffscreenCanvas | null = null\n let scanned: OffscreenCanvas | null = null\n try {\n const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas\n if (copyable) {\n this.srcW = source instanceof VideoFrame ? source.displayWidth : source.width\n this.srcH = source instanceof VideoFrame ? source.displayHeight : source.height\n }\n if (copyable && (kind === \"face\" || kind === \"faceExtra\")) {\n followed = this.followCopy(source, timestampUs)\n if (!followed) scanned = this.scanCopy(source, timestampUs)\n }\n frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(source, timestampUs) : (source as CanvasImageSource)), {\n timestamp: timestampUs,\n })\n } catch {\n // ImageData has no VideoFrame form: this frame goes without.\n }\n if (frame && detect.request(kind === \"face\" || kind === \"faceExtra\" ? \"face\" : \"mask\", frame, timestampUs, this.effects.occluders ?? false, followed ? this.followRetry : null)) {\n const now = performance.now()\n this.sent.set(kind, { ts: timestampUs, at: now })\n this.lastSentAt.set(kind, now)\n if (lockstep) this.faceAsked.add(timestampUs)\n if (kind !== \"face\" && kind !== \"faceExtra\" && this.remoteMaskKind() === \"merged\") this.noteThumb(timestampUs)\n } else if (followed || scanned) this.faceCrops.delete(timestampUs)\n }\n\n private followCopy(source: VideoFrame | OffscreenCanvas, timestampUs: number): OffscreenCanvas | null {\n const box = this.followBox\n if (!box || timestampUs - this.followTs > FOLLOW_STALE_US) return null\n const sw = source instanceof VideoFrame ? source.displayWidth : source.width\n const sh = source instanceof VideoFrame ? source.displayHeight : source.height\n const want = Math.max(FOLLOW_MIN_SIDE, FOLLOW_MARGIN * (1 + this.followMiss) * Math.max(box[2] * sw, box[3] * sh))\n if (want > Math.min(sw, sh) && this.followFloats > FACE_FLOATS) return null\n if (!this.followAll && this.followTurn++ % FOLLOW_REFRESH === FOLLOW_REFRESH - 1) {\n this.probes.add(timestampUs)\n return null\n }\n let side = Math.round(Math.min(sw, sh, want))\n let x = Math.round(Math.min(sw - side, Math.max(0, (box[0] + box[2] / 2) * sw - side / 2)))\n let y = Math.round(Math.min(sh - side, Math.max(0, (box[1] + box[3] / 2) * sh - side / 2)))\n const kept = this.followCrop\n if (\n kept &&\n kept[0] + kept[2] <= sw &&\n kept[1] + kept[2] <= sh &&\n Math.abs(kept[2] - side) < FOLLOW_RESIZE * side &&\n Math.abs(kept[0] - x) < FOLLOW_SHIFT * side &&\n Math.abs(kept[1] - y) < FOLLOW_SHIFT * side\n ) {\n ;[x, y, side] = kept\n } else this.followCrop = [x, y, side]\n this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE)\n this.followCanvas.getContext(\"2d\")!.drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE)\n const tight = Math.min(side, Math.max(FOLLOW_MIN_SIDE, FOLLOW_RETRY * Math.max(box[2] * sw, box[3] * sh)))\n this.followRetry = [((box[0] + box[2] / 2) * sw - x) / side, ((box[1] + box[3] / 2) * sh - y) / side, tight / side]\n this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh])\n return this.followCanvas\n }\n\n private scanCopy(source: VideoFrame | OffscreenCanvas, timestampUs: number): OffscreenCanvas | null {\n if (this.faceSeen) return null\n const turn = this.scanTurn++\n if (turn % 2 === 0) return null\n const sw = source instanceof VideoFrame ? source.displayWidth : source.width\n const sh = source instanceof VideoFrame ? source.displayHeight : source.height\n const { side, step, nx, ny } = tileGrid(sw, sh)\n const at = (this.scanFrom + (turn >> 1)) % (nx * ny)\n const x = Math.max(0, Math.min(sw - side, Math.round((at % nx) * step)))\n const y = Math.max(0, Math.min(sh - side, Math.round(Math.floor(at / nx) * step)))\n this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE)\n this.followCanvas.getContext(\"2d\")!.drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE)\n this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh])\n this.probes.add(timestampUs)\n return this.followCanvas\n }\n\n private scanTile(cx: number, cy: number): number {\n const sw = this.srcW || this.canvas.width\n const sh = this.srcH || this.canvas.height\n const { side, step, nx, ny } = tileGrid(sw, sh)\n const ix = Math.min(nx - 1, Math.max(0, Math.round((cx * sw - side / 2) / step)))\n const iy = Math.min(ny - 1, Math.max(0, Math.round((cy * sh - side / 2) / step)))\n return iy * nx + ix\n }\n\n private uncrop(tsUs: number, n: number, lm: Float32Array, rects: Float32Array | null): void {\n const crop = this.faceCrops.get(tsUs)\n for (const ts of this.faceCrops.keys()) if (ts === tsUs || ts < tsUs - FOLLOW_KEPT_US) this.faceCrops.delete(ts)\n if (!crop) return\n for (let i = 0; i < n; i += 3) {\n lm[i] = crop[0] + lm[i]! * crop[2]\n lm[i + 1] = crop[1] + lm[i + 1]! * crop[3]\n lm[i + 2] = lm[i + 2]! * crop[2]\n }\n for (let i = 0; rects && i < rects.length; i += 3) {\n rects[i] = crop[0] + rects[i]! * crop[2]\n rects[i + 1] = crop[1] + rects[i + 1]! * crop[3]\n rects[i + 2] = rects[i + 2]! * crop[2]\n }\n }\n\n private dedupe(n: number, lm: Float32Array, cover: Uint8Array | null, rects: Float32Array | null): { n: number; cover: Uint8Array | null; rects: Float32Array | null } {\n const faces = n / FACE_FLOATS\n if (faces < 2) return { n, cover, rects }\n const boxes = Array.from({ length: faces }, (_, f) => faceBox(lm, f * FACE_FLOATS))\n const ref = this.followBox\n const score = (b: Box) => (ref ? overlap(b, ref) : 0) + b[2] * b[3] * 1e-3\n const keep = boxes.map(() => true)\n for (let a = 0; a < faces; a++) {\n for (let b = a + 1; b < faces; b++) {\n if (!keep[a] || !keep[b] || overlap(boxes[a]!, boxes[b]!) <= SAME_FACE) continue\n keep[score(boxes[a]!) >= score(boxes[b]!) ? b : a] = false\n }\n }\n if (keep.every(Boolean)) return { n, cover, rects }\n const cells = COVER_SIZE * COVER_SIZE\n const outCover = cover ? new Uint8Array(cover.length) : null\n const outRects = rects ? new Float32Array(rects.length) : null\n let k = 0\n for (let f = 0; f < faces; f++) {\n if (!keep[f]) continue\n if (k !== f) lm.copyWithin(k * FACE_FLOATS, f * FACE_FLOATS, (f + 1) * FACE_FLOATS)\n if (cover && outCover) outCover.set(cover.subarray(f * cells, (f + 1) * cells), k * cells)\n if (rects && outRects) outRects.set(rects.subarray(f * 3, f * 3 + 3), k * 3)\n k++\n }\n return { n: k * FACE_FLOATS, cover: outCover ? outCover.slice(0, k * cells) : null, rects: outRects ? outRects.slice(0, k * 3) : null }\n }\n\n private follow(tsUs: number, n: number, lm: Float32Array, probe: boolean): void {\n for (const ts of this.probes) if (ts < tsUs - FOLLOW_KEPT_US) this.probes.delete(ts)\n if (tsUs <= this.followTs || (probe && (n === 0 || n < this.followFloats))) return\n this.followTs = tsUs\n this.faceSeen = n > 0\n if (n === 0) {\n this.followGrow = 0\n this.followFloats = 0\n this.followAll = false\n const box = this.followBox\n if (box && this.followMiss < FOLLOW_WIDEN) {\n this.followMiss++\n return\n }\n this.followMiss = 0\n if (box) this.scanFrom = this.scanTile(box[0] + box[2] / 2, box[1] + box[3] / 2)\n this.scanTurn = 1\n this.followBox = null\n this.followCrop = null\n this.boxFloats = 0\n return\n }\n this.followMiss = 0\n const old = this.followBox\n const grow = old !== null && this.boxFloats > 0 && n > this.boxFloats && !probe\n this.followGrow = grow ? this.followGrow + 1 : 0\n const take = grow && this.followGrow < FOLLOW_GROW ? this.boxFloats : n\n const boxes: Box[] = []\n for (let f = 0; f < n; f += FACE_FLOATS) boxes.push(faceBox(lm, f))\n if (take < n && old) boxes.sort((a, b) => overlap(b, old) - overlap(a, old))\n const kept = boxes.slice(0, take / FACE_FLOATS)\n const x0 = Math.min(...kept.map((b) => b[0]))\n const y0 = Math.min(...kept.map((b) => b[1]))\n const x1 = Math.max(...kept.map((b) => b[0] + b[2]))\n const y1 = Math.max(...kept.map((b) => b[1] + b[3]))\n this.followBox = [x0, y0, x1 - x0, y1 - y0]\n this.boxFloats = take\n this.followFloats = take\n this.followAll = take >= this.faceCount * FACE_FLOATS\n }\n\n private freeFaceWorker(): RemoteKind | null {\n if (this.detects.get(\"face\")?.accepts(\"face\")) return \"face\"\n if (this.faceExtraUp && this.detects.get(\"faceExtra\")?.accepts(\"face\")) return \"faceExtra\"\n return null\n }\n\n private ensureFaceExtra(): void {\n if (this.faceExtraTried || this.closed) return\n this.faceExtraTried = true\n const n = this.faceCount\n this.remote(\"faceExtra\", (d) => d.initFace(n))\n .then(() => {\n this.faceExtraUp = true\n })\n .catch(() => {\n this.detects.get(\"faceExtra\")?.close()\n this.detects.delete(\"faceExtra\")\n })\n }\n\n /** Face and mask asked on the same frame share one draw. */\n private detectCopy(source: VideoFrame | OffscreenCanvas, timestampUs: number): OffscreenCanvas {\n const sw = source instanceof VideoFrame ? source.displayWidth : source.width\n const sh = source instanceof VideoFrame ? source.displayHeight : source.height\n // Same long edge as MAX_EDGE in detect-worker/entry.ts.\n const s = Math.min(1, 512 / Math.max(sw, sh))\n const w = Math.max(1, Math.round(sw * s))\n const h = Math.max(1, Math.round(sh * s))\n if (!this.detectCanvas || this.detectCanvas.width !== w || this.detectCanvas.height !== h) {\n this.detectCanvas = new OffscreenCanvas(w, h)\n this.detectCanvasTs = -1\n }\n if (this.detectCanvasTs !== timestampUs) {\n this.detectCanvas.getContext(\"2d\")!.drawImage(source, 0, 0, w, h)\n this.detectCanvasTs = timestampUs\n }\n return this.detectCanvas\n }\n\n private ensureClassSegmenter(): Promise<void> {\n if (this.classSegmenter || this.classRemote || this.classFailed || this.closed) return Promise.resolve()\n if (this.classLoading) return this.classLoading\n this.classLoading = this.remote(\"mask\", (d) => d.initMask(\"classes\"))\n .then(() => {\n this.classRemote = true\n })\n .catch((e: unknown) => {\n if (e instanceof LoadTimeout) throw e\n return withTimeout(createSegmenter(this.canvas, \"classes\" satisfies SegmenterModel), LOAD_MS, \"skin segmentation\", (s) => s.close()).then((s) => {\n if (this.closed) {\n s.close()\n return\n }\n this.classSegmenter = s\n })\n })\n .catch((e: unknown) => {\n // Not fatal: the person segmenter and the face-held fallback carry on.\n this.classFailed = true\n if (!(e instanceof LoadTimeout)) console.error(\"mediakit: multiclass segmenter failed to load\", e)\n else console.warn(`${e.message}; the person model stands in`)\n if (needsSegmentation(this.filter, this.effects)) void this.ensureSegmenter()\n })\n .finally(() => {\n this.classLoading = null\n })\n return this.classLoading\n }\n\n private ensureSegmenter(): Promise<void> {\n if (this.segmenter || this.failed.has(\"segmenter\") || this.closed) return Promise.resolve()\n if (this.segmenterLoading) return this.segmenterLoading\n\n this.segmenterLoading = withTimeout(createSegmenter(this.canvas), LOAD_MS, \"person segmentation\", (s) => s.close())\n .then((s) => {\n if (this.closed) {\n s.close()\n return\n }\n this.segmenter = s\n })\n .catch((e: unknown) => {\n this.failed.add(\"segmenter\")\n this.gaveUp(\"background and skin effects\", e)\n if (!(e instanceof LoadTimeout)) console.error(\"mediakit: segmenter failed to load\", e)\n })\n .finally(() => {\n this.segmenterLoading = null\n })\n return this.segmenterLoading\n }\n\n /**\n * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask\n * yet, the segmenter is still loading, or the recipe is inactive.\n *\n * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────\n * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does\n * MediaPipe. That is what lets the fallback transport (Firefox, and Safari before the\n * worker path) work with NO WebCodecs at all: it passes the `<video>` element straight in.\n *\n * LiveKit's reference implementation requires a `VideoFrame` even on its fallback path, so\n * it constructs one only to destroy it again.\n */\n render(source: TexImageSource, timestampUs: number): boolean {\n if (this.closed || this.lostDuring) return false\n if (this.lastHeld) this.spare.push(this.lastHeld)\n this.lastHeld = null\n this.swallowed = false\n if (this.prevTs >= 0 && timestampUs > this.prevTs) {\n this.gapUs += (Math.min(timestampUs - this.prevTs, 200_000) - this.gapUs) * 0.1\n }\n if (timestampUs < this.prevTs) {\n this.faceResults = []\n this.maskResults = []\n this.faceAsked.clear()\n this.faceCrops.clear()\n this.followBox = null\n this.followCrop = null\n this.followTs = -Infinity\n this.faceSeen = false\n this.followFloats = 0\n this.followAll = false\n this.followTurn = 0\n this.followMiss = 0\n this.followGrow = 0\n this.boxFloats = 0\n this.scanFrom = 0\n this.scanTurn = 0\n this.probes.clear()\n this.caughtUpTs = -Infinity\n this.thumbs.clear()\n }\n this.prevTs = timestampUs\n if (!this.syncing() || (typeof ImageData !== \"undefined\" && source instanceof ImageData)) {\n this.releaseHeld()\n this.renderedTs = timestampUs\n return this.draw(source, timestampUs, false)\n }\n this.ensureFaceExtra()\n this.requestRemote(\"face\", source, timestampUs)\n const remoteMask = this.remoteMaskKind()\n if (remoteMask === \"merged\") {\n this.requestRemote(\"person\", source, timestampUs)\n this.requestRemote(\"mask\", source, timestampUs)\n } else if (remoteMask) this.requestRemote(remoteMask, source, timestampUs)\n this.queue.push({ c: this.hold(source), ts: timestampUs })\n while (this.queue.length > MAX_HOLD + 1) this.faceAsked.delete(this.spareFront())\n if (this.queue.length <= MAX_HOLD && !this.faceReady(this.queue[0]!.ts)) {\n this.swallowed = true\n return false\n }\n if (this.queue.length > 2 && this.faceReady(this.queue[1]!.ts) && timestampUs - this.caughtUpTs >= CATCH_UP_EVERY_US) {\n this.caughtUpTs = timestampUs\n this.faceAsked.delete(this.spareFront())\n }\n const front = this.queue.shift()!\n this.faceAsked.delete(front.ts)\n this.faceFor(front.ts)\n this.masksFor(front.ts)\n this.lastHeld = front.c\n this.renderedTs = front.ts\n return this.draw(front.c, front.ts, true)\n }\n\n private remoteMaskKind(): \"person\" | \"mask\" | \"merged\" | null {\n const person = this.personRemote && this.personRemoteWanted(this.filter, this.effects)\n if (!needsSkinClasses(this.filter, this.effects)) return person ? \"person\" : null\n if (this.classRemote) return person ? \"merged\" : \"mask\"\n return person && !this.inThread.has(\"mask\") ? \"person\" : null\n }\n\n private spareFront(): number {\n const h = this.queue.shift()!\n this.spare.push(h.c)\n return h.ts\n }\n\n private applyMask(r: MaskResult): void {\n if (r.person) {\n this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, r.width, r.height, r.data)\n this.personMaskFresh = true\n this.personMaskTs = r.ts\n this.personWorkerMs = r.ms\n this.personBytes = { width: r.width, height: r.height, data: r.data }\n this.merge(r.ts)\n return\n }\n this.uploadClassMask(r.width, r.height, r.data)\n this.classMaskTs = r.ts\n this.maskWorkerMs = r.ms\n this.classBytes = { width: r.width, height: r.height, data: r.data }\n this.merge(this.personMaskTs)\n }\n\n private masksFor(tsUs: number): void {\n for (const person of [false, true]) {\n let pick: MaskResult | null = null\n for (const r of this.maskResults) if (r.person === person && (!pick || Math.abs(r.ts - tsUs) < Math.abs(pick.ts - tsUs))) pick = r\n if (!pick) continue\n const chosen = pick\n this.maskResults = this.maskResults.filter((r) => r.person !== person || r.ts >= chosen.ts)\n if (chosen.ts !== (person ? this.personMaskTs : this.classMaskTs)) this.applyMask(chosen)\n }\n }\n\n private faceReady(tsUs: number): boolean {\n const asked = this.faceAsked.has(tsUs)\n return this.faceResults.some((r) => (asked ? r.ts === tsUs : r.ts > tsUs))\n }\n\n private dutyAllows(kind: RemoteKind): boolean {\n const took = kind === \"face\" ? this.faceLatencyMs : (this.maskLatencyMs.get(kind) ?? 0)\n if (took * 1000 < this.gapUs) return true\n const last = this.lastSentAt.get(kind)\n return last === undefined || performance.now() - last >= took / DETECT_DUTY\n }\n\n private took(kind: RemoteKind, tsUs: number): number | null {\n const s = this.sent.get(kind)\n if (s?.ts !== tsUs) return null\n this.sent.delete(kind)\n return performance.now() - s.at\n }\n\n private applyFace(tsUs: number, n: number, lm: Float32Array, cover: Uint8Array | null, rects: Float32Array | null): void {\n this.faceMisses = n === 0 ? this.faceMisses + 1 : 0\n if (n > 0) this.showCover(cover, rects)\n else if (this.faceMisses >= COVER_MISSES) this.hideCover()\n this.lmBuf!.set(lm)\n const [lo, hi] = splitMicros(tsUs)\n this.core.setFace(lo, hi, n)\n this.faceTs = tsUs\n }\n\n private faceFor(tsUs: number): void {\n this.faceResults.sort((a, b) => a.ts - b.ts)\n let pick = -1\n for (let i = 0; i < this.faceResults.length; i++) if (this.faceResults[i]!.ts <= tsUs) pick = i\n if (pick < 0) return\n const r = this.faceResults[pick]!\n const next = this.faceResults[pick + 1]\n this.faceResults.splice(0, pick)\n if (r.ts === tsUs || !next || !this.sameFaces(r, next)) {\n if (r.ts !== this.faceTs) this.applyFace(r.ts, r.n, r.lm, r.cover, r.rects)\n return\n }\n const a = (tsUs - r.ts) / (next.ts - r.ts)\n if (!this.lerpBuf || this.lerpBuf.length !== r.lm.length) this.lerpBuf = new Float32Array(r.lm.length)\n for (let i = 0; i < r.n; i++) this.lerpBuf[i] = r.lm[i]! + (next.lm[i]! - r.lm[i]!) * a\n const near = a < 0.5 ? r : next\n this.applyFace(tsUs, r.n, this.lerpBuf, near.cover, near.rects)\n }\n\n private hideCover(): void {\n if (!this.coverOn || !this.coverCanvas || this.coverHidden) return\n const ctx = this.coverCanvas.getContext(\"2d\")!\n ctx.fillStyle = \"#000\"\n ctx.fillRect(0, 0, this.coverCanvas.width, this.coverCanvas.height)\n this.core.setFaceCover(this.coverCanvas)\n this.coverShown = null\n this.coverHidden = true\n }\n\n private showCover(cover: Uint8Array | null, rects: Float32Array | null): void {\n this.coverHidden = false\n if (!cover || !rects || !(this.effects.occluders ?? false)) {\n if (this.coverOn) this.core.setFaceCover(null)\n this.coverOn = false\n this.coverShown = null\n return\n }\n if (cover === this.coverShown && this.coverOn) return\n const w = COVER_FRAME_W\n const h = Math.max(1, Math.round((w * (this.srcH || this.canvas.height)) / (this.srcW || this.canvas.width)))\n if (!this.coverCanvas || this.coverCanvas.height !== h) this.coverCanvas = new OffscreenCanvas(w, h)\n this.coverCell ??= new OffscreenCanvas(COVER_SIZE, COVER_SIZE)\n const ctx = this.coverCanvas.getContext(\"2d\")!\n const cell = this.coverCell.getContext(\"2d\")!\n ctx.fillStyle = \"#fff\"\n ctx.fillRect(0, 0, w, h)\n this.coverImg ??= cell.createImageData(COVER_SIZE, COVER_SIZE)\n const img = this.coverImg\n const cells = COVER_SIZE * COVER_SIZE\n const held = this.coverLast && this.coverLast !== cover && this.coverLast.length === cover.length ? this.coverLast : null\n for (let f = 0; f * 3 < rects.length; f++) {\n for (let i = 0; i < cells; i++) {\n const now = cover[f * cells + i]!\n const v = held ? Math.min(now, now * (1 - COVER_HOLD) + held[f * cells + i]! * COVER_HOLD) : now\n img.data[i * 4] = v\n img.data[i * 4 + 1] = v\n img.data[i * 4 + 2] = v\n img.data[i * 4 + 3] = 255\n }\n cell.putImageData(img, 0, 0)\n const side = rects[f * 3 + 2]! * w\n ctx.drawImage(this.coverCell, rects[f * 3]! * w - side / 2, rects[f * 3 + 1]! * h - side / 2, side, side)\n }\n this.core.setFaceCover(this.coverCanvas)\n this.coverOn = true\n this.coverLast = cover\n this.coverShown = cover\n }\n\n private sameFaces(a: { n: number; lm: Float32Array }, b: { n: number; lm: Float32Array }): boolean {\n if (a.n === 0 || a.n !== b.n) return false\n for (let k = 0; k < a.n; k += FACE_FLOATS) {\n const nose = k + 3\n if (Math.abs(a.lm[nose]! - b.lm[nose]!) > FACE_JUMP || Math.abs(a.lm[nose + 1]! - b.lm[nose + 1]!) > FACE_JUMP) return false\n }\n return true\n }\n\n private releaseHeld(): void {\n for (const h of this.queue) this.spare.push(h.c)\n this.queue = []\n }\n\n dropped(): boolean {\n return this.swallowed\n }\n\n passthrough(): VideoFrame | null {\n return this.lastHeld ? new VideoFrame(this.lastHeld, { timestamp: this.renderedTs }) : null\n }\n\n private syncing(): boolean {\n return this.syncFaces && this.faceRemote && needsFace(this.effects)\n }\n\n private hold(source: TexImageSource): OffscreenCanvas {\n const [w, h] = sourceSize(source)\n let c = this.spare.pop()\n while (c && (c.width !== w || c.height !== h)) c = this.spare.pop()\n c ??= new OffscreenCanvas(w, h)\n c.getContext(\"2d\")!.drawImage(source as CanvasImageSource, 0, 0, w, h)\n return c\n }\n\n private draw(source: TexImageSource, timestampUs: number, faceDone: boolean): boolean {\n const t0 = performance.now()\n const [lo, hi] = splitMicros(timestampUs)\n const needSeg = this.core.decide(lo, hi, this.prevTotalMs, this.prevSegMs) === 1\n\n let mask: WebGLTexture | null = null\n let maskKind = 0\n let maskTs = timestampUs\n let segMs = 0\n let faceMs = 0\n this.used = null\n let served = false\n const remoteMask = this.remoteMaskKind()\n if (remoteMask === \"merged\") {\n if (!faceDone) {\n this.requestRemote(\"person\", source, timestampUs)\n this.requestRemote(\"mask\", source, timestampUs)\n }\n const tex = this.mergedTex ?? this.personMaskTex\n if (tex) {\n served = true\n if (this.mergedTex ? this.mergedFresh : this.personMaskFresh) {\n this.mergedFresh = false\n this.personMaskFresh = false\n mask = tex\n maskKind = this.mergedTex ? 1 : 0\n maskTs = this.mergedTex ? this.mergedTs : this.personMaskTs\n segMs = this.personWorkerMs\n }\n }\n } else if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs)\n if (remoteMask === \"person\") {\n if (this.personMaskTex) {\n served = true\n if (this.personMaskFresh) {\n this.personMaskFresh = false\n mask = this.personMaskTex\n maskTs = this.personMaskTs\n segMs = this.personWorkerMs\n }\n }\n }\n if (remoteMask === \"mask\") {\n if (this.classMaskTex) {\n served = true\n if (this.classMaskFresh) {\n this.classMaskFresh = false\n mask = this.classMaskTex\n maskKind = 1\n maskTs = this.classMaskTs\n segMs = this.maskWorkerMs\n }\n }\n }\n if (needSeg && !served) {\n // The multiclass model when the recipe wants it and it is up.\n const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects)\n const seg = classes ? this.classSegmenter : this.segmenter\n if (!seg) {\n // The recipe wants a mask but the segmenter is not up yet. Kick off the load\n // and let this frame through - Go handles the no-mask case itself.\n if (!this.remoteMaskComing(this.filter, this.effects)) void this.ensureSegmenter()\n } else {\n const s0 = performance.now()\n // MediaPipe counts in milliseconds, not microseconds.\n mask = seg.segment(source as VideoFrame, timestampUs / 1000)\n segMs = performance.now() - s0\n this.used = seg\n maskKind = classes ? 1 : 0\n }\n }\n\n // Face detection is STAGGERED against segmentation - the core decides, this only obeys.\n if (faceDone) {\n faceMs = this.faceWorkerMs\n } else if (this.faceRemote && needsFace(this.effects)) {\n this.requestRemote(\"face\", source, timestampUs)\n faceMs = this.faceWorkerMs\n } else if (this.core.decideFace() === 1) {\n if (this.faceRemote) {\n faceMs = this.faceWorkerMs\n } else if (!this.face) {\n void this.ensureFace()\n } else if (this.lmBuf) {\n const f0 = performance.now()\n const n = this.face.detect(source, timestampUs / 1000, this.lmBuf)\n faceMs = performance.now() - f0\n this.core.setFace(lo, hi, n)\n this.faceTs = timestampUs\n }\n }\n\n if (mask) this.maskUsedTs = maskTs\n const [maskLo, maskHi] = splitMicros(maskTs)\n const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi)\n\n // Give the mask buffer back right AFTER process, not before - see Segmenter.release.\n if (mask) this.used?.release()\n this.used = null\n this.noteLinking()\n\n if (!this.programErr) {\n const err = this.core.programError?.() ?? \"\"\n if (err) {\n this.programErr = `mediakit: ${err}; makeup and teeth stay off, the rest runs [GPU: ${gpuName(this.gl)}]`\n console.warn(this.programErr)\n }\n }\n\n this.prevSegMs = segMs\n this.prevTotalMs = performance.now() - t0\n\n const s = this.core.stats()\n this.last = {\n totalMs: this.prevTotalMs,\n segMs,\n faceMs,\n glCalls,\n segmented: needSeg && mask !== null,\n maskScale: s ? s[1] : 1,\n workScale: s ? s[2] : 1,\n cropCX: s ? s[4] : 0.5,\n cropCY: s ? s[5] : 0.5,\n cropZoom: s ? s[6] : 1,\n needsMask: s ? s[7] > 0.5 : false,\n faceFound: s ? s[8] > 0.5 : false,\n faceSize: s ? s[9] : 0,\n needsFace: s ? s[10] > 0.5 : false,\n autoExposure: s ? s[11] : 0,\n faces: s ? s[12] : 0,\n heldFrames: faceDone ? this.queue.length : 0,\n faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1000 : 0,\n maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1000 : 0,\n effectError: this.programErr || this.loadErr,\n }\n\n return glCalls > 0\n }\n\n /**\n * Wrap the output canvas as a new VideoFrame.\n *\n * The timestamp is the SOURCE frame's, carried through unchanged. It is not rebuilt from\n * ticks: whole microseconds cannot represent a frame boundary at 30fps (a frame is\n * 33333.33 us), so every tick-to-microsecond round trip loses information. Ticks are only\n * for the governor and the graph to decide with. See the ToMicros comment in\n * `core/clock.go`.\n */\n capture(timestampUs: number, keepAlpha = false): VideoFrame {\n return new VideoFrame(this.canvas, { timestamp: timestampUs, alpha: keepAlpha ? \"keep\" : \"discard\" })\n }\n\n close(): void {\n if (this.closed) return\n this.closed = true\n this.segmenter?.close()\n this.segmenter = null\n this.classSegmenter?.close()\n this.classSegmenter = null\n this.face?.close()\n this.face = null\n for (const detect of this.detects.values()) detect.close()\n this.detects.clear()\n this.faceRemote = false\n this.classRemote = false\n if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex)\n if (this.personMaskTex) this.gl.deleteTexture(this.personMaskTex)\n this.personMaskTex = null\n if (this.mergedTex) this.gl.deleteTexture(this.mergedTex)\n this.mergedTex = null\n this.personBytes = null\n this.classBytes = null\n this.mergedBytes = null\n this.personRemote = false\n this.classMaskTex = null\n this.lmBuf = null\n this.queue = []\n this.spare = []\n this.lastHeld = null\n this.core.close()\n this.background?.close()\n this.background = null\n this.backgroundPath = null\n this.lutPath = \"\"\n this.makeupPath = \"\"\n // Release the context now rather than wait for GC: browsers cap how many live WebGL\n // contexts there are (usually 8-16), and a long meeting can rebuild the pipeline\n // several times. At the cap the OLDEST context is reclaimed - the running one dies,\n // not the new one.\n this.gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n }\n}\n\n/**\n * Decode a background image into an ImageBitmap.\n *\n * Through an `<img>` and not `createImageBitmap(blob)`, because Chrome CANNOT decode SVG out\n * of a Blob: it throws `InvalidStateError: The source image could not be decoded`. Measured\n * 2026-09-26 on Chrome 154, against an SVG carrying width, height AND a viewBox - so it is\n * not the missing-intrinsic-size case. The same file through an `<img>` decodes fine, which\n * is also the route @livekit/track-processors takes.\n *\n * That difference is the whole bug this replaces: a host shipping SVG backgrounds lost every\n * one of them while blur and uploaded JPEGs kept working, and the throw was swallowed by the\n * caller, so the picker simply did nothing.\n *\n * A worker has no `Image`, and there an SVG cannot be decoded at all. Say that, rather than\n * let an InvalidStateError name nothing.\n */\nexport async function decodeImage(path: string, opts?: ImageBitmapOptions): Promise<ImageBitmap> {\n if (typeof Image === \"undefined\") {\n const res = await fetch(path)\n if (!res.ok) throw new Error(`mediakit: cannot load image ${path} (HTTP ${res.status})`)\n const blob = await res.blob()\n try {\n return await createImageBitmap(blob, opts)\n } catch (err) {\n if (blob.type.includes(\"svg\")) {\n throw new Error(\n `mediakit: cannot decode the SVG background ${path} off the main thread - give this transport a raster image`,\n )\n }\n throw err\n }\n }\n\n const img = new Image()\n // Set for the same reason LiveKit sets it: a cross-origin background served without CORS\n // then fails here, loudly, instead of tainting the canvas and throwing SecurityError one\n // step later where the cause is no longer visible.\n img.crossOrigin = \"anonymous\"\n await new Promise<void>((resolve, reject) => {\n img.onload = () => resolve()\n img.onerror = () => reject(new Error(`mediakit: cannot load background image ${path}`))\n img.src = path\n })\n if (!img.naturalWidth || !img.naturalHeight) {\n throw new Error(\n `mediakit: background image ${path} has no intrinsic size - an SVG needs width and height, a viewBox alone is not enough`,\n )\n }\n return createImageBitmap(img, opts)\n}\n\n/**\n * Load a background image and COVER-crop it to the frame aspect.\n *\n * ── Why the crop belongs here ────────────────────────────────────────────────────────\n * The shader samples the background with the frame's own UV coordinates, so an image of a\n * different aspect comes out STRETCHED. Bundled 16:9 backgrounds never show it; an image the\n * user uploaded shows it immediately, and a host that downscales uploads *contain*-style\n * turns a portrait photo into a portrait canvas that is then stretched sideways to fill.\n *\n * Cropping at load rather than in the shader: it happens ONCE when the user picks an image\n * instead of every frame, and it costs no extra uniform - the uniform layout is exactly where\n * a silent bug already came from (T6 in doc/apps/mediakit/PLAN.md), so adding a slot to it is\n * worth avoiding when there is another way.\n */\nasync function loadBitmap(path: string, w: number, h: number): Promise<ImageBitmap> {\n return coverCrop(await decodeImage(path), w, h)\n}\n\n/** The cover crop half of {@link loadBitmap}. Takes ownership of `src`. */\nasync function coverCrop(src: ImageBitmap, w: number, h: number): Promise<ImageBitmap> {\n if (src.width * h === src.height * w) return src // already the right aspect\n\n // The largest region of the source that has the frame's aspect, centred.\n const scale = Math.max(w / src.width, h / src.height)\n const cw = Math.min(src.width, Math.round(w / scale))\n const ch = Math.min(src.height, Math.round(h / scale))\n const out = await createImageBitmap(\n src,\n Math.round((src.width - cw) / 2),\n Math.round((src.height - ch) / 2),\n cw,\n ch,\n { resizeWidth: w, resizeHeight: h, resizeQuality: \"high\" },\n )\n src.close()\n return out\n}\n","import { Engine, decodeImage, type FrameStats } from \"./engine\"\nimport { NO_EFFECTS, type BgFilter, type DebugView, type Effects } from \"./recipe\"\nimport type { FromWorker, ToWorker } from \"./worker/entry\"\nimport { GpuLostError, gpuRecord, recordLoss, type GpuRecord, type LossPhase } from \"./gpu-guard\"\nimport { assetUrl } from \"./assets\"\n\n/**\n * A camera track in, a processed camera track out.\n *\n * This is the transport layer: it owns nothing about pixels, only about how frames get to the\n * {@link Engine} and back. The host app wraps it in whatever seam its SDK wants - in meet that\n * is a LiveKit `TrackProcessor`, roughly thirty lines.\n *\n * ── The three transports ─────────────────────────────────────────────────────────────\n *\n * worker preferred - same APIs as `insertable`, but the frame streams are transferred\n * into a worker so the Engine runs off the main thread entirely\n * insertable MediaStreamTrackProcessor + MediaStreamTrackGenerator, on this thread\n * canvas anything else - <video> + captureStream\n *\n * The worker path is what clears defect #1 of the LiveKit implementation\n * (doc/apps/mediakit/PLAN.md section 1): MediaPipe's `segmentForVideo` is a SYNCHRONOUS call\n * tens of milliseconds long, so on the main thread it blocks the event loop and the UI\n * stutters the moment background blur goes on.\n *\n * The `canvas` path here still beats LiveKit's on three measurable points:\n * 1. `requestVideoFrameCallback` instead of polling `currentTime` inside\n * `requestAnimationFrame` - on the real frame rhythm, so no jitter.\n * 2. `captureStream` reads the canvas mediakit already drew, dropping one full-frame\n * `drawImage` per frame.\n * 3. No WebCodecs needed: the `<video>` element goes straight into `texImage2D`.\n */\n\nexport type Transport = \"worker\" | \"insertable\" | \"canvas\"\n\nconst SLOW_FRAME_MS = 150\nconst SLOW_TICKS = 3\nconst MAX_GPU_RECOVERIES = 2\n\n/** How long the worker gets to answer \"start\" before the main thread gives up on it. */\nconst WORKER_READY_MS = 8_000\n\n/** No frame out for this long, with the camera live, counts as a stall. */\nconst STALL_MS = 2_000\n/** The same while a detector is loading. */\nconst LOADING_STALL_MS = 20_000\n/** Silence for this long on the worker transport means the worker is gone. */\nconst WORKER_DEAD_MS = 8_000\n\nexport interface PipelineOptions {\n /** Keep the output's alpha channel, for `subscribeFrames` with a `cutout` background. */\n alpha?: boolean\n /**\n * Faces to track, 1-3, default 3. One person per camera should say 1: looking for more re-runs\n * the face detector on every call, about a third of the landmark cost.\n */\n maxFaces?: number\n syncFaces?: boolean\n /** Starts with an inner layer drawn instead of the picture; see `setDebug`. */\n debug?: DebugView\n /** No processed frame for 2 s while the camera is live (20 s while a detector loads). */\n onStall?: (info: { transport: Transport; sinceMs: number }) => void\n /** The pipeline replaced `processedTrack` mid-session. */\n onTrackReplaced?: (track: MediaStreamTrack, previous: MediaStreamTrack | undefined) => void\n /** Something degraded while running; see {@link IssueCode}. Each code fires once until it clears. */\n onIssue?: (issue: PipelineIssue) => void\n}\n\n/** What degraded; each code and what the app should do is in the README, \"Handling a weak or failing GPU\". */\nexport type IssueCode = \"stall\" | \"slow\" | \"effect-off\" | \"worker-moved\" | \"gpu-lost\"\n\nexport interface PipelineIssue {\n code: IssueCode\n message: string\n transport: Transport\n}\n\n/** `gpu-blocked`: this GPU lost its WebGL context building mediakit's shaders in the last 3 days. */\nexport type SupportReason = \"no-window\" | \"no-wasm\" | \"no-webgl2\" | \"no-transport\" | \"gpu-blocked\"\n\nexport interface SupportReport {\n supported: boolean\n /** Every reason it cannot run, empty when supported. */\n reasons: SupportReason[]\n /** WebGL2 only through a software rasteriser (SwiftShader, llvmpipe): it runs, but slowly. */\n softwareRenderer: boolean\n /** The GPU the browser reports, \"\" when it hides it. */\n gpu: string\n /** What this browser remembers about `gpu` failing under mediakit; see `forgetGpuFailures`. */\n remembered: GpuRecord | null\n}\n\n/** What `health` reports. */\nexport interface PipelineHealth {\n transport: Transport\n /** Frames out since start, or since the last transport change. */\n frames: number\n /** Milliseconds since a frame last came out. */\n sinceMs: number\n stalled: boolean\n /** Why some effects are off while the picture still runs (see `FrameStats.effectError`); \"\" when none. */\n effectError: string\n}\n\n/** Chrome exposes these on the main thread; the standard versions are worker-only. */\nfunction hasInsertableStreams(): boolean {\n return (\n typeof window !== \"undefined\" &&\n \"MediaStreamTrackProcessor\" in window &&\n \"MediaStreamTrackGenerator\" in window\n )\n}\n\n/** Whether mediakit can run in this browser, and every reason it cannot. Creates and frees two WebGL contexts. */\nexport function checkSupport(): SupportReport {\n if (typeof window === \"undefined\") return { supported: false, reasons: [\"no-window\"], softwareRenderer: false, gpu: \"\", remembered: null }\n const reasons: SupportReason[] = []\n if (typeof WebAssembly === \"undefined\") reasons.push(\"no-wasm\")\n const gl = document.createElement(\"canvas\").getContext(\"webgl2\")\n let gpu = \"\"\n let softwareRenderer = false\n if (!gl) reasons.push(\"no-webgl2\")\n else {\n const info = gl.getExtension(\"WEBGL_debug_renderer_info\")\n gpu = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? \"\")\n const fast = document.createElement(\"canvas\").getContext(\"webgl2\", { failIfMajorPerformanceCaveat: true })\n softwareRenderer = !fast || /swiftshader|llvmpipe|software|basic render/i.test(gpu)\n fast?.getExtension(\"WEBGL_lose_context\")?.loseContext()\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n }\n if (!hasInsertableStreams() && !(\"captureStream\" in HTMLCanvasElement.prototype)) reasons.push(\"no-transport\")\n const remembered = gpuRecord(gpu)\n if (remembered?.init) reasons.push(\"gpu-blocked\")\n probedGpu = gpu\n return { supported: reasons.length === 0, reasons, softwareRenderer, gpu, remembered }\n}\n\nlet probedGpu: string | null = null\n\nfunction probeGpu(): string {\n if (probedGpu !== null) return probedGpu\n const gl = typeof document === \"undefined\" ? null : document.createElement(\"canvas\").getContext(\"webgl2\")\n if (!gl) return \"\"\n const info = gl.getExtension(\"WEBGL_debug_renderer_info\")\n probedGpu = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? \"\")\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n return probedGpu\n}\n\n/** Whether mediakit can run in this browser at all; {@link checkSupport} says why not. */\nexport function mediakitSupported(): boolean {\n return checkSupport().supported\n}\n\nexport class VideoPipeline {\n processedTrack?: MediaStreamTrack\n\n private filter: BgFilter\n private effects: Effects\n private opts: PipelineOptions\n private debug: DebugView = \"off\"\n\n // Health: a beat per frame out.\n private source: MediaStreamTrack | null = null\n private size = { width: 1280, height: 720, fps: 30 }\n private lastBeat = 0\n private frames = 0\n private stalled = false\n private watchdog: ReturnType<typeof setInterval> | null = null\n private movedOff = false\n private raised = new Set<IssueCode>()\n private slowTicks = 0\n private gpuRecoveries = 0\n private gpu = \"\"\n private faceColorLost = false\n private recovering = false\n private workerDialect: \"streams\" | \"track\" | null = null\n private generator: MediaStreamTrackGenerator<VideoFrame> | null = null\n private piping: Promise<void> = Promise.resolve()\n /** What the worker last said about loading detectors. */\n private workerLoading = false\n\n // Frames handed out alongside the track - see subscribeFrames.\n private frameSubs = new Set<(frame: VideoFrame) => void>()\n private engine: Engine | null = null\n private transport: Transport = \"insertable\"\n\n // insertable path\n private abort: AbortController | null = null\n\n // worker path\n private worker: Worker | null = null\n private workerStats: FrameStats | null = null\n /** The background path the worker already holds; see backgroundForWorker. */\n private workerBackgroundPath: string | null = null\n\n // canvas path\n private video: HTMLVideoElement | null = null\n private rvfcHandle = 0\n private stopped = false\n\n constructor(filter: BgFilter, effects: Effects = NO_EFFECTS, opts: PipelineOptions = {}) {\n this.filter = filter\n this.effects = effects\n this.opts = opts\n this.debug = opts.debug ?? \"off\"\n }\n\n /** Whether frames are coming out, and how long since the last one. */\n get health(): PipelineHealth {\n return {\n transport: this.transport,\n frames: this.frames,\n sinceMs: this.lastBeat ? performance.now() - this.lastBeat : 0,\n stalled: this.stalled,\n effectError: this.stats?.effectError ?? \"\",\n }\n }\n\n /** Every processed frame. */\n subscribeFrames(cb: (frame: VideoFrame) => void): () => void {\n this.frameSubs.add(cb)\n if (this.frameSubs.size === 1) this.send({ t: \"frames\", on: true })\n return () => {\n this.frameSubs.delete(cb)\n if (this.frameSubs.size === 0) this.send({ t: \"frames\", on: false })\n }\n }\n\n private deliver(frame: VideoFrame) {\n const subs = [...this.frameSubs]\n if (subs.length === 0) {\n frame.close()\n return\n }\n subs.forEach((cb, i) => {\n try {\n cb(i === subs.length - 1 ? frame : frame.clone())\n } catch (e) {\n console.error(\"mediakit: frame subscriber threw\", e)\n }\n })\n }\n\n private issue(code: IssueCode, message: string) {\n if (this.raised.has(code)) return\n this.raised.add(code)\n console.warn(`mediakit: ${code}: ${message}`)\n try {\n this.opts.onIssue?.({ code, message, transport: this.transport })\n } catch (e) {\n console.error(\"mediakit: onIssue threw\", e)\n }\n }\n\n private watchQuality() {\n const s = this.stats\n if (!s) return\n if (s.effectError) this.issue(\"effect-off\", s.effectError)\n const slow = s.totalMs > SLOW_FRAME_MS || s.faceMs > SLOW_FRAME_MS\n this.slowTicks = slow ? Math.max(1, this.slowTicks + 1) : Math.min(-1, this.slowTicks - 1)\n if (this.slowTicks >= SLOW_TICKS) {\n this.issue(\"slow\", `frames take ${Math.round(s.totalMs)}ms, face detection ${Math.round(s.faceMs)}ms`)\n } else if (this.slowTicks <= -SLOW_TICKS) {\n this.raised.delete(\"slow\")\n }\n const phase = this.engine?.lostDuring\n if (phase) void this.recoverGpu(\"the main-thread WebGL context was lost\", phase)\n }\n\n private noFaceColor(): boolean {\n return this.faceColorLost || (gpuRecord(this.gpu)?.faceColor ?? false)\n }\n\n /** A \"link\" loss rebuilds without face colour, a \"run\" loss as before; an \"init\" loss would only repeat. */\n private async recoverGpu(why: string, phase: LossPhase, gpu = this.gpu) {\n if (this.recovering || this.stopped || !this.source || this.raised.has(\"gpu-lost\")) return\n recordLoss(gpu, phase)\n if (phase === \"link\") this.faceColorLost = true\n const retry = phase !== \"init\" && this.gpuRecoveries < MAX_GPU_RECOVERIES\n const during = phase === \"link\" ? \"linking a makeup shader\" : phase === \"init\" ? \"building the shaders\" : \"while running\"\n const next = !retry ? \"not rebuilding\" : phase === \"link\" ? \"rebuilding without makeup\" : \"rebuilding\"\n this.issue(\"gpu-lost\", `${why} (${during}, ${next})`)\n if (!retry) return\n this.gpuRecoveries++\n this.recovering = true\n try {\n if (this.transport === \"worker\" && phase === \"run\") await this.moveOffWorker(\"lost its WebGL context\")\n else await this.rebuild(this.source)\n this.raised.delete(\"gpu-lost\")\n } catch (e) {\n console.error(\"mediakit: rebuilding after a lost WebGL context failed\", e)\n } finally {\n this.recovering = false\n }\n }\n\n private beat() {\n this.lastBeat = performance.now()\n this.frames++\n this.stalled = false\n }\n\n private startWatchdog() {\n this.stopWatchdog()\n this.lastBeat = performance.now()\n this.watchdog = setInterval(() => {\n if (this.stopped || !this.source) return\n // A camera that is not producing is not a stall of ours.\n if (this.source.readyState !== \"live\" || this.source.muted) {\n this.lastBeat = performance.now()\n return\n }\n if (this.transport === \"canvas\" && typeof document !== \"undefined\" && document.visibilityState !== \"visible\") {\n this.lastBeat = performance.now()\n return\n }\n const since = performance.now() - this.lastBeat\n const loading = this.transport === \"worker\" ? this.workerLoading : (this.engine?.loading ?? false)\n const transport = this.transport\n if (since >= (loading ? LOADING_STALL_MS : STALL_MS) && !this.stalled) {\n this.stalled = true\n this.issue(\"stall\", `no frame out for ${Math.round(since)}ms on the ${transport} transport`)\n this.opts.onStall?.({ transport, sinceMs: since })\n }\n if (!this.stalled) this.raised.delete(\"stall\")\n this.watchQuality()\n if (transport === \"worker\" && since >= (loading ? LOADING_STALL_MS : WORKER_DEAD_MS)) {\n void this.moveOffWorker(\"silent\")\n }\n }, 1_000)\n }\n\n private stopWatchdog() {\n if (this.watchdog) clearInterval(this.watchdog)\n this.watchdog = null\n }\n\n /** The worker failed or stalled AFTER the host published its track. */\n private async moveOffWorker(reason: string) {\n if (this.movedOff || this.stopped || !this.source) return\n this.movedOff = true\n this.issue(\"worker-moved\", `worker ${reason} after start, moving to the main thread`)\n const previous = this.processedTrack\n this.teardownWorker()\n try {\n await this.startMain(this.source)\n } catch (e) {\n console.error(\"mediakit: main-thread fallback failed\", e)\n return\n }\n previous?.stop()\n if (this.processedTrack) this.opts.onTrackReplaced?.(this.processedTrack, previous)\n }\n\n get stats(): FrameStats | null {\n // On the worker path the Engine lives over there, so stats arrive by message.\n return this.transport === \"worker\" ? this.workerStats : (this.engine?.last ?? null)\n }\n\n get transportName(): Transport {\n return this.transport\n }\n\n /** Take over `source` and publish the result on {@link processedTrack}. */\n async start(source: MediaStreamTrack): Promise<void> {\n this.gpu ||= probeGpu()\n const known = gpuRecord(this.gpu)\n if (known?.init) {\n throw new GpuLostError(\"init\", this.gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`)\n }\n const settings = source.getSettings()\n const width = settings.width ?? 1280\n const height = settings.height ?? 720\n\n this.stopped = false\n this.source = source\n this.size = { width, height, fps: settings.frameRate ?? 30 }\n this.frames = 0\n this.movedOff = false\n this.startWatchdog()\n\n // The worker path builds its streams on THIS thread (see startWorker), so the probe\n // belongs here and is honest. Anything short of a \"ready\" still falls through to the\n // transports below, which is what covers a worker that loads and then fails.\n if (\n hasInsertableStreams() &&\n typeof Worker !== \"undefined\" &&\n typeof OffscreenCanvas !== \"undefined\"\n ) {\n try {\n await this.startWorker(source, width, height, await this.backgroundForWorker(this.filter))\n this.transport = \"worker\"\n this.workerDialect = \"streams\"\n return\n } catch (e) {\n this.teardownWorker()\n if (e instanceof GpuLostError) throw e\n console.warn(\"mediakit: worker unusable, falling back to the main thread\", e)\n }\n } else if (typeof Worker !== \"undefined\" && typeof OffscreenCanvas !== \"undefined\") {\n // No insertable streams HERE - Safari keeps them in workers.\n try {\n await this.startWorkerWithTrack(source, width, height, await this.backgroundForWorker(this.filter))\n this.transport = \"worker\"\n this.workerDialect = \"track\"\n return\n } catch (e) {\n this.teardownWorker()\n if (e instanceof GpuLostError) throw e\n console.warn(\"mediakit: no worker transport in this browser, staying on the main thread\", e)\n }\n }\n\n await this.startMain(source)\n }\n\n private async startMain(source: MediaStreamTrack) {\n const { width, height, fps } = this.size\n this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces, {\n noFaceColor: this.noFaceColor(),\n })\n this.engine.syncFaces = this.opts.syncFaces ?? false\n this.engine.setDebug(this.debug)\n this.transport = hasInsertableStreams() ? \"insertable\" : \"canvas\"\n this.frames = 0\n this.lastBeat = performance.now()\n // A fresh transport gets a fresh watch: if this one stalls too, the host hears again.\n this.stalled = false\n\n if (this.transport === \"insertable\") {\n this.startInsertable(source)\n } else {\n await this.startCanvas(source, fps)\n }\n }\n\n /**\n * Feed a different camera into the running pipeline, as Tencent's `resetCore(input)`. At the\n * same resolution {@link processedTrack} stays the same track; otherwise the pipeline rebuilds\n * and `onTrackReplaced` fires. The caller still owns both sources: neither is stopped here.\n */\n async replaceSource(next: MediaStreamTrack): Promise<MediaStreamTrack | undefined> {\n if (this.stopped || !this.source) throw new Error(\"mediakit: replaceSource before start\")\n const settings = next.getSettings()\n const width = settings.width ?? 1280\n const height = settings.height ?? 720\n if (width !== this.size.width || height !== this.size.height) {\n await this.rebuild(next)\n return this.processedTrack\n }\n if (this.transport === \"worker\" && this.workerDialect === \"streams\") {\n const processor = new MediaStreamTrackProcessor({ track: next as MediaStreamVideoTrack })\n this.send({ t: \"source\", readable: processor.readable }, [processor.readable])\n } else if (this.transport === \"worker\") {\n const clone = next.clone()\n this.send({ t: \"sourceTrack\", track: clone }, [clone as unknown as Transferable])\n } else if (this.transport === \"insertable\") {\n this.pipeInsertable(next)\n } else if (this.video) {\n this.video.srcObject = new MediaStream([next])\n await this.video.play()\n }\n this.source = next\n this.size.fps = settings.frameRate ?? this.size.fps\n this.lastBeat = performance.now()\n return this.processedTrack\n }\n\n private async rebuild(source: MediaStreamTrack) {\n const previous = this.processedTrack\n this.processedTrack = undefined\n this.teardownTransports()\n await this.start(source)\n previous?.stop()\n if (this.processedTrack) this.opts.onTrackReplaced?.(this.processedTrack, previous)\n }\n\n /** Swap the background in place - no pipeline rebuild, so the picture does not flash. */\n async switchTo(filter: BgFilter): Promise<void> {\n this.filter = filter\n await this.pushRecipe()\n }\n\n /**\n * Draw an inner layer instead of the picture: \"skin\" (red smoothing, green whitening, blue face\n * mesh), \"mask\" (the person or class mask) or \"face\" (tracked outlines and necks). \"off\" restores it.\n */\n setDebug(view: DebugView): void {\n this.debug = view\n if (this.worker) this.send({ t: \"debug\", view })\n else this.engine?.setDebug(view)\n }\n\n get debugView(): DebugView {\n return this.debug\n }\n\n /** Change the effects outside the background. */\n async setEffects(effects: Effects): Promise<void> {\n this.effects = effects\n await this.pushRecipe()\n }\n\n private async pushRecipe(): Promise<void> {\n if (this.worker) {\n const filter = this.filter\n const background = await this.backgroundForWorker(filter)\n this.send({ t: \"recipe\", filter, effects: this.effects, background }, background ? [background] : [])\n return\n }\n await this.engine?.setRecipe(this.filter, this.effects)\n }\n\n async stop(): Promise<void> {\n this.stopped = true\n this.stopWatchdog()\n this.source = null\n this.teardownTransports()\n this.processedTrack?.stop()\n this.processedTrack = undefined\n }\n\n private teardownTransports() {\n this.abort?.abort()\n this.abort = null\n this.generator = null\n\n if (this.rvfcHandle && this.video) {\n this.video.cancelVideoFrameCallback?.(this.rvfcHandle)\n }\n this.rvfcHandle = 0\n if (this.video) {\n this.video.pause()\n this.video.srcObject = null\n this.video.remove()\n this.video = null\n }\n\n this.teardownWorker()\n\n this.engine?.close()\n this.engine = null\n }\n\n // ── worker ───────────────────────────────────────────────────────────────────────\n\n /**\n * The image background decoded HERE, for the worker: it has no `Image`, so it cannot decode\n * an SVG, which is every background meet bundles. Only when the path changed - the worker\n * Engine keeps the last one by path, and a slider drag must not decode it again.\n */\n private async backgroundForWorker(filter: BgFilter): Promise<ImageBitmap | undefined> {\n if (filter.kind !== \"image\" || filter.imagePath === this.workerBackgroundPath) return undefined\n const bmp = await decodeImage(filter.imagePath)\n this.workerBackgroundPath = filter.imagePath\n return bmp\n }\n\n private send(m: ToWorker, transfer: Transferable[] = []) {\n this.worker?.postMessage(m, transfer)\n }\n\n private teardownWorker() {\n if (!this.worker) return\n this.send({ t: \"stop\" })\n // terminate() rather than waiting for the stop to be handled: the worker owns nothing\n // the page outlives, and a worker that is already wedged would never get to the stop.\n this.worker.terminate()\n this.worker = null\n this.workerDialect = null\n this.workerStats = null\n this.workerLoading = false\n this.workerBackgroundPath = null\n }\n\n /**\n * Give the worker the frame STREAMS, and keep the track on this thread.\n *\n * ── Why not transfer the track ───────────────────────────────────────────────────\n * The obvious shape is to transfer the camera track into the worker and let it build its\n * own processor and generator there. It does not work, for two independent reasons, and\n * both were measured on 2026-09-26:\n *\n * 1. Chrome 154 does not treat a MediaStreamTrack as transferable at all:\n * `DataCloneError: Value at index 0 does not have a transferable type`. So the whole\n * path fell back to the main thread on every start, on the one browser that has all\n * the APIs it needs.\n * 2. On a browser where the transfer DID succeed it would be worse than useless. A\n * transfer detaches the main-thread object, and a host keeps using it: LiveKit's\n * `setProcessor` calls `attachToElement(_mediaStreamTrack, ...)`, `detachTrack` and\n * registers an `ended` listener on that same object AFTER `init()` returns. Stealing\n * it breaks the camera, not just the effect.\n *\n * A ReadableStream and a WritableStream are both transferable, so the split below moves\n * every frame into the worker with no copy while ownership of the track never leaves this\n * thread. The Engine, MediaPipe and the whole pass chain still run off the main thread,\n * which was the point.\n *\n * The cost: this needs `MediaStreamTrackProcessor` and `MediaStreamTrackGenerator` HERE,\n * so it is the Chrome dialect. A browser that only has them inside a worker (Safari) does\n * not get this path and stays on the canvas transport until someone can test that.\n */\n private startWorker(\n source: MediaStreamTrack,\n width: number,\n height: number,\n background?: ImageBitmap,\n ): Promise<void> {\n const processor = new MediaStreamTrackProcessor({ track: source as MediaStreamVideoTrack })\n // `signalTarget` forwards control signals back to the camera, exactly as on the\n // main-thread transport below.\n const generator = new MediaStreamTrackGenerator({\n kind: \"video\",\n signalTarget: source as MediaStreamVideoTrack,\n })\n\n return this.attachWorker(\n (ready) => {\n this.processedTrack = ready.track ?? generator\n },\n () => generator.stop(),\n () =>\n this.send(\n {\n t: \"start\",\n readable: processor.readable,\n writable: generator.writable,\n width,\n height,\n filter: this.filter,\n effects: this.effects,\n background,\n alpha: this.opts.alpha,\n maxFaces: this.opts.maxFaces,\n syncFaces: this.opts.syncFaces,\n debug: this.debug,\n noFaceColor: this.noFaceColor(),\n },\n background\n ? [processor.readable, generator.writable, background]\n : [processor.readable, generator.writable],\n ),\n )\n }\n\n /** Safari's dialect (see `startTrack` in worker/entry.ts). */\n private startWorkerWithTrack(\n source: MediaStreamTrack,\n width: number,\n height: number,\n background?: ImageBitmap,\n ): Promise<void> {\n const clone = source.clone()\n return this.attachWorker(\n (ready) => {\n if (!ready.track) throw new Error(\"mediakit: the worker sent no track\")\n this.processedTrack = ready.track\n },\n () => clone.stop(),\n () =>\n this.send(\n {\n t: \"startTrack\",\n track: clone,\n width,\n height,\n filter: this.filter,\n effects: this.effects,\n background,\n alpha: this.opts.alpha,\n maxFaces: this.opts.maxFaces,\n syncFaces: this.opts.syncFaces,\n debug: this.debug,\n noFaceColor: this.noFaceColor(),\n },\n background\n ? [clone as unknown as Transferable, background]\n : [clone as unknown as Transferable],\n ),\n )\n }\n\n /** Starts the worker and waits for its \"ready\". */\n private attachWorker(\n onReady: (ready: Extract<FromWorker, { t: \"ready\" }>) => void,\n cleanup: () => void,\n post: () => void,\n ): Promise<void> {\n // A static URL, not new URL(import.meta.url): Turbopack does not bundle workers from\n // source - measured 2026-09-26 - so this package ships the worker pre-bundled in\n // dist/worker.js and the host serves it alongside the other mediakit assets.\n //\n // CLASSIC, not `{ type: \"module\" }`: MediaPipe loads its wasm glue with\n // importScripts(), which a module worker forbids. See the tsup config.\n const worker = new Worker(assetUrl(\"worker.js\"))\n this.worker = worker\n\n return new Promise<void>((resolve, reject) => {\n let settled = false\n const fail = (err: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n // Nothing downstream has this track yet, and a generator left running holds a\n // sink open for frames that will never arrive.\n cleanup()\n reject(err)\n }\n // The timeout is the one that matters: a worker that neither answers nor throws\n // would otherwise leave start() hanging and the user staring at a dead camera.\n const timer = setTimeout(\n () => fail(new Error(`mediakit: worker silent for more than ${WORKER_READY_MS}ms`)),\n WORKER_READY_MS,\n )\n\n worker.onerror = (e) => {\n if (settled) {\n void this.moveOffWorker(e.message || \"crashed\")\n return\n }\n fail(new Error(e.message || \"mediakit: worker failed to load\"))\n }\n\n worker.onmessage = (e: MessageEvent<FromWorker>) => {\n const m = e.data\n if (m.t === \"stats\") {\n this.workerStats = m.stats\n // Stats come every half second, drawn or passed through: the heartbeat.\n this.lastBeat = performance.now()\n if (m.frames >= 0) this.frames = m.frames\n this.workerLoading = m.loading\n this.stalled = false\n return\n }\n if (m.t === \"frame\") {\n this.deliver(m.frame)\n return\n }\n if (m.t === \"lost\") {\n const gpu = m.gpu || this.gpu\n if (settled) void this.recoverGpu(\"the worker's WebGL context was lost\", m.phase, gpu)\n else {\n recordLoss(gpu, m.phase)\n fail(m.phase === \"init\" ? new GpuLostError(\"init\", gpu, m.message) : new Error(\"mediakit: the worker's WebGL context was lost\"))\n }\n return\n }\n if (m.t === \"error\") {\n if (settled) {\n // Past the point where anything can reject.\n console.error(\"mediakit: worker failed after start\", m.message)\n void this.moveOffWorker(\"failed\")\n return\n }\n fail(new Error(m.message))\n return\n }\n this.workerLoading = m.loading\n try {\n onReady(m)\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)))\n return\n }\n settled = true\n clearTimeout(timer)\n if (this.frameSubs.size > 0) this.send({ t: \"frames\", on: true })\n resolve()\n }\n\n try {\n post()\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)))\n }\n })\n }\n\n // ── insertable ───────────────────────────────────────────────────────────────────\n\n private startInsertable(source: MediaStreamTrack) {\n // `signalTarget` forwards control signals (a request-frame, say) back to the camera.\n // Without it, sources that only produce a frame when asked stand still.\n this.generator = new MediaStreamTrackGenerator({\n kind: \"video\",\n signalTarget: source as MediaStreamVideoTrack,\n })\n this.processedTrack = this.generator\n this.pipeInsertable(source)\n }\n\n private pipeInsertable(source: MediaStreamTrack) {\n const generator = this.generator\n if (!generator) return\n const processor = new MediaStreamTrackProcessor({\n track: source as MediaStreamVideoTrack,\n })\n\n const transform = new TransformStream<VideoFrame, VideoFrame>({\n transform: (frame, controller) => {\n this.beat()\n const engine = this.engine\n if (!engine) {\n controller.enqueue(frame)\n return\n }\n try {\n const drew = engine.render(frame, frame.timestamp)\n const held = drew ? null : engine.passthrough()\n if (drew) {\n controller.enqueue(engine.capture(engine.renderedTs))\n if (this.frameSubs.size > 0) this.deliver(engine.capture(engine.renderedTs, true))\n } else if (held) {\n if (this.frameSubs.size > 0) this.deliver(held.clone())\n controller.enqueue(held)\n } else if (!engine.dropped()) {\n // Subscribers get the source frame, as the track does.\n if (this.frameSubs.size > 0) this.deliver(frame.clone())\n // Nothing drawn yet - no mask in the first few frames, or the recipe\n // is inactive. Forward the source frame: dropping it here makes the\n // camera flash black.\n controller.enqueue(frame)\n return\n }\n } catch (e) {\n console.error(\"mediakit: frame processing failed\", e)\n controller.enqueue(frame)\n return\n }\n // Close the source frame IMMEDIATELY after use. Without this the browser\n // pipeline's buffer pool runs dry after a few dozen frames and the camera\n // freezes.\n frame.close()\n },\n })\n\n this.abort?.abort()\n const abort = new AbortController()\n this.abort = abort\n const previous = this.piping\n this.piping = previous.then(() => {\n if (abort.signal.aborted) return\n return processor.readable\n .pipeThrough(transform, { signal: abort.signal })\n .pipeTo(generator.writable, { signal: abort.signal, preventAbort: true, preventClose: true })\n .catch((e: unknown) => {\n if (abort.signal.aborted) return\n if (!this.stopped) console.error(\"mediakit: pipe broke\", e)\n })\n })\n }\n\n // ── canvas ───────────────────────────────────────────────────────────────────────\n\n private async startCanvas(source: MediaStreamTrack, fps: number) {\n const engine = this.engine!\n\n const video = document.createElement(\"video\")\n video.muted = true\n video.playsInline = true\n // Out of the layout flow: this element is only a decode source, never displayed.\n video.style.position = \"fixed\"\n video.style.opacity = \"0\"\n video.style.pointerEvents = \"none\"\n video.width = 1\n video.height = 1\n video.srcObject = new MediaStream([source])\n document.body.appendChild(video)\n this.video = video\n await video.play()\n\n // captureStream reads the canvas mediakit already drew. LiveKit's implementation draws\n // the processed frame onto a SECOND canvas and captures from that - one full-frame\n // copy per frame, to obtain the pixels that were already there.\n //\n // The Engine also accepts an OffscreenCanvas, because a worker has to hand it one.\n // Only this transport calls captureStream, and only it builds the Engine through\n // `create` - so the narrowing cannot fail here. It is checked rather than cast so that\n // moving this code somewhere else fails loudly instead of at runtime.\n const out = engine.outputCanvas\n if (!(out instanceof HTMLCanvasElement)) {\n throw new Error(\"mediakit: the canvas transport needs an HTMLCanvasElement\")\n }\n const stream = out.captureStream(fps)\n this.processedTrack = stream.getVideoTracks()[0]\n\n // requestVideoFrameCallback fires exactly when a NEW frame exists, with an accurate\n // mediaTime. LiveKit runs requestAnimationFrame and compares `video.currentTime` to\n // guess whether a new frame arrived - a rhythm that does not match the camera's, so\n // the picture shimmers slightly and the same frame is sometimes processed twice.\n const pump = (_now: number, meta: VideoFrameCallbackMetadata) => {\n if (this.stopped || !this.engine) return\n this.beat()\n try {\n const ts = Math.round(meta.mediaTime * 1_000_000)\n const drew = this.engine.render(video, ts)\n if (this.frameSubs.size > 0) {\n // Nothing drawn: the source, so a subscriber's picture never freezes.\n this.deliver(drew ? this.engine.capture(ts, true) : new VideoFrame(video, { timestamp: ts }))\n }\n } catch (e) {\n console.error(\"mediakit: frame processing failed\", e)\n }\n this.rvfcHandle = video.requestVideoFrameCallback(pump)\n }\n\n if (typeof video.requestVideoFrameCallback !== \"function\") {\n throw new Error(\n \"mediakit: browser has neither requestVideoFrameCallback nor insertable streams\",\n )\n }\n this.rvfcHandle = video.requestVideoFrameCallback(pump)\n }\n}\n","import { Engine, decodeImage } from \"./engine\"\nimport { loadCore, splitMicros, type MediakitCore } from \"./wasm\"\nimport { NO_EFFECTS, coreRecipe, type BgFilter, type Effects } from \"./recipe\"\nimport { TRANSITIONS, coreLayer, hitTest, parseColor, type Color, type SceneLayer, type TransitionKind } from \"./layout\"\n\n/**\n * Layers several sources onto one output, OBS style: cameras (each with its own mediakit\n * recipe, `cutout` included), screen shares, video files, images, text and any canvas.\n *\n * Main thread only. The layout maths, animations and transitions run in the Go core\n * (`core/scene`); this class owns the sources and their lifetimes and hands each frame's\n * pictures over.\n *\n * Each camera with effects runs its own {@link Engine} on its own WebGL context, and its finished\n * picture is uploaded here like any other source. Browsers cap live contexts at 8-16, so a scene\n * holds at most a handful of processed cameras.\n */\n\nexport type SceneSource =\n /** A camera, processed by its own Engine. No filter and no effects means none is created. */\n | { kind: \"camera\"; track: MediaStreamTrack; filter?: BgFilter; effects?: Effects }\n /** Any video track shown as it is: a screen share, a remote participant, a second camera. */\n | { kind: \"track\"; track: MediaStreamTrack }\n | { kind: \"video\"; url: string; loop?: boolean }\n | { kind: \"image\"; url: string }\n | { kind: \"image\"; bitmap: ImageBitmap }\n | { kind: \"text\"; text: string; style?: TextStyle }\n /** Uploaded every frame: for anything the host draws itself. */\n | { kind: \"canvas\"; canvas: HTMLCanvasElement | OffscreenCanvas }\n\n/** Sizes are in pixels of the text's own picture; the layer then scales it. */\nexport interface TextStyle {\n /** A CSS font. Default `600 48px sans-serif`. */\n font?: string\n color?: Color\n background?: Color\n padding?: number\n radius?: number\n align?: \"left\" | \"center\" | \"right\"\n /** Wraps at this width. Default: no wrapping. */\n maxWidth?: number\n /** A multiple of the font size. Default 1.25. */\n lineHeight?: number\n outline?: { width: number; color: Color }\n}\n\nexport interface SceneOptions {\n width: number\n height: number\n /** The render loop's rate. Default 30. */\n fps?: number\n background?: Color\n}\n\nexport interface SceneStats {\n glCalls: number\n /** Time spent on the last frame, sources included, in milliseconds. */\n frameMs: number\n sources: number\n layers: number\n}\n\nconst MAX_SOURCES = 8\n\ninterface Live {\n slot: number\n spec: SceneSource\n video?: HTMLVideoElement\n engine?: Engine\n /** The engine is being built or rebuilt; frames go through raw meanwhile. */\n engineBusy?: boolean\n picture?: ImageBitmap | HTMLCanvasElement | OffscreenCanvas\n /** A still picture changed and has to be uploaded once. */\n dirty: boolean\n /** A video delivered a frame since the last upload. Only meaningful when `rvfc`. */\n fresh: boolean\n rvfc?: boolean\n}\n\nexport class Scene {\n readonly canvas: HTMLCanvasElement\n private core: MediakitCore\n private gl: WebGL2RenderingContext\n private sources = new Map<string, Live>()\n private current: SceneLayer[] = []\n private fps: number\n private timer: ReturnType<typeof setTimeout> | null = null\n private closed = false\n private recorder: MediaRecorder | null = null\n private recorded: Blob[] = []\n\n last: SceneStats = { glCalls: 0, frameMs: 0, sources: 0, layers: 0 }\n\n private constructor(canvas: HTMLCanvasElement, gl: WebGL2RenderingContext, core: MediakitCore, fps: number) {\n this.canvas = canvas\n this.gl = gl\n this.core = core\n this.fps = fps\n }\n\n static async create(opts: SceneOptions): Promise<Scene> {\n const canvas = document.createElement(\"canvas\")\n canvas.width = opts.width\n canvas.height = opts.height\n // `preserveDrawingBuffer` so a snapshot or captureStream taken between two renders\n // reads the last frame rather than a cleared buffer.\n const gl = canvas.getContext(\"webgl2\", {\n alpha: false,\n premultipliedAlpha: false,\n antialias: false,\n depth: false,\n stencil: false,\n preserveDrawingBuffer: true,\n })\n if (!gl) throw new Error(\"mediakit: no WebGL2 in this browser\")\n let core: MediakitCore | undefined\n try {\n core = await loadCore()\n const err = core.sceneInit(gl, opts.width, opts.height)\n if (err) throw new Error(`mediakit: ${err}`)\n } catch (err) {\n // Give the context back at once - see the cap in Engine.on.\n core?.sceneClose()\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n throw err\n }\n const scene = new Scene(canvas, gl, core, opts.fps ?? 30)\n scene.setBackground(opts.background ?? \"#000\")\n return scene\n }\n\n setBackground(c: Color): void {\n const [r, g, b] = parseColor(c)\n this.core.sceneBackground(r, g, b)\n }\n\n /** Add a source, or replace the one with this id; it keeps its slot, so layers stay put. */\n async addSource(id: string, spec: SceneSource): Promise<void> {\n if (this.closed) return\n const old = this.sources.get(id)\n const slot = old ? old.slot : this.freeSlot()\n if (slot < 0) throw new Error(`mediakit: a scene holds at most ${MAX_SOURCES} sources`)\n if (old) this.dispose(old)\n\n const live: Live = { slot, spec, dirty: false, fresh: false }\n this.sources.set(id, live)\n try {\n await this.open(live)\n } catch (err) {\n this.dispose(live)\n if (this.sources.get(id) === live) {\n this.sources.delete(id)\n this.core.sceneUpload(slot, null, 0, 0)\n }\n throw err\n }\n // Replaced or closed while opening: what this call opened belongs to nobody now, and a\n // video left playing here would keep decoding for the life of the page.\n if (this.closed || this.sources.get(id) !== live) {\n this.dispose(live)\n return\n }\n // Layers naming this id were sent hidden while it was missing.\n this.push(0)\n }\n\n /**\n * Change a source without replacing it: new text or style for text, a new recipe for a\n * camera. Anything else is the same as {@link addSource}.\n */\n async updateSource(id: string, spec: SceneSource): Promise<void> {\n const live = this.sources.get(id)\n if (!live || this.closed) return\n if (spec.kind === \"text\" && live.spec.kind === \"text\") {\n live.spec = spec\n live.picture = renderText(spec.text, spec.style)\n live.dirty = true\n return\n }\n if (spec.kind === \"camera\" && live.spec.kind === \"camera\" && spec.track === live.spec.track) {\n live.spec = spec\n await this.ensureEngine(live)\n return\n }\n return this.addSource(id, spec)\n }\n\n removeSource(id: string): void {\n const live = this.sources.get(id)\n if (!live) return\n this.dispose(live)\n this.sources.delete(id)\n this.core.sceneUpload(live.slot, null, 0, 0)\n // A later source may reuse the slot; layers still naming this id must not show it.\n this.push(0)\n }\n\n get layers(): readonly SceneLayer[] {\n return this.current\n }\n\n /** Change the layout in place. With `animate` (ms) layers glide to their new state. */\n setLayers(layers: SceneLayer[], opts: { animate?: number } = {}): void {\n this.current = layers.slice()\n this.push(opts.animate ?? 0)\n }\n\n /** Move to another layout through a transition. */\n switchTo(layers: SceneLayer[], transition: { kind: TransitionKind; duration?: number } = { kind: \"cut\" }): void {\n if (this.closed) return\n this.current = layers.slice()\n const [lo, hi] = splitMicros(now())\n this.core.sceneSwitch(this.coreLayers(), lo, hi, Math.max(0, TRANSITIONS.indexOf(transition.kind)), transition.duration ?? 500)\n }\n\n /** The topmost layer under a point of the output, in fractions, for picking and dragging. */\n layerAt(x: number, y: number): SceneLayer | undefined {\n return hitTest(this.current, x, y, this.canvas.width / this.canvas.height)\n }\n\n start(): void {\n if (this.timer || this.closed) return\n const period = 1000 / this.fps\n let next = performance.now()\n let failed = false\n const tick = () => {\n // One bad frame - a camera's segmenter throwing, say - must not end the loop: the\n // output would freeze on its last frame with nothing reported after the first error.\n try {\n this.render()\n } catch (err) {\n if (!failed) console.error(\"mediakit: scene frame failed\", err)\n failed = true\n }\n // Scheduled against the ideal time rather than \"period from now\", so a slow frame\n // does not push every later one back.\n next += period\n const t = performance.now()\n if (next < t) next = t\n this.timer = setTimeout(tick, next - t)\n }\n tick()\n }\n\n stop(): void {\n if (this.timer) clearTimeout(this.timer)\n this.timer = null\n }\n\n /** Draw one frame now. The loop calls this; a host with its own loop can instead. */\n render(): number {\n if (this.closed) return 0\n const t0 = performance.now()\n const us = now()\n for (const live of this.sources.values()) this.feed(live, us)\n const [lo, hi] = splitMicros(us)\n const calls = this.core.sceneRender(lo, hi)\n this.last = { glCalls: calls, frameMs: performance.now() - t0, sources: this.sources.size, layers: this.current.length }\n return calls\n }\n\n /** The output as a live stream, for a call, a recorder or a `<video>`. */\n captureStream(fps = this.fps): MediaStream {\n return this.canvas.captureStream(fps)\n }\n\n /** The current frame as an image file. */\n snapshot(type = \"image/png\"): Promise<Blob> {\n return new Promise((resolve, reject) =>\n this.canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(\"mediakit: snapshot failed\"))), type),\n )\n }\n\n /** Record the output, optionally with an audio track, until {@link stopRecording}. */\n startRecording(opts: { audio?: MediaStreamTrack; mimeType?: string; videoBitsPerSecond?: number } = {}): void {\n if (this.recorder) return\n const stream = this.captureStream()\n if (opts.audio) stream.addTrack(opts.audio)\n const rec = new MediaRecorder(stream, { mimeType: opts.mimeType, videoBitsPerSecond: opts.videoBitsPerSecond })\n // Collected from the start: with a timeslice the recorder hands a chunk over every second,\n // and the first carries the WebM header - a file missing it does not play at all.\n const chunks: Blob[] = []\n rec.ondataavailable = (e) => chunks.push(e.data)\n this.recorder = rec\n this.recorded = chunks\n rec.start(1000)\n }\n\n stopRecording(): Promise<Blob> {\n const rec = this.recorder\n if (!rec) return Promise.reject(new Error(\"mediakit: not recording\"))\n const chunks = this.recorded\n this.recorder = null\n this.recorded = []\n return new Promise((resolve) => {\n rec.onstop = () => {\n // Only the scene's own capture track: an audio track came from the host.\n for (const t of rec.stream.getVideoTracks()) t.stop()\n resolve(new Blob(chunks, { type: rec.mimeType }))\n }\n rec.stop()\n })\n }\n\n close(): void {\n if (this.closed) return\n this.stop()\n if (this.recorder && this.recorder.state !== \"inactive\") this.recorder.stop()\n for (const t of this.recorder?.stream.getVideoTracks() ?? []) t.stop()\n this.recorder = null\n this.recorded = []\n for (const live of this.sources.values()) this.dispose(live)\n this.sources.clear()\n this.closed = true\n this.core.sceneClose()\n this.gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n }\n\n private freeSlot(): number {\n const used = new Set([...this.sources.values()].map((s) => s.slot))\n for (let i = 0; i < MAX_SOURCES; i++) if (!used.has(i)) return i\n return -1\n }\n\n private coreLayers() {\n return this.current.map((l) => coreLayer(l, (id) => this.sources.get(id)?.slot ?? -1))\n }\n\n private push(animateMs: number): void {\n if (this.closed) return\n const [lo, hi] = splitMicros(now())\n this.core.sceneSet(this.coreLayers(), lo, hi, animateMs)\n }\n\n private async open(live: Live): Promise<void> {\n const s = live.spec\n switch (s.kind) {\n case \"camera\":\n case \"track\":\n live.video = await playVideo((v) => (v.srcObject = new MediaStream([s.track])))\n watchFrames(live)\n if (s.kind === \"camera\") await this.ensureEngine(live)\n return\n case \"video\":\n live.video = await playVideo((v) => {\n v.src = s.url\n v.loop = s.loop ?? true\n v.crossOrigin = \"anonymous\"\n })\n watchFrames(live)\n return\n case \"image\":\n live.picture = \"bitmap\" in s ? s.bitmap : await decodeImage(s.url)\n live.dirty = true\n return\n case \"text\":\n live.picture = renderText(s.text, s.style)\n live.dirty = true\n return\n case \"canvas\":\n live.picture = s.canvas\n return\n }\n }\n\n /**\n * Build, update or drop a camera's Engine to match its recipe and its current size. An\n * Engine is sized at creation, so a camera that changes resolution needs a new one.\n */\n private async ensureEngine(live: Live): Promise<void> {\n const s = live.spec\n const v = live.video\n // A build already running picks up whatever spec is current when it finishes - see below.\n if (s.kind !== \"camera\" || !v || live.engineBusy) return\n const filter = s.filter ?? { kind: \"none\" }\n const effects = s.effects ?? NO_EFFECTS\n const wanted = filter.kind !== \"none\" || active(effects)\n const w = v.videoWidth\n const h = v.videoHeight\n const e = live.engine\n if (e && wanted && e.outputCanvas.width === w && e.outputCanvas.height === h) {\n await e.setRecipe(filter, effects)\n return\n }\n e?.close()\n live.engine = undefined\n if (!wanted || !w || !h) return\n live.engineBusy = true\n try {\n const canvas = document.createElement(\"canvas\")\n canvas.width = w\n canvas.height = h\n const engine = await Engine.on(canvas, filter, effects, undefined, true)\n if (this.closed || ![...this.sources.values()].includes(live)) engine.close()\n else live.engine = engine\n } finally {\n live.engineBusy = false\n }\n // The recipe changed while the engine was being built, and that call returned early\n // above; bring the new engine up to date.\n if (live.engine && live.spec !== s) await this.ensureEngine(live)\n }\n\n private feed(live: Live, us: number): void {\n const v = live.video\n if (v) {\n if ((live.rvfc && !live.fresh) || v.readyState < 2 || !v.videoWidth) return\n live.fresh = false\n const e = live.engine\n if (e && (e.outputCanvas.width !== v.videoWidth || e.outputCanvas.height !== v.videoHeight)) {\n void this.ensureEngine(live)\n } else if (e && e.render(v, us)) {\n this.core.sceneUpload(live.slot, e.outputCanvas, e.outputCanvas.width, e.outputCanvas.height)\n return\n }\n this.core.sceneUpload(live.slot, v, v.videoWidth, v.videoHeight)\n return\n }\n const p = live.picture\n if (!p) return\n if (live.spec.kind === \"canvas\" || live.dirty) {\n live.dirty = false\n this.core.sceneUpload(live.slot, p, p.width, p.height)\n }\n }\n\n private dispose(live: Live): void {\n live.engine?.close()\n live.engine = undefined\n if (live.video) {\n live.video.pause()\n live.video.srcObject = null\n live.video.removeAttribute(\"src\")\n live.video.load()\n live.video = undefined\n }\n // A bitmap the host handed over stays theirs; one decoded here is closed here.\n const s = live.spec\n if (live.picture instanceof ImageBitmap && !(s.kind === \"image\" && \"bitmap\" in s)) live.picture.close()\n live.picture = undefined\n }\n}\n\nfunction now(): number {\n return Math.round(performance.now() * 1000)\n}\n\nfunction active(e: Effects): boolean {\n const r = coreRecipe({ kind: \"none\" }, e)\n return Object.entries(r).some(([k, v]) => k !== \"background\" && (typeof v === \"number\" ? v !== 0 : v === true))\n}\n\nasync function playVideo(setup: (v: HTMLVideoElement) => void): Promise<HTMLVideoElement> {\n const v = document.createElement(\"video\")\n v.muted = true\n v.playsInline = true\n setup(v)\n await v.play()\n return v\n}\n\n/**\n * Mark a video fresh each time it presents a frame, so a 15 fps screen share is uploaded 15\n * times a second rather than at the scene's rate. Without requestVideoFrameCallback every scene\n * frame counts as fresh.\n */\nfunction watchFrames(live: Live): void {\n const v = live.video\n if (!v || !(\"requestVideoFrameCallback\" in v)) return\n live.rvfc = true\n const on = () => {\n if (live.video !== v) return\n live.fresh = true\n v.requestVideoFrameCallback(on)\n }\n v.requestVideoFrameCallback(on)\n}\n\n/** Draw text onto its own canvas, sized to fit it. */\nexport function renderText(text: string, style: TextStyle = {}): HTMLCanvasElement {\n const font = style.font ?? \"600 48px sans-serif\"\n const pad = style.padding ?? 16\n const c = document.createElement(\"canvas\")\n const ctx = c.getContext(\"2d\")!\n ctx.font = font\n const size = ctx.measureText(\"M\").width * 1.2\n const lineH = size * (style.lineHeight ?? 1.25)\n const lines: string[] = []\n for (const para of text.split(\"\\n\")) {\n if (!style.maxWidth) {\n lines.push(para)\n continue\n }\n let line = \"\"\n for (const word of para.split(/\\s+/)) {\n const next = line ? `${line} ${word}` : word\n if (line && ctx.measureText(next).width > style.maxWidth) {\n lines.push(line)\n line = word\n } else line = next\n }\n lines.push(line)\n }\n const outline = style.outline?.width ?? 0\n const textW = Math.max(1, ...lines.map((l) => ctx.measureText(l).width))\n c.width = Math.ceil(textW + 2 * pad + 2 * outline)\n c.height = Math.ceil(lines.length * lineH + 2 * pad + 2 * outline)\n\n // Resizing the canvas resets its context state.\n ctx.font = font\n if (style.background !== undefined) {\n ctx.fillStyle = css(style.background)\n ctx.beginPath()\n ctx.roundRect(0, 0, c.width, c.height, style.radius ?? 0)\n ctx.fill()\n }\n const align = style.align ?? \"left\"\n ctx.textAlign = align\n ctx.textBaseline = \"middle\"\n const x = align === \"left\" ? pad + outline : align === \"right\" ? c.width - pad - outline : c.width / 2\n lines.forEach((line, i) => {\n const y = pad + outline + lineH * (i + 0.5)\n if (outline > 0) {\n ctx.lineWidth = outline * 2\n ctx.lineJoin = \"round\"\n ctx.strokeStyle = css(style.outline!.color)\n ctx.strokeText(line, x, y)\n }\n ctx.fillStyle = css(style.color ?? \"#fff\")\n ctx.fillText(line, x, y)\n })\n return c\n}\n\nfunction css(c: Color): string {\n const [r, g, b, a] = parseColor(c)\n return `rgba(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)},${a})`\n}\n","// Code generated from MediaPipe's canonical_face_model.obj (mediapipe/modules/face_geometry/data,\n// Apache License 2.0, Copyright The MediaPipe Authors) - the same table as core/facemesh. DO NOT EDIT.\n\n/** Where each of the face landmarker's first 468 landmarks lies on the canonical face texture. */\nexport const FACE_UV = new Float32Array([\n 0.49998, 0.65253, 0.50003, 0.54749, 0.49997, 0.60237, 0.48211, 0.47198, 0.50015, 0.52716,\n 0.49991, 0.49825, 0.49952, 0.40106, 0.28971, 0.38076, 0.49995, 0.31240, 0.49999, 0.26992,\n 0.50002, 0.10705, 0.50002, 0.66623, 0.50002, 0.67922, 0.50002, 0.69235, 0.49998, 0.69528,\n 0.49998, 0.70593, 0.49998, 0.71938, 0.49998, 0.73702, 0.49997, 0.78137, 0.49982, 0.56298,\n 0.47377, 0.57391, 0.10491, 0.25414, 0.36593, 0.40958, 0.33876, 0.41302, 0.31112, 0.40946,\n 0.27466, 0.38913, 0.39336, 0.40371, 0.34523, 0.34401, 0.37009, 0.34608, 0.31932, 0.34727,\n 0.29790, 0.35359, 0.24779, 0.41081, 0.39689, 0.84276, 0.28010, 0.37560, 0.10631, 0.39996,\n 0.20993, 0.39135, 0.35581, 0.53441, 0.47175, 0.65040, 0.47415, 0.68019, 0.43978, 0.65723,\n 0.41462, 0.66654, 0.45037, 0.68086, 0.42877, 0.68269, 0.37497, 0.72781, 0.48672, 0.54763,\n 0.48530, 0.52740, 0.25777, 0.31449, 0.40122, 0.45517, 0.42982, 0.54862, 0.42135, 0.53374,\n 0.27690, 0.53206, 0.48337, 0.49959, 0.33721, 0.28288, 0.29639, 0.29324, 0.16930, 0.19381,\n 0.44758, 0.30261, 0.39239, 0.35389, 0.35449, 0.69678, 0.06731, 0.73011, 0.44274, 0.57283,\n 0.45710, 0.58479, 0.38197, 0.69471, 0.39239, 0.69420, 0.27708, 0.27193, 0.42255, 0.56323,\n 0.38592, 0.28136, 0.38310, 0.25584, 0.33143, 0.11971, 0.22992, 0.23200, 0.36450, 0.18911,\n 0.22962, 0.29954, 0.17329, 0.27875, 0.47288, 0.66620, 0.44683, 0.66853, 0.42276, 0.67389,\n 0.44531, 0.58007, 0.38810, 0.69396, 0.40304, 0.70654, 0.40363, 0.69395, 0.46004, 0.55714,\n 0.43116, 0.69237, 0.45218, 0.69237, 0.47539, 0.69237, 0.46583, 0.77919, 0.47233, 0.73623,\n 0.47309, 0.71786, 0.47312, 0.70463, 0.47303, 0.69528, 0.42794, 0.69528, 0.42648, 0.70354,\n 0.42316, 0.71185, 0.41831, 0.72006, 0.39010, 0.63957, 0.01395, 0.56003, 0.49991, 0.58015,\n 0.41320, 0.69540, 0.40963, 0.70182, 0.46808, 0.60153, 0.42273, 0.58598, 0.46308, 0.59378,\n 0.37212, 0.47341, 0.33456, 0.49607, 0.41167, 0.54696, 0.24218, 0.14768, 0.29078, 0.20145,\n 0.32734, 0.25653, 0.39951, 0.74892, 0.44173, 0.26168, 0.42977, 0.18783, 0.41220, 0.10890,\n 0.28896, 0.39895, 0.21894, 0.43541, 0.41278, 0.39897, 0.25714, 0.35544, 0.42768, 0.43796,\n 0.44834, 0.53694, 0.17856, 0.45755, 0.24731, 0.45719, 0.28627, 0.46767, 0.33283, 0.46071,\n 0.36876, 0.44721, 0.39896, 0.43266, 0.47641, 0.40581, 0.18924, 0.52392, 0.22896, 0.34895,\n 0.49073, 0.56240, 0.40467, 0.48513, 0.01947, 0.40156, 0.42624, 0.42043, 0.39699, 0.54880,\n 0.26647, 0.37698, 0.43912, 0.51896, 0.03231, 0.64436, 0.41905, 0.38716, 0.46278, 0.50575,\n 0.23898, 0.77975, 0.19822, 0.83194, 0.10755, 0.54075, 0.18361, 0.74026, 0.13441, 0.33368,\n 0.38576, 0.88315, 0.49097, 0.57938, 0.38238, 0.50857, 0.17440, 0.39767, 0.31878, 0.39624,\n 0.34336, 0.40060, 0.39610, 0.71022, 0.18788, 0.58854, 0.43099, 0.94407, 0.31899, 0.89829,\n 0.26625, 0.86970, 0.50002, 0.19058, 0.49998, 0.95445, 0.36617, 0.39882, 0.39321, 0.39554,\n 0.41037, 0.39108, 0.19499, 0.34210, 0.38866, 0.36228, 0.36596, 0.35597, 0.34336, 0.35536,\n 0.31878, 0.35834, 0.30141, 0.36316, 0.05813, 0.31908, 0.30141, 0.38745, 0.49999, 0.61843,\n 0.41584, 0.62420, 0.44568, 0.56608, 0.46584, 0.62064, 0.49992, 0.35152, 0.28872, 0.81995,\n 0.33528, 0.85282, 0.44051, 0.90242, 0.12829, 0.79194, 0.40877, 0.37389, 0.45561, 0.45180,\n 0.49988, 0.90899, 0.37544, 0.92419, 0.11421, 0.61502, 0.44866, 0.69528, 0.44802, 0.70463,\n 0.44711, 0.71581, 0.44483, 0.73079, 0.43001, 0.76681, 0.40679, 0.68567, 0.40074, 0.68107,\n 0.39240, 0.67770, 0.36786, 0.66392, 0.24792, 0.60133, 0.45277, 0.42085, 0.43639, 0.35989,\n 0.41616, 0.36871, 0.41339, 0.69237, 0.22802, 0.68357, 0.46827, 0.35267, 0.41136, 0.80433,\n 0.49999, 0.46983, 0.47915, 0.44265, 0.49997, 0.43964, 0.43211, 0.49359, 0.49989, 0.86692,\n 0.49991, 0.82173, 0.45655, 0.81920, 0.34455, 0.74544, 0.37891, 0.57401, 0.37429, 0.78019,\n 0.31969, 0.57074, 0.35716, 0.60427, 0.29528, 0.62158, 0.44775, 0.86248, 0.41099, 0.50872,\n 0.31395, 0.77531, 0.35413, 0.81255, 0.32455, 0.70399, 0.18910, 0.64630, 0.27978, 0.71466,\n 0.13382, 0.68270, 0.33677, 0.64473, 0.42988, 0.46652, 0.45553, 0.54862, 0.43711, 0.55890,\n 0.46729, 0.52992, 0.41471, 0.33522, 0.37705, 0.32278, 0.34411, 0.32015, 0.31288, 0.32233,\n 0.28353, 0.33319, 0.24125, 0.38279, 0.10299, 0.46876, 0.26761, 0.42456, 0.29788, 0.43318,\n 0.33343, 0.43388, 0.36643, 0.42612, 0.39601, 0.41670, 0.42012, 0.41023, 0.00756, 0.48078,\n 0.43295, 0.56952, 0.45864, 0.47909, 0.47347, 0.54574, 0.47609, 0.56383, 0.46847, 0.55506,\n 0.43399, 0.58236, 0.48352, 0.56298, 0.48248, 0.57785, 0.42645, 0.38980, 0.43900, 0.39650,\n 0.45007, 0.40043, 0.28971, 0.36825, 0.27667, 0.36337, 0.51786, 0.47195, 0.71029, 0.38076,\n 0.52623, 0.57391, 0.89509, 0.25414, 0.63407, 0.40958, 0.66124, 0.41302, 0.68888, 0.40946,\n 0.72534, 0.38913, 0.60663, 0.40370, 0.65477, 0.34401, 0.62991, 0.34608, 0.68068, 0.34727,\n 0.70210, 0.35359, 0.75221, 0.41080, 0.60292, 0.84286, 0.71990, 0.37560, 0.89369, 0.39996,\n 0.79008, 0.39135, 0.64400, 0.53449, 0.52825, 0.65040, 0.52585, 0.68019, 0.56022, 0.65723,\n 0.58538, 0.66654, 0.54963, 0.68086, 0.57123, 0.68269, 0.62485, 0.72810, 0.51305, 0.54728,\n 0.51510, 0.52725, 0.74225, 0.31451, 0.59863, 0.45498, 0.57034, 0.54858, 0.57863, 0.53362,\n 0.72309, 0.53205, 0.51645, 0.49964, 0.66280, 0.28292, 0.70362, 0.29327, 0.83071, 0.19381,\n 0.55239, 0.30257, 0.60761, 0.35389, 0.64543, 0.69671, 0.93270, 0.73011, 0.55726, 0.57283,\n 0.54290, 0.58479, 0.61803, 0.69471, 0.60759, 0.69420, 0.72294, 0.27196, 0.57741, 0.56317,\n 0.61408, 0.28139, 0.61691, 0.25589, 0.66851, 0.11991, 0.77009, 0.23202, 0.63554, 0.18925,\n 0.77039, 0.29956, 0.82672, 0.27875, 0.52712, 0.66620, 0.55317, 0.66853, 0.57724, 0.67389,\n 0.55469, 0.58007, 0.61190, 0.69396, 0.59696, 0.70654, 0.59637, 0.69395, 0.53996, 0.55714,\n 0.56884, 0.69237, 0.54782, 0.69237, 0.52461, 0.69237, 0.53409, 0.77914, 0.52767, 0.73623,\n 0.52691, 0.71786, 0.52688, 0.70463, 0.52697, 0.69528, 0.57206, 0.69528, 0.57352, 0.70354,\n 0.57684, 0.71185, 0.58169, 0.72006, 0.60994, 0.63991, 0.98605, 0.56003, 0.58680, 0.69540,\n 0.59037, 0.70182, 0.53192, 0.60154, 0.57727, 0.58593, 0.53692, 0.59379, 0.62754, 0.47335,\n 0.66559, 0.49595, 0.58835, 0.54686, 0.75782, 0.14768, 0.70925, 0.20151, 0.67268, 0.25658,\n 0.60041, 0.74900, 0.55827, 0.26167, 0.57030, 0.18787, 0.58817, 0.10904, 0.71105, 0.39895,\n 0.78107, 0.43541, 0.58725, 0.39893, 0.74287, 0.35545, 0.57216, 0.43765, 0.55187, 0.53657,\n 0.82144, 0.45756, 0.75270, 0.45718, 0.71376, 0.46763, 0.66711, 0.46067, 0.63110, 0.44715,\n 0.60086, 0.43247, 0.52348, 0.40563, 0.81075, 0.52393, 0.77105, 0.34896, 0.50913, 0.56272,\n 0.59529, 0.48502, 0.98053, 0.40156, 0.57350, 0.42000, 0.60299, 0.54869, 0.73353, 0.37698,\n 0.56061, 0.51902, 0.96769, 0.64436, 0.58098, 0.38716, 0.53773, 0.50538, 0.76097, 0.77975,\n 0.80178, 0.83194, 0.89244, 0.54076, 0.81635, 0.74026, 0.86560, 0.33369, 0.61407, 0.88325,\n 0.50895, 0.57944, 0.61794, 0.50832, 0.82561, 0.39768, 0.68122, 0.39624, 0.65664, 0.40060,\n 0.60390, 0.71022, 0.81209, 0.58854, 0.56801, 0.94456, 0.68101, 0.89829, 0.73375, 0.86970,\n 0.63383, 0.39882, 0.60679, 0.39554, 0.58966, 0.39106, 0.80502, 0.34211, 0.61133, 0.36228,\n 0.63404, 0.35597, 0.65664, 0.35536, 0.68122, 0.35834, 0.69859, 0.36316, 0.94187, 0.31908,\n 0.69859, 0.38745, 0.58418, 0.62411, 0.55432, 0.56608, 0.53415, 0.62064, 0.71122, 0.81998,\n 0.66463, 0.85287, 0.55910, 0.90263, 0.87171, 0.79194, 0.59123, 0.37389, 0.54434, 0.45158,\n 0.62456, 0.92419, 0.88577, 0.61503, 0.55134, 0.69528, 0.55198, 0.70463, 0.55289, 0.71581,\n 0.55517, 0.73079, 0.56994, 0.76704, 0.59320, 0.68568, 0.59926, 0.68107, 0.60760, 0.67770,\n 0.63194, 0.66350, 0.75203, 0.60132, 0.54723, 0.42039, 0.56354, 0.35983, 0.58384, 0.36871,\n 0.58661, 0.69237, 0.77192, 0.68358, 0.53160, 0.35248, 0.58837, 0.80444, 0.52080, 0.44256,\n 0.56798, 0.49348, 0.54328, 0.81926, 0.65532, 0.74551, 0.62101, 0.57402, 0.62556, 0.78031,\n 0.68020, 0.57072, 0.64276, 0.60434, 0.70466, 0.62153, 0.55201, 0.86259, 0.58907, 0.50864,\n 0.68595, 0.77536, 0.64573, 0.81264, 0.67534, 0.70398, 0.81086, 0.64631, 0.72012, 0.71467,\n 0.86615, 0.68271, 0.66319, 0.64460, 0.57008, 0.46633, 0.54456, 0.54838, 0.56276, 0.55878,\n 0.53199, 0.53014, 0.58527, 0.33518, 0.62295, 0.32278, 0.65590, 0.32016, 0.68713, 0.32235,\n 0.71648, 0.33320, 0.75876, 0.38279, 0.89701, 0.46877, 0.73239, 0.42455, 0.70211, 0.43316,\n 0.66653, 0.43387, 0.63350, 0.42609, 0.60388, 0.41659, 0.57966, 0.40995, 0.99244, 0.48078,\n 0.56719, 0.56942, 0.54137, 0.47890, 0.52656, 0.54612, 0.52391, 0.56383, 0.53153, 0.55506,\n 0.56604, 0.58233, 0.51631, 0.56305, 0.51747, 0.57788, 0.57359, 0.38981, 0.56070, 0.39533,\n 0.54976, 0.39975, 0.71029, 0.36825, 0.72333, 0.36337,\n])\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,uBAAuB;AAGzB,IAAM,SAAS,SAAS,IAAI;AAE5B,IAAM,YAAY;AAAA,EACrB,QAAQ,SAAS,yBAAyB;AAAA,EAC1C,SAAS,SAAS,kCAAkC;AAAA,EACpD,MAAM,SAAS,sBAAsB;AACzC;AAGO,IAAM,UAAU;AAIvB,IAAI,UAAmC;AAGhC,SAAS,gBAAkC;AAC9C,cAAY,gBAAgB,eAAe,MAAM,EAAE,MAAM,CAAC,MAAe;AACrE,cAAU;AACV,UAAM;AAA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F;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EACjF;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EACjF;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EACjF;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EACjF;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EACjF;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AAAA,EAAS;AACjD,CAAC;","names":["fileset","fileset","now","a"]}
|
|
1
|
+
{"version":3,"sources":["../src/segmenter.ts","../src/mp.ts","../src/mp-clock.ts","../src/face.ts","../src/detect-remote.ts","../src/wasm.ts","../src/gpu-guard.ts","../src/mask-merge.ts","../src/engine.ts","../src/pipeline.ts","../src/scene.ts","../src/facemesh.ts"],"sourcesContent":["import { ImageSegmenter } from \"@mediapipe/tasks-vision\"\nimport { MODEL_URL, visionFileset } from \"./mp\"\nimport { monotonicClock } from \"./mp-clock\"\n\n/**\n * Person segmentation, on the GPU, with the mask staying on the GPU.\n *\n * ── The two facts that decide the whole design ───────────────────────────────────────\n *\n * 1. **It shares the WebGL context with mediakit.** `createFromOptions` is given the very\n * canvas the Device took its context from, so `getAsWebGLTexture()` returns a texture\n * mediakit can sample directly. With separate contexts the mask would have to be read back\n * to the CPU and uploaded again - the most expensive round trip in the pipeline, for data\n * that was already in the right place.\n *\n * The price is that MediaPipe changes GL state behind mediakit's back. That is handled in\n * `ResetState` in `gpu/webgl/device.go` - read the comment there before changing anything\n * here.\n *\n * 2. **Assets are served from the consuming origin.** Everything lives under `/mediakit/`,\n * which the host app copies out of this package's `dist/`. Nothing is fetched from a third\n * party while a frame is being processed - that is gate P0.8.\n */\n\n/** Which model: `person` is the selfie segmenter, person against background, 244 kB. */\nexport type SegmenterModel = \"person\" | \"classes\"\n\nexport interface Segmenter {\n /** The raw mask as a WebGLTexture, or null when this frame produced no result. */\n segment(frame: VideoFrame, timestampMs: number): WebGLTexture | null\n /**\n * Hand the last result's buffer back to MediaPipe.\n *\n * Call it AFTER mediakit is done with the texture, not before. Closing the result and then\n * sampling the texture reads a buffer that has gone back to the shared pool - it may still\n * hold the same mask, or it may hold another frame's. Neither reports anything.\n *\n * Not calling it breaks differently: MediaPipe runs out of buffers after a few dozen\n * frames, quietly stops returning masks, and the effect freezes on the last one it managed.\n */\n release(): void\n close(): void\n}\n\n/**\n * Build a segmenter on the canvas mediakit is drawing to.\n *\n * `canvas` must be the EXACT canvas whose `WebGL2RenderingContext` was passed to `core.init` -\n * see reason 1 above.\n */\nexport async function createSegmenter(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n model: SegmenterModel = \"person\",\n): Promise<Segmenter> {\n const fileset = await visionFileset()\n\n const segmenter = await ImageSegmenter.createFromOptions(fileset, {\n baseOptions: {\n modelAssetPath: MODEL_URL[model],\n // MediaPipe's GPU delegate runs on WebGL2, which Chrome, Safari and Firefox all\n // have. That is why mediakit picked MediaPipe over ONNX Runtime Web at P1: ORT's\n // fast path is WebGPU, which Firefox only has on Windows.\n delegate: \"GPU\",\n },\n canvas,\n runningMode: \"VIDEO\",\n // Category mask, not a confidence mask. The values are category INDICES, so they need\n // normalising before they can act as alpha - MaskGain and MaskInvert in `core/graph.go`\n // do that.\n outputCategoryMask: true,\n outputConfidenceMasks: false,\n })\n\n const clock = monotonicClock()\n // The open result, held until mediakit is done with its texture.\n let pending: { close(): void } | null = null\n\n const release = () => {\n pending?.close()\n pending = null\n }\n\n return {\n segment(frame, timestampMs) {\n // The previous result was never given back - the caller forgot to release, or the\n // frame before threw part way through. Give it back now rather than leak until the\n // pool runs dry.\n release()\n\n let texture: WebGLTexture | null = null\n // This callback is SYNCHRONOUS - it finishes before segmentForVideo returns. That\n // is also why the call blocks the event loop for tens of milliseconds, and why\n // mediakit has a governor at all: the cheapest way to make it faster is to call it\n // less often.\n segmenter.segmentForVideo(frame, clock(timestampMs), (result) => {\n const mask = result.categoryMask\n if (mask) texture = mask.getAsWebGLTexture()\n // NOT closed here - the texture has to outlive core.process(). See release().\n pending = result\n })\n return texture\n },\n release,\n close() {\n release()\n segmenter.close()\n },\n }\n}\n\n/** A category mask read back to bytes: one category index per pixel, row 0 at the top. */\nexport interface MaskBytes {\n width: number\n height: number\n data: Uint8Array\n}\n\n/**\n * A segmenter for a worker of its own: it reads the mask back instead of lending a texture, since\n * a texture cannot leave its context. The read happens there, off the frame path.\n */\nexport async function createMaskReader(\n canvas: OffscreenCanvas,\n model: SegmenterModel,\n delegate: \"GPU\" | \"CPU\",\n): Promise<{ read(frame: OffscreenCanvas, timestampMs: number): MaskBytes | null; close(): void }> {\n const fileset = await visionFileset()\n const segmenter = await ImageSegmenter.createFromOptions(fileset, {\n baseOptions: { modelAssetPath: MODEL_URL[model], delegate },\n canvas,\n runningMode: \"VIDEO\",\n outputCategoryMask: true,\n outputConfidenceMasks: false,\n })\n const clock = monotonicClock()\n return {\n read(frame, timestampMs) {\n let out: MaskBytes | null = null\n segmenter.segmentForVideo(frame, clock(timestampMs), (result) => {\n const mask = result.categoryMask\n if (mask) out = { width: mask.width, height: mask.height, data: mask.getAsUint8Array().slice() }\n result.close()\n })\n return out\n },\n close() {\n segmenter.close()\n },\n }\n}\n","import { FilesetResolver } from \"@mediapipe/tasks-vision\"\nimport { ASSETS, assetUrl } from \"./assets\"\n\nexport const MP_DIR = assetUrl(\"mp\")\n\nexport const MODEL_URL = {\n person: assetUrl(\"selfie_segmenter.tflite\"),\n classes: assetUrl(\"selfie_multiclass_256x256.tflite\"),\n face: assetUrl(\"face_landmarker.task\"),\n} as const\n\n/** How long one detector may take to download and build before its effects are given up on. */\nexport const LOAD_MS = 60_000\n\ntype Fileset = Awaited<ReturnType<typeof FilesetResolver.forVisionTasks>>\n\nlet fileset: Promise<Fileset> | null = null\n\n/** The MediaPipe runtime paths, resolved once per realm. */\nexport function visionFileset(): Promise<Fileset> {\n fileset ??= FilesetResolver.forVisionTasks(MP_DIR).catch((e: unknown) => {\n fileset = null\n throw e\n })\n return fileset\n}\n\n/** A detector that did not come up within {@link LOAD_MS}. */\nexport class LoadTimeout extends Error {\n constructor(what: string, ms: number) {\n super(`mediakit: ${what} did not load within ${Math.round(ms / 1000)} s`)\n this.name = \"LoadTimeout\"\n }\n}\n\n/** `p`, or a LoadTimeout after `ms`; what `p` brings after that goes to `late`. */\nexport function withTimeout<T>(p: Promise<T>, ms: number, what: string, late: (v: T) => void): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let done = false\n const timer = setTimeout(() => {\n done = true\n reject(new LoadTimeout(what, ms))\n }, ms)\n p.then(\n (v) => {\n if (done) late(v)\n else {\n done = true\n clearTimeout(timer)\n resolve(v)\n }\n },\n (e: unknown) => {\n if (done) return\n done = true\n clearTimeout(timer)\n reject(e)\n },\n )\n })\n}\n\n/** Which detectors {@link preloadDetectors} fetches; the MediaPipe runtime comes with any of them. */\nexport interface PreloadParts {\n person?: boolean\n classes?: boolean\n face?: boolean\n cover?: boolean\n}\n\nexport interface PreloadProgress {\n loaded: number\n total: number\n done: number\n files: number\n}\n\nconst PROGRESS_MS = 100\n\n/**\n * Warm the HTTP cache with the MediaPipe runtime and the chosen models, at low priority, so the\n * first recipe that needs them builds without waiting on the network. Never rejects.\n */\nexport async function preloadDetectors(\n parts: PreloadParts = { person: true, classes: true, face: true },\n onProgress?: (p: PreloadProgress) => void,\n): Promise<void> {\n const urls: string[] = []\n if (parts.cover) for (const a of ASSETS) if (a.part === \"cover\") urls.push(assetUrl(a.path))\n if (parts.person || parts.classes || parts.face) {\n try {\n const fs = await visionFileset()\n urls.push(fs.wasmBinaryPath, fs.wasmLoaderPath)\n for (const k of [\"person\", \"classes\", \"face\"] as const) if (parts[k]) urls.push(MODEL_URL[k])\n } catch {}\n }\n const p: PreloadProgress = { loaded: 0, total: 0, done: 0, files: urls.length }\n const sizes: (number | null | undefined)[] = urls.map(() => undefined)\n let told = 0\n let broken = false\n const tell = (force: boolean) => {\n if (!onProgress || broken) return\n const now = performance.now()\n if (!force && now - told < PROGRESS_MS) return\n told = now\n const known = sizes.every((n) => n !== null && n !== undefined)\n const total = known ? sizes.reduce<number>((a, n) => a + (n ?? 0), 0) : 0\n try {\n onProgress({ ...p, total, loaded: total ? Math.min(p.loaded, total) : p.loaded })\n } catch (e) {\n broken = true\n console.error(\"mediakit: onProgress threw, no more progress from this preload\", e)\n }\n }\n tell(true)\n await Promise.all(\n urls.map(async (u, i) => {\n try {\n const r = await fetch(u, { priority: \"low\" } as RequestInit)\n if (!r.ok) {\n sizes[i] = 0\n await r.body?.cancel()\n } else {\n const encoding = r.headers.get(\"content-encoding\")\n const length = Number(r.headers.get(\"content-length\"))\n sizes[i] = (!encoding || encoding === \"identity\") && length > 0 ? length : null\n const reader = r.body?.getReader()\n if (reader) {\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n p.loaded += value.byteLength\n tell(false)\n }\n }\n }\n } catch {\n sizes[i] ??= 0\n }\n p.done++\n tell(true)\n }),\n )\n}\n","const SOURCE_SWITCH_GAP_MS = 33\n\nexport function monotonicClock(): (timestampMs: number) => number {\n let offset = 0\n let last = -Infinity\n return (timestampMs) => {\n let t = timestampMs + offset\n if (t <= last) {\n offset += last + SOURCE_SWITCH_GAP_MS - t\n t = last + SOURCE_SWITCH_GAP_MS\n }\n last = t\n return t\n }\n}\n","import { FaceLandmarker } from \"@mediapipe/tasks-vision\"\nimport { monotonicClock } from \"./mp-clock\"\nimport { MODEL_URL, visionFileset } from \"./mp\"\n\n/**\n * Face landmark detection.\n *\n * Separate from `segmenter.ts` because the two detectors are INDEPENDENT costs: whitening\n * teeth does not need a person mask, replacing a background does not need to know where the\n * eyes are. This one loads only when the recipe actually asks for it - the model is ~3.7 MB,\n * fifteen times the segmentation one.\n *\n * Landmarks are NOT interpreted here. They are written straight into the Go core's buffer, and\n * every region derivation and all the smoothing live in `core/face`. The reason is in that\n * package's header: the hard part is not the coordinate transform, it is deciding when a\n * region is allowed to move - a control problem, not a geometry one.\n */\n\n\nexport interface FaceDetector {\n /**\n * Write every face's landmarks into `out`, back to back, and return how many cells were\n * written. 0 means no face.\n *\n * `out` is allocated by the Go core - writing straight into it avoids one new array per\n * frame - and its length is what bounds how many faces fit.\n */\n detect(frame: TexImageSource | OffscreenCanvas, timestampMs: number, out: Float32Array): number\n close(): void\n}\n\n/** Floats per face: FaceLandmarker's 478 points times x, y, z. Mirrors `face.Floats` in Go. */\nexport const FACE_FLOATS = 478 * 3\n\nexport const COVER_SIZE = 96\n\nexport type Box = [number, number, number, number]\n\nexport function faceBox(lm: Float32Array, at: number): Box {\n let x0 = 1\n let y0 = 1\n let x1 = 0\n let y1 = 0\n for (let i = at; i < at + FACE_FLOATS; i += 3) {\n x0 = Math.min(x0, lm[i]!)\n x1 = Math.max(x1, lm[i]!)\n y0 = Math.min(y0, lm[i + 1]!)\n y1 = Math.max(y1, lm[i + 1]!)\n }\n return [x0, y0, x1 - x0, y1 - y0]\n}\n\n/**\n * `maxFaces` comes from the Go core's buffer (its length over FACE_FLOATS), so the number of\n * faces tracked is decided in one place.\n */\nexport async function createFaceDetector(\n canvas: HTMLCanvasElement | OffscreenCanvas,\n maxFaces: number,\n delegate: \"GPU\" | \"CPU\" = \"GPU\",\n mode: \"VIDEO\" | \"IMAGE\" = \"VIDEO\",\n): Promise<FaceDetector> {\n const fileset = await visionFileset()\n\n const landmarker = await FaceLandmarker.createFromOptions(fileset, {\n baseOptions: { modelAssetPath: MODEL_URL.face, delegate },\n canvas,\n runningMode: mode,\n // As many as the core tracks: one landmark pass returns them all, so the cost of a second\n // face is the copy below and its own shader passes, not a second inference.\n numFaces: maxFaces,\n // No blendshapes and no transformation matrix - extra work for data nobody reads.\n outputFaceBlendshapes: false,\n outputFacialTransformationMatrixes: false,\n })\n\n const clock = monotonicClock()\n return {\n detect(frame, timestampMs, out) {\n const res = mode === \"VIDEO\" ? landmarker.detectForVideo(frame, clock(timestampMs)) : landmarker.detect(frame)\n let n = 0\n for (const lm of res.faceLandmarks ?? []) {\n // Whole faces only: a face cut off by the end of the buffer would parse as garbage.\n if (lm.length * 3 !== FACE_FLOATS || n + FACE_FLOATS > out.length) break\n for (let i = 0; i < lm.length; i++) {\n const p = lm[i]\n out[n + i * 3] = p.x\n out[n + i * 3 + 1] = p.y\n out[n + i * 3 + 2] = p.z\n }\n n += FACE_FLOATS\n }\n return n\n },\n close() {\n landmarker.close()\n },\n }\n}\n","import type { DetectReply, DetectRequest } from \"./detect-worker/entry\"\nimport { LOAD_MS, LoadTimeout } from \"./mp\"\nimport type { SegmenterModel } from \"./segmenter\"\nimport { assetUrl } from \"./assets\"\n\nconst DETECT_WORKER_URL = assetUrl(\"detect-worker.js\")\n\ntype Kind = \"face\" | \"mask\"\n\nexport interface DetectHandlers {\n face(tsUs: number, n: number, lm: Float32Array, ms: number, cover: Uint8Array | null, rects: Float32Array | null): void\n mask(tsUs: number, width: number, height: number, data: Uint8Array, ms: number): void\n /** That kind stopped working after it was ready; the caller detects in-thread from now on. */\n failed(kind: Kind, reason: string): void\n cover(ok: boolean, message: string): void\n}\n\n/**\n * Detection in a worker of its own. At most one frame in flight per kind: a request while one is\n * pending is dropped, and the regions or the last mask carry on until the answer lands.\n */\nexport class DetectWorker {\n private worker: Worker | null\n private readonly ready = new Map<Kind, { resolve(): void; reject(e: Error): void; timer: ReturnType<typeof setTimeout> }>()\n private readonly up = new Set<Kind>()\n private readonly busy = new Set<Kind>()\n\n constructor(private readonly on: DetectHandlers) {\n this.worker = new Worker(DETECT_WORKER_URL)\n this.worker.onerror = (e) => this.failAll(e.message || \"detect worker failed to load\")\n this.worker.onmessage = (e: MessageEvent<DetectReply>) => this.receive(e.data)\n }\n\n initFace(maxFaces: number): Promise<void> {\n return this.init(\"face\", { t: \"initFace\", maxFaces })\n }\n\n initMask(model: SegmenterModel): Promise<void> {\n return this.init(\"mask\", { t: \"initMask\", model })\n }\n\n /** Whether `request` would take a frame of this kind now. */\n accepts(kind: Kind): boolean {\n return this.worker !== null && this.up.has(kind) && !this.busy.has(kind)\n }\n\n /** Transfers the frame. False when that kind is busy or not up; the frame is then closed. */\n request(kind: Kind, frame: VideoFrame, tsUs: number, cover = false, retry: [number, number, number] | null = null): boolean {\n if (!this.accepts(kind)) {\n frame.close()\n return false\n }\n this.busy.add(kind)\n this.send(kind === \"face\" ? { t: kind, frame, tsUs, cover, retry } : { t: kind, frame, tsUs }, [frame])\n return true\n }\n\n isUp(kind: Kind): boolean {\n return this.up.has(kind)\n }\n\n close(): void {\n this.send({ t: \"close\" })\n this.worker = null\n for (const kind of [...this.ready.keys()]) this.settle(kind, new Error(\"closed\"))\n this.up.clear()\n }\n\n private init(kind: Kind, m: DetectRequest): Promise<void> {\n if (this.up.has(kind)) return Promise.resolve()\n return new Promise((resolve, reject) => {\n if (!this.worker) {\n reject(new Error(\"detect worker gone\"))\n return\n }\n const timer = setTimeout(() => this.settle(kind, new LoadTimeout(`${kind} detection`, LOAD_MS)), LOAD_MS)\n this.ready.set(kind, { resolve, reject, timer })\n this.send(m)\n })\n }\n\n private receive(m: DetectReply): void {\n switch (m.t) {\n case \"ready\":\n this.up.add(m.kind)\n this.settle(m.kind)\n break\n case \"error\":\n if (this.ready.has(m.kind)) this.settle(m.kind, new Error(m.message))\n else this.fail(m.kind, m.message)\n break\n case \"face\":\n this.busy.delete(\"face\")\n if (this.up.has(\"face\")) this.on.face(m.tsUs, m.n, m.lm, m.ms, m.cover, m.rects)\n break\n case \"cover\":\n this.on.cover(m.ok, m.message)\n break\n case \"mask\":\n this.busy.delete(\"mask\")\n if (this.up.has(\"mask\") && m.width > 0) this.on.mask(m.tsUs, m.width, m.height, m.data, m.ms)\n break\n }\n }\n\n private settle(kind: Kind, err?: Error): void {\n const r = this.ready.get(kind)\n if (!r) return\n this.ready.delete(kind)\n clearTimeout(r.timer)\n if (err) r.reject(err)\n else r.resolve()\n }\n\n private fail(kind: Kind, reason: string): void {\n if (!this.up.delete(kind)) return\n this.busy.delete(kind)\n this.on.failed(kind, reason)\n }\n\n private failAll(reason: string): void {\n this.worker?.terminate()\n this.worker = null\n for (const kind of [...this.ready.keys()]) this.settle(kind, new Error(reason))\n for (const kind of [...this.up]) this.fail(kind, reason)\n }\n\n private send(m: DetectRequest, transfer: Transferable[] = []): void {\n this.worker?.postMessage(m, transfer)\n }\n}\n","/**\n * Loads the Go core.\n *\n * The core is built from this repo for `GOOS=js GOARCH=wasm`. It never touches a pixel: every\n * frame, mask and texture crosses into it as a handle, and the per-pixel work happens in the\n * WebGL2 shaders it drives. See `doc/apps/mediakit/PLAN.md` section 2.\n */\n\nimport type { CoreRecipe } from \"./recipe\"\nimport type { CoreLayer } from \"./layout\"\nimport { assetUrl } from \"./assets\"\n\n/** The surface the Go core exports. Matches `wasmjs/main.go`. */\nexport interface MediakitCore {\n /** Empty string on success, an error message otherwise. */\n init(gl: WebGL2RenderingContext, width: number, height: number): string\n /** Takes an object with NAMED fields - see `setRecipe` in wasmjs/main.go. */\n setRecipe(recipe: CoreRecipe): string\n /** Shared array to write landmarks into. Allocated once, by the core. */\n faceBuffer(): Float32Array | null\n /** Commit the landmarks just written. n = cell count; 0 means no face this frame. */\n setFace(usLo: number, usHi: number, n: number): string\n setDebug(view: number): string\n /** The first background shader link that failed, empty while none has. */\n programError?(): string\n /** Never link a face colour shader again; `reason` becomes the programError. */\n disableFaceColor?(reason: string): void\n /** How many face colour shaders the driver is still linking. */\n linking?(): number\n /** How many face colour links were started, failed ones included. */\n links?(): number\n /** Returns 1 when the coming frame NEEDS segmentation. */\n decide(usLo: number, usHi: number, prevTotalMs: number, prevSegMs: number): number\n /** Returns 1 when the coming frame needs landmark detection. Reads back decide's verdict. */\n decideFace(): number\n /**\n * Returns the GL call count for this frame - the P0.2 gate is measured from it - or 0 when\n * nothing was drawn and the source frame has to be shown instead.\n */\n /** `maskKind` is what `mask` carries: 0 a person mask, 1 the multiclass categories. */\n process(frame: unknown, mask: unknown, background: unknown, maskKind?: number, maskUsLo?: number, maskUsHi?: number): number\n /** Hand the colour LUT image over once; null clears it. Not per frame - see Pipeline.SetLut. */\n setLut(image: unknown): string\n /** Hand the makeup texture over once; null clears it. See Pipeline.SetMakeup. */\n setMakeup(image: unknown): string\n setFaceCover(image: unknown): string\n /** Hand the pink whitening table over once; null clears it. See Pipeline.SetSkinLut. */\n setSkinLut(image: unknown): string\n /** 16 cells - layout in `statsFloats` in wasmjs/main.go. */\n stats(): Float32Array | null\n close(): void\n\n // The scene compositor - `sceneState` in wasmjs/main.go. One core runs either a camera\n // pipeline or a scene in practice, but the two do not share state.\n sceneInit(gl: WebGL2RenderingContext, width: number, height: number): string\n sceneBackground(r: number, g: number, b: number): string\n /** Copy one source's picture into its slot; null empties the slot. */\n sceneUpload(slot: number, image: unknown, width: number, height: number): string\n sceneSet(layers: CoreLayer[], usLo: number, usHi: number, animateMs: number): string\n sceneSwitch(layers: CoreLayer[], usLo: number, usHi: number, transition: number, durationMs: number): string\n /** GL call count of the frame, 0 once closed. */\n sceneRender(usLo: number, usHi: number): number\n sceneClose(): string\n}\n\n// Declared on globalThis rather than Window: the same two names have to be reachable from a\n// DedicatedWorker, where Window does not exist.\ndeclare global {\n var Go:\n | (new () => {\n importObject: WebAssembly.Imports\n run(instance: WebAssembly.Instance): Promise<void>\n })\n | undefined\n var __mediakitAttach: ((core: MediakitCore) => void) | undefined\n}\n\nconst WASM_URL = assetUrl(\"mediakit.wasm\")\nconst EXEC_URL = assetUrl(\"wasm_exec.js\")\n\nlet execLoaded: Promise<void> | null = null\nlet compiled: Promise<WebAssembly.Module> | null = null\n\n/**\n * `wasm_exec.js` is the shim Go ships, and it MUST come from the same Go release that built\n * the `.wasm`. A skew between them is not a compile error: it surfaces at runtime, with a\n * message that points nowhere near the cause. Both files travel in this package's `dist/` and\n * the consumer copies them in one step, so never update one alone.\n */\n//\n// Two ways in, because a worker has no document. The script tag stays the main-thread path\n// because it is the one that has been running; a worker takes the dynamic import instead.\n// wasm_exec.js is an IIFE that assigns globalThis.Go, so importing it for its side effect is\n// enough - it exports nothing.\nfunction loadExec(): Promise<void> {\n if (execLoaded) return execLoaded\n execLoaded = (async () => {\n if (globalThis.Go) return\n const workerLoad = (globalThis as { importScripts?: (url: string) => void }).importScripts\n if (typeof workerLoad === \"function\") {\n // A CLASSIC worker. It has to be classic, because MediaPipe loads its own wasm glue\n // with importScripts() and a module worker forbids that - so the Go shim comes in\n // the same way rather than through a dynamic import.\n workerLoad.call(globalThis, EXEC_URL)\n } else if (typeof document === \"undefined\") {\n await import(/* webpackIgnore: true */ EXEC_URL)\n } else {\n await new Promise<void>((resolve, reject) => {\n const el = document.createElement(\"script\")\n el.src = EXEC_URL\n el.async = true\n el.onload = () => resolve()\n el.onerror = () => reject(new Error(`mediakit: cannot load ${EXEC_URL}`))\n document.head.appendChild(el)\n })\n }\n if (!globalThis.Go) throw new Error(\"mediakit: wasm_exec.js did not define Go\")\n })()\n return execLoaded\n}\n\n/**\n * Compile the module ONCE, then instantiate it as often as needed.\n *\n * Compiling is the expensive half; instantiating is cheap. Each instance gets its own memory\n * and its own globals, so two pipelines running side by side cannot tread on each other.\n */\nfunction compileModule(): Promise<WebAssembly.Module> {\n if (compiled) return compiled\n compiled = (async () => {\n const res = await fetch(WASM_URL)\n if (!res.ok) {\n throw new Error(\n `mediakit: cannot load ${WASM_URL} (HTTP ${res.status}) - ` +\n \"the host has to serve this package's dist/ under /mediakit/\",\n )\n }\n return WebAssembly.compileStreaming(res)\n })()\n return compiled\n}\n\n/**\n * Bring up one independent mediakit core.\n *\n * `go.run()` NEVER resolves: the core's `main()` ends in `select{}` to keep the runtime alive,\n * because a Go/wasm program exits when main returns and exiting turns every registered\n * function into a call into a dead runtime. So wait for the attach callback rather than\n * awaiting `go.run()`.\n */\nexport async function loadCore(): Promise<MediakitCore> {\n await loadExec()\n const mod = await compileModule()\n\n const Go = globalThis.Go!\n const go = new Go()\n const instance = await WebAssembly.instantiate(mod, go.importObject)\n\n return new Promise<MediakitCore>((resolve, reject) => {\n const timer = setTimeout(\n () => reject(new Error(\"mediakit: core did not attach within 10s\")),\n 10_000,\n )\n globalThis.__mediakitAttach = (core) => {\n clearTimeout(timer)\n delete globalThis.__mediakitAttach\n resolve(core)\n }\n void go.run(instance).catch((e: unknown) => {\n clearTimeout(timer)\n reject(e instanceof Error ? e : new Error(String(e)))\n })\n })\n}\n\n/** Split a microsecond count into the two 32-bit halves `decide` takes. */\nexport function splitMicros(us: number): [number, number] {\n const lo = us >>> 0\n const hi = Math.floor(us / 2 ** 32)\n return [lo, hi | 0]\n}\n","/** When a lost WebGL context happened: building the core's shaders, linking a face colour shader, or later. */\nexport type LossPhase = \"init\" | \"link\" | \"run\"\n\n/** What this browser remembers about a GPU that lost its context under mediakit. */\nexport interface GpuRecord {\n /** Lost the context building the core's shaders: mediakit does not start on it. */\n init: boolean\n /** Lost the context linking a face colour shader: makeup and teeth stay off on it. */\n faceColor: boolean\n /** When the last loss was recorded, ms since the epoch. */\n at: number\n}\n\nconst KEY = \"mediakit-gpu-guard\"\nconst TTL_MS = 3 * 24 * 3600 * 1000\n\ntype Store = Record<string, GpuRecord>\n\nfunction storage(): Storage | null {\n try {\n return typeof localStorage === \"undefined\" ? null : localStorage\n } catch {\n return null\n }\n}\n\nfunction load(): Store {\n const s = storage()\n if (!s) return {}\n try {\n const parsed: unknown = JSON.parse(s.getItem(KEY) ?? \"{}\")\n return parsed && typeof parsed === \"object\" ? (parsed as Store) : {}\n } catch {\n return {}\n }\n}\n\nfunction save(store: Store): void {\n try {\n storage()?.setItem(KEY, JSON.stringify(store))\n } catch {\n return\n }\n}\n\n/** The record for `gpu`, null when there is none, it expired, or this realm has no localStorage. */\nexport function gpuRecord(gpu: string): GpuRecord | null {\n if (!gpu) return null\n const r = load()[gpu]\n if (!r || typeof r.at !== \"number\" || Date.now() - r.at > TTL_MS) return null\n return { init: r.init === true, faceColor: r.faceColor === true, at: r.at }\n}\n\n/** Remember a loss on `gpu`; a \"run\" loss is a reset or a reclaim, not a shader, and is not kept. */\nexport function recordLoss(gpu: string, phase: LossPhase): void {\n if (!gpu || phase === \"run\" || !storage()) return\n const store = load()\n const was = gpuRecord(gpu)\n store[gpu] = {\n init: phase === \"init\" || (was?.init ?? false),\n faceColor: phase === \"link\" || (was?.faceColor ?? false),\n at: Date.now(),\n }\n save(store)\n}\n\n/** Forget every GPU failure this browser remembers - for a \"try again\" after a driver update. */\nexport function forgetGpuFailures(): void {\n try {\n storage()?.removeItem(KEY)\n } catch {\n return\n }\n}\n\n/** The renderer name a WebGL2 context reports, \"\" when the browser hides it or the context is gone. */\nexport function rendererOf(gl: WebGL2RenderingContext): string {\n if (gl.isContextLost()) return \"\"\n const info = gl.getExtension(\"WEBGL_debug_renderer_info\")\n return String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? \"\")\n}\n\n/** A WebGL context lost while mediakit was building or linking its shaders. */\nexport class GpuLostError extends Error {\n constructor(\n readonly phase: LossPhase,\n readonly gpu: string,\n readonly detail = \"\",\n ) {\n super(`mediakit: the WebGL context was lost ${phase === \"init\" ? \"building the shaders\" : phase === \"link\" ? \"linking a makeup shader\" : \"while running\"}${detail ? ` (${detail})` : \"\"} [GPU: ${gpu || \"unknown\"}]`)\n this.name = \"GpuLostError\"\n }\n}\n","import type { MaskBytes } from \"./segmenter\"\n\nexport const CLASS_BACKGROUND = 0\nexport const CLASS_BODY_SKIN = 2\nexport const CLASS_CLOTHES = 4\nexport const CLASS_OTHERS = 5\nexport const CLASS_STALE_OCCLUDER = 6\n\nexport const THUMB_W = 64\nexport const THUMB_H = 36\nconst MOVED_LUMA = 12\n\nexport function lumaThumb(rgba: Uint8ClampedArray): Uint8Array {\n const y = new Uint8Array(THUMB_W * THUMB_H)\n for (let i = 0; i < y.length; i++) y[i] = (rgba[i * 4]! * 77 + rgba[i * 4 + 1]! * 150 + rgba[i * 4 + 2]! * 29) >> 8\n return y\n}\n\nexport function movedBetween(a: Uint8Array, b: Uint8Array): MaskBytes {\n const w = THUMB_W\n const h = THUMB_H\n const hit = new Uint8Array(w * h)\n for (let i = 0; i < hit.length; i++) hit[i] = Math.abs(a[i]! - b[i]!) > MOVED_LUMA ? 1 : 0\n const data = new Uint8Array(w * h)\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n let v = 0\n for (let dy = -1; dy <= 1 && !v; dy++) {\n const yy = y + dy\n if (yy < 0 || yy >= h) continue\n for (let dx = -1; dx <= 1; dx++) {\n const xx = x + dx\n if (xx >= 0 && xx < w && hit[yy * w + xx]) {\n v = 1\n break\n }\n }\n }\n data[y * w + x] = v\n }\n }\n return { width: w, height: h, data }\n}\n\nexport function mergeMasks(person: MaskBytes, classes: MaskBytes, out: Uint8Array | null, moved: MaskBytes | null = null): Uint8Array {\n const { width: w, height: h } = person\n const merged = out && out.length === w * h ? out : new Uint8Array(w * h)\n const cw = classes.width\n const ch = classes.height\n const sx = cw / w\n const sy = ch / h\n const mw = moved?.width ?? 0\n const mh = moved?.height ?? 0\n for (let y = 0; y < h; y++) {\n const crow = Math.min(ch - 1, Math.floor((y + 0.5) * sy)) * cw\n const mrow = moved ? Math.min(mh - 1, Math.floor(((y + 0.5) * mh) / h)) * mw : 0\n const prow = y * w\n for (let x = 0; x < w; x++) {\n if (person.data[prow + x] !== 0) {\n merged[prow + x] = CLASS_BACKGROUND\n continue\n }\n const c = classes.data[crow + Math.min(cw - 1, Math.floor((x + 0.5) * sx))]!\n if (c === CLASS_BACKGROUND) {\n merged[prow + x] = CLASS_CLOTHES\n continue\n }\n const stale = moved !== null && (c === CLASS_BODY_SKIN || c === CLASS_OTHERS) && moved.data[mrow + Math.min(mw - 1, Math.floor(((x + 0.5) * mw) / w))] !== 0\n merged[prow + x] = stale ? CLASS_STALE_OCCLUDER : c\n }\n }\n return merged\n}\n","import { createSegmenter, type MaskBytes, type Segmenter, type SegmenterModel } from \"./segmenter\"\nimport { COVER_SIZE, FACE_FLOATS, createFaceDetector, faceBox, type Box, type FaceDetector } from \"./face\"\nimport { DetectWorker, type DetectHandlers } from \"./detect-remote\"\nimport { loadCore, splitMicros, type MediakitCore } from \"./wasm\"\nimport { GpuLostError, gpuRecord, recordLoss, rendererOf, type LossPhase } from \"./gpu-guard\"\nimport { LOAD_MS, LoadTimeout, withTimeout } from \"./mp\"\nimport { lumaThumb, mergeMasks, movedBetween, THUMB_H, THUMB_W } from \"./mask-merge\"\nimport {\n NO_EFFECTS,\n coreRecipe,\n debugCode,\n needsFace,\n needsSegmentation,\n needsSkinClasses,\n type BgFilter,\n type DebugView,\n type Effects,\n} from \"./recipe\"\nimport { assetUrl } from \"./assets\"\n\n/**\n * One mediakit pipeline: canvas plus WebGL2 plus the Go core plus the detectors, which is\n * everything needed to turn a source frame into a processed one.\n *\n * The Engine does NOT know where a frame came from or where it goes - that is the transport's\n * job (`pipeline.ts`). They are separate because three browsers need three transports but all\n * three drive this same engine.\n */\n\nexport type PartState = \"off\" | \"loading\" | \"ready\" | \"failed\"\n\nexport interface PartStates {\n person: PartState\n classes: PartState\n face: PartState\n cover: PartState\n}\n\nexport type Part = keyof PartStates\n\nexport type PartErrors = Record<Part, string>\n\nexport const NO_PARTS: Readonly<PartStates> = Object.freeze({ person: \"off\", classes: \"off\", face: \"off\", cover: \"off\" })\n\nexport const NO_PART_ERRORS: Readonly<PartErrors> = Object.freeze({ person: \"\", classes: \"\", face: \"\", cover: \"\" })\n\nconst COVER_IN_THREAD = \"mediakit: the face cover runs only in the detect worker, and face detection runs in this thread; occluders stays off\"\n\nexport interface FrameStats {\n /** Total time spent on one frame, in milliseconds. */\n totalMs: number\n /** How much of that was segmentation. */\n segMs: number\n /** The last landmark detection; in its worker it no longer holds up the frame. */\n faceMs: number\n /** WebGL call count - the P0.2 gate in doc/apps/mediakit/PLAN.md. */\n glCalls: number\n /** Whether this frame ran segmentation or reused the previous mask. */\n segmented: boolean\n /** The resolution ratios the governor settled on. */\n maskScale: number\n workScale: number\n /** The autoframe window: centre and zoom, in UV coordinates. */\n cropCX: number\n cropCY: number\n cropZoom: number\n /** Whether the current recipe needs a person mask. */\n needsMask: boolean\n /** Whether a face is currently being tracked. */\n faceFound: boolean\n /** Face size as a fraction of frame height. */\n faceSize: number\n /** Whether the current recipe needs face landmarks. */\n needsFace: boolean\n /** The exposure lift auto light is applying, 0 when it is off or the room is bright. */\n autoExposure: number\n /** How many faces are being tracked. */\n faces: number\n /** Frames `syncFaces` holds back right now, sized to how long landmarks take; 0 when off. */\n heldFrames: number\n /** How old the landmarks behind this frame are, from the frame they were found on; 0 without landmarks. */\n faceAgeMs: number\n /** How old the segmentation mask behind this frame is; 0 without one. */\n maskAgeMs: number\n /** Why makeup and teeth are off while the rest runs (their shader failed to link); \"\" when none. */\n effectError: string\n parts: PartStates\n partErrors: PartErrors\n}\n\nconst ZERO_STATS: FrameStats = {\n totalMs: 0,\n segMs: 0,\n faceMs: 0,\n glCalls: 0,\n segmented: false,\n maskScale: 1,\n workScale: 1,\n cropCX: 0.5,\n cropCY: 0.5,\n cropZoom: 1,\n needsMask: false,\n faceFound: false,\n faceSize: 0,\n needsFace: false,\n autoExposure: 0,\n faces: 0,\n heldFrames: 0,\n faceAgeMs: 0,\n maskAgeMs: 0,\n effectError: \"\",\n parts: { ...NO_PARTS },\n partErrors: { ...NO_PART_ERRORS },\n}\n\nconst MAX_HOLD = 3\nconst COVER_FRAME_W = 256\nconst COVER_HOLD = 0.6\nconst COVER_MISSES = 2\nconst FOLLOW_SIDE = 384\nconst FOLLOW_MARGIN = 2.6\nconst FOLLOW_RETRY = 2\nconst FOLLOW_MIN_SIDE = 64\nconst FOLLOW_SHIFT = 0.06\nconst FOLLOW_RESIZE = 0.12\nconst FOLLOW_STALE_US = 500_000\nconst FOLLOW_KEPT_US = 1_000_000\nconst SCAN_SHARE = 0.5\nconst SCAN_STEP = 0.75\nconst FOLLOW_REFRESH = 30\nconst FOLLOW_WIDEN = 2\nconst FOLLOW_GROW = 3\nconst SAME_FACE = 0.3\nconst FACE_RESULTS_KEPT = 8\nconst THUMBS_KEPT = 12\nconst LINK_LOSS_WINDOW_MS = 3_000\nconst FACE_JUMP = 0.15\nconst CATCH_UP_EVERY_US = 1_000_000\nconst MASK_RESULTS_KEPT = 8\n\ntype MaskResult = { person: boolean; ts: number; width: number; height: number; data: Uint8Array; ms: number }\nconst DETECT_DUTY = 0.6\n\nfunction gpuName(gl: WebGL2RenderingContext): string {\n const info = gl.getExtension(\"WEBGL_debug_renderer_info\")\n const name = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? \"unknown\")\n return gl.isContextLost() ? `${name}, context lost` : name\n}\n\n// A worker has no document, so the Engine has to accept the canvas it is handed rather than\n// make one. segmenter.ts and face.ts already took this union - this is the last place that did\n// not.\nexport type EngineCanvas = HTMLCanvasElement | OffscreenCanvas\n\nfunction sourceSize(source: TexImageSource): [number, number] {\n if (source instanceof VideoFrame) return [source.displayWidth, source.displayHeight]\n if (typeof HTMLVideoElement !== \"undefined\" && source instanceof HTMLVideoElement) return [source.videoWidth, source.videoHeight]\n const s = source as { width: number; height: number }\n return [s.width, s.height]\n}\n\nfunction tileGrid(sw: number, sh: number): { side: number; step: number; nx: number; ny: number } {\n const side = Math.max(FOLLOW_MIN_SIDE, Math.round(Math.min(sw, sh) * SCAN_SHARE))\n const step = side * SCAN_STEP\n return { side, step, nx: Math.max(1, Math.ceil((sw - side) / step) + 1), ny: Math.max(1, Math.ceil((sh - side) / step) + 1) }\n}\n\nfunction overlap(a: Box, b: Box): number {\n const w = Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0])\n const h = Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1])\n if (w <= 0 || h <= 0) return 0\n const i = w * h\n return i / (a[2] * a[3] + b[2] * b[3] - i)\n}\n\ntype FaceResult = { ts: number; n: number; lm: Float32Array; cover: Uint8Array | null; rects: Float32Array | null }\ntype RemoteKind = \"face\" | \"faceExtra\" | \"mask\" | \"person\"\n\n/** What the Engine skips on a GPU known to fail; a host on the main thread gets it from the GPU guard. */\nexport interface EngineGuard {\n noFaceColor?: boolean\n}\n\nconst FACE_COLOR_SKIPPED = \"face colour shaders skipped: linking one lost the WebGL context on this GPU before\"\n\nexport class Engine {\n private canvas: EngineCanvas\n private gl: WebGL2RenderingContext\n private core: MediakitCore\n private background: ImageBitmap | null = null\n // The path the current bitmap came from, so a recipe change that leaves the background\n // alone does not refetch and re-crop it. Without this every slider input event while an\n // image background is on costs a fetch plus two createImageBitmap calls, which is a\n // visible stutter under a dragged finger and the exact case setRecipe exists to make cheap.\n private backgroundPath: string | null = null\n /** The LUT the core holds, by path, so a slider drag does not decode it again. */\n private lutPath = \"\"\n /** The makeup texture the core holds, by path - see setRecipe. */\n private makeupPath = \"\"\n /** Whether the core holds the pink whitening table. */\n private skinLutState: \"none\" | \"loading\" | \"ready\" | \"failed\" = \"none\"\n private closed = false\n\n /**\n * The segmenter loads LAZILY - only once a recipe actually needs a person mask.\n *\n * The MediaPipe runtime is ~9 MB of wasm plus a model. Someone who only wants a brighter\n * picture has no reason to download that.\n */\n private segmenter: Segmenter | null = null\n private segmenterLoading: Promise<void> | null = null\n /** The multiclass segmenter, for recipes that tell skin from clothes (`needsSkinClasses`). */\n private classSegmenter: Segmenter | null = null\n private classLoading: Promise<void> | null = null\n /** The segmenter whose result this frame borrowed, to give it back after process(). */\n private used: Segmenter | null = null\n private programErr = \"\"\n private loadErr = \"\"\n private gpu = \"\"\n private linkSeenAt = -Infinity\n private links = 0\n private lostPhase: LossPhase | null = null\n private classFailed = false\n private readonly failed = new Set<\"face\" | \"person\" | \"segmenter\">()\n\n /**\n * The landmark detector, also lazy and independent of the segmenter.\n *\n * Its model is ~3.7 MB, fifteen times the segmentation one. Someone who only replaces\n * their background has no reason to download it, and the other way round.\n */\n private face: FaceDetector | null = null\n // Preferred over `face`: a landmarker call can take longer than a frame, and in-thread it\n // stalls the picture for that long. `face` is the fallback when no worker can be made.\n private faceRemote = false\n private faceWorkerMs = 0\n private classRemote = false\n private classMaskTex: WebGLTexture | null = null\n private classMaskFresh = false\n private classMaskTs = -1\n syncFaces = false\n renderedTs = 0\n private queue: { c: OffscreenCanvas; ts: number }[] = []\n private spare: OffscreenCanvas[] = []\n private faceExtraUp = false\n private faceExtraTried = false\n private lerpBuf: Float32Array | null = null\n private gapUs = 33_333\n private prevTs = -1\n private readonly sent = new Map<RemoteKind, { ts: number; at: number }>()\n private readonly lastSentAt = new Map<RemoteKind, number>()\n private faceLatencyMs = 0\n private readonly maskLatencyMs = new Map<RemoteKind, number>()\n private faceTs = -1\n private faceResults: FaceResult[] = []\n private coverCanvas: OffscreenCanvas | null = null\n private coverCell: OffscreenCanvas | null = null\n private coverOn = false\n private coverState: \"loading\" | \"ready\" | \"failed\" = \"loading\"\n private readonly partErr = new Map<Part, string>()\n private faceMisses = 0\n private coverHidden = false\n private srcW = 0\n private srcH = 0\n private coverLast: Uint8Array | null = null\n private coverShown: Uint8Array | null = null\n private coverImg: ImageData | null = null\n private readonly faceAsked = new Set<number>()\n private readonly faceCrops = new Map<number, Box>()\n private followBox: Box | null = null\n private followTs = -Infinity\n private followCrop: [number, number, number] | null = null\n private followCanvas: OffscreenCanvas | null = null\n private followRetry: [number, number, number] | null = null\n private faceSeen = false\n private followFloats = 0\n private followAll = false\n private followTurn = 0\n private followMiss = 0\n private followGrow = 0\n private boxFloats = 0\n private scanFrom = 0\n private scanTurn = 0\n private readonly probes = new Set<number>()\n private maskResults: MaskResult[] = []\n private maskUsedTs = -1\n private lastHeld: OffscreenCanvas | null = null\n private swallowed = false\n private maskWorkerMs = 0\n private readonly detects = new Map<RemoteKind, DetectWorker>()\n private personRemote = false\n private personLoading: Promise<void> | null = null\n private personMaskTex: WebGLTexture | null = null\n private personMaskFresh = false\n private personMaskTs = -1\n private personWorkerMs = 0\n private personBytes: MaskBytes | null = null\n private classBytes: MaskBytes | null = null\n private mergedBytes: Uint8Array | null = null\n private mergedTex: WebGLTexture | null = null\n private mergedFresh = false\n private mergedTs = 0\n private detectCanvas: OffscreenCanvas | null = null\n private detectCanvasTs = -1\n private thumbCanvas: OffscreenCanvas | null = null\n private readonly thumbs = new Map<number, Uint8Array>()\n // A kind whose worker failed once stays in-thread.\n private readonly inThread = new Set<RemoteKind>()\n private faceLoading: Promise<void> | null = null\n private faceCount = 1\n private caughtUpTs = -Infinity\n private maxFaces = 3\n private lmBuf: Float32Array | null = null\n\n private filter: BgFilter = { kind: \"none\" }\n private effects: Effects = NO_EFFECTS\n\n // The PREVIOUS frame's measurements, fed to the governor for the next one. The governor\n // steers on past numbers because there is no way to know in advance what a frame will cost.\n private prevTotalMs = 0\n private prevSegMs = 0\n\n last: FrameStats = { ...ZERO_STATS }\n\n private constructor(canvas: EngineCanvas, gl: WebGL2RenderingContext, core: MediakitCore) {\n this.canvas = canvas\n this.gl = gl\n this.core = core\n }\n\n /** Main thread: makes its own canvas. A worker calls `on` with an OffscreenCanvas. */\n static async create(\n width: number,\n height: number,\n filter: BgFilter,\n effects: Effects = NO_EFFECTS,\n alpha = false,\n maxFaces = 3,\n guard: EngineGuard = {},\n ): Promise<Engine> {\n const canvas = document.createElement(\"canvas\")\n canvas.width = width\n canvas.height = height\n return Engine.on(canvas, filter, effects, undefined, alpha, maxFaces, guard)\n }\n\n /**\n * `background`: see {@link Engine.setRecipe}. `alpha` keeps the output's alpha channel, which\n * only a `cutout` background writes; it is fixed for the life of the context, so a host that\n * may switch to `cutout` later has to ask for it here. `maxFaces` (1-3) is how many faces the\n * landmarker looks for: below 3 it skips re-running its face detector on every call. Throws\n * GpuLostError when the context is lost building the shaders, or this GPU is remembered for it.\n */\n static async on(\n canvas: EngineCanvas,\n filter: BgFilter,\n effects: Effects = NO_EFFECTS,\n background?: ImageBitmap,\n alpha = false,\n maxFaces = 3,\n guard: EngineGuard = {},\n ): Promise<Engine> {\n const width = canvas.width\n const height = canvas.height\n\n // `premultipliedAlpha: false` because the shaders blend themselves; `alpha` off unless\n // asked because an opaque output makes the alpha channel pure bandwidth;\n // depth/stencil/antialias off because no pass uses them.\n //\n // `desynchronized` is DELIBERATELY not set. It decouples the canvas from the page's\n // paint rhythm to get pixels on screen sooner - but the destination here is\n // `new VideoFrame(canvas)`, which READS the canvas back inside the same task.\n // Decoupling at exactly that point opens the door to reading a buffer that is still\n // being drawn, and the symptom would be occasional torn frames: not reproducible, and\n // with no error anywhere.\n // Typed by hand: on the HTMLCanvasElement | OffscreenCanvas union, TS resolves the\n // getContext overload differently depending on what else it checked first.\n const gl = canvas.getContext(\"webgl2\", {\n alpha,\n premultipliedAlpha: false,\n antialias: false,\n depth: false,\n stencil: false,\n }) as WebGL2RenderingContext | null\n if (!gl) throw new Error(\"mediakit: no WebGL2 in this browser (none available, blocked, or the GPU process was reset)\")\n const gpu = rendererOf(gl)\n const known = gpuRecord(gpu)\n if (known?.init) {\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n throw new GpuLostError(\"init\", gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`)\n }\n\n // From here on a context exists, and every failure below has to give it back.\n //\n // Browsers cap how many WebGL contexts live at once, usually 8-16, and when the cap is\n // hit the OLDEST one is reclaimed - the meeting that is running, not the attempt that\n // just failed. So a caller retrying create() walks that cap and kills the call it is\n // trying to fix. Nothing reports it: the reclaimed context just stops drawing.\n let core: MediakitCore | undefined\n let engine: Engine | undefined\n try {\n core = await loadCore()\n const err = core.init(gl, width, height)\n if (err && gl.isContextLost()) {\n recordLoss(gpu, \"init\")\n throw new GpuLostError(\"init\", gpu, err)\n }\n if (err) throw new Error(`mediakit: ${err} [GPU: ${gpuName(gl)}]`)\n\n engine = new Engine(canvas, gl, core)\n engine.gpu = gpu\n if (guard.noFaceColor || known?.faceColor) core.disableFaceColor?.(FACE_COLOR_SKIPPED)\n engine.maxFaces = Math.min(3, Math.max(1, Math.floor(maxFaces) || 3))\n await engine.setRecipe(filter, effects, background)\n return engine\n } catch (err) {\n // Teardown must never replace the diagnosis. Closing a half-built segmenter can\n // throw, and then the caller reads a cleanup error instead of the reason create()\n // actually failed - pointing the search at the wrong layer.\n try {\n // Once the Engine exists its own close() is the complete teardown - segmenter,\n // face detector, core and context. Before that there is only the core and the\n // context to undo, and running both paths would tear down twice.\n if (engine) engine.close()\n else {\n core?.close()\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n }\n } catch {\n // Nothing useful to do: the context is going away with the page anyway, and the\n // error below is the one worth reading.\n }\n throw err\n }\n }\n\n /** The GPU the context reported at creation, \"\" when the browser hides it. */\n get gpuName(): string {\n return this.gpu\n }\n\n get loading(): boolean {\n return this.segmenterLoading !== null || this.classLoading !== null || this.faceLoading !== null\n }\n\n /** The browser took the WebGL context away (GPU process reset or reclaimed); this Engine is done. */\n get lost(): boolean {\n return this.gl.isContextLost()\n }\n\n /**\n * When the context was lost: \"link\" within 3 s of a face colour shader starting or still linking, else \"run\";\n * null while it is not. The first read decides, and on the main thread it is remembered per GPU.\n */\n get lostDuring(): LossPhase | null {\n if (this.closed || !this.gl.isContextLost()) return null\n if (!this.lostPhase) {\n this.lostPhase = performance.now() - this.linkSeenAt < LINK_LOSS_WINDOW_MS ? \"link\" : \"run\"\n recordLoss(this.gpu, this.lostPhase)\n }\n return this.lostPhase\n }\n\n get outputCanvas(): EngineCanvas {\n return this.canvas\n }\n\n /** Draws an inner layer instead of the picture until set back to \"off\". */\n setDebug(view: DebugView): void {\n if (this.closed) return\n this.core.setDebug(debugCode(view))\n }\n\n /**\n * Change the recipe without rebuilding the pipeline, so dragging a slider does not flash.\n *\n * `background` is `filter.imagePath` already decoded, and the Engine takes ownership of it.\n * A worker needs it: there is no `Image` there, so an SVG - every background meet bundles -\n * cannot be decoded at all, and the main thread has to do it and transfer the bitmap.\n */\n async setRecipe(filter: BgFilter, effects: Effects = this.effects, background?: ImageBitmap): Promise<void> {\n if (this.closed) return\n this.filter = filter\n this.effects = effects\n\n if (filter.kind === \"image\" && (background || filter.imagePath !== this.backgroundPath)) {\n const w = this.canvas.width\n const h = this.canvas.height\n const bmp = background ? await coverCrop(background, w, h) : await loadBitmap(filter.imagePath, w, h)\n if (this.closed) {\n bmp.close()\n return\n }\n this.background?.close()\n this.background = bmp\n this.backgroundPath = filter.imagePath\n }\n\n if (effects.lut !== this.lutPath) {\n if (effects.lut) {\n // Not cover-cropped like a background: a LUT is data laid out on a fixed grid,\n // and resampling it would mix neighbouring colours into each other. No colour-space\n // conversion either: an embedded gamma or ICC profile would shift every entry.\n let bmp: ImageBitmap | null = null\n try {\n bmp = await decodeImage(effects.lut, { colorSpaceConversion: \"none\", premultiplyAlpha: \"none\" })\n } catch (e: unknown) {\n // A broken LUT must not hold back the rest of the recipe, nor be fetched again\n // on every slider event after it.\n console.error(\"mediakit: LUT failed to load\", e)\n }\n // A newer setRecipe ran during the decode and already owns the core's state;\n // applying this one now would put an older LUT and recipe back over it.\n if (this.closed || this.filter !== filter || this.effects !== effects) {\n bmp?.close()\n return\n }\n this.core.setLut(bmp)\n bmp?.close()\n } else {\n this.core.setLut(null)\n }\n this.lutPath = effects.lut\n }\n\n if (effects.whitenStyle === \"pink\" && this.skinLutState === \"none\") {\n // Not awaited: until it is in, the core whitens the natural way.\n this.skinLutState = \"loading\"\n decodeImage(assetUrl(\"whiten_pink.png\"), { colorSpaceConversion: \"none\", premultiplyAlpha: \"none\" })\n .then((bmp) => {\n if (this.closed) {\n bmp.close()\n return\n }\n this.core.setSkinLut(bmp)\n bmp.close()\n this.skinLutState = \"ready\"\n })\n .catch((err: unknown) => {\n // Not retried on every recipe change.\n console.error(\"mediakit: pink whitening table failed to load\", err)\n this.skinLutState = \"failed\"\n })\n }\n\n const makeupTexture = effects.makeupTexture ?? \"\"\n if (makeupTexture !== this.makeupPath) {\n if (makeupTexture) {\n // Decoded as it is, like a LUT.\n let bmp: ImageBitmap | null = null\n try {\n bmp = await decodeImage(makeupTexture, { premultiplyAlpha: \"none\" })\n } catch (e: unknown) {\n console.error(\"mediakit: makeup texture failed to load\", e)\n }\n if (this.closed || this.filter !== filter || this.effects !== effects) {\n bmp?.close()\n return\n }\n this.core.setMakeup(bmp)\n bmp?.close()\n } else {\n this.core.setMakeup(null)\n }\n this.makeupPath = makeupTexture\n }\n\n this.core.setRecipe(coreRecipe(filter, effects))\n this.noteLinking()\n\n // Start a detector the moment a recipe begins to need it. Not awaited: the frames in\n // the meantime pass through unprocessed, exactly like the first frames before any mask\n // exists.\n if (needsSegmentation(filter, effects) && !this.remoteMaskComing(filter, effects)) void this.ensureSegmenter()\n if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter()\n if (this.personRemoteWanted(filter, effects)) void this.ensurePersonRemote()\n if (needsFace(effects)) void this.ensureFace()\n }\n\n private noteLinking(): void {\n const links = this.core.links?.() ?? 0\n if (links !== this.links || (this.core.linking?.() ?? 0) > 0) this.linkSeenAt = performance.now()\n this.links = links\n }\n\n /** A worker, or the multiclass model, will bring the mask: no in-thread person model for it. */\n private remoteMaskComing(filter: BgFilter, effects: Effects): boolean {\n if (needsSkinClasses(filter, effects) && !this.classFailed) return true\n return this.personRemoteWanted(filter, effects) && !this.inThread.has(\"person\")\n }\n\n private gaveUp(what: string, e: unknown): void {\n if (!(e instanceof LoadTimeout)) return\n this.loadErr ||= `${e.message}; ${what} stay off`\n console.warn(this.loadErr)\n }\n\n private ensureFace(): Promise<void> {\n if (this.face || this.faceRemote || this.failed.has(\"face\") || this.closed) return Promise.resolve()\n if (this.faceLoading) return this.faceLoading\n\n // The buffer first: its length is how many faces the core tracks, and the detector has to\n // be built for that many.\n const buf = this.core.faceBuffer()\n if (!buf) return Promise.resolve()\n const n = Math.min(Math.max(1, Math.floor(buf.length / FACE_FLOATS)), this.maxFaces)\n this.faceLoading = this.remote(\"face\", (d) => d.initFace(n))\n .then(() => {\n this.faceRemote = true\n this.lmBuf = buf\n this.faceCount = n\n })\n .catch((e: unknown) => {\n if (e instanceof LoadTimeout) throw e\n if (!this.inThread.has(\"face\")) console.warn(\"mediakit: no detect worker for faces, detecting in this thread\", e)\n return withTimeout(createFaceDetector(this.canvas, n), LOAD_MS, \"face detection\", (f) => f.close()).then((f) => {\n if (this.closed) {\n f.close()\n return\n }\n this.face = f\n this.lmBuf = buf\n })\n })\n .catch((e: unknown) => {\n this.failed.add(\"face\")\n this.partFailed(\"face\", \"face detection\", \"face effects\", e)\n this.gaveUp(\"face effects\", e)\n if (!(e instanceof LoadTimeout)) console.error(\"mediakit: face detector failed to load\", e)\n })\n .finally(() => {\n this.faceLoading = null\n })\n return this.faceLoading\n }\n\n /** The detect worker for `kind`, made on first use; rejects when that kind must stay in-thread. */\n private personRemoteWanted(filter: BgFilter, effects: Effects): boolean {\n return filter.kind === \"none\" && needsSegmentation(filter, effects)\n }\n\n private ensurePersonRemote(): Promise<void> {\n if (this.personRemote || this.failed.has(\"person\") || this.closed) return Promise.resolve()\n this.personLoading ??= this.remote(\"person\", (d) => d.initMask(\"person\"))\n .then(() => {\n this.personRemote = true\n })\n .catch((e: unknown) => {\n if (!(e instanceof LoadTimeout)) return\n this.failed.add(\"person\")\n this.partFailed(\"person\", \"person segmentation\", \"background effects\", e)\n this.gaveUp(\"background effects\", e)\n })\n .finally(() => {\n this.personLoading = null\n })\n return this.personLoading\n }\n\n private async remote(kind: RemoteKind, init: (d: DetectWorker) => Promise<void>): Promise<void> {\n if (this.inThread.has(kind) || typeof Worker === \"undefined\" || typeof VideoFrame === \"undefined\") {\n this.inThread.add(kind)\n throw new Error(\"in-thread\")\n }\n let detect = this.detects.get(kind)\n if (!detect) {\n detect = new DetectWorker(this.detectHandlers(kind))\n this.detects.set(kind, detect)\n }\n try {\n await init(detect)\n } catch (e) {\n if (e instanceof LoadTimeout) {\n detect.close()\n this.detects.delete(kind)\n } else this.inThread.add(kind)\n throw e\n }\n if (this.closed) throw new Error(\"closed\")\n }\n\n private detectHandlers(key: RemoteKind): DetectHandlers {\n return {\n face: (tsUs, found, lm, ms, foundCover, foundRects) => {\n if (this.closed || !this.lmBuf || tsUs > this.prevTs) return\n this.faceWorkerMs = ms\n this.uncrop(tsUs, found, lm, foundRects)\n const { n, cover, rects } = this.dedupe(found, lm, foundCover, foundRects)\n this.follow(tsUs, n, lm, this.probes.delete(tsUs))\n if (this.syncing()) {\n this.faceResults.push({ ts: tsUs, n, lm: lm.slice(), cover, rects })\n if (this.faceResults.length > FACE_RESULTS_KEPT) this.faceResults.shift()\n } else this.applyFace(tsUs, n, lm, cover, rects)\n const took = this.took(key === \"faceExtra\" ? \"faceExtra\" : \"face\", tsUs)\n if (took !== null) this.faceLatencyMs = this.faceLatencyMs ? this.faceLatencyMs + (took - this.faceLatencyMs) * 0.2 : took\n },\n mask: (tsUs, width, height, data, ms) => {\n if (this.closed) return\n const took = this.took(key, tsUs)\n if (took !== null) {\n const was = this.maskLatencyMs.get(key)\n this.maskLatencyMs.set(key, was ? was + (took - was) * 0.2 : took)\n }\n const r = { person: key === \"person\", ts: tsUs, width, height, data, ms }\n if (!this.syncing()) {\n this.applyMask(r)\n return\n }\n this.maskResults.push(r)\n if (this.maskResults.length > MASK_RESULTS_KEPT) this.maskResults.shift()\n },\n cover: (ok, message) => {\n if (key !== \"face\" || this.coverState === \"failed\") return\n this.coverState = ok ? \"ready\" : \"failed\"\n if (!ok) this.partErr.set(\"cover\", `mediakit: ${message}; occluders stays off`)\n },\n failed: (k, reason) => {\n if (key === \"faceExtra\") {\n this.faceExtraUp = false\n this.detects.get(key)?.close()\n this.detects.delete(key)\n return\n }\n console.warn(`mediakit: ${key} detection moves into this thread:`, reason)\n this.inThread.add(key)\n if (key === \"person\") {\n this.personRemote = false\n } else if (k === \"face\") {\n this.faceRemote = false\n if (this.coverOn) this.core.setFaceCover(null)\n this.coverOn = false\n this.coverShown = null\n void this.ensureFace()\n } else {\n this.classRemote = false\n void this.ensureClassSegmenter()\n }\n },\n }\n }\n\n private noteThumb(timestampUs: number): void {\n if (this.thumbs.has(timestampUs) || !this.detectCanvas || this.detectCanvasTs !== timestampUs) return\n this.thumbCanvas ??= new OffscreenCanvas(THUMB_W, THUMB_H)\n const ctx = this.thumbCanvas.getContext(\"2d\", { willReadFrequently: true })!\n ctx.drawImage(this.detectCanvas, 0, 0, THUMB_W, THUMB_H)\n this.thumbs.set(timestampUs, lumaThumb(ctx.getImageData(0, 0, THUMB_W, THUMB_H).data))\n if (this.thumbs.size > THUMBS_KEPT) this.thumbs.delete(this.thumbs.keys().next().value!)\n }\n\n private merge(tsUs: number): void {\n if (!this.personBytes || !this.classBytes || !needsSkinClasses(this.filter, this.effects)) return\n const then = this.thumbs.get(this.classMaskTs)\n const now = this.thumbs.get(this.personMaskTs)\n const moved = then && now && this.classMaskTs !== this.personMaskTs ? movedBetween(then, now) : null\n this.mergedBytes = mergeMasks(this.personBytes, this.classBytes, this.mergedBytes, moved)\n this.mergedTex = this.uploadMaskBytes(this.mergedTex, this.personBytes.width, this.personBytes.height, this.mergedBytes)\n this.mergedFresh = true\n this.mergedTs = tsUs\n }\n\n private uploadClassMask(width: number, height: number, data: Uint8Array): void {\n this.classMaskTex = this.uploadMaskBytes(this.classMaskTex, width, height, data)\n this.classMaskFresh = true\n }\n\n // Category indices: NEAREST, since a blend of two indices is a third, wrong category.\n private uploadMaskBytes(tex: WebGLTexture | null, width: number, height: number, data: Uint8Array): WebGLTexture | null {\n const gl = this.gl\n if (!tex) {\n tex = gl.createTexture()\n gl.bindTexture(gl.TEXTURE_2D, tex)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)\n }\n gl.bindTexture(gl.TEXTURE_2D, tex)\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1)\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.R8, width, height, 0, gl.RED, gl.UNSIGNED_BYTE, data)\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4)\n gl.bindTexture(gl.TEXTURE_2D, null)\n return tex\n }\n\n /**\n * Sends the detect worker a downscaled copy, never a clone: a camera frame held through a slow\n * detection drains Chrome's few capture buffers and throttles the camera itself.\n */\n private requestRemote(want: RemoteKind, source: TexImageSource, timestampUs: number): void {\n const lockstep = want === \"face\" && this.syncing()\n const kind = lockstep ? this.freeFaceWorker() : want\n if (!kind) return\n const detect = this.detects.get(kind)\n if (!detect?.accepts(kind === \"face\" || kind === \"faceExtra\" ? \"face\" : \"mask\")) return\n if (!lockstep && !this.dutyAllows(kind)) return\n let frame: VideoFrame | null = null\n let followed: OffscreenCanvas | null = null\n let scanned: OffscreenCanvas | null = null\n try {\n const copyable = source instanceof VideoFrame || source instanceof OffscreenCanvas\n if (copyable) {\n this.srcW = source instanceof VideoFrame ? source.displayWidth : source.width\n this.srcH = source instanceof VideoFrame ? source.displayHeight : source.height\n }\n if (copyable && (kind === \"face\" || kind === \"faceExtra\")) {\n followed = this.followCopy(source, timestampUs)\n if (!followed) scanned = this.scanCopy(source, timestampUs)\n }\n frame = new VideoFrame(followed ?? scanned ?? (copyable ? this.detectCopy(source, timestampUs) : (source as CanvasImageSource)), {\n timestamp: timestampUs,\n })\n } catch {\n // ImageData has no VideoFrame form: this frame goes without.\n }\n if (frame && detect.request(kind === \"face\" || kind === \"faceExtra\" ? \"face\" : \"mask\", frame, timestampUs, this.effects.occluders ?? false, followed ? this.followRetry : null)) {\n const now = performance.now()\n this.sent.set(kind, { ts: timestampUs, at: now })\n this.lastSentAt.set(kind, now)\n if (lockstep) this.faceAsked.add(timestampUs)\n if (kind !== \"face\" && kind !== \"faceExtra\" && this.remoteMaskKind() === \"merged\") this.noteThumb(timestampUs)\n } else if (followed || scanned) this.faceCrops.delete(timestampUs)\n }\n\n private followCopy(source: VideoFrame | OffscreenCanvas, timestampUs: number): OffscreenCanvas | null {\n const box = this.followBox\n if (!box || timestampUs - this.followTs > FOLLOW_STALE_US) return null\n const sw = source instanceof VideoFrame ? source.displayWidth : source.width\n const sh = source instanceof VideoFrame ? source.displayHeight : source.height\n const want = Math.max(FOLLOW_MIN_SIDE, FOLLOW_MARGIN * (1 + this.followMiss) * Math.max(box[2] * sw, box[3] * sh))\n if (want > Math.min(sw, sh) && this.followFloats > FACE_FLOATS) return null\n if (!this.followAll && this.followTurn++ % FOLLOW_REFRESH === FOLLOW_REFRESH - 1) {\n this.probes.add(timestampUs)\n return null\n }\n let side = Math.round(Math.min(sw, sh, want))\n let x = Math.round(Math.min(sw - side, Math.max(0, (box[0] + box[2] / 2) * sw - side / 2)))\n let y = Math.round(Math.min(sh - side, Math.max(0, (box[1] + box[3] / 2) * sh - side / 2)))\n const kept = this.followCrop\n if (\n kept &&\n kept[0] + kept[2] <= sw &&\n kept[1] + kept[2] <= sh &&\n Math.abs(kept[2] - side) < FOLLOW_RESIZE * side &&\n Math.abs(kept[0] - x) < FOLLOW_SHIFT * side &&\n Math.abs(kept[1] - y) < FOLLOW_SHIFT * side\n ) {\n ;[x, y, side] = kept\n } else this.followCrop = [x, y, side]\n this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE)\n this.followCanvas.getContext(\"2d\")!.drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE)\n const tight = Math.min(side, Math.max(FOLLOW_MIN_SIDE, FOLLOW_RETRY * Math.max(box[2] * sw, box[3] * sh)))\n this.followRetry = [((box[0] + box[2] / 2) * sw - x) / side, ((box[1] + box[3] / 2) * sh - y) / side, tight / side]\n this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh])\n return this.followCanvas\n }\n\n private scanCopy(source: VideoFrame | OffscreenCanvas, timestampUs: number): OffscreenCanvas | null {\n if (this.faceSeen) return null\n const turn = this.scanTurn++\n if (turn % 2 === 0) return null\n const sw = source instanceof VideoFrame ? source.displayWidth : source.width\n const sh = source instanceof VideoFrame ? source.displayHeight : source.height\n const { side, step, nx, ny } = tileGrid(sw, sh)\n const at = (this.scanFrom + (turn >> 1)) % (nx * ny)\n const x = Math.max(0, Math.min(sw - side, Math.round((at % nx) * step)))\n const y = Math.max(0, Math.min(sh - side, Math.round(Math.floor(at / nx) * step)))\n this.followCanvas ??= new OffscreenCanvas(FOLLOW_SIDE, FOLLOW_SIDE)\n this.followCanvas.getContext(\"2d\")!.drawImage(source, x, y, side, side, 0, 0, FOLLOW_SIDE, FOLLOW_SIDE)\n this.faceCrops.set(timestampUs, [x / sw, y / sh, side / sw, side / sh])\n this.probes.add(timestampUs)\n return this.followCanvas\n }\n\n private scanTile(cx: number, cy: number): number {\n const sw = this.srcW || this.canvas.width\n const sh = this.srcH || this.canvas.height\n const { side, step, nx, ny } = tileGrid(sw, sh)\n const ix = Math.min(nx - 1, Math.max(0, Math.round((cx * sw - side / 2) / step)))\n const iy = Math.min(ny - 1, Math.max(0, Math.round((cy * sh - side / 2) / step)))\n return iy * nx + ix\n }\n\n private uncrop(tsUs: number, n: number, lm: Float32Array, rects: Float32Array | null): void {\n const crop = this.faceCrops.get(tsUs)\n for (const ts of this.faceCrops.keys()) if (ts === tsUs || ts < tsUs - FOLLOW_KEPT_US) this.faceCrops.delete(ts)\n if (!crop) return\n for (let i = 0; i < n; i += 3) {\n lm[i] = crop[0] + lm[i]! * crop[2]\n lm[i + 1] = crop[1] + lm[i + 1]! * crop[3]\n lm[i + 2] = lm[i + 2]! * crop[2]\n }\n for (let i = 0; rects && i < rects.length; i += 3) {\n rects[i] = crop[0] + rects[i]! * crop[2]\n rects[i + 1] = crop[1] + rects[i + 1]! * crop[3]\n rects[i + 2] = rects[i + 2]! * crop[2]\n }\n }\n\n private dedupe(n: number, lm: Float32Array, cover: Uint8Array | null, rects: Float32Array | null): { n: number; cover: Uint8Array | null; rects: Float32Array | null } {\n const faces = n / FACE_FLOATS\n if (faces < 2) return { n, cover, rects }\n const boxes = Array.from({ length: faces }, (_, f) => faceBox(lm, f * FACE_FLOATS))\n const ref = this.followBox\n const score = (b: Box) => (ref ? overlap(b, ref) : 0) + b[2] * b[3] * 1e-3\n const keep = boxes.map(() => true)\n for (let a = 0; a < faces; a++) {\n for (let b = a + 1; b < faces; b++) {\n if (!keep[a] || !keep[b] || overlap(boxes[a]!, boxes[b]!) <= SAME_FACE) continue\n keep[score(boxes[a]!) >= score(boxes[b]!) ? b : a] = false\n }\n }\n if (keep.every(Boolean)) return { n, cover, rects }\n const cells = COVER_SIZE * COVER_SIZE\n const outCover = cover ? new Uint8Array(cover.length) : null\n const outRects = rects ? new Float32Array(rects.length) : null\n let k = 0\n for (let f = 0; f < faces; f++) {\n if (!keep[f]) continue\n if (k !== f) lm.copyWithin(k * FACE_FLOATS, f * FACE_FLOATS, (f + 1) * FACE_FLOATS)\n if (cover && outCover) outCover.set(cover.subarray(f * cells, (f + 1) * cells), k * cells)\n if (rects && outRects) outRects.set(rects.subarray(f * 3, f * 3 + 3), k * 3)\n k++\n }\n return { n: k * FACE_FLOATS, cover: outCover ? outCover.slice(0, k * cells) : null, rects: outRects ? outRects.slice(0, k * 3) : null }\n }\n\n private follow(tsUs: number, n: number, lm: Float32Array, probe: boolean): void {\n for (const ts of this.probes) if (ts < tsUs - FOLLOW_KEPT_US) this.probes.delete(ts)\n if (tsUs <= this.followTs || (probe && (n === 0 || n < this.followFloats))) return\n this.followTs = tsUs\n this.faceSeen = n > 0\n if (n === 0) {\n this.followGrow = 0\n this.followFloats = 0\n this.followAll = false\n const box = this.followBox\n if (box && this.followMiss < FOLLOW_WIDEN) {\n this.followMiss++\n return\n }\n this.followMiss = 0\n if (box) this.scanFrom = this.scanTile(box[0] + box[2] / 2, box[1] + box[3] / 2)\n this.scanTurn = 1\n this.followBox = null\n this.followCrop = null\n this.boxFloats = 0\n return\n }\n this.followMiss = 0\n const old = this.followBox\n const grow = old !== null && this.boxFloats > 0 && n > this.boxFloats && !probe\n this.followGrow = grow ? this.followGrow + 1 : 0\n const take = grow && this.followGrow < FOLLOW_GROW ? this.boxFloats : n\n const boxes: Box[] = []\n for (let f = 0; f < n; f += FACE_FLOATS) boxes.push(faceBox(lm, f))\n if (take < n && old) boxes.sort((a, b) => overlap(b, old) - overlap(a, old))\n const kept = boxes.slice(0, take / FACE_FLOATS)\n const x0 = Math.min(...kept.map((b) => b[0]))\n const y0 = Math.min(...kept.map((b) => b[1]))\n const x1 = Math.max(...kept.map((b) => b[0] + b[2]))\n const y1 = Math.max(...kept.map((b) => b[1] + b[3]))\n this.followBox = [x0, y0, x1 - x0, y1 - y0]\n this.boxFloats = take\n this.followFloats = take\n this.followAll = take >= this.faceCount * FACE_FLOATS\n }\n\n private freeFaceWorker(): RemoteKind | null {\n if (this.detects.get(\"face\")?.accepts(\"face\")) return \"face\"\n if (this.faceExtraUp && this.detects.get(\"faceExtra\")?.accepts(\"face\")) return \"faceExtra\"\n return null\n }\n\n private ensureFaceExtra(): void {\n if (this.faceExtraTried || this.closed) return\n this.faceExtraTried = true\n const n = this.faceCount\n this.remote(\"faceExtra\", (d) => d.initFace(n))\n .then(() => {\n this.faceExtraUp = true\n })\n .catch(() => {\n this.detects.get(\"faceExtra\")?.close()\n this.detects.delete(\"faceExtra\")\n })\n }\n\n /** Face and mask asked on the same frame share one draw. */\n private detectCopy(source: VideoFrame | OffscreenCanvas, timestampUs: number): OffscreenCanvas {\n const sw = source instanceof VideoFrame ? source.displayWidth : source.width\n const sh = source instanceof VideoFrame ? source.displayHeight : source.height\n // Same long edge as MAX_EDGE in detect-worker/entry.ts.\n const s = Math.min(1, 512 / Math.max(sw, sh))\n const w = Math.max(1, Math.round(sw * s))\n const h = Math.max(1, Math.round(sh * s))\n if (!this.detectCanvas || this.detectCanvas.width !== w || this.detectCanvas.height !== h) {\n this.detectCanvas = new OffscreenCanvas(w, h)\n this.detectCanvasTs = -1\n }\n if (this.detectCanvasTs !== timestampUs) {\n this.detectCanvas.getContext(\"2d\")!.drawImage(source, 0, 0, w, h)\n this.detectCanvasTs = timestampUs\n }\n return this.detectCanvas\n }\n\n private ensureClassSegmenter(): Promise<void> {\n if (this.classSegmenter || this.classRemote || this.classFailed || this.closed) return Promise.resolve()\n if (this.classLoading) return this.classLoading\n this.classLoading = this.remote(\"mask\", (d) => d.initMask(\"classes\"))\n .then(() => {\n this.classRemote = true\n })\n .catch((e: unknown) => {\n if (e instanceof LoadTimeout) throw e\n return withTimeout(createSegmenter(this.canvas, \"classes\" satisfies SegmenterModel), LOAD_MS, \"skin segmentation\", (s) => s.close()).then((s) => {\n if (this.closed) {\n s.close()\n return\n }\n this.classSegmenter = s\n })\n })\n .catch((e: unknown) => {\n // Not fatal: the person segmenter and the face-held fallback carry on.\n this.classFailed = true\n this.partFailed(\"classes\", \"skin segmentation\", \"skin, hair and product effects use the person model\", e)\n if (!(e instanceof LoadTimeout)) console.error(\"mediakit: multiclass segmenter failed to load\", e)\n else console.warn(`${e.message}; the person model stands in`)\n if (needsSegmentation(this.filter, this.effects)) void this.ensureSegmenter()\n })\n .finally(() => {\n this.classLoading = null\n })\n return this.classLoading\n }\n\n private ensureSegmenter(): Promise<void> {\n if (this.segmenter || this.failed.has(\"segmenter\") || this.closed) return Promise.resolve()\n if (this.segmenterLoading) return this.segmenterLoading\n\n this.segmenterLoading = withTimeout(createSegmenter(this.canvas), LOAD_MS, \"person segmentation\", (s) => s.close())\n .then((s) => {\n if (this.closed) {\n s.close()\n return\n }\n this.segmenter = s\n })\n .catch((e: unknown) => {\n this.failed.add(\"segmenter\")\n this.partFailed(\"person\", \"person segmentation\", \"background and skin effects\", e)\n this.gaveUp(\"background and skin effects\", e)\n if (!(e instanceof LoadTimeout)) console.error(\"mediakit: segmenter failed to load\", e)\n })\n .finally(() => {\n this.segmenterLoading = null\n })\n return this.segmenterLoading\n }\n\n /**\n * Draw one source frame onto the output canvas. `false` means nothing was drawn - no mask\n * yet, the segmenter is still loading, or the recipe is inactive.\n *\n * ── Why it takes `TexImageSource` and not just `VideoFrame` ───────────────────────\n * `texImage2D` accepts a `VideoFrame` and an `HTMLVideoElement` alike, and so does\n * MediaPipe. That is what lets the fallback transport (Firefox, and Safari before the\n * worker path) work with NO WebCodecs at all: it passes the `<video>` element straight in.\n *\n * LiveKit's reference implementation requires a `VideoFrame` even on its fallback path, so\n * it constructs one only to destroy it again.\n */\n render(source: TexImageSource, timestampUs: number): boolean {\n if (this.closed || this.lostDuring) return false\n if (this.lastHeld) this.spare.push(this.lastHeld)\n this.lastHeld = null\n this.swallowed = false\n if (this.prevTs >= 0 && timestampUs > this.prevTs) {\n this.gapUs += (Math.min(timestampUs - this.prevTs, 200_000) - this.gapUs) * 0.1\n }\n if (timestampUs < this.prevTs) {\n this.faceResults = []\n this.maskResults = []\n this.faceAsked.clear()\n this.faceCrops.clear()\n this.followBox = null\n this.followCrop = null\n this.followTs = -Infinity\n this.faceSeen = false\n this.followFloats = 0\n this.followAll = false\n this.followTurn = 0\n this.followMiss = 0\n this.followGrow = 0\n this.boxFloats = 0\n this.scanFrom = 0\n this.scanTurn = 0\n this.probes.clear()\n this.caughtUpTs = -Infinity\n this.thumbs.clear()\n }\n this.prevTs = timestampUs\n if (!this.syncing() || (typeof ImageData !== \"undefined\" && source instanceof ImageData)) {\n this.releaseHeld()\n this.renderedTs = timestampUs\n return this.draw(source, timestampUs, false)\n }\n this.ensureFaceExtra()\n this.requestRemote(\"face\", source, timestampUs)\n const remoteMask = this.remoteMaskKind()\n if (remoteMask === \"merged\") {\n this.requestRemote(\"person\", source, timestampUs)\n this.requestRemote(\"mask\", source, timestampUs)\n } else if (remoteMask) this.requestRemote(remoteMask, source, timestampUs)\n this.queue.push({ c: this.hold(source), ts: timestampUs })\n while (this.queue.length > MAX_HOLD + 1) this.faceAsked.delete(this.spareFront())\n if (this.queue.length <= MAX_HOLD && !this.faceReady(this.queue[0]!.ts)) {\n this.swallowed = true\n return false\n }\n if (this.queue.length > 2 && this.faceReady(this.queue[1]!.ts) && timestampUs - this.caughtUpTs >= CATCH_UP_EVERY_US) {\n this.caughtUpTs = timestampUs\n this.faceAsked.delete(this.spareFront())\n }\n const front = this.queue.shift()!\n this.faceAsked.delete(front.ts)\n this.faceFor(front.ts)\n this.masksFor(front.ts)\n this.lastHeld = front.c\n this.renderedTs = front.ts\n return this.draw(front.c, front.ts, true)\n }\n\n private remoteMaskKind(): \"person\" | \"mask\" | \"merged\" | null {\n const person = this.personRemote && this.personRemoteWanted(this.filter, this.effects)\n if (!needsSkinClasses(this.filter, this.effects)) return person ? \"person\" : null\n if (this.classRemote) return person ? \"merged\" : \"mask\"\n return person && !this.inThread.has(\"mask\") ? \"person\" : null\n }\n\n private spareFront(): number {\n const h = this.queue.shift()!\n this.spare.push(h.c)\n return h.ts\n }\n\n private applyMask(r: MaskResult): void {\n if (r.person) {\n this.personMaskTex = this.uploadMaskBytes(this.personMaskTex, r.width, r.height, r.data)\n this.personMaskFresh = true\n this.personMaskTs = r.ts\n this.personWorkerMs = r.ms\n this.personBytes = { width: r.width, height: r.height, data: r.data }\n this.merge(r.ts)\n return\n }\n this.uploadClassMask(r.width, r.height, r.data)\n this.classMaskTs = r.ts\n this.maskWorkerMs = r.ms\n this.classBytes = { width: r.width, height: r.height, data: r.data }\n this.merge(this.personMaskTs)\n }\n\n private masksFor(tsUs: number): void {\n for (const person of [false, true]) {\n let pick: MaskResult | null = null\n for (const r of this.maskResults) if (r.person === person && (!pick || Math.abs(r.ts - tsUs) < Math.abs(pick.ts - tsUs))) pick = r\n if (!pick) continue\n const chosen = pick\n this.maskResults = this.maskResults.filter((r) => r.person !== person || r.ts >= chosen.ts)\n if (chosen.ts !== (person ? this.personMaskTs : this.classMaskTs)) this.applyMask(chosen)\n }\n }\n\n private faceReady(tsUs: number): boolean {\n const asked = this.faceAsked.has(tsUs)\n return this.faceResults.some((r) => (asked ? r.ts === tsUs : r.ts > tsUs))\n }\n\n private dutyAllows(kind: RemoteKind): boolean {\n const took = kind === \"face\" ? this.faceLatencyMs : (this.maskLatencyMs.get(kind) ?? 0)\n if (took * 1000 < this.gapUs) return true\n const last = this.lastSentAt.get(kind)\n return last === undefined || performance.now() - last >= took / DETECT_DUTY\n }\n\n private took(kind: RemoteKind, tsUs: number): number | null {\n const s = this.sent.get(kind)\n if (s?.ts !== tsUs) return null\n this.sent.delete(kind)\n return performance.now() - s.at\n }\n\n private applyFace(tsUs: number, n: number, lm: Float32Array, cover: Uint8Array | null, rects: Float32Array | null): void {\n this.faceMisses = n === 0 ? this.faceMisses + 1 : 0\n if (n > 0) this.showCover(cover, rects)\n else if (this.faceMisses >= COVER_MISSES) this.hideCover()\n this.lmBuf!.set(lm)\n const [lo, hi] = splitMicros(tsUs)\n this.core.setFace(lo, hi, n)\n this.faceTs = tsUs\n }\n\n private faceFor(tsUs: number): void {\n this.faceResults.sort((a, b) => a.ts - b.ts)\n let pick = -1\n for (let i = 0; i < this.faceResults.length; i++) if (this.faceResults[i]!.ts <= tsUs) pick = i\n if (pick < 0) return\n const r = this.faceResults[pick]!\n const next = this.faceResults[pick + 1]\n this.faceResults.splice(0, pick)\n if (r.ts === tsUs || !next || !this.sameFaces(r, next)) {\n if (r.ts !== this.faceTs) this.applyFace(r.ts, r.n, r.lm, r.cover, r.rects)\n return\n }\n const a = (tsUs - r.ts) / (next.ts - r.ts)\n if (!this.lerpBuf || this.lerpBuf.length !== r.lm.length) this.lerpBuf = new Float32Array(r.lm.length)\n for (let i = 0; i < r.n; i++) this.lerpBuf[i] = r.lm[i]! + (next.lm[i]! - r.lm[i]!) * a\n const near = a < 0.5 ? r : next\n this.applyFace(tsUs, r.n, this.lerpBuf, near.cover, near.rects)\n }\n\n private hideCover(): void {\n if (!this.coverOn || !this.coverCanvas || this.coverHidden) return\n const ctx = this.coverCanvas.getContext(\"2d\")!\n ctx.fillStyle = \"#000\"\n ctx.fillRect(0, 0, this.coverCanvas.width, this.coverCanvas.height)\n this.core.setFaceCover(this.coverCanvas)\n this.coverShown = null\n this.coverHidden = true\n }\n\n private showCover(cover: Uint8Array | null, rects: Float32Array | null): void {\n this.coverHidden = false\n if (!cover || !rects || !(this.effects.occluders ?? false)) {\n if (this.coverOn) this.core.setFaceCover(null)\n this.coverOn = false\n this.coverShown = null\n return\n }\n if (cover === this.coverShown && this.coverOn) return\n const w = COVER_FRAME_W\n const h = Math.max(1, Math.round((w * (this.srcH || this.canvas.height)) / (this.srcW || this.canvas.width)))\n if (!this.coverCanvas || this.coverCanvas.height !== h) this.coverCanvas = new OffscreenCanvas(w, h)\n this.coverCell ??= new OffscreenCanvas(COVER_SIZE, COVER_SIZE)\n const ctx = this.coverCanvas.getContext(\"2d\")!\n const cell = this.coverCell.getContext(\"2d\")!\n ctx.fillStyle = \"#fff\"\n ctx.fillRect(0, 0, w, h)\n this.coverImg ??= cell.createImageData(COVER_SIZE, COVER_SIZE)\n const img = this.coverImg\n const cells = COVER_SIZE * COVER_SIZE\n const held = this.coverLast && this.coverLast !== cover && this.coverLast.length === cover.length ? this.coverLast : null\n for (let f = 0; f * 3 < rects.length; f++) {\n for (let i = 0; i < cells; i++) {\n const now = cover[f * cells + i]!\n const v = held ? Math.min(now, now * (1 - COVER_HOLD) + held[f * cells + i]! * COVER_HOLD) : now\n img.data[i * 4] = v\n img.data[i * 4 + 1] = v\n img.data[i * 4 + 2] = v\n img.data[i * 4 + 3] = 255\n }\n cell.putImageData(img, 0, 0)\n const side = rects[f * 3 + 2]! * w\n ctx.drawImage(this.coverCell, rects[f * 3]! * w - side / 2, rects[f * 3 + 1]! * h - side / 2, side, side)\n }\n this.core.setFaceCover(this.coverCanvas)\n this.coverOn = true\n this.coverLast = cover\n this.coverShown = cover\n }\n\n private sameFaces(a: { n: number; lm: Float32Array }, b: { n: number; lm: Float32Array }): boolean {\n if (a.n === 0 || a.n !== b.n) return false\n for (let k = 0; k < a.n; k += FACE_FLOATS) {\n const nose = k + 3\n if (Math.abs(a.lm[nose]! - b.lm[nose]!) > FACE_JUMP || Math.abs(a.lm[nose + 1]! - b.lm[nose + 1]!) > FACE_JUMP) return false\n }\n return true\n }\n\n private releaseHeld(): void {\n for (const h of this.queue) this.spare.push(h.c)\n this.queue = []\n }\n\n dropped(): boolean {\n return this.swallowed\n }\n\n passthrough(): VideoFrame | null {\n return this.lastHeld ? new VideoFrame(this.lastHeld, { timestamp: this.renderedTs }) : null\n }\n\n private syncing(): boolean {\n return this.syncFaces && this.faceRemote && needsFace(this.effects)\n }\n\n private hold(source: TexImageSource): OffscreenCanvas {\n const [w, h] = sourceSize(source)\n let c = this.spare.pop()\n while (c && (c.width !== w || c.height !== h)) c = this.spare.pop()\n c ??= new OffscreenCanvas(w, h)\n c.getContext(\"2d\")!.drawImage(source as CanvasImageSource, 0, 0, w, h)\n return c\n }\n\n private draw(source: TexImageSource, timestampUs: number, faceDone: boolean): boolean {\n const t0 = performance.now()\n const [lo, hi] = splitMicros(timestampUs)\n const needSeg = this.core.decide(lo, hi, this.prevTotalMs, this.prevSegMs) === 1\n\n let mask: WebGLTexture | null = null\n let maskKind = 0\n let maskTs = timestampUs\n let segMs = 0\n let faceMs = 0\n this.used = null\n let served = false\n const remoteMask = this.remoteMaskKind()\n if (remoteMask === \"merged\") {\n if (!faceDone) {\n this.requestRemote(\"person\", source, timestampUs)\n this.requestRemote(\"mask\", source, timestampUs)\n }\n const tex = this.mergedTex ?? this.personMaskTex\n if (tex) {\n served = true\n if (this.mergedTex ? this.mergedFresh : this.personMaskFresh) {\n this.mergedFresh = false\n this.personMaskFresh = false\n mask = tex\n maskKind = this.mergedTex ? 1 : 0\n maskTs = this.mergedTex ? this.mergedTs : this.personMaskTs\n segMs = this.personWorkerMs\n }\n }\n } else if (remoteMask && !faceDone) this.requestRemote(remoteMask, source, timestampUs)\n if (remoteMask === \"person\") {\n if (this.personMaskTex) {\n served = true\n if (this.personMaskFresh) {\n this.personMaskFresh = false\n mask = this.personMaskTex\n maskTs = this.personMaskTs\n segMs = this.personWorkerMs\n }\n }\n }\n if (remoteMask === \"mask\") {\n if (this.classMaskTex) {\n served = true\n if (this.classMaskFresh) {\n this.classMaskFresh = false\n mask = this.classMaskTex\n maskKind = 1\n maskTs = this.classMaskTs\n segMs = this.maskWorkerMs\n }\n }\n }\n if (needSeg && !served) {\n // The multiclass model when the recipe wants it and it is up.\n const classes = this.classSegmenter !== null && needsSkinClasses(this.filter, this.effects)\n const seg = classes ? this.classSegmenter : this.segmenter\n if (!seg) {\n // The recipe wants a mask but the segmenter is not up yet. Kick off the load\n // and let this frame through - Go handles the no-mask case itself.\n if (!this.remoteMaskComing(this.filter, this.effects)) void this.ensureSegmenter()\n } else {\n const s0 = performance.now()\n // MediaPipe counts in milliseconds, not microseconds.\n mask = seg.segment(source as VideoFrame, timestampUs / 1000)\n segMs = performance.now() - s0\n this.used = seg\n maskKind = classes ? 1 : 0\n }\n }\n\n // Face detection is STAGGERED against segmentation - the core decides, this only obeys.\n if (faceDone) {\n faceMs = this.faceWorkerMs\n } else if (this.faceRemote && needsFace(this.effects)) {\n this.requestRemote(\"face\", source, timestampUs)\n faceMs = this.faceWorkerMs\n } else if (this.core.decideFace() === 1) {\n if (this.faceRemote) {\n faceMs = this.faceWorkerMs\n } else if (!this.face) {\n void this.ensureFace()\n } else if (this.lmBuf) {\n const f0 = performance.now()\n const n = this.face.detect(source, timestampUs / 1000, this.lmBuf)\n faceMs = performance.now() - f0\n this.core.setFace(lo, hi, n)\n this.faceTs = timestampUs\n }\n }\n\n if (mask) this.maskUsedTs = maskTs\n const [maskLo, maskHi] = splitMicros(maskTs)\n const glCalls = this.core.process(source, mask, this.background, maskKind, maskLo, maskHi)\n\n // Give the mask buffer back right AFTER process, not before - see Segmenter.release.\n if (mask) this.used?.release()\n this.used = null\n this.noteLinking()\n\n if (!this.programErr) {\n const err = this.core.programError?.() ?? \"\"\n if (err) {\n this.programErr = `mediakit: ${err}; makeup and teeth stay off, the rest runs [GPU: ${gpuName(this.gl)}]`\n console.warn(this.programErr)\n }\n }\n\n this.prevSegMs = segMs\n this.prevTotalMs = performance.now() - t0\n\n const s = this.core.stats()\n const parts = this.parts()\n this.last = {\n totalMs: this.prevTotalMs,\n segMs,\n faceMs,\n glCalls,\n segmented: needSeg && mask !== null,\n maskScale: s ? s[1] : 1,\n workScale: s ? s[2] : 1,\n cropCX: s ? s[4] : 0.5,\n cropCY: s ? s[5] : 0.5,\n cropZoom: s ? s[6] : 1,\n needsMask: s ? s[7] > 0.5 : false,\n faceFound: s ? s[8] > 0.5 : false,\n faceSize: s ? s[9] : 0,\n needsFace: s ? s[10] > 0.5 : false,\n autoExposure: s ? s[11] : 0,\n faces: s ? s[12] : 0,\n heldFrames: faceDone ? this.queue.length : 0,\n faceAgeMs: s && s[10] > 0.5 && this.faceTs >= 0 ? (timestampUs - this.faceTs) / 1000 : 0,\n maskAgeMs: (needSeg || remoteMask !== null) && this.maskUsedTs >= 0 ? (timestampUs - this.maskUsedTs) / 1000 : 0,\n effectError: this.programErr || this.loadErr,\n parts,\n partErrors: this.partErrors(parts),\n }\n\n return glCalls > 0\n }\n\n private partFailed(part: Part, what: string, off: string, e: unknown): void {\n if (this.partErr.has(part)) return\n const why = e instanceof LoadTimeout ? e.message : `mediakit: ${what} did not load: ${String((e as Error)?.message ?? e)}`\n this.partErr.set(part, `${why}; ${off} stay off`)\n }\n\n private parts(): PartStates {\n const f = this.filter\n const e = this.effects\n const face: PartState = !needsFace(e)\n ? \"off\"\n : this.failed.has(\"face\")\n ? \"failed\"\n : this.face || this.faceRemote\n ? \"ready\"\n : \"loading\"\n const classes: PartState = !needsSkinClasses(f, e)\n ? \"off\"\n : this.classFailed\n ? \"failed\"\n : this.classSegmenter || this.classRemote\n ? \"ready\"\n : \"loading\"\n let person: PartState = \"off\"\n if (needsSegmentation(f, e)) {\n if (this.segmenter || (this.personRemote && this.personRemoteWanted(f, e))) person = \"ready\"\n else if (this.segmenterLoading || this.personLoading) person = \"loading\"\n else if (this.failed.has(\"segmenter\") || this.failed.has(\"person\")) person = classes === \"ready\" ? \"ready\" : \"failed\"\n else person = classes === \"off\" ? \"loading\" : classes\n }\n let cover: PartState = \"off\"\n if (face !== \"off\" && (e.occluders ?? false)) {\n cover = face === \"loading\" ? \"loading\" : face === \"failed\" || this.inThread.has(\"face\") ? \"failed\" : this.coverState\n }\n return { person, classes, face, cover }\n }\n\n private partErrors(p: PartStates): PartErrors {\n const why = (part: Part) => (p[part] === \"failed\" ? (this.partErr.get(part) ?? \"\") : \"\")\n let cover = why(\"cover\")\n if (p.cover === \"failed\" && !cover) cover = p.face === \"failed\" ? why(\"face\") : COVER_IN_THREAD\n return { person: why(\"person\"), classes: why(\"classes\"), face: why(\"face\"), cover }\n }\n\n /**\n * Wrap the output canvas as a new VideoFrame.\n *\n * The timestamp is the SOURCE frame's, carried through unchanged. It is not rebuilt from\n * ticks: whole microseconds cannot represent a frame boundary at 30fps (a frame is\n * 33333.33 us), so every tick-to-microsecond round trip loses information. Ticks are only\n * for the governor and the graph to decide with. See the ToMicros comment in\n * `core/clock.go`.\n */\n capture(timestampUs: number, keepAlpha = false): VideoFrame {\n return new VideoFrame(this.canvas, { timestamp: timestampUs, alpha: keepAlpha ? \"keep\" : \"discard\" })\n }\n\n close(): void {\n if (this.closed) return\n this.closed = true\n this.segmenter?.close()\n this.segmenter = null\n this.classSegmenter?.close()\n this.classSegmenter = null\n this.face?.close()\n this.face = null\n for (const detect of this.detects.values()) detect.close()\n this.detects.clear()\n this.faceRemote = false\n this.classRemote = false\n if (this.classMaskTex) this.gl.deleteTexture(this.classMaskTex)\n if (this.personMaskTex) this.gl.deleteTexture(this.personMaskTex)\n this.personMaskTex = null\n if (this.mergedTex) this.gl.deleteTexture(this.mergedTex)\n this.mergedTex = null\n this.personBytes = null\n this.classBytes = null\n this.mergedBytes = null\n this.personRemote = false\n this.classMaskTex = null\n this.lmBuf = null\n this.queue = []\n this.spare = []\n this.lastHeld = null\n this.core.close()\n this.background?.close()\n this.background = null\n this.backgroundPath = null\n this.lutPath = \"\"\n this.makeupPath = \"\"\n // Release the context now rather than wait for GC: browsers cap how many live WebGL\n // contexts there are (usually 8-16), and a long meeting can rebuild the pipeline\n // several times. At the cap the OLDEST context is reclaimed - the running one dies,\n // not the new one.\n this.gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n }\n}\n\n/**\n * Decode a background image into an ImageBitmap.\n *\n * Through an `<img>` and not `createImageBitmap(blob)`, because Chrome CANNOT decode SVG out\n * of a Blob: it throws `InvalidStateError: The source image could not be decoded`. Measured\n * 2026-09-26 on Chrome 154, against an SVG carrying width, height AND a viewBox - so it is\n * not the missing-intrinsic-size case. The same file through an `<img>` decodes fine, which\n * is also the route @livekit/track-processors takes.\n *\n * That difference is the whole bug this replaces: a host shipping SVG backgrounds lost every\n * one of them while blur and uploaded JPEGs kept working, and the throw was swallowed by the\n * caller, so the picker simply did nothing.\n *\n * A worker has no `Image`, and there an SVG cannot be decoded at all. Say that, rather than\n * let an InvalidStateError name nothing.\n */\nexport async function decodeImage(path: string, opts?: ImageBitmapOptions): Promise<ImageBitmap> {\n if (typeof Image === \"undefined\") {\n const res = await fetch(path)\n if (!res.ok) throw new Error(`mediakit: cannot load image ${path} (HTTP ${res.status})`)\n const blob = await res.blob()\n try {\n return await createImageBitmap(blob, opts)\n } catch (err) {\n if (blob.type.includes(\"svg\")) {\n throw new Error(\n `mediakit: cannot decode the SVG background ${path} off the main thread - give this transport a raster image`,\n )\n }\n throw err\n }\n }\n\n const img = new Image()\n // Set for the same reason LiveKit sets it: a cross-origin background served without CORS\n // then fails here, loudly, instead of tainting the canvas and throwing SecurityError one\n // step later where the cause is no longer visible.\n img.crossOrigin = \"anonymous\"\n await new Promise<void>((resolve, reject) => {\n img.onload = () => resolve()\n img.onerror = () => reject(new Error(`mediakit: cannot load background image ${path}`))\n img.src = path\n })\n if (!img.naturalWidth || !img.naturalHeight) {\n throw new Error(\n `mediakit: background image ${path} has no intrinsic size - an SVG needs width and height, a viewBox alone is not enough`,\n )\n }\n return createImageBitmap(img, opts)\n}\n\n/**\n * Load a background image and COVER-crop it to the frame aspect.\n *\n * ── Why the crop belongs here ────────────────────────────────────────────────────────\n * The shader samples the background with the frame's own UV coordinates, so an image of a\n * different aspect comes out STRETCHED. Bundled 16:9 backgrounds never show it; an image the\n * user uploaded shows it immediately, and a host that downscales uploads *contain*-style\n * turns a portrait photo into a portrait canvas that is then stretched sideways to fill.\n *\n * Cropping at load rather than in the shader: it happens ONCE when the user picks an image\n * instead of every frame, and it costs no extra uniform - the uniform layout is exactly where\n * a silent bug already came from (T6 in doc/apps/mediakit/PLAN.md), so adding a slot to it is\n * worth avoiding when there is another way.\n */\nasync function loadBitmap(path: string, w: number, h: number): Promise<ImageBitmap> {\n return coverCrop(await decodeImage(path), w, h)\n}\n\n/** The cover crop half of {@link loadBitmap}. Takes ownership of `src`. */\nasync function coverCrop(src: ImageBitmap, w: number, h: number): Promise<ImageBitmap> {\n if (src.width * h === src.height * w) return src // already the right aspect\n\n // The largest region of the source that has the frame's aspect, centred.\n const scale = Math.max(w / src.width, h / src.height)\n const cw = Math.min(src.width, Math.round(w / scale))\n const ch = Math.min(src.height, Math.round(h / scale))\n const out = await createImageBitmap(\n src,\n Math.round((src.width - cw) / 2),\n Math.round((src.height - ch) / 2),\n cw,\n ch,\n { resizeWidth: w, resizeHeight: h, resizeQuality: \"high\" },\n )\n src.close()\n return out\n}\n","import { Engine, NO_PARTS, NO_PART_ERRORS, decodeImage, type FrameStats, type Part, type PartErrors, type PartStates } from \"./engine\"\nimport { NO_EFFECTS, type BgFilter, type DebugView, type Effects } from \"./recipe\"\nimport type { FromWorker, ToWorker } from \"./worker/entry\"\nimport { GpuLostError, gpuRecord, recordLoss, type GpuRecord, type LossPhase } from \"./gpu-guard\"\nimport { assetUrl } from \"./assets\"\n\n/**\n * A camera track in, a processed camera track out.\n *\n * This is the transport layer: it owns nothing about pixels, only about how frames get to the\n * {@link Engine} and back. The host app wraps it in whatever seam its SDK wants - in meet that\n * is a LiveKit `TrackProcessor`, roughly thirty lines.\n *\n * ── The three transports ─────────────────────────────────────────────────────────────\n *\n * worker preferred - same APIs as `insertable`, but the frame streams are transferred\n * into a worker so the Engine runs off the main thread entirely\n * insertable MediaStreamTrackProcessor + MediaStreamTrackGenerator, on this thread\n * canvas anything else - <video> + captureStream\n *\n * The worker path is what clears defect #1 of the LiveKit implementation\n * (doc/apps/mediakit/PLAN.md section 1): MediaPipe's `segmentForVideo` is a SYNCHRONOUS call\n * tens of milliseconds long, so on the main thread it blocks the event loop and the UI\n * stutters the moment background blur goes on.\n *\n * The `canvas` path here still beats LiveKit's on three measurable points:\n * 1. `requestVideoFrameCallback` instead of polling `currentTime` inside\n * `requestAnimationFrame` - on the real frame rhythm, so no jitter.\n * 2. `captureStream` reads the canvas mediakit already drew, dropping one full-frame\n * `drawImage` per frame.\n * 3. No WebCodecs needed: the `<video>` element goes straight into `texImage2D`.\n */\n\nexport type Transport = \"worker\" | \"insertable\" | \"canvas\"\n\nconst SLOW_FRAME_MS = 150\nconst SLOW_TICKS = 3\nconst MAX_GPU_RECOVERIES = 2\n\n/** How long the worker gets to answer \"start\" before the main thread gives up on it. */\nconst WORKER_READY_MS = 8_000\n\n/** No frame out for this long, with the camera live, counts as a stall. */\nconst STALL_MS = 2_000\n/** The same while a detector is loading. */\nconst LOADING_STALL_MS = 20_000\n/** Silence for this long on the worker transport means the worker is gone. */\nconst WORKER_DEAD_MS = 8_000\n\nexport interface PipelineOptions {\n /** Keep the output's alpha channel, for `subscribeFrames` with a `cutout` background. */\n alpha?: boolean\n /**\n * Faces to track, 1-3, default 3. One person per camera should say 1: looking for more re-runs\n * the face detector on every call, about a third of the landmark cost.\n */\n maxFaces?: number\n syncFaces?: boolean\n /** Starts with an inner layer drawn instead of the picture; see `setDebug`. */\n debug?: DebugView\n /** No processed frame for 2 s while the camera is live (20 s while a detector loads). */\n onStall?: (info: { transport: Transport; sinceMs: number }) => void\n /** The pipeline replaced `processedTrack` mid-session. */\n onTrackReplaced?: (track: MediaStreamTrack, previous: MediaStreamTrack | undefined) => void\n /** Something degraded while running; see {@link IssueCode}. Each code fires once until it clears. */\n onIssue?: (issue: PipelineIssue) => void\n}\n\n/** What degraded; each code and what the app should do is in the README, \"Handling a weak or failing GPU\". */\nexport type IssueCode = \"stall\" | \"slow\" | \"effect-off\" | \"part-off\" | \"worker-moved\" | \"gpu-lost\"\n\nexport interface PipelineIssue {\n code: IssueCode\n message: string\n transport: Transport\n}\n\n/** `gpu-blocked`: this GPU lost its WebGL context building mediakit's shaders in the last 3 days. */\nexport type SupportReason = \"no-window\" | \"no-wasm\" | \"no-webgl2\" | \"no-transport\" | \"gpu-blocked\"\n\nexport interface SupportReport {\n supported: boolean\n /** Every reason it cannot run, empty when supported. */\n reasons: SupportReason[]\n /** WebGL2 only through a software rasteriser (SwiftShader, llvmpipe): it runs, but slowly. */\n softwareRenderer: boolean\n /** The GPU the browser reports, \"\" when it hides it. */\n gpu: string\n /** What this browser remembers about `gpu` failing under mediakit; see `forgetGpuFailures`. */\n remembered: GpuRecord | null\n}\n\n/** What `health` reports. */\nexport interface PipelineHealth {\n transport: Transport\n /** Frames out since start, or since the last transport change. */\n frames: number\n /** Milliseconds since a frame last came out. */\n sinceMs: number\n stalled: boolean\n /** Why some effects are off while the picture still runs (see `FrameStats.effectError`); \"\" when none. */\n effectError: string\n parts: PartStates\n partErrors: PartErrors\n}\n\n/** Chrome exposes these on the main thread; the standard versions are worker-only. */\nfunction hasInsertableStreams(): boolean {\n return (\n typeof window !== \"undefined\" &&\n \"MediaStreamTrackProcessor\" in window &&\n \"MediaStreamTrackGenerator\" in window\n )\n}\n\n/** Whether mediakit can run in this browser, and every reason it cannot. Creates and frees two WebGL contexts. */\nexport function checkSupport(): SupportReport {\n if (typeof window === \"undefined\") return { supported: false, reasons: [\"no-window\"], softwareRenderer: false, gpu: \"\", remembered: null }\n const reasons: SupportReason[] = []\n if (typeof WebAssembly === \"undefined\") reasons.push(\"no-wasm\")\n const gl = document.createElement(\"canvas\").getContext(\"webgl2\")\n let gpu = \"\"\n let softwareRenderer = false\n if (!gl) reasons.push(\"no-webgl2\")\n else {\n const info = gl.getExtension(\"WEBGL_debug_renderer_info\")\n gpu = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? \"\")\n const fast = document.createElement(\"canvas\").getContext(\"webgl2\", { failIfMajorPerformanceCaveat: true })\n softwareRenderer = !fast || /swiftshader|llvmpipe|software|basic render/i.test(gpu)\n fast?.getExtension(\"WEBGL_lose_context\")?.loseContext()\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n }\n if (!hasInsertableStreams() && !(\"captureStream\" in HTMLCanvasElement.prototype)) reasons.push(\"no-transport\")\n const remembered = gpuRecord(gpu)\n if (remembered?.init) reasons.push(\"gpu-blocked\")\n probedGpu = gpu\n return { supported: reasons.length === 0, reasons, softwareRenderer, gpu, remembered }\n}\n\nlet probedGpu: string | null = null\n\nfunction probeGpu(): string {\n if (probedGpu !== null) return probedGpu\n const gl = typeof document === \"undefined\" ? null : document.createElement(\"canvas\").getContext(\"webgl2\")\n if (!gl) return \"\"\n const info = gl.getExtension(\"WEBGL_debug_renderer_info\")\n probedGpu = String(gl.getParameter(info ? info.UNMASKED_RENDERER_WEBGL : gl.RENDERER) ?? \"\")\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n return probedGpu\n}\n\n/** Whether mediakit can run in this browser at all; {@link checkSupport} says why not. */\nexport function mediakitSupported(): boolean {\n return checkSupport().supported\n}\n\nexport class VideoPipeline {\n processedTrack?: MediaStreamTrack\n\n private filter: BgFilter\n private effects: Effects\n private opts: PipelineOptions\n private debug: DebugView = \"off\"\n\n // Health: a beat per frame out.\n private source: MediaStreamTrack | null = null\n private size = { width: 1280, height: 720, fps: 30 }\n private lastBeat = 0\n private frames = 0\n private stalled = false\n private watchdog: ReturnType<typeof setInterval> | null = null\n private movedOff = false\n private raised = new Set<string>()\n private slowTicks = 0\n private gpuRecoveries = 0\n private gpu = \"\"\n private faceColorLost = false\n private recovering = false\n private workerDialect: \"streams\" | \"track\" | null = null\n private generator: MediaStreamTrackGenerator<VideoFrame> | null = null\n private piping: Promise<void> = Promise.resolve()\n /** What the worker last said about loading detectors. */\n private workerLoading = false\n\n // Frames handed out alongside the track - see subscribeFrames.\n private frameSubs = new Set<(frame: VideoFrame) => void>()\n private engine: Engine | null = null\n private transport: Transport = \"insertable\"\n\n // insertable path\n private abort: AbortController | null = null\n\n // worker path\n private worker: Worker | null = null\n private workerStats: FrameStats | null = null\n /** The background path the worker already holds; see backgroundForWorker. */\n private workerBackgroundPath: string | null = null\n\n // canvas path\n private video: HTMLVideoElement | null = null\n private rvfcHandle = 0\n private stopped = false\n\n constructor(filter: BgFilter, effects: Effects = NO_EFFECTS, opts: PipelineOptions = {}) {\n this.filter = filter\n this.effects = effects\n this.opts = opts\n this.debug = opts.debug ?? \"off\"\n }\n\n /** Whether frames are coming out, and how long since the last one. */\n get health(): PipelineHealth {\n return {\n transport: this.transport,\n frames: this.frames,\n sinceMs: this.lastBeat ? performance.now() - this.lastBeat : 0,\n stalled: this.stalled,\n effectError: this.stats?.effectError ?? \"\",\n parts: { ...(this.stats?.parts ?? NO_PARTS) },\n partErrors: { ...(this.stats?.partErrors ?? NO_PART_ERRORS) },\n }\n }\n\n /** Every processed frame. */\n subscribeFrames(cb: (frame: VideoFrame) => void): () => void {\n this.frameSubs.add(cb)\n if (this.frameSubs.size === 1) this.send({ t: \"frames\", on: true })\n return () => {\n this.frameSubs.delete(cb)\n if (this.frameSubs.size === 0) this.send({ t: \"frames\", on: false })\n }\n }\n\n private deliver(frame: VideoFrame) {\n const subs = [...this.frameSubs]\n if (subs.length === 0) {\n frame.close()\n return\n }\n subs.forEach((cb, i) => {\n try {\n cb(i === subs.length - 1 ? frame : frame.clone())\n } catch (e) {\n console.error(\"mediakit: frame subscriber threw\", e)\n }\n })\n }\n\n private issue(code: IssueCode, message: string, key: string = code) {\n if (this.raised.has(key)) return\n this.raised.add(key)\n console.warn(`mediakit: ${code}: ${message}`)\n try {\n this.opts.onIssue?.({ code, message, transport: this.transport })\n } catch (e) {\n console.error(\"mediakit: onIssue threw\", e)\n }\n }\n\n private watchQuality() {\n const s = this.stats\n if (!s) return\n if (s.effectError) this.issue(\"effect-off\", s.effectError)\n for (const part of Object.keys(s.parts ?? {}) as Part[]) {\n if (s.parts[part] !== \"failed\") continue\n const why = s.partErrors?.[part] || `mediakit: ${part} failed to load; its effects stay off`\n if (s.effectError && s.effectError.includes(why)) continue\n this.issue(\"part-off\", why, `part-off:${why}`)\n }\n const slow = s.totalMs > SLOW_FRAME_MS || s.faceMs > SLOW_FRAME_MS\n this.slowTicks = slow ? Math.max(1, this.slowTicks + 1) : Math.min(-1, this.slowTicks - 1)\n if (this.slowTicks >= SLOW_TICKS) {\n this.issue(\"slow\", `frames take ${Math.round(s.totalMs)}ms, face detection ${Math.round(s.faceMs)}ms`)\n } else if (this.slowTicks <= -SLOW_TICKS) {\n this.raised.delete(\"slow\")\n }\n const phase = this.engine?.lostDuring\n if (phase) void this.recoverGpu(\"the main-thread WebGL context was lost\", phase)\n }\n\n private noFaceColor(): boolean {\n return this.faceColorLost || (gpuRecord(this.gpu)?.faceColor ?? false)\n }\n\n /** A \"link\" loss rebuilds without face colour, a \"run\" loss as before; an \"init\" loss would only repeat. */\n private async recoverGpu(why: string, phase: LossPhase, gpu = this.gpu) {\n if (this.recovering || this.stopped || !this.source || this.raised.has(\"gpu-lost\")) return\n recordLoss(gpu, phase)\n if (phase === \"link\") this.faceColorLost = true\n const retry = phase !== \"init\" && this.gpuRecoveries < MAX_GPU_RECOVERIES\n const during = phase === \"link\" ? \"linking a makeup shader\" : phase === \"init\" ? \"building the shaders\" : \"while running\"\n const next = !retry ? \"not rebuilding\" : phase === \"link\" ? \"rebuilding without makeup\" : \"rebuilding\"\n this.issue(\"gpu-lost\", `${why} (${during}, ${next})`)\n if (!retry) return\n this.gpuRecoveries++\n this.recovering = true\n try {\n if (this.transport === \"worker\" && phase === \"run\") await this.moveOffWorker(\"lost its WebGL context\")\n else await this.rebuild(this.source)\n this.raised.delete(\"gpu-lost\")\n } catch (e) {\n console.error(\"mediakit: rebuilding after a lost WebGL context failed\", e)\n } finally {\n this.recovering = false\n }\n }\n\n private beat() {\n this.lastBeat = performance.now()\n this.frames++\n this.stalled = false\n }\n\n private startWatchdog() {\n this.stopWatchdog()\n this.lastBeat = performance.now()\n this.watchdog = setInterval(() => {\n if (this.stopped || !this.source) return\n // A camera that is not producing is not a stall of ours.\n if (this.source.readyState !== \"live\" || this.source.muted) {\n this.lastBeat = performance.now()\n return\n }\n if (this.transport === \"canvas\" && typeof document !== \"undefined\" && document.visibilityState !== \"visible\") {\n this.lastBeat = performance.now()\n return\n }\n const since = performance.now() - this.lastBeat\n const loading = this.transport === \"worker\" ? this.workerLoading : (this.engine?.loading ?? false)\n const transport = this.transport\n if (since >= (loading ? LOADING_STALL_MS : STALL_MS) && !this.stalled) {\n this.stalled = true\n this.issue(\"stall\", `no frame out for ${Math.round(since)}ms on the ${transport} transport`)\n this.opts.onStall?.({ transport, sinceMs: since })\n }\n if (!this.stalled) this.raised.delete(\"stall\")\n this.watchQuality()\n if (transport === \"worker\" && since >= (loading ? LOADING_STALL_MS : WORKER_DEAD_MS)) {\n void this.moveOffWorker(\"silent\")\n }\n }, 1_000)\n }\n\n private stopWatchdog() {\n if (this.watchdog) clearInterval(this.watchdog)\n this.watchdog = null\n }\n\n /** The worker failed or stalled AFTER the host published its track. */\n private async moveOffWorker(reason: string) {\n if (this.movedOff || this.stopped || !this.source) return\n this.movedOff = true\n this.issue(\"worker-moved\", `worker ${reason} after start, moving to the main thread`)\n const previous = this.processedTrack\n this.teardownWorker()\n try {\n await this.startMain(this.source)\n } catch (e) {\n console.error(\"mediakit: main-thread fallback failed\", e)\n return\n }\n previous?.stop()\n if (this.processedTrack) this.opts.onTrackReplaced?.(this.processedTrack, previous)\n }\n\n get stats(): FrameStats | null {\n // On the worker path the Engine lives over there, so stats arrive by message.\n return this.transport === \"worker\" ? this.workerStats : (this.engine?.last ?? null)\n }\n\n get transportName(): Transport {\n return this.transport\n }\n\n /** Take over `source` and publish the result on {@link processedTrack}. */\n async start(source: MediaStreamTrack): Promise<void> {\n this.gpu ||= probeGpu()\n const known = gpuRecord(this.gpu)\n if (known?.init) {\n throw new GpuLostError(\"init\", this.gpu, `remembered from ${new Date(known.at).toISOString()}, forgetGpuFailures() retries`)\n }\n const settings = source.getSettings()\n const width = settings.width ?? 1280\n const height = settings.height ?? 720\n\n this.stopped = false\n this.source = source\n this.size = { width, height, fps: settings.frameRate ?? 30 }\n this.frames = 0\n this.movedOff = false\n this.startWatchdog()\n\n // The worker path builds its streams on THIS thread (see startWorker), so the probe\n // belongs here and is honest. Anything short of a \"ready\" still falls through to the\n // transports below, which is what covers a worker that loads and then fails.\n if (\n hasInsertableStreams() &&\n typeof Worker !== \"undefined\" &&\n typeof OffscreenCanvas !== \"undefined\"\n ) {\n try {\n await this.startWorker(source, width, height, await this.backgroundForWorker(this.filter))\n this.transport = \"worker\"\n this.workerDialect = \"streams\"\n return\n } catch (e) {\n this.teardownWorker()\n if (e instanceof GpuLostError) throw e\n console.warn(\"mediakit: worker unusable, falling back to the main thread\", e)\n }\n } else if (typeof Worker !== \"undefined\" && typeof OffscreenCanvas !== \"undefined\") {\n // No insertable streams HERE - Safari keeps them in workers.\n try {\n await this.startWorkerWithTrack(source, width, height, await this.backgroundForWorker(this.filter))\n this.transport = \"worker\"\n this.workerDialect = \"track\"\n return\n } catch (e) {\n this.teardownWorker()\n if (e instanceof GpuLostError) throw e\n console.warn(\"mediakit: no worker transport in this browser, staying on the main thread\", e)\n }\n }\n\n await this.startMain(source)\n }\n\n private async startMain(source: MediaStreamTrack) {\n const { width, height, fps } = this.size\n this.engine = await Engine.create(width, height, this.filter, this.effects, this.opts.alpha ?? false, this.opts.maxFaces, {\n noFaceColor: this.noFaceColor(),\n })\n this.engine.syncFaces = this.opts.syncFaces ?? false\n this.engine.setDebug(this.debug)\n this.transport = hasInsertableStreams() ? \"insertable\" : \"canvas\"\n this.frames = 0\n this.lastBeat = performance.now()\n // A fresh transport gets a fresh watch: if this one stalls too, the host hears again.\n this.stalled = false\n\n if (this.transport === \"insertable\") {\n this.startInsertable(source)\n } else {\n await this.startCanvas(source, fps)\n }\n }\n\n /**\n * Feed a different camera into the running pipeline, as Tencent's `resetCore(input)`. At the\n * same resolution {@link processedTrack} stays the same track; otherwise the pipeline rebuilds\n * and `onTrackReplaced` fires. The caller still owns both sources: neither is stopped here.\n */\n async replaceSource(next: MediaStreamTrack): Promise<MediaStreamTrack | undefined> {\n if (this.stopped || !this.source) throw new Error(\"mediakit: replaceSource before start\")\n const settings = next.getSettings()\n const width = settings.width ?? 1280\n const height = settings.height ?? 720\n if (width !== this.size.width || height !== this.size.height) {\n await this.rebuild(next)\n return this.processedTrack\n }\n if (this.transport === \"worker\" && this.workerDialect === \"streams\") {\n const processor = new MediaStreamTrackProcessor({ track: next as MediaStreamVideoTrack })\n this.send({ t: \"source\", readable: processor.readable }, [processor.readable])\n } else if (this.transport === \"worker\") {\n const clone = next.clone()\n this.send({ t: \"sourceTrack\", track: clone }, [clone as unknown as Transferable])\n } else if (this.transport === \"insertable\") {\n this.pipeInsertable(next)\n } else if (this.video) {\n this.video.srcObject = new MediaStream([next])\n await this.video.play()\n }\n this.source = next\n this.size.fps = settings.frameRate ?? this.size.fps\n this.lastBeat = performance.now()\n return this.processedTrack\n }\n\n private async rebuild(source: MediaStreamTrack) {\n const previous = this.processedTrack\n this.processedTrack = undefined\n this.teardownTransports()\n await this.start(source)\n previous?.stop()\n if (this.processedTrack) this.opts.onTrackReplaced?.(this.processedTrack, previous)\n }\n\n /** Swap the background in place - no pipeline rebuild, so the picture does not flash. */\n async switchTo(filter: BgFilter): Promise<void> {\n this.filter = filter\n await this.pushRecipe()\n }\n\n /**\n * Draw an inner layer instead of the picture: \"skin\" (red smoothing, green whitening, blue face\n * mesh), \"mask\" (the person or class mask) or \"face\" (tracked outlines and necks). \"off\" restores it.\n */\n setDebug(view: DebugView): void {\n this.debug = view\n if (this.worker) this.send({ t: \"debug\", view })\n else this.engine?.setDebug(view)\n }\n\n get debugView(): DebugView {\n return this.debug\n }\n\n /** Change the effects outside the background. */\n async setEffects(effects: Effects): Promise<void> {\n this.effects = effects\n await this.pushRecipe()\n }\n\n private async pushRecipe(): Promise<void> {\n if (this.worker) {\n const filter = this.filter\n const background = await this.backgroundForWorker(filter)\n this.send({ t: \"recipe\", filter, effects: this.effects, background }, background ? [background] : [])\n return\n }\n await this.engine?.setRecipe(this.filter, this.effects)\n }\n\n async stop(): Promise<void> {\n this.stopped = true\n this.stopWatchdog()\n this.source = null\n this.teardownTransports()\n this.processedTrack?.stop()\n this.processedTrack = undefined\n }\n\n private teardownTransports() {\n this.abort?.abort()\n this.abort = null\n this.generator = null\n\n if (this.rvfcHandle && this.video) {\n this.video.cancelVideoFrameCallback?.(this.rvfcHandle)\n }\n this.rvfcHandle = 0\n if (this.video) {\n this.video.pause()\n this.video.srcObject = null\n this.video.remove()\n this.video = null\n }\n\n this.teardownWorker()\n\n this.engine?.close()\n this.engine = null\n }\n\n // ── worker ───────────────────────────────────────────────────────────────────────\n\n /**\n * The image background decoded HERE, for the worker: it has no `Image`, so it cannot decode\n * an SVG, which is every background meet bundles. Only when the path changed - the worker\n * Engine keeps the last one by path, and a slider drag must not decode it again.\n */\n private async backgroundForWorker(filter: BgFilter): Promise<ImageBitmap | undefined> {\n if (filter.kind !== \"image\" || filter.imagePath === this.workerBackgroundPath) return undefined\n const bmp = await decodeImage(filter.imagePath)\n this.workerBackgroundPath = filter.imagePath\n return bmp\n }\n\n private send(m: ToWorker, transfer: Transferable[] = []) {\n this.worker?.postMessage(m, transfer)\n }\n\n private teardownWorker() {\n if (!this.worker) return\n this.send({ t: \"stop\" })\n // terminate() rather than waiting for the stop to be handled: the worker owns nothing\n // the page outlives, and a worker that is already wedged would never get to the stop.\n this.worker.terminate()\n this.worker = null\n this.workerDialect = null\n this.workerStats = null\n this.workerLoading = false\n this.workerBackgroundPath = null\n }\n\n /**\n * Give the worker the frame STREAMS, and keep the track on this thread.\n *\n * ── Why not transfer the track ───────────────────────────────────────────────────\n * The obvious shape is to transfer the camera track into the worker and let it build its\n * own processor and generator there. It does not work, for two independent reasons, and\n * both were measured on 2026-09-26:\n *\n * 1. Chrome 154 does not treat a MediaStreamTrack as transferable at all:\n * `DataCloneError: Value at index 0 does not have a transferable type`. So the whole\n * path fell back to the main thread on every start, on the one browser that has all\n * the APIs it needs.\n * 2. On a browser where the transfer DID succeed it would be worse than useless. A\n * transfer detaches the main-thread object, and a host keeps using it: LiveKit's\n * `setProcessor` calls `attachToElement(_mediaStreamTrack, ...)`, `detachTrack` and\n * registers an `ended` listener on that same object AFTER `init()` returns. Stealing\n * it breaks the camera, not just the effect.\n *\n * A ReadableStream and a WritableStream are both transferable, so the split below moves\n * every frame into the worker with no copy while ownership of the track never leaves this\n * thread. The Engine, MediaPipe and the whole pass chain still run off the main thread,\n * which was the point.\n *\n * The cost: this needs `MediaStreamTrackProcessor` and `MediaStreamTrackGenerator` HERE,\n * so it is the Chrome dialect. A browser that only has them inside a worker (Safari) does\n * not get this path and stays on the canvas transport until someone can test that.\n */\n private startWorker(\n source: MediaStreamTrack,\n width: number,\n height: number,\n background?: ImageBitmap,\n ): Promise<void> {\n const processor = new MediaStreamTrackProcessor({ track: source as MediaStreamVideoTrack })\n // `signalTarget` forwards control signals back to the camera, exactly as on the\n // main-thread transport below.\n const generator = new MediaStreamTrackGenerator({\n kind: \"video\",\n signalTarget: source as MediaStreamVideoTrack,\n })\n\n return this.attachWorker(\n (ready) => {\n this.processedTrack = ready.track ?? generator\n },\n () => generator.stop(),\n () =>\n this.send(\n {\n t: \"start\",\n readable: processor.readable,\n writable: generator.writable,\n width,\n height,\n filter: this.filter,\n effects: this.effects,\n background,\n alpha: this.opts.alpha,\n maxFaces: this.opts.maxFaces,\n syncFaces: this.opts.syncFaces,\n debug: this.debug,\n noFaceColor: this.noFaceColor(),\n },\n background\n ? [processor.readable, generator.writable, background]\n : [processor.readable, generator.writable],\n ),\n )\n }\n\n /** Safari's dialect (see `startTrack` in worker/entry.ts). */\n private startWorkerWithTrack(\n source: MediaStreamTrack,\n width: number,\n height: number,\n background?: ImageBitmap,\n ): Promise<void> {\n const clone = source.clone()\n return this.attachWorker(\n (ready) => {\n if (!ready.track) throw new Error(\"mediakit: the worker sent no track\")\n this.processedTrack = ready.track\n },\n () => clone.stop(),\n () =>\n this.send(\n {\n t: \"startTrack\",\n track: clone,\n width,\n height,\n filter: this.filter,\n effects: this.effects,\n background,\n alpha: this.opts.alpha,\n maxFaces: this.opts.maxFaces,\n syncFaces: this.opts.syncFaces,\n debug: this.debug,\n noFaceColor: this.noFaceColor(),\n },\n background\n ? [clone as unknown as Transferable, background]\n : [clone as unknown as Transferable],\n ),\n )\n }\n\n /** Starts the worker and waits for its \"ready\". */\n private attachWorker(\n onReady: (ready: Extract<FromWorker, { t: \"ready\" }>) => void,\n cleanup: () => void,\n post: () => void,\n ): Promise<void> {\n // A static URL, not new URL(import.meta.url): Turbopack does not bundle workers from\n // source - measured 2026-09-26 - so this package ships the worker pre-bundled in\n // dist/worker.js and the host serves it alongside the other mediakit assets.\n //\n // CLASSIC, not `{ type: \"module\" }`: MediaPipe loads its wasm glue with\n // importScripts(), which a module worker forbids. See the tsup config.\n const worker = new Worker(assetUrl(\"worker.js\"))\n this.worker = worker\n\n return new Promise<void>((resolve, reject) => {\n let settled = false\n const fail = (err: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n // Nothing downstream has this track yet, and a generator left running holds a\n // sink open for frames that will never arrive.\n cleanup()\n reject(err)\n }\n // The timeout is the one that matters: a worker that neither answers nor throws\n // would otherwise leave start() hanging and the user staring at a dead camera.\n const timer = setTimeout(\n () => fail(new Error(`mediakit: worker silent for more than ${WORKER_READY_MS}ms`)),\n WORKER_READY_MS,\n )\n\n worker.onerror = (e) => {\n if (settled) {\n void this.moveOffWorker(e.message || \"crashed\")\n return\n }\n fail(new Error(e.message || \"mediakit: worker failed to load\"))\n }\n\n worker.onmessage = (e: MessageEvent<FromWorker>) => {\n const m = e.data\n if (m.t === \"stats\") {\n this.workerStats = m.stats\n // Stats come every half second, drawn or passed through: the heartbeat.\n this.lastBeat = performance.now()\n if (m.frames >= 0) this.frames = m.frames\n this.workerLoading = m.loading\n this.stalled = false\n return\n }\n if (m.t === \"frame\") {\n this.deliver(m.frame)\n return\n }\n if (m.t === \"lost\") {\n const gpu = m.gpu || this.gpu\n if (settled) void this.recoverGpu(\"the worker's WebGL context was lost\", m.phase, gpu)\n else {\n recordLoss(gpu, m.phase)\n fail(m.phase === \"init\" ? new GpuLostError(\"init\", gpu, m.message) : new Error(\"mediakit: the worker's WebGL context was lost\"))\n }\n return\n }\n if (m.t === \"error\") {\n if (settled) {\n // Past the point where anything can reject.\n console.error(\"mediakit: worker failed after start\", m.message)\n void this.moveOffWorker(\"failed\")\n return\n }\n fail(new Error(m.message))\n return\n }\n this.workerLoading = m.loading\n try {\n onReady(m)\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)))\n return\n }\n settled = true\n clearTimeout(timer)\n if (this.frameSubs.size > 0) this.send({ t: \"frames\", on: true })\n resolve()\n }\n\n try {\n post()\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)))\n }\n })\n }\n\n // ── insertable ───────────────────────────────────────────────────────────────────\n\n private startInsertable(source: MediaStreamTrack) {\n // `signalTarget` forwards control signals (a request-frame, say) back to the camera.\n // Without it, sources that only produce a frame when asked stand still.\n this.generator = new MediaStreamTrackGenerator({\n kind: \"video\",\n signalTarget: source as MediaStreamVideoTrack,\n })\n this.processedTrack = this.generator\n this.pipeInsertable(source)\n }\n\n private pipeInsertable(source: MediaStreamTrack) {\n const generator = this.generator\n if (!generator) return\n const processor = new MediaStreamTrackProcessor({\n track: source as MediaStreamVideoTrack,\n })\n\n const transform = new TransformStream<VideoFrame, VideoFrame>({\n transform: (frame, controller) => {\n this.beat()\n const engine = this.engine\n if (!engine) {\n controller.enqueue(frame)\n return\n }\n try {\n const drew = engine.render(frame, frame.timestamp)\n const held = drew ? null : engine.passthrough()\n if (drew) {\n controller.enqueue(engine.capture(engine.renderedTs))\n if (this.frameSubs.size > 0) this.deliver(engine.capture(engine.renderedTs, true))\n } else if (held) {\n if (this.frameSubs.size > 0) this.deliver(held.clone())\n controller.enqueue(held)\n } else if (!engine.dropped()) {\n // Subscribers get the source frame, as the track does.\n if (this.frameSubs.size > 0) this.deliver(frame.clone())\n // Nothing drawn yet - no mask in the first few frames, or the recipe\n // is inactive. Forward the source frame: dropping it here makes the\n // camera flash black.\n controller.enqueue(frame)\n return\n }\n } catch (e) {\n console.error(\"mediakit: frame processing failed\", e)\n controller.enqueue(frame)\n return\n }\n // Close the source frame IMMEDIATELY after use. Without this the browser\n // pipeline's buffer pool runs dry after a few dozen frames and the camera\n // freezes.\n frame.close()\n },\n })\n\n this.abort?.abort()\n const abort = new AbortController()\n this.abort = abort\n const previous = this.piping\n this.piping = previous.then(() => {\n if (abort.signal.aborted) return\n return processor.readable\n .pipeThrough(transform, { signal: abort.signal })\n .pipeTo(generator.writable, { signal: abort.signal, preventAbort: true, preventClose: true })\n .catch((e: unknown) => {\n if (abort.signal.aborted) return\n if (!this.stopped) console.error(\"mediakit: pipe broke\", e)\n })\n })\n }\n\n // ── canvas ───────────────────────────────────────────────────────────────────────\n\n private async startCanvas(source: MediaStreamTrack, fps: number) {\n const engine = this.engine!\n\n const video = document.createElement(\"video\")\n video.muted = true\n video.playsInline = true\n // Out of the layout flow: this element is only a decode source, never displayed.\n video.style.position = \"fixed\"\n video.style.opacity = \"0\"\n video.style.pointerEvents = \"none\"\n video.width = 1\n video.height = 1\n video.srcObject = new MediaStream([source])\n document.body.appendChild(video)\n this.video = video\n await video.play()\n\n // captureStream reads the canvas mediakit already drew. LiveKit's implementation draws\n // the processed frame onto a SECOND canvas and captures from that - one full-frame\n // copy per frame, to obtain the pixels that were already there.\n //\n // The Engine also accepts an OffscreenCanvas, because a worker has to hand it one.\n // Only this transport calls captureStream, and only it builds the Engine through\n // `create` - so the narrowing cannot fail here. It is checked rather than cast so that\n // moving this code somewhere else fails loudly instead of at runtime.\n const out = engine.outputCanvas\n if (!(out instanceof HTMLCanvasElement)) {\n throw new Error(\"mediakit: the canvas transport needs an HTMLCanvasElement\")\n }\n const stream = out.captureStream(fps)\n this.processedTrack = stream.getVideoTracks()[0]\n\n // requestVideoFrameCallback fires exactly when a NEW frame exists, with an accurate\n // mediaTime. LiveKit runs requestAnimationFrame and compares `video.currentTime` to\n // guess whether a new frame arrived - a rhythm that does not match the camera's, so\n // the picture shimmers slightly and the same frame is sometimes processed twice.\n const pump = (_now: number, meta: VideoFrameCallbackMetadata) => {\n if (this.stopped || !this.engine) return\n this.beat()\n try {\n const ts = Math.round(meta.mediaTime * 1_000_000)\n const drew = this.engine.render(video, ts)\n if (this.frameSubs.size > 0) {\n // Nothing drawn: the source, so a subscriber's picture never freezes.\n this.deliver(drew ? this.engine.capture(ts, true) : new VideoFrame(video, { timestamp: ts }))\n }\n } catch (e) {\n console.error(\"mediakit: frame processing failed\", e)\n }\n this.rvfcHandle = video.requestVideoFrameCallback(pump)\n }\n\n if (typeof video.requestVideoFrameCallback !== \"function\") {\n throw new Error(\n \"mediakit: browser has neither requestVideoFrameCallback nor insertable streams\",\n )\n }\n this.rvfcHandle = video.requestVideoFrameCallback(pump)\n }\n}\n","import { Engine, decodeImage } from \"./engine\"\nimport { loadCore, splitMicros, type MediakitCore } from \"./wasm\"\nimport { NO_EFFECTS, coreRecipe, type BgFilter, type Effects } from \"./recipe\"\nimport { TRANSITIONS, coreLayer, hitTest, parseColor, type Color, type SceneLayer, type TransitionKind } from \"./layout\"\n\n/**\n * Layers several sources onto one output, OBS style: cameras (each with its own mediakit\n * recipe, `cutout` included), screen shares, video files, images, text and any canvas.\n *\n * Main thread only. The layout maths, animations and transitions run in the Go core\n * (`core/scene`); this class owns the sources and their lifetimes and hands each frame's\n * pictures over.\n *\n * Each camera with effects runs its own {@link Engine} on its own WebGL context, and its finished\n * picture is uploaded here like any other source. Browsers cap live contexts at 8-16, so a scene\n * holds at most a handful of processed cameras.\n */\n\nexport type SceneSource =\n /** A camera, processed by its own Engine. No filter and no effects means none is created. */\n | { kind: \"camera\"; track: MediaStreamTrack; filter?: BgFilter; effects?: Effects }\n /** Any video track shown as it is: a screen share, a remote participant, a second camera. */\n | { kind: \"track\"; track: MediaStreamTrack }\n | { kind: \"video\"; url: string; loop?: boolean }\n | { kind: \"image\"; url: string }\n | { kind: \"image\"; bitmap: ImageBitmap }\n | { kind: \"text\"; text: string; style?: TextStyle }\n /** Uploaded every frame: for anything the host draws itself. */\n | { kind: \"canvas\"; canvas: HTMLCanvasElement | OffscreenCanvas }\n\n/** Sizes are in pixels of the text's own picture; the layer then scales it. */\nexport interface TextStyle {\n /** A CSS font. Default `600 48px sans-serif`. */\n font?: string\n color?: Color\n background?: Color\n padding?: number\n radius?: number\n align?: \"left\" | \"center\" | \"right\"\n /** Wraps at this width. Default: no wrapping. */\n maxWidth?: number\n /** A multiple of the font size. Default 1.25. */\n lineHeight?: number\n outline?: { width: number; color: Color }\n}\n\nexport interface SceneOptions {\n width: number\n height: number\n /** The render loop's rate. Default 30. */\n fps?: number\n background?: Color\n}\n\nexport interface SceneStats {\n glCalls: number\n /** Time spent on the last frame, sources included, in milliseconds. */\n frameMs: number\n sources: number\n layers: number\n}\n\nconst MAX_SOURCES = 8\n\ninterface Live {\n slot: number\n spec: SceneSource\n video?: HTMLVideoElement\n engine?: Engine\n /** The engine is being built or rebuilt; frames go through raw meanwhile. */\n engineBusy?: boolean\n picture?: ImageBitmap | HTMLCanvasElement | OffscreenCanvas\n /** A still picture changed and has to be uploaded once. */\n dirty: boolean\n /** A video delivered a frame since the last upload. Only meaningful when `rvfc`. */\n fresh: boolean\n rvfc?: boolean\n}\n\nexport class Scene {\n readonly canvas: HTMLCanvasElement\n private core: MediakitCore\n private gl: WebGL2RenderingContext\n private sources = new Map<string, Live>()\n private current: SceneLayer[] = []\n private fps: number\n private timer: ReturnType<typeof setTimeout> | null = null\n private closed = false\n private recorder: MediaRecorder | null = null\n private recorded: Blob[] = []\n\n last: SceneStats = { glCalls: 0, frameMs: 0, sources: 0, layers: 0 }\n\n private constructor(canvas: HTMLCanvasElement, gl: WebGL2RenderingContext, core: MediakitCore, fps: number) {\n this.canvas = canvas\n this.gl = gl\n this.core = core\n this.fps = fps\n }\n\n static async create(opts: SceneOptions): Promise<Scene> {\n const canvas = document.createElement(\"canvas\")\n canvas.width = opts.width\n canvas.height = opts.height\n // `preserveDrawingBuffer` so a snapshot or captureStream taken between two renders\n // reads the last frame rather than a cleared buffer.\n const gl = canvas.getContext(\"webgl2\", {\n alpha: false,\n premultipliedAlpha: false,\n antialias: false,\n depth: false,\n stencil: false,\n preserveDrawingBuffer: true,\n })\n if (!gl) throw new Error(\"mediakit: no WebGL2 in this browser\")\n let core: MediakitCore | undefined\n try {\n core = await loadCore()\n const err = core.sceneInit(gl, opts.width, opts.height)\n if (err) throw new Error(`mediakit: ${err}`)\n } catch (err) {\n // Give the context back at once - see the cap in Engine.on.\n core?.sceneClose()\n gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n throw err\n }\n const scene = new Scene(canvas, gl, core, opts.fps ?? 30)\n scene.setBackground(opts.background ?? \"#000\")\n return scene\n }\n\n setBackground(c: Color): void {\n const [r, g, b] = parseColor(c)\n this.core.sceneBackground(r, g, b)\n }\n\n /** Add a source, or replace the one with this id; it keeps its slot, so layers stay put. */\n async addSource(id: string, spec: SceneSource): Promise<void> {\n if (this.closed) return\n const old = this.sources.get(id)\n const slot = old ? old.slot : this.freeSlot()\n if (slot < 0) throw new Error(`mediakit: a scene holds at most ${MAX_SOURCES} sources`)\n if (old) this.dispose(old)\n\n const live: Live = { slot, spec, dirty: false, fresh: false }\n this.sources.set(id, live)\n try {\n await this.open(live)\n } catch (err) {\n this.dispose(live)\n if (this.sources.get(id) === live) {\n this.sources.delete(id)\n this.core.sceneUpload(slot, null, 0, 0)\n }\n throw err\n }\n // Replaced or closed while opening: what this call opened belongs to nobody now, and a\n // video left playing here would keep decoding for the life of the page.\n if (this.closed || this.sources.get(id) !== live) {\n this.dispose(live)\n return\n }\n // Layers naming this id were sent hidden while it was missing.\n this.push(0)\n }\n\n /**\n * Change a source without replacing it: new text or style for text, a new recipe for a\n * camera. Anything else is the same as {@link addSource}.\n */\n async updateSource(id: string, spec: SceneSource): Promise<void> {\n const live = this.sources.get(id)\n if (!live || this.closed) return\n if (spec.kind === \"text\" && live.spec.kind === \"text\") {\n live.spec = spec\n live.picture = renderText(spec.text, spec.style)\n live.dirty = true\n return\n }\n if (spec.kind === \"camera\" && live.spec.kind === \"camera\" && spec.track === live.spec.track) {\n live.spec = spec\n await this.ensureEngine(live)\n return\n }\n return this.addSource(id, spec)\n }\n\n removeSource(id: string): void {\n const live = this.sources.get(id)\n if (!live) return\n this.dispose(live)\n this.sources.delete(id)\n this.core.sceneUpload(live.slot, null, 0, 0)\n // A later source may reuse the slot; layers still naming this id must not show it.\n this.push(0)\n }\n\n get layers(): readonly SceneLayer[] {\n return this.current\n }\n\n /** Change the layout in place. With `animate` (ms) layers glide to their new state. */\n setLayers(layers: SceneLayer[], opts: { animate?: number } = {}): void {\n this.current = layers.slice()\n this.push(opts.animate ?? 0)\n }\n\n /** Move to another layout through a transition. */\n switchTo(layers: SceneLayer[], transition: { kind: TransitionKind; duration?: number } = { kind: \"cut\" }): void {\n if (this.closed) return\n this.current = layers.slice()\n const [lo, hi] = splitMicros(now())\n this.core.sceneSwitch(this.coreLayers(), lo, hi, Math.max(0, TRANSITIONS.indexOf(transition.kind)), transition.duration ?? 500)\n }\n\n /** The topmost layer under a point of the output, in fractions, for picking and dragging. */\n layerAt(x: number, y: number): SceneLayer | undefined {\n return hitTest(this.current, x, y, this.canvas.width / this.canvas.height)\n }\n\n start(): void {\n if (this.timer || this.closed) return\n const period = 1000 / this.fps\n let next = performance.now()\n let failed = false\n const tick = () => {\n // One bad frame - a camera's segmenter throwing, say - must not end the loop: the\n // output would freeze on its last frame with nothing reported after the first error.\n try {\n this.render()\n } catch (err) {\n if (!failed) console.error(\"mediakit: scene frame failed\", err)\n failed = true\n }\n // Scheduled against the ideal time rather than \"period from now\", so a slow frame\n // does not push every later one back.\n next += period\n const t = performance.now()\n if (next < t) next = t\n this.timer = setTimeout(tick, next - t)\n }\n tick()\n }\n\n stop(): void {\n if (this.timer) clearTimeout(this.timer)\n this.timer = null\n }\n\n /** Draw one frame now. The loop calls this; a host with its own loop can instead. */\n render(): number {\n if (this.closed) return 0\n const t0 = performance.now()\n const us = now()\n for (const live of this.sources.values()) this.feed(live, us)\n const [lo, hi] = splitMicros(us)\n const calls = this.core.sceneRender(lo, hi)\n this.last = { glCalls: calls, frameMs: performance.now() - t0, sources: this.sources.size, layers: this.current.length }\n return calls\n }\n\n /** The output as a live stream, for a call, a recorder or a `<video>`. */\n captureStream(fps = this.fps): MediaStream {\n return this.canvas.captureStream(fps)\n }\n\n /** The current frame as an image file. */\n snapshot(type = \"image/png\"): Promise<Blob> {\n return new Promise((resolve, reject) =>\n this.canvas.toBlob((b) => (b ? resolve(b) : reject(new Error(\"mediakit: snapshot failed\"))), type),\n )\n }\n\n /** Record the output, optionally with an audio track, until {@link stopRecording}. */\n startRecording(opts: { audio?: MediaStreamTrack; mimeType?: string; videoBitsPerSecond?: number } = {}): void {\n if (this.recorder) return\n const stream = this.captureStream()\n if (opts.audio) stream.addTrack(opts.audio)\n const rec = new MediaRecorder(stream, { mimeType: opts.mimeType, videoBitsPerSecond: opts.videoBitsPerSecond })\n // Collected from the start: with a timeslice the recorder hands a chunk over every second,\n // and the first carries the WebM header - a file missing it does not play at all.\n const chunks: Blob[] = []\n rec.ondataavailable = (e) => chunks.push(e.data)\n this.recorder = rec\n this.recorded = chunks\n rec.start(1000)\n }\n\n stopRecording(): Promise<Blob> {\n const rec = this.recorder\n if (!rec) return Promise.reject(new Error(\"mediakit: not recording\"))\n const chunks = this.recorded\n this.recorder = null\n this.recorded = []\n return new Promise((resolve) => {\n rec.onstop = () => {\n // Only the scene's own capture track: an audio track came from the host.\n for (const t of rec.stream.getVideoTracks()) t.stop()\n resolve(new Blob(chunks, { type: rec.mimeType }))\n }\n rec.stop()\n })\n }\n\n close(): void {\n if (this.closed) return\n this.stop()\n if (this.recorder && this.recorder.state !== \"inactive\") this.recorder.stop()\n for (const t of this.recorder?.stream.getVideoTracks() ?? []) t.stop()\n this.recorder = null\n this.recorded = []\n for (const live of this.sources.values()) this.dispose(live)\n this.sources.clear()\n this.closed = true\n this.core.sceneClose()\n this.gl.getExtension(\"WEBGL_lose_context\")?.loseContext()\n }\n\n private freeSlot(): number {\n const used = new Set([...this.sources.values()].map((s) => s.slot))\n for (let i = 0; i < MAX_SOURCES; i++) if (!used.has(i)) return i\n return -1\n }\n\n private coreLayers() {\n return this.current.map((l) => coreLayer(l, (id) => this.sources.get(id)?.slot ?? -1))\n }\n\n private push(animateMs: number): void {\n if (this.closed) return\n const [lo, hi] = splitMicros(now())\n this.core.sceneSet(this.coreLayers(), lo, hi, animateMs)\n }\n\n private async open(live: Live): Promise<void> {\n const s = live.spec\n switch (s.kind) {\n case \"camera\":\n case \"track\":\n live.video = await playVideo((v) => (v.srcObject = new MediaStream([s.track])))\n watchFrames(live)\n if (s.kind === \"camera\") await this.ensureEngine(live)\n return\n case \"video\":\n live.video = await playVideo((v) => {\n v.src = s.url\n v.loop = s.loop ?? true\n v.crossOrigin = \"anonymous\"\n })\n watchFrames(live)\n return\n case \"image\":\n live.picture = \"bitmap\" in s ? s.bitmap : await decodeImage(s.url)\n live.dirty = true\n return\n case \"text\":\n live.picture = renderText(s.text, s.style)\n live.dirty = true\n return\n case \"canvas\":\n live.picture = s.canvas\n return\n }\n }\n\n /**\n * Build, update or drop a camera's Engine to match its recipe and its current size. An\n * Engine is sized at creation, so a camera that changes resolution needs a new one.\n */\n private async ensureEngine(live: Live): Promise<void> {\n const s = live.spec\n const v = live.video\n // A build already running picks up whatever spec is current when it finishes - see below.\n if (s.kind !== \"camera\" || !v || live.engineBusy) return\n const filter = s.filter ?? { kind: \"none\" }\n const effects = s.effects ?? NO_EFFECTS\n const wanted = filter.kind !== \"none\" || active(effects)\n const w = v.videoWidth\n const h = v.videoHeight\n const e = live.engine\n if (e && wanted && e.outputCanvas.width === w && e.outputCanvas.height === h) {\n await e.setRecipe(filter, effects)\n return\n }\n e?.close()\n live.engine = undefined\n if (!wanted || !w || !h) return\n live.engineBusy = true\n try {\n const canvas = document.createElement(\"canvas\")\n canvas.width = w\n canvas.height = h\n const engine = await Engine.on(canvas, filter, effects, undefined, true)\n if (this.closed || ![...this.sources.values()].includes(live)) engine.close()\n else live.engine = engine\n } finally {\n live.engineBusy = false\n }\n // The recipe changed while the engine was being built, and that call returned early\n // above; bring the new engine up to date.\n if (live.engine && live.spec !== s) await this.ensureEngine(live)\n }\n\n private feed(live: Live, us: number): void {\n const v = live.video\n if (v) {\n if ((live.rvfc && !live.fresh) || v.readyState < 2 || !v.videoWidth) return\n live.fresh = false\n const e = live.engine\n if (e && (e.outputCanvas.width !== v.videoWidth || e.outputCanvas.height !== v.videoHeight)) {\n void this.ensureEngine(live)\n } else if (e && e.render(v, us)) {\n this.core.sceneUpload(live.slot, e.outputCanvas, e.outputCanvas.width, e.outputCanvas.height)\n return\n }\n this.core.sceneUpload(live.slot, v, v.videoWidth, v.videoHeight)\n return\n }\n const p = live.picture\n if (!p) return\n if (live.spec.kind === \"canvas\" || live.dirty) {\n live.dirty = false\n this.core.sceneUpload(live.slot, p, p.width, p.height)\n }\n }\n\n private dispose(live: Live): void {\n live.engine?.close()\n live.engine = undefined\n if (live.video) {\n live.video.pause()\n live.video.srcObject = null\n live.video.removeAttribute(\"src\")\n live.video.load()\n live.video = undefined\n }\n // A bitmap the host handed over stays theirs; one decoded here is closed here.\n const s = live.spec\n if (live.picture instanceof ImageBitmap && !(s.kind === \"image\" && \"bitmap\" in s)) live.picture.close()\n live.picture = undefined\n }\n}\n\nfunction now(): number {\n return Math.round(performance.now() * 1000)\n}\n\nfunction active(e: Effects): boolean {\n const r = coreRecipe({ kind: \"none\" }, e)\n return Object.entries(r).some(([k, v]) => k !== \"background\" && (typeof v === \"number\" ? v !== 0 : v === true))\n}\n\nasync function playVideo(setup: (v: HTMLVideoElement) => void): Promise<HTMLVideoElement> {\n const v = document.createElement(\"video\")\n v.muted = true\n v.playsInline = true\n setup(v)\n await v.play()\n return v\n}\n\n/**\n * Mark a video fresh each time it presents a frame, so a 15 fps screen share is uploaded 15\n * times a second rather than at the scene's rate. Without requestVideoFrameCallback every scene\n * frame counts as fresh.\n */\nfunction watchFrames(live: Live): void {\n const v = live.video\n if (!v || !(\"requestVideoFrameCallback\" in v)) return\n live.rvfc = true\n const on = () => {\n if (live.video !== v) return\n live.fresh = true\n v.requestVideoFrameCallback(on)\n }\n v.requestVideoFrameCallback(on)\n}\n\n/** Draw text onto its own canvas, sized to fit it. */\nexport function renderText(text: string, style: TextStyle = {}): HTMLCanvasElement {\n const font = style.font ?? \"600 48px sans-serif\"\n const pad = style.padding ?? 16\n const c = document.createElement(\"canvas\")\n const ctx = c.getContext(\"2d\")!\n ctx.font = font\n const size = ctx.measureText(\"M\").width * 1.2\n const lineH = size * (style.lineHeight ?? 1.25)\n const lines: string[] = []\n for (const para of text.split(\"\\n\")) {\n if (!style.maxWidth) {\n lines.push(para)\n continue\n }\n let line = \"\"\n for (const word of para.split(/\\s+/)) {\n const next = line ? `${line} ${word}` : word\n if (line && ctx.measureText(next).width > style.maxWidth) {\n lines.push(line)\n line = word\n } else line = next\n }\n lines.push(line)\n }\n const outline = style.outline?.width ?? 0\n const textW = Math.max(1, ...lines.map((l) => ctx.measureText(l).width))\n c.width = Math.ceil(textW + 2 * pad + 2 * outline)\n c.height = Math.ceil(lines.length * lineH + 2 * pad + 2 * outline)\n\n // Resizing the canvas resets its context state.\n ctx.font = font\n if (style.background !== undefined) {\n ctx.fillStyle = css(style.background)\n ctx.beginPath()\n ctx.roundRect(0, 0, c.width, c.height, style.radius ?? 0)\n ctx.fill()\n }\n const align = style.align ?? \"left\"\n ctx.textAlign = align\n ctx.textBaseline = \"middle\"\n const x = align === \"left\" ? pad + outline : align === \"right\" ? c.width - pad - outline : c.width / 2\n lines.forEach((line, i) => {\n const y = pad + outline + lineH * (i + 0.5)\n if (outline > 0) {\n ctx.lineWidth = outline * 2\n ctx.lineJoin = \"round\"\n ctx.strokeStyle = css(style.outline!.color)\n ctx.strokeText(line, x, y)\n }\n ctx.fillStyle = css(style.color ?? \"#fff\")\n ctx.fillText(line, x, y)\n })\n return c\n}\n\nfunction css(c: Color): string {\n const [r, g, b, a] = parseColor(c)\n return `rgba(${Math.round(r * 255)},${Math.round(g * 255)},${Math.round(b * 255)},${a})`\n}\n","// Code generated from MediaPipe's canonical_face_model.obj (mediapipe/modules/face_geometry/data,\n// Apache License 2.0, Copyright The MediaPipe Authors) - the same table as core/facemesh. DO NOT EDIT.\n\n/** Where each of the face landmarker's first 468 landmarks lies on the canonical face texture. */\nexport const FACE_UV = new Float32Array([\n 0.49998, 0.65253, 0.50003, 0.54749, 0.49997, 0.60237, 0.48211, 0.47198, 0.50015, 0.52716,\n 0.49991, 0.49825, 0.49952, 0.40106, 0.28971, 0.38076, 0.49995, 0.31240, 0.49999, 0.26992,\n 0.50002, 0.10705, 0.50002, 0.66623, 0.50002, 0.67922, 0.50002, 0.69235, 0.49998, 0.69528,\n 0.49998, 0.70593, 0.49998, 0.71938, 0.49998, 0.73702, 0.49997, 0.78137, 0.49982, 0.56298,\n 0.47377, 0.57391, 0.10491, 0.25414, 0.36593, 0.40958, 0.33876, 0.41302, 0.31112, 0.40946,\n 0.27466, 0.38913, 0.39336, 0.40371, 0.34523, 0.34401, 0.37009, 0.34608, 0.31932, 0.34727,\n 0.29790, 0.35359, 0.24779, 0.41081, 0.39689, 0.84276, 0.28010, 0.37560, 0.10631, 0.39996,\n 0.20993, 0.39135, 0.35581, 0.53441, 0.47175, 0.65040, 0.47415, 0.68019, 0.43978, 0.65723,\n 0.41462, 0.66654, 0.45037, 0.68086, 0.42877, 0.68269, 0.37497, 0.72781, 0.48672, 0.54763,\n 0.48530, 0.52740, 0.25777, 0.31449, 0.40122, 0.45517, 0.42982, 0.54862, 0.42135, 0.53374,\n 0.27690, 0.53206, 0.48337, 0.49959, 0.33721, 0.28288, 0.29639, 0.29324, 0.16930, 0.19381,\n 0.44758, 0.30261, 0.39239, 0.35389, 0.35449, 0.69678, 0.06731, 0.73011, 0.44274, 0.57283,\n 0.45710, 0.58479, 0.38197, 0.69471, 0.39239, 0.69420, 0.27708, 0.27193, 0.42255, 0.56323,\n 0.38592, 0.28136, 0.38310, 0.25584, 0.33143, 0.11971, 0.22992, 0.23200, 0.36450, 0.18911,\n 0.22962, 0.29954, 0.17329, 0.27875, 0.47288, 0.66620, 0.44683, 0.66853, 0.42276, 0.67389,\n 0.44531, 0.58007, 0.38810, 0.69396, 0.40304, 0.70654, 0.40363, 0.69395, 0.46004, 0.55714,\n 0.43116, 0.69237, 0.45218, 0.69237, 0.47539, 0.69237, 0.46583, 0.77919, 0.47233, 0.73623,\n 0.47309, 0.71786, 0.47312, 0.70463, 0.47303, 0.69528, 0.42794, 0.69528, 0.42648, 0.70354,\n 0.42316, 0.71185, 0.41831, 0.72006, 0.39010, 0.63957, 0.01395, 0.56003, 0.49991, 0.58015,\n 0.41320, 0.69540, 0.40963, 0.70182, 0.46808, 0.60153, 0.42273, 0.58598, 0.46308, 0.59378,\n 0.37212, 0.47341, 0.33456, 0.49607, 0.41167, 0.54696, 0.24218, 0.14768, 0.29078, 0.20145,\n 0.32734, 0.25653, 0.39951, 0.74892, 0.44173, 0.26168, 0.42977, 0.18783, 0.41220, 0.10890,\n 0.28896, 0.39895, 0.21894, 0.43541, 0.41278, 0.39897, 0.25714, 0.35544, 0.42768, 0.43796,\n 0.44834, 0.53694, 0.17856, 0.45755, 0.24731, 0.45719, 0.28627, 0.46767, 0.33283, 0.46071,\n 0.36876, 0.44721, 0.39896, 0.43266, 0.47641, 0.40581, 0.18924, 0.52392, 0.22896, 0.34895,\n 0.49073, 0.56240, 0.40467, 0.48513, 0.01947, 0.40156, 0.42624, 0.42043, 0.39699, 0.54880,\n 0.26647, 0.37698, 0.43912, 0.51896, 0.03231, 0.64436, 0.41905, 0.38716, 0.46278, 0.50575,\n 0.23898, 0.77975, 0.19822, 0.83194, 0.10755, 0.54075, 0.18361, 0.74026, 0.13441, 0.33368,\n 0.38576, 0.88315, 0.49097, 0.57938, 0.38238, 0.50857, 0.17440, 0.39767, 0.31878, 0.39624,\n 0.34336, 0.40060, 0.39610, 0.71022, 0.18788, 0.58854, 0.43099, 0.94407, 0.31899, 0.89829,\n 0.26625, 0.86970, 0.50002, 0.19058, 0.49998, 0.95445, 0.36617, 0.39882, 0.39321, 0.39554,\n 0.41037, 0.39108, 0.19499, 0.34210, 0.38866, 0.36228, 0.36596, 0.35597, 0.34336, 0.35536,\n 0.31878, 0.35834, 0.30141, 0.36316, 0.05813, 0.31908, 0.30141, 0.38745, 0.49999, 0.61843,\n 0.41584, 0.62420, 0.44568, 0.56608, 0.46584, 0.62064, 0.49992, 0.35152, 0.28872, 0.81995,\n 0.33528, 0.85282, 0.44051, 0.90242, 0.12829, 0.79194, 0.40877, 0.37389, 0.45561, 0.45180,\n 0.49988, 0.90899, 0.37544, 0.92419, 0.11421, 0.61502, 0.44866, 0.69528, 0.44802, 0.70463,\n 0.44711, 0.71581, 0.44483, 0.73079, 0.43001, 0.76681, 0.40679, 0.68567, 0.40074, 0.68107,\n 0.39240, 0.67770, 0.36786, 0.66392, 0.24792, 0.60133, 0.45277, 0.42085, 0.43639, 0.35989,\n 0.41616, 0.36871, 0.41339, 0.69237, 0.22802, 0.68357, 0.46827, 0.35267, 0.41136, 0.80433,\n 0.49999, 0.46983, 0.47915, 0.44265, 0.49997, 0.43964, 0.43211, 0.49359, 0.49989, 0.86692,\n 0.49991, 0.82173, 0.45655, 0.81920, 0.34455, 0.74544, 0.37891, 0.57401, 0.37429, 0.78019,\n 0.31969, 0.57074, 0.35716, 0.60427, 0.29528, 0.62158, 0.44775, 0.86248, 0.41099, 0.50872,\n 0.31395, 0.77531, 0.35413, 0.81255, 0.32455, 0.70399, 0.18910, 0.64630, 0.27978, 0.71466,\n 0.13382, 0.68270, 0.33677, 0.64473, 0.42988, 0.46652, 0.45553, 0.54862, 0.43711, 0.55890,\n 0.46729, 0.52992, 0.41471, 0.33522, 0.37705, 0.32278, 0.34411, 0.32015, 0.31288, 0.32233,\n 0.28353, 0.33319, 0.24125, 0.38279, 0.10299, 0.46876, 0.26761, 0.42456, 0.29788, 0.43318,\n 0.33343, 0.43388, 0.36643, 0.42612, 0.39601, 0.41670, 0.42012, 0.41023, 0.00756, 0.48078,\n 0.43295, 0.56952, 0.45864, 0.47909, 0.47347, 0.54574, 0.47609, 0.56383, 0.46847, 0.55506,\n 0.43399, 0.58236, 0.48352, 0.56298, 0.48248, 0.57785, 0.42645, 0.38980, 0.43900, 0.39650,\n 0.45007, 0.40043, 0.28971, 0.36825, 0.27667, 0.36337, 0.51786, 0.47195, 0.71029, 0.38076,\n 0.52623, 0.57391, 0.89509, 0.25414, 0.63407, 0.40958, 0.66124, 0.41302, 0.68888, 0.40946,\n 0.72534, 0.38913, 0.60663, 0.40370, 0.65477, 0.34401, 0.62991, 0.34608, 0.68068, 0.34727,\n 0.70210, 0.35359, 0.75221, 0.41080, 0.60292, 0.84286, 0.71990, 0.37560, 0.89369, 0.39996,\n 0.79008, 0.39135, 0.64400, 0.53449, 0.52825, 0.65040, 0.52585, 0.68019, 0.56022, 0.65723,\n 0.58538, 0.66654, 0.54963, 0.68086, 0.57123, 0.68269, 0.62485, 0.72810, 0.51305, 0.54728,\n 0.51510, 0.52725, 0.74225, 0.31451, 0.59863, 0.45498, 0.57034, 0.54858, 0.57863, 0.53362,\n 0.72309, 0.53205, 0.51645, 0.49964, 0.66280, 0.28292, 0.70362, 0.29327, 0.83071, 0.19381,\n 0.55239, 0.30257, 0.60761, 0.35389, 0.64543, 0.69671, 0.93270, 0.73011, 0.55726, 0.57283,\n 0.54290, 0.58479, 0.61803, 0.69471, 0.60759, 0.69420, 0.72294, 0.27196, 0.57741, 0.56317,\n 0.61408, 0.28139, 0.61691, 0.25589, 0.66851, 0.11991, 0.77009, 0.23202, 0.63554, 0.18925,\n 0.77039, 0.29956, 0.82672, 0.27875, 0.52712, 0.66620, 0.55317, 0.66853, 0.57724, 0.67389,\n 0.55469, 0.58007, 0.61190, 0.69396, 0.59696, 0.70654, 0.59637, 0.69395, 0.53996, 0.55714,\n 0.56884, 0.69237, 0.54782, 0.69237, 0.52461, 0.69237, 0.53409, 0.77914, 0.52767, 0.73623,\n 0.52691, 0.71786, 0.52688, 0.70463, 0.52697, 0.69528, 0.57206, 0.69528, 0.57352, 0.70354,\n 0.57684, 0.71185, 0.58169, 0.72006, 0.60994, 0.63991, 0.98605, 0.56003, 0.58680, 0.69540,\n 0.59037, 0.70182, 0.53192, 0.60154, 0.57727, 0.58593, 0.53692, 0.59379, 0.62754, 0.47335,\n 0.66559, 0.49595, 0.58835, 0.54686, 0.75782, 0.14768, 0.70925, 0.20151, 0.67268, 0.25658,\n 0.60041, 0.74900, 0.55827, 0.26167, 0.57030, 0.18787, 0.58817, 0.10904, 0.71105, 0.39895,\n 0.78107, 0.43541, 0.58725, 0.39893, 0.74287, 0.35545, 0.57216, 0.43765, 0.55187, 0.53657,\n 0.82144, 0.45756, 0.75270, 0.45718, 0.71376, 0.46763, 0.66711, 0.46067, 0.63110, 0.44715,\n 0.60086, 0.43247, 0.52348, 0.40563, 0.81075, 0.52393, 0.77105, 0.34896, 0.50913, 0.56272,\n 0.59529, 0.48502, 0.98053, 0.40156, 0.57350, 0.42000, 0.60299, 0.54869, 0.73353, 0.37698,\n 0.56061, 0.51902, 0.96769, 0.64436, 0.58098, 0.38716, 0.53773, 0.50538, 0.76097, 0.77975,\n 0.80178, 0.83194, 0.89244, 0.54076, 0.81635, 0.74026, 0.86560, 0.33369, 0.61407, 0.88325,\n 0.50895, 0.57944, 0.61794, 0.50832, 0.82561, 0.39768, 0.68122, 0.39624, 0.65664, 0.40060,\n 0.60390, 0.71022, 0.81209, 0.58854, 0.56801, 0.94456, 0.68101, 0.89829, 0.73375, 0.86970,\n 0.63383, 0.39882, 0.60679, 0.39554, 0.58966, 0.39106, 0.80502, 0.34211, 0.61133, 0.36228,\n 0.63404, 0.35597, 0.65664, 0.35536, 0.68122, 0.35834, 0.69859, 0.36316, 0.94187, 0.31908,\n 0.69859, 0.38745, 0.58418, 0.62411, 0.55432, 0.56608, 0.53415, 0.62064, 0.71122, 0.81998,\n 0.66463, 0.85287, 0.55910, 0.90263, 0.87171, 0.79194, 0.59123, 0.37389, 0.54434, 0.45158,\n 0.62456, 0.92419, 0.88577, 0.61503, 0.55134, 0.69528, 0.55198, 0.70463, 0.55289, 0.71581,\n 0.55517, 0.73079, 0.56994, 0.76704, 0.59320, 0.68568, 0.59926, 0.68107, 0.60760, 0.67770,\n 0.63194, 0.66350, 0.75203, 0.60132, 0.54723, 0.42039, 0.56354, 0.35983, 0.58384, 0.36871,\n 0.58661, 0.69237, 0.77192, 0.68358, 0.53160, 0.35248, 0.58837, 0.80444, 0.52080, 0.44256,\n 0.56798, 0.49348, 0.54328, 0.81926, 0.65532, 0.74551, 0.62101, 0.57402, 0.62556, 0.78031,\n 0.68020, 0.57072, 0.64276, 0.60434, 0.70466, 0.62153, 0.55201, 0.86259, 0.58907, 0.50864,\n 0.68595, 0.77536, 0.64573, 0.81264, 0.67534, 0.70398, 0.81086, 0.64631, 0.72012, 0.71467,\n 0.86615, 0.68271, 0.66319, 0.64460, 0.57008, 0.46633, 0.54456, 0.54838, 0.56276, 0.55878,\n 0.53199, 0.53014, 0.58527, 0.33518, 0.62295, 0.32278, 0.65590, 0.32016, 0.68713, 0.32235,\n 0.71648, 0.33320, 0.75876, 0.38279, 0.89701, 0.46877, 0.73239, 0.42455, 0.70211, 0.43316,\n 0.66653, 0.43387, 0.63350, 0.42609, 0.60388, 0.41659, 0.57966, 0.40995, 0.99244, 0.48078,\n 0.56719, 0.56942, 0.54137, 0.47890, 0.52656, 0.54612, 0.52391, 0.56383, 0.53153, 0.55506,\n 0.56604, 0.58233, 0.51631, 0.56305, 0.51747, 0.57788, 0.57359, 0.38981, 0.56070, 0.39533,\n 0.54976, 0.39975, 0.71029, 0.36825, 0.72333, 0.36337,\n])\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,sBAAsB;;;ACA/B,SAAS,uBAAuB;AAGzB,IAAM,SAAS,SAAS,IAAI;AAE5B,IAAM,YAAY;AAAA,EACrB,QAAQ,SAAS,yBAAyB;AAAA,EAC1C,SAAS,SAAS,kCAAkC;AAAA,EACpD,MAAM,SAAS,sBAAsB;AACzC;AAGO,IAAM,UAAU;AAIvB,IAAI,UAAmC;AAGhC,SAAS,gBAAkC;AAC9C,cAAY,gBAAgB,eAAe,MAAM,EAAE,MAAM,CAAC,MAAe;AACrE,cAAU;AACV,UAAM;AAAA,EACV,CAAC;AACD,SAAO;AACX;AAGO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACnC,YAAY,MAAc,IAAY;AAClC,UAAM,aAAa,IAAI,wBAAwB,KAAK,MAAM,KAAK,GAAI,CAAC,IAAI;AACxE,SAAK,OAAO;AAAA,EAChB;AACJ;AAGO,SAAS,YAAe,GAAe,IAAY,MAAc,MAAkC;AACtG,SAAO,IAAI,QAAW,CAAC,SAAS,WAAW;AACvC,QAAI,OAAO;AACX,UAAM,QAAQ,WAAW,MAAM;AAC3B,aAA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