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.

TL5a, TL7g: a mask's, a key's and a crop's numbers keyed, and a part's own Adjust in the SDK. sdk/video nudge.tsx: <Nudge keys> takes dotted names (NUDGE_KEYED: mask.x..mask.round, chroma.strength, chroma.shadow, crop.left..crop.bottom, adjust.<kind>), each set into its still mask, key or crop (a mask or key it keys must be given; an adjustment starts as shot), a curve that overshoots held inside the value's range. sdk/video adjust.ts: CapCut's Adjust (brightness, contrast, saturation, exposure, sharpen, highlights, shadows, temperature, tint, fade, vignette, grain) as one SVG filter (a tone table, saturate and a warmth matrix, a 3x3 sharpen, a fractal noise added about its middle, its seed the frame) and a vignette layer; <Nudge adjust> draws them after its chroma key. A probe in raea and in Chrome: tone, colour, sharpen and vignette within 0.4% RMSE, grain the same strength (sd 0.0307 against 0.0308), its noise pattern raea's own. sdk/timeline: KEY_NAMES and KEYABLE (a clip's prop to its <Nudge keys> name, maskFeather to mask.feather), read back and written by them; propsAt, a clip's props at a frame with its keyed ones there. Tests: 25 Nudge keys and cutout, 12 adjust conformance, 99 timeline SDK; the counts (39 browser tests in Chrome, 37 of 39 in raea's window, raea-feed PR #19 e2d005b); the manual regenerated

