npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tradalab/mediakit

v2.10.0

Published

Tradalab realtime camera processing

Readme

@tradalab/mediakit

Realtime camera processing in the browser: a camera track goes in, a processed camera track comes out. Background replacement and blur, skin smoothing, colour adjustment, autoframing and face retouching.

The examples named below live in the repository under web/example/; make example serves them.

Upgrading to 2.10.0

No change to the API an app calls; serve the new worker.js, detect-worker.js and mediakit.wasm, and install @tradalab/tskit, now a dependency (a bundler picks it up; a page that loads dist/index.js through an import map maps @tradalab/tskit/assets and @tradalab/tskit/progress too, as the examples do).

New: every file mediakit fetches is downloaded once per origin and kept. The MediaPipe runtime, the models, the face cover and its onnxruntime wasm, mediakit.wasm and wasm_exec.js now go through one manager on the page (@tradalab/tskit/assets): workers ask the page for them instead of fetching on their own, and the bytes are kept in Cache Storage under mediakit-v<version>, which does not depend on HTTP caching. Measured on Edge with three pipelines started at once on a server sending no cache headers (the case of a self-signed certificate): 15 requests before, 6 of them for the 13.5 MB MediaPipe wasm; 4 now, one per file; 0 on the next page load, where the first pipeline was ready in 1.7 s instead of 2.6 s. Output pixels unchanged. Where Cache Storage is missing (not a secure context) the files are kept in memory for the page. The files of older mediakit versions are deleted from Cache Storage the first time a page of this version uses mediakit.

The MediaPipe runtime, wasm_exec.js and onnxruntime's glue now load from blob: URLs made from those bytes. A page with a Content-Security-Policy has to allow blob: in script-src (and in worker-src where it is set); without it the detectors fail to load and health.parts says so.

New: clearCachedAssets() deletes what this version keeps on disk, for a "free up space" setting. Pipelines already running keep working; the next one downloads what it needs again.

preloadDetectors keeps its signature and its progress rules; it now fills Cache Storage rather than the HTTP cache, so it helps on hosts that do not send cache headers too. Images the app gives (backgrounds, LUTs, makeup textures) are still fetched as before.

Upgrading to 2.9.0

No change for an app that does not read the new fields; serve the new worker.js, detect-worker.js and mediakit.wasm.

New: what each detector is doing, in health.parts and FrameStats.parts. One state per part - person, classes, face and cover (the face cover behind occluders) - each "off" (the recipe does not need it), "loading", "ready" or "failed", and partErrors with the reason for each failed part ("" for the others). An app can show "filter ready" before going live, or "getting the filter ready" while a part loads, without guessing from which effects show. On a fake camera with lipstick, smoothing and occluders: all four "off" before the first frame, person, face and cover "loading" at 0.5 s and "ready" at 1 s. cover follows face: "loading" while landmarks load, "failed" when they fail, with their reason.

Fix: a detector that failed was told to nobody unless it timed out. Only a load over 60 s reached effectError; a 404 on a model, a wasm error, or a face cover that did not load turned the effects off with nothing but a console line - for the cover, makeup on hands for the whole session. Now the part turns "failed", partErrors says why (mediakit: face detection did not load: Failed to fetch model: /mediakit/face_landmarker.task (404); face effects stay off, mediakit: the face cover model did not load: ...; occluders stays off) and onIssue fires the new code part-off once per reason, unless effect-off already said the same. Without the detect worker the cover is "failed" too: it runs only there. The cover model now also gives up after 60 s, as the MediaPipe models do. With syncFaces, cover is the state of the first face worker; the second one's cover does not change it.

New: preloadDetectors(parts, onProgress) reports the download as it goes: { loaded, total, done, files } - bytes so far, the sum of the files' sizes, and files finished out of files asked for. total is 0 until every file's headers are in, and stays 0 when one of them gives no usable size (no Content-Length, or a compressed response, whose Content-Length is not the size the browser hands over); show done/files then. loaded never passes a known total. It is called at the start, at most every 100 ms while bytes arrive, and once per finished file, the last call with done === files. A file that fails, or answers with an error status, counts as done and adds no bytes; one that breaks off partway takes back the bytes it had sent, so loaded can drop. A callback that throws is not called again. The MediaPipe runtime and onnxruntime load in workers that report nothing, so this is the only progress there is: an app that wants a progress line calls preloadDetectors when the camera screen opens and shows it, and the detectors then load from the HTTP cache.

Upgrading to 2.8.0

No change at runtime for a recipe that already works: serve the new worker.js, detect-worker.js and mediakit.wasm, as with every release.

