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.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
layers LA2b, LA3a, LA4a: `raea export layers` writes the layers and layers.json; the 3D is the layer under the page
Zachary Guglin6b410a9827c1
diff --git a/Cargo.lock b/Cargo.lockindex a5ef7b24..a561a383 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -13747,7 +13747,7 @@ version = "0.1.0"dependencies = ["dunce","image",- "raea-core-scene",+ "raea-app-layers","raea-io-alpha","raea-io-capcut","raea-io-home",@@ -13890,6 +13890,19 @@ dependencies = ["ureq 2.12.1",]+[[package]]+name = "raea-app-layers"+version = "0.1.0"+dependencies = [+ "dunce",+ "raea-core-scene",+ "raea-io-alpha",+ "raea-io-media",+ "raea-runtime-bundle",+ "serde",+ "serde_json",+]+[[package]]name = "raea-app-media"version = "0.1.0"@@ -14231,6 +14244,7 @@ dependencies = ["raea-app-fingerprint","raea-app-game","raea-app-judge",+ "raea-app-layers","raea-app-media","raea-app-notes","raea-app-play",diff --git a/Cargo.toml b/Cargo.tomlindex d6e82584..47734003 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -193,6 +193,7 @@ members = ["apps/targets","apps/game","apps/capcut",+ "apps/layers","apps/play","tools/sdk-props","tools/hands-audit",diff --git a/apps/capcut/Cargo.toml b/apps/capcut/Cargo.tomlindex f445cc1a..438bdba7 100644--- a/apps/capcut/Cargo.toml+++ b/apps/capcut/Cargo.toml@@ -13,7 +13,7 @@ raea-io-capcut = { path = "../../io/capcut" }raea-io-alpha = { path = "../../io/alpha" }raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }raea-io-home = { path = "../../io/home" }-# the renderer's own lookup of a staticFile path (/media/x), so the export finds the files the render drew-raea-core-scene = { path = "../../core/scene" }+# the manifest read as what an export places, shared with every editor's export (docs/layers.feature LA4)+raea-app-layers = { path = "../layers" }serde_json = "1"image = { version = "0.25", default-features = false, features = ["jpeg"] }diff --git a/apps/capcut/src/lib.rs b/apps/capcut/src/lib.rsindex 6874b6b3..7c5fb436 100644--- a/apps/capcut/src/lib.rs+++ b/apps/capcut/src/lib.rs@@ -28,7 +28,7 @@ pub fn cli(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<Rmatch args.first().map(String::as_str) {Some("export") => Some(match args.get(1).map(String::as_str) {Some("capcut") => export(&args[2..]),- other => Err(format!("raea export takes where to export to{}: capcut\nusage: {USAGE}", other.map_or(String::new(), |o| format!(", not {o:?}")))),+ other => Err(format!("raea export takes where to export to{}: capcut or layers\nusage: {USAGE}\n {}", other.map_or(String::new(), |o| format!(", not {o:?}")), raea_app_layers::USAGE)),}),Some("render") => movie(args, render),_ => None,diff --git a/apps/capcut/src/plan.rs b/apps/capcut/src/plan.rsindex 829e7e1d..5a5f320f 100644--- a/apps/capcut/src/plan.rs+++ b/apps/capcut/src/plan.rs@@ -1,133 +1,12 @@//! The render's manifest as a CapCut timeline (docs/capcut.feature CC2): each run of frames showing one file as a//! clip of it, each sound clip as an audio clip (or as its footage's own sound), each run of frames the overlay draws//! as a clip of the overlay movie, and the tracks they go on. Pure: the export (lib.rs) renders and probes around it.--use std::path::{Path, PathBuf};+//! What reads the manifest is raea-app-layers' (every editor's export reads it the same way); where a clip sits and+//! the tracks it goes on are CapCut's.use raea_io_capcut::{Clip, Kind, Place, Track};-use serde_json::Value;--/// One file shown over a run of frames, as the manifest's frames say: its first source time and rate, its box and-/// fit at its first frame, its place in the page's order (lower draws first), and whether it moved or faded.-#[derive(Clone, Debug, PartialEq)]-pub struct Run {- pub src: String,- pub key: String,- pub start: i64,- pub end: i64,- pub at: f64,- pub last_at: f64,- pub rate: Option<f64>,- pub bx: [f64; 4],- pub fit: String,- pub opacity: f64,- pub z: usize,- pub moved: bool,- pub faded: bool,-}--/// One sound clip of the manifest: its file, frames, source time, gain, rate and fades.-#[derive(Clone, Debug, PartialEq)]-pub struct Sound {- pub src: String,- pub from: i64,- pub to: i64,- pub at: f64,- pub gain_db: f64,- pub rate: f64,- pub fade_in: f64,- pub fade_out: f64,-}--/// The footage's runs, frame by frame: a run goes on while the same element shows the same file with its source time-/// advancing at one rate; a jump in source time (a cut within one take) starts another.-pub fn runs(manifest: &Value, fps: f64) -> Vec<Run> {- let mut done: Vec<Run> = Vec::new();- let mut open: Vec<Run> = Vec::new();- let frames = manifest["frames"].as_array().cloned().unwrap_or_default();- for (i, fr) in frames.iter().enumerate() {- let f = fr["frame"].as_i64().unwrap_or(i as i64);- let mut next = Vec::new();- for (z, v) in fr["videos"].as_array().into_iter().flatten().enumerate() {- let src = v["src"].as_str().unwrap_or_default().to_string();- let key = format!("{src}|{}|{}|{}", v["loc"], v["use"], v["index"]);- let at = v["at"].as_f64().unwrap_or(0.0);- let bx: [f64; 4] = std::array::from_fn(|k| v["box"][k].as_f64().unwrap_or(0.0));- let opacity = v["opacity"].as_f64().unwrap_or(1.0);- let continues = |r: &Run| {- let step = at - r.last_at;- r.key == key && r.end == f && step > 0.0 && match r.rate {- Some(rate) => (step - rate / fps).abs() <= 0.6 / fps,- None => step * fps <= 8.0,- }- };- if let Some(k) = open.iter().position(continues) {- let mut r = open.remove(k);- r.rate.get_or_insert((at - r.last_at) * fps);- r.moved |= r.bx.iter().zip(&bx).any(|(a, b)| (a - b).abs() > 1.0);- r.faded |= (r.opacity - opacity).abs() > 0.02;- (r.end, r.last_at) = (f + 1, at);- next.push(r);- } else {- next.push(Run { src, key, start: f, end: f + 1, at, last_at: at, rate: None, bx, fit: v["fit"].as_str().unwrap_or("fill").to_string(), opacity, z, moved: false, faded: false });- }- }- done.append(&mut open);- open = next;- }- done.append(&mut open);- // the rate over the whole run (source times are whole milliseconds, so one step's can be 1% off), to hundredths- for r in &mut done {- if r.end - r.start > 1 {- r.rate = Some(((r.last_at - r.at) * fps / (r.end - r.start - 1) as f64 * 100.0).round() / 100.0);- }- }- done.sort_by_key(|r| (r.start, r.z));- done-}-/// The manifest's sound clips.-pub fn sounds(manifest: &Value) -> Vec<Sound> {- let s = &manifest["sounds"]["clips"];- s.as_array()- .into_iter()- .flatten()- .map(|c| Sound {- src: c["src"].as_str().unwrap_or_default().to_string(),- from: c["from"].as_i64().unwrap_or(0),- to: c["to"].as_i64().unwrap_or(0),- at: c["at"].as_f64().unwrap_or(0.0),- gain_db: c["gainDb"].as_f64().unwrap_or(0.0),- rate: c["rate"].as_f64().unwrap_or(1.0),- fade_in: c["fadeIn"].as_f64().unwrap_or(0.0),- fade_out: c["fadeOut"].as_f64().unwrap_or(0.0),- })- .filter(|c| c.to > c.from)- .collect()-}--/// Runs of frames that draw something.-pub fn spans(drawn: &[bool]) -> Vec<(i64, i64)> {- let mut out = Vec::new();- let mut f = 0;- while f < drawn.len() {- if !drawn[f] {- f += 1;- continue;- }- let a = f;- while f < drawn.len() && drawn[f] {- f += 1;- }- out.push((a as i64, f as i64));- }- out-}--/// Whether a box covers the whole canvas.-pub fn full(bx: &[f64; 4], w: f64, h: f64) -> bool {- bx[0] <= 1.0 && bx[1] <= 1.0 && bx[0] + bx[2] >= w - 1.0 && bx[1] + bx[3] >= h - 1.0-}+pub use raea_app_layers::plan::{Run, Sound, full, resolve, runs, sounds, spans};/// Where a picture of `mw` x `mh` sits to show as it does in its box with its object-fit, in CapCut's terms (scale 1:/// fitted inside the canvas; a crop is fitted as the part it keeps). A warning when CapCut can't show it so.@@ -173,10 +52,3 @@ pub fn lay(kind: Kind, name: &str, clips: Vec<Clip>) -> Vec<Track> {}tracks}--/// A file the manifest names, as a path, found as the renderer finds it: a staticFile path (/media/x) in the edit's-/// media/, then the project's media/ and assets/; else absolute; else relative to the composition's folder.-pub fn resolve(dir: &Path, src: &str) -> PathBuf {- let p = raea_core_scene::media_path(dir, src);- dunce::canonicalize(&p).unwrap_or(p)-}diff --git a/apps/layers/Cargo.toml b/apps/layers/Cargo.tomlnew file mode 100644index 00000000..db423a70--- /dev/null+++ b/apps/layers/Cargo.toml@@ -0,0 +1,18 @@+[package]+name = "raea-app-layers"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "`raea export layers`: a composition as its layers (captions, graphics, footage, under, sound) and the timeline that places them, layers.json, which every editor's export is written from (docs/layers.feature LA4)"++[dependencies]+raea-runtime-bundle = { path = "../../runtime/bundle" }+raea-io-alpha = { path = "../../io/alpha" }+raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }+# the renderer's own lookup of a staticFile path (/media/x), so the export finds the files the render drew+raea-core-scene = { path = "../../core/scene" }+# canonicalize without Windows' \\?\ prefix, as the rest of raea does+dunce = "1"+serde = { version = "1", features = ["derive"] }+serde_json = "1"diff --git a/apps/layers/fixtures/highlight.tsx b/apps/layers/fixtures/highlight.tsxnew file mode 100644index 00000000..93b80d96--- /dev/null+++ b/apps/layers/fixtures/highlight.tsx@@ -0,0 +1,21 @@+// docs/layers.feature LA3a: captions whose words light up as they're said, over full-frame footage+import { AbsoluteFill, Composition, Video, registerRoot, staticFile, useCurrentFrame } from "raea";++const WORDS = ["Each", "word", "lights", "up"];++function Edit() {+ const f = useCurrentFrame();+ const lit = Math.min(WORDS.length - 1, Math.floor(f / 12));+ return (+ <AbsoluteFill style={{ background: "#000" }}>+ <Video src={staticFile("clip.mp4")} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />+ <div data-raea-role="caption" style={{ position: "absolute", left: 0, right: 0, bottom: 80, textAlign: "center", fontSize: 60, fontWeight: 800, color: "#fff" }}>+ {WORDS.map((w, i) => (+ <span key={w} style={{ color: i === lit ? "#ffd400" : "#fff" }}>{w} </span>+ ))}+ </div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="edit" width={1280} height={720} fps={30} durationInFrames={60} component={Edit} />);diff --git a/apps/layers/fixtures/lower-third.tsx b/apps/layers/fixtures/lower-third.tsxnew file mode 100644index 00000000..65cb5e24--- /dev/null+++ b/apps/layers/fixtures/lower-third.tsx@@ -0,0 +1,20 @@+// docs/layers.feature LA3a: full-frame footage with a lower third (a bar and words) and captions+import { AbsoluteFill, Composition, Sequence, Video, registerRoot, staticFile } from "raea";++function Edit() {+ return (+ <AbsoluteFill style={{ background: "#000" }}>+ <Video src={staticFile("clip.mp4")} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover" }} />+ <div style={{ position: "absolute", left: 0, bottom: 200, width: 620, height: 90, background: "#ff3b30" }}>+ <span style={{ position: "absolute", left: 32, top: 18, fontSize: 44, color: "#fff" }}>Jane Doe, raea</span>+ </div>+ <Sequence from={10} durationInFrames={40}>+ <div data-raea-role="caption" style={{ position: "absolute", left: 0, right: 0, bottom: 60, textAlign: "center", fontSize: 52, color: "#fff", textShadow: "0 2px 6px #000" }}>+ The words as they're said+ </div>+ </Sequence>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="edit" width={1280} height={720} fps={30} durationInFrames={60} component={Edit} />);diff --git a/apps/layers/fixtures/pip-card.tsx b/apps/layers/fixtures/pip-card.tsxnew file mode 100644index 00000000..cc528a32--- /dev/null+++ b/apps/layers/fixtures/pip-card.tsx@@ -0,0 +1,15 @@+// docs/layers.feature LA3a: footage as a picture in picture on a coloured card, over a background+import { AbsoluteFill, Composition, Video, registerRoot, staticFile } from "raea";++function Edit() {+ return (+ <AbsoluteFill style={{ background: "#14161c" }}>+ <div style={{ position: "absolute", left: 120, top: 120, width: 700, height: 420, background: "#2050ff", borderRadius: 24 }}>+ <Video src={staticFile("clip.mp4")} style={{ position: "absolute", left: 30, top: 30, width: 640, height: 360 }} />+ </div>+ <div style={{ position: "absolute", left: 880, top: 160, fontSize: 56, fontWeight: 800, color: "#fff" }}>On the card</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="edit" width={1280} height={720} fps={30} durationInFrames={60} component={Edit} />);diff --git a/apps/layers/fixtures/three-d.tsx b/apps/layers/fixtures/three-d.tsxnew file mode 100644index 00000000..8f165868--- /dev/null+++ b/apps/layers/fixtures/three-d.tsx@@ -0,0 +1,29 @@+// docs/layers.feature LA3a: 3D with a title over it and a caption (the 3D is in the graphics layer, never the captions')+import { AbsoluteFill, Composition, registerRoot, useCurrentFrame } from "raea";+import { Entity } from "raea/3d";+import { StandardMaterial } from "raea/pbr";+import { Cuboid, Mesh3d } from "raea/mesh";+import { AmbientLight, DirectionalLight } from "raea/light";+import { Quat, Transform } from "raea/transform";+import { Camera3d } from "raea/camera";++function Edit() {+ const turn = (useCurrentFrame() / 30) * (Math.PI / 3);+ return (+ <AbsoluteFill style={{ background: "#14161c" }}>+ <Camera3d transform={Transform.fromXyz(0, 1.6, 6).lookingAt([0, 0.5, 0])} projection={{ Perspective: { fov: (40 * Math.PI) / 180 } }} />+ <AmbientLight brightness={160} />+ <DirectionalLight transform={Transform.fromXyz(3, 5, 4).lookingAt([0, 0, 0])} illuminance={11200} />+ <Entity transform={Transform.IDENTITY.withRotation(Quat.fromEuler("XYZ", 0, turn, 0))}>+ <Mesh3d transform={Transform.fromXyz(0, 0.6, 0)}>+ <Cuboid half_size={[0.6, 0.6, 0.6]} />+ <StandardMaterial base_color="#e8b04a" perceptual_roughness={0.35} />+ </Mesh3d>+ </Entity>+ <div style={{ position: "absolute", top: 60, width: "100%", textAlign: "center", fontSize: 64, fontWeight: 800, color: "#fff" }}>Made to be seen</div>+ <div data-raea-role="caption" style={{ position: "absolute", bottom: 60, width: "100%", textAlign: "center", fontSize: 48, color: "#ff0" }}>a caption over 3D</div>+ </AbsoluteFill>+ );+}++registerRoot(() => <Composition id="edit" width={1280} height={720} fps={30} durationInFrames={60} component={Edit} />);diff --git a/apps/layers/src/composite.rs b/apps/layers/src/composite.rsnew file mode 100644index 00000000..d1a3e0e1--- /dev/null+++ b/apps/layers/src/composite.rs@@ -0,0 +1,183 @@+//! docs/layers.feature LA3a: the layers put back together are the render. Each fixture (apps/layers/fixtures) is+//! exported in layers by a built raea, its passes' frames kept; at each clip's first, middle and last frame the layers+//! are composited bottom to top (under, footage as layers.json places it, graphics, captions) and compared with the+//! reference render's frame. A test of the method, run by hand on a machine with a GPU:+//! cargo test -p raea-app-layers composite -- --ignored --nocapture (RAEA_BIN: the raea, default target/release/raea)++use std::path::{Path, PathBuf};+use std::process::Command;++use crate::model::{Clip, Layer, Layers};++/// The least PSNR (dB) a composited frame has against the reference render's: the reference is an H.264 movie and the+/// footage is decoded and scaled here as the page does it, so a frame is never exact.+const MIN_PSNR: f64 = 30.0;++/// An RGB picture, 0..1, row by row.+struct Picture {+ w: usize,+ h: usize,+ px: Vec<[f32; 3]>,+}++impl Picture {+ fn black(w: usize, h: usize) -> Picture {+ Picture { w, h, px: vec![[0.0; 3]; w * h] }+ }++ /// `rgba` (straight alpha, 8 bits) laid over this at full size, times `opacity`.+ fn over(&mut self, rgba: &[u8], opacity: f32) {+ for (k, p) in self.px.iter_mut().enumerate() {+ let a = rgba[k * 4 + 3] as f32 / 255.0 * opacity;+ for c in 0..3 {+ p[c] = p[c] * (1.0 - a) + rgba[k * 4 + c] as f32 / 255.0 * a;+ }+ }+ }++ /// A picture of `mw` x `mh` (RGBA) drawn into `bx` as CSS's object-fit `fit` draws it (centred, clipped to its+ /// box), sampled bilinearly, times `opacity`.+ fn draw(&mut self, rgba: &[u8], mw: usize, mh: usize, bx: [f64; 4], fit: &str, opacity: f32) {+ let [bx0, by0, bw, bh] = bx;+ let (sx, sy) = (bw / mw as f64, bh / mh as f64);+ let (sx, sy) = match fit {+ "cover" => (sx.max(sy), sx.max(sy)),+ "contain" => (sx.min(sy), sx.min(sy)),+ "none" => (1.0, 1.0),+ "scale-down" => (sx.min(sy).min(1.0), sx.min(sy).min(1.0)),+ _ => (sx, sy),+ };+ let (ox, oy) = (bx0 + (bw - mw as f64 * sx) / 2.0, by0 + (bh - mh as f64 * sy) / 2.0);+ let (x0, y0) = (bx0.max(0.0) as usize, by0.max(0.0) as usize);+ let (x1, y1) = (((bx0 + bw).ceil() as usize).min(self.w), ((by0 + bh).ceil() as usize).min(self.h));+ let at = |x: usize, y: usize, c: usize| rgba[(y.min(mh - 1) * mw + x.min(mw - 1)) * 4 + c] as f32 / 255.0;+ for y in y0..y1 {+ for x in x0..x1 {+ let (u, v) = ((x as f64 + 0.5 - ox) / sx - 0.5, (y as f64 + 0.5 - oy) / sy - 0.5);+ if u < -0.5 || v < -0.5 || u > mw as f64 - 0.5 || v > mh as f64 - 0.5 {+ continue;+ }+ let (u, v) = (u.max(0.0), v.max(0.0));+ let (iu, iv, fu, fv) = (u as usize, v as usize, (u.fract()) as f32, (v.fract()) as f32);+ let p = &mut self.px[y * self.w + x];+ for c in 0..3 {+ let s = at(iu, iv, c) * (1.0 - fu) * (1.0 - fv) + at(iu + 1, iv, c) * fu * (1.0 - fv) + at(iu, iv + 1, c) * (1.0 - fu) * fv + at(iu + 1, iv + 1, c) * fu * fv;+ p[c] = p[c] * (1.0 - opacity) + s * opacity;+ }+ }+ }+ }++ /// Peak signal-to-noise ratio against `rgba`, in dB (infinite when they're the same).+ fn psnr(&self, rgba: &[u8]) -> f64 {+ let mut se = 0.0f64;+ for (k, p) in self.px.iter().enumerate() {+ for c in 0..3 {+ let d = p[c] as f64 - rgba[k * 4 + c] as f64 / 255.0;+ se += d * d;+ }+ }+ let mse = se / (self.px.len() * 3) as f64;+ if mse == 0.0 { f64::INFINITY } else { 10.0 * (1.0 / mse).log10() }+ }+}++/// A movie's frame at `secs`, as RGBA, with its size.+fn frame(path: &Path, secs: f64) -> Result<(Vec<u8>, usize, usize), String> {+ let mut d = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(path).ok()).ok_or_else(|| format!("{}: no backend opens it", path.display()))?;+ let f = d.frame_at(secs).map_err(|e| format!("{}: {e}", path.display()))?;+ Ok((f.rgba.to_vec(), f.width as usize, f.height as usize))+}++/// Frame `f` of the export in `dir` composited from its layers, bottom to top.+fn composite(dir: &Path, l: &Layers, f: i64) -> Result<Picture, String> {+ let mut pic = Picture::black(l.width as usize, l.height as usize);+ let on = |c: &&Clip| c.start <= f && f < c.end();+ for t in l.tracks.iter().rev() {+ for c in t.clips.iter().filter(on) {+ match t.layer {+ Layer::Sound => {}+ Layer::Footage => {+ let file = &l.files[c.file];+ let secs = c.source_in + (f - c.start) as f64 / l.fps * c.speed + 0.25 / l.fps;+ let (rgba, w, h) = frame(Path::new(&file.path), secs)?;+ pic.draw(&rgba, w, h, c.r#box.unwrap(), c.fit.as_deref().unwrap_or("fill"), c.opacity as f32);+ }+ layer => {+ let name = format!("{layer:?}").to_lowercase();+ let png = dir.join(format!("{name}.frames/frame-{f:05}.png"));+ let (rgba, _, _) = raea_io_alpha::read_png(&png)?;+ pic.over(&rgba, 1.0);+ }+ }+ }+ }+ Ok(pic)+}++/// Each fixture exported by `bin` into its own folder under `work`: its layers.json and the folder.+fn export(bin: &Path, fixture: &Path, work: &Path) -> Result<(Layers, PathBuf), String> {+ let name = fixture.file_stem().unwrap().to_string_lossy().into_owned();+ let src = work.join(&name);+ let _ = std::fs::remove_dir_all(&src);+ std::fs::create_dir_all(src.join("media")).map_err(|e| e.to_string())?;+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");+ std::fs::copy(fixture, src.join("edit.tsx")).map_err(|e| e.to_string())?;+ std::fs::copy(root.join("engine/rune/media/tests/fixtures/clip.mp4"), src.join("media/clip.mp4")).map_err(|e| e.to_string())?;+ let out = src.join("layers");+ let run = Command::new(bin)+ .args(["export", "layers", "edit.tsx", "-o"])+ .arg(&out)+ .current_dir(&src)+ .env("RAEA_LAYERS_KEEP_FRAMES", "1")+ .env("RAEA_EXPORT_CACHE", "0")+ .output()+ .map_err(|e| format!("{}: {e}", bin.display()))?;+ if !run.status.success() {+ return Err(format!("{name}: {}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr)));+ }+ println!("{name}: {}", String::from_utf8_lossy(&run.stdout).trim());+ let l: Layers = serde_json::from_str(&std::fs::read_to_string(out.join("layers.json")).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;+ Ok((l, out))+}++#[test]+#[ignore]+fn composite_the_layers_back_and_they_are_the_render() {+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");+ let bin = std::env::var_os("RAEA_BIN").map_or_else(|| root.join("target/release/raea"), PathBuf::from);+ let work = std::env::temp_dir().join(format!("raea-layers-la3a-{}", std::process::id()));+ let mut fixtures: Vec<PathBuf> = std::fs::read_dir(Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures")).unwrap().flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "tsx")).collect();+ fixtures.sort();+ let mut failed = Vec::new();+ for fx in &fixtures {+ let name = fx.file_stem().unwrap().to_string_lossy().into_owned();+ let (l, dir) = match export(&bin, fx, &work) {+ Ok(x) => x,+ Err(e) => {+ failed.push(e);+ continue;+ }+ };+ // each clip's first, middle and last frame+ let mut at: Vec<i64> = l.tracks.iter().filter(|t| t.layer != Layer::Sound).flat_map(|t| t.clips.iter()).flat_map(|c| [c.start, c.start + c.frames / 2, c.end() - 1]).filter(|f| (0..l.frames).contains(f)).collect();+ at.sort();+ at.dedup();+ for f in at {+ let got = composite(&dir, &l, f).and_then(|pic| frame(&dir.join(&l.reference), (f as f64 + 0.25) / l.fps).map(|r| (pic, r)));+ match got {+ Ok((pic, (reference, w, h))) if (w, h) == (pic.w, pic.h) => {+ let db = pic.psnr(&reference);+ println!(" {name} frame {f}: {db:.1} dB");+ if db < MIN_PSNR {+ failed.push(format!("{name} frame {f}: the layers composited are {db:.1} dB from the reference (at least {MIN_PSNR})"));+ }+ }+ Ok((pic, (_, w, h))) => failed.push(format!("{name} frame {f}: the reference is {w}x{h}, the layers {}x{}", pic.w, pic.h)),+ Err(e) => failed.push(format!("{name} frame {f}: {e}")),+ }+ }+ }+ let _ = std::fs::remove_dir_all(&work);+ assert!(failed.is_empty(), "{}", failed.join("\n"));+}diff --git a/apps/layers/src/lib.rs b/apps/layers/src/lib.rsnew file mode 100644index 00000000..72364d0a--- /dev/null+++ b/apps/layers/src/lib.rs@@ -0,0 +1,298 @@+//! `raea export layers EDIT.tsx` (docs/layers.feature LA4a): a composition as its layers and layers.json, the timeline+//! that places them, which every editor's export is written from. Its renders, each by this same program:+//! 1. as it is, with its manifest: the reference render, and what shows when (each file's runs, each sound clip, the+//! words a caption says);+//! 2. RAEA_LAYER=graphics: what the page draws over the footage, less the captions, transparent;+//! 3. RAEA_LAYER=under, when there is footage or 3D: what's drawn under the page's footage and graphics (the+//! backgrounds holding footage, and the 3D), opaque, kept unless it's black;+//! 4. RAEA_LAYER=captions, when a frame shows a caption: the captions alone, and the words as SubRip.+//! The footage and sounds are clips of their own files where they are; each layer is clips of its movie, cut where it+//! draws something. A render that isn't an export draws once, as it always has (LA2o).++pub mod model;+pub mod plan;+pub mod srt;+#[cfg(test)]+mod composite;+#[cfg(test)]+mod tests;++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::process::Command;++use model::{Clip, File, FileKind, Layer, Layers, Track};+use raea_runtime_bundle::flag;+use serde_json::Value;++pub type R<T> = Result<T, String>;++pub const USAGE: &str = "raea export layers EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] (the composition as its layers and the timeline that places them, layers.json: the captions and the graphics as transparent movies, what's under the footage (and any 3D) as an opaque one, the footage and sounds as clips of their own files where they are, the captions also as SubRip, and the reference render; into out/layers/NAME, or DIR)";++/// `export layers ...`; None for anything else.+pub fn cli(args: &[String]) -> Option<R<String>> {+ (args.first().map(String::as_str) == Some("export") && args.get(1).map(String::as_str) == Some("layers")).then(|| export(&args[2..]).map(|(_, said)| said))+}++/// `raea render ARGS` by this same program with only `env`'s layer settings: none of the person's own RAEA_LAYER or+/// RAEA_HIDE_MEDIA reaches a render it didn't ask for. Its failure is the export's.+pub fn render(args: &[String], env: &[(&str, &str)]) -> R<()> {+ let exe = std::env::current_exe().map_err(|e| e.to_string())?;+ let mut c = Command::new(exe);+ c.arg("render").args(args).env_remove("RAEA_LAYER").env_remove("RAEA_HIDE_MEDIA");+ for (k, v) in env {+ c.env(k, v);+ }+ let out = c.output().map_err(|e| e.to_string())?;+ if !out.status.success() {+ let said = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));+ return Err(format!("the render failed:\n{}", said.trim()));+ }+ Ok(())+}++/// A layer's movie, rendered with RAEA_LAYER=`layer` into DIR/LAYER.CODEC.mov: what it made and its frames' folder,+/// which is removed unless `keep` (LA3a's test reads the frames).+fn pass(tsx: &Path, comp: &[String], dir: &Path, layer: &str, codec: raea_io_alpha::Codec, fps: f64, keep: bool, also: impl FnOnce(&Path) -> bool) -> R<Option<(PathBuf, raea_io_alpha::Made)>> {+ // the layer under the page is the bottom one, so it's drawn opaque: over 3D the page's background is the 3D's+ // clear, which --alpha would clear to nothing+ let alpha: &[String] = if layer == "under" { &[] } else { &["--alpha".to_string()] };+ let frames = dir.join(format!("{layer}.frames"));+ let _ = std::fs::remove_dir_all(&frames);+ let out = dir.join(format!("{layer}.{}.mov", codec_ext(codec)));+ let done = render(&[[tsx.display().to_string(), "-o".into(), format!("{}/", frames.display())].as_slice(), alpha, comp].concat(), &[("RAEA_LAYER", layer)])+ .and_then(|_| if also(&frames) { raea_io_alpha::encode_dir(&frames, &out, codec, fps, 0.9).map(|m| Some((out, m))) } else { Ok(None) });+ // the frames' render leaves its manifest beside them: the reference's is the export's+ let _ = std::fs::remove_file(dir.join(format!("{layer}.render.json")));+ if !keep {+ let _ = std::fs::remove_dir_all(&frames);+ }+ done+}++/// The export: the layers and layers.json in DIR, and what it says.+pub fn export(args: &[String]) -> R<(Layers, String)> {+ let tsx = args.first().filter(|a| !a.starts_with('-')).ok_or(USAGE)?;+ let tsx = dunce::canonicalize(PathBuf::from(tsx)).map_err(|e| format!("{tsx}: {e}"))?;+ let edit_dir = tsx.parent().unwrap().to_path_buf();+ let codec = flag(args, "--alpha-codec").map_or(Ok(raea_io_alpha::Codec::default_here()), |c| raea_io_alpha::Codec::parse(&c))?;+ let name = flag(args, "--name").unwrap_or_else(|| tsx.file_stem().unwrap().to_string_lossy().into_owned());+ let dir = flag(args, "-o").map_or_else(|| edit_dir.join("out/layers").join(&name), PathBuf::from);+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let dir = dunce::canonicalize(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;+ let comp: Vec<String> = flag(args, "--composition").map(|c| vec!["--composition".into(), c]).unwrap_or_default();+ // LA3a's test keeps each pass's frames to composite them back+ let keep = std::env::var_os("RAEA_LAYERS_KEEP_FRAMES").is_some();++ // 1. as it is: the reference render and its manifest+ let (reference, manifest_path) = (dir.join("reference.mp4"), dir.join("render.json"));+ render(&[[tsx.display().to_string(), "-o".into(), reference.display().to_string(), "--manifest".into(), manifest_path.display().to_string()].as_slice(), &comp].concat(), &[])?;+ let manifest: Value = serde_json::from_str(&std::fs::read_to_string(&manifest_path).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;+ let (w, h, fps) = (manifest["width"].as_u64().unwrap_or(0) as u32, manifest["height"].as_u64().unwrap_or(0) as u32, manifest["fps"].as_f64().unwrap_or(30.0));+ let length = manifest["frames"].as_array().map_or(0, Vec::len) as i64;+ let runs = plan::runs(&manifest, fps);+ let said = srt::said(&manifest);++ // 2-4. the layers' passes+ // (its frames kept until the footage it covers is found)+ let graphics = pass(&tsx, &comp, &dir, "graphics", codec, fps, true, |_| true)?;+ // footage the graphics cover (opaque over most of its box at its middle frame) goes above them: the composition+ // draws it under something it draws in front of it+ let covered: Vec<bool> = runs.iter().map(|r| graphics.is_some() && opaque_over(&dir.join("graphics.frames"), r)).collect();+ if !keep {+ let _ = std::fs::remove_dir_all(dir.join("graphics.frames"));+ }+ // what's under the page: the backgrounds holding footage, and the 3D, which the whole page is drawn over+ let under = if runs.is_empty() && manifest["has3d"] != true { None } else { pass(&tsx, &comp, &dir, "under", codec, fps, keep, lit)? };+ let captions = if said.iter().any(|s| !s.is_empty()) { pass(&tsx, &comp, &dir, "captions", codec, fps, keep, |_| true)? } else { None };+ let srt_lines = srt::lines(&said);+ let srt_name = (!srt_lines.is_empty()).then(|| format!("{name}.srt"));+ if let Some(n) = &srt_name {+ std::fs::write(dir.join(n), srt::write(&srt_lines, fps)).map_err(|e| e.to_string())?;+ }++ // the timeline, top to bottom+ let mut files: Vec<File> = Vec::new();+ let mut index: HashMap<PathBuf, usize> = HashMap::new();+ let mut notes: Vec<String> = Vec::new();+ let mut sounds = plan::sounds(&manifest);+ let mut ids = Ids::default();+ let (mut main, mut rest, mut over, mut linked) = (Vec::new(), Vec::new(), Vec::new(), Vec::new());+ for (r, cov) in runs.iter().zip(&covered) {+ let path = plan::resolve(&edit_dir, &r.src);+ let f = add(&mut files, &mut index, &path, video)?;+ let what = format!("{} (frames {}-{})", r.src, r.start, r.end - 1);+ if r.moved {+ notes.push(format!("{what}: moves or scales in its box; placed as its first frame shows it"));+ }+ if r.faded {+ notes.push(format!("{what}: fades; placed at its first frame's opacity"));+ }+ if r.fit == "fill" && files[f].width > 0 && ((r.bx[2] / r.bx[3].max(1.0)) - (files[f].width as f64 / files[f].height.max(1) as f64)).abs() > 0.01 * (files[f].width as f64 / files[f].height.max(1) as f64) {+ notes.push(format!("{what}: stretched to its {:.0}x{:.0} box (object-fit: fill); an editor may fit it inside instead", r.bx[2], r.bx[3]));+ }+ if *cov {+ notes.push(format!("{what}: raea draws over all of it from outside what holds it (a layer before it in the page); placed above the graphics, so their drawing over it is hidden in an editor"));+ }+ let mut clip = Clip { r#box: Some(r.bx), fit: Some(r.fit.clone()), opacity: r.opacity, speed: r.rate.unwrap_or(1.0).max(0.01), ..Clip::new(ids.next("v"), f, r.start, r.end - r.start, r.at) };+ // its own sound: the manifest's sound clip of the same file over the same frames from the same time+ if let Some(k) = sounds.iter().position(|c| plan::resolve(&edit_dir, &c.src) == path && (c.from - r.start).abs() <= 1 && (c.to - r.end).abs() <= 1 && (c.at - r.at).abs() <= 1.5 / fps) {+ let s = sounds.remove(k);+ let a = Clip { gain_db: s.gain_db, fade_in: s.fade_in, fade_out: s.fade_out, speed: s.rate, link: Some(clip.id.clone()), ..Clip::new(ids.next("a"), f, s.from, s.to - s.from, s.at) };+ clip.link = Some(a.id.clone());+ linked.push(a);+ }+ match (*cov, plan::full(&r.bx, w as f64, h as f64)) {+ (true, _) => over.push(clip),+ (false, true) => main.push(clip),+ (false, false) => rest.push(clip),+ }+ }+ let mut tracks: Vec<Track> = Vec::new();+ let movie = |files: &mut Vec<File>, made: &Option<(PathBuf, raea_io_alpha::Made)>, layer: Layer, name: &str, ids: &mut Ids| -> Vec<Track> {+ let Some((path, m)) = made else { return Vec::new() };+ let spans = plan::spans(&m.drawn);+ if spans.is_empty() {+ let _ = std::fs::remove_file(path);+ return Vec::new();+ }+ files.push(File { path: path.file_name().unwrap().to_string_lossy().into_owned(), kind: FileKind::Video, seconds: m.frames as f64 / fps, width: m.width, height: m.height, has_audio: false });+ let k = files.len() - 1;+ let clips = spans.iter().map(|&(a, b)| Clip::new(ids.next(&name[..1]), k, a, b - a, a as f64 / fps)).collect();+ model::lay(layer, name, clips)+ };+ tracks.extend(movie(&mut files, &captions, Layer::Captions, "captions", &mut ids));+ tracks.extend(model::lay(Layer::Footage, "footage over", over));+ tracks.extend(movie(&mut files, &graphics, Layer::Graphics, "graphics", &mut ids));+ tracks.extend(model::lay(Layer::Footage, "picture in picture", rest));+ tracks.extend(model::lay(Layer::Footage, "footage", main));+ tracks.extend(movie(&mut files, &under, Layer::Under, "under", &mut ids));+ let mut audio = linked;+ for c in sounds {+ let f = add(&mut files, &mut index, &plan::resolve(&edit_dir, &c.src), sound)?;+ audio.push(Clip { gain_db: c.gain_db, fade_in: c.fade_in, fade_out: c.fade_out, speed: c.rate, ..Clip::new(ids.next("a"), f, c.from, c.to - c.from, c.at) });+ }+ audio.sort_by_key(|c| c.start);+ // the first sound track is the top one, so later ones are listed after it (lay lists the last laid first)+ let mut sound_tracks = model::lay(Layer::Sound, "sound", audio);+ sound_tracks.reverse();+ tracks.extend(sound_tracks);+ let notes_made = manifest["sounds"]["notes"].as_array().map_or(0, Vec::len);+ if notes_made > 0 {+ notes.push(format!("the Tone graph's music ({notes_made} notes) has no file to place: it is in the reference render's sound"));+ }++ let layers = Layers { version: model::VERSION, name: name.clone(), width: w, height: h, fps, frames: length, reference: "reference.mp4".into(), srt: srt_name.clone(), files, tracks, notes };+ let json = serde_json::to_string_pretty(&layers).map_err(|e| e.to_string())?;+ std::fs::write(dir.join("layers.json"), json + "\n").map_err(|e| e.to_string())?;++ let count = |l: Layer| layers.tracks.iter().filter(|t| t.layer == l).map(|t| t.clips.len()).sum::<usize>();+ let mut said = format!(+ "APPLIED layers \"{name}\" at {}: {} tracks; {}, {}, {}, {}, {}{}; {:.2} s at {fps} fps, {w}x{h}",+ dir.display(),+ layers.tracks.len(),+ many(count(Layer::Captions), "captions clip"),+ many(count(Layer::Graphics), "graphics clip"),+ many(count(Layer::Footage), "footage clip"),+ if count(Layer::Under) == 1 { "1 clip under the footage".to_string() } else { format!("{} clips under the footage", count(Layer::Under)) },+ many(count(Layer::Sound), "sound"),+ srt_name.as_ref().map_or(String::new(), |n| format!("; {} in {n}", many(srt_lines.len(), "caption line"))),+ length as f64 / fps,+ );+ for n in &layers.notes {+ said.push_str(&format!("\n note {n}"));+ }+ Ok((layers, said))+}++/// Clip ids by kind: v1, v2... for footage, a1... for sounds, c1, g1, u1... for the captions', graphics' and under's.+#[derive(Default)]+struct Ids(HashMap<String, usize>);++impl Ids {+ fn next(&mut self, kind: &str) -> String {+ let n = self.0.entry(kind.to_string()).or_default();+ *n += 1;+ format!("{kind}{n}")+ }+}++/// "1 clip", "4 clips"+fn many(k: usize, what: &str) -> String {+ if k == 1 { format!("1 {what}") } else { format!("{k} {what}s") }+}++/// A file's place in `files`, probed the first time it's named.+fn add(files: &mut Vec<File>, index: &mut HashMap<PathBuf, usize>, p: &Path, probe: fn(&Path) -> R<File>) -> R<usize> {+ if let Some(i) = index.get(p) {+ return Ok(*i);+ }+ files.push(probe(p)?);+ index.insert(p.to_path_buf(), files.len() - 1);+ Ok(files.len() - 1)+}++/// A video file: its upright size and length from the first of raea's media backends that opens it, and whether a short+/// window of its sound decodes to samples.+pub fn video(path: &Path) -> R<File> {+ let mut why = Vec::new();+ for b in raea_io_media::preferred() {+ match b.open_video(path) {+ Ok(d) => {+ let i = d.info();+ let has_audio = raea_io_media::decode_audio_window(path, 0.0, 0.05).is_ok_and(|a| a.len() > 0);+ return Ok(File { path: path.display().to_string(), kind: FileKind::Video, seconds: i.duration, width: i.width, height: i.height, has_audio });+ }+ Err(e) => why.push(format!("{}: {e}", b.name())),+ }+ }+ Err(format!("{} didn't open as video ({})", path.display(), why.join("; ")))+}++/// A sound file: its length from its container.+pub fn sound(path: &Path) -> R<File> {+ let seconds = raea_io_media::probe_seconds(path).ok_or_else(|| format!("{}: no sound length", path.display()))?;+ Ok(File { path: path.display().to_string(), kind: FileKind::Audio, seconds, width: 0, height: 0, has_audio: true })+}++pub fn codec_ext(c: raea_io_alpha::Codec) -> &'static str {+ match c {+ raea_io_alpha::Codec::ProRes => "prores",+ raea_io_alpha::Codec::Hevc => "hevc",+ raea_io_alpha::Codec::Rle => "rle",+ raea_io_alpha::Codec::Png => "png",+ }+}++/// Whether the graphics are opaque over 90% of a run's box at its middle frame (a grid of points inside it).+fn opaque_over(frames: &Path, r: &plan::Run) -> bool {+ let mid = (r.start + r.end - 1) / 2;+ let Ok((px, w, h)) = raea_io_alpha::read_png(&frames.join(format!("frame-{mid:05}.png"))) else { return false };+ let (mut n, mut opaque) = (0, 0);+ for j in 0..16 {+ for i in 0..16 {+ let x = (r.bx[0] + r.bx[2] * (i as f64 + 0.5) / 16.0) as i64;+ let y = (r.bx[1] + r.bx[3] * (j as f64 + 0.5) / 16.0) as i64;+ if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 {+ continue;+ }+ n += 1;+ opaque += usize::from(px[((y as usize) * w as usize + x as usize) * 4 + 3] >= 250);+ }+ }+ n > 0 && opaque * 10 >= n * 9+}++/// Whether any frame in `frames` draws anything but black, at any alpha (a grid of points on each).+pub fn lit(frames: &Path) -> bool {+ raea_io_alpha::frames_in(frames).iter().any(|p| {+ let Ok((px, w, h)) = raea_io_alpha::read_png(p) else { return true };+ (0..32).any(|j| {+ (0..32).any(|i| {+ let (x, y) = ((w as usize * (2 * i + 1)) / 64, (h as usize * (2 * j + 1)) / 64);+ let k = (y * w as usize + x) * 4;+ px[k + 3] >= 8 && px[k..k + 3].iter().any(|&c| c >= 8)+ })+ })+ })+}diff --git a/apps/layers/src/model.rs b/apps/layers/src/model.rsnew file mode 100644index 00000000..26f5e4ca--- /dev/null+++ b/apps/layers/src/model.rs@@ -0,0 +1,140 @@+//! layers.json (docs/layers.feature LA4a): a composition's layers and the timeline that places them, in no editor's+//! terms. Each editor's export (CapCut's draft, the FCP7 XML) is written from it. Tracks are listed top to bottom;+//! frames are the composition's, whole; a clip's source time is in seconds.++use serde::{Deserialize, Serialize};++/// The layers.json format's version, which a reader checks before it reads the rest.+pub const VERSION: u32 = 1;++/// A composition's layers and their timeline.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Layers {+ pub version: u32,+ /// the export's name (the composition's file stem, unless --name says)+ pub name: String,+ pub width: u32,+ pub height: u32,+ pub fps: f64,+ /// the composition's length in frames+ pub frames: i64,+ /// the reference render, beside layers.json: the composition as raea draws it, on no track+ pub reference: String,+ /// the captions as SubRip, beside layers.json, when there are captions (LA2b); on no track+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub srt: Option<String>,+ /// every file a clip shows or plays: the footage and sounds where they are, the layers' movies beside layers.json+ pub files: Vec<File>,+ /// top to bottom+ pub tracks: Vec<Track>,+ /// what doesn't carry into an editor, said once each (CC2e)+ pub notes: Vec<String>,+}++/// A file a clip shows or plays.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct File {+ /// absolute for the footage and sounds (never copied, LA5a); relative to layers.json for a layer's movie+ pub path: String,+ pub kind: FileKind,+ pub seconds: f64,+ /// a picture's upright size; 0 for a sound+ pub width: u32,+ pub height: u32,+ /// whether it has sound of its own (footage)+ pub has_audio: bool,+}++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum FileKind {+ Video,+ Audio,+}++/// Which layer a track holds (the layers table in docs/layers.feature).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Layer {+ Captions,+ Graphics,+ Footage,+ Under,+ Sound,+}++/// A track: clips of one layer that never overlap.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Track {+ pub layer: Layer,+ /// what an editor calls it: "captions", "graphics", "footage", "footage 2", "footage over", "under", "sound"+ pub name: String,+ pub clips: Vec<Clip>,+}++/// A span of a file on a track.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Clip {+ /// its own id, unique in the timeline+ pub id: String,+ /// its file, an index into `files`+ pub file: usize,+ /// its first frame on the timeline, and how many it lasts+ pub start: i64,+ pub frames: i64,+ /// the source time it starts from, in seconds+ pub source_in: f64,+ /// how fast the source plays (1 as recorded)+ pub speed: f64,+ /// footage: its box on the canvas at its first frame [x, y, width, height] and how the picture fills it (CSS's+ /// object-fit); a layer's movie fills the canvas and has none+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub r#box: Option<[f64; 4]>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub fit: Option<String>,+ /// footage: its opacity at its first frame+ pub opacity: f64,+ /// a sound: its gain in decibels and its fades in seconds+ #[serde(default, skip_serializing_if = "is_zero")]+ pub gain_db: f64,+ #[serde(default, skip_serializing_if = "is_zero")]+ pub fade_in: f64,+ #[serde(default, skip_serializing_if = "is_zero")]+ pub fade_out: f64,+ /// footage and its own sound: the other's id, so an editor moves them together until it's told not to. Footage+ /// whose file has sound and no link plays silent: the composition doesn't play its sound there+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub link: Option<String>,+}++fn is_zero(v: &f64) -> bool {+ *v == 0.0+}++impl Clip {+ /// A clip of `file` from `start` for `frames`, from its source's `source_in` at speed 1, fully opaque.+ pub fn new(id: String, file: usize, start: i64, frames: i64, source_in: f64) -> Clip {+ Clip { id, file, start, frames, source_in, speed: 1.0, r#box: None, fit: None, opacity: 1.0, gain_db: 0.0, fade_in: 0.0, fade_out: 0.0, link: None }+ }++ pub fn end(&self) -> i64 {+ self.start + self.frames+ }+}++/// Clips laid on as few tracks as hold them without overlap, first come first: `layer` tracks named `name`,+/// `name 2`... (the second and later are above the first, so they're listed before it: tracks go top to bottom).+pub fn lay(layer: Layer, name: &str, clips: Vec<Clip>) -> Vec<Track> {+ let mut tracks: Vec<Track> = Vec::new();+ for c in clips {+ match tracks.iter_mut().find(|t| t.clips.last().map_or(i64::MIN, Clip::end) <= c.start) {+ Some(t) => t.clips.push(c),+ None => {+ let n = tracks.len();+ tracks.push(Track { layer, name: if n == 0 { name.to_string() } else { format!("{name} {}", n + 1) }, clips: vec![c] });+ }+ }+ }+ tracks.reverse();+ tracks+}diff --git a/apps/layers/src/plan.rs b/apps/layers/src/plan.rsnew file mode 100644index 00000000..b6930d54--- /dev/null+++ b/apps/layers/src/plan.rs@@ -0,0 +1,136 @@+//! The render's manifest read as what an export places (docs/layers.feature LA4a, docs/capcut.feature CC2): each run of+//! frames showing one file, each sound clip, the runs of frames a layer draws, and where a file the manifest names is.+//! Pure: the export (lib.rs) renders and probes around it.++use std::path::{Path, PathBuf};++use serde_json::Value;++/// One file shown over a run of frames, as the manifest's frames say: its first source time and rate, its box and+/// fit at its first frame, its place in the page's order (lower draws first), and whether it moved or faded.+#[derive(Clone, Debug, PartialEq)]+pub struct Run {+ pub src: String,+ pub key: String,+ pub start: i64,+ pub end: i64,+ pub at: f64,+ pub last_at: f64,+ pub rate: Option<f64>,+ pub bx: [f64; 4],+ pub fit: String,+ pub opacity: f64,+ pub z: usize,+ pub moved: bool,+ pub faded: bool,+}++/// One sound clip of the manifest: its file, frames, source time, gain, rate and fades.+#[derive(Clone, Debug, PartialEq)]+pub struct Sound {+ pub src: String,+ pub from: i64,+ pub to: i64,+ pub at: f64,+ pub gain_db: f64,+ pub rate: f64,+ pub fade_in: f64,+ pub fade_out: f64,+}++/// The footage's runs, frame by frame: a run goes on while the same element shows the same file with its source time+/// advancing at one rate; a jump in source time (a cut within one take) starts another.+pub fn runs(manifest: &Value, fps: f64) -> Vec<Run> {+ let mut done: Vec<Run> = Vec::new();+ let mut open: Vec<Run> = Vec::new();+ let frames = manifest["frames"].as_array().cloned().unwrap_or_default();+ for (i, fr) in frames.iter().enumerate() {+ let f = fr["frame"].as_i64().unwrap_or(i as i64);+ let mut next = Vec::new();+ for (z, v) in fr["videos"].as_array().into_iter().flatten().enumerate() {+ let src = v["src"].as_str().unwrap_or_default().to_string();+ let key = format!("{src}|{}|{}|{}", v["loc"], v["use"], v["index"]);+ let at = v["at"].as_f64().unwrap_or(0.0);+ let bx: [f64; 4] = std::array::from_fn(|k| v["box"][k].as_f64().unwrap_or(0.0));+ let opacity = v["opacity"].as_f64().unwrap_or(1.0);+ let continues = |r: &Run| {+ let step = at - r.last_at;+ r.key == key && r.end == f && step > 0.0 && match r.rate {+ Some(rate) => (step - rate / fps).abs() <= 0.6 / fps,+ None => step * fps <= 8.0,+ }+ };+ if let Some(k) = open.iter().position(continues) {+ let mut r = open.remove(k);+ r.rate.get_or_insert((at - r.last_at) * fps);+ r.moved |= r.bx.iter().zip(&bx).any(|(a, b)| (a - b).abs() > 1.0);+ r.faded |= (r.opacity - opacity).abs() > 0.02;+ (r.end, r.last_at) = (f + 1, at);+ next.push(r);+ } else {+ next.push(Run { src, key, start: f, end: f + 1, at, last_at: at, rate: None, bx, fit: v["fit"].as_str().unwrap_or("fill").to_string(), opacity, z, moved: false, faded: false });+ }+ }+ done.append(&mut open);+ open = next;+ }+ done.append(&mut open);+ // the rate over the whole run (source times are whole milliseconds, so one step's can be 1% off), to hundredths+ for r in &mut done {+ if r.end - r.start > 1 {+ r.rate = Some(((r.last_at - r.at) * fps / (r.end - r.start - 1) as f64 * 100.0).round() / 100.0);+ }+ }+ done.sort_by_key(|r| (r.start, r.z));+ done+}++/// The manifest's sound clips.+pub fn sounds(manifest: &Value) -> Vec<Sound> {+ let s = &manifest["sounds"]["clips"];+ s.as_array()+ .into_iter()+ .flatten()+ .map(|c| Sound {+ src: c["src"].as_str().unwrap_or_default().to_string(),+ from: c["from"].as_i64().unwrap_or(0),+ to: c["to"].as_i64().unwrap_or(0),+ at: c["at"].as_f64().unwrap_or(0.0),+ gain_db: c["gainDb"].as_f64().unwrap_or(0.0),+ rate: c["rate"].as_f64().unwrap_or(1.0),+ fade_in: c["fadeIn"].as_f64().unwrap_or(0.0),+ fade_out: c["fadeOut"].as_f64().unwrap_or(0.0),+ })+ .filter(|c| c.to > c.from)+ .collect()+}++/// Runs of frames that draw something.+pub fn spans(drawn: &[bool]) -> Vec<(i64, i64)> {+ let mut out = Vec::new();+ let mut f = 0;+ while f < drawn.len() {+ if !drawn[f] {+ f += 1;+ continue;+ }+ let a = f;+ while f < drawn.len() && drawn[f] {+ f += 1;+ }+ out.push((a as i64, f as i64));+ }+ out+}++/// Whether a box covers the whole canvas.+pub fn full(bx: &[f64; 4], w: f64, h: f64) -> bool {+ bx[0] <= 1.0 && bx[1] <= 1.0 && bx[0] + bx[2] >= w - 1.0 && bx[1] + bx[3] >= h - 1.0+}++/// A file the manifest names, as a path, found as the renderer finds it: a staticFile path (/media/x) in the edit's+/// media/, then the project's media/ and assets/; else absolute; else relative to the composition's folder.+pub fn resolve(dir: &Path, src: &str) -> PathBuf {+ let p = raea_core_scene::media_path(dir, src);+ dunce::canonicalize(&p).unwrap_or(p)+}diff --git a/apps/layers/src/srt.rs b/apps/layers/src/srt.rsnew file mode 100644index 00000000..563ece58--- /dev/null+++ b/apps/layers/src/srt.rs@@ -0,0 +1,57 @@+//! Captions as SubRip (docs/layers.feature LA2b): each run of frames a caption shows one line of words, from the+//! render manifest's text marked `caption` (engine/page manifest.rs).++use serde_json::Value;++/// One SubRip entry: its words, its first frame and the frame after its last.+#[derive(Clone, Debug, PartialEq)]+pub struct Line {+ pub text: String,+ pub from: i64,+ pub to: i64,+}++/// The words the captions show on each frame, joined in the page's order; empty where none shows.+pub fn said(manifest: &Value) -> Vec<String> {+ manifest["frames"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|f| {+ let words: Vec<String> = f["text"].as_array().into_iter().flatten().filter(|t| t["caption"] == true && t["opacity"].as_f64().unwrap_or(1.0) > 0.01).filter_map(|t| t["text"].as_str()).map(|s| s.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|s| !s.is_empty()).collect();+ words.join(" ")+ })+ .collect()+}++/// The lines: a run of frames showing the same words is one, and so is a line whose words come in one by one (each+/// frame's words starting with the last's) or go one by one, shown whole for the run. A word's colour changing (a+/// highlight as it's said) isn't in the words, so it never starts a line.+pub fn lines(said: &[String]) -> Vec<Line> {+ let mut out: Vec<Line> = Vec::new();+ for (f, words) in said.iter().enumerate() {+ let f = f as i64;+ if words.is_empty() {+ continue;+ }+ match out.last_mut() {+ Some(l) if l.to == f && (words.starts_with(l.text.as_str()) || l.text.starts_with(words.as_str())) => {+ if words.len() > l.text.len() {+ l.text = words.clone();+ }+ l.to = f + 1;+ }+ _ => out.push(Line { text: words.clone(), from: f, to: f + 1 }),+ }+ }+ out+}++/// SubRip's text: each line numbered from 1, its times as HH:MM:SS,mmm at `fps`.+pub fn write(lines: &[Line], fps: f64) -> String {+ let t = |f: i64| {+ let ms = (f as f64 * 1000.0 / fps).round() as i64;+ format!("{:02}:{:02}:{:02},{:03}", ms / 3_600_000, ms / 60_000 % 60, ms / 1000 % 60, ms % 1000)+ };+ lines.iter().enumerate().map(|(k, l)| format!("{}\n{} --> {}\n{}\n", k + 1, t(l.from), t(l.to), l.text)).collect::<Vec<_>>().join("\n")+}diff --git a/apps/layers/src/tests.rs b/apps/layers/src/tests.rsnew file mode 100644index 00000000..817926f5--- /dev/null+++ b/apps/layers/src/tests.rs@@ -0,0 +1,61 @@+use serde_json::json;++use crate::model::{self, Clip, Layer, Layers};+use crate::srt;++fn said(frames: &[&[(&str, bool)]]) -> serde_json::Value {+ let frames: Vec<_> = frames.iter().enumerate().map(|(i, t)| json!({"frame": i, "videos": [], "text": t.iter().map(|(w, cap)| if *cap { json!({"text": w, "caption": true, "opacity": 1.0}) } else { json!({"text": w, "opacity": 1.0}) }).collect::<Vec<_>>()})).collect();+ json!({"frames": frames})+}++#[test]+fn a_frames_captions_are_its_caption_words_alone() {+ // docs/layers.feature LA2b: words marked caption, in the page's order; a title's words aren't+ let m = said(&[&[("Jane Doe", false), ("Hello", true), (" there ", true)], &[], &[("Jane Doe", false)]]);+ assert_eq!(srt::said(&m), ["Hello there", "", ""]);+}++#[test]+fn a_line_lasts_while_its_words_do_and_a_highlight_starts_none() {+ let s = |v: &[&str]| v.iter().map(|w| w.to_string()).collect::<Vec<_>>();+ // the same words over frames 0-2 (a word's colour changing isn't in the words), a gap, then a line said word by word+ let lines = srt::lines(&s(&["Hello there", "Hello there", "Hello there", "", "This", "This is", "This is raea", "Next"]));+ assert_eq!(lines, [srt::Line { text: "Hello there".into(), from: 0, to: 3 }, srt::Line { text: "This is raea".into(), from: 4, to: 7 }, srt::Line { text: "Next".into(), from: 7, to: 8 }]);+ assert_eq!(srt::write(&lines[..2], 30.0), "1\n00:00:00,000 --> 00:00:00,100\nHello there\n\n2\n00:00:00,133 --> 00:00:00,233\nThis is raea\n");+ // timecodes past a minute and an hour+ assert_eq!(srt::write(&[srt::Line { text: "x".into(), from: 108_000, to: 108_015 }], 30.0), "1\n01:00:00,000 --> 01:00:00,500\nx\n");+}++#[test]+fn clips_go_on_as_few_tracks_as_hold_them_listed_top_down() {+ let c = |id: &str, start, frames| Clip::new(id.into(), 0, start, frames, 0.0);+ let t = model::lay(Layer::Footage, "footage", vec![c("v1", 0, 30), c("v2", 10, 30), c("v3", 30, 10), c("v4", 41, 5)]);+ // v2 overlaps v1, so it goes on a second track, above the first+ assert_eq!(t.iter().map(|t| (t.name.as_str(), t.clips.iter().map(|c| c.id.as_str()).collect::<Vec<_>>())).collect::<Vec<_>>(), [("footage 2", vec!["v2"]), ("footage", vec!["v1", "v3", "v4"])]);+}++#[test]+fn layers_json_reads_back_as_it_was_written() {+ let mut v = Clip { r#box: Some([140.0, 160.0, 800.0, 470.0]), fit: Some("cover".into()), link: Some("a1".into()), ..Clip::new("v1".into(), 0, 0, 90, 1.5) };+ v.speed = 2.0;+ let a = Clip { gain_db: -6.0, fade_in: 0.5, link: Some("v1".into()), ..Clip::new("a1".into(), 0, 0, 90, 1.5) };+ let l = Layers {+ version: model::VERSION,+ name: "edit".into(),+ width: 1080,+ height: 1920,+ fps: 30.0,+ frames: 90,+ reference: "reference.mp4".into(),+ srt: Some("edit.srt".into()),+ files: vec![model::File { path: "/m/clip.mp4".into(), kind: model::FileKind::Video, seconds: 3.0, width: 640, height: 360, has_audio: true }],+ tracks: vec![model::Track { layer: Layer::Footage, name: "footage".into(), clips: vec![v] }, model::Track { layer: Layer::Sound, name: "sound".into(), clips: vec![a] }],+ notes: vec![],+ };+ let text = serde_json::to_string(&l).unwrap();+ assert_eq!(serde_json::from_str::<Layers>(&text).unwrap(), l);+ // what a clip doesn't have isn't written: a sound has no box, footage no gain+ let j: serde_json::Value = serde_json::from_str(&text).unwrap();+ assert_eq!(j["tracks"][0]["layer"], "footage");+ assert!(j["tracks"][0]["clips"][0].get("gain_db").is_none() && j["tracks"][1]["clips"][0].get("box").is_none(), "{j}");+}diff --git a/docs/layers.feature b/docs/layers.featureindex a4d1661c..3ad98fc0 100644--- a/docs/layers.feature+++ b/docs/layers.feature@@ -30,10 +30,10 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaThe layers, top to bottom, and what each is:| layer | what it holds | what the editor gets || captions | the words said, as raea draws them, marked (LA1) | a transparent movie + an .srt beside |- | graphics | everything else raea draws over the footage: text, shapes, 3D | a transparent movie |+ | graphics | everything else the page draws over the footage: text, shapes | a transparent movie || footage | each <Video>'s file, at its trims, place and size (CC2a) | clips of the original files |- | under | what raea draws beneath the footage: the backgrounds of what | a movie, left out when all black |- | | holds it (CC2b) | |+ | under | what's drawn beneath the footage: the backgrounds of what | an opaque movie, left out when all |+ | | holds it (CC2b), and the 3D, which the whole page is drawn over | black || sound | each sound clip, and footage's own sound linked to its clip | audio clips of the original files |A layer with nothing in it is left out.@@ -68,12 +68,19 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaThen it is rendered --alpha once for each layer that has something in it, with RAEA_LAYER naming the layer:| RAEA_LAYER | draws || captions | only what is marked a caption, and none of the 3D |- | graphics | what RAEA_HIDE_MEDIA=1 draws today, less captions |- | under | what RAEA_HIDE_MEDIA=under draws today, less captions and the 3D |+ | graphics | what RAEA_HIDE_MEDIA=1 draws today, less captions and the 3D |+ | under | what RAEA_HIDE_MEDIA=under draws today and the 3D, less captions; opaque |And the page draws nothing inside a hidden element, so the captions pass clears what holds a caption (itsbackground, border, shadow and outline) and hides the rest, as RAEA_HIDE_MEDIA=under clears what holds footage+ And the 3D is drawn first and the whole page over it, footage included, so it is under the footage: the layer+ under the page draws it, and since --alpha clears the 3D's clear colour (the page's background over 3D) to+ nothing, that layer is rendered opaque, the bottom of every timelineAnd the 3D is Bevy's, not the page's, so a layer that draws none of it leaves its parts out of the frame's scene(runtime/scene items_of) and keeps its cameras, which render an empty view+ And the under pass runs when there is footage or 3D (the manifest's has3d)+ And an element whose `:has()` was matched is matched again when a node is inserted or removed under it+ (vendor/blitz-dom mutator.rs), as Chrome does: a caption a <Sequence> put on the page at frame 10 stayed hidden+ under the captions pass's `:not(:has(...))`, and so would footage that comes in later under RAEA_HIDE_MEDIA=underAnd the captions pass runs only when the manifest says a caption was drawnAnd RAEA_HIDE_MEDIA keeps working as it does, so `raea export capcut` is unchanged until LA4bAnd a pass is cut into clips where it draws something, frames that draw nothing a gap (CC2b)@@ -82,17 +89,25 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaGiven the manifest says, for each frame, the words of each caption drawn thereThen each run of frames a caption shows one line of words is an entry of NAME.srt: its words as the page showsthem (a word highlight doesn't start a new entry), its first frame and the frame after its last, in timecode+ And a line whose words come in one by one (each frame's words starting with the last's) is one entry, its words+ wholeAnd the .srt is written beside the export for the person to upload to a network or keep, and no editor'sproject imports it (the captions movie is what the timeline shows, in raea's own style)Rule: LA3. The layers put back together are the renderScenario: LA3a. The fixtures' layers composited over each other match their reference renderGiven fixtures: full-frame footage with a lower third (a bar and words) and captions; a picture in picture on a- coloured card; captions with a word highlight; 3D over footage+ coloured card; captions with a word highlight; 3D with a title and a captionWhen each is exported in layers and composited bottom to top (under, footage, graphics, captions)Then every frame matches the reference render within the alpha codec's error (CC1a's numbers), checked at leastat each clip's first, middle and last frame- And this is a test of the method, run with raea's tests; an export doesn't composite its layers back+ And this is a test of the method, not of every export: apps/layers composite.rs, run by hand on a machine with a+ GPU (`cargo test -p raea-app-layers composite -- --ignored`, RAEA_BIN the raea), the fixtures in+ apps/layers/fixtures, the footage engine/rune/media/tests/fixtures/clip.mp4; RAEA_LAYERS_KEEP_FRAMES keeps+ each pass's frames for it+ And on 11-16 (this Mac, M-series, a source build): highlight 33.0-35.1 dB, lower-third 34.1-35.1, pip-card+ 33.2-33.5, three-d 39.1-39.8; the floor is 30 dB (the reference is H.264, and the footage is decoded and scaled+ by the test, not the page)Scenario: LA3b. What doesn't carry is said, not dropped quietlyThen captions always go on top: a caption drawn under something else is still the top layer in the export@@ -100,8 +115,10 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaRule: LA4. One layered timeline, written by `raea export layers`, read by every editor's exportScenario: LA4a. `raea export layers EDIT.tsx -o DIR` writes the layers and their timeline- Then DIR holds layers.json, each layer's movie, NAME.srt when there are captions, and reference.mp4 (the- reference render, to compare the editor's timeline against; on no timeline)+ Then DIR holds layers.json, each layer's movie, NAME.srt when there are captions, reference.mp4 (the reference+ render, to compare the editor's timeline against; on no timeline) and render.json, its manifest+ And footage whose file has sound but no linked sound clip plays silent there: the composition doesn't play its+ sound at that placeAnd layers.json says the frame rate, size and length, and the tracks top to bottom, each with its layer andits clips: the file, where it starts and how long, its first source frame, its place and size, its gain andfades, and the id of the clip it's linked to (footage and its own sound)diff --git a/docs/manual/reference/cli/export.md b/docs/manual/reference/cli/export.mdindex f692152f..d66d23e7 100644--- a/docs/manual/reference/cli/export.md+++ b/docs/manual/reference/cli/export.md@@ -24,6 +24,7 @@ CapCut rewrites its project list when it quits, so `raea export capcut` refuses```shraea export capcut EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] [--no-register] (the composition as a CapCut draft ready in its timeline: its footage and sounds as clips of their own files at their trims and gains, everything raea draws as transparent overlay clips above them; into CapCut's projects, entered in its project list while CapCut is closed, or a draft folder in DIR; the reference render and the overlay movie kept in out/capcut/NAME)+raea export layers EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] (the composition as its layers and the timeline that places them, layers.json: the captions and the graphics as transparent movies, what's under the footage (and any 3D) as an opaque one, the footage and sounds as clips of their own files where they are, the captions also as SubRip, and the reference render; into out/layers/NAME, or DIR)```Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.tomlindex 92a5bb67..8c2066b5 100644--- a/engine/cli/Cargo.toml+++ b/engine/cli/Cargo.toml@@ -71,6 +71,7 @@ raea-app-media = { path = "../../apps/media" }raea-app-targets = { path = "../../apps/targets" }raea-app-game = { path = "../../apps/game" }raea-app-capcut = { path = "../../apps/capcut" }+raea-app-layers = { path = "../../apps/layers" }raea-app-play = { path = "../../apps/play", features = ["ml"] }raea-bevy-plugins = { path = "../../engine/bevy-plugins", optional = true }# raea-bevy-sdk's reflection of the plugin build's App: the type registry, a one-camera program, the animation typediff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rsindex 0ab75b9b..eb21ab86 100644--- a/engine/cli/src/cli.rs+++ b/engine/cli/src/cli.rs@@ -142,9 +142,9 @@ pub fn run(args: &[String]) -> R<String> {let usage = format!("{usage}\n raea bug TITLE... --text TEXT [--command CMD] [--error TEXT] [--agent NAME] [--dry-run] (a bug in raea itself, not in your own composition, sent to raea's server with raea's version and the OS, no account needed: words only, paths, emails and keys taken out before it goes; five a day from a machine, the same bug again counted on the first report; --dry-run prints what would go and sends nothing)");// a workspace's files and specs (docs/projects.feature), listed under render's usage like librarylet usage = format!("{usage}\n raea spec FILE.ts [--as brief|script|taste|plan|controller] (a spec's default export as JSON, checked against its schema: brief.ts, script.ts, taste.ts, plan.ts, controllers/ID.ts)\n raea workspace init [NAME] [--layout LAYOUT] | raea workspace adopt DIR [--name NAME] | raea workspace [--json] (a workspace: a git repo of projects and controllers under raea.root, ~/Documents/raea unless git config says)\n raea project new NAME [--storage inline|submodule] | raea project split NAME [--remote URL] | raea project join NAME | raea project [--json] (a project in the workspace: its folder, brief.ts, media/, out/; split and join keep its history)\n raea controller ls [--json] | raea controller get PATH [--json] | raea controller set PATH VALUE [--project] [--by NAME] | raea controller write FILE.ts [--by NAME] | raea controller rm ID [--by NAME] (the workspace's controllers, controllers/ID.ts; PATH is controller.group.field; every change a commit)\n raea check EDIT.tsx --quick [--shape S] [--platform P] [--taste T] [-o check.json] (three stills of a composition checked for text: clipped, cramped, safe areas, sizes; about a second)\n raea hook [claude|codex|gemini|kimi] (every agent's tool hooks, which raea skills install adds: before a shell command, media opened in the Mac's viewer while the raea app is installed is stopped once for raea show (the same command again goes through); after a save, the quick check on a composition)\n raea next [DIR] (the two or three useful next steps for the project, from its brief, compositions, renders and checks)\n raea doctor [--fix] [DIR] (what doesn't match this raea: old brief files, an older workspace format, an agent's skill from another version)\n raea app run|check|bundle APP.tsx [--target web|native] [--size WxH] [--script steps.json] [--png DIR] [-o App.app] (a TSX app on @raea/ui: its window, the headless check, a Mac app; web is Blitz on Bevy, native is Rune; the app's `export const app` sets the target, web when it doesn't; raea rune ... is --target native)\n {}\n {}\n {}\n {}\n {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE, raea_app_engines::shot::USAGE, raea_app_engines::round::USAGE);- let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);+ let (export_game, capcut, layers, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);let apps = format!(" {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n {}\n", raea_app_direction::check::USAGE, raea_app_check::USAGE, raea_app_solid::USAGE, raea_app_judge::USAGE, raea_app_direction::USAGE, raea_app_direction::findings::USAGE, raea_app_notes::USAGE, raea_app_fingerprint::USAGE, raea_sys_index::cli::USAGE);- return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));+ return Ok(format!("raea: renders, plays and checks raea compositions (React and TypeScript) on the GPU.\n\nusage: {usage}\n raea init (a project's files where they're missing: edit.tsx, cuts.ts, components/, AGENTS.md)\n raea cut TAKE \"line\" ... | --at A-B ... [--append] (cuts.ts and words.json: a take under media/ cut in the pauses around each line it says, transcribed first if it has no TAKE.words.json; or at those seconds)\n raea frame TAKE [--at S] (how a take fits the edit: a talking take for <FaceFrame>, a screen for <ScreenFit>, from where its face is)\n raea component list | raea component add NAME ... [--shared] [--force] | raea part list | raea part add NAME ... [--shared] [--force] (a ready component or set copied into components/, or the workspace's shared/components/ with --shared, yours to change; raea part is its old name)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {layers}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));}// `--version`: the release's version, which a skill's front matter names (docs/skills.feature SK6)if args.len() == 1 && matches!(args[0].as_str(), "--version" | "-V") {@@ -218,6 +218,8 @@ pub fn run(args: &[String]) -> R<String> {if args.first().map(String::as_str) == Some("play") {return raea_app_play::play(args);}+ // `export layers EDIT.tsx`: the composition as its layers and layers.json, every editor's export's (apps/layers)+ if let Some(done) = raea_app_layers::cli(args) { return done; }// `export capcut EDIT.tsx` (a CapCut draft) and `render ... -o OUT.mov --alpha` (a transparent movie): apps/capcutif let Some(done) = raea_app_capcut::cli(args, |a| raea_app_sound::render(a).unwrap_or_else(|| raea_runtime_export::render(a))) { return done; }// `export-game EDIT.tsx -o OUT`: the game as a program of its own (game.rs, sdk/react/docs/game-export.md)diff --git a/engine/page/src/motion/manifest.rs b/engine/page/src/motion/manifest.rsindex c1e256eb..a990aed6 100644--- a/engine/page/src/motion/manifest.rs+++ b/engine/page/src/motion/manifest.rs@@ -160,6 +160,11 @@ impl BlitzPage {if let Some(l) = node.element_data().and_then(|e| e.inline_layout_data.as_ref()) {t["lines"] = json!(l.layout.len());}+ // words a caption says (docs/layers.feature LA1a, LA2b): an export in layers renders captions as a pass of+ // their own only when a frame has some, and writes them as SubRip+ if in_caption(doc, owner) {+ t["caption"] = json!(true);+ }stamps(owner, &mut t);text.push(t);}@@ -245,6 +250,19 @@ fn stamps(doc: &blitz_dom::BaseDocument, n: blitz_dom::NodeId, entry: &mut serde}}+/// Whether `n` is a caption or inside one: it or an element up from it carries data-raea-role="caption".+fn in_caption(doc: &blitz_dom::BaseDocument, n: blitz_dom::NodeId) -> bool {+ let mut at = Some(n);+ while let Some(x) = at {+ let Some(node) = doc.get_node(x) else { break };+ if node.attr(LocalName::from("data-raea-role")) == Some("caption") {+ return true;+ }+ at = node.parent;+ }+ false+}+/// An svg's shown <text>s, in document order: each one's words (as [`run_text`] joins its chunks), its box in the/// svg's canvas, and its opacity times its groups' (from `a`, the svg element's own). One under 0.01 isn't shown.fn svg_runs(g: &usvg::Group, a: f64) -> Vec<(String, usvg::Rect, f64)> {diff --git a/runtime/export/src/lib.rs b/runtime/export/src/lib.rsindex fde5c7d7..1ab310d0 100644--- a/runtime/export/src/lib.rs+++ b/runtime/export/src/lib.rs@@ -68,11 +68,12 @@ pub(crate) struct Sound {static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);/// The manifest, its folder made first (2D stills write it before their frames): the composition's length in frames-/// (whatever was rendered of it; raea check --quick samples by it, #86), boxes as drawn, findings, sounds.+/// (whatever was rendered of it; raea check --quick samples by it, #86), boxes as drawn, findings, sounds, and whether+/// it drew 3D (an export in layers draws the 3D in the layer under the page, docs/layers.feature LA2a).fn write_manifest(cx: &mut Ctx, (w, h, fps, length): (u32, u32, f64, i64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {let (Some(path), Some(frames)) = (MANIFEST.lock().unwrap().clone(), cx.manifest.take()) else { return Ok(()) };path.parent().map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", path.display()))?;- std::fs::write(&path, json!({"width": w, "height": h, "fps": fps, "length": length, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps)}).to_string()).map_err(|e| format!("{}: {e}", path.display()))+ std::fs::write(&path, json!({"width": w, "height": h, "fps": fps, "length": length, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps), "has3d": cx.scene3d.is_some() || cx.live3d.is_some()}).to_string()).map_err(|e| format!("{}: {e}", path.display()))}/// `render --stage WxH`: a responsive composition (one that lays out from useVideoConfig) laid out at a stage's size, asdiff --git a/systems/layers/src/hide.rs b/systems/layers/src/hide.rsindex dd2f2a6b..6ed5d49a 100644--- a/systems/layers/src/hide.rs+++ b/systems/layers/src/hide.rs@@ -65,11 +65,12 @@ pub fn hiding_css(keys: &str, media: Option<&str>, layer: Option<&str>) -> Optio(!css.is_empty()).then_some(css)}-/// Whether an export's layer (RAEA_LAYER's value) draws the composition's 3D: the graphics do, as everything raea-/// draws over the footage; captions and what's under the footage don't (docs/layers.feature LA2a). 3D is drawn by-/// Bevy, not the page, so the page's CSS can't hide it: runtime/scene leaves its parts out instead.+/// Whether an export's layer (RAEA_LAYER's value) draws the composition's 3D: only the layer under the page does+/// (docs/layers.feature LA2a). The 3D is drawn first and the whole page over it, footage included, so it's under+/// everything the page draws. It's drawn by Bevy, not the page, so the page's CSS can't hide it: runtime/scene leaves+/// its parts out of the captions and graphics layers instead.pub fn draws_3d(layer: Option<&str>) -> bool {- !matches!(layer, Some("captions" | "under"))+ !matches!(layer, Some("captions" | "graphics"))}/// Whether an export's layer draws a part of the 3D of `kind` (runtime/scene's): every part, or in a layer that drawsdiff --git a/systems/layers/src/tests.rs b/systems/layers/src/tests.rsindex f2871f17..c99f9a73 100644--- a/systems/layers/src/tests.rs+++ b/systems/layers/src/tests.rs@@ -122,16 +122,16 @@ fn an_exports_layers_split_the_captions_from_the_rest() {assert_eq!(hiding_css("", Some("1"), Some("text")), None);}-/// docs/layers.feature LA2a: the captions and under layers draw none of the 3D, keeping only its cameras; the-/// graphics layer and a render that isn't an export draw it all+/// docs/layers.feature LA2a: the captions and graphics layers draw none of the 3D, keeping only its cameras; the+/// layer under the page and a render that isn't an export draw it all#[test]fn a_layer_without_3d_keeps_only_the_cameras() {let all = ["camera", "mesh", "directional", "text", "rendercam", "splat"];let kinds = |layer: Option<&str>| all.iter().filter(|k| draws_part(layer, k)).copied().collect::<Vec<_>>();- for layer in [Some("captions"), Some("under")] {+ for layer in [Some("captions"), Some("graphics")] {assert_eq!(kinds(layer), ["camera", "rendercam"], "{layer:?}");}- for layer in [None, Some("graphics")] {+ for layer in [None, Some("under")] {assert_eq!(kinds(layer).len(), 6, "{layer:?}");}}diff --git a/tools/layers.toml b/tools/layers.tomlindex 9a212298..edfdbab7 100644--- a/tools/layers.toml+++ b/tools/layers.toml@@ -182,6 +182,7 @@ raea-app-media = "apps"raea-app-targets = "apps"raea-app-game = "apps"raea-app-capcut = "apps"+raea-app-layers = "apps"raea-app-play = "apps"raea-page-host = "runtime"raea-rune-host = "runtime"diff --git a/vendor/blitz-dom/src/mutator.rs b/vendor/blitz-dom/src/mutator.rsindex 979ebe75..a5be97c2 100644--- a/vendor/blitz-dom/src/mutator.rs+++ b/vendor/blitz-dom/src/mutator.rs@@ -13,6 +13,7 @@ use crate::{};use blitz_traits::shell::Viewport;use style::Atom;+use selectors::matching::ElementSelectorFlags;use style::invalidation::element::restyle_hints::RestyleHint;use style::stylesheets::OriginSet;use thin_vec::ThinVec;@@ -290,6 +291,25 @@ impl DocumentMutator<'_> {}}+ /// raea: `from` and each element up from it whose `:has()` was matched (Stylo flags it ANCHORS_RELATIVE_SELECTOR)+ /// matched again, itself only, after a node under it was inserted or removed. The traversal visited them (their+ /// ancestors marked dirty) but kept the answer their `:has()` gave before: a caption a <Sequence> put on the page+ /// at its frame stayed hidden under `:not(:has([data-raea-role="caption"]))` (docs/layers.feature LA2a, an+ /// export's captions pass), and footage that came in later under RAEA_HIDE_MEDIA=under. Chrome matches them again.+ fn restyle_has_anchors(&mut self, from: NodeId) {+ let anchors = ElementSelectorFlags::ANCHORS_RELATIVE_SELECTOR | ElementSelectorFlags::ANCHORS_RELATIVE_SELECTOR_NON_SUBJECT;+ let mut at = Some(from);+ while let Some(id) = at {+ let Some(node) = self.doc.nodes.get_mut(id) else { break };+ if node.element_data().is_some_and(|e| e.selector_flags.get().intersects(anchors)) {+ if let Some(mut data) = node.try_stylo_element_data_mut().and_then(|s| s.get_mut()) {+ data.hint |= RestyleHint::RESTYLE_SELF;+ }+ }+ at = node.parent;+ }+ }+pub fn set_attribute(&mut self, node_id: NodeId, name: QualName, value: &str) {let node_is_in_document = self.doc.nodes[node_id].flags.is_in_document();if node_is_in_document {@@ -595,6 +615,9 @@ impl DocumentMutator<'_> {parent.mark_ancestors_dirty();parent.children.retain(|id| *id != node_id);self.maybe_record_node(parent_id);+ if node_is_in_document {+ self.restyle_has_anchors(parent_id);+ }}}@@ -635,6 +658,9 @@ impl DocumentMutator<'_> {parent.children.retain(|id| *id != node_id);self.maybe_record_node(parent_id);+ if parent_is_in_doc {+ self.restyle_has_anchors(parent_id);+ }}node@@ -662,6 +688,9 @@ impl DocumentMutator<'_> {self.process_removed_subtree(child_id);let _ = self.doc.drop_node_ignoring_parent(child_id);}+ if parent_is_in_doc {+ self.restyle_has_anchors(node_id);+ }self.maybe_record_node(node_id);}@@ -740,6 +769,9 @@ impl DocumentMutator<'_> {old_parent.children.retain(|id| *id != child_id);self.maybe_record_node(old_parent_id);+ if child_was_in_doc {+ self.restyle_has_anchors(old_parent_id);+ }}let new_parent = &mut self.doc.nodes[parent_id];@@ -758,6 +790,9 @@ impl DocumentMutator<'_> {}insert_children_fn(new_parent, child_ids);+ if new_parent_is_in_document {+ self.restyle_has_anchors(parent_id);+ }for child_id in child_ids.iter().copied() {let child = &mut self.doc.nodes[child_id];diff --git a/vendor/vendor.toml b/vendor/vendor.tomlindex 1b7ea35d..a496a42e 100644--- a/vendor/vendor.toml+++ b/vendor/vendor.toml@@ -70,7 +70,7 @@ exit = "a Blitz release that draws these"path = "vendor/blitz-dom"upstream = "crates.io:0.3.0-beta.4"kind = "patch"-reason = "inline flex/grid baselines, auto table columns, table row rects, inline image load events, SVG text fonts, SVG non-scaling strokes, url() filters; Blitz main's #1244 and #1246; a node removed in a mutation batch dropped from the style, form and title nodes the batch flushes (raea #24); a node in a 3D rendering context (or with a projection) placed again on every resolve, so it follows a preserve-3d parent whose transform a script set (raea #19); a ParseErrorReporter (not_applied.rs) on every author parse, keeping what stylo drops for the render to say once (raea #34); a bevy_text box whose lines are no finite size (an Apple bitmap-only face, which parley scales by a units-per-em of 0) measures 0 by 0, as bevy_text does; a family list ending in ; getBoundingClientRect and the geometry walks stop at a freed containing-block link instead of panicking on its key, and an element in a display: none subtree answers a zero rect (raea #108)"raea-bevy fallback" (bevy_text's FontSource::Family) falls to the collection's fallback families, not to serif nor to the CoreText pick (parley: NO_HOOK_FAMILY); an out-of-flow box painted by the stacking context between it and its containing block, inside its opacity group (raea #39); an SVG's paint properties from CSS written into its serialized source for usvg (raea #45); transform-box: stroke-box as fill-box under non-scaling-stroke, a stylesheet's stroke in the stroke box, and the non-scaling mark on an element with its own id (raea #50); an SVG element's rewritten style attribute without a leading `;` when its own declarations were transforms alone; transform-box: view-box's reference box at the origin of user space, not at the viewBox's x and y; every inline box laid out in full while its line is only measured, since Taffy's measure cache keeps a box's size without its baseline (raea #109); an inline element has a border edge only where its border has a style, so a plain span (border-style none, its width still `medium`) doesn't split the shaping at its edges and lose the kerning across them (docs/layout-reads.feature LR10); an app-bundled svg face of a family the page already gave is left out, as one given before the page's is removed (raea/text loadFont fetches Google's faces at import, LR10); getBoundingClientRect through a perspective's projection (the node's Projection), and transformed_rect for a rect inside a node's box (LR10)"+reason = "inline flex/grid baselines, auto table columns, table row rects, inline image load events, SVG text fonts, SVG non-scaling strokes, url() filters; Blitz main's #1244 and #1246; a node removed in a mutation batch dropped from the style, form and title nodes the batch flushes (raea #24); a node in a 3D rendering context (or with a projection) placed again on every resolve, so it follows a preserve-3d parent whose transform a script set (raea #19); a ParseErrorReporter (not_applied.rs) on every author parse, keeping what stylo drops for the render to say once (raea #34); a bevy_text box whose lines are no finite size (an Apple bitmap-only face, which parley scales by a units-per-em of 0) measures 0 by 0, as bevy_text does; a family list ending in ; getBoundingClientRect and the geometry walks stop at a freed containing-block link instead of panicking on its key, and an element in a display: none subtree answers a zero rect (raea #108)"raea-bevy fallback" (bevy_text's FontSource::Family) falls to the collection's fallback families, not to serif nor to the CoreText pick (parley: NO_HOOK_FAMILY); an out-of-flow box painted by the stacking context between it and its containing block, inside its opacity group (raea #39); an SVG's paint properties from CSS written into its serialized source for usvg (raea #45); transform-box: stroke-box as fill-box under non-scaling-stroke, a stylesheet's stroke in the stroke box, and the non-scaling mark on an element with its own id (raea #50); an SVG element's rewritten style attribute without a leading `;` when its own declarations were transforms alone; transform-box: view-box's reference box at the origin of user space, not at the viewBox's x and y; every inline box laid out in full while its line is only measured, since Taffy's measure cache keeps a box's size without its baseline (raea #109); an inline element has a border edge only where its border has a style, so a plain span (border-style none, its width still `medium`) doesn't split the shaping at its edges and lose the kerning across them (docs/layout-reads.feature LR10); an app-bundled svg face of a family the page already gave is left out, as one given before the page's is removed (raea/text loadFont fetches Google's faces at import, LR10); getBoundingClientRect through a perspective's projection (the node's Projection), and transformed_rect for a rect inside a node's box (LR10); an element whose `:has()` was matched is matched again when a node under it is inserted or removed (raea layers LA2a: a caption a <Sequence> put on the page stayed hidden under `:not(:has(...))`)"exit = "a Blitz release with #1244/#1246 and these"[parley_engine]