@tradalab/mediakit 1.0.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/chunk-5KXLFDFV.js +62 -0
- package/dist/chunk-5KXLFDFV.js.map +1 -0
- package/dist/index.d.ts +189 -0
- package/dist/index.js +722 -0
- package/dist/index.js.map +1 -0
- package/dist/mediakit.wasm +0 -0
- package/dist/recipe.d.ts +99 -0
- package/dist/recipe.js +21 -0
- package/dist/recipe.js.map +1 -0
- package/dist/wasm_exec.js +575 -0
- package/dist/worker.js +4538 -0
- package/dist/worker.js.map +1 -0
- package/package.json +48 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/segmenter.ts","../src/face.ts","../src/wasm.ts","../src/engine.ts","../src/pipeline.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 landmarks into `out` and return how many cells were 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.\n */\n detect(frame: TexImageSource, timestampMs: number, out: Float32Array): number\n close(): void\n}\n\nexport async function createFaceDetector(\n canvas: HTMLCanvasElement | OffscreenCanvas,\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 // One face: this is the user's own camera. More faces is more inference for a result\n // the layer above can only use one of.\n numFaces: 1,\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 const lm = res.faceLandmarks?.[0]\n if (!lm || lm.length === 0) return 0\n\n const n = Math.min(lm.length * 3, out.length)\n for (let i = 0; i * 3 < n; i++) {\n const p = lm[i]\n out[i * 3] = p.x\n out[i * 3 + 1] = p.y\n out[i * 3 + 2] = p.z\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\"\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 /** Returns the GL call count for this frame - the P0.2 gate is measured from it. */\n process(frame: unknown, mask: unknown, background: unknown): number\n /** 12 cells - layout in `statsFloats` in wasmjs/main.go. */\n stats(): Float32Array | null\n close(): void\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 { createFaceDetector, type FaceDetector } from \"./face\"\nimport { loadCore, splitMicros, type MediakitCore } from \"./wasm\"\nimport {\n NO_EFFECTS,\n coreRecipe,\n needsFace,\n needsMask,\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}\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}\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 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 static async on(\n canvas: EngineCanvas,\n filter: BgFilter,\n effects: Effects = NO_EFFECTS,\n ): Promise<Engine> {\n const width = canvas.width\n const height = canvas.height\n\n // `premultipliedAlpha: false` because the shaders blend themselves; `alpha: false`\n // because the output is always opaque and the alpha channel is 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: false,\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)\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 /** Change the recipe without rebuilding the pipeline, so dragging a slider does not flash. */\n async setRecipe(filter: BgFilter, effects: Effects = this.effects): Promise<void> {\n if (this.closed) return\n this.filter = filter\n this.effects = effects\n\n if (filter.kind === \"image\" && filter.imagePath !== this.backgroundPath) {\n const bmp = await loadBitmap(filter.imagePath, this.canvas.width, this.canvas.height)\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 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 (needsMask(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 this.faceLoading = createFaceDetector(this.canvas)\n .then((f) => {\n if (this.closed) {\n f.close()\n return\n }\n this.face = f\n this.lmBuf = this.core.faceBuffer()\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 }\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 // 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 */\nasync function decodeImage(path: string): Promise<ImageBitmap> {\n if (typeof Image === \"undefined\") {\n const res = await fetch(path)\n if (!res.ok) throw new Error(`mediakit: cannot load background image ${path} (HTTP ${res.status})`)\n const blob = await res.blob()\n try {\n return await createImageBitmap(blob)\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)\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 const src = await decodeImage(path)\n\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, 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\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)\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 this.send({ t: \"recipe\", filter: this.filter, effects: this.effects })\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 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 }\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(source: MediaStreamTrack, width: number, height: number): 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 },\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"],"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,QAA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IAC9D,CAAC;AAAA,EACT;AAAA;AAAA,EAIA,MAAc,YAAY,QAA0B,KAAa;AAC7D,UAAM,SAAS,KAAK;AAEpB,UAAM,QAAQ,SAAS,cAAc,OAAO;AAC5C,UAAM,QAAQ;AACd,UAAM,cAAc;AAEpB,UAAM,MAAM,WAAW;AACvB,UAAM,MAAM,UAAU;AACtB,UAAM,MAAM,gBAAgB;AAC5B,UAAM,QAAQ;AACd,UAAM,SAAS;AACf,UAAM,YAAY,IAAI,YAAY,CAAC,MAAM,CAAC;AAC1C,aAAS,KAAK,YAAY,KAAK;AAC/B,SAAK,QAAQ;AACb,UAAM,MAAM,KAAK;AAUjB,UAAM,MAAM,OAAO;AACnB,QAAI,EAAE,eAAe,oBAAoB;AACrC,YAAM,IAAI,MAAM,2DAA2D;AAAA,IAC/E;AACA,UAAM,SAAS,IAAI,cAAc,GAAG;AACpC,SAAK,iBAAiB,OAAO,eAAe,EAAE,CAAC;AAM/C,UAAM,OAAO,CAAC,MAAc,SAAqC;AAC7D,UAAI,KAAK,WAAW,CAAC,KAAK,OAAQ;AAClC,UAAI;AACA,aAAK,OAAO,OAAO,OAAO,KAAK,MAAM,KAAK,YAAY,GAAS,CAAC;AAAA,MACpE,SAAS,GAAG;AACR,gBAAQ,MAAM,qCAAqC,CAAC;AAAA,MACxD;AACA,WAAK,aAAa,MAAM,0BAA0B,IAAI;AAAA,IAC1D;AAEA,QAAI,OAAO,MAAM,8BAA8B,YAAY;AACvD,YAAM,IAAI;AAAA,QACN;AAAA,MACJ;AAAA,IACJ;AACA,SAAK,aAAa,MAAM,0BAA0B,IAAI;AAAA,EAC1D;AACJ;","names":["FilesetResolver","WASM_DIR","MODEL_URL"]}
|
|
Binary file
|
package/dist/recipe.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge between what the user picked and the recipe the Go core takes.
|
|
3
|
+
*
|
|
4
|
+
* Both halves live here because both map onto `core.Recipe` field for field: BgFilter carries
|
|
5
|
+
* the background mode and its one parameter, Effects carries everything else. They are two
|
|
6
|
+
* types rather than one because the UI edits them from two different places - a preset picker
|
|
7
|
+
* and a slider panel - not because they belong to different layers.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* What replaces the background.
|
|
11
|
+
*
|
|
12
|
+
* `imagePath` is a URL the consuming app serves: a path under its own public root, or a data
|
|
13
|
+
* URL for something the user uploaded. The Engine fetches it and cover-crops it to the frame
|
|
14
|
+
* aspect, so any shape is safe to pass.
|
|
15
|
+
*/
|
|
16
|
+
type BgFilter = {
|
|
17
|
+
kind: "none";
|
|
18
|
+
} | {
|
|
19
|
+
kind: "blur";
|
|
20
|
+
blurRadius: number;
|
|
21
|
+
} | {
|
|
22
|
+
kind: "image";
|
|
23
|
+
imagePath: string;
|
|
24
|
+
};
|
|
25
|
+
interface Effects {
|
|
26
|
+
/** Skin smoothing, 0..1. Needs the person mask, so it pulls in the segmentation cost. */
|
|
27
|
+
beautify: number;
|
|
28
|
+
/** Exposure, -1..1. Positive lifts the shadows more than the highlights. */
|
|
29
|
+
exposure: number;
|
|
30
|
+
/** Contrast, -1..1. */
|
|
31
|
+
contrast: number;
|
|
32
|
+
/** Saturation, -1..1. */
|
|
33
|
+
saturation: number;
|
|
34
|
+
/** Warm (positive) or cool (negative), -1..1. */
|
|
35
|
+
warmth: number;
|
|
36
|
+
/** Keep the person framed. Needs the person mask. */
|
|
37
|
+
autoframe: boolean;
|
|
38
|
+
/** Teeth whitening, 0..1. */
|
|
39
|
+
teeth: number;
|
|
40
|
+
/** Brighten the whites of the eyes, 0..1. */
|
|
41
|
+
eyeBright: number;
|
|
42
|
+
/** Reduce under-eye shadow, 0..1. */
|
|
43
|
+
underEye: number;
|
|
44
|
+
/**
|
|
45
|
+
* Jawline slimming, 0..1.
|
|
46
|
+
*
|
|
47
|
+
* Deliberately NOT offered in meet: Zoom, Google Meet and Teams all ship without face
|
|
48
|
+
* reshaping, and in a work setting it reads as unserious. The field is here because the
|
|
49
|
+
* second consumer of mediakit is slate, where reshaping is ordinary.
|
|
50
|
+
*/
|
|
51
|
+
slimFace: number;
|
|
52
|
+
/** Eye enlargement, 0..1. Withheld from meet for the same reason as slimFace. */
|
|
53
|
+
enlargeEyes: number;
|
|
54
|
+
}
|
|
55
|
+
declare const NO_EFFECTS: Effects;
|
|
56
|
+
/** Go-side `BackgroundMode`. Must match `core/recipe.go`. */
|
|
57
|
+
declare const MODE_NONE = 0;
|
|
58
|
+
declare const MODE_BLUR = 1;
|
|
59
|
+
declare const MODE_IMAGE = 2;
|
|
60
|
+
declare function backgroundMode(f: BgFilter): number;
|
|
61
|
+
/**
|
|
62
|
+
* Whether this recipe needs the person mask.
|
|
63
|
+
*
|
|
64
|
+
* Must match `Recipe.NeedsMask` on the Go side. This is the single biggest saving in the
|
|
65
|
+
* module: a colour-only recipe skips MediaPipe entirely - the most expensive part of a frame,
|
|
66
|
+
* and 9 MB of wasm the user then never downloads.
|
|
67
|
+
*
|
|
68
|
+
* The Go version is authoritative; this one exists so the JS side knows whether to load the
|
|
69
|
+
* segmenter at all, BEFORE it can ask Go.
|
|
70
|
+
*/
|
|
71
|
+
declare function needsMask(f: BgFilter, e: Effects): boolean;
|
|
72
|
+
/**
|
|
73
|
+
* Whether this recipe needs face landmarks.
|
|
74
|
+
*
|
|
75
|
+
* Must match `Recipe.NeedsFace` on the Go side. Split from {@link needsMask} because the two
|
|
76
|
+
* detectors are independent costs, and the landmark model is 15 times the size of the
|
|
77
|
+
* segmentation one - making someone who only wants a blurred background download it is waste
|
|
78
|
+
* that shows up on the first load.
|
|
79
|
+
*/
|
|
80
|
+
declare function needsFace(e: Effects): boolean;
|
|
81
|
+
/** The recipe in the shape the Go core takes. Field names must match `setRecipe` in wasmjs/main.go. */
|
|
82
|
+
interface CoreRecipe {
|
|
83
|
+
background: number;
|
|
84
|
+
blurRadius: number;
|
|
85
|
+
beautify: number;
|
|
86
|
+
exposure: number;
|
|
87
|
+
contrast: number;
|
|
88
|
+
saturation: number;
|
|
89
|
+
warmth: number;
|
|
90
|
+
autoframe: boolean;
|
|
91
|
+
teeth: number;
|
|
92
|
+
eyeBright: number;
|
|
93
|
+
underEye: number;
|
|
94
|
+
slimFace: number;
|
|
95
|
+
enlargeEyes: number;
|
|
96
|
+
}
|
|
97
|
+
declare function coreRecipe(f: BgFilter, e: Effects): CoreRecipe;
|
|
98
|
+
|
|
99
|
+
export { type BgFilter, type CoreRecipe, type Effects, MODE_BLUR, MODE_IMAGE, MODE_NONE, NO_EFFECTS, backgroundMode, coreRecipe, needsFace, needsMask };
|
package/dist/recipe.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MODE_BLUR,
|
|
3
|
+
MODE_IMAGE,
|
|
4
|
+
MODE_NONE,
|
|
5
|
+
NO_EFFECTS,
|
|
6
|
+
backgroundMode,
|
|
7
|
+
coreRecipe,
|
|
8
|
+
needsFace,
|
|
9
|
+
needsMask
|
|
10
|
+
} from "./chunk-5KXLFDFV.js";
|
|
11
|
+
export {
|
|
12
|
+
MODE_BLUR,
|
|
13
|
+
MODE_IMAGE,
|
|
14
|
+
MODE_NONE,
|
|
15
|
+
NO_EFFECTS,
|
|
16
|
+
backgroundMode,
|
|
17
|
+
coreRecipe,
|
|
18
|
+
needsFace,
|
|
19
|
+
needsMask
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=recipe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|