shinyobjectzfa884594a671
diff --git a/docs/manual/reference/sdk/editor.md b/docs/manual/reference/sdk/editor.md
index 5713e662..8384c7cf 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 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).
+`raea/editor` exports 59 functions, 24 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
@@ -370,6 +370,15 @@ The speed at each of `n` places along the clip's own time (the line drawn over t
function profile(curve: SpeedPoint[], source: number, n: number): number[]
```
+### `propsAt`
+
+A clip's props as they stand `frame` frames from its start: each keyed one at its value there, the rest as set
+(what a mask's, a key's or a crop's look is drawn from while its numbers are keyed, TL5a).
+
+```ts
+function propsAt(clip: { props?: Record<string, boolean | Value> | undefined; keys?: Record<string, Key[]> | undefined; }, frame: number): Record<string, boolean | Value>
+```
+
### `readAdds`
A plugin's additions as written in its manifest, checked: what is well formed, and why the rest isn't.
@@ -557,13 +566,22 @@ The easing presets raea registers; a plugin adds its own beside them.
### `FASTEST`
+### `KEY_NAMES`
+
+What a sequence's <Nudge> can key, as a clip's prop and its <Nudge keys> name: the placement, and the
+numbers inside its mask, its chroma key and its crop ("mask.x" for maskX).
+
### `KEY_PROPS`
A chroma key's values as a clip's props.
+### `KEYABLE`
+
+The clip props a sequence keys.
+
### `KEYED`
-The properties a sequence's <Nudge> can key (sdk/video nudge.tsx).
+A sequence's <Nudge> placement, as still values and as keys (sdk/video nudge.tsx).
### `MASK_KINDS`
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index f6026b6d..f2698836 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. | 58 functions, 22 values, 42 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. | 59 functions, 24 values, 42 types |
## 3D
diff --git a/docs/manual/reference/sdk/raea.md b/docs/manual/reference/sdk/raea.md
index c62e9385..6f70a1dd 100644
--- a/docs/manual/reference/sdk/raea.md
+++ b/docs/manual/reference/sdk/raea.md
@@ -194,7 +194,8 @@ component, whose box it can't reach, or a part with a mask, is placed inside a f
| `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. |
+| `adjust` | `Adjust` | its brightness, contrast, saturation, exposure, sharpen, highlights, shadows, temperature, tint, fade, vignette and grain, each 0 as shot (sdk/video adjust.ts, TL7g) |
+| `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), by the names in NUDGE_KEYED ("mask.x", "chroma.strength", "crop.left" for what is inside a mask, a key or a crop). 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 |
### `Overlay`
diff --git a/docs/timeline.feature b/docs/timeline.feature
index cef715f0..8fded029 100644
--- a/docs/timeline.feature
+++ b/docs/timeline.feature
@@ -88,17 +88,19 @@ Feature: The timeline SDK (0.1.5): CapCut's timeline, on the composition, in the
playback's mapping, readers and writers for a composition's sequences (its footage and sound, its text, its
effects, a recording, a project's file), a film's scenes and a sound's tracks, the palette a plugin adds to; 77
tests), and in
- sdk/video <Nudge keys mask blend chroma> (cutout.ts: a mask's six shapes, CSS's blend modes, a chroma key), <Transition in out combo> (fade, slide, wipe, zoom; a Combo's seven waves), <Effect kind amount in out> (blur, mono,
+ sdk/video <Nudge keys mask blend chroma> (keys for the placement and, by a dotted name, a mask's, a key's and a
+ crop's numbers; cutout.ts: a mask's six shapes, CSS's blend modes, a chroma key), <Transition in out combo> (fade, slide, wipe, zoom; a Combo's seven waves), <Effect kind amount in out> (blur, mono,
sepia, vivid, faded, contrast, bright, dark, invert, hue: a filter on the picture under it) and a <Video>'s or
an <Audio>'s speedCurve (the mixer carries its sound through the changing rate as one voice). In raea-feed, draft
- PR #19: the new timeline is the timeline (localStorage raea.timeline-sdk = 0 brings the old strip back); 38 browser
- tests in Chrome, all passing; in a headless raea window 36 of the 38 pass and two skip themselves there with their
+ PR #19: the new timeline is the timeline (localStorage raea.timeline-sdk = 0 brings the old strip back); 39 browser
+ tests in Chrome, all passing; in a headless raea window 37 of the 39 pass and two skip themselves there with their
reason (the voice test, which would ask for this Mac's microphone, and TL10d, whose film the window decodes itself,
so no route can hold its data), among them TL9c, an agent's edits, a composition's every edit, freeze and reverse, mirror and
crop, effects, groups and compounds, the posted item's, a plugin's effect, text style, tool and snap grid, saved
curves, Settings' kept frames, both kinds of sound taken out, the switcher, the export range, media added, the
Option keys, captions made from what is said, a clip's In, Out and Combo, and its mask, blend and chroma key (whose
- sliders are a track of their own, as the volume's is: the window doesn't move a range input). The window runner (blitz/pw.mjs) answers routes one at a time in the order asked, keeps a reload's
+ sliders are a track of their own, as the volume's is: the window doesn't move a range input), their numbers and the
+ crop's sides keyed (TL5a). The window runner (blitz/pw.mjs) answers routes one at a time in the order asked, keeps a reload's
address and each test's storage, and has keyboard down and up, toBeFocused and waitForResponse. The timeline's keys
follow the pointer over it, not :hover, which raea's window doesn't match for a script, so there they only worked
after a click in the timeline:
@@ -387,6 +389,10 @@ Feature: The timeline SDK (0.1.5): CapCut's timeline, on the composition, in the
declares as a number, a colour or a point)
Then that property has a key there; changing the value at another frame adds a key there
And between two keys the value follows the first key's ease; before the first and after the last it holds
+ And the numbers inside a mask (its centre, size, turn, feather, corners), a chroma key (strength, shadow) and a
+ crop (each side) have their keys beside them in their panels, as the placement's are in the row, and the
+ picture follows them as it plays; in a composition they are the <Nudge keys> of a dotted name ("mask.feather",
+ "chroma.strength", "crop.left"), a curve that overshoots held inside what the value can be
Scenario: TL5b. Keys on the clip
Then a clip with keys shows them as diamonds along it (Option+K shows or hides a row a property)
@@ -467,6 +473,16 @@ Feature: The timeline SDK (0.1.5): CapCut's timeline, on the composition, in the
says; a grey, which has no hue to key by, is refused in words
And in a composition each is a prop of the sequence's <Nudge> (mask, blend, chroma), written and read back,
and raea's renderer draws them as the preview does
+
+ Scenario: TL7g. A clip's own Adjust
+ Given a clip of footage or a still picked
+ When I adjust it (CapCut's Adjust tab: brightness, contrast, saturation, exposure, sharpen, highlights, shadows,
+ temperature, tint, fade, vignette, grain), each a slider from as shot, keyed as any number is (TL5a)
+ Then the picture shows it at once, under the effects over it, after its chroma key
+ And in a composition it is the sequence's <Nudge adjust>, written and read back: its tone one curve read through
+ a table, its colour two colour matrices, sharpen a convolution, grain a noise whose seed is the frame, and a
+ vignette a darkening laid over the part's frame; raea's renderer draws them as Chrome does (11-14 probe: tone,
+ colour, sharpen and vignette within 0.4% RMSE of Chrome, grain the same strength, its noise its own)
And Send tells the agent the mask, the blend and the key as they now stand
Rule: TL8. Sound
diff --git a/sdk/raea/conformance/adjust.test.tsx b/sdk/raea/conformance/adjust.test.tsx
new file mode 100644
index 00000000..95744209
--- /dev/null
+++ b/sdk/raea/conformance/adjust.test.tsx
@@ -0,0 +1,103 @@
+// <Nudge adjust>: a part's brightness, contrast, saturation, exposure, sharpen, highlights, shadows, temperature, tint,
+// fade, vignette and grain (docs/timeline.feature TL7g; sdk/video adjust.ts).
+import { describe, expect, test } from "bun:test";
+import { adjustError, adjustId, adjustSteps, toneAt, vignetteStyle } from "@raea/video/adjust";
+import { Nudge } from "@raea/video/nudge";
+import { renderFrame } from "../src/test";
+
+const opts = { fps: 30, width: 1920, height: 1080, durationInFrames: 300 };
+const at = (el: JSX.Element, frame = 0) => renderFrame(el, { ...opts, frame });
+
+describe("the tone curve", () => {
+ test("as shot it is the picture as it was", () => {
+ for (const v of [0, 0.25, 0.5, 0.75, 1]) expect(toneAt({}, v)).toBeCloseTo(v, 6);
+ expect(adjustSteps({})).toEqual([]);
+ });
+
+ test("exposure is a stop either way, brightness lifts the mids and holds the ends", () => {
+ expect(toneAt({ exposure: 1 }, 0.25)).toBeCloseTo(0.5, 6);
+ expect(toneAt({ exposure: -1 }, 0.5)).toBeCloseTo(0.25, 6);
+ expect(toneAt({ brightness: 1 }, 0.25)).toBeCloseTo(0.5, 6);
+ expect([toneAt({ brightness: 1 }, 0), toneAt({ brightness: 1 }, 1)]).toEqual([0, 1]);
+ });
+
+ test("contrast turns about the middle grey; highlights and shadows each move their own end", () => {
+ expect(toneAt({ contrast: 1 }, 0.5)).toBeCloseTo(0.5, 6);
+ expect(toneAt({ contrast: 1 }, 0.75)).toBeCloseTo(1, 6);
+ expect(toneAt({ contrast: -1 }, 1)).toBeLessThan(0.7);
+ // highlights moves the bright more than the dark, shadows the dark more than the bright
+ expect(toneAt({ highlights: 1 }, 0.75) - 0.75).toBeGreaterThan(toneAt({ highlights: 1 }, 0.25) - 0.25);
+ expect(toneAt({ shadows: 1 }, 0.25) - 0.25).toBeGreaterThan(toneAt({ shadows: 1 }, 0.75) - 0.75);
+ expect(toneAt({ highlights: -1 }, 0.8)).toBeLessThan(0.8);
+ });
+
+ test("fade lifts the blacks and lowers the whites", () => {
+ expect(toneAt({ fade: 1 }, 0)).toBeCloseTo(0.22, 6);
+ expect(toneAt({ fade: 1 }, 1)).toBeCloseTo(0.9, 6);
+ });
+});
+
+describe("the filter's steps", () => {
+ test("only what is changed: a tone table, a saturation, a warmth, a sharpen, a grain", () => {
+ expect(adjustSteps({ contrast: 0.3 }).map((s) => s.tag)).toEqual(["feComponentTransfer"]);
+ expect(adjustSteps({ saturation: -1 })).toEqual([{ tag: "feColorMatrix", attrs: { type: "saturate", values: "0" } }]);
+ expect(adjustSteps({ temperature: 1 })[0].attrs.values).toBe("1.12 0 0 0 0 0 1 0 0 0 0 0 0.88 0 0 0 0 0 1 0");
+ expect(adjustSteps({ sharpen: 1 })[0].attrs.kernelMatrix).toBe("0 -0.4 0 -0.4 2.6 -0.4 0 -0.4 0");
+ // the tone table: 17 levels each for red, green and blue, alpha left as it is
+ const table = adjustSteps({ exposure: 1 })[0];
+ expect(table.children?.map((c) => c.tag)).toEqual(["feFuncR", "feFuncG", "feFuncB"]);
+ expect(table.children?.[0].attrs.tableValues.split(" ")).toHaveLength(17);
+ });
+
+ test("grain is a noise added about its middle, kept to where the part is, its seed the frame", () => {
+ const steps = adjustSteps({ contrast: 0.2, grain: 0.5 }, 42);
+ expect(steps.map((s) => s.tag)).toEqual(["feComponentTransfer", "feTurbulence", "feColorMatrix", "feComposite", "feComposite"]);
+ expect(steps[0].attrs.result).toBe("toned");
+ expect(steps[1].attrs.seed).toBe("42");
+ expect(steps[3].attrs).toMatchObject({ in: "toned", in2: "grey", operator: "arithmetic", k3: "0.15", k4: "-0.075" });
+ expect(steps[4].attrs).toEqual({ in: "grained", in2: "SourceGraphic", operator: "in" });
+ expect(adjustId({ grain: 0.5 }, 7)).not.toBe(adjustId({ grain: 0.5 }, 8));
+ expect(adjustId({ contrast: 0.5 }, 7)).toBe(adjustId({ contrast: 0.5 }, 8));
+ });
+
+ test("a vignette is a darkening over the frame, none at 0", () => {
+ expect(vignetteStyle(0)).toBeUndefined();
+ expect(vignetteStyle(1)?.background).toBe("radial-gradient(ellipse at center, rgba(0, 0, 0, 0) 35%, rgba(0, 0, 0, 0.85) 100%)");
+ });
+
+ test("what is wrong is said", () => {
+ expect(adjustError({ glow: 1 } as never)).toMatch(/"glow" isn't one/);
+ expect(adjustError({ sharpen: -0.5 })).toMatch(/sharpen is from 0 to 1/);
+ expect(adjustError({ contrast: 2 })).toMatch(/contrast is from -1 to 1/);
+ expect(adjustError({ contrast: -1, vignette: 1 })).toBeUndefined();
+ });
+});
+
+describe("<Nudge adjust>", () => {
+ test("the part wears the adjustment's filter, after its key, with the filter beside it", () => {
+ const html = at(<Nudge adjust={{ contrast: 0.4, saturation: 0.2 }} chroma={{ color: "#00ff00" }}><div>hi</div></Nudge>);
+ const id = adjustId({ contrast: 0.4, saturation: 0.2 });
+ expect(html).toContain(`filter:url(#raea-key-00ff00-50-20) url(#${id})`);
+ expect(html).toContain(`<filter id="${id}"`);
+ expect(html).toContain('type="table"');
+ expect(html).toContain('type="saturate" values="1.2"');
+ });
+
+ test("a vignette is a layer over the part's frame", () => {
+ const html = at(<Nudge adjust={{ vignette: 0.5 }}><div>hi</div></Nudge>);
+ expect(html).toContain("radial-gradient(ellipse at center, rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.425) 100%)");
+ // a vignette alone needs no filter
+ expect(html).not.toContain("<filter");
+ });
+
+ test("keyed: an adjustment's number over time, from as shot, without a still adjust", () => {
+ const el = (frame: number) => at(<Nudge keys={{ "adjust.saturation": [[0, 0], [10, -1]] }}><div>hi</div></Nudge>, frame);
+ expect(el(0)).not.toContain("<filter");
+ expect(el(5)).toContain('type="saturate" values="0.5"');
+ expect(el(10)).toContain('type="saturate" values="0"');
+ });
+
+ test("an adjustment out of range fails", () => {
+ expect(() => at(<Nudge adjust={{ grain: 2 }}><div>hi</div></Nudge>)).toThrow(/grain is from 0 to 1/);
+ });
+});
diff --git a/sdk/raea/conformance/nudge-keys.test.tsx b/sdk/raea/conformance/nudge-keys.test.tsx
index cff36078..f3b95170 100644
--- a/sdk/raea/conformance/nudge-keys.test.tsx
+++ b/sdk/raea/conformance/nudge-keys.test.tsx
@@ -38,6 +38,44 @@ describe("a keyed property's value at a frame", () => {
});
});
+describe("the numbers inside a mask, a key and a crop, keyed by a dotted name (TL5a)", () => {
+ const at = (el: JSX.Element, frame: number) => renderFrame(el, { ...opts, frame });
+ const mask = { kind: "circle" as const, x: 0.5, y: 0.5, w: 0.3, h: 0.5 };
+ // the mask image's SVG, decoded
+ const svg = (html: string) => decodeURIComponent(/mask-image:url\(&quot;data:image\/svg\+xml,([^&]*)&quot;\)/.exec(html)?.[1] ?? "");
+
+ test("a mask moves and softens over time, its still kind kept", () => {
+ const el = (frame: number) => at(<Nudge mask={mask} keys={{ "mask.x": [[0, 0.25], [30, 0.75]], "mask.feather": [[0, 0], [30, 0.4]] }}><div>hi</div></Nudge>, frame);
+ // 0.25 of 1920 at the first frame, the middle halfway, 0.75 at the last
+ expect(svg(el(0))).toContain('cx="480"');
+ expect(svg(el(15))).toContain('cx="960"');
+ expect(svg(el(30))).toContain('cx="1440"');
+ expect(svg(el(0))).not.toContain("feGaussianBlur");
+ expect(svg(el(30))).toContain('stdDeviation="21.6"');
+ });
+
+ test("a key's strength over time is a filter of its own each frame", () => {
+ const el = (frame: number) => at(<Nudge chroma={{ color: "#00ff00" }} keys={{ "chroma.strength": [[0, 0.2], [10, 0.8]] }}><div>hi</div></Nudge>, frame);
+ expect(el(0)).toContain("raea-key-00ff00-20-20");
+ expect(el(10)).toContain("raea-key-00ff00-80-20");
+ });
+
+ test("a crop's side over time, the others as still", () => {
+ const el = (frame: number) => at(<Nudge crop={[0, 0.1, 0, 0]} keys={{ "crop.left": [[0, 0], [20, 0.5]] }}><div>hi</div></Nudge>, frame);
+ expect(el(10)).toContain("clip-path:inset(10% 0% 0% 25%)");
+ });
+
+ test("a curve that overshoots stays inside what the value can be", () => {
+ const el = at(<Nudge mask={mask} keys={{ "mask.feather": [[0, 0, [0.3, 1.8, 0.6, 1]], [30, 1]] }}><div>hi</div></Nudge>, 12);
+ expect(svg(el)).toContain('stdDeviation="54"');
+ });
+
+ test("keys for a mask with no mask, or a name it hasn't, fail", () => {
+ expect(() => at(<Nudge keys={{ "mask.x": [[0, 0.2]] }}><div>hi</div></Nudge>, 0)).toThrow(/need a mask/);
+ expect(() => at(<Nudge keys={{ "mask.kind": [[0, 1]] } as never}><div>hi</div></Nudge>, 0)).toThrow(/keys are for/);
+ });
+});
+
describe("a placed part mirrored and cropped (docs/timeline.feature TL3h)", () => {
const at = (el: JSX.Element) => renderFrame(el, { ...opts, frame: 0 });
diff --git a/sdk/timeline/src/keys.ts b/sdk/timeline/src/keys.ts
index 9e5cd2b7..8bb83633 100644
--- a/sdk/timeline/src/keys.ts
+++ b/sdk/timeline/src/keys.ts
@@ -76,6 +76,16 @@ export function valueAt(keys: Key[] | undefined, frame: Frames): Value | undefin
return mix(a.value, b.value, eased(a.ease, (frame - a.at) / (b.at - a.at)))
}
+/** A clip's props as they stand `frame` frames from its start: each keyed one at its value there, the rest as set
+ * (what a mask's, a key's or a crop's look is drawn from while its numbers are keyed, TL5a). */
+export function propsAt(clip: { props?: Record<string, Value | boolean>; keys?: Record<string, Key[]> }, frame: Frames): Record<string, Value | boolean> {
+ const keyed = Object.entries(clip.keys ?? {}).flatMap(([p, ks]) => {
+ const v = valueAt(ks, frame)
+ return v === undefined ? [] : [[p, v] as const]
+ })
+ return { ...clip.props, ...Object.fromEntries(keyed) }
+}
+
/** The keys either side of a cut at `frame` (TL3d: a split clip's keys stay at their frames): the left clip's, and
* the right clip's in its own frames. A cut between two keys puts a key of the value there on both sides, so each
* half moves as the whole did up to the cut. */
diff --git a/sdk/timeline/src/read.ts b/sdk/timeline/src/read.ts
index 3384d877..a18b8669 100644
--- a/sdk/timeline/src/read.ts
+++ b/sdk/timeline/src/read.ts
@@ -6,7 +6,7 @@ import { type Clip, type Ease, empty, end, find, type Frames, type Key, type Tim
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"
+import { CUTOUT_PROPS, cutoutError, cutoutOf, cutoutProps, KEY_PROPS, MASK_PROPS, 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 {
@@ -141,8 +141,19 @@ export type SeqEdit =
/** The transitions a composition's <Transition> draws (sdk/video edges.ts). */
export const CODE_KINDS: string[] = TRANSITION_KINDS
-/** The properties a sequence's <Nudge> can key (sdk/video nudge.tsx). */
+/** A sequence's <Nudge> placement, as still values and as keys (sdk/video nudge.tsx). */
export const KEYED = ["x", "y", "scale", "rotate", "opacity"]
+/** What a sequence's <Nudge> can key, as a clip's prop and its <Nudge keys> name (TL5a): the placement, and the
+ * numbers inside its mask, its chroma key and its crop ("mask.x" for maskX). */
+export const KEY_NAMES: Record<string, string> = {
+ ...Object.fromEntries(KEYED.map((k) => [k, k])),
+ ...Object.fromEntries((["x", "y", "w", "h", "rotate", "feather", "round"] as const).map((k) => [MASK_PROPS[k], `mask.${k}`])),
+ ...Object.fromEntries((["strength", "shadow"] as const).map((k) => [KEY_PROPS[k], `chroma.${k}`])),
+ ...Object.fromEntries(CROPS.map((k) => [k, `crop.${k.slice(4).toLowerCase()}`])),
+}
+/** The clip props a sequence keys. */
+export const KEYABLE = Object.keys(KEY_NAMES)
+const PROP_OF: Record<string, string> = Object.fromEntries(Object.entries(KEY_NAMES).map(([p, n]) => [n, p]))
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)
@@ -163,7 +174,7 @@ export function fromSequences(rows: SeqRow[], fps: number): Timeline {
const media = rows.filter((r) => r.media)
rows = rows.filter((r) => !r.media)
const lanes = [...new Set(rows.map((r) => r.lane))].sort((a, b) => a - b)
- const clipsOf = (lane: number): Clip[] => rows.filter((r) => r.lane === lane).sort((a, b) => a.from - b.from).map((r) => ({ id: seqId(r.i), kind: r.effect ? "effect" : r.text === undefined ? "sequence" : "text", name: r.effect ? (EFFECTS.find((e) => e.kind === r.effect!.kind)?.title ?? r.effect.kind) : (r.text ?? r.label ?? r.name), ...(r.effect && { props: { effect: r.effect.kind, amount: r.effect.amount, ...(r.effect.parts && { parts: JSON.stringify(r.effect.parts) }) } }), ...(r.look && Object.keys(r.look).length && { props: lookProps(r.look) }), start: r.from, length: Math.max(1, r.to - r.from), ...(r.locked && { locked: r.locked }), ...(r.speed && r.speed !== 1 && { speed: r.speed }), ...(r.curve?.length && r.shows && { curve: r.curve.map(([at, speed]) => ({ at, speed })), shows: r.shows }), ...(r.keys && Object.keys(r.keys).length && { keys: Object.fromEntries(Object.entries(r.keys).map(([p, ks]) => [p, ks.map(([at, value, ease]): Key => ({ at, value, ...(ease !== undefined && { ease }) }))])) }) }))
+ const clipsOf = (lane: number): Clip[] => rows.filter((r) => r.lane === lane).sort((a, b) => a.from - b.from).map((r) => ({ id: seqId(r.i), kind: r.effect ? "effect" : r.text === undefined ? "sequence" : "text", name: r.effect ? (EFFECTS.find((e) => e.kind === r.effect!.kind)?.title ?? r.effect.kind) : (r.text ?? r.label ?? r.name), ...(r.effect && { props: { effect: r.effect.kind, amount: r.effect.amount, ...(r.effect.parts && { parts: JSON.stringify(r.effect.parts) }) } }), ...(r.look && Object.keys(r.look).length && { props: lookProps(r.look) }), start: r.from, length: Math.max(1, r.to - r.from), ...(r.locked && { locked: r.locked }), ...(r.speed && r.speed !== 1 && { speed: r.speed }), ...(r.curve?.length && r.shows && { curve: r.curve.map(([at, speed]) => ({ at, speed })), shows: r.shows }), ...(r.keys && Object.keys(r.keys).length && { keys: Object.fromEntries(Object.entries(r.keys).map(([p, ks]) => [PROP_OF[p] ?? p, ks.map(([at, value, ease]): Key => ({ at, value, ...(ease !== undefined && { ease }) }))])) }) }))
const first = lanes.length ? clipsOf(lanes[0]) : []
const gapless = first.length > 0 && first.every((c, n) => c.start === (n ? end(first[n - 1]) : 0))
const tracks: Track[] = lanes.map((lane, n) => ({ id: n === 0 && gapless ? "main" : `overlay-${lane}`, kind: n === 0 && gapless ? "main" : "overlay", clips: clipsOf(lane) }))
@@ -356,7 +367,7 @@ export function seqEdits(t: Timeline, op: Op): SeqEdit[] | { why: string } {
case "unkey":
case "moveKey":
case "ease": {
- if (!KEYED.includes(op.prop)) return { why: `a sequence keys its ${KEYED.join(", ")}: ${op.prop} is its own code's` }
+ if (!KEYABLE.includes(op.prop)) return { why: `a sequence keys its ${KEYED.join(", ")} and the numbers of its mask, key and crop: ${op.prop} is its own code's` }
if (op.op === "key" && typeof op.value !== "number") return { why: `${op.prop} is a number` }
const r = row(op.id)
if (!r) return { why: "that isn't one of the composition's sequences" }
@@ -364,7 +375,7 @@ export function seqEdits(t: Timeline, op: Op): SeqEdit[] | { why: string } {
const after = apply(t, op)
if (!after.ok) return { why: after.why }
const keys = find(after.timeline, op.id)?.clip.keys ?? {}
- return [{ op: "keys", i: r.i, keys: Object.fromEntries(Object.entries(keys).filter(([p]) => KEYED.includes(p)).map(([p, ks]) => [p, ks.map((k): [number, number, Ease?] => (k.ease === undefined || k.ease === "linear" ? [k.at, k.value as number] : [k.at, k.value as number, k.ease]))])) }]
+ return [{ op: "keys", i: r.i, keys: Object.fromEntries(Object.entries(keys).filter(([p]) => KEYABLE.includes(p)).map(([p, ks]) => [KEY_NAMES[p], ks.map((k): [number, number, Ease?] => (k.ease === undefined || k.ease === "linear" ? [k.at, k.value as number] : [k.at, k.value as number, k.ease]))])) }]
}
case "add": {
// an effect put on the picture: a new sequence of its own, holding an <Effect>
diff --git a/sdk/timeline/test/cutout.test.ts b/sdk/timeline/test/cutout.test.ts
index 7647864c..cb37e7d9 100644
--- a/sdk/timeline/test/cutout.test.ts
+++ b/sdk/timeline/test/cutout.test.ts
@@ -1,7 +1,7 @@
// 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"
+import { CUTOUT_PROPS, cutoutError, cutoutLook, cutoutOf, cutoutProps, fromSequences, KEY_NAMES, maskPlain, propsAt, 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", () => {
@@ -66,3 +66,27 @@ describe("TL7f: in a composition it is the sequence's <Nudge mask blend chroma>"
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" })
})
})
+
+describe("TL5a: a mask's, a key's and a crop's numbers are keyed like the placement", () => {
+ const row = { i: 0, name: "Sequence", label: "First scene", from: 0, to: 90, lane: 0 }
+
+ test("the clip's props as they stand at a frame: each keyed one at its value there", () => {
+ const clip = { props: { mask: "circle", maskX: 0.5, maskFeather: 0 }, keys: { maskX: [{ at: 0, value: 0.2 }, { at: 30, value: 0.8 }] } }
+ expect(propsAt(clip, 15)).toEqual({ mask: "circle", maskX: 0.5, maskFeather: 0 })
+ expect(propsAt(clip, 15).maskX).toBeCloseTo(0.5)
+ expect(propsAt(clip, 0).maskX).toBe(0.2)
+ expect(propsAt({ props: { scale: 2 } }, 10)).toEqual({ scale: 2 })
+ })
+
+ test("a key on a mask's feather, a key's strength or a crop's side is its <Nudge keys> by a dotted name, and read back", () => {
+ expect(KEY_NAMES.maskFeather).toBe("mask.feather")
+ expect(KEY_NAMES.keyStrength).toBe("chroma.strength")
+ expect(KEY_NAMES.cropLeft).toBe("crop.left")
+ const t = fromSequences([{ ...row, look: { mask: { kind: "circle" } } }], 30)
+ expect(seqEdits(t, { op: "key", id: "seq-0", prop: "maskFeather", at: 10, value: 0.4 })).toEqual([{ op: "keys", i: 0, keys: { "mask.feather": [[10, 0.4]] } }])
+ const read = fromSequences([{ ...row, look: { mask: { kind: "circle" } }, keys: { "mask.x": [[0, 0.2], [30, 0.8, "hold"]], "crop.top": [[5, 0.1]] } }], 30)
+ expect(read.tracks[0].clips[0].keys).toEqual({ maskX: [{ at: 0, value: 0.2 }, { at: 30, value: 0.8, ease: "hold" }], cropTop: [{ at: 5, value: 0.1 }] })
+ // written back whole, by the same names
+ expect(seqEdits(read, { op: "unkey", id: "seq-0", prop: "cropTop", at: 5 })).toEqual([{ op: "keys", i: 0, keys: { "mask.x": [[0, 0.2], [30, 0.8, "hold"]] } }])
+ })
+})
diff --git a/sdk/timeline/test/read.test.ts b/sdk/timeline/test/read.test.ts
index af52a159..03132855 100644
--- a/sdk/timeline/test/read.test.ts
+++ b/sdk/timeline/test/read.test.ts
@@ -169,7 +169,7 @@ describe("TL0c: a timeline is read from a composition", () => {
expect(seqEdits(keyed, { op: "key", id: "seq-0", prop: "opacity", at: 10, value: 0.5 })).toEqual([{ op: "keys", i: 0, keys: { scale: [[0, 1], [45, 1.2, [0.2, 0, 0, 1]]], opacity: [[10, 0.5]] } }])
expect(seqEdits(keyed, { op: "ease", id: "seq-0", prop: "scale", at: 0, ease: "hold" })).toEqual([{ op: "keys", i: 0, keys: { scale: [[0, 1, "hold"], [45, 1.2, [0.2, 0, 0, 1]]] } }])
expect(seqEdits(keyed, { op: "unkey", id: "seq-0", prop: "scale", at: 45 })).toEqual([{ op: "keys", i: 0, keys: { scale: [[0, 1]] } }])
- expect(seqEdits(keyed, { op: "key", id: "seq-0", prop: "blur", at: 0, value: 1 })).toEqual({ why: "a sequence keys its x, y, scale, rotate, opacity: blur is its own code's" })
+ expect(seqEdits(keyed, { op: "key", id: "seq-0", prop: "blur", at: 0, value: 1 })).toEqual({ why: "a sequence keys its x, y, scale, rotate, opacity and the numbers of its mask, key and crop: blur is its own code's" })
})
})
diff --git a/sdk/video/package.json b/sdk/video/package.json
index 45d5b4c4..34614c95 100644
--- a/sdk/video/package.json
+++ b/sdk/video/package.json
@@ -18,6 +18,7 @@
"./transition": "./src/transition.tsx",
"./edges": "./src/edges.ts",
"./cutout": "./src/cutout.ts",
+ "./adjust": "./src/adjust.ts",
"./words": "./src/words.tsx",
"./region": "./src/region.tsx",
"./overlay": "./src/overlay.tsx",
diff --git a/sdk/video/src/adjust.ts b/sdk/video/src/adjust.ts
new file mode 100644
index 00000000..3cd181cf
--- /dev/null
+++ b/sdk/video/src/adjust.ts
@@ -0,0 +1,113 @@
+// A part's Adjust (docs/timeline.feature TL7g): CapCut's Adjust tab as numbers the timeline writes and <Nudge adjust>
+// draws, and the editor's preview draws the same way. Its tone (exposure, brightness, contrast, highlights, shadows,
+// fade) is one curve read through a table, its colour (saturation, temperature, tint) two colour matrices, sharpen a
+// 3x3 convolution and grain a fractal noise added and centred: one SVG filter, the steps raea's renderer draws as
+// Chrome does. A vignette is a darkening laid over the part's frame, a radial gradient.
+
+/** CapCut's Adjust, in its order: each from -1 to 1 (0 as shot), but sharpen, fade, vignette and grain, from 0. */
+export const ADJUSTS = [
+ { kind: "brightness", title: "Brightness", min: -1 },
+ { kind: "contrast", title: "Contrast", min: -1 },
+ { kind: "saturation", title: "Saturation", min: -1 },
+ { kind: "exposure", title: "Exposure", min: -1 },
+ { kind: "sharpen", title: "Sharpen", min: 0 },
+ { kind: "highlights", title: "Highlights", min: -1 },
+ { kind: "shadows", title: "Shadows", min: -1 },
+ { kind: "temperature", title: "Temperature", min: -1 },
+ { kind: "tint", title: "Tint", min: -1 },
+ { kind: "fade", title: "Fade", min: 0 },
+ { kind: "vignette", title: "Vignette", min: 0 },
+ { kind: "grain", title: "Grain", min: 0 },
+] as const;
+export type AdjustKind = (typeof ADJUSTS)[number]["kind"];
+export const ADJUST_KINDS: AdjustKind[] = ADJUSTS.map((a) => a.kind);
+
+/** A part's adjustments, each 0 (or left out) as shot: brightness, contrast, saturation, exposure, highlights,
+ * shadows, temperature (warm above 0) and tint (magenta above 0) from -1 to 1; sharpen, fade, vignette and grain from
+ * 0 to 1. */
+export type Adjust = Partial<Record<AdjustKind, number>>;
+
+/** An adjustment's errors: a kind it hasn't got, or a value out of its range; undefined when it is right. */
+export function adjustError(a: Adjust): string | undefined {
+ if (!a || typeof a !== "object") return `an adjust is { brightness, contrast, ... }, got ${JSON.stringify(a)}`;
+ for (const [k, v] of Object.entries(a)) {
+ const spec = ADJUSTS.find((x) => x.kind === k);
+ if (!spec) return `an adjust is ${ADJUST_KINDS.join(", ")}: ${JSON.stringify(k)} isn't one`;
+ if (typeof v !== "number" || !(v >= spec.min && v <= 1)) return `an adjust's ${k} is from ${spec.min} to 1, got ${v}`;
+ }
+}
+
+const r4 = (n: number) => Math.round(n * 10000) / 10000;
+const clamp01 = (v: number) => Math.min(1, Math.max(0, v));
+
+/** The tone curve the table holds: an input level (0 to 1) to an output one. */
+export function toneAt(a: Adjust, v: number): number {
+ const { exposure = 0, brightness = 0, contrast = 0, highlights = 0, shadows = 0, fade = 0 } = a;
+ // exposure: a stop either way at its ends
+ let o = clamp01(v * 2 ** exposure);
+ // brightness: the mids raised or lowered by a gamma, the ends held
+ o = o ** (2 ** -brightness);
+ // contrast: about the middle grey, down to a third of it at -1
+ o = clamp01(0.5 + (o - 0.5) * (contrast >= 0 ? 1 + contrast : 1 + contrast * 0.66));
+ // highlights and shadows: the bright and the dark parts moved, each by a bump that leaves the ends where they are
+ o = clamp01(o + 0.35 * highlights * 4 * o * o * (1 - o) + 0.35 * shadows * 4 * o * (1 - o) * (1 - o));
+ // fade: the blacks lifted and the whites lowered, washed out
+ return clamp01(0.22 * fade + o * (1 - 0.32 * fade));
+}
+
+/** One step of an SVG filter: its tag and its attributes, so React and the DOM can each make it. */
+export interface FilterStep {
+ tag: "feComponentTransfer" | "feFuncR" | "feFuncG" | "feFuncB" | "feColorMatrix" | "feConvolveMatrix" | "feTurbulence" | "feComposite";
+ attrs: Record<string, string>;
+ /** a component transfer's functions */
+ children?: FilterStep[];
+}
+
+/** The adjustment as an SVG filter's steps, or none when nothing in it changes the picture's colour or detail (a
+ * vignette alone is an overlay, vignetteStyle). `seed` moves the grain: a render passes the frame, so it lives. */
+export function adjustSteps(a: Adjust, seed = 0): FilterStep[] {
+ const e = adjustError(a);
+ if (e) throw new RangeError(`Adjust: ${e}`);
+ const steps: FilterStep[] = [];
+ if (["exposure", "brightness", "contrast", "highlights", "shadows", "fade"].some((k) => a[k as AdjustKind])) {
+ const table = Array.from({ length: 17 }, (_, i) => r4(toneAt(a, i / 16))).join(" ");
+ steps.push({ tag: "feComponentTransfer", attrs: {}, children: (["feFuncR", "feFuncG", "feFuncB"] as const).map((tag) => ({ tag, attrs: { type: "table", tableValues: table } })) });
+ }
+ if (a.saturation) steps.push({ tag: "feColorMatrix", attrs: { type: "saturate", values: String(r4(1 + a.saturation)) } });
+ if (a.temperature || a.tint) {
+ const t = a.temperature ?? 0, n = a.tint ?? 0;
+ const [r, g, b] = [1 + 0.12 * t + 0.04 * n, 1 - 0.08 * n, 1 - 0.12 * t + 0.04 * n].map(r4);
+ steps.push({ tag: "feColorMatrix", attrs: { type: "matrix", values: `${r} 0 0 0 0 0 ${g} 0 0 0 0 0 ${b} 0 0 0 0 0 1 0` } });
+ }
+ if (a.sharpen) {
+ const s = r4(0.4 * a.sharpen);
+ steps.push({ tag: "feConvolveMatrix", attrs: { order: "3", kernelMatrix: `0 ${-s} 0 ${-s} ${r4(1 + 4 * s)} ${-s} 0 ${-s} 0`, preserveAlpha: "true", edgeMode: "duplicate" } });
+ }
+ if (a.grain) {
+ const g = r4(0.3 * a.grain);
+ const before = steps.length ? "toned" : "SourceGraphic";
+ if (steps.length) steps[steps.length - 1].attrs.result = "toned";
+ steps.push(
+ { tag: "feTurbulence", attrs: { type: "fractalNoise", baseFrequency: "0.9", numOctaves: "1", seed: String(Math.round(seed) % 1000), result: "noise" } },
+ // the noise as one grey, fully seen
+ { tag: "feColorMatrix", attrs: { in: "noise", type: "matrix", values: "1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 1", result: "grey" } },
+ // the picture, plus the grey less its middle: as much lighter as darker
+ { tag: "feComposite", attrs: { in: before, in2: "grey", operator: "arithmetic", k1: "0", k2: "1", k3: String(g), k4: String(r4(-g / 2)), result: "grained" } },
+ // only where the part is
+ { tag: "feComposite", attrs: { in: "grained", in2: "SourceGraphic", operator: "in" } },
+ );
+ }
+ return steps;
+}
+
+/** The id of the SVG filter an adjustment is drawn by: one id for one adjustment (and grain's seed). */
+export function adjustId(a: Adjust, seed = 0): string {
+ const parts = ADJUST_KINDS.filter((k) => a[k] && k !== "vignette").map((k) => `${k.slice(0, 3)}${Math.round(a[k]! * 100)}`);
+ return `raea-adjust-${parts.join("-")}${a.grain ? `-s${Math.round(seed) % 1000}` : ""}`;
+}
+
+/** A vignette as the CSS of a layer over the part's frame: the edges darkened, more and further in as it rises. */
+export function vignetteStyle(v: number): { background: string } | undefined {
+ if (!(v > 0)) return undefined;
+ return { background: `radial-gradient(ellipse at center, rgba(0, 0, 0, 0) ${r4(65 - 30 * v)}%, rgba(0, 0, 0, ${r4(0.85 * v)}) 100%)` };
+}
diff --git a/sdk/video/src/nudge.tsx b/sdk/video/src/nudge.tsx
index 5fd15731..9aa32c32 100644
--- a/sdk/video/src/nudge.tsx
+++ b/sdk/video/src/nudge.tsx
@@ -2,19 +2,36 @@
// 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, 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 { cloneElement, createElement, isValidElement, type CSSProperties, type ReactElement, type ReactNode } from "react";
import { useCurrentFrame, useVideoConfig } from "@raea/app/clock";
import { Easing } from "@raea/math/easing";
+import { ADJUST_KINDS, ADJUSTS, adjustError, adjustId, adjustSteps, vignetteStyle, type Adjust, type FilterStep } from "./adjust";
import { BLEND_KINDS, chromaError, chromaId, chromaMatrix, maskStyle, type Blend, type ChromaKey, type Mask } from "./cutout";
import { AbsoluteFill } from "./timeline";
+export { ADJUSTS, type Adjust, type AdjustKind } from "./adjust";
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). */
export type NudgeKey = [frame: number, value: number, ease?: "linear" | "hold" | [number, number, number, number]];
-export type NudgeProp = "x" | "y" | "scale" | "rotate" | "opacity";
+/** What a <Nudge> keys: its placement, and the numbers inside its mask, its chroma key and its crop, by a dotted
+ * name ("mask.feather" is the mask's feather; a mask or key it keys must be given, as the still kind and colour). */
+export const NUDGE_KEYED = [
+ "x", "y", "scale", "rotate", "opacity",
+ "mask.x", "mask.y", "mask.w", "mask.h", "mask.rotate", "mask.feather", "mask.round",
+ "chroma.strength", "chroma.shadow",
+ "crop.left", "crop.top", "crop.right", "crop.bottom",
+ ...ADJUST_KINDS.map((k) => `adjust.${k}` as const),
+] as const;
+export type NudgeProp = (typeof NUDGE_KEYED)[number];
+const CROP_SIDES = ["left", "top", "right", "bottom"] as const;
+const KEY_RANGE: Partial<Record<NudgeProp, [number, number]>> = {
+ opacity: [0, 1], "mask.w": [0, Infinity], "mask.h": [0, Infinity], "mask.feather": [0, 1], "mask.round": [0, 1],
+ "chroma.strength": [0, 1], "chroma.shadow": [0, 1], "crop.left": [0, 0.9], "crop.top": [0, 0.9], "crop.right": [0, 0.9], "crop.bottom": [0, 0.9],
+ ...Object.fromEntries(ADJUSTS.map((a) => [`adjust.${a.kind}`, [a.min, 1]])),
+};
/** A keyed property's value at `frame`: before its first key and after its last it holds; between two it follows
* the first one's ease. */
@@ -53,8 +70,12 @@ export interface NudgeProps {
blend?: Blend;
/** a colour taken out of it, as a green screen is: { color, strength, shadow } */
chroma?: ChromaKey;
+ /** its brightness, contrast, saturation, exposure, sharpen, highlights, shadows, temperature, tint, fade, vignette
+ * and grain, each 0 as shot (sdk/video adjust.ts, TL7g) */
+ adjust?: Adjust;
/** 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. */
+ * (its <Sequence>'s first frame), by the names in NUDGE_KEYED ("mask.x", "chroma.strength", "crop.left" for what
+ * is inside a mask, a key or a crop). A keyed property's still value is ignored. */
keys?: Partial<Record<NudgeProp, NudgeKey[]>>;
/** the part it places: an element, or a component, which moves inside a full-frame layer */
children?: ReactNode;
@@ -69,8 +90,26 @@ export function Nudge({ keys, ...still }: NudgeProps) {
function Keyed({ keys, children, ...still }: NudgeProps & { keys: NonNullable<NudgeProps["keys"]> }) {
const frame = useCurrentFrame();
- const now: Partial<Record<NudgeProp, number>> = {};
- for (const [prop, ks] of Object.entries(keys) as [NudgeProp, NudgeKey[] | undefined][]) if (ks?.length) now[prop] = keyedAt(ks, frame);
+ const now: Omit<NudgeProps, "keys" | "children"> = {};
+ for (const [prop, ks] of Object.entries(keys) as [NudgeProp, NudgeKey[] | undefined][]) {
+ if (!ks?.length) continue;
+ if (!NUDGE_KEYED.includes(prop)) throw new RangeError(`Nudge: keys are for ${NUDGE_KEYED.join(", ")}, got ${JSON.stringify(prop)}`);
+ // a curve that overshoots stays inside what the value can be
+ const [lo, hi] = KEY_RANGE[prop] ?? [-Infinity, Infinity];
+ const v = Math.min(hi, Math.max(lo, keyedAt(ks, frame)));
+ const [whole, part] = prop.split(".") as [string, string | undefined];
+ if (!part) (now as Record<string, number>)[whole] = v;
+ else if (whole === "crop") {
+ const crop = [...(now.crop ?? still.crop ?? [0, 0, 0, 0])] as [number, number, number, number];
+ crop[CROP_SIDES.indexOf(part as (typeof CROP_SIDES)[number])] = v;
+ now.crop = crop;
+ } else {
+ // a mask's or a key's number: the still one holds its kind or colour; an adjustment's start as shot
+ const own = (now[whole as "mask" | "chroma" | "adjust"] ?? still[whole as "mask" | "chroma" | "adjust"] ?? (whole === "adjust" ? {} : undefined)) as Record<string, unknown> | undefined;
+ if (!own) throw new RangeError(`Nudge: keys for ${prop} need a ${whole} to key`);
+ (now as Record<string, unknown>)[whole] = { ...own, [part]: v };
+ }
+ }
return <Placed {...still} {...now}>{children}</Placed>;
}
@@ -89,8 +128,23 @@ function KeyFilter({ chroma }: { chroma: ChromaKey }) {
);
}
-function Placed({ x = 0, y = 0, scale = 1, rotate = 0, opacity = 1, mirror = false, crop, mask, blend, chroma, children }: Omit<NudgeProps, "keys">) {
+/** An adjustment's SVG filter (adjust.ts), beside the part it adjusts. */
+function AdjustFilter({ id, steps }: { id: string; steps: FilterStep[] }) {
+ const made = (s: FilterStep, i: number): ReactElement => createElement(s.tag, { key: i, ...s.attrs }, ...(s.children ?? []).map(made));
+ return (
+ <svg width={0} height={0} style={{ position: "absolute" }} aria-hidden>
+ <defs>
+ <filter id={id} colorInterpolationFilters="sRGB" x="0" y="0" width="1" height="1">
+ {steps.map(made)}
+ </filter>
+ </defs>
+ </svg>
+ );
+}
+
+function Placed({ x = 0, y = 0, scale = 1, rotate = 0, opacity = 1, mirror = false, crop, mask, blend, chroma, adjust, children }: Omit<NudgeProps, "keys">) {
const { width, height } = useVideoConfig();
+ const frame = useCurrentFrame();
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}`);
@@ -106,14 +160,21 @@ function Placed({ x = 0, y = 0, scale = 1, rotate = 0, opacity = 1, mirror = fal
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}`);
+ const adjustWrong = adjust && adjustError(adjust);
+ if (adjustWrong) throw new RangeError(`Nudge: ${adjustWrong}`);
// 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);
+ // its adjustment's filter (the grain's seed the frame, so it lives) and its vignette
+ const steps = adjust ? adjustSteps(adjust, frame) : [];
+ const tuned = steps.length ? adjustId(adjust!, frame) : undefined;
+ const vignette = adjust?.vignette ? vignetteStyle(adjust.vignette) : undefined;
+ // the key first, then the adjustment, then the part's own filter: CapCut keys the screen before it grades
+ const own = [chroma && `url(#${chromaId(chroma)})`, tuned && `url(#${tuned})`].filter(Boolean).join(" ") || undefined;
+ const placed = (filter?: CSSProperties["filter"]): CSSProperties => ({ ...(cut ? { clipPath: cut } : {}), ...cutout, ...(own ? { filter: filter ? `${own} ${filter}` : own } : {}) });
+ const withKey = (el: ReactNode) => (chroma || tuned ? <>{chroma && <KeyFilter chroma={chroma} />}{tuned && <AdjustFilter id={tuned} steps={steps} />}{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) {
+ // moves with it; on an element's own box it would be squeezed into that box. A vignette is a layer over that frame.
+ if (isValidElement(children) && typeof children.type === "string" && !mask && !vignette) {
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 withKey(cloneElement(children as ReactElement<{ style?: CSSProperties }>, {
@@ -125,5 +186,10 @@ function Placed({ x = 0, y = 0, scale = 1, rotate = 0, opacity = 1, mirror = fal
},
}));
}
- return withKey(<AbsoluteFill style={{ ...(move ? { transform: move } : {}), ...(fade !== 1 ? { opacity: fade } : {}), ...placed() }}>{children}</AbsoluteFill>);
+ return withKey(
+ <AbsoluteFill style={{ ...(move ? { transform: move } : {}), ...(fade !== 1 ? { opacity: fade } : {}), ...placed() }}>
+ {children}
+ {vignette && <AbsoluteFill style={vignette} />}
+ </AbsoluteFill>,
+ );
}