Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

TL7f: a part's mask, blend and chroma key, CapCut's Mask, Basic's Blend and Cutout's Chroma key. sdk/video cutout.ts: a mask is an SVG mask image laid over the frame (line, mirror, circle, rect, heart, star; turned, feathered by a blur no larger than the frame and its reach, inverted by excluding it from a solid layer), a blend is CSS's mix-blend-mode (CapCut's modes CSS has, Add as plus-lighter, then difference and exclusion), a chroma key an SVG filter whose colour matrix makes the key's hue transparent (strength, and shadow letting the screen's darker parts through half seen). <Nudge mask blend chroma> draws them; a masked part is placed in a full-frame layer so the mask moves with it. raea's renderer draws all three as Chrome does (a probe of a keyed green panel, a feathered heart, an inverted turned star and a screen blend; an SVG <mask> for inverting overran Vello's buffers, so it is mask-composite). sdk/timeline cutout.ts: a clip's cutout as props (mask, maskX..maskInvert, blend, keyColor, keyStrength, keyShadow), taken off by their plain values, the preview's look (cutoutLook) and its errors; a sequence's <Nudge> read back with them and written whole by the nudge edit. 18 conformance tests, 97 SDK tests; the manual regenerated

shinyobjectza36df13992f9
diff --git a/docs/manual/reference/sdk/editor.md b/docs/manual/reference/sdk/editor.md
index 14748f90..5713e662 100644
--- a/docs/manual/reference/sdk/editor.md
+++ b/docs/manual/reference/sdk/editor.md
@@ -21,7 +21,7 @@ built, edited and undone.
import { ahead, animStyle, apply, applyAll } from "raea/editor"
```
-`raea/editor` exports 53 functions, 16 values, 37 types. Bevy's counterpart: `raea's own; Bevy has no timeline editor`. Source: [sdk/raea/src/editor.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/editor.ts).
+`raea/editor` exports 58 functions, 22 values, 42 types. Bevy's counterpart: `raea's own; Bevy has no timeline editor`. Source: [sdk/raea/src/editor.ts](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/editor.ts).
## Functions
@@ -114,6 +114,42 @@ half moves as the whole did up to the cut.
function cut(keys: Key[], frame: number): [Key[], Key[]]
```
+### `cutoutError`
+
+What is wrong with a clip's cutout props as they stand, or undefined: a mask kind or blend it hasn't got, a value
+out of range, a grey key.
+
+```ts
+function cutoutError(props?: Props): string | undefined
+```
+
+### `cutoutLook`
+
+How the editor's preview draws a clip's cutout on its picture, as <Nudge> draws it in a composition: CSS for the
+picture, and the SVG filter its key needs (an feColorMatrix's values under `id`, to put beside the picture).
+
+```ts
+function cutoutLook(props: Props | undefined, width: number, height: number): { style: Record<string, string>; key?: { id: string; matrix: string; } | undefined; }
+```
+
+### `cutoutOf`
+
+A clip's cutout read from its props: a mask when its kind is one, a blend other than normal, a key when it has a
+colour.
+
+```ts
+function cutoutOf(props?: Props): Cutout
+```
+
+### `cutoutProps`
+
+A cutout as a clip's props: every one of them, what it hasn't got at its plain value, so a set takes off the
+rest. Values to five places.
+
+```ts
+function cutoutProps(c: Cutout): Props
+```
+
### `eased`
How far along (0..1, or past it for a handle that overshoots) a value is at `p` of the way between two keys.
@@ -260,6 +296,15 @@ function length(t: Timeline): number
Used in: [manual: edits](https://github.com/shinyobjectz/raea/blob/main/docs/manual/examples/edits.tsx).
+### `maskPlain`
+
+A mask's values when a kind is chosen: in the middle, half the frame's shorter side across, so a circle is round
+on any frame; a mirror a band a fifth of the frame's height.
+
+```ts
+function maskPlain(kind: "circle" | "line" | "rect" | "mirror" | "heart" | "star", width: number, height: number): Required<Mask>
+```
+
### `next`
Where the player goes when what it is playing ends at timeline frame `frame`: the next clip's first frame (at
@@ -479,6 +524,13 @@ function without(ranges: Range[], cut: Range[]): Range[]
## Values
+### `BLEND_KINDS`
+
+### `BLENDS`
+
+How a part is drawn over what is under it: CapCut's Blend modes that CSS has (Add is plus-lighter), in its order,
+then difference and exclusion.
+
### `CODE_KINDS`
The transitions a composition's <Transition> draws (sdk/video edges.ts).
@@ -493,6 +545,10 @@ raea's own Combos: the kinds <Transition combo> draws. A plugin adds its own as
CapCut's curve presets, as points over the source; a plugin adds its own.
+### `CUTOUT_PROPS`
+
+Every prop a clip's cutout is held in.
+
### `EASES`
The easing presets raea registers; a plugin adds its own beside them.
@@ -501,10 +557,23 @@ The easing presets raea registers; a plugin adds its own beside them.
### `FASTEST`
+### `KEY_PROPS`
+
+A chroma key's values as a clip's props.
+
### `KEYED`
The properties a sequence's <Nudge> can key (sdk/video nudge.tsx).
+### `MASK_KINDS`
+
+A mask's shapes, in CapCut's order: a line (what is above it is kept), a mirror (a band), a circle, a rectangle,
+a heart and a star.
+
+### `MASK_PROPS`
+
+A mask's values as a clip's props.
+
### `ORDER`
### `PRESET_PROPS`
@@ -567,6 +636,22 @@ How a clip comes in or goes out on its own: a transition's kind over its own fir
type Applied = { ok: true; timeline: Timeline; inverse: Op } | { ok: false; why: string }
```
+### `Blend`
+
+```ts
+type Blend = (typeof BLENDS)[number]["kind"]
+```
+
+### `ChromaKey`
+
+A chroma key: the colour taken out (a green or blue screen), how much of what is near it goes, and how softly.
+
+| Field | Type | What it is |
+| --- | --- | --- |
+| `color` (required) | `string` | the key colour, #rrggbb or #rgb |
+| `strength` | `number` | how far from the key colour is still taken out, 0 (only it) to 1 (most of its hue); 0.5 when not said |
+| `shadow` | `number` | how much of the screen's shadows (its darker, duller parts, nearer grey than the key) is let through half seen rather than kept whole, 0 (none) to 1; it softens the edge too. 0.2 when not said |
+
### `Clip`
A span of something on a track: footage, a sound, words, a composition's sequence, an effect.
@@ -639,6 +724,16 @@ that ends where it starts plays once over the part as CapCut's Combo does, and l
| `rotate` | `number[]` | turned, in degrees |
| `opacity` | `number[]` | how much of it shows, 0 to 1 |
+### `Cutout`
+
+A clip's mask, blend and key, each there only when it has one.
+
+| Field | Type | What it is |
+| --- | --- | --- |
+| `mask` | `Mask` | what of it is seen: a shape in shares of the frame |
+| `blend` | `Blend` | how it is drawn over what is under it |
+| `chroma` | `ChromaKey` | a colour taken out of it |
+
### `Ease`
How a value travels from one key to the next: a straight line, no travel (it holds, then jumps), or a cubic
@@ -735,6 +830,28 @@ A mark at a frame: a beat, a comment's time or one put there by hand.
| `name` | `string` | what it says, shown on hover |
| `color` | `string` | its colour, any CSS colour |
+### `Mask`
+
+A mask, in shares of the part's frame.
+
+| Field | Type | What it is |
+| --- | --- | --- |
+| `kind` (required) | `MaskKind` | its shape: line, mirror, circle, rect, heart or star |
+| `x` | `number` | its centre, a share of the frame's width from the left (0.5 the middle) |
+| `y` | `number` | its centre, a share of the frame's height from the top |
+| `w` | `number` | its width, a share of the frame's (a line has none) |
+| `h` | `number` | its height, a share of the frame's (a mirror's band is this thick) |
+| `rotate` | `number` | a turn, in degrees |
+| `feather` | `number` | how soft its edge is, 0 sharp to 1 (a blur a twentieth of the frame's shorter side) |
+| `round` | `number` | a rectangle's corners, 0 square to 1 as round as its shorter side allows |
+| `invert` | `boolean` | keeps what is outside it instead |
+
+### `MaskKind`
+
+```ts
+type MaskKind = (typeof MASK_KINDS)[number]
+```
+
### `Op`
```ts
@@ -788,6 +905,9 @@ A sequence's still placement: its <Nudge>'s props (sdk/video nudge.tsx). `crop`
| `opacity` | `number` | from 0 (gone) to 1 (as it is) |
| `mirror` | `boolean` | flipped left to right |
| `crop` | `[number, number, number, number]` | cut in from each edge, in % of its size: left, top, right, bottom |
+| `mask` | `Mask` | what of it is seen: a shape in shares of the frame |
+| `blend` | `Blend` | how it is drawn over what is under it, normal when not said |
+| `chroma` | `ChromaKey` | a colour taken out of it |
### `SeqRow`
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index a915f1ec..f6026b6d 100644
--- a/docs/manual/reference/sdk/index.md
+++ b/docs/manual/reference/sdk/index.md
@@ -61,7 +61,7 @@ Footage, pictures, sound, words and colour, and the timeline they are edited on.
| [`raea/image`](image.md) | Pictures on the page and in the world, and texture atlases packed from them. | 3 components, 1 class, 5 types |
| [`raea/asset`](asset.md) | Files the project holds and assets made for it: staticFile, generated sound and music, and glTF bytes. | 9 functions, 1 value, 8 types |
| [`raea/color`](color.md) | Bevy's colour types: Srgba, LinearRgba, Hsla, Oklab, Oklch and the rest, with their conversions. | 2 functions, 7 classes |
-| [`raea/editor`](editor.md) | The timeline the feed edits a film, a scene or a sound on, as data: tracks, clips, keys and markers, every edit an operation with its inverse, a film's scenes read in (fromRender) and its cut read back out as segments (segmentsOf). No React and no DOM: an agent's script, the app's host and a test use the same model the app's timeline does. | 53 functions, 16 values, 37 types |
+| [`raea/editor`](editor.md) | The timeline the feed edits a film, a scene or a sound on, as data: tracks, clips, keys and markers, every edit an operation with its inverse, a film's scenes read in (fromRender) and its cut read back out as segments (segmentsOf). No React and no DOM: an agent's script, the app's host and a test use the same model the app's timeline does. | 58 functions, 22 values, 42 types |
## 3D
diff --git a/docs/manual/reference/sdk/raea.md b/docs/manual/reference/sdk/raea.md
index d9edea32..c62e9385 100644
--- a/docs/manual/reference/sdk/raea.md
+++ b/docs/manual/reference/sdk/raea.md
@@ -180,7 +180,7 @@ The master: every sound in the composition brought to `lufs` integrated loudness
### `Nudge`
Places its child: an element gets the move in front of its own transform and the fade times its own opacity; a
-component, whose box it can't reach, is placed inside a full-frame layer.
+component, whose box it can't reach, or a part with a mask, is placed inside a full-frame layer.
| Prop | Type | What it does |
| --- | --- | --- |
@@ -191,6 +191,9 @@ component, whose box it can't reach, is placed inside a full-frame layer.
| `opacity` | `number` | 0 (gone) to 1 (as it was), times its own opacity |
| `mirror` | `boolean` | flipped left to right |
| `crop` | `[left: number, top: number, right: number, bottom: number]` | how much is cut off its left, top, right and bottom, each a share of that side from 0 to 0.9 |
+| `mask` | `Mask` | what of it is seen: a shape in shares of the frame (line, mirror, circle, rect, heart, star), turned, feathered or inverted (sdk/video cutout.ts, TL7f) |
+| `blend` | `Blend` | how it is drawn over what is under it: screen, multiply, overlay and the rest of CSS's blend modes |
+| `chroma` | `ChromaKey` | a colour taken out of it, as a green screen is: { color, strength, shadow } |
| `keys` | `Partial<Record<NudgeProp, NudgeKey[]>>` | any of the above over time: its keys, each [frame, value, ease?], in frames from where this part's time starts (its <Sequence>'s first frame). A keyed property's still value is ignored. |
| `children` | `ReactNode` | the part it places: an element, or a component, which moves inside a full-frame layer |
diff --git a/sdk/raea/conformance/cutout.test.tsx b/sdk/raea/conformance/cutout.test.tsx
new file mode 100644
index 00000000..4594ad27
--- /dev/null
+++ b/sdk/raea/conformance/cutout.test.tsx
@@ -0,0 +1,133 @@
+// A part's mask, blend and chroma key (docs/timeline.feature TL7f): CapCut's Mask, Blend and Chroma key, drawn by
+// <Nudge> from sdk/video cutout.ts.
+import { describe, expect, test } from "bun:test";
+import { BLEND_KINDS, chromaError, chromaId, chromaMatrix, maskError, maskPlain, maskStyle, maskSvg } from "@raea/video/cutout";
+import { Nudge } from "@raea/video/nudge";
+import { renderFrame } from "../src/test";
+
+const opts = { fps: 30, width: 1920, height: 1080, durationInFrames: 30, frame: 0 };
+const attr = (svg: string, name: string) => [...svg.matchAll(new RegExp(` ${name}="([^"]*)"`, "g"))].map((m) => m[1]);
+
+describe("a mask keeps a shape of the part (TL7f)", () => {
+ test("a circle chosen is round on any frame: half the shorter side across, in the middle", () => {
+ expect(maskPlain("circle", 1920, 1080)).toMatchObject({ x: 0.5, y: 0.5, w: 0.28125, h: 0.5, feather: 0, invert: false });
+ const svg = maskSvg({ kind: "circle" }, 1920, 1080);
+ expect(attr(svg, "cx")).toEqual(["960"]);
+ expect(attr(svg, "rx")).toEqual(["270"]);
+ expect(attr(svg, "ry")).toEqual(["270"]);
+ expect(svg).not.toContain("<filter");
+ });
+
+ test("each shape: a line keeps what is above it, a mirror a band, a rectangle its corners rounded, a heart and a star in their box", () => {
+ const line = maskSvg({ kind: "line", y: 0.25 }, 1000, 500).split("<rect")[1];
+ // a rect reaching far up, its bottom edge on the line at 125 px
+ expect(Number(attr(line, "y")[0]) + Number(attr(line, "height")[0])).toBe(125);
+ const mirror = maskSvg({ kind: "mirror", h: 0.2 }, 1000, 500).split("<rect")[1];
+ expect(attr(mirror, "height")).toEqual(["100"]);
+ expect(attr(maskSvg({ kind: "rect", w: 0.4, h: 0.4, round: 1 }, 1000, 500), "rx")).toEqual(["100"]);
+ expect(maskSvg({ kind: "heart" }, 1000, 500)).toContain("<path");
+ expect(maskSvg({ kind: "star" }, 1000, 500)).toContain("<polygon");
+ });
+
+ test("turned about its centre, feathered by a blur no larger than the frame and its reach, inverted by excluding it from a solid layer", () => {
+ expect(maskSvg({ kind: "rect", x: 0.25, y: 0.5, rotate: 30 }, 1000, 500)).toContain('transform="rotate(30 250 250)"');
+ const soft = maskSvg({ kind: "circle", feather: 1 }, 1000, 500);
+ expect(attr(soft, "stdDeviation")).toEqual(["25"]);
+ expect(soft).toContain('x="-75" y="-75" width="1150" height="650"');
+ const inverted = maskStyle({ kind: "circle", invert: true }, 1000, 500);
+ expect(inverted.maskImage.startsWith("linear-gradient(#000, #000), url(")).toBe(true);
+ expect(inverted).toMatchObject({ maskComposite: "exclude", WebkitMaskComposite: "xor" });
+ expect(maskStyle({ kind: "circle" }, 1000, 500)).not.toHaveProperty("maskComposite");
+ });
+
+ test("as a mask image the size of the part, its own url()s escaped so they aren't read as the page's", () => {
+ const s = maskStyle({ kind: "circle", feather: 0.5 }, 1920, 1080);
+ expect(s.maskImage.startsWith('url("data:image/svg+xml,')).toBe(true);
+ expect(s.maskImage.slice(5)).not.toMatch(/url\(/);
+ expect(s).toMatchObject({ maskSize: "100% 100%", maskRepeat: "no-repeat" });
+ });
+
+ test("a kind it hasn't got, or a value out of range, is refused", () => {
+ expect(maskError({ kind: "moon" as never })).toMatch(/kind is one of line, mirror, circle, rect, heart, star/);
+ expect(maskError({ kind: "circle", feather: 2 })).toMatch(/feather is from 0 to 1/);
+ expect(maskError({ kind: "circle", w: -1 })).toMatch(/0 or more/);
+ expect(maskError({ kind: "circle", x: 0.2 })).toBeUndefined();
+ });
+});
+
+describe("a chroma key takes a colour out (TL7f)", () => {
+ // what the matrix gives a colour's alpha, as the filter clamps it
+ const alpha = (values: string, [r, g, b]: number[]) => {
+ const a = values.split(" ").map(Number).slice(15);
+ return Math.min(1, Math.max(0, a[0] * r + a[1] * g + a[2] * b + a[4]));
+ };
+
+ test("a green screen goes, red and white and grey stay, a dark green is half seen", () => {
+ const m = chromaMatrix({ color: "#00ff00" });
+ expect(alpha(m, [0, 1, 0])).toBe(0);
+ expect(alpha(m, [0.1, 0.9, 0.15])).toBe(0);
+ expect(alpha(m, [1, 0, 0])).toBe(1);
+ expect(alpha(m, [1, 1, 1])).toBe(1);
+ expect(alpha(m, [0.4, 0.4, 0.4])).toBe(1);
+ const dark = alpha(m, [0, 0.5, 0]);
+ expect(dark).toBeGreaterThan(0);
+ expect(dark).toBeLessThan(1);
+ // the colour rows are as they were
+ expect(m.split(" ").slice(0, 15).join(" ")).toBe("1 0 0 0 0 0 1 0 0 0 0 0 1 0 0");
+ });
+
+ test("more strength takes more of the hue; more shadow lets the screen's shadows through half seen", () => {
+ const pale = [0.5, 0.8, 0.5];
+ expect(alpha(chromaMatrix({ color: "#0f0", strength: 0.2 }), pale)).toBe(1);
+ expect(alpha(chromaMatrix({ color: "#0f0", strength: 1 }), pale)).toBe(0);
+ // a shadow on the screen: a darker, duller green
+ const shade = [0.05, 0.5, 0.05];
+ expect(alpha(chromaMatrix({ color: "#0f0", shadow: 0 }), shade)).toBe(1);
+ const half = alpha(chromaMatrix({ color: "#0f0", shadow: 1 }), shade);
+ expect(half).toBeGreaterThan(0.1);
+ expect(half).toBeLessThan(0.5);
+ });
+
+ test("a blue screen keys blue, not green", () => {
+ const m = chromaMatrix({ color: "#1040e0" });
+ expect(alpha(m, [0.06, 0.25, 0.88])).toBe(0);
+ expect(alpha(m, [0, 1, 0])).toBe(1);
+ });
+
+ test("a grey has no hue to key by, and a colour must be one", () => {
+ expect(chromaError({ color: "#808080" })).toMatch(/is grey/);
+ expect(chromaError({ color: "green" })).toMatch(/#rrggbb or #rgb/);
+ expect(chromaError({ color: "#0f0", strength: 3 })).toMatch(/strength is from 0 to 1/);
+ expect(chromaId({ color: "#0f0" })).toBe("raea-key-00ff00-50-20");
+ });
+});
+
+describe("<Nudge> draws them on the part it places", () => {
+ test("an element gets the blend, and the key as its filter before its own, drawn beside it", () => {
+ const html = renderFrame(<Nudge blend="screen" chroma={{ color: "#00ff00" }}><div style={{ filter: "blur(2px)" }}>hi</div></Nudge>, opts);
+ expect(html).toContain("mix-blend-mode:screen");
+ expect(html).toContain("filter:url(#raea-key-00ff00-50-20) blur(2px)");
+ expect(html).toContain('<filter id="raea-key-00ff00-50-20" color-interpolation-filters="sRGB"');
+ expect(html).toContain("<feColorMatrix");
+ expect(html).toContain('operator="in"');
+ });
+
+ test("a masked element is placed in a full-frame layer, so the mask is laid over the frame and moves with it", () => {
+ const html = renderFrame(<Nudge x={40} mask={{ kind: "circle" }}><div style={{ width: 100 }}>hi</div></Nudge>, opts);
+ expect(html).toMatch(/<div style="[^"]*transform:translate\(40px, 0px\)[^"]*mask-image:url\(&quot;data:image\/svg\+xml,[^"]*"><div style="width:100px">hi<\/div><\/div>/);
+ });
+
+ test("a component is placed in a full-frame layer that carries them; normal is no blend", () => {
+ const Part = () => <p>part</p>;
+ const html = renderFrame(<Nudge mask={{ kind: "line", rotate: 10 }} blend="normal"><Part /></Nudge>, opts);
+ expect(html).toContain("mask-image:url(");
+ expect(html).not.toContain("mix-blend-mode");
+ });
+
+ test("a blend it hasn't got, a grey key and a bad mask are refused", () => {
+ expect(BLEND_KINDS).toContain("plus-lighter");
+ expect(() => renderFrame(<Nudge blend={"glow" as never}><div /></Nudge>, opts)).toThrow(/blend is one of normal, darken, screen/);
+ expect(() => renderFrame(<Nudge chroma={{ color: "#777777" }}><div /></Nudge>, opts)).toThrow(/is grey/);
+ expect(() => renderFrame(<Nudge mask={{ kind: "circle", round: 4 }}><div /></Nudge>, opts)).toThrow(/round is from 0 to 1/);
+ });
+});
diff --git a/sdk/timeline/src/cutout.ts b/sdk/timeline/src/cutout.ts
new file mode 100644
index 00000000..de650f65
--- /dev/null
+++ b/sdk/timeline/src/cutout.ts
@@ -0,0 +1,84 @@
+// A clip's mask, blend and chroma key (docs/timeline.feature TL7f: CapCut's Mask, Basic's Blend, Cutout's Chroma
+// key) as its props, a prop a value as a film's crop is a prop a side, so a preset sets them, the editor's preview
+// draws them and a composition's <Nudge mask blend chroma> holds them, drawn by sdk/video cutout.ts in both.
+// Taken off as crop and mirror are, by their plain value: the mask "none", the blend "normal", the key colour "".
+import { BLEND_KINDS, BLENDS, chromaError, chromaId, chromaMatrix, MASK_KINDS, maskError, maskPlain, maskStyle, type Blend, type ChromaKey, type Mask, type MaskKind } from "@raea/video/cutout"
+import type { Value } from "./model"
+
+export { BLEND_KINDS, BLENDS, MASK_KINDS, maskPlain, type Blend, type ChromaKey, type Mask, type MaskKind }
+
+/** A mask's values as a clip's props. */
+export const MASK_PROPS = { kind: "mask", x: "maskX", y: "maskY", w: "maskW", h: "maskH", rotate: "maskRotate", feather: "maskFeather", round: "maskRound", invert: "maskInvert" } as const
+/** A chroma key's values as a clip's props. */
+export const KEY_PROPS = { color: "keyColor", strength: "keyStrength", shadow: "keyShadow" } as const
+/** Every prop a clip's cutout is held in. */
+export const CUTOUT_PROPS: string[] = [...Object.values(MASK_PROPS), "blend", ...Object.values(KEY_PROPS)]
+
+/** A clip's mask, blend and key, each there only when it has one. */
+export interface Cutout {
+ /** what of it is seen: a shape in shares of the frame */
+ mask?: Mask
+ /** how it is drawn over what is under it */
+ blend?: Blend
+ /** a colour taken out of it */
+ chroma?: ChromaKey
+}
+
+type Props = Record<string, Value | boolean>
+const NUMS = ["x", "y", "w", "h", "rotate", "feather", "round"] as const
+
+/** A clip's cutout read from its props: a mask when its kind is one, a blend other than normal, a key when it has a
+ * colour. */
+export function cutoutOf(props: Props = {}): Cutout {
+ const num = (k: string) => (typeof props[k] === "number" && Number.isFinite(props[k]) ? (props[k] as number) : undefined)
+ const kind = props[MASK_PROPS.kind]
+ const mask: Mask | undefined =
+ typeof kind === "string" && (MASK_KINDS as readonly string[]).includes(kind)
+ ? { kind: kind as MaskKind, ...Object.fromEntries(NUMS.flatMap((k) => (num(MASK_PROPS[k]) === undefined ? [] : [[k, num(MASK_PROPS[k])]]))), ...(props[MASK_PROPS.invert] === true && { invert: true }) }
+ : undefined
+ const blend = typeof props.blend === "string" && props.blend !== "normal" && (BLEND_KINDS as string[]).includes(props.blend) ? (props.blend as Blend) : undefined
+ const color = props[KEY_PROPS.color]
+ const chroma: ChromaKey | undefined =
+ typeof color === "string" && color
+ ? { color, ...(num(KEY_PROPS.strength) !== undefined && { strength: num(KEY_PROPS.strength) }), ...(num(KEY_PROPS.shadow) !== undefined && { shadow: num(KEY_PROPS.shadow) }) }
+ : undefined
+ return { ...(mask && { mask }), ...(blend && { blend }), ...(chroma && { chroma }) }
+}
+
+/** A cutout as a clip's props: every one of them, what it hasn't got at its plain value, so a set takes off the
+ * rest. Values to five places. */
+export function cutoutProps(c: Cutout): Props {
+ const r = (n: number) => Math.round(n * 100000) / 100000
+ const m = c.mask
+ return {
+ [MASK_PROPS.kind]: m?.kind ?? "none",
+ ...(m ? Object.fromEntries(NUMS.flatMap((k) => (m[k] === undefined ? [] : [[MASK_PROPS[k], r(m[k]!)]]))) : {}),
+ [MASK_PROPS.invert]: !!m?.invert,
+ blend: c.blend ?? "normal",
+ [KEY_PROPS.color]: c.chroma?.color ?? "",
+ ...(c.chroma?.strength !== undefined && { [KEY_PROPS.strength]: r(c.chroma.strength) }),
+ ...(c.chroma?.shadow !== undefined && { [KEY_PROPS.shadow]: r(c.chroma.shadow) }),
+ }
+}
+
+/** What is wrong with a clip's cutout props as they stand, or undefined: a mask kind or blend it hasn't got, a value
+ * out of range, a grey key. */
+export function cutoutError(props: Props = {}): string | undefined {
+ const kind = props[MASK_PROPS.kind]
+ if (kind !== undefined && kind !== "none" && !(MASK_KINDS as readonly unknown[]).includes(kind)) return `a mask is one of ${MASK_KINDS.join(", ")}, or none: "${String(kind)}" isn't one`
+ if (props.blend !== undefined && !(BLEND_KINDS as unknown[]).includes(props.blend)) return `a blend is one of ${BLEND_KINDS.join(", ")}: "${String(props.blend)}" isn't one`
+ const c = cutoutOf(props)
+ return (c.mask && maskError(c.mask)) || (c.chroma && chromaError(c.chroma)) || undefined
+}
+
+/** How the editor's preview draws a clip's cutout on its picture, as <Nudge> draws it in a composition: CSS for the
+ * picture, and the SVG filter its key needs (an feColorMatrix's values under `id`, to put beside the picture). */
+export function cutoutLook(props: Props | undefined, width: number, height: number): { style: Record<string, string>; key?: { id: string; matrix: string } } {
+ const c = cutoutOf(props)
+ if (cutoutError(props)) return { style: {} }
+ const key = c.chroma && { id: chromaId(c.chroma), matrix: chromaMatrix(c.chroma) }
+ return {
+ style: { ...(c.mask ? (maskStyle(c.mask, width, height) as Record<string, string>) : {}), ...(c.blend && { mixBlendMode: c.blend }), ...(key && { filter: `url(#${key.id})` }) },
+ ...(key && { key }),
+ }
+}
diff --git a/sdk/timeline/src/index.ts b/sdk/timeline/src/index.ts
index b2737fe0..581cf57c 100644
--- a/sdk/timeline/src/index.ts
+++ b/sdk/timeline/src/index.ts
@@ -11,4 +11,5 @@ export * from "./registry"
export * from "./play"
export * from "./captions"
export * from "./anim"
+export * from "./cutout"
export * from "./sounds"
diff --git a/sdk/timeline/src/read.ts b/sdk/timeline/src/read.ts
index cc7f1be5..3384d877 100644
--- a/sdk/timeline/src/read.ts
+++ b/sdk/timeline/src/read.ts
@@ -2,10 +2,11 @@
// lists them (raea-feed host/sequences.ts), or a film with no composition as its scenes and its sound. And an
// operation on a sequences' timeline as the host's own edits to those elements (docs/editing.feature E3b), until
// every operation is a code edit of its own (edits.ts).
-import { type Clip, type Ease, empty, end, find, type Frames, type Key, type Timeline, type Track } from "./model"
+import { type Clip, type Ease, empty, end, find, type Frames, type Key, type Timeline, type Track, type Value } from "./model"
import { apply, type Op } from "./ops"
import { EFFECTS, type EffectPart, type TextStyle, textStyleError } from "./registry"
import { COMBO_KINDS, TRANSITION_KINDS } from "@raea/video/edges"
+import { CUTOUT_PROPS, cutoutError, cutoutOf, cutoutProps, type Blend, type ChromaKey, type Mask } from "./cutout"
/** A text clip's style, kept in its props as JSON: read back when it is well formed. */
export function textStyleOf(v: unknown): TextStyle | undefined {
@@ -93,6 +94,12 @@ export interface SeqLook {
mirror?: boolean
/** cut in from each edge, in % of its size: left, top, right, bottom */
crop?: [number, number, number, number]
+ /** what of it is seen: a shape in shares of the frame (TL7f) */
+ mask?: Mask
+ /** how it is drawn over what is under it, normal when not said (TL7f) */
+ blend?: Blend
+ /** a colour taken out of it (TL7f) */
+ chroma?: ChromaKey
}
const CROPS = ["cropLeft", "cropTop", "cropRight", "cropBottom"]
/** The host's edit to a sequence: its new span, a split, a delete. */
@@ -139,10 +146,11 @@ export const KEYED = ["x", "y", "scale", "rotate", "opacity"]
const seqId = (i: number) => `seq-${i}`
// a sequence's placement as its clip's props (the crop a prop a side, as a film's clip has it)
-const lookProps = (l: SeqLook): Record<string, number | boolean> => ({
+const lookProps = (l: SeqLook): Record<string, Value | boolean> => ({
...Object.fromEntries(KEYED.flatMap((k) => (typeof l[k as keyof SeqLook] === "number" ? [[k, l[k as keyof SeqLook] as number]] : []))),
...(l.mirror && { mirror: true }),
...(l.crop && Object.fromEntries(CROPS.map((k, n) => [k, l.crop![n]]))),
+ ...((l.mask || l.blend || l.chroma) && cutoutProps(l)),
})
// the edits to later elements first (an edit that adds or removes an element moves the places after it)
const later = (a: SeqEdit, b: SeqEdit) => ("i" in b ? b.i : 0) - ("i" in a ? a.i : 0)
@@ -295,17 +303,19 @@ export function seqEdits(t: Timeline, op: Op): SeqEdit[] | { why: string } {
if (amount !== undefined && !(typeof amount === "number" && amount >= 0 && amount <= 1)) return { why: "an effect's amount runs from 0 to 1" }
return each([op.id], (r) => ({ op: "fx", i: r.i, ...(effect !== undefined && { kind: String(effect) }), ...(amount !== undefined && { amount: Math.round((amount as number) * 1000) / 1000 }) }))
}
- // how a sequence is placed (moved, scaled, turned, faded, mirrored, cropped): its <Nudge>'s still props
+ // how a sequence is placed (moved, scaled, turned, faded, mirrored, cropped, masked, blended, keyed): its <Nudge>'s still props
if (only.length === 1 && only[0] === "props" && find(t, op.id)?.clip.kind !== "effect") {
- const bad = Object.keys(op.set.props!).filter((k) => !KEYED.includes(k) && k !== "mirror" && !CROPS.includes(k))
- if (bad.length) return { why: `a sequence is placed by its ${[...KEYED, "mirror", "crop"].join(", ")}: ${bad.join(", ")} ${bad.length > 1 ? "are" : "is"} its own code's` }
+ const bad = Object.keys(op.set.props!).filter((k) => !KEYED.includes(k) && k !== "mirror" && !CROPS.includes(k) && !CUTOUT_PROPS.includes(k))
+ if (bad.length) return { why: `a sequence is placed by its ${[...KEYED, "mirror", "crop", "mask", "blend", "chroma"].join(", ")}: ${bad.join(", ")} ${bad.length > 1 ? "are" : "is"} its own code's` }
const after = apply(t, op)
if (!after.ok) return { why: after.why }
const p = find(after.timeline, op.id)?.clip.props ?? {}
const num = (k: string) => (typeof p[k] === "number" && Number.isFinite(p[k]) ? Math.round((p[k] as number) * 1000) / 1000 : undefined)
if ((num("scale") ?? 1) <= 0) return { why: "a scale is above 0" }
+ const cut = cutoutError(p)
+ if (cut) return { why: cut }
const crop = CROPS.map((k) => Math.min(0.9, Math.max(0, num(k) ?? 0))) as [number, number, number, number]
- const look: SeqLook = { ...Object.fromEntries(KEYED.flatMap((k) => (num(k) === undefined ? [] : [[k, num(k)]]))), ...(p.mirror === true && { mirror: true }), ...(crop.some((v) => v > 0) && { crop }) }
+ const look: SeqLook = { ...Object.fromEntries(KEYED.flatMap((k) => (num(k) === undefined ? [] : [[k, num(k)]]))), ...(p.mirror === true && { mirror: true }), ...(crop.some((v) => v > 0) && { crop }), ...cutoutOf(p) }
return each([op.id], (r) => ({ op: "nudge", i: r.i, look }))
}
// its In and Out animations (TL7d) and its Combo (TL7e): its <Transition>'s edges, as a cut's transition writes them
diff --git a/sdk/timeline/test/cutout.test.ts b/sdk/timeline/test/cutout.test.ts
new file mode 100644
index 00000000..7647864c
--- /dev/null
+++ b/sdk/timeline/test/cutout.test.ts
@@ -0,0 +1,68 @@
+// A clip's mask, blend and chroma key (docs/timeline.feature TL7f): its props, the preview's look, and a
+// composition's <Nudge mask blend chroma>.
+import { describe, expect, test } from "bun:test"
+import { CUTOUT_PROPS, cutoutError, cutoutLook, cutoutOf, cutoutProps, fromSequences, maskPlain, seqEdits } from "../src"
+
+describe("TL7f: a clip's cutout is its props", () => {
+ test("read from props: a mask when its kind is one, a blend other than normal, a key when it has a colour", () => {
+ expect(cutoutOf({ mask: "circle", maskX: 0.3, maskFeather: 0.2, maskInvert: true, blend: "screen", keyColor: "#00ff00", keyStrength: 0.7 })).toEqual({
+ mask: { kind: "circle", x: 0.3, feather: 0.2, invert: true },
+ blend: "screen",
+ chroma: { color: "#00ff00", strength: 0.7 },
+ })
+ // taken off by their plain values
+ expect(cutoutOf({ mask: "none", maskX: 0.3, blend: "normal", keyColor: "" })).toEqual({})
+ expect(cutoutOf(undefined)).toEqual({})
+ })
+
+ test("written as every prop, what it hasn't got at its plain value, so a set takes off the rest", () => {
+ expect(cutoutProps({ mask: { kind: "rect", w: 0.4, h: 0.3, round: 0.5 } })).toEqual({ mask: "rect", maskW: 0.4, maskH: 0.3, maskRound: 0.5, maskInvert: false, blend: "normal", keyColor: "" })
+ expect(cutoutProps({})).toEqual({ mask: "none", maskInvert: false, blend: "normal", keyColor: "" })
+ const c = { mask: { kind: "star" as const, x: 0.25, rotate: 15, invert: true }, blend: "multiply" as const, chroma: { color: "#1040e0", shadow: 0.4 } }
+ expect(cutoutOf(cutoutProps(c))).toEqual(c)
+ for (const k of Object.keys(cutoutProps(c))) expect(CUTOUT_PROPS).toContain(k)
+ })
+
+ test("what is wrong is said: a mask or blend it hasn't got, a value out of range, a grey key", () => {
+ expect(cutoutError({ mask: "moon" })).toMatch(/a mask is one of line, mirror, circle, rect, heart, star, or none/)
+ expect(cutoutError({ blend: "glow" })).toMatch(/a blend is one of normal, darken, screen/)
+ expect(cutoutError({ mask: "circle", maskFeather: 3 })).toMatch(/feather is from 0 to 1/)
+ expect(cutoutError({ keyColor: "#777" })).toMatch(/is grey/)
+ expect(cutoutError({ mask: "heart", blend: "overlay", keyColor: "#0f0" })).toBeUndefined()
+ })
+
+ test("the preview draws it as <Nudge> does: the mask image, the blend, and the key's filter to put beside the picture", () => {
+ const look = cutoutLook({ mask: "circle", maskInvert: true, blend: "screen", keyColor: "#00ff00" }, 1920, 1080)
+ expect(look.style.maskImage).toMatch(/^linear-gradient\(#000, #000\), url\("data:image\/svg\+xml,/)
+ expect(look.style).toMatchObject({ mixBlendMode: "screen", filter: "url(#raea-key-00ff00-50-20)", maskComposite: "exclude" })
+ expect(look.key?.id).toBe("raea-key-00ff00-50-20")
+ expect(look.key?.matrix.split(" ")).toHaveLength(20)
+ // a wrong one draws nothing rather than throwing in the editor
+ expect(cutoutLook({ mask: "moon" }, 1920, 1080)).toEqual({ style: {} })
+ expect(cutoutLook({}, 1920, 1080)).toEqual({ style: {} })
+ })
+
+ test("a mask chosen starts round in the middle of the frame", () => {
+ expect(maskPlain("circle", 1080, 1920)).toMatchObject({ x: 0.5, y: 0.5, w: 0.5, h: 0.28125 })
+ })
+})
+
+describe("TL7f: in a composition it is the sequence's <Nudge mask blend chroma>", () => {
+ const row = { i: 0, name: "Sequence", label: "First scene", from: 0, to: 90, lane: 0 }
+
+ test("read back as the clip's props, beside its placement", () => {
+ const t = fromSequences([{ ...row, look: { scale: 1.2, mask: { kind: "heart", feather: 0.3 }, blend: "screen", chroma: { color: "#00ff00" } } }], 30)
+ expect(t.tracks[0].clips[0].props).toEqual({ scale: 1.2, mask: "heart", maskFeather: 0.3, maskInvert: false, blend: "screen", keyColor: "#00ff00" })
+ // a sequence with none has none of the props
+ expect(fromSequences([{ ...row, look: { scale: 1.2 } }], 30).tracks[0].clips[0].props).toEqual({ scale: 1.2 })
+ })
+
+ test("set on a clip, the whole placement goes to the host with its mask, blend and key; taken off, they go", () => {
+ const t = fromSequences([{ ...row, look: { scale: 1.2 } }], 30)
+ const masked = seqEdits(t, { op: "set", id: "seq-0", set: { props: { mask: "circle", maskW: 0.3, maskH: 0.5, blend: "multiply", keyColor: "#0f0", keyStrength: 0.6 } } })
+ expect(masked).toEqual([{ op: "nudge", i: 0, look: { scale: 1.2, mask: { kind: "circle", w: 0.3, h: 0.5 }, blend: "multiply", chroma: { color: "#0f0", strength: 0.6 } } }])
+ const had = fromSequences([{ ...row, look: { scale: 1.2, mask: { kind: "circle" }, blend: "screen", chroma: { color: "#0f0" } } }], 30)
+ expect(seqEdits(had, { op: "set", id: "seq-0", set: { props: { mask: "none", blend: "normal", keyColor: "" } } })).toEqual([{ op: "nudge", i: 0, look: { scale: 1.2 } }])
+ expect(seqEdits(t, { op: "set", id: "seq-0", set: { props: { keyColor: "#808080" } } })).toEqual({ why: "a chroma key's colour needs a hue to key by: #808080 is grey" })
+ })
+})
diff --git a/sdk/video/package.json b/sdk/video/package.json
index 62ea54fd..45d5b4c4 100644
--- a/sdk/video/package.json
+++ b/sdk/video/package.json
@@ -17,6 +17,7 @@
"./speed": "./src/speed.ts",
"./transition": "./src/transition.tsx",
"./edges": "./src/edges.ts",
+ "./cutout": "./src/cutout.ts",
"./words": "./src/words.tsx",
"./region": "./src/region.tsx",
"./overlay": "./src/overlay.tsx",
diff --git a/sdk/video/src/cutout.ts b/sdk/video/src/cutout.ts
new file mode 100644
index 00000000..521eb736
--- /dev/null
+++ b/sdk/video/src/cutout.ts
@@ -0,0 +1,170 @@
+// A part's mask, blend and chroma key (docs/timeline.feature TL7f): CapCut's Mask tab, Basic's Blend and Cutout's
+// Chroma key, as data the timeline writes and <Nudge> draws, and the editor's preview draws the same way. A mask is
+// an SVG drawn as the part's mask image (a shape, turned, feathered by a blur, or inverted); a chroma key is an SVG
+// filter whose colour matrix makes the key colour's hue transparent. raea's renderer draws both as Chrome does.
+
+/** A mask's shapes, in CapCut's order: a line (what is above it is kept), a mirror (a band), a circle, a rectangle,
+ * a heart and a star. */
+export const MASK_KINDS = ["line", "mirror", "circle", "rect", "heart", "star"] as const;
+export type MaskKind = (typeof MASK_KINDS)[number];
+
+/** A mask, in shares of the part's frame. */
+export interface Mask {
+ /** its shape: line, mirror, circle, rect, heart or star */
+ kind: MaskKind;
+ /** its centre, a share of the frame's width from the left (0.5 the middle) */
+ x?: number;
+ /** its centre, a share of the frame's height from the top */
+ y?: number;
+ /** its width, a share of the frame's (a line has none) */
+ w?: number;
+ /** its height, a share of the frame's (a mirror's band is this thick) */
+ h?: number;
+ /** a turn, in degrees */
+ rotate?: number;
+ /** how soft its edge is, 0 sharp to 1 (a blur a twentieth of the frame's shorter side) */
+ feather?: number;
+ /** a rectangle's corners, 0 square to 1 as round as its shorter side allows */
+ round?: number;
+ /** keeps what is outside it instead */
+ invert?: boolean;
+}
+
+/** A mask's values when a kind is chosen: in the middle, half the frame's shorter side across, so a circle is round
+ * on any frame; a mirror a band a fifth of the frame's height. */
+export function maskPlain(kind: MaskKind, width: number, height: number): Required<Mask> {
+ const side = Math.min(width, height) / 2;
+ return { kind, x: 0.5, y: 0.5, w: r5(side / width), h: kind === "mirror" ? 0.2 : r5(side / height), rotate: 0, feather: 0, round: 0, invert: false };
+}
+
+const r2 = (n: number) => Math.round(n * 100) / 100;
+const r3 = (n: number) => Math.round(n * 1000) / 1000;
+// shares to five places: a 1920 px frame's 540 px is 0.28125, which three places would leave 0.48 px short
+const r5 = (n: number) => Math.round(n * 100000) / 100000;
+
+/** A mask's errors: a kind it doesn't have, or a value out of its range; empty when it is right. */
+export function maskError(m: Mask): string | undefined {
+ if (!m || !MASK_KINDS.includes(m.kind)) return `a mask's kind is one of ${MASK_KINDS.join(", ")}, got ${JSON.stringify(m?.kind)}`;
+ for (const k of ["x", "y", "w", "h", "rotate", "feather", "round"] as const)
+ if (m[k] !== undefined && !Number.isFinite(m[k])) return `a mask's ${k} must be a finite number, got ${m[k]}`;
+ if ((m.w ?? 0) < 0 || (m.h ?? 0) < 0) return `a mask's w and h are 0 or more, got ${m.w}, ${m.h}`;
+ for (const k of ["feather", "round"] as const) if (m[k] !== undefined && !(m[k]! >= 0 && m[k]! <= 1)) return `a mask's ${k} is from 0 to 1, got ${m[k]}`;
+}
+
+// a 5-point star in a unit box, its top point up (the inner points at 0.382 of the outer, a regular star's)
+const STAR = Array.from({ length: 10 }, (_, n) => {
+ const r = n % 2 ? 0.191 : 0.5, a = (n * Math.PI) / 5 - Math.PI / 2;
+ return `${r3(0.5 + r * Math.cos(a))},${r3(0.53 + r * Math.sin(a))}`;
+}).join(" ");
+const HEART = "M0.5 0.92C0.12 0.64 0 0.42 0.04 0.26C0.09 0.06 0.34 -0.02 0.5 0.2C0.66 -0.02 0.91 0.06 0.96 0.26C1 0.42 0.88 0.64 0.5 0.92Z";
+
+/** The mask's shape as SVG markup in the frame's pixels: black (what a mask image keeps) on nothing, turned about
+ * its centre and blurred by its feather. maskStyle inverts it. */
+export function maskSvg(m: Mask, width: number, height: number): string {
+ const e = maskError(m);
+ if (e) throw new RangeError(`Mask: ${e}`);
+ const p = { ...maskPlain(m.kind, width, height), ...m };
+ const cx = r2(p.x * width), cy = r2(p.y * height), w = r2(p.w * width), h = r2(p.h * height), far = width + height;
+ const turn = p.rotate ? ` transform="rotate(${r2(p.rotate)} ${cx} ${cy})"` : "";
+ const unit = (d: string) => `<g${turn}><g transform="translate(${r2(cx - w / 2)} ${r2(cy - h / 2)}) scale(${w || 0.01} ${h || 0.01})">${d}</g></g>`;
+ // black: what a mask image keeps
+ const fill = "#000";
+ const shape = {
+ line: `<rect x="${r2(cx - far)}" y="${r2(cy - far)}" width="${2 * far}" height="${far}"${turn} fill="${fill}"/>`,
+ mirror: `<rect x="${r2(cx - far)}" y="${r2(cy - h / 2)}" width="${2 * far}" height="${h}"${turn} fill="${fill}"/>`,
+ circle: `<ellipse cx="${cx}" cy="${cy}" rx="${r2(w / 2)}" ry="${r2(h / 2)}"${turn} fill="${fill}"/>`,
+ rect: `<rect x="${r2(cx - w / 2)}" y="${r2(cy - h / 2)}" width="${w}" height="${h}" rx="${r2((p.round * Math.min(w, h)) / 2)}"${turn} fill="${fill}"/>`,
+ heart: unit(`<path d="${HEART}" fill="${fill}"/>`),
+ star: unit(`<polygon points="${STAR}" fill="${fill}"/>`),
+ }[p.kind];
+ const sigma = r2(p.feather * Math.min(width, height) * 0.05);
+ const blur = sigma > 0 ? ` filter="url(#f)"` : "";
+ // the blur's area: the frame and as far past it as a blur reaches (three of its widths), no larger, since a filter
+ // is a layer that size (three frames each way overran Vello's buffers)
+ const reach = Math.ceil(3 * sigma);
+ const defs = sigma > 0 ? `<defs><filter id="f" filterUnits="userSpaceOnUse" x="${-reach}" y="${-reach}" width="${width + 2 * reach}" height="${height + 2 * reach}"><feGaussianBlur stdDeviation="${sigma}"/></filter></defs>` : "";
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">${defs}<g${blur}>${shape}</g></svg>`;
+}
+
+/** The mask as CSS mask images the size of the part's box: the shape, or inverted, the shape excluded from a solid
+ * layer (1 less the shape, its feather kept; an SVG <mask> drawing the same overran Vello's buffers). The SVG's
+ * parentheses are escaped too, so its own url()s aren't read as the page's. */
+export function maskStyle(m: Mask, width: number, height: number) {
+ const shape = `url("data:image/svg+xml,${encodeURIComponent(maskSvg(m, width, height)).replace(/\(/g, "%28").replace(/\)/g, "%29")}")`;
+ const image = m.invert ? `linear-gradient(#000, #000), ${shape}` : shape;
+ return {
+ maskImage: image,
+ WebkitMaskImage: image,
+ maskSize: "100% 100%",
+ WebkitMaskSize: "100% 100%",
+ maskRepeat: "no-repeat",
+ WebkitMaskRepeat: "no-repeat",
+ ...(m.invert ? { maskComposite: "exclude", WebkitMaskComposite: "xor" } : {}),
+ };
+}
+
+/** How a part is drawn over what is under it: CapCut's Blend modes that CSS has (Add is plus-lighter), in its order,
+ * then difference and exclusion. */
+export const BLENDS = [
+ { kind: "normal", title: "Normal" },
+ { kind: "darken", title: "Darken" },
+ { kind: "screen", title: "Screen" },
+ { kind: "overlay", title: "Overlay" },
+ { kind: "multiply", title: "Multiply" },
+ { kind: "lighten", title: "Lighten" },
+ { kind: "hard-light", title: "Hard light" },
+ { kind: "soft-light", title: "Soft light" },
+ { kind: "color-burn", title: "Color burn" },
+ { kind: "color-dodge", title: "Color dodge" },
+ { kind: "plus-lighter", title: "Add" },
+ { kind: "difference", title: "Difference" },
+ { kind: "exclusion", title: "Exclusion" },
+] as const;
+export type Blend = (typeof BLENDS)[number]["kind"];
+export const BLEND_KINDS: Blend[] = BLENDS.map((b) => b.kind);
+
+/** A chroma key: the colour taken out (a green or blue screen), how much of what is near it goes, and how softly. */
+export interface ChromaKey {
+ /** the key colour, #rrggbb or #rgb */
+ color: string;
+ /** how far from the key colour is still taken out, 0 (only it) to 1 (most of its hue); 0.5 when not said */
+ strength?: number;
+ /** how much of the screen's shadows (its darker, duller parts, nearer grey than the key) is let through half seen
+ * rather than kept whole, 0 (none) to 1; it softens the edge too. 0.2 when not said */
+ shadow?: number;
+}
+
+/** A #rgb or #rrggbb colour as 0-1 channels, or undefined. */
+export function rgbOf(color: string): [number, number, number] | undefined {
+ const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color?.trim() ?? "");
+ if (!m) return undefined;
+ const hex = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1];
+ return [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255) as [number, number, number];
+}
+
+/** A chroma key's errors, or undefined. A grey can't be keyed by its hue, which it hasn't got. */
+export function chromaError(k: ChromaKey): string | undefined {
+ const rgb = rgbOf(k?.color);
+ if (!rgb) return `a chroma key's colour is #rrggbb or #rgb, got ${JSON.stringify(k?.color)}`;
+ const mean = (rgb[0] + rgb[1] + rgb[2]) / 3;
+ if (rgb.reduce((s, c) => s + (c - mean) ** 2, 0) < 0.02) return `a chroma key's colour needs a hue to key by: ${k.color} is grey`;
+ for (const p of ["strength", "shadow"] as const) if (k[p] !== undefined && !(k[p]! >= 0 && k[p]! <= 1)) return `a chroma key's ${p} is from 0 to 1, got ${k[p]}`;
+}
+
+/** The chroma key as an feColorMatrix's 20 values. A colour's share of the key's hue is p = (C · d) / |d|², d the key
+ * colour less its grey (1 for the key, 0 for any grey, below 0 for the opposite hue); alpha falls from 1 to 0 as p
+ * rises through the strength's cut, over the shadow's width. The colour rows are left as they are. */
+export function chromaMatrix(k: ChromaKey): string {
+ const e = chromaError(k);
+ if (e) throw new RangeError(`Chroma key: ${e}`);
+ const rgb = rgbOf(k.color)!;
+ const mean = (rgb[0] + rgb[1] + rgb[2]) / 3;
+ const d = rgb.map((c) => c - mean);
+ const dd = d.reduce((s, c) => s + c * c, 0);
+ const cut = 1 - 0.85 * (k.strength ?? 0.5), width = 0.03 + 0.4 * (k.shadow ?? 0.2);
+ const a = d.map((c) => r3(-c / dd / width));
+ return ["1 0 0 0 0", "0 1 0 0 0", "0 0 1 0 0", `${a[0]} ${a[1]} ${a[2]} 0 ${r3(cut / width)}`].join(" ");
+}
+
+/** The id of the SVG filter a chroma key is drawn by: one id for one key, so two parts keyed alike share it. */
+export const chromaId = (k: ChromaKey) => `raea-key-${rgbOf(k.color)!.map((c) => Math.round(c * 255).toString(16).padStart(2, "0")).join("")}-${Math.round((k.strength ?? 0.5) * 100)}-${Math.round((k.shadow ?? 0.2) * 100)}`;
diff --git a/sdk/video/src/nudge.tsx b/sdk/video/src/nudge.tsx
index f8820c3d..5fd15731 100644
--- a/sdk/video/src/nudge.tsx
+++ b/sdk/video/src/nudge.tsx
@@ -1,12 +1,15 @@
// Nudge: a part placed by hand on raea's picture (docs/editing.feature, E1). The editor writes a moved, scaled, turned
// or faded part back to the composition as one <Nudge x y scale rotate opacity> around the element that holds it (the
-// timeline also writes mirror and crop, docs/timeline.feature TL3h); the
+// timeline also writes mirror and crop, docs/timeline.feature TL3h, and a mask, a blend and a chroma key, TL7f); the
// next change to the same part re-writes that line.
import { cloneElement, isValidElement, type CSSProperties, type ReactElement, type ReactNode } from "react";
-import { useCurrentFrame } from "@raea/app/clock";
+import { useCurrentFrame, useVideoConfig } from "@raea/app/clock";
import { Easing } from "@raea/math/easing";
+import { BLEND_KINDS, chromaError, chromaId, chromaMatrix, maskStyle, type Blend, type ChromaKey, type Mask } from "./cutout";
import { AbsoluteFill } from "./timeline";
+export { BLENDS, MASK_KINDS, type Blend, type ChromaKey, type Mask, type MaskKind } from "./cutout";
+
/** A property's value at a frame, and how it leaves for the next key: a straight line (the default), no travel
* ("hold": it stays, then jumps), or a cubic bezier's two handles [x1, y1, x2, y2] as CSS writes them. The timeline
* writes these (docs/timeline.feature TL5d). */
@@ -43,6 +46,13 @@ export interface NudgeProps {
mirror?: boolean;
/** how much is cut off its left, top, right and bottom, each a share of that side from 0 to 0.9 */
crop?: [left: number, top: number, right: number, bottom: number];
+ /** what of it is seen: a shape in shares of the frame (line, mirror, circle, rect, heart, star), turned, feathered
+ * or inverted (sdk/video cutout.ts, TL7f) */
+ mask?: Mask;
+ /** how it is drawn over what is under it: screen, multiply, overlay and the rest of CSS's blend modes */
+ blend?: Blend;
+ /** a colour taken out of it, as a green screen is: { color, strength, shadow } */
+ chroma?: ChromaKey;
/** any of the above over time: its keys, each [frame, value, ease?], in frames from where this part's time starts
* (its <Sequence>'s first frame). A keyed property's still value is ignored. */
keys?: Partial<Record<NudgeProp, NudgeKey[]>>;
@@ -51,7 +61,7 @@ export interface NudgeProps {
}
/** Places its child: an element gets the move in front of its own transform and the fade times its own opacity; a
- * component, whose box it can't reach, is placed inside a full-frame layer. */
+ * component, whose box it can't reach, or a part with a mask, is placed inside a full-frame layer. */
export function Nudge({ keys, ...still }: NudgeProps) {
// keyed: the frame is read where the keys are (a hook, so in a component of its own), and the values placed as still ones
return keys && Object.values(keys).some((k) => k?.length) ? <Keyed keys={keys} {...still} /> : <Placed {...still} />;
@@ -64,7 +74,23 @@ function Keyed({ keys, children, ...still }: NudgeProps & { keys: NonNullable<Nu
return <Placed {...still} {...now}>{children}</Placed>;
}
-function Placed({ x = 0, y = 0, scale = 1, rotate = 0, opacity = 1, mirror = false, crop, children }: Omit<NudgeProps, "keys">) {
+/** The SVG filter a chroma key is drawn by (cutout.ts), beside the part it keys: the key's colour matrix, its alpha
+ * then times the part's own so what was clear stays clear. */
+function KeyFilter({ chroma }: { chroma: ChromaKey }) {
+ return (
+ <svg width={0} height={0} style={{ position: "absolute" }} aria-hidden>
+ <defs>
+ <filter id={chromaId(chroma)} colorInterpolationFilters="sRGB" x="0" y="0" width="1" height="1">
+ <feColorMatrix type="matrix" in="SourceGraphic" result="keyed" values={chromaMatrix(chroma)} />
+ <feComposite in="keyed" in2="SourceGraphic" operator="in" />
+ </filter>
+ </defs>
+ </svg>
+ );
+}
+
+function Placed({ x = 0, y = 0, scale = 1, rotate = 0, opacity = 1, mirror = false, crop, mask, blend, chroma, children }: Omit<NudgeProps, "keys">) {
+ const { width, height } = useVideoConfig();
for (const [k, v] of Object.entries({ x, y, scale, rotate, opacity }))
if (!Number.isFinite(v)) throw new RangeError(`Nudge: ${k} must be a finite number, got ${v}`);
if (scale <= 0) throw new RangeError(`Nudge: scale must be above 0, got ${scale}`);
@@ -77,17 +103,27 @@ function Placed({ x = 0, y = 0, scale = 1, rotate = 0, opacity = 1, mirror = fal
if (crop !== undefined && (!Array.isArray(crop) || crop.length !== 4 || crop.some((v) => !(v >= 0 && v <= 0.9)))) throw new RangeError(`Nudge: crop is [left, top, right, bottom], each from 0 to 0.9, got ${JSON.stringify(crop)}`);
// (inset's order is top, right, bottom, left)
const cut = crop?.some((v) => v > 0) ? `inset(${crop[1] * 100}% ${crop[2] * 100}% ${crop[3] * 100}% ${crop[0] * 100}%)` : undefined;
- if (isValidElement(children) && typeof children.type === "string") {
+ if (blend !== undefined && !BLEND_KINDS.includes(blend)) throw new RangeError(`Nudge: blend is one of ${BLEND_KINDS.join(", ")}, got ${JSON.stringify(blend)}`);
+ const keyError = chroma && chromaError(chroma);
+ if (keyError) throw new RangeError(`Nudge: ${keyError}`);
+ // the mask, laid over the frame's shape, and the blend: CSS on the part, so they move with it
+ const cutout: CSSProperties = { ...(mask ? (maskStyle(mask, width, height) as CSSProperties) : {}), ...(blend && blend !== "normal" ? { mixBlendMode: blend } : {}) };
+ const keyed = chroma ? `url(#${chromaId(chroma)})` : undefined;
+ const placed = (filter?: CSSProperties["filter"]): CSSProperties => ({ ...(cut ? { clipPath: cut } : {}), ...cutout, ...(keyed ? { filter: filter ? `${keyed} ${filter}` : keyed } : {}) });
+ const withKey = (el: ReactNode) => (chroma ? <><KeyFilter chroma={chroma} />{el}</> : el);
+ // a mask is laid over the frame, so a masked part is placed in a full-frame layer, as a component is, and the mask
+ // moves with it; on an element's own box it would be squeezed into that box
+ if (isValidElement(children) && typeof children.type === "string" && !mask) {
const style = ((children.props as { style?: CSSProperties }).style ?? {}) as CSSProperties;
const own = typeof style.opacity === "number" ? style.opacity : style.opacity === undefined ? 1 : Number(style.opacity);
- return cloneElement(children as ReactElement<{ style?: CSSProperties }>, {
+ return withKey(cloneElement(children as ReactElement<{ style?: CSSProperties }>, {
style: {
...style,
...(move ? { transform: style.transform ? `${move} ${style.transform}` : move } : {}),
...(fade !== 1 ? { opacity: own * fade } : {}),
- ...(cut ? { clipPath: cut } : {}),
+ ...placed(style.filter),
},
- });
+ }));
}
- return <AbsoluteFill style={{ ...(move ? { transform: move } : {}), ...(fade !== 1 ? { opacity: fade } : {}), ...(cut ? { clipPath: cut } : {}) }}>{children}</AbsoluteFill>;
+ return withKey(<AbsoluteFill style={{ ...(move ? { transform: move } : {}), ...(fade !== 1 ? { opacity: fade } : {}), ...placed() }}>{children}</AbsoluteFill>);
}