mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-01 12:44:11 -10:00
Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a8a7df53d | ||
|
|
ef8ea7563d | ||
|
|
6716b6b9f0 | ||
|
|
313ac8ab83 | ||
|
|
cdfb043026 | ||
|
|
35267727b8 | ||
|
|
c72717a635 | ||
|
|
0256cb9673 | ||
|
|
b9b0d76568 | ||
|
|
bda521b3ce | ||
|
|
740f3c2cf4 |
No files matched your search
Generated
+24
-4
@@ -15509,6 +15509,7 @@ dependencies = [
|
||||
"raea-runtime-page",
|
||||
"raea-runtime-pagestore",
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-review",
|
||||
"raea-runtime-scene",
|
||||
"raea-runtime-scene3d",
|
||||
"raea-runtime-sound",
|
||||
@@ -15658,12 +15659,9 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bevy",
|
||||
"image",
|
||||
"raea-core-scene",
|
||||
"raea-core-wire",
|
||||
"raea-io-assets",
|
||||
"raea-io-home",
|
||||
"raea-io-media",
|
||||
"raea-io-net",
|
||||
"raea-page",
|
||||
"raea-render",
|
||||
@@ -15672,8 +15670,8 @@ dependencies = [
|
||||
"raea-runtime-react",
|
||||
"raea-runtime-twins",
|
||||
"raea-runtime-view",
|
||||
"raea-sys-facetrack",
|
||||
"raea-sys-fonts",
|
||||
"raea-sys-frame",
|
||||
"raea-sys-image",
|
||||
"raea-sys-page",
|
||||
"raea-sys-screen",
|
||||
@@ -15753,6 +15751,17 @@ dependencies = [
|
||||
"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]]
|
||||
name = "raea-runtime-scene"
|
||||
version = "0.1.0"
|
||||
@@ -16139,6 +16148,17 @@ dependencies = [
|
||||
"parry3d",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-facetrack"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"image",
|
||||
"raea-io-assets",
|
||||
"raea-io-media",
|
||||
"raea-sys-frame",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raea-sys-filters"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -127,6 +127,7 @@ members = [
|
||||
"systems/page-net",
|
||||
"systems/page-ops",
|
||||
"systems/frame",
|
||||
"systems/facetrack",
|
||||
"systems/engine-shaders",
|
||||
"systems/shots",
|
||||
"systems/hold",
|
||||
@@ -184,6 +185,7 @@ members = [
|
||||
"runtime/react",
|
||||
"runtime/track",
|
||||
"runtime/pagestore",
|
||||
"runtime/review",
|
||||
"runtime/cssurls",
|
||||
"runtime/pid",
|
||||
"bench/bridge",
|
||||
|
||||
@@ -40,6 +40,29 @@ 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());
|
||||
@@ -47,10 +70,9 @@ 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])?;
|
||||
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)?));
|
||||
}
|
||||
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));
|
||||
} else {
|
||||
for f in files {
|
||||
let p = probe_of(f)?;
|
||||
|
||||
+69
-62
@@ -1,6 +1,7 @@
|
||||
//! `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
|
||||
@@ -38,7 +39,11 @@ pub fn probe_of(path: &Path) -> R<Probe> {
|
||||
}
|
||||
i
|
||||
});
|
||||
let audio = soft()?.decode_audio(path).ok().filter(|a| a.len() > 0).map(|a| (a.rate, a.channels.len(), a.duration()));
|
||||
// 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())),
|
||||
};
|
||||
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();
|
||||
@@ -124,74 +129,37 @@ impl Track {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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;
|
||||
/// 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)?)
|
||||
}
|
||||
|
||||
pub(crate) fn audio_in(moov: &[u8]) -> Option<(u32, usize, f64)> {
|
||||
for (k, trak) in boxes(moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
}
|
||||
if size < hdr || i + size > b.len() {
|
||||
break;
|
||||
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;
|
||||
}
|
||||
out.push((kind, &b[i + hdr..i + size]));
|
||||
i += size;
|
||||
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));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
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()?))
|
||||
None
|
||||
}
|
||||
|
||||
/// The first video track's timing, for MP4 and QuickTime files.
|
||||
pub fn video_track(path: &Path) -> Option<Track> {
|
||||
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;
|
||||
};
|
||||
let moov = moov_of(path)?;
|
||||
for (k, trak) in boxes(&moov) {
|
||||
if &k != b"trak" {
|
||||
continue;
|
||||
@@ -295,3 +263,42 @@ 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);
|
||||
}
|
||||
}
|
||||
@@ -44,6 +44,32 @@ pub struct VideoFit {
|
||||
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.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
struct Sent {
|
||||
|
||||
+5
-1
@@ -318,7 +318,7 @@ Feature: Goal: the loop every piece of work runs, one goal or a workflow of them
|
||||
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
|
||||
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]`
|
||||
And a `says` rule is clear only when review/judge/NAME.json, written by `raea goal judge [DIR] [--by claude|kimi|clef]`
|
||||
(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
|
||||
("says")
|
||||
@@ -456,6 +456,10 @@ 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
|
||||
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
|
||||
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
|
||||
`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
|
||||
|
||||
@@ -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 |
|
||||
| `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 |
|
||||
| `seen` | cut, floor | its contact sheet looked at since its last render (`raea goal seen FILE`, then `raea goal seen FILE "..."`) |
|
||||
| `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 "..."`) |
|
||||
| `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 |
|
||||
| `sizes` | cut | one size first: no other size before a person approves the first |
|
||||
@@ -54,8 +54,11 @@ 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
|
||||
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
|
||||
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude` or `kimi`) and keeps its
|
||||
verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's newest file.
|
||||
work, judged by a fresh critic that may only read: `raea goal judge` asks one (`--by claude`, `kimi` or `clef`) and
|
||||
keeps its verdict in review/judge/NAME.json, and the rule clears only while that verdict is no older than the work's
|
||||
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
|
||||
import { brief, rules } from "raea/brief"
|
||||
@@ -77,7 +80,7 @@ export default brief({
|
||||
```sh
|
||||
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 seen out/cuts/acme_dog_hook1_v2_9x16.mp4 && raea goal seen out/cuts/acme_dog_hook1_v2_9x16.mp4 "..."
|
||||
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 tasks --json # the brief's plan, every task
|
||||
raea goal next
|
||||
```
|
||||
@@ -94,8 +97,8 @@ goal's rules are never copied into the plan: the plan is the work, the goal is w
|
||||
```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 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"] [--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] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json)
|
||||
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 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 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)
|
||||
```
|
||||
@@ -108,9 +111,10 @@ 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 |
|
||||
| `--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` | The critic `judge` asks, a fresh session that may only read (default `claude`). |
|
||||
| `--by` | `claude\|kimi\|clef` | 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) |
|
||||
| `--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 |
|
||||
| `--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` |
|
||||
|
||||
@@ -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).
|
||||
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 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] (a goal's `says` rules judged by a fresh critic that only reads; review/judge/NAME.json)
|
||||
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 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 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
|
||||
|
||||
@@ -384,7 +384,7 @@ pub fn run(args: &[String]) -> R<String> {
|
||||
}
|
||||
if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
|
||||
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] [--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] [--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 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>)",
|
||||
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
|
||||
|
||||
@@ -80,11 +80,14 @@ 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
|
||||
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
|
||||
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). Style only with the brand
|
||||
classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg), text-brand-on-surface,
|
||||
text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body; size text-display,
|
||||
text-title, text-caption, text-body, text-label (scaled for a 1080-wide frame); corners rounded-brand. Where a
|
||||
class can't reach, the --brand-* variables. Never a colour, font or size of your own.
|
||||
Tailwind: \`<style>{css}</style>\`, css from "./styles.gen" (raea render writes it). The brand's colours and
|
||||
faces are the palette, as classes: colour text-brand-accent, bg-brand-accent, bg-brand-surface (bg-brand-bg),
|
||||
text-brand-on-surface, text-brand-on-accent, text-brand-ink, brand-1/2/3; face font-brand, font-brand-body (where
|
||||
the brand's face is missing, install a free face close to it, never a system fallback); the --brand-* variables
|
||||
where a class can't reach. Never a colour from outside the brand. The design is yours: size, weight, shape, layout
|
||||
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
|
||||
--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);
|
||||
|
||||
@@ -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") };
|
||||
}
|
||||
|
||||
/** 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 */
|
||||
/** raea-perceive, as `raea song` finds it (raea-io-assets perceive_bin): $RAEA_PERCEIVE, else beside raea, else on PATH */
|
||||
function perceive(): string {
|
||||
// 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;
|
||||
|
||||
@@ -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);
|
||||
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) };
|
||||
// (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) };
|
||||
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,6 +53,11 @@ 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() {
|
||||
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()))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
//! 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();
|
||||
}
|
||||
+79
-16
@@ -74,45 +74,88 @@ pub fn picture(doc: &mut blitz_dom::BaseDocument, n: blitz_dom::NodeId, w: u32,
|
||||
node.mark_ancestors_dirty();
|
||||
}
|
||||
|
||||
/// Video elements' frames: a decoder per file, and the frame each element shows (file, frame index), so a frame
|
||||
/// already shown isn't decoded again.
|
||||
/// One reader of a file: its decoder, the frame it gave last (its index and picture), and when it was last asked.
|
||||
struct Reader {
|
||||
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)]
|
||||
pub struct Videos {
|
||||
decoders: HashMap<std::path::PathBuf, Box<dyn raea_io_media::VideoDecoder>>,
|
||||
readers: HashMap<std::path::PathBuf, Vec<Reader>>,
|
||||
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 {
|
||||
/// `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.
|
||||
pub fn frame(&mut self, v: &raea_core_wire::tree::VideoAt) -> R<Option<raea_io_media::Frame>> {
|
||||
if !self.decoders.contains_key(&v.file) {
|
||||
// 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);
|
||||
if !self.readers.contains_key(&v.file) {
|
||||
self.readers.insert(v.file.clone(), vec![Reader { dec: raea_io_media::open_video(&v.file)?, last: None, used: 0 }]);
|
||||
}
|
||||
let d = self.decoders.get_mut(&v.file).unwrap();
|
||||
let key = d.index_at(v.at).map(|i| i as i64).unwrap_or((v.at * 1e6) as i64 + (1 << 40));
|
||||
let rs = self.readers.get_mut(&v.file).unwrap();
|
||||
let index = rs[0].dec.index_at(v.at).map(|i| i as i64);
|
||||
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) {
|
||||
return Ok(None);
|
||||
}
|
||||
let f = match d.frame_at(v.at) {
|
||||
self.tick += 1;
|
||||
// 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,
|
||||
Err(e) => {
|
||||
let i = d.info();
|
||||
let i = r.dec.info();
|
||||
let end = (i.duration - 0.5 / i.fps.max(1.0)).max(0.0);
|
||||
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())) }
|
||||
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())) }
|
||||
}
|
||||
};
|
||||
r.last = Some((key, f.clone()));
|
||||
Ok(Some(f))
|
||||
}
|
||||
|
||||
/// `v`'s frame is now its element's picture.
|
||||
pub fn shows(&mut self, v: raea_core_wire::tree::VideoAt) {
|
||||
let Some(d) = self.decoders.get_mut(&v.file) else { return };
|
||||
let Some(d) = self.readers.get_mut(&v.file).and_then(|rs| rs.first_mut()).map(|r| &mut r.dec) else { return };
|
||||
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));
|
||||
}
|
||||
@@ -418,3 +461,23 @@ pub fn shots(size: (u32, u32), root: Option<&Path>, fonts: Option<&Path>) -> R<(
|
||||
}
|
||||
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)));
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,30 @@ 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
|
||||
/// shown isn't decoded again.
|
||||
pub fn place_videos(&mut self, videos: Vec<raea_core_wire::tree::VideoAt>) -> R<()> {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
pub mod audio;
|
||||
pub mod mezz;
|
||||
pub mod mp4box;
|
||||
#[cfg(feature = "mux")]
|
||||
pub mod remux;
|
||||
pub mod samples;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
//! 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;
|
||||
}
|
||||
}
|
||||
+95
-31
@@ -9,6 +9,8 @@ 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`)
|
||||
@@ -50,17 +52,86 @@ fn says(option: &str) -> String {
|
||||
/// 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.
|
||||
pub fn h264() -> Option<Vec<&'static str>> {
|
||||
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 enc = listed()?;
|
||||
let rate: &[&'static str] = if enc == "libx264" { &[] } else { &["-b:v", "8M"] };
|
||||
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
|
||||
/// 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",
|
||||
@@ -69,11 +140,9 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
"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}"))?;
|
||||
@@ -96,12 +165,15 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
.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> = 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> = 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(),
|
||||
};
|
||||
pts.sort_by(f64::total_cmp);
|
||||
let duration = j["format"]["duration"]
|
||||
.as_str()
|
||||
@@ -117,9 +189,7 @@ fn probe(path: &Path) -> R<(Info, Vec<f64>, bool, Option<&'static str>)> {
|
||||
_ => None,
|
||||
};
|
||||
// an ffmpeg built without libvpx decodes the picture alone, as before
|
||||
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));
|
||||
let alpha = alpha.filter(|c| lists("-decoders", c));
|
||||
Ok((
|
||||
Info {
|
||||
codec: s["codec_name"].as_str().unwrap_or("?").into(),
|
||||
@@ -155,7 +225,12 @@ impl Decoder {
|
||||
}
|
||||
let start = self.pts[at] - self.pts[0];
|
||||
let mut cmd = cli("ffmpeg", false)?;
|
||||
cmd.args(["-v", "error"]).args(self.vpx.map(|c| ["-c:v", c]).into_iter().flatten()).args(["-ss", &format!("{start:.6}"), "-i"]).arg(&self.path);
|
||||
cmd.args(["-v", "error"]).args(self.vpx.map(|c| ["-c:v", c]).into_iter().flatten());
|
||||
// (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 {
|
||||
cmd.args(["-vf", "scale=in_color_matrix=bt709:in_range=tv"]);
|
||||
}
|
||||
@@ -358,6 +433,7 @@ impl Backend for Ffmpeg {
|
||||
}
|
||||
fn encoder(&self, out: &Path, o: &EncodeOpts) -> R<Box<dyn VideoEncoder>> {
|
||||
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)?
|
||||
.args([
|
||||
"-v",
|
||||
@@ -374,19 +450,7 @@ impl Backend for Ffmpeg {
|
||||
"-i",
|
||||
"-",
|
||||
])
|
||||
.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(video_args(enc, o))
|
||||
.args([
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
//! 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
|
||||
}
|
||||
@@ -32,3 +32,72 @@ fn vp9_webm_keeps_its_alpha() {
|
||||
}
|
||||
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());
|
||||
}
|
||||
@@ -71,6 +71,14 @@ pub fn backend_unsigned(name: &str) -> R<Box<dyn Backend>> {
|
||||
pub mod sign;
|
||||
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
|
||||
/// (which reads what the others don't: VP9 WebM).
|
||||
pub fn preferred() -> Vec<Box<dyn Backend>> {
|
||||
|
||||
+1
-12
@@ -83,18 +83,7 @@ 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()),
|
||||
None => (0.0, p.secs),
|
||||
};
|
||||
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 mut dec = crate::open_video(src)?;
|
||||
let info = dec.info().clone();
|
||||
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));
|
||||
|
||||
@@ -45,6 +45,8 @@ raea-sys-light-meter = { path = "../../systems/light-meter" }
|
||||
raea-runtime-scene3d = { path = "../scene3d" }
|
||||
# --review: the fixed cameras
|
||||
raea-core-review = { path = "../../core/review" }
|
||||
# render --review's tiles and sheets
|
||||
raea-runtime-review = { path = "../review" }
|
||||
raea-sys-mix = { path = "../../systems/mix" }
|
||||
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
|
||||
|
||||
@@ -245,6 +245,14 @@ pub(crate) fn bevy_page_frame(world: &mut World, page: &mut raea_runtime_page::B
|
||||
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
|
||||
/// 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.
|
||||
|
||||
@@ -246,11 +246,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
|
||||
}
|
||||
let t_react = std::time::Instant::now();
|
||||
engine_before(app, cx, 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;
|
||||
step_react(app, bevy, cx, (f, fps), asked != Some(f))?;
|
||||
// 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
|
||||
// reads changes (the frames come in order; one asked for out of order is asked for again)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! `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())
|
||||
}
|
||||
@@ -31,6 +31,7 @@ pub(crate) use raea_runtime_react::{ReactKind, ReactOutbox, ReactPlugin, ReactPr
|
||||
|
||||
mod bevy_frame;
|
||||
use bevy_frame::*;
|
||||
mod keys;
|
||||
mod pages;
|
||||
use pages::*;
|
||||
mod program;
|
||||
@@ -64,6 +65,9 @@ pub(crate) struct Sound {
|
||||
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.
|
||||
static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
|
||||
|
||||
|
||||
@@ -65,6 +65,12 @@ 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<_>>()?),
|
||||
_ => 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);
|
||||
*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);
|
||||
@@ -297,6 +303,9 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
||||
raea_gpu_device::check::mem_fits(w, h, None)?;
|
||||
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 };
|
||||
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 let Some(p) = scene {
|
||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
use super::*;
|
||||
use crate::scene::items;
|
||||
use raea_core_review::{TILE_W, VIEWS, boxes_of, cameras, ceiling, inside, parts_box, passed, whole};
|
||||
use raea_core_review::{boxes_of, cameras, ceiling, inside, parts_box, whole};
|
||||
|
||||
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]))?;
|
||||
@@ -31,63 +31,5 @@ pub fn review(args: &[String], dir_out: &Path) -> R<String> {
|
||||
let ceil = ceiling(&all, wlo, whi);
|
||||
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)))));
|
||||
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)
|
||||
raea_runtime_review::sheets(&tsx, args, dir_out, &cams, raea_runtime_review::Shot { frame, aspect, parts: (lo, hi), interior: ceil.is_some() })
|
||||
}
|
||||
@@ -9,8 +9,8 @@ description = "A composition's page in Bevy: React's elements laid out and paint
|
||||
[dependencies]
|
||||
raea-runtime-view = { path = "../view" }
|
||||
raea-runtime-appscreen = { path = "../appscreen" }
|
||||
raea-sys-frame = { path = "../../systems/frame" }
|
||||
raea-io-assets = { path = "../../io/assets" }
|
||||
# a take's face track, for <Video framing="face">
|
||||
raea-sys-facetrack = { path = "../../systems/facetrack" }
|
||||
raea-io-net = { path = "../../io/net" }
|
||||
raea-io-home = { path = "../../io/home" }
|
||||
raea-runtime-react = { path = "../../runtime/react", default-features = false }
|
||||
@@ -26,9 +26,7 @@ raea-sys-image = { path = "../../systems/image" }
|
||||
raea-runtime-twins = { path = "../twins" }
|
||||
raea-runtime-input = { path = "../input" }
|
||||
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"] }
|
||||
image = { version = "0.25", default-features = false, features = ["png", "hdr"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
wgpu = "=30.0.1"
|
||||
@@ -25,6 +25,11 @@ pub struct BevyPage {
|
||||
pub(crate) surf: Option<Entity>,
|
||||
/// the UiMaterial elements the last sync met: page id and spec (JSON)
|
||||
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 {
|
||||
@@ -34,7 +39,7 @@ impl BevyPage {
|
||||
// they draw as it is
|
||||
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()))?;
|
||||
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() })
|
||||
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() })
|
||||
}
|
||||
|
||||
/// The page made to match the React tree in `react` (the composition's App's World). `holders`: the props elements
|
||||
@@ -62,6 +67,7 @@ impl BevyPage {
|
||||
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);
|
||||
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
|
||||
// a framed take with no face track
|
||||
let refused = REFUSED.with(|c| std::mem::take(&mut *c.borrow_mut()));
|
||||
@@ -72,6 +78,7 @@ impl BevyPage {
|
||||
// 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();
|
||||
for s in screens {
|
||||
key = key.map(|k| raea_core_wire::tree::key(k, &s.want, &s.videos, &self.dir));
|
||||
videos.extend(s.videos);
|
||||
let (mut want, mut order, first) = frame_wants(s.w, s.h, brand);
|
||||
want.extend(s.want);
|
||||
@@ -99,6 +106,15 @@ impl BevyPage {
|
||||
}
|
||||
crate::screen::retire(&mut self.apps, &self.app_screens);
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ pub(crate) fn video_fit(props: Option<&Map<String, Value>>, file: &Path, at: f64
|
||||
if !face {
|
||||
return Some(VideoFit { at: (0.5, 0.5), to: (0.5, 0.5), scale });
|
||||
}
|
||||
match crate::faces::track(file) {
|
||||
match raea_sys_facetrack::track(file) {
|
||||
Ok(t) => t.eyes_at(at).map(|eyes| VideoFit { at: eyes, to: (0.5, 0.38), scale }),
|
||||
Err(e) => {
|
||||
REFUSED.with(|c| c.borrow_mut().push(e));
|
||||
|
||||
@@ -36,7 +36,6 @@ pub use world::*;
|
||||
// app screens (`<Screen app>`): a component on @raea/ui's react-dom in a raea-runtime-js root of its own
|
||||
pub mod screen;
|
||||
// a take's face track (<Video framing="face">)
|
||||
pub(crate) mod faces;
|
||||
|
||||
type R<T> = Result<T, String>;
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[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"
|
||||
@@ -0,0 +1,83 @@
|
||||
//! `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)
|
||||
}
|
||||
@@ -86,7 +86,8 @@ 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
|
||||
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
|
||||
# (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
|
||||
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
|
||||
|
||||
@@ -21,6 +21,11 @@ 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
|
||||
@@ -103,6 +108,9 @@ 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
|
||||
|
||||
@@ -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",
|
||||
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",
|
||||
seen: "its contact sheet looked at since its last render, and what was seen and would change said",
|
||||
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",
|
||||
surprise: "one earned surprise, named with its moment in seconds",
|
||||
naming: "files named client_concept_variant_v#_size",
|
||||
sizes: "one size first: no other size before the first is approved",
|
||||
|
||||
@@ -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 }
|
||||
/** `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[] } }
|
||||
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`) */
|
||||
export type Seen = { video: string; render: string; seen: string; surprise?: string; at?: string }
|
||||
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`); `look` is its design judged at full size */
|
||||
export type Seen = { video: string; render: string; seen: string; look?: string; surprise?: string; at?: string }
|
||||
|
||||
export interface FileFacts {
|
||||
/** as the project names it (relative to its folder) */
|
||||
|
||||
+21
-1
@@ -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
|
||||
// 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 { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
import type { Scene } from "./packs/place.ts"
|
||||
@@ -252,3 +252,23 @@ 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)}`)
|
||||
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))
|
||||
@@ -9,8 +9,9 @@ import { spawnSync } from "node:child_process"
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { check, found } from "raea/check"
|
||||
import { type Contract, nameOf, saysOf } from "../contract.ts"
|
||||
import { type Contract, nameOf, type Said, saysOf } from "../contract.ts"
|
||||
import type { Job } from "../facts.ts"
|
||||
import { RAEA } from "../media.ts"
|
||||
|
||||
/** where a goal's critic verdict is kept, relative to the brief */
|
||||
export const verdictPath = (g: Contract) => `review/judge/${nameOf(g)}.json`
|
||||
@@ -118,7 +119,69 @@ export function lastVerdict(text: string): Verdict | null {
|
||||
return null
|
||||
}
|
||||
|
||||
export const BY = ["claude", "kimi"] as const
|
||||
export const BY = ["claude", "kimi", "clef"] 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,
|
||||
* stamped with when it was asked (so work changed while it judged counts as changed after) */
|
||||
@@ -126,6 +189,7 @@ 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 (!(BY as readonly string[]).includes(by)) throw new Error(`--by ${by}: the critics are ${BY.join(", ")}`)
|
||||
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 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?)`)
|
||||
@@ -136,7 +200,9 @@ export function judge(g: Contract, dir: string, by: string): Verdict {
|
||||
} catch {}
|
||||
const v = lastVerdict(words)
|
||||
if (!v) throw new Error(`${by} answered no verdict: ${words.slice(-300).trim()}`)
|
||||
const out: Verdict = { ...v, at: asked, by, goal: g.aim ?? nameOf(g) }
|
||||
return keep(g, dir, { ...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))
|
||||
mkdirSync(path.dirname(file), { recursive: true })
|
||||
writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`)
|
||||
|
||||
@@ -2,26 +2,35 @@
|
||||
// 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
|
||||
// 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.
|
||||
// are tied to the file as it is now (its time and size): a render after it needs a new look. A video's
|
||||
// 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
|
||||
// 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 { check, found } from "raea/check"
|
||||
import type { FileFacts } from "../facts.ts"
|
||||
import { RAEA, stem } from "../media.ts"
|
||||
import { bookkeeping } from "./naming.ts"
|
||||
|
||||
/** the least a look says: what's in it and what would change, not "looks good" */
|
||||
export const SEEN_LEAST = 80
|
||||
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)
|
||||
|
||||
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) => {
|
||||
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) => {
|
||||
if (!looked(f)) return
|
||||
const s = f.seen()
|
||||
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.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) => {
|
||||
@@ -30,3 +39,48 @@ export const surprisePack = check<FileFacts>({ id: "surprise", text: "one earned
|
||||
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"` })
|
||||
})
|
||||
|
||||
/** 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 [] } })
|
||||
}
|
||||
@@ -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("_")
|
||||
|
||||
/** the job's own writing about itself: review rounds, previews, sheets */
|
||||
export const bookkeeping = (rel: string) => /^(\.\/)?(review|previews|\.raea)\//.test(rel) || /\.(sheet|seen|check)\.[a-z]+$/i.test(rel)
|
||||
export const bookkeeping = (rel: string) => /^(\.\/)?(review|previews|\.raea)\//.test(rel) || /\.(sheet|seen|second|check)\.[a-z]+$/i.test(rel) || /\.looks\//.test(rel)
|
||||
|
||||
export default check<FileFacts>(
|
||||
{ id: "naming", text: "files named client_concept_variant_v#_size", over: "file", at: ["edit", "render", "publish", "done"] },
|
||||
|
||||
+19
-11
@@ -13,7 +13,7 @@
|
||||
// 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 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] a fresh critic over a goal's `says` rules (review/judge/)
|
||||
// raea goal judge [--goal NAME] [--by claude|kimi|clef] a fresh critic over a goal's `says` rules (review/judge/)
|
||||
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
@@ -24,8 +24,9 @@ import * as media from "./media.ts"
|
||||
import { registeredPack } from "./packs/job.ts"
|
||||
import { tastePack } from "./packs/taste.ts"
|
||||
import { loadProject, type Project } from "./project.ts"
|
||||
import { judge } from "./packs/goal.ts"
|
||||
import { critic, judge } from "./packs/goal.ts"
|
||||
import { PACK_CHECKS } from "./packs/index.ts"
|
||||
import { second } from "./packs/look.ts"
|
||||
import { deliverablesOf } from "./packs/job.ts"
|
||||
import { bookkeeping } from "./packs/naming.ts"
|
||||
import { placeReport } from "./packs/place.ts"
|
||||
@@ -227,9 +228,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]
|
||||
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
|
||||
raea goal seen FILE (its contact sheet, to look at every frame)
|
||||
raea goal seen FILE "what you see and would change" [--surprise "SECONDS s: what it is"]
|
||||
raea goal judge [--goal NAME] [--by claude|kimi]
|
||||
raea goal seen FILE (its contact sheet and its frames at full size, to look at)
|
||||
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 judge [--goal NAME] [--by claude|kimi|clef]
|
||||
raea make place FILE [--at S[,S...]] [--box WxH]`
|
||||
|
||||
export async function main(argv: string[]): Promise<number> {
|
||||
@@ -254,11 +255,15 @@ export async function main(argv: string[]): Promise<number> {
|
||||
}
|
||||
if (verb === "tasks") return tasksMain(a)
|
||||
if (verb === "seen") {
|
||||
const [file, said] = positional(a, ["--surprise"])
|
||||
const [file, said] = positional(a, ["--surprise", "--look"])
|
||||
if (!file || !existsSync(file)) return usage()
|
||||
if (!said?.trim()) {
|
||||
const sheet = media.sheet(path.resolve(file))
|
||||
console.log(`${sheet}\nlook at every frame, then: raea goal seen ${file} "what you see and would change"`)
|
||||
const full = kindOf(path.resolve(file)) === "video" ? media.looks(path.resolve(file)) : []
|
||||
// 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
|
||||
}
|
||||
const abs = path.resolve(file)
|
||||
@@ -267,9 +272,12 @@ 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`)
|
||||
return 1
|
||||
}
|
||||
const st = statSync(abs)
|
||||
const surprise = flag(a, "--surprise")
|
||||
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`)
|
||||
const [st, surprise, look] = [statSync(abs), flag(a, "--surprise"), flag(a, "--look")?.trim()]
|
||||
if (kindOf(abs) === "video" && (!look || !media.looksFresh(abs))) {
|
||||
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"`)
|
||||
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`)
|
||||
return 0
|
||||
}
|
||||
@@ -304,7 +312,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`}`)
|
||||
return 2
|
||||
}
|
||||
const v = judge(said[0], root, flag(a, "--by") ?? "claude")
|
||||
const v = judge(said[0], root, flag(a, "--by") ?? critic())
|
||||
for (const [id, r] of Object.entries(v.rules)) console.log(`${r?.pass ? "ok " : "open"} ${id}: ${r?.why ?? ""}`)
|
||||
return 0
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
// 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, writeFileSync } from "node:fs"
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import path from "node:path"
|
||||
import { lastVerdict, newest } from "../src/packs/goal.ts"
|
||||
import { clefVerdict, lastVerdict, newest } from "../src/packs/goal.ts"
|
||||
import { goalCheck } from "../src/run.ts"
|
||||
import { project, put } from "./project.ts"
|
||||
|
||||
@@ -61,3 +62,21 @@ 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: "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")
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
// 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()
|
||||
})
|
||||
@@ -38,8 +38,9 @@ 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):
|
||||
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;
|
||||
and that you looked at its contact sheet since its last render (`raea goal seen CUT`, then `raea goal seen CUT
|
||||
"..."`). Every render ends with `raea goal check CUT --at render`; the job isn't done, and the Stop hook won't let
|
||||
and that you looked at it since its last render: its contact sheet for what happens, and its frames at full size
|
||||
(CUT.looks/) for how it looks, since a sheet's tiles are too small to judge type, captions and cards on (`raea goal
|
||||
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
|
||||
pack off on the contract (`packs: { place: false }`) only when the brief says so.
|
||||
|
||||
|
||||
@@ -40,6 +40,20 @@
|
||||
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
|
||||
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
|
||||
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
|
||||
|
||||
+1
-1
Submodule skills updated: 105aede654...a2481c23ef.
@@ -0,0 +1,17 @@
|
||||
[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"
|
||||
@@ -14,14 +14,14 @@ const RATE: f64 = 4.0;
|
||||
const SIDE: u32 = 640;
|
||||
|
||||
/// The eyes at each sample, in shares of the picture (None: no face in that sample).
|
||||
pub(crate) struct Track {
|
||||
pub struct Track {
|
||||
every: f64,
|
||||
eyes: Vec<Option<(f64, f64)>>,
|
||||
}
|
||||
|
||||
impl Track {
|
||||
/// The eyes at `t` seconds: between the samples around it, or the nearest sample with a face.
|
||||
pub(crate) fn eyes_at(&self, t: f64) -> Option<(f32, f32)> {
|
||||
pub fn eyes_at(&self, t: f64) -> Option<(f32, f32)> {
|
||||
let i = (t / self.every).max(0.0);
|
||||
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()) {
|
||||
@@ -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).
|
||||
/// An error says why there's none (no raea-perceive, no face in the take), once per take.
|
||||
pub(crate) fn track(take: &Path) -> Result<Rc<Track>, String> {
|
||||
pub fn track(take: &Path) -> Result<Rc<Track>, String> {
|
||||
if let Some(t) = TRACKS.with_borrow(|m| m.get(take).cloned()) {
|
||||
return t;
|
||||
}
|
||||
@@ -129,6 +129,8 @@ raea-sys-page = "systems"
|
||||
raea-sys-page-net = "systems"
|
||||
raea-sys-page-ops = "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-hold = "systems"
|
||||
raea-sys-body = "systems"
|
||||
@@ -188,6 +190,8 @@ raea-runtime-canvas = "runtime"
|
||||
raea-runtime-wear = "runtime"
|
||||
raea-runtime-export = "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-pid = "runtime"
|
||||
raea-runtime-page = "runtime"
|
||||
|
||||
@@ -30,7 +30,7 @@ pub(crate) fn run(args: &[String], flag: &dyn Fn(&str) -> Option<String>) -> Res
|
||||
Some("eyes") => {
|
||||
// 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
|
||||
// runtime/page/src/faces.rs). The face mesh's iris centres (points 468 and 473); BlazeFace's eye keypoints when
|
||||
// systems/facetrack). 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 irises are at 0.305)
|
||||
let m = raea_sys_vision::face::models()?;
|
||||
|
||||
@@ -40,12 +40,18 @@ 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
|
||||
# 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 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_sha=c20cd71e3a4e3b80c3483cef793cda3f4e990aca14014d23c544ca3ce1270b4d
|
||||
# An existing download can be supplied for offline packaging; it is still verified.
|
||||
deploy=${RAEA_LINUXDEPLOY:-$work/linuxdeploy-x86_64.AppImage}
|
||||
if [[ -z ${RAEA_LINUXDEPLOY:-} ]]; then
|
||||
curl -fLsS --retry 3 "https://github.com/linuxdeploy/linuxdeploy/releases/download/$deploy_version/linuxdeploy-x86_64.AppImage" -o "$deploy"
|
||||
fetch "https://github.com/linuxdeploy/linuxdeploy/releases/download/$deploy_version/linuxdeploy-x86_64.AppImage" "linuxdeploy/$deploy_version/linuxdeploy-x86_64.AppImage" "$deploy"
|
||||
fi
|
||||
deploy=$(realpath "$deploy")
|
||||
echo "$deploy_sha $deploy" | sha256sum -c -
|
||||
@@ -55,7 +61,7 @@ runtime_version=20251108
|
||||
runtime_sha=2fca8b443c92510f1483a883f60061ad09b46b978b2631c807cd873a47ec260d
|
||||
runtime=${RAEA_APPIMAGE_RUNTIME:-$work/runtime-x86_64}
|
||||
if [[ -z ${RAEA_APPIMAGE_RUNTIME:-} ]]; then
|
||||
curl -fLsS --retry 3 "https://github.com/AppImage/type2-runtime/releases/download/$runtime_version/runtime-x86_64" -o "$runtime"
|
||||
fetch "https://github.com/AppImage/type2-runtime/releases/download/$runtime_version/runtime-x86_64" "type2-runtime/$runtime_version/runtime-x86_64" "$runtime"
|
||||
fi
|
||||
runtime=$(realpath "$runtime")
|
||||
echo "$runtime_sha $runtime" | sha256sum -c -
|
||||
|
||||
@@ -195,6 +195,14 @@ 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
|
||||
|
||||
Reference in new issue
Block a user