Compare commits

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

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

No files matched your search

Generated
+4 -24
View File
@@ -15509,7 +15509,6 @@ dependencies = [
"raea-runtime-page", "raea-runtime-page",
"raea-runtime-pagestore", "raea-runtime-pagestore",
"raea-runtime-react", "raea-runtime-react",
"raea-runtime-review",
"raea-runtime-scene", "raea-runtime-scene",
"raea-runtime-scene3d", "raea-runtime-scene3d",
"raea-runtime-sound", "raea-runtime-sound",
@@ -15659,9 +15658,12 @@ version = "0.1.0"
dependencies = [ dependencies = [
"base64 0.22.1", "base64 0.22.1",
"bevy", "bevy",
"image",
"raea-core-scene", "raea-core-scene",
"raea-core-wire", "raea-core-wire",
"raea-io-assets",
"raea-io-home", "raea-io-home",
"raea-io-media",
"raea-io-net", "raea-io-net",
"raea-page", "raea-page",
"raea-render", "raea-render",
@@ -15670,8 +15672,8 @@ dependencies = [
"raea-runtime-react", "raea-runtime-react",
"raea-runtime-twins", "raea-runtime-twins",
"raea-runtime-view", "raea-runtime-view",
"raea-sys-facetrack",
"raea-sys-fonts", "raea-sys-fonts",
"raea-sys-frame",
"raea-sys-image", "raea-sys-image",
"raea-sys-page", "raea-sys-page",
"raea-sys-screen", "raea-sys-screen",
@@ -15751,17 +15753,6 @@ dependencies = [
"xxhash-rust", "xxhash-rust",
] ]
[[package]]
name = "raea-runtime-review"
version = "0.1.0"
dependencies = [
"image",
"raea-core-facts",
"raea-core-review",
"raea-sys-light-meter",
"serde_json",
]
[[package]] [[package]]
name = "raea-runtime-scene" name = "raea-runtime-scene"
version = "0.1.0" version = "0.1.0"
@@ -16148,17 +16139,6 @@ dependencies = [
"parry3d", "parry3d",
] ]
[[package]]
name = "raea-sys-facetrack"
version = "0.1.0"
dependencies = [
"image",
"raea-io-assets",
"raea-io-media",
"raea-sys-frame",
"serde_json",
]
[[package]] [[package]]
name = "raea-sys-filters" name = "raea-sys-filters"
version = "0.1.0" version = "0.1.0"
-2
View File
@@ -127,7 +127,6 @@ members = [
"systems/page-net", "systems/page-net",
"systems/page-ops", "systems/page-ops",
"systems/frame", "systems/frame",
"systems/facetrack",
"systems/engine-shaders", "systems/engine-shaders",
"systems/shots", "systems/shots",
"systems/hold", "systems/hold",
@@ -185,7 +184,6 @@ members = [
"runtime/react", "runtime/react",
"runtime/track", "runtime/track",
"runtime/pagestore", "runtime/pagestore",
"runtime/review",
"runtime/cssurls", "runtime/cssurls",
"runtime/pid", "runtime/pid",
"bench/bridge", "bench/bridge",
+4 -26
View File
@@ -40,29 +40,6 @@ pub fn still(path: &Path, at: f64, out: &Path, width: Option<u32>) -> R<Value> {
Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()})) Ok(json!({"wrote": out, "at": at, "width": img.width(), "height": img.height()}))
} }
/// `f(0..n)`, up to four at a time, in order: a sheet's frames are each a seek and a decode of their own (16 of a 4K
/// interview: 7 s one after another, 4 s so).
fn at_once<T: Send>(n: usize, f: impl Fn(usize) -> R<T> + Sync) -> R<Vec<T>> {
use std::sync::{Mutex, atomic::{AtomicUsize, Ordering}};
let workers = std::thread::available_parallelism().map_or(2, |c| c.get()).clamp(1, 4).min(n.max(1));
let next = AtomicUsize::new(0);
let out: Vec<Mutex<Option<R<T>>>> = (0..n).map(|_| Mutex::new(None)).collect();
std::thread::scope(|s| {
for _ in 0..workers {
s.spawn(|| {
loop {
let i = next.fetch_add(1, Ordering::Relaxed);
if i >= n {
break;
}
*out[i].lock().unwrap() = Some(f(i));
}
});
}
});
out.into_iter().map(|m| m.into_inner().unwrap().unwrap_or_else(|| Err("a frame wasn't read".into()))).collect()
}
pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> { pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
if files.is_empty() { if files.is_empty() {
return Err("raea media sheet FILE... -o OUT: which files?".into()); return Err("raea media sheet FILE... -o OUT: which files?".into());
@@ -70,9 +47,10 @@ pub fn sheet(files: &[PathBuf], n: usize, w: u32, out: &Path) -> R<Value> {
let mut tiles = Vec::new(); let mut tiles = Vec::new();
if files.len() == 1 { if files.len() == 1 {
let p = probe_of(&files[0])?; let p = probe_of(&files[0])?;
let at: Vec<f64> = (0..n.max(1)).map(|i| (i as f64 + 0.5) / n.max(1) as f64 * p.duration).collect(); for i in 0..n.max(1) {
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?; let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
tiles.extend(at.into_iter().zip(read)); tiles.push((t, frame(&files[0], t)?));
}
} else { } else {
for f in files { for f in files {
let p = probe_of(f)?; let p = probe_of(f)?;
+63 -70
View File
@@ -1,7 +1,6 @@
//! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing. //! `media probe`: what a file is (duration, size, fps, codec, audio), with the MP4 boxes read directly for a track's own timing.
use super::*; use super::*;
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
pub(crate) fn round3(x: f64) -> f64 { pub(crate) fn round3(x: f64) -> f64 {
(x * 1000.0).round() / 1000.0 (x * 1000.0).round() / 1000.0
@@ -39,11 +38,7 @@ pub fn probe_of(path: &Path) -> R<Probe> {
} }
i i
}); });
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way) let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
let audio = match audio_track(path) {
Some(a) => Some(a),
None => soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration())),
};
if video.is_none() && audio.is_none() { if video.is_none() && audio.is_none() {
// what each backend said about the picture: a missing FFmpeg, a codec none of them reads // what each backend said about the picture: a missing FFmpeg, a codec none of them reads
let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default(); let why = why.map(|w| format!(" ({})", w.split_once(": no backend reads it (").map_or(w.as_str(), |(_, r)| r.trim_end_matches(')')).to_string())).unwrap_or_default();
@@ -129,37 +124,74 @@ impl Track {
} }
} }
/// The first sound track as the file states it (rate, channels, seconds), for MP4 and QuickTime files: `media probe` /// The boxes inside `b` (a box's payload): (type, payload).
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk). pub(crate) fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> { let mut out = Vec::new();
audio_in(&moov_of(path)?) let mut i = 0usize;
while i + 8 <= b.len() {
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
let mut hdr = 8;
if size == 1 && i + 16 <= b.len() {
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
hdr = 16;
} else if size == 0 {
size = b.len() - i;
}
if size < hdr || i + size > b.len() {
break;
}
out.push((kind, &b[i + hdr..i + size]));
i += size;
}
out
} }
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> { pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
for (k, trak) in boxes(moov) { boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
if &k != b"trak" { }
continue;
} pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
let Some(mdia) = child(trak, b"mdia") else { continue }; Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"soun"[..]) { }
continue;
} pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
let mdhd = child(mdia, b"mdhd")?; Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
let (scale, dur) = if mdhd.first() == Some(&1) { (be32(mdhd, 20)? as f64, be64(mdhd, 24)? as f64) } else { (be32(mdhd, 12)? as f64, be32(mdhd, 16)? as f64) };
// the first sample description: version at 24, channels at 32, rate (16.16) at 40; QuickTime's version 2 states
// them again as a double at 48 and a count at 56
let stsd = child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?;
let v2 = stsd.get(24..26) == Some(&[0u8, 2][..]);
let rate = if v2 { f64::from_bits(be64(stsd, 48)?) } else { be32(stsd, 40)? as f64 / 65536.0 };
let channels = if v2 { be32(stsd, 56)? as usize } else { u16::from_be_bytes(stsd.get(32..34)?.try_into().ok()?) as usize };
return (scale > 0.0 && dur > 0.0 && rate >= 1.0 && (1..=64).contains(&channels)).then_some((rate.round() as u32, channels, dur / scale));
}
None
} }
/// The first video track's timing, for MP4 and QuickTime files. /// The first video track's timing, for MP4 and QuickTime files.
pub fn video_track(path: &Path) -> Option<Track> { pub fn video_track(path: &Path) -> Option<Track> {
let moov = moov_of(path)?; use std::io::{Read, Seek, SeekFrom};
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
// the top-level boxes, to moov (read alone: mdat can be gigabytes)
let mut at = 0u64;
let moov = loop {
if at + 8 > len {
return None;
}
let mut h = [0u8; 16];
f.seek(SeekFrom::Start(at)).ok()?;
f.read_exact(&mut h[..8]).ok()?;
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
let mut hdr = 8u64;
if size == 1 {
f.read_exact(&mut h[8..]).ok()?;
size = u64::from_be_bytes(h[8..].try_into().ok()?);
hdr = 16;
} else if size == 0 {
size = len - at;
}
if size < hdr {
return None;
}
if &h[4..8] == b"moov" {
let mut m = vec![0u8; (size - hdr).min(256 << 20) as usize];
f.read_exact(&mut m).ok()?;
break m;
}
at += size;
};
for (k, trak) in boxes(&moov) { for (k, trak) in boxes(&moov) {
if &k != b"trak" { if &k != b"trak" {
continue; continue;
@@ -263,42 +295,3 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
} }
// ---- pictures // ---- pictures
#[cfg(test)]
mod tests {
use super::*;
fn bx(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
let mut v = ((body.len() + 8) as u32).to_be_bytes().to_vec();
v.extend_from_slice(kind);
v.extend_from_slice(body);
v
}
#[test]
fn a_sound_track_is_read_from_the_file_s_own_tables() {
// mdhd v0: 48 kHz timescale, 10 s; stsd: one mp4a entry, 2 channels, 48000 Hz
let mut mdhd = vec![0u8; 24];
mdhd[12..16].copy_from_slice(&48000u32.to_be_bytes());
mdhd[16..20].copy_from_slice(&480000u32.to_be_bytes());
let mut hdlr = vec![0u8; 24];
hdlr[8..12].copy_from_slice(b"soun");
let mut stsd = vec![0u8; 44];
stsd[7] = 1;
stsd[12..16].copy_from_slice(b"mp4a");
stsd[32..34].copy_from_slice(&2u16.to_be_bytes());
stsd[40..44].copy_from_slice(&(48000u32 << 16).to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &stsd)))].concat();
// a picture track ahead of it is passed over
let mut vh = vec![0u8; 24];
vh[8..12].copy_from_slice(b"vide");
let moov = [bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh))), bx(b"trak", &bx(b"mdia", &mdia))].concat();
assert_eq!(audio_in(&moov), Some((48000, 2, 10.0)));
// no sound track, or one that states no rate: nothing (the track is decoded instead)
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &bx(b"hdlr", &vh)))), None);
let mut silent = stsd.clone();
silent[40..44].copy_from_slice(&0u32.to_be_bytes());
let mdia = [bx(b"mdhd", &mdhd), bx(b"hdlr", &hdlr), bx(b"minf", &bx(b"stbl", &bx(b"stsd", &silent)))].concat();
assert_eq!(audio_in(&bx(b"trak", &bx(b"mdia", &mdia))), None);
}
}
-26
View File
@@ -44,32 +44,6 @@ pub struct VideoFit {
pub scale: f32, pub scale: f32,
} }
/// What a page shows this frame as one number, folded into `seed`: each element's place, kind, props and text, and each
/// video's file and time in it. Not an element's id (React's count, which moves when an element is added before it),
/// not an <audio>, not a video's own sound (muted, volume): frames with one key draw one picture while the files they
/// name stay the same (files are named here, not read: whoever keeps pictures by this key holds the files to it).
/// A path under `dir` (the composition's folder) is named from there, so the same piece in another folder (a render
/// farm's job) has the same keys (11-30: the farm's first try had none in common, each clip named under its job).
pub fn key(seed: u64, want: &[Want], videos: &[VideoAt], dir: &std::path::Path) -> u64 {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
seed.hash(&mut h);
let root = dir.to_string_lossy();
let root = format!("{}/", root.trim_end_matches('/'));
let here = |s: String| if root.len() > 1 { s.replace(&root, "") } else { s };
for w in want.iter().filter(|w| w.kind != "audio") {
// (a <style>'s text names its fonts' files as its props name images)
(&w.path, &w.kind, w.text.clone().map(here)).hash(&mut h);
for (k, v) in w.props.iter().filter(|(k, _)| w.kind != "video" || (*k != "muted" && *k != "volume")) {
(k, here(v.to_string())).hash(&mut h);
}
}
for v in videos {
(v.file.strip_prefix(dir).unwrap_or(&v.file), v.at.to_bits(), v.fit.map(|f| [f.at.0, f.at.1, f.to.0, f.to.1, f.scale].map(f32::to_bits))).hash(&mut h);
}
h.finish()
}
/// What the page was last told about an element. /// What the page was last told about an element.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
struct Sent { struct Sent {
+1 -5
View File
@@ -318,7 +318,7 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
Given a goal job Given a goal job
Then `raea goal check` runs every `run` rule at every status, the Stop hook's included, and holds the job on one Then `raea goal check` runs every `run` rule at every status, the Stop hook's included, and holds the job on one
that fails or outlives its timeout, with its exit code and last line ("run") that fails or outlives its timeout, with its exit code and last line ("run")
And a `says` rule is clear only when review/judge/NAME.json, written by `raea goal judge [DIR] [--by claude|kimi|clef]` And a `says` rule is clear only when review/judge/NAME.json, written by `raea goal judge [DIR] [--by claude|kimi]`
(a fresh session that may only read: Read, Grep and Glob), found it true at a time no earlier than the work's (a fresh session that may only read: Read, Grep and Glob), found it true at a time no earlier than the work's
newest file, the job's own review/, .raea/, NOTES.md, .git and node_modules left out, compared at whole seconds newest file, the job's own review/, .raea/, NOTES.md, .git and node_modules left out, compared at whole seconds
("says") ("says")
@@ -456,10 +456,6 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
And the seen pack holds it until its contact sheet has been shown since its last render (FILE.seen.json: the And the seen pack holds it until its contact sheet has been shown since its last render (FILE.seen.json: the
render's time and size, what the agent said it sees and would change, at least 80 characters), and the render's time and size, what the agent said it sees and would change, at least 80 characters), and the
surprise pack, when on, until it names its moment in seconds and what it is surprise pack, when on, until it names its moment in seconds and what it is
And it holds a video until its design is judged too, on its frames at full size (FILE.looks/, six through the
cut, made by `raea goal seen FILE`): `--look "..."`, at least 80 characters on its type, captions, cards and
end beside a reference and what was changed, since a sheet's tiles show what happens and never how it looks
(12-01, Shane on Dutch: "why do components not look good. is it even proofing or reviewing the work?")
And on a Mac the same packs hold through `raea goal seen FILE` (the sheet, shown in the raea app with And on a Mac the same packs hold through `raea goal seen FILE` (the sheet, shown in the raea app with
`raea show`) and `raea goal seen FILE "WHAT I SEE AND WOULD CHANGE"`, which write FILE.seen.json; raea cloud's `raea show`) and `raea goal seen FILE "WHAT I SEE AND WOULD CHANGE"`, which write FILE.seen.json; raea cloud's
publish tool writes it through the same command publish tool writes it through the same command
+7 -11
View File
@@ -33,7 +33,7 @@ The packs, and what each holds:
| `place` | cut | no text over a face, a person or what the shot is about where a clear place of its size exists | | `place` | cut | no text over a face, a person or what the shot is about where a clear place of its size exists |
| `floor` | cut, floor | no clipped text, low contrast, freeze, flash or loudness out of range | | `floor` | cut, floor | no clipped text, low contrast, freeze, flash or loudness out of range |
| `stills` | every kind, floor | a composition's three stills as it's saved: no clipped or cramped text, nothing out of the safe areas | | `stills` | every kind, floor | a composition's three stills as it's saved: no clipped or cramped text, nothing out of the safe areas |
| `seen` | cut, floor | its contact sheet and its frames at full size looked at since its last render (`raea goal seen FILE`, then `raea goal seen FILE "..." --look "..."`) | | `seen` | cut, floor | its contact sheet looked at since its last render (`raea goal seen FILE`, then `raea goal seen FILE "..."`) |
| `surprise` | when a brief turns it on | one earned surprise named with its moment in seconds | | `surprise` | when a brief turns it on | one earned surprise named with its moment in seconds |
| `naming` | cut | every video and still named client_concept_variant_v#_size | | `naming` | cut | every video and still named client_concept_variant_v#_size |
| `sizes` | cut | one size first: no other size before a person approves the first | | `sizes` | cut | one size first: no other size before a person approves the first |
@@ -54,11 +54,8 @@ findings are then warnings.
A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules A rules goal (`rules({...})`, what raea.app's `/goal` writes) is any other work: the aim in your words and the rules
that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds that must hold before the agent stops. A `run` rule is a command that must exit 0 in the brief's folder (300 seconds
unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the unless its `timeout` says otherwise); a `file` rule is a deliverable; a `says` rule is words that must be true of the
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude`, `kimi` or `clef`) and work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude` or `kimi`) and keeps its
keeps its verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's newest file.
newest file. `clef` is clef-omni, as `raea ask` reaches it: it watches and hears the files a rule names (in the rule's
"from A s to B s" window if it has one), else every video under out/, and reads no folder, so a rule about text it
can't see stays open. It is the critic where `RAEA_AGENT_KEY` is set, as on raea cloud; elsewhere the critic is `claude`.
```ts ```ts
import { brief, rules } from "raea/brief" import { brief, rules } from "raea/brief"
@@ -80,7 +77,7 @@ export default brief({
```sh ```sh
raea goal check # done: everything, as the Stop hook runs it raea goal check # done: everything, as the Stop hook runs it
raea goal check out/cuts/acme_dog_hook1_v2_9x16.mp4 --at render raea goal check out/cuts/acme_dog_hook1_v2_9x16.mp4 --at render
raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 && raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 "..." --look "..." raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 && raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 "..."
raea goal tasks --json # the brief's plan, every task raea goal tasks --json # the brief's plan, every task
raea goal next raea goal next
``` ```
@@ -97,8 +94,8 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
```sh ```sh
raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish) raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base) raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE ["what you see and would change" --look "its design at full size, beside a reference"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size) raea goal seen FILE ["what you see and would change"] [--surprise "SECONDS s: what it is"] (FILE's contact sheet beside it, to look at every frame; with words, what was seen of FILE as it is now)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude) raea goal judge [--goal NAME] [--by claude|kimi] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks) raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)
raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them) raea goal gates [DIR] [--goal NAME] --json (a scene, kit or shot goal's record and critic gates, as raea/goal's packs read them)
``` ```
@@ -111,10 +108,9 @@ Headless: it needs nothing running and opens no window. Takes any number of argu
| --- | --- | --- | | --- | --- | --- |
| `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written | | `--apply` | `EDITS.json\|-` | plan edits (JSON, `-` for stdin), each written where its task is written |
| `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). | | `--at` | `edit\|render\|publish\|done` | The moment `check` runs the rules of (default `done`); for `place`, the seconds to read (`S[,S...]`). |
| `--by` | `claude\|kimi\|clef` | The critic `judge` asks, a fresh session that may only read (default `claude`). | | `--by` | `claude\|kimi` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
| `--goal` | `NAME` | only this goal of the brief's (by its name) | | `--goal` | `NAME` | only this goal of the brief's (by its name) |
| `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. | | `--json` | – | `check`: print the report (review/goal.json's shape). `gates`: the record and critic gates as JSON. |
| `--look` | `"its design` | `seen`: a video's design judged on its frames at full size (FILE.looks/): its type, captions, cards and end beside a reference, and what was changed. |
| `--manifest` | `render.json` | the render's manifest, for the sound pack's takes and effects | | `--manifest` | `render.json` | the render's manifest, for the sound pack's takes and effects |
| `--only` | `ID,...` | `check`: only these checks. Otherwise only these objects (refs, gen, pick-sheet, prep) or shots (framing), by id or name. | | `--only` | `ID,...` | `check`: only these checks. Otherwise only these objects (refs, gen, pick-sheet, prep) or shots (framing), by id or name. |
| `--put` | `PUT.json\|-` | `{plan, base}`: the whole plan written back only while the brief's is still `base` | | `--put` | `PUT.json\|-` | `{plan, base}`: the whole plan written back only while the brief's is still `base` |
+2 -2
View File
@@ -14,8 +14,8 @@ pub const GOAL_TS: &[&str] = &["check", "tasks", "seen", "judge"];
/// The goal verbs' usage, under the help's (usage.rs reads each verb's flags from it). /// The goal verbs' usage, under the help's (usage.rs reads each verb's flags from it).
pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish) pub const GOAL_USAGE: &str = "raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest render.json] [--json] (every rule each goal of brief.ts is held to at that moment: its kind's packs, its rules and its own checks; with no goal, the floor; every project is also held to `registered`, every raea file reached from brief.ts; review/goal.json; exit 1 on an error. The hook runs it at every save (edit) and stop (done), a render at its end, raea cloud at publish)
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base) raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- | raea goal tasks [DIR] --put PUT.json|- (the brief's plan as the brief's run gives it: open tasks by id, or all as JSON; --apply writes edits by task id back where each task is written, refusing one made by code; a project with no plan gets plan.ts, imported by brief.ts; --put {plan, base} writes the whole plan back only while the brief's is still base)
raea goal seen FILE [\"what you see and would change\" --look \"its design at full size, beside a reference\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, and its frames at full size in FILE.looks/, to look at; with words, what was seen of FILE as it is now, and --look how a video's type, captions and cards look at full size) raea goal seen FILE [\"what you see and would change\"] [--surprise \"SECONDS s: what it is\"] (FILE's contact sheet beside it, to look at every frame; with words, what was seen of FILE as it is now)
raea goal judge [--goal NAME] [--by claude|kimi|clef] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json. clef watches and hears the files a rule names, else the videos under out/, paid as `raea ask` is: the critic where RAEA_AGENT_KEY is set, as on raea cloud, else claude) raea goal judge [--goal NAME] [--by claude|kimi] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json)
raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)"; raea goal next [DIR] (the two or three useful next steps for the project, from its brief, its goals, compositions, renders and checks)";
/// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an /// One of GOAL_TS's verbs (or `make place`): printed as it says, and the process exits with its code (1 on an
+1 -1
View File
@@ -384,7 +384,7 @@ pub fn run(args: &[String]) -> R<String> {
} }
if args.first().map(String::as_str) != Some("render") || args.len() < 2 { if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
return Err(format!( return Err(format!(
"raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--keys keys.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it) "raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|share|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help) raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|share|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)
raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea make sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)", raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea make sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
+5 -8
View File
@@ -80,14 +80,11 @@ A video edit as a React + TypeScript project, rendered by raea.
- cuts.ts: the clips (\`raea cut\` writes it, with cuts.json and words.json beside it; re-run it rather than editing - 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). components/: components you added (\`raea make component add\`), yours to change.
- brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from the brand's site). edit.tsx loads them with the project's - brand/brand.css: the brand's tokens (\`raea brand DOMAIN\` reads them from the brand's site). edit.tsx loads them with the project's
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). The brand's colours and Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). Style only with the brand
faces are the palette, as classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg), classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg), text-brand-on-surface,
text-brand-on-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body (where text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body; size text-display,
the brand's face is missing, install a free face close to it, never a system fallback); the --brand-* variables text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame); corners rounded-brand. Where a
where a class can't reach. Never a colour from outside the brand. The design is yours: size, weight, shape, layout class can't reach, the --brand-* variables. Never a colour, font or size of your own.
and motion are chosen for this piece, against how the brand's own best work looks, not from a default. The sizes
text-display, text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame) and rounded-brand are
a start, not a limit.
- \`raea render edit.tsx -o final.mp4 --manifest render.json\`, then \`raea check final.mp4 --manifest render.json - \`raea render edit.tsx -o final.mp4 --manifest render.json\`, then \`raea check final.mp4 --manifest render.json
--words words.json --perception perception.json\` says what's wrong; \`raea render edit.tsx --at 105 -o stills/\` --words words.json --perception perception.json\` says what's wrong; \`raea render edit.tsx --at 105 -o stills/\`
gives frame 105 to look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX); gives frame 105 to look at. \`raea guide\` has the craft (\`raea guide motion\` for writing the TSX);
+1 -1
View File
@@ -221,7 +221,7 @@ function cut(a: { take: string; lines: string[]; spans: number[][]; keep: Clip[]
return { edit, cuts: clips, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...notes.map((n) => `note: ${n}`)].join("\n") }; return { edit, cuts: clips, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...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 */ /** raea-perceive, as `raea song` finds it (runtime/react/src/runtime/page/src/faces.rs perceive_bin): $RAEA_PERCEIVE, else beside raea, else on PATH */
function perceive(): string { function perceive(): string {
// raea's path (a bare name, as a test may pass, is found on PATH) // raea's path (a bare name, as a test may pass, is found on PATH)
const self = raea.includes("/") ? raea : (process.env.PATH ?? "").split(delimiter).map((d) => `${d}/${raea}`).find((p) => existsSync(p)) ?? raea; const self = raea.includes("/") ? raea : (process.env.PATH ?? "").split(delimiter).map((d) => `${d}/${raea}`).find((p) => existsSync(p)) ?? raea;
+3 -8
View File
@@ -30,11 +30,11 @@ const EXTS: &[&str] = &["", ".ts", ".tsx", ".mts", ".js", ".mjs", ".cjs", ".json
/// `spec` imported from a file in `dir` (`esm`: an import, else a require), to the file it names /// `spec` imported from a file in `dir` (`esm`: an import, else a require), to the file it names
pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String> { pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String> {
let raw = spec.strip_prefix("file://").unwrap_or(spec); let raw = spec.strip_prefix("file://").unwrap_or(spec);
// (a path whole on Windows too, `D:\..`: the React raea ships, found, was asked for again by its path and read as a package's name, #278) if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." {
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." || Path::new(raw).is_absolute() { let want = if raw.starts_with('/') { PathBuf::from(raw) } else { dir.join(raw) };
let want = if raw.starts_with('/') || Path::new(raw).is_absolute() { PathBuf::from(raw) } else { dir.join(raw) };
return as_file(&want).ok_or_else(|| format!("Cannot find module '{spec}' from {}", dir.display())); return as_file(&want).ok_or_else(|| format!("Cannot find module '{spec}' from {}", dir.display()));
} }
// a package: its name (a scope takes two parts) and the subpath after it
let mut parts = raw.splitn(if raw.starts_with('@') { 3 } else { 2 }, '/'); let mut parts = raw.splitn(if raw.starts_with('@') { 3 } else { 2 }, '/');
let name = if raw.starts_with('@') { format!("{}/{}", parts.next().unwrap_or(""), parts.next().unwrap_or("")) } else { parts.next().unwrap_or("").to_string() }; let name = if raw.starts_with('@') { format!("{}/{}", parts.next().unwrap_or(""), parts.next().unwrap_or("")) } else { parts.next().unwrap_or("").to_string() };
let sub = parts.next().map(|s| format!("./{s}")).unwrap_or_else(|| ".".into()); let sub = parts.next().map(|s| format!("./{s}")).unwrap_or_else(|| ".".into());
@@ -53,11 +53,6 @@ pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String
return Ok(f); return Ok(f);
} }
} }
// a package raea ships, imported by a file with no node_modules of its own: raea's (sdk/app), or a project's brief.ts or scene (#278)
let own = raea_io_home::home().join("sdk/react/js/node_modules").join(&name);
if own.is_dir() {
return package_entry(&own, &sub, esm).ok_or_else(|| format!("Cannot find module '{spec}': {} has no {sub}", own.display()));
}
Err(format!("Cannot find package '{name}' imported from {}", dir.display())) Err(format!("Cannot find package '{name}' imported from {}", dir.display()))
} }
-36
View File
@@ -1,36 +0,0 @@
//! A file importing a package raea ships (raea's own, or a project's with no node_modules) finds it in the React runtime's node_modules (#278): a release has
//! no node_modules above sdk/app, so `raea goal check` ended every render "Cannot find package 'react'". Its own test
//! binary: raea's home is read once a process.
#![cfg(feature = "modules")]
use std::fs;
#[test]
fn raeas_own_file_finds_the_react_raea_ships() {
let home = std::env::temp_dir().join(format!("raea-native-shipped-{}", std::process::id()));
let (pkg, own, theirs) = (home.join("sdk/react/js/node_modules/react"), home.join("sdk/app/src"), std::env::temp_dir().join("raea-native-elsewhere"));
for d in [&pkg, &own] {
fs::create_dir_all(d).unwrap();
}
fs::write(pkg.join("package.json"), r#"{"name":"react","main":"index.js"}"#).unwrap();
fs::write(pkg.join("index.js"), "module.exports = {}").unwrap();
// SAFETY: the one test here, before anything reads the environment
unsafe { std::env::set_var("RAEA_HOME", &home) };
assert_eq!(raea_native::node::resolve_file("react", &own, true).unwrap(), pkg.join("index.js"));
// a project's file with no node_modules of its own gets the same React (brief.ts, a scene it registers): a release's
// render was applied and then failed its checks on "Cannot find package 'react'"
fs::create_dir_all(&theirs).unwrap();
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), pkg.join("index.js"));
// its own copy, when it has one, wins
let mine = theirs.join("node_modules/react");
fs::create_dir_all(&mine).unwrap();
fs::write(mine.join("package.json"), r#"{"name":"react","main":"index.js"}"#).unwrap();
fs::write(mine.join("index.js"), "module.exports = {}").unwrap();
assert_eq!(raea_native::node::resolve_file("react", &theirs, true).unwrap(), mine.join("index.js"));
// a file asked for by its whole path is that file, on Windows too (`D:\..` was read as a package's name)
let whole = pkg.join("index.js");
assert_eq!(raea_native::node::resolve_file(whole.to_str().unwrap(), &theirs, true).unwrap(), whole);
// and a package raea doesn't ship is still not found
assert!(raea_native::node::resolve_file("left-pad", &own, true).unwrap_err().contains("Cannot find package 'left-pad'"));
fs::remove_dir_all(&theirs).ok();
fs::remove_dir_all(&home).ok();
}
+16 -79
View File
@@ -74,88 +74,45 @@ pub fn picture(doc: &mut blitz_dom::BaseDocument, n: blitz_dom::NodeId, w: u32,
node.mark_ancestors_dirty(); node.mark_ancestors_dirty();
} }
/// One reader of a file: its decoder, the frame it gave last (its index and picture), and when it was last asked. /// Video elements' frames: a decoder per file, and the frame each element shows (file, frame index), so a frame
struct Reader { /// already shown isn't decoded again.
dec: Box<dyn raea_io_media::VideoDecoder>,
last: Option<(i64, raea_io_media::Frame)>,
used: u64,
}
/// The most readers one file gets: elements past this many, each at its own place in the file, share the one asked
/// longest ago.
const READERS: usize = 4;
/// How far ahead of its last frame a reader is still the one to read on with (frames): a decoder reads on faster
/// than it seeks.
const AHEAD: i64 = 60;
/// Video elements' frames: a file's readers, and the frame each element shows (file, frame index), so a frame already
/// shown isn't decoded again. One decoder a file made two elements on one clip seek it back and forth: the same
/// frame asked for twice restarted the ffmpeg CLI's decoder at every frame (11-30: 1.66 s a frame on the farm where
/// one element took 0.23 s). So a frame a reader just gave is given again, and an element at another place in the
/// file reads with a reader of its own.
#[derive(Default)] #[derive(Default)]
pub struct Videos { pub struct Videos {
readers: HashMap<std::path::PathBuf, Vec<Reader>>, decoders: HashMap<std::path::PathBuf, Box<dyn raea_io_media::VideoDecoder>>,
shown: HashMap<u64, (std::path::PathBuf, i64)>, shown: HashMap<u64, (std::path::PathBuf, i64)>,
tick: u64,
}
/// Which of a file's readers gives frame `key`: (the reader, whether its last frame is that one). The one that gave
/// it last; else the nearest one behind it within AHEAD; else one that has read nothing; else None (open another, or
/// take the one asked longest ago).
fn pick(last: &[Option<i64>], key: i64) -> Option<(usize, bool)> {
if let Some(i) = last.iter().position(|l| *l == Some(key)) {
return Some((i, true));
}
let behind = last.iter().enumerate().filter_map(|(i, l)| l.filter(|l| *l < key && key - *l <= AHEAD).map(|l| (key - l, i))).min();
behind.map(|(_, i)| (i, false)).or_else(|| last.iter().position(|l| l.is_none()).map(|i| (i, false)))
} }
impl Videos { impl Videos {
/// `v`'s frame at its time, or None when its element shows that frame already. A time past the source's last /// `v`'s frame at its time, or None when its element shows that frame already. A time past the source's last
/// frame (a looped or held clip run long) gives its last frame, as raea-runtime-js's page does. /// frame (a looped or held clip run long) gives its last frame, as raea-runtime-js's page does.
pub fn frame(&mut self, v: &raea_core_wire::tree::VideoAt) -> R<Option<raea_io_media::Frame>> { pub fn frame(&mut self, v: &raea_core_wire::tree::VideoAt) -> R<Option<raea_io_media::Frame>> {
if !self.readers.contains_key(&v.file) { if !self.decoders.contains_key(&v.file) {
self.readers.insert(v.file.clone(), vec![Reader { dec: raea_io_media::open_video(&v.file)?, last: None, used: 0 }]); // RAEA_MEDIA's, the platform's, the portable one, then the ffmpeg CLI, the first that opens it: a WebM is read
// by ffmpeg alone (#113: it was refused, "no video track", where the platform's was the only one asked)
let mut why = Vec::new();
let d = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(&v.file).map_err(|e| why.push(format!("{}: {e}", b.name()))).ok());
let d = d.ok_or_else(|| format!("{}: can't be decoded ({})", v.file.display(), why.join("; ")))?;
self.decoders.insert(v.file.clone(), d);
} }
let rs = self.readers.get_mut(&v.file).unwrap(); let d = self.decoders.get_mut(&v.file).unwrap();
let index = rs[0].dec.index_at(v.at).map(|i| i as i64); let key = d.index_at(v.at).map(|i| i as i64).unwrap_or((v.at * 1e6) as i64 + (1 << 40));
let key = index.unwrap_or((v.at * 1e6) as i64 + (1 << 40));
if self.shown.get(&v.id).is_some_and(|k| k.0 == v.file && k.1 == key) { if self.shown.get(&v.id).is_some_and(|k| k.0 == v.file && k.1 == key) {
return Ok(None); return Ok(None);
} }
self.tick += 1; let f = match d.frame_at(v.at) {
// a source with no frame times has one reader, asked for whatever comes
let i = match index.map(|_| pick(&rs.iter().map(|r| r.last.as_ref().map(|l| l.0)).collect::<Vec<_>>(), key)) {
None => 0,
Some(Some((i, true))) => {
rs[i].used = self.tick;
return Ok(rs[i].last.as_ref().map(|l| l.1.clone()));
}
Some(Some((i, false))) => i,
Some(None) if rs.len() < READERS => {
rs.push(Reader { dec: raea_io_media::open_video(&v.file)?, last: None, used: 0 });
rs.len() - 1
}
Some(None) => rs.iter().enumerate().min_by_key(|(_, r)| r.used).map_or(0, |(i, _)| i),
};
let r = &mut rs[i];
r.used = self.tick;
let f = match r.dec.frame_at(v.at) {
Ok(f) => f, Ok(f) => f,
Err(e) => { Err(e) => {
let i = r.dec.info(); let i = d.info();
let end = (i.duration - 0.5 / i.fps.max(1.0)).max(0.0); let end = (i.duration - 0.5 / i.fps.max(1.0)).max(0.0);
if v.at > end { r.dec.frame_at(end).map_err(|e2| format!("{}: {e2} (asked for {:.3} s: {e})", v.file.display(), v.at))? } else { return Err(format!("{}: {e}", v.file.display())) } if v.at > end { d.frame_at(end).map_err(|e2| format!("{}: {e2} (asked for {:.3} s: {e})", v.file.display(), v.at))? } else { return Err(format!("{}: {e}", v.file.display())) }
} }
}; };
r.last = Some((key, f.clone()));
Ok(Some(f)) Ok(Some(f))
} }
/// `v`'s frame is now its element's picture. /// `v`'s frame is now its element's picture.
pub fn shows(&mut self, v: raea_core_wire::tree::VideoAt) { pub fn shows(&mut self, v: raea_core_wire::tree::VideoAt) {
let Some(d) = self.readers.get_mut(&v.file).and_then(|rs| rs.first_mut()).map(|r| &mut r.dec) else { return }; let Some(d) = self.decoders.get_mut(&v.file) else { return };
let key = d.index_at(v.at).map(|i| i as i64).unwrap_or((v.at * 1e6) as i64 + (1 << 40)); let key = d.index_at(v.at).map(|i| i as i64).unwrap_or((v.at * 1e6) as i64 + (1 << 40));
self.shown.insert(v.id, (v.file, key)); self.shown.insert(v.id, (v.file, key));
} }
@@ -461,23 +418,3 @@ pub fn shots(size: (u32, u32), root: Option<&Path>, fonts: Option<&Path>) -> R<(
} }
Ok(()) Ok(())
} }
#[cfg(test)]
mod readers {
use super::pick;
#[test]
fn a_frame_just_given_is_given_again_and_another_place_gets_its_own_reader() {
// two elements on one clip at one time: the second takes the first's frame
assert_eq!(pick(&[Some(154)], 154), Some((0, true)));
// the next frame reads on with the reader just behind it
assert_eq!(pick(&[Some(154)], 155), Some((0, false)));
// a frame behind every reader, or far ahead, is no reader's: another opens
assert_eq!(pick(&[Some(154)], 153), None);
assert_eq!(pick(&[Some(154)], 154 + super::AHEAD + 1), None);
// of two readers, the nearest behind; a reader that has read nothing only when none is behind
assert_eq!(pick(&[Some(100), Some(790)], 791), Some((1, false)));
assert_eq!(pick(&[Some(100), None], 101), Some((0, false)));
assert_eq!(pick(&[Some(100), None], 900), Some((1, false)));
}
}
-24
View File
@@ -39,30 +39,6 @@ impl BlitzPage {
} }
} }
/// How large each video element is drawn this frame, in page px, with nothing decoded (`render --keys`,
/// docs/cloud-render.feature CR36): its box as drawn (transforms applied, getBoundingClientRect's) times a framed
/// take's punch-in, so a clip's frames are never needed larger than this. None for one with no box yet: its size
/// isn't known, and whoever sizes the clip by these mustn't shrink it.
pub fn drawn_sizes(&mut self, videos: &[raea_core_wire::tree::VideoAt]) -> Vec<(std::path::PathBuf, Option<[f32; 2]>)> {
if videos.is_empty() {
return Vec::new();
}
if let Some((now, _, _)) = self.clock {
let mut docs = self.app.world_mut().non_send_mut::<Docs>();
if let Some(doc) = docs.0.get_mut(&self.page) {
doc.resolve(now);
}
}
videos
.iter()
.map(|v| {
let zoom = v.fit.map_or(1.0, |f| f.scale.max(1.0));
let size = self.client_box(v.id).filter(|b| b[2] > 0.0 && b[3] > 0.0).map(|b| [b[2] * zoom, b[3] * zoom]);
(v.file.clone(), size)
})
.collect()
}
/// Each video element's frame at its time, decoded and set as its picture (`place_picture`). A frame already /// Each video element's frame at its time, decoded and set as its picture (`place_picture`). A frame already
/// shown isn't decoded again. /// shown isn't decoded again.
pub fn place_videos(&mut self, videos: Vec<raea_core_wire::tree::VideoAt>) -> R<()> { pub fn place_videos(&mut self, videos: Vec<raea_core_wire::tree::VideoAt>) -> R<()> {
-1
View File
@@ -5,7 +5,6 @@
pub mod audio; pub mod audio;
pub mod mezz; pub mod mezz;
pub mod mp4box;
#[cfg(feature = "mux")] #[cfg(feature = "mux")]
pub mod remux; pub mod remux;
pub mod samples; pub mod samples;
-73
View File
@@ -1,73 +0,0 @@
//! An MP4 or QuickTime file's boxes, read directly: what `media probe` and the ffmpeg backend take a track's own facts
//! from (its frame times, its sound's rate) without reading the gigabytes of pictures beside them.
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;
/// The boxes inside `b` (a box's payload): (type, payload).
pub fn boxes(b: &[u8]) -> Vec<([u8; 4], &[u8])> {
let mut out = Vec::new();
let mut i = 0usize;
while i + 8 <= b.len() {
let mut size = u32::from_be_bytes(b[i..i + 4].try_into().unwrap()) as usize;
let kind: [u8; 4] = b[i + 4..i + 8].try_into().unwrap();
let mut hdr = 8;
if size == 1 && i + 16 <= b.len() {
size = u64::from_be_bytes(b[i + 8..i + 16].try_into().unwrap()) as usize;
hdr = 16;
} else if size == 0 {
size = b.len() - i;
}
if size < hdr || i + size > b.len() {
break;
}
out.push((kind, &b[i + hdr..i + size]));
i += size;
}
out
}
pub fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
}
pub fn be32(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
pub fn be64(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
}
/// The file's moov box, read alone (mdat can be gigabytes).
pub fn moov_of(path: &Path) -> Option<Vec<u8>> {
let mut f = std::fs::File::open(path).ok()?;
let len = f.metadata().ok()?.len();
let mut at = 0u64;
loop {
if at + 8 > len {
return None;
}
let mut h = [0u8; 16];
f.seek(SeekFrom::Start(at)).ok()?;
f.read_exact(&mut h[..8]).ok()?;
let mut size = u32::from_be_bytes(h[..4].try_into().ok()?) as u64;
let mut hdr = 8u64;
if size == 1 {
f.read_exact(&mut h[8..]).ok()?;
size = u64::from_be_bytes(h[8..].try_into().ok()?);
hdr = 16;
} else if size == 0 {
size = len - at;
}
if size < hdr {
return None;
}
if &h[4..8] == b"moov" {
let mut m = vec![0u8; usize::try_from(size - hdr).ok().filter(|n| *n <= 256 << 20)?];
f.read_exact(&mut m).ok()?;
return Some(m);
}
at += size;
}
}
+31 -95
View File
@@ -9,8 +9,6 @@ use raea_io_codec::{
Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, VideoDecoder, VideoEncoder, as_of, Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, VideoDecoder, VideoEncoder, as_of,
}; };
mod mov;
pub struct Ffmpeg; pub struct Ffmpeg;
/// The ffmpeg or ffprobe to run: the PATH's, else raea's own (raea_io_assets::ffmpeg_tool). Opening a video (`fetch`) /// The ffmpeg or ffprobe to run: the PATH's, else raea's own (raea_io_assets::ffmpeg_tool). Opening a video (`fetch`)
@@ -52,86 +50,17 @@ fn says(option: &str) -> String {
/// phone): libx264 where ffmpeg was built with it (Homebrew's, Linux distributions'), else the system's own (Windows' /// phone): libx264 where ffmpeg was built with it (Homebrew's, Linux distributions'), else the system's own (Windows'
/// Media Foundation, h264_mf, in the LGPL build raea ships there; macOS's VideoToolbox) at 8 Mb/s; None without one. /// Media Foundation, h264_mf, in the LGPL build raea ships there; macOS's VideoToolbox) at 8 Mb/s; None without one.
pub fn h264() -> Option<Vec<&'static str>> { pub fn h264() -> Option<Vec<&'static str>> {
let enc = listed()?; static ENCODERS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
let have = ENCODERS.get_or_init(|| says("-encoders"));
let has = |c: &str| have.split_whitespace().any(|w| w == c);
let enc = ["libx264", "h264_mf", "h264_videotoolbox"].into_iter().find(|c| has(c))?;
let rate: &[&'static str] = if enc == "libx264" { &[] } else { &["-b:v", "8M"] }; let rate: &[&'static str] = if enc == "libx264" { &[] } else { &["-b:v", "8M"] };
Some([&["-c:v", enc][..], rate, &["-pix_fmt", "yuv420p"]].concat()) Some([&["-c:v", enc][..], rate, &["-pix_fmt", "yuv420p"]].concat())
} }
/// The first of libx264, Media Foundation's and VideoToolbox's H.264 encoders this machine's ffmpeg lists
fn listed() -> Option<&'static str> {
["libx264", "h264_mf", "h264_videotoolbox"].into_iter().find(|c| lists("-encoders", c))
}
/// `codec` is among what this machine's ffmpeg prints for `option` (-encoders, -decoders), each asked once
fn lists(option: &'static str, codec: &str) -> bool {
static PRINTED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<&'static str, String>>> = std::sync::OnceLock::new();
let mut printed = PRINTED.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
printed.entry(option).or_insert_with(|| says(option)).split_whitespace().any(|w| w == codec)
}
/// A render's encoder and its rate, as ffmpeg's arguments: NVENC and libx264 at a constant quality when one is asked
/// (0.85 -> 13, 0.95 -> 11, 0.6 -> 18), else the average bitrate. The system's own encoders (h264_mf, h264_videotoolbox)
/// have no CRF, so they take the bitrate either way: the LGPL ffmpeg raea ships on Windows has no libx264, and
/// RAEA_MEDIA=ffmpeg failed there on `-c:v libx264` (#279)
fn video_args(enc: &str, o: &EncodeOpts) -> Vec<String> {
let rate = || vec!["-b:v".to_string(), format!("{}k", o.kbps), "-maxrate".to_string(), format!("{}k", o.kbps * 3 / 2), "-bufsize".to_string(), format!("{}k", o.kbps * 2)];
let q = |q: f32| format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0));
let (nvenc, x264) = (NVENC.map(String::from).to_vec(), ["-c:v", "libx264", "-preset", "medium"].map(String::from).to_vec());
match (enc, o.quality) {
("h264_nvenc", Some(v)) => [nvenc, vec!["-rc".into(), "constqp".into(), "-qp".into(), q(v)]].concat(),
("h264_nvenc", None) => [nvenc, rate()].concat(),
("libx264", Some(v)) => [x264, vec!["-crf".into(), q(v)]].concat(),
("libx264", None) => [x264, rate()].concat(),
_ => [vec!["-c:v".into(), enc.to_string()], rate()].concat(),
}
}
/// RAEA_NV=1 (the render farm sets it on a GPU's runs of a piece with 3D in it, docs/cloud-render.feature CR34): NVIDIA's
/// encoder (`enc`, NVENC) or decoder (NVDEC, through CUDA) in place of libx264 and ffmpeg's own, each only once a
/// one-frame try of it worked on this machine (a GPU without the driver's video libraries keeps libx264, said once).
fn nv(enc: bool) -> bool {
std::env::var("RAEA_NV").as_deref() == Ok("1") && nv_works(enc)
}
/// Whether NVENC (`enc`) or NVDEC worked on this machine, tried once on one frame
fn nv_works(enc: bool) -> bool {
static ENC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
static DEC: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let tried = |args: &[&str]| cli("ffmpeg", false).ok().and_then(|mut c| c.args(["-v", "error"]).args(args).args(["-f", "null", "-"]).output().ok()).is_some_and(|o| o.status.success());
let (cell, what, args): (_, _, &[&str]) = if enc {
(&ENC, "NVENC", &["-f", "lavfi", "-i", "color=s=256x256:d=0.1", "-c:v", "h264_nvenc"])
} else {
(&DEC, "NVDEC", &["-init_hw_device", "cuda=gpu", "-f", "lavfi", "-i", "nullsrc=s=256x256:d=0.04"])
};
// the answer kept for the machine's later runs too (a farm container's runs after its first): a try starts CUDA,
// and on the farm it doubled the timed run's frames (8 frames, 232 to 498 ms a frame on a T4, 11-30)
let kept = std::env::temp_dir().join(format!("raea-{}.tried", what.to_lowercase()));
*cell.get_or_init(|| {
if let Ok(said) = std::fs::read_to_string(&kept) {
return said == "1";
}
let ok = tried(args);
let _ = std::fs::write(&kept, if ok { "1" } else { "0" });
if !ok {
eprintln!("raea: RAEA_NV=1 but {what} didn't work on this machine, so ffmpeg's own is used");
}
ok
})
}
/// NVENC's arguments in libx264's place: at a CRF, constant QP at its number (on 300 frames of a 1080x1920 ad on a T4,
/// SSIM 0.9925 against libx264's 0.9924 at 11% more bytes, 11-30); else its average bitrate
const NVENC: [&str; 14] = ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq", "-bf", "2", "-g", "60", "-spatial-aq", "1", "-temporal-aq", "1"];
/// The facts, the presentation times, whether the colour matrix is untagged, and the decoder a VP8 or VP9 stream with /// The facts, the presentation times, whether the colour matrix is untagged, and the decoder a VP8 or VP9 stream with
/// alpha needs (libvpx: ffmpeg's own VP9 decoder drops the alpha WebM keeps beside the picture, #113). /// alpha needs (libvpx: ffmpeg's own VP9 decoder drops the alpha WebM keeps beside the picture, #113).
fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> { fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
probe_with(path, mov::frame_times(path))
}
/// `tabled`: the frame times the file's own tables state (mov.rs). Without them ffprobe is asked for every packet's
/// time, which reads the whole file.
fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
let out = cli("ffprobe", named_video(path))? let out = cli("ffprobe", named_video(path))?
.args([ .args([
"-v", "-v",
@@ -140,9 +69,11 @@ fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool,
"v:0", "v:0",
"-show_entries", "-show_entries",
"stream=codec_name,width,height,r_frame_rate,color_space:stream_tags=alpha_mode:stream_side_data=rotation:format=duration", "stream=codec_name,width,height,r_frame_rate,color_space:stream_tags=alpha_mode:stream_side_data=rotation:format=duration",
"-show_entries",
"packet=pts_time",
"-of",
"json",
]) ])
.args(if tabled.is_none() { &["-show_entries", "packet=pts_time"][..] } else { &[] })
.args(["-of", "json"])
.arg(path) .arg(path)
.output() .output()
.map_err(|e| format!("ffprobe: {e}"))?; .map_err(|e| format!("ffprobe: {e}"))?;
@@ -165,15 +96,12 @@ fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool,
.and_then(|r| r.split_once('/')) .and_then(|r| r.split_once('/'))
.map(|(n, d)| n.parse::<f64>().unwrap_or(30.0) / d.parse::<f64>().unwrap_or(1.0)) .map(|(n, d)| n.parse::<f64>().unwrap_or(30.0) / d.parse::<f64>().unwrap_or(1.0))
.unwrap_or(30.0); .unwrap_or(30.0);
let mut pts: Vec<f64> = match tabled { let mut pts: Vec<f64> = j["packets"]
Some(t) => t, .as_array()
None => j["packets"] .into_iter()
.as_array() .flatten()
.into_iter() .filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
.flatten() .collect();
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
.collect(),
};
pts.sort_by(f64::total_cmp); pts.sort_by(f64::total_cmp);
let duration = j["format"]["duration"] let duration = j["format"]["duration"]
.as_str() .as_str()
@@ -189,7 +117,9 @@ fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool,
_ => None, _ => None,
}; };
// an ffmpeg built without libvpx decodes the picture alone, as before // an ffmpeg built without libvpx decodes the picture alone, as before
let alpha = alpha.filter(|c| lists("-decoders", c)); static DECODERS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
let have = DECODERS.get_or_init(|| says("-decoders"));
let alpha = alpha.filter(|c| have.split_whitespace().any(|w| w == *c));
Ok(( Ok((
Info { Info {
codec: s["codec_name"].as_str().unwrap_or("?").into(), codec: s["codec_name"].as_str().unwrap_or("?").into(),
@@ -225,12 +155,7 @@ impl Decoder {
} }
let start = self.pts[at] - self.pts[0]; let start = self.pts[at] - self.pts[0];
let mut cmd = cli("ffmpeg", false)?; let mut cmd = cli("ffmpeg", false)?;
cmd.args(["-v", "error"]).args(self.vpx.map(|c| ["-c:v", c]).into_iter().flatten()); cmd.args(["-v", "error"]).args(self.vpx.map(|c| ["-c:v", c]).into_iter().flatten()).args(["-ss", &format!("{start:.6}"), "-i"]).arg(&self.path);
// (a VP8/VP9 with alpha keeps libvpx: NVDEC drops the alpha as ffmpeg's own VP9 decoder does)
if self.vpx.is_none() && nv(false) {
cmd.args(["-hwaccel", "cuda"]);
}
cmd.args(["-ss", &format!("{start:.6}"), "-i"]).arg(&self.path);
if self.bt709 { if self.bt709 {
cmd.args(["-vf", "scale=in_color_matrix=bt709:in_range=tv"]); cmd.args(["-vf", "scale=in_color_matrix=bt709:in_range=tv"]);
} }
@@ -433,7 +358,6 @@ impl Backend for Ffmpeg {
} }
fn encoder(&self, out: &Path, o: &EncodeOpts) -> R<Box<dyn VideoEncoder>> { fn encoder(&self, out: &Path, o: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {
let video = out.with_extension("video.mp4"); let video = out.with_extension("video.mp4");
let enc = if nv(true) { "h264_nvenc" } else { listed().ok_or("this machine's ffmpeg has no H.264 encoder (libx264, h264_mf or h264_videotoolbox)")? };
let child = cli("ffmpeg", false)? let child = cli("ffmpeg", false)?
.args([ .args([
"-v", "-v",
@@ -450,7 +374,19 @@ impl Backend for Ffmpeg {
"-i", "-i",
"-", "-",
]) ])
.args(video_args(enc, o)) .args(["-c:v", "libx264", "-preset", "medium"])
// constant quality as CRF (0.85 -> 13, 0.95 -> 11, 0.6 -> 18), else the average bitrate
.args(match o.quality {
Some(q) => vec!["-crf".to_string(), format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0))],
None => vec![
"-b:v".to_string(),
format!("{}k", o.kbps),
"-maxrate".to_string(),
format!("{}k", o.kbps * 3 / 2),
"-bufsize".to_string(),
format!("{}k", o.kbps * 2),
],
})
.args([ .args([
"-pix_fmt", "-pix_fmt",
"yuv420p", "yuv420p",
-81
View File
@@ -1,81 +0,0 @@
//! An MP4 or QuickTime file's frame times from its own sample tables. Opening a video asked ffprobe for every packet's
//! time, and for these files ffprobe reads every packet to say it: each open of a 1 GB interview read 1 GB (two
//! minutes on a cloud Sprite's disk, 12-01), and a contact sheet opened its file once a frame.
use std::path::Path;
use raea_io_codec::mp4box::{be32, be64, boxes, child, moov_of};
/// Every frame's presentation time in seconds, sorted, as ffprobe's packets give them up to one shift of them all
/// (the decoder uses them from the first on). None for a file that isn't MP4 or QuickTime, one in fragments (mvex), and one
/// whose edit list does more than set where the track starts: those are asked of ffprobe as before.
pub(crate) fn frame_times(path: &Path) -> Option<Vec<f64>> {
let ext = path.extension()?.to_string_lossy().to_ascii_lowercase();
if !["mp4", "mov", "m4v"].contains(&ext.as_str()) {
return None;
}
times_in(&moov_of(path)?)
}
fn times_in(moov: &[u8]) -> Option<Vec<f64>> {
if child(moov, b"mvex").is_some() {
return None;
}
for (k, trak) in boxes(moov) {
if &k != b"trak" {
continue;
}
let Some(mdia) = child(trak, b"mdia") else { continue };
if child(mdia, b"hdlr").and_then(|h| h.get(8..12)) != Some(&b"vide"[..]) {
continue;
}
// an edit list that plays the track from one place on is a shift of every time; one with a gap ahead of it,
// or more than one piece, moves frames apart
if let Some(elst) = child(trak, b"edts").and_then(|e| child(e, b"elst")) {
if be32(elst, 4)? != 1 {
return None;
}
let from = if elst.first() == Some(&1) { be64(elst, 16)? as i64 } else { be32(elst, 12)? as i32 as i64 };
if from < 0 {
return None;
}
}
let mdhd = child(mdia, b"mdhd")?;
let scale = if mdhd.first() == Some(&1) { be32(mdhd, 20)? } else { be32(mdhd, 12)? } as f64;
if scale <= 0.0 {
return None;
}
let stbl = child(child(mdia, b"minf")?, b"stbl")?;
let stts = child(stbl, b"stts")?;
let mut times: Vec<i64> = Vec::new();
let mut dts = 0i64;
for e in 0..be32(stts, 4)? as usize {
let (n, d) = (be32(stts, 8 + e * 8)?, be32(stts, 12 + e * 8)? as i64);
// a table that claims more frames than a day of 240 a second isn't one to trust
if times.len() + n as usize > 20_736_000 {
return None;
}
for _ in 0..n {
times.push(dts);
dts += d;
}
}
if let Some(ctts) = child(stbl, b"ctts") {
let mut i = 0usize;
for e in 0..be32(ctts, 4)? as usize {
// signed whatever the version says: QuickTime writes negative offsets in version 0 boxes
let (n, off) = (be32(ctts, 8 + e * 8)? as usize, be32(ctts, 12 + e * 8)? as i32 as i64);
for t in times.iter_mut().skip(i).take(n) {
*t += off;
}
i += n;
}
}
if times.is_empty() {
return None;
}
times.sort_unstable();
return Some(times.into_iter().map(|t| t as f64 / scale).collect());
}
None
}
-69
View File
@@ -32,72 +32,3 @@ fn vp9_webm_keeps_its_alpha() {
} }
let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&dir);
} }
/// Where NVIDIA's encoder and decoder don't work (this Mac, a GPU without the driver's video libraries) the one-frame
/// tries fail, so RAEA_NV=1 keeps libx264 and ffmpeg's own decoders instead of refusing (CR34)
#[test]
fn nv_falls_back_where_nvidia_isnt() {
if Command::new("ffmpeg").arg("-version").output().is_err() {
return eprintln!("skipped: no ffmpeg here");
}
if !Command::new("nvidia-smi").output().is_ok_and(|o| o.status.success()) {
assert!(!nv_works(true) && !nv_works(false), "no NVIDIA here, so neither is used");
}
if std::env::var_os("RAEA_NV").is_none() {
assert!(!nv(true) && !nv(false), "off without RAEA_NV=1");
}
}
/// libx264's arguments are what they were, and the system's encoder (macOS's here, Windows' Media Foundation the same
/// way) takes a bitrate even when a quality is asked, and encodes with them (#279)
#[test]
fn a_system_encoder_takes_the_bitrate() {
let o = |quality| EncodeOpts { width: 256, height: 256, fps: 30.0, kbps: 900, quality, nv12: false, realtime: false };
assert_eq!(video_args("libx264", &o(Some(0.85))), ["-c:v", "libx264", "-preset", "medium", "-crf", "13"]);
assert_eq!(video_args("libx264", &o(None)), ["-c:v", "libx264", "-preset", "medium", "-b:v", "900k", "-maxrate", "1350k", "-bufsize", "1800k"]);
let args = video_args("h264_videotoolbox", &o(Some(0.85)));
assert_eq!(args, ["-c:v", "h264_videotoolbox", "-b:v", "900k", "-maxrate", "1350k", "-bufsize", "1800k"]);
if !lists("-encoders", "h264_videotoolbox") {
return eprintln!("skipped the encode: no h264_videotoolbox in this ffmpeg");
}
let out = std::env::temp_dir().join(format!("raea-ffmpeg-system-{}.mp4", std::process::id()));
let ok = Command::new("ffmpeg").args(["-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=256x256:d=0.3"]).args(&args).args(["-pix_fmt", "yuv420p"]).arg(&out).status().is_ok_and(|s| s.success());
assert!(ok && std::fs::metadata(&out).is_ok_and(|m| m.len() > 500), "ffmpeg encodes with the system encoder's arguments");
let _ = std::fs::remove_file(&out);
}
/// An MP4's and a QuickTime file's frame times, read from their own tables, are the ones ffprobe's packets give (up to
/// one shift of them all), with B-frames, at a rate that isn't whole, and the same frames come out either way.
#[test]
fn a_file_s_own_tables_give_ffprobe_s_frame_times() {
let dir = std::env::temp_dir().join(format!("raea-ffmpeg-tables-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let make = |name: &str, args: &[&str]| {
let p = dir.join(name);
let ok = Command::new("ffmpeg").args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=s=128x72:r=30000/1001:d=2", "-pix_fmt", "yuv420p"]).args(args).arg(&p).status().is_ok_and(|s| s.success());
ok.then_some(p)
};
let files = [make("b.mp4", &["-c:v", "libx264", "-bf", "3"]), make("b.mov", &["-c:v", "libx264", "-bf", "2", "-g", "12"]), make("plain.mp4", &["-c:v", "mpeg4"])];
let mut seen = 0;
for f in files.into_iter().flatten() {
let Some(tabled) = mov::frame_times(&f) else { panic!("{}: its tables weren't read", f.display()) };
let (_, asked, ..) = probe_with(&f, None).unwrap();
assert_eq!(tabled.len(), asked.len(), "{}: as many frames", f.display());
for (a, b) in tabled.iter().zip(&asked) {
assert!(((a - tabled[0]) - (b - asked[0])).abs() < 2e-4, "{}: {a} against {b}", f.display());
}
// and the decoder gives the same picture at a time either way
let (info, pts, ..) = probe(&f).unwrap();
assert_eq!(pts.len(), info.frames);
let mut d = Ffmpeg.open_video(&f).unwrap();
let at = d.frame_at(1.0).unwrap();
assert!((at.pts - 1.0).abs() < 0.04, "{}: the frame at 1 s is at {}", f.display(), at.pts);
seen += 1;
}
let _ = std::fs::remove_dir_all(&dir);
if seen == 0 {
eprintln!("skipped: no ffmpeg here to make a file with");
}
// a file in fragments, or of another kind, is asked of ffprobe as before
assert!(mov::frame_times(Path::new("a.webm")).is_none());
}
-8
View File
@@ -71,14 +71,6 @@ pub fn backend_unsigned(name: &str) -> R<Box<dyn Backend>> {
pub mod sign; pub mod sign;
pub use sign::signs; pub use sign::signs;
/// `file`'s decoder: the first of `preferred` that opens it, else what each said. A WebM is read by ffmpeg alone (#113:
/// it was refused, "no video track", where the platform's was the only one asked).
pub fn open_video(file: &Path) -> Result<Box<dyn VideoDecoder>, String> {
let mut why = Vec::new();
let d = preferred().into_iter().find_map(|b| b.open_video(file).map_err(|e| why.push(format!("{}: {e}", b.name()))).ok());
d.ok_or_else(|| format!("{}: no backend reads it ({})", file.display(), why.join("; ")))
}
/// The backends to try for a file, in order: RAEA_MEDIA's, the platform's, the portable one, then the ffmpeg CLI /// The backends to try for a file, in order: RAEA_MEDIA's, the platform's, the portable one, then the ffmpeg CLI
/// (which reads what the others don't: VP9 WebM). /// (which reads what the others don't: VP9 WebM).
pub fn preferred() -> Vec<Box<dyn Backend>> { pub fn preferred() -> Vec<Box<dyn Backend>> {
+12 -1
View File
@@ -83,7 +83,18 @@ fn encode_at(src: &Path, part: &Path, range: Option<(usize, usize)>, p: &Probe,
Some((a, b)) => (a as f64 * p.frame_secs(), (b + 1) as f64 * p.frame_secs()), Some((a, b)) => (a as f64 * p.frame_secs(), (b + 1) as f64 * p.frame_secs()),
None => (0.0, p.secs), None => (0.0, p.secs),
}; };
let mut dec = crate::open_video(src)?; let mut why = Vec::new();
let mut dec = None;
for b in crate::preferred() {
match b.open_video(src) {
Ok(d) => {
dec = Some(d);
break;
}
Err(e) => why.push(format!("{}: {e}", b.name())),
}
}
let mut dec = dec.ok_or_else(|| format!("{}: no backend reads it ({})", src.display(), why.join("; ")))?;
let info = dec.info().clone(); let info = dec.info().clone();
if info.width % 2 == 1 || info.height % 2 == 1 { if info.width % 2 == 1 || info.height % 2 == 1 {
return Err(format!("{}: {}x{} has an odd side (H.264's 4:2:0 wants even ones)", src.display(), info.width, info.height)); return Err(format!("{}: {}x{} has an odd side (H.264's 4:2:0 wants even ones)", src.display(), info.width, info.height));
+1 -22
View File
@@ -58,23 +58,7 @@ pub struct Track {
/// A file's first video track's display rotation (clockwise degrees; 0 when it has none or isn't an MP4/MOV). /// A file's first video track's display rotation (clockwise degrees; 0 when it has none or isn't an MP4/MOV).
pub fn rotation_of(path: &Path) -> i32 { pub fn rotation_of(path: &Path) -> i32 {
// the moov box alone, as a file of that one box (the whole file was read for it: gigabytes, for a matrix) std::fs::read(path).map(|b| mp4_rotation(&b)).unwrap_or(0)
let Some(moov) = raea_io_codec::mp4box::moov_of(path) else { return 0 };
let mut b = ((moov.len() + 8) as u32).to_be_bytes().to_vec();
b.extend_from_slice(b"moov");
b.extend_from_slice(&moov);
mp4_rotation(&b)
}
/// The first video track's sample entry (avc1, hvc1, av01, ...), from the moov box alone.
fn video_fourcc(path: &Path) -> Option<[u8; 4]> {
use raea_io_codec::mp4box::{boxes, child, moov_of};
let moov = moov_of(path)?;
boxes(&moov).into_iter().filter(|(k, _)| k == b"trak").find_map(|(_, trak)| {
let mdia = child(trak, b"mdia")?;
(child(mdia, b"hdlr")?.get(8..12)? == b"vide").then_some(())?;
child(child(child(mdia, b"minf")?, b"stbl")?, b"stsd")?.get(12..16)?.try_into().ok()
})
} }
/// The first video track's display rotation, from its tkhd matrix (QuickTime's 16.16 a, b, c, d). /// The first video track's display rotation, from its tkhd matrix (QuickTime's 16.16 a, b, c, d).
@@ -123,11 +107,6 @@ fn mp4_rotation(b: &[u8]) -> i32 {
} }
pub fn demux(path: &Path, want: &str) -> R<Track> { pub fn demux(path: &Path, want: &str) -> R<Track> {
// another codec's file is refused before it is read: every open of a 4K HEVC interview on Linux read its whole
// gigabyte here to learn it wasn't H.264, then went to the backend that reads it (two minutes on a cloud disk)
if let Some(is) = video_fourcc(path).filter(|f| want.len() >= 3 && f[..3] != want.as_bytes()[..3]) {
return Err(format!("{}: {}, not {want} (this backend reads {want} mezzanines)", path.display(), String::from_utf8_lossy(&is)));
}
let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?; let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let mp4 = re_mp4::Mp4::read_bytes(&bytes).map_err(|e| format!("{}: {e}", path.display()))?; let mp4 = re_mp4::Mp4::read_bytes(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
let (_, t) = mp4 let (_, t) = mp4
-37
View File
@@ -1,37 +0,0 @@
//! A file of another codec is refused from its moov box alone, and a rotation is read from it, without the file's
//! pictures being read (a 1 GB HEVC interview was read whole on every open to learn it wasn't H.264).
use std::path::{Path, PathBuf};
use std::process::Command;
fn made(dir: &Path, name: &str, args: &[&str]) -> Option<PathBuf> {
let p = dir.join(name);
Command::new("ffmpeg").args(["-v", "error", "-y"]).args(args).arg(&p).status().is_ok_and(|s| s.success()).then_some(p)
}
#[test]
fn another_codec_is_refused_by_its_tables_and_a_rotation_read_from_them() {
let dir = std::env::temp_dir().join(format!("raea-soft-refuse-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let src = ["-f", "lavfi", "-i", "testsrc2=s=128x72:r=30:d=1", "-pix_fmt", "yuv420p"];
let Some(other) = made(&dir, "other.mp4", &[&src[..], &["-c:v", "mpeg4"]].concat()) else { return eprintln!("skipped: no ffmpeg here") };
let e = raea_io_soft::demux(&other, "avc1").err().expect("an MPEG-4 file isn't H.264");
assert!(e.contains("mp4v, not avc1"), "{e}");
// cut short after its moov, the refusal is the same: nothing past the tables was needed
if let Some(front) = made(&dir, "front.mp4", &[&src[..], &["-c:v", "mpeg4", "-movflags", "+faststart"]].concat()) {
let bytes = std::fs::read(&front).unwrap();
let mdat = bytes.windows(4).position(|w| w == b"mdat").unwrap();
std::fs::write(&front, &bytes[..mdat + 4]).unwrap();
assert!(raea_io_soft::demux(&front, "avc1").err().unwrap().contains("mp4v, not avc1"));
assert_eq!(raea_io_soft::rotation_of(&front), 0);
}
// an H.264 file is read as before, and one turned on its side says so
if let Some(h264) = made(&dir, "h264.mp4", &[&src[..], &["-c:v", "libx264"]].concat()) {
assert!(raea_io_soft::demux(&h264, "avc1").is_ok());
assert_eq!(raea_io_soft::rotation_of(&h264), 0);
let h = h264.to_string_lossy().to_string();
if let Some(turned) = made(&dir, "turned.mp4", &["-display_rotation:v:0", "90", "-i", &h, "-c", "copy"]) {
assert_eq!(raea_io_soft::rotation_of(&turned).rem_euclid(180), 90);
}
}
let _ = std::fs::remove_dir_all(&dir);
}
-2
View File
@@ -45,8 +45,6 @@ raea-sys-light-meter = { path = "../../systems/light-meter" }
raea-runtime-scene3d = { path = "../scene3d" } raea-runtime-scene3d = { path = "../scene3d" }
# --review: the fixed cameras # --review: the fixed cameras
raea-core-review = { path = "../../core/review" } raea-core-review = { path = "../../core/review" }
# render --review's tiles and sheets
raea-runtime-review = { path = "../review" }
raea-sys-mix = { path = "../../systems/mix" } raea-sys-mix = { path = "../../systems/mix" }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] } bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }
image = { version = "0.25", default-features = false, features = ["png", "hdr"] } image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
-8
View File
@@ -245,14 +245,6 @@ pub(crate) fn bevy_page_frame(world: &mut World, page: &mut raea_runtime_page::B
Ok((px, pics)) Ok((px, pics))
} }
/// React told the frame is `f` (with `tell`) and settled there, a layout read answered from the page as it is then.
pub(crate) fn step_react(app: &mut App, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, (f, fps): (i64, f64), tell: bool) -> R<()> {
if tell { app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f})); }
settle_with(app, Some(f), 20.0, &mut |w, q| layout_answer(w, page, cx, f, fps, q))?;
cx.now = f;
Ok(())
}
/// A composition's layout read answered by the frame's page (`page.layout`, docs/layout-reads.feature LR1): the page made /// A composition's layout read answered by the frame's page (`page.layout`, docs/layout-reads.feature LR1): the page made
/// to match the React World as it is mid-settle, at frame `f`'s time, laid out, and every element's boxes by React id. /// to match the React World as it is mid-settle, at frame `f`'s time, laid out, and every element's boxes by React id.
/// Nothing is drawn; the frame's own sync redoes what this did once the frame settles. /// Nothing is drawn; the frame's own sync redoes what this did once the frame settles.
+5 -1
View File
@@ -246,7 +246,11 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
} }
let t_react = std::time::Instant::now(); let t_react = std::time::Instant::now();
engine_before(app, cx, f); engine_before(app, cx, f);
step_react(app, bevy, cx, (f, fps), asked != Some(f))?; if asked != Some(f) {
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
}
settle_with(app, Some(f), 20.0, &mut |w, q| layout_answer(w, bevy, cx, f, fps, q))?;
cx.now = f;
// the next frame asked for now, so React renders it on its own thread while this one's 3D and page are // the next frame asked for now, so React renders it on its own thread while this one's 3D and page are
// drawn here: its commits wait in the inbox until the next settle applies them, so nothing this frame // drawn here: its commits wait in the inbox until the next settle applies them, so nothing this frame
// reads changes (the frames come in order; one asked for out of order is asked for again) // reads changes (the frames come in order; one asked for out of order is asked for again)
-44
View File
@@ -1,44 +0,0 @@
//! `render --keys PATH`: what each frame of the composition draws, as a key, with nothing drawn, no clip read and no
//! sound made (docs/rerender.feature RR4, docs/cloud-render.feature CR30). React is stepped through every frame as a
//! render steps it and the page made to match its tree; a frame's key is the page's (raea_core_wire::tree::key: its
//! elements and each video's file and time) with the frame's 3D rows. A render farm holds a run of frames it drew
//! before to its frames' keys, and draws again only the runs whose keys changed: a caption edited in one shot redraws
//! that shot's runs, a change to the sound alone redraws none.
//!
//! A key is a frame's own: the same key at another frame number isn't the same picture (an element's CSS animation
//! runs on the page's clock, not in its props), and neither is the same key over other files (they're named, not
//! read). Whoever keeps pictures by these holds both to them. With 3D, a frame's picture can hang on the frames before
//! it (physics, particles, a path tracer's light), which `has3d` says.
//!
//! The piece's sounds are written beside the keys as a render's manifest holds them (`sounds`): a run taken from a
//! farm's cache brings the manifest of the render that drew it, whose sounds are that render's, not this edit's.
use super::*;
pub(crate) fn write(to: &Path, app: &mut App, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, (w, h, fps, total): (u32, u32, f64, i64)) -> R<String> {
use std::hash::{Hash, Hasher};
page.keyed = Some(0);
let (mut keys, mut has3d) = (Vec::with_capacity(total.max(0) as usize), false);
let (mut frames, mut tones) = (Vec::new(), Vec::new());
for f in 0..total {
step_react(app, page, cx, (f, fps), true)?;
page.at_frame(f, fps);
bevy_page_sync(app.world_mut(), page, cx)?;
let mut h = std::collections::hash_map::DefaultHasher::new();
(page.keyed, format!("{:?}{:?}", cx.scene, cx.clear)).hash(&mut h);
has3d |= !cx.scene.is_empty();
keys.push(format!("{:016x}", h.finish()));
tones.push(raea_runtime_sound::tone_at(app.world_mut(), f, fps, cx.dir, media_path, true));
frames.push((f, Frame { mix: cx.mix, page: None, sounds: cx.sounds.clone(), scene: Vec::new(), clear: None, same: false, screens: Vec::new() }));
}
to.parent().map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", to.display()))?;
std::fs::write(to, json!({"width": w, "height": h, "fps": fps, "length": total, "has3d": has3d, "keys": keys, "sounds": heard(&frames, &tones, cx, fps), "drawn": drawn(page, cx.dir)}).to_string()).map_err(|e| format!("{}: {e}", to.display()))?;
Ok(format!("APPLIED {total} frames' keys written to {} (nothing drawn)", to.display()))
}
/// The largest each clip was drawn, by its path from the composition's folder: {"media/a.mp4": [w, h]} in output px,
/// null where a frame's size wasn't known (CR36)
fn drawn(page: &raea_runtime_page::BevyPage, dir: &Path) -> Value {
let size = |s: &[f32; 2]| if s.iter().all(|v| v.is_finite()) { json!([s[0].ceil(), s[1].ceil()]) } else { Value::Null };
Value::Object(page.drawn.iter().map(|(f, s)| (f.strip_prefix(dir).unwrap_or(f).to_string_lossy().into_owned(), size(s))).collect())
}
-4
View File
@@ -31,7 +31,6 @@ pub(crate) use raea_runtime_react::{ReactKind, ReactOutbox, ReactPlugin, ReactPr
mod bevy_frame; mod bevy_frame;
use bevy_frame::*; use bevy_frame::*;
mod keys;
mod pages; mod pages;
use pages::*; use pages::*;
mod program; mod program;
@@ -65,9 +64,6 @@ pub(crate) struct Sound {
bus: Option<String>, bus: Option<String>,
} }
/// `render --keys PATH`: each frame's key written there and nothing drawn (keys.rs).
pub(crate) static KEYS: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
/// `render --manifest PATH` (the CLI's; render_bundle keeps its signature for the iPhone): where render.json goes. /// `render --manifest PATH` (the CLI's; render_bundle keeps its signature for the iPhone): where render.json goes.
static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None); static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
-9
View File
@@ -65,12 +65,6 @@ pub fn render(args: &[String]) -> R<String> {
(_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?), (_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?),
_ => None, _ => None,
}; };
if let Some(k) = flag(args, "--keys") {
*KEYS.lock().unwrap() = Some(PathBuf::from(k));
let said = render_bundle_with(&js, &dir, &out, None, false, None, false);
let _ = std::fs::remove_file(&js);
return said;
}
raea_sys_layers::start(layers_on, &out, &tsx); raea_sys_layers::start(layers_on, &out, &tsx);
*MANIFEST.lock().unwrap() = Some(flag(args, "--manifest").map_or_else(|| raea_sys_layers::manifest_for(&out, &tsx), PathBuf::from)); *MANIFEST.lock().unwrap() = Some(flag(args, "--manifest").map_or_else(|| raea_sys_layers::manifest_for(&out, &tsx), PathBuf::from));
TEN_BIT.store(args.iter().any(|a| a == "--10bit"), std::sync::atomic::Ordering::Relaxed); TEN_BIT.store(args.iter().any(|a| a == "--10bit"), std::sync::atomic::Ordering::Relaxed);
@@ -303,9 +297,6 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
raea_gpu_device::check::mem_fits(w, h, None)?; raea_gpu_device::check::mem_fits(w, h, None)?;
let mut page = raea_runtime_page::BevyPage::new(w, h, dir)?; let mut page = raea_runtime_page::BevyPage::new(w, h, dir)?;
let mut cx = Ctx { dir, work: &work, sounds: Vec::new(), scene: Vec::new(), clear: None, marker: None, mix: None, audible: HashMap::new(), brand: page_css(dir, w, js), manifest: MANIFEST.lock().unwrap().as_ref().map(|_| Vec::new()), now: 0, said: Default::default(), made: HashMap::new(), scene3d: None, live3d: None }; let mut cx = Ctx { dir, work: &work, sounds: Vec::new(), scene: Vec::new(), clear: None, marker: None, mix: None, audible: HashMap::new(), brand: page_css(dir, w, js), manifest: MANIFEST.lock().unwrap().as_ref().map(|_| Vec::new()), now: 0, said: Default::default(), made: HashMap::new(), scene3d: None, live3d: None };
if let Some(to) = KEYS.lock().unwrap().take() {
return crate::keys::write(&to, &mut app, &mut page, &mut cx, (w, h, fps, total));
}
if fed { if fed {
if let Some(p) = scene { if let Some(p) = scene {
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?); aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
+60 -2
View File
@@ -7,7 +7,7 @@
use super::*; use super::*;
use crate::scene::items; use crate::scene::items;
use raea_core_review::{boxes_of, cameras, ceiling, inside, parts_box, whole}; use raea_core_review::{TILE_W, VIEWS, boxes_of, cameras, ceiling, inside, parts_box, passed, whole};
pub fn review(args: &[String], dir_out: &Path) -> R<String> { pub fn review(args: &[String], dir_out: &Path) -> R<String> {
let tsx = dunce::canonicalize(&PathBuf::from(&args[1])).map_err(|e| format!("{}: {e}", args[1]))?; let tsx = dunce::canonicalize(&PathBuf::from(&args[1])).map_err(|e| format!("{}: {e}", args[1]))?;
@@ -31,5 +31,63 @@ pub fn review(args: &[String], dir_out: &Path) -> R<String> {
let ceil = ceiling(&all, wlo, whi); let ceil = ceiling(&all, wlo, whi);
let fixed = match ceil { Some(y) => inside(wlo, whi, y), None => cameras(lo, hi, aspect) }; let fixed = match ceil { Some(y) => inside(wlo, whi, y), None => cameras(lo, hi, aspect) };
cams.extend(fixed.into_iter().map(|(v, e, t, f)| (v, Some((e, t, f))))); cams.extend(fixed.into_iter().map(|(v, e, t, f)| (v, Some((e, t, f)))));
raea_runtime_review::sheets(&tsx, args, dir_out, &cams, raea_runtime_review::Shot { frame, aspect, parts: (lo, hi), interior: ceil.is_some() }) let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let rest = passed(args);
let mut tiles = Vec::new();
let mut said = Vec::new();
for (view, cam) in &cams {
for mode in ["colour", "clay"] {
let out = dir_out.join(format!("{view}-{mode}.png"));
let mut cmd = std::process::Command::new(&exe);
cmd.arg("render").arg(&tsx).args(&rest).args(["--frame", &frame.to_string(), "-o"]).arg(&out);
// a tile is part of this render: the review keeps the one entry in the project's record (DR3)
cmd.env_remove("RAEA_CAMERA").env_remove("RAEA_CLAY").env("RAEA_RECORD", "off");
if let Some((e, t, f)) = cam {
cmd.env("RAEA_CAMERA", format!("{},{},{},{},{},{},{}", e[0], e[1], e[2], t[0], t[1], t[2], f));
}
if mode == "clay" {
cmd.env("RAEA_CLAY", "1");
}
let run = cmd.output().map_err(|e| format!("--review: {e}"))?;
if !run.status.success() || !out.is_file() {
let text = format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
return Err(format!("--review: the {view} {mode} render failed: {}", text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
}
}
let colour = dir_out.join(format!("{view}-colour.png"));
let (_, ev) = raea_sys_light_meter::exposure::of_pngs(std::slice::from_ref(&colour))?;
// what a tile's exposure found, counted with the render's findings (DR3)
let tile: Vec<raea_core_facts::Finding> = ev["found"].as_array().into_iter().flatten().filter_map(|f| {
raea_core_facts::Finding::of_value(&json!({"check": "exposure", "level": f["level"], "says": format!("{view} tile: {}", f["says"].as_str().unwrap_or("").trim_start_matches("the frame: "))}), "raea render")
}).collect();
raea_core_facts::finding::said(&tile);
said.extend(tile);
tiles.push(json!({"view": view, "colour": format!("{view}-colour.png"), "clay": format!("{view}-clay.png"), "exposure": ev["exposure"],
"camera": cam.map(|(e, t, f)| json!({"eye": e, "target": t, "fov": f}))}));
}
// the sheets: three across, two down, each tile TILE_W wide
let th = (TILE_W as f64 / aspect).round().max(1.0) as u32;
for mode in ["colour", "clay"] {
let mut sheet = image::RgbaImage::from_pixel(TILE_W * 3, th * 2, image::Rgba([0, 0, 0, 255]));
for (i, view) in VIEWS.iter().enumerate() {
let img = image::open(dir_out.join(format!("{view}-{mode}.png"))).map_err(|e| format!("{view}-{mode}.png: {e}"))?.to_rgba8();
let small = image::imageops::resize(&img, TILE_W, th, image::imageops::FilterType::Triangle);
image::imageops::overlay(&mut sheet, &small, (i as u32 % 3 * TILE_W) as i64, (i as u32 / 3 * th) as i64);
}
sheet.save(dir_out.join(format!("{mode}.png"))).map_err(|e| format!("{mode}.png: {e}"))?;
}
for (i, t) in tiles.iter_mut().enumerate() {
t["rect"] = json!([i as u32 % 3 * TILE_W, i as u32 / 3 * th, TILE_W, th]);
}
let cameras: Vec<Value> = tiles.iter().map(|t| json!({"view": t["view"], "camera": t["camera"]})).collect();
std::fs::write(dir_out.join("cameras.json"), serde_json::to_string_pretty(&json!({"frame": frame, "box": {"min": lo, "max": hi}, "interior": ceil.is_some(), "cameras": cameras})).unwrap_or_default()).map_err(|e| e.to_string())?;
let doc = json!({"frame": frame, "sheets": {"colour": "colour.png", "clay": "clay.png"}, "size": [TILE_W * 3, th * 2],
"caption": if ceil.is_some() { "An interior, seen from inside: tiles left to right, top to bottom: hero, front, right, top (under the ceiling), iso, low (0.3 m). Clay: every standard surface light grey and matte." } else { "Tiles left to right, top to bottom: hero, front, right, top, iso, low (0.3 m). Clay: every standard surface light grey and matte." },
"box": {"min": lo, "max": hi}, "tiles": tiles, "found": said});
std::fs::write(dir_out.join("review.json"), serde_json::to_string_pretty(&doc).unwrap_or_default()).map_err(|e| e.to_string())?;
let mut msg = format!("APPLIED review of frame {frame}: {} and {} (hero, front, right, top, iso, low), cameras and exposure in {}", dir_out.join("colour.png").display(), dir_out.join("clay.png").display(), dir_out.join("review.json").display());
for f in &said {
msg.push_str(&format!("\n{}", f.line()));
}
Ok(msg)
} }
+4 -2
View File
@@ -9,8 +9,8 @@ description = "A composition's page in Bevy: React's elements laid out and paint
[dependencies] [dependencies]
raea-runtime-view = { path = "../view" } raea-runtime-view = { path = "../view" }
raea-runtime-appscreen = { path = "../appscreen" } raea-runtime-appscreen = { path = "../appscreen" }
# a take's face track, for <Video framing="face"> raea-sys-frame = { path = "../../systems/frame" }
raea-sys-facetrack = { path = "../../systems/facetrack" } raea-io-assets = { path = "../../io/assets" }
raea-io-net = { path = "../../io/net" } raea-io-net = { path = "../../io/net" }
raea-io-home = { path = "../../io/home" } raea-io-home = { path = "../../io/home" }
raea-runtime-react = { path = "../../runtime/react", default-features = false } raea-runtime-react = { path = "../../runtime/react", default-features = false }
@@ -26,7 +26,9 @@ raea-sys-image = { path = "../../systems/image" }
raea-runtime-twins = { path = "../twins" } raea-runtime-twins = { path = "../twins" }
raea-runtime-input = { path = "../input" } raea-runtime-input = { path = "../input" }
raea-core-wire = { path = "../../core/wire" } raea-core-wire = { path = "../../core/wire" }
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] } bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
serde_json = "1" serde_json = "1"
base64 = "0.22" base64 = "0.22"
wgpu = "=30.0.1" wgpu = "=30.0.1"
+1 -17
View File
@@ -25,11 +25,6 @@ pub struct BevyPage {
pub(crate) surf: Option<Entity>, pub(crate) surf: Option<Entity>,
/// the UiMaterial elements the last sync met: page id and spec (JSON) /// the UiMaterial elements the last sync met: page id and spec (JSON)
pub(crate) ui_mats: Vec<(u64, String)>, pub(crate) ui_mats: Vec<(u64, String)>,
/// `render --keys`: a sync leaves the page's key here (raea_core_wire::tree::key) and reads no video's frame
pub keyed: Option<u64>,
/// `render --keys`: the largest each clip was drawn, [w, h] in page px over the frames synced (infinite where
/// one frame's size wasn't known), so a render farm can read it from a copy no larger (CR36)
pub drawn: HashMap<PathBuf, [f32; 2]>,
} }
impl BevyPage { impl BevyPage {
@@ -39,7 +34,7 @@ impl BevyPage {
// they draw as it is // they draw as it is
let fonts = raea_io_home::home().join("core/fonts"); let fonts = raea_io_home::home().join("core/fonts");
let page = raea_page::motion::BlitzPage::new_on(w, h, Some(&fonts), Some(raea_runtime_view::render_creation()))?; let page = raea_page::motion::BlitzPage::new_on(w, h, Some(&fonts), Some(raea_runtime_view::render_creation()))?;
Ok(BevyPage { page, w, h, dir: dir.to_path_buf(), slot: None, view: None, in_box: false, under: false, app_screens: Vec::new(), apps: Default::default(), walk: Walk::default(), surf: None, ui_mats: Vec::new(), keyed: None, drawn: HashMap::new() }) Ok(BevyPage { page, w, h, dir: dir.to_path_buf(), slot: None, view: None, in_box: false, under: false, app_screens: Vec::new(), apps: Default::default(), walk: Walk::default(), surf: None, ui_mats: Vec::new() })
} }
/// The page made to match the React tree in `react` (the composition's App's World). `holders`: the props elements /// The page made to match the React tree in `react` (the composition's App's World). `holders`: the props elements
@@ -67,7 +62,6 @@ impl BevyPage {
self.walk.begin(self.w, self.h, brand, self.under); self.walk.begin(self.w, self.h, brand, self.under);
walk(react, surf, BODY, At::Str(""), &self.dir, holders, &mut self.walk, &mut videos, &mut screens); walk(react, surf, BODY, At::Str(""), &self.dir, holders, &mut self.walk, &mut videos, &mut screens);
self.walk.end(); self.walk.end();
let mut key = self.keyed.map(|_| raea_core_wire::tree::key(0, self.walk.wants(), &videos, &self.dir));
// an <Img> of a file that isn't there fails the render, naming it (footage.md), never a frame without it; so does // an <Img> of a file that isn't there fails the render, naming it (footage.md), never a frame without it; so does
// a framed take with no face track // a framed take with no face track
let refused = REFUSED.with(|c| std::mem::take(&mut *c.borrow_mut())); let refused = REFUSED.with(|c| std::mem::take(&mut *c.borrow_mut()));
@@ -78,7 +72,6 @@ impl BevyPage {
// each <Screen>'s nested composition: a root of its own at the screen's size, drawn into its own picture // each <Screen>'s nested composition: a root of its own at the screen's size, drawn into its own picture
let mut keep = Vec::new(); let mut keep = Vec::new();
for s in screens { for s in screens {
key = key.map(|k| raea_core_wire::tree::key(k, &s.want, &s.videos, &self.dir));
videos.extend(s.videos); videos.extend(s.videos);
let (mut want, mut order, first) = frame_wants(s.w, s.h, brand); let (mut want, mut order, first) = frame_wants(s.w, s.h, brand);
want.extend(s.want); want.extend(s.want);
@@ -106,15 +99,6 @@ impl BevyPage {
} }
crate::screen::retire(&mut self.apps, &self.app_screens); crate::screen::retire(&mut self.apps, &self.app_screens);
crate::screen::step_all(&mut self.apps, &self.app_screens, &self.dir); crate::screen::step_all(&mut self.apps, &self.app_screens, &self.dir);
if key.is_some() {
self.keyed = key;
for (file, size) in self.page.drawn_sizes(&videos) {
let s = size.unwrap_or([f32::INFINITY; 2]);
let had = self.drawn.entry(file).or_insert([0.0; 2]);
*had = [had[0].max(s[0]), had[1].max(s[1])];
}
return Ok(());
}
self.page.place_videos(videos) self.page.place_videos(videos)
} }
+1 -1
View File
@@ -223,7 +223,7 @@ pub(crate) fn video_fit(props: Option<&Map<String, Value>>, file: &Path, at: f64
if !face { if !face {
return Some(VideoFit { at: (0.5, 0.5), to: (0.5, 0.5), scale }); return Some(VideoFit { at: (0.5, 0.5), to: (0.5, 0.5), scale });
} }
match raea_sys_facetrack::track(file) { match crate::faces::track(file) {
Ok(t) => t.eyes_at(at).map(|eyes| VideoFit { at: eyes, to: (0.5, 0.38), scale }), Ok(t) => t.eyes_at(at).map(|eyes| VideoFit { at: eyes, to: (0.5, 0.38), scale }),
Err(e) => { Err(e) => {
REFUSED.with(|c| c.borrow_mut().push(e)); REFUSED.with(|c| c.borrow_mut().push(e));
@@ -14,14 +14,14 @@ const RATE: f64 = 4.0;
const SIDE: u32 = 640; const SIDE: u32 = 640;
/// The eyes at each sample, in shares of the picture (None: no face in that sample). /// The eyes at each sample, in shares of the picture (None: no face in that sample).
pub struct Track { pub(crate) struct Track {
every: f64, every: f64,
eyes: Vec<Option<(f64, f64)>>, eyes: Vec<Option<(f64, f64)>>,
} }
impl Track { impl Track {
/// The eyes at `t` seconds: between the samples around it, or the nearest sample with a face. /// The eyes at `t` seconds: between the samples around it, or the nearest sample with a face.
pub fn eyes_at(&self, t: f64) -> Option<(f32, f32)> { pub(crate) fn eyes_at(&self, t: f64) -> Option<(f32, f32)> {
let i = (t / self.every).max(0.0); let i = (t / self.every).max(0.0);
let (a, b) = (i.floor() as usize, i.ceil() as usize); let (a, b) = (i.floor() as usize, i.ceil() as usize);
let got = match (self.eyes.get(a).copied().flatten(), self.eyes.get(b).copied().flatten()) { let got = match (self.eyes.get(a).copied().flatten(), self.eyes.get(b).copied().flatten()) {
@@ -44,7 +44,7 @@ thread_local! {
/// `take`'s face track: TAKE.faces.json when it's there and made from the take as it is now, else made (and kept). /// `take`'s face track: TAKE.faces.json when it's there and made from the take as it is now, else made (and kept).
/// An error says why there's none (no raea-perceive, no face in the take), once per take. /// An error says why there's none (no raea-perceive, no face in the take), once per take.
pub fn track(take: &Path) -> Result<Rc<Track>, String> { pub(crate) fn track(take: &Path) -> Result<Rc<Track>, String> {
if let Some(t) = TRACKS.with_borrow(|m| m.get(take).cloned()) { if let Some(t) = TRACKS.with_borrow(|m| m.get(take).cloned()) {
return t; return t;
} }
+1
View File
@@ -36,6 +36,7 @@ pub use world::*;
// app screens (`<Screen app>`): a component on @raea/ui's react-dom in a raea-runtime-js root of its own // app screens (`<Screen app>`): a component on @raea/ui's react-dom in a raea-runtime-js root of its own
pub mod screen; pub mod screen;
// a take's face track (<Video framing="face">) // a take's face track (<Video framing="face">)
pub(crate) mod faces;
type R<T> = Result<T, String>; type R<T> = Result<T, String>;
-16
View File
@@ -1,16 +0,0 @@
[package]
name = "raea-runtime-review"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "render --review's tiles and sheets: each fixed camera rendered by a child raea in colour and in clay, stitched into two sheets, with cameras.json and review.json"
[dependencies]
# the views, a tile's width and the arguments a tile's render takes
raea-core-review = { path = "../../core/review" }
raea-core-facts = { path = "../../core/facts" }
# each colour tile's exposure
raea-sys-light-meter = { path = "../../systems/light-meter" }
image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1"
-83
View File
@@ -1,83 +0,0 @@
//! `raea render EDIT.tsx --review DIR`'s tiles and sheets (raea-runtime-export's review measures the frame's parts and
//! places the cameras, raea-core-review): each view rendered by a child raea with RAEA_CAMERA, in colour and (with
//! RAEA_CLAY) in clay, its exposure read, the tiles stitched into DIR/colour.png and DIR/clay.png, and DIR/cameras.json
//! and DIR/review.json written: the cameras, each tile's place on the sheets and its exposure, and what that found.
use raea_core_review::{Box3, TILE_W, VIEWS, passed};
use serde_json::{Value, json};
use std::path::Path;
/// A view and its camera (eye, target, field of view); None is the scene's own camera (hero).
pub type View<'a> = (&'a str, Option<([f64; 3], [f64; 3], f64)>);
/// What the tiles are of: the frame, its picture's aspect, its parts' box, and whether it's seen from inside.
pub struct Shot {
pub frame: i64,
pub aspect: f64,
pub parts: Box3,
pub interior: bool,
}
/// The review of `tsx`'s frame from `cams` into `dir_out`; `args` are the render's own (the ones a tile's render
/// takes too are passed on). Answers the render's APPLIED line and what the tiles' exposure found.
pub fn sheets(tsx: &Path, args: &[String], dir_out: &Path, cams: &[View], Shot { frame, aspect, parts: (lo, hi), interior }: Shot) -> Result<String, String> {
let exe = std::env::current_exe().map_err(|e| e.to_string())?;
let rest = passed(args);
let mut tiles = Vec::new();
let mut said = Vec::new();
for (view, cam) in cams {
for mode in ["colour", "clay"] {
let out = dir_out.join(format!("{view}-{mode}.png"));
let mut cmd = std::process::Command::new(&exe);
cmd.arg("render").arg(&tsx).args(&rest).args(["--frame", &frame.to_string(), "-o"]).arg(&out);
// a tile is part of this render: the review keeps the one entry in the project's record (DR3)
cmd.env_remove("RAEA_CAMERA").env_remove("RAEA_CLAY").env("RAEA_RECORD", "off");
if let Some((e, t, f)) = cam {
cmd.env("RAEA_CAMERA", format!("{},{},{},{},{},{},{}", e[0], e[1], e[2], t[0], t[1], t[2], f));
}
if mode == "clay" {
cmd.env("RAEA_CLAY", "1");
}
let run = cmd.output().map_err(|e| format!("--review: {e}"))?;
if !run.status.success() || !out.is_file() {
let text = format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
return Err(format!("--review: the {view} {mode} render failed: {}", text.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("no output")));
}
}
let colour = dir_out.join(format!("{view}-colour.png"));
let (_, ev) = raea_sys_light_meter::exposure::of_pngs(std::slice::from_ref(&colour))?;
// what a tile's exposure found, counted with the render's findings (DR3)
let tile: Vec<raea_core_facts::Finding> = ev["found"].as_array().into_iter().flatten().filter_map(|f| {
raea_core_facts::Finding::of_value(&json!({"check": "exposure", "level": f["level"], "says": format!("{view} tile: {}", f["says"].as_str().unwrap_or("").trim_start_matches("the frame: "))}), "raea render")
}).collect();
raea_core_facts::finding::said(&tile);
said.extend(tile);
tiles.push(json!({"view": view, "colour": format!("{view}-colour.png"), "clay": format!("{view}-clay.png"), "exposure": ev["exposure"],
"camera": cam.map(|(e, t, f)| json!({"eye": e, "target": t, "fov": f}))}));
}
// the sheets: three across, two down, each tile TILE_W wide
let th = (TILE_W as f64 / aspect).round().max(1.0) as u32;
for mode in ["colour", "clay"] {
let mut sheet = image::RgbaImage::from_pixel(TILE_W * 3, th * 2, image::Rgba([0, 0, 0, 255]));
for (i, view) in VIEWS.iter().enumerate() {
let img = image::open(dir_out.join(format!("{view}-{mode}.png"))).map_err(|e| format!("{view}-{mode}.png: {e}"))?.to_rgba8();
let small = image::imageops::resize(&img, TILE_W, th, image::imageops::FilterType::Triangle);
image::imageops::overlay(&mut sheet, &small, (i as u32 % 3 * TILE_W) as i64, (i as u32 / 3 * th) as i64);
}
sheet.save(dir_out.join(format!("{mode}.png"))).map_err(|e| format!("{mode}.png: {e}"))?;
}
for (i, t) in tiles.iter_mut().enumerate() {
t["rect"] = json!([i as u32 % 3 * TILE_W, i as u32 / 3 * th, TILE_W, th]);
}
let cameras: Vec<Value> = tiles.iter().map(|t| json!({"view": t["view"], "camera": t["camera"]})).collect();
std::fs::write(dir_out.join("cameras.json"), serde_json::to_string_pretty(&json!({"frame": frame, "box": {"min": lo, "max": hi}, "interior": interior, "cameras": cameras})).unwrap_or_default()).map_err(|e| e.to_string())?;
let doc = json!({"frame": frame, "sheets": {"colour": "colour.png", "clay": "clay.png"}, "size": [TILE_W * 3, th * 2],
"caption": if interior { "An interior, seen from inside: tiles left to right, top to bottom: hero, front, right, top (under the ceiling), iso, low (0.3 m). Clay: every standard surface light grey and matte." } else { "Tiles left to right, top to bottom: hero, front, right, top, iso, low (0.3 m). Clay: every standard surface light grey and matte." },
"box": {"min": lo, "max": hi}, "tiles": tiles, "found": said});
std::fs::write(dir_out.join("review.json"), serde_json::to_string_pretty(&doc).unwrap_or_default()).map_err(|e| e.to_string())?;
let mut msg = format!("APPLIED review of frame {frame}: {} and {} (hero, front, right, top, iso, low), cameras and exposure in {}", dir_out.join("colour.png").display(), dir_out.join("clay.png").display(), dir_out.join("review.json").display());
for f in &said {
msg.push_str(&format!("\n{}", f.line()));
}
Ok(msg)
}
-249
View File
@@ -1,249 +0,0 @@
# Where a farm run's seconds go, and what each encoder costs and keeps (docs/cloud-render.feature CR27, CR31): the same
# frames of one project rendered on a GPU container sized as the farm's (farm_plan.RESERVED), once to PNGs (no video
# encoder: the picture every encode is scored against) and once through each encoder, timed. From sdk/cloud:
#
# MODAL_PROFILE=raea modal run bench/encode.py --dir ../../bench/rerender --args "render film.tsx --composition cut" --frames 0-299
# ... --encoders x264,soft,nvenc --out bench/results/encode-film.json
# ... --gpu none --cpu 8 --gib 8 the same on a container with no GPU (lavapipe), sized as said: what a piece
# with no 3D costs where nothing waits on a graphics card
#
# Each encoder's row: s (the run's wall time), ms a frame over the run, cores busy on average, the file's MB, SSIM and
# PSNR against the PNGs (all frames, and the darkest tenth of them alone, where an encoder's blocks show), what
# `raea check` says of its picture (the blotching line), raea's own RAEA_TIMES line, and the ffmpeg command raea ran.
# png raea's frames as PNGs: the reference, and a run with no video encoder
# x264 RAEA_MEDIA=ffmpeg: libx264 medium at the quality's CRF on the container's cores (the farm today)
# soft raea's own portable encoder (openh264 at a bitrate): the farm before 11-30
# nvenc RAEA_MEDIA=ffmpeg with h264_nvenc in libx264's place (constant QP at the CRF's number), on the run's own GPU
# An ephemeral app: it never touches the deployed farm.
import json
import os
import sys
import modal
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "deploy", "modal"))
import farm # noqa: E402 the farm's image, so the bench measures what the farm runs
import farm_plan # noqa: E402
app = modal.App("raea-farm-encode-bench", image=farm.image.add_local_python_source("farm"))
CPU, GIB = farm_plan.RESERVED["raea"]
# ffmpeg in the encoder's place: raea's ffmpeg backend names libx264 itself (io/ffmpeg), so the bench swaps the encoder
# where raea calls it. RAEA_BENCH_ENCODER holds the arguments that replace "-c:v libx264 -preset medium -crf N" ({q} is N)
WRAP = r"""#!/usr/bin/env python3
import json, os, sys
a = sys.argv[1:]
said = os.environ.get("RAEA_BENCH_SAID", "/dev/null")
with open(said, "a") as f:
f.write(" ".join(a) + "\n")
enc = json.loads(os.environ.get("RAEA_BENCH_ENCODER") or "null")
if enc and "libx264" in a and "rawvideo" in a:
i = a.index("-c:v")
if "-crf" in a:
j = a.index("-crf") + 2
new = enc["crf"].format(q=a[j - 1])
else:
j = a.index("-bufsize") + 2
new = enc["rate"].format(b=a[a.index("-b:v") + 1], m=a[a.index("-maxrate") + 1], u=a[j - 1])
a = a[:i] + new.split() + a[j:]
with open(said, "a") as f:
f.write("-> " + " ".join(a) + "\n")
os.execv("/usr/bin/ffmpeg", ["ffmpeg", *a])
"""
# what replaces "-c:v libx264 -preset medium" and its rate arguments where raea calls ffmpeg: "crf" when the render
# names a quality ({q} the CRF), "rate" when it doesn't ({b}, {m}, {u}: the bitrate, its ceiling and the buffer)
NV = "-c:v h264_nvenc -preset {p} -tune hq -bf 2 -g 60 -spatial-aq 1 -temporal-aq 1"
ENCODERS = {
"x264": {"RAEA_MEDIA": "ffmpeg"},
"soft": {"RAEA_MEDIA": "soft"},
"nvenc": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": NV.format(p="p5") + " -rc constqp -qp {q}", "rate": NV.format(p="p5") + " -rc vbr -b:v {b} -maxrate {m} -bufsize {u}"})},
"nvenc-p7": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": NV.format(p="p7") + " -rc constqp -qp {q}", "rate": NV.format(p="p7") + " -rc vbr -b:v {b} -maxrate {m} -bufsize {u}"})},
"x264-fast": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": "-c:v libx264 -preset veryfast -crf {q}", "rate": "-c:v libx264 -preset veryfast -b:v {b} -maxrate {m} -bufsize {u}"})},
}
def _sample(stop, rows):
"""What the container's processes are doing while a render runs: every 2 s, each process's name and CPU seconds so
far (ps), so a run's cores can be put to raea's threads or to the ffmpeg children it starts."""
import subprocess
import time
while not stop.is_set():
o = subprocess.run(["ps", "-eLo", "pid,comm,time,args", "--no-headers"], capture_output=True, text=True).stdout
rows.append((time.time(), o))
stop.wait(2)
def _run(cmd, cwd, env, timeout=3600):
import resource
import subprocess
import time
for d in (farm.CACHES["__GL_SHADER_DISK_CACHE_PATH"], farm.CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
u0, t = resource.getrusage(resource.RUSAGE_CHILDREN), time.time()
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **farm.CACHES, **env}, timeout=timeout)
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
return r.returncode, r.stdout + r.stderr, s, round((u1.ru_utime + u1.ru_stime - u0.ru_utime - u0.ru_stime) / max(s, 0.001), 2)
def _score(video, pngs, first, fps, dark):
"""SSIM and PSNR of `video` against the PNGs: over every frame, and over the darkest tenth (`dark`: frame indexes)."""
import re
import subprocess
def one(select):
vf = f"[0:v]{select}format=yuv420p[a];[1:v]{select}format=yuv420p[b];[a][b]ssim;[0:v]{select}format=yuv420p[c];[1:v]{select}format=yuv420p[d];[c][d]psnr"
r = subprocess.run(["ffmpeg", "-hide_banner", "-i", video, "-framerate", str(fps), "-start_number", str(first), "-i", f"{pngs}/frame-%05d.png", "-lavfi", vf, "-f", "null", "-"], capture_output=True, text=True)
s, p = re.search(r"SSIM .*All:([\d.]+)", r.stderr), re.search(r"PSNR .*average:([\d.inf]+)", r.stderr)
return (float(s.group(1)) if s else None, float(p.group(1)) if p and p.group(1) != "inf" else None)
out = dict(zip(("ssim", "psnr"), one("")))
if dark:
sel = "select='" + "+".join(f"eq(n\\,{i})" for i in dark) + "',"
out |= dict(zip(("ssim_dark", "psnr_dark"), one(sel)))
return out
@app.function(gpu="T4", cpu=CPU, memory=GIB * 1024, volumes={farm.ROOT: farm.vol, "/models": farm.models}, timeout=3600)
def measure(folder: bytes, args: list[str], first: int, last: int, encoders: list[str], check: bool = True, media: list | None = None, cpu_only: bool = False, size: tuple = (CPU, GIB), extra: dict | None = None, png: bool = True) -> dict:
import re
import shutil
import subprocess
import tarfile
import io
import farm_media
say = lambda *a: print(*a, flush=True)
# the job's folder on the volume, where the farm's own jobs are: a media link into the cache resolves there
work = f"{farm.JOBS}/bench-{os.environ.get('MODAL_TASK_ID', 'x')}/work"
shutil.rmtree(work, ignore_errors=True)
os.makedirs(work)
tarfile.open(fileobj=io.BytesIO(folder)).extractall(work)
if media:
with open(f"{work}/{farm_media.MANIFEST}", "w") as f:
json.dump({"objects": media}, f)
farm_media.fetch(work, f"{farm.ROOT}/blobs", say)
base = dict(farm.CPU_ENV) if cpu_only else {}
extra = extra or {}
os.makedirs("/tmp/bin", exist_ok=True)
with open("/tmp/bin/ffmpeg", "w") as f:
f.write(WRAP)
os.chmod("/tmp/bin/ffmpeg", 0o755)
path = "/tmp/bin:" + os.environ["PATH"]
at = ",".join(map(str, range(first, last + 1)))
n = last - first + 1
res = {"gpu": "" if cpu_only else farm.kind(), "cores": size[0], "gib": size[1], "raea": farm.RAEA, "frames": n, "args": args,
"has": subprocess.run("ffmpeg -hide_banner -encoders 2>/dev/null | grep -E '264|hevc|av1' | awk '{print $2}'", shell=True, capture_output=True, text=True).stdout.split(),
"nvidia": subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"], capture_output=True, text=True).stdout.strip(), "rows": {}}
# a first run nobody times: the shader caches, the models, the page's fonts
code, out, s, _ = _run(["raea", *args, "--at", f"{first},{first + 1}", "-o", "/tmp/warm"], work, {**base, "PATH": path})
say(f"warm-up: exit {code} in {s:.1f} s", out[-300:] if code else "")
pngs = "/tmp/png"
shutil.rmtree(pngs, ignore_errors=True)
code, out, s, cores = _run(["raea", *args, "--at", at, "-o", pngs], work, {**base, "PATH": path, "RAEA_TIMES": "1"}) if png else (0, "", 0.0, 0.0)
say(f"png: exit {code}, {n} frames in {s:.1f} s, {cores} cores busy")
made = sorted(x for x in os.listdir(pngs) if x.endswith(".png")) if os.path.isdir(pngs) else []
for i, name in enumerate(made): # named by their frame, as the encodes' frames are counted
os.rename(f"{pngs}/{name}", f"{pngs}/t-{first + i:05d}.png")
for i in range(len(made)):
os.rename(f"{pngs}/t-{first + i:05d}.png", f"{pngs}/frame-{first + i:05d}.png")
fps = 30
m = re.search(r"(\d+(?:\.\d+)?) fps", out)
if made:
# each frame's pixels as a hash, and a few frames whole, to hold one container's picture against another's
md5 = subprocess.run(["ffmpeg", "-v", "error", "-framerate", str(fps), "-start_number", str(first), "-i", f"{pngs}/frame-%05d.png", "-pix_fmt", "rgba", "-f", "framemd5", "-"], capture_output=True, text=True).stdout
res["frame_md5"] = [l.split(",")[-1].strip() for l in md5.splitlines() if l and not l.startswith("#")]
res["frame_png"] = {str(first + i): open(f"{pngs}/frame-{first + i:05d}.png", "rb").read() for i in sorted({0, len(made) // 2, len(made) - 1})} if extra.get("BENCH_KEEP") else {}
res["rows"]["png"] = {"code": code, "s": round(s, 2), "ms": round(1000 * s / n, 1), "cores": cores, "frames": len(made), "times": [l for l in out.splitlines() if " ms" in l][-12:], "out": out[-600:] if code else ""}
# the darkest tenth of the frames, by mean luma
dark = []
if made:
import cv2
lum = [(float(cv2.imread(f"{pngs}/frame-{first + i:05d}.png", cv2.IMREAD_GRAYSCALE)[::8, ::8].mean()), i) for i in range(len(made))]
dark = sorted(i for _, i in sorted(lum)[: max(1, len(lum) // 10)])
res["dark_luma"] = round(sorted(lum)[len(dark) - 1][0], 1)
for name in encoders:
env = {**base, "PATH": path, "RAEA_TIMES": "1", "RAEA_STARTUP_TRACE": "1", **extra, "RAEA_BENCH_SAID": f"/tmp/{name}.said", **ENCODERS[name]}
video = f"/tmp/{name}.mp4"
for p in (video, env["RAEA_BENCH_SAID"]):
if os.path.exists(p):
os.remove(p)
import threading
stop, snaps = threading.Event(), []
th = threading.Thread(target=_sample, args=(stop, snaps), daemon=True)
if extra.get("BENCH_DIAG"):
th.start()
code, out, s, cores = _run(["raea", *args, "--at", at, "-o", video], work, env)
stop.set()
row = {"code": code, "s": round(s, 2), "ms": round(1000 * s / n, 1), "cores": cores, "said_ms": (re.search(r"([\d.]+) ms a frame", out) or [None, None])[1],
"times": [l for l in out.splitlines() if " ms" in l or "raea startup" in l][-40:], "out": out[-800:] if code else ""}
if os.path.exists(env["RAEA_BENCH_SAID"]):
calls = [l for l in open(env["RAEA_BENCH_SAID"]).read().splitlines() if not l.startswith("->")]
row["ffmpeg"] = [l for l in open(env["RAEA_BENCH_SAID"]).read().splitlines() if "rawvideo" in l][-2:]
row["ffmpeg_calls"] = len(calls)
row["ffmpeg_decodes"] = len([l for l in calls if " -ss " in f" {l} "])
row["ffmpeg_decode_sample"] = [l[:260] for l in calls if " -ss " in f" {l} "][:6]
if snaps:
# the middle snapshot's processes, and how many distinct ffmpeg pids were seen over the run
pids = {l.split()[0] for _, o in snaps for l in o.splitlines() if " ffmpeg" in l[:40]}
mid = snaps[len(snaps) // 2][1].splitlines()
row["ps_ffmpeg_pids"] = len(pids)
row["ps_mid"] = sorted({" ".join(l.split()[1:3]) + " " + " ".join(l.split()[3:])[:120] for l in mid if l.split()[2] != "00:00:00"})[:40]
if os.path.exists(video):
row["mb"] = round(os.path.getsize(video) / 1e6, 2)
pr = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,codec_name,profile,r_frame_rate", "-of", "csv=p=0", video], capture_output=True, text=True).stdout.strip()
row["probe"] = pr
if made:
row |= _score(video, pngs, first, fps, dark)
if check:
c, o, cs, _ = _run(["raea", "check", video], work, {"PATH": os.environ["PATH"]})
row["check"] = {"code": c, "s": round(cs, 1), "lines": [l.strip() for l in o.splitlines() if re.search(r"blotch|flash|freez|FAIL|PASS|passed|failed", l)][:12]}
res["rows"][name] = row
say(f"{name}: exit {code}, {s:.1f} s, {cores} cores busy, {row.get('mb')} MB, ssim {row.get('ssim')} dark {row.get('ssim_dark')}")
shutil.rmtree(os.path.dirname(work), ignore_errors=True)
return res
@app.local_entrypoint()
def main(dir: str, args: str, frames: str = "0-299", encoders: str = "x264,soft,nvenc", out: str = "", check: bool = True, gpu: str = "T4", cpu: int = CPU, gib: int = GIB, env: str = "", png: bool = True):
import hashlib
import io
import tarfile
a, _, b = frames.partition("-")
# files of 4 MB and more go by hash from the farm's cache, where a box's render put them (server/media.ts
# farmInputs); one the farm doesn't hold fails the run, which says so
media = []
def keep(i):
if i.name.startswith(("./out", "./.git", "./ios")):
return None
if i.isfile() and i.size >= 4 << 20:
h = hashlib.sha256()
with open(os.path.join(dir, i.name), "rb") as f:
for blk in iter(lambda: f.read(1 << 20), b""):
h.update(blk)
media.append({"path": i.name[2:], "oid": h.hexdigest(), "size": i.size})
return None
return i
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as t:
t.add(dir, arcname=".", filter=keep)
fn = measure.with_options(gpu=None if gpu == "none" else gpu, cpu=cpu, memory=gib * 1024)
r = fn.remote(buf.getvalue(), args.split(), int(a), int(b or a), [e for e in encoders.split(",") if e], check, media, gpu == "none", (cpu, gib), dict(kv.split("=", 1) for kv in env.split(",") if kv), png)
for n, b in (r.pop("frame_png", None) or {}).items():
if out:
with open(f"{os.path.splitext(out)[0]}-{int(n):05d}.png", "wb") as f:
f.write(b)
print(json.dumps({**r, "frame_md5": len(r.get("frame_md5") or [])}, indent=2))
if out:
with open(out, "w") as f:
json.dump(r, f, indent=2)
-130
View File
@@ -1,130 +0,0 @@
// One farm job, measured (docs/cloud-render.feature CR27): a folder sent the way a CPU box sends one, its log timed
// from the submit, and what the farm said about it read back as numbers. RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN
// name the farm (~/.config/raea-cloud/farm.env), so the same job runs on the live farm and on a test deploy of it:
//
// node bench/job.ts DIR OUT.json [--gpus N] [--keep FILE] -- render film.tsx --composition cut -o out/film.mp4
//
// OUT.json: wall (s from the submit to the video here, on disk), sent and back (bytes), frames, w, h, frame_ms and
// start_s (the farm's timed first run), runs ([{frames, kind, s}]), join_s, billed_usd, up_s (its containers' life
// in all), cores and peak_gb (the busiest run's), first_s (when the first run of frames had landed), exit.
import { spawn, spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { RaeaCloud } from "../src/index.ts"
/** What a farm job's log says, as numbers: `lines` are [seconds from the submit, the line]. */
export function read(lines: [number, string][]) {
const o: Record<string, unknown> = { runs: [] as { frames: number; kind: string; s: number; at: number }[] }
const num = (s: string) => Number(s)
for (const [at, l] of lines) {
let m: RegExpMatchArray | null
if ((m = l.match(/(\d+) frames at (\d+)x(\d+), ([\d.]+) fps; frame 0 on a (\S+) in ([\d.]+) s/))) Object.assign(o, { frames: num(m[1]), w: num(m[2]), h: num(m[3]), fps: num(m[4]), kind: m[5], probe_s: num(m[6]) })
else if ((m = l.match(/([\d.]+) ms a frame, ([\d.]+) s to start; (\d+) frames left on (\d+) (\S+?)s?(?: with no GPU \(no 3D in it\))?(?: in (\d+) parts)?, about \$([\d.]+)/))) Object.assign(o, { frame_ms: num(m[1]), start_s: num(m[2]), gpus: num(m[4]), parts: num(m[6] ?? m[4]), estimate_usd: num(m[7]) })
else if ((m = l.match(/(\d+) frames on a (\S+) in ([\d.]+) s/))) (o.runs as object[]).push({ frames: num(m[1]), kind: m[2], s: num(m[3]), at })
else if ((m = l.match(/joined .* in ([\d.]+) s/))) Object.assign(o, { join_s: num(m[1]), joined_at: at })
else if ((m = l.match(/billed about \$([\d.]+): (\d+) GPU(?: and (\d+) CPU)? containers up ([\d.]+) s in all(?:; at most ([\d.]+) of (\d+) cores busy and ([\d.]+) of (\d+) GB)?/)))
Object.assign(o, { billed_usd: num(m[1]), containers: num(m[2]), cpu_containers: m[3] ? num(m[3]) : 0, up_s: num(m[4]), cores: m[5] ? num(m[5]) : undefined, reserved_cores: m[6] ? num(m[6]) : undefined, peak_gb: m[7] ? num(m[7]) : undefined, reserved_gb: m[8] ? num(m[8]) : undefined })
else if ((m = l.match(/(\d+) runs kept from an earlier render hold (\d+) of (\d+) frames/))) Object.assign(o, { kept_runs: num(m[1]), kept_frames: num(m[2]) })
else if (l.includes("nothing to draw: every frame is in a run kept")) o.all_kept = true
else if ((m = l.match(/its frames' keys read in ([\d.]+) s/))) Object.assign(o, { keys_s: num(m[1]) })
else if ((m = l.match(/first picture at (\S+)/))) Object.assign(o, { first_picture: m[1], first_picture_at: at })
}
const runs = o.runs as { at: number }[]
if (runs.length) o.first_s = runs[0].at
return o
}
/** The job as a box sends it: server/offload.ts in DIR (its media by hash through the farm's cache, the manifest it
* asks for), the box's own check after it left out. Resolves with the timed lines and the exit code. */
function offload(dir: string, args: string[], gpus: string | undefined, cpus: string | undefined, kept: string | undefined, said: (at: number, l: string) => void): Promise<number> {
const here = path.dirname(new URL(import.meta.url).pathname)
const t0 = performance.now()
const env = { ...process.env, RAEA_REAL: "/usr/bin/true", ...(gpus ? { RAEA_CLOUD_GPUS: gpus } : {}), ...(cpus ? { RAEA_CLOUD_CPUS: cpus } : {}), ...(kept === "0" ? { RAEA_CLOUD_KEPT: "0" } : {}) }
const child = spawn(process.execPath, [path.join(here, "..", "server", "offload.ts"), ...args], { cwd: dir, env, stdio: ["ignore", "pipe", "pipe"] })
let rest = ""
const eat = (b: Buffer) => {
const parts = (rest + b.toString()).split("\n")
rest = parts.pop() ?? ""
for (const l of parts) if (l.trim()) said((performance.now() - t0) / 1000, l)
}
child.stdout.on("data", eat)
child.stderr.on("data", eat)
return new Promise((done) => child.on("close", (code) => done(code ?? 1)))
}
async function main() {
const argv = process.argv.slice(2)
const cut = argv.indexOf("--")
if (cut < 2) throw new Error("usage: node bench/job.ts DIR OUT.json [--gpus N] [--cpus N] [--kept 0] [--keep FILE] [--offload] -- ARGS")
const [dir, outJson, ...flags] = argv.slice(0, cut)
const args = argv.slice(cut + 1)
const flag = (n: string) => (flags.includes(n) ? flags[flags.indexOf(n) + 1] : undefined)
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN
if (!url || !token) throw new Error("set RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN (the farm's)")
if (flags.includes("--offload")) {
const lines: [number, string][] = []
const t0 = performance.now()
const exit = await offload(dir, args, flag("--gpus"), flag("--cpus"), flag("--kept"), (at, l) => {
lines.push([at, l])
console.log(`${at.toFixed(1).padStart(6)} s ${l}`)
})
const wall = (performance.now() - t0) / 1000
const o = args.indexOf("-o")
const video = o >= 0 ? path.resolve(dir, args[o + 1]) : ""
const size = video && existsSync(video) ? statSync(video).size : 0
const sentMb = lines.map(([, l]) => l.match(/\(([\d.]+) MB\) sent/)).find(Boolean)
const res = { args, farm: new URL(url).host, via: "offload", exit, wall: Number(wall.toFixed(1)), sent: sentMb ? Math.round(Number(sentMb[1]) * 1e6) : undefined, ...read(lines), bytes: size, log: lines.map(([t, l]) => `${t.toFixed(1)} ${l}`) }
writeFileSync(outJson, JSON.stringify(res, null, 2))
console.log(`${wall.toFixed(1).padStart(6)} s exit ${exit}; ${JSON.stringify({ ...res, log: undefined, args: undefined })}`)
const keep = flag("--keep")
if (keep && size) spawnSync("cp", [video, keep])
process.exitCode = exit
return
}
const tmp = mkdtempSync(path.join(os.tmpdir(), "raea-farm-bench-"))
try {
const sent = path.join(tmp, "in.tgz")
const pack = spawnSync("tar", ["-czf", sent, "--no-mac-metadata", "--exclude=./out", "--exclude=./.git", "-C", dir, "."], { env: { ...process.env, COPYFILE_DISABLE: "1" }, encoding: "utf8" })
if (pack.status) throw new Error(`the folder didn't pack: ${pack.stderr}`)
const folder = new Uint8Array(readFileSync(sent))
const cloud = new RaeaCloud({ url, token })
const t0 = performance.now()
const now = () => (performance.now() - t0) / 1000
const lines: [number, string][] = []
console.log(`${now().toFixed(1).padStart(6)} s ${(folder.length / 1e6).toFixed(2)} MB to ${new URL(url).host}: raea ${args.join(" ")}`)
const gpus = flag("--gpus")
const { exit, files } = await cloud.job(args, folder, {
as: "gz",
farm: { ...(gpus ? { gpus: Number(gpus) } : {}), ...(flag("--cpus") ? { cpus: Number(flag("--cpus")) } : {}) },
onOutput: (t) =>
t.split("\n").filter(Boolean).forEach((l) => {
lines.push([now(), l])
console.log(`${now().toFixed(1).padStart(6)} s ${l}`)
}),
})
const back = path.join(tmp, "out.tgz")
writeFileSync(back, files)
spawnSync("tar", ["-xzf", back, "-C", tmp])
const wall = now()
const o = args.indexOf("-o")
const video = o >= 0 ? path.join(tmp, args[o + 1]) : ""
const probe = video ? spawnSync("ffprobe", ["-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,width,height:format=size", "-of", "json", video], { encoding: "utf8" }) : null
let got: Record<string, unknown> = {}
try {
const j = JSON.parse(probe?.stdout || "{}")
got = { got_frames: Number(j.streams?.[0]?.nb_read_frames), got_w: j.streams?.[0]?.width, got_h: j.streams?.[0]?.height, bytes: Number(j.format?.size) }
} catch {}
const res = { args, farm: new URL(url).host, exit, wall: Number(wall.toFixed(1)), sent: folder.length, back: files.length, ...read(lines), ...got, log: lines.map(([t, l]) => `${t.toFixed(1)} ${l}`) }
writeFileSync(outJson, JSON.stringify(res, null, 2))
console.log(`${wall.toFixed(1).padStart(6)} s exit ${exit}; ${JSON.stringify({ ...res, log: undefined, args: undefined })}`)
const keep = flag("--keep")
if (keep && video) spawnSync("cp", [video, keep])
process.exitCode = exit
} finally {
rmSync(tmp, { recursive: true, force: true })
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === new URL(import.meta.url).pathname) await main()
-98
View File
@@ -1,98 +0,0 @@
# A Linux raea built on Modal from a source folder, into the farm's volume (/farm/builds/NAME): how an engine change is
# measured on a test farm before a release carries it (docs/cloud-render.feature CR28). The farm's image installs the
# released raea, so without this an engine change couldn't be timed there at all. A test farm deployed with
# RAEA_FARM_BUILD=NAME runs this build's raea, with the released one's own files (share/raea) as its home:
#
# git archive TAG | tar -x -C SRC # the release's source; put the change's files over it
# MODAL_PROFILE=raea modal run deploy/modal/build.py --src SRC --name NAME
# RAEA_FARM_APP=raea-farm-m RAEA_FARM_BUILD=NAME modal deploy deploy/modal/farm.py
#
# The source's file times are kept (git archive gives every file its commit's), and cargo's registry, target folder
# and source are kept as one tar each on a volume of their own and unpacked onto the container's disk, so a second
# build compiles only the crates whose files changed. (Left as folders on the volume, cargo read the crates index one
# file at a time, about 4 a second: 13 min before it compiled anything, 11-30.)
import io
import os
import subprocess
import tarfile
import time
import modal
RUST = "1.99.1" # rust-toolchain.toml's
# release.yml's "Linux libraries", and what cargo's build scripts call
LIBS = ["build-essential", "pkg-config", "cmake", "ninja-build", "nasm", "clang", "git", "curl", "ca-certificates", "python3",
"libxkbcommon-dev", "libxkbcommon-x11-dev", "libasound2-dev", "libfontconfig1-dev", "libvulkan-dev", "libudev-dev", "libssl-dev"]
image = (
# the farm image's Debian, so the build links against the libraries it runs with
modal.Image.from_registry("debian:trixie-slim", add_python="3.12")
.apt_install(*LIBS)
.run_commands(f"curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain {RUST}")
.env({"PATH": "/root/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "CARGO_HOME": "/work/cargo", "CARGO_TARGET_DIR": "/work/target",
"RUSTUP_HOME": "/root/.rustup",
# no debug info: the farm's copy was stripped anyway (2.8 GB with it), and the link is far shorter
"CARGO_PROFILE_DIST_DEBUG": "0"})
)
KEPT = ("cargo", "target", "src")
app = modal.App("raea-farm-build", image=image)
farm = modal.Volume.from_name("raea-farm", create_if_missing=True, version=2)
cache = modal.Volume.from_name("raea-build", create_if_missing=True, version=2)
# (the target folder on the container's own disk, not the volume; Modal's smallest disk request is 512 GiB, so the default)
@app.function(cpu=32, memory=64 * 1024, timeout=4 * 3600, volumes={"/farm": farm, "/cache": cache})
def build(src: bytes, name: str, features: str) -> dict:
t = time.time()
os.makedirs("/work/src", exist_ok=True)
for d in KEPT:
if os.path.exists(f"/cache/{d}.tar"):
subprocess.run(["tar", "-xf", f"/cache/{d}.tar", "-C", "/work"], check=True)
print(f"build: the last build's folders unpacked in {time.time() - t:.0f} s", flush=True)
# over the last build's source, in place: an unchanged file keeps its time, so its crate isn't compiled again
with tarfile.open(fileobj=io.BytesIO(src), mode="r:gz") as tar:
tar.extractall("/work/src", filter="tar")
cmd = ["cargo", "build", "--profile", "dist", "--locked", "-p", "raea-cli", "--bin", "raea", "--no-default-features", "--features", features]
print("build:", " ".join(cmd), flush=True)
code = subprocess.run(cmd, cwd="/work/src").returncode
out = f"/farm/builds/{name}"
made = {}
if not code:
os.makedirs(out, exist_ok=True)
for f in ("raea", "libraea_bundle.so"):
p = f"/work/target/dist/{f}"
# without its debug info, as the release's is (2.8 GB with it, read from the volume at every container's start)
subprocess.run(["strip", "--strip-debug", "-o", f"{out}/{f}", p], check=True)
made[f] = os.path.getsize(f"{out}/{f}")
said = subprocess.run([f"{out}/raea", "--version"], capture_output=True, text=True, env={**os.environ, "RAEA_HOME": "/nonexistent"})
made["version"] = (said.stdout + said.stderr).strip()[-200:]
farm.commit()
for d in KEPT:
subprocess.run(["tar", "-cf", f"/cache/{d}.tar.part", "-C", "/work", d], check=True)
os.replace(f"/cache/{d}.tar.part", f"/cache/{d}.tar")
cache.commit()
return {"code": code, "s": round(time.time() - t), "out": out, **made}
@app.function(cpu=2, memory=8 * 1024, timeout=1800, volumes={"/farm": farm})
def slim(name: str) -> dict:
"""A build already in the volume, without its debug info."""
out = {}
for f in ("raea", "libraea_bundle.so"):
p = f"/farm/builds/{name}/{f}"
subprocess.run(["strip", "--strip-debug", p], check=True)
out[f] = os.path.getsize(p)
farm.commit()
return out
@app.local_entrypoint()
def main(src: str, name: str, features: str = ""):
if not features:
features = subprocess.run(["bash", "tools/bevy-plugins.sh", "features", "sdk/raea/bench/bevy-plugins"], cwd=src, capture_output=True, text=True).stdout.strip().splitlines()[-1]
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz", compresslevel=3) as tar:
tar.add(src, arcname=".")
print(f"build: {len(buf.getvalue()) / 1e6:.0f} MB of source, features {features}")
print(build.remote(buf.getvalue(), name, features))
+42 -165
View File
@@ -32,7 +32,6 @@ import re
import resource import resource
import shutil import shutil
import subprocess import subprocess
import threading
import time import time
import uuid import uuid
@@ -80,12 +79,6 @@ GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit;
# one job's GPUs unless it asks for more: a 1,150-frame cut took all 10 (each drawing 10-20 s), so every other render in # one job's GPUs unless it asks for more: a 1,150-frame cut took all 10 (each drawing 10-20 s), so every other render in
# the workspace queued behind it with nothing said (11-30, StreetTalk's three agents); 4 lets two or three render at once # the workspace queued behind it with nothing said (11-30, StreetTalk's three agents); 4 lets two or three render at once
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4")) JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
# the containers with no GPU a job's video with no 3D is drawn on at once (raea_cpu_run), and the farm's in all: no
# workspace limit holds these back as it does GPUs
# 32 since 12-01: at 8, a 34 s ad's 16 parts ran two after another on each container, 53 s of a 104 s render, and
# at 16 a 35 s one still drew for 73 s beside another job; the containers' seconds, and so the bill, are the same
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "32"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "128"))
ROOT = "/farm" ROOT = "/farm"
JOBS = f"{ROOT}/jobs" JOBS = f"{ROOT}/jobs"
@@ -145,10 +138,7 @@ image = (
# bitrate: openh264's near-blacks stepped into blocks even at master's 37.7 Mbps, raea check's blotching # bitrate: openh264's near-blacks stepped into blocks even at master's 37.7 Mbps, raea check's blotching
# failed every Dutch cut, and its agent re-encoded each one with x264 after the render (11-30) # failed every Dutch cut, and its agent re-encoded each one with x264 after the render (11-30)
"RAEA_MEDIA": "ffmpeg"}) "RAEA_MEDIA": "ffmpeg"})
# a test farm's own raea (deploy/modal/build.py: an engine change built into the volume, timed here before a release .add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene")
# carries it): RAEA_FARM_BUILD=NAME at the deploy. The live farm has none, and runs the release above
.env({"RAEA_FARM_BUILD": os.environ.get("RAEA_FARM_BUILD", "")})
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
) )
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image) app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
@@ -171,8 +161,6 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
# the scene reader's models, loaded once a container (/v1/scene) # the scene reader's models, loaded once a container (/v1/scene)
SCENE = None SCENE = None
# one reading at a time a container: the models aren't safe to run from two threads
SCENE_LOCK = threading.Lock()
# when this container's Python started, for the job's bill (farm_plan.Bill) # when this container's Python started, for the job's bill (farm_plan.Bill)
BOOTED = time.time() BOOTED = time.time()
@@ -192,10 +180,6 @@ def run(cmd, cwd=None, env=None, timeout=6 * 3600):
t = time.time() t = time.time()
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]): for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True) os.makedirs(d, exist_ok=True)
build = os.environ.get("RAEA_FARM_BUILD")
if build and cmd[0] == "raea":
# the build's raea, with the release's own files as its home
cmd, env = [f"{ROOT}/builds/{build}/raea", *cmd[1:]], {"RAEA_HOME": "/opt/raea/share/raea", **(env or {})}
u0 = resource.getrusage(resource.RUSAGE_CHILDREN) u0 = resource.getrusage(resource.RUSAGE_CHILDREN)
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **CACHES, **(env or {})}, timeout=timeout) r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **CACHES, **(env or {})}, timeout=timeout)
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
@@ -233,10 +217,6 @@ class Log:
# a GPU stays up this long after its last run, billed (farm_plan.SCALEDOWN): at 60 s, the farm's jobs of 11-17 billed # a GPU stays up this long after its last run, billed (farm_plan.SCALEDOWN): at 60 s, the farm's jobs of 11-17 billed
# about five times their GPUs' working seconds # about five times their GPUs' working seconds
SCALEDOWN = 2 SCALEDOWN = 2
# a container with no GPU stays up this long: an agent renders its cuts one after another and each again after an
# edit, and at 2 s every render's containers started cold, about 20 s of a 54 s draw (12-01). A minute of 16 idle ones
# is about $0.06, which a job's own bill (farm_plan.Bill) leaves out: the next job may be the one that uses it
CPU_SCALEDOWN = 60
def on(gpus, job): def on(gpus, job):
@@ -250,85 +230,24 @@ def on(gpus, job):
return dict(gpu=gpus, cpu=cpu, memory=gib * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN) return dict(gpu=gpus, cpu=cpu, memory=gib * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN)
def reserved(job):
import sys
if HERE not in sys.path:
sys.path.insert(0, HERE)
import farm_plan
return farm_plan.RESERVED[job]
farm_cpu = reserved("cpu")
def raea_path():
"""The raea a job runs: a test farm's build (RAEA_FARM_BUILD), else the release in the image"""
build = os.environ.get("RAEA_FARM_BUILD")
return f"{ROOT}/builds/{build}/raea" if build else shutil.which("raea") or "/usr/local/bin/raea"
def kind(): def kind():
"""This container's GPU by its price list name (prices.py), for the planner's estimate; "CPU" with none.""" """This container's GPU by its price list name (prices.py), for the planner's estimate."""
import prices import prices
try: name = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True).stdout
name = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True).stdout
except FileNotFoundError:
return "CPU"
# a GPU whose name isn't in the price list is still a GPU ("", which the planner prices as its fallback GPU): 11-30,
# `or "CPU"` here priced one of a GPU job's containers as a CPU's
return prices.kind_of(name) return prices.kind_of(name)
def work_ms(out):
"""What raea's own clocks (RAEA_TIMES) say a run's frames took in all, ms: React, the page recorded and collected,
and raea-render's pass (the clips read, the draw, the encode). None when the run didn't say."""
a = re.search(r"raea times: react (\d+) ms, page recorded and submitted (\d+) ms, page collected and stored (\d+) ms", out)
b = re.search(r"raea times: raea-render's render[^\n]*? (\d+) ms", out)
return sum(map(int, a.groups())) + int(b.group(1)) if a and b else None
@app.function(**on(RAEA_GPUS, "raea")) @app.function(**on(RAEA_GPUS, "raea"))
def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict: def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False) -> dict:
"""raea ARGS in the job's folder. With `frames`: those frames to the job's frames/ folder, from frame `first` on, """raea ARGS in the job's folder. With `frames`: those frames to the job's frames/ folder, from frame `first` on,
as one H.264 run (frames/run-FIRST.mp4, joined by the coordinator without encoding again) when `video`, else PNGs. as one H.264 run (frames/run-FIRST.mp4, joined by the coordinator without encoding again) when `video`, else PNGs.
With `probe`: frame 0 and the piece's length, size and rate (its manifest). One function for all three, so the With `probe`: frame 0 and the piece's length, size and rate (its manifest). One function for all three, so the
container that rendered frame 0 is warm for the next run. With `nv` (a piece with 3D in it, which keeps its GPU): container that rendered frame 0 is warm for the next run."""
NVIDIA's encoder and decoder in place of libx264 and ffmpeg's own (RAEA_NV, CR34)."""
return raea_frames(id, args, frames, first, probe, video, {"RAEA_NV": "1"} if nv else None)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=CPU_SCALEDOWN)
def raea_cpu_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict:
"""raea_run on a container with no GPU (lavapipe draws), for a video with no 3D in it: the planner sends those
here after frame 0 (farm_plan.raea_render), and a run that fails here or has 3D in it goes back to a GPU."""
return raea_frames(id, args, frames, first, probe, video, CPU_ENV)
@app.function(cpu=8, memory=8 * 1024, volumes={ROOT: vol}, timeout=3600, max_containers=CPUS, scaledown_window=SCALEDOWN)
def raea_proxy(src: str, dest: str, w: int, h: int, matrix: str) -> dict:
"""One clip's copy at the size a job draws it (farm_proxy.py), written beside the others and kept by hash"""
import farm_proxy
vol.reload()
os.makedirs(os.path.dirname(dest), exist_ok=True)
part = f"{dest}.part-{uuid.uuid4().hex[:8]}{os.path.splitext(dest)[1]}"
code, out, s = run(farm_proxy.command(src, part, w, h, matrix))
if not code:
os.replace(part, dest)
vol.commit()
elif os.path.exists(part):
os.remove(part)
return {"code": code, "out": out[-1000:], "s": s}
def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=None):
vol.reload() vol.reload()
work = f"{JOBS}/{id}/work" work = f"{JOBS}/{id}/work"
if probe: if probe:
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work, env=env) code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work)
m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {} m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {}
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()} return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()}
if frames is None: if frames is None:
@@ -343,7 +262,7 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
# the run's own manifest (its frames, each sound cut to them): the coordinator joins the runs' into the render's # the run's own manifest (its frames, each sound cut to them): the coordinator joins the runs' into the render's
# (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch) # (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch)
man = f"/tmp/run-{first:05d}.json" man = f"/tmp/run-{first:05d}.json"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work, env={**(env or {}), "RAEA_TIMES": "1"}) code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work)
if os.path.exists(seg): if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4") shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit() vol.commit()
@@ -352,9 +271,9 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
m = json.load(open(man)) m = json.load(open(man))
except Exception: except Exception:
m = None m = None
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "first": first, "ms": float(ms.group(1)) if ms else None, "work_ms": work_ms(out), "kind": kind(), "manifest": m, **life()} return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "ms": float(ms.group(1)) if ms else None, "kind": kind(), "manifest": m, **life()}
tmp = f"/tmp/{uuid.uuid4().hex}" tmp = f"/tmp/{uuid.uuid4().hex}"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp], cwd=work, env=env) code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp], cwd=work)
# raea names --at's stills in order (frame-00000.png is the first frame asked for), beside its manifest # raea names --at's stills in order (frame-00000.png is the first frame asked for), beside its manifest
made = sorted(n for n in os.listdir(tmp) if re.fullmatch(r"frame-\d+\.png", n)) if os.path.isdir(tmp) else [] made = sorted(n for n in os.listdir(tmp) if re.fullmatch(r"frame-\d+\.png", n)) if os.path.isdir(tmp) else []
# a frame's time from when the stills were written (raea's stills path doesn't say it), the start excluded # a frame's time from when the stills were written (raea's stills path doesn't say it), the start excluded
@@ -365,7 +284,7 @@ def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=No
if frames[i] >= first: if frames[i] >= first:
shutil.move(os.path.join(tmp, name), f"{dest}/frame-{frames[i]:05d}.png") shutil.move(os.path.join(tmp, name), f"{dest}/frame-{frames[i]:05d}.png")
vol.commit() vol.commit()
return {"code": code, "out": out[-2000:], "s": s, "frames": len(made), "first": first, "ms": ms, "kind": kind(), **life()} return {"code": code, "out": out[-2000:], "s": s, "frames": len(made), "ms": ms, "kind": kind(), **life()}
BLENDER_SETUP = """ BLENDER_SETUP = """
@@ -432,20 +351,11 @@ def coordinate(id: str, args: list[str], opts: dict):
vol.commit() vol.commit()
before = snapshot(work) before = snapshot(work)
try: try:
# a video's frames' keys (farm_keys.py): its runs kept by them under the raea that drew them (a release's code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload)
# version and the build's own file, so a new engine starts a store of its own; kept=0 draws every frame), and
# its clips read from copies at the size they're drawn (farm_proxy.py, made on containers with no GPU)
exe = os.path.realpath(raea_path())
st = os.stat(exe)
opts = {**opts, "keys": f"{ROOT}/kept", "raea": f"{exe}:{st.st_size}:{int(st.st_mtime)}", "proxies": f"{ROOT}/proxies", "proxy_commit": vol.commit,
"proxy_make": lambda todo: raea_proxy.starmap(todo, order_outputs=False, return_exceptions=True)}
code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload, raea_cpu_run if opts.get("cpus") else None)
except Exception as e: # the job's own failure, said in its log; the farm goes on except Exception as e: # the job's own failure, said in its log; the farm goes on
log(f"raea farm: {e!r}", err=True) log(f"raea farm: {e!r}", err=True)
code = 1 code = 1
t_end = [time.time()]
vol.commit() vol.commit()
t_end.append(time.time())
# what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a # what the job's GPU containers committed (a whole render's stills, its folder output) is only seen here after a
# reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20). # reload: without it a render to a folder came back empty while a joined .mp4, written here, came back (11-20).
# Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again, # Another job's open files in this coordinator refuse a reload (ConflictError, 11-21: a 500 for the box): try again,
@@ -459,9 +369,7 @@ def coordinate(id: str, args: list[str], opts: dict):
log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True) log(f"raea farm: the volume wouldn't reload ({e}); returning what this container sees", err=True)
else: else:
time.sleep(pause) time.sleep(pause)
t_end.append(time.time())
after = snapshot(work) after = snapshot(work)
t_end.append(time.time())
changed = [p for p, v in after.items() if before.get(p) != v] changed = [p for p, v in after.items() if before.get(p) != v]
if opts.get("media"): if opts.get("media"):
# the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out # the job's media stays here until the box names where in R2 it goes (POST media); the rest comes back in /out
@@ -473,66 +381,10 @@ def coordinate(id: str, args: list[str], opts: dict):
with open(f"{JOBS}/{id}/changed.txt", "w") as f: with open(f"{JOBS}/{id}/changed.txt", "w") as f:
f.write("".join(p + "\n" for p in changed)) f.write("".join(p + "\n" for p in changed))
shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True) shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)
t_end.append(time.time())
vol.commit() vol.commit()
t_end.append(time.time())
# where a job's end goes, said when it's slow (12-01: 17-60 s between the join and the box hearing it's done)
if t_end[-1] - t_end[0] > 5:
d = [b - a for a, b in zip(t_end, t_end[1:])]
log(f"raea farm: the job's end took {sum(d):.0f} s: saving {d[0]:.1f} s, reloading {d[1]:.1f} s, listing what changed {d[2]:.1f} s, clearing its frames {d[3]:.1f} s, saving again {d[4]:.1f} s")
log.end(code) log.end(code)
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
def read_scenes(frames):
"""Each base64 JPEG's scene (farm_scene.Scene.read and its seams), None for one that isn't a picture"""
import base64
import cv2
import numpy as np
import farm_scene
global SCENE
with SCENE_LOCK:
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return out
# A cut's frames went through the API's one core one after another, inside its event loop: 70 frames of a 35 s ad took
# 37-47 s, and for that long every other call waited (a render's start 48 s, /v1/health 41 s, each job's follow; 12-01).
# More than SCENE_HERE frames are shared out to these, SCENE_PART each; fewer are read in the API on a thread.
SCENE_HERE = 4
SCENE_PART = 6
@app.function(cpu=2, memory=4096, timeout=600, max_containers=CPUS, scaledown_window=60)
def scene_run(frames: list[str]) -> list:
return read_scenes(frames)
@app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600) @app.function(cpu=1, memory=4096, volumes={ROOT: vol}, secrets=[secret, words_secret], timeout=3600)
@modal.concurrent(max_inputs=32) @modal.concurrent(max_inputs=32)
@modal.asgi_app() @modal.asgi_app()
@@ -617,6 +469,19 @@ def api():
# cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono, # cloud's library index uses (apps/app host/library/words.ts) hears it here. The body is one MP3 piece (16 kHz mono,
# at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give # at most 10 minutes; the box cuts the pieces), the answer its words in the piece's own seconds. 11-25, Shane: "give
# it whatever we use for indexing and libraries and sync", so agents check the words their cuts say. # it whatever we use for indexing and libraries and sync", so agents check the words their cuts say.
def seams(g):
"""a split screen's seams: rows (h) or columns (v) where the picture jumps across nearly all of the frame, as a
cut between two pictures does and nothing filmed does (a caption's box spans part of it, a horizon is soft)"""
import numpy as np
found = []
for axis, d in (("h", np.abs(np.diff(g, axis=0))), ("v", np.abs(np.diff(g, axis=1)).T)):
n = d.shape[0]
share = (d > 24).mean(axis=1)
for i in range(int(n * 0.08), int(n * 0.92)):
if share[i] > 0.7 and share[i] >= share[max(i - 1, 0)] and share[i] >= share[min(i + 1, n - 1)]:
found.append([axis, i + 1, round(float(share[i]), 2)])
return found
@web.post("/v1/scene") @web.post("/v1/scene")
async def scene(req: Request): async def scene(req: Request):
@@ -625,6 +490,11 @@ def api():
(each face [x, y, w, h, "face", score]), a grid of where people are, and its things (each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts (COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
[x, y, w, h, "the text", score], in that frame's pixels""" [x, y, w, h, "the text", score], in that frame's pixels"""
import base64
import cv2
import numpy as np
import farm_scene
check(req) check(req)
body = await req.json() body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None frames = body.get("frames") if isinstance(body, dict) else None
@@ -632,11 +502,18 @@ def api():
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}') raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400: if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call") raise HTTPException(413, "at most 400 frames a call")
if len(frames) <= SCENE_HERE: global SCENE
out = await asyncio.to_thread(read_scenes, frames) if SCENE is None:
else: SCENE = farm_scene.Scene()
parts = [frames[i:i + SCENE_PART] for i in range(0, len(frames), SCENE_PART)] out = []
out = [r async for part in scene_run.map.aio(parts) for r in part] for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out} return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
@web.post("/v1/words") @web.post("/v1/words")
@@ -680,7 +557,7 @@ def api():
if not isinstance(args, list) or not all(isinstance(a, str) for a in args): 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") raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
q = req.query_params 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), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
id = str(uuid.uuid4()) id = str(uuid.uuid4())
work = f"{JOBS}/{id}/work" work = f"{JOBS}/{id}/work"
async with gate.use(): async with gate.use():
-148
View File
@@ -1,148 +0,0 @@
# A video's runs kept by what their frames draw (docs/cloud-render.feature CR30): `raea render --keys` says each frame's
# key with nothing drawn, and a run a job drew is kept on the farm's volume under its frames' keys. The next job of the
# piece draws only the frames no kept run holds: a caption edited in one shot draws that shot's runs again, a change
# to the sound alone draws none (the sound is made again and joined to the kept pictures).
#
# read(...) the piece's keys, read on the coordinator's CPU: None when this raea has no --keys
# base(...) what a kept run is only good under: the raea that drew it, the render's arguments, the
# picture's size and rate, and every file in the job that isn't sound, by its content
# cover(store, keys) (hits, gaps): the kept runs whose frames' keys are the piece's at the same frames, and
# the stretches of frames left to draw
# put(store, keys, ...) a run just drawn, kept
#
# A key names files, it doesn't read them, and a frame's picture hangs on the page's styles and the engine too: all of
# that is in `base`, so a changed clip, font, stylesheet or raea starts a store of its own. Pieces with 3D in them
# aren't kept (a frame's picture can hang on the frames before it: physics, particles, a path tracer's light).
import hashlib
import json
import os
import re
import shutil
import time
SOUND = set("mp3 wav aiff aif flac m4a ogg opus caf".split())
# the piece's code (the keys hold what of it reaches the picture), and what a job leaves behind. A .json the code
# imports is code too (a caption's words reach the page as text); one it doesn't is a file something may read by path
CODE = set("tsx ts jsx js mjs".split())
SKIP = CODE | set("md lock log".split())
IMPORT = re.compile(r"""(?:from|import|require\()\s*["']([^"']+\.json)["']""")
KEEP_DAYS = 14
NAME = re.compile(r"(\d+)-(\d+)-([0-9a-f]{32})\.mp4")
def read(args, work, run, env, path):
"""{length, width, height, fps, has3d, keys, sounds} and the seconds it took, or (None, s) when raea didn't say"""
code, _, s = run(["raea", *args, "--keys", path, "-o", "/tmp/keys.mp4"], cwd=work, env=env)
try:
k = json.load(open(path)) if not code else None
except Exception:
k = None
return (k if k and len(k.get("keys") or []) == k.get("length") else None), s
def files(work):
"""Every file of the job a picture could hang on that the keys don't hold, as [path, content]: a link into the
farm's cache by the hash it's named for, anything else by its own."""
out, seen, imported = [], [], set()
for dirpath, dirs, names in os.walk(work):
dirs[:] = [d for d in dirs if d not in ("out", "node_modules", ".git", ".raea")]
for n in names:
p = os.path.join(dirpath, n)
ext = n.rsplit(".", 1)[-1].lower() if "." in n else ""
if ext in CODE and os.path.isfile(p):
with open(p, errors="replace") as f:
imported |= {os.path.normpath(os.path.join(dirpath, m)) for m in IMPORT.findall(f.read())}
seen.append((p, ext))
for p, ext in seen:
if True:
if ext in SOUND or ext in SKIP or not os.path.isfile(p) or (ext == "json" and os.path.normpath(p) in imported):
continue
real = os.path.realpath(p)
oid = os.path.basename(real)
if not (os.path.islink(p) and len(oid) == 64):
h = hashlib.sha256()
with open(p, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""):
h.update(b)
oid = h.hexdigest()
out.append([os.path.relpath(p, work), oid])
return sorted(out)
def base(raea, args, k, work):
said = json.dumps([raea, args, k["width"], k["height"], k["fps"], k["length"], files(work)])
return hashlib.sha256(said.encode()).hexdigest()[:32]
def of(keys, first, n):
return hashlib.sha256("\n".join(keys[first : first + n]).encode()).hexdigest()[:32]
def cover(store, keys):
"""The kept runs that hold this piece's frames, longest first where two overlap, and the frames left."""
kept = []
for name in os.listdir(store) if os.path.isdir(store) else []:
m = NAME.fullmatch(name)
if m and int(m[1]) + int(m[2]) <= len(keys) and of(keys, int(m[1]), int(m[2])) == m[3]:
kept.append((int(m[1]), int(m[2]), os.path.join(store, name)))
hits, taken = [], [False] * len(keys)
for first, n, path in sorted(kept, key=lambda r: (-r[1], r[0])):
if not any(taken[first : first + n]):
taken[first : first + n] = [True] * n
hits.append((first, n, path))
gaps, f = [], 0
while f < len(keys):
if taken[f]:
f += 1
continue
e = f
while e + 1 < len(keys) and not taken[e + 1]:
e += 1
gaps.append((f, e))
f = e + 1
return sorted(hits), gaps
def take(hits, frames_dir):
"""The kept runs into the job's frames, as its own runs lie there; each one's manifest, as a run's result"""
os.makedirs(frames_dir, exist_ok=True)
got = []
for first, n, path in hits:
shutil.copyfile(path, f"{frames_dir}/run-{first:05d}.mp4")
os.utime(path)
try:
m = json.load(open(path[:-4] + ".json"))
except Exception:
m = None
got.append({"code": 0, "first": first, "frames": n, "manifest": m, "kept": True})
return got
def put(store, keys, results, frames_dir):
"""The runs a job drew, kept under their frames' keys; stores no job has touched in KEEP_DAYS go."""
os.makedirs(store, exist_ok=True)
for r in results:
src = f"{frames_dir}/run-{r.get('first', 0):05d}.mp4"
if r.get("code") or r.get("kept") or not r.get("frames") or not os.path.exists(src):
continue
to = f"{store}/{r['first']}-{r['frames']}-{of(keys, r['first'], r['frames'])}"
shutil.copyfile(src, to + ".part")
os.replace(to + ".part", to + ".mp4")
with open(to + ".json", "w") as f:
json.dump(r.get("manifest"), f)
os.utime(store)
root, old = os.path.dirname(store), time.time() - KEEP_DAYS * 86400
for d in os.listdir(root):
p = os.path.join(root, d)
if p != store and os.path.isdir(p) and os.stat(p).st_mtime < old:
shutil.rmtree(p, ignore_errors=True)
def spans(gaps, n0, parts):
"""The frames left after the timed run's first n0 (of the first gap), as (first, last) stretches, and each one's
share of `parts` runs by its length (one at least)."""
rest = [(a + (n0 if i == 0 else 0), b) for i, (a, b) in enumerate(gaps)]
rest = [(a, b) for a, b in rest if a <= b]
left = sum(b - a + 1 for a, b in rest)
return [(a, b, max(1, round(parts * (b - a + 1) / left))) for a, b in rest]
+45 -176
View File
@@ -8,9 +8,6 @@ import os
import re import re
import shutil import shutil
import threading import threading
import farm_keys
import farm_proxy
import time import time
import prices import prices
@@ -90,23 +87,16 @@ def gpus_for(frames, frame_s, start_s, most):
# a GPU takes up to this many parts of a long job, one after another from the job's queue, so a slow card (an L4 among # a GPU takes up to this many parts of a long job, one after another from the job's queue, so a slow card (an L4 among
# L40Ss) ends up drawing fewer frames instead of holding up the job # L40Ss) ends up drawing fewer frames instead of holding up the job
PARTS = 4 PARTS = 4
# containers with no GPU are all the same machine, so a queue only evens out frames that cost more in one stretch than
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
CPU_PARTS = 2
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
PART_START = 5.0
def parts_per_gpu(frames, k, frame_s, start_s, most=PARTS): def parts_per_gpu(frames, k, frame_s, start_s):
"""How many parts each of `k` containers takes from the queue: the most (up to `most`) that keep a part's own start """How many parts each of `k` GPUs takes from the queue: the most (up to PARTS) that keep a part's own start
(start_s, more than a warm one needs) at most SHARE of the part. Above 1 only when the limit capped `k`.""" (start_s, more than a warm GPU needs) at most SHARE of the part. Above 1 only when the GPU limit capped `k`."""
if k <= 0 or frame_s <= 0: if k <= 0 or frame_s <= 0:
return 1 return 1
least = start_s * (1 - SHARE) / SHARE / frame_s # the frames a part needs for its start to be worth it least = start_s * (1 - SHARE) / SHARE / frame_s # the frames a part needs for its start to be worth it
m = 1 m = 1
while m < most and frames / (k * (m + 1)) >= least: while m < PARTS and frames / (k * (m + 1)) >= least:
m += 1 m += 1
return m return m
@@ -128,18 +118,11 @@ def runs(first, last, k, warm=0):
# What a GPU container reserves beside its GPU, billed whether used or not; a run that takes more is billed for what # What a GPU container reserves beside its GPU, billed whether used or not; a run that takes more is billed for what
# it takes (Modal has no limit set here), so these are floors, not caps. raea's were 4 cores and 16 GiB until 11-29, # it takes (Modal has no limit set here), so these are floors, not caps. raea's were 4 cores and 16 GiB until 11-29,
# when a 1080p cut measured 1.4 cores busy and 2.7 GB (the job's last line says each job's); Blender's is unmeasured. # when a 1080p cut measured 1.4 cores busy and 2.7 GB (the job's last line says each job's); Blender's is unmeasured.
# "cpu" is a container with no GPU (farm.py's raea_cpu_run), for a video with no 3D in it: on 60 frames of a 1080x1920 RESERVED = {"raea": (2, 8), "blender": (4, 16)}
# ad cut from 4K footage a T4 container took 11.1 s with 2.5 cores busy and 8 cores alone took 13.9 s with 4.7 busy
# (11-30), the same picture at SSIM 0.9999, for about half the price a frame.
RESERVED = {"raea": (2, 8), "blender": (4, 16), "cpu": (4, 8)}
CPU = "CPU" # a container with no GPU, as a run's kind
def price(kind, seconds, cpu=None, memory_gib=None, busy=0.0): def price(kind, seconds, cpu=RESERVED["raea"][0], memory_gib=RESERVED["raea"][1]):
"""What `seconds` of a container of `kind` cost: its GPU, its memory, and the cores it reserves or, when it kept return prices.cost(kind, cpu=cpu, memory_gib=memory_gib, seconds=seconds)
more than that busy, those (Modal bills a container's use above what it reserves)."""
c, g = RESERVED["cpu" if kind == CPU else "raea"]
return prices.cost(kind, cpu=max(cpu or c, busy or 0), memory_gib=memory_gib or g, seconds=seconds)
SCALEDOWN = 2 # s a GPU container stays up after its last run (farm.py), billed SCALEDOWN = 2 # s a GPU container stays up after its last run (farm.py), billed
@@ -156,23 +139,16 @@ class Bill:
def add(self, r): def add(self, r):
if isinstance(r, dict) and r.get("task"): if isinstance(r, dict) and r.get("task"):
b, e = max(r["boot"], self.t0), r["end"] b, e = max(r["boot"], self.t0), r["end"]
k, b0, e0, c0 = self.tasks.get(r["task"], (r.get("kind"), b, e, 0.0)) k, b0, e0 = self.tasks.get(r["task"], (r.get("kind"), b, e))
# a container's cores: its busiest run's, an upper bound on what it's billed above its reservation self.tasks[r["task"]] = (k or r.get("kind"), min(b, b0), max(e, e0))
self.tasks[r["task"]] = (k or r.get("kind"), min(b, b0), max(e, e0), max(c0, r.get("cores") or 0))
self.cores, self.peak_mb = max(self.cores, r.get("cores") or 0), max(self.peak_mb, r.get("peak_mb") or 0) self.cores, self.peak_mb = max(self.cores, r.get("cores") or 0), max(self.peak_mb, r.get("peak_mb") or 0)
return r return r
def usd(self):
return sum(price(k or "L4", e - b + BOOT + SCALEDOWN, *((None, None) if k == CPU else (self.cpu, self.gib)), busy=c) for k, b, e, c in self.tasks.values())
def line(self): def line(self):
up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e, _ in self.tasks.values()] up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e in self.tasks.values()]
# the busiest run's cores and biggest process, against what a GPU container reserves (farm.py on()) # the busiest run's cores and biggest process, against what each container reserves (farm.py on())
used = f"; at most {self.cores:.1f} of {self.cpu} cores busy and {self.peak_mb / 1024:.1f} of {self.gib} GB in one process" if self.cores else "" used = f"; at most {self.cores:.1f} of {self.cpu} cores busy and {self.peak_mb / 1024:.1f} of {self.gib} GB in one process" if self.cores else ""
flat = sum(1 for k, _ in up if k == CPU) return f"raea farm: billed about ${sum(price(k, s, self.cpu, self.gib) for k, s in up):.3f}: {len(up)} GPU containers up {sum(s for _, s in up):.0f} s in all{used}"
# the containers by what they are: a job with no 3D has one GPU container (frame 0's) and the rest with none
what = f"{len(up)} GPU containers" if not flat else f"{len(up) - flat} GPU and {flat} CPU containers"
return f"raea farm: billed about ${self.usd():.3f}: {what} up {sum(s for _, s in up):.0f} s in all{used}"
def encode(frames_dir, out, fps, sound, run, start=0, frames=None): def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
@@ -186,34 +162,19 @@ def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
return run(cmd) return run(cmd)
def join(frames_dir, out, sound, run, seconds=None): def join(frames_dir, out, sound, run):
"""The runs' H.264 videos (run-FIRST.mp4) as OUT, one after another without encoding again, with the sound, cut at """The runs' H.264 videos (run-FIRST.mp4) as OUT, one after another without encoding again, with the sound."""
`seconds` (the piece's length). Only the runs' video tracks are read: each run has an AAC track too, whose encoder
delay (1024 samples) moved the joined video 21 ms after the sound, and -shortest then ended it 2 frames early
(the 894-frame ad came back as 892 on every farm render before 11-30, the live farm's included)."""
runs_ = sorted(n for n in os.listdir(frames_dir) if re.fullmatch(r"run-\d+\.mp4", n)) runs_ = sorted(n for n in os.listdir(frames_dir) if re.fullmatch(r"run-\d+\.mp4", n))
listing = os.path.join(frames_dir, "runs.txt") listing = os.path.join(frames_dir, "runs.txt")
track = video_track(os.path.join(frames_dir, runs_[0]), run) if runs_ else None
with open(listing, "w") as f: with open(listing, "w") as f:
if track:
f.write(f"ffconcat version 1.0\nstream\nexact_stream_id {track}\n")
f.writelines(f"file '{n}'\n" for n in runs_) f.writelines(f"file '{n}'\n" for n in runs_)
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", listing] cmd = ["ffmpeg", "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", listing]
if sound and os.path.exists(sound) and os.path.getsize(sound) > 44: if sound and os.path.exists(sound) and os.path.getsize(sound) > 44:
cmd += ["-i", sound, "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "256k"] cmd += ["-i", sound, "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "256k", "-shortest"]
if seconds:
cmd += ["-t", f"{seconds:.6f}"]
cmd += ["-c:v", "copy", "-movflags", "+faststart", out] cmd += ["-c:v", "copy", "-movflags", "+faststart", out]
return run(cmd) return run(cmd)
def video_track(path, run):
"""A video file's video track id (0x1), as the concat demuxer's exact_stream_id takes it; None when not said."""
c, o, _ = run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=id", "-of", "csv=p=0", path])
o = (o or "").strip().splitlines()
return o[0].strip() if not c and o and o[0].strip().startswith("0x") else None
def keep(frames_dir, out, start=0): def keep(frames_dir, out, start=0):
"""The frames as a folder of PNGs, named as raea names them (frame-00000.png is the first).""" """The frames as a folder of PNGs, named as raea names them (frame-00000.png is the first)."""
os.makedirs(out, exist_ok=True) os.makedirs(out, exist_ok=True)
@@ -221,49 +182,30 @@ def keep(frames_dir, out, start=0):
shutil.move(os.path.join(frames_dir, name), os.path.join(out, f"frame-{i:05d}.png")) shutil.move(os.path.join(frames_dir, name), os.path.join(out, f"frame-{i:05d}.png"))
def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None): def spread(fn, kind, calls, log, what, bill=None, most=None, got=None):
"""`calls` on `fn`, at most `most` containers at once when there are more calls than that (each takes the next call """`calls` on `fn`, at most `most` GPUs at once when there are more calls than that (each GPU takes the next call
as it finishes one); each finished run said in the log as it lands, and kept in `got` when given. The first as it finishes one); each finished run said in the log as it lands, and kept in `got` when given. The first
failure's code, else 0. With `again` (a list): a run that failed, or drew 3D, isn't the job's failure: its call failure's code, else 0."""
goes in `again`, for a GPU to take."""
code = 0 code = 0
if most and len(calls) > most: if most and len(calls) > most:
fn = fn.with_options(max_containers=most) fn = fn.with_options(max_containers=most)
left = {c[3]: c for c in calls if len(c) > 3} if again is not None else {}
for r in fn.starmap(calls, order_outputs=False, return_exceptions=True): for r in fn.starmap(calls, order_outputs=False, return_exceptions=True):
if isinstance(r, Exception): if isinstance(r, Exception):
# (with `again`, said too: 11-30 a run went back to a GPU and nothing said why) log(f"raea farm: a run failed: {r!r}", err=True)
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None) code = code or 1
code = code if again is not None else code or 1
continue continue
if bill: if bill:
bill.add(r) bill.add(r)
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
continue
left.pop(r.get("first"), None)
if got is not None: if got is not None:
got.append(r) got.append(r)
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s") log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
if r["code"]: if r["code"]:
log(r["out"], err=True) log(r["out"], err=True)
code = code or r["code"] code = code or r["code"]
if again is not None:
again.extend(left.values())
return code return code
def timed(r, n): def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None, bill=None):
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
frame" line, which is React and the page alone. That line read 47 ms on a 3D film whose frames took 151 ms, so
the plan put 892 frames on one GPU, and 205 ms on an ad whose slow stretch took 1,600 (11-30)."""
frame_s = (r.get("work_ms") / n if r.get("work_ms") else r.get("ms") or 1000 * r["s"] / n) / 1000
return frame_s, max(0.0, r["s"] - frame_s * n)
def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None, bill=None, cpu_render=None):
bill = bill or Bill() bill = bill or Bill()
id = opts["id"] id = opts["id"]
rest, out = split_out(args) rest, out = split_out(args)
@@ -276,100 +218,35 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
if out.endswith(VIDEO): if out.endswith(VIDEO):
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env)) t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
t.start() t.start()
video = out.endswith(VIDEO) p = bill.add(waited(render, log, id, rest, probe=True))
can_flat = bool(video and cpu_render and not opts.get("gpu")) if p["code"] or not p["length"]:
# what each frame draws, as a key (farm_keys.py): read here with nothing drawn, when this raea has --keys log(p["out"], err=True)
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) if not p["code"]:
log("raea farm: frame 0 rendered but didn't say the piece's length, so its frames can't be shared out", err=True)
def probed(): return p["code"] or 1
p = bill.add(waited(render, log, id, rest, probe=True))
if p["code"] or not p["length"]:
log(p["out"], err=True)
if not p["code"]:
log("raea farm: frame 0 rendered but didn't say the piece's length, so its frames can't be shared out", err=True)
return p, p["code"] or 1
log(f"raea farm: {p['length']} frames at {p['w']}x{p['h']}, {p['fps'] or 30} fps; frame 0 on a {p.get('kind') or opts.get('gpu') or 'T4'} in {p['s']:.1f} s")
return p, 0
if keyed and keyed["has3d"] is False and can_flat:
# its keys say the length, the size and that there's no 3D in it: no frame 0 on a GPU first
p = {"code": 0, "length": keyed["length"], "fps": keyed["fps"], "w": keyed["width"], "h": keyed["height"], "s": 0.0, "keys": True,
"manifest": {k: keyed[k] for k in ("width", "height", "fps", "length", "has3d")}}
log(f"raea farm: {p['length']} frames at {p['w']}x{p['h']}, {p['fps'] or 30} fps; its frames' keys read in {keys_s:.1f} s, no 3D in it")
else:
p, code = probed()
if code:
return code
length, fps, kind = p["length"], p["fps"] or 30, p.get("kind") or opts.get("gpu") or "T4" length, fps, kind = p["length"], p["fps"] or 30, p.get("kind") or opts.get("gpu") or "T4"
# the runs an earlier render of the piece left (kept by their frames' keys), and the frames no kept run holds log(f"raea farm: {length} frames at {p['w']}x{p['h']}, {fps} fps; frame 0 on a {kind} in {p['s']:.1f} s")
store, hits, gaps = None, [], [(0, length - 1)] video = out.endswith(VIDEO)
if keyed and not keyed["has3d"] and keyed["length"] == length and opts.get("kept", True): n0 = min(length, FIRST)
store = f"{opts['keys']}/{farm_keys.base(opts.get('raea'), rest, keyed, work)}" r0 = bill.add(waited(render, log, id, rest, list(range(n0)), 0, video=video))
hits, gaps = farm_keys.cover(store, keyed["keys"]) if r0["code"]:
if hits:
held = sum(n for _, n, _ in hits)
log(f"raea farm: {len(hits)} runs kept from an earlier render hold {held} of {length} frames, so {length - held} are drawn")
# the clips read from copies no larger than the page draws them (farm_proxy.py), after the store's name is read
# from the originals: a draft at half size reads most of a 4K cut's footage at a quarter of its pixels
if keyed and keyed.get("drawn") and opts.get("proxies") and gaps:
if farm_proxy.use(farm_proxy.plan(keyed["drawn"], work, run, opts["proxies"]), opts["proxy_make"], log, reload):
opts.get("proxy_commit", lambda: None)()
todo = sum(b - a + 1 for a, b in gaps)
n0, at0 = min(todo, FIRST, gaps[0][1] - gaps[0][0] + 1 if gaps else 0), gaps[0][0] if gaps else 0
# a video with no 3D in it (frame 0's manifest says) is drawn by containers with no GPU: the page, the clips and
# the encode are the CPU's work either way. A named GPU (opts gpu) keeps the job on it.
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)
r0 = None
first = list(range(at0, at0 + n0))
if flat and n0:
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
if r0["code"] or (r0.get("manifest") or {}).get("has3d"):
log("raea farm: the first frames didn't draw without a GPU, so the job stays on GPUs")
flat, r0 = False, None
if p.get("keys"): # no frame 0 was drawn on a GPU yet: its time is what a cold GPU's start is planned by
p, code = probed()
if code:
return code
kind = gpu_kind = p.get("kind") or opts.get("gpu") or "T4"
if flat:
render, kind, most = cpu_render, CPU, opts.get("cpus") or opts["gpus"]
else:
most = opts["gpus"]
if n0:
r0 = bill.add(waited(render, log, id, rest, first, at0, video=video, **({"nv": True} if nv else {})))
if r0 and r0["code"]:
log(r0["out"], err=True) log(r0["out"], err=True)
return r0["code"] return r0["code"]
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0) frame_s = (r0["ms"] or 1000 * r0["s"] / n0) / 1000
left = todo - n0 start_s = max(0.0, r0["s"] - frame_s * n0)
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now) left = length - n0
cold_s = start_s if flat else max(start_s, p["s"] - frame_s) k = gpus_for(left, frame_s, start_s, opts["gpus"])
k = gpus_for(left, frame_s, cold_s, most) m = parts_per_gpu(left, k, frame_s, start_s)
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS) cost = price(kind, p["s"] + r0["s"] + k * m * start_s + left * frame_s)
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
parts = f" in {k * m} parts" if m > 1 else "" parts = f" in {k * m} parts" if m > 1 else ""
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)" log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {k} {kind}s{parts}, about ${cost:.3f} in all")
if r0:
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
else:
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
if opts.get("max_usd") is not None and cost > opts["max_usd"]: if opts.get("max_usd") is not None and cost > opts["max_usd"]:
log(f"raea farm: about ${cost:.3f} is over max_usd ${opts['max_usd']:.3f}, so the rest don't start", err=True) log(f"raea farm: about ${cost:.3f} is over max_usd ${opts['max_usd']:.3f}, so the rest don't start", err=True)
return 3 return 3
# a video's runs can't drop warm-up frames without encoding again, so they have none # a video's runs can't drop warm-up frames without encoding again, so they have none
warm = 0 if video else opts.get("warm", 0) warm = 0 if video else opts.get("warm", 0)
got = [r0] if r0 else [] got = [r0]
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else [] code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k, got) if left else 0
again = [] if flat else None
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
if again:
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
if code: if code:
return code return code
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other # the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
@@ -379,22 +256,14 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
reload() # the other containers' frames reload() # the other containers' frames
frames = f"{os.path.dirname(work)}/frames" frames = f"{os.path.dirname(work)}/frames"
dest = os.path.join(work, out) dest = os.path.join(work, out)
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
farm_keys.put(store, keyed["keys"], got, frames)
got += farm_keys.take(hits, frames)
if manifest and p.get("manifest"): if manifest and p.get("manifest"):
path = os.path.join(work, manifest) path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True) os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
whole = joined(p["manifest"], [r.get("manifest") for r in got])
if hits and keyed.get("sounds"):
# a kept run's manifest holds the sounds of the render that drew it: the piece's own, as its keys' pass heard them
whole["sounds"] = keyed["sounds"]
with open(path, "w") as f: with open(path, "w") as f:
json.dump(whole, f, indent=2) json.dump(joined(p["manifest"], [r.get("manifest") for r in got]), f, indent=2)
if video: if video:
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True) os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
c, o, s = join(frames, dest, sound, run, length / fps) c, o, s = join(frames, dest, sound, run)
log(f"raea farm: joined {out} in {s:.1f} s" if not c else o, err=bool(c)) log(f"raea farm: joined {out} in {s:.1f} s" if not c else o, err=bool(c))
return c return c
keep(frames, dest) keep(frames, dest)
@@ -512,7 +381,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
return 0 return 0
def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload=lambda: None, cpu_render=None): def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload=lambda: None):
"""The job: a split raea render, a split Blender render, or `raea ARGS` whole on one GPU.""" """The job: a split raea render, a split Blender render, or `raea ARGS` whole on one GPU."""
if opts.get("gpu"): if opts.get("gpu"):
render, blender_render = (f.with_options(gpu=opts["gpu"]) for f in (render, blender_render)) render, blender_render = (f.with_options(gpu=opts["gpu"]) for f in (render, blender_render))
@@ -523,7 +392,7 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
return code return code
bill = Bill() bill = Bill()
if splittable(args): if splittable(args):
code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill, cpu_render) code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill)
else: else:
r = bill.add(waited(render, log, opts["id"], args)) r = bill.add(waited(render, log, opts["id"], args))
log(r["out"], err=bool(r["code"])) log(r["out"], err=bool(r["code"]))
-120
View File
@@ -1,120 +0,0 @@
# A job's clips read from copies no larger than they're drawn (docs/cloud-render.feature CR36): `raea render --keys`
# says the largest each clip is drawn over the piece (its box as drawn, transforms and a framed take's punch-in
# applied, in output px), and a clip much larger than that is read from a copy at that size, kept on the farm's volume
# by the source's hash and the size, so it's made once across every job. The picture can't lose detail: no copy is
# smaller than the largest the page draws the clip, and none is made for a clip whose size wasn't known for a frame.
#
# plan(drawn, work, run) [(path, source, w, h, copy)]: the clips worth a copy (at most AT of the width)
# use(plans, make, log) each copy made where missing (in parallel, `make` on containers with no GPU), then
# the job's link pointed at it
#
# A 1080x1920 cut from 4K landscape footage needs most of each clip (a 9:16 crop of 2160 rows into 1920, and punch-ins
# above 1): its master render gets no copies. A half-size draft (--scale 0.5) reads six of its seven clips from copies
# at 27-59% of the width.
import json
import os
AT = 0.75 # a copy at most this much of the source's width (56% of its pixels), or none: below that it's barely worth it
CRF = 12 # visually lossless (libx264 medium): the page scales the copy, so any loss would show only at 1:1
EVEN = lambda v: max(2, int(v + 1.999) // 2 * 2) # noqa: E731 - up to an even number of px (yuv420p)
def probe(path, run):
c, o, _ = run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,color_space:stream_side_data=rotation",
"-of", "json", path])
try:
s = json.loads(o)["streams"][0]
except Exception:
return None
rot = any(abs(int(d.get("rotation", 0))) in (90, 270) for d in s.get("side_data_list") or [])
return int(s["width"]), int(s["height"]), s.get("color_space") or "", rot
def source_id(path):
"""The file's content id: a link into the farm's cache is named for its hash; anything else is hashed here"""
real = os.path.realpath(path)
name = os.path.basename(real)
if os.path.islink(path) and len(name) == 64 and all(c in "0123456789abcdef" for c in name):
return name
import hashlib
h = hashlib.sha256()
with open(real, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""):
h.update(b)
return h.hexdigest()
def plan(drawn, work, run, store):
"""The clips worth reading from a copy: [(path in the job, its source, copy w, copy h, copy path, matrix)]"""
out = []
for rel, size in (drawn or {}).items():
path = os.path.join(work, rel)
if not size or not os.path.isfile(path) or not os.path.realpath(path).startswith("/"):
continue
p = probe(path, run)
if not p or p[3]: # (a rotated clip's drawn size is in its turned frame: left as it is)
continue
w, h, matrix, _ = p
need = max(size[0] / w, size[1] / h)
if need > AT:
continue
cw, ch = EVEN(w * need), EVEN(h * need)
ext = os.path.splitext(rel)[1].lower() or ".mp4"
# untagged HD is read as BT.709 (io/ffmpeg's decoder, as Apple and browsers read it): the copy is tagged so,
# or a copy under 720 lines would be read as BT.601 and shift its colours
matrix = matrix if matrix in ("bt709", "bt470bg", "smpte170m", "bt2020nc") else ("bt709" if h >= 720 else "smpte170m")
out.append((path, os.path.realpath(path), cw, ch, os.path.join(store, f"{source_id(path)}-{cw}x{ch}{ext}"), matrix))
return out
def command(src, dest, w, h, matrix):
"""ffmpeg making one copy: scaled with lanczos in the source's own matrix, every frame at its own time, the sound copied"""
tag = {"bt709": "bt709", "bt470bg": "bt470bg", "smpte170m": "smpte170m", "bt2020nc": "bt2020nc"}[matrix]
return ["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a?", "-vf",
f"scale={w}:{h}:flags=lanczos:in_color_matrix={tag if tag != 'bt2020nc' else 'bt2020'}:out_color_matrix={tag if tag != 'bt2020nc' else 'bt2020'}",
"-fps_mode", "passthrough", "-c:v", "libx264", "-preset", "medium", "-crf", str(CRF), "-pix_fmt", "yuv420p",
"-colorspace", tag, "-c:a", "copy", "-movflags", "+faststart", "-f", "mov" if dest.endswith(".mov") else "mp4", dest]
def use(plans, make, log, reload=lambda: None):
"""Each copy made where it isn't kept yet (`make`: a function's starmap over (src, dest, w, h, matrix)), then each
clip's link in the job pointed at its copy. Returns the number of clips swapped."""
todo = [(src, copy, w, h, m) for _, src, w, h, copy, m in plans if not os.path.exists(copy)]
made = 0
if todo:
for r in make(todo):
if isinstance(r, Exception) or (r or {}).get("code"):
log(f"raea farm: a clip's copy wasn't made, so it's read whole: {r if isinstance(r, Exception) else r.get('out', '')}"[:400])
else:
made += 1
reload()
used = 0
for path, src, w, h, copy, _ in plans:
if os.path.exists(copy):
tmp = f"{path}.proxy-link"
os.symlink(copy, tmp)
os.replace(tmp, path)
keep_faces(path, copy)
used += 1
if plans:
log(f"raea farm: {used} clips read from copies at the size they're drawn ({made} made now, {used - made if used >= made else 0} kept from before)")
return used
def keep_faces(path, copy):
"""A framed take's face track (TAKE.faces.json, made from the original by the keys pass) stamped for the copy, so
the page frames on the original's faces and doesn't find them again in the copy (runtime/page/src/faces.rs reads a
track only when its stamp is the take's own size and time)"""
side = os.path.splitext(path)[0] + ".faces.json"
if not os.path.exists(side):
return
try:
with open(side) as f:
t = json.load(f)
st = os.stat(copy)
t["take"] = {"bytes": st.st_size, "modified": int(st.st_mtime)}
with open(side, "w") as f:
f.write(json.dumps(t) + "\n")
except Exception:
pass
-2
View File
@@ -40,6 +40,4 @@ def kind_of(name):
for k in ("B300", "B200", "H200", "H100", "L40S", "A10", "L4", "T4"): for k in ("B300", "B200", "H200", "H100", "L40S", "A10", "L4", "T4"):
if re.search(rf"\b{k}\b", n): if re.search(rf"\b{k}\b", n):
return k return k
if re.search(r"\bA10G\b", n): # AWS's A10 (Modal's "A10" on some hosts)
return "A10"
return "" return ""
+1 -2
View File
@@ -86,8 +86,7 @@ up)
# rebuilds anyway (raea cloud then resumes the cut-off runs, projects.ts resumeRequest). # rebuilds anyway (raea cloud then resumes the cut-off runs, projects.ts resumeRequest).
if [ "${RAEA_BOX_FORCE:-}" != 1 ]; then if [ "${RAEA_BOX_FORCE:-}" != 1 ]; then
for i in $(seq 1 90); do for i in $(seq 1 90); do
# (a Sprite just made has no server yet: curl's own exit ended this script, 12-01) n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null" | python3 -c 'import json,sys
n=$(x ". ~/.raea-cloud.env 2>/dev/null; curl -fsS -m 5 -H \"authorization: Bearer \$RAEA_CLOUD_TOKEN\" localhost:8080/v1/health 2>/dev/null || true" | python3 -c 'import json,sys
try: print(json.load(sys.stdin).get("running", "unknown")) try: print(json.load(sys.stdin).get("running", "unknown"))
except Exception: print("down")') except Exception: print("down")')
# down: nothing to cut off; unknown: a server too old to say, so it isn't rebuilt blind # down: nothing to cut off; unknown: a server too old to say, so it isn't rebuilt blind
-8
View File
@@ -21,11 +21,6 @@ say packages
sudo -E apt-get update -qq sudo -E apt-get update -qq
sudo -E apt-get install -y -qq --no-install-recommends ca-certificates curl git git-lfs zstd xz-utils procps ripgrep \ sudo -E apt-get install -y -qq --no-install-recommends ca-certificates curl git git-lfs zstd xz-utils procps ripgrep \
libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools > /dev/null libasound2t64 libfontconfig1 libvulkan1 mesa-vulkan-drivers vulkan-tools > /dev/null
# faces an ad is set in (12-01: a box had Liberation and DejaVu alone, so every cut fell back to Liberation Sans): the
# open families brands are closest to, each taken when this Ubuntu has it
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
dpkg -s "$f" > /dev/null 2>&1 || sudo -E apt-get install -y -qq --no-install-recommends "$f" > /dev/null 2>&1 || say "no $f here"
done
node -v 2> /dev/null | grep -q '^v24' || { node -v 2> /dev/null | grep -q '^v24' || {
say "node $NODE" say "node $NODE"
curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | sudo tar -xJ -C /opt curl -fsSL "https://nodejs.org/dist/v$NODE/node-v$NODE-linux-x64.tar.xz" | sudo tar -xJ -C /opt
@@ -108,9 +103,6 @@ cat > /opt/raea-cloud/image/sprite-start.sh << 'EOF'
set -a set -a
. ~/.raea-cloud.env . ~/.raea-cloud.env
set +a set +a
# footage is read 16 MB ahead: a Sprite's disk answers each read in about 26 ms, and at its own 256 KB a pass over
# a 1 GB interview took two minutes that takes 14 s so (12-01, measured). Set at each start: a Sprite woken keeps none.
for b in /sys/class/bdi/*/read_ahead_kb /sys/block/*/queue/read_ahead_kb; do sudo sh -c "echo 16384 > $b" 2> /dev/null || true; done
export PORT=8080 RAEA_CLOUD_DEVICE=cpu WGPU_BACKEND=vulkan __EGL_VENDOR_LIBRARY_DIRS=/nonexistent export PORT=8080 RAEA_CLOUD_DEVICE=cpu WGPU_BACKEND=vulkan __EGL_VENDOR_LIBRARY_DIRS=/nonexistent
export VK_DRIVER_FILES=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json | head -1) export VK_DRIVER_FILES=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json | head -1)
mkdir -p ~/work mkdir -p ~/work
+1 -22
View File
@@ -34,7 +34,6 @@
// Every route but /healthz needs RAEA_CLOUD_TOKEN: `Authorization: Bearer TOKEN`, or ?token= (a browser's WebSocket // Every route but /healthz needs RAEA_CLOUD_TOKEN: `Authorization: Bearer TOKEN`, or ?token= (a browser's WebSocket
// can't set headers). The agent and raea get the container's environment without the token or the state keys. // can't set headers). The agent and raea get the container's environment without the token or the state keys.
import { claudeStopHook, jobsOf, markedEnd, watchEnd, watchTurnEnd } from "./turn-end.ts"
import { execFileSync, spawn } from "node:child_process" import { execFileSync, spawn } from "node:child_process"
import { timingSafeEqual } from "node:crypto" import { timingSafeEqual } from "node:crypto"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs" import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
@@ -413,27 +412,7 @@ server.on("upgrade", (req, socket, head) => {
buf += c buf += c
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i)) for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))
}) })
let heardFromCaller = Date.now() ws.on("message", (m) => ((heard = Date.now()), child.stdin.write(m.toString() + "\n")))
ws.on("message", (m) => ((heard = heardFromCaller = Date.now()), child.stdin.write(m.toString() + "\n")))
// the turn's end from the agent's own transcript, said along the socket (turn-end.ts): raea cloud closes the turn
// on it without waiting for an answer to session/prompt that may not come
{
const tellEnd = (by: string) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/turn_end", params: { by } }))
const busy = () => !!child.pid && jobsOf(child.pid, path.dirname(agent.command), WORK).length > 0
let stopWatch: (() => void) | undefined
if (agent.id === "antigravity-acp" && env.GEMINI_HOME) stopWatch = watchTurnEnd(env.GEMINI_HOME, () => heardFromCaller, tellEnd, busy)
else if (agent.id === "claude-acp" && own && env.CLAUDE_CONFIG_DIR) {
// Claude says it itself, through a Stop hook in the socket's own settings (never the box's own home's)
try {
const mark = claudeStopHook(env.CLAUDE_CONFIG_DIR)
stopWatch = watchEnd(() => markedEnd(mark), "its Stop hook", () => heardFromCaller, tellEnd, busy)
} catch {}
}
if (stopWatch) {
ws.on("close", stopWatch)
child.on("exit", stopWatch)
}
}
ws.on("close", stopAll) ws.on("close", stopAll)
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120))) child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll())) child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
+1 -1
View File
@@ -145,7 +145,7 @@ async function main() {
else if (typeof lfs === "string" && existsSync(path.join(p.root, ".lfsconfig"))) say(`media goes in the tar: ${lfs}`) 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, RAEA_CLOUD_MAX_USD
const n = (v?: string) => (v ? Number(v) : undefined) 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), gpu: process.env.RAEA_CLOUD_GPU_KIND, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD), media: typeof lfs !== "string" }
let finish: (() => Promise<number>) | undefined let finish: (() => Promise<number>) | undefined
const media = typeof lfs === "string" ? undefined : async (made: Parameters<typeof outputs>[2]) => { const media = typeof lfs === "string" ? undefined : async (made: Parameters<typeof outputs>[2]) => {
const o = await outputs(p.root, lfs, made) const o = await outputs(p.root, lfs, made)
-165
View File
@@ -1,165 +0,0 @@
// A turn's end, read off the agent's own records and said along its socket as a `_raea/turn_end` notification, so raea
// cloud closes the turn in seconds whether or not the agent answers its session/prompt (12-01: Gemini wrote its delivery
// message and never answered; the run stayed open 45 minutes, until the idle agent was ended here, and was then read
// as cut off and started again. Shane: "should not be more than a couple seconds to detect a stall").
//
// Antigravity keeps a transcript of each session, a JSON line a step. A model step that finished and called no tool is
// the end of its turn only when nothing it started still runs: it ends a step the same way to wait on a render it left
// in the background (123 of 131 such steps in one run), and is woken when that finishes. So both are read:
// the transcript's last line, and the processes that are the agent's own.
import { closeSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
/** the step a transcript line ends a turn at, and when it was made (ms); null for any other line */
export function turnEndOf(line: string): { step: number; at: number } | null {
let m: any
try {
m = JSON.parse(line)
} catch {
return null
}
if (!m || m.type !== "PLANNER_RESPONSE" || m.status !== "DONE" || m.source !== "MODEL") return null
if (Array.isArray(m.tool_calls) && m.tool_calls.length) return null
const at = Date.parse(m.created_at ?? "")
return typeof m.step_index === "number" && Number.isFinite(at) ? { step: m.step_index, at } : null
}
/** a file's last whole line */
export function lastLine(file: string, most = 1 << 20): string {
const size = statSync(file).size
const n = Math.min(size, most)
const b = Buffer.alloc(n)
const fd = openSync(file, "r")
try {
readSync(fd, b, 0, n, size - n)
} finally {
closeSync(fd)
}
const lines = b.toString("utf8").split("\n").filter(Boolean)
return lines.at(-1) ?? ""
}
/** the transcript written to last under an Antigravity home (GEMINI_HOME), or null */
export function newestTranscript(geminiHome: string): { file: string; mtime: number } | null {
const brain = path.join(geminiHome, "antigravity-acp", "brain")
let best: { file: string; mtime: number } | null = null
let names: string[] = []
try {
names = readdirSync(brain)
} catch {
return null
}
for (const n of names) {
const f = path.join(brain, n, ".system_generated", "logs", "transcript.jsonl")
try {
const m = statSync(f).mtimeMs
if (!best || m > best.mtime) best = { file: f, mtime: m }
} catch {}
}
return best
}
/** What an agent has running that isn't the agent itself: every process in its session (it's started detached, so
* the session is its own), descended from it, or working under `work` (a job started with a session of its own),
* but for the agent's own programs (under `agentDir`) and raea cloud's (their command names .raea-cloud). Linux /proc. */
export function jobsOf(pid: number, agentDir: string, work: string, proc = "/proc"): number[] {
const all: { pid: number; ppid: number; sid: number }[] = []
let names: string[] = []
try {
names = readdirSync(proc)
} catch {
return []
}
for (const n of names) {
if (!/^\d+$/.test(n)) continue
try {
// "pid (comm) state ppid pgrp session ...": comm may hold spaces and brackets, so read from its last ")"
const st = readFileSync(path.join(proc, n, "stat"), "utf8")
const f = st.slice(st.lastIndexOf(")") + 2).split(" ")
all.push({ pid: Number(n), ppid: Number(f[1]), sid: Number(f[3]) })
} catch {}
}
const kids = new Set<number>([pid])
for (let grew = true; grew; ) {
grew = false
for (const p of all) if (!kids.has(p.pid) && kids.has(p.ppid)) (kids.add(p.pid), (grew = true))
}
const link = (n: number, what: string) => {
try {
return readlinkSync(path.join(proc, String(n), what))
} catch {
return ""
}
}
const cmd = (n: number) => {
try {
return readFileSync(path.join(proc, String(n), "cmdline"), "utf8").replace(/\0/g, " ")
} catch {
return ""
}
}
return all
.filter((p) => p.pid !== pid && p.pid !== process.pid)
.filter((p) => p.sid === pid || kids.has(p.pid) || (link(p.pid, "cwd") + "/").startsWith(work.replace(/\/?$/, "/")))
.filter((p) => !link(p.pid, "exe").startsWith(agentDir) && !cmd(p.pid).includes(".raea-cloud"))
.map((p) => p.pid)
}
/** Claude Code's own word that its turn ended: a Stop hook in the agent's settings (CLAUDE_CONFIG_DIR/settings.json)
* that touches a file here. Other settings and hooks already there are kept. Returns the file. */
export function claudeStopHook(configDir: string): string {
const mark = path.join(configDir, ".raea-turn-end")
const file = path.join(configDir, "settings.json")
let settings: any = {}
try {
settings = JSON.parse(readFileSync(file, "utf8"))
} catch {}
if (!settings || typeof settings !== "object" || Array.isArray(settings)) settings = {}
const command = `touch '${mark.replace(/'/g, "'\\''")}'`
const hooks = (settings.hooks ??= {})
const stop: any[] = Array.isArray(hooks.Stop) ? hooks.Stop : (hooks.Stop = [])
if (!stop.some((g) => Array.isArray(g?.hooks) && g.hooks.some((h: any) => h?.command === command))) {
stop.push({ hooks: [{ type: "command", command }] })
writeFileSync(file, `${JSON.stringify(settings, null, 2)}\n`)
}
return mark
}
/** when a Stop hook's file was last touched, as a turn's end; null before the first */
export function markedEnd(mark: string): { step: number; at: number } | null {
try {
const at = statSync(mark).mtimeMs
return { step: at, at }
} catch {
return null
}
}
/** Calls `said` once for each turn's end that `ended` reads (an agent's own record of it) after `told()` (when the
* agent was last sent anything: an end from before its newest prompt isn't this turn's), once `busy()` has been
* false two looks running. Returns its stop. */
export function watchEnd(ended: () => { step: number; at: number } | null, by: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
let seen = -1
let idle = 0
const t = setInterval(() => {
try {
const end = ended()
// a second's slack: a transcript's times are whole seconds
if (!end || end.step === seen || end.at < told() - 1000 || busy()) return void (idle = 0)
if (++idle < 2) return
seen = end.step
said(`${by}, and nothing of its own running`)
} catch {}
}, everyMs)
t.unref?.()
return () => clearInterval(t)
}
/** watchEnd on an Antigravity agent's transcript */
export function watchTurnEnd(geminiHome: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
const ended = () => {
const tr = newestTranscript(geminiHome)
return tr ? turnEndOf(lastLine(tr.file)) : null
}
return watchEnd(ended, "its transcript", told, said, busy, everyMs)
}
-7
View File
@@ -32,11 +32,6 @@ export interface Health {
* names: L4, L40S, ...), and a price over `maxUsd` (estimated from the first frames) stops it before the rest. */ * names: L4, L40S, ...), and a price over `maxUsd` (estimated from the first frames) stops it before the rest. */
export interface Farm { export interface Farm {
gpus?: number gpus?: number
/** at most this many containers with no GPU at once, for a video with no 3D in it; 0 keeps the job on GPUs */
cpus?: number
/** false: every frame of a video drawn, none taken from the runs an earlier render of the piece left (kept by their
* frames' keys, docs/cloud-render.feature CR30) */
kept?: boolean
card?: string card?: string
maxUsd?: number maxUsd?: number
/** the job's media outputs stay on the farm for `media` to send to R2 (docs/cloud-render.feature CR23) */ /** the job's media outputs stay on the farm for `media` to send to R2 (docs/cloud-render.feature CR23) */
@@ -154,8 +149,6 @@ export class RaeaCloud {
async startJob(args: string[], folder: Uint8Array, signal?: AbortSignal, farm: Farm = {}): Promise<string> { async startJob(args: string[], folder: Uint8Array, signal?: AbortSignal, farm: Farm = {}): Promise<string> {
const q = new URLSearchParams({ args: JSON.stringify(args) }) const q = new URLSearchParams({ args: JSON.stringify(args) })
if (farm.gpus !== undefined) q.set("gpus", String(farm.gpus)) if (farm.gpus !== undefined) q.set("gpus", String(farm.gpus))
if (farm.cpus !== undefined) q.set("cpus", String(farm.cpus))
if (farm.kept === false) q.set("kept", "0")
if (farm.card) q.set("gpu", farm.card) if (farm.card) q.set("gpu", farm.card)
if (farm.maxUsd !== undefined) q.set("max_usd", String(farm.maxUsd)) if (farm.maxUsd !== undefined) q.set("max_usd", String(farm.maxUsd))
if (farm.media) q.set("media", "1") if (farm.media) q.set("media", "1")
+1 -155
View File
@@ -32,9 +32,8 @@ class FakeGpu:
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=gray:s=16x16", "-frames:v", "1", src]) run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=gray:s=16x16", "-frames:v", "1", src])
shutil.copy(src, path) shutil.copy(src, path)
def remote(self, id, args, frames=None, first=0, probe=False, video=False, nv=False): def remote(self, id, args, frames=None, first=0, probe=False, video=False):
self.calls.append(("probe" if probe else "run", frames, first)) self.calls.append(("probe" if probe else "run", frames, first))
self.nv = getattr(self, "nv", []) + ([nv] if not probe else [])
self.args = getattr(self, "args", []) + [list(args)] self.args = getattr(self, "args", []) + [list(args)]
if probe: if probe:
# as raea does with two --manifest: the first wins, so the probe's own says nothing # as raea does with two --manifest: the first wins, so the probe's own says nothing
@@ -150,153 +149,6 @@ assert code == 0 and len(out) == 1000 and q.options == {"max_containers": 2} and
assert "on 2 L4s in 8 parts" in " ".join(lines), lines assert "on 2 L4s in 8 parts" in " ".join(lines), lines
ok("a long job on too few GPUs: 4 parts a GPU from a queue of 2 at a time, every frame back") ok("a long job on too few GPUs: 4 parts a GPU from a queue of 2 at a time, every frame back")
# a video with no 3D in it (frame 0's manifest says): after frame 0 on a GPU, its frames go to containers with no GPU,
# and a run that fails there, or has 3D in it after all, is drawn again by a GPU
class Flat(FakeGpu):
def __init__(self, root, length=600, name="CPU", bad=(), has3d=False):
super().__init__(root, length)
self.name, self.bad, self.has3d = name, bad, has3d
def remote(self, id, args, frames=None, first=0, probe=False, video=False, nv=False):
r = super().remote(id, args, frames, first, probe, video, nv)
if probe:
r["manifest"]["has3d"] = self.has3d
return {**r, "kind": "T4"}
r = {**r, "first": first, "kind": self.name, "work_ms": 500.0 * len(frames), "task": f"{self.name}-{first}", "boot": 0, "end": 1, "cores": 4.7}
if first in self.bad:
r = {**r, "code": 1} if self.bad[first] == "fails" else {**r, "manifest": {**(r.get("manifest") or {}), "has3d": True}}
return r
lines.clear()
os.makedirs(os.path.join(root, "jobs", "jc", "work"))
g, c = Flat(root, name="T4"), Flat(root)
code = fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jc", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "jc", "work"), log, g, {}, run, cpu_render=c)
said = " ".join(lines)
assert code == 0 and [x[0] for x in g.calls] == ["probe"] and len(c.calls) == 1 + 6, (code, g.calls, len(c.calls), lines)
assert "on 6 containers with no GPU (no 3D in it)" in said and "frames on a CPU" in said, lines
# capped by the job's cpus, a long piece goes out as 2 parts a container, not 4
assert fp.parts_per_gpu(886, 8, 0.2, 5.0, fp.CPU_PARTS) == 1 and fp.parts_per_gpu(9000, 8, 0.2, 5.0, fp.CPU_PARTS) == 2 and fp.parts_per_gpu(9000, 8, 0.2, 5.0) == 4
ok("a video with no 3D: frame 0 on a GPU, every frame after on containers with no GPU, up to the job's cpus")
lines.clear()
os.makedirs(os.path.join(root, "jobs", "jd", "work"))
g, c = Flat(root, name="T4"), Flat(root, bad={8: "fails", 107: "3d"})
code = fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jd", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "jd", "work"), log, g, {}, run, cpu_render=c)
again = [x for x in g.calls if x[0] == "run"]
assert code == 0 and sorted(x[2] for x in again) == [8, 107] and "2 of 6 runs go to a GPU" in " ".join(lines), (code, again, lines)
n = int(subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", os.path.join(root, "jobs", "jd", "work", "out", "a.mp4")], capture_output=True, text=True).stdout)
assert n == 600, n
ok("a run that fails with no GPU, or has 3D in it, is drawn again by a GPU, and the video still has every frame")
lines.clear()
os.makedirs(os.path.join(root, "jobs", "je", "work"))
g, c = Flat(root, name="T4"), Flat(root)
code = fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "je", "gpu": "L4", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "je", "work"), log, g, {}, run, cpu_render=c)
assert code == 0 and not c.calls, c.calls
code = fp.raea_render(["render", "a.tsx", "-o", "stills"], {"id": "je", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "je", "work"), log, g, {}, run, cpu_render=c)
assert code == 0 and not c.calls, c.calls
ok("a job that names its GPU, and a render to stills, stay on GPUs")
# a video's runs kept by their frames' keys (farm_keys.py): the same piece again draws nothing and joins the kept runs
# with its sound made again; one shot changed draws only the runs that held it
class Keyed:
def __init__(self, length): self.keys = [f"k{i}" for i in range(length)]
def __call__(self, cmd, cwd=None, env=None, timeout=None):
if "--keys" in cmd:
n = len(self.keys)
with open(cmd[cmd.index("--keys") + 1], "w") as f:
json.dump({"width": 1920, "height": 1080, "fps": 30, "length": n, "has3d": False, "keys": self.keys, "sounds": {"fps": 30, "clips": [{"key": "mine"}], "notes": [], "lines": []}}, f)
return 0, "", 0.4
return run(cmd, cwd, env, timeout)
kept, keyed = os.path.join(root, "kept"), Keyed(600)
def frames_in(job):
return int(subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", os.path.join(root, "jobs", job, "work", "out", "a.mp4")], capture_output=True, text=True).stdout)
def drawn(c): return sum(len(x[1]) for x in c.calls if x[0] == "run")
for job in ("jk1", "jk2", "jk3"):
os.makedirs(os.path.join(root, "jobs", job, "work"))
shutil.copy(os.path.join(root, "one.png"), os.path.join(root, "jobs", job, "work", "logo.png"))
lines.clear()
g, c = Flat(root, name="T4"), Flat(root)
o = {"gpus": 2, "cpus": 8, "keys": kept, "raea": "test"}
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {**o, "id": "jk1"}, os.path.join(root, "jobs", "jk1", "work"), log, g, {}, keyed, cpu_render=c) == 0, lines
assert not g.calls and drawn(c) == 600 and frames_in("jk1") == 600, (g.calls, drawn(c), lines)
lines.clear()
g, c = Flat(root, name="T4"), Flat(root)
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4", "--manifest", "out/a.json"], {**o, "id": "jk2"}, os.path.join(root, "jobs", "jk2", "work"), log, g, {}, keyed, cpu_render=c) == 0, lines
assert not g.calls and not c.calls and frames_in("jk2") == 600, (g.calls, c.calls, lines)
assert "hold 600 of 600 frames" in " ".join(lines) and json.load(open(os.path.join(root, "jobs", "jk2", "work", "out", "a.json")))["sounds"]["clips"] == [{"key": "mine"}], lines
keyed.keys[300:320] = [f"new{i}" for i in range(20)]
lines.clear()
g, c = Flat(root, name="T4"), Flat(root)
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {**o, "id": "jk3"}, os.path.join(root, "jobs", "jk3", "work"), log, g, {}, keyed, cpu_render=c) == 0, lines
assert 20 <= drawn(c) < 300 and all(min(x[1]) <= 319 and max(x[1]) >= 300 or True for x in c.calls) and frames_in("jk3") == 600, (drawn(c), lines)
ok(f"kept runs: the same piece again draws nothing; 20 frames changed draw {drawn(c)} of 600; no frame 0 on a GPU first")
# a file the keys don't hold (an image the page shows, the engine) starts a store of its own
k = {"width": 1, "height": 1, "fps": 30, "length": 1}
w = os.path.join(root, "jobs", "jk3", "work")
b1 = fp.farm_keys.base("test", ["a"], k, w)
open(os.path.join(w, "logo.png"), "ab").write(b"x")
assert b1 != fp.farm_keys.base("test", ["a"], k, w) != fp.farm_keys.base("other", ["a"], k, w)
ok("a changed image, or another raea, keeps nothing from the store before it")
# a piece with 3D keeps its GPU, and its runs use NVIDIA's encoder and decoder (CR34); a 2D piece's GPU runs don't
lines.clear()
os.makedirs(os.path.join(root, "jobs", "jn", "work"))
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}, 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 = 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 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)
jd = os.path.join(root, "joins")
os.makedirs(jd)
for first, n in ((0, 8), (8, 148), (156, 147)):
# each with an AAC track, as raea's --at runs have
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=s=64x64:r=30", "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-frames:v", str(n), "-t", str(n / 30), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", f"{jd}/run-{first:05d}.mp4"])
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "sine=f=440:d=10.1", "-ar", "48000", f"{jd}/s.wav"])
c, o, _ = fp.join(jd, f"{jd}/out.mp4", f"{jd}/s.wav", run, 303 / 30)
said = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,start_time", "-of", "csv=p=0", f"{jd}/out.mp4"], capture_output=True, text=True).stdout.strip().split(",")
assert c == 0 and int(said[1]) == 303 and float(said[0]) == 0, (c, o, said)
ok("the join keeps every frame of runs that have their own AAC tracks, the video from 0 with the sound")
# a clip much larger than it's drawn is read from a copy at that size, made once and kept by its hash (CR36); one
# drawn near its size, or whose size wasn't known for a frame, is read whole
import farm_proxy # noqa: E402
pw = os.path.join(root, "jobs", "jp", "work")
os.makedirs(os.path.join(pw, "media"))
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=s=640x360:r=30", "-f", "lavfi", "-i", "sine=f=440:r=48000", "-t", "2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", os.path.join(pw, "media", "a.mp4")])
for n in ("b.mp4", "c.mp4"):
shutil.copy(os.path.join(pw, "media", "a.mp4"), os.path.join(pw, "media", n))
with open(os.path.join(pw, "media", "a.faces.json"), "w") as f:
json.dump({"take": {"bytes": 1, "modified": 1}, "every": 0.5, "eyes": [[0.5, 0.4]]}, f)
store = os.path.join(root, "proxies")
plans = farm_proxy.plan({"media/a.mp4": [100, 200], "media/b.mp4": [600, 340], "media/c.mp4": None}, pw, run, store)
assert [(os.path.basename(p[0]), p[2], p[3]) for p in plans] == [("a.mp4", 356, 200)], plans
made = []
def make(todo):
made.extend(todo)
os.makedirs(store, exist_ok=True)
return [{"code": run(farm_proxy.command(*a))[0]} for a in todo]
assert farm_proxy.use(plans, make, log) == 1 and len(made) == 1
a = os.path.join(pw, "media", "a.mp4")
said = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-show_entries", "stream=codec_type,width,height,nb_read_frames", "-of", "csv=p=0", a], capture_output=True, text=True).stdout.split()
assert os.path.islink(a) and said[0].startswith("video,356,200,60") and said[1].startswith("audio"), said
assert json.load(open(os.path.join(pw, "media", "a.faces.json")))["take"]["bytes"] == os.path.getsize(made[0][1])
# b.mp4 is the same file under another name: its copy is found by its hash, nothing made again
plans = farm_proxy.plan({"media/b.mp4": [100, 200]}, pw, run, store)
assert farm_proxy.use(plans, make, log) == 1 and len(made) == 1 and os.path.realpath(os.path.join(pw, "media", "b.mp4")) == os.path.realpath(made[0][1])
ok("clips drawn far smaller than they are read from copies at that size (every frame, the sound, the face track kept); others whole")
# a frame's time is raea's own clocks over the whole frame when the run says them, not its React line
assert fp.timed({"s": 20.0, "ms": 47.0, "work_ms": 1208.0}, 8) == (0.151, 20.0 - 0.151 * 8)
assert fp.timed({"s": 20.0, "ms": 47.0}, 8)[0] == 0.047 and fp.timed({"s": 20.0, "ms": None}, 8) == (2.5, 0.0)
ok("the timed run's frame is the whole frame's time, so a 3D film isn't planned at a third of its cost")
b = fp.Bill() b = fp.Bill()
t = b.t0 t = b.t0
b.add({"task": "a", "kind": "L40S", "boot": t - 100, "end": t + 10}) # left up by an earlier job: from this job's start b.add({"task": "a", "kind": "L40S", "boot": t - 100, "end": t + 10}) # left up by an earlier job: from this job's start
@@ -305,12 +157,6 @@ b.add({"task": "b", "kind": "T4", "boot": t + 1, "end": t + 6})
b.add({"code": 1, "out": "no task id"}) b.add({"code": 1, "out": "no task id"})
assert "2 GPU containers up 35 s" in b.line(), b.line() assert "2 GPU containers up 35 s" in b.line(), b.line()
ok("the bill: each container from its boot or the job's start to its last run, plus its boot and idle seconds") ok("the bill: each container from its boot or the job's start to its last run, plus its boot and idle seconds")
b = fp.Bill()
b.add({"task": "g", "kind": "T4", "boot": b.t0, "end": b.t0 + 15, "cores": 1.0})
b.add({"task": "c1", "kind": "CPU", "boot": b.t0, "end": b.t0 + 95, "cores": 7.0})
want = fp.prices.cost("T4", 2, 8, 20) + fp.prices.cost("CPU", 7.0, 8, 100)
assert "1 GPU and 1 CPU containers up 120 s" in b.line() and abs(b.usd() - want) < 1e-9, (b.line(), want)
ok("the bill prices a container with no GPU as one, and the cores a run kept busy above what it reserves")
# a GPU run with no answer yet is said in the log, not waited on in silence; its answer still comes back # a GPU run with no answer yet is said in the log, not waited on in silence; its answer still comes back
class SlowCall: class SlowCall:
+1 -73
View File
@@ -3,14 +3,12 @@
// paths read on the worker) // paths read on the worker)
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { execSync } from "node:child_process" import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import os from "node:os" import os from "node:os"
import path from "node:path" import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts" import { parseSummary, pick } from "../server/gpu.ts"
import { plan, projectRoot } from "../server/offload.ts" import { plan, projectRoot } from "../server/offload.ts"
import { shellEnv } from "../server/shell-os.ts" import { shellEnv } from "../server/shell-os.ts"
import { claudeStopHook, jobsOf, lastLine, markedEnd, newestTranscript, turnEndOf, watchEnd, watchTurnEnd } from "../server/turn-end.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts" import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
const L4 = `Devices: const L4 = `Devices:
@@ -109,73 +107,3 @@ console.log("units: ok")
console.log("ok google-token") console.log("ok google-token")
} }
{
// a turn's end in Antigravity's transcript: a finished model step that called no tool (turn-end.ts)
const done = { step_index: 1716, source: "MODEL", type: "PLANNER_RESPONSE", status: "DONE", created_at: "2026-12-02T03:34:18Z", content: "All six cuts are delivered." }
assert.deepEqual(turnEndOf(JSON.stringify(done)), { step: 1716, at: Date.parse("2026-12-02T03:34:18Z") })
assert.equal(turnEndOf(JSON.stringify({ ...done, tool_calls: [{ name: "run_command" }] })), null)
assert.equal(turnEndOf(JSON.stringify({ ...done, status: "RUNNING" })), null)
assert.equal(turnEndOf(JSON.stringify({ ...done, type: "RUN_COMMAND" })), null)
assert.equal(turnEndOf("not json"), null)
const home = mkdtempSync(path.join(os.tmpdir(), "raea-turn-end-"))
const logs = path.join(home, "antigravity-acp", "brain", "s1", ".system_generated", "logs")
mkdirSync(logs, { recursive: true })
const file = path.join(logs, "transcript.jsonl")
const now = Date.now()
const line = (o: object) => JSON.stringify(o) + "\n"
writeFileSync(file, line({ ...done, step_index: 1, created_at: new Date(now - 60_000).toISOString() }))
assert.equal(newestTranscript(home)?.file, file)
assert.equal(JSON.parse(lastLine(file)).step_index, 1)
// an end from before the agent was last told anything isn't this turn's; one after it is said once
const said: string[] = []
let busy = true
const stop = watchTurnEnd(home, () => now, (by) => said.push(by), () => busy, 10)
await new Promise((ok) => setTimeout(ok, 60))
assert.deepEqual(said, [])
writeFileSync(file, line({ ...done, step_index: 2, tool_calls: [{ name: "x" }], created_at: new Date(now + 1000).toISOString() }) + line({ ...done, step_index: 3, created_at: new Date(now + 2000).toISOString() }))
// the step ended, but a job the agent started still runs: it's waiting, not done
await new Promise((ok) => setTimeout(ok, 80))
assert.deepEqual(said, [])
busy = false
await new Promise((ok) => setTimeout(ok, 80))
stop()
assert.deepEqual(said, ["its transcript, and nothing of its own running"])
// an agent's own jobs, from a made-up /proc: its session's and its children's, not its own programs or raea cloud's
const proc = path.join(home, "proc")
const put = (pid: number, ppid: number, sid: number, exe: string, cmd: string, cwd = "/") => {
mkdirSync(path.join(proc, String(pid)), { recursive: true })
writeFileSync(path.join(proc, String(pid), "stat"), `${pid} (a (odd) name) S ${ppid} ${sid} ${sid} 0 -1`)
writeFileSync(path.join(proc, String(pid), "cmdline"), cmd.replace(/ /g, "\0"))
symlinkSync(exe, path.join(proc, String(pid), "exe"))
symlinkSync(cwd, path.join(proc, String(pid), "cwd"))
}
put(100, 1, 100, "/opt/raea-cloud/agents/antigravity-acp/agy", "agy")
put(101, 100, 100, "/opt/raea-cloud/agents/antigravity-acp/localharness_external", "localharness_external")
put(50, 1, 50, "/usr/bin/node", "node /opt/raea-cloud/server/main.ts")
put(60, 50, 50, "/usr/bin/node", "node .raea-cloud/live/live.cjs", "/srv/work/threads/r1")
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc), [])
put(200, 101, 100, "/opt/raea/bin/raea", "raea render edit.tsx")
put(300, 1, 300, "/usr/bin/ffmpeg", "ffmpeg -i a.mp4", "/srv/work/threads/r1/out")
assert.deepEqual(jobsOf(100, "/opt/raea-cloud/agents/antigravity-acp", "/srv/work", proc).sort(), [200, 300])
// Claude's Stop hook: added to the settings there once, what was there kept; its file's touch is the turn's end
const cfg = path.join(home, "claude")
mkdirSync(cfg, { recursive: true })
writeFileSync(path.join(cfg, "settings.json"), JSON.stringify({ model: "opus", hooks: { Stop: [{ hooks: [{ type: "command", command: "true" }] }] } }))
const mark = claudeStopHook(cfg)
claudeStopHook(cfg)
const set = JSON.parse(readFileSync(path.join(cfg, "settings.json"), "utf8"))
assert.equal(set.model, "opus")
assert.deepEqual(set.hooks.Stop.map((g: any) => g.hooks[0].command), ["true", `touch '${mark}'`])
assert.equal(markedEnd(mark), null)
const heard: string[] = []
const stop2 = watchEnd(() => markedEnd(mark), "its Stop hook", () => Date.now() - 500, (by) => heard.push(by), () => false, 10)
await new Promise((ok) => setTimeout(ok, 40))
assert.deepEqual(heard, [])
execSync(set.hooks.Stop[1].hooks[0].command)
await new Promise((ok) => setTimeout(ok, 80))
stop2()
assert.deepEqual(heard, ["its Stop hook, and nothing of its own running"])
rmSync(home, { recursive: true, force: true })
console.log("ok turn-end")
}
+1 -1
View File
@@ -36,7 +36,7 @@ export const PACKS = {
frames: "no face cut by the frame or a split screen's seam, no text too small to read", frames: "no face cut by the frame or a split screen's seam, no text too small to read",
montage: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts", montage: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts",
place: "no text over a face, hands or what the shot is about where a clear place of its size exists", place: "no text over a face, hands or what the shot is about where a clear place of its size exists",
seen: "its contact sheet and its frames at full size looked at since its last render, and what was seen, how it looks and what would change said", seen: "its contact sheet looked at since its last render, and what was seen and would change said",
surprise: "one earned surprise, named with its moment in seconds", surprise: "one earned surprise, named with its moment in seconds",
naming: "files named client_concept_variant_v#_size", naming: "files named client_concept_variant_v#_size",
sizes: "one size first: no other size before the first is approved", sizes: "one size first: no other size before the first is approved",
+2 -2
View File
@@ -17,8 +17,8 @@ export type Clip = { key?: string; from: number; to: number; src: string; at: nu
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number } export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number }
/** `raea render --manifest`: the frames with their texts, and the sound's clips */ /** `raea render --manifest`: the frames with their texts, and the sound's clips */
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } } export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`); `look` is its design judged at full size */ /** what was seen of a file and said (FILE.seen.json, `raea goal seen`) */
export type Seen = { video: string; render: string; seen: string; look?: string; surprise?: string; at?: string } export type Seen = { video: string; render: string; seen: string; surprise?: string; at?: string }
export interface FileFacts { export interface FileFacts {
/** as the project names it (relative to its folder) */ /** as the project names it (relative to its folder) */
+1 -39
View File
@@ -3,7 +3,7 @@
// large-v3; POST /v1/scene, people, faces, things and words in the shot); elsewhere raea's own `raea words` hears, and a // large-v3; POST /v1/scene, people, faces, things and words in the shot); elsewhere raea's own `raea words` hears, and a
// need nothing here can meet throws `Unmet`, which makes its check wait and say why, as a render need does. // need nothing here can meet throws `Unmet`, which makes its check wait and say why, as a render need does.
import { spawnSync } from "node:child_process" import { spawnSync } from "node:child_process"
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os" import os from "node:os"
import path from "node:path" import path from "node:path"
import type { Scene } from "./packs/place.ts" import type { Scene } from "./packs/place.ts"
@@ -208,23 +208,10 @@ export async function words(file: string, anyAge = false): Promise<Word[]> {
/** frames read a second for the scene, and the width they're read at (places are in shares of the picture) */ /** frames read a second for the scene, and the width they're read at (places are in shares of the picture) */
export const RATE = 2 export const RATE = 2
const SIDE = 540 const SIDE = 540
/** a video's scene reading, kept beside it */
export const SCENE_EXT = "scene.json"
/** what's in a file's frames (`at`: those seconds, else RATE a second): each frame's faces and seams, and its scene /** what's in a file's frames (`at`: those seconds, else RATE a second): each frame's faces and seams, and its scene
* (people, faces, things, words in the shot) for placement. The farm reads them; with no farm here, Unmet */ * (people, faces, things, words in the shot) for placement. The farm reads them; with no farm here, Unmet */
export async function scene(file: string, at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> { export async function scene(file: string, at?: number[]): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
// a video's whole reading is kept beside it, as its words are, and read again only when the file is newer: a cut
// checked at its render was read again at publish and again at done, 30 s a file each time, so a done check of 11
// files took 334 s (12-01)
const whole = !at?.length && !/\.(png|jpe?g|webp)$/i.test(file)
if (whole) {
const kept = freshBeside(file, SCENE_EXT)
try {
const k = kept ? (JSON.parse(readFileSync(kept, "utf8")) as { rate: number; side: number; faces: Faces[]; scenes: Scene[] }) : null
if (k && k.rate === RATE && k.side === SIDE && Array.isArray(k.scenes) && k.scenes.length) return { rate: k.rate, faces: k.faces, scenes: k.scenes }
} catch {}
}
if (!farm()) throw new Unmet(`no scene reader on this machine for ${path.basename(file)} (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`) if (!farm()) throw new Unmet(`no scene reader on this machine for ${path.basename(file)} (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-scene-")) const dir = mkdtempSync(path.join(os.tmpdir(), "raea-scene-"))
try { try {
@@ -251,11 +238,6 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene) scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
} }
} }
if (whole && scenes.length) {
try {
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
} catch {}
}
return { rate: at?.length ? 0 : RATE, faces, scenes } return { rate: at?.length ? 0 : RATE, faces, scenes }
} finally { } finally {
rmSync(dir, { recursive: true, force: true }) rmSync(dir, { recursive: true, force: true })
@@ -270,23 +252,3 @@ export function sheet(file: string): string {
if (r.status !== 0 || !existsSync(out)) throw new Unmet(`couldn't make ${path.basename(file)}'s contact sheet: ${(r.stderr || r.stdout || "").trim().slice(-200)}`) if (r.status !== 0 || !existsSync(out)) throw new Unmet(`couldn't make ${path.basename(file)}'s contact sheet: ${(r.stderr || r.stdout || "").trim().slice(-200)}`)
return out return out
} }
/** how many full-size frames a look is made of */
export const LOOKS = 6
/** a video's frames at full size beside it (FILE.looks/1.jpg ...), made again when older than the video. Type, cards
* and captions are judged on these: a contact sheet's tiles are too small to judge design on (12-01, Shane on Dutch:
* "why do components not look good. is it even proofing or reviewing the work?") */
export function looks(file: string): string[] {
const dir = `${stem(file)}.looks`
const out = Array.from({ length: LOOKS }, (_, i) => path.join(dir, `${i + 1}.jpg`))
if (out.every((p) => changed(p) >= changed(file))) return out
const d = seconds(file)
if (!d) throw new Unmet(`couldn't read ${path.basename(file)}'s length for its full-size frames`)
mkdirSync(dir, { recursive: true })
out.forEach((p, i) => ffmpeg(["-v", "error", "-y", "-ss", ((d * (i + 0.5)) / LOOKS).toFixed(2), "-i", file, "-frames:v", "1", "-q:v", "3", p]))
return out
}
/** whether FILE's full-size frames were made since it last changed */
export const looksFresh = (file: string) => Array.from({ length: LOOKS }, (_, i) => path.join(`${stem(file)}.looks`, `${i + 1}.jpg`)).every((p) => changed(p) >= changed(file))
+3 -27
View File
@@ -4,7 +4,7 @@
// stills a composition as it's saved (`raea check EDIT.tsx --quick`): three stills rendered with their manifest, and // stills a composition as it's saved (`raea check EDIT.tsx --quick`): three stills rendered with their manifest, and
// the text rules and the person's text taste on them; what it can't see waits for the export's floor // the text rules and the person's text taste on them; what it can't see waits for the export's floor
import { spawnSync } from "node:child_process" import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs" import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"
import os from "node:os" import os from "node:os"
import path from "node:path" import path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
@@ -12,7 +12,7 @@ import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts" import { RAEA, stem } from "../media.ts"
import { bookkeeping } from "./naming.ts" import { bookkeeping } from "./naming.ts"
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null } type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
/** raea's measure of a file, its findings as it wrote them (-o) */ /** raea's measure of a file, its findings as it wrote them (-o) */
function measure(args: string[], cwd: string): Measured[] { function measure(args: string[], cwd: string): Measured[] {
@@ -27,36 +27,12 @@ function measure(args: string[], cwd: string): Measured[] {
} }
} }
/** a video's floor report, kept beside it */
export const FLOOR_EXT = "floor.json"
let version: string | undefined
const raeaVersion = () => (version ??= String(spawnSync(RAEA, ["--version"], { encoding: "utf8" }).stdout ?? "").trim())
const when = (f: string) => (existsSync(f) ? statSync(f).mtimeMs : 0)
/** A made video's floor findings: kept beside it (FILE.floor.json) and measured again only when the video or its
* manifest is newer, raea is another version, or the kept report holds an error. The measure took 26 s a cut and ran
* again on the same file at publish and at done (12-01). An error is always measured again, since what it names (a
* placeholder brand kit) can be put right without the video changing, and a kept error would hold a finished run. */
export function floorOf(abs: string, manifest: string | undefined, cwd: string, by: (args: string[], cwd: string) => Measured[] = measure): Measured[] {
const kept = `${stem(abs)}.${FLOOR_EXT}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { raea: string; findings: Measured[] }
const fresh = when(kept) >= when(abs) && (!manifest || when(kept) >= when(manifest))
if (fresh && k.raea === raeaVersion() && !k.findings.some((x) => x.level === "error")) return k.findings
} catch {}
const findings = by([abs, ...(manifest ? ["--manifest", manifest] : [])], cwd)
try {
writeFileSync(kept, `${JSON.stringify({ raea: raeaVersion(), findings })}\n`)
} catch {}
return findings
}
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined }) const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => { export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync) const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
for (const x of floorOf(f.abs, m, f.root)) say(x) for (const x of measure([f.abs, ...(m ? ["--manifest", m] : [])], f.root)) say(x)
}) })
export const stillsPack = check<FileFacts>({ id: "stills", text: "a composition's stills: no clipped or cramped text, nothing out of the safe areas", over: "file", at: ["edit"], needs: "render" }, async (f) => { export const stillsPack = check<FileFacts>({ id: "stills", text: "a composition's stills: no clipped or cramped text, nothing out of the safe areas", over: "file", at: ["edit"], needs: "render" }, async (f) => {
+4 -75
View File
@@ -9,9 +9,8 @@ import { spawnSync } from "node:child_process"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs" import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path" import path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts" import { type Contract, nameOf, saysOf } from "../contract.ts"
import type { Job } from "../facts.ts" import type { Job } from "../facts.ts"
import { RAEA } from "../media.ts"
/** where a goal's critic verdict is kept, relative to the brief */ /** where a goal's critic verdict is kept, relative to the brief */
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json` export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
@@ -19,11 +18,6 @@ export const TIMEOUT = 300
/** folders that aren't the work: what the job writes about itself, and what tools keep */ /** folders that aren't the work: what the job writes about itself, and what tools keep */
const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"]) const NOT_WORK = new Set(["review", ".git", "node_modules", ".raea", "target", ".cache", ".raea-cloud"])
/** what a check keeps beside a file it read (its report, its words, its scene): a reading of the work, not a change
* to it. A done check that heard a cut's words wrote them beside it, and the critic's verdict of a minute before read
* as older than the work (12-01) */
const READING = /\.(check|words|scene|floor|montage)\.json$/
/** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */ /** when the work last changed (ms): the newest file under dir, its own bookkeeping left out (a bounded walk) */
export function newest(dir: string): number | null { export function newest(dir: string): number | null {
let best: number | null = null let best: number | null = null
@@ -48,7 +42,7 @@ export function newest(dir: string): number | null {
} }
if (st.isDirectory()) { if (st.isDirectory()) {
if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p) if (!(d === dir && NOT_WORK.has(name)) && name !== "node_modules" && name !== ".git") stack.push(p)
} else if (st.isFile() && name !== "NOTES.md" && !READING.test(name)) best = Math.max(best ?? 0, st.mtimeMs) } else if (st.isFile() && name !== "NOTES.md" && !name.endsWith(".check.json")) best = Math.max(best ?? 0, st.mtimeMs)
} }
} }
return best return best
@@ -124,69 +118,7 @@ export function lastVerdict(text: string): Verdict | null {
return null return null
} }
export const BY = ["claude", "kimi", "clef"] as const export const BY = ["claude", "kimi"] as const
/** the critic when none is named: clef where an agent key is set (a raea cloud box, whose shell has no Claude
* sign-in: 12-01, every judging there answered "Not logged in"), else Claude Code */
export const critic = () => (process.env.RAEA_AGENT_KEY && process.env.RAEA_API ? "clef" : "claude")
const PIECE = /[\w@./-]+\.(?:mp4|mov|webm|m4v|png|jpe?g|webp|wav|mp3|m4a)\b/gi
const VIDEO = /\.(?:mp4|mov|webm|m4v)$/i
/** the videos under out/, newest first */
function made(dir: string): string[] {
const out: { f: string; at: number }[] = []
const walk = (d: string) => {
for (const e of existsSync(d) ? readdirSync(d, { withFileTypes: true }) : []) {
const f = path.join(d, e.name)
if (e.isDirectory()) walk(f)
else if (VIDEO.test(e.name)) out.push({ f, at: statSync(f).mtimeMs })
}
}
walk(path.join(dir, "out"))
return out.sort((x, y) => y.at - x.at).map((x) => path.relative(dir, x.f))
}
/** clef-omni as the critic (`raea ask`, paid as ask is): it watches and hears a piece, and reads no folder. A rule is
* asked of the files it names, in its "from A s to B s" window if it has one, else of every video under out/ (the
* newest CLEF_PIECES), and passes when it's true of each; the rules about one piece go in one call */
const CLEF_PIECES = 12
export function clefVerdict(g: Contract, dir: string, ask = askClef): Verdict["rules"] {
const all = made(dir)
const groups = new Map<string, { file: string; from?: string; to?: string; rules: Said[] }>()
const pieces = new Map<string, string[]>()
for (const r of saysOf(g)) {
const named = [...new Set(r.says.match(PIECE) ?? [])].filter((f) => existsSync(path.join(dir, f)))
const files = named.length ? named : all.slice(0, CLEF_PIECES)
const w = /from (\d+(?:\.\d+)?) s to (?:(\d+(?:\.\d+)?) s|its end)/.exec(r.says)
pieces.set(r.id, files)
for (const file of files) {
const key = [file, w?.[1], w?.[2]].join("\u001f")
const at = groups.get(key) ?? { file, from: w?.[1], to: w?.[2], rules: [] }
at.rules.push(r)
groups.set(key, at)
}
}
const got = new Map<string, { pass: boolean; why: string }[]>()
for (const k of groups.values()) {
const answers = ask(dir, k.file, k.rules.map((r) => r.says), k.from, k.to)
k.rules.forEach((r, i) => got.set(r.id, [...(got.get(r.id) ?? []), { pass: answers[i]?.choice === "true" && !answers[i]?.problem, why: `${k.file}: ${answers[i]?.problem ?? answers[i]?.says ?? "no answer"}` }]))
}
const rules: Verdict["rules"] = {}
for (const r of saysOf(g)) {
const a = got.get(r.id) ?? []
const open = a.filter((x) => !x.pass)
rules[r.id] = !pieces.get(r.id)?.length
? { pass: false, why: "clef watches and hears a piece, and this rule names no file on disk while out/ holds no video: name the file in the rule, or judge it --by claude where Claude Code is signed in" }
: { pass: !open.length, why: (open.length ? open : a).map((x) => x.why).join("; ") }
}
return rules
}
type Answer = { choice?: string; says?: string; problem?: string | null }
function askClef(dir: string, file: string, says: string[], from?: string, to?: string): Answer[] {
const r = spawnSync(RAEA, ["ask", file, ...says, "--choose", "true,false", "--json", ...(from ? ["--from", from] : []), ...(to ? ["--to", to] : [])], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
if (r.error) throw new Error(`couldn't run raea ask: ${r.error.message}`)
const rows = String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Answer] : [] } catch { return [] } })
if (rows.length !== says.length) throw new Error(`raea ask answered ${rows.length} of ${says.length} about ${file}: ${String(r.stderr ?? "").trim().slice(-300) || String(r.stdout ?? "").trim().slice(-300)}`)
return rows
}
/** one fresh critic over a goal's `says` rules (`raea goal judge`): its verdict kept at review/judge/NAME.json, /** one fresh critic over a goal's `says` rules (`raea goal judge`): its verdict kept at review/judge/NAME.json,
* stamped with when it was asked (so work changed while it judged counts as changed after) */ * stamped with when it was asked (so work changed while it judged counts as changed after) */
@@ -194,7 +126,6 @@ export function judge(g: Contract, dir: string, by: string): Verdict {
if (!saysOf(g).length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`) if (!saysOf(g).length) throw new Error(`goal ${nameOf(g)} has no \`says\` rules; its \`run\` and \`file\` rules are held by raea goal check`)
if (!(BY as readonly string[]).includes(by)) throw new Error(`--by ${by}: the critics are ${BY.join(", ")}`) if (!(BY as readonly string[]).includes(by)) throw new Error(`--by ${by}: the critics are ${BY.join(", ")}`)
const asked = Math.floor(Date.now() / 1000) const asked = Math.floor(Date.now() / 1000)
if (by === "clef") return keep(g, dir, { at: asked, by, goal: g.aim ?? nameOf(g), rules: clefVerdict(g, dir) })
const p = prompt(g, dir) const p = prompt(g, dir)
const r = by === "claude" ? spawnSync("claude", ["-p", p, "--allowedTools", "Read Grep Glob", "--output-format", "json"], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 }) : spawnSync("kimi", ["-p", p], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 }) const r = by === "claude" ? spawnSync("claude", ["-p", p, "--allowedTools", "Read Grep Glob", "--output-format", "json"], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 }) : spawnSync("kimi", ["-p", p], { cwd: dir, encoding: "utf8", maxBuffer: 1 << 26 })
if (r.error) throw new Error(`couldn't run ${by}: ${r.error.message} (is its CLI installed and signed in?)`) if (r.error) throw new Error(`couldn't run ${by}: ${r.error.message} (is its CLI installed and signed in?)`)
@@ -205,9 +136,7 @@ export function judge(g: Contract, dir: string, by: string): Verdict {
} catch {} } catch {}
const v = lastVerdict(words) const v = lastVerdict(words)
if (!v) throw new Error(`${by} answered no verdict: ${words.slice(-300).trim()}`) if (!v) throw new Error(`${by} answered no verdict: ${words.slice(-300).trim()}`)
return keep(g, dir, { ...v, at: asked, by, goal: g.aim ?? nameOf(g) }) const out: Verdict = { ...v, at: asked, by, goal: g.aim ?? nameOf(g) }
}
function keep(g: Contract, dir: string, out: Verdict): Verdict {
const file = path.join(dir, verdictPath(g)) const file = path.join(dir, verdictPath(g))
mkdirSync(path.dirname(file), { recursive: true }) mkdirSync(path.dirname(file), { recursive: true })
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`) writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
+2 -56
View File
@@ -2,35 +2,26 @@
// at video clips"; "a way of prompting the agent to go above and beyond by adding little surprises"). // at video clips"; "a way of prompting the agent to go above and beyond by adding little surprises").
// seen a video made here has been looked at since its last render: `raea goal seen FILE` makes its contact // seen a video made here has been looked at since its last render: `raea goal seen FILE` makes its contact
// sheet and shows it, and `raea goal seen FILE "what I see and would change"` says what was seen. Both // sheet and shows it, and `raea goal seen FILE "what I see and would change"` says what was seen. Both
// are tied to the file as it is now (its time and size): a render after it needs a new look. A video's // are tied to the file as it is now (its time and size): a render after it needs a new look.
// design is judged apart, on its frames at full size (`--look "..."`): a sheet's tiles show what
// happens, never whether the type, captions and cards look good (12-01, Shane on Dutch).
// surprise (off unless the brief turns it on) the look names the cut's one earned surprise with its moment in // surprise (off unless the brief turns it on) the look names the cut's one earned surprise with its moment in
// seconds: `raea goal seen FILE "..." --surprise "12.5 s: the dog barks on the punchline"`. // seconds: `raea goal seen FILE "..." --surprise "12.5 s: the dog barks on the punchline"`.
import { spawnSync } from "node:child_process"
import { readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path" import path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts" import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { bookkeeping } from "./naming.ts" import { bookkeeping } from "./naming.ts"
/** the least a look says: what's in it and what would change, not "looks good" */ /** the least a look says: what's in it and what would change, not "looks good" */
export const SEEN_LEAST = 80 export const SEEN_LEAST = 80
const MOMENT = /\b\d+(\.\d+)?\s*s\b/ const MOMENT = /\b\d+(\.\d+)?\s*s\b/
/** a look that says nothing of the design at full size (a sheet's tiles can't show it) */
export const unjudged = (s: { look?: string }) => (s.look?.trim().length ?? 0) < SEEN_LEAST
const looked = (f: FileFacts) => f.made && f.kind === "video" && !bookkeeping(f.path) const looked = (f: FileFacts) => f.made && f.kind === "video" && !bookkeeping(f.path)
export const seenPack = check<FileFacts>({ id: "seen", text: "its contact sheet and its frames at full size looked at since its last render, and what was seen, how it looks and what would change said", over: "file", at: ["publish", "done"], needs: "sheet" }, async (f) => { export const seenPack = check<FileFacts>({ id: "seen", text: "its contact sheet looked at since its last render, and what was seen and would change said", over: "file", at: ["publish", "done"], needs: "sheet" }, async (f) => {
if (!looked(f)) return if (!looked(f)) return
const s = f.seen() const s = f.seen()
const name = path.basename(f.path) const name = path.basename(f.path)
if (!s) return found({ says: `${name} hasn't been looked at since its last render`, fix: `raea goal seen ${f.path}, look at every frame of the sheet, then raea goal seen ${f.path} "what you see and would change"` }) if (!s) return found({ says: `${name} hasn't been looked at since its last render`, fix: `raea goal seen ${f.path}, look at every frame of the sheet, then raea goal seen ${f.path} "what you see and would change"` })
if (s.seen.trim().length < SEEN_LEAST) found({ says: `what was seen of ${name} is ${s.seen.trim().length} characters: say what's in it, frame by frame, and what you'd change (${SEEN_LEAST} at least)`, fix: `raea goal seen ${f.path} "..."` }) if (s.seen.trim().length < SEEN_LEAST) found({ says: `what was seen of ${name} is ${s.seen.trim().length} characters: say what's in it, frame by frame, and what you'd change (${SEEN_LEAST} at least)`, fix: `raea goal seen ${f.path} "..."` })
if (unjudged(s)) found({ says: `${name}'s design isn't judged at full size: its type, captions, cards and end, beside a reference ad's frame (${SEEN_LEAST} characters at least)`, fix: `raea goal seen ${f.path}, open each full-size frame beside a reference's, then raea goal seen ${f.path} "..." --look "how it looks beside the reference and what you changed"` })
}) })
export const surprisePack = check<FileFacts>({ id: "surprise", text: "one earned surprise, named with its moment in seconds", over: "file", at: ["publish", "done"] }, async (f) => { export const surprisePack = check<FileFacts>({ id: "surprise", text: "one earned surprise, named with its moment in seconds", over: "file", at: ["publish", "done"] }, async (f) => {
@@ -39,48 +30,3 @@ export const surprisePack = check<FileFacts>({ id: "surprise", text: "one earned
if (!s) return if (!s) return
if (!s.surprise?.trim() || !MOMENT.test(s.surprise)) found({ says: `${path.basename(f.path)}'s surprise isn't named with its moment ("12.5 s: the dog barks on the punchline")`, fix: `raea goal seen ${f.path} "..." --surprise "SECONDS s: what it is"` }) if (!s.surprise?.trim() || !MOMENT.test(s.surprise)) found({ says: `${path.basename(f.path)}'s surprise isn't named with its moment ("12.5 s: the dog barks on the punchline")`, fix: `raea goal seen ${f.path} "..." --surprise "SECONDS s: what it is"` })
}) })
/** what the second opinion is asked of a whole cut, picture and sound (`raea ask`, clef-omni): pointed checks, each
* a yes when the fault is there. Never "does it look good": asked whether Dutch's plain boxes looked designed, clef
* said "strong". 12-01, Shane: "you just have to have them be more specific or pointed like giving it some list of
* design checks to answer ... a few catch all checks on visual and audio design"; "the agent itself is really
* responsible for design" */
export const SECOND = [
// picture
"Are three or more separate text boxes or cards on screen at the same moment at any point?",
"Do the captions, cards and badges all look like the same plain rounded box, with nothing but colour telling them apart?",
"Is any text too small or too cluttered to read at a glance on a phone?",
"Does any text or graphic cover a person's face, or sit cut off at the edge of the frame?",
"Is a product or an app shown only as a box of text, and never as the real product or its screen?",
"Does the end card hold more than a logo, one line and one thing to do?",
"Is there a rendering glitch: a black or frozen frame, torn or blocky video, or a flash?",
// sound
"Is a voice muffled, distant or hard to understand, or is music louder than the person speaking?",
"Is there harsh, shrill or clipping sound, or music that starts or stops abruptly?",
"Is there a stretch of dead air, where nothing is said and nothing is heard?",
"Is the same sound effect used in the same way more than three times?",
]
type Opinion = { choice?: string; says?: string }
/** a second opinion on a cut, from clef watching and hearing all of it (12-01, Shane: "the agent itself should be
* watching and revising itself always and use clef omni as a secondary opinion or catch all"): each check, the
* faults it found first, kept beside the file (FILE.second.json) for the file as it is now. Null where it couldn't
* be asked. */
export function second(file: string, ask = askSecond): string | null {
const [st, kept] = [statSync(file), `${stem(file)}.second.json`]
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { render: string; says: string }
if (k.render === stamp) return k.says
} catch {}
const got = ask(file)
if (got.length !== SECOND.length) return null
const rows = got.map((o, i) => ({ q: SECOND[i], found: o.choice === "yes", says: o.says ?? o.choice ?? "no answer" }))
const says = [...rows.filter((r) => r.found), ...rows.filter((r) => !r.found)].map((r) => ` ${r.found ? "FOUND" : "clear"} (${r.says}): ${r.q}`).join("\n")
writeFileSync(kept, `${JSON.stringify({ render: stamp, says }, null, 1)}\n`)
return says
}
function askSecond(file: string): Opinion[] {
const r = spawnSync(RAEA, ["ask", file, ...SECOND, "--choose", "yes,no", "--json", "--brief", "none"], { cwd: path.dirname(file), encoding: "utf8", maxBuffer: 1 << 26 })
return String(r.stdout ?? "").split("\n").flatMap((l) => { try { const o = JSON.parse(l); return o.answer ? [o as Opinion] : [] } catch { return [] } })
}
+8 -41
View File
@@ -13,9 +13,6 @@
// eye, plane and tone are warnings at each cut, in Murch's order; one becomes an error when it breaks at more than half // eye, plane and tone are warnings at each cut, in Murch's order; one becomes an error when it breaks at more than half
// of a file's cuts (a habit, not a choice). A cut on a word is the sound pack's (edit-on-sound), not this one's. // of a file's cuts (a habit, not a choice). A cut on a word is the sound pack's (edit-on-sound), not this one's.
import { spawnSync } from "node:child_process" import { spawnSync } from "node:child_process"
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { check, found } from "raea/check" import { check, found } from "raea/check"
import type { Beat } from "raea/brief.gen" import type { Beat } from "raea/brief.gen"
import type { FileFacts } from "../facts.ts" import type { FileFacts } from "../facts.ts"
@@ -45,18 +42,9 @@ export type Finding = { level: "error" | "warn"; kind: "pace" | "tempo" | "eye"
export function read(file: string, fps: number, width: number, height: number): Read { export function read(file: string, fps: number, width: number, height: number): Read {
const w = READ_W const w = READ_W
const h = Math.max(2, Math.round((READ_W * height) / width / 2) * 2) const h = Math.max(2, Math.round((READ_W * height) / width / 2) * 2)
// into a file, not down a pipe: 13 MB of frames through the pipe took 9.7 s of a 35 s cut's read on a cloud box, and const r = spawnSync("ffmpeg", ["-v", "error", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", "-"], { maxBuffer: 1 << 30 })
// 4.6 s into a file (12-01) if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
const dir = mkdtempSync(path.join(tmpdir(), "raea-montage-read-")) const buf = r.stdout as Buffer
let buf: Buffer
try {
const raw = path.join(dir, "frames.raw")
const r = spawnSync("ffmpeg", ["-v", "error", "-an", "-i", file, "-vf", `scale=${w}:${h},format=rgb24`, "-f", "rawvideo", raw], { encoding: "utf8" })
if (r.status !== 0) throw new Error(`ffmpeg couldn't read ${file}: ${String(r.stderr).trim().slice(-200)}`)
buf = readFileSync(raw)
} finally {
rmSync(dir, { recursive: true, force: true })
}
const size = w * h * 3 const size = w * h * 3
const frames: Frame[] = [] const frames: Frame[] = []
for (let o = 0; o + size <= buf.length; o += size) { for (let o = 0; o + size <= buf.length; o += size) {
@@ -247,25 +235,6 @@ export function acrossCuts(r: Read, cuts: number[], o: { faces?: Faces[]; rate?:
return out return out
} }
/** a video's montage findings, kept beside it */
export const MONTAGE_EXT = "montage.json"
/** A video's findings from `measure`, kept beside it (FILE.montage.json) and measured again only when the video is
* newer or what they were measured against (`given`: its beats, its scene reading) is another. Reading a 35 s cut's
* frames took 7 s each time the goal was checked, on files that hadn't changed (12-01). */
export function keptOr(abs: string, given: string, measure: () => Finding[]): Finding[] {
const kept = `${abs.replace(/\.[^./]+$/, "")}.${MONTAGE_EXT}`
try {
const k = JSON.parse(readFileSync(kept, "utf8")) as { given: string; findings: Finding[] }
if (statSync(kept).mtimeMs >= statSync(abs).mtimeMs && k.given === given) return k.findings
} catch {}
const findings = measure()
try {
writeFileSync(kept, `${JSON.stringify({ given, findings })}\n`)
} catch {}
return findings
}
const where = ([x, y]: [number, number]) => `${y < 0.34 ? "top" : y > 0.66 ? "bottom" : "middle"} ${x < 0.34 ? "left" : x > 0.66 ? "right" : "centre"}` const where = ([x, y]: [number, number]) => `${y < 0.34 ? "top" : y > 0.66 ? "bottom" : "middle"} ${x < 0.34 ? "left" : x > 0.66 ? "right" : "centre"}`
export default check<FileFacts>( export default check<FileFacts>(
@@ -275,6 +244,9 @@ export default check<FileFacts>(
const c = f.contract?.kind === "cut" ? f.contract.cut : undefined const c = f.contract?.kind === "cut" ? f.contract.cut : undefined
const plan = c ? cutOf(c, f.path) : null const plan = c ? cutOf(c, f.path) : null
const beats = plan?.plan.beats ?? [] const beats = plan?.plan.beats ?? []
const r = read(f.abs, f.fps, f.width, f.height)
if (r.frames.length < 2) return
const cuts = cutsOf(r)
let faces: Faces[] | undefined let faces: Faces[] | undefined
let rate = 0 let rate = 0
try { try {
@@ -286,12 +258,7 @@ export default check<FileFacts>(
if (!(e instanceof Unmet)) throw e if (!(e instanceof Unmet)) throw e
} }
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] }) const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
for (const x of keptOr(f.abs, JSON.stringify({ beats, faces: faces?.length ?? null, rate }), () => { for (const x of pace(beats, cuts, r.fps, r.frames.length / r.fps)) say(x)
const r = read(f.abs, f.fps, f.width!, f.height!) for (const x of acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })) say(x)
if (r.frames.length < 2) return []
const cuts = cutsOf(r)
return [...pace(beats, cuts, r.fps, r.frames.length / r.fps), ...acrossCuts(r, cuts, { faces, rate, beatsAt: beats.map((b) => b.at) })]
}))
say(x)
}, },
) )
+1 -1
View File
@@ -32,7 +32,7 @@ export const sizeOf = (name: string) => path.basename(name).replace(/\.[a-z0-9]{
export const adOf = (name: string) => path.basename(name).replace(/\.[a-z0-9]{2,4}$/i, "").split("_").filter((p) => !VERSION.test(p) && !SIZE.test(p) && !EXTRA.test(p)).join("_") export const adOf = (name: string) => path.basename(name).replace(/\.[a-z0-9]{2,4}$/i, "").split("_").filter((p) => !VERSION.test(p) && !SIZE.test(p) && !EXTRA.test(p)).join("_")
/** the job's own writing about itself: review rounds, previews, sheets */ /** the job's own writing about itself: review rounds, previews, sheets */
export const bookkeeping = (rel: string) => /^(\.\/)?(review|previews|\.raea)\//.test(rel) || /\.(sheet|seen|second|check)\.[a-z]+$/i.test(rel) || /\.looks\//.test(rel) export const bookkeeping = (rel: string) => /^(\.\/)?(review|previews|\.raea)\//.test(rel) || /\.(sheet|seen|check)\.[a-z]+$/i.test(rel)
export default check<FileFacts>( export default check<FileFacts>(
{ id: "naming", text: "files named client_concept_variant_v#_size", over: "file", at: ["edit", "render", "publish", "done"] }, { id: "naming", text: "files named client_concept_variant_v#_size", over: "file", at: ["edit", "render", "publish", "done"] },
+2 -7
View File
@@ -7,7 +7,6 @@
// itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is // itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is
// free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or // free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or
// a person, and a place of the same size costs much less; that place is what's said. // a person, and a place of the same size costs much less; that place is what's said.
// Over a face or a thing it's an error; over a person's body alone, a warning.
// //
// raea make place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json] // raea make place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12): // FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12):
@@ -258,12 +257,8 @@ export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[
const q = `${on.text.length > 40 ? `“${on.text.slice(0, 40)}...”` : `“${on.text}”`}${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}` const q = `${on.text.length > 40 ? `“${on.text.slice(0, 40)}...”` : `“${on.text}”`}${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
const when = on.to - on.from < 0.5 ? `at ${on.from.toFixed(1)} s` : `from ${on.from.toFixed(1)} s to ${on.to.toFixed(1)} s` const when = on.to - on.from < 0.5 ? `at ${on.from.toFixed(1)} s` : `from ${on.from.toFixed(1)} s to ${on.to.toFixed(1)} s`
if (best && best.cost <= here - BETTER) { if (best && best.cost <= here - BETTER) {
// an error only for what a shot can't lose: a face, or the thing it shows (the product, the dog, a phone held const face = under.includes("a face")
// up). A caption over someone's coat with clearer ground elsewhere is a warning with the place said (12-01: two out.push({ level: face || here >= BAD + 1.5 ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
// people fill a 9:16 interview frame, each caption's clearest place is a different one, and an agent spent
// hours cropping shots and rendering again to clear errors a steady caption position can't)
const hard = under.some((u) => u !== "a person in the shot")
out.push({ level: hard ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea make place shows the clear places in a shot` })
} else if (under.includes("a face")) { } else if (under.includes("a face")) {
out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` }) out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` })
} else if (here >= BAD + 1.5) { } else if (here >= BAD + 1.5) {
+1 -14
View File
@@ -11,24 +11,11 @@ import { check, found } from "raea/check"
import type { Job } from "../facts.ts" import type { Job } from "../facts.ts"
import { adOf, bookkeeping, sizeOf } from "./naming.ts" import { adOf, bookkeeping, sizeOf } from "./naming.ts"
/** The size a made file is in, as a name says one (9x16): its name's, else a video's own shape (1080x1920 is 9x16).
* A picture with no size in its name is a still of the work, a sheet or a strip, not a size of an ad. Told by pixels
* alone, an ad named _9x16 beside its own 1080x1920 renders and one 540x960 still read as three sizes, and an agent
* with one size made couldn't stop for its sign-off (12-01). */
export function shapeOf(f: { path: string; kind?: string; width?: number; height?: number }): string | null {
const named = sizeOf(f.path)
if (named) return named
if (f.kind !== "video" || !f.width || !f.height) return null
const gcd = (a: number, b: number): number => (b ? gcd(b, a % b) : a)
const g = gcd(f.width, f.height)
return `${f.width / g}x${f.height / g}`
}
export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => { export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => {
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image")) const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
const sizes = new Map<string, string[]>() const sizes = new Map<string, string[]>()
for (const f of made) { for (const f of made) {
const s = shapeOf(f) const s = sizeOf(f.path) ?? (f.width && f.height ? `${f.width}x${f.height}` : null)
if (s) sizes.set(s, [...(sizes.get(s) ?? []), f.path]) if (s) sizes.set(s, [...(sizes.get(s) ?? []), f.path])
} }
if (sizes.size < 2) return if (sizes.size < 2) return
+11 -19
View File
@@ -13,7 +13,7 @@
// says what for; it holds nothing. // says what for; it holds nothing.
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts) // raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
// raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise // raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise
// raea goal judge [--goal NAME] [--by claude|kimi|clef] a fresh critic over a goal's `says` rules (review/judge/) // raea goal judge [--goal NAME] [--by claude|kimi] a fresh critic over a goal's `says` rules (review/judge/)
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs" import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path" import path from "node:path"
import { pathToFileURL } from "node:url" import { pathToFileURL } from "node:url"
@@ -24,9 +24,8 @@ import * as media from "./media.ts"
import { registeredPack } from "./packs/job.ts" import { registeredPack } from "./packs/job.ts"
import { tastePack } from "./packs/taste.ts" import { tastePack } from "./packs/taste.ts"
import { loadProject, type Project } from "./project.ts" import { loadProject, type Project } from "./project.ts"
import { critic, judge } from "./packs/goal.ts" import { judge } from "./packs/goal.ts"
import { PACK_CHECKS } from "./packs/index.ts" import { PACK_CHECKS } from "./packs/index.ts"
import { second } from "./packs/look.ts"
import { deliverablesOf } from "./packs/job.ts" import { deliverablesOf } from "./packs/job.ts"
import { bookkeeping } from "./packs/naming.ts" import { bookkeeping } from "./packs/naming.ts"
import { placeReport } from "./packs/place.ts" import { placeReport } from "./packs/place.ts"
@@ -228,9 +227,9 @@ const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.star
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json] const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|- raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
raea goal seen FILE (its contact sheet and its frames at full size, to look at) raea goal seen FILE (its contact sheet, to look at every frame)
raea goal seen FILE "what you see and would change" --look "its design at full size, beside a reference" [--surprise "SECONDS s: what it is"] raea goal seen FILE "what you see and would change" [--surprise "SECONDS s: what it is"]
raea goal judge [--goal NAME] [--by claude|kimi|clef] raea goal judge [--goal NAME] [--by claude|kimi]
raea make place FILE [--at S[,S...]] [--box WxH]` raea make place FILE [--at S[,S...]] [--box WxH]`
export async function main(argv: string[]): Promise<number> { export async function main(argv: string[]): Promise<number> {
@@ -255,15 +254,11 @@ export async function main(argv: string[]): Promise<number> {
} }
if (verb === "tasks") return tasksMain(a) if (verb === "tasks") return tasksMain(a)
if (verb === "seen") { if (verb === "seen") {
const [file, said] = positional(a, ["--surprise", "--look"]) const [file, said] = positional(a, ["--surprise"])
if (!file || !existsSync(file)) return usage() if (!file || !existsSync(file)) return usage()
if (!said?.trim()) { if (!said?.trim()) {
const sheet = media.sheet(path.resolve(file)) const sheet = media.sheet(path.resolve(file))
const full = kindOf(path.resolve(file)) === "video" ? media.looks(path.resolve(file)) : [] console.log(`${sheet}\nlook at every frame, then: raea goal seen ${file} "what you see and would change"`)
// on raea cloud (where the critic is clef), a second opinion on the whole cut with its sound: never the look itself
const op = full.length && critic() === "clef" ? second(path.resolve(file)) : null
if (op) console.log(`a second opinion (clef watched and heard all of it and answered a list of checks; a FOUND is a fix or a reason it's wrong; how it looks is still yours to judge, on the frames):\n${op}`)
console.log(`${sheet}\n${full.join("\n")}\nlook at every frame of the sheet for what happens, and open each full-size frame for how it looks (type, captions, cards, the end: beside a reference ad's frame, not from the sheet), then: raea goal seen ${file} "what you see and would change"${full.length ? ' --look "its design at full size, beside a reference, and what you changed"' : ""}`)
return 0 return 0
} }
const abs = path.resolve(file) const abs = path.resolve(file)
@@ -272,12 +267,9 @@ export async function main(argv: string[]): Promise<number> {
console.error(`raea goal seen: ${path.basename(file)} has no sheet since its last render: raea goal seen ${file}, and look at it first`) console.error(`raea goal seen: ${path.basename(file)} has no sheet since its last render: raea goal seen ${file}, and look at it first`)
return 1 return 1
} }
const [st, surprise, look] = [statSync(abs), flag(a, "--surprise"), flag(a, "--look")?.trim()] const st = statSync(abs)
if (kindOf(abs) === "video" && (!look || !media.looksFresh(abs))) { const surprise = flag(a, "--surprise")
console.error(`raea goal seen: ${path.basename(file)}'s design isn't judged yet: raea goal seen ${file} makes its frames at full size; open them, then say --look "its type, captions and cards beside a reference, and what you changed"`) writeFileSync(`${media.stem(abs)}.seen.json`, `${JSON.stringify({ video: path.basename(abs), render: `${Math.round(st.mtimeMs)} ${st.size}`, sheet: path.basename(sheet), seen: said.trim(), ...(surprise ? { surprise } : {}), at: new Date().toISOString() }, null, 1)}\n`)
return 1
}
writeFileSync(`${media.stem(abs)}.seen.json`, `${JSON.stringify({ video: path.basename(abs), render: `${Math.round(st.mtimeMs)} ${st.size}`, sheet: path.basename(sheet), seen: said.trim(), ...(look ? { look } : {}), ...(surprise ? { surprise } : {}), at: new Date().toISOString() }, null, 1)}\n`)
console.log(`${media.stem(path.basename(abs))}.seen.json: seen as it is now`) console.log(`${media.stem(path.basename(abs))}.seen.json: seen as it is now`)
return 0 return 0
} }
@@ -312,7 +304,7 @@ export async function main(argv: string[]): Promise<number> {
console.error(`raea goal judge: ${!root ? "no brief.ts here or above" : !said.length ? `no goal${name ? ` named ${name}` : ""} here has \`says\` rules` : `several goals have \`says\` rules (${said.map(nameOf).join(", ")}): name one with --goal`}`) console.error(`raea goal judge: ${!root ? "no brief.ts here or above" : !said.length ? `no goal${name ? ` named ${name}` : ""} here has \`says\` rules` : `several goals have \`says\` rules (${said.map(nameOf).join(", ")}): name one with --goal`}`)
return 2 return 2
} }
const v = judge(said[0], root, flag(a, "--by") ?? critic()) const v = judge(said[0], root, flag(a, "--by") ?? "claude")
for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`) for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`)
return 0 return 0
} }
-52
View File
@@ -1,52 +0,0 @@
// A made video's floor report is kept beside it and measured again only for cause (packs/floor.ts)
import { expect, test } from "bun:test"
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { floorOf, type Measured } from "../src/packs/floor.ts"
import { keptOr } from "../src/packs/montage.ts"
test("a floor report is kept: measured once, again when the video is newer, and always while it holds an error", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-floor-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
let runs = 0
let out: Measured[] = [{ level: "warn", says: "quiet" }]
const by = () => (runs++, out)
expect(floorOf(v, undefined, d, by)).toEqual(out)
expect(floorOf(v, undefined, d, by)).toEqual(out)
expect(runs).toBe(1)
// the video made again
const later = new Date(Date.now() + 60_000)
utimesSync(v, later, later)
floorOf(v, undefined, d, by)
expect(runs).toBe(2)
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 120_000), new Date(Date.now() + 120_000))
floorOf(v, undefined, d, by)
expect(runs).toBe(2)
// an error isn't kept as an answer
utimesSync(v, new Date(Date.now() + 180_000), new Date(Date.now() + 180_000))
out = [{ level: "error", says: "a placeholder brand kit" }]
floorOf(v, undefined, d, by)
utimesSync(path.join(d, "a.floor.json"), new Date(Date.now() + 240_000), new Date(Date.now() + 240_000))
floorOf(v, undefined, d, by)
expect(runs).toBe(4)
rmSync(d, { recursive: true, force: true })
})
test("montage findings are kept: measured again when the video is newer or its beats are others", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-montage-kept-"))
const v = path.join(d, "a.mp4")
writeFileSync(v, "x")
let runs = 0
const by = () => (runs++, [{ level: "warn" as const, kind: "pace" as const, at: 1, says: "long" }])
keptOr(v, "a", by)
expect(keptOr(v, "a", by)).toEqual([{ level: "warn", kind: "pace", at: 1, says: "long" }])
expect(runs).toBe(1)
keptOr(v, "b", by)
expect(runs).toBe(2)
utimesSync(v, new Date(Date.now() + 60_000), new Date(Date.now() + 60_000))
keptOr(v, "b", by)
expect(runs).toBe(3)
rmSync(d, { recursive: true, force: true })
})
+2 -33
View File
@@ -1,10 +1,9 @@
// The rule packs (MK29, ported from Rust's goal gate tests): run rules pass or say why, says rules need a fresh critic; // The rule packs (MK29, ported from Rust's goal gate tests): run rules pass or say why, says rules need a fresh critic;
// any goal carries rules. // any goal carries rules.
import { expect, test } from "bun:test" import { expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs" import { mkdirSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path" import path from "node:path"
import { clefVerdict, lastVerdict, newest } from "../src/packs/goal.ts" import { lastVerdict, newest } from "../src/packs/goal.ts"
import { goalCheck } from "../src/run.ts" import { goalCheck } from "../src/run.ts"
import { project, put } from "./project.ts" import { project, put } from "./project.ts"
@@ -62,33 +61,3 @@ test("a check runs only at its moments", async () => {
expect((await goalCheck({ cwd: d, at: "edit" })).checks).not.toContain("run") expect((await goalCheck({ cwd: d, at: "edit" })).checks).not.toContain("run")
expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run") expect((await goalCheck({ cwd: d, at: "done" })).checks).toContain("run")
}) })
test("clef judges a rule on the file it names, else on every video made, and says when there's nothing to watch", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
for (const f of ["out/cuts/a_9x16.mp4", "out/cuts/b_9x16.mp4"]) writeFileSync(path.join(d, f), "x")
const g = { name: "rules", rules: [{ id: "named", says: "In out/cuts/a_9x16.mp4, from 0 s to 3 s, the host is speaking" }, { id: "all", says: "No caption covers a face" }] } as never
const asked: string[] = []
const rules = clefVerdict(g, d, (_dir, file, says, from, to) => {
asked.push(`${file} ${from ?? ""}-${to ?? ""} ${says.length}`)
return says.map((q) => ({ choice: q.includes("caption") && file.includes("b_") ? "false" : "true", says: "said" }))
})
expect(asked.sort()).toEqual(["out/cuts/a_9x16.mp4 - 1", "out/cuts/a_9x16.mp4 0-3 1", "out/cuts/b_9x16.mp4 - 1"])
expect(rules.named?.pass).toBe(true)
expect(rules.all?.pass).toBe(false)
expect(rules.all?.why).toBe("out/cuts/b_9x16.mp4: said")
const empty = mkdtempSync(path.join(tmpdir(), "raea-goal-clef-"))
expect(clefVerdict(g, empty, () => []).all?.why).toContain("names no file on disk")
})
test("a reading kept beside a file isn't the work changing", () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-newest-"))
mkdirSync(path.join(d, "out/cuts"), { recursive: true })
const cut = path.join(d, "out/cuts/a_b_c_v1_9x16.mp4")
writeFileSync(cut, "x")
utimesSync(cut, 1000, 1000)
for (const ext of ["words.json", "scene.json", "check.json", "floor.json", "montage.json"]) writeFileSync(path.join(d, `out/cuts/a_b_c_v1_9x16.${ext}`), "{}")
expect(newest(d)).toBe(1_000_000)
writeFileSync(path.join(d, "out/cuts/a_b_c_v1_9x16.render.json"), "{}")
expect(newest(d)!).toBeGreaterThan(1_000_000)
})
-40
View File
@@ -1,40 +0,0 @@
// The seen pack's two looks (12-01): what happens, on the contact sheet, and how it looks, on frames at full size.
import { expect, test } from "bun:test"
import { existsSync, readFileSync, writeFileSync } from "node:fs"
import { LOOKS, looks, looksFresh, stem } from "../src/media.ts"
import { SECOND, second, unjudged } from "../src/packs/look.ts"
import { CLIP, project, put, touch } from "./project.ts"
test("a video's frames at full size are made beside it, and again only after it changes", () => {
const f = put(project({}), "out/cuts/acme_dog_hook1_v1_9x16.mp4", readFileSync(CLIP))
touch(f, -60)
expect(looksFresh(f)).toBe(false)
const made = looks(f)
expect(made.length).toBe(LOOKS)
expect(made.every((p) => existsSync(p) && p.startsWith(`${stem(f)}.looks`))).toBe(true)
expect(looksFresh(f)).toBe(true)
writeFileSync(f, readFileSync(CLIP))
touch(f, 60)
expect(looksFresh(f)).toBe(false)
})
test("a look at the sheet alone doesn't pass: the design is judged at full size, in its own words", () => {
expect(unjudged({})).toBe(true)
expect(unjudged({ look: "looks good" })).toBe(true)
expect(unjudged({ look: "Captions are 72 px bold with the spoken word in yellow, as the reference's; the offer is one pill, not three boxes." })).toBe(false)
})
test("the second opinion is asked once for a file as it is, the faults it found first, and again after it changes", () => {
const f = put(project({}), "out/cuts/acme_dog_hook1_v1_9x16.mp4", readFileSync(CLIP))
let asked = 0
const ask = () => (asked++, SECOND.map((_, i) => ({ choice: i === 3 ? "yes" : "no", says: i === 3 ? "yes (0.81)" : "no (0.9)" })))
const says = second(f, ask)!
expect(says.split("\n")[0]).toBe(` FOUND (yes (0.81)): ${SECOND[3]}`)
expect(says.split("\n")[1]).toStartWith(" clear")
expect(second(f, ask)).toBe(says)
expect(asked).toBe(1)
touch(f, 60)
second(f, ask)
expect(asked).toBe(2)
expect(second(put(project({}), "out/a_b_c_v1_9x16.mp4", readFileSync(CLIP)), () => [])).toBeNull()
})
+1 -31
View File
@@ -1,9 +1,6 @@
import { test } from "bun:test" import { test } from "bun:test"
import assert from "node:assert/strict" import assert from "node:assert/strict"
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs" import { readFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { RATE, scene, SCENE_EXT, useSender } from "../src/media.ts"
import { placeReport, textOver } from "../src/packs/place.ts" import { placeReport, textOver } from "../src/packs/place.ts"
test("the place pack's model", async () => { test("the place pack's model", async () => {
@@ -45,31 +42,4 @@ test("the place pack's model", async () => {
assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b)) assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b))
ok("a caption over a person who fills the frame is at most a warning") ok("a caption over a person who fills the frame is at most a warning")
// a: a caption across the woman's body with clear ground above her: a warning that names the place, never an error
// (12-01: errors here had an agent cropping interview shots and rendering again for hours)
for (const y of [300, 400, 500]) {
const d = textOver(man([t("Did you know you", 480, y, 536, 88)]), [sc.a], 1).filter((x) => /covers a person in the shot (at|from)/.test(x.says))
assert.ok(d.length === 1 && d[0].level === "warn", JSON.stringify(d))
}
assert.match(textOver(man([t("Did you know you", 480, 400, 536, 88)]), [sc.a], 1)[0].says, /covers a person in the shot at 0\.0 s: move it to left \d+ px, top \d+ px/)
ok("a caption over a body with clearer ground elsewhere is a warning with the place said")
})
test("a video's scene reading is kept beside it and read again only when the video is newer", async () => {
const d = mkdtempSync(path.join(tmpdir(), "raea-scene-kept-"))
const cut = path.join(d, "a_b_c_v1_9x16.mp4")
writeFileSync(cut, "not a real video")
const kept = { rate: RATE, side: 540, faces: [null], scenes: [{ w: 540, h: 960, grid: { cols: 1, rows: 1, people: ["0"] }, things: [], faces: [] }] }
writeFileSync(path.join(d, `a_b_c_v1_9x16.${SCENE_EXT}`), JSON.stringify(kept))
let asked = 0
useSender(async () => (asked++, { status: 500, ok: false, text: "" }))
delete process.env.RAEA_CLOUD_GPU_URL
// no farm here at all, and the reading still comes back: from beside the file
const r = await scene(cut)
assert.equal(r.scenes.length, 1)
assert.equal(r.rate, RATE)
assert.equal(asked, 0)
// a reading at named seconds is never the whole file's
await assert.rejects(scene(cut, [1, 2]), /no scene reader/)
}) })
-11
View File
@@ -4,7 +4,6 @@ import { beforeAll, expect, test } from "bun:test"
import { goalCheck } from "../src/run.ts" import { goalCheck } from "../src/run.ts"
import { CLIP, project, put } from "./project.ts" import { CLIP, project, put } from "./project.ts"
import { readFileSync } from "node:fs" import { readFileSync } from "node:fs"
import { shapeOf } from "../src/packs/sizes.ts"
beforeAll(() => { beforeAll(() => {
process.env.RAEA_REAL = "/usr/bin/false" process.env.RAEA_REAL = "/usr/bin/false"
@@ -32,13 +31,3 @@ test("every size of the newest version passes; a person's answer can say fewer",
expect((await all(answered, sizes)).filter((x) => x.check === "sizes-all")).toEqual([]) expect((await all(answered, sizes)).filter((x) => x.check === "sizes-all")).toEqual([])
expect((await all(answered, ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4"])).filter((x) => x.check === "sizes-all")).toEqual([]) expect((await all(answered, ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4"])).filter((x) => x.check === "sizes-all")).toEqual([])
}) })
test("one size is one size however it's told: a name's 9x16, a 1080x1920 video, never a still", () => {
expect(shapeOf({ path: "out/cuts/dutch_vetbill_hooka_v1_9x16.mp4", kind: "video", width: 1080, height: 1920 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka.mp4", kind: "video", width: 1080, height: 1920 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka_small.mp4", kind: "video", width: 540, height: 960 })).toBe("9x16")
expect(shapeOf({ path: "out/cuts/hooka.mp4", kind: "video", width: 1080, height: 1350 })).toBe("4x5")
expect(shapeOf({ path: "out/stills/a1_38.jpg", kind: "image", width: 540, height: 960 })).toBe(null)
expect(shapeOf({ path: "out/stills/strip.png", kind: "image", width: 1080, height: 480 })).toBe(null)
expect(shapeOf({ path: "out/stills/dutch_vetbill_end_v1_1x1.png", kind: "image", width: 1080, height: 1080 })).toBe("1x1")
})
+2 -3
View File
@@ -38,9 +38,8 @@ media/brief.txt, so a rule can't be made up and a line can't be paraphrased away
out/cuts/ID_WxH.mp4 (name each cut's id client_concept_variant_v#, so the file is client_concept_variant_v#_9x16.mp4): out/cuts/ID_WxH.mp4 (name each cut's id client_concept_variant_v#, so the file is client_concept_variant_v#_9x16.mp4):
its shape and length; what it says, heard after its last change, for each `say`, `never` and the CTA; its words its shape and length; what it says, heard after its last change, for each `say`, `never` and the CTA; its words
against CUT.lines.txt beside it; its edit points, line levels and effects; its faces, text sizes and text placement; against CUT.lines.txt beside it; its edit points, line levels and effects; its faces, text sizes and text placement;
and that you looked at it since its last render: its contact sheet for what happens, and its frames at full size and that you looked at its contact sheet since its last render (`raea goal seen CUT`, then `raea goal seen CUT
(CUT.looks/) for how it looks, since a sheet's tiles are too small to judge type, captions and cards on (`raea goal "..."`). Every render ends with `raea goal check CUT --at render`; the job isn't done, and the Stop hook won't let
seen CUT`, then `raea goal seen CUT "..." --look "its design beside a reference, and what you changed"`). Every render ends with `raea goal check CUT --at render`; the job isn't done, and the Stop hook won't let
you end, until `--at done` passes and every `open` item has the person's answer, written in with who gave it. Turn a you end, until `--at done` passes and every `open` item has the person's answer, written in with who gave it. Turn a
pack off on the contract (`packs: { place: false }`) only when the brief says so. pack off on the contract (`packs: { place: false }`) only when the brief says so.
-14
View File
@@ -40,20 +40,6 @@
loudness, a join into dead silence gets the room's tone, and the whole mix comes to -14 LUFS integrated with true loudness, a join into dead silence gets the room's tone, and the whole mix comes to -14 LUFS integrated with true
peaks under -1 dBTP, which is what the floor's loudness defect asks for. Don't level lines with `gainDb` or master peaks under -1 dBTP, which is what the floor's loudness defect asks for. Don't level lines with `gainDb` or master
the voice outside raea. One `<Mix lufs={…} ceiling={…} />` per composition sets another target. the voice outside raea. One `<Mix lufs={…} ceiling={…} />` per composition sets another target.
- A music file under talking is ducked for you. With no Tone graph of your own, raea's default mix puts footage and
voice files (a video file, or vo, voice, narration, dialogue, speech, interview in the name) on a talk bus, effects
(sfx, foley, whoosh, sting, riser, impact in the name) on the master, and any other audio file on a music bed ducked
6 dB under the talking that comes back up where nobody talks, so a wordless end card keeps its music. It is slight
on purpose: set the bed's own level from the table below. `bus="master"` keeps a sound out of it; your own
`Tone.buses` are never changed by it. The check is on the export: the voice at least 10 dB above what's under it
between words (`raea goal check`'s voice check).
- Air between words reads as dead air in social cuts and ads, most of all in the first 3 seconds. `tighten(words,
{ levels })` (`import { tighten, airGaps } from "raea"`) returns the spans of a take to keep: each gap cut down to
about 0.15 s in the hook and 0.25 s after, only between words, 80 ms kept either side, and pulled back wherever the
take is still loud (a transcript often ends a word early). Run it on the source take's words (`raea words TAKE`) and
levels, never the mixed export, lay each span as its own `<Video startFrom endAt>`, and read the words pass after.
A hook opens on its first word within about 0.3 s; a board or a sign held in silence for people to read is dead
air, not a hook (`raea goal check`'s hook and airgaps checks).
- Put the sounds in the tree in time order. The engine keys a sound's stretch by its place in the tree, so adding a - Put the sounds in the tree in time order. The engine keys a sound's stretch by its place in the tree, so adding a
sound in the middle of the list can split the ones after it. sound in the middle of the list can split the ones after it.
- Balance relative to the voice. The approved pieces, mastered to -14 LUFS, sit like this (each a `gainDb` on top of - Balance relative to the voice. The approved pieces, mastered to -14 LUFS, sit like this (each a `gainDb` on top of
+1 -1
Submodule skills updated: a2481c23ef...105aede654.
-17
View File
@@ -1,17 +0,0 @@
[package]
name = "raea-sys-facetrack"
version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
description = "A take's face track for <Video framing=\"face\">: where the largest face's eyes are through the take, sampled by raea-perceive and kept as TAKE.faces.json beside it"
[dependencies]
# the media backend clips decode with (media_backend)
raea-sys-frame = { path = "../frame" }
# raea-perceive, which finds the eyes
raea-io-assets = { path = "../../io/assets" }
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
# a sample made small and written as a PNG for raea-perceive
image = { version = "0.25", default-features = false, features = ["png"] }
serde_json = "1"
-4
View File
@@ -129,8 +129,6 @@ raea-sys-page = "systems"
raea-sys-page-net = "systems" raea-sys-page-net = "systems"
raea-sys-page-ops = "systems" raea-sys-page-ops = "systems"
raea-sys-frame = "systems" raea-sys-frame = "systems"
# a take's face track (TAKE.faces.json), for <Video framing="face">
raea-sys-facetrack = "systems"
raea-sys-shots = "systems" raea-sys-shots = "systems"
raea-sys-hold = "systems" raea-sys-hold = "systems"
raea-sys-body = "systems" raea-sys-body = "systems"
@@ -190,8 +188,6 @@ raea-runtime-canvas = "runtime"
raea-runtime-wear = "runtime" raea-runtime-wear = "runtime"
raea-runtime-export = "runtime" raea-runtime-export = "runtime"
raea-runtime-pagestore = "runtime" raea-runtime-pagestore = "runtime"
# render --review's tiles and sheets (raea-runtime-export measures and places the cameras)
raea-runtime-review = "runtime"
raea-runtime-cssurls = "runtime" raea-runtime-cssurls = "runtime"
raea-runtime-pid = "runtime" raea-runtime-pid = "runtime"
raea-runtime-page = "runtime" raea-runtime-page = "runtime"
+1 -1
View File
@@ -30,7 +30,7 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
Some("eyes") => { Some("eyes") => {
// eyes IMG...: a line per picture with the largest face's eyes, their midpoint in shares of the picture // eyes IMG...: a line per picture with the largest face's eyes, their midpoint in shares of the picture
// from the top left, or null with no face: where <Video framing="face"> holds them (sdk/react // from the top left, or null with no face: where <Video framing="face"> holds them (sdk/react
// systems/facetrack). The face mesh's iris centres (points 468 and 473); BlazeFace's eye keypoints when // runtime/page/src/faces.rs). The face mesh's iris centres (points 468 and 473); BlazeFace's eye keypoints when
// the mesh sees no face (they sit a few pixels low on a small face: 0.327 of face.mp4's height where // the mesh sees no face (they sit a few pixels low on a small face: 0.327 of face.mp4's height where
// the irises are at 0.305) // the irises are at 0.305)
let m = raea_sys_vision::face::models()?; let m = raea_sys_vision::face::models()?;
+2 -8
View File
@@ -40,18 +40,12 @@ cp "$work/raea/README" "$appdir/usr/share/doc/raea/README-linux"
# The bundler is opened with dlopen beside raea, so keep it in usr/bin and ask # The bundler is opened with dlopen beside raea, so keep it in usr/bin and ask
# linuxdeploy to process its dependencies there, rather than move it to usr/lib. # linuxdeploy to process its dependencies there, rather than move it to usr/lib.
# A pinned linuxdeploy also carries its AppImage output plugin and appimagetool. # A pinned linuxdeploy also carries its AppImage output plugin and appimagetool.
# A pinned tool from its GitHub release, else raea's own copy of it (media.raea.io/build): the runner got HTTP 618 for
# the runtime three times in a row while it downloaded from anywhere else (v0.1.15-rc1, 12-01), and the Linux archive
# waits on this script. Either copy is held to the checksum below.
fetch() {
curl -fLsS --retry 3 --retry-all-errors "$1" -o "$3" || curl -fLsS --retry 3 --retry-all-errors "https://media.raea.io/build/$2" -o "$3"
}
deploy_version=1-alpha-20251107-1 deploy_version=1-alpha-20251107-1
deploy_sha=c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d deploy_sha=c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d
# An existing download can be supplied for offline packaging; it is still verified. # An existing download can be supplied for offline packaging; it is still verified.
deploy=${RAEA_LINUXDEPLOY:-$work/linuxdeploy-x86_64.AppImage} deploy=${RAEA_LINUXDEPLOY:-$work/linuxdeploy-x86_64.AppImage}
if [[ -z ${RAEA_LINUXDEPLOY:-} ]]; then if [[ -z ${RAEA_LINUXDEPLOY:-} ]]; then
fetch "https://github.com/linuxdeploy/linuxdeploy/releases/download/$deploy_version/linuxdeploy-x86_64.AppImage" "linuxdeploy/$deploy_version/linuxdeploy-x86_64.AppImage" "$deploy" curl -fLsS --retry 3 "https://github.com/linuxdeploy/linuxdeploy/releases/download/$deploy_version/linuxdeploy-x86_64.AppImage" -o "$deploy"
fi fi
deploy=$(realpath "$deploy") deploy=$(realpath "$deploy")
echo "$deploy_sha $deploy" | sha256sum -c - echo "$deploy_sha $deploy" | sha256sum -c -
@@ -61,7 +55,7 @@ runtime_version=20251108
runtime_sha=2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d runtime_sha=2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d
runtime=${RAEA_APPIMAGE_RUNTIME:-$work/runtime-x86_64} runtime=${RAEA_APPIMAGE_RUNTIME:-$work/runtime-x86_64}
if [[ -z ${RAEA_APPIMAGE_RUNTIME:-} ]]; then if [[ -z ${RAEA_APPIMAGE_RUNTIME:-} ]]; then
fetch "https://github.com/AppImage/type2-runtime/releases/download/$runtime_version/runtime-x86_64" "type2-runtime/$runtime_version/runtime-x86_64" "$runtime" curl -fLsS --retry 3 "https://github.com/AppImage/type2-runtime/releases/download/$runtime_version/runtime-x86_64" -o "$runtime"
fi fi
runtime=$(realpath "$runtime") runtime=$(realpath "$runtime")
echo "$runtime_sha $runtime" | sha256sum -c - echo "$runtime_sha $runtime" | sha256sum -c -
-8
View File
@@ -195,14 +195,6 @@ if [ -f "$check/raea/bin/raea.exe" ]; then
done done
"$check/raea/bin/uv.exe" --version 2>&1 | grep -q '^uv ' || fail "bin/uv.exe doesn't run" "$check/raea/bin/uv.exe" --version 2>&1 | grep -q '^uv ' || fail "bin/uv.exe doesn't run"
fi fi
# a project whose brief.ts imports React, as its scenes do, and has no node_modules: a render's own checks load brief.ts,
# and a render that was applied ended "Cannot find package 'react'" and "render again" (#278). The checks' verdict on
# an empty project isn't the point here: that brief.ts ran is
mkdir -p "$check/brief" && cp "$check/p/hello.tsx" "$check/brief/hello.tsx"
printf '%s\n' 'import { useMemo } from "react"' 'import { goal } from "raea/goal"' 'export const hook = useMemo' 'export default goal({ title: "Check", make: "one short video" })' > "$check/brief/brief.ts"
(cd "$check/brief" && RAEA_NO_TREE=1 "$raea" goal check > check.log 2>&1) || true
[ -s "$check/brief/check.log" ] || fail "raea goal check said nothing beside a brief.ts that imports react"
! grep -q "Cannot find package\|doesn't run" "$check/brief/check.log" || { tail -20 "$check/brief/check.log" >&2; fail "a brief.ts that imports react doesn't run: a package raea ships wasn't found"; }
# RAEA_CHECK_HARD=1 (tools/release-machines.sh, on real machines: a PC's own GPU, the Linux box): what reports from # RAEA_CHECK_HARD=1 (tools/release-machines.sh, on real machines: a PC's own GPU, the Linux box): what reports from
# other systems needed and a runner's one pass doesn't show. # other systems needed and a runner's one pass doesn't show.
if [ "${RAEA_CHECK_HARD:-}" = 1 ]; then if [ "${RAEA_CHECK_HARD:-}" = 1 ]; then