mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 05:33:38 -10:00
Jump cuts read through the ffmpeg CLI (6-8 s per take on a box against 38-66 s); each clip's face for perception.json read from footage/faces.json, which prep makes; and a phrase the transcriber squeezed into one instant dropped from a take's words, so a line is found where it was said (Body Shop's CTA started inside "up").
125 lines
6.8 KiB
TypeScript
125 lines
6.8 KiB
TypeScript
// 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 { spawnSync } from "node:child_process";
|
|
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;
|
|
|
|
/** A take's jump cuts read through the ffmpeg CLI where there is one: its luma at 160x90, every frame, scored as raea
|
|
* media cuts scores them (ffmpeg's select scene: each frame's mean absolute difference from the last, less the
|
|
* difference before it, over 100). ffmpeg decodes on every core; the engine's own decoder on a Linux box is openh264 on
|
|
* one (12-05: 38 s for a 3.5-minute light copy, 66 s for a 6-minute one, against 4 s for ffmpeg), and a box step has
|
|
* 3 minutes. The small picture leaves a hard cut's score where it was and a frame's grain out. null where ffmpeg
|
|
* can't read it: the engine reads it then. */
|
|
export function ffmpegCuts(file: string, threshold: number): number[] | null {
|
|
const [w, h] = [160, 90];
|
|
const r = spawnSync("ffmpeg", ["-v", "info", "-nostats", "-i", file, "-an", "-vf", `scale=${w}:${h}:flags=area,format=gray,showinfo`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 });
|
|
if (r.error || r.status !== 0 || !r.stdout?.length) return null;
|
|
// each frame's time, from showinfo's lines in order
|
|
const times = [...String(r.stderr).matchAll(/\bn:\s*\d+\s+pts:\s*-?\d+\s+pts_time:(-?[\d.]+)/g)].map((m) => Number(m[1]));
|
|
const n = w * h;
|
|
const frames = Math.floor(r.stdout.length / n);
|
|
if (!frames || times.length !== frames) return null;
|
|
const y = r.stdout as Buffer;
|
|
const out: number[] = [];
|
|
let prev = 0;
|
|
for (let f = 1; f < frames; f++) {
|
|
let sad = 0;
|
|
for (let i = f * n, j = (f - 1) * n, e = i + n; i < e; i++, j++) sad += Math.abs(y[i] - y[j]);
|
|
const mafd = sad / n;
|
|
const score = Math.min(Math.max(Math.min(mafd, Math.abs(mafd - prev)) / 100, 0), 1);
|
|
prev = mafd;
|
|
if (score > threshold) out.push(ms(times[f]));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** 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 = ffmpegCuts(file, 0.08) ?? (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 };
|
|
}
|