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 LA2c: what's behind a picture in picture is its own layer, between it and the footage under it
Zachary Guglin338c140f4c3d
diff --git a/apps/capcut/src/from_layers.rs b/apps/capcut/src/from_layers.rsindex 6da634d8..228c8dbd 100644--- a/apps/capcut/src/from_layers.rs+++ b/apps/capcut/src/from_layers.rs@@ -15,7 +15,7 @@ pub fn track_name(layer: Layer, name: &str) -> String {match layer {Layer::Captions => format!("raea {name}"),Layer::Graphics => name.replacen("graphics", "raea overlay", 1),- Layer::Under => format!("raea {name}"),+ Layer::Under | Layer::Backing => format!("raea {name}"),Layer::Footage | Layer::Sound => name.to_string(),}}@@ -52,7 +52,7 @@ pub fn timeline(l: &Layers, dir: &Path) -> Timeline {let own = c.link.as_deref().and_then(|id| all().find(|a| a.id == id));Clip { volume: own.map_or(0.0, |a| 10f64.powf(a.gain_db / 20.0)), place, ..base }}- Layer::Graphics | Layer::Captions | Layer::Under => Clip { volume: 0.0, place: Place::centred(l.width, l.height), ..base },+ Layer::Graphics | Layer::Captions | Layer::Under | Layer::Backing => Clip { volume: 0.0, place: Place::centred(l.width, l.height), ..base },}}).collect();diff --git a/apps/layers/src/composite.rs b/apps/layers/src/composite.rsindex d1a3e0e1..4f80dac8 100644--- a/apps/layers/src/composite.rs+++ b/apps/layers/src/composite.rs@@ -2,7 +2,8 @@//! 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)+//! cargo test -p raea-app-layers composite -- --ignored --nocapture (RAEA_BIN: the raea, default target/release/raea;+//! RAEA_LAYERS_PROJECT=DIR/EDIT.tsx checks that composition, its media/ beside it, in place of the fixtures)use std::path::{Path, PathBuf};use std::process::Command;@@ -103,8 +104,9 @@ fn composite(dir: &Path, l: &Layers, f: i64) -> Result<Picture, String> {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();+ _ => {+ // a layer's movie is NAME.CODEC.mov, its frames NAME.frames+ let name = l.files[c.file].path.split('.').next().unwrap_or_default().to_string();let png = dir.join(format!("{name}.frames/frame-{f:05}.png"));let (rgba, _, _) = raea_io_alpha::read_png(&png)?;pic.over(&rgba, 1.0);@@ -122,11 +124,17 @@ fn export(bin: &Path, fixture: &Path, work: &Path) -> Result<(Layers, PathBuf),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");+ // a project of its own is exported where it is; a fixture is copied with the test clip beside it+ let (src, edit) = if fixture.parent() == Some(&Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures")) {+ 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())?;+ (src, "edit.tsx".to_string())+ } else {+ (fixture.parent().unwrap().to_path_buf(), fixture.file_name().unwrap().to_string_lossy().into_owned())+ };+ let out = work.join(&name).join("layers");let run = Command::new(bin)- .args(["export", "layers", "edit.tsx", "-o"])+ .args(["export", "layers", edit.as_str(), "-o"]).arg(&out).current_dir(&src).env("RAEA_LAYERS_KEEP_FRAMES", "1")@@ -147,7 +155,10 @@ 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();+ let mut fixtures: Vec<PathBuf> = match std::env::var_os("RAEA_LAYERS_PROJECT") {+ Some(p) => vec![PathBuf::from(p)],+ None => 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 {diff --git a/apps/layers/src/lib.rs b/apps/layers/src/lib.rsindex 72364d0a..6f0b89c6 100644--- a/apps/layers/src/lib.rs+++ b/apps/layers/src/lib.rs@@ -5,7 +5,9 @@//! 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.+//! 4. RAEA_LAYER=captions, when a frame shows a caption: the captions alone, and the words as SubRip;+//! 5. RAEA_LAYER=behind:FILE, for each file shown as a picture in picture: what's drawn behind it (its card), kept+//! only where it's a picture in picture, on a track between it and the footage under it.//! 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).@@ -51,19 +53,24 @@ pub fn render(args: &[String], env: &[(&str, &str)]) -> R<()> {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).+/// A layer's movie, rendered with RAEA_LAYER=`layer` into DIR/NAME.CODEC.mov (NAME the layer's, or `name` for one of+/// many), its frames in DIR/NAME.frames, removed unless `keep` (LA3a's test reads them).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)>> {+ pass_named(tsx, comp, dir, layer, layer, codec, fps, keep, also)+}++#[allow(clippy::too_many_arguments)]+fn pass_named(tsx: &Path, comp: &[String], dir: &Path, name: &str, 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 nothinglet alpha: &[String] = if layer == "under" { &[] } else { &["--alpha".to_string()] };- let frames = dir.join(format!("{layer}.frames"));+ let frames = dir.join(format!("{name}.frames"));let _ = std::fs::remove_dir_all(&frames);- let out = dir.join(format!("{layer}.{}.mov", codec_ext(codec)));+ let out = dir.join(format!("{name}.{}.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")));+ let _ = std::fs::remove_file(dir.join(format!("{name}.render.json")));if !keep {let _ = std::fs::remove_dir_all(&frames);}@@ -105,6 +112,19 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {// what's under the page: the backgrounds holding footage, and the 3D, which the whole page is drawn overlet 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 };+ // what's behind each file shown as a picture in picture (its card), between it and the footage under it (LA2c):+ // a pass for each such file, kept only where it's a picture in picture+ let full = |r: &plan::Run| plan::full(&r.bx, w as f64, h as f64);+ let mut pips: Vec<String> = runs.iter().zip(&covered).filter(|(r, c)| !**c && !full(r)).map(|(r, _)| r.src.clone()).collect();+ pips.dedup();+ pips.sort();+ pips.dedup();+ let mut behind = Vec::new();+ for (k, src) in pips.iter().enumerate() {+ let made = pass_named(&tsx, &comp, &dir, &format!("behind-{}", k + 1), &format!("behind:{src}"), codec, fps, keep, |_| true)?;+ let shown: Vec<(i64, i64)> = runs.iter().zip(&covered).filter(|(r, c)| !**c && !full(r) && r.src == *src).map(|(r, _)| (r.start, r.end)).collect();+ behind.push((made, shown));+ }let srt_lines = srt::lines(&said);let srt_name = (!srt_lines.is_empty()).then(|| format!("{name}.srt"));if let Some(n) = &srt_name {@@ -149,9 +169,13 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {}}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 movie = |files: &mut Vec<File>, made: &Option<(PathBuf, raea_io_alpha::Made)>, layer: Layer, name: &str, ids: &mut Ids, within: Option<&[(i64, i64)]>| -> Vec<Track> {let Some((path, m)) = made else { return Vec::new() };- let spans = plan::spans(&m.drawn);+ // where it draws something, and (behind a picture in picture) only within the frames given+ let spans: Vec<(i64, i64)> = match within {+ None => plan::spans(&m.drawn),+ Some(w) => plan::spans(&m.drawn).into_iter().flat_map(|(a, b)| w.iter().map(move |&(c, d)| (a.max(c), b.min(d)))).filter(|(a, b)| a < b).collect(),+ };if spans.is_empty() {let _ = std::fs::remove_file(path);return Vec::new();@@ -161,12 +185,19 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {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(movie(&mut files, &captions, Layer::Captions, "captions", &mut ids, None));tracks.extend(model::lay(Layer::Footage, "footage over", over));- tracks.extend(movie(&mut files, &graphics, Layer::Graphics, "graphics", &mut ids));+ tracks.extend(movie(&mut files, &graphics, Layer::Graphics, "graphics", &mut ids, None));tracks.extend(model::lay(Layer::Footage, "picture in picture", rest));+ // every file's backing on as few tracks as hold them, under the pictures in picture+ let mut backing: Vec<Clip> = Vec::new();+ for (made, shown) in &behind {+ backing.extend(movie(&mut files, made, Layer::Backing, "behind picture in picture", &mut ids, Some(shown)).into_iter().flat_map(|t| t.clips));+ }+ backing.sort_by_key(|c| c.start);+ tracks.extend(model::lay(Layer::Backing, "behind picture in picture", backing));tracks.extend(model::lay(Layer::Footage, "footage", main));- tracks.extend(movie(&mut files, &under, Layer::Under, "under", &mut ids));+ tracks.extend(movie(&mut files, &under, Layer::Under, "under", &mut ids, None));let mut audio = linked;for c in sounds {let f = add(&mut files, &mut index, &plan::resolve(&edit_dir, &c.src), sound)?;@@ -188,12 +219,13 @@ pub fn export(args: &[String]) -> R<(Layers, 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}",+ "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"),+ Some(count(Layer::Backing)).filter(|&k| k > 0).map_or(String::new(), |k| format!(", {} behind a picture in picture", many(k, "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"))),diff --git a/apps/layers/src/model.rs b/apps/layers/src/model.rsindex 26f5e4ca..7e404eaf 100644--- a/apps/layers/src/model.rs+++ b/apps/layers/src/model.rs@@ -59,6 +59,8 @@ pub enum Layer {Captions,Graphics,Footage,+ /// what's drawn behind a picture in picture, between it and the footage under it (its card, LA2c)+ Backing,Under,Sound,}@@ -67,7 +69,8 @@ pub enum Layer {#[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"+ /// what an editor calls it: "captions", "graphics", "picture in picture", "behind picture in picture", "footage",+ /// "footage 2", "footage over", "under", "sound"pub name: String,pub clips: Vec<Clip>,}diff --git a/docs/layers.feature b/docs/layers.featureindex 5007896f..5b0adcf0 100644--- a/docs/layers.feature+++ b/docs/layers.feature@@ -32,6 +32,8 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for Ca| captions | the words said, as raea draws them, marked (LA1) | a transparent movie + an .srt beside || 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 |+ | behind | what's drawn behind a picture in picture (its card), between | a transparent movie for each file |+ | | it and the footage under it (LA2c) | shown as a picture in picture || 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 |@@ -94,6 +96,19 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaAnd 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)+ Scenario: LA2c. What's behind a picture in picture sits between it and the footage under it+ Given footage that doesn't fill the frame (a picture in picture) over other footage, on a card: an element+ holding it whose background is drawn over the footage under it+ Then for each file shown as a picture in picture, RAEA_LAYER=behind:FILE draws the backgrounds of what holds that+ file and no other footage; what holds other footage too is cleared, not hidden; the rest is hidden+ And its clips are kept only where that file is a picture in picture, on a track named "behind picture in+ picture", above the footage that fills the frame and below the pictures in picture+ And the under layer, beneath all the footage, can't hold it: footage that fills the frame would cover it (the+ multi-clip test's card behind C at 4-6 s: 23.2 dB with it in the under layer, 37.7 with it behind C)+ And where a picture in picture is the only footage, what holds it also holds the page's background, so the+ backing layer and the under layer both draw it: the same picture, but a picture in picture moved in an editor+ leaves its card behind in the under layer+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@@ -108,6 +123,9 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaAnd on 11-16 (this Mac, M-series, a source build): highlight 33.0-35.1 dB, lower-third 34.1-35.1, pip-card33.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 scaledby the test, not the page)+ And RAEA_LAYERS_PROJECT=DIR/EDIT.tsx checks a project of its own in place of the fixtures: on 11-16 a 10 s cut of+ three raea-rendered clips (cuts, one clip at two trims, a picture in picture on a card, four captions, a lower+ third and a title that come and go, its own sound and a muted clip over a music bed) at 36.2-42.7 dBScenario: 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 exportdiff --git a/systems/layers/src/hide.rs b/systems/layers/src/hide.rsindex 6ed5d49a..b5e87aac 100644--- a/systems/layers/src/hide.rs+++ b/systems/layers/src/hide.rs@@ -16,8 +16,9 @@ const HOLDS: &str = r#":has([data-raea-role="caption"]):not([data-raea-role="cap/// RAEA_HIDE_LAYERS: the layers keyed (a key a line or comma) drawn hidden, each element with its stamps and all/// inside it; RAEA_HIDE_MEDIA: the footage (the page's only elements with data-raea-src) and what's over it or under-/// it, as above; RAEA_LAYER: one layer of an export, which wins over RAEA_HIDE_MEDIA; as page CSS. None when none of-/// them hides anything.+/// it, as above; RAEA_LAYER: one layer of an export (captions, graphics, under, or behind:FILE, what's drawn behind+/// the footage of FILE where it's a picture in picture), which wins over RAEA_HIDE_MEDIA; as page CSS. None when none+/// of them hides anything.pub fn hidden_css() -> Option<String> {let var = |k: &str| std::env::var(k).ok();hiding_css(&var("RAEA_HIDE_LAYERS").unwrap_or_default(), var("RAEA_HIDE_MEDIA").as_deref(), var("RAEA_LAYER").as_deref())@@ -52,11 +53,22 @@ pub fn hiding_css(keys: &str, media: Option<&str>, layer: Option<&str>) -> Optiocss.push_str(&format!("{HOLDS} {{ background: transparent !important; border-color: transparent !important; box-shadow: none !important; outline: none !important; }}\n"));hide.push(format!(":not({HOLDS}, [data-raea-role=\"caption\"], [data-raea-role=\"caption\"] *)"));}+ // what's drawn behind one picture in picture (docs/layers.feature LA2c): the backgrounds of what holds that+ // file and no other footage (its card); what also holds other footage is cleared, not hidden, since the page+ // draws nothing inside a hidden element; the footage and everything else hidden+ Some(l) if l.starts_with("behind:") => {+ let src = serde_json::to_string(&l["behind:".len()..]).unwrap_or_default();+ let holds = format!(":has([data-raea-src={src}])");+ css.push_str("html, body { background: transparent !important; }\n");+ css.push_str(&format!("{holds} {{ color: transparent !important; text-shadow: none !important; }}\n"));+ css.push_str(&format!("{holds}:has([data-raea-src]:not([data-raea-src={src}])) {{ background: transparent !important; border-color: transparent !important; box-shadow: none !important; outline: none !important; }}\n"));+ hide.push(format!(":not({holds})"));+ }Some(mode @ ("graphics" | "under")) => {footage(&mut hide, &mut css, if mode == "graphics" { "1" } else { "under" });hide.push(CAPTION.into());}- Some(other) => eprintln!("raea: RAEA_LAYER={other} isn't a layer (captions, graphics or under); the page is drawn whole"),+ Some(other) => eprintln!("raea: RAEA_LAYER={other} isn't a layer (captions, graphics, under or behind:FILE); the page is drawn whole"),None => footage(&mut hide, &mut css, media.unwrap_or_default()),}if !hide.is_empty() {@@ -70,7 +82,7 @@ pub fn hiding_css(keys: &str, media: Option<&str>, layer: Option<&str>) -> Optio/// 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" | "graphics"))+ !matches!(layer, Some("captions" | "graphics")) && !layer.is_some_and(|l| l.starts_with("behind:"))}/// 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 c99f9a73..0dab43c5 100644--- a/systems/layers/src/tests.rs+++ b/systems/layers/src/tests.rs@@ -135,3 +135,15 @@ fn a_layer_without_3d_keeps_only_the_cameras() {assert_eq!(kinds(layer).len(), 6, "{layer:?}");}}++#[test]+fn whats_behind_a_picture_in_picture_is_its_own_holders_alone() {+ // docs/layers.feature LA2c: the card holding C and no other footage keeps its background; what holds C and other+ // footage too (the page) is cleared, not hidden; everything else (the footage among it) is hidden+ let css = hiding_css("", None, Some("behind:/media/C.mp4")).unwrap();+ assert!(css.contains(r#":has([data-raea-src="/media/C.mp4"]):has([data-raea-src]:not([data-raea-src="/media/C.mp4"])) { background: transparent !important;"#), "{css}");+ assert!(css.ends_with(r#":not(:has([data-raea-src="/media/C.mp4"])) { visibility: hidden !important; }"#), "{css}");+ // a file's name is quoted as CSS reads it+ assert!(hiding_css("", None, Some(r#"behind:/media/a "b".mp4"#)).unwrap().contains(r#"[data-raea-src="/media/a \"b\".mp4"]"#));+ assert!(!draws_3d(Some("behind:/media/C.mp4")));+}