Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

DR2: every render writes its manifest beside its output (OUT.render.json, or DIR/NAME.render.json); raea world joins the composition's newest render (from the project's record, or --render OUT): each text's Contrast against its pixels, the frame's and each shot's Picture (light and movement), the render's Mix, each cue's Onset in it, and Covers from a render with --layers, measured on the output when asked (raea-sys-measure, which raea check's contrast and loudness now call) and kept in the manifest; a frame or world with no render says what Waits for one

shinyobjectzbb0a1768c5f9
diff --git a/Cargo.lock b/Cargo.lock
index 7dd78497..f4c347a4 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13595,6 +13595,7 @@ dependencies = [
"raea-core-brief",
"raea-core-facts",
"raea-io-trace",
+ "raea-sys-measure",
"serde_json",
]
@@ -15130,6 +15131,7 @@ name = "raea-runtime-world"
version = "0.1.0"
dependencies = [
"bevy",
+ "flate2",
"raea-core-facts",
"raea-core-scene",
"raea-runtime-bake",
@@ -15138,6 +15140,7 @@ dependencies = [
"raea-runtime-react",
"raea-runtime-scene",
"raea-sys-layers",
+ "raea-sys-measure",
"serde_json",
"sha2 0.10.9",
]
@@ -15456,6 +15459,10 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "raea-sys-measure"
+version = "0.1.0"
+
[[package]]
name = "raea-sys-mesh"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index a62e1705..c5419a54 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -86,6 +86,7 @@ members = [
"systems/bake",
"systems/contact",
"systems/light-meter",
+ "systems/measure",
"systems/canvas",
"systems/tweak",
"systems/filters",
diff --git a/apps/check/Cargo.toml b/apps/check/Cargo.toml
index 9cff13cd..1d65d447 100644
--- a/apps/check/Cargo.toml
+++ b/apps/check/Cargo.toml
@@ -13,4 +13,6 @@ raea-core-brief = { path = "../../core/brief" }
raea-core-facts = { path = "../../core/facts" }
# a check's record named by when it was (UTC, DR3)
raea-io-trace = { path = "../../io/trace" }
+# caption contrast and loudness, measured as `raea world` measures a render (DR2)
+raea-sys-measure = { path = "../../systems/measure" }
serde_json = "1"
diff --git a/apps/check/src/sound.rs b/apps/check/src/sound.rs
index d47d8592..e10b6d78 100644
--- a/apps/check/src/sound.rs
+++ b/apps/check/src/sound.rs
@@ -206,10 +206,8 @@ pub(crate) fn ffmpeg_stderr(args: &[&str]) -> R<String> {
/// -14 LUFS integrated (±1) and a true peak at or below -1 dBTP (the floor's mix line)
pub(crate) fn loudness(video: &str, taste: Option<&Taste>, issues: &mut Vec<Issue>, passed: &mut Vec<String>) -> R<()> {
- let err = ffmpeg_stderr(&["-hide_banner", "-nostats", "-i", video, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"])?;
- let summary = err.rsplit("Summary:").next().unwrap_or("");
- let num = |key: &str| summary.lines().find(|l| l.trim_start().starts_with(key)).and_then(|l| l.split_whitespace().nth(1)).and_then(|x| x.parse::<f64>().ok());
- let (Some(i), peak) = (num("I:"), num("Peak:")) else { return Ok(()) };
+ // the same measure `raea world` joins to a render as its Mix (raea-sys-measure, DR2)
+ let Some((i, peak)) = raea_sys_measure::loudness(std::path::Path::new(video)) else { return Ok(()) };
let mut ok = true;
let target = taste.map_or(-14.0, |t| t.value);
if (i - target).abs() > 1.0 {
diff --git a/apps/check/src/text.rs b/apps/check/src/text.rs
index 5f795ba8..cd23a72d 100644
--- a/apps/check/src/text.rs
+++ b/apps/check/src/text.rs
@@ -195,20 +195,6 @@ pub(crate) fn quote(s: &str) -> String {
format!("\u{201c}{s}\u{201d}")
}
-pub(crate) fn rgb_of(css: &str) -> [f64; 3] {
- let n: Vec<f64> = css.split(|c: char| !(c.is_ascii_digit() || c == '.')).filter(|s| !s.is_empty()).filter_map(|s| s.parse().ok()).collect();
- [n.first().copied().unwrap_or(255.0), n.get(1).copied().unwrap_or(255.0), n.get(2).copied().unwrap_or(255.0)]
-}
-
-/// relative luminance (WCAG) of an sRGB colour 0-255
-pub(crate) fn lum([r, g, b]: [f64; 3]) -> f64 {
- let c = |v: f64| {
- let v = v / 255.0;
- if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
- };
- 0.2126 * c(r) + 0.7152 * c(g) + 0.0722 * c(b)
-}
-
/// Caption contrast: at each text's middle frame, the pixels behind it against its colour, at least 3:1. The pixels
/// behind are the half of the box least like the text.
pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe, issues: &mut Vec<Issue>, passed: &mut Vec<String>) {
@@ -217,29 +203,13 @@ pub(crate) fn contrast(video: &str, runs: &[Run], w: f64, h: f64, probe: &Probe,
let mut measured = 0;
for r in runs.iter().filter(|r| r.size >= 20.0).take(80) {
let [x, y, bw, bh] = r.box_;
- // even sizes and offsets: the decoder's 4:2:0 frame crops to them
- let (cx, cy, cw, ch) = ((x * sx).max(0.0) as u32 & !1, (y * sy).max(0.0) as u32 & !1, ((bw * sx) as u32).max(2) & !1, ((bh * sy) as u32).max(2) & !1);
- if cx + cw > probe.w as u32 || cy + ch > probe.h as u32 {
+ let crop = [(x * sx).max(0.0) as u32, (y * sy).max(0.0) as u32, (bw * sx) as u32, (bh * sy) as u32];
+ if crop[0] + crop[2] > probe.w as u32 || crop[1] + crop[3] > probe.h as u32 {
continue;
}
let t = (r.from + r.to) / 2.0;
- let Ok(out) = Command::new("ffmpeg")
- .args(["-v", "error", "-ss", &format!("{t:.3}"), "-i", video, "-frames:v", "1", "-vf", &format!("crop={cw}:{ch}:{cx}:{cy}"), "-f", "rawvideo", "-pix_fmt", "rgb24", "-"])
- .output()
- else {
- continue;
- };
- if out.stdout.len() < (cw * ch * 3) as usize {
- continue;
- }
- let text = lum(rgb_of(&r.color));
- let mut ls: Vec<f64> = out.stdout.chunks_exact(3).map(|p| lum([p[0] as f64, p[1] as f64, p[2] as f64])).collect();
- ls.sort_by(|a, b| (b - text).abs().total_cmp(&(a - text).abs()));
- let behind = &ls[..ls.len() / 2];
- let mut sorted = behind.to_vec();
- sorted.sort_by(f64::total_cmp);
- let bg = sorted[sorted.len() / 2];
- let ratio = (text.max(bg) + 0.05) / (text.min(bg) + 0.05);
+ // the same measure `raea world` joins to a text from its render (raea-sys-measure, DR2)
+ let Some(ratio) = raea_sys_measure::contrast(std::path::Path::new(video), t, crop, &r.color) else { continue };
measured += 1;
if ratio < 3.0 {
low += 1;
diff --git a/apps/direction/src/rendered.rs b/apps/direction/src/rendered.rs
index b6956098..e7622eed 100644
--- a/apps/direction/src/rendered.rs
+++ b/apps/direction/src/rendered.rs
@@ -41,7 +41,10 @@ pub fn rendered(args: &[String]) -> i32 {
let found = finding::taken();
let through = despite(args, std::env::var("RAEA_DESPITE").ok());
let excused: Vec<Despite> = through.iter().map(|(c, w)| Despite { check: c.clone(), why: w.clone() }).collect();
- if let Some(m) = raea_runtime_bundle::flag(args, "--manifest") {
+ let out = raea_runtime_bundle::flag(args, "-o").or_else(|| raea_runtime_bundle::flag(args, "--review")).map(PathBuf::from);
+ // the manifest every render writes beside its output (DR2), or where --manifest put it
+ let manifest = raea_runtime_bundle::flag(args, "--manifest").map(PathBuf::from).or_else(|| Some(raea_runtime_world::manifest_for(out.as_deref()?, std::path::Path::new(args.get(1)?))));
+ if let Some(m) = manifest {
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {
v["findings"] = json!(found);
if !excused.is_empty() {
@@ -52,7 +55,6 @@ pub fn rendered(args: &[String]) -> i32 {
}
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
- let out = raea_runtime_bundle::flag(args, "-o").or_else(|| raea_runtime_bundle::flag(args, "--review")).map(PathBuf::from);
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
}
diff --git a/apps/direction/src/world.rs b/apps/direction/src/world.rs
index 629d41f7..7123a766 100644
--- a/apps/direction/src/world.rs
+++ b/apps/direction/src/world.rs
@@ -2,11 +2,11 @@
//! nothing drawn; the page laid out unless `--no-layout`. `--find` is one query of it, raea/ecs's find: the entities
//! with every component `with` names, none `without` names, and each `where` field equal (`"Layer.medium": "2d-type"`).
-use raea_runtime_world::{Ask, Entity, Facts};
+use raea_runtime_world::{Ask, Entity, Facts, Render};
use raea_runtime_bundle::flag;
use serde_json::{json, Value};
-pub const USAGE: &str = "raea world EDIT.tsx [--composition ID] [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--json] (a frame as one world: its layers, text, parts, camera, shots, clips, cues and lines as entities with components, each measured; --find '{\"with\": [\"Text\", \"Layer\"], \"where\": {\"Layer.medium\": \"2d-type\"}}' is one query across media)";
+pub const USAGE: &str = "raea world EDIT.tsx [--composition ID] [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--render OUT | --no-render] [--json] (a frame as one world: its layers, text, parts, camera, shots, clips, cues and lines as entities with components, each measured, with what its newest render measured (contrast, light and movement, loudness, onsets, covers) or what waits for one; --find '{\"with\": [\"Text\", \"Layer\"], \"where\": {\"Layer.medium\": \"2d-type\"}}' is one query across media)";
/// A query: the components an entity has, those it hasn't, and fields (Component.field.field) equal to a value.
#[derive(Debug, Default, PartialEq)]
@@ -92,6 +92,10 @@ fn line(e: &Entity) -> String {
"Cue" => format!("{} from {:.2}s{}", s(&c["source"]), c["at"].as_f64().unwrap_or(0.0), c["gain"].as_f64().map(|g| format!(" at {g} dB")).unwrap_or_default()),
"Line" => format!("\"{}\" from {:.2}s{}", s(&c["text"]), c["from"].as_f64().unwrap_or(0.0), c["needs"].as_str().map(|n| format!(" (needs {n})")).unwrap_or_default()),
"Source" => format!("{}:{}{}", s(&c["file"]), c["line"], c["component"].as_str().map(|n| format!(" <{n}>")).unwrap_or_default()),
+ "Contrast" => format!("{}:1 against its pixels", c["ratio"]),
+ "Picture" => picture(c),
+ "Onset" => c["at"].as_f64().map_or_else(|| "not heard where it starts".into(), |a| format!("heard at {a:.2}s ({:+} ms)", c["late_ms"].as_f64().unwrap_or(0.0))),
+ "Covers" => c.as_array().into_iter().flatten().map(|x| format!("#{} {:.0}%", x["layer"], x["share"].as_f64().unwrap_or(0.0) * 100.0)).collect::<Vec<_>>().join(", "),
_ => c.get("to").map_or_else(|| c.to_string(), |t| format!("#{t}")),
};
out.push_str(&format!(" {name} {gist}"));
@@ -99,10 +103,57 @@ fn line(e: &Entity) -> String {
out
}
+/// A picture's light and movement as words.
+fn picture(c: &Value) -> String {
+ let moved = c["motion"].as_f64().map(|m| format!(", motion {m:.3}")).unwrap_or_default();
+ format!("luma {:.3}{moved}{}", c["luma"].as_f64().unwrap_or(0.0), c["frames"].as_u64().map(|n| format!(" over {n} frames")).unwrap_or_default())
+}
+
+/// The frame's resources as lines: the render its facts came from, its mix and picture, what waits for one.
+fn resources(w: &Facts) -> Vec<String> {
+ let r = &w.resources;
+ let mut out = Vec::new();
+ if let Some(x) = r.get("Rendered") {
+ let stale = if x["stale"] == true { " (made before the composition last changed: its measures are of that version)" } else { "" };
+ out.push(format!(" rendered: {}{}{stale}", raea_runtime_world::text_of(&x["out"]), x["record"].as_str().map(|i| format!(" ({i})")).unwrap_or_default()));
+ }
+ if let Some(m) = r.get("Mix") {
+ out.push(match m["lufs"].as_f64() {
+ Some(l) => format!(" mix: {l:.1} LUFS{}", m["peak"].as_f64().map(|p| format!(", true peak {p:.1} dBTP")).unwrap_or_default()),
+ None => " mix: no sound".into(),
+ });
+ }
+ if let Some(p) = r.get("Picture") {
+ out.push(format!(" picture: {}", picture(p)));
+ }
+ if let Some(Value::Object(ws)) = r.get("Waits") {
+ let mut by: Vec<(String, Vec<&str>)> = Vec::new();
+ for (c, on) in ws {
+ let on = raea_runtime_world::text_of(on);
+ match by.iter_mut().find(|(o, _)| *o == on) {
+ Some((_, cs)) => cs.push(c),
+ None => by.push((on, vec![c])),
+ }
+ }
+ out.extend(by.into_iter().map(|(on, cs)| format!(" waits for {on}: {}", cs.join(", "))));
+ }
+ out
+}
+
+/// Which render's facts join: `--render OUT`, none with `--no-render`, else the newest in the project's record.
+fn render(args: &[String]) -> Result<Render, String> {
+ match (flag(args, "--render"), args.iter().any(|a| a == "--no-render")) {
+ (Some(_), true) => Err("give --render or --no-render, not both".into()),
+ (Some(o), false) => Ok(Render::From(o.into())),
+ (None, true) => Ok(Render::Off),
+ (None, false) => Ok(Render::Newest),
+ }
+}
+
fn run(args: &[String]) -> Result<String, String> {
let edit = args.iter().find(|a| a.ends_with(".tsx")).ok_or(USAGE)?;
let q = flag(args, "--find").as_deref().map(Find::parse).transpose()?;
- let ask = Ask { frames: frames(args)?, layout: !args.iter().any(|a| a == "--no-layout") };
+ let ask = Ask { frames: frames(args)?, layout: !args.iter().any(|a| a == "--no-layout"), render: render(args)? };
let worlds = raea_runtime_world::read(std::path::Path::new(edit), &raea_runtime_bundle::comp_opts(args)?, &ask)?;
if args.iter().any(|a| a == "--json") {
let one = |w: &Facts| match &q {
@@ -116,6 +167,7 @@ fn run(args: &[String]) -> Result<String, String> {
for w in &worlds {
let shown = q.as_ref().map_or_else(|| w.entities.iter().collect(), |q| find(w, q));
out.push(format!("frame {} ({}x{} at {} fps): {} of {} entities", w.frame, w.width, w.height, w.fps, shown.len(), w.entities.len()));
+ out.extend(resources(w));
out.extend(shown.into_iter().map(line));
}
Ok(out.join("\n"))
diff --git a/core/facts/src/components.rs b/core/facts/src/components.rs
index 410a14e1..b3284a53 100644
--- a/core/facts/src/components.rs
+++ b/core/facts/src/components.rs
@@ -24,11 +24,18 @@ pub struct Facts {
pub height: u32,
pub fps: f64,
pub entities: Vec<Entity>,
+ /// what belongs to the frame, not to one entity (the render's Mix, what Waits for one), by name
+ #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
+ pub resources: BTreeMap<String, Value>,
}
impl Facts {
pub fn new(frame: i64, width: u32, height: u32, fps: f64) -> Self {
- Facts { frame, width, height, fps, entities: Vec::new() }
+ Facts { frame, width, height, fps, entities: Vec::new(), resources: BTreeMap::new() }
+ }
+ /// A resource, by its type's name (a second replaces the first).
+ pub fn set<C: Component>(&mut self, c: &C) {
+ self.resources.insert(C::NAME.to_string(), serde_json::to_value(c).unwrap_or(Value::Null));
}
/// A new entity with no components yet: its id.
pub fn spawn(&mut self, parent: Option<u32>) -> u32 {
@@ -67,8 +74,9 @@ pub trait Component: Serialize + for<'a> Deserialize<'a> {
const NAME: &'static str;
}
macro_rules! component {
- ($($t:ident),*) => { $(impl Component for $t { const NAME: &'static str = stringify!($t); })* };
+ ($($t:ident),*) => { $(impl $crate::components::Component for $t { const NAME: &'static str = stringify!($t); })* };
}
+pub(crate) use component;
component!(Source, Layer, Text, Part, Camera, Shot, Clip, Cue, Line);
/// Where a thing was written: its file and line, the component that drew it, and the chain of uses down to it (the
@@ -230,7 +238,8 @@ pub struct Line {
pub fn declarations() -> Vec<String> {
let cfg = Config::default();
macro_rules! decls { ($($t:ty),*) => { vec![$(format!("export {}", <$t as TS>::decl(&cfg))),*] }; }
- decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Word, Clip, Cue, Line, crate::Level, crate::About, crate::Measure, crate::Finding)
+ use crate::rendered::*;
+ decls!(Source, Medium, Layer, Text, Part, Camera, Shot, Word, Clip, Cue, Line, Contrast, Picture, Onset, Covered, Covers, Mix, Rendered, Waits, crate::Level, crate::About, crate::Measure, crate::Finding)
}
#[cfg(test)]
diff --git a/core/facts/src/lib.rs b/core/facts/src/lib.rs
index 31bbf5ad..fb3bc848 100644
--- a/core/facts/src/lib.rs
+++ b/core/facts/src/lib.rs
@@ -12,6 +12,10 @@ pub use words::transcript_words;
pub mod finding;
pub use finding::{About, Finding, Level, Measure};
+// what a render adds to a frame's world, and what waits for one (DR2)
+pub mod rendered;
+pub use rendered::*;
+
// the project's record: what each render and check found, kept by render and commit (DR3)
pub mod record;
diff --git a/core/facts/src/rendered.rs b/core/facts/src/rendered.rs
new file mode 100644
index 00000000..c4f20adb
--- /dev/null
+++ b/core/facts/src/rendered.rs
@@ -0,0 +1,68 @@
+//! What a render adds to a frame's world (docs/direction.feature DR2): facts only its output holds, each measured on
+//! it when a check asks and kept in its manifest. A world read with no render says what waits for one (`Waits`).
+
+use std::collections::BTreeMap;
+
+use serde::{Deserialize, Serialize};
+use ts_rs::TS;
+
+/// A text's contrast against the pixels behind it in the render (WCAG's ratio, 1 to 21: `raea check`'s measure).
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+pub struct Contrast {
+ pub ratio: f64,
+}
+
+/// The picture's light and movement: its mean luma (0 to 1) and the mean change from the frame before (0 to 1; None
+/// with no frame before it rendered). As a resource, this frame's; on a Shot, the mean over its frames rendered,
+/// counted in `frames`.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+#[ts(optional_fields)]
+pub struct Picture {
+ pub luma: f64,
+ pub motion: Option<f64>,
+ pub frames: Option<u32>,
+}
+
+/// When a cue is heard in the render's mix: the onset nearest its start (seconds) and how late it is (ms; before its
+/// start is negative). Both None when nothing starts there: under a louder bed, or not playing.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+#[ts(optional_fields)]
+pub struct Onset {
+ pub at: Option<f64>,
+ pub late_ms: Option<f64>,
+}
+
+/// One layer a layer is drawn over this frame, and the share of its box covered.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+pub struct Covered {
+ pub layer: u32,
+ pub share: f64,
+}
+
+/// A layer drawn over others (a render with --layers, its masks): each it covers.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+pub struct Covers(pub Vec<Covered>);
+
+/// A resource: the render's mix, its integrated loudness (LUFS) and true peak (dBTP). None: it has no sound.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+#[ts(optional_fields)]
+pub struct Mix {
+ pub lufs: Option<f64>,
+ pub peak: Option<f64>,
+}
+
+/// A resource: the render these facts came from, its record entry, and whether the composition changed after it.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, TS)]
+#[ts(optional_fields)]
+pub struct Rendered {
+ pub out: String,
+ pub manifest: String,
+ pub record: Option<String>,
+ pub stale: bool,
+}
+
+/// A resource: each component a render would add, and what it waits for ("a render", "a render with --layers").
+#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, TS)]
+pub struct Waits(pub BTreeMap<String, String>);
+
+crate::components::component!(Contrast, Picture, Onset, Covers, Mix, Rendered, Waits);
diff --git a/docs/direction.feature b/docs/direction.feature
index 8f007d9c..7b10fd8b 100644
--- a/docs/direction.feature
+++ b/docs/direction.feature
@@ -208,15 +208,59 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
And a query spans media: "every Text whose Layer is 2d-type and that no Part masks during its Line" is one find
And the same frame gives the same world whenever it's asked for, and a range of frames gives one a frame
- @needs:DR1
+ @needs:DR1 @done
Scenario: DR2. What only a render knows joins the same world
+ # Status 11-10: built. Every render writes its manifest beside its output (OUT.render.json, or DIR/NAME.render.json
+ # for frames; --manifest still moves it): 54 KB and no measurable time on a 150-frame shot. `raea world` joins the
+ # composition's newest render in the project's record (the newest whose manifest has this composition's size and
+ # rate and whose output still exists), or the one `--render OUT` names; `--no-render` joins none. It adds each
+ # text's Contrast against its pixels, the frame's Picture (a resource) and each shot's (the mean of its frames; a
+ # shot's first frame is the cut into it, so its motion is left out), the Mix (integrated LUFS, true peak), each
+ # cue's Onset, and Covers from a render with --layers (NAME.layers: the share of a layer's box that layers drawn
+ # after it, neither inside nor around it, cover). raea-sys-measure measures the output with ffmpeg the first time
+ # a number is asked for and keeps it in the manifest's "measured", so asking again reads it back; raea check's
+ # contrast and loudness call it too. Rendered names the render and says stale when the composition changed after
+ # it; Waits names each component a render would add and what it waits for.
+ # Real run (release binary, M5 Pro, a scratch project: two shots, a caption a band covers from frame 30, a grey
+ # line on grey, a beep at 1 s, a silent cue at 2 s): the caption 18.1:1 and the grey line 1.2:1; the band covers
+ # 52% of the caption at frame 35 and nothing at frame 10; the dark shot's luma 0.112, the light one's 0.842; the
+ # beep heard at 1.00 s (+0 ms), the silent cue "not heard where it starts"; the mix -27.4 LUFS. Three frames read
+ # the first time, measuring, in 0.97 s; one frame read back from the manifest in 0.52-0.59 s.
+ # The cheats, each fails: --no-render adds nothing and lists what waits; a composition changed after its render
+ # says stale; a still rendered after the video is the newest render, so Mix and Onset wait for a video render,
+ # Covers for one with --layers, and a frame it didn't draw takes nothing of another frame's; --render naming the
+ # video joins it again.
+ # Found and fixed on the way: `raea render --layers` recorded masks of no layer unless RAEA_SOURCE_STAMPS=1 was
+ # set (the layer pass keys pixels by source stamps; fixed on main by the layer pass's lane, 43429e6f2); an onset
+ # read 20 ms early on an AAC encoder's pre-echo (-111 dB out of digital silence), so a rise now counts once it is
+ # within 10 dB of where the sound goes; a shot's motion counted the cut into it; --render dated the render by its
+ # manifest, which a read rewrites, instead of by its output.
+ # Proved by tests in raea-sys-measure (4), raea-runtime-world (12: renders 3, covers 1), raea-core-facts (8),
+ # raea-app-check (27), raea-app-direction (5) and raea-sys-layers (7).
+ # Not seen, or left: the test render wasn't watched or listened to; its numbers are what the measures read. What
+ # the page draws over a 3D part isn't kept (NAME.layers holds only each pixel's frontmost layer), so no part is
+ # ever covered. Plain elements are ordered by document order, not z-index. Light and movement are read from 64x64
+ # grey frames, so motion is small for small things (a 200 px box moving 15 px a frame reads 0.001). An onset is
+ # found to 10 ms. Contrast is the text against the half of its box least like it, so a caption half under a band
+ # reads as its visible half; the band is what Covers says.
+ Given the plan
+ | crate | file | lines | job |
+ | raea-sys-measure | systems/measure/src/lib.rs | 220 | a render's output measured (ffmpeg reads it): each frame's luminance and motion, a box's contrast against its text's colour, the mix's loudness and true peak, the onset nearest a time |
+ | raea-core-facts | core/facts/src/rendered.rs | 90 | what a render adds to a world: Covers, Contrast, Picture, Onset; the world's resources (Mix, the render it came from, what waits for one) |
+ | raea-runtime-world | runtime/world/src/renders.rs | 240 | a composition's newest render found (the project's record, or --render), its manifest's frames joined to the frame's entities, its measures kept in its manifest |
+ | raea-runtime-world | runtime/world/src/covers.rs | 160 | NAME.layers (a render with --layers) read: how much of each layer the layers drawn over it cover this frame |
Then every render writes its manifest (today only with --manifest), beside its output
And the manifest is entities too, added to the frame's world when a check asks for them: the layer
masks (review.feature R2b) as `Covers { layer, share }` between layers, each text's contrast against what is
behind it, each shot's measured motion and luminance (goal.feature Track G's columns), the mix's loudness and
each cue's measured onset
- And a check says whether it needs them (`needs: "render"`); `raea check` on a project with no render runs the
- rest and lists what waits for one
+ And what a render adds says it needs one: a world with no render, or a frame the render didn't draw, has a
+ `Waits` resource naming each component it would add and what it waits for ("a render", "a video render", "a
+ render with --layers", "a render of frame N")
+ # Fixed in the code (DR2): this line said "a check says whether it needs them; `raea check` on a project with no
+ # render runs the rest and lists what waits for one". A check that declares `needs` is DR4's (`check({ id, text,
+ # needs, level }, ...)`), and before DR4 there is no set of checks for `raea check` to run "the rest" of. DR2
+ # gives the world `Waits`, the data that needs it; DR4 now holds the `raea check` half.
@needs:DR1 @done
Scenario: DR3. One finding, for every command
@@ -293,6 +337,8 @@ Feature: Direction that holds: one world of facts, findings and rules, so a pers
`found(...)`, and the components' types generated from core/facts (ts-rs, as core/brief's are)
Then `raea check [PROJECT | EDIT.tsx | VIDEO.mp4] [--stage S] [--only ID] [--json]` runs every check that
applies: raea's floor, the person's taste, the workspace's and the project's rules, the project's notes
+ And a check says whether it needs a render (`needs: "render"`); on a project or composition with no render,
+ `raea check` runs the checks that need none and lists each that waits, with what it waits for (DR2's Waits)
And a check is told once what it ranges over (`frames: "all" | "cuts" | "lines" | [..]`) and is run there; it
finds entities, measures, and calls `found(...)`; it never prints
And the same check text reads for a mesh and for a caption: `world.find({ with: ["Text", "Layer"] })`
diff --git a/docs/manual/reference/cli/render.md b/docs/manual/reference/cli/render.md
index ecc78bf1..a543ae6e 100644
--- a/docs/manual/reference/cli/render.md
+++ b/docs/manual/reference/cli/render.md
@@ -35,9 +35,14 @@ to the composition are loaded on their own, as `raea play` loads them; a flag na
A whole video made from the same inputs as an earlier one is copied from the export cache rather than drawn again,
and the command says so.
+Every render writes its manifest beside its output: `OUT.render.json` (`DIR/NAME.render.json` for a folder of
+frames), or where `--manifest` says. It holds what each frame showed as laid out (each text's words, box, colour and
+size, each video's source and time), the sounds heard and what the render found. `raea check` reads it, and so does
+[`raea world`](world.md), which measures the output against it when a check asks.
+
A render checks what it draws: 3D parts passing into each other (the clipping check) and its pictures' exposure
-(clipping to white, crushing to black). Each finding is said as it is found, written into the manifest with
-`--manifest`, and counted on the last line the command prints (`raea render: 1 error, 0 warns, 0 notes`). An error
+(clipping to white, crushing to black). Each finding is said as it is found, written into the manifest, and
+counted on the last line the command prints (`raea render: 1 error, 0 warns, 0 notes`). An error
makes the render exit 1 once its output is written; `--despite CHECK WHY` lets that check's errors through and puts
the reason in the manifest. A render of a file in a raea project also keeps its findings in the project's record
(`.raea/record/`, by render and commit), which `raea findings` and `raea next` read.
@@ -78,7 +83,7 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| `--kbps` | `N` | A fixed video bitrate in kbit/s, in place of the default that follows size and frame rate. |
| `--layers` | – | Write `NAME.layers` beside the export: which layer (a 3D part, an element, its text, an image or a video, by where its JSX is written) each pixel of each frame shows, for raea's player to select layers by clicking. The manifest (`--manifest`, or `NAME.render.json` beside it) names it. The export cache is skipped. |
| `--lite` | – | Draw with raea's live view runtime instead of React, as a live game does. Used by the app when it opens a game. |
-| `--manifest` | `render.json` | Write a manifest of the render to this file: every frame's element boxes as drawn, the 3D's clipping and the sounds heard, which `raea check` reads. |
+| `--manifest` | `render.json` | Write the render's manifest to this file instead of beside the output: every frame's element boxes as drawn, what the render found and the sounds heard, which `raea check` and `raea world` read. |
| `--perception` | `P.json` | The perception the composition's Clock reads (faces, boxes, one for every frame or by frame), when it isn't the `perception.json` beside it. |
| `--quality` | `draft\|high\|master\|0..1` | Constant-quality encoding: `draft` for previews, `high` for most deliveries, `master` for type and hard edges, or a number from 0 to 1. On Windows and Linux (OpenH264) it scales the bitrate instead, and once a frame fits at OpenH264's finest quantiser (12), a higher setting writes the same file. |
| `--review` | `DIR` | Render a 3D scene from six fixed cameras (hero, front, right, top, iso, low), in colour and in clay, to `DIR/colour.png`, `DIR/clay.png` and `DIR/review.json`. |
diff --git a/docs/manual/reference/cli/world.md b/docs/manual/reference/cli/world.md
index 76254a36..a1a1aabf 100644
--- a/docs/manual/reference/cli/world.md
+++ b/docs/manual/reference/cli/world.md
@@ -15,6 +15,13 @@ carries its Source: the file and line that wrote it and the component it was use
`--find` is one query across all of it: the entities with every component `with` names, none of those `without`
names, and each `where` field equal to its value.
+What only a render knows joins the same world. The newest render of the composition in its project's record (or the
+one `--render` names) adds each text's `Contrast` against the pixels behind it, the frame's and each shot's
+`Picture` (light and movement), the `Mix`'s loudness and each cue's `Onset` in it, and, from a render with
+`--layers`, which layers `Covers` which. Each is measured on the output the first time it's asked for and kept in the
+render's manifest. The `Rendered` resource names the render, and says `stale` when the composition changed after it.
+With no render, or on a frame the render didn't draw, the `Waits` resource says what waits for one.
+
```sh
raea world edit.tsx --frame 120
raea world edit.tsx --at 0-29 --json > world.json
@@ -27,7 +34,7 @@ raea world edit.tsx --frame 48 --find '{"with": ["Part"], "where": {"Part.kind":
## Usage
```sh
-raea world EDIT.tsx [--composition ID] [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--json] (a frame as one world: its layers, text, parts, camera, shots, clips, cues and lines as entities with components, each measured; --find '{"with": ["Text", "Layer"], "where": {"Layer.medium": "2d-type"}}' is one query across media)
+raea world EDIT.tsx [--composition ID] [--frame N | --at A-B|A,B] [--find JSON] [--no-layout] [--render OUT | --no-render] [--json] (a frame as one world: its layers, text, parts, camera, shots, clips, cues and lines as entities with components, each measured, with what its newest render measured (contrast, light and movement, loudness, onsets, covers) or what waits for one; --find '{"with": ["Text", "Layer"], "where": {"Layer.medium": "2d-type"}}' is one query across media)
```
Headless: it needs nothing running and opens no window. Takes up to 1 argument besides its flags.
@@ -42,6 +49,8 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| `--frame` | `N` | The frame to read (0 when neither this nor `--at` is given). |
| `--json` | – | Print each frame as JSON: its size, fps and every entity with its id, parent and components. |
| `--no-layout` | – | Don't lay the page out. Faster, but text has no box, size or line count and carries `needs: "render"`. |
+| `--no-render` | – | Join no render: the world as the composition says, with what a render would add listed in `Waits`. |
+| `--render` | `OUT` | Join this render (an output of `raea render`, its manifest beside it) instead of the newest one in the project's record. |
<!-- generated:end -->
@@ -58,6 +67,14 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| `Cue` | a sound on the timeline | `source`, `at` (seconds), `gain` (dB), `bus` |
| `Line` | a line sung or said now | `text`, `from`, `to`, `words` with their times (the project's words.json) |
| `Source` | whatever was written | `file`, `line`, `component`, `key` (the layer key) |
+| `Contrast` | a run of 2D type, from a render | `ratio`: its colour against the pixels behind it (WCAG, 1 to 21), as `raea check` measures it |
+| `Picture` | a shot, and the frame as a resource, from a render | `luma` (0 to 1), `motion` (the mean change from the frame before, 0 to 1; a shot leaves out its first frame, the cut into it), `frames` measured on a shot |
+| `Onset` | a cue, from a video render | `at`: when the mix rises 6 dB where it starts, to within 10 dB of where it goes (seconds), `late_ms`; both empty when nothing starts there |
+| `Covers` | a layer drawn over others, from a render with `--layers` | each layer it covers and the `share` of that layer's box |
+
+Resources belong to the frame, not to one entity: `Mix` (the render's `lufs` and true `peak`), `Rendered` (its
+output, manifest, record entry and whether it is `stale`) and `Waits` (each component a render would add, and what
+it waits for).
A field raea can't know without a render says so: text from a page that wasn't laid out has `needs: "render"`, and
a `<Speech>` line has `needs: "transcript"` for its word times.
diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rs
index 850d75fc..15610100 100644
--- a/runtime/export/src/render.rs
+++ b/runtime/export/src/render.rs
@@ -60,8 +60,8 @@ 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,
};
- let layers = raea_sys_layers::start(layers_on, &out, &tsx);
- *MANIFEST.lock().unwrap() = flag(args, "--manifest").map(PathBuf::from).or(layers);
+ 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);
AOV.store(args.iter().any(|a| a == "--aov"), std::sync::atomic::Ordering::Relaxed);
if AOV.load(std::sync::atomic::Ordering::Relaxed) && !out_ext(&out).is_empty() {
diff --git a/runtime/world/Cargo.toml b/runtime/world/Cargo.toml
index 420d2441..9b6a35b3 100644
--- a/runtime/world/Cargo.toml
+++ b/runtime/world/Cargo.toml
@@ -16,6 +16,9 @@ raea-runtime-bundle = { path = "../bundle" }
# the page laid out with nothing drawn (BevyPage::lay_out), its text and boxes read as a render's manifest reads them
raea-runtime-page = { path = "../page" }
raea-sys-layers = { path = "../../systems/layers" }
+# what a render's output measures, joined to the world (DR2), and its layers file read
+raea-sys-measure = { path = "../../systems/measure" }
+flate2 = "1"
bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app"] }
serde_json = "1"
# a clip's file's identity (its SHA-256, as raea's asset store names files)
diff --git a/runtime/world/src/covers.rs b/runtime/world/src/covers.rs
new file mode 100644
index 00000000..b3a3e274
--- /dev/null
+++ b/runtime/world/src/covers.rs
@@ -0,0 +1,162 @@
+//! Which layers cover which this frame (docs/direction.feature DR2), from a render with --layers: NAME.layers holds
+//! each frame's frontmost layer per quarter pixel (systems/layers file.rs). A layer covers another where it shows
+//! inside the other's box and is drawn after it: later in the page's document order, and neither inside the other
+//! (an element's own background is behind it). The 3D is drawn under the page, so a part covers no page layer here;
+//! what the page hides of a part the file doesn't keep (only the frontmost layer of each pixel), so no part is covered.
+
+use std::collections::HashMap;
+use std::io::Read;
+use std::path::Path;
+
+use raea_core_facts::{Covered, Covers, Facts, Source};
+use serde_json::Value;
+
+/// NAME.layers read: the mask's size and each frame's runs, the table's keys, kinds and parents, and which frame
+/// each recorded mask is.
+pub(crate) struct Masks {
+ w: usize,
+ h: usize,
+ keys: Vec<String>,
+ kinds: Vec<String>,
+ parents: Vec<Option<usize>>,
+ frames: HashMap<i64, Vec<(u16, u16)>>,
+}
+
+pub(crate) fn read(path: &Path) -> Result<Masks, String> {
+ let mut b = Vec::new();
+ flate2::read::GzDecoder::new(std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?).read_to_end(&mut b).map_err(|e| format!("{}: {e}", path.display()))?;
+ let bad = || format!("{}: not a layers file", path.display());
+ let u32_at = |i: usize| b.get(i..i + 4).map(|x| u32::from_le_bytes([x[0], x[1], x[2], x[3]]) as usize);
+ if !b.starts_with(b"RAEALAYR") {
+ return Err(bad());
+ }
+ let n = u32_at(8).ok_or_else(bad)?;
+ let head: Value = serde_json::from_slice(b.get(12..12 + n).ok_or_else(bad)?).map_err(|_| bad())?;
+ let layers = head["layers"].as_array().cloned().unwrap_or_default();
+ let field = |name: &str| -> Vec<String> { layers.iter().map(|l| l[name].as_str().unwrap_or_default().to_string()).collect() };
+ let (keys, kinds) = (field("key"), field("kind"));
+ let at: HashMap<&str, usize> = keys.iter().enumerate().map(|(i, k)| (k.as_str(), i)).collect();
+ let parents = field("parent").iter().map(|p| at.get(p.as_str()).copied()).collect();
+ let count = head["frames"].as_u64().unwrap_or(0) as i64;
+ let which: Vec<i64> = head["at"].as_array().map(|a| a.iter().filter_map(Value::as_i64).collect()).unwrap_or_else(|| (0..count).collect());
+ let (mut frames, mut i, mut before) = (HashMap::new(), 12 + n, Vec::new());
+ for f in which {
+ let runs = u32_at(i).ok_or_else(bad)?;
+ i += 4;
+ if runs > 0 {
+ let body = b.get(i..i + runs * 4).ok_or_else(bad)?;
+ before = body.chunks_exact(4).map(|r| (u16::from_le_bytes([r[0], r[1]]), u16::from_le_bytes([r[2], r[3]]))).collect();
+ i += runs * 4;
+ }
+ frames.insert(f, before.clone());
+ }
+ Ok(Masks { w: head["mask"]["w"].as_u64().unwrap_or(0) as usize, h: head["mask"]["h"].as_u64().unwrap_or(0) as usize, keys, kinds, parents, frames })
+}
+
+impl Masks {
+ /// Whether layer `a` is `b` or inside it.
+ fn within(&self, mut a: usize, b: usize) -> bool {
+ for _ in 0..self.keys.len() {
+ if a == b {
+ return true;
+ }
+ let Some(p) = self.parents[a] else { return false };
+ a = p;
+ }
+ false
+ }
+
+ /// Frame `f`'s layers drawn over the one keyed `key` inside `bx` (x0, y0, x1, y1, each 0 to 1), each with the
+ /// share of the box it covers, by `order` (each key's place in the page's document order).
+ pub(crate) fn over(&self, f: i64, key: &str, bx: [f64; 4], order: &HashMap<String, usize>) -> Vec<(String, f64)> {
+ let (Some(runs), Some(me), Some(&mine)) = (self.frames.get(&f), self.keys.iter().position(|k| k == key), order.get(key)) else { return Vec::new() };
+ let mask: Vec<u16> = runs.iter().flat_map(|(v, n)| std::iter::repeat_n(*v, *n as usize)).collect();
+ let span = |a: f64, b: f64, n: usize| ((a * n as f64).floor().max(0.0) as usize, ((b * n as f64).ceil() as usize).min(n));
+ let ((x0, x1), (y0, y1)) = (span(bx[0], bx[2], self.w), span(bx[1], bx[3], self.h));
+ let mut seen: HashMap<u16, usize> = HashMap::new();
+ for y in y0..y1 {
+ for x in x0..x1 {
+ *seen.entry(mask.get(y * self.w + x).copied().unwrap_or(0)).or_default() += 1;
+ }
+ }
+ let all = ((x1.saturating_sub(x0)) * (y1.saturating_sub(y0))).max(1) as f64;
+ let mut out: Vec<(String, f64)> = seen
+ .into_iter()
+ .filter_map(|(v, n)| {
+ let j = (v as usize).checked_sub(1).filter(|j| *j < self.keys.len())?;
+ let later = order.get(&self.keys[j]).is_some_and(|o| *o > mine);
+ let apart = !self.within(j, me) && !self.within(me, j);
+ (later && apart && self.kinds[j] != "mesh").then(|| (self.keys[j].clone(), ((n as f64 / all) * 1000.0).round() / 1000.0)).filter(|(_, s)| *s > 0.0)
+ })
+ .collect();
+ out.sort_by(|a, b| b.1.total_cmp(&a.1));
+ out
+ }
+}
+
+/// Each boxed layer of the world (`boxed`: its entity, key and box) and what covers it this frame, as Covers on the
+/// covering layer's entity: the world's entity with that key, or a new one with only its Source when the page drew it
+/// but the world holds no entity of it (a plain element, a band).
+pub(crate) fn put(facts: &mut Facts, masks: &Masks, boxed: &[(u32, String, [f64; 4])], order: &HashMap<String, usize>) {
+ let mut by: HashMap<String, Vec<Covered>> = HashMap::new();
+ for (e, key, bx) in boxed {
+ for (k, share) in masks.over(facts.frame, key, *bx, order) {
+ by.entry(k).or_default().push(Covered { layer: *e, share });
+ }
+ }
+ let mut keys: Vec<String> = by.keys().cloned().collect();
+ keys.sort_by_key(|k| order.get(k).copied());
+ for k in keys {
+ let id = keyed(facts, &k).unwrap_or_else(|| {
+ let id = facts.spawn(None);
+ facts.put(id, &source_of(&k));
+ id
+ });
+ facts.put(id, &Covers(by.remove(&k).unwrap_or_default()));
+ }
+}
+
+/// The world's entity whose Source has the layer key `key`.
+pub(crate) fn keyed(facts: &Facts, key: &str) -> Option<u32> {
+ facts.entities.iter().find(|e| e.components.get("Source").and_then(|s| s["key"].as_str()) == Some(key)).map(|e| e.id)
+}
+
+/// A key's Source: its file and line ("file:line:col[#index][|use...]").
+fn source_of(key: &str) -> Source {
+ let loc = key.split(['|', '#']).next().unwrap_or(key);
+ let mut parts = loc.rsplitn(3, ':');
+ let (_col, line, file) = (parts.next(), parts.next().and_then(|l| l.parse().ok()), parts.next());
+ Source { file: file.map(str::to_string), line, component: None, key: Some(key.to_string()) }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn masks(mask: &[u16]) -> Masks {
+ let runs = mask.iter().map(|v| (*v, 1)).collect();
+ let keys = ["bg.tsx:1:1", "bg.tsx:2:3", "bg.tsx:3:3", "bg.tsx:4:3"].map(String::from).to_vec();
+ // the caption (2) is inside the background (1); the band (3) and the mesh (4) are its siblings
+ Masks { w: 4, h: 1, keys, kinds: ["element", "text", "element", "mesh"].map(String::from).to_vec(), parents: vec![None, Some(0), Some(0), None], frames: HashMap::from([(7, runs)]) }
+ }
+
+ #[test]
+ fn a_layer_drawn_after_another_covers_its_share_of_the_box_and_a_background_does_not() {
+ let order: HashMap<String, usize> = [("bg.tsx:1:1", 0), ("bg.tsx:2:3", 1), ("bg.tsx:3:3", 2), ("bg.tsx:4:3", 3)].map(|(k, o)| (k.to_string(), o)).into();
+ // the caption's box is the whole row: its own ink, its background, the band twice
+ let m = masks(&[2, 1, 3, 3]);
+ assert_eq!(m.over(7, "bg.tsx:2:3", [0.0, 0.0, 1.0, 1.0], &order), vec![("bg.tsx:3:3".to_string(), 0.5)]);
+ // drawn before the caption, the band is behind it: it covers nothing
+ let back: HashMap<String, usize> = order.iter().map(|(k, o)| (k.clone(), if k == "bg.tsx:3:3" { 0 } else { o + 1 })).collect();
+ assert!(m.over(7, "bg.tsx:2:3", [0.0, 0.0, 1.0, 1.0], &back).is_empty());
+ // a 3D part shows only where the page painted nothing: it covers no page layer
+ assert!(masks(&[4, 4, 2, 2]).over(7, "bg.tsx:2:3", [0.0, 0.0, 1.0, 1.0], &order).is_empty());
+ assert!(m.over(8, "bg.tsx:2:3", [0.0, 0.0, 1.0, 1.0], &order).is_empty(), "a frame not recorded");
+ let mut w = Facts::new(7, 4, 1, 30.0);
+ let caption = w.spawn(None);
+ put(&mut w, &m, &[(caption, "bg.tsx:2:3".into(), [0.0, 0.0, 1.0, 1.0])], &order);
+ let band = w.find(&["Covers"])[0];
+ assert_eq!(band.components["Covers"], serde_json::json!([{"layer": caption, "share": 0.5}]));
+ assert_eq!((band.components["Source"]["file"].as_str(), band.components["Source"]["line"].as_u64()), (Some("bg.tsx"), Some(3)));
+ }
+}
diff --git a/runtime/world/src/lib.rs b/runtime/world/src/lib.rs
index 26d62408..d253ce58 100644
--- a/runtime/world/src/lib.rs
+++ b/runtime/world/src/lib.rs
@@ -3,16 +3,22 @@
//! (page.rs) and its timeline's shots, clips, cues and lines (timeline.rs) become entities with components
//! (raea-core-facts), so one query can span every medium a piece has.
+mod covers;
mod page;
+mod renders;
mod scene;
mod source;
mod timeline;
+pub use renders::Render;
+
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use bevy::prelude::{App, MinimalPlugins};
pub use raea_core_facts::*;
+// where a render's manifest is (every render writes one beside its output, DR2)
+pub use raea_sys_layers::manifest_for;
use raea_runtime_bundle::{bundle_composition, CompOpts};
use raea_core_scene::num;
use serde_json::Value;
@@ -24,6 +30,8 @@ type R<T> = Result<T, String>;
pub struct Ask {
pub frames: Vec<i64>,
pub layout: bool,
+ /// which render's facts join the world (DR2)
+ pub render: Render,
}
/// One stepped frame: its 3D, its React tree, and its page as laid out.
@@ -37,8 +45,7 @@ struct Snap {
/// gives the same world each time: frames are pure.
pub fn read(tsx: &Path, o: &CompOpts, ask: &Ask) -> R<Vec<Facts>> {
let tsx = tsx.canonicalize().map_err(|e| format!("{}: {e}", tsx.display()))?;
- let dir = tsx.parent().ok_or("the edit has no folder")?.to_path_buf();
- let js = std::env::temp_dir().join(format!("raea-world-{}.js", std::process::id()));
+ let js =std::env::temp_dir().join(format!("raea-world-{}.js", std::process::id()));
// every element and part stamped with its place in the code, so each entity has its Source (as the stage's
// picks have their keys, engine/page/stage); RAEA_SOURCE_STAMPS=0 in the environment keeps them off
if std::env::var_os("RAEA_SOURCE_STAMPS").is_none() {
@@ -46,13 +53,14 @@ pub fn read(tsx: &Path, o: &CompOpts, ask: &Ask) -> R<Vec<Facts>> {
unsafe { std::env::set_var("RAEA_SOURCE_STAMPS", "1") };
}
bundle_composition(&tsx, &js, o, None)?;
- let got = stepped(&js, &dir, ask, o.words.as_ref());
+ let got = stepped(&js, &tsx, ask, o.words.as_ref());
let _ = std::fs::remove_file(&js);
got
}
-fn stepped(js: &Path, dir: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Facts>> {
+fn stepped(js: &Path, tsx: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Facts>> {
use raea_runtime_react::scene::{edit_dir, scene_of, settle};
+ let dir = tsx.parent().ok_or("the edit has no folder")?;
edit_dir(dir);
let mut app = App::new();
app.add_plugins(MinimalPlugins).add_plugins(raea_runtime_react::ReactPlugin::new(js.to_path_buf()));
@@ -79,7 +87,8 @@ fn stepped(js: &Path, dir: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Fac
})?;
}
let lines = timeline::project_lines(words, dir, fps);
- Ok(ask
+ let mut render = renders::find(&ask.render, tsx, (w, h, fps));
+ let worlds = ask
.frames
.iter()
.map(|&f| {
@@ -89,9 +98,17 @@ fn stepped(js: &Path, dir: &Path, ask: &Ask, words: Option<&Value>) -> R<Vec<Fac
scene::put(&mut facts, &now.scene, snaps.get(&(f + 1)).map(|n| &n.scene[..]), fps, dir, &mut order);
timeline::put(&mut facts, &now.tree, now.laid.as_ref(), (w, h, fps), dir, &mut order);
timeline::put_lines(&mut facts, &lines, &now.tree, f, fps);
+ // what only a render knows, or what waits for one (DR2)
+ if ask.render != Render::Off {
+ renders::join(&mut facts, render.as_mut(), &now.tree);
+ }
facts
})
- .collect())
+ .collect();
+ if let Some(r) = render {
+ r.keep();
+ }
+ Ok(worlds)
}
#[cfg(test)]
diff --git a/runtime/world/src/renders.rs b/runtime/world/src/renders.rs
new file mode 100644
index 00000000..f2beb922
--- /dev/null
+++ b/runtime/world/src/renders.rs
@@ -0,0 +1,259 @@
+//! What a composition's render knows, joined to each frame's world (docs/direction.feature DR2). Every render writes
+//! its manifest beside its output (render.json: what each frame showed, as laid out); the world takes the newest of
+//! the composition's renders in its project's record, or one it's given, and adds what only that render holds: each
+//! text's contrast against its pixels, the frame's and each shot's light and movement, the mix's loudness, when each
+//! cue is heard, and, from a render with --layers, which layers cover which (covers.rs). Each is measured on the
+//! output when first asked for and kept in the manifest's "measured", so asking again reads it back. A world with no
+//! render, or a frame the render didn't draw, says what waits for one (`Waits`).
+
+use std::collections::{BTreeMap, HashMap};
+use std::path::{Path, PathBuf};
+
+use raea_core_facts::{record, Contrast, Cue, Facts, Mix, Onset, Picture, Rendered, Shot, Source, Text, Waits};
+use raea_sys_measure as measure;
+use serde_json::{json, Value};
+
+use crate::timeline::El;
+
+/// Which render joins the world.
+#[derive(Debug, Clone, Default, PartialEq)]
+pub enum Render {
+ /// the newest render of the composition in its project's record whose manifest is this composition's
+ #[default]
+ Newest,
+ /// this output
+ From(PathBuf),
+ Off,
+}
+
+/// The components a render adds, and what each waits for when there is none.
+const FROM_A_RENDER: [&str; 5] = ["Contrast", "Picture", "Mix", "Onset", "Covers"];
+
+/// A render found: its output, its manifest, its record entry, whether the composition changed after it, and each
+/// frame's place among the frames it drew.
+pub(crate) struct Found {
+ out: PathBuf,
+ path: PathBuf,
+ m: Value,
+ record: Option<String>,
+ stale: bool,
+ at: HashMap<i64, usize>,
+ /// whether "measured" gained anything to write back
+ dirty: bool,
+ env: Option<Vec<f32>>,
+ masks: Option<Option<crate::covers::Masks>>,
+}
+
+fn secs(p: &Path) -> u64 {
+ p.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_secs())
+}
+
+/// The render `how` names, if its manifest is this composition's (`size`: its width, height and frame rate).
+pub(crate) fn find(how: &Render, tsx: &Path, size: (u32, u32, f64)) -> Option<Found> {
+ let outs: Vec<(PathBuf, Option<String>, u64)> = match how {
+ Render::Off => return None,
+ // when it was made: the output's time (its manifest is written again whenever a measure is kept in it)
+ Render::From(p) => vec![(p.clone(), None, secs(p))],
+ Render::Newest => {
+ let project = record::up(tsx.parent()?, ".raea/project")?;
+ let of = record::rel(&project, tsx);
+ // the record reads oldest first: this composition's renders, newest first
+ let mut outs = Vec::new();
+ for e in record::read(&project).into_iter().rev() {
+ if let (true, Some(out)) = (e.by == "raea render" && e.of == of, e.out.as_deref()) {
+ outs.push((project.join(out), Some(e.id.clone()), e.at));
+ }
+ }
+ outs
+ }
+ };
+ outs.into_iter().find_map(|(out, record, made)| {
+ let path = crate::manifest_for(&out, tsx);
+ let m: Value = serde_json::from_slice(&std::fs::read(&path).ok()?).ok()?;
+ // another composition of the file draws another size or rate
+ let same = m["width"] == size.0 && m["height"] == size.1 && m["fps"].as_f64() == Some(size.2);
+ let at = m["frames"].as_array()?.iter().enumerate().filter_map(|(k, f)| Some((f["frame"].as_i64()?, k))).collect();
+ (same && out.exists()).then(|| Found { stale: secs(tsx) > made, out, path, m, record, at, dirty: false, env: None, masks: None })
+ })
+}
+
+impl Found {
+ fn video(&self) -> bool {
+ self.out.extension().is_some_and(|x| matches!(x.to_ascii_lowercase().to_str(), Some("mp4" | "mov" | "wav")))
+ }
+
+ /// The picture drawn as the `k`th frame of the render: its file, and the second to read it at.
+ fn picture_at(&self, k: usize) -> (PathBuf, f64) {
+ match self.out.extension() {
+ Some(_) if self.video() => (self.out.clone(), (k as f64 + 0.5) / self.m["fps"].as_f64().unwrap_or(30.0)),
+ Some(_) => (self.out.clone(), 0.0),
+ None => (self.out.join(format!("frame-{k:05}.png")), 0.0),
+ }
+ }
+
+ /// A measure kept in the manifest under `name`/`key`, or `make`'s, kept.
+ fn kept(&mut self, name: &str, key: &str, make: impl FnOnce(&mut Found) -> Value) -> Value {
+ if let Some(v) = self.m["measured"][name].get(key) {
+ return v.clone();
+ }
+ let v = make(self);
+ if !self.m["measured"].is_object() {
+ self.m["measured"] = json!({});
+ }
+ if !self.m["measured"][name].is_object() {
+ self.m["measured"][name] = json!({});
+ }
+ self.m["measured"][name][key] = v.clone();
+ self.dirty = true;
+ v
+ }
+
+ /// The `k`th frame's light and movement.
+ fn picture(&mut self, k: usize) -> Option<Picture> {
+ let v = if self.video() {
+ // a video's frames are read in one pass, all of them, the first time any is asked for
+ let all = self.kept("picture", "all", |r| json!(measure::pictures(&r.out).map(|ps| ps.iter().map(|p| json!([p.luma, p.motion])).collect::<Vec<_>>()).unwrap_or_default()));
+ all.get(k).cloned()?
+ } else {
+ let (file, _) = self.picture_at(k);
+ self.kept("picture", &k.to_string(), |_| measure::pictures(&file).ok().and_then(|p| p.first().map(|p| json!([p.luma, Value::Null]))).unwrap_or(Value::Null))
+ };
+ let r3 = |x: f64| (x * 1000.0).round() / 1000.0;
+ Some(Picture { luma: r3(v[0].as_f64()?), motion: v[1].as_f64().map(r3), frames: None })
+ }
+
+ /// A cue's onset in the mix, for one starting at `at` seconds.
+ fn onset(&mut self, at: f64) -> Onset {
+ let v = self.kept("onsets", &format!("{at:.3}"), |r| {
+ let env = r.env.get_or_insert_with(|| measure::envelope(&r.out).unwrap_or_default());
+ json!(measure::onset(env, at))
+ });
+ let heard = v.as_f64();
+ Onset { at: heard, late_ms: heard.map(|h| ((h - at) * 1000.0).round()) }
+ }
+
+ /// Writes "measured" back into the manifest, when it gained anything.
+ pub(crate) fn keep(self) {
+ if self.dirty {
+ let tmp = self.path.with_extension(format!("json.{}.tmp", std::process::id()));
+ if std::fs::write(&tmp, self.m.to_string()).is_ok() {
+ let _ = std::fs::rename(&tmp, &self.path);
+ }
+ }
+ }
+}
+
+/// A manifest entry's layer key, as a Source's: its stamp, list key and uses.
+fn key_of(t: &Value) -> Option<String> {
+ let uses = t["use"].as_array().map(|u| u.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("|"));
+ raea_sys_layers::key_of(t["loc"].as_str(), t["index"].as_str(), uses.as_deref())
+}
+
+/// What the render adds to `facts` (its frame's world), or what waits for one. `tree` is the frame's page in
+/// document order (whose layers are drawn over whose).
+pub(crate) fn join(facts: &mut Facts, found: Option<&mut Found>, tree: &[El]) {
+ let Some(r) = found else {
+ return facts.set(&Waits(FROM_A_RENDER.iter().map(|c| (c.to_string(), "a render".to_string())).collect()));
+ };
+ facts.set(&Rendered { out: r.out.display().to_string(), manifest: r.path.display().to_string(), record: r.record.clone(), stale: r.stale });
+ let mut waits = BTreeMap::new();
+ if r.video() {
+ let mix = r.kept("mix", "all", |r| json!(measure::loudness(&r.out)));
+ facts.set(&Mix { lufs: mix[0].as_f64(), peak: mix[1].as_f64() });
+ for e in facts.find(&["Cue"]).iter().map(|e| e.id).collect::<Vec<_>>() {
+ if let Some(c) = facts.get::<Cue>(e) {
+ facts.put(e, &r.onset(c.at));
+ }
+ }
+ } else {
+ for c in ["Mix", "Onset"] {
+ waits.insert(c.to_string(), "a video render".to_string());
+ }
+ }
+ let Some(k) = r.at.get(&facts.frame).copied() else {
+ for c in ["Contrast", "Picture", "Covers"] {
+ waits.insert(c.to_string(), format!("a render of frame {}", facts.frame));
+ }
+ return facts.set(&Waits(waits));
+ };
+ if let Some(p) = r.picture(k) {
+ facts.set(&p);
+ }
+ shots(facts, r);
+ let laid = r.m["frames"][k].clone();
+ let mut boxed = Vec::new();
+ for e in facts.find(&["Text"]).iter().map(|e| e.id).collect::<Vec<_>>() {
+ let (Some(t), key) = (facts.get::<Text>(e), facts.get::<Source>(e).and_then(|s| s.key)) else { continue };
+ // its own entry by its layer key, else the one with its words
+ let texts = || laid["text"].as_array().into_iter().flatten();
+ let entry = texts().find(|x| key.is_some() && key_of(x) == key).or_else(|| texts().find(|x| x["text"].as_str() == Some(t.words.as_str())));
+ let (Some(x), Some(bx)) = (entry, t.box_) else { continue };
+ let b: Vec<f64> = x["box"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect();
+ let (file, sec) = r.picture_at(k);
+ let id = format!("{}|{}", facts.frame, key.clone().unwrap_or_else(|| t.words.clone()));
+ let crop = (b.len() == 4).then(|| [b[0], b[1], b[2], b[3]].map(|v| v.max(0.0) as u32));
+ let ratio = r.kept("contrast", &id, |_| json!(crop.and_then(|c| measure::contrast(&file, sec, c, x["color"].as_str().unwrap_or("")))));
+ if let Some(ratio) = ratio.as_f64() {
+ facts.put(e, &Contrast { ratio: (ratio * 10.0).round() / 10.0 });
+ }
+ if let Some(k) = key {
+ boxed.push((e, k, bx));
+ }
+ }
+ covers(facts, r, &laid, tree, boxed, &mut waits);
+ if !waits.is_empty() {
+ facts.set(&Waits(waits));
+ }
+}
+
+/// Each shot's light and movement: the mean over its frames the render drew. Its first frame's change is the cut
+/// into it, not movement in it, so its motion is left out.
+fn shots(facts: &mut Facts, r: &mut Found) {
+ for e in facts.find(&["Shot"]).iter().map(|e| e.id).collect::<Vec<_>>() {
+ let Some(s) = facts.get::<Shot>(e) else { continue };
+ let mut ks: Vec<(i64, usize)> = r.at.iter().filter(|(f, _)| **f >= s.from && s.to.is_none_or(|t| **f < t)).map(|(f, k)| (*f, *k)).collect();
+ ks.sort();
+ let ps: Vec<(i64, Picture)> = ks.into_iter().filter_map(|(f, k)| Some((f, r.picture(k)?))).collect();
+ let (mut luma, mut motions) = (Vec::new(), Vec::new());
+ for (f, p) in &ps {
+ luma.push(p.luma);
+ if let (Some(m), true) = (p.motion, *f != s.from) {
+ motions.push(m);
+ }
+ }
+ if let Some(luma) = mean(&luma) {
+ facts.put(e, &Picture { luma, motion: mean(&motions), frames: Some(ps.len() as u32) });
+ }
+ }
+}
+
+/// The mean of `v` to three places; None for none.
+fn mean(v: &[f64]) -> Option<f64> {
+ let n = v.len() as f64;
+ (n > 0.0).then(|| (v.iter().sum::<f64>() / n * 1000.0).round() / 1000.0)
+}
+
+/// Covers from the render's layers (a render with --layers): each boxed layer, and footage by its box this frame.
+fn covers(facts: &mut Facts, r: &mut Found, laid: &Value, tree: &[El], mut boxed: Vec<(u32, String, [f64; 4])>, waits: &mut BTreeMap<String, String>) {
+ if r.masks.is_none() {
+ let named = r.m["layers"].as_str().map(str::to_string);
+ r.masks = Some(named.and_then(|n| crate::covers::read(&r.path.with_file_name(n)).ok()));
+ }
+ let Some(masks) = r.masks.as_ref().and_then(Option::as_ref) else {
+ waits.insert("Covers".into(), "a render with --layers".into());
+ return;
+ };
+ let (w, h) = (facts.width as f64, facts.height as f64);
+ for v in laid["videos"].as_array().into_iter().flatten() {
+ let b: Vec<f64> = v["box"].as_array().into_iter().flatten().filter_map(Value::as_f64).collect();
+ let found = key_of(v).and_then(|k| Some((crate::covers::keyed(facts, &k)?, k)));
+ if let (Some((e, k)), 4) = (found, b.len()) {
+ boxed.push((e, k, [b[0] / w, b[1] / h, (b[0] + b[2]) / w, (b[1] + b[3]) / h]));
+ }
+ }
+ let order: HashMap<String, usize> = tree.iter().enumerate().filter_map(|(i, el)| Some((raea_sys_layers::key_from_props(&el.props)?, i))).collect();
+ crate::covers::put(facts, masks, &boxed, &order);
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/runtime/world/src/renders/tests.rs b/runtime/world/src/renders/tests.rs
new file mode 100644
index 00000000..b9663356
--- /dev/null
+++ b/runtime/world/src/renders/tests.rs
@@ -0,0 +1,108 @@
+use super::*;
+use raea_core_facts::{Layer, Medium};
+
+/// A raea project in a fresh folder with a composition in it.
+fn project(name: &str) -> (PathBuf, PathBuf) {
+ let dir = std::env::temp_dir().join(format!("raea-dr2-{name}-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(dir.join(".raea")).unwrap();
+ std::fs::write(dir.join(".raea/project"), "").unwrap();
+ let tsx = dir.join("piece.tsx");
+ std::fs::write(&tsx, "export default 1").unwrap();
+ let dir = dir.canonicalize().unwrap();
+ (dir.clone(), dir.join("piece.tsx"))
+}
+
+/// A render of `tsx` to `out` kept in the record, its manifest saying `size` and `frames`, with `measured` in it.
+fn rendered(tsx: &Path, out: &Path, size: (u32, u32, f64), frames: &[i64], measured: Value, stamp: &str) {
+ std::fs::write(out, b"made").unwrap();
+ let fs: Vec<Value> = frames.iter().map(|f| json!({"frame": f, "text": [{"text": "SALE", "box": [10, 10, 100, 40], "color": "rgb(255, 255, 255)", "loc": "piece.tsx:3:5"}], "videos": []})).collect();
+ let m = json!({"width": size.0, "height": size.1, "fps": size.2, "frames": fs, "measured": measured});
+ std::fs::write(crate::manifest_for(out, tsx), m.to_string()).unwrap();
+ record::keep("raea render", tsx, Some(out), &[], vec![], stamp).unwrap();
+}
+
+#[test]
+fn the_newest_render_of_this_composition_joins_and_says_when_the_composition_changed_after_it() {
+ let (dir, tsx) = project("find");
+ assert!(find(&Render::Newest, &tsx, (1920, 1080, 30.0)).is_none(), "no render yet");
+ rendered(&tsx, &dir.join("a.mp4"), (1920, 1080, 30.0), &[0], json!({}), "20261110-100000");
+ rendered(&tsx, &dir.join("b.mp4"), (1920, 1080, 30.0), &[0], json!({}), "20261110-100001");
+ // the file's other composition, rendered last: another size, so not this one's
+ rendered(&tsx, &dir.join("tall.mp4"), (1080, 1920, 30.0), &[0], json!({}), "20261110-100002");
+ let r = find(&Render::Newest, &tsx, (1920, 1080, 30.0)).unwrap();
+ assert_eq!((r.out.file_name().unwrap().to_str(), r.stale), (Some("b.mp4"), false));
+ assert_eq!(find(&Render::Newest, &tsx, (1080, 1920, 30.0)).unwrap().out, dir.join("tall.mp4"));
+ // an output since deleted is no render to measure
+ std::fs::remove_file(dir.join("b.mp4")).unwrap();
+ assert_eq!(find(&Render::Newest, &tsx, (1920, 1080, 30.0)).unwrap().out, dir.join("a.mp4"));
+ assert_eq!(find(&Render::From(dir.join("tall.mp4")), &tsx, (1080, 1920, 30.0)).unwrap().record, None, "one named, not from the record");
+ assert!(find(&Render::Off, &tsx, (1920, 1080, 30.0)).is_none());
+ // the composition changed after its render: its measures are of the version before
+ let later = std::time::SystemTime::now() + std::time::Duration::from_secs(120);
+ std::fs::File::options().append(true).open(&tsx).unwrap().set_modified(later).unwrap();
+ assert!(find(&Render::Newest, &tsx, (1920, 1080, 30.0)).unwrap().stale);
+}
+
+/// A world of frame `f` as the page reads it: the caption, a cue at 0.5 s, a shot over frames 0-9.
+fn world(f: i64) -> Facts {
+ let mut w = Facts::new(f, 1920, 1080, 30.0);
+ let t = w.spawn(None);
+ w.put(t, &Layer { medium: Medium::Type2d, order: 1, opacity: 1.0, blend: None });
+ w.put(t, &Text { words: "SALE".into(), font: None, size: Some(36.0), box_: Some([0.005, 0.009, 0.057, 0.046]), extruded: 0.0, lines: Some(1), needs: None });
+ w.put(t, &Source { file: Some("piece.tsx".into()), line: Some(3), component: None, key: Some("piece.tsx:3:5".into()) });
+ let c = w.spawn(None);
+ w.put(c, &Cue { source: "hit.wav".into(), at: 0.5, gain: None, bus: None });
+ let s = w.spawn(None);
+ w.put(s, &Shot { name: Some("open".into()), from: 0, to: Some(10) });
+ w
+}
+
+#[test]
+fn a_render_adds_what_it_measured_and_what_it_did_not_draw_waits() {
+ let (dir, tsx) = project("join");
+ let measured = json!({"picture": {"all": [[0.5, null], [0.25, 0.125]]}, "mix": {"all": [-14.2, -1.3]}, "onsets": {"0.500": 0.51}, "contrast": {"1|piece.tsx:3:5": 4.54}});
+ rendered(&tsx, &dir.join("v.mp4"), (1920, 1080, 30.0), &[0, 1], measured, "20261110-110000");
+ let mut r = find(&Render::Newest, &tsx, (1920, 1080, 30.0)).unwrap();
+ let mut w = world(1);
+ join(&mut w, Some(&mut r), &[]);
+ let get = |w: &Facts, c: &str| w.find(&[c]).first().map(|e| e.components[c].clone());
+ assert_eq!(get(&w, "Contrast"), Some(json!({"ratio": 4.5})));
+ assert_eq!(w.resources["Picture"], json!({"luma": 0.25, "motion": 0.125, "frames": null}));
+ assert_eq!(get(&w, "Picture"), Some(json!({"luma": 0.375, "motion": 0.125, "frames": 2})), "the shot's mean over the frames drawn");
+ assert_eq!(w.resources["Mix"], json!({"lufs": -14.2, "peak": -1.3}));
+ assert_eq!(get(&w, "Onset"), Some(json!({"at": 0.51, "late_ms": 10.0})));
+ assert_eq!(w.resources["Rendered"]["stale"], false);
+ assert_eq!(w.resources["Waits"], json!({"Covers": "a render with --layers"}), "no --layers, no covers");
+ // a shot that starts on frame 1: frame 1's change is the cut into it, not movement
+ let mut cut = world(1);
+ let s = cut.find(&["Shot"])[0].id;
+ cut.put(s, &Shot { name: Some("close".into()), from: 1, to: Some(10) });
+ join(&mut cut, Some(&mut r), &[]);
+ assert_eq!(get(&cut, "Picture"), Some(json!({"luma": 0.25, "motion": null, "frames": 1})));
+ // a frame the render didn't draw takes nothing of another frame's
+ let mut far = world(20);
+ join(&mut far, Some(&mut r), &[]);
+ assert!(far.find(&["Contrast"]).is_empty() && !far.resources.contains_key("Picture"));
+ assert_eq!(far.resources["Waits"]["Contrast"], "a render of frame 20");
+ // what was read is kept; nothing new to write back
+ assert!(!r.dirty);
+ // no render: all five wait for one
+ let mut none = world(1);
+ join(&mut none, None, &[]);
+ assert_eq!(none.resources["Waits"].as_object().map(|o| o.len()), Some(5));
+ assert!(none.find(&["Onset"]).is_empty(), "a cue isn't heard because it was placed");
+}
+
+#[test]
+fn a_still_has_no_mix_to_measure() {
+ let (dir, tsx) = project("still");
+ let measured = json!({"picture": {"0": [0.5, null]}, "contrast": {"0|piece.tsx:3:5": 1.2}});
+ rendered(&tsx, &dir.join("s.png"), (1920, 1080, 30.0), &[0], measured, "20261110-120000");
+ let mut r = find(&Render::Newest, &tsx, (1920, 1080, 30.0)).unwrap();
+ let mut w = world(0);
+ join(&mut w, Some(&mut r), &[]);
+ assert_eq!(w.resources["Waits"]["Mix"], "a video render");
+ assert_eq!(w.resources["Waits"]["Onset"], "a video render");
+ assert_eq!(w.find(&["Contrast"])[0].components["Contrast"]["ratio"], 1.2, "a low contrast is said as measured");
+}
diff --git a/systems/layers/src/lib.rs b/systems/layers/src/lib.rs
index 0e584fef..f5275988 100644
--- a/systems/layers/src/lib.rs
+++ b/systems/layers/src/lib.rs
@@ -86,7 +86,13 @@ pub fn start(on: bool, out: &std::path::Path, tsx: &std::path::Path) -> Option<P
let video = out.file_name().unwrap_or_default().to_string_lossy().into_owned();
let src = tsx.parent().map(PathBuf::from).unwrap_or_default();
ON.with(|r| *r.borrow_mut() = path.clone().map(|p| Recorder::new(p, video).named_from(src)));
- path.map(|p| p.with_extension("render.json"))
+ path.map(|_| manifest_for(out, tsx))
+}
+
+/// The render.json beside an export `out` (OUT.render.json, or DIR/NAME.render.json for a folder of frames), which
+/// every render writes unless `--manifest` puts it elsewhere (docs/direction.feature DR2).
+pub fn manifest_for(out: &std::path::Path, tsx: &std::path::Path) -> PathBuf {
+ path_for(out, tsx).with_extension("render.json")
}
/// Whether this render records its layers.
diff --git a/systems/measure/Cargo.toml b/systems/measure/Cargo.toml
new file mode 100644
index 00000000..d9ea3b0b
--- /dev/null
+++ b/systems/measure/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+name = "raea-sys-measure"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "What a render's output measures, read with ffmpeg: each frame's light and movement, a text's contrast against its pixels, the mix's loudness and when a sound starts in it"
+
+[dependencies]
diff --git a/systems/measure/src/lib.rs b/systems/measure/src/lib.rs
new file mode 100644
index 00000000..8ba86ed4
--- /dev/null
+++ b/systems/measure/src/lib.rs
@@ -0,0 +1,136 @@
+//! What a render's output measures (docs/direction.feature DR2), read with ffmpeg as `raea check` reads an export:
+//! each frame's light and how much it changed from the frame before, a text's contrast against the pixels behind it,
+//! the mix's integrated loudness and true peak, and when a sound starts in the mix. Each is a number a check compares
+//! with its own limit; nothing here decides.
+
+use std::path::Path;
+use std::process::{Command, Output};
+
+/// Frames are read at this size: enough to see light and movement, small enough that a two-minute video reads in
+/// seconds. Mean light and mean change don't depend on the frame's shape.
+const SIDE: usize = 64;
+/// The sound envelope's step, in seconds.
+pub const HOP: f64 = 0.01;
+/// How far after a sound's start its onset is looked for, and how far before (a render rounds a start to a frame).
+const AFTER: f64 = 0.2;
+const BEFORE: f64 = 0.05;
+/// A rise this many dB over three steps (30 ms) is an onset.
+const RISE: f32 = 6.0;
+/// ... once it is within this many dB of the loudest step in the next tenth of a second: a rise out of digital
+/// silence to a level no one hears (an encoder's pre-echo, 20 ms before the sound and 80 dB under it) isn't one.
+const NEAR: f32 = 10.0;
+
+/// One frame's light and movement: its mean luma (0 black, 1 white) and the mean change of each pixel's luma from the
+/// frame before (0 to 1; None for the first).
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub struct Picture {
+ pub luma: f64,
+ pub motion: Option<f64>,
+}
+
+fn ffmpeg(args: &[&str]) -> Result<Output, String> {
+ let out = Command::new("ffmpeg").args(["-v", "error", "-nostdin"]).args(args).output().map_err(|e| format!("ffmpeg: {e}"))?;
+ if out.status.success() { Ok(out) } else { Err(format!("ffmpeg: {}", String::from_utf8_lossy(&out.stderr).trim())) }
+}
+
+fn name(file: &Path) -> Result<&str, String> {
+ file.to_str().ok_or_else(|| format!("{}: its name isn't text", file.display()))
+}
+
+/// Each frame of a video, or the one of an image, as its light and movement, in order.
+pub fn pictures(file: &Path) -> Result<Vec<Picture>, String> {
+ let scale = format!("scale={SIDE}:{SIDE}:flags=area:out_range=full,format=gray");
+ let out = ffmpeg(&["-i", name(file)?, "-an", "-vf", &scale, "-f", "rawvideo", "-"])?;
+ Ok(of_gray(&out.stdout))
+}
+
+/// Frames of SIDE x SIDE grey bytes as pictures.
+pub fn of_gray(bytes: &[u8]) -> Vec<Picture> {
+ let n = (SIDE * SIDE) as f64;
+ let frames: Vec<&[u8]> = bytes.chunks_exact(SIDE * SIDE).collect();
+ let mut out = Vec::with_capacity(frames.len());
+ for (i, f) in frames.iter().enumerate() {
+ let luma = f.iter().map(|&v| v as f64).sum::<f64>() / n / 255.0;
+ let motion = i.checked_sub(1).map(|b| f.iter().zip(frames[b]).map(|(a, b)| (*a as f64 - *b as f64).abs()).sum::<f64>() / n / 255.0);
+ out.push(Picture { luma, motion });
+ }
+ out
+}
+
+/// A CSS colour's red, green and blue, 0-255 (`rgb(..)`, `rgba(..)`; white where it says none).
+pub fn rgb_of(css: &str) -> [f64; 3] {
+ let n: Vec<f64> = css.split(|c: char| !(c.is_ascii_digit() || c == '.')).filter(|s| !s.is_empty()).filter_map(|s| s.parse().ok()).collect();
+ [n.first().copied().unwrap_or(255.0), n.get(1).copied().unwrap_or(255.0), n.get(2).copied().unwrap_or(255.0)]
+}
+
+/// The relative luminance (WCAG) of an sRGB colour 0-255.
+pub fn lum([r, g, b]: [f64; 3]) -> f64 {
+ let c = |v: f64| {
+ let v = v / 255.0;
+ if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
+ };
+ 0.2126 * c(r) + 0.7152 * c(g) + 0.0722 * c(b)
+}
+
+/// WCAG's contrast ratio (1 to 21) of a text of luminance `text` against RGB pixels: the median of the half least
+/// like the text is what is behind it (the other half is mostly the letters themselves).
+pub fn ratio_behind(rgb: &[u8], text: f64) -> Option<f64> {
+ let mut ls: Vec<f64> = rgb.chunks_exact(3).map(|p| lum([p[0] as f64, p[1] as f64, p[2] as f64])).collect();
+ if ls.len() < 2 {
+ return None;
+ }
+ ls.sort_by(|a, b| (b - text).abs().total_cmp(&(a - text).abs()));
+ let mut behind = ls[..ls.len() / 2].to_vec();
+ behind.sort_by(f64::total_cmp);
+ let bg = behind[behind.len() / 2];
+ Some((text.max(bg) + 0.05) / (text.min(bg) + 0.05))
+}
+
+/// The contrast of the text of colour `color` drawn in `crop` (x, y, w, h in the file's pixels) at `at` seconds of a
+/// video (an image has one frame), against what is behind it: `raea check`'s caption contrast. None when the crop
+/// falls outside the frame or ffmpeg can't read it.
+pub fn contrast(file: &Path, at: f64, crop: [u32; 4], color: &str) -> Option<f64> {
+ // even sizes and offsets: a 4:2:0 frame crops to them
+ let [x, y, w, h] = [crop[0] & !1, crop[1] & !1, crop[2].max(2) & !1, crop[3].max(2) & !1];
+ let vf = format!("crop={w}:{h}:{x}:{y}");
+ let out = ffmpeg(&["-ss", &format!("{at:.3}"), "-i", name(file).ok()?, "-frames:v", "1", "-vf", &vf, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]).ok()?;
+ (out.stdout.len() >= (w * h * 3) as usize).then(|| ratio_behind(&out.stdout, lum(rgb_of(color)))).flatten()
+}
+
+/// The mix's integrated loudness in LUFS and its true peak in dBTP (EBU R128, ffmpeg's ebur128). None when the file
+/// has no sound.
+pub fn loudness(file: &Path) -> Option<(f64, Option<f64>)> {
+ let out = Command::new("ffmpeg").args(["-hide_banner", "-nostats", "-i", name(file).ok()?, "-vn", "-af", "ebur128=peak=true", "-f", "null", "-"]).output().ok()?;
+ of_ebur128(&String::from_utf8_lossy(&out.stderr))
+}
+
+/// ebur128's summary read: its integrated loudness and true peak.
+pub fn of_ebur128(log: &str) -> Option<(f64, Option<f64>)> {
+ let summary = log.rsplit_once("Summary:")?.1;
+ let num = |key: &str| summary.lines().find(|l| l.trim_start().starts_with(key)).and_then(|l| l.split_whitespace().nth(1)).and_then(|x| x.parse::<f64>().ok());
+ Some((num("I:")?, num("Peak:")))
+}
+
+/// The mix's level in dB every HOP seconds (its RMS, mono, -120 at silence). Empty when the file has no sound.
+pub fn envelope(file: &Path) -> Result<Vec<f32>, String> {
+ let out = ffmpeg(&["-i", name(file)?, "-vn", "-ac", "1", "-ar", "16000", "-f", "f32le", "-"])?;
+ let samples: Vec<f32> = out.stdout.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect();
+ Ok(levels(&samples, (16000.0 * HOP) as usize))
+}
+
+/// Samples as dB a step of `hop` samples.
+pub fn levels(samples: &[f32], hop: usize) -> Vec<f32> {
+ samples.chunks(hop.max(1)).map(|c| 10.0 * ((c.iter().map(|s| s * s).sum::<f32>() / c.len() as f32).max(1e-12)).log10()).collect()
+}
+
+/// When the sound placed at `at` seconds is heard: the start of the first step, from BEFORE before it to AFTER after
+/// it, where the mix has risen RISE dB over the three steps before and come within NEAR dB of where it goes (within a
+/// step, 10 ms). None when nothing starts there: a sound under a louder bed, or one that never plays.
+pub fn onset(env: &[f32], at: f64) -> Option<f64> {
+ let (a, b) = (((at - BEFORE) / HOP).floor().max(3.0) as usize, (((at + AFTER) / HOP).ceil().max(0.0) as usize).min(env.len()));
+ let loudest = |i: usize| env[i..(i + 10).min(env.len())].iter().copied().fold(f32::MIN, f32::max);
+ (a..b).find(|&i| env[i] - env[i - 3] >= RISE && env[i] >= loudest(i) - NEAR).map(|i| i as f64 * HOP)
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/systems/measure/src/tests.rs b/systems/measure/src/tests.rs
new file mode 100644
index 00000000..6f6d4633
--- /dev/null
+++ b/systems/measure/src/tests.rs
@@ -0,0 +1,57 @@
+use super::*;
+
+#[test]
+fn a_frame_reads_as_its_light_and_how_much_it_changed() {
+ let n = SIDE * SIDE;
+ let mut bytes = vec![0u8; n];
+ bytes.extend(vec![255u8; n]);
+ bytes.extend(vec![255u8; n]);
+ let p = of_gray(&bytes);
+ assert_eq!(p.len(), 3);
+ assert_eq!(p[0], Picture { luma: 0.0, motion: None });
+ assert_eq!((p[1].luma, p[1].motion), (1.0, Some(1.0)), "black to white is all change");
+ assert_eq!(p[2].motion, Some(0.0), "a held frame doesn't move");
+ assert!(of_gray(&bytes[..n - 1]).is_empty(), "a part frame isn't one");
+}
+
+#[test]
+fn contrast_is_the_text_against_the_half_least_like_it() {
+ // white letters over black: half the pixels each
+ let px: Vec<u8> = (0..100).flat_map(|i| if i % 2 == 0 { [255u8; 3] } else { [0u8; 3] }).collect();
+ let r = ratio_behind(&px, lum(rgb_of("rgb(255, 255, 255)"))).unwrap();
+ assert!((r - 21.0).abs() < 0.01, "{r}");
+ // the same white over white is no contrast, whatever the letters
+ let flat = vec![255u8; 300];
+ assert!((ratio_behind(&flat, lum([255.0; 3])).unwrap() - 1.0).abs() < 1e-9);
+ assert_eq!(rgb_of("rgba(10, 20, 30, 0.5)"), [10.0, 20.0, 30.0]);
+ assert!(ratio_behind(&[], 1.0).is_none());
+}
+
+#[test]
+fn ebur128s_summary_reads_as_loudness_and_peak() {
+ let log = "[Parsed_ebur128_0] t: 1 M: -20\n[Parsed_ebur128_0] Summary:\n\n Integrated loudness:\n I: -14.2 LUFS\n Threshold: -24.4 LUFS\n\n True peak:\n Peak: -1.3 dBFS\n";
+ assert_eq!(of_ebur128(log), Some((-14.2, Some(-1.3))));
+ assert_eq!(of_ebur128("Output #0, null: no audio"), None, "no sound, no loudness");
+}
+
+#[test]
+fn a_sound_is_heard_where_the_mix_rises_and_not_under_a_louder_bed() {
+ // 2 s at 16 kHz: silence, a tone from 0.50 s
+ let rate = 16000;
+ let tone: Vec<f32> = (0..2 * rate).map(|i| if i >= rate / 2 { 0.5 * (i as f32 * 0.1).sin() } else { 0.0 }).collect();
+ let env = levels(&tone, rate / 100);
+ let at = onset(&env, 0.5).unwrap();
+ assert!((at - 0.5).abs() <= HOP + 1e-9, "heard at {at}");
+ assert_eq!(onset(&env, 1.5), None, "nothing starts at 1.5 s: the tone is already playing");
+ // the same tone under a bed 20 dB louder doesn't rise 6 dB
+ let bed: Vec<f32> = tone.iter().enumerate().map(|(i, s)| s * 0.1 + 0.5 * (i as f32 * 0.37).sin()).collect();
+ assert_eq!(onset(&levels(&bed, rate / 100), 0.5), None);
+ assert_eq!(onset(&env, 30.0), None, "past the end");
+ assert_eq!(onset(&env, 0.0), None, "the start of silence");
+ // a real render's beep at 1.00 s (bench: an AAC mix read back): the encoder's pre-echo leaks 20 ms early, far
+ // under the beep; it is heard where the beep is
+ let mut aac = vec![-120.0f32; 98];
+ aac.extend([-111.0, -102.9, -26.9, -24.1, -24.1, -23.9, -24.2]);
+ aac.extend(vec![-24.0; 30]);
+ assert_eq!(onset(&aac, 1.0), Some(1.0));
+}
diff --git a/tools/layers.toml b/tools/layers.toml
index 7e2c02ed..7fad4601 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -78,6 +78,7 @@ raea-sys-a11y = "systems"
raea-sys-bake = "systems"
raea-sys-contact = "systems"
raea-sys-light-meter = "systems"
+raea-sys-measure = "systems"
raea-sys-canvas = "systems"
raea-sys-tweak = "systems"
raea-sys-filters = "systems"