Compare commits

...
Author SHA1 Message Date
shinyobjectz 20249b43e9 One opener for a video (raea_io_media::open_video) and one step of React to a frame (step_react), where the render-cost work had copied each 2026-11-30 19:06:26 -08:00
shinyobjectz 88223b9388 Merge remote-tracking branch 'origin/main' into engine-render-cost 2026-11-30 19:02:01 -08:00
shinyobjectz f605e309e4 The face track and render --review's sheets are crates of their own (raea-sys-facetrack, raea-runtime-review): raea-runtime-page and raea-runtime-export are under 2000 lines again 2026-11-30 19:02:00 -08:00
shinyobjectz e75a0f626d RAEA_NV=1: NVENC and NVDEC in the ffmpeg backend, each after a one-frame try on the machine
The render farm sets it on a GPU's runs of a piece with 3D in it. h264_nvenc at libx264's CRF number as constant QP
(SSIM 0.9925 to libx264's 0.9924 on the ad) and clips through CUDA; where a try fails, libx264 and ffmpeg's own,
said once. The answer is kept for the machine's later runs (CR34).
2026-11-30 18:14:16 -08:00
shinyobjectz db4cbb5814 render --keys: each frame's key with nothing drawn, and the largest each clip is drawn
raea render EDIT --keys keys.json steps React through every frame and makes the page match it without reading a clip
or drawing: each frame's key (its elements' place, kind, props and text, each video's file and time, its 3D rows;
paths named from the composition's folder), has3d, the piece's sounds, and the largest each clip is drawn (box as
drawn, transforms and punch-in applied). A render farm keeps runs by these keys and reads clips from copies no larger
than they're drawn. On the ad: 6.7 s for 894 frames; a caption word changed 70 frames' keys, a sound 3 dB louder none
(CR32, CR36).
2026-11-30 18:14:16 -08:00
shinyobjectz 9008056959 A page reads a clip on from where it stopped: up to 4 readers a file, so a clip shown twice at once isn't sought every frame
Where two elements showed one 4K clip, they shared one decoder and ffmpeg restarted every frame (31 starts in 30
frames). Each file now keeps up to 4 readers, each reading on from its last frame (the one behind within 60 frames,
else a new one, else the least used), and the frame it read last for a second ask. Those frames: 909 to 53 ms on the
Mac, SSIM 1.000000; a 30 s ad of 4K street-interview clips on the farm's GPUs 277 s and $0.106 to 153 s and $0.033.
2026-11-30 18:14:16 -08:00
28 changed files with 440 additions and 112 deletions

No files matched your search

Generated
+24 -4
View File
@@ -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"
+2
View File
@@ -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",
+26
View File
@@ -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 {
+1 -1
View File
@@ -384,7 +384,7 @@ pub fn run(args: &[String]) -> R<String> {
}
if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
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
+1 -1
View File
@@ -221,7 +221,7 @@ function cut(a: { take: string; lines: string[]; spans: number[][]; keep: Clip[]
return { edit, cuts: clips, words: timeline, perception: perception(edit, clips), said: [head, ...said, ...notes.map((n) => `note: ${n}`)].join("\n") };
}
/** 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;
+79 -16
View File
@@ -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)));
}
}
+24
View File
@@ -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<()> {
+45 -2
View File
@@ -58,6 +58,43 @@ pub fn h264() -> Option<Vec<&'static str>> {
Some([&["-c:v", enc][..], rate, &["-pix_fmt", "yuv420p"]].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>)> {
@@ -155,7 +192,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"]);
}
@@ -374,9 +416,10 @@ impl Backend for Ffmpeg {
"-i",
"-",
])
.args(["-c:v", "libx264", "-preset", "medium"])
.args(if nv(true) { &NVENC[..] } else { &["-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) if nv(true) => vec!["-rc".to_string(), "constqp".to_string(), "-qp".to_string(), format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0))],
Some(q) => vec!["-crf".to_string(), format!("{:.0}", 30.0 - 20.0 * q.clamp(0.0, 1.0))],
None => vec![
"-b:v".to_string(),
+15
View File
@@ -32,3 +32,18 @@ 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");
}
}
+8
View File
@@ -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
View File
@@ -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));
+2
View File
@@ -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"] }
+8
View File
@@ -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.
+1 -5
View File
@@ -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)
+44
View File
@@ -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())
}
+4
View File
@@ -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);
+9
View File
@@ -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)?);
+2 -60
View File
@@ -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() })
}
+2 -4
View File
@@ -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"
+17 -1
View File
@@ -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)
}
+1 -1
View File
@@ -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));
-1
View File
@@ -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>;
+16
View File
@@ -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"
+83
View File
@@ -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)
}
+17
View File
@@ -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;
}
+4
View File
@@ -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"
+1 -1
View File
@@ -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()?;