Skip to content

armgit / raea

Public Imported from GitHub
0

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

layers LA4b: `raea export capcut` is written from layers.json, with a captions track and the reference in the draft

Zachary Guglin26a3415c47e8
diff --git a/Cargo.lock b/Cargo.lock
index a561a383..5bcf0fe9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13753,7 +13753,6 @@ dependencies = [
"raea-io-home",
"raea-io-media",
"raea-runtime-bundle",
- "serde_json",
]
[[package]]
diff --git a/apps/capcut/Cargo.toml b/apps/capcut/Cargo.toml
index 438bdba7..9f81f0d1 100644
--- a/apps/capcut/Cargo.toml
+++ b/apps/capcut/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
license = "FSL-1.1-ALv2"
publish = false
-description = "`raea export capcut`: a composition as a CapCut draft ready in its timeline, its footage and sounds as clips of their files and what raea draws as transparent overlays (docs/capcut.feature)"
+description = "`raea export capcut`: a composition as a CapCut draft ready in its timeline, written from its layers (raea-app-layers: footage and sounds as clips of their files, the graphics, captions and what is under the footage as movies; docs/capcut.feature, docs/layers.feature LA4b)"
[dependencies]
dunce = "1"
@@ -13,7 +13,6 @@ 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 manifest read as what an export places, shared with every editor's export (docs/layers.feature LA4)
+# the composition exported in layers (layers.json), which the draft is written from (docs/layers.feature LA4b)
raea-app-layers = { path = "../layers" }
-serde_json = "1"
image = { version = "0.25", default-features = false, features = ["jpeg"] }
diff --git a/apps/capcut/src/from_layers.rs b/apps/capcut/src/from_layers.rs
new file mode 100644
index 00000000..6da634d8
--- /dev/null
+++ b/apps/capcut/src/from_layers.rs
@@ -0,0 +1,72 @@
+//! layers.json as a CapCut timeline (docs/layers.feature LA4b): its tracks bottom first, as CapCut lists them (the
+//! first video track is CapCut's main track); footage placed in CapCut's terms (plan::place); a footage clip's own
+//! sound, which layers.json links to it, as the clip's volume (CapCut's Extract audio separates it); every layer's
+//! movie a full-canvas clip. Pure: the export (lib.rs) makes the layers and writes the draft around it.
+
+use std::path::Path;
+
+use raea_app_layers::model::{FileKind, Layer, Layers};
+use raea_io_capcut::{Clip, Kind, Media, MediaKind, Place, Timeline, Track};
+
+use crate::plan;
+
+/// The track names CapCut shows for raea's layers (the overlay's, as the export has always named it).
+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::Footage | Layer::Sound => name.to_string(),
+ }
+}
+
+/// The timeline. `dir` is where layers.json is: its movies' paths are relative to it.
+pub fn timeline(l: &Layers, dir: &Path) -> Timeline {
+ let media: Vec<Media> = l
+ .files
+ .iter()
+ .map(|f| {
+ let p = Path::new(&f.path);
+ Media { path: if p.is_absolute() { p.to_path_buf() } else { dir.join(p) }, kind: if f.kind == FileKind::Audio { MediaKind::Audio } else { MediaKind::Video }, seconds: f.seconds, width: f.width, height: f.height, has_audio: f.has_audio }
+ })
+ .collect();
+ let all = || l.tracks.iter().flat_map(|t| t.clips.iter());
+ // the sound clips a footage clip carries as its own (their ids)
+ let carried: Vec<&str> = all().filter(|c| c.r#box.is_some()).filter_map(|c| c.link.as_deref()).collect();
+ let mut video: Vec<Track> = Vec::new();
+ let mut audio: Vec<Track> = Vec::new();
+ for t in &l.tracks {
+ let clips: Vec<Clip> = t
+ .clips
+ .iter()
+ .filter(|c| !carried.contains(&c.id.as_str()))
+ .map(|c| {
+ let base = Clip { media: c.file, start: c.start, frames: c.frames, source_in: c.source_in, speed: c.speed.max(0.01), ..Clip::default() };
+ match t.layer {
+ Layer::Sound => Clip { volume: 10f64.powf(c.gain_db / 20.0), fade_in: c.fade_in, fade_out: c.fade_out, ..base },
+ Layer::Footage => {
+ let m = &media[c.file];
+ // (a picture stretched to its box is noted by the layers export already, for every editor)
+ let (place, _) = plan::place(&c.r#box.unwrap_or([0.0, 0.0, l.width as f64, l.height as f64]), c.fit.as_deref().unwrap_or("fill"), (m.width as f64).max(1.0), (m.height as f64).max(1.0), l.width as f64, l.height as f64, c.opacity);
+ // its own sound at its gain, or silent: the composition doesn't play its sound there
+ 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 },
+ }
+ })
+ .collect();
+ if clips.is_empty() {
+ continue;
+ }
+ let track = Track { kind: if t.layer == Layer::Sound { Kind::Audio } else { Kind::Video }, name: track_name(t.layer, &t.name), clips };
+ if t.layer == Layer::Sound { audio.push(track) } else { video.push(track) }
+ }
+ // bottom first; CapCut's main track (the first) keeps no name of its own when it's footage
+ video.reverse();
+ if let Some(main) = video.first_mut().filter(|t| t.name.starts_with("footage")) {
+ main.name.clear();
+ }
+ video.extend(audio);
+ Timeline { width: l.width, height: l.height, fps: l.fps, media, tracks: video }
+}
diff --git a/apps/capcut/src/lib.rs b/apps/capcut/src/lib.rs
index 7c5fb436..2dbfcc6a 100644
--- a/apps/capcut/src/lib.rs
+++ b/apps/capcut/src/lib.rs
@@ -1,26 +1,23 @@
-//! `raea export capcut EDIT.tsx` (docs/capcut.feature CC2): the composition as a CapCut draft ready in its timeline.
-//! And `raea render ... -o OUT.mov --alpha` (CC1), the transparent movie its overlays are, for any editor.
-//! Three renders of it: as it is, with its manifest (the reference render, and what shows when: each file's runs,
-//! each sound clip); with its footage and the backgrounds holding it hidden, transparent (what raea draws over the
-//! footage); and with only those backgrounds (what it draws under). The footage and sounds become clips of their own
-//! files at their trims and gains; what raea draws becomes clips of transparent movies (raea-io-alpha), cut where the
-//! drawing comes and goes, the one under the footage left out when it's black; raea-io-capcut writes the draft.
+//! `raea export capcut EDIT.tsx` (docs/capcut.feature CC2, docs/layers.feature LA4b): the composition as a CapCut draft
+//! ready in its timeline. And `raea render ... -o OUT.mov --alpha` (CC1), the transparent movie its overlays are, for
+//! any editor. The composition is exported in layers first (raea-app-layers: the reference render and its manifest,
+//! the graphics, captions and what's under the footage, layers.json); layers.json is then written as CapCut's tracks
+//! (from_layers.rs) and raea-io-capcut writes the draft, with the reference render copied into its folder.
+mod from_layers;
mod media;
pub mod plan;
#[cfg(test)]
mod tests;
use std::path::{Path, PathBuf};
-use std::process::Command;
-use raea_io_capcut::{Clip, Kind, Media, MediaKind, Place, Timeline, Track};
+use raea_io_capcut::Kind;
use raea_runtime_bundle::flag;
-use serde_json::Value;
pub type R<T> = Result<T, String>;
-pub const USAGE: &str = "raea 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)";
+pub const USAGE: &str = "raea 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; the captions on a track of their own above it; into CapCut's projects, entered in its project list while CapCut is closed, or a draft folder in DIR; the reference render copied into the draft's folder, and it and the layers kept in out/capcut/NAME)";
/// `export capcut ...` (or what export takes), and `render ... -o OUT.mov --alpha` through `render`, the CLI's own;
/// None for anything else.
@@ -46,22 +43,6 @@ fn movie(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<R<S
Some(raea_io_alpha::render_movie(args, Path::new(&out), flag(args, "--alpha-codec").as_deref(), flag(args, "--manifest").map(PathBuf::from), quality, render))
}
-/// `raea render ARGS` by this same program, with `env` set; its output said through, its failure the export's.
-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);
- 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(())
-}
-
fn export(args: &[String]) -> R<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}"))?;
@@ -87,102 +68,23 @@ fn export(args: &[String]) -> R<String> {
name = (2..).map(|k| format!("{base} {k}")).find(|n| !root.join(n).exists()).unwrap();
}
let work = dir.join("out/capcut").join(&name);
- std::fs::create_dir_all(&work).map_err(|e| format!("{}: {e}", work.display()))?;
- let comp: Vec<String> = flag(args, "--composition").map(|c| vec!["--composition".into(), c]).unwrap_or_default();
- let s = |p: &Path| p.display().to_string();
-
- // 1. as it is: the reference render and its manifest
- let (reference, manifest_path) = (work.join("reference.mp4"), work.join("render.json"));
- render(&[[s(&tsx), "-o".into(), s(&reference), "--manifest".into(), s(&manifest_path)].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 (wf, hf) = (w as f64, h as f64);
-
- // 2. its footage hidden, transparent: what raea draws over it
- let runs = plan::runs(&manifest, fps);
- let frames = work.join(format!("overlay.{}.frames", std::process::id()));
- let drawn_result = render(&[[s(&tsx), "-o".into(), format!("{}/", frames.display()), "--alpha".into()].as_slice(), &comp].concat(), &[("RAEA_HIDE_MEDIA", "1")]);
- // footage the overlay covers (opaque over most of its box at its middle frame) is drawn over the overlay: what the
- // composition draws under it, a background
- let covered: Vec<bool> = runs.iter().map(|r| drawn_result.is_ok() && opaque_under(&frames, r)).collect();
- let overlay = work.join(format!("overlay.{}.mov", ext_of(codec)));
- let made = drawn_result.and_then(|_| raea_io_alpha::encode_dir(&frames, &overlay, codec, fps, 0.9));
- // the frames folder this export made, and only it
- let _ = std::fs::remove_dir_all(&frames);
- let made = made?;
-
- // 3. only the backgrounds holding the footage: what raea draws under it, unless that's black (CapCut's canvas)
- let under = if runs.is_empty() {
- None
- } else {
- let frames = work.join(format!("under.{}.frames", std::process::id()));
- let out = work.join(format!("under.{}.mov", ext_of(codec)));
- let done = render(&[[s(&tsx), "-o".into(), format!("{}/", frames.display()), "--alpha".into()].as_slice(), &comp].concat(), &[("RAEA_HIDE_MEDIA", "under")])
- .and_then(|_| if lit(&frames) { raea_io_alpha::encode_dir(&frames, &out, codec, fps, 0.9).map(|m| Some((out, m))) } else { Ok(None) });
- let _ = std::fs::remove_dir_all(&frames);
- done?
- };
- // 4. the timeline
- let mut notes: Vec<String> = Vec::new();
- let mut media: Vec<Media> = Vec::new();
- let mut index = std::collections::HashMap::<PathBuf, usize>::new();
- let mut sounds = plan::sounds(&manifest);
- let (mut main, mut rest, mut above) = (Vec::new(), Vec::new(), Vec::new());
- for (r, cov) in runs.iter().zip(&covered) {
- let path = plan::resolve(&dir, &r.src);
- let m = add(&mut media, &mut index, path.clone(), media::video)?;
- let (mw, mh) = (media[m].width as f64, media[m].height as f64);
- let (place, warn) = plan::place(&r.bx, &r.fit, mw.max(1.0), mh.max(1.0), wf, hf, r.opacity);
- let what = format!("{} (frames {}-{})", r.src, r.start, r.end - 1);
- if let Some(wn) = warn {
- notes.push(format!("{what}: {wn}"));
- }
- if r.moved {
- notes.push(format!("{what}: moves or scales in its box; placed as its first frame shows it (CapCut keyframes don't carry yet)"));
- }
- if r.faded {
- notes.push(format!("{what}: fades; placed at its first frame's opacity"));
- }
- // its own sound: the manifest's sound clip of the same file over the same frames from the same time
- let own = sounds.iter().position(|c| plan::resolve(&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 volume = own.map_or(0.0, |k| 10f64.powf(sounds.remove(k).gain_db / 20.0));
- let clip = Clip { media: m, start: r.start, frames: r.end - r.start, source_in: r.at, speed: r.rate.unwrap_or(1.0).max(0.01), volume, place, ..Clip::default() };
- 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 over the overlay, so the overlay's drawing over it is hidden in CapCut"));
- }
- match (*cov, plan::full(&r.bx, wf, hf)) {
- (true, _) => above.push(clip),
- (false, true) => main.push(clip),
- (false, false) => rest.push(clip),
- }
- }
- // the main track first (the clips covering the canvas), the rest above it in the page's order, then the overlay,
- // then footage the overlay draws under
- let mut tracks: Vec<Track> = Vec::new();
- if let Some((path, m)) = &under {
- tracks.extend(drawn(&mut media, path, m, fps, "raea under"));
- }
- tracks.extend(plan::lay(Kind::Video, if under.is_some() { "footage" } else { "" }, main));
- tracks.extend(plan::lay(Kind::Video, "footage", rest));
- tracks.extend(drawn(&mut media, &overlay, &made, fps, "raea overlay"));
- tracks.extend(plan::lay(Kind::Video, "footage over", above));
- let mut audio = Vec::new();
- for c in sounds {
- let m = add(&mut media, &mut index, plan::resolve(&dir, &c.src), media::sound)?;
- audio.push(Clip { media: m, start: c.from, frames: c.to - c.from, source_in: c.at, speed: c.rate, volume: 10f64.powf(c.gain_db / 20.0), fade_in: c.fade_in, fade_out: c.fade_out, ..Clip::default() });
- }
- tracks.extend(plan::lay(Kind::Audio, "sound", audio));
- 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"));
+ // 1. the layers and layers.json (raea export layers), in out/capcut/NAME
+ let mut layer_args = vec![tsx.display().to_string(), "-o".into(), work.display().to_string(), "--name".into(), name.clone(), "--alpha-codec".into(), raea_app_layers::codec_ext(codec).into()];
+ if let Some(c) = flag(args, "--composition") {
+ layer_args.extend(["--composition".into(), c]);
}
- let tl = Timeline { width: w, height: h, fps, media, tracks };
+ let (layers, _) = raea_app_layers::export(&layer_args)?;
+ let reference = work.join(&layers.reference);
- // 5. the draft
+ // 2. its tracks as CapCut's, and the draft
+ let tl = from_layers::timeline(&layers, &work);
+ let mut notes = layers.notes.clone();
let markers = raea_io_capcut::seed(&root);
let written = raea_io_capcut::write(&tl, &root, &name, &markers, media::cover(&reference).as_deref())?;
notes.extend(written.warnings.iter().cloned());
+ // the reference render in the draft's folder, on no track, to set beside what CapCut plays (LA4b)
+ std::fs::copy(&reference, written.dir.join("reference.mp4")).map_err(|e| format!("{}: {e}", written.dir.join("reference.mp4").display()))?;
let listed = if !in_store || args.iter().any(|a| a == "--no-register") {
"not entered in CapCut's project list".to_string()
} else {
@@ -192,17 +94,22 @@ fn export(args: &[String]) -> R<String> {
}
};
let count = |k: Kind, n: &str| tl.tracks.iter().filter(|t| t.kind == k && t.name.starts_with(n)).map(|t| t.clips.len()).sum::<usize>();
+ let bytes = |layer: &str| std::fs::metadata(work.join(format!("{layer}.{}.mov", raea_app_layers::codec_ext(codec)))).map_or(0.0, |m| m.len() as f64 / 1e6);
let mut said = format!(
- "APPLIED CapCut draft \"{name}\" at {}: {} tracks, {}, {} ({}, {:.1} MB){}, {}; {:.2} s at {fps} fps, {w}x{h}; {listed}; markers from {}\n the reference render and the movies raea drew: {}",
+ "APPLIED CapCut draft \"{name}\" at {}: {} tracks, {}, {} ({}, {:.1} MB){}{}, {}; {:.2} s at {} fps, {}x{}; {listed}; markers from {}\n the layers, layers.json and the reference render (also in the draft's folder): {}",
written.dir.display(),
tl.tracks.len(),
many(count(Kind::Video, "") - count(Kind::Video, "raea "), "footage clip"),
many(count(Kind::Video, "raea overlay"), "overlay clip"),
codec.name(),
- made.bytes as f64 / 1e6,
- under.as_ref().map_or(String::new(), |(_, m)| format!(", {} under the footage ({:.1} MB)", many(count(Kind::Video, "raea under"), "clip"), m.bytes as f64 / 1e6)),
+ bytes("graphics"),
+ Some(count(Kind::Video, "raea captions")).filter(|&k| k > 0).map_or(String::new(), |k| format!(", {} ({:.1} MB){}", many(k, "captions clip"), bytes("captions"), layers.srt.as_ref().map_or(String::new(), |s| format!(" and {s}")))),
+ Some(count(Kind::Video, "raea under")).filter(|&k| k > 0).map_or(String::new(), |k| format!(", {} under the footage ({:.1} MB)", many(k, "clip"), bytes("under"))),
many(count(Kind::Audio, ""), "sound"),
written.duration_us as f64 / 1e6,
+ layers.fps,
+ layers.width,
+ layers.height,
markers.from.as_deref().map_or("CapCut 8.5.0 (no draft CapCut made is in the store)".to_string(), |d| format!("the draft \"{d}\" CapCut made")),
work.display()
);
@@ -226,67 +133,3 @@ fn backups() -> PathBuf {
None => raea_io_home::env_path("RAEA_CAPCUT_BACKUPS", ".raea/capcut/backups"),
}
}
-
-/// A movie raea drew, as clips of it wherever it draws, full frame on tracks named `name`; none when it draws nothing.
-fn drawn(media: &mut Vec<Media>, path: &Path, m: &raea_io_alpha::Made, fps: f64, name: &str) -> Vec<Track> {
- let spans = plan::spans(&m.drawn);
- if spans.is_empty() {
- return Vec::new();
- }
- let k = media.len();
- media.push(Media { path: path.to_path_buf(), kind: MediaKind::Video, seconds: m.frames as f64 / fps, width: m.width, height: m.height, has_audio: false });
- let clips = spans.iter().map(|&(a, b)| Clip { media: k, start: a, frames: b - a, source_in: a as f64 / fps, volume: 0.0, place: Place::centred(m.width, m.height), ..Clip::default() }).collect();
- plan::lay(Kind::Video, name, clips)
-}
-
-/// A file's place in the media list, probed the first time it's named.
-fn add(media: &mut Vec<Media>, index: &mut std::collections::HashMap<PathBuf, usize>, p: PathBuf, probe: fn(&Path) -> R<Media>) -> R<usize> {
- if let Some(i) = index.get(&p) {
- return Ok(*i);
- }
- media.push(probe(&p)?);
- index.insert(p, media.len() - 1);
- Ok(media.len() - 1)
-}
-
-fn ext_of(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 overlay is opaque over 90% of a run's box at its middle frame (a grid of points inside it).
-fn opaque_under(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).
-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/capcut/src/media.rs b/apps/capcut/src/media.rs
index 16f7b7c6..44c9d97c 100644
--- a/apps/capcut/src/media.rs
+++ b/apps/capcut/src/media.rs
@@ -1,35 +1,8 @@
-//! The files a draft uses, probed through raea's media backends (a picture's upright size and length, whether it has
-//! sound; a sound's length), and the draft's cover: the reference render's first frame as a small JPEG.
+//! The draft's cover: the reference render's first frame as a small JPEG. (The files a draft uses are probed by the
+//! layers export, raea-app-layers.)
use std::path::Path;
-use raea_io_capcut::{Media, MediaKind};
-
-use crate::R;
-
-/// A video file: its display size (rotation applied) and length from the first backend that opens it, and whether a
-/// short window of its sound decodes to samples.
-pub fn video(path: &Path) -> R<Media> {
- 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(Media { path: path.to_path_buf(), kind: MediaKind::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<Media> {
- let seconds = raea_io_media::probe_seconds(path).ok_or_else(|| format!("{}: no sound length", path.display()))?;
- Ok(Media { path: path.to_path_buf(), kind: MediaKind::Audio, seconds, width: 0, height: 0, has_audio: true })
-}
-
/// The first frame of `video`, at most 540 pixels on its long side, as a JPEG.
pub fn cover(video: &Path) -> Option<Vec<u8>> {
let mut d = raea_io_media::preferred().into_iter().find_map(|b| b.open_video(video).ok())?;
diff --git a/apps/capcut/src/plan.rs b/apps/capcut/src/plan.rs
index 5a5f320f..5cb687ef 100644
--- a/apps/capcut/src/plan.rs
+++ b/apps/capcut/src/plan.rs
@@ -1,12 +1,8 @@
-//! 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.
-//! 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.
+//! Where a picture sits in CapCut's terms (docs/capcut.feature CC2a). The manifest is read by raea-app-layers, the same
+//! for every editor; this is CapCut's own.
-use raea_io_capcut::{Clip, Kind, Place, Track};
-
-pub use raea_app_layers::plan::{Run, Sound, full, resolve, runs, sounds, spans};
+use raea_app_layers::plan::full;
+use raea_io_capcut::Place;
/// 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.
@@ -36,19 +32,3 @@ pub fn place(bx: &[f64; 4], fit: &str, mw: f64, mh: f64, w: f64, h: f64, opacity
};
(Place { x, y, scale, opacity, crop }, warn)
}
-
-/// Clips laid on as few tracks as hold them without overlap, first come first: `kind` tracks named `name`, `name 2`...
-pub fn lay(kind: Kind, name: &str, clips: Vec<Clip>) -> Vec<Track> {
- let mut tracks: Vec<Track> = Vec::new();
- for c in clips {
- let end = |t: &Track| t.clips.last().map_or(i64::MIN, |l| l.start + l.frames);
- match tracks.iter_mut().find(|t| end(t) <= c.start) {
- Some(t) => t.clips.push(c),
- None => {
- let n = tracks.len();
- tracks.push(Track { kind, name: if n == 0 || name.is_empty() { name.to_string() } else { format!("{name} {}", n + 1) }, clips: vec![c] });
- }
- }
- }
- tracks
-}
diff --git a/apps/capcut/src/tests.rs b/apps/capcut/src/tests.rs
index ce5c070f..8dfd3707 100644
--- a/apps/capcut/src/tests.rs
+++ b/apps/capcut/src/tests.rs
@@ -1,50 +1,12 @@
-//! CC2a-c without a render: a manifest's frames as footage runs, its sound clips, the overlay's spans, where a picture
-//! sits in CapCut's terms, and clips laid on tracks.
+//! CC2a without a render: where a picture sits in CapCut's terms, and layers.json as CapCut's tracks (LA4b). The
+//! manifest's runs, sounds and spans are tested where they're read, in raea-app-layers.
-use serde_json::json;
+use std::path::Path;
-use crate::plan::*;
-use raea_io_capcut::{Clip, Kind};
-
-/// 90 frames at 30 fps: one take cut into two pieces (a jump in its source time at frame 45), another file in a
-/// corner from frame 60, moving one pixel at frame 70. Source times in whole milliseconds, as the manifest has them.
-fn manifest() -> serde_json::Value {
- let ms = |t: f64| (t * 1000.0).round() / 1000.0;
- let frames: Vec<_> = (0..90)
- .map(|f| {
- let mut v = vec![json!({"src": "media/a.mp4", "at": ms(if f < 45 { 0.5 + f as f64 / 30.0 } else { 3.0 + (f - 45) as f64 / 30.0 }), "box": [0.0, 0.0, 1080.0, 1920.0], "fit": "cover", "opacity": 1.0})];
- if f >= 60 {
- v.push(json!({"src": "media/pip.mp4", "at": ms((f - 60) as f64 / 15.0), "box": [if f >= 70 { 662.0 } else { 660.0 }, 200.0, 360.0, 360.0], "opacity": 1.0}));
- }
- json!({"frame": f, "videos": v})
- })
- .collect();
- json!({"width": 1080, "height": 1920, "fps": 30.0, "frames": frames, "sounds": {"clips": [{"src": "/m/music.wav", "from": 0, "to": 90, "at": 0.0, "gainDb": -6.0, "fadeOut": 0.5}]}})
-}
-
-#[test]
-fn footage_runs_break_where_the_source_jumps() {
- let r = runs(&manifest(), 30.0);
- assert_eq!(r.iter().map(|r| (r.src.as_str(), r.start, r.end)).collect::<Vec<_>>(), [("media/a.mp4", 0, 45), ("media/a.mp4", 45, 90), ("media/pip.mp4", 60, 90)]);
- assert!((r[1].at - 3.0).abs() < 1e-9);
- assert_eq!((r[0].rate, r[1].rate), (Some(1.0), Some(1.0)), "a take at its own speed, though each step is 33 or 34 ms");
- assert!((r[2].rate.unwrap() - 2.0).abs() < 1e-6, "the corner plays at twice its speed");
- assert!(r[2].moved && !r[0].moved);
- assert_eq!(r[2].fit, "fill");
-}
+use raea_app_layers::model::{self, Clip as LClip, File, FileKind, Layer, Layers, Track as LTrack};
-#[test]
-fn sounds_keep_gain_and_fades() {
- let s = sounds(&manifest());
- assert_eq!(s.len(), 1);
- assert_eq!((s[0].from, s[0].to, s[0].gain_db, s[0].fade_out), (0, 90, -6.0, 0.5));
-}
-
-#[test]
-fn overlay_spans_are_runs_of_drawn_frames() {
- assert_eq!(spans(&[false, true, true, false, false, true]), [(1, 3), (5, 6)]);
- assert!(spans(&[false; 4]).is_empty());
-}
+use crate::from_layers;
+use crate::plan::*;
#[test]
fn pictures_sit_as_their_fit_shows_them() {
@@ -64,22 +26,47 @@ fn pictures_sit_as_their_fit_shows_them() {
}
#[test]
-fn clips_go_on_as_few_tracks_as_hold_them() {
- let c = |start, frames| Clip { start, frames, ..Clip::default() };
- let t = lay(Kind::Audio, "sound", vec![c(0, 90), c(10, 5), c(15, 10), c(90, 5)]);
- assert_eq!(t.iter().map(|t| (t.name.as_str(), t.clips.len())).collect::<Vec<_>>(), [("sound", 2), ("sound 2", 2)]);
-}
-
-/// staticFile("x.mp4") is "/media/x.mp4" in the manifest: the export finds it where the render did, in media/ beside
-/// the edit, as it finds a relative path; an absolute path stays as it is
-#[test]
-fn a_static_file_is_found_in_the_edits_media_folder() {
- let dir = std::env::temp_dir().join(format!("raea-capcut-resolve-{}", std::process::id()));
- std::fs::create_dir_all(dir.join("media")).unwrap();
- std::fs::write(dir.join("media/a.mp4"), "").unwrap();
- let want = dunce::canonicalize(&dir.join("media/a.mp4")).unwrap();
- assert_eq!(resolve(&dir, "/media/a.mp4"), want);
- assert_eq!(resolve(&dir, "media/a.mp4"), want);
- assert_eq!(resolve(&dir, want.to_str().unwrap()), want);
- std::fs::remove_dir_all(&dir).unwrap();
+fn layers_json_goes_bottom_first_with_footage_carrying_its_own_sound() {
+ let file = |path: &str, kind, w, h| File { path: path.into(), kind, seconds: 3.0, width: w, height: h, has_audio: kind == FileKind::Video };
+ let clip = |id: &str, f, start, frames| LClip::new(id.into(), f, start, frames, 0.0);
+ let t = |layer, name: &str, clips| LTrack { layer, name: name.into(), clips };
+ let v1 = LClip { r#box: Some([0.0, 0.0, 1080.0, 1920.0]), fit: Some("cover".into()), link: Some("a1".into()), ..clip("v1", 0, 0, 90) };
+ let a1 = LClip { gain_db: -6.0, link: Some("v1".into()), ..clip("a1", 0, 0, 90) };
+ 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![file("/m/a.mp4", FileKind::Video, 1920, 1080), file("captions.prores.mov", FileKind::Video, 1080, 1920), file("graphics.prores.mov", FileKind::Video, 1080, 1920), file("/m/music.wav", FileKind::Audio, 0, 0)],
+ tracks: vec![
+ t(Layer::Captions, "captions", vec![clip("c1", 1, 10, 30)]),
+ t(Layer::Graphics, "graphics", vec![clip("g1", 2, 0, 90)]),
+ t(Layer::Footage, "footage", vec![v1]),
+ t(Layer::Sound, "sound", vec![a1, LClip { gain_db: -12.0, fade_out: 0.5, ..clip("a2", 3, 0, 90) }]),
+ ],
+ notes: vec![],
+ };
+ let tl = from_layers::timeline(&l, Path::new("/out/edit"));
+ // bottom first: the footage is CapCut's main track (no name), then the overlay, then the captions; sound after
+ assert_eq!(tl.tracks.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["", "raea overlay", "raea captions", "sound"]);
+ // a layer's movie is found beside layers.json; the footage where it is
+ assert_eq!(tl.media[1].path, Path::new("/out/edit/captions.prores.mov"));
+ assert_eq!(tl.media[0].path, Path::new("/m/a.mp4"));
+ // the footage carries its own sound at its gain (-6 dB), so that sound isn't a clip of its own; the music is
+ let foot = &tl.tracks[0].clips[0];
+ assert!((foot.volume - 10f64.powf(-6.0 / 20.0)).abs() < 1e-9);
+ assert_eq!(tl.tracks[3].clips.len(), 1);
+ assert!((tl.tracks[3].clips[0].volume - 10f64.powf(-12.0 / 20.0)).abs() < 1e-9 && tl.tracks[3].clips[0].fade_out == 0.5);
+ // the layers' movies fill the canvas, silent
+ let cap = &tl.tracks[2].clips[0];
+ assert_eq!((cap.start, cap.frames, cap.volume, cap.place.scale, cap.place.x, cap.place.y), (10, 30, 0.0, 1.0, 540.0, 960.0));
+ // footage with no linked sound plays silent
+ let mut quiet = l.clone();
+ quiet.tracks[2].clips[0].link = None;
+ quiet.tracks[3].clips.remove(0);
+ assert_eq!(from_layers::timeline(&quiet, Path::new("/out/edit")).tracks[0].clips[0].volume, 0.0);
}
diff --git a/apps/layers/src/tests.rs b/apps/layers/src/tests.rs
index 817926f5..3393a69d 100644
--- a/apps/layers/src/tests.rs
+++ b/apps/layers/src/tests.rs
@@ -1,6 +1,7 @@
use serde_json::json;
use crate::model::{self, Clip, Layer, Layers};
+use crate::plan::*;
use crate::srt;
fn said(frames: &[&[(&str, bool)]]) -> serde_json::Value {
@@ -59,3 +60,59 @@ fn layers_json_reads_back_as_it_was_written() {
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}");
}
+
+// the manifest read as runs, sounds and spans (moved from apps/capcut, docs/capcut.feature CC2a-c)
+
+/// 90 frames at 30 fps: one take cut into two pieces (a jump in its source time at frame 45), another file in a
+/// corner from frame 60, moving one pixel at frame 70. Source times in whole milliseconds, as the manifest has them.
+fn manifest() -> serde_json::Value {
+ let ms = |t: f64| (t * 1000.0).round() / 1000.0;
+ let frames: Vec<_> = (0..90)
+ .map(|f| {
+ let mut v = vec![json!({"src": "media/a.mp4", "at": ms(if f < 45 { 0.5 + f as f64 / 30.0 } else { 3.0 + (f - 45) as f64 / 30.0 }), "box": [0.0, 0.0, 1080.0, 1920.0], "fit": "cover", "opacity": 1.0})];
+ if f >= 60 {
+ v.push(json!({"src": "media/pip.mp4", "at": ms((f - 60) as f64 / 15.0), "box": [if f >= 70 { 662.0 } else { 660.0 }, 200.0, 360.0, 360.0], "opacity": 1.0}));
+ }
+ json!({"frame": f, "videos": v})
+ })
+ .collect();
+ json!({"width": 1080, "height": 1920, "fps": 30.0, "frames": frames, "sounds": {"clips": [{"src": "/m/music.wav", "from": 0, "to": 90, "at": 0.0, "gainDb": -6.0, "fadeOut": 0.5}]}})
+}
+
+#[test]
+fn footage_runs_break_where_the_source_jumps() {
+ let r = runs(&manifest(), 30.0);
+ assert_eq!(r.iter().map(|r| (r.src.as_str(), r.start, r.end)).collect::<Vec<_>>(), [("media/a.mp4", 0, 45), ("media/a.mp4", 45, 90), ("media/pip.mp4", 60, 90)]);
+ assert!((r[1].at - 3.0).abs() < 1e-9);
+ assert_eq!((r[0].rate, r[1].rate), (Some(1.0), Some(1.0)), "a take at its own speed, though each step is 33 or 34 ms");
+ assert!((r[2].rate.unwrap() - 2.0).abs() < 1e-6, "the corner plays at twice its speed");
+ assert!(r[2].moved && !r[0].moved);
+ assert_eq!(r[2].fit, "fill");
+}
+
+#[test]
+fn sounds_keep_gain_and_fades() {
+ let s = sounds(&manifest());
+ assert_eq!(s.len(), 1);
+ assert_eq!((s[0].from, s[0].to, s[0].gain_db, s[0].fade_out), (0, 90, -6.0, 0.5));
+}
+
+#[test]
+fn overlay_spans_are_runs_of_drawn_frames() {
+ assert_eq!(spans(&[false, true, true, false, false, true]), [(1, 3), (5, 6)]);
+ assert!(spans(&[false; 4]).is_empty());
+}
+
+/// staticFile("x.mp4") is "/media/x.mp4" in the manifest: the export finds it where the render did, in media/ beside
+/// the edit, as it finds a relative path; an absolute path stays as it is
+#[test]
+fn a_static_file_is_found_in_the_edits_media_folder() {
+ let dir = std::env::temp_dir().join(format!("raea-layers-resolve-{}", std::process::id()));
+ std::fs::create_dir_all(dir.join("media")).unwrap();
+ std::fs::write(dir.join("media/a.mp4"), "").unwrap();
+ let want = dunce::canonicalize(dir.join("media/a.mp4")).unwrap();
+ assert_eq!(resolve(&dir, "/media/a.mp4"), want);
+ assert_eq!(resolve(&dir, "media/a.mp4"), want);
+ assert_eq!(resolve(&dir, want.to_str().unwrap()), want);
+ std::fs::remove_dir_all(&dir).unwrap();
+}
diff --git a/docs/layers.feature b/docs/layers.feature
index 3ad98fc0..5007896f 100644
--- a/docs/layers.feature
+++ b/docs/layers.feature
@@ -126,8 +126,13 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for Ca
And it names no editor's format: CapCut's draft and the XML are written from it
Scenario: LA4b. The CapCut export reads it
- Then `raea export capcut` is layers.json written as a CapCut draft, with a captions track above the overlay,
- and apps/capcut's tests pass as before for a composition with no captions
+ Then `raea export capcut` exports the composition in layers into out/capcut/NAME (raea-app-layers) and writes
+ layers.json as a CapCut draft (apps/capcut from_layers.rs): its tracks bottom first, the footage CapCut's main
+ track, then "raea overlay" (the graphics), then "raea captions"; "raea under" below the footage when there is one
+ And a footage clip's linked sound is the clip's own volume, as CapCut keeps a video's sound, which its Extract
+ audio separates; footage with no linked sound is silent
+ And for a composition with no captions the draft is the one it was before, less the 3D, which is now under the
+ footage as raea draws it
And reference.mp4 is copied into the draft's folder, on no track, where CC2d kept it only beside the draft;
every export's folder holds it, so the person can compare what the editor plays with what raea rendered
diff --git a/docs/manual/reference/cli/export.md b/docs/manual/reference/cli/export.md
index d66d23e7..25882f38 100644
--- a/docs/manual/reference/cli/export.md
+++ b/docs/manual/reference/cli/export.md
@@ -23,7 +23,7 @@ CapCut rewrites its project list when it quits, so `raea export capcut` refuses
## Usage
```sh
-raea 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 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; the captions on a track of their own above it; into CapCut's projects, entered in its project list while CapCut is closed, or a draft folder in DIR; the reference render copied into the draft's folder, and it and the layers 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)
```