New: mediakit-assets copies what has to be served. Every app kept its own script with the list of files under /mediakit/, so each release that added one (2.7.0 added face_cover.onnx and onnxruntime-web's wasm) had to be followed in every app by hand, and a file left out showed only as an effect that did nothing. The list now ships with the package and the command copies it, with the version rules for the MediaPipe and onnxruntime wasm; see "Serve the assets first". Replace the app's script with mediakit-assets <public dir>/mediakit --parts=... --models=skip in predev and prebuild (--models=fetch once, where the network is there), and --check where a build has to fail on a missing file.

New: preloadDetectors({ cover: true }) also fetches face_cover.onnx and the onnxruntime wasm (15 MB) at low priority, whether or not the MediaPipe runtime loads. Without it the first recipe with occluders on a machine draws makeup over a hand for the seconds that download takes.

Upgrading to 2.7.0

Upgrade the package and serve its mediakit.wasm; the one new recipe field, occluders, is off by default and, when on, needs two more files served (face_cover.onnx and the onnxruntime-web wasm, both in the table under "Serve the assets first").

Fix: whitening and skin light stopped in a straight line across the forehead. With the face mesh up and skinScope: "face", skin outside the 478-point mesh was the neck alone, so every skin effect ended where MediaPipe's mesh ends, part-way up the forehead - plain from whiten about 0.5 or skinLight about 0.25. Outside the mesh the face scope now also takes the ring round the head, held to this person's skin colour (as without the mesh), fading in as the mesh fades out: the forehead lightens up to the hairline, hair and hats stay as they were.

Fix: above the face mesh, brown or dark hair in dim light passed as skin. The face scope there kept any pixel of this person's skin chroma, so whitening ran past the hairline up to an oval round the head. It now also drops what is under 0.3-0.5 or over 1.35-1.7 of the measured forehead luma (and, with the multiclass mask, what it calls hair): the effects stop at the hairline, strand by strand. Hair close to the skin in both colour and brightness still passes without the multiclass mask.

Fix: smoothing at the hairline. Above the mesh, smoothing was weighed per sharp pixel, so it smoothed the skin between hair strands and left the strands as dark dashes along the hairline; and with smoothing alone there was no measured forehead luma, so nothing stopped it at the hair. It is now weighed on the smoothed frame and fades where a darker neighbour (the hair) is within about the smoothing radius, so the whole forehead is smoothed and the strands are not touched; beautify with skinScope: "face" now measures the skin reference too.

Fix: a whitened face over an untouched neck read as a mask. Under the jaw the hair gate above dropped a neck in shadow, and the neck region was a narrow band under the chin that missed the side of the neck on a turned head. The neck now drops only what is under 0.12-0.25 of the forehead luma (a beard), reaches the sides of the jaw, and just outside the mesh inside the face outline the skin takes the mesh's wider colour band. On the e2e clips the face skin covered at full whitening rose from 73.5 % to 75.9 % and from 70.5 % to 72 %, with the share landing on skin unchanged.

Fix: a tone kept off products trailed the person by up to 600 ms. gradeScope: "person" and "skin" (and hair) read the multiclass segmenter, about 85 ms a frame in its worker, so its mask came about seven times a second and the tone's edge, and the face scope above the mesh, lagged a moving body. The person segmenter (about 18 ms) now runs beside it in its own worker: its fresh mask is the person's outline every frame, and the latest multiclass labels (skin, hair, a held product) fill it. In a test run with a tone and products kept: mask age from 100-630 ms to 0-33 ms, 24 to 28 fps. Such a recipe now also fetches the 244 kB person model.

Fix: whitening stopped part way down the neck. The neck region ended a third of a face below the chin, so a long neck showed a whitened upper part over an untouched lower part. It now fades out between 0.3 and 1 face-height below the chin. Neck skin covered at full whitening on the e2e clips: 10 % to 71 %, 24 % to 90 % and 19 % to 59 %.

Fix: with syncFaces, makeup and the skin effects trailed a moving face and spilled past it. The face landmarker runs on the CPU in its worker (on the GPU it queues behind the drawing and takes 60-165 ms), about 27-40 ms a call, longer than a frame: only 37-49 % of frames had landmarks of their own, and the rest were drawn with landmarks 33-80 ms old, carried along the face's velocity, which overshoots when the head turns back. syncFaces now runs a second face worker, so every frame is sent for detection, and draws each held frame only once its own landmarks are in (or, for a frame no worker was free for, landmarks interpolated between the frames on either side); the person and multiclass masks are kept by timestamp the same way, so each frame takes the mask of its own frame or the nearest to it. At most 3 frames are held, and one frame a second is dropped while more are queued than needed. Lipstick on a face moving 20 px a frame, with maxFaces: 1: trail p90 25 -> 4-6 px (max 56 -> 15-25); on the 3x-speed e2e clips lipstick spilling past the lips p90 0.52 -> 0.03 and 0.16 -> 0.07. The cost is a second face worker (one more MediaPipe runtime and CPU core while the face is tracked) and latency: the frame waits for its landmarks, 67-100 ms from camera to output in the e2e runs; an app streaming the result should delay its audio by stats.heldFrames frames to keep lip sync.

Fix: makeup still trailed a face moving slowly, by one to four frames, with or without syncFaces. Two filters sat between a frame's landmarks and the frame drawn. The face tracker smoothed every landmark with a 0.12 s time constant, a quarter of the way a frame, and let go only for a jump over about 9 px a frame, so talking, nodding and turning the head were drawn three to four frames late while fast test motion was not. And the landmarker ran in MediaPipe's video mode, which smooths a single face's landmarks over time: another 0.3-0.7 of a frame. The landmarker now runs per frame in image mode (same cost, about 25 ms) and the tracker's time constant is 0.03 s. Measured on a fake camera playing the e2e clips, lipstick against reference landmarks of the very camera frame: frames drawn with an earlier frame's lips 42-71 % -> 14-27 %, mean lag 0.7-1.9 -> 0-0.4 frames, lip overlap p50 0.59 -> 0.67 on the 1x clip. Image mode finds the face anew in every frame and, on the whole picture, loses it more often than video mode did; the next entry is what keeps it.

Fix: the face dropped out for a few frames when it turned, was small in the frame or was half covered. Landmarks were found on the whole frame scaled to 512 px, where MediaPipe's face detector sees a face a tenth of the frame wide at about 15 px, so a turned head or a cup at the mouth sat at its threshold. On a fake camera playing the e2e clips 128 of 699 detections found no face: most frames of a sip, and 16 with the lips in plain view, where makeup blinked off or stayed behind where the face had been. Each frame is now cut to a square round the face of the frames before it (2.6 times its size, drawn at 384 px), so the detector sees the face large; when that finds nothing the worker tries once more on a tighter cut (2 times), and after a real miss the next frame goes back to the whole picture. The detector keeps no state, so nothing lags. On the same clips: no detection without a face, 10 of about 640 found on the second try. The same detection run in Python on a synthetic clip, a frontal portrait under known motion: lip position error p50 2.8 -> 1.3 px and frame-to-frame jitter 2.7 -> 0.9 px at 1280 px, and the face is kept while a hand covers the mouth (44 frames lost -> 0). On the strongly turned face of the cafe clip the lip outline sits where full-frame detection puts it (overlap with full-resolution reference landmarks p50 0.83 and 0.82); the tight cut alone lost nothing either but moved a turned face's lips towards the cheek (0.72), which is why it is only the second try. The crop takes the box round every face found; when that box does not fit a square of the frame, detection runs on the whole frame as before. While maxFaces has free slots, one detection a second runs on the whole frame to find a newcomer. A face lost by the crop is looked for twice more in a crop two and three times as wide before the crop is dropped. With no face at all, every other detection runs on one square of a grid of half the frame's height instead of the whole frame, starting where the face was last: a face 70 px wide, which the whole frame at 512 px never finds, is found within about a second and then followed (on the fake-camera clip, lipstick missing in 233 -> 1 of 233 frames). A detection that saw only part of the frame and found fewer faces than are followed changes nothing. Detection in the page thread, without the detect worker, keeps MediaPipe's video mode and the whole frame. Of two faces found overlapping by more than 30 %, the one less like the face followed is dropped before it is drawn or followed: a hand over the mouth can come back from the landmarker as a second face. A face more than the crop follows widens it only once three crop detections in a row have it, while a whole-frame detection adds it at once, so a person walking in is followed from the next second. With maxFaces: 3, lip jitter p90 on the hand clip 11.6 -> 3.7-5.5 px over three runs (3.2 with maxFaces: 1) and on the two-face clip 19.7 -> 4.4 px; a second person walking in gets lipstick in every frame they are in.

Fix: with syncFaces, a held frame was drawn with an older mask than it had to be. It took the last mask before it even when the mask of a later frame was already in; it now takes the mask nearest in time. The multiclass mask's held-object channel is also no longer blended 45 % with the previous segmentation, which kept an object's outline for a whole segmentation after it had moved.

Fix: switching the source killed the detector worker. replaceSource with a track whose clock starts lower than the old one (another camera, a canvas or a video) handed MediaPipe a timestamp that went backwards, which its video mode rejects ("Packet timestamp mismatch"): the worker failed and the pipeline moved to the main thread. Each detector now shifts a step back forward, keeping the spacing between frames.

New: occluders keeps hands, hair and held objects in front of the face out of the face effects. The face mesh guesses the face behind whatever covers it, so a hand or a cup over the mouth was smoothed and whitened and took the lipstick, and a blonde fringe passed every luma and colour gate. Lip colour cannot tell bare lips from fingers (on four of nine test faces the lips sit within 0.02 Cr of the cheek), and the multiclass segmenter, which can, takes 60-150 ms a mask beside the drawing on an integrated GPU: two masks a second, late when a hand arrives and late when it leaves. occluders: true instead runs a small network of this package's own in the face worker (face_cover.onnx, 150 k parameters, 0.6 MB, onnxruntime-web on the CPU, about 2 ms) on each frame's landmarks: a 96 px crop round the face in, a 96 x 96 map of where the face shows out. Makeup, teeth and eye colour and the mesh skin (smoothing, whitening) fade where the map says hidden, hold a hidden cell one frame longer, and count a face lost for two frames as hidden whole. With syncFaces the map is of the very frame drawn.

The network was distilled from the multiclass segmenter on 14 401 LFW and COCO val faces with hands, cut-out objects and drawn cups pasted over them. Lab status: those are research sets and the licence of the weights is not cleared. Measured on the fake-camera run of the e2e clips with skin effects and makeup, frames labelled by eye: lips covered by a cup, a glass or a hand, 159 frames - lipstick on the cover in none; lips in view, 416 frames - no lipstick in 3 and under half of it in 11, all of them a cup rising just under the lips or the frame or two after it leaves. The map errs towards hidden: lipstick goes a few frames before a cup reaches the lips, and a clear glass counts as a cover. On the synthetic clip a hand passing over the mouth takes lipstick in at most 1 of 36 covered frames, the one it arrives in. Such a recipe draws 29 fps of 30 on an integrated GPU, where the multiclass mask held it to 23-26. The map is made in the detect worker only: without detect-worker.js, face_cover.onnx or the onnxruntime-web wasm served, occluders does nothing, and for the last two the console says so. Outside the face outline (its 36 landmarks) the map counts as visible, because there it cannot tell a hand from the background. Inside it, a hidden patch that touches nowhere on the outline counts as visible too: a hand or a cup comes in from outside the face, while what the model wrongly hides on its own - closed dark lips in a soft picture, a brow - sits in the middle. On a dark face blown up from a small picture, lips in view with no lipstick 79 -> 3 of 232 frames and lip jitter p90 20 -> 6 px; on the hand, cup and brush clips nothing more lands on the cover. The far end of a brow by the temple can still be dimmed, by about a third on a man in a cap. Something held wholly inside the outline, a pen or a small microphone in front of the mouth, counts as face by the same rule and takes the effects. A recipe with only skin effects or only reshaping now gets the map too (it was read only with makeup), and the reshaping (slimFace, enlargeEyes, nose, chin, jaw, cheekbone, forehead) no longer moves what covers the face inside the outline: on the hand and brush clips the share of the slimming that landed on the hand 0.58 -> 0.31 and 1.28 -> 0.92 with the slimming itself unchanged; what is left is the part of a hand outside the jaw line. The mesh skin's hull channel is no longer cut by the map, so a covered pixel stays out of the generic skin path, and with the multiclass mask bound the makeup takes both cuts. A failure of the cover model no longer stops face detection: the worker warns once and carries on without it. The map adds about 8 ms to each landmark call. With syncFaces two workers share the frames and nothing changes; without it the one face worker can fall past a frame a call and then lands on every other frame, so makeup trails a moving face further (on the synthetic clip at 15-23 px a frame the lipstick sits 21 px off the lips, 13 px without occluders): use syncFaces with makeup.

With the multiclass mask on for another reason, its fourth channel now carries body skin as well as held objects, and a person-scoped grade drops only the part of it that is not skin-coloured.

Fix: with the multiclass mask, a hand left a hand-shaped hole in the skin effects after it moved away. The mask arrives 67-133 ms behind the frame, so for 2-4 frames it still cut the hand out where the face now shows. Each frame sent to the detectors now keeps a 64x36 luma thumbnail; where the picture changed between the frame the classes came from and the newest person mask, a hand or object label counts as stale and the skin effects take the pixel as skin again.

Fix: a line down the cheek on a turned head. The face mesh was drawn without depth, so the far side's soft edge folded over the near cheek and cut a line from the eye to the jaw where smoothing and whitening stopped; the makeup's face map folded the same way. Both mesh passes now drop the triangles facing away, and the skin map keeps the larger value where two faces overlap.

Fix: lipstick hardly showed on dark lips. The shade was scaled by the square root of the lip's own brightness, so on dark lips a wine shade came out nearly as dark as the bare lip. Dark lips now keep most of the shade's brightness; light lips are unchanged.

Fix: a pale rim along the face outline. The mesh reaches a little past the cheek and its gate reads the blurred frame, so the background just outside the face was whitened. The mesh's skin now stops at the person mask.

Fix: a step at the jaw. Under the jaw the neck was held to two narrow skin-colour tests, so a shaded neck took a third to two thirds of the face's whitening. The neck now passes the face's own gate where the class mask says skin, or, without it, where the colour is near this person's skin. Neck against face whitening on the e2e clips: 0.34 to 0.73, 0.60 to 0.97, 0.77 to 0.90; the share landing on clothes rose by 0.1-1.6 points.

  • web/example/studio-live.html caps each slider at a level that still looks natural (smooth 0.8, whiten 0.5, rosy 0.45, brightness 0.5, clarity 0.7, slim face 0.7, sharpen 0.6), tones at 0.8, makeup at about two thirds of 2.6.0 with lip gloss following the amount, and Sharpen moved into the level sliders.
  • web/example/studio-live.html plays sample videos besides the camera: four Wikimedia Commons clips that make example-assets fetches into web/mediakit/videos/ (makeup brushes over the face, two sign-language clips with hands in front of the face, one of them portrait, and a three-quarter talking head), plus the e2e clips when web/e2e/media/ has them. "Side by side" shows the original next to the filtered picture, frame-matched by timestamp, and ?source= and ?split=1 open the page that way. The clips are fetched whole and played from memory, because python3 -m http.server cannot serve the byte ranges a seek needs.

Upgrading to 2.6.0

Existing calls are unchanged. Serve the new mediakit.wasm, worker.js and detect-worker.js with the new JS.

  • Fewer MediaPipe instances. A recipe whose mask comes from a detect worker (the multiclass model, or the person model with no background) no longer also builds the person segmenter in the frame thread to stand in until the worker is up: the frames before it pass through as they do before any mask. The Studio recipe (beauty, hair or skin-scoped grade, makeup) now builds two instances instead of three, and fetches the 13.5 MB MediaPipe runtime twice instead of three times (measured on the e2e server, which sends no cache headers). The person model in the frame thread still comes up when a worker fails, when the multiclass model fails, and for any background.

  • Detector loads time out at 60 s (LOAD_MS), in a worker and in the frame thread. A timed-out detector is not retried in the frame thread, which would wait on the same network: its effects stay off, effectError says ... did not load within 60 s; face effects stay off, and onIssue fires effect-off. A failed load is no longer retried on every frame.

  • preloadDetectors({ person, classes, face }) (and cover since 2.8.0) fetches the MediaPipe runtime and those models at low priority, to warm the HTTP cache before the first recipe that needs them (call it when the camera screen opens). It never rejects. It only helps when /mediakit/ is served cacheable.

  • GPU guard: a lost context is not repeated. Chromium blocks WebGL for the whole site after a few lost contexts in a short time, so a driver that loses the context on one shader must not be handed that shader again. The Engine now tells when a loss happened:

    • building the shaders (init): start() rejects with GpuLostError (phase: "init") and does NOT try the main thread after the worker. This browser remembers the GPU for 3 days: checkSupport() reports gpu-blocked and start() rejects at once, before creating a context.
    • within 3 s of a makeup shader linking (link): the pipeline rebuilds once without face colour (makeup and teeth off, effect-off says why) and remembers it for that GPU, so later starts skip the makeup shader from the beginning.
    • later (run): a GPU reset or a reclaimed context, rebuilt as before and not remembered.

    checkSupport().remembered and gpuRecord(gpu) show what is remembered; forgetGpuFailures() clears it, for a "try again" button after a driver update. The memory is localStorage (mediakit-gpu-guard) on the page's origin.

Upgrading to 2.5.0

Existing calls are unchanged; everything below is new. Serve the new mediakit.wasm, worker.js and detect-worker.js together with the new JS: an older mediakit.wasm still runs under it, without the new effects.

Fix: the filter never started on AMD Radeon 680M (Windows, ANGLE D3D11). The composite shader chose between the two skin measures (multiclass mask, or colour and face shape) with a branch. Linking it hit a backend error after 4-7 s; ANGLE then loses the WebGL context instead of writing a log, so the filter fell back to the raw camera with webgl: link: and an empty log, and after a few tries Edge blocked WebGL for the page. Both measures are now computed and mixed, with no branch; the picture is unchanged (GPU comparison over 400 random inputs: at most 1/255). Found by bisecting on the failing laptop: either measure alone links, either branch form (? : or if/else) fails, mix links (composite in 0.8 s).

Taken from what Tencent Beauty AR Web, BytePlus's web beauty extension and GPUPixel do better:

  • Makeup shader compiled per effect group (GPUPixel's small per-filter programs). facecolor is built with only the groups the recipe uses (lips, contour, brows, shadow, blush, iris colour, makeup texture), the first time a recipe needs them, in the background where the browser has KHR_parallel_shader_compile. Measured cold (driver shader cache off) on Edge, ANGLE GL, Intel UHD: no group 55 ms, the Studio set (lips, blush, shadow) ~300 ms, all seven ~900 ms. While a group set links, the closest ready one keeps drawing; smoothing, whitening and reshape never wait for it.

  • Shader failures do not take the filter down. A face colour link failure turns makeup and teeth off, the rest keeps running, and the console says once mediakit: shader facecolor: ...; makeup and teeth stay off, the rest runs [GPU: ...]. health.effectError and FrameStats.effectError carry it. Any shader error names the shader and the GPU, "the driver gave no log" for an empty log and "context lost" for a GPU reset.

  • checkSupport() (BytePlus checkCompatibility): { supported, reasons, softwareRenderer, gpu }, reasons from no-window, no-wasm, no-webgl2, no-transport. mediakitSupported() is checkSupport().supported.

  • onIssue (Tencent's error and warning codes), once per code until it clears:

    | Code | When | The app should | |---|---|---| | stall | no frame out for 2 s with the camera live (also onStall) | fall back to the raw camera after a grace period | | slow | frames or face detection over 150 ms for 3 s (Tencent's 50005) | suggest a lower resolution or fewer effects | | effect-off | some effects are off, the rest runs (health.effectError) | say which ones and why | | part-off | a detector failed and effect-off has not said so, once per reason (health.parts, health.partErrors) | say what is off; for cover, that makeup may land on a hand | | worker-moved | the worker failed, the pipeline moved to the main thread | install the track from onTrackReplaced | | gpu-lost | the WebGL context was lost | nothing: the pipeline rebuilds itself (up to twice; once without makeup after a makeup link loss, never after a loss building the shaders) and fires onTrackReplaced |

  • replaceSource(track) (Tencent resetCore(input)): another camera into the running pipeline. Same resolution: processedTrack stays the same track, on every transport. Another resolution: it rebuilds and fires onTrackReplaced. The caller still owns both sources.

  • sharpen 0..1 (Tencent usm, BytePlus sharpen): unsharp mask over the whole frame in the grade pass, eased on skin while beautify smooths it. Measured at 1: edge energy x1.7 off skin; with beautify 0.6, x1.35 on skin.

  • hair / hairColor (Tencent setHairColor): dyes the hair from the multiclass segmenter's hair class, keeping strands and shading. Needs /mediakit/selfie_multiclass_256x256.tflite; without it the effect does nothing.

Handling a weak or failing GPU in an app

| Situation | mediakit | The app should | |---|---|---| | No WebGL2 / WASM / transport | checkSupport().reasons | not start; tell the user how to enable hardware acceleration | | GPU lost its context building the shaders in the last 3 days | checkSupport().reasons has gpu-blocked; start() rejects with GpuLostError at once | use the raw camera; offer "update the driver, then try again" calling forgetGpuFailures() | | Software renderer (SwiftShader, llvmpipe) | runs, slowly; checkSupport().softwareRenderer | warn | | Makeup shader slow or failing to link, or losing the context linking | makeup off, rest runs, effect-off; remembered per GPU after a loss | show that makeup is off, keep the camera on | | A detector does not load within 60 s | its effects off, rest runs, effect-off | say the network is slow; preloadDetectors() earlier helps the next time | | The face cover model or its runtime does not load, or face detection runs without the detect worker | occluders off, rest runs, part-off, health.parts.cover "failed" | say that makeup may land on a hand or a cup; offer to turn makeup off | | Overloaded machine | slow, then stall | lower the load, then fall back to the raw camera | | GPU context lost while running | rebuilds, gpu-lost, onTrackReplaced | install the new track | | start() throws GpuLostError | lost the context building the shaders; remembered | use the raw camera; do not retry, mediakit would refuse anyway | | start() throws another GPU error (webgl) | rejects with the shader and GPU named | use the raw camera; retry once on the next start, then stop trying for the session |

Upgrading to 2.4.1

No API change: serve the new worker.js and detect-worker.js.

  • On a machine too slow for the detectors to keep up with the camera (one detection outlasts a frame), the detect workers are asked at most 60% of the time instead of back to back. Back to back they took a whole core and starved the main thread, where frames are handed between workers: a live studio with two channels, six overlays and a green screen on one core ran at 18-19 fps with the camera stopping for up to 1.8 s; now 21-22 fps and 1.0 s. A machine that keeps up is untouched.
  • web/example/studio-live.html starts with the beauty filter off, like the live studio it simulates.

Upgrading to 2.4

2.3.0 was committed but never published; everything below ships first in 2.4.0.

Nothing breaks: the API only grows (setDebug, the debug option, DEBUG_VIEWS, and stats.heldFrames, faceAgeMs, maskAgeMs). Serve the new dist/mediakit.wasm, worker.js and detect-worker.js together, as for every release. A recipe with grade and gradeScope: "person" now loads the face landmarker too (/mediakit/face_landmarker.task, ~3.7 MB), so its mask can follow the head.

  • Between two landmark detections a face is now carried along its turn and its change of size as well as its drift: lipstick, blush, eye shadow and the face-skin mesh stay on a head that tilts or comes closer, where before they only followed sideways movement.
  • syncFaces now holds as many frames as landmark detection takes, up to two, instead of always one. On a machine where a detection outlasts a frame (about 54 ms), lipstick on a face moving sideways trails by half as much (p50 15 -> 8 px at 1280x720). New stats.heldFrames.
  • With the detect worker, landmarks are asked for on every frame the worker is free for, not on the governor's every-other-frame schedule: without syncFaces they are 33-67 ms old instead of 67-100 ms, and lipstick on a face moving sideways trails 10 px instead of 14 (p50). New stats.faceAgeMs and stats.maskAgeMs say how old the landmarks and the mask behind a frame are.
  • The multiclass segmenter (the one behind gradeScope: "person" with products kept, and skin classes) runs on the GPU in its worker, falling back to the CPU when the worker has no WebGL2. Its mask was up to 670 ms old on the CPU, so a tone on the host trailed a moving head; it is now at most about 70 ms old, with no measurable cost to the frame.
  • A mask from the detect worker is asked for on every frame the worker is free for and used the frame it lands, instead of waiting for the governor's segmentation turn. With syncFaces it is asked for when the frame arrives, and the hold covers the mask's latency as well as the landmarks'. A person-scoped grade now tracks the face too, so its multiclass mask is carried with the head. A tone on the host no longer trails a moving head (mask age p90 130 -> 0 ms with syncFaces).
  • Switching from a face-scoped skin effect to rosy or teeth alone no longer turns the picture black: a texture unit a pass does not read is now unbound instead of keeping the last pass's texture, which WebGL refused as a feedback loop with the target being drawn.
  • skinScope: "face" now holds smoothing and whitening to the face mesh (where a lit or shaded cheek used to drop out) and the neck right under the jaw. It no longer takes skin-coloured hair above the forehead, the temples or the chest.
  • New pipeline.setDebug(view) / engine.setDebug(view) and the debug option: draw the skin weights, the mask or the tracked faces instead of the picture. See the pipeline section.
  • web/example/studio-live.html simulates a live-room beauty panel - levels, makeup sets, tones, hold to compare, reset with undo - over VideoPipeline with syncFaces, with an "applied area" overlay and a debug view picker (?debug=skin|mask|face).
  • web/example/beauty.html turns syncFaces on, looks for one face and starts with skinScope: "face": smoothing and whitening stay on the face and neck instead of every skin-coloured thing in the person mask.
  • web/example/studio.html feeds the engine one frame per camera frame with real timestamps; it used to draw every animation frame with a fixed 33 ms step, which on a 60-144 Hz screen slowed the engine's clock two to five times and made effects trail.
  • web/example/studio.html has a "Kiểm chuyển động" panel: a sideways, tilting or approaching motion applied to the source (still image or camera), with syncFaces and maxFaces toggles. ?motion=tilt&period=2&sync=1&faces=1 sets it from the URL, and a camera picker.

Upgrading to 2.2

  • Face landmarks and the multiclass segmenter now run in two detect workers, one each, so a slow multiclass call (150-350 ms on a laptop CPU) no longer holds the landmarks back. Same /mediakit/detect-worker.js; budget roughly one more MediaPipe runtime of memory.
  • Whitening, skin light and smoothing take the face's skin from the face mesh of the frame being drawn, so they no longer trail a moving face or catch light hair. Around it (forehead up to the hairline, temples, ears, neck) they take what matches this person's measured skin colour.
  • whiten and skinLight no longer load the multiclass segmenter and now stay on the head and neck in both scopes: a 150-350 ms model cannot follow a turning head, and colour alone took skin-coloured clothes. Hands and arms are no longer whitened. skinScope still decides where beautify lands.
  • A face the detector loses (a quick head turn) fades its effects out within about 0.2 s instead of holding them where it was for half a second, and is back at full strength the moment it is found again.
  • New syncFaces pipeline option: one frame of delay buys landmarks of the very frame drawn.

Upgrading to 2.1

Serve dist/detect-worker.js as /mediakit/detect-worker.js next to worker.js. Face landmarks and the multiclass segmenter run there, off the frame path. Without it they run in-thread as in 2.0, and the studio recipes can stall frames.

Upgrading to 2.0

2.0 moves to @mediapipe/tasks-vision 1.1.1. Install @mediapipe/tasks-vision@~1.1.1 and serve its wasm/ files under /mediakit/mp/: the worker carries 1.1.1 and its wasm must match. The TypeScript API is unchanged.

Install

pnpm add @tradalab/mediakit @mediapipe/tasks-vision@~1.1.1

@mediapipe/tasks-vision is a peer dependency, ~1.1.1: your bundler provides it for the main thread, and the worker carries its own 1.1.1 copy inside dist/worker.js. The wasm you serve under /mediakit/mp/ comes from your install, so it has to be 1.1.x too - the worker's JS and the wasm must be the same release.

Serve the assets first

Nothing works until these are reachable on your own origin, under /mediakit/. Nothing is ever fetched from a third party while a frame is being processed.

| URL | Copy from | Needed when | |---|---|---| | /mediakit/mediakit.wasm | this package's dist/ | always | | /mediakit/wasm_exec.js | this package's dist/ | always, and it must stay with that .wasm | | /mediakit/worker.js | this package's dist/ | to get the worker transport | | /mediakit/detect-worker.js | this package's dist/ | face landmarks and the multiclass segmenter off the frame path; without it they run in-thread and can stall frames, and occluders has no effect | | /mediakit/mp/ | the files inside @mediapipe/tasks-vision/wasm/, flat, from the same 1.1.x release | any recipe where needsMask() or needsFace() is true | | /mediakit/selfie_segmenter.tflite | MediaPipe model | needsMask() is true | | /mediakit/face_landmarker.task | MediaPipe model | needsFace() is true | | /mediakit/whiten_pink.png | this package's dist/ | whitenStyle: "pink" | | /mediakit/selfie_multiclass_256x256.tflite | MediaPipe model, 16 MB | needsSkinClasses() is true; without it those recipes fall back to skin measured on the face | | /mediakit/face_cover.onnx | this package's dist/, 0.6 MB | occluders with a face effect; without it makeup is drawn over a hand or a cup | | /mediakit/ort/ort-wasm-simd-threaded.wasm and .mjs | onnxruntime-web/dist/ of exactly 1.31.1 (an optional peer dependency: the worker bundles its JS, so another release's wasm does not fit), 15 MB | the same recipes: the runtime of face_cover.onnx | | /mediakit/NOTICE | this package's dist/ | not fetched; the licence of the tables in whiten_pink.png, served beside it |

worker.js is fetched, not imported, so no bundler will pick it up for you. The models are not shipped in the package; fetch them once and serve them yourself.

The package does all of this with one command, run before the app's dev server and build:

mediakit-assets public/mediakit --parts=person,classes,face,cover --models=skip
  • --parts: which detectors besides the core (mediakit.wasm, wasm_exec.js, both workers, whiten_pink.png, NOTICE, mp/). person, classes and face are the three MediaPipe models, cover is face_cover.onnx with onnxruntime-web for occluders. Default person,classes,face: the cover model's licence is not cleared, so it is copied only when asked for.
  • --models: fetch (the default) downloads a missing MediaPipe model from Google (a model already there is kept), skip leaves them out, <dir> copies them from a local folder. A build that must not depend on the network runs skip, with the models fetched once beforehand.
  • --check writes nothing and exits 1 when a file is missing or is not the one of the installed release (a mediakit.wasm left from another version is exactly that), naming each one. With --models=skip it does not ask for the models either.

It copies the MediaPipe and onnxruntime files from the releases this package resolves; when one is not of the release its peer dependencies ask for, that file is reported missing with the version found, the rest is still copied, and the exit code is 1. Every file is written under a .part name and renamed, so an interrupted run leaves no half file behind. Exit code 1 means a file could not be written or is missing, 2 a wrong argument. From a script, syncAssets() in @tradalab/mediakit/assets/node does the same and returns what it wrote, kept, skipped and missed; @tradalab/mediakit/assets is the list itself (ASSETS, assetsFor(parts)), safe to import in the browser.

Run it

import { VideoPipeline } from "@tradalab/mediakit"
import { NO_EFFECTS } from "@tradalab/mediakit/recipe"

const pipeline = new VideoPipeline({ kind: "blur", blurRadius: 12 }, NO_EFFECTS)
await pipeline.start(cameraTrack)                       // a MediaStreamTrack
videoEl.srcObject = new MediaStream([pipeline.processedTrack!])

Changing a setting does not rebuild the pipeline, so dragging a slider does not flash:

await pipeline.switchTo({ kind: "image", imagePath: "/backgrounds/office.png" })
await pipeline.setEffects({ ...NO_EFFECTS, beautify: 0.4, warmth: 0.2 })
await pipeline.stop()

Import the vocabulary from @tradalab/mediakit/recipe, not from the root, anywhere that does not process a frame - a preset list, a settings panel, a storage key. The root pulls in the engine, the wasm loader and the MediaPipe bindings; /recipe is 1.5 kB and pulls in nothing.

The background

type BgFilter =
    | { kind: "none" }
    | { kind: "blur"; blurRadius: number }   // 0 < r <= 32; above 32 is clamped, 0 means none
    | { kind: "image"; imagePath: string }   // any URL, including a data URL
    | { kind: "cutout" }                     // transparent background, for a Scene

cutout writes the person's mask into the output's alpha. It only means something to a consumer that reads alpha - a Scene layer, or an Engine created with alpha: true - since a video track has none.

An image of any aspect ratio is safe: it is cover-cropped to the frame once, when you set it, not per frame. An SVG works on the main thread but not inside the worker - see the limits below.

The effects

Every field is independent and defaults to off. NO_EFFECTS is that default; spread it rather than building the object by hand, so a new field cannot arrive as undefined.

| Field | Range | Does | |---|---|---| | exposure | -1 … 1 | Brightness. Positive lifts shadows more than highlights, so a backlit face recovers without blowing out the window behind it. | | contrast | -1 … 1 | Contrast. | | saturation | -1 … 1 | Colour intensity. | | warmth | -1 … 1 | Positive warm, negative cool. | | tint | -1 … 1 | Positive magenta, negative green: with warmth, a white balance. GPUPixel's tint, a shift along YIQ's Q axis, so brightness does not move. | | vibrance | -1 … 1 | Saturation that moves dull colours more than vivid ones and skin least. Measured at 1: a dull blue +84 %, skin +20 % - where saturation: 0.5 takes skin +50 % and turns faces orange first. | | grain | 0 … 1 | Film grain: luminance noise, a new pattern every frame, strongest in the midtones, none at black or white. About 6 levels at 1. Noise is what an encoder spends the most bits on; keep it low on a live stream. | | sharpen | 0 … 1 | Unsharp mask over the whole frame, in the last (grade) pass, on luminance only so edges gain no colour fringe. Eased on skin while beautify smooths it, so it does not bring back what smoothing took. At 1, edge energy x1.7; on skin with beautify 0.6, x1.35. | | occluders | boolean | Keeps hands, hair and held objects in front of the face out of smoothing, whitening and face colour. Runs the face cover model in the face worker while any face effect is on: face_cover.onnx (0.6 MB) and the onnxruntime-web wasm must be served. | | autoLight | boolean | Lifts exposure when the room is dark, on top of exposure, and only ever brightens. Measures the person when a mask exists, the centre of the frame otherwise. Moves over about a second, so a lamp switching on does not flash the picture. | | mirror | boolean | Flips the finished picture left to right, as a selfie preview shows it. Only the last pass flips, so face tracking, masks and autoframe still see the camera as it is; free on top of any other effect, one pass on its own. Off by default: a mirrored whiteboard reads backwards to everyone else. | | beautify | 0 … 1 | Skin smoothing in two bands: uneven colour (redness, marks, patches) evened hard, fine texture (pores) only eased, so skin stays skin; features - eyes, brows, the lip line - keep both, and small dark spots are lifted. The radius follows the face's size when landmarks run. With the multiclass segmenter loaded it keeps to the skin it labels; otherwise to the person's skin-coloured pixels. | | whiten | 0 … 1 | Brightens the skin as a brighter light would - one gain per patch, from the smoothed skin along a gamma curve, chroma kept, highlights rolled off - and cools only its yellow. Not a fade to white: that greyed dark skin, chalked light skin and flattened the face's form. Loads the multiclass segmenter (16 MB), which labels face skin, body skin, hair, clothes and held objects apart: the face, neck, chest, arms and hands are whitened, clothes and a product in the hand are not, whatever their colour. Until that model is up - or if it never loads - it falls back to the faces and the throats below them, measured against this person's skin colour sampled off their face. Needs landmarks too. Eyes, brows and teeth are left alone. | | whitenStyle | "natural", "pink" | pink is the "fair and rosy" look of East Asian beauty apps: GPUPixel's tuned skin tables (Apache-2.0, dist/NOTICE), served as /mediakit/whiten_pink.png and loaded the first time it is asked for. It takes over on light and medium skin and hands back to natural on dark skin, by the skin measured on each face - those tables were not tuned for it and came out mottled. | | skinLight | 0 … 1 | The same relighting without the cooling: brightness on that same skin, its colour and shading kept. exposure stays whole-frame. | | clarity | 0 … 1 | Local contrast on the faces: the detail beautify separates out, added on top. Its own knob - beautify gives back only what it took. Needs landmarks; kept off the cut-out edge, where it would draw a rim. Dropped with beautify when the governor is short of time. | | hair, hairColor | 0 … 1, [r, g, b] | Hair dye: keeps the hair's own brightness and strands and takes the colour's hue; very dark hair takes less, as real dye does. Drawn from the hair class of the multiclass segmenter, so it needs /mediakit/selfie_multiclass_256x256.tflite - without it nothing is dyed. Facial hair is left alone. | | skinScope | "person", "face" | Where smoothing (and the two above, already held to the face) may land. person, the default, is skin anywhere on the person, hands included; face keeps smoothing to faces and necks, so a hand holding a product - or a lipstick swatch on the back of it - is left alone. With no face found, face lands nowhere. | | autoframe | boolean | Keeps the person framed, with headroom. Moves by time, not by frame, so it looks the same at 24fps and 60fps. | | teeth | 0 … 1 | Whitens teeth. | | eyeBright | 0 … 1 | Brightens the whites of the eyes and adds clarity to the iris. | | underEye | 0 … 1 | Reduces under-eye shadow, keeping the skin's own tone. | | smileLines | 0 … 1 | Softens the nasolabial folds by filling the crease from the skin either side of it. | | lips, lipColor | 0 … 1, [r, g, b] | Lip tint, drawn against the lip contour itself; the teeth and the inside of the mouth stay untouched. The lip's mean brightness maps to the colour's own, so a dark shade stays dark while the lip's texture and highlights show through. | | blush, blushColor | 0 … 1, [r, g, b] | A wide, faint flush on the apples of the cheeks, held inside the face outline. | | rosy, rosyColor | 0 … 1, [r, g, b] | A flush over the skin of the whole face, capped at 0.3 opacity. Fills the face outline, so it needs landmarks but not the mesh. | | eyeShadow, eyeShadowColor | 0 … 1, [r, g, b] | Multiplied into the lower part of the lid-to-brow band, deepest at the outer corner and fading up. | | lipGloss | 0 … 1 | A white highlight across the middle of the lower lip, a quarter of its width. Matte is 0; works with lips at 0 too. | | iris, irisColor | 0 … 1, [r, g, b] | Iris colour: the ring only, clipped by the eyelids, pupil and catchlights left alone. | | lut, grade | URL, 0 … 1 | A colour LUT and its strength, applied last. See below. | | gradeScope | "frame", "person", "skin" | Where the LUT lands. person keeps it off the background and - with the multiclass segmenter, which this loads - off a product held up, which it labels apart from the person; clothes worn are the person, and take it. skin is the skin the segmenter labels, falling back to faces and throats as for whiten. Anything but frame needs the person mask. | | chromaKey | boolean | Takes the person mask from a green or blue screen instead of segmentation: MediaPipe is never loaded, and hair and edges come out cleaner. Removes the screen's colour cast from the person too. Pair it with a blur or image background. | | keyColor, keyTolerance | [r, g, b], -1 … 1 | The screen's colour - [0, 0, 0], the default, finds it from the frame's border and follows it as the camera's white balance drifts. keyTolerance widens (+) or narrows (-) what counts as screen. | | slimFace | 0 … 1 | Narrows the jawline. Capped internally at a subtle maximum. | | enlargeEyes | 0 … 1 | Enlarges the eyes. Same cap. | | noseSlim | 0 … 1 | Narrows the nose, mostly at the wings. Same cap. | | chin | -1 … 1 | Shortens or lengthens the chin; the mouth stays where it is. Same cap. | | jaw, cheekbone | 0 … 1 | Narrow the lower jaw towards a V-line, or the cheekbones. Unlike the reshaping above, which pushes an ellipse, these move the face's own outline - its 36 contour landmarks - so the jaw that narrows is this person's. Capped; reads the landmark mesh. | | forehead | -1 … 1 | A smaller (-) or fuller (+) forehead, by the same contour. | | brow, browColor | 0 … 1, [r, g, b] | Fills and darkens the brows, multiplied in so the hairs show; lighter at the inner end. | | contour | 0 … 1 | Shades under the cheekbones, along the jaw and beside the nose. | | highlight | 0 … 1 | Lifts the nose bridge, cheekbone tops, mid forehead and chin. |

Values outside the range are clamped, not rejected. Every face region follows head tilt, and up to three faces are tracked and retouched at once, each with its own smoothing. The smoothing lets go as a face moves, and between detections - which run every second frame or less - the regions are carried along the face's velocity, so makeup keeps up with a turning head (measured: 22 px behind on a moving head before, under 4 after). Recipes that stretch gradients - whitening, skin light, clarity, a scoped grade - dither by half a level, so no banding shows. A face that has just appeared takes reshaping and face colour at a growing share of their strength, reaching all of it after 0.3 s; one that leaves loses them at once, since fading over a frame with no face in it reads as a rendering fault.

Colour LUTs

lut is a URL your app serves, decoded once when it changes - not per frame. The layout is the common 512x512 "lookup" PNG: 64 levels per channel, the blue axis laid out as 8x8 tiles of red (across) by green (down), row 0 at the top. Most grading tools export it; an identity one is a plain gradient, so you can also generate your own. Run the identity one at grade: 1 first: the picture must not change, and if it does, the file is laid out differently.

@tradalab/mediakit/lut bakes one without an image file, and without pulling the engine in:

import { chain, curve, levels, lutDataUrl, parseCube, vibrance, whiteBalance } from "@tradalab/mediakit/lut"

const film = lutDataUrl(chain(whiteBalance(0.15, -0.05), curve([[0, 0], [0.5, 0.48], [1, 1]]), levels(0, 1, 1, 0.08, 1)))
const designer = lutDataUrl(parseCube(await (await fetch("/looks/warm.cube")).text()))
await pipeline.setEffects({ ...NO_EFFECTS, lut: film, grade: 0.6, gradeScope: "person" })
  • parseCube reads a .cube file (3D, any size, trilinear; or 1D per channel).
  • curve is a curves panel: monotone cubic through the points, all channels or one.
  • levels sets input black/white, gamma, output black/white.
  • whiteBalance and vibrance do what warmth/tint and vibrance do live.
  • lutPixels gives the raw RGBA when there is no DOM to bake on.

lutDataUrl runs the function 262 144 times; cache the result. Grain cannot live in a LUT: it is noise in time, so a film look sets grain beside it.

Storing a recipe

EFFECTS_SCHEMA gives every field's kind and range (amount 0..1, signed -1..1, color, choice with its values, bool, url), the same ranges the core clamps to. normalizeEffects turns anything - a stored recipe, one from an older build, a server's - into a valid Effects: out-of-range numbers clamped, missing or malformed fields set to NO_EFFECTS, unknown ones dropped. Both are in @tradalab/mediakit/recipe.

One knob instead of five

touchUp(amount) sets beautify, eyeBright, underEye, smileLines and teeth together, in proportions tuned to read as rested rather than filtered at 1. Spread it into the effects; touchUpAmount(effects) reads a stored recipe back into the knob's position.

import { NO_EFFECTS, touchUp } from "@tradalab/mediakit/recipe"
const effects = { ...NO_EFFECTS, ...touchUp(0.5) }

web/example/beauty.html (make example, then /example/beauty.html) puts every effect behind a phone-style beauty panel: tabs, one slider for the selected item, colour swatches for makeup, filter thumbnails made from your own camera, and hold-to-compare. It is the shape to copy for a selfie or short-video app.

web/example/bench.html measures the beauty filter on this machine's GPU: quality on seven portraits (how much skin whitening reaches, how much leaks onto clothes and products, texture and blotchiness left after smoothing), makeup lag on a swaying head, and frame cost per recipe with the real governor. make example fetches the portraits; their licences are listed on the page.

web/example/studio.html is the beauty panel of a livestream studio - four levels, eight makeup sets, seven tones and a "keep product colour" switch - built for CALIBRATION: its source can be a still image (upload one, or ?img=<url>) so numbers change against a fixed picture, and it exports the frame as PNG with the recipe that made it. Every number on it is that product's, not the package's.

What each one costs

The two detectors are separate downloads and separate per-frame costs, and each loads only when a recipe first needs it:

| | Pulled in by | Cost | |---|---|---| | person mask | any background other than none, beautify, whiten, skinLight, clarity, autoframe, a gradeScope other than frame | MediaPipe runtime plus a 244 kB model | | face landmarks | teeth, eyeBright, underEye, smileLines, lips, blush, iris, rosy, eyeShadow, lipGloss, brow, contour, highlight, whiten, skinLight, clarity, gradeScope: "skin", slimFace, enlargeEyes, noseSlim, chin, jaw, cheekbone, forehead, and skinScope: "face" with beautify | a 3.7 MB model, fifteen times the other | | skin classes | a gradeScope other than frame (needsSkinClasses()) | a second, multiclass segmenter: 16 MB, float32 only. Loaded beside the person one; until it is up those recipes fall back as described above |

autoLight needs neither: it reads the frame's brightness from a 32x18 grid. chromaKey turns the person mask's cost into one shader pass - needsSegmentation() says whether MediaPipe has to be loaded at all.

A colour-only recipe needs neither, and then the pipeline skips MediaPipe entirely. Ask before you commit to a recipe:

import { needsMask, needsFace } from "@tradalab/mediakit/recipe"

A user who turns nothing on downloads nothing - the wasm core itself is only fetched on the first active recipe.

Reading what it is doing

pipeline.stats returns the last frame's numbers, or null before the first one. Poll it a few times a second; reading it per frame costs more than it tells you.

const s = pipeline.stats
// s.totalMs, s.segMs, s.faceMs, s.glCalls, s.segmented, s.maskScale, s.workScale,
// s.cropCX, s.cropCY, s.cropZoom, s.needsMask, s.faceFound, s.faceSize, s.needsFace,
// s.heldFrames

pipeline.transportName says which of the three paths is running: worker, insertable or canvas. It is chosen automatically and falls back on its own, so treat it as a diagnostic, not a setting.

Health, fallback and several consumers

const pipeline = new VideoPipeline(filter, effects, {
    alpha: true,                                     // keep alpha for subscribeFrames + cutout
    maxFaces: 1,                                     // one person per camera: ~a third less landmark cost
    syncFaces: true,                                 // each frame waits for its own landmarks, makeup sits on the moving face
    debug: "off",                                    // or "skin" | "mask" | "face" - see below
    onStall: ({ transport, sinceMs }) => report(transport, sinceMs),
    onTrackReplaced: (track) => sender.replaceTrack(track),
})
const stop = pipeline.subscribeFrames((frame) => { draw(frame); frame.close() })
pipeline.health   // { transport, frames, sinceMs, stalled, effectError, parts, partErrors }
  • No frame for two seconds fires onStall (a machine too slow for the recipe, or a hang). A worker that fails, or stays silent for eight seconds, AFTER the host published its track is taken for dead and the work moves to the main thread on its own; onTrackReplaced hands the host the new track. A detector loading - seconds for the 16 MB model - counts as neither.
  • subscribeFrames gives every processed frame, alpha kept when asked, one clone per subscriber
    • one processing for a host that composites the camera into several outputs.
  • On Safari the worker path takes a clone of the camera track into the worker (untested on Safari so far); anything that fails falls back to the canvas transport.
  • syncFaces holds frames back by as many as the landmarks take to come back - one frame (about 33 ms at 30 fps) on a machine that detects within a frame, two at most on a slower one - so each frame is drawn between two detections instead of ahead of the last one: lips, blush, eye shadow and reshaping stay on a fast-moving face. stats.heldFrames says how many it holds now. The output frame keeps its source timestamp. The audio is not delayed with it; two frames (about 66 ms) is the cap because more starts to show as lip sync. It needs the detect worker and does nothing for a recipe without landmarks.
  • pipeline.setDebug(view) (also engine.setDebug, and the debug option at construction) draws an inner layer instead of the picture, for tuning a recipe or answering "where does it land": "skin" - red where smoothing lands, green where whitening and brightness land, blue the face mesh, the rest dimmed; "mask" - the person mask in red, or with the multiclass model green skin, blue hair, red held objects; "face" - each tracked face outline in yellow and the neck the skin effects reach in blue. "off" restores the picture. Makeup and tones are not drawn while a view is on. It is not part of Effects, so a saved look never carries it. DEBUG_VIEWS lists the names, for a picker.

Lower level

Engine takes one frame and draws one canvas, for a host that already owns its frame loop:

import { Engine } from "@tradalab/mediakit"

const engine = await Engine.on(canvas, filter, effects)
const drew = engine.render(videoOrFrame, timestampMicros)
if (drew) out.enqueue(engine.capture(timestampMicros))

render returning false means nothing was drawn - no mask yet, or the recipe is inactive. Forward the source frame when that happens; dropping it freezes the picture.

Scenes: layering sources

Scene puts several sources on one output, the way OBS does: cameras (each with its own recipe), screen shares, video files, images, text and any canvas, placed, shaped and blended as layers, with animated edits and transitions between layouts.

import { Scene, layouts } from "@tradalab/mediakit"

const scene = await Scene.create({ width: 1280, height: 720, background: "#0b1220" })
await scene.addSource("cam", { kind: "camera", track: camTrack, filter: { kind: "cutout" } })
await scene.addSource("screen", { kind: "track", track: screenTrack })
await scene.addSource("name", { kind: "text", text: "Nguyen Van A", style: { background: "#000a", padding: 20 } })

const p = layouts.presenter("right")
scene.setLayers([
    { id: 1, source: "screen", ...p.content, fit: "contain", shape: "rounded", radius: 0.03 },
    { id: 2, source: "cam", ...p.person, fit: "contain" },
    { id: 3, source: "name", ...layouts.lowerThird(), fit: "contain" },
])
scene.start()
const track = scene.captureStream().getVideoTracks()[0]

// Later: glide a layer somewhere else, or change the whole layout through a transition.
scene.setLayers(next, { animate: 300 })
scene.switchTo(other, { kind: "iris", duration: 600 })

A layer is a rect in fractions of the output, origin top left, plus any of:

| Field | Values | |---|---| | source / color / color2 | a source id; or a fill colour; or a gradient from color to color2 along gradientAngle | | fit | cover (default), contain (the rect shrinks to the picture), stretch | | crop, flipX, flipY, rotation | fractions of the source; mirror; degrees clockwise | | opacity, hidden | 0..1 (default 1) | | shape, radius | rect, rounded (radius as a share of the shorter side), ellipse | | border, shadow | width and colour; softness, offset and opacity, all in output heights | | blend | normal, add, screen, multiply, overlay, darken, lighten | | tone | exposure, contrast, saturation, warmth, -1..1, as in the camera recipe (not tint, vibrance or grain) | | key | remove a colour from the source, e.g. a green-screen clip |

Layers draw in array order, first at the bottom; at most 16, and 8 sources. Each layer costs one full-frame pass. id is what an animation follows: with animate, a layer with the same id glides from where it is, a new id fades in, a dropped one fades out.

Transitions: cut, fade, fadeThrough, slideLeft/Right/Up/Down, pushLeft/Right, wipeLeft/Right, iris, zoom. During one, both layouts are drawn, so it costs every layer twice for its duration.

Also: layerAt(x, y) for picking and dragging, updateSource (new text, a new camera recipe), snapshot() to PNG, startRecording()/stopRecording() to WebM. layouts has full, pip, columns, grid, lowerThird and presenter; the layout vocabulary is also its own entry, @tradalab/mediakit/layout, so a layout picker does not pull the wasm loader in.

web/example/scene.html (make example, then /example/scene.html) is a working editor.

Limits worth knowing before you design around them

  • A Scene runs on the main thread, and its loop is a timer: a hidden tab slows it to the