@tradalab/mediakit 1.4.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,360 @@
1
+ # @tradalab/mediakit
2
+
3
+ Realtime camera processing in the browser: a camera track goes in, a processed camera track
4
+ comes out. Background replacement and blur, skin smoothing, colour adjustment, autoframing and
5
+ face retouching.
6
+
7
+ The examples named below live in the repository under `web/example/`; `make example` serves them.
8
+
9
+ ### Upgrading to 2.1
10
+
11
+ Serve `dist/detect-worker.js` as `/mediakit/detect-worker.js` next to `worker.js`. Face landmarks
12
+ and the multiclass segmenter run there, off the frame path. Without it they run in-thread as in
13
+ 2.0, and the studio recipes can stall frames.
14
+
15
+ ### Upgrading to 2.0
16
+
17
+ 2.0 moves to `@mediapipe/tasks-vision` 1.1.1. Install `@mediapipe/tasks-vision@~1.1.1` and serve
18
+ its `wasm/` files under `/mediakit/mp/`: the worker carries 1.1.1 and its wasm must match. The
19
+ TypeScript API is unchanged.
20
+
21
+ ## Install
22
+
23
+ ```sh
24
+ pnpm add @tradalab/mediakit @mediapipe/tasks-vision@~1.1.1
25
+ ```
26
+
27
+ `@mediapipe/tasks-vision` is a peer dependency, `~1.1.1`: your bundler provides it for the main
28
+ thread, and the worker carries its own 1.1.1 copy inside `dist/worker.js`. The wasm you serve
29
+ under `/mediakit/mp/` comes from your install, so it has to be 1.1.x too - the worker's JS and
30
+ the wasm must be the same release.
31
+
32
+ ## Serve the assets first
33
+
34
+ Nothing works until these are reachable on **your own origin**, under `/mediakit/`. Nothing is
35
+ ever fetched from a third party while a frame is being processed.
36
+
37
+ | URL | Copy from | Needed when |
38
+ |---|---|---|
39
+ | `/mediakit/mediakit.wasm` | this package's `dist/` | always |
40
+ | `/mediakit/wasm_exec.js` | this package's `dist/` | always, and it must stay with that `.wasm` |
41
+ | `/mediakit/worker.js` | this package's `dist/` | to get the worker transport |
42
+ | `/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 |
43
+ | `/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 |
44
+ | `/mediakit/selfie_segmenter.tflite` | MediaPipe model | `needsMask()` is true |
45
+ | `/mediakit/face_landmarker.task` | MediaPipe model | `needsFace()` is true |
46
+ | `/mediakit/whiten_pink.png` | this package's `dist/` | `whitenStyle: "pink"` |
47
+ | `/mediakit/selfie_multiclass_256x256.tflite` | MediaPipe model, 16 MB | `needsSkinClasses()` is true; without it those recipes fall back to skin measured on the face |
48
+
49
+ `worker.js` is **fetched**, not imported, so no bundler will pick it up for you. The models are
50
+ not shipped in the package; fetch them once and serve them yourself.
51
+
52
+ ## Run it
53
+
54
+ ```ts
55
+ import { VideoPipeline } from "@tradalab/mediakit"
56
+ import { NO_EFFECTS } from "@tradalab/mediakit/recipe"
57
+
58
+ const pipeline = new VideoPipeline({ kind: "blur", blurRadius: 12 }, NO_EFFECTS)
59
+ await pipeline.start(cameraTrack) // a MediaStreamTrack
60
+ videoEl.srcObject = new MediaStream([pipeline.processedTrack!])
61
+ ```
62
+
63
+ Changing a setting does **not** rebuild the pipeline, so dragging a slider does not flash:
64
+
65
+ ```ts
66
+ await pipeline.switchTo({ kind: "image", imagePath: "/backgrounds/office.png" })
67
+ await pipeline.setEffects({ ...NO_EFFECTS, beautify: 0.4, warmth: 0.2 })
68
+ await pipeline.stop()
69
+ ```
70
+
71
+ Import the vocabulary from `@tradalab/mediakit/recipe`, not from the root, anywhere that does
72
+ not process a frame - a preset list, a settings panel, a storage key. The root pulls in the
73
+ engine, the wasm loader and the MediaPipe bindings; `/recipe` is 1.5 kB and pulls in nothing.
74
+
75
+ ## The background
76
+
77
+ ```ts
78
+ type BgFilter =
79
+ | { kind: "none" }
80
+ | { kind: "blur"; blurRadius: number } // 0 < r <= 32; above 32 is clamped, 0 means none
81
+ | { kind: "image"; imagePath: string } // any URL, including a data URL
82
+ | { kind: "cutout" } // transparent background, for a Scene
83
+ ```
84
+
85
+ `cutout` writes the person's mask into the output's alpha. It only means something to a
86
+ consumer that reads alpha - a `Scene` layer, or an `Engine` created with `alpha: true` - since a
87
+ video track has none.
88
+
89
+ An image of any aspect ratio is safe: it is cover-cropped to the frame once, when you set it,
90
+ not per frame. An SVG works on the main thread but **not** inside the worker - see the limits
91
+ below.
92
+
93
+ ## The effects
94
+
95
+ Every field is independent and defaults to off. `NO_EFFECTS` is that default; spread it rather
96
+ than building the object by hand, so a new field cannot arrive as `undefined`.
97
+
98
+ | Field | Range | Does |
99
+ |---|---|---|
100
+ | `exposure` | -1 … 1 | Brightness. Positive lifts shadows more than highlights, so a backlit face recovers without blowing out the window behind it. |
101
+ | `contrast` | -1 … 1 | Contrast. |
102
+ | `saturation` | -1 … 1 | Colour intensity. |
103
+ | `warmth` | -1 … 1 | Positive warm, negative cool. |
104
+ | `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. |
105
+ | `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. |
106
+ | `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. |
107
+ | `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. |
108
+ | `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. |
109
+ | `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. |
110
+ | `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. |
111
+ | `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. |
112
+ | `skinLight` | 0 … 1 | The same relighting without the cooling: brightness on that same skin, its colour and shading kept. `exposure` stays whole-frame. |
113
+ | `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. |
114
+ | `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. |
115
+ | `autoframe` | boolean | Keeps the person framed, with headroom. Moves by time, not by frame, so it looks the same at 24fps and 60fps. |
116
+ | `teeth` | 0 … 1 | Whitens teeth. |
117
+ | `eyeBright` | 0 … 1 | Brightens the whites of the eyes and adds clarity to the iris. |
118
+ | `underEye` | 0 … 1 | Reduces under-eye shadow, keeping the skin's own tone. |
119
+ | `smileLines` | 0 … 1 | Softens the nasolabial folds by filling the crease from the skin either side of it. |
120
+ | `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. |
121
+ | `blush`, `blushColor` | 0 … 1, `[r, g, b]` | A wide, faint flush on the apples of the cheeks, held inside the face outline. |
122
+ | `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. |
123
+ | `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. |
124
+ | `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. |
125
+ | `iris`, `irisColor` | 0 … 1, `[r, g, b]` | Iris colour: the ring only, clipped by the eyelids, pupil and catchlights left alone. |
126
+ | `lut`, `grade` | URL, 0 … 1 | A colour LUT and its strength, applied last. See below. |
127
+ | `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. |
128
+ | `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. |
129
+ | `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. |
130
+ | `slimFace` | 0 … 1 | Narrows the jawline. Capped internally at a subtle maximum. |
131
+ | `enlargeEyes` | 0 … 1 | Enlarges the eyes. Same cap. |
132
+ | `noseSlim` | 0 … 1 | Narrows the nose, mostly at the wings. Same cap. |
133
+ | `chin` | -1 … 1 | Shortens or lengthens the chin; the mouth stays where it is. Same cap. |
134
+ | `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. |
135
+ | `forehead` | -1 … 1 | A smaller (-) or fuller (+) forehead, by the same contour. |
136
+ | `brow`, `browColor` | 0 … 1, `[r, g, b]` | Fills and darkens the brows, multiplied in so the hairs show; lighter at the inner end. |
137
+ | `contour` | 0 … 1 | Shades under the cheekbones, along the jaw and beside the nose. |
138
+ | `highlight` | 0 … 1 | Lifts the nose bridge, cheekbone tops, mid forehead and chin. |
139
+
140
+ Values outside the range are clamped, not rejected. Every face region follows head tilt, and up
141
+ to three faces are tracked and retouched at once, each with its own smoothing. The smoothing lets
142
+ go as a face moves, and between detections - which run every second frame or less - the regions
143
+ are carried along the face's velocity, so makeup keeps up with a turning head (measured: 22 px
144
+ behind on a moving head before, under 4 after). Recipes that stretch gradients - whitening, skin
145
+ light, clarity, a scoped grade - dither by half a level, so no banding shows. A face that has
146
+ just appeared takes reshaping and face colour at a growing share of their strength, reaching all
147
+ of it after 0.3 s; one that leaves loses them at once, since fading over a frame with no face in
148
+ it reads as a rendering fault.
149
+
150
+ ### Colour LUTs
151
+
152
+ `lut` is a URL your app serves, decoded once when it changes - not per frame. The layout is the
153
+ common 512x512 "lookup" PNG: 64 levels per channel, the blue axis laid out as 8x8 tiles of red
154
+ (across) by green (down), row 0 at the top. Most grading tools export it; an identity one is a
155
+ plain gradient, so you can also generate your own. Run the identity one at `grade: 1` first: the
156
+ picture must not change, and if it does, the file is laid out differently.
157
+
158
+ `@tradalab/mediakit/lut` bakes one without an image file, and without pulling the engine in:
159
+
160
+ ```ts
161
+ import { chain, curve, levels, lutDataUrl, parseCube, vibrance, whiteBalance } from "@tradalab/mediakit/lut"
162
+
163
+ 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)))
164
+ const designer = lutDataUrl(parseCube(await (await fetch("/looks/warm.cube")).text()))
165
+ await pipeline.setEffects({ ...NO_EFFECTS, lut: film, grade: 0.6, gradeScope: "person" })
166
+ ```
167
+
168
+ - `parseCube` reads a `.cube` file (3D, any size, trilinear; or 1D per channel).
169
+ - `curve` is a curves panel: monotone cubic through the points, all channels or one.
170
+ - `levels` sets input black/white, gamma, output black/white.
171
+ - `whiteBalance` and `vibrance` do what `warmth`/`tint` and `vibrance` do live.
172
+ - `lutPixels` gives the raw RGBA when there is no DOM to bake on.
173
+
174
+ `lutDataUrl` runs the function 262 144 times; cache the result. Grain cannot live in a LUT: it is
175
+ noise in time, so a film look sets `grain` beside it.
176
+
177
+ ### Storing a recipe
178
+
179
+ `EFFECTS_SCHEMA` gives every field's kind and range (`amount` 0..1, `signed` -1..1, `color`,
180
+ `choice` with its values, `bool`, `url`), the same ranges the core clamps to. `normalizeEffects`
181
+ turns anything - a stored recipe, one from an older build, a server's - into a valid `Effects`:
182
+ out-of-range numbers clamped, missing or malformed fields set to `NO_EFFECTS`, unknown ones dropped.
183
+ Both are in `@tradalab/mediakit/recipe`.
184
+
185
+ ### One knob instead of five
186
+
187
+ `touchUp(amount)` sets `beautify`, `eyeBright`, `underEye`, `smileLines` and `teeth` together,
188
+ in proportions tuned to read as rested rather than filtered at 1. Spread it into the effects;
189
+ `touchUpAmount(effects)` reads a stored recipe back into the knob's position.
190
+
191
+ ```ts
192
+ import { NO_EFFECTS, touchUp } from "@tradalab/mediakit/recipe"
193
+ const effects = { ...NO_EFFECTS, ...touchUp(0.5) }
194
+ ```
195
+
196
+ `web/example/beauty.html` (`make example`, then `/example/beauty.html`) puts every effect behind a
197
+ phone-style beauty panel: tabs, one slider for the selected item, colour swatches for makeup,
198
+ filter thumbnails made from your own camera, and hold-to-compare. It is the shape to copy for a
199
+ selfie or short-video app.
200
+
201
+ `web/example/bench.html` measures the beauty filter on this machine's GPU: quality on seven
202
+ portraits (how much skin whitening reaches, how much leaks onto clothes and products, texture and
203
+ blotchiness left after smoothing), makeup lag on a swaying head, and frame cost per recipe with the
204
+ real governor. `make example` fetches the portraits; their licences are listed on the page.
205
+
206
+ `web/example/studio.html` is the beauty panel of a livestream studio - four levels, eight
207
+ makeup sets, seven tones and a "keep product colour" switch - built for CALIBRATION: its source
208
+ can be a still image (upload one, or `?img=<url>`) so numbers change against a fixed picture, and
209
+ it exports the frame as PNG with the recipe that made it. Every number on it is that product's,
210
+ not the package's.
211
+
212
+ ### What each one costs
213
+
214
+ The two detectors are separate downloads and separate per-frame costs, and each loads only
215
+ when a recipe first needs it:
216
+
217
+ | | Pulled in by | Cost |
218
+ |---|---|---|
219
+ | **person mask** | any background other than `none`, `beautify`, `whiten`, `skinLight`, `clarity`, `autoframe`, a `gradeScope` other than `frame` | MediaPipe runtime plus a 244 kB model |
220
+ | **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 |
221
+ | **skin classes** | `whiten`, `skinLight`, 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 |
222
+
223
+ `autoLight` needs neither: it reads the frame's brightness from a 32x18 grid. `chromaKey` turns
224
+ the person mask's cost into one shader pass - `needsSegmentation()` says whether MediaPipe has to
225
+ be loaded at all.
226
+
227
+ A colour-only recipe needs neither, and then the pipeline skips MediaPipe entirely. Ask before
228
+ you commit to a recipe:
229
+
230
+ ```ts
231
+ import { needsMask, needsFace } from "@tradalab/mediakit/recipe"
232
+ ```
233
+
234
+ A user who turns nothing on downloads **nothing** - the wasm core itself is only fetched on the
235
+ first active recipe.
236
+
237
+ ## Reading what it is doing
238
+
239
+ `pipeline.stats` returns the last frame's numbers, or `null` before the first one. Poll it a
240
+ few times a second; reading it per frame costs more than it tells you.
241
+
242
+ ```ts
243
+ const s = pipeline.stats
244
+ // s.totalMs, s.segMs, s.faceMs, s.glCalls, s.segmented, s.maskScale, s.workScale,
245
+ // s.cropCX, s.cropCY, s.cropZoom, s.needsMask, s.faceFound, s.faceSize, s.needsFace
246
+ ```
247
+
248
+ `pipeline.transportName` says which of the three paths is running: `worker`, `insertable` or
249
+ `canvas`. It is chosen automatically and falls back on its own, so treat it as a diagnostic,
250
+ not a setting.
251
+
252
+ ## Health, fallback and several consumers
253
+
254
+ ```ts
255
+ const pipeline = new VideoPipeline(filter, effects, {
256
+ alpha: true, // keep alpha for subscribeFrames + cutout
257
+ maxFaces: 1, // one person per camera: ~a third less landmark cost
258
+ onStall: ({ transport, sinceMs }) => report(transport, sinceMs),
259
+ onTrackReplaced: (track) => sender.replaceTrack(track),
260
+ })
261
+ const stop = pipeline.subscribeFrames((frame) => { draw(frame); frame.close() })
262
+ pipeline.health // { transport, frames, sinceMs, stalled }
263
+ ```
264
+
265
+ - No frame for two seconds fires `onStall` (a machine too slow for the recipe, or a hang). A worker
266
+ that fails, or stays silent for eight seconds, AFTER the host published its track is taken for
267
+ dead and the work moves to the main thread on its own; `onTrackReplaced` hands the host the new
268
+ track. A detector loading - seconds for the 16 MB model - counts as neither.
269
+ - `subscribeFrames` gives every processed frame, alpha kept when asked, one clone per subscriber
270
+ - one processing for a host that composites the camera into several outputs.
271
+ - On Safari the worker path takes a clone of the camera track into the worker (untested on Safari
272
+ so far); anything that fails falls back to the canvas transport.
273
+
274
+ ## Lower level
275
+
276
+ `Engine` takes one frame and draws one canvas, for a host that already owns its frame loop:
277
+
278
+ ```ts
279
+ import { Engine } from "@tradalab/mediakit"
280
+
281
+ const engine = await Engine.on(canvas, filter, effects)
282
+ const drew = engine.render(videoOrFrame, timestampMicros)
283
+ if (drew) out.enqueue(engine.capture(timestampMicros))
284
+ ```
285
+
286
+ `render` returning `false` means nothing was drawn - no mask yet, or the recipe is inactive.
287
+ Forward the source frame when that happens; dropping it freezes the picture.
288
+
289
+ ## Scenes: layering sources
290
+
291
+ `Scene` puts several sources on one output, the way OBS does: cameras (each with its own recipe),
292
+ screen shares, video files, images, text and any canvas, placed, shaped and blended as layers,
293
+ with animated edits and transitions between layouts.
294
+
295
+ ```ts
296
+ import { Scene, layouts } from "@tradalab/mediakit"
297
+
298
+ const scene = await Scene.create({ width: 1280, height: 720, background: "#0b1220" })
299
+ await scene.addSource("cam", { kind: "camera", track: camTrack, filter: { kind: "cutout" } })
300
+ await scene.addSource("screen", { kind: "track", track: screenTrack })
301
+ await scene.addSource("name", { kind: "text", text: "Nguyen Van A", style: { background: "#000a", padding: 20 } })
302
+
303
+ const p = layouts.presenter("right")
304
+ scene.setLayers([
305
+ { id: 1, source: "screen", ...p.content, fit: "contain", shape: "rounded", radius: 0.03 },
306
+ { id: 2, source: "cam", ...p.person, fit: "contain" },
307
+ { id: 3, source: "name", ...layouts.lowerThird(), fit: "contain" },
308
+ ])
309
+ scene.start()
310
+ const track = scene.captureStream().getVideoTracks()[0]
311
+
312
+ // Later: glide a layer somewhere else, or change the whole layout through a transition.
313
+ scene.setLayers(next, { animate: 300 })
314
+ scene.switchTo(other, { kind: "iris", duration: 600 })
315
+ ```
316
+
317
+ A layer is a rect in fractions of the output, origin top left, plus any of:
318
+
319
+ | Field | Values |
320
+ |---|---|
321
+ | `source` / `color` / `color2` | a source id; or a fill colour; or a gradient from `color` to `color2` along `gradientAngle` |
322
+ | `fit` | `cover` (default), `contain` (the rect shrinks to the picture), `stretch` |
323
+ | `crop`, `flipX`, `flipY`, `rotation` | fractions of the source; mirror; degrees clockwise |
324
+ | `opacity`, `hidden` | 0..1 (default 1) |
325
+ | `shape`, `radius` | `rect`, `rounded` (radius as a share of the shorter side), `ellipse` |
326
+ | `border`, `shadow` | width and colour; softness, offset and opacity, all in output heights |
327
+ | `blend` | `normal`, `add`, `screen`, `multiply`, `overlay`, `darken`, `lighten` |
328
+ | `tone` | `exposure`, `contrast`, `saturation`, `warmth`, -1..1, as in the camera recipe (not `tint`, `vibrance` or `grain`) |
329
+ | `key` | remove a colour from the source, e.g. a green-screen clip |
330
+
331
+ Layers draw in array order, first at the bottom; at most 16, and 8 sources. Each layer costs one
332
+ full-frame pass. `id` is what an animation follows: with `animate`, a layer with the same id
333
+ glides from where it is, a new id fades in, a dropped one fades out.
334
+
335
+ Transitions: `cut`, `fade`, `fadeThrough`, `slideLeft`/`Right`/`Up`/`Down`, `pushLeft`/`Right`,
336
+ `wipeLeft`/`Right`, `iris`, `zoom`. During one, both layouts are drawn, so it costs every layer
337
+ twice for its duration.
338
+
339
+ Also: `layerAt(x, y)` for picking and dragging, `updateSource` (new text, a new camera recipe),
340
+ `snapshot()` to PNG, `startRecording()`/`stopRecording()` to WebM. `layouts` has `full`, `pip`,
341
+ `columns`, `grid`, `lowerThird` and `presenter`; the layout vocabulary is also its own entry,
342
+ `@tradalab/mediakit/layout`, so a layout picker does not pull the wasm loader in.
343
+
344
+ `web/example/scene.html` (`make example`, then `/example/scene.html`) is a working editor.
345
+
346
+ ## Limits worth knowing before you design around them
347
+
348
+ - **A Scene runs on the main thread**, and its loop is a timer: a hidden tab slows it to the
349
+ browser's background timer rate.
350
+ - **Every processed camera in a Scene is its own WebGL context.** Browsers keep 8-16 alive and
351
+ reclaim the oldest past that, so keep processed cameras to a handful. A camera with no filter
352
+ and no effects uses none.
353
+
354
+ - **SVG backgrounds fall back to the main thread.** There is no `Image` in a worker, so the
355
+ pipeline switches transport for those recipes. The picture is correct, the worker benefit is
356
+ not. Raster backgrounds keep the worker.
357
+ - **Safari hands the camera track to the worker**, because it exposes the breakout-box APIs only
358
+ there; where that fails it runs on the `canvas` transport.
359
+ - **`crossOrigin` is set on background images.** A cross-origin background without CORS headers
360
+ fails to load rather than silently tainting the canvas.