Compare commits

...
Author SHA1 Message Date
shinyobjectz a90420a8bf no-void leaves the component library out: its gradient shader's own name is void 2026-11-30 18:12:05 -08:00
shinyobjectz 7309e95d90 raea help's line for make component says list WORDS searches the library 2026-11-30 18:07:55 -08:00
shinyobjectz 853f77eb1c The component library: 609 open-source effects sorted by use, searched by raea make component list WORDS and copied by add NAME
sdk/raea/library/components holds 475 pieces from remocn, 79 from the React Video Editor templates and 55 from snapcn,
ported to raea's composition API and sorted by what they're for (text, numbers, transitions, screens, HUDs and more),
not by who made them. catalog.json lists each piece's category, type, what it does, its files, the shared helpers it
needs, its fonts and npm packages and its source; CREDITS.md holds the licences and every file's first line names its
source.

- `raea make component list` ends with the library's categories; `list WORDS` searches by category, category/type or
  words (catalog.ts). `add NAME` copies the piece into components/CATEGORY/NAME/ with its helpers under
  components/_lib/, and installs its npm packages through the engine.
- The native host reads the library beside the binary (share/raea, which tools/release.sh already packs from
  sdk/raea/library), in RAEA_HOME, or in the tree a built raea runs from.
- tools/effects-catalog.sh writes the cut-down catalogue raea cloud's dashboard imports (Libraries › Effects).
- tools/size.sh leaves the library out: it's other people's code, kept as they wrote it but for imports.
- conformance/catalog.test.ts: every listed file exists, imports stay inside what a piece copies, none imports another
  video framework, and search finds by use.
2026-11-30 18:06:34 -08:00
shaneandshinyobjectz 95b2c01a24 raea goal check reads an export's captions and hears its voice (captions + voice packs; farm reads text) (#280)
* raea goal check reads an export's captions and hears its voice: captions and voice packs, and the farm reads text

Shane 11-30: "running a transcription and ocr pass on the final output ... catch if audio captions pick up something
else that's not supposed to be there or if we cut off words. as well we should be checking audio if it's too quiet
for dialogue". Elfster's cut 1 shipped hand-typed captions that dropped "when they get", "okay, this is" and
"organize your"; Body Shop's reaction cut buried the host 7 dB over its music. No check saw either.

captions (sdk/goal/src/packs/captions.ts): the farm's /v1/scene now reads each line of text (texts, RapidOCR
PP-OCRv4, Apache-2.0, about 0.13 s a 540-wide frame on CPU). A line is a caption when it fits what's said while
it's up with few edits (capitals, a badge's style, held stricter), lasts under 4.5 s, sits in a row with other
captions, in a frame with 3 lines or fewer, and the cut has a track of them (8 showings, 40% of the speech).
Shown-not-said: letters no word near it holds. Said-not-shown: words between captioned words that no caption has,
an error for 3 or more in a row where the captions are phrases; a line at a caption run's edge is a warning.
Calibrated on our 8 Elfster/Body Shop cuts and 4 shipped client refs: the refs' phrase captions pass clean but
one (Body Shop Video6's opening line under its hook card), and ours find what was found by hand.

voice (packs/voice.ts): on the export, the speech's level (80th percentile inside words) over the bed between
words: under 6 dB an error, under 10 a warning; each line against the typical line: 6 dB quieter an error, 4 a
warning. The 4 refs are clean; Elfster 2am (4.5 dB) and Body Shop edible (4.4) fail.

Both are in the cut and floor sets. The Scene type carries texts; media.ts passes them through. The farm needs a
deploy (rapidocr in the image) before captions reads anything; until then it notes the reader has no texts.

* raea goal check times on-screen text against its words: the reading pack

Shane 11-30: "the words on screen relative to duration ... if a wordy CTA or component or scene is meant to be fully
read or if it just adds glossable content or context, and if it's on screen long enough to be read."

From the farm's texts, every line that isn't a caption (nor words shown as they're said) is followed frame to frame;
lines that come up together are one block. A block needs 0.5 s plus 3 words a second: under that a warning, under 60%
of it an error. A block of 25 words or more, small text (under 54 px of 1080x1920) or a phone's screen (a status-bar
clock) is texture: a warning that asks whether it's meant to be read. Frames with more than 6 lines (a shelf of
labels, an app shot whole) and blocks of 3 words or fewer are left out. Every finding gives words, seconds and words
a second.

Calibrated on the 8 Elfster/Body Shop cuts and 4 shipped refs: it finds Elfster cut 2's 15-word hook card up 1 s and
Body Shop's reaction CTA card (11 words, 2 s); the refs give one error (an Elfster app screen up 1 s). In cut and floor.

* raea goal check holds every size the brief asks for at done (sizes-all)

Shane 11-30: "it will show completed but what about doing all the resizes". Dutch finished on its 9:16 masters alone:
the brief's 4:5, 1:1 and 16:9 were never made, because one-size-first was a rule against resizing early and nothing
asked for the other sizes at the end. At done, every ad's newest version (adOf, _v#) must be in every format its
brief names (cut `formats`, the brief's and each cut's), unless a person's answer to the open item about "sizes"
names fewer. The finding says which sizes are missing and the file name each takes. test/sizes.test.ts.

* raea ducks music under the talking by default, and goal check holds the hook and the air between words

Shane 11-30: the StreetTalk cuts' music was "about 4 or 5 decibels too loud ... make sure standards and measurements
correctly mix by default to move audio down in the mix, especially while talking, but a CTA with no audio is fine";
Elfster's Voted cut opened on 1.5 s of a silent whiteboard ("a hook really should have audio and video stimulation");
and "measuring and cutting air gaps safely ... it CANNOT destroy words".

- systems/mix: an edit with no Tone graph gets DEFAULT_GRAPH: footage and voice files on a `talk` bus, effects on the
  master, any other audio file on a `bed` bus ducked DEFAULT_DUCK_DB (-6) under the talking, released where nobody
  talks. The names aren't raea/tone's, so an edit's own buses never change; `bus="master"` opts a sound out. Offline
  bounce and live play pick it the same way (score.rs routes a bus-less sound by default_bus). Test: the music sits
  6 dB down under the talk and comes back after it.
