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 LA5a: `raea export xml` writes an FCP7 XML project for Premiere Pro and DaVinci Resolve (work in progress)

Zachary Guglin230a265b3454
diff --git a/apps/capcut/src/lib.rs b/apps/capcut/src/lib.rs
index 2dbfcc6a..e2b6a1d6 100644
--- a/apps/capcut/src/lib.rs
+++ b/apps/capcut/src/lib.rs
@@ -25,7 +25,7 @@ pub fn cli(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<R
match 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 or layers\nusage: {USAGE}\n {}", other.map_or(String::new(), |o| format!(", not {o:?}")), raea_app_layers::USAGE)),
+ other => Err(format!("raea export takes where to export to{}: capcut, layers or xml\nusage: {USAGE}\n {}\n {}", other.map_or(String::new(), |o| format!(", not {o:?}")), raea_app_layers::USAGE, raea_app_layers::USAGE_XML)),
}),
Some("render") => movie(args, render),
_ => None,
diff --git a/apps/capcut/src/tests.rs b/apps/capcut/src/tests.rs
index 8dfd3707..a3089831 100644
--- a/apps/capcut/src/tests.rs
+++ b/apps/capcut/src/tests.rs
@@ -27,7 +27,7 @@ fn pictures_sit_as_their_fit_shows_them() {
#[test]
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 file = |path: &str, kind, w, h| File { path: path.into(), kind, seconds: 3.0, width: w, height: h, has_audio: kind == FileKind::Video, channels: 2, sample_rate: 48_000 };
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) };
diff --git a/apps/layers/src/lib.rs b/apps/layers/src/lib.rs
index 6f0b89c6..3620eabf 100644
--- a/apps/layers/src/lib.rs
+++ b/apps/layers/src/lib.rs
@@ -14,6 +14,7 @@
pub mod model;
pub mod plan;
pub mod srt;
+pub mod xml;
#[cfg(test)]
mod composite;
#[cfg(test)]
@@ -31,9 +32,47 @@ 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 const USAGE_XML: &str = "raea export xml EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] (the composition as an FCP7 XML project for Premiere Pro (File, Import) and DaVinci Resolve (File, Import, Timeline): its layers as raea export layers writes them, NAME.xml beside them placing them on a timeline, the footage and sounds as clips of their own files where they are, each clip's own sound linked to it; into out/xml/NAME, or DIR)";
+
+/// `export layers ...` and `export xml ...`; 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))
+ if args.first().map(String::as_str) != Some("export") {
+ return None;
+ }
+ match args.get(1).map(String::as_str) {
+ Some("layers") => Some(export(&args[2..]).map(|(_, said)| said)),
+ Some("xml") => Some(export_xml(&args[2..])),
+ _ => None,
+ }
+}
+
+/// `raea export xml`: the layers into DIR (out/xml/NAME unless -o says), then NAME.xml beside them (LA5a).
+fn export_xml(args: &[String]) -> R<String> {
+ let tsx = args.first().filter(|a| !a.starts_with('-')).ok_or(USAGE_XML)?;
+ let edit = dunce::canonicalize(PathBuf::from(tsx)).map_err(|e| format!("{tsx}: {e}"))?;
+ let name = flag(args, "--name").unwrap_or_else(|| edit.file_stem().unwrap().to_string_lossy().into_owned());
+ let dir = flag(args, "-o").map_or_else(|| edit.parent().unwrap().join("out/xml").join(&name), PathBuf::from);
+ let mut layer_args = args.to_vec();
+ if flag(args, "-o").is_none() {
+ layer_args.extend(["-o".into(), dir.display().to_string()]);
+ }
+ let (layers, _) = export(&layer_args)?;
+ let dir = dunce::canonicalize(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ let (text, notes) = xml::write(&layers, &dir);
+ let out = dir.join(format!("{name}.xml"));
+ std::fs::write(&out, text).map_err(|e| format!("{}: {e}", out.display()))?;
+ let count = |l: Layer| layers.tracks.iter().filter(|t| t.layer == l).count();
+ let mut said = format!(
+ "APPLIED FCP7 XML \"{name}\" at {}: {} video tracks, {} audio tracks; import it in Premiere Pro (File, Import) or DaVinci Resolve (File, Import, Timeline); the layers, layers.json{} and the reference render beside it",
+ out.display(),
+ layers.tracks.len() - count(Layer::Sound),
+ count(Layer::Sound),
+ layers.srt.as_ref().map_or(String::new(), |s| format!(", {s} (captions to upload)")),
+ );
+ for n in layers.notes.iter().chain(&notes) {
+ said.push_str(&format!("\n note {n}"));
+ }
+ Ok(said)
}
/// `raea render ARGS` by this same program with only `env`'s layer settings: none of the person's own RAEA_LAYER or
@@ -180,7 +219,7 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {
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 });
+ 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, channels: 2, sample_rate: 48_000 });
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)
@@ -272,8 +311,8 @@ pub fn video(path: &Path) -> R<File> {
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 });
+ let (has_audio, channels, sample_rate) = heard(path);
+ return Ok(File { path: path.display().to_string(), kind: FileKind::Video, seconds: i.duration, width: i.width, height: i.height, has_audio, channels, sample_rate });
}
Err(e) => why.push(format!("{}: {e}", b.name())),
}
@@ -284,7 +323,17 @@ pub fn video(path: &Path) -> R<File> {
/// 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 })
+ let (_, channels, sample_rate) = heard(path);
+ Ok(File { path: path.display().to_string(), kind: FileKind::Audio, seconds, width: 0, height: 0, has_audio: true, channels, sample_rate })
+}
+
+/// Whether a short window of a file's sound decodes to samples, and its channels and sample rate (stereo at 48 kHz
+/// when it has none to read).
+fn heard(path: &Path) -> (bool, u32, u32) {
+ match raea_io_media::decode_audio_window(path, 0.0, 0.05) {
+ Ok(a) if a.len() > 0 => (true, (a.channels.len() as u32).max(1), a.rate),
+ _ => (false, 2, 48_000),
+ }
}
pub fn codec_ext(c: raea_io_alpha::Codec) -> &'static str {
diff --git a/apps/layers/src/model.rs b/apps/layers/src/model.rs
index 7e404eaf..e732736d 100644
--- a/apps/layers/src/model.rs
+++ b/apps/layers/src/model.rs
@@ -43,6 +43,19 @@ pub struct File {
pub height: u32,
/// whether it has sound of its own (footage)
pub has_audio: bool,
+ /// its sound's channels and sample rate, when it has sound (an editor places each channel; Premiere a track each)
+ #[serde(default = "two")]
+ pub channels: u32,
+ #[serde(default = "rate_48k")]
+ pub sample_rate: u32,
+}
+
+fn two() -> u32 {
+ 2
+}
+
+fn rate_48k() -> u32 {
+ 48_000
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
diff --git a/apps/layers/src/tests.rs b/apps/layers/src/tests.rs
index 3393a69d..58f6b792 100644
--- a/apps/layers/src/tests.rs
+++ b/apps/layers/src/tests.rs
@@ -49,7 +49,7 @@ fn layers_json_reads_back_as_it_was_written() {
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 }],
+ files: vec![model::File { path: "/m/clip.mp4".into(), kind: model::FileKind::Video, seconds: 3.0, width: 640, height: 360, has_audio: true, channels: 2, sample_rate: 48_000 }],
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![],
};
@@ -116,3 +116,73 @@ fn a_static_file_is_found_in_the_edits_media_folder() {
assert_eq!(resolve(&dir, want.to_str().unwrap()), want);
std::fs::remove_dir_all(&dir).unwrap();
}
+
+// the FCP7 XML (docs/layers.feature LA5a)
+
+#[test]
+fn a_picture_in_picture_sits_as_raea_drew_it_in_basic_motions_terms() {
+ use crate::xml::motion;
+ // C (1280x720) contained in a 380x225 box at (850, 50) on a 1280x720 sequence: scaled to 380/1280, its centre
+ // right of and above the frame's, nothing cut
+ let (scale, centre, crop, note) = motion([850.0, 50.0, 380.0, 225.0], "contain", 1280.0, 720.0, 1280.0, 720.0);
+ assert!((scale - 380.0 / 1280.0 * 100.0).abs() < 1e-9 && note.is_none());
+ assert!((centre[0] - (1040.0 - 640.0) / 1280.0).abs() < 1e-9 && (centre[1] - (162.5 - 360.0) / 720.0).abs() < 1e-9);
+ assert_eq!(crop, [0.0; 4]);
+ // a landscape take covering a portrait frame: scaled to fill its height, its sides cut evenly
+ let (scale, centre, crop, _) = motion([0.0, 0.0, 1080.0, 1920.0], "cover", 1920.0, 1080.0, 1080.0, 1920.0);
+ assert!((scale - 1920.0 / 1080.0 * 100.0).abs() < 1e-9 && centre == [0.0, 0.0]);
+ assert!((crop[0] - (3413.333_333 - 1080.0) / 2.0 / 3413.333_333 * 100.0).abs() < 1e-3 && crop[0] == crop[1] && crop[2] == 0.0);
+ // stretched in raea: fitted inside, and said
+ assert!(motion([0.0, 0.0, 500.0, 100.0], "fill", 640.0, 640.0, 1080.0, 1920.0).3.is_some());
+}
+
+#[test]
+fn the_xml_has_the_tracks_bottom_first_and_footage_linked_to_its_sound() {
+ use crate::model::{File, FileKind, Track};
+ let file = |path: &str, kind, w, h, a| File { path: path.into(), kind, seconds: 10.0, width: w, height: h, has_audio: a, channels: 2, sample_rate: 48_000 };
+ let c = |id: &str, f, start, frames, at| Clip::new(id.into(), f, start, frames, at);
+ let v1 = Clip { r#box: Some([0.0, 0.0, 1280.0, 720.0]), fit: Some("cover".into()), link: Some("a1".into()), ..c("v1", 0, 0, 90, 1.0) };
+ let v2 = Clip { r#box: Some([0.0, 0.0, 1280.0, 720.0]), fit: Some("cover".into()), ..c("v2", 0, 90, 30, 5.0) };
+ let a1 = Clip { link: Some("v1".into()), ..c("a1", 0, 0, 90, 1.0) };
+ let l = Layers {
+ version: model::VERSION,
+ name: "edit & co".into(),
+ width: 1280,
+ height: 720,
+ fps: 29.97,
+ frames: 120,
+ reference: "reference.mp4".into(),
+ srt: None,
+ files: vec![file("/m/my clip.mp4", FileKind::Video, 1280, 720, true), file("graphics.prores.mov", FileKind::Video, 1280, 720, false), file("/m/music.wav", FileKind::Audio, 0, 0, true)],
+ tracks: vec![
+ Track { layer: Layer::Graphics, name: "graphics".into(), clips: vec![c("g1", 1, 30, 60, 1.0)] },
+ Track { layer: Layer::Footage, name: "footage".into(), clips: vec![v1, v2] },
+ Track { layer: Layer::Sound, name: "sound".into(), clips: vec![a1, Clip { gain_db: -12.0, ..c("a2", 2, 0, 120, 0.0) }] },
+ ],
+ notes: vec![],
+ };
+ let (x, notes) = crate::xml::write(&l, std::path::Path::new("/out/xml/edit"));
+ assert!(notes.is_empty(), "{notes:?}");
+ // 29.97 is a timebase of 30, NTSC; the name escaped
+ assert!(x.contains("<name>edit &amp; co</name><duration>120</duration><rate><timebase>30</timebase><ntsc>TRUE</ntsc></rate>"), "{x}");
+ // video tracks bottom first: the footage (v1 from 30 source frames in, v2 from 150), then the graphics
+ let footage = x.find("<clipitem id=\"v1\"").unwrap();
+ assert!(footage < x.find("<clipitem id=\"g1\"").unwrap());
+ assert!(x.contains("<start>0</start><end>90</end><in>30</in><out>120</out>") && x.contains("<start>90</start><end>120</end><in>150</in><out>180</out>"), "{x}");
+ // a file in full once (its path percent-encoded), by id after
+ assert_eq!(x.matches("<pathurl>file://localhost/m/my%20clip.mp4</pathurl>").count(), 1);
+ assert!(x.contains("<file id=\"file-1\"/>"));
+ // the graphics' movie found beside the XML, its alpha straight
+ assert!(x.contains("<pathurl>file://localhost/out/xml/edit/graphics.prores.mov</pathurl>") && x.contains("<alphatype>straight</alphatype>"));
+ // v1 and its sound's two channels (each a mono clipitem on a track of its own, as Premiere writes a stereo clip)
+ // linked together, in each of the three; v2 has no sound placed
+ let link = "<link><linkclipref>v1</linkclipref><mediatype>video</mediatype><trackindex>1</trackindex><clipindex>1</clipindex></link><link><linkclipref>a1</linkclipref><mediatype>audio</mediatype><trackindex>1</trackindex><clipindex>1</clipindex></link><link><linkclipref>a1-2</linkclipref><mediatype>audio</mediatype><trackindex>2</trackindex><clipindex>1</clipindex></link>";
+ assert_eq!(x.matches(link).count(), 3, "{x}");
+ assert!(x.contains("<clipitem id=\"a1-2\" premiereChannelType=\"mono\"><masterclipid>masterclip-1</masterclipid>"), "{x}");
+ assert!(x.contains("<sourcetrack><mediatype>audio</mediatype><trackindex>2</trackindex></sourcetrack>"));
+ // the file's sound as its two channels, left and right; the two tracks to output channels 1 and 2
+ assert!(x.contains("<channelcount>1</channelcount><layout>stereo</layout><audiochannel><sourcechannel>2</sourcechannel><channellabel>right</channellabel></audiochannel>"));
+ assert!(x.contains("<outputchannelindex>1</outputchannelindex></track>") && x.contains("<outputchannelindex>2</outputchannelindex></track>"));
+ // the music at -12 dB as Audio Levels' linear gain
+ assert!(x.contains("<parameterid>level</parameterid><name>Level</name><valuemin>0.00003162</valuemin><valuemax>31.6228</valuemax><value>0.251189</value>"), "{x}");
+}
diff --git a/apps/layers/src/xml.rs b/apps/layers/src/xml.rs
new file mode 100644
index 00000000..c30b1bda
--- /dev/null
+++ b/apps/layers/src/xml.rs
@@ -0,0 +1,249 @@
+//! layers.json as an FCP7 XML project (xmeml version 5, docs/layers.feature LA5a), which Premiere Pro (File, Import)
+//! and DaVinci Resolve (File, Import, Timeline) both read: one sequence at the composition's rate and size, its video
+//! tracks bottom first (under, the footage, what's behind a picture in picture, the pictures in picture, graphics,
+//! captions), its audio tracks below. Footage points at its file where it is, placed as raea drew it (Basic Motion's
+//! scale and centre, a Crop where object-fit: cover cuts it, its Opacity); a footage clip and its own sound are linked
+//! clipitems, which Premiere's Unlink and Resolve's Link Clips separate. Sound is laid out as Premiere writes it (read
+//! from an XML Premiere Pro 2026 exported): a stereo file's channels each a mono clipitem on a track of its own. A layer's movie fills the frame, its alpha
+//! straight. Pure: the export (lib.rs) makes the layers and writes this beside them.
+
+use std::fmt::Write as _;
+use std::path::Path;
+
+use crate::model::{Clip, FileKind, Layer, Layers};
+
+/// xmeml's rate: a whole timebase and whether it runs at 1000/1001 of it (29.97 is 30 NTSC).
+fn rate(fps: f64) -> (u32, bool) {
+ let base = fps.round().max(1.0);
+ (base as u32, (fps - base).abs() > 0.001 && (fps * 1001.0 / 1000.0 - base).abs() < 0.01)
+}
+
+fn rate_xml(fps: f64) -> String {
+ let (tb, ntsc) = rate(fps);
+ format!("<rate><timebase>{tb}</timebase><ntsc>{}</ntsc></rate>", if ntsc { "TRUE" } else { "FALSE" })
+}
+
+/// A timecode from 0, as Premiere gives a sequence and every file.
+fn timecode(fps: f64) -> String {
+ let drop = rate(fps).1;
+ format!("<timecode>{}<string>{}</string><frame>0</frame><displayformat>{}</displayformat></timecode>", rate_xml(fps), if drop { "00;00;00;00" } else { "00:00:00:00" }, if drop { "DF" } else { "NDF" })
+}
+
+/// A UUID-shaped id for the sequence, the same for the same name (FNV-1a over it, twice).
+fn uuid(name: &str) -> String {
+ let h = |seed: u64| name.bytes().fold(seed, |k, b| (k ^ b as u64).wrapping_mul(0x100_0000_01b3));
+ let (a, b) = (h(0xcbf2_9ce4_8422_2325), h(0x8422_2325_cbf2_9ce4));
+ format!("{:08x}-{:04x}-4{:03x}-8{:03x}-{:012x}", a >> 32, (a >> 16) & 0xffff, a & 0xfff, (b >> 52) & 0xfff, b & 0xffff_ffff_ffff)
+}
+
+fn esc(s: &str) -> String {
+ s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
+}
+
+/// A file's path as xmeml's pathurl: file://localhost and the absolute path, each byte outside the unreserved set
+/// percent-encoded.
+fn pathurl(p: &Path) -> String {
+ let mut out = String::from("file://localhost");
+ for b in p.to_string_lossy().bytes() {
+ if b.is_ascii_alphanumeric() || b"/-_.~".contains(&b) {
+ out.push(b as char);
+ } else {
+ let _ = write!(out, "%{b:02X}");
+ }
+ }
+ out
+}
+
+/// Where a picture of `mw` x `mh` sits in `bx` with CSS's object-fit `fit`, in Basic Motion's terms on a `w` x `h`
+/// sequence: its scale (100: the media's own pixels), its centre (0, 0: the frame's; a unit is the frame's width or
+/// height) and what Crop cuts from each side (percent of the media: left, right, top, bottom); and a note when it
+/// can't be shown so (a stretched picture).
+pub fn motion(bx: [f64; 4], fit: &str, mw: f64, mh: f64, w: f64, h: f64) -> (f64, [f64; 2], [f64; 4], Option<String>) {
+ let [x, y, bw, bh] = bx;
+ let (sx, sy) = (bw / mw, bh / mh);
+ let mut note = None;
+ let s = match fit {
+ "cover" => sx.max(sy),
+ "none" => 1.0,
+ "scale-down" => sx.min(sy).min(1.0),
+ "contain" => sx.min(sy),
+ _ => {
+ if (sx - sy).abs() > 0.01 * sx.max(sy) {
+ note = Some(format!("stretched to its {bw:.0}x{bh:.0} box (object-fit: fill); fitted inside it"));
+ }
+ sx.min(sy)
+ }
+ };
+ // what's drawn past its box is cut, each side by the share of the scaled picture that overhangs it
+ let (dw, dh) = (mw * s, mh * s);
+ let cut = |d: f64, b: f64| ((d - b) / 2.0 / d * 100.0).max(0.0);
+ let (cx, cy) = (cut(dw, bw), cut(dh, bh));
+ let centre = [(x + bw / 2.0 - w / 2.0) / w, (y + bh / 2.0 - h / 2.0) / h];
+ (s * 100.0, centre, [cx, cx, cy, cy], note)
+}
+
+fn param(id: &str, name: &str, min: f64, max: f64, value: &str) -> String {
+ format!("<parameter><parameterid>{id}</parameterid><name>{name}</name><valuemin>{min}</valuemin><valuemax>{max}</valuemax><value>{value}</value></parameter>")
+}
+
+fn effect(name: &str, id: &str, category: &str, kind: &str, media: &str, params: &str) -> String {
+ format!("<filter><effect><name>{name}</name><effectid>{id}</effectid><effectcategory>{category}</effectcategory><effecttype>{kind}</effecttype><mediatype>{media}</mediatype>{params}</effect></filter>")
+}
+
+/// The XML, and what it can't carry. `dir` is where layers.json is: its movies' paths are relative to it.
+pub fn write(l: &Layers, dir: &Path) -> (String, Vec<String>) {
+ let mut notes = Vec::new();
+ let fps = l.fps;
+ let frames = |secs: f64| (secs * fps).round() as i64;
+ let path = |k: usize| {
+ let p = Path::new(&l.files[k].path);
+ if p.is_absolute() { p.to_path_buf() } else { dir.join(p) }
+ };
+ let name_of = |k: usize| path(k).file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());
+
+ // the tracks bottom first, xmeml's order; sounds apart, each sound track as one mono track a channel, as Premiere
+ // writes a stereo clip: its left channel on one track, its right on the next, two clipitems linked
+ let video: Vec<_> = l.tracks.iter().rev().filter(|t| t.layer != Layer::Sound).collect();
+ let audio: Vec<_> = l.tracks.iter().filter(|t| t.layer == Layer::Sound).collect();
+ let channels = |c: &Clip| l.files[c.file].channels.clamp(1, 2) as usize;
+ let mut mono: Vec<Vec<(String, &Clip, usize)>> = Vec::new();
+ for t in &audio {
+ let base = mono.len();
+ mono.resize_with(base + t.clips.iter().map(channels).max().unwrap_or(1), Vec::new);
+ for c in &t.clips {
+ for ch in 1..=channels(c) {
+ mono[base + ch - 1].push((if ch == 1 { c.id.clone() } else { format!("{}-{ch}", c.id) }, c, ch));
+ }
+ }
+ }
+ // each clipitem's place: (video?, track index from 1, clip index from 1), for links
+ let mut at: std::collections::HashMap<String, (bool, usize, usize)> = std::collections::HashMap::new();
+ for (ti, t) in video.iter().enumerate() {
+ for (ci, c) in t.clips.iter().enumerate() {
+ at.insert(c.id.clone(), (true, ti + 1, ci + 1));
+ }
+ }
+ for (ti, m) in mono.iter().enumerate() {
+ for (ci, (id, _, _)) in m.iter().enumerate() {
+ at.insert(id.clone(), (false, ti + 1, ci + 1));
+ }
+ }
+ let by_id: std::collections::HashMap<&str, &Clip> = l.tracks.iter().flat_map(|t| t.clips.iter()).map(|c| (c.id.as_str(), c)).collect();
+ // a clip's clipitems: footage's one, a sound's one a channel
+ let items = |c: &Clip| -> Vec<String> { std::iter::once(c.id.clone()).chain((2..=2).map(|ch| format!("{}-{ch}", c.id))).filter(|id| at.contains_key(id)).collect() };
+ // every clipitem of a clip and of the clip it's linked to, linked together (the video first), as Premiere links them
+ let links = |c: &Clip| -> String {
+ let mut all = items(c);
+ if let Some(other) = c.link.as_deref().and_then(|o| by_id.get(o)) {
+ all.extend(items(other));
+ }
+ if all.len() < 2 {
+ return String::new();
+ }
+ all.sort_by_key(|id| (!at[id].0, at[id].1));
+ all.iter()
+ .map(|id| {
+ let (v, ti, ci) = at[id];
+ format!("<link><linkclipref>{id}</linkclipref><mediatype>{}</mediatype><trackindex>{ti}</trackindex><clipindex>{ci}</clipindex></link>", if v { "video" } else { "audio" })
+ })
+ .collect()
+ };
+ // a file is described in full the first time a clip names it, by its id after; its sound a channel at a time
+ let mut described = std::collections::HashSet::new();
+ let mut file = |k: usize| -> String {
+ let id = format!("file-{}", k + 1);
+ if !described.insert(k) {
+ return format!("<file id=\"{id}\"/>");
+ }
+ let f = &l.files[k];
+ let mut media = String::new();
+ if f.kind == FileKind::Video {
+ let _ = write!(media, "<video><samplecharacteristics>{}<width>{}</width><height>{}</height></samplecharacteristics></video>", rate_xml(fps), f.width, f.height);
+ }
+ if f.has_audio {
+ let n = f.channels.clamp(1, 2);
+ for ch in 1..=n {
+ let label = match (n, ch) {
+ (1, _) => "mono",
+ (_, 1) => "left",
+ _ => "right",
+ };
+ let _ = write!(media, "<audio><samplecharacteristics><depth>16</depth><samplerate>{}</samplerate></samplecharacteristics><channelcount>1</channelcount><layout>{}</layout><audiochannel><sourcechannel>{ch}</sourcechannel><channellabel>{label}</channellabel></audiochannel></audio>", f.sample_rate, if n == 1 { "mono" } else { "stereo" });
+ }
+ }
+ format!("<file id=\"{id}\"><name>{}</name><pathurl>{}</pathurl>{}<duration>{}</duration>{}<media>{media}</media></file>", esc(&name_of(k)), pathurl(&path(k)), rate_xml(fps), frames(f.seconds), timecode(fps))
+ };
+ let clipitem = |id: &str, attrs: &str, c: &Clip, body: &str, file: String| -> String {
+ let src_in = frames(c.source_in);
+ format!(
+ "<clipitem id=\"{id}\"{attrs}><masterclipid>masterclip-{}</masterclipid><name>{}</name><enabled>TRUE</enabled><duration>{}</duration>{}<start>{}</start><end>{}</end><in>{src_in}</in><out>{}</out>{file}{body}{}</clipitem>",
+ c.file + 1,
+ esc(&name_of(c.file)),
+ frames(l.files[c.file].seconds),
+ rate_xml(fps),
+ c.start,
+ c.end(),
+ src_in + (c.frames as f64 * c.speed).round() as i64,
+ links(c)
+ )
+ };
+
+ let mut v = String::new();
+ for t in &video {
+ let _ = write!(v, "<track>");
+ for c in &t.clips {
+ let mut body = String::new();
+ if (c.speed - 1.0).abs() > 0.001 {
+ notes.push(format!("{} (frames {}-{}): plays at {:.2}x in raea; placed at its own speed", name_of(c.file), c.start, c.end() - 1, c.speed));
+ }
+ match (t.layer, c.r#box) {
+ (Layer::Footage, Some(bx)) => {
+ let f = &l.files[c.file];
+ let (scale, centre, crop, note) = motion(bx, c.fit.as_deref().unwrap_or("fill"), f.width.max(1) as f64, f.height.max(1) as f64, l.width as f64, l.height as f64);
+ if let Some(n) = note {
+ notes.push(format!("{} (frames {}-{}): {n}", name_of(c.file), c.start, c.end() - 1));
+ }
+ body.push_str(&effect("Basic Motion", "basic", "motion", "motion", "video", &format!("{}{}", param("scale", "Scale", 0.0, 1000.0, &format!("{scale:.4}")), format!("<parameter><parameterid>center</parameterid><name>Center</name><value><horiz>{:.6}</horiz><vert>{:.6}</vert></value></parameter>", centre[0], centre[1]))));
+ if crop.iter().any(|&k| k > 0.001) {
+ body.push_str(&effect("Crop", "crop", "motion", "motion", "video", &["left", "right", "top", "bottom"].iter().zip(crop).map(|(side, k)| param(side, &format!("{}{}", side[..1].to_uppercase(), &side[1..]), 0.0, 100.0, &format!("{k:.4}"))).collect::<String>()));
+ }
+ if c.opacity < 0.999 {
+ body.push_str(&effect("Opacity", "opacity", "motion", "motion", "video", &param("opacity", "Opacity", 0.0, 100.0, &format!("{:.2}", c.opacity * 100.0))));
+ }
+ }
+ // a layer's movie fills the frame, its alpha straight
+ _ => body.push_str("<alphatype>straight</alphatype>"),
+ }
+ let _ = write!(v, "{}", clipitem(&c.id, "", c, &body, file(c.file)));
+ }
+ let _ = write!(v, "<enabled>TRUE</enabled><locked>FALSE</locked></track>");
+ }
+ let mut a = String::new();
+ for (ti, m) in mono.iter().enumerate() {
+ // a stereo pair's left track goes to output channel 1, its right to 2
+ let out = if mono.get(ti + 1).is_some_and(|n| n.iter().any(|(_, _, ch)| *ch == 2)) || m.iter().any(|(_, _, ch)| *ch == 2) { format!("<outputchannelindex>{}</outputchannelindex>", if m.iter().any(|(_, _, ch)| *ch == 2) { 2 } else { 1 }) } else { String::new() };
+ let _ = write!(a, "<track currentExplodedTrackIndex=\"0\" totalExplodedTrackCount=\"1\" premiereTrackType=\"Mono\">");
+ for (id, c, ch) in m {
+ let gain = 10f64.powf(c.gain_db / 20.0);
+ let mut body = format!("<sourcetrack><mediatype>audio</mediatype><trackindex>{ch}</trackindex></sourcetrack>");
+ if (gain - 1.0).abs() > 1e-6 {
+ body.push_str(&effect("Audio Levels", "audiolevels", "audiolevels", "audiolevels", "audio", &param("level", "Level", 0.00003162, 31.6228, &format!("{gain:.6}"))));
+ }
+ if *ch == 1 && (c.fade_in > 0.0 || c.fade_out > 0.0) {
+ notes.push(format!("{} (frames {}-{}): its fades ({:.2} s in, {:.2} s out) aren't carried; set them in the editor", name_of(c.file), c.start, c.end() - 1, c.fade_in, c.fade_out));
+ }
+ let _ = write!(a, "{}", clipitem(id, " premiereChannelType=\"mono\"", c, &body, file(c.file)));
+ }
+ let _ = write!(a, "<enabled>TRUE</enabled><locked>FALSE</locked>{out}</track>");
+ }
+ let format = format!("<format><samplecharacteristics>{}<width>{}</width><height>{}</height><pixelaspectratio>square</pixelaspectratio><anamorphic>FALSE</anamorphic><fielddominance>none</fielddominance></samplecharacteristics></format>", rate_xml(fps), l.width, l.height);
+ let xml = format!(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE xmeml>\n<xmeml version=\"5\"><sequence id=\"sequence-1\" explodedTracks=\"true\"><uuid>{}</uuid><name>{}</name><duration>{}</duration>{}{}<media><video>{format}{v}</video><audio><numOutputChannels>2</numOutputChannels><format><samplecharacteristics><depth>16</depth><samplerate>48000</samplerate></samplecharacteristics></format><outputs><group><index>1</index><numchannels>1</numchannels><downmix>0</downmix><channel><index>1</index></channel></group><group><index>2</index><numchannels>1</numchannels><downmix>0</downmix><channel><index>2</index></channel></group></outputs>{a}</audio></media></sequence></xmeml>\n",
+ uuid(&l.name),
+ esc(&l.name),
+ l.frames,
+ rate_xml(fps),
+ timecode(fps),
+ );
+ (xml, notes)
+}
diff --git a/docs/manual/reference/cli/export.md b/docs/manual/reference/cli/export.md
index 25882f38..bd0c9cf5 100644
--- a/docs/manual/reference/cli/export.md
+++ b/docs/manual/reference/cli/export.md
@@ -25,6 +25,7 @@ CapCut rewrites its project list when it quits, so `raea export capcut` refuses
```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; 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)
+raea export xml EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] (the composition as an FCP7 XML project for Premiere Pro (File, Import) and DaVinci Resolve (File, Import, Timeline): its layers as raea export layers writes them, NAME.xml beside them placing them on a timeline, the footage and sounds as clips of their own files where they are, each clip's own sound linked to it; into out/xml/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/src/cli.rs b/engine/cli/src/cli.rs
index eb21ab86..8ed11c6a 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 library
let 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, 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 (export_game, capcut, layers, xml, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, raea_app_layers::USAGE, raea_app_layers::USAGE_XML, 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 {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)"));
+ 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 {xml}\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,7 +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)
+ // `export layers EDIT.tsx` (the composition as its layers and layers.json, every editor's export's) and `export xml
+ // EDIT.tsx` (an FCP7 XML project for Premiere Pro and DaVinci Resolve): 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/capcut
if let Some(done) = raea_app_capcut::cli(args, |a| raea_app_sound::render(a).unwrap_or_else(|| raea_runtime_export::render(a))) { return done; }