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.

CC1, CC2: `raea render -o OUT.mov --alpha` writes a transparent movie natively, and `raea export capcut EDIT.tsx` writes the composition as a CapCut draft ready in its timeline (docs/capcut.feature)

shinyobjectz07cd85e6636b
diff --git a/Cargo.lock b/Cargo.lock
index 83a43f9d..34c511df 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -13597,6 +13597,19 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "019b4b213425016d7d84a153c4c73afb0946fbb4840e4eece7ba8848b9d6da22"
+[[package]]
+name = "raea-app-capcut"
+version = "0.1.0"
+dependencies = [
+ "image",
+ "raea-io-alpha",
+ "raea-io-capcut",
+ "raea-io-home",
+ "raea-io-media",
+ "raea-runtime-bundle",
+ "serde_json",
+]
+
[[package]]
name = "raea-app-check"
version = "0.1.0"
@@ -13998,6 +14011,7 @@ name = "raea-cli"
version = "0.1.0"
dependencies = [
"bevy",
+ "raea-app-capcut",
"raea-app-check",
"raea-app-ci",
"raea-app-direction",
@@ -14184,6 +14198,24 @@ dependencies = [
"wgpu",
]
+[[package]]
+name = "raea-io-alpha"
+version = "0.1.0"
+dependencies = [
+ "block2 0.6.2",
+ "image",
+ "objc2 0.6.5",
+ "objc2-av-foundation",
+ "objc2-core-foundation",
+ "objc2-core-media",
+ "objc2-core-video",
+ "objc2-foundation 0.3.2",
+ "objc2-video-toolbox",
+ "png 0.17.16",
+ "raea-io-apple",
+ "serde_json",
+]
+
[[package]]
name = "raea-io-apple"
version = "0.1.0"
@@ -14243,6 +14275,13 @@ dependencies = [
"rav1e",
]
+[[package]]
+name = "raea-io-capcut"
+version = "0.1.0"
+dependencies = [
+ "serde_json",
+]
+
[[package]]
name = "raea-io-codec"
version = "0.1.0"
@@ -14863,6 +14902,7 @@ dependencies = [
"raea-core-review",
"raea-core-scene",
"raea-gpu-device",
+ "raea-io-alpha",
"raea-io-assets",
"raea-io-media",
"raea-io-net",
diff --git a/Cargo.toml b/Cargo.toml
index 7bde0598..aa26b538 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -68,6 +68,8 @@ members = [
"io/ffmpeg",
"io/apple",
"io/apple-coding",
+ "io/alpha",
+ "io/capcut",
"io/shell",
"gpu/device",
"core/k",
@@ -166,6 +168,7 @@ members = [
"apps/media",
"apps/targets",
"apps/game",
+ "apps/capcut",
"apps/play",
"tools/sdk-props",
]
diff --git a/apps/capcut/Cargo.toml b/apps/capcut/Cargo.toml
new file mode 100644
index 00000000..29ae4bc7
--- /dev/null
+++ b/apps/capcut/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "raea-app-capcut"
+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)"
+
+[dependencies]
+raea-runtime-bundle = { path = "../../runtime/bundle" }
+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" }
+serde_json = "1"
+image = { version = "0.25", default-features = false, features = ["jpeg"] }
diff --git a/apps/capcut/src/lib.rs b/apps/capcut/src/lib.rs
new file mode 100644
index 00000000..03febc31
--- /dev/null
+++ b/apps/capcut/src/lib.rs
@@ -0,0 +1,278 @@
+//! `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.
+
+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_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)";
+
+/// `export capcut ...` (or what export takes), and `render ... -o OUT.mov --alpha` through `render`, the CLI's own;
+/// None for anything else.
+pub fn cli(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<R<String>> {
+ 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\nusage: {USAGE}", other.map_or(String::new(), |o| format!(", not {o:?}")))),
+ }),
+ Some("render") => movie(args, render),
+ _ => None,
+ }
+}
+
+/// `render ... -o OUT.mov --alpha`: the frames as transparent PNGs, then one movie of them, the overlay an editor lays
+/// over footage (raea-io-alpha, docs/capcut.feature CC1); None for any other render.
+fn movie(args: &[String], render: impl Fn(&[String]) -> R<String>) -> Option<R<String>> {
+ let out = flag(args, "-o").filter(|o| args.iter().any(|a| a == "--alpha") && o.to_lowercase().ends_with(".mov"))?;
+ let quality = match flag(args, "--quality").map(|q| raea_io_media::parse_quality(&q)).transpose() {
+ Ok(q) => q.unwrap_or(0.9),
+ Err(e) => return Some(Err(e.to_string())),
+ };
+ 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 = PathBuf::from(tsx).canonicalize().map_err(|e| format!("{tsx}: {e}"))?;
+ let dir = tsx.parent().unwrap().to_path_buf();
+ let codec = flag(args, "--alpha-codec").map_or(Ok(raea_io_alpha::Codec::default_here()), |c| raea_io_alpha::Codec::parse(&c))?;
+ let (root, in_store) = match flag(args, "-o") {
+ Some(o) => (PathBuf::from(o), false),
+ None => {
+ let s = raea_io_capcut::store_root().ok_or("CapCut keeps its projects only on a Mac or Windows: -o DIR writes the draft folder anywhere")?;
+ if !s.parent().is_some_and(Path::exists) {
+ return Err(format!("CapCut hasn't kept a project on this machine ({} isn't there): open CapCut once, or write the draft folder with -o DIR", s.display()));
+ }
+ if !args.iter().any(|a| a == "--no-register") && raea_io_capcut::capcut_running() {
+ return Err("CapCut is open: it rewrites its project list when it quits, which would drop the new draft from it. Quit CapCut and export again, or pass --no-register (the draft lands in its folder, unlisted) or -o DIR".into());
+ }
+ (s, true)
+ }
+ };
+ let stem = tsx.file_stem().unwrap().to_string_lossy().into_owned();
+ let mut name = flag(args, "--name").unwrap_or(stem);
+ if root.join(&name).exists() {
+ let base = name.clone();
+ 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"));
+ }
+ let tl = Timeline { width: w, height: h, fps, media, tracks };
+
+ // 5. the draft
+ 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());
+ let listed = if !in_store || args.iter().any(|a| a == "--no-register") {
+ "not entered in CapCut's project list".to_string()
+ } else {
+ let backups = raea_io_home::home().join("capcut/backups");
+ match raea_io_capcut::register(&root, &written.dir, &written.meta, written.info_bytes, &backups) {
+ Ok(b) => format!("entered in CapCut's project list (its list before: {})", b.display()),
+ Err(e) => format!("not entered in CapCut's project list: {e}"),
+ }
+ };
+ 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 mut said = format!(
+ "APPLIED CapCut draft \"{name}\" at {}: {} tracks, {} footage clips, {} overlay clips ({}, {:.1} MB){}, {} sounds; {:.2} s at {fps} fps, {w}x{h}; {listed}; markers from {}\n the reference render and the movies raea drew: {}",
+ written.dir.display(),
+ tl.tracks.len(),
+ count(Kind::Video, "") - count(Kind::Video, "raea "),
+ count(Kind::Video, "raea overlay"),
+ codec.name(),
+ made.bytes as f64 / 1e6,
+ under.as_ref().map_or(String::new(), |(_, m)| format!(", {} clips under the footage ({:.1} MB)", count(Kind::Video, "raea under"), m.bytes as f64 / 1e6)),
+ count(Kind::Audio, ""),
+ written.duration_us as f64 / 1e6,
+ 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()
+ );
+ for n in notes {
+ said.push_str(&format!("\n note {n}"));
+ }
+ Ok(said)
+}
+
+/// 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
new file mode 100644
index 00000000..16f7b7c6
--- /dev/null
+++ b/apps/capcut/src/media.rs
@@ -0,0 +1,50 @@
+//! 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.
+
+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())?;
+ let f = d.frame_at(0.0).ok()?;
+ let (w, h) = (f.width as usize, f.height as usize);
+ let step = (w.max(h)).div_ceil(540).max(1);
+ let (tw, th) = (w / step, h / step);
+ let mut rgb = Vec::with_capacity(tw * th * 3);
+ for y in 0..th {
+ for x in 0..tw {
+ let k = ((y * step) * w + x * step) * 4;
+ rgb.extend_from_slice(&f.rgba[k..k + 3]);
+ }
+ }
+ let mut out = Vec::new();
+ image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, 82).encode(&rgb, tw as u32, th as u32, image::ExtendedColorType::Rgb8).ok()?;
+ Some(out)
+}
diff --git a/apps/capcut/src/plan.rs b/apps/capcut/src/plan.rs
new file mode 100644
index 00000000..ed23c652
--- /dev/null
+++ b/apps/capcut/src/plan.rs
@@ -0,0 +1,182 @@
+//! The render's manifest as a CapCut timeline (docs/capcut.feature CC2): each run of frames showing one file as a
+//! clip of it, each sound clip as an audio clip (or as its footage's own sound), each run of frames the overlay draws
+//! as a clip of the overlay movie, and the tracks they go on. Pure: the export (lib.rs) renders and probes around it.
+
+use std::path::{Path, PathBuf};
+
+use raea_io_capcut::{Clip, Kind, Place, Track};
+use serde_json::Value;
+
+/// One file shown over a run of frames, as the manifest's frames say: its first source time and rate, its box and
+/// fit at its first frame, its place in the page's order (lower draws first), and whether it moved or faded.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Run {
+ pub src: String,
+ pub key: String,
+ pub start: i64,
+ pub end: i64,
+ pub at: f64,
+ pub last_at: f64,
+ pub rate: Option<f64>,
+ pub bx: [f64; 4],
+ pub fit: String,
+ pub opacity: f64,
+ pub z: usize,
+ pub moved: bool,
+ pub faded: bool,
+}
+
+/// One sound clip of the manifest: its file, frames, source time, gain, rate and fades.
+#[derive(Clone, Debug, PartialEq)]
+pub struct Sound {
+ pub src: String,
+ pub from: i64,
+ pub to: i64,
+ pub at: f64,
+ pub gain_db: f64,
+ pub rate: f64,
+ pub fade_in: f64,
+ pub fade_out: f64,
+}
+
+/// The footage's runs, frame by frame: a run goes on while the same element shows the same file with its source time
+/// advancing at one rate; a jump in source time (a cut within one take) starts another.
+pub fn runs(manifest: &Value, fps: f64) -> Vec<Run> {
+ let mut done: Vec<Run> = Vec::new();
+ let mut open: Vec<Run> = Vec::new();
+ let frames = manifest["frames"].as_array().cloned().unwrap_or_default();
+ for (i, fr) in frames.iter().enumerate() {
+ let f = fr["frame"].as_i64().unwrap_or(i as i64);
+ let mut next = Vec::new();
+ for (z, v) in fr["videos"].as_array().into_iter().flatten().enumerate() {
+ let src = v["src"].as_str().unwrap_or_default().to_string();
+ let key = format!("{src}|{}|{}|{}", v["loc"], v["use"], v["index"]);
+ let at = v["at"].as_f64().unwrap_or(0.0);
+ let bx: [f64; 4] = std::array::from_fn(|k| v["box"][k].as_f64().unwrap_or(0.0));
+ let opacity = v["opacity"].as_f64().unwrap_or(1.0);
+ let continues = |r: &Run| {
+ let step = at - r.last_at;
+ r.key == key && r.end == f && step > 0.0 && match r.rate {
+ Some(rate) => (step - rate / fps).abs() <= 0.6 / fps,
+ None => step * fps <= 8.0,
+ }
+ };
+ if let Some(k) = open.iter().position(continues) {
+ let mut r = open.remove(k);
+ r.rate.get_or_insert((at - r.last_at) * fps);
+ r.moved |= r.bx.iter().zip(&bx).any(|(a, b)| (a - b).abs() > 1.0);
+ r.faded |= (r.opacity - opacity).abs() > 0.02;
+ (r.end, r.last_at) = (f + 1, at);
+ next.push(r);
+ } else {
+ next.push(Run { src, key, start: f, end: f + 1, at, last_at: at, rate: None, bx, fit: v["fit"].as_str().unwrap_or("fill").to_string(), opacity, z, moved: false, faded: false });
+ }
+ }
+ done.append(&mut open);
+ open = next;
+ }
+ done.append(&mut open);
+ // the rate over the whole run (source times are whole milliseconds, so one step's can be 1% off), to hundredths
+ for r in &mut done {
+ if r.end - r.start > 1 {
+ r.rate = Some(((r.last_at - r.at) * fps / (r.end - r.start - 1) as f64 * 100.0).round() / 100.0);
+ }
+ }
+ done.sort_by_key(|r| (r.start, r.z));
+ done
+}
+
+/// The manifest's sound clips.
+pub fn sounds(manifest: &Value) -> Vec<Sound> {
+ let s = &manifest["sounds"]["clips"];
+ s.as_array()
+ .into_iter()
+ .flatten()
+ .map(|c| Sound {
+ src: c["src"].as_str().unwrap_or_default().to_string(),
+ from: c["from"].as_i64().unwrap_or(0),
+ to: c["to"].as_i64().unwrap_or(0),
+ at: c["at"].as_f64().unwrap_or(0.0),
+ gain_db: c["gainDb"].as_f64().unwrap_or(0.0),
+ rate: c["rate"].as_f64().unwrap_or(1.0),
+ fade_in: c["fadeIn"].as_f64().unwrap_or(0.0),
+ fade_out: c["fadeOut"].as_f64().unwrap_or(0.0),
+ })
+ .filter(|c| c.to > c.from)
+ .collect()
+}
+
+/// Runs of frames that draw something.
+pub fn spans(drawn: &[bool]) -> Vec<(i64, i64)> {
+ let mut out = Vec::new();
+ let mut f = 0;
+ while f < drawn.len() {
+ if !drawn[f] {
+ f += 1;
+ continue;
+ }
+ let a = f;
+ while f < drawn.len() && drawn[f] {
+ f += 1;
+ }
+ out.push((a as i64, f as i64));
+ }
+ out
+}
+
+/// Whether a box covers the whole canvas.
+pub fn full(bx: &[f64; 4], w: f64, h: f64) -> bool {
+ bx[0] <= 1.0 && bx[1] <= 1.0 && bx[0] + bx[2] >= w - 1.0 && bx[1] + bx[3] >= h - 1.0
+}
+
+/// 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.
+pub fn place(bx: &[f64; 4], fit: &str, mw: f64, mh: f64, w: f64, h: f64, opacity: f64) -> (Place, Option<String>) {
+ let (bw, bh) = (bx[2].max(1.0), bx[3].max(1.0));
+ let (x, y) = (bx[0] + bw / 2.0, bx[1] + bh / 2.0);
+ let fit0 = (w / mw).min(h / mh);
+ let mut warn = None;
+ let contain = (bw / mw).min(bh / mh);
+ let (scale, crop) = match fit {
+ "cover" if full(bx, w, h) => ((bw / mw).max(bh / mh) / fit0, [0.0, 0.0, 1.0, 1.0]),
+ "cover" => {
+ let s = (bw / mw).max(bh / mh);
+ let (cw, ch) = (bw / (mw * s), bh / (mh * s));
+ let fitc = (w / (mw * cw)).min(h / (mh * ch));
+ (bw / (mw * cw * fitc), [(1.0 - cw) / 2.0, (1.0 - ch) / 2.0, (1.0 + cw) / 2.0, (1.0 + ch) / 2.0])
+ }
+ "none" => (1.0 / fit0, [0.0, 0.0, 1.0, 1.0]),
+ "scale-down" => (contain.min(1.0) / fit0, [0.0, 0.0, 1.0, 1.0]),
+ "contain" => (contain / fit0, [0.0, 0.0, 1.0, 1.0]),
+ _ => {
+ if ((bw / bh) - (mw / mh)).abs() > 0.01 * (mw / mh) {
+ warn = Some(format!("stretched to its {bw:.0}x{bh:.0} box in raea (object-fit: fill), fitted inside it in CapCut"));
+ }
+ (contain / fit0, [0.0, 0.0, 1.0, 1.0])
+ }
+ };
+ (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
+}
+
+/// A file the manifest names, as a path: relative to the composition's folder unless it's absolute.
+pub fn resolve(dir: &Path, src: &str) -> PathBuf {
+ let p = Path::new(src);
+ let p = if p.is_absolute() { p.to_path_buf() } else { dir.join(p) };
+ p.canonicalize().unwrap_or(p)
+}
diff --git a/apps/capcut/src/tests.rs b/apps/capcut/src/tests.rs
new file mode 100644
index 00000000..c29150e7
--- /dev/null
+++ b/apps/capcut/src/tests.rs
@@ -0,0 +1,71 @@
+//! 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.
+
+use serde_json::json;
+
+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");
+}
+
+#[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());
+}
+
+#[test]
+fn pictures_sit_as_their_fit_shows_them() {
+ // a landscape take covering a portrait canvas: scaled past the fitted width until it fills the height
+ let (p, w) = place(&[0.0, 0.0, 1080.0, 1920.0], "cover", 1920.0, 1080.0, 1080.0, 1920.0, 1.0);
+ assert!(w.is_none() && (p.scale - (1920.0 / 1080.0) / 0.5625).abs() < 1e-9 && p.crop == [0.0, 0.0, 1.0, 1.0]);
+ assert_eq!((p.x, p.y), (540.0, 960.0));
+ // a square in a corner, contained: a third of the canvas's width
+ let (p, _) = place(&[660.0, 200.0, 360.0, 360.0], "contain", 640.0, 640.0, 1080.0, 1920.0, 1.0);
+ assert!((p.scale - 1.0 / 3.0).abs() < 1e-9 && (p.x, p.y) == (840.0, 380.0));
+ // a landscape take covering a square box: cropped to its middle square, which then fits as a square
+ let (p, _) = place(&[0.0, 0.0, 540.0, 540.0], "cover", 1920.0, 1080.0, 1080.0, 1920.0, 1.0);
+ assert!((p.crop[0] - 0.21875).abs() < 1e-9 && (p.crop[2] - 0.78125).abs() < 1e-9 && p.crop[1] == 0.0);
+ assert!((p.scale - 0.5).abs() < 1e-9);
+ // stretched in raea: said
+ assert!(place(&[0.0, 0.0, 500.0, 100.0], "fill", 640.0, 640.0, 1080.0, 1920.0, 1.0).1.is_some());
+}
+
+#[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)]);
+}
diff --git a/docs/capcut.feature b/docs/capcut.feature
new file mode 100644
index 00000000..0fd469a7
--- /dev/null
+++ b/docs/capcut.feature
@@ -0,0 +1,83 @@
+@spec
+Feature: A composition handed to CapCut, ready in its timeline, and transparent video for any editor
+ Shane, 2026-11-10: "implementing an export to capcut ... how could we export to capcut a project composition
+ component etc correctly so it would be ready in the timeline. as well included how do we make sure we can natively
+ render transparent movs for overlay gfx that someone might need".
+
+ A flattened MP4 in CapCut is one clip nobody can edit. The export hands CapCut the composition's own parts instead:
+ its footage and sounds as clips of the original files at their own trims and gains, so an editor can retime a cut,
+ swap a take or ride a level; and everything raea draws (titles, lower thirds, shapes, 3D, effects) as transparent
+ overlay clips above them, cut where the drawing comes and goes. The format is CapCut 8.5.0's draft as CapCut
+ writes it, read from an empty project CapCut made and one with a clip placed by hand, which gives the companion
+ materials a segment carries.
+
+ Background:
+ Given a composition renders with --manifest (render.json): each frame's footage (its file, source time and box),
+ each sound clip (its file, first and last frame, source time and gain) and what the page drew
+ And RAEA_HIDE_MEDIA=1 draws a render with every <Video> hidden (any element carrying data-raea-src), everything
+ else as it is; a still (<Img>) stays in the overlay
+
+ Rule: CC1. `raea render EDIT.tsx -o OUT.mov --alpha` writes transparent video natively, no ffmpeg
+ The frames are rendered as --alpha PNGs (straight alpha) and encoded in raea (io/alpha) as one of:
+ | codec | what | where | gfx.tsx: 3 s, 1080x1920 |
+ | prores | Apple ProRes 4444 with alpha (ap4h) | Mac (VideoToolbox) | 12.3 MB |
+ | hevc | HEVC with alpha (hvc1, an alpha layer) | Mac (VideoToolbox) | 0.34 MB |
+ | rle | QuickTime Animation, 32-bit ARGB, lossless | every platform | 0.84 MB |
+ | png | PNG frames in a QuickTime movie, lossless | every platform | 7.4 MB |
+ `--alpha-codec C` picks one; prores on the Mac, rle elsewhere, when none is named. The movie has no sound.
+
+ @done
+ Scenario: CC1a. Each codec's movie decodes to the frames' own alpha
+ Given the fixture's graphics (the lower third fading in over nothing) rendered with --alpha
+ When it is written as each codec's .mov
+ Then ffprobe reads the codec and an alpha pixel format, and the decoded alpha of every frame matches the PNG's:
+ exactly for rle and png, within the codec's error for prores and hevc
+ And a frame the composition leaves empty decodes fully transparent
+ And on 11-10 (FFmpeg 9.0.2, frame 50 against its PNG; colour compared premultiplied, over black): prores
+ yuva444p12le, alpha 61.5 dB, colour 80.7 dB; hevc yuva420p (ffprobe names the base layer yuv420p; FFmpeg
+ decodes the alpha layer), alpha 61.3 dB, colour 52.8 dB at --quality 0.9; rle argb and png rgba identical
+ (infinite PSNR); frame 85, which draws nothing, has no alpha above 0 in any of the four
+
+ Rule: CC2. `raea export capcut EDIT.tsx` writes a CapCut draft whose timeline is the composition
+ Scenario: CC2a. Footage is clips of the original files, placed as the composition shows them
+ Then each run of frames showing one file continuously (its source time advancing with the frames) is a clip of
+ that file from its source time, at its rate, on a video track
+ And the clips covering the whole frame are the main track, butted shot after shot; the others (a picture in
+ picture) are on tracks above it, in the composition's order, scaled and placed to their box
+ And the footage's own sound stays on its clip at the composition's gain when the manifest plays it there (its
+ sound clip of the same file over the same frames from the same time); otherwise the clip is muted, and any
+ other sound of the file is an audio clip (CC2c), so nothing plays twice
+
+ Scenario: CC2b. What raea draws is transparent overlay clips above the footage, and under it what's under it
+ Given the composition rendered again with its footage hidden, --alpha (RAEA_HIDE_MEDIA=1), the backgrounds of
+ the elements holding footage cleared, since they paint under it
+ Then each run of frames that draws something is one clip of one overlay movie, on the track above the footage
+ And frames that draw nothing are a gap, so an editor sees a clip where each title or graphic is
+ And a third render draws only those backgrounds (RAEA_HIDE_MEDIA=under); unless it is all black, CapCut's own
+ canvas, its movie's clips are the bottom track, under the footage
+ And footage that something else raea draws covers (a full layer before it in the page, not holding it) goes
+ above the overlay, and the export says so, since the overlay's drawing over it is hidden there
+
+ Scenario: CC2c. Sounds are audio clips with their trims, gains and fades
+ Then each sound clip in the manifest is an audio clip of its file from its source time, its gain as CapCut's
+ volume, on audio tracks that never overlap a clip on the same track
+
+ Scenario: CC2d. The draft is a CapCut project folder
+ Then it is written into CapCut's draft store (~/Movies/CapCut/User Data/Projects/com.lveditor.draft on the Mac,
+ %LOCALAPPDATA%\CapCut\User Data\Projects\com.lveditor.draft on Windows) or -o DIR, never over a folder there
+ And every file it uses is cloned (APFS) or copied into its assets/ folder, where sandboxed CapCut can read it
+ And its version markers are the newest app-made draft's in the store, else CapCut 8.5.0's
+ And a draft written into the store is entered in root_meta_info.json (a copy kept first in
+ ~/.raea/capcut/backups) unless --no-register; CapCut open is refused, since CapCut rewrites that file when it
+ quits, and the draft stays in its folder for the next export or a restart to enter
+ And the reference render (the composition as raea draws it) is kept beside the draft, not in it
+
+ Scenario: CC2e. What doesn't carry is said, not dropped quietly
+ Then footage drawn with a CSS filter, a rotation, a mask or a crop that isn't a box, sounds the Tone graph makes
+ (notes), and <Mix>'s mastering are named in the export's output
+
+ Rule: CC3. CapCut opens it
+ Scenario: CC3a. CapCut, quit and opened, lists the draft and plays it as raea renders it
+ Then the timeline has the main track's shots, the picture in picture above, the overlay clips above that and the
+ audio below, and the frame at each shot's middle matches the reference render's
+ And which overlay codecs stay transparent in CapCut is recorded here, and the export uses the first that does
diff --git a/docs/manual/reference/cli/app.md b/docs/manual/reference/cli/app.md
index f3aac5ff..f68fba68 100644
--- a/docs/manual/reference/cli/app.md
+++ b/docs/manual/reference/cli/app.md
@@ -1,7 +1,7 @@
---
title: "raea app"
summary: "Run, check headless and package a desktop app written as one TSX file on @raea/ui."
-order: 6
+order: 7
sources: ["engine/cli/src/cli.rs", "engine/rune/src/main.rs"]
---
diff --git a/docs/manual/reference/cli/bundle.md b/docs/manual/reference/cli/bundle.md
index ba05b439..8677ac22 100644
--- a/docs/manual/reference/cli/bundle.md
+++ b/docs/manual/reference/cli/bundle.md
@@ -1,7 +1,7 @@
---
title: "raea bundle"
summary: "Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone."
-order: 5
+order: 6
sources: ["engine/cli/src/cli.rs", "runtime/bundle/src/lib.rs"]
---
diff --git a/docs/manual/reference/cli/export.md b/docs/manual/reference/cli/export.md
new file mode 100644
index 00000000..355f8d7f
--- /dev/null
+++ b/docs/manual/reference/cli/export.md
@@ -0,0 +1,41 @@
+---
+title: "raea export"
+summary: "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."
+order: 5
+sources: ["engine/cli/src/cli.rs"]
+---
+
+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.
+
+```sh
+raea export capcut edit.tsx # into CapCut's projects; open CapCut and it's in the list
+raea export capcut edit.tsx -o drafts/ # a draft folder to copy into CapCut's projects folder yourself
+```
+
+raea renders the composition three times. The first render, as it is, is kept in `out/capcut/NAME/reference.mp4` to compare against. The second hides the footage and draws everything else with a transparent background: titles, lower thirds, shapes, 3D and effects. That render becomes one transparent movie, cut into a clip wherever something is drawn, on a track above the footage. The third draws only the backgrounds that sit behind the footage (a card behind a picture in picture, a coloured page), and goes under it unless it's black.
+
+Each stretch of frames that shows one video file becomes a clip of that file, starting where the composition starts it and playing at its rate. It is placed and scaled as `object-fit` shows it in raea (`cover`, `contain`, a crop). Clips covering the whole frame go on the main track; the others go on tracks above it. A video's own sound stays on its clip at the composition's volume; every other sound becomes an audio clip with its gain and fades. The output names what doesn't carry over, such as the Tone graph's music, which has no file, or a clip that moves or fades within its shot (placed as its first frame shows it).
+
+CapCut rewrites its project list when it quits, so `raea export capcut` refuses to write into CapCut's projects while CapCut is open. Quit it first, or pass `--no-register` or `-o`. The previous project list is kept in `~/.raea/capcut/backups` first.
+
+<!-- generated:begin by tools/manual-ref/cli.ts from `raea help --json`; edit only the flag descriptions -->
+
+## 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)
+```
+
+Headless: it needs nothing running and opens no window. Takes up to 2 arguments besides its flags.
+
+## Flags
+
+| Flag | Takes | What it does |
+| --- | --- | --- |
+| `--alpha-codec` | `prores\|hevc\|rle\|png` | The overlay movie's codec. ProRes 4444 by default on a Mac, QuickTime Animation elsewhere; HEVC with alpha is far smaller and Mac-only, like ProRes. |
+| `--composition` | `ID` | The composition to export when the file registers more than one. |
+| `--name` | `NAME` | The draft's name in CapCut. The file's name by default; a name already taken gets " 2", " 3" and so on. |
+| `--no-register` | – | Write the draft into CapCut's projects folder without adding it to CapCut's project list. |
+| `-o` | `DIR` | Write the draft folder into DIR instead of CapCut's projects folder (to copy to another machine, or to look at first). |
+
+<!-- generated:end -->
diff --git a/docs/manual/reference/cli/index.md b/docs/manual/reference/cli/index.md
index f6f78908..ee15c28b 100644
--- a/docs/manual/reference/cli/index.md
+++ b/docs/manual/reference/cli/index.md
@@ -35,6 +35,7 @@ Render, play and package what you wrote.
| [`raea render`](render.md) | Render a composition to an MP4, a PNG or a folder of frames, on the GPU and headless. |
| [`raea play`](play.md) | Play a game live in a window, or headless with scripted keys, snapshots and a timing report. |
| [`raea export-game`](export-game.md) | Package a game as a program of its own: a Mac app or a command-line program. |
+| [`raea export`](export.md) | 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. |
| [`raea bundle`](bundle.md) | Bundle a composition into one JavaScript file that render_bundle draws, on the Mac or the iPhone. |
| [`raea app`](app.md) | Run, check headless and package a desktop app written as one TSX file on @raea/ui. |
| [`raea run`](run.md) | Run a TypeScript program on the engine, headless, and print what it prints. |
diff --git a/docs/manual/reference/cli/render.md b/docs/manual/reference/cli/render.md
index 20865d85..9de671c9 100644
--- a/docs/manual/reference/cli/render.md
+++ b/docs/manual/reference/cli/render.md
@@ -14,6 +14,7 @@ raea render piece.tsx -o piece.mp4 # the whole video
raea render piece.tsx --frame 120 -o frame-120.png # one frame
raea render piece.tsx --at 15,63,144 -o stills/ # some frames, in order: stills/frame-00000.png is frame 15
raea render piece.tsx --alpha -o frames/ # every frame as a transparent PNG
+raea render piece.tsx --alpha -o overlay.mov # a transparent movie (ProRes 4444 on a Mac)
raea render piece.tsx --quality master -o final.mp4 # constant quality for type and thin lines
raea render scene.tsx --review review/ # a 3D scene from six fixed cameras, in colour and clay
raea render piece.tsx -o piece.wav # the sound alone, no frames drawn
@@ -52,7 +53,7 @@ the reason in the manifest. A render of a file in a raea project also keeps its
## Usage
```sh
-raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)
+raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)
raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)
raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)
raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
@@ -65,7 +66,8 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
| Flag | Takes | What it does |
| --- | --- | --- |
| `--10bit` | – | Encode the video as 10-bit HEVC (Main 10), whose decoded colours match the render exactly; H.264 8-bit otherwise. |
-| `--alpha` | – | Keep the background transparent. Writes PNGs only (`-o OUT.png` or a folder): H.264 and HEVC hold no alpha, so encode the folder to ProRes 4444 afterwards if you need a video. |
+| `--alpha` | – | Keep the background transparent: PNGs (`-o OUT.png` or a folder) or a transparent movie (`-o OUT.mov`, see `--alpha-codec`). An `.mp4` holds no alpha. |
+| `--alpha-codec` | `prores\|hevc\|rle\|png` | With `--alpha` and `-o OUT.mov`: ProRes 4444 (the default on a Mac) or HEVC with alpha, both through VideoToolbox on a Mac; QuickTime Animation (lossless, the default elsewhere) or PNG frames, on every platform. Editors that take overlays (Final Cut, Premiere, DaVinci Resolve, CapCut) read all four, HEVC in the newest versions. |
| `--aov` | – | Write each frame's motion vectors and depth beside its colour, in `DIR/motion` and `DIR/depth`, for [`raea neural`](neural.md). `-o` must name a folder. |
| `--at` | `A,B` | Render only these frame numbers, comma-separated. |
| `--audio` | `OUT.wav` | With a video `-o`: also write its sound to `OUT.wav`, the same mastered sound the video carries (before AAC), from the same pass. |
diff --git a/docs/manual/reference/cli/run.md b/docs/manual/reference/cli/run.md
index 0fb55a8f..c85615b1 100644
--- a/docs/manual/reference/cli/run.md
+++ b/docs/manual/reference/cli/run.md
@@ -1,7 +1,7 @@
---
title: "raea run"
summary: "Run a TypeScript program on the engine, headless, and print what it prints."
-order: 7
+order: 8
sources: ["engine/cli/src/cli.rs"]
---
diff --git a/engine/cli/Cargo.toml b/engine/cli/Cargo.toml
index 4f303e40..1aaddf99 100644
--- a/engine/cli/Cargo.toml
+++ b/engine/cli/Cargo.toml
@@ -65,6 +65,7 @@ raea-app-media = { path = "../../apps/media" }
# `raea app run|check|bundle` and `raea rune` on either target (docs/targets.feature T0b)
raea-app-targets = { path = "../../apps/targets" }
raea-app-game = { path = "../../apps/game" }
+raea-app-capcut = { path = "../../apps/capcut" }
raea-app-play = { path = "../../apps/play", features = ["ml"] }
raea-bevy-plugins = { path = "../../engine/bevy-plugins", optional = true }
# raea-bevy-sdk's reflection of the plugin build's App: the type registry, a one-camera program, the animation type
diff --git a/engine/cli/src/cli.rs b/engine/cli/src/cli.rs
index 99a1e349..51bb145c 100644
--- a/engine/cli/src/cli.rs
+++ b/engine/cli/src/cli.rs
@@ -136,9 +136,9 @@ pub fn run(args: &[String]) -> R<String> {
let usage = format!("{usage}\n raea show FILE... [--title T] [--ask LINE] [--project P] [--replaces ITEM] [--as NAME] [--role ROLE] [--inbox NAME] [--open] | raea show --question Q --choice A --choice B [STILL...] | raea show [--title T] --question Q [--preview FILE] --choice A [--preview FILE] --choice B ... [--question Q2] ... | raea show --on ITEM [--working ID] [--ask TEXT] [--status S] [--states S1,S2] [--sign N --clip FILE --render HASH] [--done ID] [--note LINE] [--sub NAME] (shown in the raea app as an item the person can use and answer, posted quietly with a notice, the window left where they are unless --open: stills (several, a storyboard), a video, a sound, a NAME.script.ts or .md, a .tsx (an interactive artifact; a project's composition opens in its editor), or questions, all of them one item, each question and choice with a --preview to play or read while answering (a still, a video, a sound, a script or .md; after a --choice that choice's, else the question's); what they send comes to ~/.raea/inbox/INBOX.jsonl; their edit comments are tasks: --working ID as you start one (each --ask with it one ask you read it as, for the person to correct; --status and --states where the note and each ask stand: to restate, to check, failing, to sign, passing, signed; --sign N --clip FILE --render HASH a clip under ask N for them to sign; a note closes when they retire it, never with --done), --done ID when it's settled, or with the version that settles it, FILE --replaces ITEM --done ID; never open media in Preview while the app is installed)");
// 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 {}", skill::USAGE, tools::blender::USAGE, raea_app_engines::godot::USAGE);
- let (export_game, scene, physics, splat) = (raea_app_game::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
+ let (export_game, capcut, scene, physics, splat) = (raea_app_game::USAGE, raea_app_capcut::USAGE, export::SCENE_USAGE, motion::physics::USAGE, tools::splat::USAGE);
let apps = format!(" {}\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);
- 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 part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\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 {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 part list | raea part add NAME ... [--force] (a ready part copied into components/, yours to change)\n raea brand DOMAIN|URL (the brand kit read from its website on this machine: brand/brand.css, brand/brand.json, BRAND.md, logos in media/brand; says when a plain fetch saw too little)\n raea guide [NAME] (craft, the floor read before any edit; the modes: pitch, explain, story, play, tool; motion, music, layout and the rest; bevy and bevy/NAME for 3D)\n raea context PROJECT (what to read before working on a project: taste, brief, look, the floor and its modes' guides)\n{apps} raea play EDIT.tsx [--input | --input-script KEYS.json] [--size WxH] [--seconds N|end] (a game, live; also: --input-log FILE --offscreen --snapshot T FILE --json FILE --seek F FILE --pick X,Y --view YAW,PITCH,DISTANCE --scrub N --baked --autoplay --no-vsync --master --3d)\n {export_game} (a game as a program of its own: a Mac app or a command)\n {capcut}\n {scene} (what each 3D part rests on: floating, sunk and clipping parts; light: the scene's lighting)\n {physics} (the bakes <Physics> and <Goo> make)\n {splat} (footage trained into a Gaussian splat for <Splat>; setup installs its tools)\n raea run SCRIPT.ts (a TypeScript program on the engine, headless: its default export is called, what it prints is the answer; a check like a room's checkLayout; also: --timeout S)\n raea gen image|video|music|sfx|speech|mesh|text \"PROMPT\" | gen plan|run FLOW.ts|FLOW.json | gen comfy import|export|run|schema FILE | gen models | gen balance (generated media through made.app, fal, Replicate, OpenRouter, Modal or ComfyUI; ComfyUI workflows both ways: raea gen alone lists its flags)\n {neural_usage} (DLSS 5 neural rendering on a `render --aov` folder, with its motion and depth: your own MLX-DLSS build and weights, RAEA_MLXDLSS and RAEA_DLSS_MODEL)\n raea mezz [--check] PATH... (an intra-only ProRes copy of each long-GOP source over 1080p, for smooth scrubbing; --check says which would get one)\n raea traces [show [N|last|DIR]] (the sessions raea left, newest first: how each ended, its glitches; show tells one in full)"));
}
// `--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") {
@@ -214,6 +214,8 @@ pub fn run(args: &[String]) -> R<String> {
if args.first().map(String::as_str) == Some("play") {
return raea_app_play::play(args);
}
+ // `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; }
// `export-game EDIT.tsx -o OUT`: the game as a program of its own (game.rs, sdk/react/docs/game-export.md)
if args.first().map(String::as_str) == Some("export-game") {
return raea_app_game::export(args);
@@ -352,7 +354,7 @@ pub fn run(args: &[String]) -> R<String> {
}
if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
return Err(format!(
- "raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
+ "raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)
raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
diff --git a/engine/page/src/motion/manifest.rs b/engine/page/src/motion/manifest.rs
index 7c43665f..d71ff0f8 100644
--- a/engine/page/src/motion/manifest.rs
+++ b/engine/page/src/motion/manifest.rs
@@ -66,6 +66,17 @@ impl BlitzPage {
if let (Some(b), true) = (rect(n), a > 0.01) {
let at = node.attr(LocalName::from("data-raea-at")).and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
let mut v = json!({"src": src, "at": at, "box": [r(b.x), r(b.y), r(b.width), r(b.height)], "opacity": (a * 100.0).round() / 100.0});
+ // how the picture fills its box (the CapCut export places a clip by it, docs/capcut.feature CC2a)
+ if let Some(s) = node.primary_styles() {
+ use style::computed_values::object_fit::T as Fit;
+ v["fit"] = json!(match s.clone_object_fit() {
+ Fit::Contain => "contain",
+ Fit::Cover => "cover",
+ Fit::Fill => "fill",
+ Fit::None => "none",
+ Fit::ScaleDown => "scale-down",
+ });
+ }
stamps(n, &mut v);
videos.push(v);
}
diff --git a/io/alpha/Cargo.toml b/io/alpha/Cargo.toml
new file mode 100644
index 00000000..19d8b85b
--- /dev/null
+++ b/io/alpha/Cargo.toml
@@ -0,0 +1,24 @@
+[package]
+name = "raea-io-alpha"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "Transparent video written natively (docs/capcut.feature CC1): ProRes 4444 and HEVC with alpha through VideoToolbox on Apple, QuickTime Animation and PNG movies everywhere"
+
+[dependencies]
+png = "0.17"
+image = { version = "0.25", default-features = false, features = ["png"] }
+serde_json = "1"
+
+[target.'cfg(target_vendor = "apple")'.dependencies]
+# its toll-free bridge for CoreFoundation keys
+raea-io-apple = { path = "../apple" }
+objc2 = "0.6"
+objc2-foundation = "0.3"
+objc2-av-foundation = { version = "0.3", features = ["objc2-core-media", "objc2-core-video", "block2"] }
+objc2-core-media = "0.3"
+objc2-core-video = "0.3"
+objc2-core-foundation = "0.3"
+objc2-video-toolbox = "0.3"
+block2 = "0.6"
diff --git a/io/alpha/src/apple.rs b/io/alpha/src/apple.rs
new file mode 100644
index 00000000..ba1e74ed
--- /dev/null
+++ b/io/alpha/src/apple.rs
@@ -0,0 +1,119 @@
+//! ProRes 4444 and HEVC with alpha through AVAssetWriter (VideoToolbox) into a QuickTime movie: BGRA pixel buffers
+//! from the writer's pool, each marked straight alpha, as raea's --alpha frames are.
+
+use std::path::Path;
+
+use objc2::rc::Retained;
+use objc2::runtime::AnyObject;
+use objc2_av_foundation::*;
+use objc2_core_media::CMTime;
+use objc2_core_video::*;
+use objc2_foundation::{NSDictionary, NSNumber, NSString, NSURL};
+
+use crate::R;
+
+use raea_io_apple::cf_key as key;
+
+pub(crate) struct Writer {
+ writer: Retained<AVAssetWriter>,
+ input: Retained<AVAssetWriterInput>,
+ adaptor: Retained<AVAssetWriterInputPixelBufferAdaptor>,
+ fps: f64,
+ n: i64,
+}
+
+impl Writer {
+ /// `hevc`: HEVC with alpha (its colour and alpha at `quality`, 0..1); else ProRes 4444.
+ pub(crate) fn new(out: &Path, hevc: bool, width: u32, height: u32, fps: f64, quality: f32) -> R<Writer> {
+ let _ = std::fs::remove_file(out);
+ unsafe {
+ let url = NSURL::fileURLWithPath(&NSString::from_str(&out.display().to_string()));
+ let writer = AVAssetWriter::assetWriterWithURL_fileType_error(&url, AVFileTypeQuickTimeMovie.ok_or("AVFileTypeQuickTimeMovie")?).map_err(|e| format!("AVAssetWriter: {}", e.localizedDescription()))?;
+ let codec: &NSString = if hevc { AVVideoCodecTypeHEVCWithAlpha } else { AVVideoCodecTypeAppleProRes4444 }.ok_or("no alpha codec in this AVFoundation")?;
+ let num = |v: f64| NSNumber::new_f64(v);
+ let mut keys: Vec<&NSString> = vec![AVVideoCodecKey.ok_or("key")?, AVVideoWidthKey.ok_or("key")?, AVVideoHeightKey.ok_or("key")?];
+ let (w, h) = (num(width as f64), num(height as f64));
+ let mut vals: Vec<&AnyObject> = vec![codec as &AnyObject, &*w as &AnyObject, &*h as &AnyObject];
+ // HEVC takes the alpha's mode and quality; ProRes 4444's alpha is lossless-ish and takes neither (an
+ // unknown key there throws)
+ let q = num(quality as f64);
+ let compression: Retained<NSDictionary<NSString, AnyObject>> = NSDictionary::from_slices(
+ &[key(objc2_video_toolbox::kVTCompressionPropertyKey_AlphaChannelMode), AVVideoQualityKey.ok_or("key")?, key(objc2_video_toolbox::kVTCompressionPropertyKey_TargetQualityForAlpha)],
+ &[key(objc2_video_toolbox::kVTAlphaChannelMode_StraightAlpha) as &AnyObject, &*q as &AnyObject, &*q as &AnyObject],
+ );
+ if hevc {
+ keys.push(AVVideoCompressionPropertiesKey.ok_or("key")?);
+ vals.push(&*compression as &AnyObject);
+ }
+ let settings: Retained<NSDictionary<NSString, AnyObject>> = NSDictionary::from_slices(&keys, &vals);
+ let input = AVAssetWriterInput::assetWriterInputWithMediaType_outputSettings(AVMediaTypeVideo.ok_or("video")?, Some(&settings));
+ input.setExpectsMediaDataInRealTime(false);
+ let (fmt, pw, ph) = (NSNumber::new_u32(kCVPixelFormatType_32BGRA), num(width as f64), num(height as f64));
+ let attrs: Retained<NSDictionary<NSString, AnyObject>> = NSDictionary::from_slices(
+ &[key(kCVPixelBufferPixelFormatTypeKey), key(kCVPixelBufferWidthKey), key(kCVPixelBufferHeightKey)],
+ &[&*fmt as &AnyObject, &*pw as &AnyObject, &*ph as &AnyObject],
+ );
+ let adaptor = AVAssetWriterInputPixelBufferAdaptor::assetWriterInputPixelBufferAdaptorWithAssetWriterInput_sourcePixelBufferAttributes(&input, Some(&attrs));
+ if !writer.canAddInput(&input) {
+ return Err(format!("AVAssetWriter can't write {} here", if hevc { "HEVC with alpha" } else { "ProRes 4444" }));
+ }
+ writer.addInput(&input);
+ if !writer.startWriting() {
+ return Err(format!("AVAssetWriter didn't start: {:?}", writer.error().map(|e| e.localizedDescription().to_string())));
+ }
+ writer.startSessionAtSourceTime(CMTime::with_seconds(0.0, 600));
+ Ok(Writer { writer, input, adaptor, fps, n: 0 })
+ }
+ }
+
+ /// One frame, straight RGBA at the movie's size.
+ pub(crate) fn push(&mut self, rgba: &[u8]) -> R<()> {
+ objc2::rc::autoreleasepool(|_| unsafe {
+ while !self.input.isReadyForMoreMediaData() {
+ std::thread::sleep(std::time::Duration::from_micros(200));
+ }
+ let pool = self.adaptor.pixelBufferPool().ok_or("no pixel buffer pool")?;
+ let mut pb: *mut CVPixelBuffer = std::ptr::null_mut();
+ if CVPixelBufferPool::create_pixel_buffer(None, &pool, std::ptr::NonNull::new(&mut pb).unwrap()) != 0 || pb.is_null() {
+ return Err("CVPixelBufferPoolCreatePixelBuffer failed".to_string());
+ }
+ let pb = objc2_core_foundation::CFRetained::from_raw(std::ptr::NonNull::new(pb).unwrap());
+ CVPixelBufferLockBaseAddress(&pb, CVPixelBufferLockFlags(0));
+ let (w, h, bpr) = (CVPixelBufferGetWidth(&pb), CVPixelBufferGetHeight(&pb), CVPixelBufferGetBytesPerRow(&pb));
+ let base = CVPixelBufferGetBaseAddress(&pb) as *mut u8;
+ for y in 0..h {
+ let row = std::slice::from_raw_parts_mut(base.add(y * bpr), w * 4);
+ let src = &rgba[y * w * 4..(y + 1) * w * 4];
+ for x in 0..w {
+ row[x * 4..x * 4 + 4].copy_from_slice(&[src[x * 4 + 2], src[x * 4 + 1], src[x * 4], src[x * 4 + 3]]);
+ }
+ }
+ CVPixelBufferUnlockBaseAddress(&pb, CVPixelBufferLockFlags(0));
+ pb.set_attachment(kCVImageBufferAlphaChannelModeKey, kCVImageBufferAlphaChannelMode_StraightAlpha, CVAttachmentMode::ShouldPropagate);
+ let t = CMTime::with_seconds(self.n as f64 / self.fps, 6000);
+ if !self.adaptor.appendPixelBuffer_withPresentationTime(&pb, t) {
+ return Err(format!("append failed: {:?}", self.writer.error().map(|e| e.localizedDescription().to_string())));
+ }
+ self.n += 1;
+ Ok(())
+ })
+ }
+
+
+ pub(crate) fn finish(self) -> R<()> {
+ unsafe {
+ self.input.markAsFinished();
+ let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let d2 = done.clone();
+ let block = block2::RcBlock::new(move || d2.store(true, std::sync::atomic::Ordering::SeqCst));
+ self.writer.finishWritingWithCompletionHandler(&block);
+ while !done.load(std::sync::atomic::Ordering::SeqCst) {
+ std::thread::sleep(std::time::Duration::from_millis(2));
+ }
+ if self.writer.status() != AVAssetWriterStatus::Completed {
+ return Err(format!("AVAssetWriter: {:?}", self.writer.error().map(|e| e.localizedDescription().to_string())));
+ }
+ }
+ Ok(())
+ }
+}
diff --git a/io/alpha/src/lib.rs b/io/alpha/src/lib.rs
new file mode 100644
index 00000000..2a16aee6
--- /dev/null
+++ b/io/alpha/src/lib.rs
@@ -0,0 +1,188 @@
+//! Transparent video written natively (docs/capcut.feature CC1): straight-alpha RGBA frames into a QuickTime movie
+//! an editor lays over footage. ProRes 4444 and HEVC with alpha through VideoToolbox on Apple; QuickTime Animation
+//! (lossless run-length ARGB) and PNG frames on every platform, written here (mov.rs) with no other tool.
+
+mod mov;
+mod movie;
+pub use movie::render_movie;
+mod rle;
+#[cfg(target_vendor = "apple")]
+mod apple;
+#[cfg(test)]
+mod tests;
+
+use std::path::{Path, PathBuf};
+
+pub type R<T> = Result<T, String>;
+
+/// The codecs a transparent movie can be.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Codec {
+ /// Apple ProRes 4444 with alpha (ap4h): what every editor reads with alpha. VideoToolbox, Apple only.
+ ProRes,
+ /// HEVC with alpha (muxa): a fraction of ProRes's size. VideoToolbox, Apple only.
+ Hevc,
+ /// QuickTime Animation at 32 bits ('rle '): lossless, small where little changes. Every platform.
+ Rle,
+ /// PNG frames in a QuickTime movie ('png '): lossless. Every platform.
+ Png,
+}
+
+pub const NAMES: &str = "prores, hevc, rle or png";
+
+impl Codec {
+ pub fn parse(s: &str) -> R<Codec> {
+ match s.to_ascii_lowercase().as_str() {
+ "prores" | "prores4444" | "ap4h" => Ok(Codec::ProRes),
+ "hevc" | "hevc-alpha" | "muxa" => Ok(Codec::Hevc),
+ "rle" | "animation" | "qtrle" => Ok(Codec::Rle),
+ "png" => Ok(Codec::Png),
+ _ => Err(format!("--alpha-codec takes {NAMES}, not {s:?}")),
+ }
+ }
+
+ /// ProRes 4444 on Apple, QuickTime Animation elsewhere.
+ pub fn default_here() -> Codec {
+ if cfg!(target_vendor = "apple") { Codec::ProRes } else { Codec::Rle }
+ }
+
+ pub fn name(self) -> &'static str {
+ match self {
+ Codec::ProRes => "ProRes 4444",
+ Codec::Hevc => "HEVC",
+ Codec::Rle => "QuickTime Animation",
+ Codec::Png => "PNG",
+ }
+ }
+
+ /// Whether this build can write it (VideoToolbox's two need Apple).
+ pub fn here(self) -> bool {
+ cfg!(target_vendor = "apple") || matches!(self, Codec::Rle | Codec::Png)
+ }
+}
+
+/// A transparent movie being written: frames in, `finish` makes the file.
+pub struct Writer {
+ inner: Inner,
+ width: u32,
+ height: u32,
+ /// frames pushed so far
+ n: usize,
+}
+
+enum Inner {
+ Mov(mov::Mov, Option<rle::Rle>, usize),
+ #[cfg(target_vendor = "apple")]
+ Apple(apple::Writer),
+}
+
+impl Writer {
+ /// A movie of `codec` at `out`; `quality` (0..1) is HEVC's, which the others don't take.
+ pub fn create(out: &Path, codec: Codec, width: u32, height: u32, fps: f64, quality: f32) -> R<Writer> {
+ if !codec.here() {
+ return Err(format!("{} is written through VideoToolbox, on a Mac: use --alpha-codec rle or png here", codec.name()));
+ }
+ if width == 0 || height == 0 || width > 0xFFFF || height > 0xFFFF {
+ return Err(format!("a {width}x{height} movie can't be written"));
+ }
+ let inner = match codec {
+ Codec::Rle => Inner::Mov(mov::Mov::create(out, b"rle ", "Animation", width, height, fps)?, Some(rle::Rle::new(width, height)), keyframe_every(fps)),
+ Codec::Png => Inner::Mov(mov::Mov::create(out, b"png ", "PNG", width, height, fps)?, None, 1),
+ #[cfg(target_vendor = "apple")]
+ Codec::ProRes | Codec::Hevc => Inner::Apple(apple::Writer::new(out, codec == Codec::Hevc, width, height, fps, quality)?),
+ #[cfg(not(target_vendor = "apple"))]
+ Codec::ProRes | Codec::Hevc => unreachable!("{quality}"),
+ };
+ Ok(Writer { inner, width, height, n: 0 })
+ }
+
+ /// One frame: straight (not premultiplied) RGBA, the movie's size, in order.
+ pub fn push(&mut self, rgba: &[u8]) -> R<()> {
+ if rgba.len() != self.width as usize * self.height as usize * 4 {
+ return Err(format!("a frame of {} bytes isn't {}x{} RGBA", rgba.len(), self.width, self.height));
+ }
+ match &mut self.inner {
+ Inner::Mov(m, Some(r), every) => {
+ let key = self.n.is_multiple_of(*every);
+ let data = r.frame(rgba, key);
+ m.add(&data, key)
+ }
+ Inner::Mov(m, None, _) => m.add(&png_frame(rgba, self.width, self.height)?, true),
+ #[cfg(target_vendor = "apple")]
+ Inner::Apple(a) => a.push(rgba),
+ }?;
+ self.n += 1;
+ Ok(())
+ }
+
+ /// The movie finished; how many frames it holds.
+ pub fn finish(self) -> R<usize> {
+ match self.inner {
+ Inner::Mov(m, _, _) => m.finish().map(drop)?,
+ #[cfg(target_vendor = "apple")]
+ Inner::Apple(a) => a.finish()?,
+ }
+ Ok(self.n)
+ }
+}
+
+/// QuickTime Animation's keyframes: one a second, so an editor seeks without decoding far back.
+fn keyframe_every(fps: f64) -> usize {
+ (fps.round() as usize).max(1)
+}
+
+/// A frame as a PNG (RGBA, fast deflate).
+fn png_frame(rgba: &[u8], width: u32, height: u32) -> R<Vec<u8>> {
+ let mut out = Vec::new();
+ let mut enc = png::Encoder::new(&mut out, width, height);
+ enc.set_color(png::ColorType::Rgba);
+ enc.set_depth(png::BitDepth::Eight);
+ enc.set_compression(png::Compression::Fast);
+ enc.write_header().and_then(|mut w| w.write_image_data(rgba)).map_err(|e| e.to_string())?;
+ Ok(out)
+}
+
+/// A PNG read as straight RGBA8 (RGB gets an opaque alpha), with its size.
+pub fn read_png(path: &Path) -> R<(Vec<u8>, u32, u32)> {
+ let img = image::open(path).map_err(|e| format!("{}: {e}", path.display()))?.into_rgba8();
+ let (w, h) = img.dimensions();
+ Ok((img.into_raw(), w, h))
+}
+
+/// A folder's frame-NNNNN.png in order.
+pub fn frames_in(dir: &Path) -> Vec<PathBuf> {
+ let mut v: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("frame-")) && p.extension().is_some_and(|x| x == "png")).collect();
+ v.sort();
+ v
+}
+
+/// What a folder of frames made: the movie's frames, size and bytes, and whether each frame draws anything (a pixel
+/// not fully transparent), which the CapCut export cuts overlay clips by.
+#[derive(Debug, Clone, Default)]
+pub struct Made {
+ pub frames: usize,
+ pub width: u32,
+ pub height: u32,
+ pub bytes: u64,
+ pub drawn: Vec<bool>,
+}
+
+/// A folder's --alpha frames (frame-NNNNN.png, straight alpha) encoded as one transparent movie.
+pub fn encode_dir(dir: &Path, out: &Path, codec: Codec, fps: f64, quality: f32) -> R<Made> {
+ let files = frames_in(dir);
+ let first = files.first().ok_or_else(|| format!("{}: no frame-NNNNN.png to encode", dir.display()))?;
+ let (_, width, height) = read_png(first)?;
+ let mut w = Writer::create(out, codec, width, height, fps, quality)?;
+ let mut drawn = Vec::with_capacity(files.len());
+ for f in &files {
+ let (px, fw, fh) = read_png(f)?;
+ if (fw, fh) != (width, height) {
+ return Err(format!("{}: {fw}x{fh}, not the first frame's {width}x{height}", f.display()));
+ }
+ drawn.push(px.as_chunks::<4>().0.iter().any(|p| p[3] != 0));
+ w.push(&px)?;
+ }
+ let frames = w.finish()?;
+ let bytes = std::fs::metadata(out).map(|m| m.len()).unwrap_or(0);
+ Ok(Made { frames, width, height, bytes, drawn })
+}
diff --git a/io/alpha/src/mov.rs b/io/alpha/src/mov.rs
new file mode 100644
index 00000000..ca14f8fc
--- /dev/null
+++ b/io/alpha/src/mov.rs
@@ -0,0 +1,127 @@
+//! A QuickTime movie of one video track whose every sample is a whole frame of a codec raea writes itself (QuickTime
+//! Animation 'rle ', PNG 'png '): the samples into a 64-bit mdat as they come, the moov after them. Each sample is its
+//! own chunk; the ones that aren't keyframes are left out of stss.
+
+use std::fs::File;
+use std::io::{BufWriter, Seek, SeekFrom, Write};
+use std::path::Path;
+
+use crate::R;
+
+/// The track's timescale and each frame's duration in it: 30000/1001 for 29.97, 30000/1000 for 30.
+pub(crate) fn timescale(fps: f64) -> (u32, u32) {
+ let ntsc = (fps * 1.001).round();
+ if ntsc > 0.0 && (ntsc * 1000.0 / 1001.0 - fps).abs() < 1e-3 {
+ return ((ntsc as u32) * 1000, 1001);
+ }
+ (((fps * 1000.0).round() as u32).max(1), 1000)
+}
+
+pub(crate) struct Mov {
+ file: BufWriter<File>,
+ fourcc: [u8; 4],
+ name: &'static str,
+ width: u32,
+ height: u32,
+ fps: f64,
+ /// where the mdat's 64-bit size is, and where its samples start
+ mdat: u64,
+ at: u64,
+ sizes: Vec<u32>,
+ offsets: Vec<u64>,
+ keys: Vec<u32>,
+}
+
+fn atom(kind: &[u8; 4], parts: &[&[u8]]) -> Vec<u8> {
+ let len: usize = parts.iter().map(|p| p.len()).sum();
+ let mut v = Vec::with_capacity(len + 8);
+ v.extend_from_slice(&(len as u32 + 8).to_be_bytes());
+ v.extend_from_slice(kind);
+ parts.iter().for_each(|p| v.extend_from_slice(p));
+ v
+}
+
+fn atoms(kind: &[u8; 4], kids: &[Vec<u8>]) -> Vec<u8> {
+ atom(kind, &kids.iter().map(Vec::as_slice).collect::<Vec<_>>())
+}
+
+const MATRIX: [u32; 9] = [0x0001_0000, 0, 0, 0, 0x0001_0000, 0, 0, 0, 0x4000_0000];
+
+/// A Pascal string of `n` bytes in all (the sample description's compressor name).
+fn pascal(s: &str, n: usize) -> Vec<u8> {
+ let b = &s.as_bytes()[..s.len().min(n - 1)];
+ let mut v = vec![b.len() as u8];
+ v.extend_from_slice(b);
+ v.resize(n, 0);
+ v
+}
+
+impl Mov {
+ pub(crate) fn create(out: &Path, fourcc: &[u8; 4], name: &'static str, width: u32, height: u32, fps: f64) -> R<Mov> {
+ let mut file = BufWriter::new(File::create(out).map_err(|e| format!("{}: {e}", out.display()))?);
+ let ftyp = atom(b"ftyp", &[b"qt ", &0x2005_0300u32.to_be_bytes(), b"qt "]);
+ file.write_all(&ftyp).map_err(|e| e.to_string())?;
+ // mdat with a 64-bit size (size 1, then the real size), patched when the movie is finished
+ let mdat = ftyp.len() as u64;
+ let head: [&[u8]; 3] = [&1u32.to_be_bytes(), b"mdat", &0u64.to_be_bytes()];
+ file.write_all(&head.concat()).map_err(|e| e.to_string())?;
+ Ok(Mov { file, fourcc: *fourcc, name, width, height, fps, mdat, at: mdat + 16, sizes: vec![], offsets: vec![], keys: vec![] })
+ }
+
+ /// One frame's sample; `key` when it decodes on its own.
+ pub(crate) fn add(&mut self, sample: &[u8], key: bool) -> R<()> {
+ self.file.write_all(sample).map_err(|e| e.to_string())?;
+ self.offsets.push(self.at);
+ self.sizes.push(sample.len() as u32);
+ self.at += sample.len() as u64;
+ if key {
+ self.keys.push(self.sizes.len() as u32);
+ }
+ Ok(())
+ }
+
+
+ /// The moov after the samples, and the mdat's size: the movie is complete.
+ pub(crate) fn finish(mut self) -> R<u64> {
+ let (scale, delta) = timescale(self.fps);
+ let n = self.sizes.len() as u32;
+ let dur = n * delta;
+ let matrix: Vec<u8> = MATRIX.iter().flat_map(|m| m.to_be_bytes()).collect();
+ let zero4 = 0u32.to_be_bytes();
+ let mvhd = atom(b"mvhd", &[&zero4, &zero4, &zero4, &scale.to_be_bytes(), &dur.to_be_bytes(), &0x0001_0000u32.to_be_bytes(), &0x0100u16.to_be_bytes(), &[0; 10], &matrix, &[0; 24], &2u32.to_be_bytes()]);
+ let tkhd = atom(b"tkhd", &[&0x0000_000Fu32.to_be_bytes(), &zero4, &zero4, &1u32.to_be_bytes(), &zero4, &dur.to_be_bytes(), &[0; 8], &[0; 8], &matrix, &(self.width << 16).to_be_bytes(), &(self.height << 16).to_be_bytes()]);
+ let mdhd = atom(b"mdhd", &[&zero4, &zero4, &zero4, &scale.to_be_bytes(), &dur.to_be_bytes(), &0u16.to_be_bytes(), &0u16.to_be_bytes()]);
+ let hdlr = |kind: &[u8; 4], sub: &[u8; 4], name: &str| atom(b"hdlr", &[&zero4, kind, sub, b"appl", &zero4, &zero4, &pascal(name, name.len() + 1)]);
+ let vmhd = atom(b"vmhd", &[&1u32.to_be_bytes(), &0x40u16.to_be_bytes(), &[0x80, 0, 0x80, 0, 0x80, 0]]);
+ let dref = atom(b"dref", &[&zero4, &1u32.to_be_bytes(), &atom(b"alis", &[&1u32.to_be_bytes()])]);
+ // the sample description: lossless spatial quality, 72 dpi, one frame a sample, 32-bit with no colour table;
+ // BT.709 primaries and transfer (what the render's sRGB pixels are shown as), square pixels
+ let colr = atom(b"colr", &[b"nclc", &1u16.to_be_bytes(), &1u16.to_be_bytes(), &1u16.to_be_bytes()]);
+ let pasp = atom(b"pasp", &[&1u32.to_be_bytes(), &1u32.to_be_bytes()]);
+ let desc = atom(&self.fourcc, &[&[0; 6], &1u16.to_be_bytes(), &0u16.to_be_bytes(), &0u16.to_be_bytes(), b"appl", &0u32.to_be_bytes(), &0x400u32.to_be_bytes(), &(self.width as u16).to_be_bytes(), &(self.height as u16).to_be_bytes(), &0x0048_0000u32.to_be_bytes(), &0x0048_0000u32.to_be_bytes(), &zero4, &1u16.to_be_bytes(), &pascal(self.name, 32), &32u16.to_be_bytes(), &0xFFFFu16.to_be_bytes(), &colr, &pasp]);
+ let stsd = atom(b"stsd", &[&zero4, &1u32.to_be_bytes(), &desc]);
+ let stts = atom(b"stts", &[&zero4, &1u32.to_be_bytes(), &n.to_be_bytes(), &delta.to_be_bytes()]);
+ let stsc = atom(b"stsc", &[&zero4, &1u32.to_be_bytes(), &1u32.to_be_bytes(), &1u32.to_be_bytes(), &1u32.to_be_bytes()]);
+ let sizes: Vec<u8> = self.sizes.iter().flat_map(|s| s.to_be_bytes()).collect();
+ let stsz = atom(b"stsz", &[&zero4, &zero4, &n.to_be_bytes(), &sizes]);
+ let offsets: Vec<u8> = self.offsets.iter().flat_map(|o| o.to_be_bytes()).collect();
+ let co64 = atom(b"co64", &[&zero4, &n.to_be_bytes(), &offsets]);
+ let mut table = vec![stsd, stts];
+ // every sample a keyframe: no stss
+ if self.keys.len() < self.sizes.len() {
+ let keys: Vec<u8> = self.keys.iter().flat_map(|k| k.to_be_bytes()).collect();
+ table.push(atom(b"stss", &[&zero4, &(self.keys.len() as u32).to_be_bytes(), &keys]));
+ }
+ table.extend([stsc, stsz, co64]);
+ let stbl = atoms(b"stbl", &table);
+ let minf = atoms(b"minf", &[vmhd, hdlr(b"dhlr", b"alis", "DataHandler"), atoms(b"dinf", &[dref]), stbl]);
+ let mdia = atoms(b"mdia", &[mdhd, hdlr(b"mhlr", b"vide", "VideoHandler"), minf]);
+ let moov = atoms(b"moov", &[mvhd, atoms(b"trak", &[tkhd, mdia])]);
+ self.file.write_all(&moov).map_err(|e| e.to_string())?;
+ let size = self.at - self.mdat;
+ self.file.seek(SeekFrom::Start(self.mdat + 8)).map_err(|e| e.to_string())?;
+ self.file.write_all(&size.to_be_bytes()).map_err(|e| e.to_string())?;
+ self.file.flush().map_err(|e| e.to_string())?;
+ Ok(self.at + moov.len() as u64)
+ }
+}
diff --git a/io/alpha/src/movie.rs b/io/alpha/src/movie.rs
new file mode 100644
index 00000000..3223caeb
--- /dev/null
+++ b/io/alpha/src/movie.rs
@@ -0,0 +1,59 @@
+//! `raea render EDIT.tsx -o OUT.mov --alpha [--alpha-codec prores|hevc|rle|png]` (docs/capcut.feature CC1): the
+//! frames rendered as --alpha PNGs (straight alpha) into a folder of this run's own beside OUT, by the render the CLI
+//! hands in, encoded as one transparent movie, then the folder removed. No sound: an overlay is laid over footage
+//! that has its own.
+
+use std::path::{Path, PathBuf};
+
+use crate::{Codec, R, encode_dir};
+
+/// The transparent movie `args` ask for (`render ... -o OUT.mov --alpha`, read by the CLI: its --alpha-codec, its
+/// --manifest, HEVC's quality 0..1), from the frames `render` writes when given the same arguments with -o FOLDER/ and
+/// --manifest in place of -o OUT.mov; what it said, APPLIED as the movie.
+pub fn render_movie(args: &[String], out: &Path, codec: Option<&str>, manifest: Option<PathBuf>, quality: f32, render: impl Fn(&[String]) -> R<String>) -> R<String> {
+ let codec = codec.map_or(Ok(Codec::default_here()), Codec::parse)?;
+ if !codec.here() {
+ return Err(format!("{} is written through VideoToolbox, on a Mac: --alpha-codec rle (QuickTime Animation) or png here", codec.name()));
+ }
+ if let Some(d) = out.parent().filter(|d| !d.as_os_str().is_empty()) {
+ std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
+ }
+ // this run's own folder (named by its process), so nothing of anyone's is written over or removed
+ let frames = out.with_extension(format!("{}.alpha-frames", std::process::id()));
+ let manifest = manifest.unwrap_or_else(|| frames.join("render.json"));
+ let mut inner: Vec<String> = Vec::with_capacity(args.len() + 2);
+ let mut it = args.iter();
+ while let Some(a) = it.next() {
+ match a.as_str() {
+ "-o" | "--manifest" | "--alpha-codec" => {
+ it.next();
+ }
+ _ => inner.push(a.clone()),
+ }
+ }
+ inner.extend(["-o".into(), format!("{}/", frames.display()), "--manifest".into(), manifest.display().to_string()]);
+ let said = render(&inner);
+ let made = said.as_ref().map_err(String::clone).and_then(|_| {
+ let fps = std::fs::read_to_string(&manifest).ok().and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok()).and_then(|m| m["fps"].as_f64()).ok_or("the render's manifest has no fps")?;
+ encode_dir(&frames, out, codec, fps, quality)
+ });
+ let _ = std::fs::remove_dir_all(&frames);
+ let (said, made) = (said?, made?);
+ let empty = made.drawn.iter().filter(|d| !**d).count();
+ let mut msg = format!(
+ "APPLIED {} frames as {} with alpha to {} ({}x{}, {:.1} MB{})",
+ made.frames,
+ codec.name(),
+ out.display(),
+ made.width,
+ made.height,
+ made.bytes as f64 / 1e6,
+ if empty > 0 { format!(", {empty} of them drawing nothing") } else { String::new() }
+ );
+ // the folder's render said its own lines; the movie is what this made of them
+ for l in said.lines().filter(|l| !l.starts_with("APPLIED")) {
+ msg.push('\n');
+ msg.push_str(l);
+ }
+ Ok(msg)
+}
diff --git a/io/alpha/src/rle.rs b/io/alpha/src/rle.rs
new file mode 100644
index 00000000..63f77247
--- /dev/null
+++ b/io/alpha/src/rle.rs
@@ -0,0 +1,174 @@
+//! QuickTime Animation ('rle ') at 32 bits: lossless ARGB, run-length coded, as FFmpeg's qtrle decoder and
+//! QuickTime read it. A keyframe codes every line; a frame after it codes only the lines from the first that changed to
+//! the last, skipping the pixels that didn't, so a still title costs almost nothing. A frame:
+//! u32 size (all of it) | u16 header: 0, or 8 then u16 first line, u16 0, u16 lines, u16 0 | the lines | u8 0
+//! and a line: u8 skip+1, then codes until -1: n > 0 that many ARGB pixels; n < 0 one pixel repeated -n times; 0 then
+//! u8 skip+1. A frame the same as the one before is the header alone (7 bytes), which decoders keep as it was.
+
+/// Pixels as big-endian ARGB words, from straight RGBA.
+pub(crate) fn argb(rgba: &[u8]) -> Vec<u32> {
+ rgba.as_chunks::<4>().0.iter().map(|p| u32::from_be_bytes([p[3], p[0], p[1], p[2]])).collect()
+}
+
+pub(crate) struct Rle {
+ width: usize,
+ height: usize,
+ prev: Option<Vec<u32>>,
+}
+
+impl Rle {
+ pub(crate) fn new(width: u32, height: u32) -> Rle {
+ Rle { width: width as usize, height: height as usize, prev: None }
+ }
+
+ /// One frame coded; a keyframe when `key` (or the first).
+ pub(crate) fn frame(&mut self, rgba: &[u8], key: bool) -> Vec<u8> {
+ let px = argb(rgba);
+ let (w, h) = (self.width, self.height);
+ let prev = self.prev.as_deref().filter(|_| !key);
+ let row = |p: &[u32], y: usize| p[y * w..(y + 1) * w].to_vec();
+ let (mut first, mut end) = (0, h);
+ if let Some(p) = prev {
+ while first < h && px[first * w..(first + 1) * w] == p[first * w..(first + 1) * w] {
+ first += 1;
+ }
+ while end > first && px[(end - 1) * w..end * w] == p[(end - 1) * w..end * w] {
+ end -= 1;
+ }
+ }
+ let mut out = vec![0u8; 4];
+ if (first == 0 && end == h) || first == h {
+ out.extend_from_slice(&0u16.to_be_bytes());
+ } else {
+ for v in [8u16, first as u16, 0, (end - first) as u16, 0] {
+ out.extend_from_slice(&v.to_be_bytes());
+ }
+ }
+ for y in first..end {
+ line(&mut out, &row(&px, y), prev.map(|p| row(p, y)).as_deref());
+ }
+ out.push(0);
+ let size = out.len() as u32;
+ out[..4].copy_from_slice(&size.to_be_bytes());
+ self.prev = Some(px);
+ out
+ }
+}
+
+/// Skip `n` pixels after a line's first skip byte: 0 then skip+1, as many times as it takes (254 at most each).
+fn skip(out: &mut Vec<u8>, mut n: usize) {
+ while n > 0 {
+ let k = n.min(254);
+ out.push(0);
+ out.push(k as u8 + 1);
+ n -= k;
+ }
+}
+
+/// One line: the pixels that differ from the line before it (all of them on a keyframe), as runs and literals.
+fn line(out: &mut Vec<u8>, px: &[u32], prev: Option<&[u32]>) {
+ let w = px.len();
+ let same = |x: usize| prev.is_some_and(|p| p[x] == px[x]);
+ let mut x = 0;
+ // the leading skip is the line's first byte (skip + 1, 254 at most), the rest through skip codes
+ let mut lead = 0;
+ while x < w && same(x) {
+ x += 1;
+ lead += 1;
+ }
+ if lead == w {
+ // a line between two that changed, itself the same: no skip at all, and its end
+ out.extend_from_slice(&[1, 0xFF]);
+ return;
+ }
+ out.push(lead.min(254) as u8 + 1);
+ skip(out, lead.saturating_sub(254));
+ while x < w {
+ // an unchanged stretch worth a skip code (two pixels or more), or the line's unchanged end: nothing to write
+ let mut s = x;
+ while s < w && same(s) {
+ s += 1;
+ }
+ if s == w {
+ break;
+ }
+ if s > x && s - x >= 2 {
+ skip(out, s - x);
+ x = s;
+ continue;
+ }
+ // a run of one colour (two or more), or literals up to the next run or unchanged stretch
+ let mut r = x + 1;
+ while r < w && px[r] == px[x] && r - x < 128 {
+ r += 1;
+ }
+ if r - x >= 2 {
+ out.push((-((r - x) as i32)) as i8 as u8);
+ out.extend_from_slice(&px[x].to_be_bytes());
+ x = r;
+ continue;
+ }
+ let mut e = x + 1;
+ while e < w && e - x < 127 && !(e + 1 < w && px[e + 1] == px[e]) && !(same(e) && e + 1 < w && same(e + 1)) {
+ e += 1;
+ }
+ out.push((e - x) as u8);
+ for p in &px[x..e] {
+ out.extend_from_slice(&p.to_be_bytes());
+ }
+ x = e;
+ }
+ out.push(0xFF);
+}
+
+/// A frame decoded onto the frame before it (`img`, ARGB words), as FFmpeg's qtrle decoder does: for the tests.
+#[cfg(test)]
+pub(crate) fn decode(data: &[u8], img: &mut [u32], width: usize, height: usize) {
+ if data.len() < 8 {
+ return;
+ }
+ let mut i = 4;
+ let rd16 = |i: &mut usize| {
+ let v = u16::from_be_bytes([data[*i], data[*i + 1]]) as usize;
+ *i += 2;
+ v
+ };
+ let header = rd16(&mut i);
+ let (start, lines) = if header & 8 != 0 {
+ let s = rd16(&mut i);
+ i += 2;
+ let n = rd16(&mut i);
+ i += 2;
+ (s, n)
+ } else {
+ (0, height)
+ };
+ for y in start..start + lines {
+ let mut x = data[i] as usize - 1;
+ i += 1;
+ loop {
+ let code = data[i] as i8;
+ i += 1;
+ if code == -1 {
+ break;
+ }
+ if code == 0 {
+ x += data[i] as usize - 1;
+ i += 1;
+ } else if code < 0 {
+ let p = u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]);
+ i += 4;
+ for _ in 0..(-(code as i32)) {
+ img[y * width + x] = p;
+ x += 1;
+ }
+ } else {
+ for _ in 0..code {
+ img[y * width + x] = u32::from_be_bytes([data[i], data[i + 1], data[i + 2], data[i + 3]]);
+ i += 4;
+ x += 1;
+ }
+ }
+ }
+ }
+}
diff --git a/io/alpha/src/tests.rs b/io/alpha/src/tests.rs
new file mode 100644
index 00000000..29fa028e
--- /dev/null
+++ b/io/alpha/src/tests.rs
@@ -0,0 +1,144 @@
+//! CC1: what each codec writes reads back as the frames given (rle and png exactly), and the movie is one QuickTime
+//! file a parser walks to its samples.
+
+use super::*;
+
+/// A frame with a soft-edged box that moves, over nothing: straight alpha, a gradient of partial alphas.
+fn frame(w: usize, h: usize, at: usize) -> Vec<u8> {
+ let mut px = vec![0u8; w * h * 4];
+ for y in (h / 4)..(h * 3 / 4) {
+ for x in (4 + at)..(40 + at).min(w) {
+ let a = (40 + (x - at) * 5).min(255) as u8;
+ px[(y * w + x) * 4..(y * w + x) * 4 + 4].copy_from_slice(&[200, 30, (x * 3) as u8, a]);
+ }
+ }
+ px
+}
+
+fn tmp(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("raea-alpha-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_file(&d);
+ d
+}
+
+/// The movie's atoms: (kind, offset of body, body length), top level and inside moov's boxes.
+fn walk(data: &[u8], at: usize, end: usize, out: &mut Vec<(String, usize, usize)>) {
+ let mut i = at;
+ while i + 8 <= end {
+ let mut size = u32::from_be_bytes(data[i..i + 4].try_into().unwrap()) as usize;
+ let kind = String::from_utf8_lossy(&data[i + 4..i + 8]).into_owned();
+ let mut head = 8;
+ if size == 1 {
+ size = u64::from_be_bytes(data[i + 8..i + 16].try_into().unwrap()) as usize;
+ head = 16;
+ }
+ out.push((kind.clone(), i + head, size - head));
+ if matches!(kind.as_str(), "moov" | "trak" | "mdia" | "minf" | "stbl") {
+ walk(data, i + head, i + size, out);
+ }
+ i += size;
+ }
+}
+
+fn samples(data: &[u8]) -> Vec<Vec<u8>> {
+ let mut atoms = vec![];
+ walk(data, 0, data.len(), &mut atoms);
+ let body = |k: &str| atoms.iter().find(|a| a.0 == k).map(|a| &data[a.1..a.1 + a.2]).unwrap();
+ let stsz = body("stsz");
+ let n = u32::from_be_bytes(stsz[8..12].try_into().unwrap()) as usize;
+ let sizes: Vec<usize> = (0..n).map(|k| u32::from_be_bytes(stsz[12 + k * 4..16 + k * 4].try_into().unwrap()) as usize).collect();
+ let co64 = body("co64");
+ (0..n).map(|k| { let o = u64::from_be_bytes(co64[8 + k * 8..16 + k * 8].try_into().unwrap()) as usize; data[o..o + sizes[k]].to_vec() }).collect()
+}
+
+#[test]
+fn rle_reads_back_exactly_and_keeps_still_frames_small() {
+ let (w, h) = (64usize, 32usize);
+ let out = tmp("rle.mov");
+ let mut m = Writer::create(&out, Codec::Rle, w as u32, h as u32, 30.0, 0.9).unwrap();
+ // moving, then still for three frames, then an empty frame
+ let frames: Vec<Vec<u8>> = (0..4).map(|k| frame(w, h, k * 3)).chain([frame(w, h, 9), frame(w, h, 9), vec![0; w * h * 4]]).collect();
+ for f in &frames {
+ m.push(f).unwrap();
+ }
+ assert_eq!(m.finish().unwrap(), frames.len());
+ let data = std::fs::read(&out).unwrap();
+ let got = samples(&data);
+ assert_eq!(got.len(), frames.len());
+ let mut img = vec![0u32; w * h];
+ for (k, s) in got.iter().enumerate() {
+ rle::decode(s, &mut img, w, h);
+ assert_eq!(img, rle::argb(&frames[k]), "frame {k}");
+ }
+ // a frame the same as the one before is its header alone
+ assert_eq!(got[5].len(), 7);
+ let _ = std::fs::remove_file(&out);
+}
+
+#[test]
+fn rle_keyframes_decode_alone() {
+ let (w, h) = (300usize, 4usize); // a line longer than one skip or run code
+ let mut r = rle::Rle::new(w as u32, h as u32);
+ let mut px = vec![0u8; w * h * 4];
+ for x in 0..w {
+ px[(w + x) * 4 + 3] = if x % 7 == 0 { 9 } else { 255 };
+ }
+ r.frame(&frame(w, h, 0), true);
+ let key = r.frame(&px, true);
+ let mut img = vec![0xDEAD_BEEFu32; w * h];
+ rle::decode(&key, &mut img, w, h);
+ assert_eq!(img, rle::argb(&px));
+}
+
+#[test]
+fn png_movie_holds_each_frame_as_given() {
+ let (w, h) = (48usize, 24usize);
+ let out = tmp("png.mov");
+ let mut m = Writer::create(&out, Codec::Png, w as u32, h as u32, 29.97, 0.9).unwrap();
+ let frames: Vec<Vec<u8>> = (0..3).map(|k| frame(w, h, k)).collect();
+ for f in &frames {
+ m.push(f).unwrap();
+ }
+ m.finish().unwrap();
+ let data = std::fs::read(&out).unwrap();
+ for (k, s) in samples(&data).iter().enumerate() {
+ let p = tmp(&format!("f{k}.png"));
+ std::fs::write(&p, s).unwrap();
+ assert_eq!(read_png(&p).unwrap().0, frames[k]);
+ let _ = std::fs::remove_file(&p);
+ }
+ let _ = std::fs::remove_file(&out);
+}
+
+#[test]
+fn timescales_are_exact() {
+ assert_eq!(mov::timescale(30.0), (30000, 1000));
+ assert_eq!(mov::timescale(30000.0 / 1001.0), (30000, 1001));
+ assert_eq!(mov::timescale(24000.0 / 1001.0), (24000, 1001));
+ assert_eq!(mov::timescale(25.0), (25000, 1000));
+ assert_eq!(mov::timescale(60.0), (60000, 1000));
+}
+
+#[test]
+fn videotoolbox_codecs_are_said_off_apple() {
+ for c in [Codec::ProRes, Codec::Hevc] {
+ assert_eq!(c.here(), cfg!(target_vendor = "apple"));
+ }
+ assert!(Codec::parse("webm").is_err());
+ assert_eq!(Codec::parse("ProRes").unwrap(), Codec::ProRes);
+}
+
+#[cfg(target_vendor = "apple")]
+#[test]
+fn videotoolbox_writes_both_alpha_codecs() {
+ for (c, name) in [(Codec::ProRes, "prores.mov"), (Codec::Hevc, "hevc.mov")] {
+ let out = tmp(name);
+ let mut m = Writer::create(&out, c, 64, 64, 30.0, 0.9).unwrap();
+ for k in 0..5 {
+ m.push(&frame(64, 64, k)).unwrap();
+ }
+ assert_eq!(m.finish().unwrap(), 5);
+ assert!(std::fs::metadata(&out).unwrap().len() > 100, "{name}");
+ let _ = std::fs::remove_file(&out);
+ }
+}
diff --git a/io/apple/src/lib.rs b/io/apple/src/lib.rs
index 2b51de6d..2ea6e148 100644
--- a/io/apple/src/lib.rs
+++ b/io/apple/src/lib.rs
@@ -34,7 +34,8 @@ use raea_io_codec::{Audio, Backend, EncodeOpts, EncodeStats, Frame, Info, R, Vid
pub struct Apple;
-fn cf_key(k: &CFString) -> &NSString {
+/// A CoreFoundation string constant as the NSString key AVFoundation takes (toll-free bridged).
+pub fn cf_key(k: &CFString) -> &NSString {
// CFString and NSString are toll-free bridged
unsafe { &*(k as *const CFString as *const NSString) }
}
diff --git a/io/capcut/Cargo.toml b/io/capcut/Cargo.toml
new file mode 100644
index 00000000..5423e867
--- /dev/null
+++ b/io/capcut/Cargo.toml
@@ -0,0 +1,10 @@
+[package]
+name = "raea-io-capcut"
+version = "0.1.0"
+edition = "2024"
+license = "FSL-1.1-ALv2"
+publish = false
+description = "A CapCut desktop draft written from a timeline of clips (docs/capcut.feature CC2): tracks, segments and materials as CapCut's own, the project folder, the store's version markers and its project list"
+
+[dependencies]
+serde_json = "1"
diff --git a/io/capcut/src/build.rs b/io/capcut/src/build.rs
new file mode 100644
index 00000000..8af511ad
--- /dev/null
+++ b/io/capcut/src/build.rs
@@ -0,0 +1,193 @@
+//! The timeline as draft_info.json: tracks of segments, each segment's materials, every time in microseconds on the
+//! frame grid (CapCut snaps boundaries to the nearest frame when it opens a draft, so writing them there keeps them).
+//! Segments and materials start from CapCut's own (skeleton.rs).
+
+use serde_json::{Value, json};
+
+use crate::*;
+
+/// What a build made: draft_info.json's object, its timeline id and length, the import list's entries (one a file, in
+/// draft_meta_info.json), and what doesn't carry exactly.
+pub struct Built {
+ pub info: Value,
+ pub timeline_id: String,
+ pub duration_us: i64,
+ pub imports: Vec<Value>,
+ pub warnings: Vec<String>,
+}
+
+/// Frame `f` in microseconds on the grid: round(f x 1e6 / fps).
+pub fn us(f: i64, fps: f64) -> i64 {
+ (f as f64 * 1e6 / fps).round() as i64
+}
+
+fn parse(s: &str) -> Value {
+ serde_json::from_str(s).expect("skeleton.rs holds JSON")
+}
+
+/// `ratio` for canvas_config: a standard one, else "original".
+fn ratio(w: u32, h: u32) -> String {
+ fn gcd(a: u32, b: u32) -> u32 {
+ if b == 0 { a } else { gcd(b, a % b) }
+ }
+ let g = gcd(w, h).max(1);
+ let r = format!("{}:{}", w / g, h / g);
+ if ["9:16", "16:9", "1:1", "4:3", "3:4", "4:5", "2:1", "21:9"].contains(&r.as_str()) { r } else { "original".into() }
+}
+
+fn r6(v: f64) -> f64 {
+ (v * 1e6).round() / 1e6
+}
+
+/// A picture's clip: the centre offset from the canvas's centre in half-canvas units, +y up.
+fn clip_json(p: &Place, w: f64, h: f64) -> Value {
+ json!({"alpha": r6(p.opacity), "flip": {"horizontal": false, "vertical": false}, "rotation": 0.0, "scale": {"x": r6(p.scale), "y": r6(p.scale)}, "transform": {"x": r6((p.x - w / 2.0) / (w / 2.0)), "y": r6((h / 2.0 - p.y) / (h / 2.0))}})
+}
+
+pub fn build(tl: &Timeline, markers: &Markers) -> R<Built> {
+ let (w, h, fps) = (tl.width as f64, tl.height as f64, tl.fps);
+ if fps <= 0.0 || tl.width == 0 || tl.height == 0 {
+ return Err(format!("a {}x{} timeline at {fps} fps", tl.width, tl.height));
+ }
+ let mut warnings = Vec::new();
+ let mut info = parse(skeleton::DRAFT_INFO);
+ let mut mats: std::collections::BTreeMap<&str, Vec<Value>> = Default::default();
+ // one import entry a file, which every material of that file names (local_material_id)
+ let locals: Vec<String> = tl.media.iter().map(|_| uid().to_lowercase()).collect();
+ let mut used = vec![false; tl.media.len()];
+ let mut tracks = Vec::new();
+ let mut duration = 0i64;
+ for (ti, t) in tl.tracks.iter().enumerate() {
+ let mut clips: Vec<&Clip> = t.clips.iter().collect();
+ clips.sort_by_key(|c| c.start);
+ let mut segments = Vec::new();
+ let mut end_before = 0i64;
+ for (ci, c) in clips.iter().enumerate() {
+ let at = format!("{} clip {ci}", t.name);
+ let m = tl.media.get(c.media).ok_or(format!("{at}: no media {}", c.media))?;
+ if t.kind == Kind::Video && m.kind == MediaKind::Audio {
+ return Err(format!("{at}: {} has no picture", m.path.display()));
+ }
+ if c.frames <= 0 {
+ return Err(format!("{at}: {} frames", c.frames));
+ }
+ if c.start < end_before {
+ return Err(format!("{at}: starts at frame {} inside the clip before it, which ends at {end_before}", c.start));
+ }
+ if ti == 0 && t.kind == Kind::Video && c.start != end_before {
+ warnings.push(format!("{at}: a gap before frame {} on the main track, which CapCut closes on the first edit", c.start));
+ }
+ end_before = c.start + c.frames;
+ let (start, end) = (us(c.start, fps), us(c.start + c.frames, fps));
+ let target = end - start;
+ let photo = m.kind == MediaKind::Photo;
+ let total = if photo { 10_800_000_000 } else { (m.seconds * 1e6).round() as i64 };
+ let src_in = if photo { 0 } else { (c.source_in * 1e6).round() as i64 };
+ let mut src_dur = if photo { target } else { (target as f64 * c.speed).round() as i64 };
+ if !photo && src_in + src_dur > total {
+ let over = src_in + src_dur - total;
+ if over as f64 > 1e6 / fps {
+ warnings.push(format!("{at}: runs {:.0} ms past the end of {}; trimmed", over as f64 / 1000.0, m.path.display()));
+ }
+ src_dur = (total - src_in).max(0);
+ }
+ let material = uid();
+ let speed_id = uid();
+ mats.entry("speeds").or_default().push(json!({"curve_speed": null, "id": speed_id, "mode": 0, "speed": c.speed, "type": "speed"}));
+ let mut refs = vec![json!(speed_id)];
+ if c.fade_in > 0.0 || c.fade_out > 0.0 {
+ let id = uid();
+ mats.entry("audio_fades").or_default().push(json!({"fade_in_duration": (c.fade_in * 1e6).round() as i64, "fade_out_duration": (c.fade_out * 1e6).round() as i64, "fade_type": 0, "id": id, "type": "audio_fade"}));
+ refs.push(json!(id));
+ }
+ let mut seg = parse(skeleton::VIDEO_SEGMENT);
+ let name = m.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
+ if t.kind == Kind::Video {
+ for (key, comp) in skeleton::COMPANIONS {
+ let mut v = parse(comp);
+ let id = uid();
+ v["id"] = json!(id);
+ mats.entry(key).or_default().push(v);
+ refs.push(json!(id));
+ }
+ let mut v = parse(skeleton::VIDEO_MATERIAL);
+ let [l, tp, r, b] = c.place.crop;
+ v["id"] = json!(material);
+ v["type"] = json!(if photo { "photo" } else { "video" });
+ v["path"] = json!(m.path.display().to_string());
+ v["material_name"] = json!(name);
+ v["local_material_id"] = json!(locals[c.media]);
+ v["duration"] = json!(total);
+ v["width"] = json!(m.width);
+ v["height"] = json!(m.height);
+ v["has_audio"] = json!(m.has_audio);
+ v["crop"] = json!({"upper_left_x": l, "upper_left_y": tp, "upper_right_x": r, "upper_right_y": tp, "lower_left_x": l, "lower_left_y": b, "lower_right_x": r, "lower_right_y": b});
+ mats.entry("videos").or_default().push(v);
+ seg["clip"] = clip_json(&c.place, w, h);
+ } else {
+ mats.entry("audios").or_default().push(json!({
+ "app_id": 0, "category_id": "", "category_name": "local", "check_flag": 1, "copyright_limit_type": "none",
+ "duration": total, "effect_id": "", "formula_id": "", "id": material, "intensifies_path": "", "is_ai_clone_tone": false,
+ "is_text_edit_overdub": false, "is_ugc": false, "local_material_id": locals[c.media], "music_id": locals[c.media],
+ "name": name, "path": m.path.display().to_string(), "query": "", "request_id": "", "resource_id": "", "search_id": "",
+ "source_from": "", "source_platform": 0, "team_id": "", "text_id": "", "tone_category_id": "", "tone_category_name": "",
+ "tone_effect_id": "", "tone_effect_name": "", "tone_platform": "", "tone_second_category_id": "",
+ "tone_second_category_name": "", "tone_speaker": "", "tone_type": "", "type": "extract_music", "video_id": "", "wave_points": []
+ }));
+ // a clip object on a sound crashes CapCut; a sound has no HDR or uniform scale
+ seg["clip"] = Value::Null;
+ seg["hdr_settings"] = Value::Null;
+ seg.as_object_mut().unwrap().remove("uniform_scale");
+ }
+ seg["id"] = json!(uid());
+ seg["material_id"] = json!(material);
+ seg["target_timerange"] = json!({"start": start, "duration": target});
+ seg["source_timerange"] = json!({"start": src_in, "duration": src_dur});
+ seg["speed"] = json!(c.speed);
+ seg["volume"] = json!(r6(c.volume));
+ seg["last_nonzero_volume"] = json!(if c.volume > 0.0 { r6(c.volume) } else { 1.0 });
+ seg["extra_material_refs"] = Value::Array(refs);
+ seg["render_index"] = json!(ti);
+ segments.push(seg);
+ used[c.media] = true;
+ duration = duration.max(end);
+ }
+ tracks.push(json!({"attribute": 0, "flag": 0, "id": uid(), "is_default_name": t.name.is_empty(), "name": t.name, "segments": segments, "type": if t.kind == Kind::Video { "video" } else { "audio" }}));
+ }
+ let timeline_id = uid();
+ info["id"] = json!(timeline_id);
+ info["version"] = json!(markers.version);
+ info["new_version"] = json!(markers.new_version);
+ info["duration"] = json!(duration);
+ info["fps"] = json!(fps);
+ info["canvas_config"] = json!({"ratio": ratio(tl.width, tl.height), "width": tl.width, "height": tl.height, "background": null});
+ info["tracks"] = Value::Array(tracks);
+ for (k, v) in mats {
+ info["materials"][k] = Value::Array(v);
+ }
+ info["platform"] = markers.platform.clone();
+ info["last_modified_platform"] = markers.platform.clone();
+ let imports = tl
+ .media
+ .iter()
+ .enumerate()
+ .filter(|(i, _)| used[*i])
+ .map(|(i, m)| {
+ let audio = m.kind == MediaKind::Audio;
+ let meta = match m.kind {
+ MediaKind::Video => "video",
+ MediaKind::Photo => "photo",
+ MediaKind::Audio => "music",
+ };
+ json!({
+ "ai_group_type": "", "create_time": -1, "duration": if m.kind == MediaKind::Photo { 5_000_000 } else { (m.seconds * 1e6).round() as i64 },
+ "enter_from": 0, "extra_info": m.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(),
+ "file_Path": m.path.display().to_string(), "height": if audio { 0 } else { m.height }, "id": locals[i], "import_time": -1,
+ "import_time_ms": -1, "item_source": 1, "material_color_tag": "", "md5": "", "metetype": meta,
+ "roughcut_time_range": {"duration": -1, "start": -1}, "sub_time_range": {"duration": -1, "start": -1}, "type": 0,
+ "width": if audio { 0 } else { m.width }
+ })
+ })
+ .collect();
+ Ok(Built { info, timeline_id, duration_us: duration, imports, warnings })
+}
diff --git a/io/capcut/src/lib.rs b/io/capcut/src/lib.rs
new file mode 100644
index 00000000..4d72fb8e
--- /dev/null
+++ b/io/capcut/src/lib.rs
@@ -0,0 +1,121 @@
+//! A CapCut desktop draft written from a timeline of clips (docs/capcut.feature CC2): the project folder CapCut opens
+//! with its tracks, clips and media in place. The format is CapCut's own, read from drafts CapCut made
+//! (CapCut 8.5.0, with what 9.x needs as well); what CapCut itself writes is kept as it wrote it (skeleton.rs). This
+//! crate takes clips in frames and media already probed; raea's export (apps/capcut) makes them from a composition.
+
+mod build;
+mod skeleton;
+mod store;
+mod write;
+#[cfg(test)]
+mod tests;
+
+use std::path::PathBuf;
+
+pub use build::{Built, build};
+pub use store::{Markers, capcut_running, register, seed, store_root};
+pub use write::{Written, write};
+
+pub type R<T> = Result<T, String>;
+
+/// A file a clip shows or plays, as probed: its picture's upright size (none for sound) and length in seconds.
+#[derive(Clone, Debug)]
+pub struct Media {
+ pub path: PathBuf,
+ pub kind: MediaKind,
+ pub seconds: f64,
+ pub width: u32,
+ pub height: u32,
+ pub has_audio: bool,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MediaKind {
+ Video,
+ Photo,
+ Audio,
+}
+
+/// The draft's timeline: its canvas, its media, and its tracks bottom first (CapCut's first video track is its main
+/// track, magnetic: clips butted from 0).
+#[derive(Clone, Debug)]
+pub struct Timeline {
+ pub width: u32,
+ pub height: u32,
+ pub fps: f64,
+ pub media: Vec<Media>,
+ pub tracks: Vec<Track>,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Kind {
+ Video,
+ Audio,
+}
+
+#[derive(Clone, Debug)]
+pub struct Track {
+ pub kind: Kind,
+ pub name: String,
+ pub clips: Vec<Clip>,
+}
+
+/// One clip: `media` (an index into Timeline.media) from `source_in` seconds at `speed`, on the timeline from frame
+/// `start` for `frames`; its gain, fades and, for a picture, where it sits.
+#[derive(Clone, Debug)]
+pub struct Clip {
+ pub media: usize,
+ pub start: i64,
+ pub frames: i64,
+ pub source_in: f64,
+ pub speed: f64,
+ /// linear gain, 1 = 0 dB; a picture's own sound
+ pub volume: f64,
+ pub fade_in: f64,
+ pub fade_out: f64,
+ pub place: Place,
+}
+
+/// Where a picture sits: its centre in canvas pixels from the top left, its scale against the media fitted inside
+/// the canvas (CapCut's 1), its opacity, and the part of the media shown (left, top, right, bottom, 0..1).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Place {
+ pub x: f64,
+ pub y: f64,
+ pub scale: f64,
+ pub opacity: f64,
+ pub crop: [f64; 4],
+}
+
+impl Place {
+ /// Filling the canvas, as CapCut places a clip it imports.
+ pub fn centred(width: u32, height: u32) -> Place {
+ Place { x: width as f64 / 2.0, y: height as f64 / 2.0, scale: 1.0, opacity: 1.0, crop: [0.0, 0.0, 1.0, 1.0] }
+ }
+}
+
+impl Default for Clip {
+ fn default() -> Clip {
+ Clip { media: 0, start: 0, frames: 0, source_in: 0.0, speed: 1.0, volume: 1.0, fade_in: 0.0, fade_out: 0.0, place: Place { x: 0.0, y: 0.0, scale: 1.0, opacity: 1.0, crop: [0.0, 0.0, 1.0, 1.0] } }
+ }
+}
+
+/// A fresh id: an uppercase UUID-shaped string, as CapCut's own ids are (random per process, counted within it).
+pub fn uid() -> String {
+ use std::hash::{BuildHasher, Hasher};
+ use std::sync::atomic::{AtomicU64, Ordering};
+ static N: AtomicU64 = AtomicU64::new(0);
+ static SEED: std::sync::OnceLock<std::collections::hash_map::RandomState> = std::sync::OnceLock::new();
+ let s = SEED.get_or_init(std::collections::hash_map::RandomState::new);
+ let n = N.fetch_add(1, Ordering::Relaxed);
+ let half = |salt: u64| {
+ let mut h = s.build_hasher();
+ h.write_u64(n);
+ h.write_u64(salt);
+ h.finish()
+ };
+ let (a, b) = (half(0x5eed), half(0xca9c));
+ let b = (b & 0x3FFF_FFFF_FFFF_FFFF) | 0x8000_0000_0000_0000; // the variant
+ let a = (a & 0xFFFF_FFFF_FFFF_0FFF) | 0x4000; // version 4
+ format!("{:08X}-{:04X}-{:04X}-{:04X}-{:012X}", a >> 32, (a >> 16) & 0xFFFF, a & 0xFFFF, b >> 48, b & 0xFFFF_FFFF_FFFF)
+}
diff --git a/io/capcut/src/skeleton.rs b/io/capcut/src/skeleton.rs
new file mode 100644
index 00000000..c63e53ff
--- /dev/null
+++ b/io/capcut/src/skeleton.rs
@@ -0,0 +1,45 @@
+//! What CapCut itself writes, kept as it wrote it: the empty project CapCut 8.5.0 (macOS) made (draft
+//! `0824`, reproduced key for key, the per-machine ids blank as CapCut's own template.tmp
+//! holds them), and from the app-made draft `1009` (8.5.0, one clip imported and placed by hand) a video clip's segment,
+//! its material and the five companion materials CapCut gives every video segment. The builder fills in ids, times,
+//! paths and sizes; every other field stays CapCut's.
+
+/// draft_info.json of an empty 8.5.0 project
+pub const DRAFT_INFO: &str = r#"{"id":"","version":360000,"new_version":"167.0.0","name":"","duration":0,"create_time":0,"update_time":0,"fps":30.0,"is_drop_frame_timecode":false,"color_space":-1,"config":{"video_mute":false,"record_audio_last_index":1,"extract_audio_last_index":1,"original_sound_last_index":1,"subtitle_recognition_id":"","subtitle_taskinfo":[],"lyrics_recognition_id":"","lyrics_taskinfo":[],"subtitle_sync":true,"lyrics_sync":true,"voice_change_sync":false,"sticker_max_index":1,"adjust_max_index":1,"material_save_mode":0,"export_range":null,"maintrack_adsorb":true,"combination_max_index":1,"attachment_info":[],"zoom_info_params":null,"system_font_list":[],"multi_language_mode":"none","multi_language_main":"none","multi_language_current":"none","multi_language_list":[],"subtitle_keywords_config":null,"use_float_render":false},"canvas_config":{"ratio":"original","width":1920,"height":1080,"background":null},"tracks":[],"group_container":null,"materials":{"flowers":[],"videos":[],"tail_leaders":[],"audios":[],"images":[],"texts":[],"effects":[],"stickers":[],"canvases":[],"transitions":[],"audio_effects":[],"audio_fades":[],"beats":[],"material_animations":[],"placeholders":[],"placeholder_infos":[],"speeds":[],"common_mask":[],"chromas":[],"text_templates":[],"realtime_denoises":[],"audio_pannings":[],"audio_pitch_shifts":[],"video_trackings":[],"hsl":[],"drafts":[],"color_curves":[],"hsl_curves":[],"primary_color_wheels":[],"log_color_wheels":[],"video_effects":[],"audio_balances":[],"handwrites":[],"manual_deformations":[],"manual_beautys":[],"plugin_effects":[],"sound_channel_mappings":[],"green_screens":[],"shapes":[],"material_colors":[],"digital_humans":[],"digital_human_model_dressing":[],"smart_crops":[],"ai_translates":[],"audio_track_indexes":[],"loudnesses":[],"vocal_beautifys":[],"vocal_separations":[],"smart_relights":[],"time_marks":[],"multi_language_refs":[],"video_shadows":[],"video_strokes":[],"video_radius":[]},"keyframes":{"videos":[],"audios":[],"texts":[],"stickers":[],"filters":[],"adjusts":[],"handwrites":[],"effects":[]},"keyframe_graph_list":[],"platform":{"os":"mac","os_version":"","app_id":359289,"app_version":"8.5.0","app_source":"cc","device_id":"","hard_disk_id":"","mac_address":""},"last_modified_platform":{"os":"mac","os_version":"","app_id":359289,"app_version":"8.5.0","app_source":"cc","device_id":"","hard_disk_id":"","mac_address":""},"mutable_config":null,"cover":null,"retouch_cover":null,"extra_info":null,"relationships":[],"render_index_track_mode_on":true,"free_render_index_mode_on":false,"static_cover_image_path":"","source":"default","time_marks":null,"path":"","lyrics_effects":[],"uneven_animation_template_info":{"composition":"","content":"","order":"","sub_template_info_list":[]},"draft_type":"video","smart_ads_info":{"page_from":"","routine":"","draft_url":""},"function_assistant_info":{"smart_rec_applied":false,"fixed_rec_applied":false,"auto_adjust":false,"auto_adjust_segid_list":[],"color_correction":false,"color_correction_segid_list":[],"enhance_quality":false,"smooth_slow_motion":false,"deflicker_segid_list":[],"video_noise_segid_list":[],"enhance_quality_segid_list":[],"smart_segid_list":[],"retouch":false,"retouch_segid_list":[],"enhande_voice":false,"enhance_voice_segid_list":[],"audio_noise_segid_list":[],"auto_caption":false,"auto_caption_segid_list":[],"auto_caption_template_id":"","caption_opt":false,"caption_opt_segid_list":[],"eye_correction":false,"eye_correction_segid_list":[],"normalize_loudness":false,"normalize_loudness_segid_list":[],"normalize_loudness_audio_denoise_segid_list":[],"auto_adjust_fixed":false,"auto_adjust_fixed_value":50.0,"color_correction_fixed":false,"color_correction_fixed_value":50.0,"normalize_loudness_fixed":false,"enhande_voice_fixed":false,"retouch_fixed":false,"enhance_quality_fixed":false,"smooth_slow_motion_fixed":false,"fps":{"num":0,"den":1}}}"#;
+
+/// draft_meta_info.json of the same project
+pub const DRAFT_META: &str = r#"{"cloud_draft_cover":false,"cloud_draft_sync":false,"cloud_package_completed_time":"","draft_cloud_capcut_purchase_info":"","draft_cloud_last_action_download":false,"draft_cloud_package_type":"","draft_cloud_purchase_info":"","draft_cloud_template_id":"","draft_cloud_tutorial_info":"","draft_cloud_videocut_purchase_info":"","draft_cover":"draft_cover.jpg","draft_deeplink_url":"","draft_enterprise_info":{"draft_enterprise_extra":"","draft_enterprise_id":"","draft_enterprise_name":"","enterprise_material":[]},"draft_fold_path":"","draft_id":"","draft_is_ae_produce":false,"draft_is_ai_packaging_used":false,"draft_is_ai_shorts":false,"draft_is_ai_translate":false,"draft_is_article_video_draft":false,"draft_is_cloud_temp_draft":false,"draft_is_from_deeplink":"false","draft_is_invisible":false,"draft_is_web_article_video":false,"draft_materials":[{"type":0,"value":[]},{"type":1,"value":[]},{"type":2,"value":[]},{"type":3,"value":[]},{"type":6,"value":[]},{"type":7,"value":[]},{"type":8,"value":[]}],"draft_materials_copied_info":[],"draft_name":"","draft_need_rename_folder":false,"draft_new_version":"","draft_removable_storage_device":"","draft_root_path":"","draft_segment_extra_info":[],"draft_timeline_materials_size_":0,"draft_type":"","draft_web_article_video_enter_from":"","tm_draft_cloud_completed":"","tm_draft_cloud_entry_id":-1,"tm_draft_cloud_modified":0,"tm_draft_cloud_parent_entry_id":-1,"tm_draft_cloud_space_id":-1,"tm_draft_cloud_user_id":-1,"tm_draft_create":0,"tm_draft_modified":0,"tm_draft_removed":0,"tm_duration":0}"#;
+
+/// one root_meta_info.json all_draft_store entry
+pub const ROOT_ENTRY: &str = r#"{"cloud_draft_cover":false,"cloud_draft_sync":false,"draft_cloud_last_action_download":false,"draft_cloud_purchase_info":"","draft_cloud_template_id":"","draft_cloud_tutorial_info":"","draft_cloud_videocut_purchase_info":"","draft_cover":"","draft_fold_path":"","draft_id":"","draft_is_ai_shorts":false,"draft_is_cloud_temp_draft":false,"draft_is_invisible":false,"draft_is_web_article_video":false,"draft_json_file":"","draft_name":"","draft_new_version":"","draft_root_path":"","draft_timeline_materials_size":0,"draft_type":"","draft_web_article_video_enter_from":"","streaming_edit_draft_ready":true,"tm_draft_cloud_completed":"","tm_draft_cloud_entry_id":-1,"tm_draft_cloud_modified":0,"tm_draft_cloud_parent_entry_id":-1,"tm_draft_cloud_space_id":-1,"tm_draft_cloud_user_id":-1,"tm_draft_create":0,"tm_draft_modified":0,"tm_draft_removed":0,"tm_duration":0}"#;
+
+/// a video segment as CapCut 8.5.0 made it
+pub const VIDEO_SEGMENT: &str = r#"{"id":"","source_timerange":{"start":0,"duration":0},"target_timerange":{"start":0,"duration":0},"render_timerange":{"start":0,"duration":0},"desc":"","state":0,"speed":1.0,"is_loop":false,"is_tone_modify":false,"reverse":false,"intensifies_audio":false,"cartoon":false,"volume":1.0,"last_nonzero_volume":1.0,"clip":{"scale":{"x":1.0,"y":1.0},"rotation":0.0,"transform":{"x":0.0,"y":0.0},"flip":{"vertical":false,"horizontal":false},"alpha":1.0},"uniform_scale":{"on":true,"value":1.0},"material_id":"","extra_material_refs":[],"render_index":0,"keyframe_refs":[],"enable_lut":true,"enable_adjust":true,"enable_hsl":false,"visible":true,"group_id":"","enable_color_curves":true,"enable_hsl_curves":true,"track_render_index":0,"hdr_settings":{"mode":1,"intensity":1.0,"nits":1000},"enable_color_wheels":true,"track_attribute":0,"is_placeholder":false,"template_id":"","enable_smart_color_adjust":false,"template_scene":"default","common_keyframes":[],"caption_info":null,"responsive_layout":{"enable":false,"target_follow":"","size_layout":0,"horizontal_pos_layout":0,"vertical_pos_layout":0},"enable_color_match_adjust":false,"enable_color_correct_adjust":false,"enable_adjust_mask":false,"raw_segment_id":"","lyric_keyframes":null,"enable_video_mask":true,"digital_human_template_group_id":"","color_correct_alg_result":"","source":"segmentsourcenormal","enable_mask_stroke":false,"enable_mask_shadow":false,"enable_color_adjust_pro":false}"#;
+
+/// a video material (materials.videos[]) as CapCut 8.5.0 made it
+pub const VIDEO_MATERIAL: &str = r#"{"id":"","unique_id":"","type":"video","duration":0,"path":"","media_path":"","local_id":"","has_audio":false,"reverse_path":"","intensifies_path":"","reverse_intensifies_path":"","intensifies_audio_path":"","cartoon_path":"","width":0,"height":0,"category_id":"","category_name":"local","material_id":"","material_name":"","material_url":"","crop":{"upper_left_x":0.0,"upper_left_y":0.0,"upper_right_x":1.0,"upper_right_y":0.0,"lower_left_x":0.0,"lower_left_y":1.0,"lower_right_x":1.0,"lower_right_y":1.0},"crop_ratio":"free","audio_fade":null,"crop_scale":1.0,"extra_type_option":0,"stable":{"stable_level":0,"matrix_path":"","time_range":{"start":0,"duration":0}},"matting":{"flag":0,"path":"","interactiveTime":[],"has_use_quick_brush":false,"strokes":[],"has_use_quick_eraser":false,"expansion":0,"feather":0,"reverse":false,"custom_matting_id":"","enable_matting_stroke":false},"source":0,"source_platform":0,"formula_id":"","check_flag":62978047,"video_algorithm":{"algorithms":[],"time_range":null,"path":"","gameplay_configs":[],"ai_in_painting_config":[],"complement_frame_config":null,"motion_blur_config":null,"deflicker":null,"noise_reduction":null,"quality_enhance":null,"super_resolution":null,"ai_background_configs":[],"smart_complement_frame":null,"aigc_generate":null,"aigc_generate_list":[],"mouth_shape_driver":null,"ai_expression_driven":null,"ai_motion_driven":null,"image_interpretation":null,"story_video_modify_video_config":{"task_id":"","is_overwrite_last_video":false,"tracker_task_id":""},"skip_algorithm_index":[]},"is_unified_beauty_mode":false,"object_locked":null,"smart_motion":null,"multi_camera_info":null,"freeze":null,"picture_from":"none","picture_set_category_id":"","picture_set_category_name":"","team_id":"","local_material_id":"","origin_material_id":"","request_id":"","has_sound_separated":false,"is_text_edit_overdub":false,"is_ai_generate_content":false,"aigc_type":"none","is_copyright":false,"aigc_history_id":"","aigc_item_id":"","local_material_from":"","smart_match_info":null,"beauty_face_preset_infos":[],"beauty_body_preset_id":"","beauty_face_auto_preset":{"preset_id":"","name":"","rate_map":"","scene":""},"beauty_face_auto_preset_infos":[],"beauty_body_auto_preset":null,"live_photo_timestamp":-1,"live_photo_cover_path":"","content_feature_info":null,"corner_pin":null,"surface_trackings":[],"video_mask_stroke":{"resource_id":"","path":"","type":"","color":"","size":0.0,"alpha":0.0,"distance":0.0,"texture":0.0,"horizontal_shift":0.0,"vertical_shift":0.0},"video_mask_shadow":{"resource_id":"","path":"","color":"","alpha":0.0,"blur":0.0,"distance":0.0,"angle":0.0}}"#;
+
+/// the companions CapCut gives every video segment (by materials key), each referenced from its extra_material_refs
+pub const COMPANIONS: &[(&str, &str)] = &[
+ ("canvases", r#"{"id":"","type":"canvas_color","color":"","blur":0.0,"image":"","album_image":"","image_id":"","image_name":"","source_platform":0,"team_id":""}"#),
+ ("placeholder_infos", r#"{"id":"","type":"placeholder_info","meta_type":"none","res_path":"","res_text":"","error_path":"","error_text":""}"#),
+ ("sound_channel_mappings", r#"{"id":"","type":"","audio_channel_mapping":0,"is_config_open":false}"#),
+ ("material_colors", r#"{"id":"","is_color_clip":false,"is_gradient":false,"solid_color":"","gradient_colors":[],"gradient_percents":[],"gradient_angle":90.0,"width":0.0,"height":0.0}"#),
+ ("vocal_separations", r#"{"id":"","type":"vocal_separation","choice":0,"removed_sounds":[],"time_range":null,"production_path":"","final_algorithm":"","enter_from":""}"#),
+];
+
+// the small sidecar files, verbatim
+pub const AGENCY_CONFIG: &str = r#"{"is_auto_agency_enabled":false,"is_auto_agency_popup":false,"is_single_agency_mode":false,"marterials":null,"use_converter":false,"video_resolution":720}"#;
+pub const PC_COMMON: &str = r#"{"ai_packaging_infos":[],"ai_packaging_report_info":{"caption_id_list":[],"commercial_material":"","material_source":"","method":"","page_from":"","style":"","task_id":"","text_style":"","tos_id":"","video_category":""},"broll":{"ai_packaging_infos":[],"ai_packaging_report_info":{"caption_id_list":[],"commercial_material":"","material_source":"","method":"","page_from":"","style":"","task_id":"","text_style":"","tos_id":"","video_category":""}},"commercial_music_category_ids":[],"pc_feature_flag":0,"recognize_tasks":[],"reference_lines_config":{"horizontal_lines":[],"is_lock":false,"is_visible":false,"vertical_lines":[]},"safe_area_type":0,"template_item_infos":[],"unlock_template_ids":[]}"#;
+pub const PERF_OPT: &str = r#"{"manual_cancle_precombine_segs":null,"need_auto_precombine_segs":null}"#;
+pub const PC_TIMELINE: &str = r#"{"reference_lines_config":{"horizontal_lines":[],"is_lock":false,"is_visible":false,"vertical_lines":[]},"safe_area_type":0}"#;
+pub const ACTION_SCENE: &str = r#"{"action_scene":{"removed_segments":[],"segment_infos":[]}}"#;
+pub const GEN_AI: &str = r#"{"gen_ai":{"ai_func_config":{"ai_common_configs":[],"ai_effect_configs":[],"ai_func_list":[],"aigc_generation_configs":[]},"cc_agent_info":{"agent_stringent_section_id_list":[],"agent_stringent_used_tool_list":[],"is_agent_stringent_used":false,"is_agent_used":false,"tool_list":[]},"id":"","scene":"","version":"1.0.0"}}"#;
+pub const SCRIPT_VIDEO: &str = r#"{"script_video":{"attachment_valid":false,"language":"","overdub_recover":[],"overdub_sentence_ids":[],"parts":[],"sync_subtitle":false,"translate_segments":[],"translate_type":"","version":"1.0.0"}}"#;
+pub const EDITING: &str = r#"{"editing_draft":{"ai_remove_filter_words":{"enter_source":"","right_id":""},"ai_shorts_info":{"report_params":"","type":0},"cover_extra_info":{"draft_id":"","position":0,"select_segment_id":"","select_segment_source_start":0,"select_segment_target_start":0,"type":1},"crop_info_extra":{"crop_mirror_type":0,"crop_rotate":0.0,"crop_rotate_total":0.0},"digital_human_template_to_video_info":{"has_upload_material":false,"template_type":0},"draft_used_recommend_function":"","edit_type":0,"eye_correct_enabled_multi_face_time":0,"has_adjusted_render_layer":false,"image_ai_chat_info":{"before_chat_edit":false,"draft_modify_time":0,"keyword_content":"","keyword_type":"","message_id":"","model_name":"","need_restore":false,"picture_id":"","prompt_content":"","prompt_from":"","sugs_info":[]},"is_open_expand_player":false,"is_template_text_ai_generate":false,"is_use_adjust":false,"is_use_ai_expand":false,"is_use_ai_remove":false,"is_use_ai_video":false,"is_use_audio_separation":false,"is_use_chroma_key":false,"is_use_curve_speed":false,"is_use_digital_human":false,"is_use_edit_multi_camera":false,"is_use_lip_sync":false,"is_use_lock_object":false,"is_use_loudness_unify":false,"is_use_noise_reduction":false,"is_use_one_click_beauty":false,"is_use_one_click_ultra_hd":false,"is_use_retouch_face":false,"is_use_smart_adjust_color":false,"is_use_smart_body_beautify":false,"is_use_smart_motion":false,"is_use_subtitle_recognition":false,"is_use_text_to_audio":false,"material_edit_session":{"material_edit_info":[],"session_id":"","session_time":0},"paste_segment_list":[],"profile_entrance_type":"","publish_enter_from":"","publish_type":"","single_function_type":0,"text_convert_case_types":[],"version":"1.0.0","video_recording_create_draft":""}}"#;
+
+/// 8.5.0's version markers, when the store has no app-made draft to take them from
+pub const VERSION: i64 = 360000;
+pub const NEW_VERSION: &str = "167.0.0";
+pub const APP_VERSION: &str = "8.5.0";
+pub const APP_ID: i64 = 359289;
diff --git a/io/capcut/src/store.rs b/io/capcut/src/store.rs
new file mode 100644
index 00000000..b4b9a034
--- /dev/null
+++ b/io/capcut/src/store.rs
@@ -0,0 +1,103 @@
+//! CapCut's draft store: where it is, the version markers of the newest draft CapCut made there (each build refuses a
+//! draft whose markers look old: "from an unusual path"), whether CapCut is running, and entering a draft in
+//! root_meta_info.json, the list CapCut shows its projects from and rewrites when it quits.
+
+use std::path::{Path, PathBuf};
+
+use serde_json::{Value, json};
+
+use crate::{R, skeleton};
+
+/// The store on this machine, whether or not CapCut has made it yet.
+pub fn store_root() -> Option<PathBuf> {
+ if cfg!(target_os = "windows") {
+ let local = std::env::var_os("LOCALAPPDATA")?;
+ return Some(PathBuf::from(local).join("CapCut/User Data/Projects/com.lveditor.draft"));
+ }
+ let home = std::env::var_os("HOME")?;
+ cfg!(target_os = "macos").then(|| PathBuf::from(home).join("Movies/CapCut/User Data/Projects/com.lveditor.draft"))
+}
+
+/// Version markers and the platform block a new draft is stamped with.
+#[derive(Clone, Debug)]
+pub struct Markers {
+ pub version: i64,
+ pub new_version: String,
+ pub platform: Value,
+ /// the draft they came from, when one did
+ pub from: Option<String>,
+}
+
+impl Default for Markers {
+ /// CapCut 8.5.0's, with this system's name and the machine's ids blank (as CapCut's own template.tmp holds them)
+ fn default() -> Markers {
+ let os = if cfg!(target_os = "windows") { "windows" } else { "mac" };
+ Markers {
+ version: skeleton::VERSION,
+ new_version: skeleton::NEW_VERSION.into(),
+ platform: json!({"os": os, "os_version": "", "app_id": skeleton::APP_ID, "app_version": skeleton::APP_VERSION, "app_source": "cc", "device_id": "", "hard_disk_id": "", "mac_address": ""}),
+ from: None,
+ }
+ }
+}
+
+/// The markers of the draft in `root` CapCut saved last (its platform's app_source "cc"), else 8.5.0's. Read only.
+pub fn seed(root: &Path) -> Markers {
+ let mut best: Option<(std::time::SystemTime, Markers)> = None;
+ for e in std::fs::read_dir(root).into_iter().flatten().flatten() {
+ let info = e.path().join("draft_info.json");
+ let Some(j) = std::fs::read_to_string(&info).ok().and_then(|t| serde_json::from_str::<Value>(&t).ok()) else { continue };
+ let p = if j["last_modified_platform"].is_object() { &j["last_modified_platform"] } else { &j["platform"] };
+ let (Some(v), Some(nv)) = (j["version"].as_i64(), j["new_version"].as_str()) else { continue };
+ if p["app_source"] != "cc" || p["app_version"].as_str().is_none_or(str::is_empty) || nv.is_empty() {
+ continue;
+ }
+ let when = std::fs::metadata(&info).and_then(|m| m.modified()).unwrap_or(std::time::UNIX_EPOCH);
+ if best.as_ref().is_none_or(|(b, _)| when > *b) {
+ best = Some((when, Markers { version: v, new_version: nv.into(), platform: p.clone(), from: Some(e.file_name().to_string_lossy().into_owned()) }));
+ }
+ }
+ best.map(|b| b.1).unwrap_or_default()
+}
+
+/// Whether CapCut is running (it rewrites root_meta_info.json when it quits, dropping what was entered meanwhile).
+pub fn capcut_running() -> bool {
+ use std::process::Command;
+ if cfg!(target_os = "windows") {
+ return Command::new("tasklist").args(["/FI", "IMAGENAME eq CapCut.exe", "/NH"]).output().is_ok_and(|o| String::from_utf8_lossy(&o.stdout).to_lowercase().contains("capcut.exe"));
+ }
+ Command::new("pgrep").args(["-f", "CapCut.app/Contents/MacOS/"]).output().is_ok_and(|o| o.status.success() && !o.stdout.is_empty())
+}
+
+/// The draft at `draft` (a folder in `root`) entered in root_meta_info.json, after a copy of that file is kept in
+/// `backups`; written through a temporary file and a rename, every other entry as it was. Refused while CapCut runs.
+pub fn register(root: &Path, draft: &Path, meta: &Value, info_bytes: usize, backups: &Path) -> R<PathBuf> {
+ if capcut_running() {
+ return Err("CapCut is open: it rewrites its project list when it quits, so the draft would drop off it. Quit CapCut and enter the draft again".into());
+ }
+ let index = root.join("root_meta_info.json");
+ let mut j: Value = match std::fs::read_to_string(&index) {
+ Ok(t) => serde_json::from_str(&t).map_err(|e| format!("{}: {e}", index.display()))?,
+ Err(_) => json!({"all_draft_store": [], "draft_ids": 0, "root_path": root.display().to_string()}),
+ };
+ std::fs::create_dir_all(backups).map_err(|e| format!("{}: {e}", backups.display()))?;
+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0);
+ let backup = backups.join(format!("root_meta_info.{stamp}.json"));
+ if index.exists() {
+ std::fs::copy(&index, &backup).map_err(|e| format!("{}: {e}", backup.display()))?;
+ }
+ let mut entry: Value = serde_json::from_str(skeleton::ROOT_ENTRY).expect("skeleton.rs holds JSON");
+ for k in ["draft_fold_path", "draft_id", "draft_name", "draft_root_path", "tm_draft_create", "tm_draft_modified", "tm_duration"] {
+ entry[k] = meta[k].clone();
+ }
+ entry["draft_cover"] = json!(draft.join("draft_cover.jpg").display().to_string());
+ entry["draft_json_file"] = json!(draft.join("draft_info.json").display().to_string());
+ entry["draft_timeline_materials_size"] = json!(info_bytes);
+ let list = j["all_draft_store"].as_array_mut().ok_or(format!("{}: no all_draft_store list", index.display()))?;
+ list.insert(0, entry);
+ j["draft_ids"] = json!(j["draft_ids"].as_i64().unwrap_or(0) + 1);
+ let tmp = root.join(format!(".root_meta_info.{}.tmp", std::process::id()));
+ std::fs::write(&tmp, serde_json::to_vec(&j).map_err(|e| e.to_string())?).map_err(|e| format!("{}: {e}", tmp.display()))?;
+ std::fs::rename(&tmp, &index).map_err(|e| format!("{}: {e}", index.display()))?;
+ Ok(backup)
+}
diff --git a/io/capcut/src/tests.rs b/io/capcut/src/tests.rs
new file mode 100644
index 00000000..ad3a6cef
--- /dev/null
+++ b/io/capcut/src/tests.rs
@@ -0,0 +1,160 @@
+//! CC2: a timeline's draft links every segment to its materials as CapCut's own do, keeps its times on the frame
+//! grid, mutes nothing it shouldn't, and lands as a whole project folder; registration keeps every other entry.
+
+use std::path::Path;
+
+use serde_json::Value;
+
+use super::*;
+
+fn tmp(name: &str) -> PathBuf {
+ let d = std::env::temp_dir().join(format!("raea-capcut-{}-{name}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&d);
+ std::fs::create_dir_all(&d).unwrap();
+ d
+}
+
+/// Two shots on the main track, a picture in picture above, a sound below; media files of a few bytes.
+fn timeline(dir: &Path) -> Timeline {
+ let file = |n: &str| {
+ let p = dir.join(n);
+ std::fs::write(&p, n.as_bytes()).unwrap();
+ p
+ };
+ let media = vec![
+ Media { path: file("a.mp4"), kind: MediaKind::Video, seconds: 4.0, width: 1080, height: 1920, has_audio: true },
+ Media { path: file("b.mp4"), kind: MediaKind::Video, seconds: 4.0, width: 1920, height: 1080, has_audio: false },
+ Media { path: file("music.wav"), kind: MediaKind::Audio, seconds: 6.0, width: 0, height: 0, has_audio: true },
+ ];
+ let main = Place::centred(1080, 1920);
+ let pip = Place { x: 840.0, y: 380.0, scale: 0.3333, opacity: 1.0, crop: [0.0, 0.0, 1.0, 1.0] };
+ Timeline {
+ width: 1080,
+ height: 1920,
+ fps: 30.0,
+ media,
+ tracks: vec![
+ Track { kind: Kind::Video, name: String::new(), clips: vec![Clip { media: 0, start: 0, frames: 45, source_in: 0.5, volume: 0.0, place: main, ..Clip::default() }, Clip { media: 1, start: 45, frames: 45, source_in: 1.0, volume: 0.0, place: main, ..Clip::default() }] },
+ Track { kind: Kind::Video, name: "pip".into(), clips: vec![Clip { media: 1, start: 60, frames: 29, source_in: 0.0, speed: 2.0, place: pip, ..Clip::default() }] },
+ Track { kind: Kind::Audio, name: "music".into(), clips: vec![Clip { media: 2, start: 0, frames: 90, volume: 0.5, fade_out: 0.5, ..Clip::default() }] },
+ ],
+ }
+}
+
+fn ids(v: &Value, key: &str) -> Vec<String> {
+ v["materials"][key].as_array().unwrap().iter().map(|m| m["id"].as_str().unwrap().to_string()).collect()
+}
+
+#[test]
+fn segments_link_to_materials_on_the_frame_grid() {
+ let d = tmp("build");
+ let b = build(&timeline(&d), &Markers::default()).unwrap();
+ let info = &b.info;
+ let tracks = info["tracks"].as_array().unwrap();
+ assert_eq!(tracks.iter().map(|t| t["type"].as_str().unwrap()).collect::<Vec<_>>(), ["video", "video", "audio"]);
+ let all: Vec<String> = info["materials"].as_object().unwrap().values().flat_map(|l| l.as_array().unwrap().iter().map(|m| m["id"].as_str().unwrap().to_string())).collect();
+ for t in tracks {
+ for s in t["segments"].as_array().unwrap() {
+ assert!(all.contains(&s["material_id"].as_str().unwrap().to_string()));
+ for r in s["extra_material_refs"].as_array().unwrap() {
+ assert!(all.contains(&r.as_str().unwrap().to_string()), "{r} names no material");
+ }
+ // on the grid: a boundary is a whole frame's microseconds
+ let st = s["target_timerange"]["start"].as_i64().unwrap();
+ assert_eq!(build::us((st as f64 * 30.0 / 1e6).round() as i64, 30.0), st);
+ }
+ }
+ let main = tracks[0]["segments"].as_array().unwrap();
+ assert_eq!(main[0]["target_timerange"], serde_json::json!({"start": 0, "duration": 1_500_000}));
+ assert_eq!(main[1]["target_timerange"]["start"], 1_500_000);
+ assert_eq!(main[0]["source_timerange"]["start"], 500_000);
+ // a video segment has CapCut's five companions and its speed
+ assert_eq!(main[0]["extra_material_refs"].as_array().unwrap().len(), 6);
+ // 2x: the source runs twice the timeline's length; 29 frames at 30 fps
+ let pip = &tracks[1]["segments"][0];
+ assert_eq!(pip["source_timerange"]["duration"].as_i64().unwrap(), 2 * (build::us(89, 30.0) - build::us(60, 30.0)));
+ let x = pip["clip"]["transform"]["x"].as_f64().unwrap();
+ assert!((x - (840.0 - 540.0) / 540.0).abs() < 1e-6 && pip["clip"]["transform"]["y"].as_f64().unwrap() > 0.0, "up is +y");
+ // a sound: no clip object (it crashes CapCut), its fade a material of its own
+ let snd = &tracks[2]["segments"][0];
+ assert!(snd["clip"].is_null() && snd["hdr_settings"].is_null() && snd.get("uniform_scale").is_none());
+ assert_eq!(snd["volume"], 0.5);
+ assert_eq!(ids(info, "audio_fades").len(), 1);
+ // one material a segment, one import a file, each material naming its file's import
+ assert_eq!(ids(info, "videos").len(), 3);
+ assert_eq!(b.imports.len(), 3);
+ let locals: Vec<&str> = b.imports.iter().map(|i| i["id"].as_str().unwrap()).collect();
+ for v in info["materials"]["videos"].as_array().unwrap() {
+ assert!(locals.contains(&v["local_material_id"].as_str().unwrap()));
+ }
+ assert_eq!(info["canvas_config"]["ratio"], "9:16");
+ assert_eq!(info["duration"], 3_000_000);
+ assert!(b.warnings.is_empty(), "{:?}", b.warnings);
+ let _ = std::fs::remove_dir_all(&d);
+}
+
+#[test]
+fn a_draft_folder_is_whole_and_its_timeline_copies_identical() {
+ let d = tmp("write");
+ let root = d.join("store");
+ let w = write(&timeline(&d), &root, "fixture", &Markers::default(), Some(b"\xFF\xD8jpeg")).unwrap();
+ let info = std::fs::read(w.dir.join("draft_info.json")).unwrap();
+ let j: Value = serde_json::from_slice(&info).unwrap();
+ let tid = j["id"].as_str().unwrap();
+ for rel in ["draft_info.json.bak", "template-2.tmp", &format!("Timelines/{tid}/draft_info.json"), &format!("Timelines/{tid}/template-2.tmp")] {
+ assert_eq!(std::fs::read(w.dir.join(rel)).unwrap(), info, "{rel}");
+ }
+ for rel in ["draft_meta_info.json", "draft_settings", "timeline_layout.json", "Timelines/project.json", "draft_cover.jpg", "assets/video/a.mp4", "assets/audio/music.wav", "matting", "Resources/videoAlg"] {
+ assert!(w.dir.join(rel).exists(), "{rel}");
+ }
+ // media named where it is in the draft
+ let path = j["materials"]["videos"][0]["path"].as_str().unwrap();
+ assert!(path.starts_with(&w.dir.display().to_string()) && Path::new(path).exists(), "{path}");
+ assert_eq!(w.meta["draft_timeline_materials_size_"], info.len());
+ // never over a draft that's there, and nothing hidden left behind
+ assert!(write(&timeline(&d), &root, "fixture", &Markers::default(), None).is_err());
+ assert_eq!(std::fs::read_dir(&root).unwrap().count(), 1);
+ let _ = std::fs::remove_dir_all(&d);
+}
+
+#[test]
+fn registration_adds_one_entry_and_keeps_the_rest() {
+ let d = tmp("register");
+ let root = d.join("store");
+ std::fs::create_dir_all(&root).unwrap();
+ std::fs::write(root.join("root_meta_info.json"), r#"{"all_draft_store":[{"draft_name":"0824","draft_id":"X"}],"draft_ids":1,"root_path":"r"}"#).unwrap();
+ let w = write(&timeline(&d), &root, "mine", &Markers::default(), None).unwrap();
+ if capcut_running() {
+ assert!(register(&root, &w.dir, &w.meta, w.info_bytes, &d.join("backups")).is_err());
+ return;
+ }
+ let backup = register(&root, &w.dir, &w.meta, w.info_bytes, &d.join("backups")).unwrap();
+ let j: Value = serde_json::from_str(&std::fs::read_to_string(root.join("root_meta_info.json")).unwrap()).unwrap();
+ let list = j["all_draft_store"].as_array().unwrap();
+ assert_eq!(list.len(), 2);
+ assert_eq!(list[0]["draft_name"], "mine");
+ assert_eq!(list[1]["draft_name"], "0824");
+ assert_eq!(j["draft_ids"], 2);
+ assert!(std::fs::read_to_string(backup).unwrap().contains("0824"));
+ let _ = std::fs::remove_dir_all(&d);
+}
+
+#[test]
+fn markers_come_from_the_newest_app_made_draft() {
+ let d = tmp("seed");
+ for (name, ver, src) in [("old", "8.5.0", "cc"), ("tool", "", "cc"), ("other", "9.1.0", "lv")] {
+ std::fs::create_dir_all(d.join(name)).unwrap();
+ std::fs::write(d.join(name).join("draft_info.json"), format!(r#"{{"version":360000,"new_version":"167.0.0","platform":{{"app_source":"{src}","app_version":"{ver}"}}}}"#)).unwrap();
+ }
+ let m = seed(&d);
+ assert_eq!(m.from.as_deref(), Some("old"));
+ assert_eq!(seed(&d.join("none")).new_version, "167.0.0");
+ let _ = std::fs::remove_dir_all(&d);
+}
+
+#[test]
+fn ids_are_uuid_shaped_and_distinct() {
+ let a: Vec<String> = (0..1000).map(|_| uid()).collect();
+ assert_eq!(a.iter().collect::<std::collections::HashSet<_>>().len(), 1000);
+ assert!(a.iter().all(|i| i.len() == 36 && i.as_bytes()[14] == b'4'));
+}
diff --git a/io/capcut/src/write.rs b/io/capcut/src/write.rs
new file mode 100644
index 00000000..fa7d7f88
--- /dev/null
+++ b/io/capcut/src/write.rs
@@ -0,0 +1,134 @@
+//! A draft folder laid out as CapCut 8.5.0 lays one out: draft_info.json and its byte-identical copies (8.4 and 8.5
+//! read the root one, 9.2.8 and later the one under Timelines/<id>/), the timeline list, the import list, the sidecars
+//! CapCut writes at their defaults, and the media in assets/ where sandboxed CapCut can read it. Built in a hidden
+//! folder beside the draft and renamed into place, so CapCut never sees half a draft; never over a folder that's there.
+
+use std::path::{Path, PathBuf};
+
+use serde_json::{Value, json};
+
+use crate::*;
+
+/// What a write made: the draft's folder and id, its length, draft_meta_info.json's object (registration reads it),
+/// draft_info.json's size, and what doesn't carry exactly.
+pub struct Written {
+ pub dir: PathBuf,
+ pub draft_id: String,
+ pub duration_us: i64,
+ pub meta: Value,
+ pub info_bytes: usize,
+ pub warnings: Vec<String>,
+}
+
+/// `tl` as a draft named `name` in `root` (CapCut's store, or any folder), its media copied into assets/ (a clone on
+/// APFS), `cover` (a JPEG) its thumbnail in CapCut's list.
+pub fn write(tl: &Timeline, root: &Path, name: &str, markers: &Markers, cover: Option<&[u8]>) -> R<Written> {
+ if name.is_empty() || name.contains(['/', '\\']) || name.starts_with('.') {
+ return Err(format!("{name:?} can't name a draft folder"));
+ }
+ let dir = root.join(name);
+ if dir.exists() {
+ return Err(format!("{} is there already; a draft is never written over", dir.display()));
+ }
+ std::fs::create_dir_all(root).map_err(|e| format!("{}: {e}", root.display()))?;
+ let tmp = root.join(format!(".raea-draft-{}-{}", std::process::id(), uid()));
+ let made = fill(tl, &tmp, &dir, root, name, markers, cover);
+ match made {
+ Ok(w) => {
+ std::fs::rename(&tmp, &dir).map_err(|e| format!("{}: {e}", dir.display()))?;
+ Ok(w)
+ }
+ Err(e) => {
+ // the hidden folder this write made, and only it
+ let _ = std::fs::remove_dir_all(&tmp);
+ Err(e)
+ }
+ }
+}
+
+fn put(dir: &Path, rel: &str, data: &[u8]) -> R<()> {
+ let p = dir.join(rel);
+ if let Some(d) = p.parent() {
+ std::fs::create_dir_all(d).map_err(|e| format!("{}: {e}", d.display()))?;
+ }
+ std::fs::write(&p, data).map_err(|e| format!("{}: {e}", p.display()))
+}
+
+fn fill(tl: &Timeline, tmp: &Path, dir: &Path, root: &Path, name: &str, markers: &Markers, cover: Option<&[u8]>) -> R<Written> {
+ // the media into assets/<kind>/, each file once, named apart when two share a name; the timeline then names them
+ // where they will be once the folder is renamed into place
+ let mut placed = tl.clone();
+ let mut names = std::collections::HashSet::new();
+ for m in &mut placed.media {
+ let kind = match m.kind {
+ MediaKind::Video => "video",
+ MediaKind::Photo => "image",
+ MediaKind::Audio => "audio",
+ };
+ let file = m.path.file_name().map(|n| n.to_string_lossy().into_owned()).ok_or(format!("{}: no file name", m.path.display()))?;
+ let mut stored = file.clone();
+ let mut k = 1;
+ while !names.insert(format!("{kind}/{stored}")) {
+ k += 1;
+ stored = format!("{k}-{file}");
+ }
+ let rel = format!("assets/{kind}/{stored}");
+ std::fs::create_dir_all(tmp.join("assets").join(kind)).map_err(|e| e.to_string())?;
+ // std's copy clones on APFS (no space until one of them changes)
+ std::fs::copy(&m.path, tmp.join(&rel)).map_err(|e| format!("{}: {e}", m.path.display()))?;
+ m.path = dir.join(&rel);
+ }
+ let built = build(&placed, markers)?;
+ let info = serde_json::to_vec(&built.info).map_err(|e| e.to_string())?;
+ for rel in ["draft_info.json", "draft_info.json.bak", "template-2.tmp"] {
+ put(tmp, rel, &info)?;
+ put(tmp, &format!("Timelines/{}/{rel}", built.timeline_id), &info)?;
+ }
+ let t = format!("Timelines/{}", built.timeline_id);
+ put(tmp, &format!("{t}/attachment_pc_common.json"), skeleton::PC_COMMON.as_bytes())?;
+ put(tmp, &format!("{t}/attachment_editing.json"), format!("{}\n", skeleton::EDITING).as_bytes())?;
+ put(tmp, &format!("{t}/common_attachment/attachment_action_scene.json"), format!("{}\n", skeleton::ACTION_SCENE).as_bytes())?;
+ put(tmp, &format!("{t}/common_attachment/attachment_gen_ai_info.json"), format!("{}\n", skeleton::GEN_AI).as_bytes())?;
+ put(tmp, &format!("{t}/common_attachment/attachment_script_video.json"), format!("{}\n", skeleton::SCRIPT_VIDEO).as_bytes())?;
+ put(tmp, &format!("{t}/common_attachment/attachment_pc_timeline.json"), skeleton::PC_TIMELINE.as_bytes())?;
+ let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_micros() as i64).unwrap_or(0);
+ let project = json!({
+ "config": {"color_space": -1, "render_index_track_mode_on": false, "use_float_render": false},
+ "create_time": now, "id": uid(), "main_timeline_id": built.timeline_id,
+ "timelines": [{"create_time": now, "id": built.timeline_id, "is_marked_delete": false, "name": "Timeline 01", "update_time": now}],
+ "update_time": now, "version": 0
+ });
+ let project = serde_json::to_vec(&project).map_err(|e| e.to_string())?;
+ put(tmp, "Timelines/project.json", &project)?;
+ put(tmp, "Timelines/project.json.bak", &project)?;
+ let layout = json!({"dockItems": [{"dockIndex": 0, "ratio": 1, "timelineIds": [built.timeline_id], "timelineNames": ["Timeline 01"]}], "layoutOrientation": 1});
+ put(tmp, "timeline_layout.json", &serde_json::to_vec(&layout).map_err(|e| e.to_string())?)?;
+ let draft_id = uid();
+ let mut meta: Value = serde_json::from_str(skeleton::DRAFT_META).expect("skeleton.rs holds JSON");
+ meta["draft_fold_path"] = json!(dir.display().to_string());
+ meta["draft_id"] = json!(draft_id);
+ meta["draft_name"] = json!(name);
+ meta["draft_root_path"] = json!(root.display().to_string());
+ meta["draft_timeline_materials_size_"] = json!(info.len());
+ meta["tm_draft_create"] = json!(now);
+ meta["tm_draft_modified"] = json!(now);
+ meta["tm_duration"] = json!(built.duration_us);
+ // type 0: the media imported, which 9.1 needs to find a clip's file and 9.3 its local_material_id
+ meta["draft_materials"][0]["value"] = Value::Array(built.imports.clone());
+ put(tmp, "draft_meta_info.json", &serde_json::to_vec(&meta).map_err(|e| e.to_string())?)?;
+ let secs = now / 1_000_000;
+ let os = if cfg!(target_os = "windows") { "windows" } else { "mac" };
+ put(tmp, "draft_settings", format!("[General]\ncloud_last_modify_platform={os}\ndraft_create_time={secs}\ndraft_last_edit_time={secs}\nreal_edit_keys=0\nreal_edit_seconds=0\n").as_bytes())?;
+ put(tmp, "draft_agency_config.json", skeleton::AGENCY_CONFIG.as_bytes())?;
+ put(tmp, "draft_biz_config.json", b"")?;
+ put(tmp, "performance_opt_info.json", skeleton::PERF_OPT.as_bytes())?;
+ put(tmp, "attachment_pc_common.json", skeleton::PC_COMMON.as_bytes())?;
+ put(tmp, "common_attachment/attachment_pc_timeline.json", skeleton::PC_TIMELINE.as_bytes())?;
+ for d in ["adjust_mask", "matting", "qr_upload", "smart_crop", "subdraft", "Resources/audioAlg", "Resources/videoAlg"] {
+ std::fs::create_dir_all(tmp.join(d)).map_err(|e| e.to_string())?;
+ }
+ if let Some(jpg) = cover {
+ put(tmp, "draft_cover.jpg", jpg)?;
+ }
+ Ok(Written { dir: dir.to_path_buf(), draft_id, duration_us: built.duration_us, meta, info_bytes: info.len(), warnings: built.warnings })
+}
diff --git a/runtime/bundle/src/cache.rs b/runtime/bundle/src/cache.rs
index c179a60e..f8d024cd 100644
--- a/runtime/bundle/src/cache.rs
+++ b/runtime/bundle/src/cache.rs
@@ -11,7 +11,9 @@ use super::*;
pub fn export_cache(tsx: &Path, js: &Path, out: &Path, args: &[String]) -> Option<PathBuf> {
let ext = out.extension()?.to_str()?.to_ascii_lowercase();
// RAEA_FRAME_LOG measures a render, so it renders (a hit would hand back the earlier file and write no log)
- if !matches!(ext.as_str(), "mp4" | "mov") || std::env::var_os("RAEA_AUDIO_BOUNCE").is_some() || std::env::var_os("RAEA_FRAME_LOG").is_some() {
+ // RAEA_HIDE_MEDIA and RAEA_HIDE_LAYERS draw a page the bundle doesn't say (CSS the render adds): never the cache's
+ let hides = std::env::var_os("RAEA_HIDE_MEDIA").is_some() || std::env::var_os("RAEA_HIDE_LAYERS").is_some();
+ if !matches!(ext.as_str(), "mp4" | "mov") || hides || std::env::var_os("RAEA_AUDIO_BOUNCE").is_some() || std::env::var_os("RAEA_FRAME_LOG").is_some() {
return None;
}
let root = match std::env::var("RAEA_EXPORT_CACHE") {
diff --git a/runtime/export/Cargo.toml b/runtime/export/Cargo.toml
index 8bb01f45..c26a49a3 100644
--- a/runtime/export/Cargo.toml
+++ b/runtime/export/Cargo.toml
@@ -24,6 +24,8 @@ raea-sys-layers = { path = "../../systems/layers" }
raea-gpu-device = { path = "../../gpu/device" }
raea-io-net = { path = "../../io/net" }
raea-io-media = { path = "../../io/media", default-features = false, features = ["soft-audio", "apple"] }
+# render -o OUT.mov --alpha: the transparent movie (docs/capcut.feature CC1)
+raea-io-alpha = { path = "../../io/alpha" }
raea-core-program = { path = "../../core/program" }
raea-core-scene = { path = "../../core/scene" }
raea-runtime-scene = { path = "../scene" }
diff --git a/runtime/export/src/lib.rs b/runtime/export/src/lib.rs
index fbb87284..fde5c7d7 100644
--- a/runtime/export/src/lib.rs
+++ b/runtime/export/src/lib.rs
@@ -211,6 +211,11 @@ fn heard(frames: &[(i64, Frame)], tones: &[raea_sys_mix::ToneCue], cx: &Ctx, fps
if let Some(b) = &s.bus {
c["bus"] = json!(b);
}
+ // its playback rate and fades, when it has them (the CapCut export's audio clips take them)
+ let extras = [("rate", Some(s.rate).filter(|r| *r != 1.0)), ("fadeIn", s.fade_in.filter(|v| *v > 0.0)), ("fadeOut", s.fade_out.filter(|v| *v > 0.0))];
+ for (k, v) in extras.into_iter().filter_map(|(k, v)| v.map(|v| (k, v))) {
+ c[k] = json!(v);
+ }
// a generated sound's key is model|prompt|seconds
if let Some(k) = made.get(&s.src) {
let (model, rest) = k.split_once('|').unwrap_or((k, ""));
diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rs
index 0965daaa..ef98595c 100644
--- a/runtime/export/src/render.rs
+++ b/runtime/export/src/render.rs
@@ -69,7 +69,7 @@ pub fn render(args: &[String]) -> R<String> {
}
let alpha = args.iter().any(|a| a == "--alpha");
if alpha && !matches!(out_ext(&out).as_str(), "png" | "") {
- return Err("--alpha writes PNGs (OUT.png or a folder): video here is H.264 or HEVC, which hold no alpha. Encode the folder with alpha after (ffmpeg -i DIR/frame-%05d.png -c:v prores_ks -profile:v 4444 -pix_fmt yuva444p10le overlay.mov)".into());
+ return Err(format!("--alpha writes PNGs (OUT.png or a folder) or a transparent movie (OUT.mov, --alpha-codec {}): an .{} holds no alpha", raea_io_alpha::NAMES, out_ext(&out)));
}
ALPHA.store(alpha, std::sync::atomic::Ordering::Relaxed);
let kbps = flag(args, "--kbps").map(|k| k.parse::<u32>().ok().filter(|k| *k > 0).ok_or("--kbps takes a bitrate in kbit/s")).transpose()?;
@@ -134,9 +134,7 @@ pub fn render(args: &[String]) -> R<String> {
/// measured by rendering them to a folder with --at), and the stats in the manifest with --manifest.
fn with_exposure(said: String, out: &Path, manifest: Option<&Path>) -> String {
let pngs: Vec<PathBuf> = if out.is_dir() {
- let mut v: Vec<PathBuf> = std::fs::read_dir(out).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("frame-")) && p.extension().is_some_and(|x| x == "png")).collect();
- v.sort();
- v
+ raea_io_alpha::frames_in(out)
} else if out.extension().is_some_and(|x| x == "png") {
vec![out.to_path_buf()]
} else {
diff --git a/systems/layers/src/hide.rs b/systems/layers/src/hide.rs
index c3965985..528ad8f6 100644
--- a/systems/layers/src/hide.rs
+++ b/systems/layers/src/hide.rs
@@ -1,14 +1,34 @@
//! Layers hidden by key (RAEA_HIDE_LAYERS), as the layer pass's oracle needs them (bench/layers/oracle.sh): a page
-//! element as CSS (this), a 3D part as its Visibility (runtime/scene).
+//! element as CSS (this), a 3D part as its Visibility (runtime/scene). And the footage hidden (RAEA_HIDE_MEDIA), for
+//! the CapCut export (docs/capcut.feature CC2b): `1` hides every <Video> drawn from a file and the backgrounds of what
+//! holds one, so what's left is what raea draws over the footage; `under` keeps only those backgrounds, what raea
+//! draws under it.
use crate::Layer;
/// RAEA_HIDE_LAYERS: the layers keyed (a key a line or comma) drawn hidden, each element with its stamps and all
-/// inside it, as page CSS. None when it names none.
+/// 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; as page CSS. None when neither hides anything.
pub fn hidden_css() -> Option<String> {
- let keys = std::env::var("RAEA_HIDE_LAYERS").ok()?;
- let rules: Vec<String> = keys.split([',', '\n']).filter(|k| !k.trim().is_empty()).map(|k| layer_selector(k.trim())).collect();
- (!rules.is_empty()).then(|| format!("{} {{ visibility: hidden !important; }}", rules.join(", ")))
+ let keys = std::env::var("RAEA_HIDE_LAYERS").unwrap_or_default();
+ let mut hide: Vec<String> = keys.split([',', '\n']).filter(|k| !k.trim().is_empty()).map(|k| layer_selector(k.trim())).collect();
+ let mut css = String::new();
+ match std::env::var("RAEA_HIDE_MEDIA").as_deref() {
+ // an element holding footage paints its background before it, under it
+ Ok("1") => {
+ hide.push("[data-raea-src]".into());
+ css.push_str(":has([data-raea-src]) { background: transparent !important; box-shadow: none !important; }\n");
+ }
+ Ok("under") => {
+ hide.extend(["[data-raea-src]".into(), ":not(:has([data-raea-src]))".into()]);
+ css.push_str(":has([data-raea-src]) { color: transparent !important; text-shadow: none !important; }\n");
+ }
+ _ => {}
+ }
+ if !hide.is_empty() {
+ css.push_str(&format!("{} {{ visibility: hidden !important; }}", hide.join(", ")));
+ }
+ (!css.is_empty()).then_some(css)
}
/// The CSS selector of the element a layer key names, and of everything inside it: "loc[#index][|use|use…]" as its
diff --git a/tools/dupes.max b/tools/dupes.max
index f7dfc43d..016992b6 100644
--- a/tools/dupes.max
+++ b/tools/dupes.max
@@ -13,5 +13,11 @@
# into raea_sys_frame::json_f32; begin_live and app_mut gone; await_models split by target); the one left is an
# accessor matched by shape: Engine::world_mut and Opening::world_mut (the canvas window goes on before the engine is
# finished, its camera after) with runtime/page bevy_page.rs BevyPage::app
+# Raised once more, 11-11, by the CapCut export (docs/capcut.feature): near 56 -> 59. Its real copies were folded
+# (io/apple's cf_key reused, runtime-bundle's flag, frames_in shared with render.rs's exposure pass, a PNG read through
+# image, the movie writers' frame counts kept once, a byte-concat wrapper gone); the three left match by shape only:
+# io/capcut store.rs:67 (tasklist's stdout, lower-cased; sdk/ui/parity main.rs:88 trims a command's stdout),
+# io/capcut build.rs:24 parse (serde_json::from_str + expect; engine/native node.rs:172 js_string, to_string), and
+# apps/capcut plan.rs:67 (a box moved more than 1 px; systems/layout mod.rs:406, within 1.5 px)
exact=294
-near=56
+near=59
diff --git a/tools/layers.toml b/tools/layers.toml
index 4016028a..0c90467d 100644
--- a/tools/layers.toml
+++ b/tools/layers.toml
@@ -36,6 +36,8 @@ raea-io-av1 = "io"
raea-io-ffmpeg = "io"
raea-io-apple = "io"
raea-io-apple-coding = "io"
+raea-io-alpha = "io"
+raea-io-capcut = "io"
raea-io-shell = "io"
raea-core-animate = "core"
raea-core-ease = "core"
@@ -152,6 +154,7 @@ raea-app-solid = "apps"
raea-app-media = "apps"
raea-app-targets = "apps"
raea-app-game = "apps"
+raea-app-capcut = "apps"
raea-app-play = "apps"
raea-page-host = "runtime"
raea-rune-host = "runtime"
diff --git a/tools/manual-ref/cli.ts b/tools/manual-ref/cli.ts
index a13804d6..5200fc09 100644
--- a/tools/manual-ref/cli.ts
+++ b/tools/manual-ref/cli.ts
@@ -25,7 +25,7 @@ const verbs: Verb[] = JSON.parse(run(["help", "--json"])).verbs
// the index's groups, in the order a reader meets them; every verb is in one
const GROUPS: [string, string, string[]][] = [
- ["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "bundle", "app", "run"]],
+ ["Make", "Render, play and package what you wrote.", ["render", "play", "export-game", "export", "bundle", "app", "run"]],
["Projects", "The workspace, its projects and what a project holds.", ["init", "workspace", "project", "controller", "spec", "part", "add", "brand", "library"]],
["Check", "What's wrong before anyone watches it.", ["check", "judge", "findings", "scene", "world", "solid", "next", "doctor", "hook", "traces"]],
["Footage", "Takes, cuts and the camera, from your own media.", ["media", "cut", "frame", "track", "splat", "mezz", "neural"]],