mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c3d7765ab | ||
|
|
1d51c09c0b | ||
|
|
02617df030 | ||
|
|
12ad441266 | ||
|
|
8e7c5a13e7 | ||
|
|
a380418ed5 | ||
|
|
6e35267060 | ||
|
|
05f82ef572 |
No files matched your search
@@ -219,7 +219,7 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
|
||||
measured += 1;
|
||||
if ratio < 3.0 {
|
||||
low += 1;
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {ratio:.1}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text)) });
|
||||
issues.push(Issue { rule: "contrast", p: 1, at: Some(t), says: format!("{} is {:.2}:1 against what's behind it; make it at least 3:1 (a band, a shadow for separation, or another colour)", quote(&r.text), (ratio * 100.0).floor() / 100.0) });
|
||||
}
|
||||
}
|
||||
if measured > 0 && low == 0 {
|
||||
|
||||
@@ -124,3 +124,37 @@ Feature: raea cloud: raea and an ACP agent on a server of your own (sdk/cloud)
|
||||
back, a second container handing its render to the first, an ACP turn round-tripped
|
||||
And with Kimi Code signed in, one real turn renders a title card with raea in the container, and the file
|
||||
comes back through /v1/files
|
||||
|
||||
Rule: a box edits on light copies, the farm renders from originals (12-05)
|
||||
Scenario: CL17. Nothing on the box takes a light copy's place
|
||||
Given raea cloud brought a run's footage as 540p light copies (footage/NAME.mp4, listed in .raea-cloud/light.txt)
|
||||
Then every look the agent takes (a still, a frame, a probe, a check of its words) reads the light copy
|
||||
And no file ever replaces footage/NAME.mp4 on the box, before a render or after one
|
||||
|
||||
Scenario: CL18. A farm render reads each light copy as its original, fetched by the farm
|
||||
Given .raea-cloud/originals.json names a light copy's original: its hash, size and a link that hasn't ended
|
||||
When a render that reads the light copy goes to the farm (server/offload.ts)
|
||||
Then its media manifest names the original under the light copy's path, with its link, and the light copy's own
|
||||
bytes go nowhere
|
||||
And the farm fetches the original from the library into its cache, checks it against its hash, and keeps it for
|
||||
every later render; the box never downloads it, hashes it or sends it
|
||||
And a light copy the render doesn't read is left out, its original included
|
||||
And a size raea cloud doesn't know goes as 0, which the farm takes with a link and never without one
|
||||
|
||||
Scenario: CL19. An original with no link goes from the box
|
||||
Given a light copy whose original has no hash, or whose link ends within 5 minutes
|
||||
When its original is in footage/originals/ under the light copy's name (any extension)
|
||||
Then the render sends that file by its own hash, under the light copy's path
|
||||
And only a farm with its media cache gets an original by its file (by LFS or in the tar it would go as the light
|
||||
copy), and only that farm an original of unknown size: for any other the take is rendered as its light copy
|
||||
And .raea-cloud/proxies/ never goes in a render's tar, and an original no source names stays on the box
|
||||
|
||||
Scenario: CL20. A render that read a light copy says so
|
||||
Given a light copy with no original either way
|
||||
Then the render prints NO ORIGINAL with its name, and is rendered from the light copy
|
||||
And its manifest records {"originals": {"read": [...], "light": [...]}} (a still's in OUT.render.json beside it),
|
||||
checked or not, from which raea cloud marks it a draft that is never shown or published
|
||||
And the farm's media list holds each original by its link in its light copy's place, with everything else that
|
||||
went (12-05 review: the farm-cache path dropped the links while the manifest said they were read)
|
||||
And an original of unknown size over 40 GB is refused as it downloads, before it fills the farm's volume
|
||||
And test/originals.ts and test/farm_media.py check CL17-CL20
|
||||
@@ -0,0 +1,68 @@
|
||||
// pace.ts on made-up words and levels: a short run between two long pauses joins a neighbour; level evening measures
|
||||
// only clips with a second of speech and gives a short clip its own take's gain
|
||||
import { expect, test } from "bun:test";
|
||||
import { evenLevels, pace, type Levels } from "../src/pace";
|
||||
|
||||
/** levels at 10 ms: speech (-20 dB) inside each word, quiet (-70 dB) elsewhere, over `seconds` */
|
||||
function levels(ws: { from: number; to: number }[], seconds: number): Levels {
|
||||
const db = Array.from({ length: Math.round(seconds * 100) }, (_, i) => (ws.some((w) => i / 100 >= w.from && i / 100 < w.to) ? -20 : -70));
|
||||
return { start: 0, db };
|
||||
}
|
||||
|
||||
test("a word alone between two long pauses joins a neighbour instead of flicking by", () => {
|
||||
const ws = [
|
||||
{ text: "Sounds", from: 0.5, to: 0.9 },
|
||||
{ text: "great.", from: 0.95, to: 1.4 },
|
||||
// 0.7 s pause
|
||||
{ text: "Available", from: 2.1, to: 2.55 },
|
||||
// 0.6 s pause
|
||||
{ text: "times", from: 3.15, to: 3.5 },
|
||||
{ text: "the", from: 3.55, to: 3.7 },
|
||||
{ text: "same", from: 3.75, to: 4.0 },
|
||||
{ text: "day.", from: 4.05, to: 4.5 },
|
||||
];
|
||||
const { pieces, trims } = pace(ws, levels(ws, 6), [[0, 6]], { hook: 0 });
|
||||
expect(pieces.length).toBe(2);
|
||||
for (const p of pieces) expect(ws[p.words[1]].to - ws[p.words[0]].from).toBeGreaterThanOrEqual(0.8);
|
||||
// the shorter pause (after "Available") is the one kept; the longer one is still cut
|
||||
expect(pieces[1].words[0]).toBe(2);
|
||||
expect(trims.filter((t) => t.kind === "pause").length).toBe(1);
|
||||
});
|
||||
|
||||
test("a clip too short to measure takes its own take's gain, and gain stays within 9 dB", () => {
|
||||
const clips = [
|
||||
{ take: "A", file: "A.mp4", from: 0, to: 3, line: "a" },
|
||||
{ take: "A", file: "A.mp4", from: 4, to: 4.5, line: "b" },
|
||||
{ take: "B", file: "B.mp4", from: 0, to: 3, line: "c" },
|
||||
{ take: "C", file: "C.mp4", from: 0, to: 3, line: "d" },
|
||||
];
|
||||
const lv: Record<string, { db: number; seconds: number }> = { a: { db: -30, seconds: 2.5 }, b: { db: -45, seconds: 0.4 }, c: { db: -18, seconds: 2.5 }, d: { db: -18, seconds: 2.5 } };
|
||||
const out = evenLevels(clips, (c) => lv[c.line]);
|
||||
expect(out[0].gainDb).toBe(9);
|
||||
expect(out[1].gainDb).toBe(9);
|
||||
expect(out[2].gainDb).toBeUndefined();
|
||||
});
|
||||
|
||||
test("a line stopping mid-sentence with no pause runs on to its sentence's end; a tight seam never crosses a word", () => {
|
||||
const ws = [
|
||||
{ text: "get", from: 0.5, to: 0.66 },
|
||||
{ text: "them", from: 0.66, to: 0.82 },
|
||||
{ text: "delivered", from: 0.82, to: 1.06 },
|
||||
{ text: "for", from: 1.06, to: 1.22 },
|
||||
{ text: "free?", from: 1.22, to: 1.46 },
|
||||
// a pause, then the next sentence
|
||||
{ text: "Uh", from: 2.0, to: 2.3 },
|
||||
{ text: "sounds", from: 2.3, to: 2.6 },
|
||||
];
|
||||
// the sound of "for" starts 60 ms after its transcript time, so halfway between the sounds would be inside it
|
||||
const l = levels([{ from: 0.5, to: 1.06 }, { from: 1.12, to: 1.46 }, { from: 2.0, to: 2.6 }], 3.5);
|
||||
const { pieces } = pace(ws, l, [[0, 2]], { hook: 0 });
|
||||
expect(pieces.length).toBe(1);
|
||||
expect(pieces[0].words).toEqual([0, 4]);
|
||||
expect(pieces[0].to).toBeGreaterThanOrEqual(1.46);
|
||||
// a line ending where the sentence goes on for more than three words is cut at the boundary, not inside the next word
|
||||
const long = [...ws.slice(0, 3), { text: "for", from: 1.06, to: 1.22 }, { text: "all", from: 1.22, to: 1.4 }, { text: "your", from: 1.4, to: 1.55 }, { text: "pets", from: 1.55, to: 1.8 }, { text: "today.", from: 1.8, to: 2.2 }];
|
||||
const l2 = levels([{ from: 0.5, to: 1.06 }, { from: 1.12, to: 2.2 }], 3);
|
||||
const r = pace(long, l2, [[0, 2]], { hook: 0 });
|
||||
expect(r.pieces[0].to).toBeLessThanOrEqual(1.06 + 1 / 30);
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// How raea cut times a take's lines: the take's light copy when raea cloud keeps one, its jump cuts (kept in raea's
|
||||
// cache) and sound level, and pace.ts's timing, kept off the take's own jump cuts. native.ts gives it the engine.
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { basename, dirname } from "node:path";
|
||||
import { levelsOf, linesIn, pace, wavSamples, type Levels, type PaceOptions, type Piece, type Trim, type Word } from "./pace";
|
||||
|
||||
/** what timing needs of the engine: a take's path, raea's commands (text and JSON), and whether a file is sound alone */
|
||||
export type TakeIO = { at: (p: string) => string; engineRun: (a: string[]) => string; engineJson: (a: string[]) => any; isAudio: (f: string) => boolean };
|
||||
|
||||
const ms = (s: number) => Math.round(s * 1000) / 1000;
|
||||
|
||||
/** cutPlan and takeLevels over `io`, each take's levels kept for the run */
|
||||
export function timing({ at, engineRun, engineJson, isAudio }: TakeIO) {
|
||||
/** The take to read for timing: its light copy when raea cloud keeps one (.raea-cloud/proxies/NAME.mp4 in the project,
|
||||
* where the light copy goes once a render brings the original into footage/). Its words, pauses, level and jump cuts
|
||||
* are the original's, read in a fraction of the time (12-05: a 4K original's jump cuts took over 10 minutes of a box's
|
||||
* CPU, and a fix pass's `raea cut` ran out of time). */
|
||||
function lightOf(file: string): string {
|
||||
const name = basename(file).replace(/\.[^.]+$/, "");
|
||||
const kept = `${process.cwd()}/.raea-cloud/proxies/${name}.mp4`;
|
||||
return existsSync(kept) ? kept : file;
|
||||
}
|
||||
|
||||
/** A take's own jump cuts (raea media cuts, every frame decoded: 43 s for a 4-minute take on a box), found once per take
|
||||
* and kept by its path, size and time in raea's cache, so the second `raea cut` on a take doesn't decode it again
|
||||
* (12-04: three cuts on one take in a step ran past a box step's 3 minutes, and the run stopped with nothing made) */
|
||||
function jumpCuts(take: string): number[] {
|
||||
const file = lightOf(at(take));
|
||||
let kept = "";
|
||||
try {
|
||||
const s = statSync(file);
|
||||
const dir = `${process.env.XDG_CACHE_HOME || `${homedir()}/.cache`}/raea/cuts`;
|
||||
kept = `${dir}/${createHash("sha1").update(`${realpathSync(file)}|${s.size}|${s.mtimeMs}|0.08`).digest("hex")}.json`;
|
||||
if (existsSync(kept)) return JSON.parse(readFileSync(kept, "utf8")) as number[];
|
||||
} catch {
|
||||
kept = "";
|
||||
}
|
||||
const cuts = (engineJson(["media", "cuts", file, "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
|
||||
if (kept)
|
||||
try {
|
||||
mkdirSync(dirname(kept), { recursive: true });
|
||||
writeFileSync(kept, JSON.stringify(cuts));
|
||||
} catch {
|
||||
// a cache that can't be written costs the next cut the decode, nothing else
|
||||
}
|
||||
return cuts;
|
||||
}
|
||||
|
||||
/** A take's sound level every 10 ms (raea media audio, 16 kHz mono), kept for this run */
|
||||
const heardLevels = new Map<string, Levels>();
|
||||
function takeLevels(take: string): Levels {
|
||||
const had = heardLevels.get(take);
|
||||
if (had) return had;
|
||||
const dir = mkdtempSync(`${tmpdir()}/raea-levels-`);
|
||||
try {
|
||||
const wav = `${dir}/take.wav`;
|
||||
engineRun(["media", "audio", lightOf(at(take)), "--rate", "16000", "--mono", "-o", wav]);
|
||||
const { pcm, rate } = wavSamples(readFileSync(wav));
|
||||
const l = { start: 0, db: levelsOf(pcm, rate) };
|
||||
heardLevels.set(take, l);
|
||||
return l;
|
||||
} catch {
|
||||
// a take with no sound to read is cut on its words alone
|
||||
return { start: 0, db: [] };
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** Where to cut a take for each line (linesIn), timed by pace.ts in the quiet around each line's sound, a breath kept,
|
||||
* long pauses, fillers and false starts taken out (unless `keep`), then off the take's own jump cuts. Pieces in the
|
||||
* take's seconds, on the edit's frame grid. */
|
||||
function cutPlan(take: string, ws: Word[], lines: string[], o: PaceOptions, start: number): { pieces: Piece[]; trims: Trim[]; notes: string[] } {
|
||||
const { spans, notes } = linesIn(ws, lines);
|
||||
// a sound-only take has no jump cuts to keep off
|
||||
const cuts = isAudio(take) ? [] : jumpCuts(take);
|
||||
const { pieces, trims } = pace(ws, takeLevels(take), spans, o, start);
|
||||
const sf = 1 / (o.fps ?? 30);
|
||||
for (const p of pieces) {
|
||||
const [i, j] = p.words;
|
||||
// a jump cut in the take near a join: start one frame after it (or end one before), never on it, or the other
|
||||
// shot's last frame can show
|
||||
const ca = cuts.find((c) => Math.abs(c - p.from) <= 0.25 && c <= ws[i].from + 0.05);
|
||||
if (ca !== undefined && ca + sf > p.from) p.from = ms(Math.ceil((ca + sf) / sf) * sf);
|
||||
const cb = cuts.find((c) => Math.abs(c - p.to) <= 0.25 && c >= ws[j].to - 0.05);
|
||||
if (cb !== undefined && cb - sf < p.to) p.to = ms(Math.floor((cb - sf) / sf) * sf);
|
||||
}
|
||||
return { pieces, trims, notes };
|
||||
}
|
||||
|
||||
return { cutPlan, takeLevels };
|
||||
}
|
||||
+54
-15
@@ -49,26 +49,54 @@ export interface Cut {
|
||||
line: string;
|
||||
/** a sound-only take's clip plays as <Audio> (#89); absent means video */
|
||||
kind?: "video" | "audio";
|
||||
/** what brings its speech to the cut's other lines (dB): raea cut evens them */
|
||||
gainDb?: number;
|
||||
/** it follows a clip of the same take with time skipped (a jump cut): the edit reframes it (punchIn(i)) */
|
||||
jump?: boolean;
|
||||
}
|
||||
|
||||
/** A cutaway: a picture laid over the join after clip `after`, `l` seconds over that clip's end (an L cut: its sound runs
|
||||
* on under the cutaway) and `j` over the next one's start (a J cut: that line's sound starts under it). */
|
||||
export interface Cutaway extends Cut {
|
||||
after: number;
|
||||
l: number;
|
||||
j: number;
|
||||
}
|
||||
|
||||
/** cuts.ts from the clips: data the edit imports (each take's file as a module, so the bundler finds the media). */
|
||||
export function cutsModule(clips: Cut[], edit: { width: number; height: number; fps: number }): string {
|
||||
const files = [...new Set(clips.map((c) => c.file))];
|
||||
export function cutsModule(clips: Cut[], edit: { width: number; height: number; fps: number }, cutaways: Cutaway[] = []): string {
|
||||
const files = [...new Set([...clips, ...cutaways].map((c) => c.file))];
|
||||
const id = (f: string) => "m_" + f.replace(/\W/g, "_");
|
||||
const rows = clips.map((c) => ` { take: ${JSON.stringify(c.take)}, src: ${id(c.file)}, from: ${c.from.toFixed(3)}, to: ${c.to.toFixed(3)}, line: ${JSON.stringify(c.line)}, kind: ${JSON.stringify(c.kind ?? "video")} },`);
|
||||
return `// written by \`raea cut\`: the clips, in order, in each take's own seconds. Re-run raea cut to change them, or edit
|
||||
// by hand (the edit reads only this file). cuts.json beside it is the same list for raea's checks.
|
||||
const more = (c: Cut) => `${c.gainDb ? `, gainDb: ${c.gainDb}` : ""}${c.jump ? ", jump: true" : ""}`;
|
||||
const row = (c: Cut) => `{ take: ${JSON.stringify(c.take)}, src: ${id(c.file)}, from: ${c.from.toFixed(3)}, to: ${c.to.toFixed(3)}, line: ${JSON.stringify(c.line)}, kind: ${JSON.stringify(c.kind ?? "video")}${more(c)} }`;
|
||||
const len = (c: Cut) => Math.max(1, Math.round((c.to - c.from) * edit.fps));
|
||||
// a cutaway's first frame in the edit: the end of the clip it lies over, less its L part
|
||||
const startOf = (x: Cutaway) => Math.max(0, clips.slice(0, x.after + 1).reduce((n, c) => n + len(c), 0) - Math.round(x.l * edit.fps));
|
||||
return `// written by \`raea cut\`: the clips, in order, in each take's own seconds, timed by their sound (a breath at each join,
|
||||
// long pauses, fillers and false starts out), each one's gainDb evening its level with the others, and a jump cut (the
|
||||
// same take with time skipped) marked jump. Re-run raea cut to change them, or edit by hand (the edit reads only this
|
||||
// file). cuts.json beside it is the same list for raea's checks.
|
||||
${files.map((f) => `import ${id(f)} from ${JSON.stringify("./" + f)};`).join("\n")}
|
||||
|
||||
export const edit = ${JSON.stringify(edit)};
|
||||
export type Cut = { take: string; src: string; from: number; to: number; line: string; kind: "video" | "audio" };
|
||||
export type Cut = { take: string; src: string; from: number; to: number; line: string; kind: "video" | "audio"; gainDb?: number; jump?: boolean };
|
||||
export const cuts: Cut[] = [
|
||||
${rows.join("\n")}
|
||||
${clips.map((c) => ` ${row(c)},`).join("\n")}
|
||||
];
|
||||
/** pictures laid over a join, muted (the clips' sound runs under them): \`start\` is the edit's frame each begins at */
|
||||
export const cutaways: (Cut & { start: number })[] = [
|
||||
${cutaways.map((x) => ` { ...${row(x)}, start: ${startOf(x)} },`).join("\n")}
|
||||
];
|
||||
/** a clip's length in the edit's frames */
|
||||
export const frames = (c: Cut) => Math.max(1, Math.round((c.to - c.from) * edit.fps));
|
||||
/** the cuts end to end, in frames */
|
||||
export const total = cuts.reduce((n, c) => n + frames(c), 0);
|
||||
/** how far clip i is punched in: a jump cut alternates 1 and 1.15 along a run of them, so the picture reframes at each */
|
||||
export const punchIn = (i: number) => {
|
||||
let k = 0;
|
||||
for (let n = i; n > 0 && cuts[n]?.jump; n--) k++;
|
||||
return k % 2 ? 1.15 : 1;
|
||||
};
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -78,7 +106,8 @@ A video edit as a React + TypeScript project, rendered by raea.
|
||||
|
||||
- edit.tsx: the composition. Change anything: layout, timing, which component plays when.
|
||||
- cuts.ts: the clips (\`raea cut\` writes it, with cuts.json and words.json beside it; re-run it rather than editing
|
||||
by hand, or captions and checks lose their timing). components/: components you added (\`raea make component add\`), yours to change.
|
||||
by hand, or captions and checks lose their timing). It times each clip by its sound: a breath at each join, long
|
||||
pauses, fillers and false starts out, each clip's gainDb evening the voices, a jump cut marked for punchIn(i). components/: components you added (\`raea make component add\`), yours to change.
|
||||
- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from its site), loaded with the project's
|
||||
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen". Its colours and faces are the palette, as classes
|
||||
(text-brand-accent, bg-brand-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3, font-brand,
|
||||
@@ -98,7 +127,10 @@ Layout: <AbsoluteFill>, <Sequence from durationInFrames>, <Series><Series.Sequen
|
||||
Media: <Video src startFrom endAt volume playbackRate muted punchIn style>; a take cropped to another shape goes
|
||||
through components/Framed.tsx when the project has it (<Framed src startFrom endAt at? punchIn?>: the crop on the
|
||||
person's face, from footage/faces.json; at picks a face), else an objectPosition you
|
||||
measured on the take, never a guess. <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
|
||||
measured on the take, never a guess. A cut of footage is composed whole with components/Cut.tsx when the project
|
||||
has it: <Cut moments={fromCuts(cuts, edit.fps, punchIn)} said={words.json} keys? hook? bed? />, each moment's show
|
||||
(speaker, two, product, broll, screen, wide, end) and who, asset or cta set by you; it frames, splits, places the
|
||||
product clear of faces, captions every word, lays the music bed under the voices at the level the check wants, and ends on the brand's card. <Audio src startFrom endAt volume={n | (f) => n} gainDb fadeIn fadeOut>,
|
||||
<Img src>. Media files import as modules: import take from
|
||||
"./media/x.mov". Sound: decide what each scene is heard as first (silence, its own sound, effects, music), and make
|
||||
it as \`raea guide sound\` says; narration is <Speech text start> from raea/speech. <Mix lufs ceiling> masters the sound.
|
||||
@@ -281,12 +313,19 @@ export function raeaHandler(host?: Host, engine?: Engine) {
|
||||
if (m) spans.push([Number(m[1]), Number(m[2])]);
|
||||
}
|
||||
});
|
||||
const [take, ...lines] = clean(args.slice(1), "--at");
|
||||
if (!take || (!lines.length && !spans.length)) return out("", 2, `raea cut TAKE "line" ["line" ...] | --at A-B [--at C-D ...] [--append]\n`);
|
||||
const prev: Cut[] = args.includes("--append") && (await c.fs.exists(p("cuts.json"))) ? JSON.parse(await c.fs.readFile(p("cuts.json"), "utf8")).cuts : [];
|
||||
const r = ask("cut", { take, lines, spans, keep: prev }) as { edit: { width: number; height: number; fps: number }; cuts: Cut[]; words: unknown[]; perception?: unknown; said: string };
|
||||
await c.fs.writeFile(p("cuts.ts"), cutsModule(r.cuts, r.edit));
|
||||
await c.fs.writeFile(p("cuts.json"), JSON.stringify({ edit: r.edit, cuts: r.cuts }, null, 2) + "\n");
|
||||
const num = (name: string) => {
|
||||
const v = flag(args, name);
|
||||
return v === undefined || !Number.isFinite(Number(v)) ? undefined : Number(v);
|
||||
};
|
||||
const [take, ...lines] = clean(args.slice(1), "--at", "--j", "--breath");
|
||||
const cutaway = args.includes("--cutaway");
|
||||
if (!take || (!lines.length && !spans.length) || (cutaway && !spans.length))
|
||||
return out("", 2, `raea cut TAKE "line" ["line" ...] | --at A-B [--at C-D ...] [--append] [--cutaway [--j S]] [--breath S] [--keep-pauses] [--no-gain]\n`);
|
||||
// a cutaway lies over the cut there is: it always appends
|
||||
const saved: { cuts?: Cut[]; cutaways?: Cutaway[] } = (args.includes("--append") || cutaway) && (await c.fs.exists(p("cuts.json"))) ? JSON.parse(await c.fs.readFile(p("cuts.json"), "utf8")) : {};
|
||||
const r = ask("cut", { take, lines, spans, keep: saved.cuts ?? [], cutaways: saved.cutaways ?? [], cutaway, j: num("--j"), breath: num("--breath"), keepPauses: args.includes("--keep-pauses"), gain: !args.includes("--no-gain") }) as { edit: { width: number; height: number; fps: number }; cuts: Cut[]; cutaways: Cutaway[]; words: unknown[]; perception?: unknown; said: string };
|
||||
await c.fs.writeFile(p("cuts.ts"), cutsModule(r.cuts, r.edit, r.cutaways));
|
||||
await c.fs.writeFile(p("cuts.json"), JSON.stringify({ edit: r.edit, cuts: r.cuts, ...(r.cutaways.length ? { cutaways: r.cutaways } : {}) }, null, 2) + "\n");
|
||||
await c.fs.writeFile(p("words.json"), JSON.stringify(r.words) + "\n");
|
||||
// where the face and the safe band are in the edit, for <Region> and the checks (a host may not see faces)
|
||||
if (r.perception) await c.fs.writeFile(p("perception.json"), JSON.stringify(r.perception) + "\n");
|
||||
|
||||
+82
-106
@@ -4,13 +4,14 @@
|
||||
//
|
||||
// native.ts RAEA VERB ARGS... RAEA: the native raea's path, for the engine's own verbs
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
||||
import { homedir, tmpdir } from "node:os";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, delimiter, dirname, extname } from "node:path";
|
||||
import { brandKit, pixelsOf } from "./brand";
|
||||
import { readSite, stylesOf } from "./scrape";
|
||||
import { wordsOf } from "./heard";
|
||||
import { evenLevels, markJumps, speechOf, toSound, type PaceOptions } from "./pace";
|
||||
import { timing } from "./cutplan";
|
||||
import { harness, library, show, task } from "./app";
|
||||
import { fromCwd } from "./show";
|
||||
import { clothesHost } from "./wardrobe";
|
||||
@@ -44,17 +45,21 @@ const AUDIO = ["wav", "mp3", "m4a", "aac", "flac", "aif", "aiff", "ogg", "opus"]
|
||||
const extOf = (f: string) => extname(f).slice(1).toLowerCase();
|
||||
const isAudio = (f: string) => AUDIO.includes(extOf(f));
|
||||
|
||||
/** Every take under media/: its path from the project's root */
|
||||
/** Every take under media/ and footage/ (not footage/originals/, which the render reads in its light copies' place): its
|
||||
* path from the project's root */
|
||||
function takes(): string[] {
|
||||
const out: string[] = [];
|
||||
const walk = (dir: string) => {
|
||||
for (const e of existsSync(at(dir)) ? readdirSync(at(dir), { withFileTypes: true }) : []) {
|
||||
const p = `${dir}/${e.name}`;
|
||||
if (e.isDirectory()) walk(p);
|
||||
else if (VIDEO.includes(extOf(e.name)) || AUDIO.includes(extOf(e.name))) out.push(p);
|
||||
if (e.isDirectory()) {
|
||||
if (p !== "footage/originals") walk(p);
|
||||
} else if (VIDEO.includes(extOf(e.name)) || AUDIO.includes(extOf(e.name))) out.push(p);
|
||||
}
|
||||
};
|
||||
// media/ is a project's own; footage/ is what raea cloud fetched (its light copies: originals/ follow on their own)
|
||||
walk("media");
|
||||
walk("footage");
|
||||
return out.sort();
|
||||
}
|
||||
|
||||
@@ -64,7 +69,7 @@ function takeOf(name: string): string {
|
||||
const all = takes();
|
||||
const bare = (p: string) => p.slice(0, p.length - extname(p).length);
|
||||
const found = all.find((p) => p === t || bare(p) === t) ?? all.find((p) => basename(p) === t || basename(bare(p)) === t || p.endsWith(`/${t}`) || p.includes(`${t}/`));
|
||||
if (!found) throw new Error(`no take "${name}" under media/ (${all.join(", ") || "none"})`);
|
||||
if (!found) throw new Error(`no take "${name}" under media/ or footage/ (${all.join(", ") || "none"})`);
|
||||
return found;
|
||||
}
|
||||
|
||||
@@ -119,132 +124,103 @@ function hearTake(take: string, out: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A take's own jump cuts (raea media cuts, every frame decoded: 43 s for a 4-minute take on a box), found once per take
|
||||
* and kept by its path, size and time in raea's cache, so the second `raea cut` on a take doesn't decode it again
|
||||
* (12-04: three cuts on one take in a step ran past a box step's 3 minutes, and the run stopped with nothing made) */
|
||||
function jumpCuts(take: string): number[] {
|
||||
const file = at(take);
|
||||
let kept = "";
|
||||
try {
|
||||
const s = statSync(file);
|
||||
const dir = `${process.env.XDG_CACHE_HOME || `${homedir()}/.cache`}/raea/cuts`;
|
||||
kept = `${dir}/${createHash("sha1").update(`${realpathSync(file)}|${s.size}|${s.mtimeMs}|0.08`).digest("hex")}.json`;
|
||||
if (existsSync(kept)) return JSON.parse(readFileSync(kept, "utf8")) as number[];
|
||||
} catch {
|
||||
kept = "";
|
||||
}
|
||||
const cuts = (engineJson(["media", "cuts", file, "--threshold", "0.08"]).cuts as { at: number }[]).map((c) => c.at);
|
||||
if (kept)
|
||||
try {
|
||||
mkdirSync(dirname(kept), { recursive: true });
|
||||
writeFileSync(kept, JSON.stringify(cuts));
|
||||
} catch {
|
||||
// a cache that can't be written costs the next cut the decode, nothing else
|
||||
}
|
||||
return cuts;
|
||||
}
|
||||
|
||||
/** Where to cut a take for each line: found word for word in its transcript, in order (a line that follows the last one
|
||||
* in the take joins its clip), else where 70% of its words are said in a window its length (and a note says so); each
|
||||
* cut inside the pauses around it, off the take's own jump cuts, on the take's frame grid. [from, to, said] in the
|
||||
* take's seconds. */
|
||||
function cutPlan(take: string, ws: Word[], lines: string[]): { plan: [number, number, string][]; notes: string[] } {
|
||||
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu, "");
|
||||
const toks = ws.map((w) => norm(w.text).trim());
|
||||
// a sound-only take has no jump cuts to keep off, and its grid is the edit's usual 30 (a probe has no video fps)
|
||||
const cuts = isAudio(take) ? [] : jumpCuts(take);
|
||||
const fps = (engineJson(["media", "probe", at(take)]).video?.fps as number) || 30;
|
||||
let from = 0;
|
||||
const spans: [number, number][] = [];
|
||||
const notes: string[] = [];
|
||||
lines.forEach((line, k) => {
|
||||
const want = norm(line).split(/\s+/).filter(Boolean);
|
||||
if (!want.length) throw new Error(`line ${k + 1} is empty`);
|
||||
const fits = (i: number) => want.every((t, o) => toks[i + o] === t);
|
||||
const close = () => {
|
||||
const n = want.length;
|
||||
if (n < 3 || toks.length < n) return undefined;
|
||||
const score = (i: number) => want.filter((t) => toks.slice(i, i + n).includes(t)).length;
|
||||
let best = 0;
|
||||
for (let i = 1; i <= toks.length - n; i++) {
|
||||
const [s, b] = [score(i), score(best)];
|
||||
if (s > b || (s === b && Math.abs(i - from) < Math.abs(best - from))) best = i;
|
||||
}
|
||||
return score(best) * 10 >= n * 7 ? best : undefined;
|
||||
};
|
||||
let exact: number | undefined;
|
||||
for (let i = from; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
|
||||
for (let i = 0; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
|
||||
const i = exact ?? close();
|
||||
if (i === undefined) {
|
||||
const near = toks.flatMap((t, n) => (t === want[0] ? [ws.slice(n, n + 10).map((w) => w.text).join(" ")] : [])).slice(0, 3);
|
||||
throw new Error(`line ${k + 1} isn't in the transcript word for word: "${line}"; it says near there: ${near.length ? near.join(" | ") : "(no match for its first word)"}`);
|
||||
}
|
||||
const j = Math.min(i + want.length - 1, toks.length - 1);
|
||||
if (exact === undefined) notes.push(`line ${k + 1} isn't said word for word; cut where the take says "${ws.slice(i, j + 1).map((w) => w.text).join(" ")}"`);
|
||||
from = j + 1;
|
||||
const last = spans[spans.length - 1];
|
||||
if (last && last[1] + 1 === i) last[1] = j;
|
||||
else spans.push([i, j]);
|
||||
});
|
||||
const sf = 1 / fps;
|
||||
const plan = spans.map(([i, j], k): [number, number, string] => {
|
||||
const before = i > 0 ? ws[i].from - ws[i - 1].to : 0.4;
|
||||
const after = j + 1 < ws.length ? ws[j + 1].from - ws[j].to : 0.6;
|
||||
// transcript word ends run early: a generous tail (more on the last line), a short lead-in, both inside the pause
|
||||
let a = ws[i].from - Math.min(before * 0.6, 0.12);
|
||||
let b = ws[j].to + Math.min(after * 0.7, k + 1 === spans.length ? 0.35 : 0.22);
|
||||
// a jump cut in the take near a join: start one take frame after it (or end one before), never on it, or the
|
||||
// other shot's last frame can show
|
||||
const ca = cuts.find((c) => Math.abs(c - a) <= 0.25 && c <= ws[i].from + 0.05);
|
||||
if (ca !== undefined) a = Math.max(a, ca + sf);
|
||||
const cb = cuts.find((c) => Math.abs(c - b) <= 0.25 && c >= ws[j].to - 0.05);
|
||||
if (cb !== undefined) b = Math.min(b, cb - sf);
|
||||
return [Math.ceil(Math.max(a, 0) * fps) / fps, Math.floor(b * fps) / fps, ws.slice(i, j + 1).map((w) => w.text).join(" ")];
|
||||
});
|
||||
return { plan, notes };
|
||||
}
|
||||
// how each line is timed (cutplan.ts): the light copy, the take's jump cuts and sound level, pace.ts
|
||||
const { cutPlan, takeLevels } = timing({ at, engineRun, engineJson, isAudio });
|
||||
|
||||
/** A clip's length in the edit's frames: cuts.ts's `frames` */
|
||||
const framesOf = (from: number, to: number, fps: number) => Math.max(1, Math.round((to - from) * fps));
|
||||
const ms = (s: number) => Math.round(s * 1000) / 1000;
|
||||
|
||||
type Clip = { take: string; file: string; from: number; to: number; line: string; kind?: "video" | "audio" };
|
||||
type Clip = { take: string; file: string; from: number; to: number; line: string; kind?: "video" | "audio"; gainDb?: number; jump?: boolean };
|
||||
/** a cutaway: a picture laid over the join after clip `after` (its index in the cut), `l` seconds over that clip's end
|
||||
* (its sound runs on under it: an L cut) and `j` over the next one's start (whose sound starts under it: a J cut) */
|
||||
type Cutaway = Clip & { after: number; l: number; j: number };
|
||||
|
||||
/** `raea cut`'s host step: the clips for the lines (or --at spans), the words in the edit's frames, and what was cut */
|
||||
function cut(a: { take: string; lines: string[]; spans: number[][]; keep: Clip[] }) {
|
||||
/** how `raea cut` is asked to cut */
|
||||
type CutAsk = { take: string; lines: string[]; spans: number[][]; keep: Clip[]; cutaways?: Cutaway[]; cutaway?: boolean; j?: number; breath?: number; keepPauses?: boolean; gain?: boolean };
|
||||
|
||||
/** A take's words with their edges on their sound (pace.ts toSound): for the timeline's words, and a clip's level */
|
||||
function heardWords(file: string): Word[] {
|
||||
return toSound(words(file), takeLevels(file));
|
||||
}
|
||||
|
||||
/** `raea cut`'s host step: the clips for the lines (or --at spans) paced (pace.ts), their levels evened and jump cuts
|
||||
* marked, the words in the edit's frames, and what was cut */
|
||||
function cut(a: CutAsk) {
|
||||
const file = takeOf(a.take);
|
||||
if (!a.lines.length && !a.spans.length) throw new Error(`cut needs lines ("what's said") or spans (--at A-B, in the take's seconds)`);
|
||||
const edit = shape();
|
||||
const stem = basename(file, extname(file));
|
||||
const kind = isAudio(file) ? "audio" as const : "video" as const;
|
||||
const clips: Clip[] = [...a.keep];
|
||||
let notes: string[] = [];
|
||||
let clips: Clip[] = [...a.keep];
|
||||
const cutaways: Cutaway[] = [...(a.cutaways ?? [])];
|
||||
const seconds = (cs: Clip[]) => cs.reduce((n, c) => n + framesOf(c.from, c.to, edit.fps), 0) / edit.fps;
|
||||
// the breath kept at a join: 40% before a line's first sound, 60% after its last
|
||||
const b = a.breath;
|
||||
const o: PaceOptions = { fps: edit.fps, keepPauses: a.keepPauses, ...(b !== undefined ? { lead: b * 0.4, tail: b * 0.6, sentence: b * 0.6 + 0.08 } : {}) };
|
||||
const notes: string[] = [];
|
||||
let trims: Trim[] = [];
|
||||
let before = 0;
|
||||
if (a.lines.length) {
|
||||
const r = cutPlan(file, words(file, true), a.lines);
|
||||
notes = r.notes;
|
||||
for (const [from, to, line] of r.plan) clips.push({ take: stem, file, from: ms(from), to: ms(to), line, kind });
|
||||
const r = cutPlan(file, words(file, true), a.lines, o, seconds(clips));
|
||||
notes.push(...r.notes);
|
||||
trims = r.trims;
|
||||
// what the lines would have run to cut as said, from each one's first word to its last
|
||||
const ws = heardWords(file);
|
||||
before = linesIn(ws, a.lines).spans.reduce((n, [i, j]) => n + ws[j].to - ws[i].from + 0.4, 0);
|
||||
for (const p of r.pieces) {
|
||||
clips.push({ take: stem, file, from: ms(p.from), to: ms(p.to), line: p.line, kind });
|
||||
if (p.tight) notes.push(`"${p.line.slice(0, 40)}" has no pause at one end (its words run on): that end is cut between two words; look at it`);
|
||||
}
|
||||
}
|
||||
const { dur } = probeOf(file);
|
||||
for (const [s, e] of a.spans) {
|
||||
const [from, to] = [Math.max(s, 0), dur > 0 ? Math.min(e, dur) : e];
|
||||
if (!(to > from)) throw new Error(`the span ${s}-${e} is outside ${file} (${dur.toFixed(1)} s)`);
|
||||
const line = words(file).filter((w) => w.from >= from - 0.02 && w.to <= to + 0.08).map((w) => w.text).join(" ");
|
||||
if (a.cutaway) {
|
||||
const k = clips.length - 1;
|
||||
if (k < 0) throw new Error("a cutaway is laid over the cut's clips: cut a line first, then the cutaway with --append");
|
||||
const j = Math.min(Math.max(a.j ?? 0, 0), to - from);
|
||||
const l = ms(to - from - j);
|
||||
if (l > clips[k].to - clips[k].from) throw new Error(`the cutaway runs ${l.toFixed(2)} s over the last clip's end, and it's ${(clips[k].to - clips[k].from).toFixed(2)} s long: give it less, or --j to put some over the next line`);
|
||||
cutaways.push({ take: stem, file, from: ms(from), to: ms(to), line: "", kind: "video", after: k, l, j: ms(j) });
|
||||
continue;
|
||||
}
|
||||
const line = heardWords(file).filter((w) => w.from >= from - 0.02 && w.to <= to + 0.08).map((w) => w.text).join(" ");
|
||||
clips.push({ take: stem, file, from: ms(from), to: ms(to), line, kind });
|
||||
}
|
||||
// the words in the edit's frames, for captions (useWords())
|
||||
// a jump cut is hidden by a cutaway over its join; the rest are marked for the edit to reframe
|
||||
clips = markJumps(clips, edit.fps).map((c, k) => (c.jump && cutaways.some((x) => x.after === k - 1) ? (({ jump: _, ...r }) => r)(c) : c));
|
||||
if (a.gain !== false)
|
||||
clips = evenLevels(clips, (c) => {
|
||||
const inside = heardWords(c.file).filter((w) => w.to > c.from && w.from < c.to).map((w) => ({ ...w, from: Math.max(w.from, c.from), to: Math.min(w.to, c.to) }));
|
||||
return inside.length ? { db: speechOf(takeLevels(c.file), inside), seconds: inside.reduce((n, w) => n + w.to - w.from, 0) } : null;
|
||||
});
|
||||
// the words in the edit's frames, for captions (useWords()): each word that sounds inside its clip
|
||||
let t = 0;
|
||||
const timeline: { text: string; from: number; to: number }[] = [];
|
||||
const said: string[] = [];
|
||||
clips.forEach((c, k) => {
|
||||
const n = framesOf(c.from, c.to, edit.fps);
|
||||
const f = (s: number) => t + Math.round((s - c.from) * edit.fps);
|
||||
for (const w of words(c.file)) if (w.from >= c.from - 0.02 && w.to <= c.to + 0.08) timeline.push({ text: w.text, from: Math.max(f(w.from), t), to: Math.max(Math.min(f(w.to), t + n), f(w.from) + 1) });
|
||||
said.push(`${String(k + 1).padStart(2)} ${(t / edit.fps).toFixed(2).padStart(5)}-${((t + n) / edit.fps).toFixed(2).padStart(5)} s ${c.take} "${c.line}"`);
|
||||
for (const w of heardWords(c.file)) if ((w.from + w.to) / 2 >= c.from && (w.from + w.to) / 2 <= c.to) timeline.push({ text: w.text, from: Math.max(f(w.from), t), to: Math.max(Math.min(f(w.to), t + n), Math.max(f(w.from), t) + 1) });
|
||||
const marks = [c.jump ? "jump" : "", c.gainDb ? `${c.gainDb > 0 ? "+" : ""}${c.gainDb} dB` : ""].filter(Boolean).join(", ");
|
||||
said.push(`${String(k + 1).padStart(2)} ${(t / edit.fps).toFixed(2).padStart(5)}-${((t + n) / edit.fps).toFixed(2).padStart(5)} s ${c.take} "${c.line}"${marks ? ` (${marks})` : ""}`);
|
||||
t += n;
|
||||
});
|
||||
const head = `cuts.ts: ${clips.length} clips, ${(t / edit.fps).toFixed(1)} s (${t} frames at ${edit.fps} fps); words.json for captions`;
|
||||
return { edit, cuts: clips, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...notes.map((n) => `note: ${n}`)].join("\n") };
|
||||
for (const x of cutaways) said.push(` cutaway ${x.take} ${x.from.toFixed(2)}-${x.to.toFixed(2)} s over the join after clip ${x.after + 1}: ${x.l.toFixed(2)} s before it${x.j ? `, ${x.j.toFixed(2)} s after` : ""}`);
|
||||
const cutOut = trims.filter((x) => x.kind !== "pause");
|
||||
const pauses = trims.filter((x) => x.kind === "pause");
|
||||
const paced = [
|
||||
pauses.length ? `${pauses.length} long pause${pauses.length === 1 ? "" : "s"} cut to a breath (${pauses.reduce((n, x) => n + x.seconds, 0).toFixed(1)} s out)` : "",
|
||||
...cutOut.map((x) => `${x.kind} "${x.said}" at ${x.at.toFixed(2)} s out`),
|
||||
].filter(Boolean);
|
||||
const head = `cuts.ts: ${clips.length} clips, ${(t / edit.fps).toFixed(1)} s (${t} frames at ${edit.fps} fps)${before ? `; the lines as said ran ${before.toFixed(1)} s` : ""}; words.json for captions`;
|
||||
const tail = [
|
||||
...(paced.length ? [`paced: ${paced.join("; ")} (--keep-pauses keeps them)`] : []),
|
||||
...(clips.some((c) => c.jump) ? ["jump: a clip marked jump follows the same take with its time skipped: reframe it (punchIn(i) in cuts.ts), or lay a cutaway over the join"] : []),
|
||||
];
|
||||
return { edit, cuts: clips, cutaways, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...tail, ...notes.map((n) => `note: ${n}`)].join("\n") };
|
||||
}
|
||||
|
||||
/** raea-perceive, as `raea song` finds it (raea-io-assets perceive_bin): $RAEA_PERCEIVE, else beside raea, else on PATH */
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
// The timing of `raea cut` (12-05, Shane: "when we assemble the clips or video footage we should be hyper focused on
|
||||
// framing and timing. both seem to go wayside or not even done ... it could be done procedurally"). The agent chooses
|
||||
// the lines and their order; this times them, from the take's words and its sound level every 10 ms, as a short-form
|
||||
// editor would (auto-editor's dead-space pass, a breath kept at each join, loudness matched per line):
|
||||
//
|
||||
// toSound each word's edges moved onto its sound: a transcriber's word times run into the pauses around it
|
||||
// (parakeet's 80 ms frames: "question?" timed 2.88-4.16 s and said 2.63-3.18 s), so a cut on them keeps
|
||||
// dead air, and captions show a word after it's said
|
||||
// joins every cut point sits in quiet by the sound check's own measure (sdk/goal packs/sound.ts: 18 dB under the
|
||||
// line's speech, or within 6 dB of a street's floor), a breath kept: ~0.06 s before a line's first sound,
|
||||
// ~0.10 s after its last (0.18 s after a sentence's end), so the join between two lines is ~0.16-0.24 s
|
||||
// pauses a pause inside a line longer than 0.45 s (0.3 s in the cut's first 3 s, the hook) is cut down to a breath
|
||||
// fillers "um", "uh" and a false start ("I I think": the first "I") come out, only with quiet on both sides
|
||||
// level each clip's gainDb brings its speech to the cut's median (the sound check errs at 6 dB apart)
|
||||
// jump a clip that follows one of the same take with its time skipped is marked jump: the edit reframes it
|
||||
//
|
||||
// Pure: native.ts reads the words and levels and writes cuts.ts.
|
||||
|
||||
/** a word in its take's seconds */
|
||||
export type Word = { text: string; from: number; to: number };
|
||||
/** a take's sound level every 10 ms (dB), from `start` seconds */
|
||||
export type Levels = { start: number; db: number[] };
|
||||
/** a stretch of quiet in a take: from its first quiet 10 ms to the first sound after it (s) */
|
||||
export type Gap = { from: number; to: number };
|
||||
|
||||
export interface PaceOptions {
|
||||
/** the edit's frame rate: every cut point lands on its grid (30) */
|
||||
fps?: number;
|
||||
/** what's kept before a line's first sound (s): 0.06 */
|
||||
lead?: number;
|
||||
/** what's kept after a line's last sound (s): 0.10, so a join keeps ~0.16 s of breath */
|
||||
tail?: number;
|
||||
/** after a sentence's end (. ? !): 0.18 */
|
||||
sentence?: number;
|
||||
/** a pause inside a line longer than this is cut down to a breath (s): 0.45 */
|
||||
pause?: number;
|
||||
/** in the cut's first `hook` seconds: 0.3 */
|
||||
hookPause?: number;
|
||||
hook?: number;
|
||||
/** pauses inside lines, fillers and false starts left as they are */
|
||||
keepPauses?: boolean;
|
||||
}
|
||||
|
||||
const DEFAULTS = { fps: 30, lead: 0.06, tail: 0.1, sentence: 0.18, pause: 0.45, hookPause: 0.3, hook: 3, keepPauses: false };
|
||||
|
||||
/** as the sound check measures (packs/sound.ts): speech is its loud 10 ms frames (90th percentile), a take's floor its
|
||||
* quietest (10th), and quiet is 18 dB under the speech, or within 6 dB of the floor, never closer than 8 to the speech */
|
||||
const SPEECH_Q = 0.9;
|
||||
const FLOOR_Q = 0.1;
|
||||
export const quietUnder = (floor: number, ref: number) => Math.min(ref - 8, Math.max(ref - 18, floor + 6));
|
||||
/** the fewest quiet frames that make a gap: a cut point needs 20 ms of quiet either side (the check's 40 ms peak) */
|
||||
const LEAST = 5;
|
||||
/** a word's edge is moved onto its sound past this much quiet (s): a shorter quiet is a stop inside the word */
|
||||
const TRIM = 0.12;
|
||||
/** the least speech a clip cut out of a line holds (s): shorter, it joins its neighbour and keeps the pause */
|
||||
const MIN_RUN = 0.8;
|
||||
/** the least quiet after a word that is a pause a line can end in (s): shorter is a breath inside a sentence */
|
||||
const PAUSE_MIN = 0.15;
|
||||
/** the least speech a clip's level is measured on (s), and the most gain evening gives (dB) */
|
||||
const MEASURE = 1;
|
||||
const MOST_GAIN = 9;
|
||||
|
||||
export 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 idx = (l: Levels, t: number) => Math.round((t - l.start) * 100);
|
||||
const dbAt = (l: Levels, i: number) => l.db[i] ?? -100;
|
||||
const span = (l: Levels, a: number, b: number) => l.db.slice(Math.max(0, idx(l, a)), Math.max(0, idx(l, b)));
|
||||
|
||||
/** speech's level over words: their loud frames */
|
||||
export function speechOf(l: Levels, ws: Word[]): number {
|
||||
return pct(ws.flatMap((w) => span(l, w.from, w.to)), SPEECH_Q);
|
||||
}
|
||||
|
||||
/** the level under which a stretch around [a, b] is quiet, for speech at `ref` */
|
||||
export function underAt(l: Levels, a: number, b: number, ref: number): number {
|
||||
return quietUnder(pct(span(l, a - 0.5, b + 0.5), FLOOR_Q), ref);
|
||||
}
|
||||
|
||||
/** the quiet stretches of LEAST frames or more in [a, b] */
|
||||
export function gapsIn(l: Levels, under: number, a: number, b: number): Gap[] {
|
||||
const out: Gap[] = [];
|
||||
let run = -1;
|
||||
const i0 = Math.max(0, idx(l, a));
|
||||
const i1 = Math.min(l.db.length, idx(l, b));
|
||||
for (let i = i0; i <= i1; i++) {
|
||||
const quiet = i < i1 && dbAt(l, i) <= under;
|
||||
if (quiet && run < 0) run = i;
|
||||
if (!quiet && run >= 0) {
|
||||
if (i - run >= LEAST) out.push({ from: l.start + run / 100, to: l.start + i / 100 });
|
||||
run = -1;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const r3 = (t: number) => Math.round(t * 1000) / 1000;
|
||||
|
||||
/** words with their edges moved onto their sound: a word's start later past quiet it was timed into, its end earlier;
|
||||
* never shorter than 80 ms (a word the levels don't hear keeps its times). Speech is each word's neighbourhood's. */
|
||||
export function toSound(ws: Word[], l: Levels): Word[] {
|
||||
if (!l.db.length) return ws.map((w) => ({ ...w }));
|
||||
return ws.map((w) => {
|
||||
const ref = pct(span(l, w.from - 1, w.to + 1), SPEECH_Q);
|
||||
const under = underAt(l, w.from, w.to, ref);
|
||||
const loud = (i: number) => dbAt(l, i) > under;
|
||||
let a = idx(l, w.from);
|
||||
let b = idx(l, w.to) - 1;
|
||||
let a1 = a;
|
||||
while (a1 <= b && !loud(a1)) a1++;
|
||||
let b1 = b;
|
||||
while (b1 >= a1 && !loud(b1)) b1--;
|
||||
const at = (i: number, k: number) => ({ text: w.text, from: r3(l.start + i / 100), to: r3(l.start + k / 100) });
|
||||
// under 80 ms of sound: a word timed past its sound (parakeet put "that?" at 23.68-24.40 s, said by 23.68), so it
|
||||
// sits on the sound it has, or the sound it touches; a word with neither keeps its times (whispered, or masked)
|
||||
if (b1 - a1 < 7) {
|
||||
if (b1 >= a1) return at(Math.max(a, a1 - 2), Math.min(b + 1, Math.max(b1 + 3, a1 + 8)));
|
||||
if (loud(a - 1)) return at(a, Math.min(b + 1, a + 8));
|
||||
if (loud(b + 1)) return at(Math.max(a, b - 7), b + 1);
|
||||
return { ...w };
|
||||
}
|
||||
// a stretch of quiet shorter than TRIM at an edge is the word's own (a stop, a soft consonant): kept
|
||||
if ((a1 - a) / 100 >= TRIM) a = a1 - 2;
|
||||
if ((b - b1) / 100 >= TRIM) b = b1 + 2;
|
||||
return { text: w.text, from: r3(l.start + a / 100), to: r3(l.start + (b + 1) / 100) };
|
||||
});
|
||||
}
|
||||
|
||||
const FILLERS = new Set(["um", "umm", "uh", "uhm", "uhh", "erm", "er", "ah", "hmm", "mm", "mhm"]);
|
||||
const norm = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}']/gu, "");
|
||||
const endsSentence = (s: string) => /[.?!]["')\]]*$/.test(s.trim());
|
||||
|
||||
/** a stretch of a take a cut keeps: its words [first, last] (indexes into the take's words) and its in and out (s) */
|
||||
export type Piece = { words: [number, number]; from: number; to: number; line: string; jump?: boolean; gainDb?: number; tight?: boolean };
|
||||
|
||||
/** What's cut out of a line, said: a filler or a false start, or a pause made shorter. */
|
||||
export type Trim = { kind: "filler" | "false start" | "pause"; at: number; seconds: number; said: string };
|
||||
|
||||
/** The pieces a run of lines keeps, in order, each line given as its words [first, last] in the take, timed as above;
|
||||
* `start` is where the first of them lands in the edit (s), for the hook's tighter pauses. */
|
||||
export function pace(ws0: Word[], l: Levels, lines: [number, number][], o: PaceOptions = {}, start = 0): { pieces: Piece[]; trims: Trim[] } {
|
||||
const p = { ...DEFAULTS, ...o };
|
||||
const ws = toSound(ws0, l);
|
||||
const n = ws.length;
|
||||
const trims: Trim[] = [];
|
||||
const pieces: Piece[] = [];
|
||||
let t = start;
|
||||
const grid = (x: number, lo: number, hi: number) => {
|
||||
// the edit's frame nearest x that keeps inside [lo, hi], else the nearest frame
|
||||
const f = x * p.fps;
|
||||
const c = [Math.round(f), Math.floor(f), Math.ceil(f)].map((k) => k / p.fps).filter((v) => v >= lo - 1e-6 && v <= hi + 1e-6);
|
||||
return r3(c.length ? c[0] : Math.round(f) / p.fps);
|
||||
};
|
||||
for (const [i, j0] of lines) {
|
||||
const ref = speechOf(l, ws.slice(i, j0 + 1));
|
||||
const under = underAt(l, ws[i].from, ws[j0].to, ref);
|
||||
const mid = (w: Word) => Math.min(0.1, (w.to - w.from) / 2);
|
||||
/** the quiet between word k and k + 1 (k = -1: before the first; k = n - 1: after the last): the longest stretch */
|
||||
const gapAfter = (k: number): Gap | null => {
|
||||
const a = k < 0 ? Math.max(0, ws[0].from - 1) : ws[k].to - mid(ws[k]);
|
||||
const b = k + 1 >= n ? ws[n - 1].to + 1 : ws[k + 1].from + mid(ws[k + 1]);
|
||||
const gs = gapsIn(l, under, a, b);
|
||||
if (!gs.length) return null;
|
||||
if (k < 0) return gs[gs.length - 1];
|
||||
if (k + 1 >= n) return gs[0];
|
||||
return gs.reduce((x, y) => (y.to - y.from > x.to - x.from ? y : x));
|
||||
};
|
||||
// a cut between two words with no quiet between: halfway between their sounds, never past the transcript's own
|
||||
// boundary (12-05: "delivered" and "for" touched at 99.12 s, the halfway of their sounds was 99.20 s, and the clip
|
||||
// ended inside "for")
|
||||
const seam = (k: number) => {
|
||||
if (k < 0) return r3(Math.max(0, ws[0].from - 0.02));
|
||||
if (k + 1 >= n) return r3(ws[n - 1].to + 0.02);
|
||||
const mid = (ws[k].to + ws[k + 1].from) / 2;
|
||||
const [lo, hi] = [ws0[k].to, ws0[k + 1].from];
|
||||
if (lo > hi) return r3(hi);
|
||||
// the quietest 10 ms between them, the nearest the middle on a tie: two words with no pause between still dip
|
||||
// somewhere, and a cut halfway can land on the first one's tail (12-05: "platform." ran on to "Yeah" with no
|
||||
// quiet, and the cut halfway was 5 dB under the speech, the word's tail cut)
|
||||
let best = Math.min(hi, Math.max(lo, mid));
|
||||
let low = Infinity;
|
||||
for (let i = idx(l, lo); i <= idx(l, hi); i++) {
|
||||
const t = l.start + i / 100;
|
||||
const d = dbAt(l, i);
|
||||
if (d < low - 0.5 || (Math.abs(d - low) <= 0.5 && Math.abs(t - mid) < Math.abs(best - mid))) {
|
||||
if (d < low - 0.5) low = d;
|
||||
best = t;
|
||||
}
|
||||
}
|
||||
return r3(Math.min(hi, Math.max(lo, best)));
|
||||
};
|
||||
// a line that stops mid-sentence with no quiet after it ends where its sentence does, when that's three words or
|
||||
// fewer and 0.8 s away (12-05: "...and get them delivered" ran straight into "for free?")
|
||||
const pausesAfter = (k: number) => {
|
||||
const g = gapAfter(k);
|
||||
return !!g && g.to - g.from >= PAUSE_MIN;
|
||||
};
|
||||
let j = j0;
|
||||
if (!endsSentence(ws[j].text) && !pausesAfter(j))
|
||||
for (let e = j + 1; e < n && e <= j + 3 && ws[e].to - ws[j].to <= 0.8; e++)
|
||||
if (endsSentence(ws[e].text) && pausesAfter(e)) {
|
||||
j = e;
|
||||
break;
|
||||
}
|
||||
// where to cut in before word k, and out after word k: in the quiet beside it, a breath from its sound
|
||||
// never into the transcript's neighbour word, on the frame grid: the check reads the transcript's word times, so a
|
||||
// cut in a short quiet its words don't have lands inside a word for it (12-05: "for" at 99.12 s, the cut at 99.20 s)
|
||||
// and holding its own word whole by the transcript too (12-05: "Available" 171.84-172.24 s by its words, its sound
|
||||
// over by 172.0 s, the cut at 172.03 s: inside the word for the check)
|
||||
const fl = (t: number) => Math.floor(t * p.fps + 1e-6) / p.fps;
|
||||
const ce = (t: number) => Math.ceil(t * p.fps - 1e-6) / p.fps;
|
||||
const notBefore = (k: number, at: number) => r3(Math.max(Math.min(at, fl(ws0[k].from)), k > 0 ? ce(ws0[k - 1].to) : 0));
|
||||
const notAfter = (k: number, at: number) => r3(Math.min(Math.max(at, ce(ws0[k].to)), k + 1 < n ? fl(ws0[k + 1].from) : Infinity));
|
||||
const cutIn = (k: number) => {
|
||||
const g = gapAfter(k - 1);
|
||||
if (!g) return { at: notBefore(k, grid(seam(k - 1), 0, Infinity)), tight: true };
|
||||
const [lo, hi] = [g.from + 0.02, g.to - 0.03];
|
||||
return { at: notBefore(k, grid(Math.min(hi, Math.max(lo, g.to - p.lead)), lo, hi)), tight: false };
|
||||
};
|
||||
const cutOut = (k: number) => {
|
||||
const g = gapAfter(k);
|
||||
if (!g) return { at: notAfter(k, grid(seam(k), 0, Infinity)), tight: true };
|
||||
const [lo, hi] = [g.from + 0.02, g.to - 0.03];
|
||||
const keep = endsSentence(ws[k].text) ? p.sentence : p.tail;
|
||||
return { at: notAfter(k, grid(Math.min(hi, Math.max(lo, g.from + keep)), lo, hi)), tight: false };
|
||||
};
|
||||
// the words kept: fillers and false starts with quiet both sides come out
|
||||
const keep = new Array<boolean>(j - i + 1).fill(true);
|
||||
const quietBoth = (a: number, b: number) => (a === i || gapAfter(a - 1) !== null) && (b === j || gapAfter(b) !== null);
|
||||
if (!p.keepPauses) {
|
||||
for (let k = i; k <= j; k++) {
|
||||
if (FILLERS.has(norm(ws[k].text)) && j > i && quietBoth(k, k)) {
|
||||
keep[k - i] = false;
|
||||
trims.push({ kind: "filler", at: ws[k].from, seconds: r3(ws[k].to - ws[k].from), said: ws[k].text });
|
||||
}
|
||||
}
|
||||
for (let k = i; k <= j; k++)
|
||||
for (let m = 1; m <= 3 && k + 2 * m - 1 <= j; m++) {
|
||||
const same = Array.from({ length: m }, (_, q) => norm(ws[k + q].text) === norm(ws[k + m + q].text) && norm(ws[k + q].text) !== "").every(Boolean);
|
||||
if (same && keep[k - i] && quietBoth(k, k + m - 1)) {
|
||||
for (let q = 0; q < m; q++) keep[k + q - i] = false;
|
||||
trims.push({ kind: "false start", at: ws[k].from, seconds: r3(ws[k + m - 1].to - ws[k].from), said: ws.slice(k, k + m).map((w) => w.text).join(" ") });
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// runs of kept words, split again at a long pause (shorter in the hook: the cut's first seconds)
|
||||
const runs: [number, number][] = [];
|
||||
const paused = new Map<number, Trim>(); // the pause after word k, cut down
|
||||
for (let k = i; k <= j; k++) {
|
||||
if (!keep[k - i]) continue;
|
||||
const last = runs[runs.length - 1];
|
||||
const cut = last && last[1] === k - 1 && !p.keepPauses ? long(k - 1, t + ws[k - 1].to - ws[i].from) : null;
|
||||
if (last && last[1] === k - 1 && !cut) last[1] = k;
|
||||
else {
|
||||
if (cut) paused.set(k - 1, cut);
|
||||
runs.push([k, k]);
|
||||
}
|
||||
}
|
||||
// a run under MIN_RUN of speech would flick by as a clip of its own (12-05: "Available", 0.47 s between two cut
|
||||
// pauses): it keeps a pause and joins its neighbour across the shorter one
|
||||
for (let r = 0; r < runs.length && runs.length > 1; r++) {
|
||||
const [a, b] = runs[r];
|
||||
if (ws[b].to - ws[a].from >= MIN_RUN) continue;
|
||||
const left = r > 0 && runs[r - 1][1] === a - 1 ? paused.get(a - 1) : undefined;
|
||||
const right = r + 1 < runs.length && runs[r + 1][0] === b + 1 ? paused.get(b) : undefined;
|
||||
if (!left && !right) continue;
|
||||
if (left && (!right || left.seconds <= right.seconds)) {
|
||||
runs[r - 1][1] = b;
|
||||
runs.splice(r, 1);
|
||||
paused.delete(a - 1);
|
||||
r = Math.max(-1, r - 2);
|
||||
} else {
|
||||
runs[r][1] = runs[r + 1][1];
|
||||
runs.splice(r + 1, 1);
|
||||
paused.delete(b);
|
||||
r -= 1;
|
||||
}
|
||||
}
|
||||
trims.push(...paused.values());
|
||||
for (const [a, b] of runs) {
|
||||
const ci = cutIn(a);
|
||||
const co = cutOut(b);
|
||||
if (co.at <= ci.at) continue;
|
||||
pieces.push({ words: [a, b], from: ci.at, to: co.at, line: ws0.slice(a, b + 1).map((w) => w.text).join(" "), ...(ci.tight || co.tight ? { tight: true } : {}) });
|
||||
t += co.at - ci.at;
|
||||
}
|
||||
/** the pause after word k is longer than the cut keeps there (`at`: where it falls in the edit) */
|
||||
function long(k: number, at: number): Trim | null {
|
||||
const g = gapAfter(k);
|
||||
if (!g || g.to - g.from <= (at < p.hook ? p.hookPause : p.pause)) return null;
|
||||
return { kind: "pause", at: r3(g.from), seconds: r3(g.to - g.from), said: `${ws[k].text} | ${ws[k + 1].text}` };
|
||||
}
|
||||
}
|
||||
// two lines that follow each other in the take with a short pause between are one clip: no cut where none is needed
|
||||
// (two cut points in a pause shorter than the breath they keep would play its middle twice)
|
||||
for (let k = pieces.length - 1; k > 0; k--) {
|
||||
const [a, b] = [pieces[k - 1], pieces[k]];
|
||||
const between = b.from - a.to;
|
||||
const inHook = pieces.slice(0, k).reduce((s, x) => s + x.to - x.from, start) < p.hook;
|
||||
if (b.words[0] === a.words[1] + 1 && between <= (inHook ? p.hookPause : p.pause) - p.lead - p.tail) {
|
||||
pieces.splice(k - 1, 2, { ...a, words: [a.words[0], b.words[1]], to: b.to, line: `${a.line} ${b.line}`, ...(a.tight || b.tight ? { tight: true } : {}) });
|
||||
}
|
||||
}
|
||||
// a pause made shorter: what was taken out of it is the pause less what the two cuts keep
|
||||
for (const x of trims) if (x.kind === "pause") x.seconds = r3(Math.max(0, x.seconds - p.lead - p.tail));
|
||||
return { pieces, trims };
|
||||
}
|
||||
|
||||
/** Which words of a take each line is: found word for word in its transcript, in order, else where 70% of its words
|
||||
* are said in a window its length (and a note says so), that window's ends trimmed of words the line doesn't have (a
|
||||
* filler before it, the next line's first word after it). Words are compared as letters and digits, a word's digits
|
||||
* apart from its letters ("about$1,200." is "about 1200"). [first, last] word of each line, in the take's words. */
|
||||
export function linesIn(ws: { text: string }[], lines: string[]): { spans: [number, number][]; notes: string[] } {
|
||||
const parts = (s: string) => s.toLowerCase().replace(/[^\p{L}\p{N}'\s]/gu, "").replace(/(\p{L})(\p{N})|(\p{N})(\p{L})/gu, "$1$3 $2$4").split(/\s+/).filter(Boolean);
|
||||
// the take's words as tokens, each with the word it's part of
|
||||
const toks: string[] = [];
|
||||
const owner: number[] = [];
|
||||
ws.forEach((w, k) => parts(w.text).forEach((t) => (toks.push(t), owner.push(k))));
|
||||
let from = 0;
|
||||
const spans: [number, number][] = [];
|
||||
const notes: string[] = [];
|
||||
lines.forEach((line, k) => {
|
||||
const want = parts(line);
|
||||
if (!want.length) throw new Error(`line ${k + 1} is empty`);
|
||||
const fits = (i: number) => want.every((t, o) => toks[i + o] === t);
|
||||
const close = () => {
|
||||
const n = want.length;
|
||||
if (n < 3 || toks.length < n) return undefined;
|
||||
const score = (i: number) => want.filter((t) => toks.slice(i, i + n).includes(t)).length;
|
||||
let best = 0;
|
||||
for (let i = 1; i <= toks.length - n; i++) {
|
||||
const [s, b] = [score(i), score(best)];
|
||||
if (s > b || (s === b && Math.abs(i - from) < Math.abs(best - from))) best = i;
|
||||
}
|
||||
return score(best) * 10 >= n * 7 ? best : undefined;
|
||||
};
|
||||
let exact: number | undefined;
|
||||
for (let i = from; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
|
||||
for (let i = 0; i < toks.length && exact === undefined; i++) if (fits(i)) exact = i;
|
||||
let i = exact ?? close();
|
||||
if (i === undefined) {
|
||||
const near = toks.flatMap((t, n) => (t === want[0] ? [ws.slice(owner[n], owner[n] + 10).map((w) => w.text).join(" ")] : [])).slice(0, 3);
|
||||
throw new Error(`line ${k + 1} isn't in the transcript word for word: "${line}"; it says near there: ${near.length ? near.join(" | ") : "(no match for its first word)"}`);
|
||||
}
|
||||
let j = Math.min(i + want.length - 1, toks.length - 1);
|
||||
if (exact === undefined) {
|
||||
while (i < j && !want.includes(toks[i])) i++;
|
||||
while (j > i && !want.includes(toks[j])) j--;
|
||||
}
|
||||
const [a, b] = [owner[i], owner[j]];
|
||||
if (exact === undefined) notes.push(`line ${k + 1} isn't said word for word; cut where the take says "${ws.slice(a, b + 1).map((w) => w.text).join(" ")}"`);
|
||||
from = j + 1;
|
||||
spans.push([a, b]);
|
||||
});
|
||||
return { spans, notes };
|
||||
}
|
||||
|
||||
/** a clip as cuts.ts holds it */
|
||||
export type Clip = { take: string; file: string; from: number; to: number; line: string; kind?: "video" | "audio"; gainDb?: number; jump?: boolean };
|
||||
|
||||
/** each clip that follows another of the same take with its time skipped (forward or back): jump, so the edit reframes it
|
||||
* (a punch-in, every other one, or a cutaway over the join); the rest lose the mark */
|
||||
export function markJumps<C extends Clip>(clips: C[], fps = 30): C[] {
|
||||
return clips.map((c, k) => {
|
||||
const prev = clips[k - 1];
|
||||
const { jump: _, ...rest } = c;
|
||||
const jump = !!prev && prev.file === c.file && Math.abs(c.from - prev.to) > 1.5 / fps;
|
||||
return (jump ? { ...rest, jump: true } : rest) as C;
|
||||
});
|
||||
}
|
||||
|
||||
/** the gainDb that brings each voice clip's speech to the clips' median, 1 dB or more off it, within +-MOST_GAIN dB.
|
||||
* A level is measured only on MEASURE s of speech or more (one word's level is mostly its edges); a shorter clip takes
|
||||
* the gain of the nearest measured clip of its own take, so one take never jumps in level at a join (12-05: a 0.47 s
|
||||
* "Available" was given +12 dB between two clips at 0). `levelOf` gives a clip's speech level and its seconds of words. */
|
||||
export function evenLevels<C extends Clip>(clips: C[], levelOf: (c: C) => { db: number; seconds: number } | null): C[] {
|
||||
const lv = clips.map((c) => {
|
||||
const x = c.to - c.from >= 0.4 ? levelOf(c) : null;
|
||||
return x && x.db > -90 && x.seconds >= MEASURE ? x.db : null;
|
||||
});
|
||||
const known = lv.filter((x): x is number => x !== null);
|
||||
if (known.length < 2) return clips;
|
||||
const mid = pct(known, 0.5);
|
||||
const gain = (k: number) => Math.max(-MOST_GAIN, Math.min(MOST_GAIN, Math.round((mid - (lv[k] as number)) * 2) / 2));
|
||||
return clips.map((c, k) => {
|
||||
const { gainDb: _, ...rest } = c;
|
||||
let g: number | null = lv[k] !== null ? gain(k) : null;
|
||||
if (g === null) {
|
||||
// the nearest measured clip of the same take, either side
|
||||
for (let d = 1; d < clips.length && g === null; d++)
|
||||
for (const q of [k - d, k + d]) if (q >= 0 && q < clips.length && lv[q] !== null && clips[q].file === c.file && g === null) g = gain(q);
|
||||
}
|
||||
if (g === null) return c;
|
||||
return (Math.abs(g) >= 1 ? { ...rest, gainDb: g } : rest) as C;
|
||||
});
|
||||
}
|
||||
|
||||
/** the level every 10 ms of 16-bit PCM samples */
|
||||
export function levelsOf(pcm: Int16Array, rate = 16000): number[] {
|
||||
const hop = Math.round(rate / 100);
|
||||
const out: number[] = [];
|
||||
for (let s = 0; s + hop <= pcm.length; s += hop) {
|
||||
let e = 0;
|
||||
for (let k = s; k < s + hop; k++) e += (pcm[k] / 32768) ** 2;
|
||||
out.push(Math.round(10 * Math.log10(e / hop + 1e-10) * 10) / 10);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** a mono 16-bit WAV's samples and rate (`raea media audio --mono` writes one) */
|
||||
export function wavSamples(buf: Uint8Array): { pcm: Int16Array; rate: number } {
|
||||
const v = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
const tag = (o: number) => String.fromCharCode(buf[o], buf[o + 1], buf[o + 2], buf[o + 3]);
|
||||
if (tag(0) !== "RIFF" || tag(8) !== "WAVE") throw new Error("not a WAV file");
|
||||
let rate = 16000;
|
||||
for (let o = 12; o + 8 <= buf.length; ) {
|
||||
const id = tag(o);
|
||||
const size = v.getUint32(o + 4, true);
|
||||
if (id === "fmt ") {
|
||||
if (v.getUint16(o + 10, true) !== 1 || v.getUint16(o + 22, true) !== 16) throw new Error("not mono 16-bit PCM");
|
||||
rate = v.getUint32(o + 12, true);
|
||||
}
|
||||
if (id === "data") {
|
||||
const n = Math.floor(Math.min(size, buf.length - o - 8) / 2);
|
||||
const copy = buf.slice(o + 8, o + 8 + n * 2);
|
||||
return { pcm: new Int16Array(copy.buffer, copy.byteOffset, n), rate };
|
||||
}
|
||||
o += 8 + size + (size % 2);
|
||||
}
|
||||
throw new Error("a WAV with no data");
|
||||
}
|
||||
@@ -22,6 +22,6 @@ export const REGISTRY: Record<string, Record<string, string>> = {
|
||||
}
|
||||
};
|
||||
export const TEMPLATE: Record<string, string> = {
|
||||
"edit.tsx": "// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),\n// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.\n// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.\nimport { AbsoluteFill, Audio, Composition, Series, Video, registerRoot } from \"raea\";\nimport { cuts, edit, frames, total } from \"./cuts\";\nimport { css } from \"./styles.gen\";\n\n// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's\n// (`raea brand SITE` writes brand/brand.css); delete it once the edit has clips.\nfunction Start() {\n return (\n <AbsoluteFill style={{ background: \"#14120f\", color: \"#f2ede4\", justifyContent: \"center\", padding: \"0 8%\", fontFamily: \"Helvetica, Arial, sans-serif\" }}>\n <div style={{ fontSize: edit.width * 0.11, fontWeight: 700, letterSpacing: \"-0.02em\" }}>raea</div>\n <div style={{ fontSize: edit.width * 0.04, marginTop: edit.width * 0.03, lineHeight: 1.4, opacity: 0.8 }}>\n No clips yet. Run raea cut on a take to put its footage in cuts.ts, and this edit plays it.\n </div>\n </AbsoluteFill>\n );\n}\n\nfunction Edit() {\n if (cuts.length === 0) return <Start />;\n return (\n <AbsoluteFill className=\"bg-brand-bg\">\n <style>{css}</style>\n <Series>\n {cuts.map((c, i) => (\n <Series.Sequence key={i} durationInFrames={frames(c)}>\n {/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with\n sound alone (a voice recording) plays under whatever you put in its place */}\n {c.kind === \"audio\" ? (\n <Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} />\n ) : (\n <Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\" }} />\n )}\n </Series.Sequence>\n ))}\n </Series>\n </AbsoluteFill>\n );\n}\n\nregisterRoot(() => <Composition id=\"edit\" component={Edit} width={edit.width} height={edit.height} fps={edit.fps} durationInFrames={total || edit.fps * 3} />);\n",
|
||||
"edit.tsx": "// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),\n// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.\n// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.\nimport { AbsoluteFill, Audio, Composition, Sequence, Series, Video, registerRoot } from \"raea\";\nimport { cutaways, cuts, edit, frames, punchIn, total } from \"./cuts\";\nimport { css } from \"./styles.gen\";\n\n// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's\n// (`raea brand SITE` writes brand/brand.css); delete it once the edit has clips.\nfunction Start() {\n return (\n <AbsoluteFill style={{ background: \"#14120f\", color: \"#f2ede4\", justifyContent: \"center\", padding: \"0 8%\", fontFamily: \"Helvetica, Arial, sans-serif\" }}>\n <div style={{ fontSize: edit.width * 0.11, fontWeight: 700, letterSpacing: \"-0.02em\" }}>raea</div>\n <div style={{ fontSize: edit.width * 0.04, marginTop: edit.width * 0.03, lineHeight: 1.4, opacity: 0.8 }}>\n No clips yet. Run raea cut on a take to put its footage in cuts.ts, and this edit plays it.\n </div>\n </AbsoluteFill>\n );\n}\n\nfunction Edit() {\n if (cuts.length === 0) return <Start />;\n return (\n <AbsoluteFill className=\"bg-brand-bg\">\n <style>{css}</style>\n <Series>\n {cuts.map((c, i) => (\n <Series.Sequence key={i} durationInFrames={frames(c)}>\n {/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with\n sound alone (a voice recording) plays under whatever you put in its place */}\n {c.kind === \"audio\" ? (\n <Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} />\n ) : (\n // a jump cut (c.jump: the same take with time skipped) reframes: punchIn(i) alternates 1 and 1.15\n <Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\", transform: `scale(${punchIn(i)})` }} />\n )}\n </Series.Sequence>\n ))}\n </Series>\n {/* cutaways (raea cut --cutaway): a picture over a join, muted, while the lines' sound runs under it */}\n {cutaways.map((c, i) => (\n <Sequence key={`away${i}`} from={c.start} durationInFrames={frames(c)}>\n <Video src={c.src} muted startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: \"100%\", height: \"100%\", objectFit: \"cover\" }} />\n </Sequence>\n ))}\n </AbsoluteFill>\n );\n}\n\nregisterRoot(() => <Composition id=\"edit\" component={Edit} width={edit.width} height={edit.height} fps={edit.fps} durationInFrames={total || edit.fps * 3} />);\n",
|
||||
"theme.css": "/* The Tailwind theme every raea project compiles with: class names (text-brand-accent, bg-brand-surface, font-brand,\n text-caption, rounded-brand) mapped onto the brand kit's variables (brand/brand.css, the --brand-* format).\n Nothing here is a colour, a font or a size of its own: change the brand, and every component follows. The kit's\n sizes are the website's, so on a 1080x1920 video they're scaled up (the kit's own note: about 2.5x). */\n@theme inline {\n --color-brand-accent: var(--brand-accent);\n --color-brand-bg: var(--brand-background);\n --color-brand-surface: var(--brand-background);\n --color-brand-on-surface: var(--brand-text);\n --color-brand-ink: var(--brand-background);\n --color-brand-on-accent: var(--brand-background);\n --color-brand-1: var(--brand-color-1);\n --color-brand-2: var(--brand-color-2);\n --color-brand-3: var(--brand-color-3);\n --font-brand: var(--brand-font-heading);\n --font-brand-body: var(--brand-font);\n --text-display: calc(var(--brand-h1-size) * 3);\n --text-title: calc(var(--brand-h2-size) * 2.5);\n --text-caption: calc(var(--brand-h2-size) * 2.5);\n --text-body: calc(var(--brand-p-size) * 2.5);\n --text-label: calc(var(--brand-h4-size) * 2.2);\n --radius-brand: var(--brand-radius);\n}\n"
|
||||
};
|
||||
@@ -1,8 +1,8 @@
|
||||
// The edit: a React composition rendered by raea (`raea render`). The clips come from cuts.ts (`raea cut` writes it),
|
||||
// the parts from components/ (`raea make component add` copies them in; they're yours to change), the look from brand/brand.css.
|
||||
// Change anything here: layout, timing, what plays when. `raea check` renders it and says what's wrong.
|
||||
import { AbsoluteFill, Audio, Composition, Series, Video, registerRoot } from "raea";
|
||||
import { cuts, edit, frames, total } from "./cuts";
|
||||
import { AbsoluteFill, Audio, Composition, Sequence, Series, Video, registerRoot } from "raea";
|
||||
import { cutaways, cuts, edit, frames, punchIn, total } from "./cuts";
|
||||
import { css } from "./styles.gen";
|
||||
|
||||
// Before any cuts: a card saying what comes next, three seconds long. Its colours are its own on purpose, not a brand's
|
||||
@@ -29,13 +29,20 @@ function Edit() {
|
||||
{/* a talking take: <FaceFrame>; a screen recording: <ScreenFit> (`raea frame TAKE` says which); a take with
|
||||
sound alone (a voice recording) plays under whatever you put in its place */}
|
||||
{c.kind === "audio" ? (
|
||||
<Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} />
|
||||
<Audio src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} />
|
||||
) : (
|
||||
<Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
|
||||
// a jump cut (c.jump: the same take with time skipped) reframes: punchIn(i) alternates 1 and 1.15
|
||||
<Video src={c.src} startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} gainDb={c.gainDb} style={{ width: "100%", height: "100%", objectFit: "cover", transform: `scale(${punchIn(i)})` }} />
|
||||
)}
|
||||
</Series.Sequence>
|
||||
))}
|
||||
</Series>
|
||||
{/* cutaways (raea cut --cutaway): a picture over a join, muted, while the lines' sound runs under it */}
|
||||
{cutaways.map((c, i) => (
|
||||
<Sequence key={`away${i}`} from={c.start} durationInFrames={frames(c)}>
|
||||
<Video src={c.src} muted startFrom={Math.round(c.from * edit.fps)} endAt={Math.round(c.to * edit.fps)} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
|
||||
</Sequence>
|
||||
))}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ ENV DEBIAN_FRONTEND=noninteractive
|
||||
RUN apt-get update -qq && apt-get install -y -qq --no-install-recommends \
|
||||
ca-certificates curl git git-lfs zstd xz-utils bzip2 unzip procps less ripgrep openssl sudo python3 \
|
||||
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools ffmpeg poppler-utils \
|
||||
xvfb x11vnc xdotool fonts-noto-color-emoji > /dev/null \
|
||||
xvfb x11vnc xdotool fonts-noto-color-emoji python3-opencv > /dev/null \
|
||||
&& for f in fonts-inter fonts-roboto fonts-open-sans fonts-lato fonts-montserrat fonts-noto-core fonts-ibm-plex \
|
||||
fonts-bebas-neue fonts-urw-base35 fonts-liberation2; do apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || echo "no $f"; done \
|
||||
&& curl -fsSLo /tmp/chrome.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \
|
||||
@@ -50,6 +50,11 @@ ARG AGENTS="antigravity-acp claude-acp kimi-code"
|
||||
RUN node server/agents.ts install $AGENTS
|
||||
COPY src src
|
||||
COPY image image
|
||||
# OpenCV's YuNet face detector (232 KB, MIT), for image/faces.py: prep finds each take's faces and components/Framed.tsx
|
||||
# crops on them (12-05: agents guessed each 9:16 crop and cut the speaker off at the edge); prep also copies the cut
|
||||
# components beside it (image/Cut.tsx, Shot, crop, Said, EndCard, brand, Title)
|
||||
RUN curl -fsSL -o /opt/yunet.onnx https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx \
|
||||
&& python3 -c "import cv2; cv2.FaceDetectorYN.create('/opt/yunet.onnx', '', (640, 360))" && chmod +x image/faces.py
|
||||
# raea's SDK files fixed after the release the image installs (image/sdk-overlay, by their path under share/raea/sdk),
|
||||
# each only while the installed file still has the fault, so a release with the fix keeps its own. 12-03: 0.1.17-rc4's
|
||||
# goal.ts named-imports spawn, which raea's runtime hasn't got, and every raea goal check on a box died (raea #329)
|
||||
|
||||
@@ -4,13 +4,14 @@
|
||||
#
|
||||
# MODAL_PROFILE=raea modal deploy deploy/modal/farm.py
|
||||
#
|
||||
# POST /v1/jobs?args=JSON[&gpus=N][&gpu=KIND][&max_usd=X] body: the project as a tar. {id}
|
||||
# POST /v1/jobs?args=JSON[&gpus=N][&gpu=KIND][&max_usd=X][&nv=1|0] body: the project as a tar. {id}
|
||||
# GET /v1/jobs/ID?from=N {log, next, exit?}, held up to 20 s for more
|
||||
# GET /v1/jobs/ID/out?as=zst|gz|tar the files the job made or changed; the job is removed
|
||||
# GET /v1/jobs/ID/media with media=1: the job's media outputs [{path, oid, size}],
|
||||
# left out of /out
|
||||
# POST /v1/jobs/ID/media {objects: [{path, oid, href, header}]} PUTs each to its signed URL in R2 (farm_media.py)
|
||||
# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid]}
|
||||
# POST /v1/blobs/have {objects: [{oid, size}]} which of a project's media the farm holds: {have: [oid],
|
||||
# links: 1} (links: it fetches an original of unknown size)
|
||||
# PUT /v1/blobs/OID?size=N one media file into the farm's cache, kept when it
|
||||
# hashes to OID (a box's project not in raea's LFS)
|
||||
# A job's folder may hold .raea-cloud-media.json: its media by Git LFS object id with URLs signed for it, fetched from
|
||||
@@ -813,7 +814,7 @@ def api():
|
||||
if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
|
||||
raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
|
||||
q = req.query_params
|
||||
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "cpus": min(int(q.get("cpus", JOB_CPUS)), CPUS), "kept": q.get("kept", "1") != "0", "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "cpus": min(int(q.get("cpus", JOB_CPUS)), CPUS), "kept": q.get("kept", "1") != "0", "gpu": q.get("gpu"), "nv": q.get("nv") if q.get("nv") in ("0", "1") else None, "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
|
||||
id = str(uuid.uuid4())
|
||||
work = f"{JOBS}/{id}/work"
|
||||
async with gate.use():
|
||||
@@ -848,7 +849,7 @@ def api():
|
||||
blob = f"{ROOT}/blobs/{oid}"
|
||||
if len(oid) == 64 and all(c in "0123456789abcdef" for c in oid) and os.path.exists(blob) and os.path.getsize(blob) == size:
|
||||
have.append(oid)
|
||||
return {"have": have}
|
||||
return {"have": have, "links": 1}
|
||||
|
||||
@web.put("/v1/blobs/{oid}")
|
||||
async def blob_put(oid: str, req: Request):
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
# outputs(work, changed) the job's media among what it made or changed: [{"path", "oid", "size"}]
|
||||
# upload(work, objects) PUTs each to its signed URL: [{"path", "oid", "href", "header"}]
|
||||
|
||||
import uuid
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -43,9 +44,21 @@ def inside(work, rel):
|
||||
return p == os.path.realpath(work) or p.startswith(os.path.realpath(work) + os.sep)
|
||||
|
||||
|
||||
def get(href, header, dest):
|
||||
# the most an original of unknown size may be: a link that answers with more is refused before it fills the volume
|
||||
UNKNOWN_MAX = 40 << 30
|
||||
|
||||
|
||||
def get(href, header, dest, limit=None):
|
||||
req = urllib.request.Request(href, headers={**AGENT, **(header or {})})
|
||||
with urllib.request.urlopen(req, timeout=600) as r, open(dest, "wb") as f:
|
||||
if limit:
|
||||
n = 0
|
||||
while chunk := r.read(8 << 20):
|
||||
n += len(chunk)
|
||||
if n > limit:
|
||||
raise ValueError(f"media: {href.split('?')[0]} is over {limit >> 30} GB, more than an original of unknown size may be")
|
||||
f.write(chunk)
|
||||
return
|
||||
shutil.copyfileobj(r, f, CHUNK)
|
||||
|
||||
|
||||
@@ -80,38 +93,64 @@ def fetch(work, cache, log=print, download=get, check=probe):
|
||||
if len(oid) != 64 or any(c not in "0123456789abcdef" for c in oid) or not inside(work, path):
|
||||
raise ValueError(f"media: {path!r} ({oid}) isn't a path in the job or an object id")
|
||||
blob = os.path.join(cache, oid)
|
||||
# size 0: a library original whose size raea cloud doesn't know (it comes with its link); its hash alone says
|
||||
# it's the one. What the box sent (no link) is held only at its own size
|
||||
held = os.path.exists(blob) and (os.path.getsize(blob) == size or (size <= 0 and bool(o.get("href"))))
|
||||
if not o.get("href"):
|
||||
# sent by the box over the farm's own token (PUT /v1/blobs), checked against its hash as it came
|
||||
if not (os.path.exists(blob) and os.path.getsize(blob) == size):
|
||||
if not held:
|
||||
raise ValueError(f"media: {path} ({oid[:12]}…) was never sent to the farm")
|
||||
cached += size
|
||||
elif os.path.exists(blob) and os.path.getsize(blob) == size:
|
||||
elif held:
|
||||
# a hash alone doesn't open the cache: the job's URL, signed for its account, has to answer
|
||||
check(o["href"], o.get("header"))
|
||||
cached += size
|
||||
cached += os.path.getsize(blob)
|
||||
else:
|
||||
tmp = f"{blob}.part-{os.getpid()}"
|
||||
download(o["href"], o.get("header"), tmp)
|
||||
tmp = f"{blob}.part-{uuid.uuid4().hex}"
|
||||
try:
|
||||
download(o["href"], o.get("header"), tmp, *([UNKNOWN_MAX] if size <= 0 else []))
|
||||
except Exception:
|
||||
if os.path.exists(tmp):
|
||||
os.remove(tmp)
|
||||
raise
|
||||
got = sha256(tmp)
|
||||
if got != oid or os.path.getsize(tmp) != size:
|
||||
if got != oid or (size > 0 and os.path.getsize(tmp) != size):
|
||||
os.remove(tmp)
|
||||
raise ValueError(f"media: {path} came back as {got[:12]}…, not {oid[:12]}…")
|
||||
fetched += os.path.getsize(tmp)
|
||||
os.replace(tmp, blob)
|
||||
fetched += size
|
||||
dest = os.path.join(work, path)
|
||||
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
||||
if os.path.lexists(dest):
|
||||
os.remove(dest)
|
||||
# a link into the cache, not a copy: a project's footage is gigabytes, the same across every job (11-25); every
|
||||
# container of the job mounts the volume at the same place, so the link resolves on the GPUs too
|
||||
# container of the job mounts the volume at the same place, so the link resolves on the GPUs too. It ends at a
|
||||
# file with the take's own name (cache/named/OID/NAME, a hard link to the blob): a bundler follows the link, and
|
||||
# a composition that knows its takes by name (Framed's faces) found only a hash and framed every shot centred
|
||||
try:
|
||||
os.symlink(blob, dest)
|
||||
os.symlink(named(cache, oid, path), dest)
|
||||
except OSError:
|
||||
shutil.copyfile(blob, dest)
|
||||
log(f"raea farm: {len(objects)} media files by hash, {fetched / 1e6:.1f} MB from R2, {cached / 1e6:.1f} MB already here")
|
||||
return {"objects": len(objects), "fetched": fetched, "cached": cached}
|
||||
|
||||
|
||||
def named(cache, oid, path):
|
||||
"""the blob under the take's own name, cache/named/OID/NAME: a hard link (the same file, no space), else the blob"""
|
||||
blob = os.path.join(cache, oid)
|
||||
out = os.path.join(cache, "named", oid, os.path.basename(path))
|
||||
if os.path.exists(out) and os.path.getsize(out) == os.path.getsize(blob):
|
||||
return out
|
||||
try:
|
||||
os.makedirs(os.path.dirname(out), exist_ok=True)
|
||||
tmp = f"{out}.part-{uuid.uuid4().hex}"
|
||||
os.link(blob, tmp)
|
||||
os.replace(tmp, out)
|
||||
return out
|
||||
except OSError:
|
||||
return blob
|
||||
|
||||
|
||||
def is_media(path, size):
|
||||
ext = path.rsplit(".", 1)[-1].lower() if "." in os.path.basename(path) else ""
|
||||
return ext in MEDIA or size >= LARGE
|
||||
|
||||
@@ -365,7 +365,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
|
||||
t.start()
|
||||
video = out.endswith(VIDEO)
|
||||
can_flat = bool(video and cpu_render and not opts.get("gpu"))
|
||||
can_flat = bool(video and cpu_render and not opts.get("gpu") and opts.get("nv") != "1")
|
||||
# what each frame draws, as a key (farm_keys.py): read here with nothing drawn, when this raea has --keys
|
||||
keyed, keys_s = farm_keys.read(rest, work, run, cpu_env, f"/tmp/{id}-keys.json") if video and opts.get("keys") else (None, 0)
|
||||
|
||||
@@ -409,8 +409,9 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
|
||||
gpu_render, gpu_kind = render, kind
|
||||
# a piece with 3D in it keeps its GPU, and its runs use the GPU's encoder and decoder too (CR34): on a 2D piece NVENC
|
||||
# bought nothing (300 frames: 210 s against libx264's 215 s, 11% more bytes), the page and the clips are the work
|
||||
nv = bool((p.get("manifest") or {}).get("has3d"))
|
||||
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
|
||||
# (opts nv "1" or "0" says so for the job, and "1" keeps it on GPUs: to measure what NVENC and NVDEC buy a cut)
|
||||
nv = opts.get("nv") == "1" or (opts.get("nv") != "0" and bool((p.get("manifest") or {}).get("has3d")))
|
||||
flat = bool(video and cpu_render and not opts.get("gpu") and opts.get("nv") != "1" and (p.get("manifest") or {}).get("has3d") is False)
|
||||
r0 = None
|
||||
# a flat video whose keys said so goes out at once: no timed first run (FLAT_PART)
|
||||
quick = bool(flat and p.get("keys"))
|
||||
|
||||
@@ -75,6 +75,9 @@ def api():
|
||||
PROXY_SHORT = 540
|
||||
PROXY_LIGHT_BPS = 2_500_000
|
||||
PART = 64 << 20
|
||||
# every proxy says what it is in its comment tag, and ffmpeg carries the tag into what's made from it: a box's renders
|
||||
# and publishes read it (raea-platform harness/light.ts) so nothing made from a proxy is shown to a person as a final
|
||||
LIGHT_TAG = "raea-light-copy"
|
||||
AGENT = {"user-agent": "raea-ingest/1"}
|
||||
|
||||
|
||||
@@ -160,7 +163,7 @@ def proxy_job(url: str, put: str, ticket: str) -> dict:
|
||||
scale = f"scale='if(gt(iw,ih),-2,trunc(min({PROXY_SHORT},iw)/2)*2)':'if(gt(iw,ih),trunc(min({PROXY_SHORT},ih)/2)*2,-2)',format=yuv420p"
|
||||
r = subprocess.run(
|
||||
["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?", "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "28",
|
||||
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-movflags", "+faststart", out],
|
||||
"-force_key_frames", "expr:gte(t,n_forced*1)", "-c:a", "aac", "-b:a", "96k", "-ac", "2", "-metadata", f"comment={LIGHT_TAG}", "-movflags", "+faststart", out],
|
||||
capture_output=True, text=True, timeout=3300,
|
||||
)
|
||||
if r.returncode != 0 or not os.path.exists(out):
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// components/Cut.tsx: a whole cut composed from its moments. The agent says, per moment, WHAT is on screen (the speaker,
|
||||
// two people, the product, a cutaway, a screen, the wide, the end card) and which take is heard; this lays each one out
|
||||
// with <Shot>, places the product clear of faces, keeps the speaker talking under a cutaway, captions every word in the
|
||||
// brand's style (on the seam of a split, at the bottom otherwise), holds the hook in <Title> at the top, and
|
||||
// ends on the brand's <EndCard>. Every cut of a project then looks the same, and nothing is placed by a typed number.
|
||||
// Put there by the box's prep beside Shot.tsx.
|
||||
//
|
||||
// <Cut said={words} keys={["the product"]} hook="Do you know her this well?" bed={bed} moments={[
|
||||
// { show: "speaker", src: "footage/A.mp4", startFrom: 30, endAt: 120, who: "right" },
|
||||
// { show: "two", src: "footage/A.mp4", startFrom: 400, endAt: 520 },
|
||||
// { show: "broll", src: "footage/A.mp4", startFrom: 520, endAt: 610, asset: "footage/B.mp4", assetFrom: 300 },
|
||||
// { show: "product", src: "footage/A.mp4", startFrom: 900, endAt: 1010, asset: "media/product.png" },
|
||||
// { show: "end", src: "footage/H.mp4", startFrom: 0, endAt: 90, cta: "Get yours today", offer: "20% off" },
|
||||
// ]} />
|
||||
//
|
||||
// A moment lasts its take's span (endAt - startFrom), or `frames` when it has no take. `said` is the cut's words in its
|
||||
// own frames, as `raea cut` gives them for these spans in this order.
|
||||
import { Audio, Sequence, useCurrentFrame } from "raea";
|
||||
import EndCard from "./EndCard";
|
||||
import Said from "./Said";
|
||||
import Shot, { type Layout } from "./Shot";
|
||||
import Title from "./Title";
|
||||
|
||||
type Who = number | string;
|
||||
type Word = { text: string; from: number; to: number };
|
||||
|
||||
export type Moment = {
|
||||
/** what's on screen: the speaker, two people (a split), the product (an insert), a cutaway, a screen (a stack), the
|
||||
* whole wide take, or the end card */
|
||||
show: "speaker" | "two" | "product" | "broll" | "screen" | "wide" | "end";
|
||||
/** the take heard (and seen, but for a cutaway, a screen's top and the end card), and its span in the edit's frames */
|
||||
src?: string;
|
||||
startFrom?: number;
|
||||
endAt?: number;
|
||||
/** the length when there's no take (an end card alone) */
|
||||
frames?: number;
|
||||
/** who's framed (Shot's `who`), and a split's two (Shot's `pair`) */
|
||||
who?: Who;
|
||||
pair?: [Who, Who];
|
||||
/** the product picture, the cutaway's take or the screen, and where its video starts */
|
||||
asset?: string;
|
||||
assetFrom?: number;
|
||||
/** the product picture's width over its height */
|
||||
aspect?: number;
|
||||
/** the clip's level change in dB (cuts.ts's gainDb) and how far it's punched in (cuts.ts's punchIn(i): a jump cut
|
||||
* reframes) */
|
||||
gainDb?: number;
|
||||
punchIn?: number;
|
||||
/** the end card's CTA (the brief's words) and offer */
|
||||
cta?: string;
|
||||
offer?: string;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
moments: Moment[];
|
||||
/** the cut's words, in its frames; no captions without them */
|
||||
said?: readonly Word[];
|
||||
/** key words the captions light (Said's `keys`) */
|
||||
keys?: string[];
|
||||
/** emoji by word (Said's `emoji`); none unless named */
|
||||
emoji?: Record<string, string>;
|
||||
/** the hook, held in <Title> at the top over the first `hookFrames` (until the first sentence ends, 2 s at most);
|
||||
* the captions run under it at the bottom, so no word goes uncaptioned */
|
||||
hook?: string;
|
||||
hookFrames?: number;
|
||||
/** the music bed under the whole cut (the generate tool's), at BED_DB with fades: never a typed level */
|
||||
bed?: string;
|
||||
};
|
||||
|
||||
/** the bed's level: about 16 dB under the voices once <Mix> masters the cut, inside the check's 12-20 dB (12-05: beds
|
||||
* typed at volume 0.07 or gainDb -21 sat 28-30 dB under, and the check heard no music) */
|
||||
export const BED_DB = -10;
|
||||
|
||||
const LAYOUT: Record<Exclude<Moment["show"], "end">, Layout> = { speaker: "face", two: "split", product: "insert", broll: "broll", screen: "stack", wide: "fit" };
|
||||
|
||||
/** each moment's first frame on the cut and its length */
|
||||
export function spans(ms: Moment[]): { from: number; len: number }[] {
|
||||
let at = 0;
|
||||
return ms.map((m) => {
|
||||
const len = Math.max(1, m.src && m.endAt !== undefined ? m.endAt - (m.startFrom ?? 0) : (m.frames ?? 60));
|
||||
const s = { from: at, len };
|
||||
at += len;
|
||||
return s;
|
||||
});
|
||||
}
|
||||
|
||||
/** the cut's words in its frames, from each heard take's words (footage/NAME.words.json, by the take's name): the words
|
||||
* each moment's span says, in the moments' order; a word cut off by a span's edge is left out */
|
||||
export function saidOf(ms: Moment[], words: Record<string, readonly { text: string; start_ms: number; end_ms: number }[]>, fps: number): Word[] {
|
||||
const out: Word[] = [];
|
||||
const sp = spans(ms);
|
||||
ms.forEach((m, i) => {
|
||||
if (!m.src) return;
|
||||
const ws = words[m.src.split("/").pop()!.replace(/\.[^.]+$/, "")] ?? [];
|
||||
const a = (m.startFrom ?? 0) / fps;
|
||||
const b = a + sp[i].len / fps;
|
||||
for (const w of ws) {
|
||||
const s = w.start_ms / 1000;
|
||||
const e = w.end_ms / 1000;
|
||||
if (s >= a - 0.02 && e <= b + 0.05) out.push({ text: w.text, from: sp[i].from + Math.max(0, Math.round((s - a) * fps)), to: sp[i].from + Math.min(sp[i].len, Math.round((e - a) * fps)) });
|
||||
}
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
/** cuts.ts's clips as moments, in order: each one the speaker (or `show` for clip i), its span in the edit's frames as
|
||||
* cuts.ts counts them, its gainDb, and a jump cut punched in every other time (cuts.ts's punchIn). Change a moment's
|
||||
* show, who or asset after; the timing stays raea cut's. */
|
||||
export function fromCuts(
|
||||
cuts: readonly { src: string; from: number; to: number; gainDb?: number; jump?: boolean; kind?: string }[],
|
||||
fps: number,
|
||||
punchIn?: (i: number) => number,
|
||||
show?: (i: number) => Partial<Moment> | undefined,
|
||||
): Moment[] {
|
||||
return cuts.map((c, i) => {
|
||||
const s = Math.round(c.from * fps);
|
||||
const len = Math.max(1, Math.round((c.to - c.from) * fps));
|
||||
const k = punchIn ? punchIn(i) : 1;
|
||||
return { show: "speaker", src: c.src, startFrom: s, endAt: s + len, ...(c.gainDb ? { gainDb: c.gainDb } : {}), ...(k !== 1 ? { punchIn: k } : {}), ...(show?.(i) ?? {}) } as Moment;
|
||||
});
|
||||
}
|
||||
|
||||
/** the captions' band for what's on screen: over a split's or a stack's seam, else at the bottom */
|
||||
const bandOf = (m?: Moment) => (m && (m.show === "two" || m.show === "screen") ? "center" : "bottom");
|
||||
|
||||
export default function Cut({ moments, said, keys, emoji, hook, hookFrames, bed }: Props) {
|
||||
const f = useCurrentFrame();
|
||||
const sp = spans(moments);
|
||||
const now = sp.findIndex((s) => f >= s.from && f < s.from + s.len);
|
||||
// the hook holds until the first sentence is said (2 s at most), unless told
|
||||
const firstEnd = said?.find((w) => /[.?!]$/.test(w.text))?.to;
|
||||
const hookLen = hookFrames ?? Math.min(60, firstEnd ?? 60);
|
||||
const showHook = !!hook && f < hookLen;
|
||||
return (
|
||||
<>
|
||||
{moments.map((m, i) => (
|
||||
<Sequence key={i} from={sp[i].from} durationInFrames={sp[i].len} name={`${m.show} ${i + 1}`}>
|
||||
{m.show === "end" ? (
|
||||
<>
|
||||
<EndCard cta={m.cta ?? ""} offer={m.offer} asset={m.asset} />
|
||||
{m.src ? <Audio src={m.src} startFrom={m.startFrom} endAt={m.endAt} gainDb={m.gainDb} /> : null}
|
||||
</>
|
||||
) : m.src ? (
|
||||
<Shot layout={LAYOUT[m.show]} src={m.src} startFrom={m.startFrom} endAt={m.endAt} who={m.who} pair={m.pair} asset={m.asset} assetFrom={m.assetFrom} aspect={m.aspect} gainDb={m.gainDb} punchIn={m.punchIn} />
|
||||
) : null}
|
||||
</Sequence>
|
||||
))}
|
||||
{bed ? <Audio src={bed} gainDb={BED_DB} fadeIn={0.3} fadeOut={1} /> : null}
|
||||
{showHook ? <Title region="top">{hook}</Title> : null}
|
||||
{said?.length ? <Said said={said} keys={keys} emoji={emoji} region={bandOf(moments[now])} /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// components/EndCard.tsx: a cut's last card from the brand template (components/brand.ts): the brand's surface, its logo,
|
||||
// the CTA in the brief's own words and the offer on the brand's button, every part inside the app's zones. Put there by
|
||||
// the box's prep beside Shot.tsx. Change the look freely; never give a part a top or a left.
|
||||
import type React from "react";
|
||||
import { AbsoluteFill, Img, interpolate, useCurrentFrame, useVideoConfig } from "raea";
|
||||
import { COLORS, FONTS, RADIUS, logo as brandLogo, zones } from "./brand";
|
||||
|
||||
type Props = {
|
||||
/** the call to action, word for word from the brief */
|
||||
cta: string;
|
||||
/** the offer (a code, a discount), on the brand's button */
|
||||
offer?: string;
|
||||
/** the logo's file; the brand kit's when unset, none when it has none */
|
||||
logo?: string | null;
|
||||
/** a product picture above the CTA */
|
||||
asset?: string;
|
||||
/** merged over the card's surface */
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
/** the offer's size: 64 px at 1080 wide, less when its line (about 0.6 em a letter in a bold face, and the button's
|
||||
* padding) wouldn't fit `inner`; never under 56 px (the check calls less small print): a longer offer wraps, evenly */
|
||||
export const offerSize = (offer: string, inner: number, s: number) => Math.max(56 * s, Math.min(64 * s, (inner - 96 * s) / (0.6 * Math.max(1, offer.length))));
|
||||
|
||||
export default function EndCard({ cta, offer, logo, asset, style }: Props) {
|
||||
const f = useCurrentFrame();
|
||||
const { width: W, height: H } = useVideoConfig();
|
||||
const z = zones(W, H);
|
||||
const s = W / 1080;
|
||||
const mark = logo === undefined ? brandLogo("dark") : logo;
|
||||
// the card's inner width: inside the app's zones and the card's own margin
|
||||
const inner = W - z.left - Math.max(z.left, z.right) - 80 * s;
|
||||
const rise = (d: number) => ({
|
||||
opacity: interpolate(f, [d, d + 8], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" }),
|
||||
transform: `translateY(${interpolate(f, [d, d + 10], [24 * s, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" })}px)`,
|
||||
});
|
||||
return (
|
||||
<AbsoluteFill data-shot="end" style={{ background: COLORS.surface, ...style }}>
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: z.left + 40 * s,
|
||||
right: Math.max(z.left, z.right) + 40 * s,
|
||||
top: z.top + 40 * s,
|
||||
bottom: z.bottom + 40 * s,
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: 56 * s,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
{mark ? <Img src={mark} style={{ maxWidth: 560 * s, maxHeight: 220 * s, objectFit: "contain", ...rise(0) }} /> : null}
|
||||
{asset ? <Img src={asset} style={{ maxWidth: 620 * s, maxHeight: 520 * s, objectFit: "contain", borderRadius: RADIUS * s, ...rise(4) }} /> : null}
|
||||
<div style={{ fontFamily: FONTS.heading, fontWeight: 800, fontSize: 88 * s, lineHeight: 1.08, color: COLORS.text, ...rise(6) }}>{cta}</div>
|
||||
{offer ? (
|
||||
// the offer on one line when it fits at 56 px or more, else wrapped evenly (12-05: "Code SAVE60 · $60 off" broke
|
||||
// over two with one word alone, and shrunk to fit it was 40 px, small print)
|
||||
<div style={{ fontFamily: FONTS.heading, fontWeight: 800, fontSize: offerSize(offer, inner, s), lineHeight: 1.1, maxWidth: inner, textWrap: "balance", color: COLORS.buttonText, background: COLORS.button, borderRadius: RADIUS * s * 2, padding: `${28 * s}px ${48 * s}px`, ...rise(12) }}>{offer}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// components/Framed.tsx: a take cropped to the edit's shape around the person in it, from footage/faces.json (the
|
||||
// box's prep finds every take's faces at its keyframes: image/faces.py). 12-05, Shane: "the ai fucks up the composition
|
||||
// of subjects in frame all the time": each crop was a number the agent guessed (objectPosition), and a 9:16 cut showed
|
||||
// a bench while the woman talking was cut off at the edge.
|
||||
//
|
||||
// <Framed src={c.src} startFrom={f0} endAt={f1} /> the clip's largest face, whole, eyes a third down
|
||||
// <Framed ... at={0.7} /> the face nearest 70% across the take (the guest, not the host)
|
||||
// <Framed ... punchIn={1.15} /> tighter, still on the face
|
||||
//
|
||||
// The crop holds still for the clip (an editor's locked-off reframe), and follows only when the face moves further
|
||||
// than one still crop can hold, smoothed over a second. A take with no faces is centred.
|
||||
import type React from "react";
|
||||
import { Video, useCurrentFrame, useVideoConfig } from "raea";
|
||||
import FACES from "../footage/faces.json";
|
||||
|
||||
type Take = { w: number; h: number; t: number[]; s: number[][][] };
|
||||
const TRACKS = FACES as unknown as Record<string, Take>;
|
||||
|
||||
type Props = {
|
||||
src: string;
|
||||
/** the take's first and last frame used, in the edit's frames (as Video takes them) */
|
||||
startFrom?: number;
|
||||
endAt?: number;
|
||||
/** which face when several: the one nearest this share across the take (0 left, 1 right); default the largest */
|
||||
at?: number;
|
||||
/** 1 = the whole height of the take; above 1 = tighter, centred on the face */
|
||||
punchIn?: number;
|
||||
volume?: number;
|
||||
/** the clip's level change in dB (cuts.ts gives it, evening the cut's voices) */
|
||||
gainDb?: number;
|
||||
playbackRate?: number;
|
||||
muted?: boolean;
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
const clamp = (x: number, a = 0, b = 1) => Math.min(b, Math.max(a, x));
|
||||
const median = (xs: number[]) => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
return s.length ? s[Math.floor(s.length / 2)] : 0.5;
|
||||
};
|
||||
/** the face's room from the crop's edge: a third of its own width either side */
|
||||
const ROOM = 1 / 3;
|
||||
|
||||
/** the take's face at each sample from `a` to `b` seconds: [t, cx, ey, fw], and every other face's span across the
|
||||
* take ([t, left, right]) */
|
||||
function path(take: Take, a: number, b: number, near?: number): { p: [number, number, number, number][]; others: [number, number, number][] } {
|
||||
const out: [number, number, number, number][] = [];
|
||||
const others: [number, number, number][] = [];
|
||||
let last: number | undefined = near;
|
||||
for (let i = 0; i < take.t.length; i++) {
|
||||
const t = take.t[i];
|
||||
if (t < a - 1 || t > b + 1) continue;
|
||||
const fs = take.s[i];
|
||||
if (!fs?.length) continue;
|
||||
// the face asked for (nearest `at`), followed from sample to sample, else the largest; a sample where no face is in
|
||||
// reach of them (a face width and a half, or 8% of the take) doesn't have them, and the crop holds: it never jumps
|
||||
// to someone else (12-05: the host at 0.4 went undetected for a second, the guest at 0.61 was nearest, and the crop
|
||||
// swung to him mid-shot, under the hook)
|
||||
const g = last === undefined ? fs[0] : fs.reduce((p, q) => (Math.abs(q[0] - last!) < Math.abs(p[0] - last!) ? q : p));
|
||||
const f = last === undefined || Math.abs(g[0] - last) <= Math.max(1.5 * g[2], 0.08) ? g : undefined;
|
||||
for (const o of fs) if (o !== f) others.push([t, o[0] - o[2] / 2, o[0] + o[2] / 2]);
|
||||
if (!f) continue;
|
||||
last = f[0];
|
||||
out.push([t, f[0], f[1], f[2]]);
|
||||
}
|
||||
return { p: out, others };
|
||||
}
|
||||
|
||||
/** the crop's left edge nearest `ideal` that keeps the framed face (lo..hi across the take) inside it and cuts no other
|
||||
* face: each other face either whole in the crop or wholly out of it (12-05, a street interview: the crop on the host cut the
|
||||
* man beside her in half at the right edge). `ideal` when no such edge exists */
|
||||
function cleanLeft(ideal: number, vw: number, lo: number, hi: number, others: [number, number][]): number {
|
||||
const most = Math.max(0, 1 - vw);
|
||||
const a = clamp(hi - vw, 0, most);
|
||||
const b = clamp(lo, 0, most);
|
||||
if (a > b || !others.length) return ideal;
|
||||
const cuts = (l: number) => others.some(([x1, x2]) => (l > x1 && l < x2) || (l + vw > x1 && l + vw < x2));
|
||||
const tries = [ideal, ...others.flatMap(([x1, x2]) => [x2 + 0.005, x1 - 0.005, x1 - vw - 0.005, x2 - vw + 0.005])];
|
||||
const ok = tries.filter((l) => l >= a && l <= b && l >= 0 && l <= most && !cuts(l));
|
||||
return ok.length ? ok.reduce((x, y) => (Math.abs(y - ideal) < Math.abs(x - ideal) ? y : x)) : ideal;
|
||||
}
|
||||
|
||||
export default function Framed({ src, startFrom = 0, endAt, at, punchIn = 1, volume, gainDb, playbackRate, muted, style }: Props) {
|
||||
const frame = useCurrentFrame();
|
||||
const { width, height, fps } = useVideoConfig();
|
||||
const name = src.split("/").pop()!.replace(/\.[^.]+$/, "");
|
||||
const take = TRACKS[name];
|
||||
const a = startFrom / fps;
|
||||
const b = endAt !== undefined ? endAt / fps : a + 600;
|
||||
const now = a + (frame / fps) * (playbackRate ?? 1);
|
||||
let pos = "50% 50%";
|
||||
let transform: string | undefined;
|
||||
let origin: string | undefined;
|
||||
if (take) {
|
||||
const k = Math.max(1, punchIn);
|
||||
// the share of the take the box shows across and down (object-fit: cover), before and after the punch-in
|
||||
const box = width / height;
|
||||
const src_ = take.w / take.h;
|
||||
const vw = Math.min(1, box / src_) / k;
|
||||
const vh = Math.min(1, src_ / box) / k;
|
||||
const { p, others } = path(take, a, b, at);
|
||||
if (p.length) {
|
||||
const xs = p.map((s) => s[1]);
|
||||
const fw = Math.max(...p.map((s) => s[3]));
|
||||
// one still crop when every sample's face fits it with room either side; else follow, smoothed over a second
|
||||
const fits = Math.max(...xs) - Math.min(...xs) + fw * (1 + 2 * ROOM) <= vw;
|
||||
const near = p.filter((s) => Math.abs(s[0] - now) <= 0.5);
|
||||
const cx = fits ? median(xs) : median((near.length ? near : p).map((s) => s[1]));
|
||||
const ey = median((fits || !near.length ? p : near).map((s) => s[2]));
|
||||
// the crop's left and top edges, in shares of the take: the face across its middle, the eyes a third down
|
||||
// the framed face's span the crop must hold (every sample's when still, the nearest second's when following),
|
||||
// and the other faces there, which it mustn't cut
|
||||
const held = fits || !near.length ? p : near;
|
||||
const lo = Math.min(...held.map((s) => s[1] - s[3] / 2));
|
||||
const hi = Math.max(...held.map((s) => s[1] + s[3] / 2));
|
||||
const span = (fits ? others : others.filter((o) => Math.abs(o[0] - now) <= 0.5)).map((o) => [o[1], o[2]] as [number, number]);
|
||||
const left = cleanLeft(clamp(cx - vw / 2, 0, 1 - vw), vw, lo, hi, span);
|
||||
const top = clamp(ey - vh / 3, 0, 1 - vh);
|
||||
if (k === 1) {
|
||||
pos = `${vw >= 1 ? 50 : (left / (1 - vw)) * 100}% ${vh >= 1 ? 50 : (top / (1 - vh)) * 100}%`;
|
||||
} else {
|
||||
// cover at 1, then scaled about the point that puts the chosen window in the box
|
||||
const vw1 = vw * k;
|
||||
const vh1 = vh * k;
|
||||
const l1 = cleanLeft(clamp(cx - vw1 / 2, 0, 1 - vw1), vw1, lo, hi, span);
|
||||
const t1 = clamp(ey - vh1 / 3, 0, 1 - vh1);
|
||||
pos = `${vw1 >= 1 ? 50 : (l1 / (1 - vw1)) * 100}% ${vh1 >= 1 ? 50 : (t1 / (1 - vh1)) * 100}%`;
|
||||
// the window's left edge at the box's left: scale about the point o where (o - l1)/vw1 = (o - left)/vw
|
||||
const ox = vw1 === vw ? 0.5 : (left * vw1 - l1 * vw) / (vw1 - vw);
|
||||
const oy = vh1 === vh ? 0.5 : (top * vh1 - t1 * vh) / (vh1 - vh);
|
||||
transform = `scale(${k})`;
|
||||
origin = `${clamp((ox - l1) / vw1) * 100}% ${clamp((oy - t1) / vh1) * 100}%`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Video
|
||||
src={src}
|
||||
startFrom={startFrom}
|
||||
endAt={endAt}
|
||||
volume={volume}
|
||||
gainDb={gainDb}
|
||||
playbackRate={playbackRate}
|
||||
muted={muted}
|
||||
style={{ width: "100%", height: "100%", objectFit: "cover", ...style, objectPosition: pos, ...(transform ? { transform, transformOrigin: origin } : {}) }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// components/Said.tsx: a cut's captions in the brand's caption style with its key words lit, through raea's <Captions>
|
||||
// (the cut's own words, in a safe band, marked as captions for the check and the layered export). Put there by the box's
|
||||
// prep beside Shot.tsx. The word being said is lit in the accent; a key word (a number, a price, a percentage, or one of
|
||||
// `keys`: the product's name, the brief's must-say) is lit from the moment it's said. An emoji goes
|
||||
// after a word only where `emoji` names it: never chosen by guess.
|
||||
import { Captions, type RegionName } from "raea";
|
||||
import { CAPTION } from "./brand";
|
||||
|
||||
type Word = { text: string; from: number; to: number };
|
||||
type Props = {
|
||||
/** the cut's words, in its frames (`raea cut` gives them) */
|
||||
said: readonly Word[];
|
||||
/** the key words and phrases to light, case ignored ("the product's name", "96 hours") */
|
||||
keys?: string[];
|
||||
/** an emoji after a word, by the word, case ignored ({ "love": "❤️" }) */
|
||||
emoji?: Record<string, string>;
|
||||
/** the band (Region): "bottom" by default; "center" over a split's or a stack's seam */
|
||||
region?: RegionName;
|
||||
/** the size in px at 1080 wide (the brand's caption size) */
|
||||
size?: number;
|
||||
/** how a misheard word is written, as Captions takes it */
|
||||
fix?: Record<string, string>;
|
||||
};
|
||||
|
||||
const bare = (t: string) => t.toLowerCase().replace(/[^\p{L}\p{N}%$€£']/gu, "");
|
||||
/** a word worth lighting by itself: a number, a price, a percentage */
|
||||
const NUMBER = /\d|%|\$|€|£/;
|
||||
|
||||
/** which of `ws` are key: a number, or part of a run of words that spells one of `keys` */
|
||||
export function keyed(ws: readonly Word[], keys: string[] = []): boolean[] {
|
||||
const out = ws.map((w) => NUMBER.test(w.text));
|
||||
const phrases = keys.map((k) => k.split(/\s+/).map(bare).filter(Boolean)).filter((k) => k.length);
|
||||
for (let i = 0; i < ws.length; i++)
|
||||
for (const k of phrases) if (k.every((p, j) => bare(ws[i + j]?.text ?? "") === p)) for (let j = 0; j < k.length; j++) out[i + j] = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
export default function Said({ said, keys, emoji, region = "bottom", size = CAPTION.size, fix }: Props) {
|
||||
const hot = keyed(said, keys);
|
||||
const at = new Map(said.map((w, i) => [w, i]));
|
||||
const em = Object.fromEntries(Object.entries(emoji ?? {}).map(([k, v]) => [bare(k), v]));
|
||||
return (
|
||||
<Captions said={said as Word[]} region={region} size={size} fix={fix}>
|
||||
{(ws, saying) =>
|
||||
ws.map((w, j) => {
|
||||
// the caption's words are copies (spelled by `fix`): found again among the cut's by their frames
|
||||
const i = at.get(said.find((x) => x.from === w.from && x.to === w.to) as Word) ?? -1;
|
||||
const key = i >= 0 && hot[i];
|
||||
const lit = j === saying || (key && saying >= j);
|
||||
const e = em[bare(w.text)];
|
||||
return (
|
||||
// a key word is lit, never drawn bigger: a bigger word made the line taller than the band Captions keeps it in,
|
||||
// and its letters reached the app's bottom zone (12-05, a composed street cut: 1 px into the 420 px)
|
||||
<span key={j} style={{ color: lit ? CAPTION.accent : undefined }}>
|
||||
{w.text}
|
||||
{e ? ` ${e}` : ""}
|
||||
{j < ws.length - 1 ? " " : ""}
|
||||
</span>
|
||||
);
|
||||
})
|
||||
}
|
||||
</Captions>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
// components/Shot.tsx: one moment of a cut, laid out from what the agent says is on screen, every time the same way. Put
|
||||
// there by the box's prep beside Framed.tsx. 12-05, Shane: framing and timing aren't enough, "it's also composition of
|
||||
// footage and assets": agents built each cut's layout by hand and by guess (a split on one face, a product card over the
|
||||
// guest's face, a cutaway with nobody talking under it). The agent picks the moment and the layout; this places it.
|
||||
//
|
||||
// <Shot layout="face" src={take} startFrom={f0} endAt={f1} who={0.7} /> the speaker framed (Framed.tsx)
|
||||
// <Shot layout="split" src={take} ... pair={["left", "right"]} /> two people of one wide take, one a half
|
||||
// <Shot layout="insert" src={take} ... asset="media/product.png" /> the speaker, the product in the clear
|
||||
// <Shot layout="stack" src={take} ... asset="media/screen.mp4" /> the asset on top, the speaker below
|
||||
// <Shot layout="fit" src={take} ... /> the whole take over a dimmed copy
|
||||
// <Shot layout="broll" src={take} ... asset="footage/broll.mp4" /> the cutaway, the take still heard (L-cut)
|
||||
//
|
||||
// Each falls back when the take can't hold it, from the faces prep found (footage/faces.json): a split with fewer than
|
||||
// two people in the moment, or two who can't each be shown whole and alone, is the face of the first; an insert with no
|
||||
// clear place off every face is a stack. Never type a crop, a top or a left: change what's on screen instead.
|
||||
import type React from "react";
|
||||
import { AbsoluteFill, Audio, Img, Video, interpolate, useCurrentFrame, useVideoConfig } from "raea";
|
||||
import FACES from "../footage/faces.json";
|
||||
import Framed from "./Framed";
|
||||
import { RADIUS, zones } from "./brand";
|
||||
import { type Take, type Win, css, holdsAlone, onScreen, people, pick, windowOn } from "./crop";
|
||||
|
||||
export type Layout = "face" | "split" | "stack" | "fit" | "insert" | "broll";
|
||||
type Who = number | string;
|
||||
|
||||
export type ShotProps = {
|
||||
layout: Layout;
|
||||
/** the take this moment is heard from (and shown from, but for a cutaway) */
|
||||
src: string;
|
||||
/** the take's first and last frame used, in the edit's frames (as Video takes them) */
|
||||
startFrom?: number;
|
||||
endAt?: number;
|
||||
/** face, insert, stack: who's framed: a share across the take (0 left, 1 right), "left", "right", or the largest */
|
||||
who?: Who;
|
||||
/** split: the two people, top first (the leftmost on top when unset) */
|
||||
pair?: [Who, Who];
|
||||
/** insert: the product or logo picture; stack: what goes on top (a picture or a video); broll: the cutaway's take */
|
||||
asset?: string;
|
||||
/** broll and stack: where the asset's video starts, in the edit's frames */
|
||||
assetFrom?: number;
|
||||
/** insert: the picture's width over its height (1) and its width as a share of the frame's (0.38) */
|
||||
aspect?: number;
|
||||
size?: number;
|
||||
/** insert: px boxes [x, y, w, h] it must keep off besides faces (the caption band is kept by default) */
|
||||
keep?: [number, number, number, number][];
|
||||
/** face: tighter than the take's whole height (Framed's punchIn) */
|
||||
punchIn?: number;
|
||||
volume?: number;
|
||||
/** the clip's level change in dB (cuts.ts's gainDb) */
|
||||
gainDb?: number;
|
||||
muted?: boolean;
|
||||
};
|
||||
|
||||
const TRACKS = FACES as unknown as Record<string, Take>;
|
||||
/** the share of a split's span each of its two must be seen in */
|
||||
const SPLIT_SEEN = 0.85;
|
||||
const nameOf = (src: string) => src.split("/").pop()!.replace(/\.[^.]+$/, "");
|
||||
const isVideo = (src: string) => /\.(mp4|mov|m4v|webm|mkv)$/i.test(src);
|
||||
|
||||
/** a take's window in a panel at x, y, w x h: the Video cropped to it, its box clipped by the panel */
|
||||
function Panel({ src, win, x, y, w, h, startFrom, endAt, volume, gainDb, muted, dim }: { src: string; win: Win; x: number; y: number; w: number; h: number; startFrom?: number; endAt?: number; volume?: number; gainDb?: number; muted?: boolean; dim?: boolean }) {
|
||||
const c = css(win, w, h);
|
||||
return (
|
||||
<div style={{ position: "absolute", left: x, top: y, width: w, height: h, overflow: "hidden", opacity: dim ? 0.45 : 1 }}>
|
||||
<Video
|
||||
src={src}
|
||||
startFrom={startFrom}
|
||||
endAt={endAt}
|
||||
volume={volume}
|
||||
gainDb={gainDb}
|
||||
muted={muted}
|
||||
style={{ position: "absolute", left: c.left, top: c.top, width: c.width, height: c.height, objectFit: "cover", objectPosition: c.objectPosition, ...(dim ? { filter: "blur(40px)" } : {}) }}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** the clearest place for a box `bw` x `bh` in a frame `W` x `H`: off every face (with a third of its width round it),
|
||||
* then off `keep`, then off the bodies below the faces, inside the app's zones; null when every place covers a face */
|
||||
export function clearSpot(W: number, H: number, faces: [number, number, number, number][], keep: [number, number, number, number][], bw: number, bh: number): [number, number] | null {
|
||||
const z = zones(W, H);
|
||||
const m = 0.04 * W;
|
||||
const x0 = z.left + m;
|
||||
const x1 = W - Math.max(z.right, z.left) - m - bw;
|
||||
const y0 = z.top + m;
|
||||
const y1 = H - z.bottom - m - bh;
|
||||
if (x1 < x0 || y1 < y0) return null;
|
||||
const over = (ax: number, ay: number, b: [number, number, number, number]) => Math.max(0, Math.min(ax + bw, b[0] + b[2]) - Math.max(ax, b[0])) * Math.max(0, Math.min(ay + bh, b[1] + b[3]) - Math.max(ay, b[1]));
|
||||
const padded = faces.map((f) => [f[0] - f[2] / 3, f[1] - f[3] / 3, f[2] * (5 / 3), f[3] * (5 / 3)] as [number, number, number, number]);
|
||||
const bodies = faces.map((f) => [f[0] - f[2] * 0.9, f[1] + f[3], f[2] * 2.8, H] as [number, number, number, number]);
|
||||
let best: [number, number] | null = null;
|
||||
let cost = Infinity;
|
||||
const step = Math.max(8, Math.round(W / 60));
|
||||
for (let y = y0; y <= y1; y += step)
|
||||
for (let x = x0; x <= x1; x += step) {
|
||||
if (padded.some((f) => over(x, y, f) > 0)) continue;
|
||||
const c = keep.reduce((s, k) => s + over(x, y, k), 0) * 3 + bodies.reduce((s, b) => s + over(x, y, b), 0) * 0.5 + Math.abs(y + bh / 2 - H / 3) * bw * 0.02;
|
||||
if (c < cost) {
|
||||
cost = c;
|
||||
best = [x, y];
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export default function Shot(p: ShotProps) {
|
||||
const { width: W, height: H, fps } = useVideoConfig();
|
||||
const frame = useCurrentFrame();
|
||||
const take = TRACKS[nameOf(p.src)];
|
||||
const a = (p.startFrom ?? 0) / fps;
|
||||
const b = p.endAt !== undefined ? p.endAt / fps : a + 600;
|
||||
const ps = people(take, a, b);
|
||||
const av = { startFrom: p.startFrom, endAt: p.endAt, volume: p.volume, gainDb: p.gainDb, muted: p.muted };
|
||||
|
||||
const face = () => {
|
||||
const at = typeof p.who === "number" ? p.who : p.who === "left" || p.who === "right" ? pick(ps, p.who)?.cx : undefined;
|
||||
// `who` beyond a place across (a person's id, "speaker") goes to Framed as it is: its take graph knows them
|
||||
const extra = typeof p.who === "string" && p.who !== "left" && p.who !== "right" ? ({ who: p.who } as Record<string, unknown>) : {};
|
||||
return (
|
||||
<AbsoluteFill data-shot="face">
|
||||
<Framed src={p.src} {...av} at={at} punchIn={p.punchIn} {...extra} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
};
|
||||
const speakerIn = (x: number, y: number, w: number, h: number, alone = false) => {
|
||||
const on = pick(ps, p.who);
|
||||
const win = take ? windowOn(take, w, h, on, ps.filter((q) => q !== on), alone) : { left: 0, top: 0, vw: 1, vh: 1, zoom: 1 };
|
||||
return { on, win, el: take ? <Panel src={p.src} win={win} x={x} y={y} w={w} h={h} {...av} /> : <Video src={p.src} {...av} style={{ position: "absolute", left: x, top: y, width: w, height: h, objectFit: "cover" }} /> };
|
||||
};
|
||||
const pic = (src: string, fit: "cover" | "contain", from?: number) =>
|
||||
isVideo(src) ? (
|
||||
<Video src={src} startFrom={from} muted style={{ width: "100%", height: "100%", objectFit: fit }} />
|
||||
) : (
|
||||
<Img src={src} style={{ width: "100%", height: "100%", objectFit: fit }} />
|
||||
);
|
||||
|
||||
switch (p.layout) {
|
||||
case "face":
|
||||
return face();
|
||||
|
||||
case "split": {
|
||||
const half = H / 2;
|
||||
// both people in nearly the whole span: a split with one half empty for a second is the fault the check names
|
||||
// (12-05: the guest's face went at 175 s, a 4 s split showed one face for its last second)
|
||||
const two = ps.filter((q) => q.seen >= SPLIT_SEEN);
|
||||
const [t0, t1] = p.pair ? [pick(two, p.pair[0]), pick(two, p.pair[1])] : [...two.slice(0, 2)].sort((q, r) => q.cx - r.cx);
|
||||
const ok = take && t0 && t1 && t0 !== t1 && holdsAlone(take, W, half, t0, ps.filter((q) => q !== t0)) && holdsAlone(take, W, half, t1, ps.filter((q) => q !== t1));
|
||||
if (!ok) return face();
|
||||
const w0 = windowOn(take!, W, half, t0, ps.filter((q) => q !== t0), true);
|
||||
const w1 = windowOn(take!, W, half, t1, ps.filter((q) => q !== t1), true);
|
||||
return (
|
||||
<AbsoluteFill data-shot="split" style={{ background: "#000" }}>
|
||||
<Panel src={p.src} win={w0} x={0} y={0} w={W} h={half} {...av} />
|
||||
<Panel src={p.src} win={w1} x={0} y={half} w={W} h={half} {...av} muted />
|
||||
<div style={{ position: "absolute", left: 0, top: half - 3, width: W, height: 6, background: "var(--brand-background, #101010)" }} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
case "insert": {
|
||||
if (!p.asset) return face();
|
||||
const s = speakerIn(0, 0, W, H);
|
||||
const bw = Math.round((p.size ?? 0.38) * W);
|
||||
const bh = Math.round(bw / (p.aspect ?? 1));
|
||||
const z = zones(W, H);
|
||||
const keep = p.keep ?? [[0, H - z.bottom - 0.16 * H, W, 0.16 * H] as [number, number, number, number]];
|
||||
const faces = ps.map((q) => onScreen(q, s.win, 0, 0, W, H));
|
||||
const at = clearSpot(W, H, faces, keep, bw, bh);
|
||||
if (!at) return <Shot {...p} layout="stack" />;
|
||||
const k = interpolate(frame, [0, 6], [0.92, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
|
||||
const o = interpolate(frame, [0, 4], [0, 1], { extrapolateLeft: "clamp", extrapolateRight: "clamp" });
|
||||
return (
|
||||
<AbsoluteFill data-shot="insert">
|
||||
{s.el}
|
||||
<div style={{ position: "absolute", left: at[0], top: at[1], width: bw, height: bh, borderRadius: RADIUS * (W / 1080) * 1.4, overflow: "hidden", boxShadow: "0 18px 48px rgba(0,0,0,0.45)", background: "#fff", opacity: o, transform: `scale(${k})` }}>
|
||||
{pic(p.asset, "contain", p.assetFrom)}
|
||||
</div>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
case "stack": {
|
||||
const half = Math.round(H / 2);
|
||||
const s = speakerIn(0, half, W, H - half);
|
||||
return (
|
||||
<AbsoluteFill data-shot="stack" style={{ background: "var(--brand-background, #101010)" }}>
|
||||
<div style={{ position: "absolute", left: 0, top: 0, width: W, height: half, overflow: "hidden" }}>{p.asset ? pic(p.asset, isVideo(p.asset) ? "cover" : "contain", p.assetFrom) : null}</div>
|
||||
{s.el}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
case "fit": {
|
||||
const h = Math.round((W * (take?.h ?? 9)) / (take?.w ?? 16));
|
||||
const whole: Win = { left: 0, top: 0, vw: 1, vh: 1, zoom: 1 };
|
||||
const back = take ? windowOn(take, W, H, undefined, []) : whole;
|
||||
return (
|
||||
<AbsoluteFill data-shot="fit" style={{ background: "#000" }}>
|
||||
<Panel src={p.src} win={back} x={0} y={0} w={W} h={H} startFrom={p.startFrom} endAt={p.endAt} muted dim />
|
||||
<Panel src={p.src} win={whole} x={0} y={Math.round((H - h) / 2)} w={W} h={h} {...av} />
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
|
||||
case "broll": {
|
||||
// the cutaway seen, the take heard: the speaker talks on under it (an L-cut), so a cutaway never plays in silence
|
||||
const src = p.asset ?? p.src;
|
||||
const own = TRACKS[nameOf(src)];
|
||||
const bp = own ? people(own, (p.assetFrom ?? 0) / fps, (p.assetFrom ?? 0) / fps + (b - a)) : [];
|
||||
const win = own ? windowOn(own, W, H, bp[0], bp.slice(1)) : undefined;
|
||||
const push = interpolate(frame, [0, Math.max(1, (b - a) * fps)], [1, 1.06], { extrapolateRight: "clamp" });
|
||||
return (
|
||||
<AbsoluteFill data-shot="broll" style={{ background: "#000" }}>
|
||||
{isVideo(src) && win ? (
|
||||
<Panel src={src} win={win} x={0} y={0} w={W} h={H} startFrom={p.assetFrom} muted />
|
||||
) : isVideo(src) ? (
|
||||
<Video src={src} startFrom={p.assetFrom} muted style={{ width: "100%", height: "100%", objectFit: "cover" }} />
|
||||
) : (
|
||||
<Img src={src} style={{ width: "100%", height: "100%", objectFit: "cover", transform: `scale(${push})` }} />
|
||||
)}
|
||||
{p.asset && !p.muted ? <Audio src={p.src} startFrom={p.startFrom} endAt={p.endAt} volume={p.volume} gainDb={p.gainDb} /> : null}
|
||||
</AbsoluteFill>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
// <Title>: a hook, a title or an offer line on a cut, placed by raea's <Region> inside the app's UI zones (the same
|
||||
// zones the check holds text to) and clear of the face when the edit knows where it is. Put there by the box's prep,
|
||||
// beside Framed.tsx: 12-05, agents typed each title's top (140-190 px) into the app's top 220 px, over faces, run after
|
||||
// run. Change the look freely; never give it a top or left.
|
||||
import type React from "react";
|
||||
import { Region, useRegion, useVideoConfig } from "raea";
|
||||
|
||||
type Props = {
|
||||
children: React.ReactNode;
|
||||
/** the band: "top" (default) for a hook, "bottom" for an offer or a CTA, "center" for a card */
|
||||
region?: "top" | "bottom" | "center";
|
||||
/** the size in px at 1080 wide (64) */
|
||||
size?: number;
|
||||
/** merged over the title's own style (colour, font, a backing box); not its place */
|
||||
style?: React.CSSProperties;
|
||||
};
|
||||
|
||||
/** how tall the title's lines are in a box `w` px wide: about 0.56 em a letter in a bold face, its line height and the
|
||||
* backing box's padding (`pad`, px top and bottom together) */
|
||||
export function heightIn(text: string, w: number, size: number, pad = 0): number {
|
||||
const perLine = Math.max(1, Math.floor(w / (0.56 * size)));
|
||||
const words = text.split(/\s+/).filter(Boolean);
|
||||
let lines = 1;
|
||||
let at = 0;
|
||||
for (const x of words) {
|
||||
const n = [...x].length;
|
||||
if (at && at + 1 + n > perLine) {
|
||||
lines++;
|
||||
at = n;
|
||||
} else at += (at ? 1 : 0) + n;
|
||||
}
|
||||
return lines * size * 1.1 + pad;
|
||||
}
|
||||
|
||||
/** the title's own text, for measuring */
|
||||
const textOf = (c: React.ReactNode): string => (typeof c === "string" || typeof c === "number" ? String(c) : Array.isArray(c) ? c.map(textOf).join("") : "");
|
||||
|
||||
/** draws `children` when the band it's in has room for them (when `fits`) or when the band before had none (`else`) */
|
||||
function Fit({ need, seen, children, when }: { need: number; seen: { top?: boolean }; children: React.ReactNode; when: "fits" | "else" }) {
|
||||
const box = useRegion();
|
||||
if (when === "fits") {
|
||||
seen.top = !!box && box.h >= need;
|
||||
return seen.top ? <>{children}</> : null;
|
||||
}
|
||||
return seen.top ? null : <>{children}</>;
|
||||
}
|
||||
|
||||
export default function Title({ children, region = "top", size = 64, style }: Props) {
|
||||
const align = (r: string) => (r === "bottom" ? "flex-end" : r === "center" ? "center" : "flex-start");
|
||||
const { width } = useVideoConfig();
|
||||
const px = size * (width / 1080);
|
||||
const pad = 2 * (typeof style?.padding === "string" ? parseFloat(style.padding) || 0 : typeof style?.padding === "number" ? style.padding : 0);
|
||||
// a hook at the top when the band over the face holds it; else in the middle, over the body and never the face
|
||||
// (12-05: street takes put the face right under the app's top zone, the top band had no height, and the hook ran down
|
||||
// over the face from it)
|
||||
// shared by the two bands in this frame's render: the top one draws first and says whether it held the hook
|
||||
const seen: { top?: boolean } = {};
|
||||
const text = textOf(children);
|
||||
const el = (
|
||||
<div
|
||||
style={{
|
||||
maxWidth: "100%",
|
||||
textAlign: "center",
|
||||
fontFamily: "var(--brand-font-heading, var(--brand-font, inherit))",
|
||||
fontWeight: 800,
|
||||
fontSize: size,
|
||||
lineHeight: 1.1,
|
||||
color: "var(--brand-text, #fff)",
|
||||
textShadow: "0 4px 24px rgba(0,0,0,0.55)",
|
||||
...style,
|
||||
position: undefined,
|
||||
top: undefined,
|
||||
left: undefined,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
if (region !== "top")
|
||||
return (
|
||||
<Region name={region} style={{ display: "flex", flexDirection: "column", justifyContent: align(region), alignItems: "center" }}>
|
||||
{el}
|
||||
</Region>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<Region name="top" style={{ display: "flex", flexDirection: "column", justifyContent: "flex-start", alignItems: "center" }}>
|
||||
<FitTop text={text} px={px} pad={pad} seen={seen}>
|
||||
{el}
|
||||
</FitTop>
|
||||
</Region>
|
||||
<Region name="center" style={{ display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
|
||||
<Fit need={0} seen={seen} when="else">
|
||||
{el}
|
||||
</Fit>
|
||||
</Region>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Fit at the top, its need measured in the band's own width */
|
||||
function FitTop({ text, px, pad, seen, children }: { text: string; px: number; pad: number; seen: { top?: boolean }; children: React.ReactNode }) {
|
||||
const box = useRegion();
|
||||
const need = box ? heightIn(text, box.w, px, pad) : Infinity;
|
||||
return (
|
||||
<Fit need={need} seen={seen} when="fits">
|
||||
{children}
|
||||
</Fit>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// components/brand.ts: the brand template every composed cut takes, read from the project's brand files, never typed per
|
||||
// cut: brand/brand.json (`raea brand SITE` writes it: colours by role, fonts, the CTA button, the logos in media/brand/;
|
||||
// prep writes {} when there's none) and brand/brand.css's --brand-* variables, which raea loads with every page. One
|
||||
// template, so every cut of a project looks the same: fonts, colours, the caption style, the logo, the end card and the
|
||||
// app's safe zones.
|
||||
import KIT from "../brand/brand.json";
|
||||
|
||||
type Logo = { file: string; type?: string; on?: "light" | "dark" | "any"; width?: number | null; height?: number | null };
|
||||
type Kit = {
|
||||
name?: string;
|
||||
palette?: { accent?: string | null; surface?: string | null; text_on_surface?: string | null; text_on_accent?: string | null; primary?: string | null };
|
||||
button?: { bg?: string | null; color?: string | null; radius?: number | null } | null;
|
||||
logos?: Logo[];
|
||||
radius?: number | null;
|
||||
};
|
||||
const kit = (KIT ?? {}) as Kit;
|
||||
|
||||
/** the brand's colours, as CSS: the kit's, else brand.css's variables, else neutral */
|
||||
export const COLORS = {
|
||||
surface: kit.palette?.surface ?? "var(--brand-background, #101010)",
|
||||
text: kit.palette?.text_on_surface ?? "var(--brand-text, #ffffff)",
|
||||
accent: kit.palette?.accent ?? "var(--brand-accent, #ffd23f)",
|
||||
onAccent: kit.palette?.text_on_accent ?? "var(--brand-background, #101010)",
|
||||
button: kit.button?.bg ?? kit.palette?.accent ?? "var(--brand-accent, #ffd23f)",
|
||||
buttonText: kit.button?.color ?? kit.palette?.text_on_accent ?? "var(--brand-background, #101010)",
|
||||
};
|
||||
export const FONTS = {
|
||||
heading: "var(--brand-font-heading, var(--brand-font, inherit))",
|
||||
body: "var(--brand-font, inherit)",
|
||||
};
|
||||
export const RADIUS = kit.button?.radius ?? kit.radius ?? 14;
|
||||
|
||||
/** the brand's logo for a background: one made for it ("light" for a light one), else any; null when the kit has none */
|
||||
export function logo(on: "light" | "dark" = "dark"): string | null {
|
||||
const ls = kit.logos ?? [];
|
||||
const l = ls.find((x) => x.on === on) ?? ls.find((x) => !x.on || x.on === "any") ?? ls[0];
|
||||
return l?.file ?? null;
|
||||
}
|
||||
|
||||
/** the caption style every cut takes: the brand's heading font, white with a shadow, the word being said and the key
|
||||
* words in the accent */
|
||||
export const CAPTION = { size: 84, accent: COLORS.accent, color: "var(--brand-text, #fff)" };
|
||||
|
||||
/** the app's UI zones (its header, buttons, caption and bar), px at this size: the same table raea's check and Region
|
||||
* hold text to (the box image's sdk/video zones.ts), so nothing placed here lands where the check says it can't */
|
||||
export function zones(width: number, height: number): { top: number; right: number; bottom: number; left: number } {
|
||||
const r = width / height;
|
||||
const s = width / 1080;
|
||||
if (r < 0.7) return { top: 220 * s, right: 140 * s, bottom: 420 * s, left: 60 * s };
|
||||
if (r < 0.9) return { top: 110 * s, right: 60 * s, bottom: 170 * s, left: 60 * s };
|
||||
if (r < 1.2) return { top: 70 * s, right: 60 * s, bottom: 120 * s, left: 60 * s };
|
||||
return { top: (120 * height) / 1080, right: (60 * width) / 1920, bottom: (120 * height) / 1080, left: (60 * width) / 1920 };
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// components/crop.ts: where the people are in a take over a span, and the window of the take a panel of any shape shows
|
||||
// so each one framed is whole, its eyes a third down, and no one else is cut by the panel's edge. Shot.tsx and Cut.tsx
|
||||
// lay out every layout from it (a split's two halves, a stack's speaker half, an insert's shot), from the faces the
|
||||
// box's prep found (footage/faces.json, image/faces.py), so no crop is a number an agent typed. Pure: no React.
|
||||
//
|
||||
// A take's faces: {"w", "h", "t": [seconds], "s": [[[cx, ey, fw, fh, score], ...], ...]}, shares of the picture, each
|
||||
// sample's largest first (faces.py).
|
||||
|
||||
export type Take = { w: number; h: number; t: number[]; s: number[][][] };
|
||||
/** someone in a take over a span: where their face sits (median), its largest size, and how often they're seen */
|
||||
export type Person = { cx: number; ey: number; fw: number; fh: number; seen: number; left: number; right: number };
|
||||
/** the part of a take a panel shows, in shares of the take: its left and top edges and its width and height */
|
||||
export type Win = { left: number; top: number; vw: number; vh: number; zoom: number };
|
||||
|
||||
const clamp = (x: number, a = 0, b = 1) => Math.min(b, Math.max(a, x));
|
||||
const median = (xs: number[]) => {
|
||||
const s = [...xs].sort((a, b) => a - b);
|
||||
return s.length ? s[Math.floor(s.length / 2)] : 0.5;
|
||||
};
|
||||
|
||||
/** a face this share of the take's height or more is someone in the shot; smaller, a passer-by */
|
||||
export const IN_SHOT = 0.05;
|
||||
/** room kept round the framed face, in its own widths, either side */
|
||||
export const ROOM = 1 / 3;
|
||||
/** the most a panel zooms into a take past cover. The render reads the originals, and a street take is a phone's 4K: 4x
|
||||
* of it is 960 px across for a 1080 panel, which holds. (faces.json is measured on the light copies, so it can't say
|
||||
* the original's size.) */
|
||||
export const MOST_ZOOM = 4;
|
||||
|
||||
/** the people in a take between `a` and `b` seconds, the most seen first: each sample's faces joined to the nearest
|
||||
* person already found (within a face width and a half across), so one person is one entry across the span */
|
||||
export function people(take: Take | undefined, a: number, b: number): Person[] {
|
||||
if (!take) return [];
|
||||
const runs: { cx: number[]; ey: number[]; fw: number[]; fh: number[]; n: number }[] = [];
|
||||
let samples = 0;
|
||||
for (let i = 0; i < take.t.length; i++) {
|
||||
if (take.t[i] < a - 0.5 || take.t[i] > b + 0.5) continue;
|
||||
samples++;
|
||||
for (const f of take.s[i] ?? []) {
|
||||
if (f[3] < IN_SHOT) continue;
|
||||
const near = runs.find((r) => Math.abs(median(r.cx) - f[0]) < 1.5 * Math.max(f[2], median(r.fw)));
|
||||
const r = near ?? (runs.push({ cx: [], ey: [], fw: [], fh: [], n: 0 }), runs[runs.length - 1]);
|
||||
r.cx.push(f[0]);
|
||||
r.ey.push(f[1]);
|
||||
r.fw.push(f[2]);
|
||||
r.fh.push(f[3]);
|
||||
r.n++;
|
||||
}
|
||||
}
|
||||
return runs
|
||||
.map((r) => {
|
||||
const fw = Math.max(...r.fw);
|
||||
return { cx: median(r.cx), ey: median(r.ey), fw, fh: Math.max(...r.fh), seen: samples ? r.n / samples : 0, left: Math.min(...r.cx) - fw / 2, right: Math.max(...r.cx) + fw / 2 };
|
||||
})
|
||||
.filter((p) => p.seen >= 0.3)
|
||||
.sort((p, q) => q.seen * q.fw - p.seen * p.fw);
|
||||
}
|
||||
|
||||
/** the person `who` names: a number is the face nearest that share across the take (0 left, 1 right), "left" and
|
||||
* "right" the leftmost and rightmost, anything else (or nothing) the largest */
|
||||
export function pick(ps: Person[], who?: number | string): Person | undefined {
|
||||
if (!ps.length) return undefined;
|
||||
if (typeof who === "number") return ps.reduce((p, q) => (Math.abs(q.cx - who) < Math.abs(p.cx - who) ? q : p));
|
||||
if (who === "left") return ps.reduce((p, q) => (q.cx < p.cx ? q : p));
|
||||
if (who === "right") return ps.reduce((p, q) => (q.cx > p.cx ? q : p));
|
||||
return ps[0];
|
||||
}
|
||||
|
||||
/** the window of `take` a panel `bw` x `bh` shows framed on `on`: the largest that holds the face whole with room and
|
||||
* cuts no one else (each other face either whole inside or wholly out), zoomed in up to MOST_ZOOM to leave the others
|
||||
* out when they'd be cut; the eyes a third down. With `alone`, zoomed until no one else shows, when that's possible */
|
||||
export function windowOn(take: Take, bw: number, bh: number, on: Person | undefined, others: Person[], alone = false): Win {
|
||||
const box = bw / bh;
|
||||
const src = take.w / take.h;
|
||||
// the window at zoom 1 (object-fit: cover), in shares of the take
|
||||
const vw1 = Math.min(1, box / src);
|
||||
const vh1 = Math.min(1, src / box);
|
||||
if (!on) return { left: (1 - vw1) / 2, top: (1 - vh1) / 2, vw: vw1, vh: vh1, zoom: 1 };
|
||||
const lo = on.left - on.fw * ROOM;
|
||||
const hi = on.right + on.fw * ROOM;
|
||||
const cuts = (l: number, vw: number) => others.some((o) => (l > o.left && l < o.right) || (l + vw > o.left && l + vw < o.right));
|
||||
const shows = (l: number, vw: number) => others.some((o) => o.right > l && o.left < l + vw);
|
||||
for (let zoom = 1; zoom <= MOST_ZOOM + 1e-6; zoom += 0.05) {
|
||||
const vw = vw1 / zoom;
|
||||
const vh = vh1 / zoom;
|
||||
if (hi - lo > vw) break; // the face and its room no longer fit: the last zoom that held it is the answer below
|
||||
const ideal = clamp(on.cx - vw / 2, 0, 1 - vw);
|
||||
// the left edges that keep the face and its room: from hi - vw to lo, inside the take
|
||||
const a = clamp(hi - vw, 0, 1 - vw);
|
||||
const b = clamp(lo, 0, 1 - vw);
|
||||
if (a > b) continue;
|
||||
const tries = [ideal, a, b, ...others.flatMap((o) => [o.right + 0.005, o.left - vw - 0.005])].map((l) => clamp(l, a, b));
|
||||
const ok = tries.filter((l) => !cuts(l, vw) && (!alone || !shows(l, vw)));
|
||||
if (ok.length) {
|
||||
const left = ok.reduce((x, y) => (Math.abs(y - ideal) < Math.abs(x - ideal) ? y : x));
|
||||
const top = clamp(on.ey - vh / 3, 0, 1 - vh);
|
||||
return { left, top, vw, vh, zoom };
|
||||
}
|
||||
}
|
||||
// no window shows them alone: the clean one that shows others too
|
||||
if (alone) return windowOn(take, bw, bh, on, others, false);
|
||||
// nothing clean: the face whole at zoom 1, centred on it (the check says what it cuts)
|
||||
return { left: clamp(on.cx - vw1 / 2, 0, 1 - vw1), top: clamp(on.ey - vh1 / 3, 0, 1 - vh1), vw: vw1, vh: vh1, zoom: 1 };
|
||||
}
|
||||
|
||||
/** whether a window can show `on` alone (no one else in it), for a split's halves */
|
||||
export function holdsAlone(take: Take, bw: number, bh: number, on: Person, others: Person[]): boolean {
|
||||
const w = windowOn(take, bw, bh, on, others, true);
|
||||
return !others.some((o) => o.right > w.left && o.left < w.left + w.vw) && on.left >= w.left - 1e-3 && on.right <= w.left + w.vw + 1e-3;
|
||||
}
|
||||
|
||||
/** a window as CSS for a <Video> filling a panel: the video's own box (px, inside the panel, overflow hidden), cover
|
||||
* fitted, and its object-position. The render's manifest then holds the window exactly (box, clip, position) */
|
||||
export function css(win: Win, bw: number, bh: number): { left: number; top: number; width: number; height: number; objectPosition: string } {
|
||||
const width = bw * win.zoom;
|
||||
const height = bh * win.zoom;
|
||||
// the window at zoom 1 (cover of the enlarged box), and where the panel sits inside it
|
||||
const vw1 = win.vw * win.zoom;
|
||||
const vh1 = win.vh * win.zoom;
|
||||
// the enlarged box shows [l1, l1 + vw1] of the take; the panel the middle `vw` of it at offset (left - l1)
|
||||
const l1 = clamp(win.left - (vw1 - win.vw) / 2, 0, 1 - vw1);
|
||||
const t1 = clamp(win.top - (vh1 - win.vh) / 3, 0, 1 - vh1);
|
||||
const px = vw1 >= 1 ? 50 : (l1 / (1 - vw1)) * 100;
|
||||
const py = vh1 >= 1 ? 50 : (t1 / (1 - vh1)) * 100;
|
||||
const left = -((win.left - l1) / vw1) * width;
|
||||
const top = -((win.top - t1) / vh1) * height;
|
||||
return { left, top, width, height, objectPosition: `${+px.toFixed(3)}% ${+py.toFixed(3)}%` };
|
||||
}
|
||||
|
||||
/** a face's box on screen (px), when its take's window `win` fills the panel at `x`, `y`, `bw` x `bh` */
|
||||
export function onScreen(p: Pick<Person, "cx" | "ey" | "fw" | "fh">, win: Win, x: number, y: number, bw: number, bh: number): [number, number, number, number] {
|
||||
const sx = bw / win.vw;
|
||||
const sy = bh / win.vh;
|
||||
const top = p.ey - 0.4 * p.fh; // the eyes sit about 0.4 of the way down a face's box (YuNet's)
|
||||
return [x + (p.cx - p.fw / 2 - win.left) * sx, y + (top - win.top) * sy, p.fw * sx, p.fh * sy];
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A take's faces, twice a second, for framing it (12-05, Shane: "the ai fucks up the composition of subjects in frame all
|
||||
the time"). The agent placed each 9:16 crop by a number it guessed (objectPosition), and cut the speaker off at the edge
|
||||
while the middle held a bench. This finds where the faces are, so components/Framed.tsx places the crop on them.
|
||||
|
||||
faces.py TAKE... -o OUT.json one JSON object, by each take's name without its extension:
|
||||
{"w": W, "h": H, "t": [seconds, ...], "s": [[[cx, ey, fw, fh, score], ...], ...]}
|
||||
|
||||
cx: the face's centre across, ey: its eyes down, fw and fh: its size, all in shares of the picture; a sample's faces
|
||||
largest first, at most 3, those YuNet scores 0.7 or more, at each of the take's keyframes (a phone's come about once a
|
||||
second: only they are decoded, so a take is read many times faster than played; 12-05, every frame took 343 s for
|
||||
a 36-take street shoot). A take it can't read is left out (the component then centres).
|
||||
YuNet (opencv_zoo face_detection_yunet_2023mar, MIT) on the CPU: a 640-wide frame in a few ms.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
MODEL = os.environ.get("RAEA_YUNET", "/opt/yunet.onnx")
|
||||
WIDE = 640
|
||||
LEAST = 0.7
|
||||
MOST = 3
|
||||
|
||||
|
||||
def size(take):
|
||||
r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:stream_side_data=rotation", "-of", "json", take], capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
||||
s = (json.loads(r.stdout or "{}").get("streams") or [{}])[0]
|
||||
w, h = int(s.get("width") or 0), int(s.get("height") or 0)
|
||||
rot = next((abs(int(d.get("rotation", 0))) for d in s.get("side_data_list") or [] if "rotation" in d), 0)
|
||||
return (h, w) if rot in (90, 270) else (w, h)
|
||||
|
||||
|
||||
def keytimes(take):
|
||||
"""the keyframes' times, from the packets' flags (nothing decoded): the frames -skip_frame nokey gives, in order"""
|
||||
r = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time,flags", "-of", "csv=p=0", take], capture_output=True, text=True, stdin=subprocess.DEVNULL)
|
||||
ts = []
|
||||
for line in r.stdout.splitlines():
|
||||
f = line.split(",")
|
||||
if len(f) >= 2 and "K" in f[1]:
|
||||
try:
|
||||
ts.append(round(float(f[0]), 2))
|
||||
except ValueError:
|
||||
pass
|
||||
return sorted(ts)
|
||||
|
||||
|
||||
def faces(take):
|
||||
w, h = size(take)
|
||||
if not w or not h:
|
||||
return None
|
||||
ts = keytimes(take)
|
||||
sw, sh = WIDE, max(2, round(WIDE * h / w / 2) * 2)
|
||||
det = cv2.FaceDetectorYN.create(MODEL, "", (sw, sh), LEAST, 0.3, 50)
|
||||
p = subprocess.Popen(["ffmpeg", "-nostdin", "-v", "error", "-skip_frame", "nokey", "-i", take, "-fps_mode", "passthrough", "-vf", f"scale={sw}:{sh}", "-f", "rawvideo", "-pix_fmt", "bgr24", "-"], stdout=subprocess.PIPE, stdin=subprocess.DEVNULL)
|
||||
n = sw * sh * 3
|
||||
out = []
|
||||
while True:
|
||||
b = p.stdout.read(n)
|
||||
if len(b) < n:
|
||||
break
|
||||
im = np.frombuffer(b, np.uint8).reshape(sh, sw, 3)
|
||||
_, got = det.detect(im)
|
||||
fs = []
|
||||
for f in got if got is not None else []:
|
||||
x, y, fw, fh = (float(v) for v in f[:4])
|
||||
ey = (float(f[5]) + float(f[7])) / 2 # the right eye's y and the left's
|
||||
fs.append([round((x + fw / 2) / sw, 3), round(ey / sh, 3), round(fw / sw, 3), round(fh / sh, 3), round(float(f[14]), 2)])
|
||||
fs.sort(key=lambda f: -f[2] * f[3])
|
||||
out.append(fs[:MOST])
|
||||
p.wait()
|
||||
k = min(len(ts), len(out))
|
||||
return {"w": w, "h": h, "t": ts[:k], "s": out[:k]}
|
||||
|
||||
|
||||
def main(a):
|
||||
if "-o" not in a or a.index("-o") + 1 >= len(a):
|
||||
print(__doc__, file=sys.stderr)
|
||||
return 2
|
||||
o = a[a.index("-o") + 1]
|
||||
takes = [x for i, x in enumerate(a) if x != "-o" and (i == 0 or a[i - 1] != "-o")]
|
||||
cv2.setNumThreads(1)
|
||||
res = {}
|
||||
with ThreadPoolExecutor(os.cpu_count() or 2) as ex:
|
||||
for take, got in zip(takes, ex.map(lambda t: (lambda: faces(t))() if os.path.exists(t) else None, takes)):
|
||||
if got and any(got["s"]):
|
||||
res[os.path.splitext(os.path.basename(take))[0]] = got
|
||||
with open(o + ".part", "w") as f:
|
||||
json.dump(res, f, separators=(",", ":"))
|
||||
os.replace(o + ".part", o)
|
||||
print(f"faces: {len(res)} of {len(takes)} takes", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -8,7 +8,7 @@
|
||||
// POST /v1/claude-token/check {token} {ok, said}: one short turn on a token
|
||||
import { type ChildProcess, spawn } from "node:child_process"
|
||||
import { randomBytes } from "node:crypto"
|
||||
import { mkdtempSync, rmSync } from "node:fs"
|
||||
import { existsSync, mkdtempSync, rmSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
@@ -48,7 +48,9 @@ while True:
|
||||
os.write(fd, b)
|
||||
os.kill(pid, 9) if os.waitpid(pid, os.WNOHANG) == (0, 0) else None
|
||||
`
|
||||
const CLAUDE = process.env.RAEA_CLAUDE_BIN ?? "claude"
|
||||
// Claude Code where the image installs it (~/.local/bin, the agents' own), not only on the server's PATH, which holds the
|
||||
// system's folders alone: 12-05, a sign-in link answered "No such file or directory" and no one could connect Claude
|
||||
const CLAUDE = process.env.RAEA_CLAUDE_BIN ?? [path.join(process.env.HOME ?? "/home/raea", ".local/bin/claude"), "/home/raea/.local/bin/claude"].find((p) => existsSync(p)) ?? "claude"
|
||||
const TOKEN = /sk-ant-oat01-[A-Za-z0-9_-]{20,}/
|
||||
|
||||
/** the text a terminal shows, with its escapes gone; OSC 8 links keep their address */
|
||||
|
||||
+23
-12
@@ -144,8 +144,9 @@ const SMALL = 256 << 10
|
||||
|
||||
/** the farm's cache of media (farm.py POST /v1/blobs/have, PUT /v1/blobs/OID), over its own token */
|
||||
export interface FarmBlobs {
|
||||
/** which of these it holds; null when this farm has no cache (an older one): the media goes in the tar */
|
||||
have(objects: { oid: string; size: number }[]): Promise<Set<string> | null>
|
||||
/** which of these it holds, and whether it fetches an original of unknown size by its link; null when this farm has
|
||||
* no cache (an older one): the media goes in the tar */
|
||||
have(objects: { oid: string; size: number }[]): Promise<{ held: Set<string>; links: boolean } | null>
|
||||
put(file: string, oid: string, size: number): Promise<void>
|
||||
}
|
||||
|
||||
@@ -156,7 +157,8 @@ export function farmBlobs(url: string, token: string): FarmBlobs {
|
||||
const r = await fetch(`${url}/v1/blobs/have`, { method: "POST", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify({ objects }) })
|
||||
if (r.status === 404) return null
|
||||
if (!r.ok) throw new Error(`the farm's media cache answered ${r.status}: ${(await r.text()).slice(0, 200)}`)
|
||||
return new Set(((await r.json()) as { have: string[] }).have)
|
||||
const j = (await r.json()) as { have: string[]; links?: number }
|
||||
return { held: new Set(j.have), links: j.links === 1 }
|
||||
},
|
||||
async put(file, oid, size) {
|
||||
// streamed from the disk: a file is never held in memory (a project's interviews are gigabytes)
|
||||
@@ -199,7 +201,7 @@ function hashes(file: string) {
|
||||
* farm's cache and named in the job's manifest with no href, so a render's tar holds the code and not the footage
|
||||
* (StreetTalk's 1.9 GB of interviews went in every render's tar, even one frame's). null when the farm has no cache.
|
||||
* `skip`: the tar's excludes. Links are left to the tar, as before. */
|
||||
export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string) => boolean = () => false, said: (s: string) => void = () => {}, store = path.join(os.homedir(), ".cache", "raea-offload", "hashes.json")): Promise<{ media: Media[]; sent: number } | null> {
|
||||
export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string) => boolean = () => false, said: (s: string) => void = () => {}, store = path.join(os.homedir(), ".cache", "raea-offload", "hashes.json"), instead: Map<string, string> = new Map()): Promise<{ media: Media[]; sent: number; links: boolean } | null> {
|
||||
const found: { path: string; abs: string; id: string; size: number; mtime: number }[] = []
|
||||
const walk = (dir: string) => {
|
||||
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
||||
@@ -208,20 +210,26 @@ export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string
|
||||
if (skip(rel)) continue
|
||||
if (e.isDirectory()) walk(abs)
|
||||
else if (e.isFile()) {
|
||||
const st = statSync(abs)
|
||||
// `instead`: a light copy whose original is here goes as that file, under the light copy's path (originals.ts)
|
||||
const file = instead.get(rel) ?? abs
|
||||
const st = statSync(file)
|
||||
const ext = e.name.includes(".") ? e.name.split(".").pop()!.toLowerCase() : ""
|
||||
if (st.size >= LARGE || (st.size >= SMALL && MEDIA.has(ext))) found.push({ path: rel, abs, id: `${st.dev}:${st.ino}`, size: st.size, mtime: st.mtimeMs })
|
||||
if (st.size >= LARGE || (st.size >= SMALL && MEDIA.has(ext))) found.push({ path: rel, abs: file, id: `${st.dev}:${st.ino}`, size: st.size, mtime: st.mtimeMs })
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
if (!found.length) return { media: [], sent: 0 }
|
||||
if (!found.length) {
|
||||
const can = await farm.have([])
|
||||
return can ? { media: [], sent: 0, links: can.links } : null
|
||||
}
|
||||
const h = hashes(store)
|
||||
const media: (Media & { abs: string })[] = []
|
||||
for (const f of found) media.push({ path: f.path, oid: await h.of(f.abs, f.id, f.size, f.mtime), size: f.size, abs: f.abs })
|
||||
h.save()
|
||||
const have = await farm.have(media.map(({ oid, size }) => ({ oid, size })))
|
||||
if (!have) return null
|
||||
const can = await farm.have(media.map(({ oid, size }) => ({ oid, size })))
|
||||
if (!can) return null
|
||||
const have = can.held
|
||||
let sent = 0
|
||||
const todo = media.filter((m, i) => !have.has(m.oid) && media.findIndex((x) => x.oid === m.oid) === i)
|
||||
if (todo.length) said(`sending ${todo.length} media files (${(todo.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) to the farm's cache, once`)
|
||||
@@ -234,7 +242,7 @@ export async function farmInputs(root: string, farm: FarmBlobs, skip: (p: string
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(4, todo.length) }, one))
|
||||
return { media: media.map(({ abs: _, ...m }) => m), sent }
|
||||
return { media: media.map(({ abs: _, ...m }) => m), sent, links: can.links }
|
||||
}
|
||||
|
||||
/** the project's video and audio that no source file names, which a render doesn't need: neither sent to the farm nor
|
||||
@@ -270,7 +278,9 @@ export function unusedMedia(root: string, skip: (p: string) => boolean = () => f
|
||||
return text.includes(rel) || text.includes(name) || (stem.length >= 3 && text.includes(stem) && (!folder || text.includes(folder)))
|
||||
}
|
||||
const used = av.filter(named)
|
||||
return used.length ? av.filter((f) => !used.includes(f)) : []
|
||||
// footage/originals/ (the full-size takes, gigabytes) goes only when a source names it, even when none names anything
|
||||
// (12-05 review): an original by its file goes in its light copy's place (originals.ts), not as itself
|
||||
return used.length ? av.filter((f) => !used.includes(f)) : av.filter((f) => f.startsWith("footage/originals/"))
|
||||
}
|
||||
|
||||
/** tar's exclude-from lines for paths that go by hash: each matched as written (glob characters escaped) */
|
||||
@@ -285,7 +295,8 @@ export function localSources(manifest: { sounds?: { clips?: { src: string }[] }
|
||||
const byOid = new Map(media.map((m) => [m.oid, m.path]))
|
||||
let n = 0
|
||||
for (const c of manifest.sounds?.clips ?? []) {
|
||||
const oid = /(?:^|\/)(?:blobs\/)?([0-9a-f]{64})$/.exec(c.src)?.[1]
|
||||
// the farm's blob (blobs/OID) or the same under its own name (blobs/named/OID/NAME)
|
||||
const oid = /(?:^|\/)(?:blobs\/)?(?:named\/)?([0-9a-f]{64})(?:\/[^/]+)?$/.exec(c.src)?.[1]
|
||||
const p = oid ? byOid.get(oid) : undefined
|
||||
if (p) {
|
||||
c.src = path.join(root, p)
|
||||
|
||||
+61
-15
@@ -22,6 +22,7 @@ import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { RaeaCloud } from "../src/index.ts"
|
||||
import { excluded, excludes as mediaExcludes, farmBlobs, farmInputs, inputs, lfsOf, localSources, outputs, unusedMedia } from "./media.ts"
|
||||
import { lightCopies, originalsRecord, recordOriginals, resolveOriginals, settle, withOriginals } from "./originals.ts"
|
||||
|
||||
const REAL = process.env.RAEA_REAL ?? "/opt/raea/bin/raea"
|
||||
// flags whose value is a path raea writes; the rest of a render's path arguments are read
|
||||
@@ -31,12 +32,24 @@ const COMPOSITION = /\.(tsx|ts|jsx|js|mjs|html)$/
|
||||
|
||||
const say = (s: string) => process.stderr.write(`raea cloud: ${s}\n`)
|
||||
|
||||
function local(args: string[], why?: string): never {
|
||||
function local(args: string[], why?: string, root?: string): never {
|
||||
if (why) say(`${why}, so this runs here, on the CPU`)
|
||||
// here every take is its light copy: the record says so, as the farm's would (CL20)
|
||||
const lit = lightCopies(root ?? process.cwd())
|
||||
if (lit.length) say(`NO ORIGINAL: a render here reads footage's light copies, so it's a draft that's never shown or published`)
|
||||
const r = spawnSync(REAL, args, { stdio: "inherit" })
|
||||
const oi = args.indexOf("-o")
|
||||
const mi = args.indexOf("--manifest")
|
||||
const out = oi >= 0 ? path.resolve(process.cwd(), args[oi + 1] ?? "") : ""
|
||||
if (lit.length && !r.status && out && existsSync(out)) keep(out, mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : null, { read: [], light: [...lit].sort() })
|
||||
process.exit(r.status ?? 1)
|
||||
}
|
||||
|
||||
/** the render's record of what it read (originals.ts recordOriginals), said aloud when it couldn't be kept */
|
||||
function keep(out: string, manifest: string | null, rec: { read: string[]; light: string[] }) {
|
||||
for (const f of recordOriginals(out, manifest, rec).failed) say(`WARNING: couldn't add what this render read to ${f} (not a JSON object): raea cloud can't tell whether it read a light copy`)
|
||||
}
|
||||
|
||||
const inside = (root: string, p: string) => p === root || p.startsWith(root + path.sep)
|
||||
|
||||
/** The project a render's composition is in: its folder, or the nearest above it that holds a project's files. */
|
||||
@@ -92,7 +105,7 @@ async function main() {
|
||||
{
|
||||
const oi = args.indexOf("-o")
|
||||
const o = oi >= 0 ? (args[oi + 1] ?? "") : ""
|
||||
if (args[0] === "render" && /\.(mp4|mov|m4v|webm)$/i.test(o) && !args.includes("--manifest") && process.env.RAEA_CLOUD_CHECK !== "0")
|
||||
if (args[0] === "render" && /\.(mp4|mov|m4v|webm)$/i.test(o) && !args.includes("--manifest"))
|
||||
args.push("--manifest", `${o.slice(0, o.length - path.extname(o).length)}.render.json`)
|
||||
}
|
||||
const url = process.env.RAEA_CLOUD_GPU_URL
|
||||
@@ -105,7 +118,7 @@ async function main() {
|
||||
try {
|
||||
// kits/ (raea-game-kit) is a link into the box's shared cache, hundreds of MB, that the farm can't follow: a
|
||||
// composition uses copies of the kit files it needs in its own folder (11-21: the dangling link hung farm jobs)
|
||||
const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out ./.raea-cloud-out-* ./kits").split(/\s+/).filter(Boolean)
|
||||
const excludes = (process.env.RAEA_CLOUD_GPU_EXCLUDE ?? "./.git ./out/* ./.raea-cloud-out ./.raea-cloud-out-* ./kits ./.raea-cloud/proxies").split(/\s+/).filter(Boolean)
|
||||
// zstd with GNU tar (the image's); gzip with another tar (a Mac's), whose zstd needs a program of its own
|
||||
const gnu = spawnSync("tar", ["--version"], { encoding: "utf8" }).stdout?.includes("GNU")
|
||||
const sent = path.join(tmp, "in.tar")
|
||||
@@ -115,15 +128,29 @@ async function main() {
|
||||
const unused = new Set(unusedMedia(p.root, excluded(excludes)))
|
||||
if (unused.size) say(`${unused.size} video and audio files no source names stay here`)
|
||||
const skip = (rel: string) => excluded(excludes)(rel) || unused.has(rel)
|
||||
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, skip)
|
||||
// each light copy the render reads goes as its full-size original (originals.ts): by its link, fetched by the farm
|
||||
// itself, else by its file here. The light copy's own bytes never go
|
||||
let orig = resolveOriginals(p.root, (rel) => !skip(rel))
|
||||
const linked = new Set(orig.byLink.map((m) => m.path))
|
||||
// what stays out of the farm's cache and LFS: what's skipped, and each light copy whose original goes by its link
|
||||
const unsent = (rel: string) => skip(rel) || linked.has(rel)
|
||||
let byHash = typeof lfs === "string" ? [] : await inputs(p.root, lfs, unsent)
|
||||
// not in raea's LFS: the media goes into the farm's own cache by hash, once, instead of in every render's tar
|
||||
// (RAEA_CLOUD_GPU_BLOBS=0 puts it back in the tar). A farm without the cache, or one that can't be reached here,
|
||||
// leaves it in the tar, and the health check below says why the farm can't be reached
|
||||
let viaFarm: { media: typeof byHash; sent: number } | null = null
|
||||
let viaFarm: { media: typeof byHash; sent: number; links: boolean } | null = null
|
||||
if (typeof lfs === "string" && process.env.RAEA_CLOUD_GPU_BLOBS !== "0") {
|
||||
viaFarm = await farmInputs(p.root, farmBlobs(url, token), skip, say).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
|
||||
viaFarm = await farmInputs(p.root, farmBlobs(url, token), unsent, say, undefined, orig.byFile).catch((e) => (say(`the farm's media cache: ${(e as Error).message}; the media goes in the tar`), null))
|
||||
if (viaFarm) byHash = viaFarm.media
|
||||
}
|
||||
// what reaches the farm decides what the render reads, decided once for every path: each original by its link in its
|
||||
// light copy's place; what can't go is the light copy, recorded
|
||||
// (LFS: the farm fetches by size from R2, so an original of unknown size or by its file can't go)
|
||||
orig = settle(orig, viaFarm ? { links: viaFarm.links } : null)
|
||||
byHash = withOriginals(byHash, orig)
|
||||
if (orig.byLink.length || orig.byFile.size) say(`${orig.byLink.length + orig.byFile.size} takes go as their full-size originals${orig.byLink.length ? ` (${orig.byLink.length} fetched by the farm from the library)` : ""}`)
|
||||
for (const w of orig.why) say(w)
|
||||
if (orig.light.length) say(`NO ORIGINAL for ${orig.light.join(", ")}: rendered from the light copy, so this render is a draft that's never shown or published`)
|
||||
const extra: string[] = []
|
||||
if (unused.size) {
|
||||
writeFileSync(path.join(tmp, "unused-excludes"), mediaExcludes([...unused].map((f) => ({ path: f, oid: "", size: 0 }))))
|
||||
@@ -144,16 +171,20 @@ async function main() {
|
||||
try {
|
||||
h = await cloud.health()
|
||||
} catch (e) {
|
||||
if (process.env.RAEA_CLOUD_GPU_FALLBACK === "cpu") local(args, `the GPU worker at ${url} didn't answer (${(e as Error).message})`)
|
||||
if (process.env.RAEA_CLOUD_GPU_FALLBACK === "cpu") local(args, `the GPU worker at ${url} didn't answer (${(e as Error).message})`, p.root)
|
||||
throw new Error(`the GPU worker at ${url} didn't answer: ${(e as Error).message} (RAEA_CLOUD_GPU_FALLBACK=cpu renders here instead)`)
|
||||
}
|
||||
say(`rendering on ${new URL(url).host}, ${h.device.renders === "gpu" ? `GPU ${h.device.name}` : `its CPU (${h.device.name})`}: ${p.root} (${(folder.length / 1e6).toFixed(1)} MB) sent`)
|
||||
if (viaFarm && byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash from the farm's cache${viaFarm.sent ? `, ${(viaFarm.sent / 1e6).toFixed(1)} MB of it sent now` : ""}`)
|
||||
else if (byHash.length) say(`${byHash.length} media files (${(byHash.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)} MB) go by hash: the farm fetches them from R2`)
|
||||
// what's fetched from the library by its link is counted apart: its size may be unknown
|
||||
const cached = byHash.filter((m) => !("href" in m && orig.byLink.some((l) => l.path === m.path)))
|
||||
const mb = (ms: { size: number }[]) => (ms.reduce((n, m) => n + m.size, 0) / 1e6).toFixed(1)
|
||||
if (viaFarm && cached.length) say(`${cached.length} media files (${mb(cached)} MB) go by hash from the farm's cache${viaFarm.sent ? `, ${(viaFarm.sent / 1e6).toFixed(1)} MB of it sent now` : ""}`)
|
||||
else if (cached.length) say(`${cached.length} media files (${mb(cached)} MB) go by hash: the farm fetches them from R2`)
|
||||
else if (typeof lfs === "string" && existsSync(path.join(p.root, ".lfsconfig"))) say(`media goes in the tar: ${lfs}`)
|
||||
// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND, RAEA_CLOUD_MAX_USD
|
||||
// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND (the card: it went as "gpu",
|
||||
// which the client never read, so a named card never reached the farm), RAEA_CLOUD_MAX_USD, RAEA_CLOUD_NV (1 or 0)
|
||||
const n = (v?: string) => (v ? Number(v) : undefined)
|
||||
const farm = { gpus: n(process.env.RAEA_CLOUD_GPUS), cpus: n(process.env.RAEA_CLOUD_CPUS), kept: process.env.RAEA_CLOUD_KEPT === "0" ? false : undefined, gpu: process.env.RAEA_CLOUD_GPU_KIND, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD), media: typeof lfs !== "string" }
|
||||
const farm = { gpus: n(process.env.RAEA_CLOUD_GPUS), cpus: n(process.env.RAEA_CLOUD_CPUS), kept: process.env.RAEA_CLOUD_KEPT === "0" ? false : undefined, card: process.env.RAEA_CLOUD_GPU_KIND || undefined, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD), nv: process.env.RAEA_CLOUD_NV === "1" ? true : process.env.RAEA_CLOUD_NV === "0" ? false : undefined, media: typeof lfs !== "string" }
|
||||
let finish: (() => Promise<number>) | undefined
|
||||
const media = typeof lfs === "string" ? undefined : async (made: Parameters<typeof outputs>[2]) => {
|
||||
const o = await outputs(p.root, lfs, made)
|
||||
@@ -181,6 +212,13 @@ async function main() {
|
||||
}
|
||||
rmSync(path.join(p.root, ".raea-cloud-out"), { recursive: true, force: true })
|
||||
for (const m of p.moves) rmSync(path.join(p.root, m.from), { force: true })
|
||||
// what it read, kept with it whether it's checked or not, video or still (CL20)
|
||||
{
|
||||
const oi = args.indexOf("-o")
|
||||
const mi = args.indexOf("--manifest")
|
||||
const out = oi >= 0 ? path.resolve(process.cwd(), args[oi + 1] ?? "") : ""
|
||||
if (out && existsSync(out)) keep(out, mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : null, originalsRecord(orig))
|
||||
}
|
||||
if (finish) {
|
||||
const bytes = await finish()
|
||||
say(`its media (${(bytes / 1e6).toFixed(1)} MB) went from the farm to R2; here it's pointers (git lfs pull PATH brings one here)`)
|
||||
@@ -201,20 +239,25 @@ async function main() {
|
||||
const man = mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : ""
|
||||
const beside = `${made.slice(0, made.length - path.extname(made).length)}.render.json`
|
||||
if (man && man !== beside && existsSync(man)) writeFileSync(beside, readFileSync(man))
|
||||
// its takes named as they are here, not as the farm's cache holds them, so every edit point is checked
|
||||
if (byHash.length && existsSync(beside)) {
|
||||
// its takes named as they are here, not as the farm's cache holds them, so every edit point is checked; and which
|
||||
// light copies it read as their originals and which as themselves (raea cloud shows none of the latter)
|
||||
if (existsSync(beside)) {
|
||||
try {
|
||||
const m = JSON.parse(readFileSync(beside, "utf8"))
|
||||
if (localSources(m, byHash, p.root)) writeFileSync(beside, JSON.stringify(m))
|
||||
if (byHash.length && localSources(m, byHash, p.root)) writeFileSync(beside, JSON.stringify(m))
|
||||
} catch (e) {
|
||||
say(`${path.basename(beside)}: ${(e as Error).message}`)
|
||||
}
|
||||
}
|
||||
say(`raea goal check ${path.basename(made)} --at render`)
|
||||
const r = spawnSync(REAL, ["make", "check", made, "--at", "render"], { stdio: "inherit", env: { ...process.env, RAEA_REAL: REAL } })
|
||||
const r = spawnSync(REAL, CHECK_ARGS(made), { stdio: "inherit", env: { ...process.env, RAEA_REAL: REAL } })
|
||||
if (r.status === 1) {
|
||||
say(`${path.basename(made)} fails its checks: fix every ERROR above (each says what to change), then render again before any review`)
|
||||
process.exitCode = 1
|
||||
} else if (r.status !== 0) {
|
||||
// a refused or crashed check is loud: called by an old name, it was refused with exit 2 and every cloud render went unchecked
|
||||
say(`raea goal check couldn't check ${path.basename(made)} (exit ${r.status ?? r.signal}): the render isn't done until it can`)
|
||||
process.exitCode = r.status || 1
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -222,6 +265,9 @@ async function main() {
|
||||
}
|
||||
}
|
||||
|
||||
/** raea's one check on a finished render, as the box runs it */
|
||||
export const CHECK_ARGS = (made: string) => ["goal", "check", made, "--at", "render"]
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
|
||||
main().catch((e) => {
|
||||
say((e as Error).message)
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// Light copies on the box, originals on the farm (docs/cloud.feature CL17-CL20). raea cloud brings a run's footage onto
|
||||
// its box as 540p light copies (footage/NAME.mp4, listed in .raea-cloud/light.txt): every look the agent takes reads
|
||||
// them, and nothing on the box ever puts anything else in their place. A render on the farm reads each one's full-size
|
||||
// original instead, resolved here as the render is sent:
|
||||
//
|
||||
// by its link .raea-cloud/originals.json, written by raea cloud at the run's start and again before each render:
|
||||
// {"footage/NAME.mp4": {"sha256", "bytes", "url", "expires"}}. The farm fetches the original from the
|
||||
// library itself and keeps it by its hash, so the box never downloads it or sends it on (12-05, Dutch
|
||||
// run 24: each run's box fetched 2.4 GB of originals and hashed and sent them to the farm again)
|
||||
// by its file footage/originals/NAME.EXT, fetched onto the box for a take the library has no hash for: sent in the
|
||||
// light copy's place, by its own hash
|
||||
//
|
||||
// A light copy with neither is rendered as itself and named in the render's manifest ("originals": {"light": [...]}),
|
||||
// so raea cloud never shows or publishes what was made from it.
|
||||
|
||||
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import type { Media } from "../src/index.ts"
|
||||
|
||||
export const LIGHT_LIST = ".raea-cloud/light.txt"
|
||||
export const ORIGINALS_MAP = ".raea-cloud/originals.json"
|
||||
export const ORIGINALS_DIR = "footage/originals"
|
||||
/** a link that ends sooner than this isn't handed to the farm: it would be gone before the farm asks for it */
|
||||
export const LINK_MARGIN_MS = 5 * 60_000
|
||||
|
||||
export interface Original {
|
||||
sha256?: string
|
||||
bytes?: number
|
||||
url?: string
|
||||
/** when the link stops working (ms since 1970); none, it's taken as working */
|
||||
expires?: number
|
||||
}
|
||||
|
||||
/** where each light copy a render reads comes from */
|
||||
export interface Resolved {
|
||||
/** fetched by the farm from its link: the light copy's path, the original's hash, size and link */
|
||||
byLink: (Media & { href: string })[]
|
||||
/** sent from the box: the light copy's path, the original's file here */
|
||||
byFile: Map<string, string>
|
||||
/** rendered as themselves: no usable link and no file */
|
||||
light: string[]
|
||||
/** why a light copy's link wasn't used, a line each */
|
||||
why: string[]
|
||||
}
|
||||
|
||||
const read = (f: string) => {
|
||||
try {
|
||||
return readFileSync(f, "utf8")
|
||||
} catch {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
const stem = (n: string) => n.replace(/\.[^./]*$/, "")
|
||||
const HASH = /^[0-9a-f]{64}$/
|
||||
|
||||
/** the light copies here, as paths from the project's top (footage/NAME.mp4) */
|
||||
export function lightCopies(root: string): string[] {
|
||||
const names = read(path.join(root, LIGHT_LIST)).split("\n").map((s) => s.trim()).filter(Boolean)
|
||||
return [...new Set(names.map((n) => (n.startsWith("footage/") ? n : `footage/${n}`)))].filter((p) => !p.includes("..") && existsSync(path.join(root, p)))
|
||||
}
|
||||
|
||||
/** .raea-cloud/originals.json, each entry kept only when it's a light copy's path and an object */
|
||||
export function originalsMap(root: string): Record<string, Original> {
|
||||
let j: unknown
|
||||
try {
|
||||
j = JSON.parse(read(path.join(root, ORIGINALS_MAP)) || "{}")
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
const out: Record<string, Original> = {}
|
||||
if (!j || typeof j !== "object" || Array.isArray(j)) return out
|
||||
for (const [k, v] of Object.entries(j as Record<string, unknown>)) if (v && typeof v === "object" && !Array.isArray(v)) out[k.startsWith("footage/") ? k : `footage/${k}`] = v as Original
|
||||
return out
|
||||
}
|
||||
|
||||
/** a light copy's original fetched onto the box: footage/originals/ holds it under the light copy's name, any extension */
|
||||
export function originalFile(root: string, light: string): string | null {
|
||||
// prep puts every light copy straight in footage/: one in a folder of its own has no original here by its name
|
||||
if (path.posix.dirname(light) !== "footage") return null
|
||||
const dir = path.join(root, ORIGINALS_DIR)
|
||||
const want = stem(path.basename(light)).toLowerCase()
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(dir)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
for (const n of names.sort()) {
|
||||
if (n === "STATUS" || n.startsWith(".") || /\.(json|txt|part|lock|tsv)$/i.test(n) || stem(n).toLowerCase() !== want) continue
|
||||
const abs = path.join(dir, n)
|
||||
try {
|
||||
const st = statSync(abs)
|
||||
if (st.isFile() && st.size > 0) return abs
|
||||
} catch {}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Each light copy a render reads (`uses`: the render's media walk would send it), resolved to its original. */
|
||||
export function resolveOriginals(root: string, uses: (p: string) => boolean, now = Date.now()): Resolved {
|
||||
const map = originalsMap(root)
|
||||
const r: Resolved = { byLink: [], byFile: new Map(), light: [], why: [] }
|
||||
for (const l of lightCopies(root)) {
|
||||
if (!uses(l)) continue
|
||||
const o = map[l]
|
||||
if (o) {
|
||||
const bad =
|
||||
typeof o.sha256 !== "string" || !HASH.test(o.sha256) ? "no hash"
|
||||
: typeof o.url !== "string" || !/^https:\/\//.test(o.url) ? "no link"
|
||||
: typeof o.expires === "number" && o.expires < now + LINK_MARGIN_MS ? "its link has ended"
|
||||
: null
|
||||
if (!bad) {
|
||||
r.byLink.push({ path: l, oid: o.sha256!, size: typeof o.bytes === "number" && o.bytes > 0 ? Math.round(o.bytes) : 0, href: o.url! })
|
||||
continue
|
||||
}
|
||||
r.why.push(`${l}: ${bad}`)
|
||||
}
|
||||
const f = originalFile(root, l)
|
||||
if (f) r.byFile.set(l, f)
|
||||
else r.light.push(l)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
/** what can reach the farm: an original by its file goes only into the farm's cache (by LFS or in the tar it would go as
|
||||
* the light copy), and one of unknown size only to a farm that says it fetches those (`links` from /v1/blobs/have: an
|
||||
* older farm checks every size). What can't is rendered as its light copy, and said */
|
||||
export function settle(r: Resolved, farm: { links: boolean } | null): Resolved {
|
||||
if (farm?.links) return r
|
||||
const out: Resolved = { byLink: [], byFile: farm ? new Map(r.byFile) : new Map(), light: [...r.light], why: [...r.why] }
|
||||
for (const m of r.byLink) {
|
||||
if (m.size > 0) out.byLink.push(m)
|
||||
else (out.light.push(m.path), out.why.push(`${m.path}: this farm doesn't fetch an original of unknown size`))
|
||||
}
|
||||
if (!farm) for (const l of r.byFile.keys()) (out.light.push(l), out.why.push(`${l}: this farm has no media cache, so its original's file can't go to it`))
|
||||
return out
|
||||
}
|
||||
|
||||
/** the paths a render's manifest names as its sources (any "src" in it, as footage/NAME), or null when it names none */
|
||||
export function manifestSources(m: unknown): Set<string> | null {
|
||||
const out = new Set<string>()
|
||||
const walk = (v: unknown) => {
|
||||
if (Array.isArray(v)) for (const x of v) walk(x)
|
||||
else if (v && typeof v === "object")
|
||||
for (const [k, x] of Object.entries(v)) {
|
||||
if (k === "src" && typeof x === "string") {
|
||||
const f = /(?:^|\/)footage\/([^/?#]+)$/.exec(x.replace(/\\/g, "/"))
|
||||
if (f) out.add(`footage/${f[1]}`)
|
||||
} else walk(x)
|
||||
}
|
||||
}
|
||||
walk(m)
|
||||
return out.size ? out : null
|
||||
}
|
||||
|
||||
/** the render's media by hash: what went (by LFS or into the farm's cache) with each original by its link in its light
|
||||
* copy's place */
|
||||
export function withOriginals<M extends { path: string }>(media: M[], r: Resolved): (M | (Media & { href: string }))[] {
|
||||
const linked = new Set(r.byLink.map((m) => m.path))
|
||||
return [...media.filter((m) => !linked.has(m.path)), ...r.byLink]
|
||||
}
|
||||
|
||||
/** a render's record of what it read, in its manifest (its --manifest, else OUT.render.json beside it, made when there's
|
||||
* none: a still), so raea cloud never shows or publishes what was made from a light copy */
|
||||
export function recordOriginals(out: string, manifest: string | null, rec: { read: string[]; light: string[] }): { files: string[]; failed: string[] } {
|
||||
const beside = `${out.slice(0, out.length - path.extname(out).length)}.render.json`
|
||||
const files: string[] = []
|
||||
const failed: string[] = []
|
||||
// into the --manifest and beside the output both: whichever raea cloud reads, it holds the record
|
||||
const targets = [...new Set([...(manifest && existsSync(manifest) ? [manifest] : []), beside])]
|
||||
let named: Set<string> | null = null
|
||||
for (const file of targets) {
|
||||
let m: Record<string, unknown> = {}
|
||||
try {
|
||||
if (existsSync(file)) m = JSON.parse(readFileSync(file, "utf8"))
|
||||
} catch {
|
||||
failed.push(file)
|
||||
continue
|
||||
}
|
||||
if (!m || typeof m !== "object" || Array.isArray(m)) {
|
||||
failed.push(file)
|
||||
continue
|
||||
}
|
||||
named ??= manifestSources(m)
|
||||
// only what this render read, when its manifest says what it read
|
||||
const r = named ? { read: rec.read.filter((f) => named!.has(f)), light: rec.light.filter((f) => named!.has(f)) } : rec
|
||||
if (!r.read.length && !r.light.length) {
|
||||
// a clean render: an earlier render's record goes, and no file is made for nothing
|
||||
if (!("originals" in m)) continue
|
||||
delete m.originals
|
||||
} else m.originals = r
|
||||
writeFileSync(file, JSON.stringify(m))
|
||||
files.push(file)
|
||||
}
|
||||
return { files, failed }
|
||||
}
|
||||
|
||||
/** what a render read, for its manifest: the light copies sent as their originals, and those sent as themselves */
|
||||
export function originalsRecord(r: Resolved): { read: string[]; light: string[] } {
|
||||
return { read: [...r.byLink.map((m) => m.path), ...r.byFile.keys()].sort(), light: [...r.light].sort() }
|
||||
}
|
||||
@@ -39,6 +39,9 @@ export interface Farm {
|
||||
kept?: boolean
|
||||
card?: string
|
||||
maxUsd?: number
|
||||
/** NVIDIA's encoder and decoder (RAEA_NV) for every run: true on, false off; unset, only a piece with 3D in it (CR34).
|
||||
* On forces the job onto GPUs */
|
||||
nv?: boolean
|
||||
/** the job's media outputs stay on the farm for `media` to send to R2 (docs/cloud-render.feature CR23) */
|
||||
media?: boolean
|
||||
}
|
||||
@@ -169,6 +172,7 @@ export class RaeaCloud {
|
||||
if (farm.card) q.set("gpu", farm.card)
|
||||
if (farm.maxUsd !== undefined) q.set("max_usd", String(farm.maxUsd))
|
||||
if (farm.media) q.set("media", "1")
|
||||
if (farm.nv !== undefined) q.set("nv", farm.nv ? "1" : "0")
|
||||
const r = await this.fetch(`/v1/jobs?${q}`, { method: "POST", body: new Blob([folder as Uint8Array<ArrayBuffer>]), headers: { "content-type": "application/octet-stream" }, signal })
|
||||
return ((await r.json()) as { id: string }).id
|
||||
}
|
||||
|
||||
@@ -79,13 +79,17 @@ ws = job([{"path": "media/int1.MOV", "oid": soid, "size": len(sent)}])
|
||||
gets = hits["GET"]
|
||||
ss = fm.fetch(ws, cache, log=lambda _: None)
|
||||
assert open(os.path.join(ws, "media/int1.MOV"), "rb").read() == sent and os.path.islink(os.path.join(ws, "media/int1.MOV"))
|
||||
# followed to the end, the link is a file with the take's own name: a bundler resolves it, and a composition that knows
|
||||
# its takes by name (Framed's faces) still finds this one
|
||||
real = os.path.realpath(os.path.join(ws, "media/int1.MOV"))
|
||||
assert os.path.basename(real) == "int1.MOV" and os.path.samefile(real, os.path.join(cache, soid)), real
|
||||
assert ss == {"objects": 1, "fetched": 0, "cached": len(sent)} and hits["GET"] == gets, ss
|
||||
try:
|
||||
fm.fetch(job([{"path": "media/gone.MOV", "oid": "ab" * 32, "size": 10}]), cache, log=lambda _: None)
|
||||
raise AssertionError("footage never sent was used")
|
||||
except ValueError as e:
|
||||
assert "never sent" in str(e)
|
||||
ok("footage the box sent the farm itself comes from the cache as a link, and footage it never sent is refused")
|
||||
ok("footage the box sent the farm itself comes from the cache as a link that ends at its own name, and footage it never sent is refused")
|
||||
|
||||
w1 = job([obj])
|
||||
s1 = fm.fetch(w1, cache, log=lambda _: None)
|
||||
@@ -120,6 +124,27 @@ except ValueError:
|
||||
pass
|
||||
ok("a file that isn't its hash, and a path out of the job, are refused")
|
||||
|
||||
# a library original whose size raea cloud doesn't know (size 0, its link given): fetched and kept by its hash alone,
|
||||
# then held for the next job; a size-0 entry with no link is never held
|
||||
c0 = tempfile.mkdtemp()
|
||||
z = dict(obj, size=0)
|
||||
w3 = job([z])
|
||||
s3 = fm.fetch(w3, c0, log=lambda _: None)
|
||||
assert open(os.path.join(w3, "footage/take.mov"), "rb").read() == take and s3["fetched"] == len(take), s3
|
||||
s4 = fm.fetch(job([z]), c0, log=lambda _: None)
|
||||
assert s4["fetched"] == 0 and s4["cached"] == len(take), s4
|
||||
try:
|
||||
fm.fetch(job([dict(z, oid="0" * 64)]), tempfile.mkdtemp(), log=lambda _: None)
|
||||
raise SystemExit("FAIL a size-0 original with the wrong hash was taken")
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
fm.fetch(job([{"path": "footage/take.mov", "oid": oid, "size": 0}]), c0, log=lambda _: None)
|
||||
raise SystemExit("FAIL a size-0 entry with no link was held")
|
||||
except ValueError as e:
|
||||
assert "never sent" in str(e)
|
||||
ok("an original of unknown size is fetched and held by its hash, a wrong one refused, and none held without its link")
|
||||
|
||||
out = tempfile.mkdtemp()
|
||||
os.makedirs(os.path.join(out, "out"))
|
||||
render = os.urandom(200_000)
|
||||
|
||||
@@ -263,6 +263,14 @@ g = Flat(root, name="T4")
|
||||
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jn", "gpus": 2, "cpus": 0}, os.path.join(root, "jobs", "jn", "work"), log, g, {}, run) == 0, lines
|
||||
assert g.nv and not any(g.nv), g.nv
|
||||
ok("a piece with 3D draws on GPUs with NVENC and NVDEC asked for; a 2D piece kept on GPUs doesn't ask")
|
||||
# the job says so (opts nv): "1" puts a 2D piece on GPUs with them, "0" keeps a 3D piece's GPU without them
|
||||
g, c = Flat(root, name="T4"), Flat(root)
|
||||
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jn", "gpus": 2, "cpus": 8, "nv": "1"}, os.path.join(root, "jobs", "jn", "work"), log, g, {}, run, cpu_render=c) == 0, lines
|
||||
assert not c.calls and g.nv and all(g.nv), (c.calls, g.nv)
|
||||
g, c = Flat(root, name="T4", has3d=True), Flat(root)
|
||||
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jn", "gpus": 2, "cpus": 8, "nv": "0"}, os.path.join(root, "jobs", "jn", "work"), log, g, {}, run, cpu_render=c) == 0, lines
|
||||
assert not c.calls and g.nv and not any(g.nv), (c.calls, g.nv)
|
||||
ok("a job's nv=1 draws a 2D piece on GPUs with NVENC and NVDEC; nv=0 keeps a 3D piece's GPU without them")
|
||||
|
||||
# the join keeps every frame of runs that have B-frames, with the piece's sound (11-30: -shortest ended the joined
|
||||
# video 2 frames early, 892 of an 894-frame ad)
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
// Light copies on the box, originals on the farm (server/originals.ts, docs/cloud.feature CL17-CL20): node
|
||||
// test/originals.ts from sdk/cloud.
|
||||
// Checked: a light copy the render reads goes as its original by its link (the light copy's own bytes never go); one
|
||||
// the render doesn't read goes nowhere; a link that has ended, or an entry with no hash, falls back to the original's
|
||||
// file under footage/originals/; with neither, the light copy is rendered as itself and named for the manifest; the
|
||||
// original's file is sent by its own hash under the light copy's path; footage/originals/ and the kept light copies
|
||||
// never go in the tar.
|
||||
|
||||
import { createHash } from "node:crypto"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"
|
||||
import { createServer } from "node:http"
|
||||
import type { AddressInfo } from "node:net"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { excluded, farmBlobs, farmInputs } from "../server/media.ts"
|
||||
import { lightCopies, originalFile, originalsRecord, recordOriginals, resolveOriginals, settle, withOriginals } from "../server/originals.ts"
|
||||
|
||||
const ok = (m: string) => console.log(`ok ${m}`)
|
||||
const assert = (c: unknown, m: string) => {
|
||||
if (!c) throw new Error(`not ok: ${m}`)
|
||||
}
|
||||
const sha = (b: Buffer | string) => createHash("sha256").update(b).digest("hex")
|
||||
|
||||
const root = mkdtempSync(path.join(tmpdir(), "originals-"))
|
||||
const put = (rel: string, body: Buffer | string) => {
|
||||
mkdirSync(path.dirname(path.join(root, rel)), { recursive: true })
|
||||
writeFileSync(path.join(root, rel), body)
|
||||
}
|
||||
// four light copies; a's and b's originals have links, c's link has ended and its original is here, d has nothing
|
||||
const light = (n: string) => Buffer.alloc(300_000, n)
|
||||
for (const n of ["a", "b", "c", "d"]) put(`footage/${n}.mp4`, light(n))
|
||||
put("footage/e.mp4", light("e")) // not a light copy: the agent's own file
|
||||
put(".raea-cloud/light.txt", "a.mp4\nb.mp4\nfootage/c.mp4\nd.mp4\nmissing.mp4\n")
|
||||
const A = "a".repeat(64)
|
||||
const now = 1_000_000_000
|
||||
put(
|
||||
".raea-cloud/originals.json",
|
||||
JSON.stringify({
|
||||
"footage/a.mp4": { sha256: A, bytes: 693_000_000, url: "https://r2.example/a?sig=1", expires: now + 86_400_000 },
|
||||
"b.mp4": { sha256: "b".repeat(64), url: "https://drive.example/b" },
|
||||
"footage/c.mp4": { sha256: "c".repeat(64), bytes: 9, url: "https://r2.example/c", expires: now + 60_000 },
|
||||
"footage/d.mp4": { url: "https://r2.example/d" },
|
||||
}),
|
||||
)
|
||||
const cOrig = Buffer.alloc(5_000_000, "C")
|
||||
put("footage/originals/c.MOV", cOrig)
|
||||
put("footage/originals/STATUS", "done")
|
||||
put("footage/originals/d.mp4.part", "half")
|
||||
|
||||
assert(lightCopies(root).join() === "footage/a.mp4,footage/b.mp4,footage/c.mp4,footage/d.mp4", "light.txt read as paths, a name with no file left out")
|
||||
assert(originalFile(root, "footage/c.mp4")?.endsWith("footage/originals/c.MOV"), "an original's file found by its name, any extension")
|
||||
assert(originalFile(root, "footage/d.mp4") === null, "a part-fetched original isn't one")
|
||||
ok("light copies and originals' files found")
|
||||
|
||||
const reads = new Set(["footage/a.mp4", "footage/b.mp4", "footage/c.mp4", "footage/d.mp4"])
|
||||
const r = resolveOriginals(root, (p) => reads.has(p), now)
|
||||
assert(r.byLink.length === 2, `two by their links (${r.byLink.map((m) => m.path)})`)
|
||||
const a = r.byLink.find((m) => m.path === "footage/a.mp4")!
|
||||
assert(a.oid === A && a.size === 693_000_000 && a.href === "https://r2.example/a?sig=1", "a's original: its hash, size and link, under the light copy's path")
|
||||
const b = r.byLink.find((m) => m.path === "footage/b.mp4")!
|
||||
assert(b.size === 0 && !("expires" in b), "a size raea cloud doesn't know goes as 0; a link with no end is used")
|
||||
assert(r.byFile.get("footage/c.mp4")?.endsWith("footage/originals/c.MOV"), "an ended link falls back to the original's file")
|
||||
assert(r.light.join() === "footage/d.mp4", "no hash and no file: the light copy as itself")
|
||||
assert(r.why.some((w) => w.startsWith("footage/c.mp4: its link has ended")) && r.why.some((w) => w.startsWith("footage/d.mp4: no hash")), `why each link wasn't used (${r.why})`)
|
||||
ok("each light copy resolved to its original's link, its file, or itself")
|
||||
|
||||
const some = resolveOriginals(root, (p) => p === "footage/a.mp4", now)
|
||||
assert(some.byLink.length === 1 && !some.byFile.size && !some.light.length, "a light copy the render doesn't read goes nowhere, its original included")
|
||||
ok("only what the render reads")
|
||||
|
||||
const rec = originalsRecord(r)
|
||||
assert(rec.read.join() === "footage/a.mp4,footage/b.mp4,footage/c.mp4" && rec.light.join() === "footage/d.mp4", "the manifest's record")
|
||||
ok("the record: read as originals, and as themselves")
|
||||
|
||||
writeFileSync(path.join(root, ".raea-cloud/originals.json"), "{not json")
|
||||
assert(resolveOriginals(root, () => true, now).byLink.length === 0, "a broken map is no map")
|
||||
writeFileSync(path.join(root, ".raea-cloud/originals.json"), JSON.stringify([1, 2]))
|
||||
assert(resolveOriginals(root, () => true, now).byLink.length === 0, "an array is no map")
|
||||
ok("a broken map renders from files or light copies, never crashes")
|
||||
|
||||
// the original's file goes to the farm by its own hash, under the light copy's path; the tar's excludes keep
|
||||
// footage/originals/ and the kept light copies out
|
||||
put(".raea-cloud/proxies/x.mp4", light("x"))
|
||||
const held = new Map<string, number>()
|
||||
const farm = createServer((req, res) => {
|
||||
const u = new URL(req.url!, "http://x")
|
||||
if (req.method === "POST" && u.pathname === "/v1/blobs/have") {
|
||||
let s = ""
|
||||
req.on("data", (c) => (s += c)).on("end", () => {
|
||||
const objects = (JSON.parse(s).objects ?? []) as { oid: string }[]
|
||||
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ have: objects.filter((o) => held.has(o.oid)).map((o) => o.oid), links: 1 }))
|
||||
})
|
||||
return
|
||||
}
|
||||
const m = /^\/v1\/blobs\/([0-9a-f]{64})$/.exec(u.pathname)
|
||||
if (req.method === "PUT" && m) {
|
||||
const h = createHash("sha256")
|
||||
let n = 0
|
||||
req.on("data", (c: Buffer) => (h.update(c), (n += c.length))).on("end", () => {
|
||||
if (h.digest("hex") !== m[1]) return void res.writeHead(400).end("wrong hash")
|
||||
held.set(m[1], n)
|
||||
res.writeHead(200).end()
|
||||
})
|
||||
return
|
||||
}
|
||||
res.writeHead(404).end()
|
||||
})
|
||||
await new Promise<void>((ok) => farm.listen(0, "127.0.0.1", ok))
|
||||
const url = `http://127.0.0.1:${(farm.address() as AddressInfo).port}`
|
||||
const tar = excluded(["./.git", "./out/*", "./.raea-cloud/proxies", "./footage/originals"])
|
||||
const linked = new Set(r.byLink.map((m) => m.path))
|
||||
const store = path.join(root, ".hashes.json")
|
||||
const got = await farmInputs(root, farmBlobs(url, "t"), (p) => tar(p) || linked.has(p), () => {}, store, r.byFile)
|
||||
farm.close()
|
||||
assert(got, "the farm has a cache")
|
||||
const paths = got!.media.map((m) => m.path).sort()
|
||||
assert(!paths.includes("footage/a.mp4") && !paths.includes("footage/b.mp4"), `light copies with links aren't sent (${paths})`)
|
||||
assert(!paths.some((p) => p.startsWith("footage/originals/") || p.startsWith(".raea-cloud/proxies/")), `footage/originals/ and the kept light copies stay out (${paths})`)
|
||||
const c = got!.media.find((m) => m.path === "footage/c.mp4")!
|
||||
assert(c.oid === sha(cOrig) && c.size === cOrig.length && held.get(c.oid) === cOrig.length, "c goes as its original's bytes, by their hash, under its own path")
|
||||
const d = got!.media.find((m) => m.path === "footage/d.mp4")!
|
||||
assert(d.oid === sha(readFileSync(path.join(root, "footage/d.mp4"))), "d, with no original, goes as itself")
|
||||
ok("an original's file sent in its light copy's place; footage/originals/ and kept light copies never sent")
|
||||
// the one list the farm gets: what went, with each original by its link in its light copy's place (12-05 review: the
|
||||
// farm-cache path kept only what went, and the links were dropped while the manifest said they were read)
|
||||
const went = [{ path: "footage/c.mp4", oid: "c".repeat(64), size: 5 }, { path: "media/logo.png", oid: "d".repeat(64), size: 9 }, { path: "footage/a.mp4", oid: "e".repeat(64), size: 7 }]
|
||||
const all = withOriginals(went, r)
|
||||
assert(all.length === 4 && all.filter((m) => m.path === "footage/a.mp4").length === 1, `each path once (${all.map((m) => m.path)})`)
|
||||
assert((all.find((m) => m.path === "footage/a.mp4") as { href?: string }).href === "https://r2.example/a?sig=1", "the light copy's path carries its original's link")
|
||||
assert(all.some((m) => m.path === "footage/b.mp4") && all.some((m) => m.path === "media/logo.png"), "the links and the rest, together")
|
||||
ok("the farm's list holds every original by its link, and what went")
|
||||
|
||||
// what a farm can take: one that fetches by link takes them all; an older cache farm, no unknown size; no cache, no file
|
||||
assert(settle(r, { links: true }) === r, "a farm that fetches by link takes them all")
|
||||
const older = settle(r, { links: false })
|
||||
assert(older.byLink.map((m) => m.path).join() === "footage/a.mp4" && older.byFile.size === 1, `an older cache farm: known sizes and files (${older.byLink.map((m) => m.path)})`)
|
||||
assert(older.light.join() === "footage/d.mp4,footage/b.mp4", `the unknown size light (${older.light})`)
|
||||
const old = settle(r, null)
|
||||
assert(old.byLink.map((m) => m.path).join() === "footage/a.mp4", `only a known size by link (${old.byLink.map((m) => m.path)})`)
|
||||
assert(old.byFile.size === 0 && old.light.join() === "footage/d.mp4,footage/b.mp4,footage/c.mp4", `the rest light (${old.light})`)
|
||||
assert(old.why.filter((w) => w.includes("no media cache")).length === 1 && old.why.some((w) => w.includes("unknown size")), "and said")
|
||||
ok("a farm gets only what it says it can take; the rest is recorded light")
|
||||
|
||||
// the record: into the manifest and beside the output, only what the render read, cleared when clean
|
||||
const rec2 = originalsRecord(old)
|
||||
const man = path.join(root, "out/m.json")
|
||||
put("out/cut.mp4", "v")
|
||||
put("out/m.json", JSON.stringify({ frames: [1], sounds: { clips: [{ src: "/farm/cache/named/x/footage/b.mp4" }, { src: "footage/a.mp4" }] } }))
|
||||
const rc = recordOriginals(path.join(root, "out/cut.mp4"), man, rec2)
|
||||
assert(rc.failed.length === 0 && rc.files.length === 2, `into both (${rc.files})`)
|
||||
const mj = JSON.parse(readFileSync(man, "utf8"))
|
||||
assert(mj.frames[0] === 1 && mj.originals.light.join() === "footage/b.mp4" && mj.originals.read.join() === "footage/a.mp4", `only what it read (${JSON.stringify(mj.originals)})`)
|
||||
assert(JSON.parse(readFileSync(path.join(root, "out/cut.render.json"), "utf8")).originals.light.join() === "footage/b.mp4", "beside it too")
|
||||
put("out/still.png", "p")
|
||||
recordOriginals(path.join(root, "out/still.png"), null, rec2)
|
||||
const side = path.join(root, "out/still.render.json")
|
||||
assert(JSON.parse(readFileSync(side, "utf8")).originals.read.join() === "footage/a.mp4", "beside a still, which names no sources: all of it")
|
||||
recordOriginals(path.join(root, "out/still.png"), null, { read: [], light: [] })
|
||||
assert(!("originals" in JSON.parse(readFileSync(side, "utf8"))), "a clean render again clears the old record")
|
||||
assert(recordOriginals(path.join(root, "out/x.png"), null, { read: [], light: [] }).files.length === 0 && !existsSync(path.join(root, "out/x.render.json")), "nothing to record, nothing made")
|
||||
put("out/bad.json", "[1]")
|
||||
assert(recordOriginals(path.join(root, "out/cut.mp4"), path.join(root, "out/bad.json"), rec2).failed.join().endsWith("out/bad.json"), "a manifest that isn't an object is said")
|
||||
ok("every render keeps its record of what it read, a still beside it, and a clean one clears it")
|
||||
|
||||
put("footage/day1/take.mp4", light("t"))
|
||||
put("footage/originals/take.mov", "T")
|
||||
assert(originalFile(root, "footage/day1/take.mp4") === null, "a light copy in a folder of its own isn't matched by name")
|
||||
ok("an original's file is matched only for a light copy straight in footage/")
|
||||
console.log("originals: all ok")
|
||||
@@ -213,6 +213,10 @@ console.log("units: ok")
|
||||
assert.equal(localSources(m, [{ path: "media/raw/a1_hl1.mov", oid }], "/work/project"), 1)
|
||||
assert.deepEqual(m.sounds.clips.map((c) => c.src), ["/work/project/media/raw/a1_hl1.mov", "/work/abc/media/music.mp3", "f".repeat(64)])
|
||||
assert.equal(localSources({}, [], "/x"), 0)
|
||||
// the farm's blob under the take's own name (blobs/named/OID/NAME) maps back the same
|
||||
const named = { sounds: { clips: [{ src: `/__modal/volumes/vo-F8fh/blobs/named/${oid}/a1_hl1.mov` }] } }
|
||||
assert.equal(localSources(named, [{ path: "media/raw/a1_hl1.mov", oid }], "/work/project"), 1)
|
||||
assert.equal(named.sounds.clips[0].src, "/work/project/media/raw/a1_hl1.mov")
|
||||
console.log("ok localSources")
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ same(unusedMedia(project({ ...takes, "cut_a.tsx": `<Video src="footage/Angle1-Ta
|
||||
same(unusedMedia(project({ ...takes, "cut_a.tsx": "const src = (id: string) => `footage/originals/${id}.mov`", "cuts.json": JSON.stringify({ shots: ["Angle1-Take1"] }) })),
|
||||
["footage/Angle1-Take2.mp4", "footage/Angle2-Take1.mp4", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov", "media/music/bed.mp3"], "the final render on the originals")
|
||||
|
||||
// nothing names any media: all of it is used, as before
|
||||
same(unusedMedia(project({ ...takes, "cut_a.tsx": "export default () => null" })), [], "no source names any")
|
||||
// nothing names any media: all of it is used, as before, but footage/originals/ (gigabytes; each original goes in its
|
||||
// light copy's place when it goes at all: originals.ts)
|
||||
same(unusedMedia(project({ ...takes, "cut_a.tsx": "export default () => null" })), ["footage/originals/Angle1-Take1.mov", "footage/originals/Angle1-Take2.mov", "footage/originals/Angle2-Take1.mov"], "no source names any")
|
||||
console.log("ok")
|
||||
@@ -226,7 +226,7 @@ const HOOK_S = 5
|
||||
* had none, read from its brief's "captions OR a text hook"): a cut with talking and no captions at all is an error,
|
||||
* and so is a stretch of talking with none up. A text hook may be on screen beside them; it doesn't stand in for them.
|
||||
* A brief that wants no captions says so, and the render says it with --despite captions WHY */
|
||||
export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) => boolean = () => false): Finding[] {
|
||||
export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) => boolean = () => false, onCard: (w: Word) => boolean = () => false): Finding[] {
|
||||
heard = asDigits(heard)
|
||||
// a brief's "captions OR a text hook, never both" means not both in one frame (12-03, Shane): the hook may hold the
|
||||
// opening alone, so words in the first HOOK_S with other text up are covered by it; anywhere later it's no caption
|
||||
@@ -237,7 +237,9 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
|
||||
if (said.length < BARE.error.words) return []
|
||||
const fix = "caption every line from the words file (whole phrases in the brand's caption style); a text hook goes with the captions, never instead of them. If the brief asks for no captions, render with --despite captions WHY"
|
||||
if (!shown.length) return [{ level: "error", kind: "uncaptioned", at: said[0].start, says: `no captions over the talking: ${said.length} words, ${(said[said.length - 1].end - said[0].start).toFixed(1)} s, and no caption track (captions one after another under ${Math.round(TRACK * 100)}% of what's said, or fewer than ${CARDS} of them). ${fix}` }]
|
||||
const up = (w: Word) => shown.some((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3)
|
||||
// a word is up when a caption is, or when text the render drew says it there (an end card with the line being said:
|
||||
// captionsOf takes a frame full of text for a card, not captions; 12-05, run 28's Elfster end cards)
|
||||
const up = (w: Word) => shown.some((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3) || onCard(w)
|
||||
const out: Finding[] = []
|
||||
for (let i = 0; i < said.length; ) {
|
||||
if (up(said[i])) { i++; continue }
|
||||
@@ -310,6 +312,13 @@ export default check<FileFacts>(
|
||||
const rate = own ? own.rate : sc!.rate || 2
|
||||
const shown = captionsOf(frames, rate, heard)
|
||||
const textUp = (t: number) => (frames[Math.round(t * rate)]?.lines ?? []).some(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4)
|
||||
for (const x of [...uncaptioned(shown, heard, textUp), ...compare(shown, heard, own ? await placedWords(f) : [])].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
// only the render's own texts say a word on screen: the footage's own (a sign, a phone) never caption anything
|
||||
const onCard = (w: Word) => {
|
||||
if (!own) return false
|
||||
const k = letters(w.text)
|
||||
const at = (t: number) => letters((frames[Math.round(t * rate)]?.lines ?? []).map((l) => l[4]).join(" "))
|
||||
return k.length > 0 && [w.start, (w.start + w.end) / 2, w.end].some((t) => at(t).includes(k))
|
||||
}
|
||||
for (const x of [...uncaptioned(shown, heard, textUp, onCard), ...compare(shown, heard, own ? await placedWords(f) : [])].sort((a, b) => a.at - b.at)) found({ level: x.level, says: x.says, seconds: x.at })
|
||||
},
|
||||
)
|
||||
@@ -7,7 +7,7 @@
|
||||
// say every phrase each cut must say, heard or shown; `every: false` phrases once across the cuts
|
||||
// never no banned phrase heard or shown
|
||||
// cta each cut ends on the CTA (in its last `within` seconds, 8 by default), heard or shown
|
||||
import { existsSync, readFileSync } from "node:fs"
|
||||
import { existsSync, readdirSync, readFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import type { CutGoal, CutPlan } from "raea/brief.gen"
|
||||
@@ -178,9 +178,53 @@ export const ctaPack = check<FileFacts>({ id: "cta", text: "each cut ends on the
|
||||
// end card showed "Code PETS60: $60 off your first year", and neither alone was 85% of the line
|
||||
const late = shownTogether(f.manifest, end - within)
|
||||
const shownLate = late.some((s) => lines.some((l) => share(l, s.split(" ")) >= CTA_SHARE || share(l, [...last, ...s.split(" ")]) >= CTA_SHARE || share(l, [...s.split(" "), ...last]) >= CTA_SHARE))
|
||||
if (best < CTA_SHARE && !shownLate) found({ says: `no CTA in its last ${within.toFixed(0)} s (${(best * 100).toFixed(0)}% of the nearest one's words heard there): "${line}"`, seconds: [Math.max(0, end - within), end] })
|
||||
if (best < CTA_SHARE && !shownLate) {
|
||||
// the takes that say it, so the fix is one `raea cut` away (12-05, a street interview run: every cut ended on a host take
|
||||
// that says "download the app", while two other takes say the brief's "Go to the site" line word for word)
|
||||
const takes = takesSaying(f.root, lines)
|
||||
const where = takes.length ? `; said in ${takes.map((t) => `${t.take} at ${t.at.toFixed(1)} s`).join(", ")}: cut it from there` : "; no take says it: show it on the end card"
|
||||
found({ says: `no CTA in its last ${within.toFixed(0)} s (${(best * 100).toFixed(0)}% of the nearest one's words heard there): "${line}"${where}`, seconds: [Math.max(0, end - within), end] })
|
||||
}
|
||||
})
|
||||
|
||||
/** the takes in footage/ whose words say one of `lines` (CTA_SHARE of its words in order, inside a window a little longer
|
||||
* than it), the closest first, three at most */
|
||||
export function takesSaying(root: string, lines: string[]): { take: string; at: number; share: number }[] {
|
||||
const dir = path.join(root, "footage")
|
||||
if (!existsSync(dir)) return []
|
||||
const out: { take: string; at: number; share: number }[] = []
|
||||
let names: string[] = []
|
||||
try {
|
||||
names = readdirSync(dir).filter((n) => n.endsWith(".words.json"))
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
const wants = lines.map((l) => norm(l).split(" ").filter(Boolean)).filter((w) => w.length)
|
||||
for (const n of names) {
|
||||
let ws: { text: string; start_ms: number; end_ms?: number }[] = []
|
||||
try {
|
||||
ws = JSON.parse(readFileSync(path.join(dir, n), "utf8"))
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
if (!Array.isArray(ws)) continue
|
||||
const heard = asDigits(ws.map((w) => ({ text: String(w.text ?? ""), start: w.start_ms / 1000, end: (w.end_ms ?? w.start_ms) / 1000 })))
|
||||
// one token per word of norm's (it makes "acme.com" two), each at its word's time
|
||||
const flat = heard.flatMap((w) => norm(w.text).split(" ").filter(Boolean).map((t) => ({ t, start: w.start })))
|
||||
const toks = flat.map((x) => x.t)
|
||||
let best: { at: number; share: number } | null = null
|
||||
for (const want of wants)
|
||||
for (let i = 0; i < toks.length; i++) {
|
||||
if (!want.includes(toks[i])) continue
|
||||
const win = toks.slice(i, i + want.length + 3)
|
||||
const sh = inOrder(want, joined(win, want).map(([w]) => w))
|
||||
if (sh >= CTA_SHARE && (!best || sh > best.share)) best = { at: flat[i].start, share: sh }
|
||||
}
|
||||
if (best) out.push({ take: n.replace(/\.words\.json$/, ""), ...best })
|
||||
}
|
||||
return out.sort((a, b) => b.share - a.share).slice(0, 3)
|
||||
}
|
||||
|
||||
/** a phrase one cut is enough for (`every: false`): some delivered cut says or shows it */
|
||||
export const sayOncePack = check<Job>({ id: "say-once", text: "each phrase one cut is enough for, said or shown by one", over: "job", at: ["publish", "done"], needs: "words" }, async (j) => {
|
||||
const c = cutJob(j)
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
// (no one reads it on a phone), under 48 px a warning.
|
||||
// faces: frames two a second through the scene reader (raea cloud's farm). A face of a person in the shot (5% of the
|
||||
// frame's height or more) touching an edge or a split screen's seam: a second or more is an error, shorter a
|
||||
// warning. A split screen with a face in one half only is a warning.
|
||||
// warning. The reader takes a hand or a bag at the edge for a face now and then (12-05, run 28: Elfster's "face cut by
|
||||
// the left edge" was a hand at 0.79 then 0.65, where the people in the shot read 0.92 and over), so a run it's less
|
||||
// than FACE_SURE sure of is a warning, never an error. A split screen with a face in one half only is a warning.
|
||||
// A face at the edge that's meant (someone walking out of shot) is said, with its reason, in OUT.despite.txt beside
|
||||
// the video: its findings are then warnings.
|
||||
import { existsSync, readFileSync } from "node:fs"
|
||||
@@ -17,6 +19,9 @@ import { quote } from "../text.ts"
|
||||
|
||||
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind */
|
||||
export const FACE_MIN = 0.05
|
||||
/** a cut face is an error only when the reader is this sure, over its run, that it's a face (a face's score; 1 when the
|
||||
* reader gives none) */
|
||||
export const FACE_SURE = 0.8
|
||||
/** least font sizes, in pixels of a frame 1080 wide (its shorter side): the Direct Response skill's table */
|
||||
export const TEXT_ERROR = 40
|
||||
export const TEXT_WARN = 48
|
||||
@@ -43,17 +48,21 @@ export function splitsOf(fr: NonNullable<Faces>): Split[] {
|
||||
const near = (a: Split, b: Split) => a.axis === b.axis && Math.abs(a.at - b.at) <= 6
|
||||
const big = (fr: NonNullable<Faces>) => fr.faces.filter((f) => f[3] >= fr.h * FACE_MIN)
|
||||
|
||||
/** what cuts a face in a frame: an edge of the frame, or a split screen's seam */
|
||||
function cutBy(fr: NonNullable<Faces>, splits: Split[]): string | null {
|
||||
for (const [x, y, fw, fh] of big(fr)) {
|
||||
if (x <= 1) return "the left edge"
|
||||
if (x + fw >= fr.w - 1) return "the right edge"
|
||||
if (y <= 1) return "the top edge"
|
||||
if (y + fh >= fr.h - 1) return "the bottom edge"
|
||||
for (const sp of splits) {
|
||||
const [a, b] = sp.axis === "h" ? [y, y + fh] : [x, x + fw]
|
||||
if ((a < sp.at - 2 && b > sp.at + 2) || Math.abs(b - sp.at) <= 3 || Math.abs(a - sp.at) <= 3) return "the split screen's seam"
|
||||
}
|
||||
/** what cuts a face in a frame (an edge of the frame, or a split screen's seam), with how sure the reader is it's a face */
|
||||
function cutBy(fr: NonNullable<Faces>, splits: Split[]): { by: string; score: number } | null {
|
||||
for (const [x, y, fw, fh, s] of big(fr)) {
|
||||
const score = Number.isFinite(s) ? s : 1
|
||||
const by =
|
||||
x <= 1 ? "the left edge"
|
||||
: x + fw >= fr.w - 1 ? "the right edge"
|
||||
: y <= 1 ? "the top edge"
|
||||
: y + fh >= fr.h - 1 ? "the bottom edge"
|
||||
: splits.some((sp) => {
|
||||
const [a, b] = sp.axis === "h" ? [y, y + fh] : [x, x + fw]
|
||||
return (a < sp.at - 2 && b > sp.at + 2) || Math.abs(b - sp.at) <= 3 || Math.abs(a - sp.at) <= 3
|
||||
}) ? "the split screen's seam"
|
||||
: null
|
||||
if (by) return { by, score }
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -83,10 +92,12 @@ export function cutFaces(frames: Faces[], rate = RATE): Finding[] {
|
||||
const held = raw.map((ss, i) => ss.filter((s) => (raw[i - 1] ?? []).some((o) => near(s, o)) || (raw[i + 1] ?? []).some((o) => near(s, o))))
|
||||
const out: Finding[] = []
|
||||
const hits = frames.map((fr, i) => (fr ? cutBy(fr, held[i]) : null))
|
||||
for (const [i, j, by] of runs(hits)) {
|
||||
for (const [i, j, { by }] of runs(hits, (a, b) => a.by === b.by)) {
|
||||
const from = i / rate
|
||||
const to = j / rate
|
||||
out.push({ level: to - from >= 1 ? "error" : "warn", kind: "face-cut", at: from, until: to, says: `a face is cut by ${by} from ${from.toFixed(1)} s to ${to.toFixed(1)} s: reframe on the person (both eyes, mouth and chin inside the picture)${by.includes("seam") ? ", or cut between two singles" : " or cut away"}` })
|
||||
const sure = hits.slice(i, j).reduce((n, h) => n + (h?.score ?? 0), 0) / (j - i)
|
||||
const doubt = sure < FACE_SURE ? ` (the reader is ${Math.round(sure * 100)}% sure it's a face: look)` : ""
|
||||
out.push({ level: to - from >= 1 && !doubt ? "error" : "warn", kind: "face-cut", at: from, until: to, says: `a face${doubt} is cut by ${by} from ${from.toFixed(1)} s to ${to.toFixed(1)} s: reframe on the person (both eyes, mouth and chin inside the picture)${by.includes("seam") ? ", or cut between two singles" : " or cut away"}` })
|
||||
}
|
||||
const split = held.map((ss) => ss[0] ?? null)
|
||||
for (const [i, j, sp] of runs(split, near)) {
|
||||
|
||||
@@ -36,6 +36,8 @@ const SUBJECT_MIN = 0.25
|
||||
const FACE_IN_SHOT = 0.05
|
||||
/** a thing this share of the frame's area or more is what the shot shows (a dog at someone's feet, a phone held up) */
|
||||
const THING_MIN = 0.006
|
||||
/** words in the shot are hidden (text over them an error) when a text covers this share of them or more */
|
||||
export const SIGN_HIDDEN = 0.3
|
||||
/** a text is badly placed when it costs this much or more, and a clear place costs this much less */
|
||||
export const BAD = 1.6
|
||||
export const BETTER = 1.2
|
||||
@@ -123,7 +125,11 @@ function thingsUnder(s: NonNullable<Scene>, b: Box, ours: Box[] = []): string[]
|
||||
const [x, y, w, h] = [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
|
||||
const ix = Math.max(0, Math.min(b[0] + b[2], x + w) - Math.max(b[0], x))
|
||||
const iy = Math.max(0, Math.min(b[1] + b[3], y + h) - Math.max(b[1], y))
|
||||
if (ix * iy > 0.12 * Math.min(w * h, b[2] * b[3])) out.add(t[4] === "person" ? "a person in the shot" : t[4] === "face" ? "a face" : t[4] === "text" ? "words in the shot (a sign)" : `a ${t[4].replace(/_/g, " ")}`)
|
||||
if (!(ix * iy > 0.12 * Math.min(w * h, b[2] * b[3]))) continue
|
||||
// words in the shot are covered when a good part of them is hidden; a caption over a sign's top edge leaves them read
|
||||
// (12-05, run 28: Dutch's "Would" and "this." sat on the edge of a handwritten sign, its words all clear)
|
||||
if (t[4] === "text") out.add(ix * iy >= SIGN_HIDDEN * w * h ? "words in the shot (a sign)" : "the edge of a sign")
|
||||
else out.add(t[4] === "person" ? "a person in the shot" : t[4] === "face" ? "a face" : `a ${t[4].replace(/_/g, " ")}`)
|
||||
}
|
||||
return [...out]
|
||||
}
|
||||
|
||||
@@ -121,6 +121,27 @@ export function seams(words: Word[]): { at: number; before: string; after: strin
|
||||
return out
|
||||
}
|
||||
|
||||
/** a manifest's clips with every seam that isn't an edit joined: a take that plays straight on across two clips (the
|
||||
* same source and level, touching in the cut and in the take, no fade between) is one clip, so its seam is never read
|
||||
* as an edit point. A composition splits a clip that way when it reframes or restyles a shot mid-clip */
|
||||
export function joined(clips: Clip[], fps: number): Clip[] {
|
||||
const out: Clip[] = []
|
||||
const frame = 1.5 / fps
|
||||
for (const c of [...clips].sort((p, q) => p.from - q.from)) {
|
||||
const prev = out.findLast((p) => p.src === c.src && Math.abs(p.to - c.from) <= 1)
|
||||
const on =
|
||||
prev &&
|
||||
(prev.gainDb ?? 0) === (c.gainDb ?? 0) &&
|
||||
prev.bus === c.bus &&
|
||||
!prev.fadeOut &&
|
||||
!c.fadeIn &&
|
||||
Math.abs(prev.at + (prev.to - prev.from) / fps - c.at) <= frame
|
||||
if (prev && on) Object.assign(prev, { to: c.to, fadeOut: c.fadeOut })
|
||||
else out.push({ ...c })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** a voice clip's in and out: inside a word, or on sound */
|
||||
export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Finding[] {
|
||||
const out: Finding[] = []
|
||||
@@ -210,7 +231,7 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
|
||||
out.push({ level: "error", kind: "manifest", at: null, says: `its render manifest holds ${frames} of the cut's ${length} frames, so its edit can't be checked: render the cut again` })
|
||||
const heard: Heard[] = []
|
||||
let voice = 0
|
||||
for (const c of m.sounds?.clips ?? []) {
|
||||
for (const c of joined(m.sounds?.clips ?? [], fps)) {
|
||||
const kind = busOf(c)
|
||||
const file = f.take(c.src)
|
||||
if (!file) {
|
||||
|
||||
@@ -90,6 +90,9 @@ test("captions are a must: a cut that talks with only a text hook up fails, a ba
|
||||
expect(uncaptioned(captionsOf(hookThenCaps, 2, said), said, hookUp)).toEqual([])
|
||||
// text up all through doesn't stand in for captions after the opening
|
||||
expect(uncaptioned(track, said, () => true).map((x) => x.level)).toEqual(["error"])
|
||||
// the bare stretch said on an end card the render drew (12-05, run 28's Elfster): the card says it, nothing more
|
||||
const card = new Set(said.filter((w) => w.start >= 7).map((w) => w.text))
|
||||
expect(uncaptioned(track, said, () => false, (w) => card.has(w.text))).toEqual([])
|
||||
// a cut with hardly any talking needs none
|
||||
expect(uncaptioned([], said.slice(0, 4))).toEqual([])
|
||||
})
|
||||
|
||||
@@ -155,3 +155,19 @@ test("a CTA said in part and shown in part lands, numbers said in words included
|
||||
put(d, S1.replace(/\.mp4$/, ".render.json"), card(["Dutch"]))
|
||||
expect(of(await run(d), "cta")).toHaveLength(1)
|
||||
})
|
||||
|
||||
test("a CTA no cut ends on is found in the takes that say it, so the fix is one raea cut away (12-05)", async () => {
|
||||
const { mkdtempSync, mkdirSync, writeFileSync } = await import("node:fs")
|
||||
const { tmpdir } = await import("node:os")
|
||||
const { join } = await import("node:path")
|
||||
const { takesSaying } = await import("../src/packs/cut.ts")
|
||||
const root = mkdtempSync(join(tmpdir(), "cta-"))
|
||||
mkdirSync(join(root, "footage"))
|
||||
const words = (s: string, from: number) => s.split(" ").map((text, i) => ({ text, start_ms: (from + i * 0.3) * 1000, end_ms: (from + i * 0.3 + 0.25) * 1000 }))
|
||||
writeFileSync(join(root, "footage", "host.words.json"), JSON.stringify(words("Alright, so download the Acme app and book a call today. Use code SAVE60 for $60 off your first year.", 0)))
|
||||
writeFileSync(join(root, "footage", "ugc4.words.json"), JSON.stringify(words("Saves a lot of time. Go to acme.com today and use code SAVE60 for sixty dollars off for your first year.", 20)))
|
||||
const got = takesSaying(root, ["Go to acme.com and use code SAVE60 for $60 off your first year."])
|
||||
expect(got.map((t) => t.take)).toEqual(["ugc4"])
|
||||
expect(got[0].at).toBeCloseTo(21.5, 1)
|
||||
expect(takesSaying(root, ["Visit the moon today."])).toEqual([])
|
||||
})
|
||||
@@ -11,6 +11,10 @@ test("the frames pack's measures", () => {
|
||||
let f = cutFaces([fr([whole]), fr([edge]), fr([edge]), fr([whole]), fr([edge]), fr([[0, 50, 10, 12, 0.9]])])
|
||||
assert.deepEqual(f.map((x) => [x.level, x.at, x.until]), [["error", 0.5, 1.5], ["warn", 2, 2.5]])
|
||||
assert.match(f[0].says, /left edge/)
|
||||
// a hand at the edge the reader half takes for a face (12-05, run 28: 0.79 then 0.65): a warning that says so
|
||||
f = cutFaces([fr([[0, 598, 41, 82, 0.79]]), fr([[0, 594, 40, 84, 0.65]]), fr([whole])])
|
||||
assert.deepEqual(f.map((x) => [x.level, x.at, x.until]), [["warn", 0, 1]])
|
||||
assert.match(f[0].says, /72% sure it's a face/)
|
||||
// a split screen: a lone line held; a caption's box (two lines close together) isn't one
|
||||
assert.deepEqual(splitsOf(fr([], [["h", 480, 0.8]])), [{ axis: "h", at: 480 }])
|
||||
assert.deepEqual(splitsOf(fr([], [["h", 446, 0.8], ["h", 513, 0.8]])), [])
|
||||
|
||||
@@ -41,6 +41,13 @@ test("the place pack's model", async () => {
|
||||
assert.ok(pa.places[0].top < 400, JSON.stringify(pa.places[0]))
|
||||
ok("raea make place keeps a caption off the sign in the shot")
|
||||
|
||||
// a caption over a sign's top edge, its words all read, is a warning (12-05, run 28's Dutch: "Would" and "this." on
|
||||
// the edge of a handwritten sign): 30% of the words' box hidden makes it "words in the shot", an error
|
||||
const signed = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, faces: [], things: [[60, 520, 420, 70, "text", 0.95], [60, 600, 420, 70, "text", 0.95]] }
|
||||
const onEdge = textOver(man([t("Would", 400, 950, 280, 110)]), [signed], 1)
|
||||
assert.ok(onEdge.every((x) => x.level === "warn" && /the edge of a sign/.test(x.says)), JSON.stringify(onEdge))
|
||||
ok("a caption over a sign's edge is a warning")
|
||||
|
||||
// b: a woman filling the frame; a caption over her coat is at most a warning
|
||||
const b = textOver(man([t("Did you know you", 272, 1344, 536, 88)]), [sc.b], 1)
|
||||
assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b))
|
||||
|
||||
@@ -2,7 +2,7 @@ import { test } from "bun:test"
|
||||
import assert from "node:assert/strict"
|
||||
import type { Clip } from "../src/facts.ts"
|
||||
import type { Levels } from "../src/media.ts"
|
||||
import { balance, busOf, editPoints, nearestGap, soundOf, type Heard } from "../src/packs/sound.ts"
|
||||
import { balance, busOf, editPoints, joined, nearestGap, soundOf, type Heard } from "../src/packs/sound.ts"
|
||||
|
||||
test("the sound pack's measures", async () => {
|
||||
// the sound pack's measures, on made-up takes
|
||||
@@ -114,3 +114,15 @@ test("a word timed longer than a word runs is no word to cut in two (12-04, Elfs
|
||||
// a cut 4 s into the stretch, on quiet: nothing to say about a word
|
||||
assert.equal(editPoints(clip, 30, words, take).filter((f) => f.kind === "edit-in-word").length, 0)
|
||||
})
|
||||
|
||||
test("a take that plays straight on across two clips is one clip: its seam is no edit point", () => {
|
||||
const take = "/w/footage/Acme_Interview.mp4"
|
||||
const a: Clip = { from: 76, to: 96, src: take, at: 53.7, gainDb: 5.5 }
|
||||
const b: Clip = { from: 96, to: 183, src: take, at: 54.3667, gainDb: 5.5 }
|
||||
assert.deepEqual(joined([b, a], 30), [{ ...a, to: 183, fadeOut: undefined }])
|
||||
// a real cut: the take jumps, or the level changes, or the two meet in a fade
|
||||
assert.equal(joined([a, { ...b, at: 92.9 }], 30).length, 2)
|
||||
assert.equal(joined([a, { ...b, gainDb: -1 }], 30).length, 2)
|
||||
assert.equal(joined([{ ...a, fadeOut: 0.2 }, b], 30).length, 2)
|
||||
assert.equal(joined([a, { ...b, src: "/w/footage/Other.mp4" }], 30).length, 2)
|
||||
})
|
||||
@@ -238,10 +238,10 @@ registerRoot(() => <Composition id="hop3d" component={Hop} width={1280} height={
|
||||
|
||||
## Sound: one-shots on transitions, music ducked under the voice
|
||||
|
||||
A game's sound is Tone.js on raea (`motion/music` has the whole of it). Every input and outcome gets a sound, the
|
||||
world's own sounds (machines, footsteps, a room's tone) sit where they are, and music, when the game has some, is a
|
||||
loop written to come round, not a pad. Build the instruments at the top level, give the music and the sounds their
|
||||
buses, and fire each one-shot on the frame its event happens:
|
||||
A game's sounds are Tone.js on raea (`motion/music` has the whole of it). Every input and outcome gets a sound, the
|
||||
world's own sounds (machines, footsteps, a room's tone) sit where they are, and music, when the game has some, is one
|
||||
bed from `raea gen music` on the music bus, never notes written by hand or a pad. Build the instruments at the top
|
||||
level, give the music and the sounds their buses, and fire each one-shot on the frame its event happens:
|
||||
|
||||
- `useGameEvents(INITIAL, fold, (before, after) => machine.state(after.hero) === "land" && machine.state(before.hero) !== "land")`
|
||||
gives the frames where a transition happened. `<Tone.Sfx when={landings.includes(frame)} play={(t) => thump.triggerAttackRelease("C2", "8n", t)} />`
|
||||
|
||||
@@ -80,7 +80,7 @@ No reason makes these right:
|
||||
- **Invented facts.** No number, result, price, quote, customer or comparison that the brief, the person or the
|
||||
footage didn't give you. If the piece needs proof you don't have, make it without the proof and say what would help.
|
||||
- **Generated images or video.** Pictures come from real footage, stock in the project's media, or are built:
|
||||
components, drawn shapes, 3D. Generated sound is allowed: TokenSynth instruments, SAO foley and Pocket TTS
|
||||
narration (all local).
|
||||
components, drawn shapes, 3D. Generated sound is allowed: the music bed from `raea gen music`, SAO foley and
|
||||
Pocket TTS narration.
|
||||
- **Redrawn logos.** Use the real files.
|
||||
- **Calling it done without looking.** A render nobody looked at isn't finished.
|
||||
@@ -68,10 +68,9 @@ Read the files a task needs with `raea guide motion/NAME`, one or two at a time,
|
||||
or `var(--brand-*)` where a class can't reach. Never write a hex palette of your own. A role the kit leaves empty
|
||||
is yours to decide from the brand's own colours (`motion/brand`).
|
||||
8. **Sound is part of the edit.** Decide what each scene is heard as (silence, its own sound, source music, score,
|
||||
effects) before placing any; music is composed for the cut, never a bed by default. Each sound goes in its own
|
||||
`<Sequence from layout="none">`. Use `gainDb` for levels, Tone.js for music (`motion/music`: sample-library or
|
||||
TokenSynth instruments in a Sampler, playing a motif, chords that move and a rhythm) and `sao()` for foley, and
|
||||
put one `<Mix lufs={-14} />` in the composition. Put the sounds in the tree in time order.
|
||||
effects) before placing any; whether it has music is the brief's or its method's call. Each sound goes in its own
|
||||
`<Sequence from layout="none">`. Use `gainDb` for levels, one instrumental bed from `raea gen music` for music
|
||||
(`motion/music`) and `sao()` for foley, and put one `<Mix lufs={-14} />` in the composition. Put the sounds in the tree in time order.
|
||||
9. **Keep animated styles present on every frame.** The engine keeps a style property that React stops sending.
|
||||
Write `transform: scale(1)` and `opacity: 1` rather than leaving them out when an animation settles. Always set
|
||||
`fontFamily`, because the engine's default face is a serif.
|
||||
|
||||
@@ -11,13 +11,11 @@
|
||||
catches a wrong name before anything renders.
|
||||
- The brand's styles come from `./styles.gen` (`<style>{css}</style>`), and `brand/brand.json` imports as JSON
|
||||
(`motion/brand`).
|
||||
- Describe generated sound as values: `sao(prompt, {seconds})` for foley, given to `<Audio src>` (`motion/sound`),
|
||||
and `Tone.tokensynth(timbre, notes)` for an instrument's notes in a `Tone.Sampler` (`motion/music`).
|
||||
- Recorded instruments are cast for each part from the thousands of free sampled instruments (Pianobook, Karoryfer,
|
||||
the SFZ index, Decent Samples, Versilian and more: `motion/music` "Cast the instruments", `motion/sources`). For a
|
||||
sketch, `raea make sounds WORDS` searches the four packs raea carries, and `raea make sounds get PACK/INSTRUMENT` copies one
|
||||
into `media/sounds/PACK-INSTRUMENT/` with a `LICENCE.txt` and prints the `staticFile` paths and the Sampler that
|
||||
plays them. How to set up SAO and TokenSynth is in `motion/sources`.
|
||||
- Describe generated sound as values: `sao(prompt, {seconds})` for foley, given to `<Audio src>` (`motion/sound`).
|
||||
The music bed is a file `raea gen music` wrote (`motion/music`), played with `<Audio src>` like any other.
|
||||
- A game's one-shots can play a recorded pack's notes: `raea make sounds WORDS` searches the four packs raea carries,
|
||||
and `raea make sounds get PACK/INSTRUMENT` copies one into `media/sounds/PACK-INSTRUMENT/` with a `LICENCE.txt` and
|
||||
prints the `staticFile` paths and the Sampler that plays them. How to set up SAO is in `motion/sources`.
|
||||
- Show stills with `<Img src>`. The frame waits for the image to load, and a missing one fails the render, naming
|
||||
`src`.
|
||||
- Keep pictures real: the person's footage, stock already in the object's media, or things you build (components,
|
||||
@@ -30,8 +28,7 @@ error and so is a URL (`https://...`). `staticFile` checks both. A module import
|
||||
fails loudly with the line that has it instead of rendering a black clip.
|
||||
|
||||
Generated imagery is banned outright (floor): no AI-generated images or video, ever. Generated sound is allowed by
|
||||
policy, and made on this computer: TokenSynth for an instrument's notes where no library has the timbre, SAO for
|
||||
foley, Pocket TTS (`<Speech>`) for narration over the picture. The sample libraries are recordings under open licences
|
||||
policy: the music bed from `raea gen music`, SAO for foley, Pocket TTS (`<Speech>`) for narration over the picture. The sample libraries are recordings under open licences
|
||||
(CC0, CC-BY, public domain); a CC-BY one is credited where the piece is shown.
|
||||
|
||||
## Common mistakes
|
||||
|
||||
@@ -11,9 +11,10 @@
|
||||
time shown at the clip's frame `f` is `(startFrom + f * playbackRate) / fps`. `trimBefore` and `trimAfter` are other
|
||||
names for the same two props: use one name or the other, never both.
|
||||
- Frame a talking head on its face. `raea frame TAKE` says whether the take is a talking take (`<FaceFrame>`, from
|
||||
`raea make component add face-frame`) or a wide screen recording (`<ScreenFit>`). `<FaceFrame src={take} />` (or
|
||||
`<Video framing="face">`) has the engine find the face and keep the eyes 38% down the frame as the speaker moves; an
|
||||
objectPosition or transform of your own on that Video turns the framing off. Zoom a clip for emphasis with
|
||||
`raea make component add face-frame`) or a wide screen recording (`<ScreenFit>`). `<FaceFrame src={take} />` has the engine find the face and keep the eyes 38% down the frame as the speaker moves; an
|
||||
objectPosition or transform of your own on it turns the framing off. A project with `components/Framed.tsx` (raea
|
||||
cloud's footage projects) frames through it instead: `<Framed src startFrom endAt>` crops on the face from
|
||||
`footage/faces.json`. Zoom a clip for emphasis with
|
||||
`punchIn={1.15}`. Alternating punched and unpunched clips between cuts gives a talking head rhythm without a zoom
|
||||
on every sentence. The face track comes from raea-perceive (the render is refused without it, or with no face found)
|
||||
and is kept beside the take as TAKE.faces.json, so a second render reads it.
|
||||
@@ -67,8 +68,8 @@ take the in- and out-points from the take's words (the gaps between them), not f
|
||||
- `endAt` at or before `startFrom`: it throws.
|
||||
- Every clip without a Sequence, so all of them play from frame 0 on top of each other.
|
||||
- `transform: scale(1.2)` on a Video inside a box without `overflow: hidden`: the zoom spills over the parts around it.
|
||||
- An `objectPosition` or `transform` on a Video with `framing="face"`: either one turns the framing off, and the crop
|
||||
stays where you put it while the speaker moves. Zoom a framed take with `punchIn`.
|
||||
- An `objectPosition` or `transform` on a `<FaceFrame>`: either one turns the framing off, and the crop stays where
|
||||
you put it while the speaker moves. Zoom a framed take with `punchIn`.
|
||||
- A zoom on every sentence. That is the template ad the floor refuses. Punch in where the line earns it.
|
||||
- Cutting on round seconds instead of word gaps.
|
||||
- Leaving the clip's sound at unity under a loud bed. Balance it in `motion/sound`.
|
||||
|
||||
@@ -3,9 +3,8 @@
|
||||
## What to do
|
||||
|
||||
- Generate a picture, a clip, music, an effect, a voice, a 3D model or words with `raea gen` when the piece needs
|
||||
something that isn't in the footage, the stock or the scene. Music only when the person asks for a generated
|
||||
track: a score is composed on instruments for the cut (`motion/music`), and a generated track can't be cut on the
|
||||
bar or edited note by note. `-o` is the folder; each command prints the files it wrote; use it like any
|
||||
something that isn't in the footage, the stock or the scene. A piece's music is always
|
||||
one instrumental bed from `raea gen music` (`motion/music`). `-o` is the folder; each command prints the files it wrote; use it like any
|
||||
other media (`<Img src>`, `<Video src>`, `<Audio src>`, `<Model src>`).
|
||||
- Quote first. `raea gen plan FLOW` and `--plan` on a one-shot cost nothing and say where each step runs and what it
|
||||
costs in cents. A run past its cap is refused before anything is spent: `--max-cents N`, else
|
||||
@@ -15,6 +14,7 @@
|
||||
```sh
|
||||
raea gen image "a paper kite over dunes at dawn, 35mm" --aspect 16:9 -o media/gen
|
||||
raea gen video "the kite climbs into the light" --image media/gen/<the still>.png --seconds 5 -o media/gen
|
||||
raea gen music "a light acoustic groove, warm and playful, instrumental, no vocals" --seconds 40 -o media/music
|
||||
raea gen sfx "paper flutter in wind, close, no music" --seconds 3 -o media/gen
|
||||
raea gen speech "Find your wind." -o media/gen
|
||||
raea gen mesh "a paper kite" --image media/gen/<the still>.png -o media/gen # the GLB and its textures together
|
||||
|
||||
@@ -1,72 +1,30 @@
|
||||
# Music and sound effects: Tone.js on raea (raea/tone)
|
||||
# Music and sound: a bed from raea gen, a game's sounds on Tone.js (raea/tone)
|
||||
|
||||
## Decide what the picture needs before writing a note
|
||||
## Music: one bed, from raea gen
|
||||
|
||||
Music is never a default. A bed under every second makes every piece sound like every other one, and a held pad or
|
||||
drone under a long reverb is what generated music sounds like. Before any instrument goes in:
|
||||
Whether a piece has music is its brief's call, or its method's (a method that says every cut has music means every
|
||||
cut). Decide what each stretch is heard as first: silence, the scene's own sound, effects, a voice, the bed.
|
||||
|
||||
- Name what each stretch is heard as: silence; the scene's own sound (diegetic: footsteps, a room, a radio, a game's
|
||||
machines, anything the people on screen could hear); source music (music playing in the scene); score (music only
|
||||
the audience hears); effects; a voice. Several at once is fine, and none is a choice too: a pitch with a voice may
|
||||
need only effects and a four-second sting on the end card. Write the decision in the storyboard or DIRECTION.md,
|
||||
one line a scene.
|
||||
- Spot the cut the way a music editor does: number each cue (1m1, 1m2...) with the frame it starts on, the moments
|
||||
it has to hit (the hook, a reveal, the logo), where it turns (where the edit changes idea) and where it stops. A
|
||||
cue ends on a hit, the "button" (the last chord on the last cut or the logo), not on a fade. Half a bar of silence
|
||||
before a reveal is what makes the reveal.
|
||||
- Take the tempo from the cut. Frames per beat = fps × 60 / bpm: at 30 fps, 12 frames at 150 bpm, 15 at 120, 20 at
|
||||
90. Pick the bpm that puts the main cuts on beats and the biggest on downbeats, or set it so they do
|
||||
(`bpm.value = (bars * 4 * 60 * fps) / framesToTheCut`). Shots of 1 to 1.5 s suit 120 to 160 bpm; shots of 3 to 5 s
|
||||
suit 70 to 100, or a half-time feel. With a song, cut to its map instead (`motion/timing`).
|
||||
- A sustained texture (a held pad, a drone, a reverb wash) goes in only when the scene asks for one by name ("dread",
|
||||
"the ship's hum") and the direction says why in a line. Even then something over it moves.
|
||||
- The music is one instrumental bed for the piece: `raea gen music "warm, playful light acoustic groove, no vocals"
|
||||
--seconds 40 -o media/music` (`motion/gen`: quote it with `--plan` first). On raea cloud, the `generate` tool makes
|
||||
the same bed. Name the feel the brief asks for, and say "instrumental, no vocals".
|
||||
- Lay it under the whole cut: `<Audio src={staticFile("music/bed.mp3")} bus="music" gainDb={-10} fadeIn={0.3}
|
||||
fadeOut={1} />`, with the voices on `bus="voice"`. raea's mix brings every line of dialogue to one level, and
|
||||
`raea check` says when the bed is lost under the voice or fights it, with the gainDb that fixes it; change the level
|
||||
only on what it says. A footage cut made with `components/Cut.tsx` takes the bed as its `bed` prop and lays it so.
|
||||
- One bed a piece. A second track, a sting or a riser made to fix the first is a second way to make music: make the bed
|
||||
again with a better prompt instead.
|
||||
|
||||
## Cast the instruments for this piece
|
||||
## A game's sounds and the buses: Tone.js on raea
|
||||
|
||||
Every agent that reaches for "a piano" gets the same Salamander grand, and every "MIDI" part the same General MIDI
|
||||
bank, so every score sounds alike. Thousands of sampled instruments are free to use, and choosing them is part of
|
||||
writing the music. Shane, 2026-11-23: "when i say midi it just picks the same ones there thousands of insturments out
|
||||
there to go use".
|
||||
|
||||
- Cast each part the way a composer books a player. Write a line per part: what it is, what it's like and how it's
|
||||
played ("an old upright, a little out of tune, felt down, close-miked"; "one cello, dry, in a small room, played
|
||||
low"; "a harmonium with its bellows audible"). Let the picture choose: its place, its era, what is in the room.
|
||||
- Search for that line in `motion/sources`' instrument libraries: Pianobook's thousands of community instruments,
|
||||
Karoryfer, the SFZ index, Decent Samples, Versilian, musical-artifacts and the rest. Listen to a few candidates on
|
||||
the part's own notes before choosing. A character instrument (a prepared piano, a music box, a bowed vibraphone, an
|
||||
out-of-tune upright, a particular cello) does more for a piece than a clean generic one.
|
||||
- `raea make sounds` (the Salamander grand, FluidR3's General MIDI set, tonejs-instruments, VCSL's single takes) is for a
|
||||
sketch, or for a part that really is that instrument. It isn't the cast. A score made only of its packs needs a
|
||||
reason in the direction.
|
||||
- "MIDI" means notes, not General MIDI sounds. A General MIDI bank (FluidR3, MuseScore General) plays a MIDI file
|
||||
as it is, to check it. A score's parts are cast instruments playing those notes.
|
||||
- Write the cast in the piece's notes: each part's instrument, where it came from and its licence. When a part
|
||||
can't be cast (no free library has it), that's when TokenSynth or a synth comes in.
|
||||
|
||||
## What to do
|
||||
|
||||
- Write music and sound effects in Tone.js, as its docs write them: `import * as Tone from "raea/tone"`, then
|
||||
- Write a game's sounds in Tone.js, as its docs write them: `import * as Tone from "raea/tone"`, then
|
||||
instruments, effects, `connect`/`toDestination`/`chain`, `triggerAttackRelease`, and the Transport with `Loop`,
|
||||
`Part`, `Sequence` and `Pattern`. What you know of Tone works; the differences are below. It's a DAW in code: a
|
||||
track is an instrument and its effects into a bus, a clip is a `Part` or `Sequence`, the arrangement is where each
|
||||
starts and stops on the Transport.
|
||||
- Make music from instruments playing notes, not from a generated track. Each instrument is a `Tone.Sampler` (a kit
|
||||
is `Tone.Players`); fill it one of three ways:
|
||||
- **A sampled instrument cast for the part** (above), first. Most come as SFZ or Decent Sampler presets: read the
|
||||
preset's map (SFZ `<region>`: `sample=`, `pitch_keycenter=`, `lokey`/`hikey`, `lovel`/`hivel`; a `.dspreset`'s
|
||||
`<sample path rootNote loNote hiNote loVel hiVel>`) into the Sampler's `urls`, one Sampler per velocity layer
|
||||
you use. For a quick sketch, `raea make sounds cello` searches the four packs raea carries (the Salamander grand;
|
||||
FluidR3's 128 General MIDI instruments; tonejs-instruments' strings, brass, woodwinds and guitars; VCSL's
|
||||
keyboards, harps, mallets, drums and percussion), and `raea make sounds get tonejs-instruments/cello` copies its notes
|
||||
into `media/sounds/` and prints the `Sampler` that plays them. Drums and hits come as takes for `Tone.Player`s.
|
||||
Everything else is fetched by hand (`motion/sources`; `raea make sounds get` reaching it all is docs/sound.feature SN4).
|
||||
- **TokenSynth** for a timbre no library has: `Tone.tokensynth("a bowed saw, close, eerie", ["C3", "E3", "G#3",
|
||||
"C4", "E4", "G#4", "C5"], { seconds: 2 })` renders those root notes, a major third apart, once on this computer,
|
||||
and the Sampler pitches between them. Describe
|
||||
the timbre the way you'd describe a patch ("a soft wooden marimba, felt mallet, warm"; "a bright analog synth
|
||||
lead, saw, short decay"); a note's `seconds` is how long it's held (under 5). Its takes need curating (below).
|
||||
- Tone's own synths (`Synth`, `PolySynth`, `MonoSynth`, `MembraneSynth`, `MetalSynth`, `NoiseSynth`, `FMSynth`) for
|
||||
parts that are synthetic on purpose: an 808 kick, an analog bass, a chiptune lead, a riser.
|
||||
`Part`, `Sequence` and `Pattern`. What you know of Tone works; the differences are below.
|
||||
- Fill an instrument for a game's one-shots with a `Tone.Sampler` (a kit is `Tone.Players`): SAO's takes
|
||||
(`Tone.sao("a bright arcade coin chime, short", { seconds: 1 })`), a recorded pack (`raea make sounds get
|
||||
vcsl/marimba` copies its notes into `media/sounds/` and prints the Sampler), or Tone's own synths (`MembraneSynth`
|
||||
for a thump, `MetalSynth` for a clank, `NoiseSynth` for a whoosh). These are effects, not a score: a game's music is
|
||||
a bed from `raea gen music`, as above.
|
||||
- Make sound effects and foley with SAO or a recorded pack: `Tone.sao("a bright arcade coin chime, short", { seconds:
|
||||
1 })` in a Sampler or Player, or `sao(...)` in an `<Audio>`, built in layers (`motion/sound`). Narration over the
|
||||
picture is `<Speech>` from `raea/speech` (Pocket TTS, local; `motion/sound`).
|
||||
@@ -88,80 +46,13 @@ there to go use".
|
||||
`when` true on that frame only (a frame from `useGameEvents`, or a machine's transition). Give one-shots
|
||||
`Tone.vary(instrument, { pitch: 0.3, volume: 2 })` so repeats don't sound copied (the variation is seeded by the
|
||||
frame, so a replay is the same). Cap their voices with `maxPolyphony` (the oldest is stolen, faded in 5 ms).
|
||||
- In a timeline, cut on the music: `Tone.Time("1m").toFrames(fps)` is a bar in frames, and `Tone.Time("4n")` a beat.
|
||||
- To hear a sound before writing it in, `raea make sao "PROMPT" --seconds 1 --dir EDIT_DIR -o EDIT_DIR/media/sfx/try.wav`
|
||||
or `raea make tokensynth "TIMBRE" --notes C3 --dir EDIT_DIR -o EDIT_DIR/media/try/` makes it now and keeps it in the
|
||||
edit's asset store (`--dir` is the edit's folder; without it, the folder you run it from), so the edit's own call
|
||||
with the same words and settings then plays what was made instead of making it again. Another `--seed` makes
|
||||
makes it now and keeps it in the edit's asset store (`--dir` is the edit's folder; without it, the folder you run it
|
||||
from), so the edit's own call with the same words and settings then plays what was made instead of making it again. Another `--seed` makes
|
||||
another take; play a seed's file by its path (`staticFile("sfx/try.wav")`), since `sao()` in the edit has no seed.
|
||||
- When SAO or TokenSynth isn't installed yet, `raea setup-audio` installs it (`motion/sources` says what it fetches
|
||||
- When SAO isn't installed yet, `raea setup-audio` installs it (`motion/sources` says what it fetches
|
||||
and what to do when it fails).
|
||||
|
||||
## Writing music for picture
|
||||
|
||||
Write it as a composer would, for this cut:
|
||||
|
||||
- **A motif first.** Three to seven notes over two to four bars, with a rhythm of its own, before any chord. Then
|
||||
vary it rather than loop it: answer it, fragment it, move it to another instrument or register, put new chords
|
||||
under it. End the cue on it.
|
||||
- **Harmony that moves.** In an active cue, change chord every bar or every two beats; keep chords of two to four bars
|
||||
for a slow passage. Move the inner voices by step or hold a common tone, set the bass against the tune (contrary
|
||||
motion, inversions so it walks), and resolve a pedal when it ends. Keep the low end open: no thirds below about C3,
|
||||
fifths down to about C2, only octaves under that.
|
||||
- **Rhythm and groove.** At least one part moves in eighths or sixteenths: an ostinato, a pizzicato, an arpeggio, a
|
||||
kit, hand percussion. Accent where the picture moves. Spread velocities (0.35 to 0.95, not all 0.8), and put a
|
||||
played part a few milliseconds off the grid (5 to 15 ms, written into the note's time: `humanize` is ignored here).
|
||||
A drummer's recorded groove beats one typed in (Groove MIDI, `motion/sources`).
|
||||
- **Orchestrate by register.** One job each: a bass (E1 to C3), sparse harmony (C3 to C5), one lead (C4 to C6), the
|
||||
rhythm, colour on top (glockenspiel, celesta, harp). Hand the tune to a new instrument each section, and use the
|
||||
articulations the library has (staccato, legato, pizzicato, tremolo, a swell). A pad, where the scene names one,
|
||||
is glue 12 dB or more under the lead, never the part.
|
||||
- **The arrangement follows the edit.** Sections change where the edit changes idea: build by adding parts and by
|
||||
switching sections, on bar lines; peak, then strip back; drop out before the reveal; end on the button. A sting
|
||||
lasts 1 to 4 s, sits in the cue's key and lands on a beat.
|
||||
- **Write around the voice.** The tune answers in the gaps between lines, and the arrangement thins under speech.
|
||||
- **Each instrument its own room.** A short reverb per instrument or per section (decay 1.2 to 2.5 s, wet 0.15 to
|
||||
0.3), never one long wash over the bus: a 6 s reverb and a low-pass on the whole music bus erase every attack, and
|
||||
that is how a score turns into a drone.
|
||||
- **Source music lives in the scene.** A radio, a band in the room, a phone: narrow it to the device (a high-pass
|
||||
around 300 Hz and a low-pass around 3.5 kHz for a small speaker), pan it to where it is (`Tone.Panner`), put it in
|
||||
the room's reverb, and let the scene's own sound sit with it. Crossing over is strong: a radio song that opens out
|
||||
to full range as it becomes the score, a score hit that lands on an action in the scene.
|
||||
- Leave silence. Let the music start after a chapter card clears and stop before the next; let a card sit on one low
|
||||
note.
|
||||
- Write for this picture's feeling, not a genre's surface: a stock walking bass and brushes under everything reads as
|
||||
pastiche as surely as a pad does.
|
||||
- Period source music can be real: US sound recordings published before 1926 and compositions published before 1931
|
||||
are public domain in the US (2026). archive.org's 78rpm transfers give the period's own sound; play them as
|
||||
`<Audio bus="music">`, narrowed and placed as source music, ducked with the rest.
|
||||
- Synth drums (`MembraneSynth` kicks, noise "brushes") sound synthetic on anything acoustic; use a library's recorded
|
||||
kit (`raea make sounds kick`, `snare`, `hihat`).
|
||||
|
||||
## Instruments from TokenSynth: build a library, don't trust a take
|
||||
|
||||
A TokenSynth note is one sample from a model, and a lot of takes are bad. In a 35-minute documentary score (2026-10-20),
|
||||
12 of 30 single-seed root notes failed: hiss and buzz in place of a horn, a sax or accordion an octave (or 34
|
||||
semitones) off, a piano note still at full level when its file ends, so every held note stopped with a click. That is
|
||||
the "vanilla and abrasive" sound. It learned from 5-second notes at four velocities, so it gives one dynamic and can
|
||||
miss the pitch asked for. So:
|
||||
|
||||
- Reach for a recorded instrument first, cast for the part (above): a recording, no gamble. Use TokenSynth for what
|
||||
no library has, or a timbre you can describe better than find.
|
||||
- Declare each instrument as a candidate, not a call: its timbre, roots every 3 to 4 semitones over the range it plays
|
||||
(a Sampler pitched further than that starts to sound fake), 3 or more seeds, and `seconds` long enough for the
|
||||
sound to die away on its own (4 for piano, 6 for sustained strings).
|
||||
- Render every candidate through a `Sampler` (one per instrument and seed, each root played once), never through an
|
||||
`<Audio>` of a tokensynth note: today an `<Audio>` drops the note's pitch and seed and makes the prompt alone.
|
||||
- Measure and pick: `uv run --with numpy --with soundfile python3 -I TOOLS/tokensynth/curate.py EDIT_DIR` (TOOLS is
|
||||
`tools/` in a raea checkout, `share/raea/tools/` beside an installed raea) checks each
|
||||
take's pitch (cents off the note), energy above 4 kHz, spectral flatness (noise), whether it has decayed by the end,
|
||||
and its onset, and writes `instruments.gen.json` ({timbre: {midi: seed}}) with the best passing seed per root.
|
||||
Build the score's Samplers from that file only; a root with no passing take gets more seeds, not a pass.
|
||||
- Prefer timbres TokenSynth does well (felt or soft piano, sustained cello section, bowed or plucked bass, vibraphone,
|
||||
clarinet in its low register) to the ones it does badly (muted trumpet, tenor sax, accordion: breath and reed
|
||||
noise come out as hiss).
|
||||
- For dynamics, render a soft and a loud velocity as two Samplers and pick one by each note's velocity.
|
||||
|
||||
## Why
|
||||
|
||||
Tone code here builds an edit's graph and an event list instead of driving Web Audio. The Transport's callbacks run in
|
||||
@@ -170,151 +61,33 @@ and a play of the same frames identical, and the same holds after a seek. A node
|
||||
rebuilds the graph (a pause in the sound), and a note triggered while rendering would fire again on every re-render.
|
||||
So the graph goes at the top level, and in-game sounds go through `<Sfx>`.
|
||||
|
||||
Generated sources are made once per their inputs: the prompt, the length, a TokenSynth note's pitch, velocity, seed
|
||||
and precision. They're normalised, cached as PCM in the object's `assets/`, and played like any file. TokenSynth and
|
||||
SAO run on this computer and install themselves the first time they're used (minutes, once; `raea setup-audio` does
|
||||
it ahead of time). Music written as notes on instruments can be edited note by note, cut on the bar and ducked per
|
||||
part; a generated track can't.
|
||||
Generated sources are made once per their inputs (the prompt, the length, the seed), cached in the object's
|
||||
`assets/`, and played like any file. SAO runs on this computer and installs itself the first time it's used
|
||||
(`raea setup-audio` does it ahead of time).
|
||||
|
||||
Policy: music is notes on Tone.js instruments (sample libraries first, TokenSynth for a timbre no library has, synths
|
||||
for synthetic parts), effects and foley are SAO or recorded packs (`motion/sources`), narration is Pocket TTS
|
||||
(`<Speech>`), all local. Any other generation is a `raea gen` step, quoted and capped (`motion/gen`). (`lyria()`, a
|
||||
remote music model, is retired: an older edit keeps the take it made, and a new one is refused.)
|
||||
Policy, the same everywhere raea runs (this guide, the raea skill, raea cloud's boxes and the desktop): a piece's music
|
||||
is one instrumental bed from `raea gen music` (raea cloud's `generate` tool is the same model); effects and foley are
|
||||
SAO or recorded packs (`motion/sources`); narration is Pocket TTS (`<Speech>`). Never music written note by note, a
|
||||
held pad or drone, a voice or lyrics in the bed, or a second track to fix the first. (`lyria()` is retired: an older
|
||||
edit keeps the take it made, and a new one is refused.)
|
||||
|
||||
## Common mistakes
|
||||
|
||||
- A pad and a sine sub through a low-pass into a long reverb as the score. That's a drone, not music: write a motif,
|
||||
chords that move and a part with rhythm.
|
||||
- One chord every four bars for a minute, or a two-bar loop for thirty seconds. Change the harmony every bar or two
|
||||
and the arrangement every four to eight.
|
||||
- Every note at the same velocity, on the grid. Spread the dynamics and move played parts a few milliseconds.
|
||||
- A cue that fades out at the end. End it on the last cut, on a chord or a hit.
|
||||
- Music under every scene because the piece "needs music". Decide per scene; silence and the scene's own sound count.
|
||||
- `synth.triggerAttackRelease(...)` in a component body. It fires on every render; use `<Tone.Sfx>`.
|
||||
- `<Tone.Sfx when={g.coinTaken}>` on a flag the state holds for many frames: it fires on every one. Give it the
|
||||
frames the event happens on (`useGameEvents`).
|
||||
- `new Tone.Synth()` inside a component. Make instruments at the top level.
|
||||
- A `https://` URL for a Sampler or a Player. Sources are media files or generated assets, and the render has no
|
||||
network: `raea make sounds get` puts a library's files in `media/` first.
|
||||
- One root for a whole part, or one an octave. A Sampler stretched far from its root sounds chipmunked or muddy;
|
||||
give it a root every 3 to 4 semitones over the range the part plays: a library's own roots (`raea make sounds get`
|
||||
with no `--notes` takes them a minor third apart, or every note the library sampled if it's sparser), or as many
|
||||
TokenSynth roots.
|
||||
- Rewording a `tokensynth()` timbre on every pass: each new wording makes its notes again. Settle the timbre first.
|
||||
- A sample library's licence ignored. CC-BY ones (FluidR3, Salamander, tonejs-instruments) need their credit where
|
||||
the piece is shown; `LICENCE.txt` beside the files has the line. VCSL is CC0.
|
||||
- `part.loop = true` after `part.start()`: the Part plays once. Set `loop` and `loopEnd` first.
|
||||
- `Tone.Draw.schedule` for visuals. There's no draw loop: read the frame (`useCurrentFrame`) and the same times.
|
||||
- Cutting on `Tone.Time("1m").toFrames(fps)` across a tempo ramp. `Tone.getTransport().bpm.rampTo(120, 4)` bends the
|
||||
grid, as in Tone (the notes come closer together; an exponential ramp runs linear), but `Time(...)` is at the tempo
|
||||
when it's read, so after a ramp a bar is no longer that many frames.
|
||||
- An LFO on an instrument's parameter (a synth's `detune`, a Sampler's `volume`): it does nothing yet. On an effect's
|
||||
or a `Gain`'s, `Volume`'s or `Channel`'s it works, as in Tone (`new Tone.LFO("4n", 400, 4000).start()
|
||||
.connect(filter.frequency)`).
|
||||
- A Sequence or Loop with no `Tone.getTransport().start()`. Nothing plays until the Transport starts, as in Tone.
|
||||
|
||||
## Example: a cue with a motif, chords that move and a kit, cut on the bar
|
||||
|
||||
Spotted as one cue over nine one-bar cards: A (bars 1 to 4) piano and a pizzicato ostinato, the flute's motif from
|
||||
bar 3; B (bars 5 to 8) the ostinato drops out, bass and kit come in, the motif climbs; the button on the end card's
|
||||
cut. The instruments are `raea make sounds` packs so the example runs anywhere with one command each; a real piece casts
|
||||
its own (above). Each command prints the roots it fetched (with no `--notes`, a minor third apart from C1 to C7, or
|
||||
every note the library sampled when that's sparser):
|
||||
|
||||
```sh
|
||||
raea make sounds get salamander/piano
|
||||
raea make sounds get fluid/pizzicato_strings
|
||||
raea make sounds get tonejs-instruments/flute
|
||||
raea make sounds get fluid/acoustic_bass
|
||||
raea make sounds get vcsl/bass-drum-1 && raea make sounds get vcsl/snare-drum-modern-1 && raea make sounds get vcsl/hi-hat-cymbal
|
||||
```
|
||||
|
||||
```tsx
|
||||
import { AbsoluteFill, Composition, Mix, Series, registerRoot, staticFile } from "raea";
|
||||
import * as Tone from "raea/tone";
|
||||
|
||||
Tone.getTransport().bpm.value = 96; // first: a Part reads its times at the tempo when it's made
|
||||
const BAR = Tone.Time("1m").toFrames(30); // 75 frames
|
||||
|
||||
// the roots each part's range needs, of those `raea make sounds get` printed (D#3 is the file Ds3.mp3)
|
||||
const notes = (dir: string, names: string[]) => Object.fromEntries(names.map((n) => [n, staticFile(`sounds/${dir}/${n.replace("#", "s")}.mp3`)]));
|
||||
const room = new Tone.Reverb({ decay: 1.6, wet: 0.2 }).connect(Tone.buses.music);
|
||||
const piano = new Tone.Sampler({ urls: notes("salamander-piano", ["A2", "C3", "D#3", "F#3", "A3", "C4", "D#4", "F#4"]), release: 1, volume: -8 }).connect(room);
|
||||
const pizz = new Tone.Sampler({ urls: notes("fluid-pizzicato_strings", ["D#2", "F#2", "A2", "C3", "D#3", "F#3", "A3", "C4"]), release: 0.2, volume: -12 }).connect(room);
|
||||
const flute = new Tone.Sampler({ urls: notes("tonejs-instruments-flute", ["E4", "A4", "C5", "E5", "A5", "C6"]), release: 0.4, volume: -6 }).connect(room);
|
||||
const bass = new Tone.Sampler({ urls: notes("fluid-acoustic_bass", ["D#1", "F#1", "A1", "C2", "D#2"]), release: 0.3, volume: -6 }).connect(Tone.buses.music);
|
||||
const kit = new Tone.Players({
|
||||
kick: staticFile("sounds/vcsl-bass-drum-1/BDrumNew_hit_v5_rr1_Sum.wav"),
|
||||
snare: staticFile("sounds/vcsl-snare-drum-modern-1/Snare2_HitSN_v5_rr1_Mid.wav"),
|
||||
hat: staticFile("sounds/vcsl-hi-hat-cymbal/HiHat_HitC_v3_rr1_Mid.wav"),
|
||||
ghost: staticFile("sounds/vcsl-hi-hat-cymbal/HiHat_HitC_v1_rr1_Mid.wav"), // the soft take, for the off-beats
|
||||
}).connect(Tone.buses.music);
|
||||
|
||||
// a chord a bar, voiced so the inner notes move by step: Am F C G, then F G Am E
|
||||
const CHORDS = [["A3", "C4", "E4"], ["A3", "C4", "F4"], ["G3", "C4", "E4"], ["G3", "B3", "D4"], ["A3", "C4", "F4"], ["G3", "B3", "D4"], ["A3", "C4", "E4"], ["G#3", "B3", "E4"]];
|
||||
// comped, not held: the downbeat and the and-of-two, the second softer
|
||||
new Tone.Part((t, c) => piano.triggerAttackRelease(c.notes, "8n", t, c.vel), CHORDS.flatMap((chord, bar) => [
|
||||
{ time: `${bar}:0`, notes: chord, vel: 0.62 },
|
||||
{ time: `${bar}:1:2`, notes: chord, vel: 0.42 },
|
||||
])).start(0);
|
||||
|
||||
// A: an eighth-note ostinato on each chord's root (root, fifth, octave, fifth), accented on the beat
|
||||
new Tone.Part((t, n) => pizz.triggerAttackRelease(n.note, "16n", t, n.vel), ["A2", "F2", "C3", "G2"].flatMap((root, bar) =>
|
||||
[0, 7, 12, 7, 0, 7, 12, 7].map((up, i) => ({ time: `${bar}:${i >> 1}:${(i & 1) * 2}`, note: Tone.Frequency(root).transpose(up).toNote(), vel: i % 2 ? 0.45 : 0.75 })),
|
||||
)).start(0);
|
||||
|
||||
// the motif (E D C D, then B A G) from bar 3, sequenced up and answered in B; each note a few ms off the grid
|
||||
const TUNE: [string, string, string, number][] = [
|
||||
["2:0", "E5", "4n", 0.7], ["2:1", "D5", "8n", 0.55], ["2:1:2", "C5", "8n", 0.6], ["2:2", "D5", "2n", 0.75],
|
||||
["3:0", "B4", "4n.", 0.65], ["3:1:2", "A4", "8n", 0.5], ["3:2", "G4", "2n", 0.6],
|
||||
["4:0", "A5", "4n", 0.8], ["4:1", "G5", "8n", 0.6], ["4:1:2", "F5", "8n", 0.65], ["4:2", "G5", "2n", 0.8],
|
||||
["5:0", "D5", "4n.", 0.7], ["5:1:2", "B4", "8n", 0.55], ["5:2", "D5", "2n", 0.7],
|
||||
["6:0", "E5", "4n", 0.75], ["6:1", "C5", "8n", 0.6], ["6:1:2", "E5", "8n", 0.7], ["6:2", "A5", "2n", 0.9],
|
||||
["7:0", "G#5", "2n.", 0.8], ["7:3", "B4", "4n", 0.6],
|
||||
];
|
||||
new Tone.Part((t, n) => flute.triggerAttackRelease(n.note, n.dur, t + n.late, n.vel),
|
||||
TUNE.map(([time, note, dur, vel], i) => ({ time, note, dur, vel, late: ((i * 5) % 3 - 1) * 0.007 }))).start(0);
|
||||
|
||||
// B: the bass walks up under the climb (F G A, then E to come home), root on one and fifth on three
|
||||
new Tone.Part((t, n) => bass.triggerAttackRelease(n.note, "4n.", t, n.vel), [["F1", "C2"], ["G1", "D2"], ["A1", "E2"], ["E1", "B1"]].flatMap(([root, fifth], i) => [
|
||||
{ time: `${4 + i}:0`, note: root, vel: 0.85 },
|
||||
{ time: `${4 + i}:2`, note: fifth, vel: 0.6 },
|
||||
])).start(0);
|
||||
|
||||
// B: the kit, four bars of sixteenth-note lanes (null rests)
|
||||
const _ = null;
|
||||
for (const steps of [
|
||||
["kick", _, _, _, _, _, "kick", _, "kick", _, _, _, _, _, _, _],
|
||||
[_, _, _, _, "snare", _, _, _, _, _, _, _, "snare", _, _, _],
|
||||
["hat", _, "ghost", _, "hat", _, "ghost", "ghost", "hat", _, "ghost", _, "hat", _, "ghost", _],
|
||||
]) {
|
||||
const lane = new Tone.Sequence((t, hit) => kit.player(hit).start(t), steps, "16n");
|
||||
lane.loop = 4; // set before start: four bars, then it stops
|
||||
lane.start("4m");
|
||||
}
|
||||
|
||||
// the button: everything on the end card's downbeat, then nothing
|
||||
Tone.getTransport().schedule((t) => {
|
||||
piano.triggerAttackRelease(["A2", "A3", "C4", "E4"], "2n", t, 0.85);
|
||||
bass.triggerAttackRelease("A1", "2n", t, 0.9);
|
||||
flute.triggerAttackRelease("A5", "4n", t, 0.8);
|
||||
kit.player("kick").start(t);
|
||||
}, "8m");
|
||||
Tone.getTransport().start();
|
||||
|
||||
// each card is one bar, so every cut lands on a downbeat; the ninth is the end card
|
||||
const Edit = () => (
|
||||
<AbsoluteFill>
|
||||
<Mix lufs={-14} ceiling={-1.5} />
|
||||
<Series>{Array.from({ length: 9 }, (_, i) => <Series.Sequence key={i} durationInFrames={BAR}>{/* card i */}</Series.Sequence>)}</Series>
|
||||
</AbsoluteFill>
|
||||
);
|
||||
|
||||
registerRoot(() => <Composition id="cue" component={Edit} width={1080} height={1920} fps={30} durationInFrames={BAR * 9} />);
|
||||
```
|
||||
|
||||
FluidR3, Salamander and tonejs-instruments (the flute) are CC-BY 3.0, so the piece credits all three (the line is in
|
||||
each `LICENCE.txt`); VCSL is CC0.
|
||||
- A score written in Tone.js, TokenSynth or `raea/music` for a piece. Its music is a `raea gen music` bed.
|
||||
|
||||
## Example: a game's sound
|
||||
|
||||
@@ -327,26 +100,9 @@ type State = { hits: number; coinTaken: boolean };
|
||||
const INITIAL: State = { hits: 0, coinTaken: false };
|
||||
const fold = (s: State): State => s;
|
||||
|
||||
Tone.getTransport().bpm.value = 112;
|
||||
Tone.buses.music.duck(Tone.buses.voice, { amount: -12 });
|
||||
const thump = Tone.vary(new Tone.MembraneSynth({ octaves: 4, maxPolyphony: 4, poly: true }), { pitch: 0.5, volume: 2 }).connect(Tone.buses.sfx);
|
||||
const coin = new Tone.Sampler({ urls: { C5: Tone.sao("a bright arcade coin chime, short", { seconds: 1 }) } }).connect(Tone.buses.sfx);
|
||||
// a recorded marimba (`raea make sounds get vcsl/marimba`: CC0, every note VCSL sampled, four to seven semitones apart)
|
||||
const marimba = new Tone.Sampler({
|
||||
urls: Object.fromEntries(["F3", "C4", "G4", "B4", "F5"].map((n) => [n, staticFile(`sounds/vcsl-marimba/${n}.wav`)])),
|
||||
release: 0.4,
|
||||
volume: -10,
|
||||
}).connect(new Tone.Reverb({ decay: 1.2, wet: 0.15 }).connect(Tone.buses.music));
|
||||
// a loop that wants to come round: a question (bars 1-2) and its answer (bars 3-4), rhythm before pitch
|
||||
const tune = new Tone.Part((t, n) => marimba.triggerAttackRelease(n.note, "8n", t, n.vel), [
|
||||
{ time: "0:0", note: "C4", vel: 0.8 }, { time: "0:0:2", note: "E4", vel: 0.5 }, { time: "0:1:2", note: "G4", vel: 0.6 }, { time: "0:3", note: "A4", vel: 0.7 },
|
||||
{ time: "1:0", note: "G4", vel: 0.8 }, { time: "1:1:2", note: "E4", vel: 0.5 }, { time: "1:2", note: "D4", vel: 0.6 },
|
||||
{ time: "2:0", note: "C4", vel: 0.8 }, { time: "2:0:2", note: "E4", vel: 0.5 }, { time: "2:1:2", note: "G4", vel: 0.6 }, { time: "2:3", note: "C5", vel: 0.75 },
|
||||
{ time: "3:0", note: "B4", vel: 0.7 }, { time: "3:1", note: "G4", vel: 0.55 }, { time: "3:2", note: "C4", vel: 0.85 },
|
||||
]);
|
||||
tune.loop = true;
|
||||
tune.loopEnd = "4m";
|
||||
tune.start(0);
|
||||
Tone.getTransport().start();
|
||||
|
||||
function Game() {
|
||||
@@ -359,6 +115,8 @@ function Game() {
|
||||
{/* ...the game's picture... */}
|
||||
<Tone.Sfx when={hits.includes(frame)} play={(t) => thump.triggerAttackRelease("C2", "8n", t)} />
|
||||
<Tone.Sfx when={coins.includes(frame)} play={(t) => coin.triggerAttackRelease("C5", "8n", t)} />
|
||||
{/* the game's music: a bed from `raea gen music "a playful marimba loop, 112 bpm, no voice" --seconds 30 -o public/music` */}
|
||||
<Audio src={staticFile("music/bed.mp3")} bus="music" gainDb={-10} fadeIn={0.3} />
|
||||
<Sequence from={90} durationInFrames={150} layout="none">
|
||||
<Audio src={staticFile("voice.wav")} bus="voice" />
|
||||
</Sequence>
|
||||
@@ -369,7 +127,5 @@ function Game() {
|
||||
registerRoot(() => <Composition id="game" component={Game} width={1920} height={1080} fps={60} durationInFrames={600} />);
|
||||
```
|
||||
|
||||
`raea/music` is the shorthand for notes on named instruments (`new Part("bass", [...])`, `<Music>`). It plays
|
||||
through the same Tone layer, so the two mix. Its named instruments are Tone synth presets (`pad` is a PolySynth of
|
||||
fat saws, `kick` a MembraneSynth), good for a sketch or a test, not a score: write the score on sampled instruments,
|
||||
as above. It also reads and writes MIDI files (`parseMidi`, `toMidi`; `motion/sources`).
|
||||
`raea/music` (notes on named Tone presets, and MIDI files read and written: `parseMidi`, `toMidi`) is for tests of
|
||||
the sound layer, never a piece's music.
|
||||
@@ -3,9 +3,9 @@
|
||||
## What to do
|
||||
|
||||
- Decide what each scene is heard as before placing anything: silence, the scene's own sound (footsteps, a room, a
|
||||
machine: what the people on screen would hear), source music, score, effects, a voice. Music is a decision per
|
||||
scene, never a bed by default (`motion/music` has the spotting and the writing; `motion/sources` where each sound
|
||||
can come from).
|
||||
machine: what the people on screen would hear), source music, effects, a voice, the music bed. Whether the piece
|
||||
has music is its brief's or method's call; when it has, it's one bed from `raea gen music` (`motion/music`;
|
||||
`motion/sources` says where each other sound can come from).
|
||||
- Put each sound in its own `<Sequence from={frame} layout="none" name>` with an `<Audio>` inside. The Sequence's
|
||||
`from` is when the sound starts, and its `durationInFrames` (optional) cuts it off. `layout="none"` because a sound
|
||||
draws nothing.
|
||||
@@ -28,11 +28,10 @@
|
||||
- Place what's in the scene where it is: pan it to its side of the frame (`Tone.Panner`, a Channel's `pan`), give
|
||||
it the room's reverb, and narrow a device (a phone, a radio) with a high-pass and a low-pass. In 3D, `<Sound3D
|
||||
src at>` places it and the camera hears it move.
|
||||
- When the piece has music, write it in Tone.js on `Tone.buses.music` (`motion/music`): instruments in a `Sampler`
|
||||
(a sample library's notes, or TokenSynth's), parts in a `Part` or `Sequence`, composed for the cut. Duck it under
|
||||
the voice with `Tone.buses.music.duck(Tone.buses.voice, { amount: -12 })`, give the voice `<Audio bus="voice">`,
|
||||
and set the music's level on the bus: `Tone.buses.music.volume.value = -21`, then
|
||||
`Tone.buses.music.volume.rampTo(-12, 0.3, t)` to lift it at `t` seconds for the end card.
|
||||
- When the piece has music, it's one instrumental bed from `raea gen music` (`motion/music`), laid under the whole
|
||||
piece on `bus="music"` with the voice on `<Audio bus="voice">`. Duck it under the voice with
|
||||
`Tone.buses.music.duck(Tone.buses.voice, { amount: -12 })`; `raea check` says when it's lost or fights the voice,
|
||||
with the gainDb that fixes it.
|
||||
- Narration over the picture, when the footage has no voice for it, is
|
||||
`<Speech text="the words" start={frame} />` from `raea/speech` (Pocket TTS, on this computer; `voice` picks a
|
||||
Pocket voice or a WAV of one).
|
||||
@@ -84,10 +83,10 @@ says what that fetches). It does better on effects and field recordings than on
|
||||
the same sound, and changing one word of the prompt makes a new one. So settle the prompt before you iterate on
|
||||
gains.
|
||||
|
||||
Policy: music is notes on Tone.js instruments (sample libraries first, TokenSynth, synths), SAO and recorded packs
|
||||
make effects and foley, and Pocket TTS (`<Speech>`) says narration over the picture, all on this computer. Any other
|
||||
generation is a `raea gen` step (`motion/gen`). (`lyria()`, a remote music model, is retired: a new take is refused,
|
||||
and music written as notes can be cut on the bar and edited note by note anyway.)
|
||||
Policy, the same everywhere raea runs: a piece's music is one instrumental bed from `raea gen music` (raea cloud's
|
||||
`generate` tool is the same model; `motion/music`), SAO and recorded packs make effects and foley, and Pocket TTS
|
||||
(`<Speech>`) says narration over the picture. Any other generation is a `raea gen` step (`motion/gen`). (`lyria()` is
|
||||
retired: a new take is refused.)
|
||||
|
||||
Sound sells the cut, but one move everywhere is a lint: a whoosh on every entrance flattens all of them. Give
|
||||
foley to the moments that are physical (a slam, a strike-through, a card landing on the beat) and let others be
|
||||
@@ -130,8 +129,8 @@ ends up shouting over the narrator while another is inaudible.
|
||||
- Rewording a `sao()` prompt on every pass. Each new prompt makes a new sound.
|
||||
- `style` on an `<Audio>`: Audio has no picture and takes no style.
|
||||
- Hand-placing dozens of game sounds from a log. Cue them from `useGameEvents` (`motion/games`).
|
||||
- Writing music note by note in `<Audio>` files, or a game's sounds by hand. Write them in Tone.js (`motion/music`):
|
||||
instruments, the Transport, buses with ducking, and `<Tone.Sfx>` for one-shots.
|
||||
- Music written note by note, in `<Audio>` files or in Tone.js: a piece's music is a `raea gen music` bed
|
||||
(`motion/music`). A game's sounds placed by hand: fire each one-shot with `<Tone.Sfx>` on its event's frame.
|
||||
|
||||
## Example: a cue that lands on the end card, a voice, a layered hit
|
||||
|
||||
@@ -143,31 +142,10 @@ import { css } from "./styles.gen";
|
||||
const FRAMES = 300;
|
||||
const END_CARD = 252; // the voice stops here
|
||||
|
||||
// the music (motion/music): a sampled piano, chords that change every bar under a motif that answers the voice,
|
||||
// ducked under it, lifted for the end card, and ending on a chord on that cut. The tempo is set from the cut:
|
||||
// four bars to the end card, so its cut is a downbeat.
|
||||
Tone.getTransport().bpm.value = (4 * 4 * 60 * 30) / END_CARD; // about 114 bpm
|
||||
// the music (motion/music): one bed from `raea gen music "warm acoustic, light, instrumental, no vocals" --seconds 12
|
||||
// -o public/music`, ducked under the voice
|
||||
Tone.buses.music.duck(Tone.buses.voice, { amount: -12 });
|
||||
Tone.buses.music.volume.value = -21;
|
||||
Tone.buses.music.volume.rampTo(-12, 0.33, END_CARD / 30);
|
||||
// `raea make sounds get salamander/piano` printed its roots a minor third apart (D#2 is the file Ds2.mp3); these cover
|
||||
// F2 to G5, what the cue plays
|
||||
const ROOTS = ["D#2", "F#2", "A2", "C3", "D#3", "F#3", "A3", "C4", "D#4", "F#4", "A4", "C5", "D#5", "F#5"];
|
||||
const piano = new Tone.Sampler({
|
||||
urls: Object.fromEntries(ROOTS.map((n) => [n, staticFile(`sounds/salamander-piano/${n.replace("#", "s")}.mp3`)])),
|
||||
release: 1,
|
||||
}).connect(new Tone.Reverb({ decay: 1.4, wet: 0.2 }).connect(Tone.buses.music));
|
||||
const CHORDS = [["A2", "E3", "C4"], ["F2", "C3", "A3"], ["C3", "G3", "E4"], ["G2", "D3", "B3"]];
|
||||
new Tone.Part((t, c) => piano.triggerAttackRelease(c.notes, "4n", t, c.vel), CHORDS.flatMap((chord, bar) => [
|
||||
{ time: `${bar}:0`, notes: chord, vel: 0.55 },
|
||||
{ time: `${bar}:2:2`, notes: chord, vel: 0.4 },
|
||||
])).start(0);
|
||||
new Tone.Part((t, n) => piano.triggerAttackRelease(n.note, "8n", t, n.vel), [
|
||||
{ time: "1:1", note: "E5", vel: 0.7 }, { time: "1:1:2", note: "D5", vel: 0.5 }, { time: "1:2", note: "C5", vel: 0.6 }, { time: "1:3", note: "A4", vel: 0.65 },
|
||||
{ time: "3:1", note: "G5", vel: 0.75 }, { time: "3:1:2", note: "F5", vel: 0.5 }, { time: "3:2", note: "E5", vel: 0.6 }, { time: "3:3", note: "D5", vel: 0.7 },
|
||||
]).start(0);
|
||||
Tone.getTransport().schedule((t) => piano.triggerAttackRelease(["A2", "E3", "A3", "C4", "E4"], "1m", t, 0.8), "4m");
|
||||
Tone.getTransport().start();
|
||||
const BED = staticFile("music/bed.mp3");
|
||||
|
||||
// one hit in three layers, on the same frame: the snap that starts it, the body that says what it is, the room's tail
|
||||
const SNAP = sao("sharp wooden snap, close, very short, dry", { seconds: 0.3 });
|
||||
@@ -183,6 +161,7 @@ const SOUNDS = [
|
||||
{ id: "hit-tail", from: 0, gainDb: -24, src: TAIL, fade: 0, bus: "sfx" },
|
||||
{ id: "voice", from: 15, to: END_CARD, gainDb: 0, src: VOICE, fade: 0.012, bus: "voice" },
|
||||
{ id: "pop", from: END_CARD + 2, gainDb: -17, src: POP, fade: 0, bus: "sfx" },
|
||||
{ id: "bed", from: 0, gainDb: -10, src: BED, fade: 0.3, bus: "music" },
|
||||
] as const;
|
||||
|
||||
export default function SoundBed() {
|
||||
|
||||
@@ -33,23 +33,15 @@ piece's modes isn't asked.
|
||||
- again (play): After a failure, is it clear what went wrong and is the next attempt one press away?
|
||||
- task (tool): Can the task the screen exists for be done without stopping to work out where to look?
|
||||
|
||||
## Music that sounds generated
|
||||
## Music
|
||||
|
||||
Listen for these before the decision model does; each is how a made score gives itself away, and the fix
|
||||
(`motion/music`):
|
||||
A piece's music is one instrumental bed from `raea gen music` (`motion/music`). Listen for:
|
||||
|
||||
- **One held texture.** A pad, a sine sub and a long reverb under everything, no attack anywhere. Write a motif, chords
|
||||
that move and a part with rhythm; reverb per instrument, nothing on the bus.
|
||||
- **Harmony that stands still.** One chord for four bars or more in a cue that's meant to move. Change it every bar or two.
|
||||
- **A loop, not a cue.** The same two bars for thirty seconds. Vary the motif, change the arrangement every four to
|
||||
eight bars, and turn where the edit turns.
|
||||
- **Played by a machine.** Every note at one velocity, exactly on the grid. Spread the dynamics; move played parts a
|
||||
few milliseconds; use a recorded groove.
|
||||
- **No ending.** A fade-out. End on a chord or a hit on the last cut.
|
||||
- **Everywhere.** Music under every scene because the piece "needs music". Some scenes belong to silence or to their
|
||||
own sound.
|
||||
- **The wrong source.** A whole score from TokenSynth takes (organ-like sustains, buzz) or from an SAO "ambient
|
||||
music" prompt. Recorded instruments play the parts; TokenSynth fills a timbre no library has; SAO makes effects.
|
||||
- **A voice in the bed.** Lyrics or a sung line under someone talking. Make it again, "instrumental, no vocals".
|
||||
- **A bed that fights the voice, or is lost under it.** `raea check` measures both and gives the gainDb.
|
||||
- **The wrong feel.** A bed that isn't what the brief or the brand asks for (upbeat where it says warm, a club beat
|
||||
under a quiet interview). Make it again with the brief's words.
|
||||
- **More than one.** A second track, a sting or a riser added to fix the first. Make the one bed better instead.
|
||||
|
||||
## Ranking
|
||||
|
||||
|
||||
@@ -19,8 +19,7 @@ sound: voice, music, foley and the master.
|
||||
## Change
|
||||
- The voice first; duck music and foley under it.
|
||||
- Sound marks moments: a hit on the cut that matters, silence before the drop. Remove what only fills.
|
||||
- Music: composed for the cut (`motion/music`) on recorded instruments first; TokenSynth takes are curated, not
|
||||
trusted. Under a voice, thin the arrangement and let the tune answer between lines.
|
||||
- Music: one instrumental bed from `raea gen music` (`motion/music`), ducked under the voice.
|
||||
- Effects: layered (a transient, a body, a tail), with repeats varied (`motion/sound`).
|
||||
- Master at -14 LUFS integrated, true peak at or below -1 dBTP.
|
||||
|
||||
|
||||
@@ -68,8 +68,40 @@ export function Captions({ region = "bottom", said, words: max = 3, pause = 8, f
|
||||
const g = i < 0 ? null : groups[i].map((w) => ({ ...w, text: spell(fix, w.text) }));
|
||||
const saying = g ? g.findIndex((w) => f >= w.from && f < Math.max(w.to, w.from + 4)) : -1;
|
||||
const px = Math.max(60, size) * (width / 1080);
|
||||
// a band too small for a line (the face fills it) is refused and draws nothing; the captions then go at the bottom of
|
||||
// the whole safe area instead, so no word goes uncaptioned (12-05: a close shot's bottom band was refused, and a
|
||||
// clip played with no captions while the ones round it ran)
|
||||
const held: { band?: boolean } = {};
|
||||
const line = (
|
||||
<CaptionLine g={g} saying={saying} px={px} accent={accent} style={style} className={className}>
|
||||
{children}
|
||||
</CaptionLine>
|
||||
);
|
||||
return (
|
||||
<Region name={region} style={{ display: "flex", flexDirection: "column", justifyContent: region === "top" ? "flex-start" : "flex-end", alignItems: "center" }}>
|
||||
<>
|
||||
<Region name={region} style={{ display: "flex", flexDirection: "column", justifyContent: region === "top" ? "flex-start" : "flex-end", alignItems: "center" }}>
|
||||
<Held held={held}>{line}</Held>
|
||||
</Region>
|
||||
<Region name="full" style={{ display: "flex", flexDirection: "column", justifyContent: "flex-end", alignItems: "center" }}>
|
||||
<Unheld held={held}>{line}</Unheld>
|
||||
</Region>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** marks that its band drew (a refused Region draws no children) */
|
||||
function Held({ held, children }: { held: { band?: boolean }; children: ReactNode }) {
|
||||
held.band = true;
|
||||
return <>{children}</>;
|
||||
}
|
||||
/** draws only when the band before it was refused */
|
||||
function Unheld({ held, children }: { held: { band?: boolean }; children: ReactNode }) {
|
||||
return held.band ? null : <>{children}</>;
|
||||
}
|
||||
|
||||
function CaptionLine({ g, saying, px, accent, style, className, children }: { g: TimelineWord[] | null; saying: number; px: number; accent: boolean; style?: CSSProperties; className?: string; children?: CaptionsProps["children"] }) {
|
||||
return (
|
||||
<>
|
||||
{g ? (
|
||||
<div
|
||||
data-raea-role="caption"
|
||||
@@ -82,7 +114,8 @@ export function Captions({ region = "bottom", said, words: max = 3, pause = 8, f
|
||||
fontSize: px,
|
||||
lineHeight: 1.05,
|
||||
color: "var(--brand-text, #fff)",
|
||||
textShadow: "0 4px 24px rgba(0,0,0,0.55)",
|
||||
// a crisp dark edge under the soft shadow: the words hold 3:1 over a white product shot or sky, not only over faces
|
||||
textShadow: "0 0 2px rgba(0,0,0,0.95), 0 0 6px rgba(0,0,0,0.8), 0 4px 24px rgba(0,0,0,0.55)",
|
||||
overflowWrap: "break-word",
|
||||
...style,
|
||||
}}
|
||||
@@ -96,6 +129,6 @@ export function Captions({ region = "bottom", said, words: max = 3, pause = 8, f
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</Region>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -29,13 +29,19 @@ interface Band {
|
||||
bottom: number;
|
||||
}
|
||||
|
||||
/** How far in from the app's top and bottom zones a band stops, as a share of the composition's height. */
|
||||
export const ZONE_INSET = 0.012;
|
||||
|
||||
/** Works out the vertical band each name stands for, given perception and the composition size. */
|
||||
export function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin = 0.06): Band {
|
||||
const m = Math.round(margin * width);
|
||||
// the app's UI zones, the same the check holds text to (./zones): a part placed here is never in them
|
||||
const z = uiZones(width, height);
|
||||
const edgeTop = Math.max(perception.safe?.top ?? 0, z.top, MIN_BAND * height);
|
||||
const edgeBottom = Math.min(perception.safe?.bottom ?? height, height - z.bottom);
|
||||
// a little in from the zones, so a line's descenders and shadow stay out of them too (12-05: captions flush on the
|
||||
// bottom zone's edge reached 1 px into it, and the check failed every caption)
|
||||
const inset = Math.round(ZONE_INSET * height);
|
||||
const edgeTop = Math.max(perception.safe?.top ?? 0, z.top + inset, MIN_BAND * height);
|
||||
const edgeBottom = Math.min(perception.safe?.bottom ?? height, height - z.bottom - inset);
|
||||
const face = perception.face;
|
||||
const top: Band = { name: "top", top: edgeTop, bottom: face ? face.y - m : 0.45 * height };
|
||||
const bottom: Band = { name: "bottom", top: face ? face.y + face.h + m : 0.55 * height, bottom: edgeBottom };
|
||||
|
||||
@@ -42,7 +42,9 @@ pub fn stats(rgba: &[u8]) -> Option<Exposure> {
|
||||
let enc = if y <= 0.0031308 { 12.92 * y } else { 1.055 * y.powf(1.0 / 2.4) - 0.055 };
|
||||
sum_luma += enc;
|
||||
hist[(enc * 255.0).round().clamp(0.0, 255.0) as usize] += 1;
|
||||
if p[0].max(p[1]).max(p[2]) >= 254 {
|
||||
// white is every channel at the top: a saturated colour (a flat yellow sun, pale sand) has one channel there and
|
||||
// isn't clipped
|
||||
if p[0].min(p[1]).min(p[2]) >= 254 {
|
||||
hi += 1;
|
||||
}
|
||||
if p[0].max(p[1]).max(p[2]) <= 1 {
|
||||
@@ -170,6 +172,15 @@ mod tests {
|
||||
assert!(b.found("f").iter().any(|(_, s)| s.contains("crush to black")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saturated_colour_is_not_clipped_white() {
|
||||
let sun: Vec<u8> = (0..100).flat_map(|_| [255, 184, 0, 255]).collect();
|
||||
let sand: Vec<u8> = (0..100).flat_map(|_| [255, 229, 165, 255]).collect();
|
||||
assert_eq!(stats(&sun).unwrap().clipped_high, 0.0);
|
||||
assert_eq!(stats(&sand).unwrap().clipped_high, 0.0);
|
||||
assert!(stats(&sun).unwrap().found("f").iter().all(|(_, s)| !s.contains("clip to white")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentiles_and_transparency() {
|
||||
// half black, half white: p01 black, p99 white; transparent pixels ignored
|
||||
|
||||
@@ -25,6 +25,7 @@ NAMES=(
|
||||
'raea-runtime-(cut|goal)-plan => sdk/goal (raea/goal)'
|
||||
'naming-check\.ts => raea/goal'"'"'s naming pack'
|
||||
'raea make (check|seen|look|judge|gates)\b => raea goal check|seen|judge|gates (MK45: goal is the loop, make the asset tools)'
|
||||
'"make", *"(check|seen|look|judge|gates)" => ["goal", "check", ...]: a spawned raea make check is refused with exit 2'
|
||||
'raea make plan\b => raea make blockout (a project'"'"'s tasks: raea goal tasks)'
|
||||
'raea next\b => raea goal next'
|
||||
'raea (clothes|motion|solid|wear|splat|physics|bake|sao|tokensynth|sounds|component)( |`|$) => raea make clothes, motion, solid... (MK45: the asset tools are under make)'
|
||||
|
||||
Reference in new issue
Block a user