Compare commits

..
Author SHA1 Message Date
shinyobjectz 78897a1539 clef's second opinion on a cut is a list of pointed picture and sound checks, the faults it found first
Asked "do the graphics look designed", clef graded Dutch's plain boxes "strong". Asked pointed yes/no checks of the
same cut it found three of them: three or more text boxes at once (0.93), captions, cards and badges all the same
plain box (0.57), the app shown only as a box of text (0.80). Shane, 12-01: "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".
2026-12-01 06:04:42 -08:00
25 changed files with 129 additions and 779 deletions

No files matched your search

+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()}))
}
/// `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> {
if files.is_empty() {
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();
if files.len() == 1 {
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();
let read = at_once(at.len(), |i| frame(&files[0], at[i]))?;
tiles.extend(at.into_iter().zip(read));
for i in 0..n.max(1) {
let t = (i as f64 + 0.5) / n.max(1) as f64 * p.duration;
tiles.push((t, frame(&files[0], t)?));
}
} else {
for f in files {
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.
use super::*;
use raea_io_media::mp4box::{be32, be64, boxes, child, moov_of};
pub(crate) fn round3(x: f64) -> f64 {
(x * 1000.0).round() / 1000.0
@@ -39,11 +38,7 @@ pub fn probe_of(path: &Path) -> R<Probe> {
}
i
});
// what the file states, when it does; else the track decoded (WAV, MP3, a container read no other way)
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())),
};
let audio = 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() {
// 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();
@@ -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`
/// decoded the whole track to learn these, which read every byte of a 1 GB interview (two minutes on a network disk).
pub fn audio_track(path: &Path) -> Option<(u32, usize, f64)> {
audio_in(&moov_of(path)?)
/// The boxes inside `b` (a box's payload): (type, payload).
pub(crate) 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(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> {
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"soun"[..]) {
continue;
}
let mdhd = child(mdia, b"mdhd")?;
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
pub(crate) fn child<'a>(b: &'a [u8], kind: &[u8; 4]) -> Option<&'a [u8]> {
boxes(b).into_iter().find(|(k, _)| k == kind).map(|(_, p)| p)
}
pub(crate) fn be32(b: &[u8], at: usize) -> Option<u32> {
Some(u32::from_be_bytes(b.get(at..at + 4)?.try_into().ok()?))
}
pub(crate) fn be64(b: &[u8], at: usize) -> Option<u64> {
Some(u64::from_be_bytes(b.get(at..at + 8)?.try_into().ok()?))
}
/// The first video track's timing, for MP4 and QuickTime files.
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) {
if &k != b"trak" {
continue;
@@ -263,42 +295,3 @@ pub(crate) fn rate_fraction(fps: f64) -> String {
}
// ---- 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);
}
}
+6 -6
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
pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String> {
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 == ".." || Path::new(raw).is_absolute() {
let want = if raw.starts_with('/') || Path::new(raw).is_absolute() { PathBuf::from(raw) } else { dir.join(raw) };
if raw.starts_with("./") || raw.starts_with("../") || raw.starts_with('/') || raw == "." || raw == ".." {
let want = if raw.starts_with('/') { PathBuf::from(raw) } else { dir.join(raw) };
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 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());
@@ -53,9 +53,9 @@ pub fn resolve_file(spec: &str, dir: &Path, esm: bool) -> Result<PathBuf, String
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() {
// raea's own file (sdk/app, under `raea goal check`) importing a package raea ships: a release has those in the React runtime's node_modules alone (#278)
let (home, own) = (raea_io_home::home(), raea_io_home::home().join("sdk/react/js/node_modules").join(&name));
if dir.starts_with(&home) && 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()))
+3 -17
View File
@@ -1,4 +1,4 @@
//! 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
//! A file of raea's own importing a package raea ships 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")]
@@ -16,21 +16,7 @@ fn raeas_own_file_finds_the_react_raea_ships() {
// 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();
// a project's own file never reaches into raea's packages
assert!(raea_native::node::resolve_file("react", &theirs, true).unwrap_err().contains("Cannot find package 'react'"));
fs::remove_dir_all(&home).ok();
}
-1
View File
@@ -5,7 +5,6 @@
pub mod audio;
pub mod mezz;
pub mod mp4box;
#[cfg(feature = "mux")]
pub mod remux;
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;
}
}
+10 -19
View File
@@ -9,8 +9,6 @@ use raea_io_codec::{
Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, VideoDecoder, VideoEncoder, as_of,
};
mod mov;
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`)
@@ -126,12 +124,6 @@ const NVENC: [&str; 14] = ["-c:v", "h264_nvenc", "-preset", "p5", "-tune", "hq",
/// 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).
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))?
.args([
"-v",
@@ -140,9 +132,11 @@ fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool,
"v:0",
"-show_entries",
"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)
.output()
.map_err(|e| format!("ffprobe: {e}"))?;
@@ -165,15 +159,12 @@ fn probe_with(path: &Path, tabled: Option<Vec<f64>>) -> R<(Info, Vec<f64>, bool,
.and_then(|r| r.split_once('/'))
.map(|(n, d)| n.parse::<f64>().unwrap_or(30.0) / d.parse::<f64>().unwrap_or(1.0))
.unwrap_or(30.0);
let mut pts: Vec<f64> = match tabled {
Some(t) => t,
None => j["packets"]
.as_array()
.into_iter()
.flatten()
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
.collect(),
};
let mut pts: Vec<f64> = j["packets"]
.as_array()
.into_iter()
.flatten()
.filter_map(|p| p["pts_time"].as_str().and_then(|t| t.parse().ok()))
.collect();
pts.sort_by(f64::total_cmp);
let duration = j["format"]["duration"]
.as_str()
-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
}
-36
View File
@@ -65,39 +65,3 @@ fn a_system_encoder_takes_the_bitrate() {
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());
}
+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).
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)
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()
})
std::fs::read(path).map(|b| mp4_rotation(&b)).unwrap_or(0)
}
/// 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> {
// 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 mp4 = re_mp4::Mp4::read_bytes(&bytes).map_err(|e| format!("{}: {e}", path.display()))?;
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);
}
+33 -77
View File
@@ -32,7 +32,6 @@ import re
import resource
import shutil
import subprocess
import threading
import time
import uuid
@@ -82,10 +81,8 @@ GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit;
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"))
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "8"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "40"))
ROOT = "/farm"
JOBS = f"{ROOT}/jobs"
@@ -171,8 +168,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)
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)
BOOTED = time.time()
@@ -233,10 +228,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
# about five times their GPUs' working seconds
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):
@@ -300,7 +291,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
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)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=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."""
@@ -443,9 +434,7 @@ def coordinate(id: str, args: list[str], opts: dict):
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)
code = 1
t_end = [time.time()]
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
# 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,
@@ -459,9 +448,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)
else:
time.sleep(pause)
t_end.append(time.time())
after = snapshot(work)
t_end.append(time.time())
changed = [p for p, v in after.items() if before.get(p) != v]
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
@@ -473,66 +460,10 @@ def coordinate(id: str, args: list[str], opts: dict):
with open(f"{JOBS}/{id}/changed.txt", "w") as f:
f.write("".join(p + "\n" for p in changed))
shutil.rmtree(f"{JOBS}/{id}/frames", ignore_errors=True)
t_end.append(time.time())
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)
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)
@modal.concurrent(max_inputs=32)
@modal.asgi_app()
@@ -617,6 +548,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,
# 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.
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")
async def scene(req: Request):
@@ -625,6 +569,11 @@ def api():
(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
[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)
body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None
@@ -632,11 +581,18 @@ def api():
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call")
if len(frames) <= SCENE_HERE:
out = await asyncio.to_thread(read_scenes, frames)
else:
parts = [frames[i:i + SCENE_PART] for i in range(0, len(frames), SCENE_PART)]
out = [r async for part in scene_run.map.aio(parts) for r in part]
global SCENE
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 {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
@web.post("/v1/words")
+1 -2
View File
@@ -86,8 +86,7 @@ up)
# rebuilds anyway (raea cloud then resumes the cut-off runs, projects.ts resumeRequest).
if [ "${RAEA_BOX_FORCE:-}" != 1 ]; then
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 || true" | 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" | python3 -c 'import json,sys
try: print(json.load(sys.stdin).get("running", "unknown"))
except Exception: print("down")')
# 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 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
# 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' || {
say "node $NODE"
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
. ~/.raea-cloud.env
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 VK_DRIVER_FILES=$(ls /usr/share/vulkan/icd.d/lvp_icd*.json | head -1)
mkdir -p ~/work
+1 -15
View File
@@ -34,7 +34,6 @@
// 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.
import { jobsOf, watchTurnEnd } from "./turn-end.ts"
import { execFileSync, spawn } from "node:child_process"
import { timingSafeEqual } from "node:crypto"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, symlinkSync, writeFileSync } from "node:fs"
@@ -413,20 +412,7 @@ server.on("upgrade", (req, socket, head) => {
buf += c
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 = 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
if (agent.id === "antigravity-acp" && env.GEMINI_HOME) {
const stopWatch = watchTurnEnd(
env.GEMINI_HOME,
() => heardFromCaller,
(by) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ jsonrpc: "2.0", method: "_raea/turn_end", params: { by } })),
() => !!child.pid && jobsOf(child.pid, path.dirname(agent.command), WORK).length > 0,
)
ws.on("close", stopWatch)
child.on("exit", stopWatch)
}
ws.on("message", (m) => ((heard = Date.now()), child.stdin.write(m.toString() + "\n")))
ws.on("close", stopAll)
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()))
-127
View File
@@ -1,127 +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 StreetTalk 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 } 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)
}
/** Watches an Antigravity agent's transcript and calls `said` once for each turn that ends after `told()` (when the
* agent was last sent anything: a turn that ended before its newest prompt isn't this one's), once `busy()` has been
* false two looks running. Returns its stop. */
export function watchTurnEnd(geminiHome: string, told: () => number, said: (by: string) => void, busy: () => boolean = () => false, everyMs = 1000): () => void {
let seen = -1
let idle = 0
const t = setInterval(() => {
try {
const tr = newestTranscript(geminiHome)
const end = tr ? turnEndOf(lastLine(tr.file)) : null
// a second's slack: the 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("its transcript, and nothing of its own running")
} catch {}
}, everyMs)
t.unref?.()
return () => clearInterval(t)
}
+1 -54
View File
@@ -3,13 +3,12 @@
// paths read on the worker)
import assert from "node:assert/strict"
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { parseSummary, pick } from "../server/gpu.ts"
import { plan, projectRoot } from "../server/offload.ts"
import { shellEnv } from "../server/shell-os.ts"
import { jobsOf, lastLine, newestTranscript, turnEndOf, watchTurnEnd } from "../server/turn-end.ts"
import { landedQuery, linkIn, packCredential, unpackCredential } from "../server/google-token.ts"
const L4 = `Devices:
@@ -108,55 +107,3 @@ console.log("units: ok")
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])
rmSync(home, { recursive: true, force: true })
console.log("ok turn-end")
}
-18
View File
@@ -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) */
export const RATE = 2
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
* (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[] }> {
// 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)`)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-scene-"))
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)
}
}
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 }
} finally {
rmSync(dir, { recursive: true, force: true })
+1 -6
View File
@@ -19,11 +19,6 @@ export const TIMEOUT = 300
/** 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"])
/** 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)\.json$/
/** 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 {
let best: number | null = null
@@ -48,7 +43,7 @@ export function newest(dir: string): number | null {
}
if (st.isDirectory()) {
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
+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
// 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.
// 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]
// 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 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) {
// an error only for what a shot can't lose: a face, or the thing it shows (the product, the dog, a phone held
// up). A caption over someone's coat with clearer ground elsewhere is a warning with the place said (12-01: two
// 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` })
const face = under.includes("a face")
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` })
} 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` })
} 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 { 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) => {
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
const sizes = new Map<string, string[]>()
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 (sizes.size < 2) return
+1 -13
View File
@@ -1,7 +1,7 @@
// 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.
import { expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { clefVerdict, lastVerdict, newest } from "../src/packs/goal.ts"
@@ -80,15 +80,3 @@ test("clef judges a rule on the file it names, else on every video made, and say
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"]) 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)
})
+1 -31
View File
@@ -1,9 +1,6 @@
import { test } from "bun:test"
import assert from "node:assert/strict"
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import path from "node:path"
import { RATE, scene, SCENE_EXT, useSender } from "../src/media.ts"
import { readFileSync } from "node:fs"
import { placeReport, textOver } from "../src/packs/place.ts"
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))
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 { CLIP, project, put } from "./project.ts"
import { readFileSync } from "node:fs"
import { shapeOf } from "../src/packs/sizes.ts"
beforeAll(() => {
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, ["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")
})
-8
View File
@@ -195,14 +195,6 @@ if [ -f "$check/raea/bin/raea.exe" ]; then
done
"$check/raea/bin/uv.exe" --version 2>&1 | grep -q '^uv ' || fail "bin/uv.exe doesn't run"
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
# other systems needed and a runner's one pass doesn't show.
if [ "${RAEA_CHECK_HARD:-}" = 1 ]; then