- @raea/video airgaps: airGaps(words) and tighten(words, { levels }): the spans of a take to keep, gaps cut to 0.15 s
  in the hook and 0.25 s after, only between words, 80 ms kept either side, each cut pulled back while the take is
  still loud (a transcript's early word end).
- goal packs hook and airgaps (cut and floor): a first word over 1 s in with a quiet opening is an error (Voted:
  1.5 s, -15 dB); gaps over 0.5 s in the first 3 s are errors, over 0.3 s warnings, over 0.8 s after warnings.
- sound pack: bus-less files classed as the mixer routes them (a music file with any name is music, not a voice
  line), the default duck counted, and music within 10 dB of the voice warns (was 6), as the voice pack does.

* The voice check judges the bed only on enough gaps between words

Body Shop's host-hook cut read "1.5 dB above what's under it" off a single 0.34 s gap between two "Mmm"s, where the
speaker was still humming; the agent's own measure (pauses of 0.8 s and more) read 11.7 dB. A tightly cut take has few
gaps, so the bed is judged only on 3 or more gaps and 1 s of them in all.

* The default mix's graph moves to raea-sys-tone, and its test to its own file, so raea-sys-mix is under 2000 lines

CI's size gate: raea-sys-mix was 2048 lines and offline.rs 530. DEFAULT_GRAPH, DEFAULT_DUCK_DB and default_bus are
the default Tone graph, so they live with the graph format in raea-sys-tone (defaults.rs) and raea-sys-mix re-exports
them; the duck test is duck_test.rs.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 15:13:18 -08:00
1296 changed files with 391834 additions and 34 deletions

No files matched your search

+12 -2
View File
@@ -2,7 +2,7 @@
title: "raea make component"
summary: "Copy a ready-made component or set into the project's components/, or the workspace's shared/components/, to use and change as your own."
order: 103
sources: ["engine/cli/src/index.ts", "engine/cli/src/registry.gen.ts"]
sources: ["engine/cli/src/index.ts", "engine/cli/src/registry.gen.ts", "engine/cli/src/catalog.ts"]
---
Components are ready-made pieces of a composition (captions, lower thirds, end cards and the like) and sets of them.
@@ -10,10 +10,20 @@ Components are ready-made pieces of a composition (captions, lower thirds, end c
never updates or overwrites it unasked. With `--shared` it goes into the workspace's `shared/components/` instead, for
every project to import as `@shared/components/NAME`. `raea part` is the old name and still works.
Beside raea's own sets is the library: several hundred open-source components (text reveals, counters, charts,
transitions, product-screen demos, game HUDs and more), sorted by what they're for rather than who made them.
`raea make component list` ends with its categories; `list WORDS` searches it by a category (`text`), a category and
type (`text/reveal`), or words in a name or description (`"count up"`). `add NAME` copies the component into
`components/CATEGORY/NAME/`, with the shared helpers it needs under `components/_lib/`. Each file's first line names
the library it came from, and `CREDITS.md` in sdk/raea/library/components holds their licences.
```sh
raea make component list
raea make component add captions end-card
raea make component add reel --shared
raea make component list text/reveal
raea make component list count up
raea make component add soft-blur-in
```
<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
@@ -21,7 +31,7 @@ raea make component add reel --shared
## Usage
```sh
raea make component list | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change)
raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, "count up")
```
Headless: it needs nothing running and opens no window. Takes any number of arguments besides its flags.
+48
View File
@@ -0,0 +1,48 @@
// The component library (sdk/raea/library/components, catalog.ts): every listed file is there, every relative import
// in it lands on a file of the library, nothing imports another video framework, and the search finds by use.
import { describe, expect, test } from "bun:test";
import { existsSync, readFileSync } from "node:fs";
import { dirname, join, normalize } from "node:path";
import { listed, type Item } from "../src/catalog";
const lib = join(import.meta.dir, "../../../sdk/raea/library/components");
const cat = JSON.parse(readFileSync(join(lib, "catalog.json"), "utf8")) as { sources: Record<string, { licence: string }>; items: Item[] };
describe("the component library", () => {
test("each item's files and the shared files it needs are there, and each item names a known source", () => {
const missing = cat.items.flatMap((i) => [...i.files, ...i.needs].filter((f) => !existsSync(join(lib, f))).map((f) => `${i.name}: ${f}`));
expect(missing).toEqual([]);
expect(cat.items.filter((i) => !cat.sources[i.from]?.licence).map((i) => i.name)).toEqual([]);
});
test("an item's relative imports land inside what it copies, and none is another framework's", () => {
const bad: string[] = [];
for (const i of cat.items) {
const copied = new Set([...i.files, ...i.needs]);
for (const f of i.files.concat(i.needs).filter((f) => /\.tsx?$/.test(f))) {
const src = readFileSync(join(lib, f), "utf8");
if (/from\s+["']@?remotion/.test(src)) bad.push(`${f}: imports remotion`);
// a package it imports is one `add` installs (its packages), or raea's own, or React
for (const [, pkg] of src.matchAll(/from\s+"([^".][^"]*)"/g)) if (!/^(raea|raea\/[\w/]+|react|react-dom)$/.test(pkg) && !(i.packages ?? []).includes(pkg)) bad.push(`${f}: imports ${pkg}, not in its packages`);
for (const [, spec] of src.matchAll(/(?:from\s+|import\s*\(?)"(\.[^"<]*)"/g)) {
const base = normalize(join(dirname(f), spec));
if (![base, `${base}.ts`, `${base}.tsx`, `${base}/index.ts`, `${base}/index.tsx`].some((c) => copied.has(c))) bad.push(`${i.name}: ${f} -> ${spec}`);
}
}
}
expect(bad).toEqual([]);
});
test("names are unique, so `add NAME` means one thing", () => {
const names = cat.items.map((i) => i.name);
expect(names.filter((n, k) => names.indexOf(n) !== k)).toEqual([]);
});
test("search: a category, a category/type, and words in what it does", () => {
expect(listed(cat.items, [])).toContain("text");
expect(listed(cat.items, ["text/reveal"])).toContain("text/soft-blur-in");
expect(listed(cat.items, ["text/reveal"])).not.toContain("numbers/");
expect(listed(cat.items, ["count", "up"]).split("\n")[0]).toContain("count");
expect(listed(cat.items, ["zzqx"])).toContain("no component in the library");
});
});
+80
View File
@@ -0,0 +1,80 @@
// The component library (sdk/raea/library/components): other people's open components, sorted by what they're for,
// not by who wrote them. catalog.json lists each: its category and type, what it does, its own files, the shared files
// it needs, the fonts it loads and where it came from (CREDITS.md beside it holds the licences). `raea make component
// list WORDS` searches it and `raea make component add NAME` copies one into the project (index.ts). The host half
// (the files) runs on the native raea; the rest is plain strings.
import { existsSync, readFileSync, realpathSync } from "node:fs";
import { dirname, join } from "node:path";
export type Item = { name: string; category: string; type: string; says: string; component: string; default?: boolean; files: string[]; needs: string[]; fonts: string[]; packages?: string[]; from: string };
type Catalog = { sources: Record<string, { url: string; licence: string }>; items: Item[] };
export type Got = { item: Item; licence: string; files: Record<string, string> };
/** The library's folder: in RAEA_HOME, beside a release's bin/raea (share/raea), or in the tree a built raea is in */
function home(raea: string, env: Record<string, string | undefined>): string | undefined {
const bin = dirname(realpathSync(raea));
const rel = "sdk/raea/library/components";
return [env.RAEA_HOME && join(env.RAEA_HOME, rel), join(bin, "../share/raea", rel), join(bin, "../..", rel)].find((p) => p && existsSync(join(p, "catalog.json")));
}
/** Host op "components": {op: "list"} is every item, {op: "get", name} one item with its files' text (by its path in
* the library, which is its path under components/). No library beside this raea: an empty list, and no item. */
export function componentsHost(raea: string, env: Record<string, string | undefined>, a: Record<string, unknown>): Item[] | Got | null {
const dir = home(raea, env);
if (!dir) return a.op === "get" ? null : [];
const cat = JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) as Catalog;
if (a.op !== "get") return cat.items;
const want = String(a.name).replace(/^\/+|\/+$/g, "");
const item = cat.items.find((i) => i.name === want || `${i.category}/${i.name}` === want || `${i.category}/${i.type}/${i.name}` === want);
if (!item) return null;
const files = Object.fromEntries([...item.files, ...item.needs].map((f) => [f, readFileSync(join(dir, f), "utf8")]));
return { item, licence: cat.sources[item.from]?.licence ?? "", files };
}
const row = (i: Item) => `${`${i.category}/${i.name}`.padEnd(34)} ${i.type.padEnd(13)} ${i.says.split(". ")[0].slice(0, 110)}`;
/** `raea make component list`'s lines for the library: with no words, each category and its types; with words, the
* items they name. A word is a category ("text"), a category/type ("text/reveal"), or anything in a name or in what
* an item does; every word must be found, and a name's own words count first. */
export function listed(items: Item[], words: string[]): string {
if (!items.length) return "";
if (!words.length) {
const cats = [...new Set(items.map((i) => i.category))].sort();
const line = (c: string) => {
const of = items.filter((i) => i.category === c);
const types = [...new Set(of.map((i) => i.type))].sort().map((t) => `${t} ${of.filter((i) => i.type === t).length}`);
return `${c.padEnd(14)} ${String(of.length).padStart(3)} ${types.join(", ")}`;
};
return `\nThe library, by what a component is for (raea make component list text, list text/reveal, list "count up"; add NAME copies one):\n${cats.map(line).join("\n")}\n`;
}
const ws = words.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
const phrase = ws.join(" ");
const score = (i: Item) => {
// the words together, as written, in what it does: ahead of the same words scattered
let s = ws.length > 1 && i.says.toLowerCase().includes(phrase) ? 3 : 0;
for (const w of ws) {
const [c, t] = w.split("/");
if (w.includes("/") ? i.category === c && (!t || i.type === t) : i.category === w || i.type === w) s += 4;
else if (i.name.split("-").includes(w)) s += 3;
else if (i.name.includes(w)) s += 2;
else if (i.says.toLowerCase().includes(w)) s += 1;
else return 0;
}
return s;
};
const found = items.map((i) => [score(i), i] as const).filter(([s]) => s > 0).sort((a, b) => b[0] - a[0] || a[1].name.localeCompare(b[1].name));
if (!found.length) return `no component in the library for "${words.join(" ")}" (raea make component list shows the categories)\n`;
return found.map(([, i]) => row(i)).join("\n") + "\n";
}
/** What `add` says of a copied item: where it is, how to import it, the fonts it loads, whose it was */
export function added(g: Got, home: string, from: string, wrote: number, kept: number, installed = ""): string {
const i = g.item;
const pk = i.packages?.length ? `\n npm packages: ${i.packages.join(", ")}${installed ? ` (${installed})` : ` (not installed: raea add ${i.packages.join(" ")})`}` : "";
const shared = i.needs.length ? `, ${i.needs.length} shared under ${home}/_lib and beside it` : "";
const fonts = i.fonts.length ? `\n fonts: ${i.fonts.join(", ")} (loaded by name; set your brand's in its props or the file)` : "";
return `${home}/${i.category}/${i.name}/ ${i.files.length} files${shared}${kept ? ` (${kept} already here, kept)` : ""}; ${wrote} written
import ${i.default ? i.component : `{ ${i.component} }`} from "${from}/${i.category}/${i.name}"; (${i.says.split(". ")[0]})
its props and their defaults are at the top of index.tsx (or none: then its words and colours are in the file): the source's samples, make them the brief's${fonts}${pk}
from ${i.from}, ${g.licence}: yours to change; the first line of each file keeps the credit\n`;
}
+1 -1
View File
@@ -149,7 +149,7 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|parts] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, NAME.parts.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] [--client NAME] | raea project tag [NAME] [--client NAME] [--no-client] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; its client, what raea.app files every card shown from it under (raea cloud's tags: projects don't nest); split and join keep its history)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {} ({})\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, tools::motion::SETUP_USAGE, tools::motion::SETUP_ABOUT, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);
let (export_game, capcut, layers, xml, scene, physics, splat, wear, bake) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, raea_app_scene::USAGE, motion::physics::USAGE, tools::splat::USAGE, raea_runtime_wear::USAGE, raea_app_lightbake::USAGE);
let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_ask::USAGE, format!("{GOAL_USAGE}\n {}", raea_app_make::USAGE), raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
return Ok(usage::under_make(&format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea words FILE [-o OUT.words.json] (what FILE says, word by word, into its words.json beside it: parakeet-mlx on a Mac, the farm's Whisper on a raea cloud box)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; WORDS search the library by use: text/reveal, \"count up\")\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {} ({})\n {capcut}\n {layers}\n {xml}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {bake}\n {wear} (a .glb's weathering causes for raea/wear: the model with a second UV set and its cause maps, made once in the asset store)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n {light_usage} (each scene on each light path against its path-traced reference: distance in stops, the worst tile, a moving shot's flicker, a frame's cost; DIR/report.json)\n {} (each case on each denoiser against its converged truth: FLIP, RMSE, bias, flicker, blotches, lag after a disocclusion or a light going out, a frame's cost, and how many of MetalFX's numbers each meets; DIR/report.json)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)", raea_app_playable::USAGE, raea_app_playable::ABOUT, raea_denoise_bench::USAGE)));
}
// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)
if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {
+31 -3
View File
@@ -27,6 +27,8 @@ import { libraryVerb } from "./library";
import { absolute, fromCwd, labelsIn, showVerb } from "./show";
// `raea make clothes` (clothes.ts): garments for SOMA's body from words
import { clothesVerb } from "./clothes";
// the component library (catalog.ts): open components sorted by use, listed and copied by `raea make component`
import { added, listed, type Got, type Item } from "./catalog";
// `raea bug` (bug.ts): an agent's report of a bug in raea, to raea's server
import { bugVerb } from "./bug";
@@ -191,8 +193,11 @@ export function raeaHandler(host?: Host, engine?: Engine) {
// LY4), or with --shared into the workspace's shared/components/, which every project imports as @shared/components/
case "component": {
const was = "";
if (args[1] === "list" || args[1] === undefined) return out(parts(), 0, was);
if (args[1] !== "add") return out("", 2, `${was}raea make component list | raea make component add NAME ... [--shared] [--force]\n`);
// the library beside this raea (none in a shell with no host: raea's own sets are all it lists)
const shelf = (): Item[] => (host ? (host("components", { op: "list" }) as Item[]) : []);
if (args[1] === undefined) return out(parts() + listed(shelf(), []), 0, was);
if (args[1] === "list") return out(clean(args.slice(2)).length ? listed(shelf(), clean(args.slice(2))) : parts() + listed(shelf(), []), 0, was);
if (args[1] !== "add") return out("", 2, `${was}raea make component list [WORDS] | raea make component add NAME ... [--shared] [--force]\n`);
const names = clean(args.slice(2));
if (!names.length) return out("", 2, `${was}raea make component add NAME ... (raea make component list shows them)\n`);
const force = args.includes("--force");
@@ -220,7 +225,30 @@ export function raeaHandler(host?: Host, engine?: Engine) {
continue;
}
const src = single(n);
if (!src) return out(done.join(""), 1, `raea make component add: no component or set "${n}" (raea make component list shows them)\n`);
// a library component: its folder under components/CATEGORY/NAME/, with the shared files it needs
const got = src || !host ? null : (host("components", { op: "get", name: n }) as Got | null);
if (got) {
let wrote = 0;
let kept = 0;
for (const [f, text] of Object.entries(got.files)) {
const dest = p(`${home}/${f}`);
if (!force && (await c.fs.exists(dest))) kept++;
else {
await c.fs.mkdir(dest.slice(0, dest.lastIndexOf("/")), { recursive: true });
await c.fs.writeFile(dest, text);
wrote++;
}
}
// its npm packages (culori and the like), installed by the engine's package manager when there is one
let installed = "";
if (got.item.packages?.length && engine) {
const r = await native(["add", ...got.item.packages]);
installed = r.exitCode ? `raea add failed: ${(r.stderr || r.stdout).trim().split("\n")[0]}` : "installed";
}
done.push(added(got, absolute(home) ? "shared/components" : home, from, wrote, kept, installed));
continue;
}
if (!src) return out(done.join(""), 1, `raea make component add: no component or set "${n}" (raea make component list shows them, list WORDS searches the library)\n`);
const dest = p(`${home}/${n}.tsx`);
if (!force && (await c.fs.exists(dest))) {
done.push(`${shown(`${home}/${n}.tsx`)} is already here (yours now; --force replaces it)\n`);
+3
View File
@@ -13,6 +13,7 @@ import { wordsOf } from "./heard";
import { harness, library, show, task } from "./app";
import { fromCwd } from "./show";
import { clothesHost } from "./wardrobe";
import { componentsHost } from "./catalog";
import { raeaHandler, type Engine, type Host } from "./index";
const [raea, ...args] = process.argv.slice(2);
@@ -426,6 +427,8 @@ const host: Host = (op, a) => {
return playable(a as { file: string });
case "clothes":
return clothesHost(raea, cwd, process.env, a);
case "components":
return componentsHost(raea, process.env, a);
case "bug":
return bug(a as { report: Record<string, unknown>; dry?: boolean });
case "harness":
+6 -2
View File
@@ -120,6 +120,9 @@ image = (
"c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063 /opt/yolox_s.onnx "
"03f550c6b406fda8bf54bd8327815f6c7e2edd98cea02348c93d879254366587 /opt/ppocr_det.onnx | sha256sum -c"
)
# /v1/scene's texts (11-30): RapidOCR's PP-OCRv4 reads each line of text in a frame, for raea goal check's captions
# pack (what an export shows, held to what it says). Apache-2.0; its ONNX models ship in the wheel
.pip_install("rapidocr_onnxruntime==1.4.4")
.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True)
# RAEA_GOAL_RENDER 0: a render here ends without raea goal check's render moment, which the box that sent it runs
# on the export it gets back (server/offload.ts), beside the project's brief.ts
@@ -485,7 +488,8 @@ def api():
"""what's in a video's frames, for raea goal check's frames and place packs and `raea make place` (farm_scene.py): the body is
{"frames": [base64 JPEG, ...]} (at most 400), the answer each frame's size, its faces and split-screen seams
(each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], in that frame's pixels"""
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
[x, y, w, h, "the text", score], in that frame's pixels"""
import base64
import cv2
import numpy as np
@@ -510,7 +514,7 @@ def api():
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar", "frames": out}
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
@web.post("/v1/words")
async def words(req: Request):
+25 -2
View File
@@ -8,6 +8,7 @@ Four small ONNX models from OpenCV's zoo, on the CPU through cv2.dnn, each pinne
YOLOX-S (2022nov, Apache-2.0): COCO's 80 things, as boxes, at 640x640
PP-OCRv3 DB (2023may, Apache-2.0): words in the shot (a sign someone holds, a shop's name), as boxes labelled "text"
YuNet (2023mar, MIT): faces, as boxes (the frames pack's)
And RapidOCR's PP-OCRv4 (1.4.4, Apache-2.0), which reads each line of text, for the captions pack.
A frame's answer: its size, a grid of how much of each cell is a person (0-9, a cell ~1/27 of the shorter side), the
faces and the things as [x, y, w, h, label, score] in the frame's pixels."""
@@ -48,6 +49,7 @@ class Scene:
self.words_model.setPolygonThreshold(0.5)
self.words_model.setMaxCandidates(200)
self.words_model.setUnclipRatio(2.0)
self.ocr = None
self.face_path = face
self.face, self.face_size = None, None
@@ -121,10 +123,31 @@ class Scene:
_, found = self.face.detect(im)
return [[round(float(f[0]), 1), round(float(f[1]), 1), round(float(f[2]), 1), round(float(f[3]), 1), "face", round(float(f[14]), 3)] for f in (found if found is not None else [])]
def read(self, im):
def texts(self, im, least=0.5):
"""each line of text in the frame, read, as [x, y, w, h, "the text", score] (11-30, the captions pack: what an
export shows, held to what it says). RapidOCR's PP-OCRv4 (Apache-2.0, its ONNX models in the wheel), on the
CPU; it reads 540-wide frames' captions word for word in about 0.13 s a frame, where OpenCV's zoo CRNN dropped
spaces and misread them. Loaded on first use"""
if self.ocr is None:
from rapidocr_onnxruntime import RapidOCR
self.ocr = RapidOCR()
found, _ = self.ocr(im, use_cls=False)
out = []
for box, text, score in found or []:
if float(score) < least:
continue
xs, ys = [p[0] for p in box], [p[1] for p in box]
out.append([round(float(min(xs)), 1), round(float(min(ys)), 1), round(float(max(xs) - min(xs)), 1), round(float(max(ys) - min(ys)), 1), str(text), round(float(score), 3)])
return out
def read(self, im, texts=True):
h, w = im.shape[:2]
p = self.people(im)
return {"w": w, "h": h, "grid": grid(p, w, h), "things": self.things(im) + self.words(im), "faces": self.faces(im)}
out = {"w": w, "h": h, "grid": grid(p, w, h), "things": self.things(im) + self.words(im), "faces": self.faces(im)}
if texts:
out["texts"] = self.texts(im)
return out
def grid(p, w, h):
+7 -2
View File
@@ -27,6 +27,11 @@ export interface Workflow {
/** raea's packs by name (packs/index.ts): what each holds a job to */
export const PACKS = {
words: "every word a cut's lines say is heard whole in its export, none faded under a crossfade",
captions: "every caption on screen says exactly what's heard there: nothing added or changed, no words dropped from a captioned line",
voice: "the dialogue on top of the mix (10 dB over what's under it) and every line as loud as the others, measured on the export",
hook: "the hook opens on words and picture together: no dead air before the first word",
airgaps: "no air between words: gaps tightened in the hook's first 3 s, no long pause after (tighten() cuts between words only)",
reading: "every block of text that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture",
sound: "edit points in the pauses, every line within 6 dB of the others, every effect heard",
frames: "no face cut by the frame or a split screen's seam, no text too small to read",
montage: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts",
@@ -55,13 +60,13 @@ export type PackName = keyof typeof PACKS
/** each kind's packs, on unless the brief switches them off (surprise is on only where a brief turns it on) */
export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
cut: ["words", "sound", "frames", "montage", "place", "floor", "stills", "seen", "naming", "sizes", "quotes", "count", "open", "say", "never", "cta", "shape"],
cut: ["words", "captions", "voice", "reading", "hook", "airgaps", "sound", "frames", "montage", "place", "floor", "stills", "seen", "naming", "sizes", "quotes", "count", "open", "say", "never", "cta", "shape"],
rules: ["deliverables", "stills"],
scene: ["deliverables", "record", "critic", "notes", "stills"],
kit: ["deliverables", "record", "critic", "notes", "stills"],
shot: ["deliverables", "record", "critic", "notes", "stills"],
// a project with no `goal`: what any made video is held to, and any composition as it's saved
floor: ["frames", "floor", "seen", "stills"],
floor: ["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"],
}
/** a `says` rule: what a fresh critic must find true of the work (`raea goal judge`) */
+2 -1
View File
@@ -234,7 +234,8 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
}
const fs = (g.faces as any[][]) ?? []
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs } as Scene)
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
}
}
return { rate: at?.length ? 0 : RATE, faces, scenes }
+214
View File
@@ -0,0 +1,214 @@
// The captions pack (11-30, Shane: "running a transcription and ocr pass on the final output as fast as possible would
// be helpful because it also helps catch if audio captions pick up something else that's not supposed to be there or if
// we cut off words"): what an export SHOWS against what it SAYS, both read off the export itself, so it can't be passed
// by what the edit meant to show. Elfster's captions, typed by hand, said "for a bad gift" (said: "when they get a bad
// gift"), "Oh my god" (said: "Oh my"), dropped half a line and two words of the brief's own call to action; every
// check passed them, since none read the picture.
//
// read: the scene reader (raea cloud's farm, POST /v1/scene) reads the text in each frame, two a second (PP-OCRv4).
// heard: the words pass's transcript of the same export.
// captions: a line of text whose letters mostly match what's said around it (within 2.5 s before to 1 s after) is a
// caption; hook text, a title, a logo or a sign isn't, and is left alone.
// shown, not said: a run of three letters or more in the captions that nothing heard near it accounts for is an
// error (a word added or changed: "god").
// said, not shown: while captions are up, a heard word the captions leave out is a warning, two or more in a row an
// error (words dropped: "when they get"). Fillers (um, uh) aren't counted.
// Letters are compared, not words: the reader often drops a caption's spaces ("Createyour GiftExchangehere.").
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import type { TextLine } from "./place.ts"
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
export type Read = TextLine
export type Finding = { level: "error" | "warn" | "note"; kind: "shown" | "dropped" | "none"; at: number; says: string }
/** a word or a line as it's compared: lower case letters and digits, nothing else */
export const letters = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "")
/** what's said that a caption may leave out without changing what's said */
const FILLER = new Set(["um", "uh", "uhh", "umm", "mm", "mhm", "hmm", "er", "erm", "ah"])
/** a line is a caption when this share of its letters is matched by what's said around it */
export const CAPTION = 0.6
/** the time around a caption that what it says may be heard: before it shows, after */
const BEFORE = 2.5
const AFTER = 1.0
/** least score a read line counts at */
export const LEAST = 0.6
/** a caption against what's said around it: the caption's letters aligned to the stretch of the heard letters they fit
* best (an edit distance with the heard text's start and end free). dist: the edits; bad: for each caption letter,
* whether it was changed or added (no heard letter matches it) */
export function fit(cap: string, said: string): { dist: number; bad: boolean[]; from: number; to: number } {
const n = cap.length
const m = said.length
// D[i][j]: edits to make cap[0..i) end at said[j); a free start anywhere in said
const D = Array.from({ length: n + 1 }, (_, i) => new Uint16Array(m + 1).fill(i))
for (let i = 1; i <= n; i++)
for (let j = 1; j <= m; j++) D[i][j] = Math.min(D[i - 1][j - 1] + (cap[i - 1] === said[j - 1] ? 0 : 1), D[i - 1][j] + 1, D[i][j - 1] + 1)
let j = 0
for (let k = 1; k <= m; k++) if (D[n][k] < D[n][j]) j = k
const dist = D[n][j]
const to = j
const bad = new Array<boolean>(n).fill(false)
let i = n
while (i > 0 && j > 0) {
const d = D[i][j]
if (d === D[i - 1][j - 1] + (cap[i - 1] === said[j - 1] ? 0 : 1)) {
if (cap[i - 1] !== said[j - 1]) bad[i - 1] = true
i--
j--
} else if (d === D[i - 1][j] + 1) bad[--i] = true
else j--
}
while (i > 0) bad[--i] = true
return { dist, bad, from: j, to }
}
/** the heard words whose time falls in [a, b] */
const heardIn = (heard: Word[], a: number, b: number) => heard.filter((w) => w.end >= a && w.start <= b)
const saidAround = (heard: Word[], a: number, b: number) => heardIn(heard, a - BEFORE, b + AFTER).map((w) => letters(w.text)).join("")
/** a caption's showings: one line of text, from its first frame to its last (the same line in frames side by side), and
* how far down the frame its middle is (a share of the frame's height) */
export type Shown = { text: string; key: string; from: number; to: number; y: number }
/** a frame's lines, and the frame's height */
export type Frame = { h: number; lines: Read[] }
/** lines whose middles are this close (a share of the frame's height) are the same line in the next frame */
const ROW = 0.03
/** a showing longer than this (s) is a title, a badge or a card, not a caption */
const HELD = 4.5
/** a caption fits what's said while it's up with at most this share of its letters edited; a line in capitals (a
* badge's style: "BODY BUTTER · UP TO 96 HOURS" over "Body Butter delivers up to 96 hours") with at most CAPS_FIT */
const FIT = 0.45
const CAPS_FIT = 0.3
/** captions are a track: up for at least this share of what's said, else the cut has none (hook text alone) */
const TRACK = 0.4
const CARDS = 8
/** more lines than this in a frame is a screen or a card */
const BUSY = 3
/** words a transcriber often leaves out of what it hears (so a caption that has them may be right) */
const SOFT = new Set(["yeah", "yes", "okay", "like", "wow", "hey", "right", "sorry", "well"])
/** words this close are one line (s) */
const LINE = 0.7
/** the frames' captions. First every line, the same line in consecutive frames joined into one showing (a line the
* reader garbled a little in one frame still joins its neighbours); then the showings that are captions: short, and
* fitting what's said while they're up with few edits. A badge, an app's screen, a sign or an end card stays up or
* says something else. With captions up for under TRACK of the speech, the cut has none to hold */
export function captionsOf(frames: Frame[], rate: number, heard: Word[]): Shown[] {
const all: (Shown & { caps: boolean })[] = []
frames.forEach((fr, i) => {
const t = i / rate
// a frame full of text is a screen or a card (an app, an end card, a product's label), not a caption over the picture
if (fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4).length > BUSY) return
for (const [, y, , h, text, score] of fr.lines) {
const key = letters(text)
if (score < LEAST || key.length < 4) continue
const mid = (y + h / 2) / Math.max(1, fr.h)
const last = all.findLast((s) => s.to >= t - 1.01 / rate && Math.abs(s.y - mid) <= ROW && similar(s.key, key))
if (last) {
last.to = t + 1 / rate
// the longest reading of the line is kept (a frame mid-fade reads part of it)
if (key.length > last.key.length) Object.assign(last, { text, key })
} else all.push({ text, key, from: t, to: t + 1 / rate, y: mid, caps: false })
}
})
const caps = (t: string) => /[A-Z]/.test(t) && !/[a-z]/.test(t)
const fitted = all.filter((s) => {
if (s.to - s.from > HELD) return false
const said = heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join("")
return fit(s.key, said).dist / s.key.length <= (caps(s.text) ? CAPS_FIT : FIT)
}).map(({ caps: _, ...s }) => s)
// kept to caption rows: where three captions or more sit (a label beside a product, a sign, sits on its own)
const rowed = fitted.filter((s) => fitted.filter((o) => Math.abs(o.y - s.y) <= ROW).length >= 3)
const talk = heard.filter((w) => !FILLER.has(letters(w.text)))
const out = rowed
const up = talk.filter((w) => out.some((s) => w.end >= s.from - 0.3 && w.start <= s.to + 0.3)).length
// and a sequence: captions come one after another (CARDS showings at least, each starting apart), where hook text
// that echoes the host is one card of a few lines at once
const starts = [...new Set(out.map((s) => Math.round(s.from * 2)))].sort((a, b) => a - b)
const cards = starts.filter((x, i) => i === 0 || x - starts[i - 1] >= 1).length
if (!talk.length || up / talk.length < TRACK || cards < CARDS) return []
return out.sort((a, b) => a.from - b.from)
}
export const similar = (a: string, b: string) => {
const [s, l] = a.length <= b.length ? [a, b] : [b, a]
return fit(s, l).dist / Math.max(1, s.length) <= 0.25 && s.length / l.length >= 0.6
}
/** letters [i, j) of a line's key are a whole word of the line as read (its spaces kept) */
function wholeWord(text: string, key: string, i: number, j: number): boolean {
let k = 0
for (const w of text.split(/\s+/)) {
const lw = letters(w)
if (k === i && k + lw.length === j) return true
k += lw.length
}
return false
}
/** the captions held to what's heard: letters shown that weren't said, and words said that no caption up then shows */
export function compare(shown: Shown[], heard: Word[]): Finding[] {
if (!shown.length) return []
const out: Finding[] = []
// shown, not said: a run of three letters or more in a caption that the stretch of speech it fits doesn't have
for (const s of shown) {
const f = fit(s.key, heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join(""))
for (let i = 0; i < f.bad.length; ) {
if (!f.bad[i]) { i++; continue }
let j = i
while (j < f.bad.length && f.bad[j]) j++
if (j - i >= 3) out.push({ level: (j - i >= 5 || wholeWord(s.text, s.key, i, j)) && !SOFT.has(s.key.slice(i, j)) ? "error" : "warn", kind: "shown", at: s.from, says: `the caption "${s.text}" at ${s.from.toFixed(1)} s shows "${s.key.slice(i, j)}", which isn't said there: a caption is the speaker's exact words, built from the words file, never retyped` })
i = j
}
}
// said, not shown: a heard word while a caption is up whose letters none of the captions up around it holds
const dropped: { w: Word; k: number }[] = []
heard.forEach((w, k) => {
const key = letters(w.text)
if (!key || FILLER.has(key)) return
const up = shown.filter((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3)
if (!up.length) return
const near = shown.filter((s) => w.end >= s.from - 2 && w.start <= s.to + 1.5).map((s) => s.key).join("")
const allowed = key.length >= 5 ? 1 : 0
if (fit(key, near).dist > allowed) dropped.push({ w, k })
})
// read two frames a second, a caption up for under a second can be missed between frames: words dropped are held as
// errors only where the captions are phrases (up a second or more, typically), and only three or more in a row
const lasts = shown.map((x) => x.to - x.from).sort((x, y) => x - y)
const phrases = lasts[Math.floor(lasts.length / 2)] >= 1
// a run inside captioned speech (the words either side of it are shown, within a line of it) is words a caption
// left out: an error. A run at a line's edge is a line left uncaptioned, which an editor may mean (the CTA under its
// badges): a warning
const lost = new Set(dropped.map((d) => d.k))
const shownAt = (k: number) => k >= 0 && k < heard.length && !lost.has(k) && shown.some((s) => heard[k].end >= s.from - 0.6 && heard[k].start <= s.to + 0.3)
for (let i = 0; i < dropped.length; ) {
let j = i + 1
while (j < dropped.length && dropped[j].k === dropped[j - 1].k + 1) j++
const run = dropped.slice(i, j).map((d) => d.w)
const a = dropped[i].k - 1
const b = dropped[j - 1].k + 1
const inside = phrases && run.length >= 3 && shownAt(a) && shownAt(b) && run[0].start - heard[a].end < LINE && heard[b].start - run[run.length - 1].end < LINE
const words = run.map((w) => w.text).join(" ")
out.push(inside
? { level: "error", kind: "dropped", at: run[0].start, says: `"${words}" is said at ${run[0].start.toFixed(1)} s, between words the captions show, but no caption shows ${run.length > 1 ? "them" : "it"}: build the captions from the words file so they say every word` }
: { level: "warn", kind: "dropped", at: run[0].start, says: `"${words}" at ${run[0].start.toFixed(1)} s has no caption while the captions around it run: caption it from the words file, unless it's meant to go uncaptioned` })
i = j
}
return out.sort((a, b) => a.at - b.at)
}
export default check<FileFacts>(
{ id: "captions", text: "every caption on screen says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const heard = await f.words()
if (!heard.length) return
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
const shown = captionsOf(frames, sc.rate || 2, heard)
for (const x of compare(shown, heard)) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+82
View File
@@ -0,0 +1,82 @@
// The hook and air-gap packs (11-30, Shane), on the export's own words and levels.
//
// hook: the first seconds have sound and picture working together. Elfster's Voted cut opened on 1.5 s of whiteboard
// with nothing said (-27 dB): "a whiteboard people will read as the hook ... that's not a hook, a hook really should
// have audio and video stimulation". The first word later than LEAD_ERROR into the cut, with nothing loud under the
// opening either, is an error; later than LEAD_WARN, a warning. Sound alone (a hit, a song's first beat) under a
// wordless opening is a warning, to be decided, not an error.
// airgaps: the silences between words. "Measuring and cutting air gaps ... especially in a hook ... for social media
// content or ads, especially if it is at all trying to look organic." In the hook's first HOOK seconds a gap over
// HOOK_ERROR is an error and over HOOK_WARN a warning; later, one over BODY_WARN is a warning. The fix is raea's
// tighten() (@raea/video airgaps), which cuts only between words and never into one.
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { airGaps } from "../../../video/src/airgaps.ts"
/** the first word this late (s): an error with a quiet opening, a warning */
export const LEAD_ERROR = 1.0
export const LEAD_WARN = 0.5
/** the opening counts as carrying sound when its loud end is within this of the speech's (dB) */
const OPENING_LOUD = 10
/** the hook's seconds, and the gaps held in them (s) */
export const HOOK = 3
export const HOOK_ERROR = 0.5
export const HOOK_WARN = 0.3
/** a gap this long after the hook (s): a warning */
export const BODY_WARN = 0.8
const pct = (xs: number[], q: number) => {
if (!xs.length) return -100
const s = [...xs].sort((a, b) => a - b)
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
}
export type HookFinding = { level: "error" | "warn"; at: number; says: string }
/** the opening and the gaps, from the words heard and the levels every 10 ms */
export function hookAndGaps(words: { text: string; start: number; end: number }[], db: number[]): { hook: HookFinding[]; gaps: HookFinding[] } {
const hook: HookFinding[] = []
const gaps: HookFinding[] = []
if (words.length < 3) return { hook, gaps }
const first = words[0].start
const speech = pct(words.flatMap((w) => db.slice(Math.floor(w.start * 100), Math.ceil(w.end * 100))), 0.8)
const opening = pct(db.slice(0, Math.max(1, Math.floor(first * 100))), 0.8)
const loud = opening > speech - OPENING_LOUD
if (first > LEAD_WARN + 0.005) {
const level = first > LEAD_ERROR && !loud ? "error" : "warn"
hook.push({
level,
at: 0,
says: loud
? `the first word comes ${first.toFixed(1)} s in, over sound alone (${opening.toFixed(0)} dB against the speech's ${speech.toFixed(0)}): a hook has words and picture together from the first frame, so open on the first line unless the sound is the hook`
: `${first.toFixed(1)} s of dead air before the first word ("${words[0].text}"), the opening ${(speech - opening).toFixed(0)} dB under the speech: a hook has sound and picture working together from the first frame. Open on the first line (cut the silent lead-in, or have the line land over the opening shot); a sign or a board people are meant to read is not a hook`,
})
}
for (const g of airGaps(words.map((w) => ({ text: w.text, start: w.start, end: w.end })), HOOK)) {
if (g.from === 0) continue // the lead-in is the hook pack's
const inHook = g.from < HOOK
const over = (x: number) => g.seconds > x + 0.005 // a transcript's times land on 10 ms steps
const level = inHook ? (over(HOOK_ERROR) ? "error" : over(HOOK_WARN) ? "warn" : null) : over(BODY_WARN) ? "warn" : null
if (!level) continue
gaps.push({ level, at: g.from, says: `${g.seconds.toFixed(2)} s of air between "${g.after}" and "${g.before}" at ${g.from.toFixed(1)} s${inHook ? " in the hook" : ""}: tighten it to about ${inHook ? 0.15 : 0.25} s with tighten() (raea's air-gap cut: between words only, never into one), unless the pause is the beat` })
}
return { hook, gaps }
}
export const hookPack = check<FileFacts>(
{ id: "hook", text: "the hook opens on words and picture together, no dead air", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const heard = await f.words()
for (const x of hookAndGaps(heard, f.levels().db).hook) found({ level: x.level, says: x.says, seconds: x.at })
},
)
export const airgapsPack = check<FileFacts>(
{ id: "airgaps", text: "no air between words: tight in the hook, no long pause after", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const heard = await f.words()
for (const x of hookAndGaps(heard, f.levels().db).gaps) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+11 -2
View File
@@ -1,6 +1,7 @@
// raea's packs by name (contract.ts PACKS says what each holds a job to).
import type { Check } from "raea/check"
import type { PackName } from "../contract.ts"
import captions from "./captions.ts"
import { countPack, ctaPack, neverPack, openPack, quotesPack, sayOncePack, sayPack, shapePack } from "./cut.ts"
import { floorPack, stillsPack } from "./floor.ts"
import frames from "./frames.ts"
@@ -10,13 +11,21 @@ import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts"
import { seenPack, surprisePack } from "./look.ts"
import naming from "./naming.ts"
import place from "./place.ts"
import sizes from "./sizes.ts"
import sizes, { allSizes } from "./sizes.ts"
import sound from "./sound.ts"
import reading from "./reading.ts"
import { airgapsPack, hookPack } from "./hook.ts"
import voice from "./voice.ts"
import words from "./words.ts"
/** each pack's checks (say holds each cut, and the phrases one cut is enough for across them) */
export const PACK_CHECKS: Record<PackName, Check[]> = {
words: [words],
captions: [captions],
voice: [voice],
reading: [reading],
hook: [hookPack],
airgaps: [airgapsPack],
sound: [sound],
frames: [frames],
montage: [montage],
@@ -24,7 +33,7 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
seen: [seenPack],
surprise: [surprisePack],
naming: [naming],
sizes: [sizes],
sizes: [sizes, allSizes],
quotes: [quotesPack],
count: [countPack],
open: [openPack],
+3 -1
View File
@@ -18,7 +18,9 @@ import type { FileFacts } from "../facts.ts"
import { RATE } from "../media.ts"
/** a frame's scene, as the farm reads it (deploy/modal/farm_scene.py), in the pixels of the frame it was sent */
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[] } | null
/** the scene reader's reading of a frame's text: [x, y, w, h, text, score] a line (the captions pack) */
export type TextLine = [number, number, number, number, string, number]
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[]; texts?: TextLine[] } | null
/** [x, y, w, h, label, score] */
export type Thing = [number, number, number, number, string, number]
/** a box in shares of the frame: x, y, w, h */
+120
View File
@@ -0,0 +1,120 @@
// The reading pack (11-30, Shane: "the words on screen relative to duration ... if a wordy CTA or component or scene is
// meant to be fully read or if it just adds glossable content or context, and if it's on screen long enough to be
// read"). From the scene reader's text (the farm's texts, two frames a second), every block of text that isn't a
// caption (captions are read while they're heard: the captions pack holds them) is timed against the words it holds.
//
// time to read: READ_BASE s to find it, then WPS words a second (a feed viewer's skim of short ad text; subtitle
// standards sit near 3 words a second). A block up for under its time is a warning; under SHORT of it an error,
// unless it holds GLOSS words or more: a screen, fine print or a dense card can't be read in an ad anyway, so it's
// texture, and the finding asks which it is meant to be.
// the measure: every finding says words, seconds and words a second, so a CTA's reading load is a number the
// editor holds (and the skill's end card rule: few words, held long enough).
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
export type Block = { text: string; words: number; from: number; to: number; size?: number }
export type Finding = { level: "error" | "warn"; at: number; says: string; block: Block }
/** seconds to find a block before reading it */
export const READ_BASE = 0.5
/** words read a second */
export const WPS = 3
/** under this share of its time to read, an error */
export const SHORT = 0.6
/** a block of this many words or more is texture unless the editor means it read */
export const GLOSS = 25
/** fewer words than this is a logo, a label or a button, read at a glance */
const FEW = 4
const wordsIn = (t: string) => t.split(/\s+/).filter((w) => letters(w).length > 0).length
/** the time a block of `words` needs on screen */
export const need = (words: number) => READ_BASE + words / WPS
/** a frame with more lines read than this is a screen, a shelf or a page (an app shot whole, a product line-up's
* labels): texture by nature, left out */
export const SCREEN = 6
/** lines whose middles are this close (a share of the frame's height) in consecutive frames are one line */
const ROW = 0.03
/** lines that come up within this of each other (s), up together, are one block */
const TOGETHER = 0.6
/** a line that fits what's said around it with at most this share of its letters edited is read with the voice */
const SAID = 0.35
/** a phone's status bar clock: the block is an app's screen, shown, not read */
/** text this small (its lines' median height, a share of the frame's) is an app's screen or fine print, not a
* designed line: 1080x1920's 54 px */
const SMALL = 0.028
const CLOCK = /\d{1,2}:\d{2}/
/** the frames' blocks of text. Each line that isn't a caption is followed from frame to frame (same row, same text,
* its fullest reading kept: text building on, or a frame mid-fade); lines that come up together and overlap are one
* block, read as one. Frames that are screens are left out */
export function blocksOf(frames: Frame[], rate: number, isCaption: (t: number, key: string) => boolean, heard: Word[] = []): Block[] {
type Line = { text: string; key: string; from: number; to: number; y: number; size: number }
const lines: Line[] = []
frames.forEach((fr, i) => {
const t = i / rate
const read = fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 2)
if (read.length > SCREEN) return
for (const [, y, , h, text] of read) {
const key = letters(text)
if (isCaption(t, key)) continue
// words shown as they're said (kinetic type, a caption the captions pack didn't take as one) are read with the voice
const said = heard.filter((w) => w.end >= t - 1.5 && w.start <= t + 2.5).map((w) => letters(w.text)).join("")
if (key.length >= 4 && fit(key, said).dist / key.length <= SAID) continue
const mid = (y + h / 2) / Math.max(1, fr.h)
const last = lines.findLast((l) => l.to >= t - 1.01 / rate && Math.abs(l.y - mid) <= ROW && (similar(l.key, key) || l.key.includes(key) || key.includes(l.key)))
if (last) {
last.to = t + 1 / rate
if (key.length > last.key.length) Object.assign(last, { text, key })
} else lines.push({ text, key, from: t, to: t + 1 / rate, y: mid, size: h / Math.max(1, fr.h) })
}
})
const blocks: (Block & { parts: Line[] })[] = []
for (const l of [...lines].sort((a, b) => a.from - b.from || a.y - b.y)) {
const b = blocks.find((x) => Math.abs(x.from - l.from) <= TOGETHER && l.from < x.to)
if (b) {
b.parts.push(l)
b.to = Math.max(b.to, l.to)
} else blocks.push({ text: "", words: 0, from: l.from, to: l.to, parts: [l] })
}
return blocks.map(({ parts, ...b }) => {
const text = parts.sort((x, y) => x.y - y.y).map((x) => x.text).join(" ")
// a block is read for as long as most of it is up: its lines' median time up
const ups = parts.map((x) => x.to - x.from).sort((x, y) => x - y)
const sizes = parts.map((x) => x.size).sort((x, y) => x - y)
return { ...b, text, words: wordsIn(text), to: b.from + ups[Math.floor(ups.length / 2)], size: sizes[Math.floor(sizes.length / 2)] }
})
}
/** blocks up for less time than their words take to read */
export function reading(blocks: Block[]): Finding[] {
const out: Finding[] = []
for (const b of blocks) {
if (b.words < FEW) continue
const up = b.to - b.from
const n = need(b.words)
if (up >= n) continue
const quote = b.text.length > 70 ? `${b.text.slice(0, 67)}...` : b.text
const load = `${b.words} words up ${up.toFixed(1)} s (${(b.words / up).toFixed(1)} words a second; reading takes about ${n.toFixed(1)} s at ${WPS} a second)`
if (b.words >= GLOSS || CLOCK.test(b.text) || (b.size !== undefined && b.size < SMALL)) out.push({ level: "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. That's texture, not reading (a screen, a page, fine print): fine if it's shown for context, but if a viewer is meant to read it, cut it to the words that matter and hold them ${need(Math.min(b.words, 8)).toFixed(1)} s or more` })
else out.push({ level: up < n * SHORT ? "error" : "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. Hold it ${(n - up).toFixed(1)} s longer, or say it in fewer words` })
}
return out
}
export default check<FileFacts>(
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((x) => x.lines.length)) return
const rate = sc.rate || 2
const heard = await f.words()
const caps = captionsOf(frames, rate, heard)
const isCaption = (t: number, key: string) => caps.some((c) => t >= c.from - 0.01 && t < c.to && (similar(c.key, key) || c.key.includes(key)))
for (const x of reading(blocksOf(frames, rate, isCaption, heard))) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+38 -1
View File
@@ -3,9 +3,13 @@
// (11-28, Shane: "always does all concepts first in one size or aspect ratio ... and then once approved we can then do
// any other resizes ... generally lean toward 9:16 first"). The approval is the brief's `open` item about "sizes",
// answered by the person (`by`).
// And every size by the end (11-30, Shane: "it will show completed but what about doing all the resizes"): Dutch
// finished on its 9:16 masters alone, the brief's 4:5, 1:1 and 16:9 never made. At done, every ad's newest version is
// there in every format its brief names (brief.ts cut `formats`), unless a person's answer to the open item about "sizes"
// says fewer.
import { check, found } from "raea/check"
import type { Job } from "../facts.ts"
import { bookkeeping, sizeOf } from "./naming.ts"
import { adOf, bookkeeping, sizeOf } from "./naming.ts"
export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => {
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
@@ -24,3 +28,36 @@ export default check<Job>({ id: "sizes", text: "one size first: no other size be
fix: `finish and show every ad in ${first[0]} first; recut the other sizes from the approved version once a person answers the brief's open item about "sizes" (with \`by\`)`,
})
})
/** a format as a name's size: "9:16" is 9x16 */
const asSize = (f: string) => f.replace(":", "x").toLowerCase()
/** a version's number in a name (v3), else 0 */
const versionOf = (name: string) => Number(/_v(\d+)(?=_|\.|$)/i.exec(name)?.[1] ?? 0)
export const allSizes = check<Job>({ id: "sizes-all", text: "every size the brief asks for, by the end", over: "job", at: ["done"] }, async (j) => {
if (j.contract?.kind !== "cut") return
const c = j.contract.cut
const want = [...new Set([...(c?.formats ?? []), ...(c?.cuts ?? []).flatMap((p) => p.formats ?? [])].map(asSize))]
if (want.length < 2) return
const sizesItem = (c?.open ?? []).find((o) => o.about === "sizes" && o.answer?.trim() && o.by?.trim())
// a person said which sizes (or that one is enough): only the sizes their answer names
const wanted = sizesItem ? want.filter((s) => new RegExp(s.replace("x", "[:x]"), "i").test(sizesItem.answer ?? "")) : want
if (wanted.length < 2) return
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image") && sizeOf(f.path))
// each ad at its newest version, and the sizes that version is in
const ads = new Map<string, { v: number; sizes: Set<string> }>()
for (const f of made) {
const ad = adOf(f.path), v = versionOf(f.path), s = sizeOf(f.path)!
const cur = ads.get(ad)
if (!cur || v > cur.v) ads.set(ad, { v, sizes: new Set([s]) })
else if (v === cur.v) cur.sizes.add(s)
}
for (const [ad, { v, sizes }] of ads) {
const missing = wanted.filter((s) => !sizes.has(s))
if (!missing.length) continue
found({
says: `${ad} v${v} is in ${[...sizes].join(", ")} but the brief asks for ${wanted.join(", ")}: ${missing.join(", ")} not made`,
fix: `recut ${ad} v${v} in ${missing.join(", ")} from the approved version (same version, a new size: ${ad}_v${v}_${missing[0]}), check each, and deliver them before you finish; a person's answer to the brief's open item about "sizes" is the only way to deliver fewer`,
})
}
})
+17 -3
View File
@@ -36,13 +36,26 @@ const LEVEL_WARN = 4
const SFX_UNDER = 10
/** music: further under than this isn't heard, closer than this fights the words */
const MUSIC_LOST = 26
const MUSIC_FIGHTS = 6
const MUSIC_FIGHTS = 10
export type Finding = { level: "error" | "warn"; kind: "edit-in-word" | "edit-on-sound" | "level" | "effect-unheard" | "music" | "manifest"; at: number | null; says: string }
const MUSIC = /music|bed|score/i
const SFX = /sfx|fx|effect|foley|sting/i
export const busOf = (c: Clip): "voice" | "music" | "sfx" => (c.bus && MUSIC.test(c.bus) ? "music" : c.bus && SFX.test(c.bus) ? "sfx" : c.bus === "voice" || !c.bus ? (SFX.test(path.basename(c.src)) ? "sfx" : MUSIC.test(path.basename(c.src)) ? "music" : "voice") : "voice")
/** a sound with no bus, as raea's default mix routes it (systems/mix default_bus, 11-30): footage and voice files are the
* talking, effects stay effects, any other audio file is the music, ducked DEFAULT_DUCK under the talking */
const VIDEO_EXT = /\.(mp4|mov|m4v|webm|mkv|avi|mxf)$/i
const VOICE_NAME = /voice|narrat|dialog|speech|_vo|vo_|-vo|vo-|interview/i
const SFX_NAME = /sfx|foley|whoosh|swoosh|sting|riser|impact|click|_fx|fx_/i
export const busOf = (c: Clip): "voice" | "music" | "sfx" => {
if (c.bus) return MUSIC.test(c.bus) ? "music" : SFX.test(c.bus) ? "sfx" : "voice"
const name = path.basename(c.src)
if (VIDEO_EXT.test(name) || VOICE_NAME.test(name)) return "voice"
if (SFX_NAME.test(name) || SFX.test(name)) return "sfx"
return "music"
}
/** how far raea's default mix ducks a music file with no bus under the talking (dB, systems/mix DEFAULT_DUCK_DB) */
export const DEFAULT_DUCK = -6
const pct = (xs: number[], q: number) => {
if (!xs.length) return -100
@@ -165,7 +178,8 @@ export function balance(heard: Heard[], fps: number): Finding[] {
out.push({ level: "error", kind: "effect-unheard", at: h.clip.from / fps, says: `the effect at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)}) peaks ${(-d).toFixed(0)} dB under the voice: no one hears it. Set its gainDb to about ${((h.clip.gainDb ?? 0) - d - 4).toFixed(1)} (4 dB under the voice), or cut it` })
}
for (const h of heard.filter((x) => x.kind === "music")) {
const d = h.level - mid
// a music file on no bus is ducked under the talking by the default mix, so it's heard that much lower
const d = h.level - mid + (h.clip.bus ? 0 : DEFAULT_DUCK)
if (d < -MUSIC_LOST) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) sits ${(-d).toFixed(0)} dB under the voice: it's barely there. A bed under speech sits 12 to 20 dB under: gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
else if (d > -MUSIC_FIGHTS) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) is within ${MUSIC_FIGHTS} dB of the voice: it fights the words. gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
}
+96
View File
@@ -0,0 +1,96 @@
// The voice pack (11-30, Shane: "we should be checking audio if its too quiet for dialogue or what is supposed to be
// primary"): whether the dialogue is on top in the export as it was mixed, measured on the export itself. The sound pack
// levels each line from its source take and the edit's gains, before the mix: ducking, the limiter and the loudness pass
// all come after it, and a line that's even in the edit can sink in the mix.
//
// on top: the speech (the words pass's words, every 10 ms inside them) against what's under it in the gaps between
// words while people are talking (music, effects, the street): under 6 dB above it is an error (the bed is as loud
// as the voice), under 10 dB a warning.
// even: each line (words with less than 0.7 s between them) against the export's typical line: 6 dB or more quieter
// is an error (a line too quiet to follow that a transcriber still hears), 4 dB a warning.
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
export type Finding = { level: "error" | "warn"; kind: "buried" | "quiet"; at: number; says: string }
/** the speech's level over what's under it (dB): under ON_TOP_ERROR an error, under ON_TOP_WARN a warning */
export const ON_TOP_ERROR = 6
export const ON_TOP_WARN = 10
/** a line this far under the typical line (dB) */
export const QUIET_ERROR = 6
export const QUIET_WARN = 4
/** words this close together are one line (s) */
const LINE_GAP = 0.7
/** a gap between words counts as the bed from this far after a word to this far before the next (s): the word's tail
* and breath are left out */
const CLEAR = 0.12
/** a gap shorter than this is too short to read the bed in (s) */
const GAP_MIN = 0.2
/** the bed is judged only on this many gaps between words, this many 10 ms frames of them in all */
const BED_GAPS = 3
const BED_FRAMES = 100
/** the level a span is read at: its loud end (this percentile of its 10 ms frames), so pauses inside words don't count */
const Q = 0.8
const pct = (xs: number[], q: number) => {
if (!xs.length) return -100
const s = [...xs].sort((a, b) => a - b)
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
}
const frames = (db: number[], a: number, b: number) => db.slice(Math.max(0, Math.floor(a * 100)), Math.min(db.length, Math.ceil(b * 100)))
/** the lines: words with under LINE_GAP between them */
export function linesOf(heard: Word[]): Word[][] {
const out: Word[][] = []
for (const w of heard) {
const last = out[out.length - 1]
if (last && w.start - last[last.length - 1].end < LINE_GAP) last.push(w)
else out.push([w])
}
return out
}
/** the speech against the bed under it, and each line against the typical line */
export function voice(db: number[], heard: Word[]): Finding[] {
if (heard.length < 4) return []
const out: Finding[] = []
const speech: number[] = []
for (const w of heard) speech.push(...frames(db, w.start, w.end))
const bed: number[] = []
let gaps = 0
const lines = linesOf(heard)
// the gaps inside lines and between lines close together: what's under the talking, not the end card's music
for (let k = 1; k < heard.length; k++) {
const a = heard[k - 1].end + CLEAR
const b = heard[k].start - CLEAR
if (b - a >= GAP_MIN && b - a < 2.5) { bed.push(...frames(db, a, b)); gaps++ }
}
const S = pct(speech, Q)
// enough of the bed to judge: a tightly cut take has few gaps, and one of them is often still a hum or a breath
// (11-30: Body Shop's host hook read 1.5 dB off a single 0.34 s gap between two "Mmm"s)
if (gaps >= BED_GAPS && bed.length >= BED_FRAMES) {
const B = pct(bed, Q)
const over = S - B
if (over < ON_TOP_WARN) out.push({ level: over < ON_TOP_ERROR ? "error" : "warn", kind: "buried", at: heard[0].start, says: `the dialogue is only ${over.toFixed(1)} dB above what's under it between words (music, effects, the street): it should be ${ON_TOP_WARN} dB or more on top. Duck the music further under the voice, or lift the voice` })
}
const lv = lines.map((l) => ({ l, db: pct(frames(db, l[0].start, l[l.length - 1].end), Q) }))
const typical = pct(lv.map((x) => x.db), 0.5)
for (const { l, db: d } of lv) {
const under = typical - d
if (under < QUIET_WARN || l.length < 2) continue
const text = l.map((w) => w.text).join(" ")
out.push({ level: under >= QUIET_ERROR ? "error" : "warn", kind: "quiet", at: l[0].start, says: `"${text.length > 60 ? `${text.slice(0, 57)}...` : text}" at ${l[0].start.toFixed(1)} s is ${under.toFixed(1)} dB quieter than the other lines: lift it about ${under.toFixed(0)} dB so it's heard like the rest` })
}
return out.sort((a, b) => a.at - b.at)
}
export default check<FileFacts>(
{ id: "voice", text: "the dialogue on top of the mix in the export, every line as loud as the others", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
if (!f.made || (f.kind !== "video" && f.kind !== "audio")) return
const heard = await f.words()
if (!heard.length) return
for (const x of voice(f.levels().db, heard)) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+72
View File
@@ -0,0 +1,72 @@
import { expect, test } from "bun:test"
import { captionsOf, compare, fit, letters } from "../src/packs/captions.ts"
import { voice } from "../src/packs/voice.ts"
// what the reader saw, two frames a second: phrase captions in one row (y 120 of 960), as Elfster's cut 1 had them
const w = (text: string, start: number, end: number) => ({ text, start, end })
const said = "Everyone has a fake I love it face when they get a bad gift. How bad is yours? Thanks. Oh my, like how did you know? Now I know for sure, okay, this is what they wanted, and everyone's happy."
.split(" ").map((t, i) => w(t, 0.2 + i * 0.3, 0.45 + i * 0.3))
const at = (t: number) => said.find((x) => x.start <= t && x.end >= t)
const shownLines: [number, number, string][] = [
[0.1, 1.4, "Everyone has a fake"], [1.4, 2.6, "'I love it' face"], [2.6, 3.8, "for a bad gift."], [3.8, 5.0, "How bad is yours?"],
[5.0, 5.9, "Oh, thanks!"], [5.9, 7.1, "Oh my god,"], [7.1, 8.6, "like, how did you know?"], [8.6, 9.6, "Now I know for sure"],
[9.6, 11.4, "what they wanted,"], [11.4, 12.6, "and everyone's happy."],
]
const frames = Array.from({ length: 27 }, (_, i) => {
const t = i / 2
const l = shownLines.find(([a, b]) => t >= a && t < b)
return { h: 960, lines: l ? [[60, 110, 420, 26, l[2], 0.95] as [number, number, number, number, string, number]] : [] }
})
test("a caption is fitted to the stretch of speech it says", () => {
expect(fit("forabadgift", letters("when they get a bad gift")).dist).toBe(3)
// a badge in capitals that echoes the line ("BODY BUTTER · UP TO 96") is held to the stricter fit (0.3), and misses it
expect(fit("bodybutterupto96", letters("body butter delivers up to 96 hours")).dist / 16).toBeGreaterThan(0.3)
})
test("captions that change or drop words are found; the same words pass", () => {
void at
const shown = captionsOf(frames, 2, said)
expect(shown.length).toBeGreaterThanOrEqual(8)
const f = compare(shown, said)
// "for" stands in for "get", "god" was never said
expect(f.some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(true)
// "when they" (before "get"), and "okay, this is" between captioned words, are dropped
expect(f.some((x) => x.kind === "dropped" && x.level === "error" && x.says.includes("okay, this is"))).toBe(true)
// captions that say exactly what's said find nothing
const exact = said.reduce<[number, number, string][]>((a, x, i) => (i % 4 === 0 ? [...a, [x.start, said[Math.min(i + 3, said.length - 1)].end, said.slice(i, i + 4).map((y) => y.text).join(" ")]] : a), [])
const fr2 = Array.from({ length: 27 }, (_, i) => {
const t = i / 2
const l = exact.find(([a, b]) => t >= a && t < b)
return { h: 960, lines: l ? [[60, 110, 420, 26, l[2], 0.95] as [number, number, number, number, string, number]] : [] }
})
expect(compare(captionsOf(fr2, 2, said), said).filter((x) => x.level === "error")).toEqual([])
})
test("hook text alone isn't a caption track", () => {
const hook = Array.from({ length: 27 }, (_, i) => ({ h: 960, lines: i < 6 ? [[60, 110, 420, 26, "Everyone has a fake 'I love it' face", 0.95] as [number, number, number, number, string, number]] : [] }))
expect(captionsOf(hook, 2, said)).toEqual([])
})
test("the voice pack: dialogue on top of the mix, every line even", () => {
const words = Array.from({ length: 25 }, (_, i) => w("word", 0.2 + i * 0.8, 0.5 + i * 0.8))
// speech at -20 dB, the bed between words at -40: 20 dB on top, nothing found
const level = (bed: number, quietFrom = 99) => Array.from({ length: 2100 }, (_, f) => {
const t = f / 100
const inWord = words.some((x) => t >= x.start && t < x.end)
return inWord ? (t >= quietFrom ? -29 : -20) : bed
})
expect(voice(level(-40), words)).toEqual([])
// the bed at -24 between words: 4 dB on top, buried
expect(voice(level(-24), words).some((x) => x.kind === "buried" && x.level === "error")).toBe(true)
// a line 9 dB quieter than the rest (words 15 on are one line with no gap > 0.7 s: all of them here, so split a line)
const two = [...words.slice(0, 20), ...words.slice(20).map((x) => ({ ...x, start: x.start + 1, end: x.end + 1 }))]
const lv = Array.from({ length: 2300 }, (_, f) => {
const t = f / 100
const x = two.find((y) => t >= y.start && t < y.end)
return x ? (two.indexOf(x) >= 20 ? -29 : -20) : -45
})
const third = [...two, ...words.slice(0, 10).map((x) => ({ ...x, start: x.start + 23, end: x.end + 23 }))]
const lv3 = [...lv, ...Array.from({ length: 600 }, (_, f) => (third.slice(40).some((y) => (2300 + f) / 100 >= y.start && (2300 + f) / 100 < y.end) ? -20 : -45))]
expect(voice(lv3, third).some((x) => x.kind === "quiet" && x.level === "error")).toBe(true)
})
+1 -1
View File
@@ -17,7 +17,7 @@ test("a cut holds the craft by default, surprise only when asked", () => {
expect(packsOf(rules({ aim: "x", rules: [{ id: "t", run: "true" }, { id: "w", says: "it reads" }] }))).toEqual(["deliverables", "stills", "run", "says"])
expect(packsOf(cut({ cut: { brief: "b.txt" }, rules: [{ id: "t", run: "true" }] }))).toContain("run")
// no contract: the floor every made video is held to
expect(packsOf(null)).toEqual(["frames", "floor", "seen", "stills"])
expect(packsOf(null)).toEqual(["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"])
})
test("a project's own check runs at its moments", async () => {
+1 -1
View File
@@ -14,7 +14,7 @@ beforeAll(() => {
const BRIEF = 'Deliverables: 10 total videos (4 solos / 1 mashup per angle).\nUse the phrase "free, fun, and easy."\nDon\'t let it read as White Elephant.\nEnd on the CTA: "Make your Wishlist and organize your Gift Exchange on Elfster. It\'s free."\nCTV specs from the client [TO CONFIRM]\n'
const contract = (cut: Record<string, unknown> = {}) => ({
kind: "cut",
packs: { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, sizes: false },
packs: { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, sizes: false, hook: false, airgaps: false },
cut: {
brief: "media/brief.txt",
count: { value: 2, from: "10 total videos" },
+54
View File
@@ -0,0 +1,54 @@
// The hook and air-gap packs, and @raea/video's tighten() they point to (11-30, Shane): no dead air before the first
// word, tight gaps in the hook, and a cut that only ever lands between words.
import { expect, test } from "bun:test"
import { hookAndGaps } from "../src/packs/hook.ts"
import { airGaps, tighten } from "../../video/src/airgaps.ts"
const W = (spec: [string, number, number][]) => spec.map(([text, start, end]) => ({ text, start, end }))
/** levels every 10 ms: `on` dB inside the words, `off` between them */
const levels = (words: { start: number; end: number }[], secs: number, on = -18, off = -50) =>
Array.from({ length: Math.ceil(secs * 100) }, (_, i) => (words.some((w) => i / 100 >= w.start && i / 100 < w.end) ? on : off))
test("Voted's opening: 1.5 s of a silent whiteboard before the first word is dead air", () => {
const words = W([["Do", 1.54, 1.6], ["you", 1.6, 1.76], ["use", 1.76, 2.0], ["Elfster?", 2.0, 2.46]])
const { hook } = hookAndGaps(words, levels(words, 4))
expect(hook).toHaveLength(1)
expect(hook[0].level).toBe("error")
expect(hook[0].says).toMatch(/1\.5 s of dead air/)
})
test("a cut that talks from its first frame has no hook finding; sound under a late first word is only a warning", () => {
const now = W([["Every", 0.08, 0.3], ["friend", 0.3, 0.6], ["group", 0.6, 0.9]])
expect(hookAndGaps(now, levels(now, 2)).hook).toEqual([])
const late = W([["So", 1.2, 1.4], ["good", 1.4, 1.7], ["really", 1.7, 2.0]])
const db = levels(late, 3).map((d, i) => (i < 120 ? -20 : d)) // a song's first beat under the opening
expect(hookAndGaps(late, db).hook[0].level).toBe("warn")
})
test("gaps: tight in the hook, only long ones after it", () => {
const words = W([["I", 0.0, 0.2], ["use", 0.8, 1.0], ["it", 1.35, 1.5], ["every", 5.0, 5.3], ["Christmas", 6.5, 7.0], ["really", 7.3, 7.6]])
const { gaps } = hookAndGaps(words, levels(words, 8))
expect(gaps.map((g) => [g.level, +g.at.toFixed(1)])).toEqual([["error", 0.2], ["warn", 1.0], ["error", 1.5], ["warn", 5.3]])
})
test("tighten() cuts only between words, leaves a pad on each, and the lead-in down to a pad", () => {
const words = W([["Do", 1.54, 1.6], ["you", 1.6, 1.76], ["use", 1.76, 2.0], ["Elfster?", 2.0, 2.46], ["I", 3.4, 3.5], ["do", 3.5, 3.7]])
const { keep, cuts } = tighten(words)
expect(cuts[0]).toEqual({ from: 0, to: 1.46 })
// every word lies whole inside what's kept
for (const w of words) expect(keep.some((k) => k.from <= w.start - 0.079 && k.to >= w.end + 0.079 - 1e-9 || (k.from <= w.start && k.to >= w.end))).toBe(true)
// the 0.94 s gap after "Elfster?" (past the 3 s hook? no: it starts at 2.46) is left at the hook's 0.16 s
const left = airGaps(words).find((g) => g.after === "Elfster?")!
const taken = cuts.filter((c) => c.from >= left.from && c.to <= left.to).reduce((n, c) => n + c.to - c.from, 0)
expect(+(left.seconds - taken).toFixed(2)).toBe(0.16)
})
test("tighten() with levels never cuts where it's still loud: a word the transcript ended early stays whole", () => {
// "gifts" is heard to 2.3 s but the transcript ends it at 2.0
const words = W([["buy", 1.0, 1.4], ["gifts", 1.5, 2.0], ["now", 3.0, 3.3]])
const db = levels(W([["buy", 1.0, 1.4], ["gifts", 1.5, 2.3], ["now", 3.0, 3.3]]), 4)
const { cuts } = tighten(words, { levels: db, lead: false })
const c = cuts.find((x) => x.from > 2)!
expect(c.from).toBeGreaterThanOrEqual(2.3)
expect(c.to).toBeLessThanOrEqual(3.0)
})
+35
View File
@@ -0,0 +1,35 @@
import { expect, test } from "bun:test"
import { blocksOf, need, reading } from "../src/packs/reading.ts"
type L = [number, number, number, number, string, number]
const line = (y: number, text: string, h = 48): L => [60, y, 420, h, text, 0.95]
const frames = (n: number, at: (t: number) => L[]) => Array.from({ length: n }, (_, i) => ({ h: 960, lines: at(i / 2) }))
const none = () => false
test("time to read: half a second, then 3 words a second", () => {
expect(need(6)).toBeCloseTo(2.5)
})
test("a wordy card up for a second is an error; held long enough, it passes", () => {
const card = [line(300, "How does your group do"), line(360, "Secret Santa this year?"), line(420, "Names in a hat or chaos")]
const quick = blocksOf(frames(10, (t) => (t < 1 ? card : [])), 2, none)
expect(quick.length).toBe(1)
expect(quick[0].words).toBe(15)
expect(reading(quick)[0].level).toBe("error")
expect(reading(blocksOf(frames(16, (t) => (t < 6 ? card : [])), 2, none))).toEqual([])
})
test("a phone's screen and small print are texture: a warning that asks, never an error", () => {
const screen = [line(40, "12:59", 18), line(300, "Awesome, your exchange is created! Invite everyone", 18)]
const f = reading(blocksOf(frames(6, (t) => (t < 0.5 ? screen : [])), 2, none))
expect(f.length).toBe(1)
expect(f[0].level).toBe("warn")
expect(f[0].says).toContain("texture")
})
test("a frame full of lines (a shelf of labels) is left out, and words said as they show are read with the voice", () => {
const shelf = Array.from({ length: 9 }, (_, i) => line(100 + i * 80, `Body Butter Mango ${i}`))
expect(blocksOf(frames(4, () => shelf), 2, none)).toEqual([])
const heard = "so good I want to eat it".split(" ").map((t, i) => ({ text: t, start: 0.2 + i * 0.3, end: 0.45 + i * 0.3 }))
expect(blocksOf(frames(4, (t) => (t < 0.5 ? [line(300, "SO GOOD I WANT TO EAT IT")] : [])), 2, none, heard)).toEqual([])
})
+33
View File
@@ -0,0 +1,33 @@
// The sizes pack's end (11-30, Shane: "it will show completed but what about doing all the resizes"): at done, every ad's
// newest version in every format the brief names, unless a person's answer about "sizes" says fewer.
import { beforeAll, expect, test } from "bun:test"
import { goalCheck } from "../src/run.ts"
import { CLIP, project, put } from "./project.ts"
import { readFileSync } from "node:fs"
beforeAll(() => {
process.env.RAEA_REAL = "/usr/bin/false"
delete process.env.RAEA_CLOUD_GPU_URL
})
const off = { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, captions: false, voice: false, reading: false, montage: false, quotes: false, count: false, open: false, say: false, never: false, cta: false, shape: false }
const contract = (open: unknown[] = []) => ({ kind: "cut", packs: off, cut: { brief: "media/brief.txt", formats: ["9:16", "4:5", "1:1"], cuts: [{ id: "a1" }], open } })
const clip = readFileSync(CLIP)
const all = async (open: unknown[] = [], files: string[]) => {
const d = project(contract(open))
put(d, "media/brief.txt", "Deliver 9:16, 4:5 and 1:1.\n")
for (const f of files) put(d, f, clip)
const r = await goalCheck({ cwd: d, at: "done" })
return r.findings.filter((x) => /sizes/.test(x.check))
}
test("done on the first size alone: every other size the brief names is missing", async () => {
const f = await all([], ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4", "out/cuts/dutch_vetbill_hooka_v1_9x16.mp4"])
expect(f.some((x) => /v2 is in 9x16 .* 4x5, 1x1 not made/.test(x.says))).toBe(true)
})
test("every size of the newest version passes; a person's answer can say fewer", async () => {
const sizes = ["9x16", "4x5", "1x1"].map((s) => `out/cuts/dutch_vetbill_hooka_v2_${s}.mp4`)
const answered = [{ question: "Which sizes?", from: "Deliver 9:16, 4:5 and 1:1.", about: "sizes", answer: "9:16 only for now", by: "shane" }]
expect((await all(answered, sizes)).filter((x) => x.check === "sizes-all")).toEqual([])
expect((await all(answered, ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4"])).filter((x) => x.check === "sizes-all")).toEqual([])
})
+6 -3
View File
@@ -11,9 +11,12 @@ docs/components.md in the raea repository.
1. **List the components before writing any.** From the brief (and its story, and each hero's `NAME.parts.ts`), name
every thing the piece needs as a component: `Kitchen`, `Kettle`, `Steam`, `BrushedSteel`, `MorningLook`,
`PriceCard`. One component is one concern: one object, one surface, one effect, one card.
2. **Look before making.** `raea make component list` shows raea's own; a project's `components/` and the workspace's
`shared/components/` hold what this person already has; `raea library search "WORDS"` finds their assets. Interface
pieces (forms, tables, charts, dashboards) come from shadcn, never rebuilt: see "shadcn" below.
2. **Look before making.** `raea make component list` shows raea's own and the library's categories; `raea make
component list WORDS` searches the library by what a piece is for (`text/reveal`, `numbers/counter`, `transitions`,
`"count up"`): several hundred open-source text reveals, counters, charts, logo stings, HUDs and screen demos. A
project's `components/` and the workspace's `shared/components/` hold what this person already has; `raea library
search "WORDS"` finds their assets. Interface pieces (forms, tables, dashboards) come from shadcn, never rebuilt:
see "shadcn" below. A library piece arrives with its source's sample words, colours and fonts: pass the brief's.
3. **Add, then adapt.** `raea make component add NAME` copies a component into `components/` (`--shared` into the
workspace's `shared/components/`, imported as `@shared/components/NAME`). It's the project's own once copied: change
it freely. Nothing updates it behind your back.
+45
View File
@@ -0,0 +1,45 @@
# Credits
The components in this folder come from other people's open libraries, sorted here by what they're used for.
Each file's first line names its source; catalog.json's `from` does the same per component.
## React Video Editor's free templates
https://github.com/reactvideoeditor/remotion-templates. Its README: "All templates in this repository are available
under the MIT License. You can use them in personal and commercial projects, but attribution is appreciated where
applicable." (the repository has no LICENSE file of its own). Created by the team at https://www.reactvideoeditor.com.
Changed for raea: imports, and the header comment replaced by this credit.
## snapcn
https://github.com/shadcn-labs/snapcn, MIT, Copyright (c) 2026 Sri Nath (snap-cn). Changed for raea: imports, fonts
(raea/text's loadFont), Remotion's getRemotionEnvironment replaced by a stand-in (_lib/snapcn/lib/raea-env.ts), and
shadcn's cn by a plain join (_lib/snapcn/lib/utils.ts). Some need npm packages (culori), which `raea make component add`
installs.
## remocn
https://github.com/Remocn/remocn, MIT. Changed for raea: imports (raea's own names for the frame, the
clock and the layout pieces), fonts (raea/text's loadFont), and one glyph helper replaced by a no-op.
MIT License
Copyright (c) 2026 Remocn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Afacad";
export const loadFont = (..._: unknown[]) => ({ ...load("Afacad"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Albert Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("Albert Sans"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Anton";
export const loadFont = (..._: unknown[]) => ({ ...load("Anton"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Antonio";
export const loadFont = (..._: unknown[]) => ({ ...load("Antonio"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Archivo";
export const loadFont = (..._: unknown[]) => ({ ...load("Archivo"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Archivo Narrow";
export const loadFont = (..._: unknown[]) => ({ ...load("Archivo Narrow"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Arimo";
export const loadFont = (..._: unknown[]) => ({ ...load("Arimo"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Azeret Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("Azeret Mono"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Barlow Condensed";
export const loadFont = (..._: unknown[]) => ({ ...load("Barlow Condensed"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Big Shoulders";
export const loadFont = (..._: unknown[]) => ({ ...load("Big Shoulders"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Bitter";
export const loadFont = (..._: unknown[]) => ({ ...load("Bitter"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Bricolage Grotesque";
export const loadFont = (..._: unknown[]) => ({ ...load("Bricolage Grotesque"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Caveat";
export const loadFont = (..._: unknown[]) => ({ ...load("Caveat"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Chakra Petch";
export const loadFont = (..._: unknown[]) => ({ ...load("Chakra Petch"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "DMSans";
export const loadFont = (..._: unknown[]) => ({ ...load("DMSans"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Epilogue";
export const loadFont = (..._: unknown[]) => ({ ...load("Epilogue"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Familjen Grotesk";
export const loadFont = (..._: unknown[]) => ({ ...load("Familjen Grotesk"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Figtree";
export const loadFont = (..._: unknown[]) => ({ ...load("Figtree"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Fraunces";
export const loadFont = (..._: unknown[]) => ({ ...load("Fraunces"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Fredoka";
export const loadFont = (..._: unknown[]) => ({ ...load("Fredoka"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Funnel Display";
export const loadFont = (..._: unknown[]) => ({ ...load("Funnel Display"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Gabarito";
export const loadFont = (..._: unknown[]) => ({ ...load("Gabarito"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Geist";
export const loadFont = (..._: unknown[]) => ({ ...load("Geist"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Geist Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("Geist Mono"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Geologica";
export const loadFont = (..._: unknown[]) => ({ ...load("Geologica"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Gloock";
export const loadFont = (..._: unknown[]) => ({ ...load("Gloock"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Golos Text";
export const loadFont = (..._: unknown[]) => ({ ...load("Golos Text"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Hanken Grotesk";
export const loadFont = (..._: unknown[]) => ({ ...load("Hanken Grotesk"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Hubot Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("Hubot Sans"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "IBMPlex Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("IBMPlex Mono"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "IBMPlex Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("IBMPlex Sans"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Instrument Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("Instrument Sans"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Instrument Serif";
export const loadFont = (..._: unknown[]) => ({ ...load("Instrument Serif"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Inter";
export const loadFont = (..._: unknown[]) => ({ ...load("Inter"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Inter Tight";
export const loadFont = (..._: unknown[]) => ({ ...load("Inter Tight"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Jet Brains Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("Jet Brains Mono"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Lexend";
export const loadFont = (..._: unknown[]) => ({ ...load("Lexend"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Lexend Exa";
export const loadFont = (..._: unknown[]) => ({ ...load("Lexend Exa"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Manrope";
export const loadFont = (..._: unknown[]) => ({ ...load("Manrope"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Newsreader";
export const loadFont = (..._: unknown[]) => ({ ...load("Newsreader"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Nunito";
export const loadFont = (..._: unknown[]) => ({ ...load("Nunito"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Onest";
export const loadFont = (..._: unknown[]) => ({ ...load("Onest"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Oswald";
export const loadFont = (..._: unknown[]) => ({ ...load("Oswald"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Outfit";
export const loadFont = (..._: unknown[]) => ({ ...load("Outfit"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Playfair Display";
export const loadFont = (..._: unknown[]) => ({ ...load("Playfair Display"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Plus Jakarta Sans";
export const loadFont = (..._: unknown[]) => ({ ...load("Plus Jakarta Sans"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Red Hat Display";
export const loadFont = (..._: unknown[]) => ({ ...load("Red Hat Display"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Rubik";
export const loadFont = (..._: unknown[]) => ({ ...load("Rubik"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Saira";
export const loadFont = (..._: unknown[]) => ({ ...load("Saira"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Schibsted Grotesk";
export const loadFont = (..._: unknown[]) => ({ ...load("Schibsted Grotesk"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Silkscreen";
export const loadFont = (..._: unknown[]) => ({ ...load("Silkscreen"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Sora";
export const loadFont = (..._: unknown[]) => ({ ...load("Sora"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Source Serif 4";
export const loadFont = (..._: unknown[]) => ({ ...load("Source Serif 4"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Space Grotesk";
export const loadFont = (..._: unknown[]) => ({ ...load("Space Grotesk"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Space Mono";
export const loadFont = (..._: unknown[]) => ({ ...load("Space Mono"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Syne";
export const loadFont = (..._: unknown[]) => ({ ...load("Syne"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Tektur";
export const loadFont = (..._: unknown[]) => ({ ...load("Tektur"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Unbounded";
export const loadFont = (..._: unknown[]) => ({ ...load("Unbounded"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Young Serif";
export const loadFont = (..._: unknown[]) => ({ ...load("Young Serif"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,4 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../CREDITS.md. Changed for raea: imports and fonts.
import { loadFont as load } from "raea/text";
export const fontFamily = "Zen Kaku Gothic New";
export const loadFont = (..._: unknown[]) => ({ ...load("Zen Kaku Gothic New"), waitUntilDone: () => Promise.resolve() });
@@ -0,0 +1,72 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../CREDITS.md. Changed for raea: imports and fonts.
import { useMemo } from "react";
import { useCurrentFrame, useVideoConfig } from "raea";
// Every timing in remocn is written in frames of a 30 fps timeline: a delay
// of 12, a rise over 20, a spring fed `fps`. Read straight from Remotion,
// those numbers mean something else in a 60 fps composition: a tween runs
// twice as fast, while a spring keeps its length, so a scene does not even
// speed up evenly.
//
// These two hooks stand in for Remotion's and answer on that 30 fps timeline
// whatever rate the composition runs at. At 60 fps the frame goes 0, 0.5, 1,
// 1.5: the scene lasts the same number of seconds and every frame in between
// is a new picture. At 30 fps they return exactly what Remotion does.
//
// const frame = useSceneFrame();
// const { fps, width } = useSceneConfig();
//
// What a component hands back to Remotion is still counted in the
// composition's own frames: `from` and `durationInFrames` of a `<Sequence>`,
// the length of a transition. `useCompositionFrames()` converts those.
/** The frame rate remocn timings are written in. */
export const SCENE_FPS = 30;
/** `useCurrentFrame()` in 30 fps frames; fractional above 30 fps. */
export function useSceneFrame(): number {
const { fps } = useVideoConfig();
return (useCurrentFrame() * SCENE_FPS) / fps;
}
/**
* `useVideoConfig()` on the 30 fps timeline: `fps` is 30 and
* `durationInFrames` counts 30 fps frames. Size and the rest are untouched.
*/
export function useSceneConfig(): ReturnType<typeof useVideoConfig> {
const config = useVideoConfig();
return useMemo(
() => ({
...config,
fps: SCENE_FPS,
durationInFrames: (config.durationInFrames * SCENE_FPS) / config.fps,
}),
[config],
);
}
/**
* Turns a count of 30 fps frames into the composition's own, for what
* Remotion itself reads: `<Sequence from={frames(24)}>`. Whole frames only,
* as Remotion requires.
*/
export function useCompositionFrames(): (sceneFrames: number) => number {
const { fps } = useVideoConfig();
return useMemo(
() => (sceneFrames: number) => Math.round((sceneFrames * fps) / SCENE_FPS),
[fps],
);
}
/**
* The other way round: a count Remotion gives a component in the
* composition's own frames, in 30 fps frames. A transition's presentation
* gets its length that way (`presentationDurationInFrames`).
*/
export function useSceneFrameCount(): (compositionFrames: number) => number {
const { fps } = useVideoConfig();
return useMemo(
() => (compositionFrames: number) => (compositionFrames * SCENE_FPS) / fps,
[fps],
);
}
@@ -0,0 +1,3 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../CREDITS.md. Changed for raea: imports and fonts.
// remocn's glide works around Chrome's glyph rasteriser; raea draws text itself, so it adds nothing.
export const useGlide = () => (_moving: boolean) => "";
@@ -0,0 +1,90 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
/**
* The seam between live gradients (mount.ts, scheduler.ts) and the GPU API
* that draws them. A backend hands out leases: a renderer drawing into an
* offscreen canvas that the mount copies onto its own 2D canvas. Because the
* visible canvas only ever holds a 2D context, switching backends (or losing
* one mid-session) never touches the DOM, and the last frame stays on screen.
*
* Two backends: WebGPU (webgpu.ts), chosen per kind when the page passed
* its adapter checks and the kind has a WGSL twin that compiled, and WebGL2
* (pool.ts) for everything else. A WebGPU kind still compiling, or a page
* still probing, gets no lease yet; the scheduler retries when WebGPU
* reports a change.
*
* Exports do not go through a backend; they use export.ts (WebGL) directly.
*/
import { acquireContext, releaseContext, webglUnsupported } from "./pool";
import type { AnyCanvas, ColorResolver } from "./renderer";
import type {
FrameInput,
GradientKind,
GradientParams,
RenderTarget,
} from "./types";
import {
acquireSurface,
releaseSurface,
webgpuStatus,
webgpuUnsupported,
} from "./webgpu";
export type BackendName = "webgl2" | "webgpu";
/** One leased renderer. Stays with its backend between leases, so `loaded` survives. */
export interface BackendLease {
/** Where frames land; the mount copies from it with drawImage. */
readonly canvas: AnyCanvas;
/** First row of the frame in `canvas` (a WebGPU lease may draw a spare row above it). */
readonly sourceY: number;
/** Colour resolver used by the renderer; set by the current leaseholder. */
resolver: ColorResolver;
/** Which params (owner and version) the renderer was last loaded with. */
loaded: { owner: object; version: number } | null;
setParams(params: GradientParams): void;
renderFrame(frame: FrameInput, target: RenderTarget): void;
/** True once the GPU resources are gone; the canvas then holds no new frame. */
isLost(): boolean;
}
export interface GradientBackend {
readonly name: BackendName;
/** Whether this backend can draw the kind right now; mounts check it before acquiring. */
supports(kind: GradientKind): boolean;
/**
* Leases a renderer, or null when the budget is used up or the backend
* cannot run. `onLost` runs if the lease is lost; it has ended by then.
* `pixels` is the size the lease will render at, for memory caps.
*/
acquire(onLost?: (() => void) | null, pixels?: number): BackendLease | null;
release(lease: BackendLease): void;
/** True once this backend has failed for good on this page. */
unsupported(): boolean;
}
export const webglBackend: GradientBackend = {
acquire: (onLost = null) => acquireContext(onLost),
name: "webgl2",
// Only ever handed its own pooled contexts back.
release: releaseContext,
supports: () => true,
unsupported: webglUnsupported,
};
export const webgpuBackend: GradientBackend = {
acquire: (onLost = null, pixels = 0) => acquireSurface(onLost, pixels),
name: "webgpu",
release: releaseSurface,
// Ready to draw now: probed, and the kind's pipeline compiled.
supports: (kind) => webgpuStatus(kind) === "ready",
unsupported: webgpuUnsupported,
};
/**
* The backend that draws `kind` on this page: WebGPU unless the
* preference, the adapter, the probes, the kind (no WGSL, or it failed to
* compile) or a device loss rule it out.
*/
export function backendFor(kind: GradientKind): GradientBackend {
return webgpuStatus(kind) === "unavailable" ? webglBackend : webgpuBackend;
}
@@ -0,0 +1,190 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
export type Rgb = readonly [number, number, number];
export type Oklab = readonly [number, number, number];
const FALLBACK_RGB: Rgb = [0.5, 0.5, 0.5];
function srgbToLinear(c: number): number {
return c <= 0.040_45 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
}
function linearToSrgb(c: number): number {
return c <= 0.003_130_8 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055;
}
/** sRGB (0-1, gamma encoded) to OKLab. */
export function srgbToOklab(rgb: Rgb): Oklab {
const r = srgbToLinear(rgb[0]);
const g = srgbToLinear(rgb[1]);
const b = srgbToLinear(rgb[2]);
const l = Math.cbrt(
0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b,
);
const m = Math.cbrt(
0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b,
);
const s = Math.cbrt(
0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b,
);
return [
0.210_454_255_3 * l + 0.793_617_785 * m - 0.004_072_046_8 * s,
1.977_998_495_1 * l - 2.428_592_205 * m + 0.450_593_709_9 * s,
0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766 * s,
];
}
/** OKLab to sRGB (0-1, gamma encoded, clamped). */
export function oklabToSrgb(lab: Oklab): Rgb {
const l = (lab[0] + 0.396_337_777_4 * lab[1] + 0.215_803_757_3 * lab[2]) ** 3;
const m = (lab[0] - 0.105_561_345_8 * lab[1] - 0.063_854_172_8 * lab[2]) ** 3;
const s = (lab[0] - 0.089_484_177_5 * lab[1] - 1.291_485_548 * lab[2]) ** 3;
const out = [
4.076_741_662_1 * l - 3.307_711_591_3 * m + 0.230_969_929_2 * s,
-1.268_438_004_6 * l + 2.609_757_401_1 * m - 0.341_319_396_5 * s,
-0.004_196_086_3 * l - 0.703_418_614_7 * m + 1.707_614_701 * s,
].map((c) => Math.min(1, Math.max(0, linearToSrgb(c))));
return [out[0] ?? 0, out[1] ?? 0, out[2] ?? 0];
}
const HEX_RE = /^#([0-9a-f]{3,8})$/i;
const RGB_RE = /^rgba?\(\s*([^)]+)\)$/i;
function parseChannel(token: string): number | null {
const value = Number.parseFloat(token);
if (Number.isNaN(value)) {
return null;
}
return token.endsWith("%") ? value / 100 : value / 255;
}
/** Parses hex and rgb() colours without a DOM. Returns null for anything else. */
export function parseColorLiteral(value: string): Rgb | null {
const input = value.trim();
const hex = HEX_RE.exec(input)?.[1];
if (hex) {
const full = hex.length <= 4 ? [...hex].map((ch) => ch + ch).join("") : hex;
if (full.length !== 6 && full.length !== 8) {
return null;
}
return [
Number.parseInt(full.slice(0, 2), 16) / 255,
Number.parseInt(full.slice(2, 4), 16) / 255,
Number.parseInt(full.slice(4, 6), 16) / 255,
];
}
const body = RGB_RE.exec(input)?.[1];
if (body) {
const parts = body
.split(/[\s,/]+/)
.filter(Boolean)
.slice(0, 3);
const channels = parts.map(parseChannel);
const [r, g, b] = channels;
if (channels.length === 3 && r != null && g != null && b != null) {
return [r, g, b];
}
}
return null;
}
type Probe = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;
let probe: Probe | null | undefined;
function getProbe(): Probe | null {
if (probe !== undefined) {
return probe;
}
probe = null;
// OffscreenCanvas first: it works in Workers and never touches document.
if (typeof OffscreenCanvas !== "undefined") {
probe = new OffscreenCanvas(1, 1).getContext("2d", {
willReadFrequently: true,
});
} else if (typeof document !== "undefined") {
const canvas = document.createElement("canvas");
canvas.width = 1;
canvas.height = 1;
probe = canvas.getContext("2d", { willReadFrequently: true });
}
return probe;
}
/** Lets the browser parse any CSS colour (oklch, hsl, names...) by painting one pixel. */
function probeColor(value: string): Rgb | null {
const ctx = getProbe();
if (!ctx) {
return null;
}
const sentinel = "#010203";
ctx.fillStyle = sentinel;
ctx.fillStyle = value;
if (ctx.fillStyle === sentinel && value.trim().toLowerCase() !== sentinel) {
return null;
}
ctx.clearRect(0, 0, 1, 1);
ctx.fillRect(0, 0, 1, 1);
const [r = 0, g = 0, b = 0] = ctx.getImageData(0, 0, 1, 1).data;
return [r / 255, g / 255, b / 255];
}
const VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*([\s\S]+))?\)$/;
/** Expands var(--x) (with fallbacks, nested) against an element's computed style. */
export function resolveCssVariables(
value: string,
scope: Element | null,
depth = 0,
): string {
const match = VAR_RE.exec(value.trim());
if (!match || depth > 8) {
return value.trim();
}
const [, name = "", fallback] = match;
const resolved =
scope && typeof getComputedStyle !== "undefined"
? getComputedStyle(scope).getPropertyValue(name).trim()
: "";
if (resolved) {
return resolveCssVariables(resolved, scope, depth + 1);
}
return fallback ? resolveCssVariables(fallback, scope, depth + 1) : "";
}
const literalCache = new Map<string, Rgb>();
/** Resolves any CSS colour, including var(--x), to sRGB. Unknown colours become mid grey. */
export function resolveColor(value: string, scope: Element | null): Rgb {
const literal = resolveCssVariables(value, scope);
const cached = literalCache.get(literal);
if (cached) {
return cached;
}
const rgb = parseColorLiteral(literal) ?? probeColor(literal) ?? FALLBACK_RGB;
if (literalCache.size > 256) {
literalCache.clear();
}
literalCache.set(literal, rgb);
return rgb;
}
export function hasCssVariable(values: readonly string[]): boolean {
return values.some((value) => value.includes("var("));
}
function toHex(rgb: Rgb): string {
return `#${rgb
.map((channel) =>
Math.round(Math.min(1, Math.max(0, channel)) * 255)
.toString(16)
.padStart(2, "0"),
)
.join("")}`;
}
/** Resolves any CSS colour (var(), oklch, names...) to a concrete #rrggbb. */
export function resolveColorToHex(
value: string,
scope: Element | null,
): string {
return toHex(resolveColor(value, scope));
}
@@ -0,0 +1,201 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import {
hasCssVariable,
resolveColor,
resolveColorToHex,
srgbToOklab,
} from "./color";
import { normalizeParams } from "./params";
import type { AnyCanvas, ColorResolver } from "./renderer";
import { createWebGLRenderer, getWebGL2 } from "./renderer";
import type { GradientParams, GradientRenderer } from "./types";
/** What the GPU allows for one export tile. Every tile edge must be at most `maxTileSize`. */
export interface ExportLimits {
/** Largest square tile this renderer can draw: the smallest of the limits below (and the requested size). */
maxTileSize: number;
maxTextureSize: number;
maxRenderbufferSize: number;
maxViewportDims: readonly [number, number];
}
export interface ExportRenderer extends GradientRenderer {
readonly limits: ExportLimits;
}
function queryLimits(
gl: WebGL2RenderingContext,
): Omit<ExportLimits, "maxTileSize"> {
const viewport: unknown = gl.getParameter(gl.MAX_VIEWPORT_DIMS);
const dims =
viewport instanceof Int32Array && viewport.length >= 2
? ([viewport[0] ?? 0, viewport[1] ?? 0] as const)
: ([0, 0] as const);
return {
maxRenderbufferSize: Number(gl.getParameter(gl.MAX_RENDERBUFFER_SIZE)) || 0,
maxTextureSize: Number(gl.getParameter(gl.MAX_TEXTURE_SIZE)) || 0,
maxViewportDims: dims,
};
}
function tileLimit(
limits: Omit<ExportLimits, "maxTileSize">,
requested: number,
): number {
return Math.max(
1,
Math.min(
Math.floor(requested),
limits.maxTextureSize,
limits.maxRenderbufferSize,
limits.maxViewportDims[0],
limits.maxViewportDims[1],
),
);
}
function createExportCanvas(): AnyCanvas {
// Start at 1x1: a huge requested size can fail before limits are known.
if (typeof OffscreenCanvas !== "undefined") {
return new OffscreenCanvas(1, 1);
}
if (typeof document !== "undefined") {
return document.createElement("canvas");
}
throw new Error("Export needs OffscreenCanvas or a document");
}
let cachedLimits: Omit<ExportLimits, "maxTileSize"> | null = null;
/**
* The GPU's export limits, so an export UI can offer only tile and image
* sizes that will work. Probes once with a throwaway context, then caches.
* Pass the tile size you want; `maxTileSize` comes back clamped.
*/
export function getExportLimits(requestedTileSize = 2048): ExportLimits {
if (!cachedLimits) {
const canvas = createExportCanvas();
const gl = getWebGL2(canvas, { preserveDrawingBuffer: false });
if (!gl) {
throw new Error("WebGL2 is not available for export");
}
cachedLimits = queryLimits(gl);
gl.getExtension("WEBGL_lose_context")?.loseContext();
}
return {
...cachedLimits,
maxTileSize: tileLimit(cachedLimits, requestedTileSize),
};
}
/**
* Returns params whose colours are concrete #rrggbb values. Run it on the
* main thread before handing params to a Worker: var(--x) needs
* getComputedStyle, which Workers don't have. `element` scopes the
* variables (default <html>).
*/
export function resolveParamsColors(
params: GradientParams,
element?: Element,
): GradientParams {
const scope =
element ??
(typeof document === "undefined" ? null : document.documentElement);
if (!scope && hasCssVariable([...params.colors, params.background])) {
throw new Error(
"resolveParamsColors: var() colours need a document; call it on the main thread",
);
}
return {
...params,
background: resolveColorToHex(params.background, scope),
colors: params.colors.map((color) => resolveColorToHex(color, scope)),
};
}
/**
* Concrete colours never touch document or getComputedStyle. var() colours
* are resolved against <html> when a document exists, and are an error in a
* Worker.
*/
const exportColorResolver: ColorResolver = (value) => {
if (hasCssVariable([value])) {
if (typeof document === "undefined") {
throw new Error(
`createExportRenderer: unresolved colour "${value}" and no document. Call resolveParamsColors(params) on the main thread first.`,
);
}
return srgbToOklab(resolveColor(value, document.documentElement));
}
return srgbToOklab(resolveColor(value, null));
};
/**
* Offscreen renderer for exports: preserveDrawingBuffer on, no listeners, no
* DPR logic. Works in a Worker when params have concrete colours (see
* resolveParamsColors). The tile size is clamped to the GPU's texture,
* renderbuffer and viewport limits; read the result from `limits`.
*/
export function createExportRenderer(
params: GradientParams,
maxTileSize = 2048,
): ExportRenderer {
// New pinned paths must complete an integer number of laps over the export
// loop. Legacy params omit drift and retain their exact historical frames.
const normalized = normalizeParams(params);
const exportParams =
normalized.drift === undefined
? normalized
: { ...normalized, speed: Math.round(normalized.speed) };
const canvas = createExportCanvas();
const gl = getWebGL2(canvas, { preserveDrawingBuffer: true });
if (!gl) {
throw new Error("WebGL2 is not available for export");
}
const queried = queryLimits(gl);
cachedLimits ??= queried;
const limits: ExportLimits = {
...queried,
maxTileSize: tileLimit(queried, maxTileSize),
};
const size = limits.maxTileSize;
canvas.width = size;
canvas.height = size;
let renderer: ReturnType<typeof createWebGLRenderer>;
try {
renderer = createWebGLRenderer({
canvas,
gl,
params: exportParams,
resolveColor: exportColorResolver,
});
} catch (error) {
gl.getExtension("WEBGL_lose_context")?.loseContext();
throw error;
}
const live = renderer;
return {
canvas,
destroy() {
live.destroy();
gl.getExtension("WEBGL_lose_context")?.loseContext();
},
limits,
renderFrame(frame, target) {
if (target && (target.width > size || target.height > size)) {
throw new RangeError(
`Tile ${target.width}x${target.height} exceeds the export tile limit ${size} (GPU max texture ${limits.maxTextureSize}, renderbuffer ${limits.maxRenderbufferSize}, viewport ${limits.maxViewportDims.join("x")})`,
);
}
live.renderFrame(
{
frameIndex: frame.frameIndex,
timeSeconds: frame.timeSeconds,
frameRate: frame.frameRate,
},
target,
);
},
setParams: (patch) => live.setParams(patch),
};
}
@@ -0,0 +1,22 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import { getKind } from "./kinds";
import type { GradientParams } from "./types";
function grainLayer(amount: number): string {
const opacity = (0.06 + amount * 0.16).toFixed(3);
const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 ${opacity}'/></filter><rect width='100%' height='100%' filter='url(#n)'/></svg>`;
return `url("data:image/svg+xml,${encodeURIComponent(svg)}") 0 0 / 180px 180px repeat`;
}
/**
* A CSS `background` value that resembles the gradient: layered radial and
* linear gradients built from the same colours, so pages never show a blank
* box. var(--x) colours are kept as-is and follow the theme natively.
*/
export function staticFallbackCss(p: GradientParams): string {
const layers = getKind(p.kind).fallbackLayers(p.colors, p.background);
if (p.grain >= 0.2) {
layers.unshift(grainLayer(p.grain));
}
return [...layers, p.background].join(", ");
}
@@ -0,0 +1,44 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
export type { ExportLimits, ExportRenderer } from "./export";
export {
createExportRenderer,
getExportLimits,
resolveParamsColors,
} from "./export";
export { staticFallbackCss } from "./fallback";
export type { GradientKindDefinition } from "./kind";
export { getKind, kindDefaults, listKinds, registerKind } from "./kinds";
export {
LOOP_RADIUS,
loopPhase,
loopVector,
loopVectorAtPhase,
splitTiles,
videoFrameTimes,
} from "./loop";
export type { MountedGradient, MountOptions } from "./mount";
export { mountGradient } from "./mount";
export {
defaultParams,
mergeParams,
normalizeParams,
parseParams,
serializeParams,
} from "./params";
export {
contextStats,
MAX_LIVE_CONTEXTS,
PIXEL_BUDGET,
PRIMARY_PIXEL_BUDGET,
paceStats,
resetPace,
setPixelBudget,
takePaintStats,
} from "./scheduler";
export type {
FrameInput,
GradientKind,
GradientParams,
GradientRenderer,
RenderTarget,
} from "./types";
@@ -0,0 +1,55 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientParams } from "./types";
/**
* One gradient kind. `glsl` defines `vec3 kindColor(vec2 p, vec2 uv)` and
* returns OKLab. `p` is centred, y up, with the short side spanning -0.5..0.5;
* `uv` is 0..1 from the top left. Use loopNoise/fbm/u_loop for motion, never
* raw time, so the loop stays seamless.
*/
export interface GradientKindDefinition {
readonly name: string;
readonly label: string;
readonly description: string;
/** Hand-tuned params for this kind. */
readonly defaults: Omit<GradientParams, "kind">;
readonly glsl: string;
/**
* Optional WGSL twin of `glsl`: `fn kindColor(p: vec2f, uv: vec2f) -> vec3f`,
* same maths, against shaders/wgsl-common.ts. Kinds with it can render on
* WebGPU (and in Node); kinds without it always render with WebGL.
*
* A loader, not the source: keep the WGSL in its own module and return
* `import("./wgsl/<kind>").then((module) => module.wgsl)`, so bundlers
* split it out and only pages that pick WebGPU download it.
*/
readonly wgsl?: () => Promise<string>;
/**
* Set when `wgsl` uses fwidth/dpdx/dpdy. Screen-space derivatives come
* from 2x2 quads whose choice of row is driver-defined, so such a kind is
* near-exact against WebGL in the browser (checked with a tolerance in
* the engine lab tests) rather than bit-exact, and Node keeps rendering
* it through Chrome.
*/
readonly wgslUsesDerivatives?: true;
/** CSS background layers (without the base colour) that resemble the kind. */
readonly fallbackLayers: (
colors: readonly string[],
background: string,
) => string[];
}
/** Picks colour i, cycling when the palette is shorter. */
export function pick(colors: readonly string[], i: number): string {
return colors[i % colors.length] ?? "transparent";
}
/** Evenly spaced colour stops for CSS gradients. */
export function stops(colors: readonly string[], from = 0, to = 100): string {
const last = Math.max(1, colors.length - 1);
return colors
.map(
(color, i) => `${color} ${(from + ((to - from) * i) / last).toFixed(1)}%`,
)
.join(", ");
}
@@ -0,0 +1,78 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { GradientKindDefinition } from "./kind";
import { aurora } from "./shaders/aurora";
import { beam } from "./shaders/beam";
import { chrome } from "./shaders/chrome";
import { ditherBurst } from "./shaders/dither-burst";
import { ditherField } from "./shaders/dither-field";
import { fluted } from "./shaders/fluted";
import { grain } from "./shaders/grain";
import { halo } from "./shaders/halo";
import { horizon } from "./shaders/horizon";
import { limb } from "./shaders/limb";
import { linearFlow } from "./shaders/linear-flow";
import { mesh } from "./shaders/mesh";
import { mist } from "./shaders/mist";
import { pixelGlass } from "./shaders/pixel-glass";
import { radialGlow } from "./shaders/radial-glow";
import { ribbon } from "./shaders/ribbon";
import { rise } from "./shaders/rise";
import { silk } from "./shaders/silk";
import { smear } from "./shaders/smear";
import { spectrum } from "./shaders/spectrum";
import { swirl } from "./shaders/swirl";
import { voidKind } from "./shaders/void";
import { waves } from "./shaders/waves";
import type { GradientKind, GradientParams } from "./types";
export type { GradientKindDefinition } from "./kind";
const registry = new Map<string, GradientKindDefinition>();
/** Adds a kind. Re-registering a name replaces it. */
export function registerKind(definition: GradientKindDefinition): void {
registry.set(definition.name, definition);
}
for (const definition of [
mesh,
grain,
aurora,
waves,
radialGlow,
linearFlow,
horizon,
ditherField,
halo,
beam,
voidKind,
limb,
ditherBurst,
pixelGlass,
fluted,
spectrum,
silk,
ribbon,
chrome,
rise,
mist,
smear,
swirl,
]) {
registerKind(definition);
}
/** The kind's definition, or mesh when the name is unknown. */
export function getKind(kind: GradientKind): GradientKindDefinition {
return registry.get(kind) ?? mesh;
}
export function listKinds(): GradientKindDefinition[] {
return [...registry.values()];
}
/** Full params tuned for a kind. */
export function kindDefaults(kind: GradientKind): GradientParams {
const definition = getKind(kind);
return { ...definition.defaults, kind: definition.name };
}
@@ -0,0 +1,97 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { RenderTarget } from "./types";
/** Radius of the time circle in noise space at speed 1. */
export const LOOP_RADIUS = 0.6;
/** Frame rate the live loop uses to derive `frameIndex`. */
export const LIVE_FPS = 60;
/** Position along one loop, 0 to 2π. Endpoint input always wraps to zero. */
export function loopPhase(timeSeconds: number, loopSeconds: number): number {
const wrapped = ((timeSeconds % loopSeconds) + loopSeconds) % loopSeconds;
return (2 * Math.PI * wrapped) / loopSeconds;
}
/**
* Noise-space time input. Without an explicit drift, retain the original
* speed-scaled radius and one lap per loop for saved params. With drift, speed
* changes pace around the pinned path.
*/
export function loopVector(
timeSeconds: number,
loopSeconds: number,
speed: number,
drift?: number,
): readonly [number, number] {
const legacy = drift === undefined;
const phase = loopPhase(timeSeconds, loopSeconds) * (legacy ? 1 : speed);
const radius = legacy ? speed * LOOP_RADIUS : drift;
return [Math.cos(phase) * radius, Math.sin(phase) * radius];
}
/** Evaluates the fixed path at an already accumulated runtime phase. */
export function loopVectorAtPhase(
phase: number,
drift = LOOP_RADIUS,
): readonly [number, number] {
return [Math.cos(phase) * drift, Math.sin(phase) * drift];
}
/**
* Grain seed for a frame. It wraps at the live loop length so the grain
* pattern repeats with the loop too.
*/
export function grainFrame(
frameIndex: number,
loopSeconds: number,
frameRate = LIVE_FPS,
): number {
const period = Math.max(1, Math.round(loopSeconds * frameRate));
return ((Math.floor(frameIndex) % period) + period) % period;
}
/** Video frame rule: N = round(loopSeconds * fps) frames at i / fps; the endpoint is omitted. */
export function videoFrameTimes(loopSeconds: number, fps: number): number[] {
const count = Math.round(loopSeconds * fps);
return Array.from({ length: count }, (_, i) => i / fps);
}
export function fullTarget(width: number, height: number): RenderTarget {
return { fullHeight: height, fullWidth: width, height, width, x: 0, y: 0 };
}
/**
* Splits an image into tiles no larger than maxTile, row by row from the
* top left. Tiles are quad-aligned so a tiled render equals the full one
* even for kinds that use screen-space derivatives (fwidth), which the GPU
* computes over 2x2 pixel quads: every tile starts at an even x, and every
* tile's bottom edge sits an even number of rows above the image's bottom
* (WebGL pairs rows from the bottom). The step is maxTile rounded down to
* even, and any odd remainder goes to the top row of tiles.
*/
export function splitTiles(
fullWidth: number,
fullHeight: number,
maxTile: number,
): RenderTarget[] {
const step = Math.max(2, Math.floor(maxTile / 2) * 2);
const rows: { y: number; height: number }[] = [];
for (let bottom = fullHeight; bottom > 0; bottom -= step) {
const y = Math.max(0, bottom - step);
rows.unshift({ height: bottom - y, y });
}
const tiles: RenderTarget[] = [];
for (const { y, height } of rows) {
for (let x = 0; x < fullWidth; x += step) {
tiles.push({
fullHeight,
fullWidth,
height,
width: Math.min(step, fullWidth - x),
x,
y,
});
}
}
return tiles;
}
@@ -0,0 +1,442 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import type { BackendLease, GradientBackend } from "./backend";
import { backendFor } from "./backend";
import { hasCssVariable, resolveColor, srgbToOklab } from "./color";
import { staticFallbackCss } from "./fallback";
import { fullTarget, LIVE_FPS, LOOP_RADIUS, loopPhase } from "./loop";
import { mergeParams, normalizeParams } from "./params";
import type { ContextSlot, FrameQuality } from "./scheduler";
import {
GRAIN_CRISP,
MIN_RENDER_SCALE,
noteFrame,
recordPaint,
registerSlot,
relearnDisplayRate,
scheduleContexts,
slotLostContext,
unregisterSlot,
} from "./scheduler";
import type { FrameInput, GradientParams } from "./types";
export interface MountOptions {
/** Device pixel ratio cap. Default 1.5. */
maxDpr?: number;
/** "respect" renders one still frame when the user prefers reduced motion. Default "respect". */
reducedMotion?: "respect" | "ignore";
/** The page's one hero canvas: renders from PRIMARY_PIXEL_BUDGET, not the shared one. Default false. */
primary?: boolean;
}
export interface MountedGradient {
setParams(p: Partial<GradientParams>): void;
unmount(): void;
}
/**
* Live, on-page gradient. Owns canvas sizing (ResizeObserver, DPR capped at
* maxDpr), rAF, pausing offscreen or when the document is hidden, smoothed
* pointer and scroll-velocity influence, reduced motion, theme colour
* re-resolution and its share of the page's WebGL context budget.
*
* The canvas gets a 2D context. Frames are rendered in a leased GPU
* surface (WebGPU, or a WebGL context from the shared pool; see backend.ts)
* and copied over, so a suspended gradient
* keeps its last frame and never shows the browser's lost-context box.
* Behind it, the canvas background is `staticFallbackCss`, which is what
* shows when WebGL2 is unavailable.
*/
export function mountGradient(
canvas: HTMLCanvasElement,
params: GradientParams,
options: MountOptions = {},
): MountedGradient {
const maxDpr = options.maxDpr ?? 1.5;
let current = normalizeParams(params);
let lease: BackendLease | null = null;
/** The backend `lease` came from; picked per kind when a lease is taken. */
let leaseBackend: GradientBackend = backendFor(current.kind);
/** The 2D canvas shows a frame that matches the current params and theme. */
let fresh = false;
let visible = false;
let raf = 0;
let lastNow: number | null = null;
let time = 0;
let phase = 0;
/** Bumped whenever params or resolved colours change. */
let version = 0;
/** Render scale and frame rate from the shared pixel budget. */
let quality: FrameQuality = { halfRate: false, scale: 1 };
let skipNext = false;
const display = canvas.getContext("2d");
/** Pixels a frame renders at, at this render scale. */
const renderPixels = (scale: number) =>
Math.max(1, Math.round(canvas.width * scale)) *
Math.max(1, Math.round(canvas.height * scale));
const initialBackground = canvas.style.background;
const motionQuery = window.matchMedia("(prefers-reduced-motion: reduce)");
const reduced = () =>
options.reducedMotion !== "ignore" && motionQuery.matches;
// Pointer and scroll targets, eased toward in the frame loop.
const pointerTarget = { strength: 0, x: 0.5, y: 0.5 };
const pointer = { strength: 0, x: 0.5, y: 0.5 };
let scrollImpulse = 0;
let scrollVelocity = 0;
let lastScroll = { t: performance.now(), y: window.scrollY };
const resolver = (value: string) =>
srgbToOklab(resolveColor(value, canvas.isConnected ? canvas : null));
const applyBackground = () => {
canvas.style.background = staticFallbackCss(current);
};
const frameInput = (): FrameInput => {
if (reduced()) {
return { frameIndex: 0, timeSeconds: 0 };
}
const input: FrameInput = {
frameIndex: Math.floor(time * LIVE_FPS),
timeSeconds: time,
};
if (current.drift !== undefined) {
input.phase = phase;
}
if (pointer.strength > 0.001) {
input.pointer = { ...pointer };
}
if (Math.abs(scrollVelocity) > 0.001) {
input.scroll = { velocity: scrollVelocity };
}
return input;
};
/** Renders one frame with a pooled context and copies it onto the canvas. */
const paintWith = (context: BackendLease, frame: FrameInput, scale = 1) => {
if (!display || context.isLost() || canvas.width === 0) {
return;
}
if (context.loaded?.owner !== slot || context.loaded.version !== version) {
context.resolver = resolver;
context.setParams(current);
context.loaded = { owner: slot, version };
}
// Over the pixel budget, render smaller and let drawImage upscale.
const width = Math.max(1, Math.round(canvas.width * scale));
const height = Math.max(1, Math.round(canvas.height * scale));
context.renderFrame(frame, fullTarget(width, height));
if (context.isLost()) {
return;
}
display.clearRect(0, 0, canvas.width, canvas.height);
// Upscaling smooths pixel-cell kinds into blur; keep their cells crisp.
display.imageSmoothingEnabled = !(
current.kind === "dither-field" || current.dither.enabled
);
// Copying right after queue.submit() is safe: reading a WebGPU canvas
// (drawImage included) runs "get a copy of the image contents of a
// context", which first ensures all submitted work has finished writing the
// current texture (https://gpuweb.github.io/gpuweb/#abstract-opdef-get-a-copy-of-the-image-contents-of-a-context,
// via #canvas-hooks). The engine lab checks it: heavy kinds at 2560x1440,
// each frame copied the moment it is submitted, never stale or blank.
display.drawImage(
context.canvas,
0,
context.sourceY,
width,
height,
0,
0,
canvas.width,
canvas.height,
);
fresh = true;
};
const draw = () => {
if (lease) {
const start = performance.now();
paintWith(lease, frameInput(), quality.scale);
recordPaint(performance.now() - start);
}
};
/** Drops a stale frame so the theme-aware CSS fallback shows instead. */
const invalidate = () => {
version += 1;
fresh = false;
if (!lease) {
display?.clearRect(0, 0, canvas.width, canvas.height);
scheduleContexts();
}
};
const shouldAnimate = () =>
lease !== null && visible && !document.hidden && !reduced();
const tick = (now: number) => {
raf = 0;
noteFrame(now);
const dt = lastNow === null ? 0 : Math.min(0.1, (now - lastNow) / 1000);
lastNow = now;
time += dt;
if (current.drift !== undefined) {
phase += (dt * current.speed * 2 * Math.PI) / current.loopSeconds;
phase %= 2 * Math.PI;
}
const ease = 1 - Math.exp(-dt * 6);
pointer.x += (pointerTarget.x - pointer.x) * ease;
pointer.y += (pointerTarget.y - pointer.y) * ease;
pointer.strength += (pointerTarget.strength - pointer.strength) * ease;
scrollImpulse *= Math.exp(-dt * 7);
scrollVelocity +=
(scrollImpulse - scrollVelocity) * (1 - Math.exp(-dt * 5));
// At half rate, time still advances every frame; only drawing skips.
skipNext = quality.halfRate && !skipNext;
if (!skipNext) {
draw();
}
if (shouldAnimate()) {
raf = window.requestAnimationFrame(tick);
}
};
/** Starts or stops the frame loop to match the current state. */
const sync = () => {
if (shouldAnimate()) {
if (raf === 0) {
lastNow = null;
raf = window.requestAnimationFrame(tick);
}
return;
}
if (raf !== 0) {
window.cancelAnimationFrame(raf);
raf = 0;
}
draw();
};
const slot: ContextSlot = {
element: canvas,
grant() {
if (lease) {
return true;
}
if (!display) {
return false;
}
leaseBackend = backendFor(current.kind);
// Still probing or compiling: no lease yet; the scheduler re-runs when ready.
lease = leaseBackend.supports(current.kind)
? leaseBackend.acquire(onLost, renderPixels(quality.scale))
: null;
if (!lease) {
if (leaseBackend.unsupported()) {
unregisterSlot(slot);
}
return false;
}
draw();
sync();
return true;
},
primary() {
return options.primary === true;
},
minScale() {
if (current.dither.enabled) {
return 1;
}
return current.grain >= GRAIN_CRISP ? 0.8 : MIN_RENDER_SCALE;
},
pixels() {
return canvas.width * canvas.height;
},
backend() {
return backendFor(current.kind).name;
},
setQuality(next) {
quality = next;
// Readable in devtools and by the engine lab's checks.
canvas.dataset.renderScale = next.scale.toFixed(3);
},
paintStill() {
if (lease || fresh || !display) {
return;
}
const backend = backendFor(current.kind);
const painter = backend.supports(current.kind)
? backend.acquire(null, renderPixels(1))
: null;
if (!painter) {
return;
}
paintWith(painter, frameInput());
backend.release(painter);
},
revoke() {
if (raf !== 0) {
window.cancelAnimationFrame(raf);
raf = 0;
}
if (lease) {
leaseBackend.release(lease);
lease = null;
}
},
setVisible(next) {
visible = next;
sync();
},
};
/**
* The pool lost our context and already ended the lease. Keep the last
* frame on screen and let the scheduler find another context; it re-runs
* again when the lost one is restored.
*/
function onLost() {
lease = null;
if (raf !== 0) {
window.cancelAnimationFrame(raf);
raf = 0;
}
slotLostContext(slot);
}
const resize = () => {
const dpr = Math.min(maxDpr, window.devicePixelRatio || 1);
const width = Math.max(1, Math.round(canvas.clientWidth * dpr));
const height = Math.max(1, Math.round(canvas.clientHeight * dpr));
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
// Resizing clears the canvas.
fresh = false;
draw();
relearnDisplayRate();
}
scheduleContexts();
};
const onPointerMove = (event: PointerEvent) => {
if (current.interaction.pointer <= 0) {
return;
}
const rect = canvas.getBoundingClientRect();
if (rect.width === 0 || rect.height === 0) {
return;
}
const x = (event.clientX - rect.left) / rect.width;
const y = (event.clientY - rect.top) / rect.height;
const inside = x >= -0.1 && x <= 1.1 && y >= -0.1 && y <= 1.1;
pointerTarget.strength = inside ? 1 : 0;
if (inside) {
pointerTarget.x = x;
pointerTarget.y = y;
}
};
const onPointerLeave = () => {
pointerTarget.strength = 0;
};
const onScroll = () => {
const now = performance.now();
const dt = Math.max(1, now - lastScroll.t) / 1000;
const dy = window.scrollY - lastScroll.y;
lastScroll = { t: now, y: window.scrollY };
if (current.interaction.scroll <= 0) {
return;
}
// Viewport heights per second, so the feel is the same on every screen.
const velocity = dy / Math.max(1, window.innerHeight) / dt;
scrollImpulse = Math.max(-6, Math.min(6, velocity));
};
const onVisibility = () => {
relearnDisplayRate();
sync();
};
const onMotionChange = () => {
time = 0;
phase = 0;
invalidate();
sync();
};
const themeObserver = new MutationObserver(() => {
if (!hasCssVariable([...current.colors, current.background])) {
return;
}
invalidate();
draw();
});
const resizeObserver = new ResizeObserver(resize);
window.addEventListener("pointermove", onPointerMove, { passive: true });
document.documentElement.addEventListener("pointerleave", onPointerLeave);
window.addEventListener("scroll", onScroll, { passive: true });
document.addEventListener("visibilitychange", onVisibility);
motionQuery.addEventListener("change", onMotionChange);
themeObserver.observe(document.documentElement, {
attributeFilter: ["class", "style"],
attributes: true,
});
resizeObserver.observe(canvas);
applyBackground();
canvas.dataset.renderScale = quality.scale.toFixed(3);
resize();
if (display) {
registerSlot(slot);
}
return {
setParams(patch) {
const speedChanged =
patch.speed !== undefined && patch.speed !== current.speed;
const enteringPinnedPath = speedChanged && current.drift === undefined;
const fullParamsPatch =
"kind" in patch && "colors" in patch && "speed" in patch;
const nextPatch: Partial<GradientParams> = enteringPinnedPath
? { ...patch, drift: current.speed * LOOP_RADIUS }
: current.drift !== undefined &&
patch.drift === undefined &&
!fullParamsPatch
? { ...patch, drift: current.drift }
: patch;
if (enteringPinnedPath) {
// Legacy frames use the angle once around the loop. Keep that angle
// while switching to the pinned path so the first edit cannot jump.
phase = loopPhase(time, current.loopSeconds);
}
current = mergeParams(current, nextPatch);
applyBackground();
if (lease && backendFor(current.kind) !== leaseBackend) {
// The new kind draws with the other backend: give the lease back and
// let the scheduler grant one from the right backend.
slot.revoke();
slotLostContext(slot);
}
invalidate();
draw();
},
unmount() {
slot.revoke();
unregisterSlot(slot);
resizeObserver.disconnect();
themeObserver.disconnect();
window.removeEventListener("pointermove", onPointerMove);
document.documentElement.removeEventListener(
"pointerleave",
onPointerLeave,
);
window.removeEventListener("scroll", onScroll);
document.removeEventListener("visibilitychange", onVisibility);
motionQuery.removeEventListener("change", onMotionChange);
display?.clearRect(0, 0, canvas.width, canvas.height);
canvas.style.background = initialBackground;
delete canvas.dataset.renderScale;
},
};
}
@@ -0,0 +1,204 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
import { mesh } from "./shaders/mesh";
import type { GradientParams } from "./types";
/** The mesh kind with its tuned defaults. */
export const defaultParams: GradientParams = { ...mesh.defaults, kind: "mesh" };
const clamp = (n: number, min: number, max: number) =>
Math.min(max, Math.max(min, n));
function record(input: unknown): Record<string, unknown> {
if (typeof input !== "object" || input === null || Array.isArray(input)) {
throw new TypeError("Expected an object");
}
// Own enumerable fields are intentional: unlike zod, inherited properties are rejected.
return Object.fromEntries(Object.entries(input));
}
function number(value: unknown, name: string): number {
if (typeof value !== "number" || !Number.isFinite(value)) {
throw new TypeError(`${name} must be a number`);
}
return value;
}
function integer(value: unknown, name: string): number {
const parsed = number(value, name);
if (!Number.isInteger(parsed)) {
throw new TypeError(`${name} must be an integer`);
}
return parsed;
}
function string(value: unknown, name: string): string {
if (typeof value !== "string") {
throw new TypeError(`${name} must be a string`);
}
return value;
}
function fullParams(input: unknown): GradientParams {
const value = record(input);
const colors = value.colors;
if (!Array.isArray(colors) || colors.length < 2 || colors.length > 6) {
throw new TypeError("colors must contain 2 to 6 entries");
}
const dither = record(value.dither);
const interaction = record(value.interaction);
const parsed = {
background: string(value.background, "background"),
blur: number(value.blur, "blur"),
colors: colors.map((color) => string(color, "colors")),
dither: {
cell: number(dither.cell, "dither.cell"),
enabled: boolean(dither.enabled, "dither.enabled"),
levels: number(dither.levels, "dither.levels"),
},
grain: number(value.grain, "grain"),
interaction: {
pointer: number(interaction.pointer, "interaction.pointer"),
scroll: number(interaction.scroll, "interaction.scroll"),
},
kind: string(value.kind, "kind"),
loopSeconds: number(value.loopSeconds, "loopSeconds"),
scale: number(value.scale, "scale"),
seed: integer(value.seed, "seed"),
speed: number(value.speed, "speed"),
warp: number(value.warp, "warp"),
};
return value.drift === undefined
? parsed
: { ...parsed, drift: number(value.drift, "drift") };
}
function boolean(value: unknown, name: string): boolean {
if (typeof value !== "boolean") {
throw new TypeError(`${name} must be a boolean`);
}
return value;
}
function partialParams(input: unknown): Partial<GradientParams> {
const value = record(input);
const output: Partial<GradientParams> = {};
if ("background" in value)
output.background = string(value.background, "background");
if ("blur" in value) output.blur = number(value.blur, "blur");
if ("colors" in value) {
if (
!Array.isArray(value.colors) ||
value.colors.length < 2 ||
value.colors.length > 6
)
throw new TypeError("colors must contain 2 to 6 entries");
output.colors = value.colors.map((color) => string(color, "colors"));
}
if ("grain" in value) output.grain = number(value.grain, "grain");
if ("kind" in value) output.kind = string(value.kind, "kind");
if ("drift" in value) output.drift = number(value.drift, "drift");
if ("loopSeconds" in value)
output.loopSeconds = number(value.loopSeconds, "loopSeconds");
if ("scale" in value) output.scale = number(value.scale, "scale");
if ("seed" in value) output.seed = integer(value.seed, "seed");
if ("speed" in value) output.speed = number(value.speed, "speed");
if ("warp" in value) output.warp = number(value.warp, "warp");
if ("dither" in value) {
const dither = partialDither(value.dither);
output.dither = {
...defaultParams.dither,
...dither,
};
}
if ("interaction" in value) {
const interaction = partialInteraction(value.interaction);
output.interaction = {
...defaultParams.interaction,
...interaction,
};
}
return output;
}
function partialDither(input: unknown): Partial<GradientParams["dither"]> {
const value = record(input);
const output: Partial<GradientParams["dither"]> = {};
if ("cell" in value) output.cell = number(value.cell, "dither.cell");
if ("levels" in value) output.levels = number(value.levels, "dither.levels");
if ("enabled" in value) {
output.enabled = boolean(value.enabled, "dither.enabled");
}
return output;
}
function partialInteraction(
input: unknown,
): Partial<GradientParams["interaction"]> {
const value = record(input);
const output: Partial<GradientParams["interaction"]> = {};
if ("pointer" in value)
output.pointer = number(value.pointer, "interaction.pointer");
if ("scroll" in value)
output.scroll = number(value.scroll, "interaction.scroll");
return output;
}
/** Validates and clamps a full params object. Throws on a malformed shape. */
export function normalizeParams(input: GradientParams): GradientParams {
const parsed = fullParams(input);
const normalized = {
...parsed,
blur: clamp(parsed.blur, 0, 1),
colors: parsed.colors.slice(0, 6),
dither: {
cell: Math.round(clamp(parsed.dither.cell, 1, 32)),
enabled: parsed.dither.enabled,
levels: Math.round(clamp(parsed.dither.levels, 2, 32)),
},
grain: clamp(parsed.grain, 0, 1),
interaction: {
pointer: clamp(parsed.interaction.pointer, 0, 1),
scroll: clamp(parsed.interaction.scroll, 0, 1),
},
loopSeconds: clamp(parsed.loopSeconds, 4, 30),
scale: clamp(parsed.scale, 0.25, 4),
speed: clamp(parsed.speed, 0, 2),
warp: clamp(parsed.warp, 0, 1),
};
if (parsed.drift !== undefined) {
normalized.drift = clamp(parsed.drift, 0, 2);
}
return normalized;
}
/** Merges a partial update into full params, keeping nested objects whole. */
export function mergeParams(
base: GradientParams,
patch: Partial<GradientParams>,
): GradientParams {
return normalizeParams({
...base,
...patch,
dither: { ...base.dither, ...patch.dither },
interaction: { ...base.interaction, ...patch.interaction },
});
}
export function serializeParams(p: GradientParams): string {
return encodeURIComponent(JSON.stringify(normalizeParams(p)));
}
export function parseParams(s: string): GradientParams {
try {
const raw: unknown = JSON.parse(decodeURIComponent(s));
const parsed = partialParams(raw);
return normalizeParams({
...defaultParams,
...parsed,
dither: { ...defaultParams.dither, ...parsed.dither },
interaction: { ...defaultParams.interaction, ...parsed.interaction },
});
} catch {
return defaultParams;
}
}
@@ -0,0 +1,199 @@
// From remocn (https://github.com/Remocn/remocn), MIT, (c) 2026 Remocn: see ../../../CREDITS.md. Changed for raea: imports and fonts.
/**
* The page's WebGL contexts. Gradients never hold a context on their own
* canvas; they lease one of at most MAX_LIVE_CONTEXTS offscreen contexts,
* render into it and copy the frame onto their 2D canvas. Returning a lease
* keeps the last frame on screen, and contexts are reused instead of being
* lost and restored.
*
* When the browser loses a context, its lease ends at once: the holder is
* told (it keeps its last frame), the context stays unavailable, and the
* scheduler re-runs so the gradient can lease another one. When the context
* is restored it becomes available again and the scheduler re-runs.
*/
import type { BackendLease } from "./backend";
import { defaultParams } from "./params";
import type { AnyCanvas, WebGLRenderer } from "./renderer";
import {
createWebGLRenderer,
documentColorResolver,
getWebGL2,
} from "./renderer";
export const MAX_LIVE_CONTEXTS = 8;
export interface PooledContext extends BackendLease {
readonly canvas: AnyCanvas;
readonly gl: WebGL2RenderingContext;
readonly renderer: WebGLRenderer;
leased: boolean;
lost: boolean;
/** Called once if the context is lost while leased. */
onLost: (() => void) | null;
}
const contexts = new Set<PooledContext>();
let unsupported = false;
const changeListeners = new Set<() => void>();
/** Runs `listener` whenever a context is lost or restored. */
export function onPoolChange(listener: () => void): () => void {
changeListeners.add(listener);
return () => changeListeners.delete(listener);
}
function notifyChange() {
for (const listener of changeListeners) {
listener();
}
}
function createCanvas(): AnyCanvas {
if (typeof OffscreenCanvas !== "undefined") {
return new OffscreenCanvas(1, 1);
}
return document.createElement("canvas");
}
function create(): PooledContext | null {
if (unsupported) {
return null;
}
let canvas = createCanvas();
let gl = getWebGL2(canvas, { preserveDrawingBuffer: false });
if (
!gl &&
typeof document !== "undefined" &&
!(canvas instanceof HTMLCanvasElement)
) {
// Some browsers have OffscreenCanvas without WebGL2 on it.
canvas = document.createElement("canvas");
gl = getWebGL2(canvas, { preserveDrawingBuffer: false });
}
if (!gl) {
unsupported = true;
return null;
}
const holder = { resolver: documentColorResolver };
const renderer = createWebGLRenderer({
canvas,
gl,
params: defaultParams,
resolveColor: (value) => holder.resolver(value),
});
const context: PooledContext = {
canvas,
gl,
isLost: () => context.lost || gl.isContextLost(),
leased: false,
loaded: null,
sourceY: 0,
lost: false,
onLost: null,
renderFrame: (frame, target) => renderer.renderFrame(frame, target),
renderer,
setParams: (next) => renderer.setParams(next),
get resolver() {
return holder.resolver;
},
set resolver(next) {
holder.resolver = next;
},
};
canvas.addEventListener("webglcontextlost", (event) => {
event.preventDefault();
context.lost = true;
context.loaded = null;
const holder = context.onLost;
context.onLost = null;
context.leased = false;
holder?.();
notifyChange();
});
canvas.addEventListener("webglcontextrestored", () => {
if (!contexts.has(context)) {
// Trimmed while lost: don't keep a restored context outside the budget.
gl.getExtension("WEBGL_lose_context")?.loseContext();
return;
}
context.lost = false;
context.loaded = null;
try {
context.renderer.restore();
} catch {
destroy(context);
}
notifyChange();
});
contexts.add(context);
return context;
}
/** True once creating a WebGL2 context has failed on this page. */
export function webglUnsupported(): boolean {
return unsupported;
}
/**
* Leases an idle context, creating one if the budget allows. `onLost` runs if
* the browser loses the context during the lease; the lease is already over
* by then.
*/
export function acquireContext(
onLost: (() => void) | null = null,
): PooledContext | null {
for (const context of contexts) {
if (!context.leased && !context.lost) {
context.leased = true;
context.onLost = onLost;
return context;
}
}
if (contexts.size >= MAX_LIVE_CONTEXTS) {
return null;
}
try {
const context = create();
if (context) {
context.leased = true;
context.onLost = onLost;
}
return context;
} catch {
// A shader that fails to compile means this engine cannot run here.
unsupported = true;
return null;
}
}
export function releaseContext(context: PooledContext): void {
context.leased = false;
context.onLost = null;
}
function destroy(context: PooledContext) {
context.renderer.destroy();
context.gl.getExtension("WEBGL_lose_context")?.loseContext();
contexts.delete(context);
}
/** Frees idle contexts until at most `keep` contexts remain. */
export function trimContexts(keep: number): void {
for (const context of [...contexts]) {
if (contexts.size <= keep) {
return;
}
if (!context.leased) {
destroy(context);
}
}
}
export function liveContextCount(): number {
return contexts.size;
}
/** The pool's contexts. For tests and the engine lab only. */
export function pooledContexts(): readonly PooledContext[] {
return [...contexts];
}
Loaded 100 of 1296 files, more files were not shown because too many files have changed in this diff. Show more