@tradalab/mediakit 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/segmenter.ts","../src/face.ts","../src/wasm.ts","../src/engine.ts","../src/pipeline.ts","../src/scene.ts"],"sourcesContent":["import { FilesetResolver, ImageSegmenter } from \"@mediapipe/tasks-vision\"\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\nconst WASM_DIR = \"/mediakit/mp\"\nconst MODEL_URL = \"/mediakit/selfie_segmenter.tflite\"\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): Promise<Segmenter> {\n const fileset = await FilesetResolver.forVisionTasks(WASM_DIR)\n\n const segmenter = await ImageSegmenter.createFromOptions(fileset, {\n baseOptions: {\n modelAssetPath: MODEL_URL,\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 // 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, 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","import { FaceLandmarker, FilesetResolver } from \"@mediapipe/tasks-vision\"\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\nconst WASM_DIR = \"/mediakit/mp\"\nconst MODEL_URL = \"/mediakit/face_landmarker.task\"\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, 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\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): Promise<FaceDetector> {\n const fileset = await FilesetResolver.forVisionTasks(WASM_DIR)\n\n const landmarker = await FaceLandmarker.createFromOptions(fileset, {\n baseOptions: { modelAssetPath: MODEL_URL, delegate: \"GPU\" },\n canvas,\n runningMode: \"VIDEO\",\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 return {\n detect(frame, timestampMs, out) {\n const res = landmarker.detectForVideo(frame, timestampMs)\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","/**\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\"\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 /** 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 process(frame: unknown, mask: unknown, background: unknown): number\n /** Hand the colour LUT image over once; null clears it. Not per frame - see Pipeline.SetLut. */\n setLut(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 = \"/mediakit/mediakit.wasm\"\nconst EXEC_URL = \"/mediakit/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","import { createSegmenter, type Segmenter } from \"./segmenter\"\nimport { FACE_FLOATS, createFaceDetector, type FaceDetector } from \"./face\"\nimport { loadCore, splitMicros, type MediakitCore } from \"./wasm\"\nimport {\n NO_EFFECTS,\n coreRecipe,\n needsFace,\n needsSegmentation,\n type BgFilter,\n type Effects,\n} from \"./recipe\"\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 /** 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}\n\nconst ZERO_STATS: FrameStats = {\n totalMs: 0,\n segMs: 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}\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\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 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\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 private faceLoading: Promise<void> | null = null\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 ): Promise<Engine> {\n const canvas = document.createElement(\"canvas\")\n canvas.width = width\n canvas.height = height\n return Engine.on(canvas, filter, effects)\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.\n */\n static async on(\n canvas: EngineCanvas,\n filter: BgFilter,\n effects: Effects = NO_EFFECTS,\n background?: ImageBitmap,\n alpha = false,\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 const gl = canvas.getContext(\"webgl2\", {\n alpha,\n premultipliedAlpha: false,\n antialias: false,\n depth: false,\n stencil: false,\n })\n if (!gl) throw new Error(\"mediakit: no WebGL2 in this browser\")\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) throw new Error(`mediakit: ${err}`)\n\n engine = new Engine(canvas, gl, core)\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 get outputCanvas(): EngineCanvas {\n return this.canvas\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 this.core.setRecipe(coreRecipe(filter, effects))\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)) void this.ensureSegmenter()\n if (needsFace(effects)) void this.ensureFace()\n }\n\n private ensureFace(): Promise<void> {\n if (this.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 this.faceLoading = createFaceDetector(this.canvas, Math.max(1, Math.floor(buf.length / FACE_FLOATS)))\n .then((f) => {\n if (this.closed) {\n f.close()\n return\n }\n this.face = f\n this.lmBuf = buf\n })\n .catch((e: unknown) => {\n console.error(\"mediakit: face detector failed to load\", e)\n })\n .finally(() => {\n this.faceLoading = null\n })\n return this.faceLoading\n }\n\n private ensureSegmenter(): Promise<void> {\n if (this.segmenter || this.closed) return Promise.resolve()\n if (this.segmenterLoading) return this.segmenterLoading\n\n this.segmenterLoading = createSegmenter(this.canvas)\n .then((s) => {\n if (this.closed) {\n s.close()\n return\n }\n this.segmenter = s\n })\n .catch((e: unknown) => {\n 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; the transport must\n * forward the original frame rather than drop it.\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) return false\n\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 segMs = 0\n if (needSeg) {\n if (!this.segmenter) {\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 void this.ensureSegmenter()\n } else {\n const s0 = performance.now()\n // MediaPipe counts in milliseconds, not microseconds.\n mask = this.segmenter.segment(source as VideoFrame, timestampUs / 1000)\n segMs = performance.now() - s0\n }\n }\n\n // Face detection is STAGGERED against segmentation - the core decides, this only obeys.\n if (this.core.decideFace() === 1) {\n if (!this.face) {\n void this.ensureFace()\n } else if (this.lmBuf) {\n const n = this.face.detect(source, timestampUs / 1000, this.lmBuf)\n this.core.setFace(lo, hi, n)\n }\n }\n\n const glCalls = this.core.process(source, mask, this.background)\n\n // Give the mask buffer back right AFTER process, not before - see Segmenter.release.\n if (mask) this.segmenter?.release()\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 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 }\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): VideoFrame {\n return new VideoFrame(this.canvas, { timestamp: timestampUs, alpha: \"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.face?.close()\n this.face = null\n this.lmBuf = null\n this.core.close()\n this.background?.close()\n this.background = null\n this.backgroundPath = null\n this.lutPath = \"\"\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 Effects } from \"./recipe\"\nimport type { FromWorker, ToWorker } from \"./worker/entry\"\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\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/** 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 at all. */\nexport function mediakitSupported(): boolean {\n if (typeof window === \"undefined\") return false\n if (typeof WebAssembly === \"undefined\") return false\n const probe = document.createElement(\"canvas\")\n if (!probe.getContext(\"webgl2\")) return false\n return hasInsertableStreams() || \"captureStream\" in HTMLCanvasElement.prototype\n}\n\nexport class VideoPipeline {\n processedTrack?: MediaStreamTrack\n\n private filter: BgFilter\n private effects: Effects\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) {\n this.filter = filter\n this.effects = effects\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 const settings = source.getSettings()\n const width = settings.width ?? 1280\n const height = settings.height ?? 720\n\n this.stopped = false\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 return\n } catch (e) {\n this.teardownWorker()\n console.warn(\"mediakit: worker unusable, falling back to the main thread\", e)\n }\n }\n\n this.engine = await Engine.create(width, height, this.filter, this.effects)\n this.transport = hasInsertableStreams() ? \"insertable\" : \"canvas\"\n\n if (this.transport === \"insertable\") {\n this.startInsertable(source)\n } else {\n await this.startCanvas(source, settings.frameRate ?? 30)\n }\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 /** 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\n this.abort?.abort()\n this.abort = 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.processedTrack?.stop()\n this.processedTrack = undefined\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.workerStats = null\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 // 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(\"/mediakit/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 generator.stop()\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) => fail(new Error(e.message || \"mediakit: worker failed to load\"))\n\n worker.onmessage = (e: MessageEvent<FromWorker>) => {\n const m = e.data\n if (m.t === \"stats\") {\n this.workerStats = m.stats\n return\n }\n if (m.t === \"error\") {\n if (settled) {\n // Past the point where anything can fall back - the host already holds\n // the generator track and has published it. Rejecting a settled promise\n // is a no-op, which is how this used to turn a broken worker into a\n // frozen camera with a clean console. Say it instead.\n console.error(\"mediakit: worker failed after start\", m.message)\n return\n }\n fail(new Error(m.message))\n return\n }\n settled = true\n clearTimeout(timer)\n this.processedTrack = generator\n resolve()\n }\n\n try {\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 },\n background\n ? [processor.readable, generator.writable, background]\n : [processor.readable, generator.writable],\n )\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 const engine = this.engine!\n const processor = new MediaStreamTrackProcessor({\n track: source as MediaStreamVideoTrack,\n })\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 const generator = new MediaStreamTrackGenerator({\n kind: \"video\",\n signalTarget: source as MediaStreamVideoTrack,\n })\n\n const transform = new TransformStream<VideoFrame, VideoFrame>({\n transform: (frame, controller) => {\n try {\n if (engine.render(frame, frame.timestamp)) {\n controller.enqueue(engine.capture(frame.timestamp))\n } else {\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 = new AbortController()\n this.processedTrack = generator\n\n processor.readable\n .pipeThrough(transform, { signal: this.abort.signal })\n .pipeTo(generator.writable, { signal: this.abort.signal })\n .catch((e: unknown) => {\n if (e instanceof DOMException && e.name === \"AbortError\") return\n if (!this.stopped) console.error(\"mediakit: pipe broke\", e)\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 try {\n this.engine.render(video, Math.round(meta.mediaTime * 1_000_000))\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAiB,sBAAsB;AAsBhD,IAAM,WAAW;AACjB,IAAM,YAAY;AAyBlB,eAAsB,gBAClB,QACkB;AAClB,QAAM,UAAU,MAAM,gBAAgB,eAAe,QAAQ;AAE7D,QAAM,YAAY,MAAM,eAAe,kBAAkB,SAAS;AAAA,IAC9D,aAAa;AAAA,MACT,gBAAgB;AAAA;AAAA;AAAA;AAAA,MAIhB,UAAU;AAAA,IACd;AAAA,IACA;AAAA,IACA,aAAa;AAAA;AAAA;AAAA;AAAA,IAIb,oBAAoB;AAAA,IACpB,uBAAuB;AAAA,EAC3B,CAAC;AAGD,MAAI,UAAoC;AAExC,QAAM,UAAU,MAAM;AAClB,aAAS,MAAM;AACf,cAAU;AAAA,EACd;AAEA,SAAO;AAAA,IACH,QAAQ,OAAO,aAAa;AAIxB,cAAQ;AAER,UAAI,UAA+B;AAKnC,gBAAU,gBAAgB,OAAO,aAAa,CAAC,WAAW;AACtD,cAAM,OAAO,OAAO;AACpB,YAAI,KAAM,WAAU,KAAK,kBAAkB;AAE3C,kBAAU;AAAA,MACd,CAAC;AACD,aAAO;AAAA,IACX;AAAA,IACA;AAAA,IACA,QAAQ;AACJ,cAAQ;AACR,gBAAU,MAAM;AAAA,IACpB;AAAA,EACJ;AACJ;;;ACxGA,SAAS,gBAAgB,mBAAAA,wBAAuB;AAgBhD,IAAMC,YAAW;AACjB,IAAMC,aAAY;AAeX,IAAM,cAAc,MAAM;AAMjC,eAAsB,mBAClB,QACA,UACqB;AACrB,QAAM,UAA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W;AACf,UAAI,cAAc,IAAI,MAAM,QAAS,KAAK;AAC1C,UAAI,WAAW,MAAM,GAAG,CAAC;AAAA,IAC7B;AACA,QAAI,YAAY,IAAI,MAAM,SAAS,MAAM;AACzC,QAAI,SAAS,MAAM,GAAG,CAAC;AAAA,EAC3B,CAAC;AACD,SAAO;AACX;AAEA,SAAS,IAAI,GAAkB;AAC3B,QAAM,CAAC,GAAG,GAAG,GAAG,CAAC,IAAI,WAAW,CAAC;AACjC,SAAO,QAAQ,KAAK,MAAM,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,IAAI,GAAG,CAAC,IAAI,CAAC;AACzF;","names":["FilesetResolver","WASM_DIR","MODEL_URL"]}
1
+ {"version":3,"sources":["../src/segmenter.ts","../src/face.ts","../src/wasm.ts","../src/engine.ts","../src/pipeline.ts","../src/scene.ts","../src/facemesh.ts"],"sourcesContent":["import { FilesetResolver, ImageSegmenter } from \"@mediapipe/tasks-vision\"\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\nconst WASM_DIR = \"/mediakit/mp\"\n\n/** Which model: `person` is the selfie segmenter, person against background, 244 kB. */\nexport type SegmenterModel = \"person\" | \"classes\"\n\nconst MODEL_URL: Record<SegmenterModel, string> = {\n person: \"/mediakit/selfie_segmenter.tflite\",\n classes: \"/mediakit/selfie_multiclass_256x256.tflite\",\n}\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 FilesetResolver.forVisionTasks(WASM_DIR)\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 // 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, 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","import { FaceLandmarker, FilesetResolver } from \"@mediapipe/tasks-vision\"\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\nconst WASM_DIR = \"/mediakit/mp\"\nconst MODEL_URL = \"/mediakit/face_landmarker.task\"\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, 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\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): Promise<FaceDetector> {\n const fileset = await FilesetResolver.forVisionTasks(WASM_DIR)\n\n const landmarker = await FaceLandmarker.createFromOptions(fileset, {\n baseOptions: { modelAssetPath: MODEL_URL, delegate: \"GPU\" },\n canvas,\n runningMode: \"VIDEO\",\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 return {\n detect(frame, timestampMs, out) {\n const res = landmarker.detectForVideo(frame, timestampMs)\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","/**\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\"\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 /** 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): 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 /** 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 = \"/mediakit/mediakit.wasm\"\nconst EXEC_URL = \"/mediakit/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","import { createSegmenter, type Segmenter, type SegmenterModel } from \"./segmenter\"\nimport { FACE_FLOATS, createFaceDetector, type FaceDetector } from \"./face\"\nimport { loadCore, splitMicros, type MediakitCore } from \"./wasm\"\nimport {\n NO_EFFECTS,\n coreRecipe,\n needsFace,\n needsSegmentation,\n needsSkinClasses,\n type BgFilter,\n type Effects,\n} from \"./recipe\"\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 /** 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}\n\nconst ZERO_STATS: FrameStats = {\n totalMs: 0,\n segMs: 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}\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\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\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 private faceLoading: Promise<void> | null = null\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 ): 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)\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.\n */\n static async on(\n canvas: EngineCanvas,\n filter: BgFilter,\n effects: Effects = NO_EFFECTS,\n background?: ImageBitmap,\n alpha = false,\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 const gl = canvas.getContext(\"webgl2\", {\n alpha,\n premultipliedAlpha: false,\n antialias: false,\n depth: false,\n stencil: false,\n })\n if (!gl) throw new Error(\"mediakit: no WebGL2 in this browser\")\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) throw new Error(`mediakit: ${err}`)\n\n engine = new Engine(canvas, gl, core)\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 get loading(): boolean {\n return this.segmenterLoading !== null || this.classLoading !== null || this.faceLoading !== null\n }\n\n get outputCanvas(): EngineCanvas {\n return this.canvas\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(\"/mediakit/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\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)) void this.ensureSegmenter()\n if (needsSkinClasses(filter, effects)) void this.ensureClassSegmenter()\n if (needsFace(effects)) void this.ensureFace()\n }\n\n private ensureFace(): Promise<void> {\n if (this.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 this.faceLoading = createFaceDetector(this.canvas, Math.max(1, Math.floor(buf.length / FACE_FLOATS)))\n .then((f) => {\n if (this.closed) {\n f.close()\n return\n }\n this.face = f\n this.lmBuf = buf\n })\n .catch((e: unknown) => {\n console.error(\"mediakit: face detector failed to load\", e)\n })\n .finally(() => {\n this.faceLoading = null\n })\n return this.faceLoading\n }\n\n private ensureClassSegmenter(): Promise<void> {\n if (this.classSegmenter || this.closed) return Promise.resolve()\n if (this.classLoading) return this.classLoading\n this.classLoading = createSegmenter(this.canvas, \"classes\" satisfies SegmenterModel)\n .then((s) => {\n if (this.closed) {\n s.close()\n return\n }\n this.classSegmenter = s\n })\n .catch((e: unknown) => {\n // Not fatal: the person segmenter and the face-held fallback carry on.\n console.error(\"mediakit: multiclass segmenter failed to load\", e)\n })\n .finally(() => {\n this.classLoading = null\n })\n return this.classLoading\n }\n\n private ensureSegmenter(): Promise<void> {\n if (this.segmenter || this.closed) return Promise.resolve()\n if (this.segmenterLoading) return this.segmenterLoading\n\n this.segmenterLoading = createSegmenter(this.canvas)\n .then((s) => {\n if (this.closed) {\n s.close()\n return\n }\n this.segmenter = s\n })\n .catch((e: unknown) => {\n 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; the transport must\n * forward the original frame rather than drop it.\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) return false\n\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 segMs = 0\n this.used = null\n if (needSeg) {\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 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 (this.core.decideFace() === 1) {\n if (!this.face) {\n void this.ensureFace()\n } else if (this.lmBuf) {\n const n = this.face.detect(source, timestampUs / 1000, this.lmBuf)\n this.core.setFace(lo, hi, n)\n }\n }\n\n const glCalls = this.core.process(source, mask, this.background, maskKind)\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\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 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 }\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 this.lmBuf = 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 Effects } from \"./recipe\"\nimport type { FromWorker, ToWorker } from \"./worker/entry\"\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\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 /** 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}\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}\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 at all. */\nexport function mediakitSupported(): boolean {\n if (typeof window === \"undefined\") return false\n if (typeof WebAssembly === \"undefined\") return false\n const probe = document.createElement(\"canvas\")\n if (!probe.getContext(\"webgl2\")) return false\n return hasInsertableStreams() || \"captureStream\" in HTMLCanvasElement.prototype\n}\n\nexport class VideoPipeline {\n processedTrack?: MediaStreamTrack\n\n private filter: BgFilter\n private effects: Effects\n private opts: PipelineOptions\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 /** 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 }\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 }\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 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 console.warn(`mediakit: no frame out for ${Math.round(since)}ms on the ${transport} transport`)\n this.opts.onStall?.({ transport, sinceMs: since })\n }\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 console.warn(`mediakit: 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 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.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 return\n } catch (e) {\n this.teardownWorker()\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 return\n } catch (e) {\n this.teardownWorker()\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)\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 /** 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 /** 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\n this.abort?.abort()\n this.abort = 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.processedTrack?.stop()\n this.processedTrack = undefined\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.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 },\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 },\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(\"/mediakit/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 === \"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 const engine = this.engine!\n const processor = new MediaStreamTrackProcessor({\n track: source as MediaStreamVideoTrack,\n })\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 const generator = new MediaStreamTrackGenerator({\n kind: \"video\",\n signalTarget: source as MediaStreamVideoTrack,\n })\n\n const transform = new TransformStream<VideoFrame, VideoFrame>({\n transform: (frame, controller) => {\n this.beat()\n try {\n if (engine.render(frame, frame.timestamp)) {\n controller.enqueue(engine.capture(frame.timestamp))\n if (this.frameSubs.size > 0) this.deliver(engine.capture(frame.timestamp, true))\n } else {\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 = new AbortController()\n this.processedTrack = generator\n\n processor.readable\n .pipeThrough(transform, { signal: this.abort.signal })\n .pipeTo(generator.writable, { signal: this.abort.signal })\n .catch((e: unknown) => {\n if (e instanceof DOMException && e.name === \"AbortError\") return\n if (!this.stopped) console.error(\"mediakit: pipe broke\", e)\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, 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