Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
layers LA4c, LA4d, CC2f: footage that moves, is cut or fades is keyed in every export, each editor placing it as raea drew it
Zachary Guglin3acbaab88080
diff --git a/apps/capcut/src/from_layers.rs b/apps/capcut/src/from_layers.rsindex 228c8dbd..3dc74369 100644--- a/apps/capcut/src/from_layers.rs+++ b/apps/capcut/src/from_layers.rs@@ -20,8 +20,9 @@ pub fn track_name(layer: Layer, name: &str) -> String {}}-/// The timeline. `dir` is where layers.json is: its movies' paths are relative to it.-pub fn timeline(l: &Layers, dir: &Path) -> Timeline {+/// The timeline, and what it can't carry. `dir` is where layers.json is: its movies' paths are relative to it.+pub fn timeline(l: &Layers, dir: &Path) -> (Timeline, Vec<String>) {+ let mut notes = Vec::new();let media: Vec<Media> = l.files.iter()@@ -47,10 +48,19 @@ pub fn timeline(l: &Layers, dir: &Path) -> Timeline {Layer::Footage => {let m = &media[c.file];// (a picture stretched to its box is noted by the layers export already, for every editor)- let (place, _) = plan::place(&c.r#box.unwrap_or([0.0, 0.0, l.width as f64, l.height as f64]), c.fit.as_deref().unwrap_or("fill"), (m.width as f64).max(1.0), (m.height as f64).max(1.0), l.width as f64, l.height as f64, c.opacity);+ let (media, canvas) = (((m.width as f64).max(1.0), (m.height as f64).max(1.0)), (l.width as f64, l.height as f64));+ let bx = c.r#box.unwrap_or([0.0, 0.0, canvas.0, canvas.1]);+ let fit = c.fit.as_deref().unwrap_or("fill");+ let (picture, _) = raea_app_layers::plan::picture(&bx, &c.clip, fit, &c.position, media, canvas);+ let place = plan::place(&picture, media, canvas, c.opacity);+ let (keys, cut_changes) = plan::keys(c, fit, picture.kept, media, canvas);+ if cut_changes {+ let name = Path::new(&l.files[c.file].path).file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned());+ notes.push(format!("{name} (frames {}-{}): what of it is cut changes over its run, and CapCut's crop holds: cut as its first frame shows it throughout, its moves and fades keyed", c.start, c.end() - 1));+ }// its own sound at its gain, or silent: the composition doesn't play its sound therelet own = c.link.as_deref().and_then(|id| all().find(|a| a.id == id));- Clip { volume: own.map_or(0.0, |a| 10f64.powf(a.gain_db / 20.0)), place, ..base }+ Clip { volume: own.map_or(0.0, |a| 10f64.powf(a.gain_db / 20.0)), place, keys, ..base }}Layer::Graphics | Layer::Captions | Layer::Under | Layer::Backing => Clip { volume: 0.0, place: Place::centred(l.width, l.height), ..base },}@@ -68,5 +78,5 @@ pub fn timeline(l: &Layers, dir: &Path) -> Timeline {main.name.clear();}video.extend(audio);- Timeline { width: l.width, height: l.height, fps: l.fps, media, tracks: video }+ (Timeline { width: l.width, height: l.height, fps: l.fps, media, tracks: video }, notes)}diff --git a/apps/capcut/src/lib.rs b/apps/capcut/src/lib.rsindex e2b6a1d6..70a62138 100644--- a/apps/capcut/src/lib.rs+++ b/apps/capcut/src/lib.rs@@ -12,6 +12,7 @@ mod tests;use std::path::{Path, PathBuf};+use raea_app_layers::many;use raea_io_capcut::Kind;use raea_runtime_bundle::flag;@@ -78,13 +79,17 @@ fn export(args: &[String]) -> R<String> {let reference = work.join(&layers.reference);// 2. its tracks as CapCut's, and the draft- let tl = from_layers::timeline(&layers, &work);+ let (tl, carried) = from_layers::timeline(&layers, &work);let mut notes = layers.notes.clone();+ notes.extend(carried);let markers = raea_io_capcut::seed(&root);let written = raea_io_capcut::write(&tl, &root, &name, &markers, media::cover(&reference).as_deref())?;notes.extend(written.warnings.iter().cloned());// the reference render in the draft's folder, on no track, to set beside what CapCut plays (LA4b)- std::fs::copy(&reference, written.dir.join("reference.mp4")).map_err(|e| format!("{}: {e}", written.dir.join("reference.mp4").display()))?;+ let beside = written.dir.join("reference.mp4");+ if let Err(e) = std::fs::copy(&reference, &beside) {+ return Err(format!("{}: {e}", beside.display()));+ }let listed = if !in_store || args.iter().any(|a| a == "--no-register") {"not entered in CapCut's project list".to_string()} else {@@ -119,11 +124,6 @@ fn export(args: &[String]) -> R<String> {Ok(said)}-/// "1 clip", "4 clips"-fn many(k: usize, what: &str) -> String {- if k == 1 { format!("1 {what}") } else { format!("{k} {what}s") }-}-/// Where CapCut's project list is copied before a draft is entered in it: the person's own folder, ~/.raea/capcut/backups/// ($RAEA_CAPCUT_BACKUPS; %LOCALAPPDATA%\raea\capcut\backups on Windows, which sets no HOME). Never raea's home, which/// is its install or, from a checkout, the source tree (11-11: a list's backup landed in the repository).diff --git a/apps/capcut/src/plan.rs b/apps/capcut/src/plan.rsindex 5cb687ef..46640738 100644--- a/apps/capcut/src/plan.rs+++ b/apps/capcut/src/plan.rs@@ -1,34 +1,46 @@//! Where a picture sits in CapCut's terms (docs/capcut.feature CC2a). The manifest is read by raea-app-layers, the same-//! for every editor; this is CapCut's own.+//! for every editor, and so is where a picture is drawn and what of it is kept (raea_app_layers::plan::picture); this+//! is CapCut's own.-use raea_app_layers::plan::full;+use raea_app_layers::model::Clip;+use raea_app_layers::plan::{self, Picture};use raea_io_capcut::Place;-/// Where a picture of `mw` x `mh` sits to show as it does in its box with its object-fit, in CapCut's terms (scale 1:-/// fitted inside the canvas; a crop is fitted as the part it keeps). A warning when CapCut can't show it so.-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)+/// Where a picture of `mw` x `mh` drawn as `p` sits in CapCut's terms on a `w` x `h` canvas: the part of it kept as+/// its crop, which CapCut fits inside the canvas (scale 1), then scaled to the size raea drew it, centred where raea+/// drew that part.+pub fn place(p: &Picture, (mw, mh): (f64, f64), (w, h): (f64, f64), opacity: f64) -> Place {+ let [dx, dy, dw, dh] = p.drawn;+ let [l, t, r, b] = p.kept;+ let (cw, ch) = ((r - l).max(1e-6), (b - t).max(1e-6));+ let fit = (w / (mw * cw)).min(h / (mh * ch));+ let (x, y) = (dx + dw * (l + r) / 2.0, dy + dh * (t + b) / 2.0);+ Place { x, y, scale: dw / (mw * fit), opacity, crop: p.kept }+}++/// A footage clip's keys in CapCut's terms (frames from its first, each its place there; none when it holds), cut+/// throughout as `first` keeps it (its first frame's): CapCut's crop holds, so its moves, scaling and fades are keyed+/// around that cut. Thinned to what a straight line between can't give, to 0.15 px and half a percent of opacity; and+/// whether what is cut changes over its run, which CapCut can't show.+pub fn keys(c: &Clip, fit: &str, first: [f64; 4], (mw, mh): (f64, f64), canvas: (f64, f64)) -> (Vec<(i64, Place)>, bool) {+ let mut changes = false;+ let all: Vec<(i64, [f64; 4])> = c+ .keys+ .iter()+ .map(|k| {+ let (p, _) = plan::picture(&k.r#box, &k.clip, fit, &k.position, (mw, mh), canvas);+ changes |= plan::apart(&p.kept, &first) > 1e-3;+ let at = place(&Picture { drawn: p.drawn, kept: first }, (mw, mh), canvas, k.opacity);+ (k.frame, [at.x, at.y, at.scale, at.opacity])+ })+ .collect();+ if all.is_empty() {+ return (Vec::new(), false);+ }+ // a scale step a 0.15 px change in the width of what's kept, as CapCut fits it inside the canvas+ let (cw, ch) = ((first[2] - first[0]).max(1e-6), (first[3] - first[1]).max(1e-6));+ let fitted = mw * cw * (canvas.0 / (mw * cw)).min(canvas.1 / (mh * ch));+ let kept = plan::thin(&all, &[0.15, 0.15, 0.15 / fitted, 0.005]);+ let keys = kept.into_iter().map(|(f, [x, y, scale, opacity])| (f, Place { x, y, scale, opacity, crop: first })).collect();+ (keys, changes)}diff --git a/apps/capcut/src/tests.rs b/apps/capcut/src/tests.rsindex a3089831..b342f1fe 100644--- a/apps/capcut/src/tests.rs+++ b/apps/capcut/src/tests.rs@@ -10,24 +10,34 @@ use crate::plan::*;#[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);+ let at = |bx: [f64; 4], fit: &str, media: (f64, f64)| {+ let (p, note) = raea_app_layers::plan::picture(&bx, &None, fit, &None, media, (1080.0, 1920.0));+ (place(&p, media, (1080.0, 1920.0), 1.0), note)+ };+ // a landscape take covering a portrait canvas: scaled past the fitted width until it fills the height, uncut (the+ // canvas cuts it)+ let (p, w) = at([0.0, 0.0, 1080.0, 1920.0], "cover", (1920.0, 1080.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);+ let (p, _) = at([660.0, 200.0, 360.0, 360.0], "contain", (640.0, 640.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);+ // a landscape take covering a square box inside the canvas: cropped to its middle square, which then fits as a square+ let (p, _) = at([100.0, 100.0, 540.0, 540.0], "cover", (1920.0, 1080.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);+ assert!((p.scale - 0.5).abs() < 1e-9 && ((p.x - 370.0).abs(), (p.y - 370.0).abs()) < (1e-9, 1e-9));+ // the same box in the canvas's corner: cut only on its right, the canvas cutting its left; the part kept sits where+ // raea drew it, its left past the canvas+ let (p, _) = at([0.0, 0.0, 540.0, 540.0], "cover", (1920.0, 1080.0));+ assert!(p.crop[0] == 0.0 && (p.crop[2] - 0.78125).abs() < 1e-9);+ assert!((p.x - (-210.0 + 750.0 / 2.0)).abs() < 1e-9 && (p.y - 270.0).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());+ assert!(at([0.0, 0.0, 500.0, 100.0], "fill", (640.0, 640.0)).1.is_some());}#[test]fn layers_json_goes_bottom_first_with_footage_carrying_its_own_sound() {- let file = |path: &str, kind, w, h| File { path: path.into(), kind, seconds: 3.0, width: w, height: h, has_audio: kind == FileKind::Video, channels: 2, sample_rate: 48_000 };+ let file = |path: &str, kind, w, h| File { path: path.into(), kind, seconds: 3.0, width: w, height: h, has_audio: kind == FileKind::Video, channels: 2, sample_rate: 48_000, rotation: 0 };let clip = |id: &str, f, start, frames| LClip::new(id.into(), f, start, frames, 0.0);let t = |layer, name: &str, clips| LTrack { layer, name: name.into(), clips };let v1 = LClip { r#box: Some([0.0, 0.0, 1080.0, 1920.0]), fit: Some("cover".into()), link: Some("a1".into()), ..clip("v1", 0, 0, 90) };@@ -50,7 +60,7 @@ fn layers_json_goes_bottom_first_with_footage_carrying_its_own_sound() {],notes: vec![],};- let tl = from_layers::timeline(&l, Path::new("/out/edit"));+ let (tl, _) = from_layers::timeline(&l, Path::new("/out/edit"));// bottom first: the footage is CapCut's main track (no name), then the overlay, then the captions; sound afterassert_eq!(tl.tracks.iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["", "raea overlay", "raea captions", "sound"]);// a layer's movie is found beside layers.json; the footage where it is@@ -68,5 +78,29 @@ fn layers_json_goes_bottom_first_with_footage_carrying_its_own_sound() {let mut quiet = l.clone();quiet.tracks[2].clips[0].link = None;quiet.tracks[3].clips.remove(0);- assert_eq!(from_layers::timeline(&quiet, Path::new("/out/edit")).tracks[0].clips[0].volume, 0.0);+ assert_eq!(from_layers::timeline(&quiet, Path::new("/out/edit")).0.tracks[0].clips[0].volume, 0.0);+}++/// CC2f: a footage clip's keys in CapCut's terms, around the cut its first frame shows: a steady move is its two ends,+/// a move inside a card keeps the card's cut, and a cut that changes (the split close) is said+#[test]+fn keyed_footage_is_keyed_around_its_first_cut() {+ use raea_app_layers::model::Key;+ let canvas = (1080.0, 1920.0);+ let key = |frame: i64, bx: [f64; 4], clip: Option<[f64; 4]>| Key { frame, r#box: bx, clip, position: None, opacity: 1.0 };+ let first = |c: &LClip| raea_app_layers::plan::picture(&c.r#box.unwrap(), &c.clip, "cover", &None, (1080.0, 1920.0), canvas).0.kept;+ // a picture in picture sliding right 10 px a frame: its two ends+ let slide = LClip { r#box: Some([100.0, 500.0, 400.0, 400.0]), keys: (0..24).map(|f| key(f, [100.0 + 10.0 * f as f64, 500.0, 400.0, 400.0], None)).collect(), ..LClip::new("v".into(), 0, 0, 24, 0.0) };+ let (got, changes) = keys(&slide, "cover", first(&slide), (1080.0, 1920.0), canvas);+ assert!(!changes && got.len() == 2 && got[1].0 == 23 && (got[1].1.x - got[0].1.x - 230.0).abs() < 1e-6);+ // inside a card that moves with it, cutting its sides: the same cut throughout, keyed as it moves+ let card = |f: i64| key(f, [80.0 + 4.0 * f as f64, 300.0, 600.0, 1066.7], Some([140.0 + 4.0 * f as f64, 300.0, 480.0, 1066.7]));+ let carded = LClip { r#box: Some(card(0).r#box), clip: card(0).clip, keys: (0..24).map(card).collect(), ..LClip::new("v".into(), 0, 0, 24, 0.0) };+ let (got, changes) = keys(&carded, "cover", first(&carded), (1080.0, 1920.0), canvas);+ assert!(!changes && got.len() == 2 && got.iter().all(|(_, p)| p.crop[0] > 0.09 && p.crop[2] < 0.91));+ // the split close: its box shrinking to the seam changes what's cut, which CapCut's crop can't follow+ let split = |f: i64, h: f64| key(f, [0.0, -260.0 * (1920.0 - h) / 1060.0, 1080.0, 1920.0], (h < 1920.0).then_some([0.0, 0.0, 1080.0, h]));+ let closing = LClip { r#box: Some(split(0, 1920.0).r#box), keys: vec![split(0, 1920.0), split(12, 860.0)], ..LClip::new("v".into(), 0, 0, 24, 0.0) };+ let (got, changes) = keys(&closing, "cover", first(&closing), (1080.0, 1920.0), canvas);+ assert!(changes && got.len() == 2 && got[1].1.crop == [0.0, 0.0, 1.0, 1.0]);}diff --git a/apps/layers/src/composite.rs b/apps/layers/src/composite.rsindex 4f80dac8..eb52491b 100644--- a/apps/layers/src/composite.rs+++ b/apps/layers/src/composite.rs@@ -3,12 +3,13 @@//! are composited bottom to top (under, footage as layers.json places it, graphics, captions) and compared with the//! reference render's frame. A test of the method, run by hand on a machine with a GPU://! cargo test -p raea-app-layers composite -- --ignored --nocapture (RAEA_BIN: the raea, default target/release/raea;-//! RAEA_LAYERS_PROJECT=DIR/EDIT.tsx checks that composition, its media/ beside it, in place of the fixtures)+//! RAEA_LAYERS_PROJECT=DIR/EDIT.tsx checks that composition, its media/ beside it, in place of the fixtures, and+//! RAEA_LAYERS_COMPOSITION=ID one of its compositions by id)use std::path::{Path, PathBuf};use std::process::Command;-use crate::model::{Clip, Layer, Layers};+use crate::model::{Clip, Key, Layer, Layers, key_at};/// The least PSNR (dB) a composited frame has against the reference render's: the reference is an H.264 movie and the/// footage is decoded and scaled here as the page does it, so a frame is never exact.@@ -36,21 +37,23 @@ impl Picture {}}- /// A picture of `mw` x `mh` (RGBA) drawn into `bx` as CSS's object-fit `fit` draws it (centred, clipped to its- /// box), sampled bilinearly, times `opacity`.- fn draw(&mut self, rgba: &[u8], mw: usize, mh: usize, bx: [f64; 4], fit: &str, opacity: f32) {- let [bx0, by0, bw, bh] = bx;- let (sx, sy) = (bw / mw as f64, bh / mh as f64);- let (sx, sy) = match fit {- "cover" => (sx.max(sy), sx.max(sy)),- "contain" => (sx.min(sy), sx.min(sy)),- "none" => (1.0, 1.0),- "scale-down" => (sx.min(sy).min(1.0), sx.min(sy).min(1.0)),- _ => (sx, sy),+ /// A picture of `mw` x `mh` (RGBA) as a footage clip shows it at `key` (layers.json's place for that frame): where+ /// plan::picture draws it and keeps it, or stretched over its box for object-fit: fill (as raea draws it; an editor+ /// fits it inside), sampled bilinearly, times its opacity.+ fn draw(&mut self, rgba: &[u8], mw: usize, mh: usize, key: &Key, fit: &str) {+ let (canvas, media) = ((self.w as f64, self.h as f64), (mw as f64, mh as f64));+ // where the whole picture is, and the edges of what of it shows+ let ([ox, oy, dw, dh], [l, t, r, b]) = if fit == "fill" {+ let [x, y, w, h] = crate::plan::shown(&key.r#box, &key.clip);+ (key.r#box, [x, y, x + w, y + h])+ } else {+ let (p, _) = crate::plan::picture(&key.r#box, &key.clip, fit, &key.position, media, canvas);+ let [dx, dy, dw, dh] = p.drawn;+ (p.drawn, [dx + p.kept[0] * dw, dy + p.kept[1] * dh, dx + p.kept[2] * dw, dy + p.kept[3] * dh])};- let (ox, oy) = (bx0 + (bw - mw as f64 * sx) / 2.0, by0 + (bh - mh as f64 * sy) / 2.0);- let (x0, y0) = (bx0.max(0.0) as usize, by0.max(0.0) as usize);- let (x1, y1) = (((bx0 + bw).ceil() as usize).min(self.w), ((by0 + bh).ceil() as usize).min(self.h));+ let (sx, sy, opacity) = (dw / media.0, dh / media.1, key.opacity as f32);+ let (x0, y0) = (l.max(0.0) as usize, t.max(0.0) as usize);+ let (x1, y1) = ((r.ceil().max(0.0) as usize).min(self.w), (b.ceil().max(0.0) as usize).min(self.h));let at = |x: usize, y: usize, c: usize| rgba[(y.min(mh - 1) * mw + x.min(mw - 1)) * 4 + c] as f32 / 255.0;for y in y0..y1 {for x in x0..x1 {@@ -61,9 +64,9 @@ impl Picture {let (u, v) = (u.max(0.0), v.max(0.0));let (iu, iv, fu, fv) = (u as usize, v as usize, (u.fract()) as f32, (v.fract()) as f32);let p = &mut self.px[y * self.w + x];- for c in 0..3 {+ for (c, ch) in p.iter_mut().enumerate() {let s = at(iu, iv, c) * (1.0 - fu) * (1.0 - fv) + at(iu + 1, iv, c) * fu * (1.0 - fv) + at(iu, iv + 1, c) * (1.0 - fu) * fv + at(iu + 1, iv + 1, c) * fu * fv;- p[c] = p[c] * (1.0 - opacity) + s * opacity;+ *ch = *ch * (1.0 - opacity) + s * opacity;}}}@@ -100,9 +103,13 @@ fn composite(dir: &Path, l: &Layers, f: i64) -> Result<Picture, String> {Layer::Sound => {}Layer::Footage => {let file = &l.files[c.file];- let secs = c.source_in + (f - c.start) as f64 / l.fps * c.speed + 0.25 / l.fps;+ // the source frame at or before the time, as raea shows it (a take faster than the edit has one+ // between two of its frames): only a hair past the time, for the manifest's whole milliseconds+ let secs = c.source_in + (f - c.start) as f64 / l.fps * c.speed + 1e-4;let (rgba, w, h) = frame(Path::new(&file.path), secs)?;- pic.draw(&rgba, w, h, c.r#box.unwrap(), c.fit.as_deref().unwrap_or("fill"), c.opacity as f32);+ let first = Key { frame: 0, r#box: c.r#box.unwrap_or([0.0, 0.0, l.width as f64, l.height as f64]), clip: c.clip, position: c.position, opacity: c.opacity };+ let key = key_at(&c.keys, f - c.start).unwrap_or(first);+ pic.draw(&rgba, w, h, &key, c.fit.as_deref().unwrap_or("fill"));}_ => {// a layer's movie is NAME.CODEC.mov, its frames NAME.frames@@ -133,8 +140,11 @@ fn export(bin: &Path, fixture: &Path, work: &Path) -> Result<(Layers, PathBuf),(fixture.parent().unwrap().to_path_buf(), fixture.file_name().unwrap().to_string_lossy().into_owned())};let out = work.join(&name).join("layers");+ let comp: Vec<String> = std::env::var("RAEA_LAYERS_COMPOSITION").map(|c| vec!["--composition".to_string(), c]).unwrap_or_default();let run = Command::new(bin)- .args(["export", "layers", edit.as_str(), "-o"])+ .args(["export", "layers", edit.as_str()])+ .args(&comp)+ .arg("-o").arg(&out).current_dir(&src).env("RAEA_LAYERS_KEEP_FRAMES", "1")diff --git a/apps/layers/src/lib.rs b/apps/layers/src/lib.rsindex 3620eabf..312702ed 100644--- a/apps/layers/src/lib.rs+++ b/apps/layers/src/lib.rs@@ -8,6 +8,7 @@//! 4. RAEA_LAYER=captions, when a frame shows a caption: the captions alone, and the words as SubRip;//! 5. RAEA_LAYER=behind:FILE, for each file shown as a picture in picture: what's drawn behind it (its card), kept//! only where it's a picture in picture, on a track between it and the footage under it.+//!//! The footage and sounds are clips of their own files where they are; each layer is clips of its movie, cut where it//! draws something. A render that isn't an export draws once, as it always has (LA2o).@@ -32,7 +33,7 @@ pub type R<T> = Result<T, String>;pub const USAGE: &str = "raea export layers EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] (the composition as its layers and the timeline that places them, layers.json: the captions and the graphics as transparent movies, what's under the footage (and any 3D) as an opaque one, the footage and sounds as clips of their own files where they are, the captions also as SubRip, and the reference render; into out/layers/NAME, or DIR)";-pub const USAGE_XML: &str = "raea export xml EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] (the composition as an FCP7 XML project for Premiere Pro (File, Import) and DaVinci Resolve (File, Import, Timeline): its layers as raea export layers writes them, NAME.xml beside them placing them on a timeline, the footage and sounds as clips of their own files where they are, each clip's own sound linked to it; into out/xml/NAME, or DIR)";+pub const USAGE_XML: &str = "raea export xml EDIT.tsx [--composition ID] [-o DIR] [--name NAME] [--alpha-codec prores|hevc|rle|png] (the composition as an FCP7 XML project for Premiere Pro (File, Import) and DaVinci Resolve (File, Import, Timeline): its layers as raea export layers writes them, NAME.premiere.xml and NAME.resolve.xml beside them placing them on a timeline, each as that editor writes it, the footage and sounds as clips of their own files where they are, each clip's own sound linked to it; into out/xml/NAME, or DIR)";/// `export layers ...` and `export xml ...`; None for anything else.pub fn cli(args: &[String]) -> Option<R<String>> {@@ -50,7 +51,7 @@ pub fn cli(args: &[String]) -> Option<R<String>> {fn export_xml(args: &[String]) -> R<String> {let tsx = args.first().filter(|a| !a.starts_with('-')).ok_or(USAGE_XML)?;let edit = dunce::canonicalize(PathBuf::from(tsx)).map_err(|e| format!("{tsx}: {e}"))?;- let name = flag(args, "--name").unwrap_or_else(|| edit.file_stem().unwrap().to_string_lossy().into_owned());+ let name = named(args, &edit);let dir = flag(args, "-o").map_or_else(|| edit.parent().unwrap().join("out/xml").join(&name), PathBuf::from);let mut layer_args = args.to_vec();if flag(args, "-o").is_none() {@@ -58,13 +59,23 @@ fn export_xml(args: &[String]) -> R<String> {}let (layers, _) = export(&layer_args)?;let dir = dunce::canonicalize(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;- let (text, notes) = xml::write(&layers, &dir);- let out = dir.join(format!("{name}.xml"));- std::fs::write(&out, text).map_err(|e| format!("{}: {e}", out.display()))?;+ // an XML an editor, the same but for what they read differently (xml::Editor)+ let mut notes: Vec<String> = Vec::new();+ for e in [xml::Editor::Premiere, xml::Editor::Resolve] {+ let (text, n) = xml::write(&layers, &dir, e);+ let out = dir.join(format!("{name}.{}.xml", e.name()));+ std::fs::write(&out, text).map_err(|e| format!("{}: {e}", out.display()))?;+ for n in n {+ if !notes.contains(&n) {+ notes.push(n);+ }+ }+ }+ let _ = std::fs::remove_file(dir.join(format!("{name}.xml")));let count = |l: Layer| layers.tracks.iter().filter(|t| t.layer == l).count();let mut said = format!(- "APPLIED FCP7 XML \"{name}\" at {}: {} video tracks, {} audio tracks; import it in Premiere Pro (File, Import) or DaVinci Resolve (File, Import, Timeline); the layers, layers.json{} and the reference render beside it",- out.display(),+ "APPLIED FCP7 XML \"{name}\" at {}: {name}.premiere.xml for Premiere Pro (File, Import), {name}.resolve.xml for DaVinci Resolve (File, Import, Timeline); {} video tracks, {} audio tracks; the layers, layers.json{} and the reference render beside them",+ dir.display(),layers.tracks.len() - count(Layer::Sound),count(Layer::Sound),layers.srt.as_ref().map_or(String::new(), |s| format!(", {s} (captions to upload)")),@@ -92,28 +103,41 @@ pub fn render(args: &[String], env: &[(&str, &str)]) -> R<()> {Ok(())}-/// A layer's movie, rendered with RAEA_LAYER=`layer` into DIR/NAME.CODEC.mov (NAME the layer's, or `name` for one of-/// many), its frames in DIR/NAME.frames, removed unless `keep` (LA3a's test reads them).-fn pass(tsx: &Path, comp: &[String], dir: &Path, layer: &str, codec: raea_io_alpha::Codec, fps: f64, keep: bool, also: impl FnOnce(&Path) -> bool) -> R<Option<(PathBuf, raea_io_alpha::Made)>> {- pass_named(tsx, comp, dir, layer, layer, codec, fps, keep, also)+/// What every layer's pass renders from: the edit, its composition flags, the export's folder, the movies' codec and+/// the rate.+struct Passes<'a> {+ tsx: &'a Path,+ comp: &'a [String],+ dir: &'a Path,+ codec: raea_io_alpha::Codec,+ fps: f64,}-#[allow(clippy::too_many_arguments)]-fn pass_named(tsx: &Path, comp: &[String], dir: &Path, name: &str, layer: &str, codec: raea_io_alpha::Codec, fps: f64, keep: bool, also: impl FnOnce(&Path) -> bool) -> R<Option<(PathBuf, raea_io_alpha::Made)>> {- // the layer under the page is the bottom one, so it's drawn opaque: over 3D the page's background is the 3D's- // clear, which --alpha would clear to nothing- let alpha: &[String] = if layer == "under" { &[] } else { &["--alpha".to_string()] };- let frames = dir.join(format!("{name}.frames"));- let _ = std::fs::remove_dir_all(&frames);- let out = dir.join(format!("{name}.{}.mov", codec_ext(codec)));- let done = render(&[[tsx.display().to_string(), "-o".into(), format!("{}/", frames.display())].as_slice(), alpha, comp].concat(), &[("RAEA_LAYER", layer)])- .and_then(|_| if also(&frames) { raea_io_alpha::encode_dir(&frames, &out, codec, fps, 0.9).map(|m| Some((out, m))) } else { Ok(None) });- // the frames' render leaves its manifest beside them: the reference's is the export's- let _ = std::fs::remove_file(dir.join(format!("{name}.render.json")));- if !keep {+impl Passes<'_> {+ /// A layer's movie, rendered with RAEA_LAYER=`layer` into DIR/NAME.CODEC.mov (`name` the layer's own, or one of+ /// many's), its frames in DIR/NAME.frames, removed unless `keep` (LA3a's test reads them); none when `also` says+ /// its frames aren't worth a movie.+ fn pass(&self, name: &str, layer: &str, keep: bool, also: impl FnOnce(&Path) -> bool) -> R<Option<(PathBuf, raea_io_alpha::Made)>> {+ // the layer under the page is the bottom one, so it's drawn opaque: over 3D the page's background is the 3D's+ // clear, which --alpha would clear to nothing+ let alpha: &[String] = if layer == "under" { &[] } else { &["--alpha".to_string()] };+ let frames = self.dir.join(format!("{name}.frames"));let _ = std::fs::remove_dir_all(&frames);+ let out = self.dir.join(format!("{name}.{}.mov", codec_ext(self.codec)));+ let done = render(&[[self.tsx.display().to_string(), "-o".into(), format!("{}/", frames.display())].as_slice(), alpha, self.comp].concat(), &[("RAEA_LAYER", layer)])+ .and_then(|_| if also(&frames) { raea_io_alpha::encode_dir(&frames, &out, self.codec, self.fps, 0.9).map(|m| Some((out, m))) } else { Ok(None) });+ // the frames' render leaves its manifest beside them: the reference's is the export's+ let _ = std::fs::remove_file(self.dir.join(format!("{name}.render.json")));+ if !keep {+ let _ = std::fs::remove_dir_all(&frames);+ }+ done}- done+}++/// The export's name: --name's, else the edit's file stem.+fn named(args: &[String], edit: &Path) -> String {+ flag(args, "--name").unwrap_or_else(|| edit.file_stem().map_or_else(|| "edit".to_string(), |s| s.to_string_lossy().into_owned()))}/// The export: the layers and layers.json in DIR, and what it says.@@ -122,7 +146,7 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {let tsx = dunce::canonicalize(PathBuf::from(tsx)).map_err(|e| format!("{tsx}: {e}"))?;let edit_dir = tsx.parent().unwrap().to_path_buf();let codec = flag(args, "--alpha-codec").map_or(Ok(raea_io_alpha::Codec::default_here()), |c| raea_io_alpha::Codec::parse(&c))?;- let name = flag(args, "--name").unwrap_or_else(|| tsx.file_stem().unwrap().to_string_lossy().into_owned());+ let name = named(args, &tsx);let dir = flag(args, "-o").map_or_else(|| edit_dir.join("out/layers").join(&name), PathBuf::from);std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;let dir = dunce::canonicalize(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;@@ -141,7 +165,8 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {// 2-4. the layers' passes// (its frames kept until the footage it covers is found)- let graphics = pass(&tsx, &comp, &dir, "graphics", codec, fps, true, |_| true)?;+ let passes = Passes { tsx: &tsx, comp: &comp, dir: &dir, codec, fps };+ let graphics = passes.pass("graphics", "graphics", true, |_| true)?;// footage the graphics cover (opaque over most of its box at its middle frame) goes above them: the composition// draws it under something it draws in front of itlet covered: Vec<bool> = runs.iter().map(|r| graphics.is_some() && opaque_over(&dir.join("graphics.frames"), r)).collect();@@ -149,18 +174,18 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {let _ = std::fs::remove_dir_all(dir.join("graphics.frames"));}// what's under the page: the backgrounds holding footage, and the 3D, which the whole page is drawn over- let under = if runs.is_empty() && manifest["has3d"] != true { None } else { pass(&tsx, &comp, &dir, "under", codec, fps, keep, lit)? };- let captions = if said.iter().any(|s| !s.is_empty()) { pass(&tsx, &comp, &dir, "captions", codec, fps, keep, |_| true)? } else { None };+ let under = if runs.is_empty() && manifest["has3d"] != true { None } else { passes.pass("under", "under", keep, lit)? };+ let captions = if said.iter().any(|s| !s.is_empty()) { passes.pass("captions", "captions", keep, |_| true)? } else { None };// what's behind each file shown as a picture in picture (its card), between it and the footage under it (LA2c):// a pass for each such file, kept only where it's a picture in picture- let full = |r: &plan::Run| plan::full(&r.bx, w as f64, h as f64);+ let full = |r: &plan::Run| plan::full(&plan::shown(&r.bx, &r.clip), w as f64, h as f64);let mut pips: Vec<String> = runs.iter().zip(&covered).filter(|(r, c)| !**c && !full(r)).map(|(r, _)| r.src.clone()).collect();pips.dedup();pips.sort();pips.dedup();let mut behind = Vec::new();for (k, src) in pips.iter().enumerate() {- let made = pass_named(&tsx, &comp, &dir, &format!("behind-{}", k + 1), &format!("behind:{src}"), codec, fps, keep, |_| true)?;+ let made = passes.pass(&format!("behind-{}", k + 1), &format!("behind:{src}"), keep, |_| true)?;let shown: Vec<(i64, i64)> = runs.iter().zip(&covered).filter(|(r, c)| !**c && !full(r) && r.src == *src).map(|(r, _)| (r.start, r.end)).collect();behind.push((made, shown));}@@ -181,19 +206,14 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {let path = plan::resolve(&edit_dir, &r.src);let f = add(&mut files, &mut index, &path, video)?;let what = format!("{} (frames {}-{})", r.src, r.start, r.end - 1);- if r.moved {- notes.push(format!("{what}: moves or scales in its box; placed as its first frame shows it"));- }- if r.faded {- notes.push(format!("{what}: fades; placed at its first frame's opacity"));- }if r.fit == "fill" && files[f].width > 0 && ((r.bx[2] / r.bx[3].max(1.0)) - (files[f].width as f64 / files[f].height.max(1) as f64)).abs() > 0.01 * (files[f].width as f64 / files[f].height.max(1) as f64) {notes.push(format!("{what}: stretched to its {:.0}x{:.0} box (object-fit: fill); an editor may fit it inside instead", r.bx[2], r.bx[3]));}if *cov {notes.push(format!("{what}: raea draws over all of it from outside what holds it (a layer before it in the page); placed above the graphics, so their drawing over it is hidden in an editor"));}- let mut clip = Clip { r#box: Some(r.bx), fit: Some(r.fit.clone()), opacity: r.opacity, speed: r.rate.unwrap_or(1.0).max(0.01), ..Clip::new(ids.next("v"), f, r.start, r.end - r.start, r.at) };+ let keys = r.keys.iter().map(|k| model::Key { frame: k.frame - r.start, ..k.clone() }).collect();+ let mut clip = Clip { r#box: Some(r.bx), fit: Some(r.fit.clone()), clip: r.clip, position: r.position, opacity: r.opacity, keys, speed: r.rate.unwrap_or(1.0).max(0.01), ..Clip::new(ids.next("v"), f, r.start, r.end - r.start, r.at) };// its own sound: the manifest's sound clip of the same file over the same frames from the same timeif let Some(k) = sounds.iter().position(|c| plan::resolve(&edit_dir, &c.src) == path && (c.from - r.start).abs() <= 1 && (c.to - r.end).abs() <= 1 && (c.at - r.at).abs() <= 1.5 / fps) {let s = sounds.remove(k);@@ -201,7 +221,7 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {clip.link = Some(a.id.clone());linked.push(a);}- match (*cov, plan::full(&r.bx, w as f64, h as f64)) {+ match (*cov, plan::full(&plan::shown(&r.bx, &r.clip), w as f64, h as f64)) {(true, _) => over.push(clip),(false, true) => main.push(clip),(false, false) => rest.push(clip),@@ -219,7 +239,7 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {let _ = std::fs::remove_file(path);return Vec::new();}- files.push(File { path: path.file_name().unwrap().to_string_lossy().into_owned(), kind: FileKind::Video, seconds: m.frames as f64 / fps, width: m.width, height: m.height, has_audio: false, channels: 2, sample_rate: 48_000 });+ files.push(File { path: path.file_name().unwrap().to_string_lossy().into_owned(), kind: FileKind::Video, seconds: m.frames as f64 / fps, width: m.width, height: m.height, has_audio: false, channels: 2, sample_rate: 48_000, rotation: 0 });let k = files.len() - 1;let clips = spans.iter().map(|&(a, b)| Clip::new(ids.next(&name[..1]), k, a, b - a, a as f64 / fps)).collect();model::lay(layer, name, clips)@@ -237,10 +257,18 @@ pub fn export(args: &[String]) -> R<(Layers, String)> {tracks.extend(model::lay(Layer::Backing, "behind picture in picture", backing));tracks.extend(model::lay(Layer::Footage, "footage", main));tracks.extend(movie(&mut files, &under, Layer::Under, "under", &mut ids, None));+ // a phone's take is stored turned and Resolve crops it mirrored (xml::Editor); ffprobe says how a file is turned+ if !runs.is_empty() && Command::new("ffprobe").arg("-version").output().is_err() {+ notes.push("ffprobe isn't installed, so how each take is turned wasn't read: all are taken as upright, and Resolve may crop a phone's take on the wrong side".to_string());+ }let mut audio = linked;for c in sounds {let f = add(&mut files, &mut index, &plan::resolve(&edit_dir, &c.src), sound)?;- audio.push(Clip { gain_db: c.gain_db, fade_in: c.fade_in, fade_out: c.fade_out, speed: c.rate, ..Clip::new(ids.next("a"), f, c.from, c.to - c.from, c.at) });+ let frames = plan::heard_frames(&c, files[f].seconds, fps);+ if frames <= 0 {+ continue;+ }+ audio.push(Clip { gain_db: c.gain_db, fade_in: c.fade_in, fade_out: c.fade_out, speed: c.rate, ..Clip::new(ids.next("a"), f, c.from, frames, c.at) });}audio.sort_by_key(|c| c.start);// the first sound track is the top one, so later ones are listed after it (lay lists the last laid first)@@ -289,7 +317,8 @@ impl Ids {}/// "1 clip", "4 clips"-fn many(k: usize, what: &str) -> String {+/// "1 clip", "3 clips".+pub fn many(k: usize, what: &str) -> String {if k == 1 { format!("1 {what}") } else { format!("{k} {what}s") }}@@ -312,7 +341,9 @@ pub fn video(path: &Path) -> R<File> {Ok(d) => {let i = d.info();let (has_audio, channels, sample_rate) = heard(path);- return Ok(File { path: path.display().to_string(), kind: FileKind::Video, seconds: i.duration, width: i.width, height: i.height, has_audio, channels, sample_rate });+ // one whose rotation can't be read is taken as upright (export notes it: only Resolve's crop turns on it)+ let rotation = rotation(path).unwrap_or(0);+ return Ok(File { path: path.display().to_string(), kind: FileKind::Video, seconds: i.duration, width: i.width, height: i.height, has_audio, channels, sample_rate, rotation });}Err(e) => why.push(format!("{}: {e}", b.name())),}@@ -324,11 +355,19 @@ pub fn video(path: &Path) -> R<File> {pub fn sound(path: &Path) -> R<File> {let seconds = raea_io_media::probe_seconds(path).ok_or_else(|| format!("{}: no sound length", path.display()))?;let (_, channels, sample_rate) = heard(path);- Ok(File { path: path.display().to_string(), kind: FileKind::Audio, seconds, width: 0, height: 0, has_audio: true, channels, sample_rate })+ Ok(File { path: path.display().to_string(), kind: FileKind::Audio, seconds, width: 0, height: 0, has_audio: true, channels, sample_rate, rotation: 0 })}/// Whether a short window of a file's sound decodes to samples, and its channels and sample rate (stereo at 48 kHz/// when it has none to read).+/// How far a video's pictures are turned to stand upright, from its container's display matrix (ffprobe's rotation,+/// counter-clockwise), as 0, 90, 180 or 270 (to the nearest quarter turn); None when ffprobe can't say (it isn't there).+fn rotation(path: &Path) -> Option<u32> {+ let out = Command::new("ffprobe").args(["-v", "error", "-select_streams", "v:0", "-show_entries", "stream_side_data=rotation", "-of", "csv=p=0"]).arg(path).output().ok().filter(|o| o.status.success())?;+ let deg = String::from_utf8_lossy(&out.stdout).lines().find_map(|l| l.trim().parse::<f64>().ok()).unwrap_or(0.0);+ Some(((deg / 90.0).round() as i64).rem_euclid(4) as u32 * 90)+}+fn heard(path: &Path) -> (bool, u32, u32) {match raea_io_media::decode_audio_window(path, 0.0, 0.05) {Ok(a) if a.len() > 0 => (true, (a.channels.len() as u32).max(1), a.rate),@@ -345,15 +384,17 @@ pub fn codec_ext(c: raea_io_alpha::Codec) -> &'static str {}}-/// Whether the graphics are opaque over 90% of a run's box at its middle frame (a grid of points inside it).+/// Whether the graphics are opaque over 90% of what shows of a run at its middle frame (a grid of points inside it).fn opaque_over(frames: &Path, r: &plan::Run) -> bool {let mid = (r.start + r.end - 1) / 2;let Ok((px, w, h)) = raea_io_alpha::read_png(&frames.join(format!("frame-{mid:05}.png"))) else { return false };+ let k = r.at(mid);+ let [bx, by, bw, bh] = plan::shown(&k.r#box, &k.clip);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;+ let x = (bx + bw * (i as f64 + 0.5) / 16.0) as i64;+ let y = (by + bh * (j as f64 + 0.5) / 16.0) as i64;if x < 0 || y < 0 || x >= w as i64 || y >= h as i64 {continue;}diff --git a/apps/layers/src/model.rs b/apps/layers/src/model.rsindex e732736d..6106481e 100644--- a/apps/layers/src/model.rs+++ b/apps/layers/src/model.rs@@ -48,6 +48,15 @@ pub struct File {pub channels: u32,#[serde(default = "rate_48k")]pub sample_rate: u32,+ /// how far its pictures are turned to stand upright, as its container says (a phone's take is stored on its side):+ /// counter-clockwise degrees, 0, 90, 180 or 270; its width and height are upright already. Resolve crops such a+ /// file mirrored (xml::Editor)+ #[serde(default, skip_serializing_if = "is_zero_u")]+ pub rotation: u32,+}++fn is_zero_u(v: &u32) -> bool {+ *v == 0}fn two() -> u32 {@@ -108,8 +117,22 @@ pub struct Clip {pub r#box: Option<[f64; 4]>,#[serde(default, skip_serializing_if = "Option::is_none")]pub fit: Option<String>,+ /// footage: what of its box shows at its first frame, when a box it's in cuts it (an `overflow: hidden` parent):+ /// [x, y, width, height] on the canvas, inside its box; none when all of the box shows+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub clip: Option<[f64; 4]>,+ /// footage: where the picture sits in what its box leaves free (CSS's object-position) when not centred, each axis+ /// as px plus a share of the free space: [x px, x share, y px, y share]+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub position: Option<[f64; 4]>,/// footage: its opacity at its first framepub opacity: f64,+ /// footage that moves, scales, is cut, pans in its box or fades over its run: its box, clip, object-position and+ /// opacity at the frames where that+ /// changes, a straight line between two keys being what each frame between them shows (the first key is its first+ /// frame, the last its last); none when it holds as its first frame shows it+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub keys: Vec<Key>,/// a sound: its gain in decibels and its fades in seconds#[serde(default, skip_serializing_if = "is_zero")]pub gain_db: f64,@@ -123,6 +146,43 @@ pub struct Clip {pub link: Option<String>,}+/// Footage's box, clip, object-position and opacity at one frame of its clip.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct Key {+ /// from the clip's first frame+ pub frame: i64,+ pub r#box: [f64; 4],+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub clip: Option<[f64; 4]>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub position: Option<[f64; 4]>,+ pub opacity: f64,+}++/// The key at `frame` (keys' frames counted alike): the straight line between the keys either side of it, the first's+/// before them and the last's after; none when there are no keys. A clip or object-position one key has and the other+/// hasn't goes from the whole box, or the centre, to it.+pub fn key_at(keys: &[Key], frame: i64) -> Option<Key> {+ let i = keys.iter().position(|k| k.frame >= frame).unwrap_or(keys.len().checked_sub(1)?);+ let b = &keys[i];+ if i == 0 || b.frame <= frame {+ return Some(Key { frame, ..b.clone() });+ }+ let a = &keys[i - 1];+ let t = (frame - a.frame) as f64 / (b.frame - a.frame) as f64;+ let clip = (a.clip.is_some() || b.clip.is_some()).then(|| toward(crate::plan::shown(&a.r#box, &a.clip), &crate::plan::shown(&b.r#box, &b.clip), t));+ let position = (a.position.is_some() || b.position.is_some()).then(|| toward(crate::plan::placed(&a.position), &crate::plan::placed(&b.position), t));+ Some(Key { frame, r#box: toward(a.r#box, &b.r#box, t), clip, position, opacity: a.opacity + (b.opacity - a.opacity) * t })+}++/// `from` moved `t` of the way to `to`, each of its four alike.+fn toward(mut from: [f64; 4], to: &[f64; 4], t: f64) -> [f64; 4] {+ for (v, end) in from.iter_mut().zip(to) {+ *v += (end - *v) * t;+ }+ from+}+fn is_zero(v: &f64) -> bool {*v == 0.0}@@ -130,7 +190,7 @@ fn is_zero(v: &f64) -> bool {impl Clip {/// A clip of `file` from `start` for `frames`, from its source's `source_in` at speed 1, fully opaque.pub fn new(id: String, file: usize, start: i64, frames: i64, source_in: f64) -> Clip {- Clip { id, file, start, frames, source_in, speed: 1.0, r#box: None, fit: None, opacity: 1.0, gain_db: 0.0, fade_in: 0.0, fade_out: 0.0, link: None }+ Clip { id, file, start, frames, source_in, speed: 1.0, r#box: None, fit: None, clip: None, position: None, opacity: 1.0, keys: Vec::new(), gain_db: 0.0, fade_in: 0.0, fade_out: 0.0, link: None }}pub fn end(&self) -> i64 {diff --git a/apps/layers/src/plan.rs b/apps/layers/src/plan.rsindex b6930d54..1a4ed2d8 100644--- a/apps/layers/src/plan.rs+++ b/apps/layers/src/plan.rs@@ -6,8 +6,11 @@ use std::path::{Path, PathBuf};use serde_json::Value;-/// One file shown over a run of frames, as the manifest's frames say: its first source time and rate, its box and-/// fit at its first frame, its place in the page's order (lower draws first), and whether it moved or faded.+pub use crate::model::{Key, key_at};++/// One file shown over a run of frames, as the manifest's frames say: its first source time and rate, its box, what of+/// it a box it's in leaves showing (its clip), its fit and object-position at its first frame, its place in the page's+/// order (lower draws first), and its keys when it moves, is cut differently or fades.#[derive(Clone, Debug, PartialEq)]pub struct Run {pub src: String,@@ -18,11 +21,52 @@ pub struct Run {pub last_at: f64,pub rate: Option<f64>,pub bx: [f64; 4],+ pub clip: Option<[f64; 4]>,pub fit: String,+ /// object-position when not centred: [x px, x share of the free space, y px, y share]+ pub position: Option<[f64; 4]>,pub opacity: f64,pub z: usize,- pub moved: bool,- pub faded: bool,+ /// its box, clip, object-position and opacity where they change, frames from the timeline's start: each frame that+ /// differs from the one before and each that differs from the one after (where a hold ends), its first and its+ /// last, so a straight line between two keys is what each frame between them shows; none when nothing changes+ pub keys: Vec<Key>,+}++/// Whether two keys show the footage alike: their boxes and clips to a twentieth of a pixel, their object-positions'+/// px to the same and their shares of the free space to a hundred-thousandth (a 4K picture's free space is a few+/// thousand px, a share's step a frame of a slow pan a few hundredths), and their opacity to half a percent.+fn same(a: &Key, b: &Key) -> bool {+ let (p, q) = (placed(&a.position), placed(&b.position));+ let most = [apart(&a.r#box, &b.r#box), apart(&shown(&a.r#box, &a.clip), &shown(&b.r#box, &b.clip)), (p[0] - q[0]).abs(), (p[2] - q[2]).abs()];+ most.into_iter().fold(0.0, f64::max) <= 0.05 && (p[1] - q[1]).abs().max((p[3] - q[3]).abs()) <= 1e-5 && (a.opacity - b.opacity).abs() <= 0.005+}++/// How far apart two fours are: their farthest pair.+pub fn apart(p: &[f64; 4], q: &[f64; 4]) -> f64 {+ let mut most = 0.0f64;+ for (x, y) in p.iter().zip(q) {+ most = most.max((x - y).abs());+ }+ most+}++impl Run {+ /// Its box, clip, object-position and opacity at `frame` (from the timeline's start): its keys' straight line+ /// there, or its first frame's when it has none.+ pub fn at(&self, frame: i64) -> Key {+ key_at(&self.keys, frame).unwrap_or(Key { frame, r#box: self.bx, clip: self.clip, position: self.position, opacity: self.opacity })+ }+}++/// Only the keys where something changes: the first, the last, and those on either side of a change (none when nothing+/// does).+fn changes(all: Vec<Key>) -> Vec<Key> {+ if all.windows(2).all(|p| same(&p[0], &p[1])) {+ return Vec::new();+ }+ let n = all.len();+ (0..n).filter(|&i| i == 0 || i + 1 == n || !same(&all[i], &all[i - 1]) || !same(&all[i], &all[i + 1])).map(|i| all[i].clone()).collect()}/// One sound clip of the manifest: its file, frames, source time, gain, rate and fades.@@ -49,13 +93,16 @@ pub fn runs(manifest: &Value, fps: f64) -> Vec<Run> {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 id = 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 four = |field: &str| -> Option<[f64; 4]> { v[field].is_array().then(|| std::array::from_fn(|k| v[field][k].as_f64().unwrap_or(0.0))) };+ let (clip, position) = (four("clip"), four("position"));+ let key = Key { frame: f, r#box: bx, clip, position, opacity };let continues = |r: &Run| {let step = at - r.last_at;- r.key == key && r.end == f && step > 0.0 && match r.rate {+ r.key == id && r.end == f && step > 0.0 && match r.rate {Some(rate) => (step - rate / fps).abs() <= 0.6 / fps,None => step * fps <= 8.0,}@@ -63,12 +110,12 @@ pub fn runs(manifest: &Value, fps: f64) -> Vec<Run> {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.keys.push(key);(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 });+ let fit = v["fit"].as_str().unwrap_or("fill").to_string();+ next.push(Run { src, key: id, start: f, end: f + 1, at, last_at: at, rate: None, bx, clip, fit, position, opacity, z, keys: vec![key] });}}done.append(&mut open);@@ -77,6 +124,7 @@ pub fn runs(manifest: &Value, fps: f64) -> Vec<Run> {done.append(&mut open);// the rate over the whole run (source times are whole milliseconds, so one step's can be 1% off), to hundredthsfor r in &mut done {+ r.keys = changes(std::mem::take(&mut r.keys));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);}@@ -105,6 +153,14 @@ pub fn sounds(manifest: &Value) -> Vec<Sound> {.collect()}+/// How many of a sound's frames it's heard for: its span on the timeline, or fewer when its file ends first (raea's+/// <Audio> stops at its file's end, so a one-second tick in a longer <Sequence> is a one-second clip, not one that+/// runs past its media in an editor).+pub fn heard_frames(s: &Sound, seconds: f64, fps: f64) -> i64 {+ let left = ((seconds - s.at) / s.rate.max(0.01) * fps + 1e-6).floor() as i64;+ (s.to - s.from).min(left.max(0))+}+/// Runs of frames that draw something.pub fn spans(drawn: &[bool]) -> Vec<(i64, i64)> {let mut out = Vec::new();@@ -123,6 +179,87 @@ pub fn spans(drawn: &[bool]) -> Vec<(i64, i64)> {out}+/// The keyframes a straight line between their neighbours can't stand for: each (when, values) whose values lie off+/// the line from the last kept to the next by more than `tol` (each value's own), kept with the first and the last. A+/// steady move or push-in is its two ends; a raea easing keeps a key a frame.+pub fn thin<const N: usize>(all: &[(i64, [f64; N])], tol: &[f64; N]) -> Vec<(i64, [f64; N])> {+ let mut kept = vec![all[0]];+ let mut from = 0;+ for to in 2..all.len() {+ let (a, b) = (&all[from], &all[to]);+ let off = (from + 1..to).any(|i| {+ let t = (all[i].0 - a.0) as f64 / (b.0 - a.0).max(1) as f64;+ (0..N).any(|k| (a.1[k] + (b.1[k] - a.1[k]) * t - all[i].1[k]).abs() > tol[k])+ });+ if off {+ from = to - 1;+ kept.push(all[from]);+ }+ }+ if all.len() > 1 {+ kept.push(all[all.len() - 1]);+ }+ kept+}++/// What of a box shows: its clip, else all of it.+pub fn shown(bx: &[f64; 4], clip: &Option<[f64; 4]>) -> [f64; 4] {+ clip.unwrap_or(*bx)+}++/// An object-position as [x px, x share, y px, y share]: its own, or centred (CSS's default) when none.+pub fn placed(position: &Option<[f64; 4]>) -> [f64; 4] {+ position.unwrap_or([0.0, 0.5, 0.0, 0.5])+}++/// A picture as raea draws it: where the whole of it is on the canvas, and what of it is kept.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Picture {+ /// the whole picture, [x, y, width, height] on the canvas (it can run past its box and the canvas)+ pub drawn: [f64; 4],+ /// what of it is kept, as shares of it: [left, top, right, bottom] edges, [0, 0, 1, 1] all of it+ pub kept: [f64; 4],+}++/// Where a picture of `mw` x `mh` (upright) is drawn in `bx` on a `w` x `h` canvas, as blitz-paint draws it: sized by+/// CSS's object-fit `fit`, placed by `position` (object-position; centred when none), and cut where its box or `clip`+/// (what a box it's in leaves showing) cut it inside the canvas. The canvas's own edges cut nothing: an editor shows no+/// more than its frame anyway, and someone reframing the clip there finds the rest of the picture, not a crop. A note+/// when an editor can't show it so (object-fit: fill stretches it; an editor fits it inside its box instead).+pub fn picture(bx: &[f64; 4], clip: &Option<[f64; 4]>, fit: &str, position: &Option<[f64; 4]>, (mw, mh): (f64, f64), (w, h): (f64, f64)) -> (Picture, Option<String>) {+ let [x, y, bw, bh] = *bx;+ let (sx, sy) = (bw / mw, bh / mh);+ let mut note = None;+ let s = match fit {+ "cover" => sx.max(sy),+ "none" => 1.0,+ "scale-down" => sx.min(sy).min(1.0),+ "contain" => sx.min(sy),+ _ => {+ if (sx - sy).abs() > 0.01 * sx.max(sy) {+ note = Some(format!("stretched to its {bw:.0}x{bh:.0} box (object-fit: fill); fitted inside it"));+ }+ sx.min(sy)+ }+ };+ let (dw, dh) = (mw * s, mh * s);+ let [xp, xs, yp, ys] = placed(position);+ let (dx, dy) = (x + xp + xs * (bw - dw), y + yp + ys * (bh - dh));+ // the edges that cut it: its box's and its clip's, those inside the canvas+ let [kx, ky, kw, kh] = shown(bx, clip);+ let near = |e: f64| e > 0.5;+ let far = |e: f64, side: f64| e < side - 0.5;+ let left = [x, kx].into_iter().filter(|&e| near(e)).fold(f64::NEG_INFINITY, f64::max);+ let top = [y, ky].into_iter().filter(|&e| near(e)).fold(f64::NEG_INFINITY, f64::max);+ let right = [x + bw, kx + kw].into_iter().filter(|&e| far(e, w)).fold(f64::INFINITY, f64::min);+ let bottom = [y + bh, ky + kh].into_iter().filter(|&e| far(e, h)).fold(f64::INFINITY, f64::min);+ // those edges on the picture (none past it), as shares of it+ let (l, r) = (left.max(dx).min(dx + dw), right.min(dx + dw).max(dx));+ let (t, b) = (top.max(dy).min(dy + dh), bottom.min(dy + dh).max(dy));+ let kept = [(l - dx) / dw, (t - dy) / dh, (r - dx) / dw, (b - dy) / dh];+ (Picture { drawn: [dx, dy, dw, dh], kept }, note)+}+/// 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.0diff --git a/apps/layers/src/srt.rs b/apps/layers/src/srt.rsindex 563ece58..9b370b46 100644--- a/apps/layers/src/srt.rs+++ b/apps/layers/src/srt.rs@@ -17,13 +17,27 @@ pub fn said(manifest: &Value) -> Vec<String> {.as_array().into_iter().flatten()- .map(|f| {- let words: Vec<String> = f["text"].as_array().into_iter().flatten().filter(|t| t["caption"] == true && t["opacity"].as_f64().unwrap_or(1.0) > 0.01).filter_map(|t| t["text"].as_str()).map(|s| s.split_whitespace().collect::<Vec<_>>().join(" ")).filter(|s| !s.is_empty()).collect();- words.join(" ")- })+ .map(caption_words).collect()}+/// A frame's caption words (text marked `caption` and shown), each run's spacing made single, joined in order.+fn caption_words(frame: &Value) -> String {+ let mut out = String::new();+ for t in frame["text"].as_array().into_iter().flatten() {+ if t["caption"] != true || t["opacity"].as_f64().unwrap_or(1.0) <= 0.01 {+ continue;+ }+ for word in t["text"].as_str().unwrap_or_default().split_whitespace() {+ if !out.is_empty() {+ out.push(' ');+ }+ out.push_str(word);+ }+ }+ out+}+/// The lines: a run of frames showing the same words is one, and so is a line whose words come in one by one (each/// frame's words starting with the last's) or go one by one, shown whole for the run. A word's colour changing (a/// highlight as it's said) isn't in the words, so it never starts a line.diff --git a/apps/layers/src/tests.rs b/apps/layers/src/tests.rsindex 365061e6..5c26a982 100644--- a/apps/layers/src/tests.rs+++ b/apps/layers/src/tests.rs@@ -49,7 +49,7 @@ fn layers_json_reads_back_as_it_was_written() {frames: 90,reference: "reference.mp4".into(),srt: Some("edit.srt".into()),- files: vec![model::File { path: "/m/clip.mp4".into(), kind: model::FileKind::Video, seconds: 3.0, width: 640, height: 360, has_audio: true, channels: 2, sample_rate: 48_000 }],+ files: vec![model::File { path: "/m/clip.mp4".into(), kind: model::FileKind::Video, seconds: 3.0, width: 640, height: 360, has_audio: true, channels: 2, sample_rate: 48_000, rotation: 0 }],tracks: vec![model::Track { layer: Layer::Footage, name: "footage".into(), clips: vec![v] }, model::Track { layer: Layer::Sound, name: "sound".into(), clips: vec![a] }],notes: vec![],};@@ -86,7 +86,7 @@ fn footage_runs_break_where_the_source_jumps() {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!(!r[2].keys.is_empty() && r[0].keys.is_empty(), "the corner moves; the take holds");assert_eq!(r[2].fit, "fill");}@@ -119,27 +119,85 @@ fn a_static_file_is_found_in_the_edits_media_folder() {// the FCP7 XML (docs/layers.feature LA5a)+/// motion's (scale, centre, crop) for a picture in `bx` on a `w` x `h` frame, in `editor`'s terms+fn placed(editor: crate::xml::Editor, bx: [f64; 4], clip: Option<[f64; 4]>, fit: &str, position: Option<[f64; 4]>, media: (f64, f64), frame: (f64, f64)) -> (f64, [f64; 2], [f64; 4]) {+ crate::xml::motion(editor, &picture(&bx, &clip, fit, &position, media, frame).0, media, false, frame)+}++fn near(a: f64, b: f64) -> bool {+ (a - b).abs() < 1e-6+}+#[test]fn a_picture_in_picture_sits_as_raea_drew_it_in_basic_motions_terms() {- use crate::xml::motion;+ use crate::xml::Editor::*;// C (1280x720) contained in a 380x225 box at (850, 50) on a 1280x720 sequence: scaled to 380/1280, its centre- // right of and above the frame's, nothing cut- let (scale, centre, crop, note) = motion([850.0, 50.0, 380.0, 225.0], "contain", 1280.0, 720.0, 1280.0, 720.0);- assert!((scale - 380.0 / 1280.0 * 100.0).abs() < 1e-9 && note.is_none());- assert!((centre[0] - (1040.0 - 640.0) / 1280.0).abs() < 1e-9 && (centre[1] - (162.5 - 360.0) / 720.0).abs() < 1e-9);- assert_eq!(crop, [0.0; 4]);- // a landscape take covering a portrait frame: scaled to fill its height, its sides cut evenly- let (scale, centre, crop, _) = motion([0.0, 0.0, 1080.0, 1920.0], "cover", 1920.0, 1080.0, 1080.0, 1920.0);- assert!((scale - 1920.0 / 1080.0 * 100.0).abs() < 1e-9 && centre == [0.0, 0.0]);- assert!((crop[0] - (3413.333_333 - 1080.0) / 2.0 / 3413.333_333 * 100.0).abs() < 1e-3 && crop[0] == crop[1] && crop[2] == 0.0);+ // right of and above the frame's, nothing cut; the media the frame's size, so both editors alike+ for e in [Premiere, Resolve] {+ let (scale, centre, crop) = placed(e, [850.0, 50.0, 380.0, 225.0], None, "contain", None, (1280.0, 720.0), (1280.0, 720.0));+ assert!(near(scale, 380.0 / 1280.0 * 100.0) && near(centre[0], (1040.0 - 640.0) / 1280.0) && near(centre[1], (162.5 - 360.0) / 720.0));+ assert_eq!(crop, [0.0; 4]);+ }// stretched in raea: fitted inside, and said- assert!(motion([0.0, 0.0, 500.0, 100.0], "fill", 640.0, 640.0, 1080.0, 1920.0).3.is_some());+ assert!(picture(&[0.0, 0.0, 500.0, 100.0], &None, "fill", &None, (640.0, 640.0), (1080.0, 1920.0)).1.is_some());+}++/// a horizontal (landscape) take covering a vertical frame: scaled to fill its height, uncut (the frame cuts its+/// sides, so an editor reframing it finds the rest); Premiere's Scale of its pixels, Resolve's of it fitted (whole) to+/// the frame+#[test]+fn a_horizontal_take_covers_a_vertical_frame_uncut() {+ use crate::xml::Editor::*;+ let (scale, centre, crop) = placed(Premiere, [0.0, 0.0, 1080.0, 1920.0], None, "cover", None, (3840.0, 2160.0), (1080.0, 1920.0));+ assert!(near(scale, 1920.0 / 2160.0 * 100.0) && centre == [0.0, 0.0] && crop == [0.0; 4]);+ let (scale, _, _) = placed(Resolve, [0.0, 0.0, 1080.0, 1920.0], None, "cover", None, (3840.0, 2160.0), (1080.0, 1920.0));+ assert!(near(scale, (1920.0 / 2160.0) / (1080.0 / 3840.0) * 100.0));+ // framed on its left third (object-position: 0% 50%): the picture's left edge on the frame's, its centre right of+ // the frame's by half its overhang, in each editor's units+ let dw = 3840.0 * 1920.0 / 2160.0;+ let (_, centre, crop) = placed(Premiere, [0.0, 0.0, 1080.0, 1920.0], None, "cover", Some([0.0, 0.0, 0.0, 0.5]), (3840.0, 2160.0), (1080.0, 1920.0));+ assert!(near(centre[0], (dw / 2.0 - 540.0) / 3840.0) && centre[1] == 0.0 && crop == [0.0; 4]);+ let (_, centre, _) = placed(Resolve, [0.0, 0.0, 1080.0, 1920.0], None, "cover", Some([0.0, 0.0, 0.0, 0.5]), (3840.0, 2160.0), (1080.0, 1920.0));+ assert!(near(centre[0], (dw / 2.0 - 540.0) / 1080.0));+ // contained in a picture in picture above the frame's middle: Premiere's Center in the take's own pixels, Resolve's in+ // the take fitted to the frame (1080 x 607.5), across and down alike (Resolve drew 1080's units 238 px low, 11-17)+ let (_, centre, _) = placed(Premiere, [80.0, 300.0, 620.0, 620.0], None, "contain", None, (3840.0, 2160.0), (1080.0, 1920.0));+ assert!(near(centre[0], -150.0 / 3840.0) && near(centre[1], -350.0 / 2160.0), "{centre:?}");+ let (_, centre, _) = placed(Resolve, [80.0, 300.0, 620.0, 620.0], None, "contain", None, (3840.0, 2160.0), (1080.0, 1920.0));+ assert!(near(centre[0], -150.0 / 1080.0) && near(centre[1], -350.0 / 607.5), "{centre:?}");+ // in a box inside the frame it's cut to the box, each side by what overhangs it+ let (_, _, crop) = placed(Premiere, [100.0, 300.0, 880.0, 880.0], None, "cover", None, (3840.0, 2160.0), (1080.0, 1920.0));+ let over = (3840.0 * 880.0 / 2160.0 - 880.0) / 2.0 / (3840.0 * 880.0 / 2160.0) * 100.0;+ assert!(near(crop[0], over) && near(crop[1], over) && crop[2] == 0.0 && crop[3] == 0.0, "{crop:?}");+}++/// composed at the footage's own size (a 4K edit of 4K takes): 100 in both editors, wherever it's placed; a 1080 edit of+/// the same takes is Premiere's 50 and Resolve's 100, its centre in each one's units+#[test]+fn footage_at_the_frames_size_is_at_100_in_both_editors() {+ use crate::xml::Editor::*;+ for e in [Premiere, Resolve] {+ let (scale, centre, crop) = placed(e, [0.0, 0.0, 2160.0, 3840.0], None, "cover", None, (2160.0, 3840.0), (2160.0, 3840.0));+ assert!(near(scale, 100.0) && centre == [0.0, 0.0] && crop == [0.0; 4], "{e:?}");+ // risen 520 px (the 1080 edit's 260): Premiere's 520 / 3840 of the take, Resolve's 520 / 3840 of the frame+ let (_, centre, _) = placed(e, [0.0, -520.0, 2160.0, 3840.0], None, "cover", None, (2160.0, 3840.0), (2160.0, 3840.0));+ assert!(near(centre[1], -520.0 / 3840.0));+ }+ let (scale, centre, _) = placed(Premiere, [0.0, -260.0, 1080.0, 1920.0], None, "cover", None, (2160.0, 3840.0), (1080.0, 1920.0));+ assert!(near(scale, 50.0) && near(centre[1], -260.0 / 3840.0));+ let (scale, centre, _) = placed(Resolve, [0.0, -260.0, 1080.0, 1920.0], None, "cover", None, (2160.0, 3840.0), (1080.0, 1920.0));+ assert!(near(scale, 100.0) && near(centre[1], -260.0 / 1920.0));+ // across, in each one's units: a picture in picture 300 px right of centre+ let (_, centre, _) = placed(Premiere, [690.0, 760.0, 300.0, 400.0], None, "cover", None, (2160.0, 3840.0), (1080.0, 1920.0));+ assert!(near(centre[0], 300.0 / 2160.0));+ let (_, centre, _) = placed(Resolve, [690.0, 760.0, 300.0, 400.0], None, "cover", None, (2160.0, 3840.0), (1080.0, 1920.0));+ assert!(near(centre[0], 300.0 / 1080.0));}#[test]fn the_xml_has_the_tracks_bottom_first_and_footage_linked_to_its_sound() {use crate::model::{File, FileKind, Track};- let file = |path: &str, kind, w, h, a| File { path: path.into(), kind, seconds: 10.0, width: w, height: h, has_audio: a, channels: 2, sample_rate: 48_000 };+ let file = |path: &str, kind, w, h, a| File { path: path.into(), kind, seconds: 10.0, width: w, height: h, has_audio: a, channels: 2, sample_rate: 48_000, rotation: 0 };let c = |id: &str, f, start, frames, at| Clip::new(id.into(), f, start, frames, at);let v1 = Clip { r#box: Some([0.0, 0.0, 1280.0, 720.0]), fit: Some("cover".into()), link: Some("a1".into()), ..c("v1", 0, 0, 90, 1.0) };let v2 = Clip { r#box: Some([0.0, 0.0, 1280.0, 720.0]), fit: Some("cover".into()), ..c("v2", 0, 90, 30, 5.0) };@@ -161,7 +219,7 @@ fn the_xml_has_the_tracks_bottom_first_and_footage_linked_to_its_sound() {],notes: vec![],};- let (x, notes) = crate::xml::write(&l, std::path::Path::new("/out/xml/edit"));+ let (x, notes) = crate::xml::write(&l, std::path::Path::new("/out/xml/edit"), crate::xml::Editor::Premiere);assert!(notes.is_empty(), "{notes:?}");// 29.97 is a timebase of 30, NTSC; the name escapedassert!(x.contains("<name>edit & co</name><duration>120</duration><rate><timebase>30</timebase><ntsc>TRUE</ntsc></rate>"), "{x}");@@ -190,3 +248,157 @@ fn the_xml_has_the_tracks_bottom_first_and_footage_linked_to_its_sound() {// the music at -12 dB as Audio Levels' linear gainassert!(x.contains("<parameterid>level</parameterid><name>Level</name><valuemin>0.00003162</valuemin><valuemax>31.6228</valuemax><value>0.251189</value>"), "{x}");}++#[test]+fn a_sound_is_a_clip_as_long_as_its_file_plays() {+ let s = |from, to, at, rate| Sound { src: "tick.wav".into(), from, to, at, gain_db: 0.0, rate, fade_in: 0.0, fade_out: 0.0 };+ // a one-second tick in a 2.5 s Sequence at 24 fps: 24 frames, not 60+ assert_eq!(heard_frames(&s(100, 160, 0.0, 1.0), 1.0, 24.0), 24);+ // a long file in a short Sequence keeps the Sequence's length+ assert_eq!(heard_frames(&s(0, 48, 0.0, 1.0), 84.0, 24.0), 48);+ // from 0.5 s in, at double speed: 0.25 s left, 6 frames+ assert_eq!(heard_frames(&s(0, 60, 0.5, 2.0), 1.0, 24.0), 6);+ // started past its end: nothing heard+ assert_eq!(heard_frames(&s(0, 60, 2.0, 1.0), 1.0, 24.0), 0);+}++/// footage that rises in a box that shrinks over it (a split screen): keys where it holds and on either side of the+/// move, a clip from its box's cut; a run that holds still has none+#[test]+fn footage_that_moves_keeps_keys_where_it_changes() {+ let frame = |f: i64, top: f64, clip_h: Option<f64>| {+ let mut v = json!({"src": "a.mp4", "at": 1.0 + f as f64 / 24.0, "box": [0.0, top, 1080.0, 1920.0], "opacity": 1.0, "fit": "cover"});+ if let Some(h) = clip_h {+ v["clip"] = json!([0.0, 0.0, 1080.0, h]);+ }+ json!({"frame": f, "videos": [v]})+ };+ // frames 0-2 full, 3-5 rising and cut, 6-8 held split+ let tops = [0.0, 0.0, 0.0, -100.0, -200.0, -260.0, -260.0, -260.0, -260.0];+ let clips = [None, None, None, Some(1400.0), Some(1000.0), Some(860.0), Some(860.0), Some(860.0), Some(860.0)];+ let m = json!({"frames": (0..9).map(|f| frame(f, tops[f as usize], clips[f as usize])).collect::<Vec<_>>()});+ let r = &runs(&m, 24.0)[0];+ assert!(r.clip.is_none());+ assert_eq!(r.keys.iter().map(|k| k.frame).collect::<Vec<_>>(), [0, 2, 3, 4, 5, 8]);+ assert_eq!(r.keys[3].clip, Some([0.0, 0.0, 1080.0, 1000.0]));+ let still = json!({"frames": (0..9).map(|f| frame(f, 0.0, Some(860.0))).collect::<Vec<_>>()});+ let r = &runs(&still, 24.0)[0];+ assert!(r.keys.is_empty() && r.clip == Some([0.0, 0.0, 1080.0, 860.0]));+ // between two keys, a straight line: halfway from frame 3 (risen 100, cut at 1400) to 4 has none, but 3.. 5 does+ let moving = runs(&m, 24.0).remove(0);+ let k = moving.at(4);+ assert_eq!((k.r#box[1], k.clip), (-200.0, Some([0.0, 0.0, 1080.0, 1000.0])));+ assert_eq!(moving.at(7).r#box[1], -260.0);+ assert_eq!((moving.at(-5).r#box[1], moving.at(20).r#box[1]), (0.0, -260.0), "before its first key and after its last");+}++#[test]+fn a_clip_cuts_the_picture_as_crop() {+ use crate::xml::Editor::Premiere;+ // a 1080x1920 take filling a portrait frame, risen 260 px, its box cut at 860: placed by its box, all below 860+ // cut; its top (past the frame, which cuts it) not+ let (scale, centre, crop) = placed(Premiere, [0.0, -260.0, 1080.0, 1920.0], Some([0.0, 0.0, 1080.0, 860.0]), "cover", None, (1080.0, 1920.0), (1080.0, 1920.0));+ assert!(near(scale, 100.0) && near(centre[1], -260.0 / 1920.0));+ assert!(crop[0] == 0.0 && crop[1] == 0.0 && crop[2] == 0.0 && near(crop[3], (1920.0 - 1120.0) / 1920.0 * 100.0), "{crop:?}");+ // a picture in picture cut by a card's edges inside the frame: cut where the card cuts it+ let (_, _, crop) = placed(Premiere, [100.0, 100.0, 400.0, 400.0], Some([150.0, 100.0, 300.0, 400.0]), "cover", None, (400.0, 400.0), (1080.0, 1920.0));+ assert!(near(crop[0], 12.5) && near(crop[1], 12.5) && crop[2] == 0.0 && crop[3] == 0.0, "{crop:?}");+}++/// a steady move is its two ends in the XML, an eased one a key a frame; a clip at another speed is placed at its own+/// speed, as many source frames as it lasts, and said+#[test]+fn steady_moves_are_two_keys_and_other_speeds_are_said() {+ use crate::model::{File, FileKind, Key, Track};+ let k = |frame: i64, x: f64| Key { frame, r#box: [x, 500.0, 400.0, 400.0], clip: None, position: None, opacity: 1.0 };+ let steady = Clip { r#box: Some([100.0, 500.0, 400.0, 400.0]), fit: Some("cover".into()), keys: (0..24).map(|f| k(f, 100.0 + 10.0 * f as f64)).collect(), ..Clip::new("v1".into(), 0, 0, 24, 0.0) };+ let eased = Clip { r#box: Some([100.0, 500.0, 400.0, 400.0]), fit: Some("cover".into()), keys: (0..24).map(|f| k(f, 100.0 + (f * f) as f64)).collect(), speed: 2.0, ..Clip::new("v2".into(), 0, 24, 24, 0.0) };+ let l = Layers {+ version: model::VERSION,+ name: "e".into(),+ width: 1080,+ height: 1920,+ fps: 24.0,+ frames: 48,+ reference: "reference.mp4".into(),+ srt: None,+ files: vec![File { path: "/m/a.mov".into(), kind: FileKind::Video, seconds: 10.0, width: 400, height: 400, has_audio: false, channels: 2, sample_rate: 48_000, rotation: 0 }],+ tracks: vec![Track { layer: Layer::Footage, name: "footage".into(), clips: vec![steady, eased] }],+ notes: vec![],+ };+ let (x, notes) = crate::xml::write(&l, std::path::Path::new("/out"), crate::xml::Editor::Premiere);+ let v1 = &x[x.find("<clipitem id=\"v1\"").unwrap()..x.find("<clipitem id=\"v2\"").unwrap()];+ assert_eq!(v1.matches("<keyframe>").count(), 2, "{v1}");+ let v2 = &x[x.find("<clipitem id=\"v2\"").unwrap()..];+ assert!(v2.matches("<keyframe>").count() > 20 && v2.contains("<start>24</start><end>48</end><in>0</in><out>24</out>"), "{v2}");+ assert!(notes.iter().any(|n| n.contains("plays at 2.00x in raea")), "{notes:?}");+}++#[test]+fn keyed_footage_is_keyframed_in_the_xml() {+ use crate::model::{File, FileKind, Key, Track};+ let k = |frame, top: f64, h: f64, opacity| Key { frame, r#box: [0.0, top, 1080.0, 1920.0], clip: (h < 1920.0).then_some([0.0, 0.0, 1080.0, h]), position: None, opacity };+ let v = Clip { r#box: Some([0.0, 0.0, 1080.0, 1920.0]), fit: Some("cover".into()), keys: vec![k(0, 0.0, 1920.0, 1.0), k(12, -260.0, 860.0, 1.0), k(40, -260.0, 860.0, 0.5)], ..Clip::new("v1".into(), 0, 100, 41, 2.0) };+ let l = Layers {+ version: model::VERSION,+ name: "e".into(),+ width: 1080,+ height: 1920,+ fps: 24.0,+ frames: 141,+ reference: "reference.mp4".into(),+ srt: None,+ files: vec![File { path: "/m/a.mov".into(), kind: FileKind::Video, seconds: 10.0, width: 1080, height: 1920, has_audio: false, channels: 2, sample_rate: 48_000, rotation: 0 }],+ tracks: vec![Track { layer: Layer::Footage, name: "footage".into(), clips: vec![v] }],+ notes: vec![],+ };+ use crate::xml::Editor;+ let (x, _) = crate::xml::write(&l, std::path::Path::new("/out"), Editor::Premiere);+ // scale holds: a value, no keyframes; the centre, crop and opacity keyed, each key in the source's frames (from 48)+ assert!(x.contains("<parameterid>scale</parameterid><name>Scale</name><valuemin>0</valuemin><valuemax>1000</valuemax><value>100.0000</value></parameter>"), "{x}");+ assert!(x.contains("<parameterid>center</parameterid><name>Center</name><value><horiz>0.000000</horiz><vert>0.000000</vert></value><keyframe><when>48</when><value><horiz>0.000000</horiz><vert>0.000000</vert></value></keyframe><keyframe><when>60</when><value><horiz>0.000000</horiz><vert>-0.135417</vert></value></keyframe>"), "{x}");+ // Premiere's crop is Basic Motion's, as Premiere writes it: the bottom 41.7% cut at the split+ assert!(x.contains("<parameterid>bottomcrop</parameterid><name>Bottom</name><valuemin>0</valuemin><valuemax>100</valuemax><value>0.0000</value><keyframe><when>48</when><value>0.0000</value></keyframe><keyframe><when>60</when><value>41.6667</value></keyframe>"), "{x}");+ assert!(!x.contains("<effectid>crop</effectid>"), "{x}");+ assert!(x.contains("<parameterid>opacity</parameterid><name>opacity</name>") && x.contains("<keyframe><when>88</when><value>50.00</value></keyframe>"), "{x}");+ // Resolve's is FCP7's Crop filter, as it is for a file stored upright: 41.7% off its bottom (its top past the frame,+ // which cuts it)+ let (x, _) = crate::xml::write(&l, std::path::Path::new("/out"), Editor::Resolve);+ assert!(!x.contains("bottomcrop") && x.contains("<effectid>crop</effectid>"), "{x}");+ // a take twice the timeline's size, stored on its side (a phone's): Premiere's is described as stored (3840 x 2160,+ // as Premiere's own XML describes it) and its Center in that, 260 px up 260 / 2160; Resolve's in the frame's+ let mut phone = l.clone();+ (phone.files[0].width, phone.files[0].height, phone.files[0].rotation) = (2160, 3840, 90);+ let premiere = crate::xml::write(&phone, std::path::Path::new("/out"), Editor::Premiere).0;+ assert!(premiere.contains("<width>3840</width><height>2160</height>") && premiere.contains("<keyframe><when>60</when><value><horiz>0.000000</horiz><vert>-0.120370</vert></value></keyframe>"), "{premiere}");+ assert!(crate::xml::write(&phone, std::path::Path::new("/out"), Editor::Resolve).0.contains("<width>2160</width><height>3840</height>"));+ assert!(crate::xml::write(&phone, std::path::Path::new("/out"), Editor::Resolve).0.contains("<keyframe><when>60</when><value><horiz>0.000000</horiz><vert>-0.135417</vert></value></keyframe>"));+ // a take twice the timeline's size: Premiere's 50 (of its pixels) is Resolve's 100 (fitted to the timeline)+ let mut big = l.clone();+ big.files[0].width = 2160;+ big.files[0].height = 3840;+ assert!(crate::xml::write(&big, std::path::Path::new("/out"), Editor::Premiere).0.contains("<parameterid>scale</parameterid><name>Scale</name><valuemin>0</valuemin><valuemax>1000</valuemax><value>50.0000</value>"));+ assert!(crate::xml::write(&big, std::path::Path::new("/out"), Editor::Resolve).0.contains("<parameterid>scale</parameterid><name>Scale</name><valuemin>0</valuemin><valuemax>1000</valuemax><value>100.0000</value>"));+ assert!(x.contains("<parameterid>bottom</parameterid><name>bottom</name><valuemin>0</valuemin><valuemax>100</valuemax><value>0.0000</value><keyframe><when>48</when><value>0.0000</value></keyframe><keyframe><when>60</when><value>41.6667</value></keyframe>"), "{x}");+ // a phone's take stored turned 90: Resolve cuts it mirrored top to bottom, so its sides go swapped (11-17's render),+ // Premiere's as they are+ let mut l = l;+ l.files[0].rotation = 90;+ assert!(crate::xml::write(&l, std::path::Path::new("/out"), Editor::Premiere).0.contains("<parameterid>bottomcrop</parameterid><name>Bottom</name><valuemin>0</valuemin><valuemax>100</valuemax><value>0.0000</value><keyframe><when>48</when><value>0.0000</value></keyframe><keyframe><when>60</when><value>41.6667</value>"));+ let (x, _) = crate::xml::write(&l, std::path::Path::new("/out"), Editor::Resolve);+ assert!(x.contains("<parameterid>top</parameterid><name>top</name><valuemin>0</valuemin><valuemax>100</valuemax><value>0.0000</value><keyframe><when>48</when><value>0.0000</value></keyframe><keyframe><when>60</when><value>41.6667</value></keyframe>"), "{x}");+ assert!(x.contains("<parameterid>bottom</parameterid><name>bottom</name><valuemin>0</valuemin><valuemax>100</valuemax><value>0.0000</value></parameter>"), "{x}");+}++/// a pan inside a still box (object-position animated, a Ken Burns across a horizontal take): keyed like a move, the+/// picture's centre crossing the frame in the XML+#[test]+fn a_pan_inside_its_box_is_keyed() {+ let frame = |f: i64| json!({"frame": f, "videos": [{"src": "land.mov", "at": f as f64 / 24.0, "box": [0.0, 0.0, 1080.0, 1920.0], "opacity": 1.0, "fit": "cover", "position": [0.0, f as f64 / 10.0, 0.0, 0.5]}]});+ let r = &runs(&json!({"frames": (0..11).map(frame).collect::<Vec<_>>()}), 24.0)[0];+ assert!(!r.keys.is_empty() && r.at(5).position == Some([0.0, 0.5, 0.0, 0.5]));+ let (from, to) = (r.at(0), r.at(10));+ let centre = |k: &Key| crate::xml::motion(crate::xml::Editor::Resolve, &picture(&k.r#box, &k.clip, "cover", &k.position, (3840.0, 2160.0), (1080.0, 1920.0)).0, (3840.0, 2160.0), false, (1080.0, 1920.0)).1[0];+ let dw = 3840.0 * 1920.0 / 2160.0;+ assert!(near(centre(&from), (dw / 2.0 - 540.0) / 1080.0) && near(centre(&to), -(dw / 2.0 - 540.0) / 1080.0));+}diff --git a/apps/layers/src/xml.rs b/apps/layers/src/xml.rsindex c69c632b..c90d1a99 100644--- a/apps/layers/src/xml.rs+++ b/apps/layers/src/xml.rs@@ -2,7 +2,8 @@//! and DaVinci Resolve (File, Import, Timeline) both read: one sequence at the composition's rate and size, its video//! tracks bottom first (under, the footage, what's behind a picture in picture, the pictures in picture, graphics,//! captions), its audio tracks below. Footage points at its file where it is, placed as raea drew it (Basic Motion's-//! scale and centre, a Crop where object-fit: cover cuts it, its Opacity); a footage clip and its own sound are linked+//! scale and centre, its crop where object-fit: cover or a box it's in cuts it, its Opacity, each keyframed where it+//! changes over the clip; the crop as each editor writes it, so an XML for each: see Editor); a footage clip and its own sound are linked//! clipitems, which Premiere's Unlink and Resolve's Link Clips separate. Sound is laid out as Premiere writes it (read//! from an XML Premiere Pro 2026 exported): a stereo file's channels each a mono clipitem on a track of its own, each//! panned to its side by an Audio Pan on the clip, as Resolve and FCP7 write it (both editors import a channel centred@@ -12,7 +13,8 @@use std::fmt::Write as _;use std::path::Path;-use crate::model::{Clip, FileKind, Layer, Layers};+use crate::model::{Clip, FileKind, Key, Layer, Layers};+use crate::plan::{self, Picture};/// xmeml's rate: a whole timebase and whether it runs at 1000/1001 of it (29.97 is 30 NTSC).fn rate(fps: f64) -> (u32, bool) {@@ -38,8 +40,20 @@ fn uuid(name: &str) -> String {format!("{:08x}-{:04x}-4{:03x}-8{:03x}-{:012x}", a >> 32, (a >> 16) & 0xffff, a & 0xfff, (b >> 52) & 0xfff, b & 0xffff_ffff_ffff)}+/// Text as XML: its five reserved characters as entities.fn esc(s: &str) -> String {- s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)+ let mut out = String::with_capacity(s.len());+ for ch in s.chars() {+ match ch {+ '&' => out.push_str("&"),+ '<' => out.push_str("<"),+ '>' => out.push_str(">"),+ '"' => out.push_str("""),+ '\'' => out.push_str("'"),+ _ => out.push(ch),+ }+ }+ out}/// A file's path as xmeml's pathurl: file://localhost and the absolute path, each byte outside the unreserved set@@ -56,47 +70,91 @@ fn pathurl(p: &Path) -> String {out}-/// Where a picture of `mw` x `mh` sits in `bx` with CSS's object-fit `fit`, in Basic Motion's terms on a `w` x `h`-/// sequence: its scale (100: the media's own pixels), its centre (0, 0: the frame's; a unit is the frame's width or-/// height) and what Crop cuts from each side (percent of the media: left, right, top, bottom); and a note when it-/// can't be shown so (a stretched picture).-pub fn motion(bx: [f64; 4], fit: &str, mw: f64, mh: f64, w: f64, h: f64) -> (f64, [f64; 2], [f64; 4], Option<String>) {- let [x, y, bw, bh] = bx;- let (sx, sy) = (bw / mw, bh / mh);- let mut note = None;- let s = match fit {- "cover" => sx.max(sy),- "none" => 1.0,- "scale-down" => sx.min(sy).min(1.0),- "contain" => sx.min(sy),- _ => {- if (sx - sy).abs() > 0.01 * sx.max(sy) {- note = Some(format!("stretched to its {bw:.0}x{bh:.0} box (object-fit: fill); fitted inside it"));- }- sx.min(sy)+/// Basic Motion's scale and centre and the crop's sides ([left, right, top, bottom], percent of the picture) for a+/// picture drawn as `p` (plan::picture) from media of `mw` x `mh` (upright; `turned` when it's stored a quarter turn+/// from that, a phone's take) on a `w` x `h` sequence, in `editor`'s terms (see units).+pub fn motion(editor: Editor, p: &Picture, media: (f64, f64), turned: bool, frame: (f64, f64)) -> (f64, [f64; 2], [f64; 4]) {+ let [dx, dy, dw, dh] = p.drawn;+ let (cx, cy) = (dx + dw / 2.0 - frame.0 / 2.0, dy + dh / 2.0 - frame.1 / 2.0);+ let (whole, unit) = units(editor, media, turned, frame);+ let [l, t, r, b] = p.kept;+ (dw / whole * 100.0, [cx / unit.0, cy / unit.1], [l * 100.0, (1.0 - r) * 100.0, t * 100.0, (1.0 - b) * 100.0])+}++/// An editor's units on the canvas, in px: the picture's width at Scale 100, and Center's 1 across and down, each the+/// clip's own size at Scale 100 as that editor has it, read from what it did with what it was given (11-17).+/// Premiere: the media's own pixels, Center in its width and height as the XML describes it, which is as stored+/// (Premiere's own XML describes a phone's take 3840 x 2160 and wrote a 68 px move of it 68 / 2160; told 2160 x 3840 it+/// placed -0.120370 at 462.2 px, 0.120370 of 3840). Resolve: the media fitted to the frame (its default Input Scaling,+/// "scale entire image to fit": its own XML gave a 4K take on a smaller timeline Scale 100), Center in that fitted+/// size too (a horizontal take fitted to a 1080 x 1920 frame is 1080 x 607.5: it placed Center vert -0.182 at 110 px).+fn units(editor: Editor, (mw, mh): (f64, f64), turned: bool, (w, h): (f64, f64)) -> (f64, (f64, f64)) {+ match editor {+ Editor::Premiere if turned => (mw, (mh, mw)),+ Editor::Premiere => (mw, (mw, mh)),+ Editor::Resolve => {+ let fit = (w / mw).min(h / mh);+ (mw * fit, (mw * fit, mh * fit))}+ }+}+++/// An FCP7 parameter: its id and name, its range (none for Center's), its value and its keyframes (none when it holds).+fn parameter(id: &str, name: &str, range: Option<(f64, f64)>, value: &str, keyframes: &str) -> String {+ let range = range.map_or(String::new(), |(a, b)| format!("<valuemin>{a}</valuemin><valuemax>{b}</valuemax>"));+ format!("<parameter><parameterid>{id}</parameterid><name>{name}</name>{range}<value>{value}</value>{keyframes}</parameter>")+}++/// A parameter that holds one value, or (its values differing) is keyframed: its first value, then a keyframe at each+/// of `at`'s whens, each value written by `value`. `range` is its (min, max), none for Center's.+fn keyed<const N: usize>(id: &str, name: &str, range: Option<(f64, f64)>, at: &[(i64, [f64; N])], value: impl Fn(&[f64; N]) -> String) -> String {+ let values: Vec<String> = at.iter().map(|(_, p)| value(p)).collect();+ let first = &values[0];+ let keys: String = if values.iter().all(|v| v == first) {+ String::new()+ } else {+ at.iter().zip(&values).map(|((when, _), v)| format!("<keyframe><when>{when}</when><value>{v}</value></keyframe>")).collect()};- // what's drawn past its box is cut, each side by the share of the scaled picture that overhangs it- let (dw, dh) = (mw * s, mh * s);- let cut = |d: f64, b: f64| ((d - b) / 2.0 / d * 100.0).max(0.0);- let (cx, cy) = (cut(dw, bw), cut(dh, bh));- let centre = [(x + bw / 2.0 - w / 2.0) / w, (y + bh / 2.0 - h / 2.0) / h];- (s * 100.0, centre, [cx, cx, cy, cy], note)+ parameter(id, name, range, first, &keys)}-fn param(id: &str, name: &str, min: f64, max: f64, value: &str) -> String {- format!("<parameter><parameterid>{id}</parameterid><name>{name}</name><valuemin>{min}</valuemin><valuemax>{max}</valuemax><value>{value}</value></parameter>")+/// A clip's filter of one FCP7 effect and its parameters (each effect here is its category's own type: motion, audio+/// levels, audio pan).+fn effect(name: &str, id: &str, category: &str, media: &str, params: &[String]) -> String {+ let mut out = format!("<filter><effect><name>{name}</name><effectid>{id}</effectid><effectcategory>{category}</effectcategory><effecttype>{category}</effecttype><mediatype>{media}</mediatype>");+ params.iter().for_each(|p| out.push_str(p));+ out.push_str("</effect></filter>");+ out}-fn effect(name: &str, id: &str, category: &str, kind: &str, media: &str, params: &str) -> String {- format!("<filter><effect><name>{name}</name><effectid>{id}</effectid><effectcategory>{category}</effectcategory><effecttype>{kind}</effecttype><mediatype>{media}</mediatype>{params}</effect></filter>")+/// Which editor an XML is for: they read xmeml alike but for crop (read from an XML each exported of a clip it+/// keyframed, and from each one's render of a timeline cropping one picture stored four ways, 11-17). Premiere's crop+/// is four parameters of Basic Motion (leftcrop, topcrop, rightcrop, bottomcrop), cutting the upright picture whatever+/// its file's rotation. Resolve's is FCP7's Crop filter, which cuts the upright picture of a file stored upright, but+/// one stored turned (a phone's take) mirrored: its top and bottom swapped at 90, its left and right at 270, both at+/// 180 (Resolve 21.2.0's Cropping does the same in its Inspector). One file can't be both: an editor reading the other's+/// crop too cuts twice.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Editor {+ Premiere,+ Resolve,+}++impl Editor {+ pub fn name(self) -> &'static str {+ match self {+ Editor::Premiere => "premiere",+ Editor::Resolve => "resolve",+ }+ }}-/// The XML, and what it can't carry. `dir` is where layers.json is: its movies' paths are relative to it.-pub fn write(l: &Layers, dir: &Path) -> (String, Vec<String>) {+/// The XML for `editor`, and what it can't carry. `dir` is where layers.json is: its movies' paths are relative to it.+pub fn write(l: &Layers, dir: &Path, editor: Editor) -> (String, Vec<String>) {let mut notes = Vec::new();let fps = l.fps;- let frames = |secs: f64| (secs * fps).round() as i64;+ let frames = |secs: f64| f64::round(secs * fps) as i64;let path = |k: usize| {let p = Path::new(&l.files[k].path);if p.is_absolute() { p.to_path_buf() } else { dir.join(p) }@@ -160,7 +218,10 @@ pub fn write(l: &Layers, dir: &Path) -> (String, Vec<String>) {let f = &l.files[k];let mut media = String::new();if f.kind == FileKind::Video {- let _ = write!(media, "<video><samplecharacteristics>{}<width>{}</width><height>{}</height></samplecharacteristics></video>", rate_xml(fps), f.width, f.height);+ // its size as stored for Premiere (a phone's take on its side, as Premiere's own XML describes it), upright+ // for Resolve, as each editor's Center is read in (see units)+ let (w, h) = if editor == Editor::Premiere && f.rotation % 180 == 90 { (f.height, f.width) } else { (f.width, f.height) };+ let _ = write!(media, "<video><samplecharacteristics>{}<width>{w}</width><height>{h}</height></samplecharacteristics></video>", rate_xml(fps));}if f.has_audio {let n = f.channels.clamp(1, 2);@@ -185,11 +246,17 @@ pub fn write(l: &Layers, dir: &Path) -> (String, Vec<String>) {rate_xml(fps),c.start,c.end(),- src_in + (c.frames as f64 * c.speed).round() as i64,+ // its own speed (raea's isn't carried, said below): as many source frames as it lasts+ src_in + c.frames,links(c))};+ // Resolve fits footage of another size to the timeline by its project's Input Scaling before its Scale applies+ let other_size = |f: &crate::model::File| f.kind == FileKind::Video && (f.width, f.height) != (l.width, l.height);+ if editor == Editor::Resolve && l.tracks.iter().any(|t| t.layer == Layer::Footage && t.clips.iter().any(|c| other_size(&l.files[c.file]))) {+ notes.push("Resolve: footage not the timeline's size is placed for its default Input Scaling, \"Scale entire image to fit\" (Project Settings, Image Scaling); with another, set it back or re-place that footage".to_string());+ }let mut v = String::new();for t in &video {let _ = write!(v, "<track>");@@ -201,16 +268,50 @@ pub fn write(l: &Layers, dir: &Path) -> (String, Vec<String>) {match (t.layer, c.r#box) {(Layer::Footage, Some(bx)) => {let f = &l.files[c.file];- let (scale, centre, crop, note) = motion(bx, c.fit.as_deref().unwrap_or("fill"), f.width.max(1) as f64, f.height.max(1) as f64, l.width as f64, l.height as f64);- if let Some(n) = note {- notes.push(format!("{} (frames {}-{}): {n}", name_of(c.file), c.start, c.end() - 1));+ let fit = c.fit.as_deref().unwrap_or("fill");+ let turned = f.rotation % 180 == 90;+ let (media, frame) = ((f.width.max(1) as f64, f.height.max(1) as f64), (l.width as f64, l.height as f64));+ // its place at its first frame, or at each of its keys, each key's when in the source's frames (FCP7+ // times a clip's filters from its media: its in point is its first frame)+ let first = [Key { frame: 0, r#box: bx, clip: c.clip, position: c.position, opacity: c.opacity }];+ let at = if c.keys.is_empty() { &first[..] } else { &c.keys[..] };+ let src_in = frames(c.source_in);+ let mut placed: Vec<(i64, [f64; 8])> = Vec::with_capacity(at.len());+ let mut widest = [1.0f64, 1.0];+ for k in at {+ // (a picture object-fit: fill stretches is said with the layers: fitted inside its box here)+ let (p, _) = plan::picture(&k.r#box, &k.clip, fit, &k.position, media, frame);+ (widest[0], widest[1]) = (widest[0].max(p.drawn[2]), widest[1].max(p.drawn[3]));+ let (scale, centre, crop) = motion(editor, &p, media, turned, frame);+ placed.push((src_in + k.frame, [scale, centre[0], centre[1], crop[0], crop[1], crop[2], crop[3], k.opacity * 100.0]));+ }+ // a key a straight line between its neighbours gives to within a seventh of a pixel on the canvas+ // (the manifest's boxes are to a tenth) and half a percent of opacity (its to a whole percent), in+ // each value's own units+ let (whole, unit) = units(editor, media, turned, frame);+ let px = 0.15;+ let (cx, cy) = (px / widest[0] * 100.0, px / widest[1] * 100.0);+ let placed = plan::thin(&placed, &[px / whole * 100.0, px / unit.0, px / unit.1, cx, cx, cy, cy, 0.5]);+ let scale = keyed("scale", "Scale", Some((0.0, 1000.0)), &placed, |p| format!("{:.4}", p[0]));+ let centre = keyed("center", "Center", None, &placed, |p| format!("<horiz>{:.6}</horiz><vert>{:.6}</vert>", p[1], p[2]));+ // the crop's sides as each editor writes them, from motion's [left, right, top, bottom]+ let cut = placed.iter().any(|(_, p)| p[3..7].iter().any(|&k| k > 0.001));+ let side = |id: &str, name: &str, i: usize| keyed(id, name, Some((0.0, 100.0)), &placed, |p| format!("{:.4}", p[3 + i]));+ let mut motion = vec![scale, centre];+ if editor == Editor::Premiere && cut {+ motion.extend([("leftcrop", "Left", 0), ("topcrop", "Top", 2), ("rightcrop", "Right", 1), ("bottomcrop", "Bottom", 3)].iter().map(|&(id, n, i)| side(id, n, i)));}- body.push_str(&effect("Basic Motion", "basic", "motion", "motion", "video", &format!("{}{}", param("scale", "Scale", 0.0, 1000.0, &format!("{scale:.4}")), format!("<parameter><parameterid>center</parameterid><name>Center</name><value><horiz>{:.6}</horiz><vert>{:.6}</vert></value></parameter>", centre[0], centre[1]))));- if crop.iter().any(|&k| k > 0.001) {- body.push_str(&effect("Crop", "crop", "motion", "motion", "video", &["left", "right", "top", "bottom"].iter().zip(crop).map(|(side, k)| param(side, &format!("{}{}", side[..1].to_uppercase(), &side[1..]), 0.0, 100.0, &format!("{k:.4}"))).collect::<String>()));+ body.push_str(&effect("Basic Motion", "basic", "motion", "video", &motion));+ if editor == Editor::Resolve && cut {+ // Resolve's sides, mirrored as it mirrors a file stored turned (see Editor)+ let (lr, tb) = (matches!(f.rotation, 180 | 270), matches!(f.rotation, 90 | 180));+ let (l, r) = if lr { (1, 0) } else { (0, 1) };+ let (t, b) = if tb { (3, 2) } else { (2, 3) };+ let sides: Vec<String> = [("left", l), ("right", r), ("top", t), ("bottom", b)].iter().map(|&(n, i)| side(n, n, i)).collect();+ body.push_str(&effect("Crop", "crop", "motion", "video", &sides));}- if c.opacity < 0.999 {- body.push_str(&effect("Opacity", "opacity", "motion", "motion", "video", ¶m("opacity", "Opacity", 0.0, 100.0, &format!("{:.2}", c.opacity * 100.0))));+ if placed.iter().any(|(_, p)| p[7] < 99.9) {+ body.push_str(&effect("Opacity", "opacity", "motion", "video", &[keyed("opacity", "opacity", Some((0.0, 100.0)), &placed, |p| format!("{:.2}", p[7]))]));}}// a layer's movie fills the frame, its alpha straight@@ -231,13 +332,16 @@ pub fn write(l: &Layers, dir: &Path) -> (String, Vec<String>) {let gain = 10f64.powf(c.gain_db / 20.0);let mut body = format!("<sourcetrack><mediatype>audio</mediatype><trackindex>{ch}</trackindex></sourcetrack>");if (gain - 1.0).abs() > 1e-6 {- body.push_str(&effect("Audio Levels", "audiolevels", "audiolevels", "audiolevels", "audio", ¶m("level", "Level", 0.00003162, 31.6228, &format!("{gain:.6}"))));+ body.push_str(&effect("Audio Levels", "audiolevels", "audiolevels", "audio", &[parameter("level", "Level", Some((0.00003162, 31.6228)), &format!("{gain:.6}"), "")]));}// a stereo file's channel panned to its own side, as FCP7's Audio Pan on the clip (-1 left, 1 right): Premiere// and Resolve both import each channel centred without it, and both read it (heard 11-16); a mono file's// stays centredif channels(c) == 2 {- body.push_str(&effect("Audio Pan", "audiopan", "audiopan", "audiopan", "audio", ¶m("pan", "Pan", -1.0, 1.0, if *ch == 1 { "-1" } else { "1" })));+ body.push_str(&effect("Audio Pan", "audiopan", "audiopan", "audio", &[parameter("pan", "Pan", Some((-1.0, 1.0)), if *ch == 1 { "-1" } else { "1" }, "")]));+ }+ if *ch == 1 && (c.speed - 1.0).abs() > 0.001 {+ notes.push(format!("{} (frames {}-{}): plays at {:.2}x in raea; placed at its own speed", name_of(c.file), c.start, c.end() - 1, c.speed));}if *ch == 1 && (c.fade_in > 0.0 || c.fade_out > 0.0) {notes.push(format!("{} (frames {}-{}): its fades ({:.2} s in, {:.2} s out) aren't carried; set them in the editor", name_of(c.file), c.start, c.end() - 1, c.fade_in, c.fade_out));diff --git a/docs/capcut.feature b/docs/capcut.featureindex 0421abd8..8b449c92 100644--- a/docs/capcut.feature+++ b/docs/capcut.feature@@ -79,6 +79,20 @@ Feature: A composition handed to CapCut, ready in its timeline, and transparentThen 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+ Scenario: CC2f. Footage that moves, scales or fades is keyframed (docs/layers.feature LA4c, LA4d)+ Given a footage clip with keys in layers.json: its box, clip, object-position and opacity at the frames they change+ Then its segment's common_keyframes hold a group each for its centre across and up (half-canvas units, +y up, as+ its clip's transform), its scale across and up alike and its opacity, each key at microseconds from the+ segment's start, straight lines between ("Line"), as published accounts of the draft give them (capcut-cli's+ draft schema, pyJianYingDraft); every property is keyed while any is, CapCut setting the clip's own aside+ And its keys are placed as CC2a places a frame (raea_app_layers::plan::picture), around the cut its first frame+ shows: CapCut's crop is its material's and holds, so a picture moving inside a card that cuts it keeps the cut+ and moves; a key a straight line between its neighbours gives to 0.15 px is left out+ And a clip whose cut changes over its run (a split screen's seam rising) is cut as its first frame shows it,+ its moves keyed, and said: CapCut's keyed crop isn't in any account of the draft+ And whether a key's time counts from the segment's start or its source's, which the accounts differ on, is read+ from a trimmed clip moving in CapCut (the Telluride close, 46 frames into its take)+Rule: CC3. CapCut opens itScenario: CC3a. CapCut, quit and opened, lists the draft and plays it as raea renders itThen the timeline has the main track's shots, the picture in picture above, the overlay clips above that and thediff --git a/docs/layers.feature b/docs/layers.featureindex 618cae1f..4a2f9eb3 100644--- a/docs/layers.feature+++ b/docs/layers.feature@@ -143,6 +143,31 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaAnd it says what CC2e notes, the same lines the command printsAnd it names no editor's format: CapCut's draft and the XML are written from it+ Scenario: LA4c. Footage that moves, scales, is cut or fades keeps its keys+ Given footage a box it's in clips (`overflow: hidden`), or whose box or opacity changes over its run (a split+ screen: the take rising into the top of the frame while the box holding it shrinks to the seam)+ Then render.json's video entry says what of its box shows (`clip`), the clip each box up its containing blocks+ that clips it leaves, read from the layout, raea's drawing unchanged; one clipped away entirely isn't listed+ And layers.json's clip has its first frame's clip and keys: its box, clip and opacity at its first and last+ frames and at the frames on either side of each change, a straight line between two keys being each frame between+ And whether it's the main footage or a picture in picture is read from what of it shows, not its box+ And each editor's export keys it in its own terms (the XML's keyframes, LA5a; CapCut's, docs/capcut.feature CC2f),+ and says what it can't (CapCut: a cut that changes over the run)++ Scenario: LA4d. Every editor places a picture as raea drew it, from one reading of it+ Given footage of any shape (upright, horizontal, square) in a composition of any size (1080 x 1920, 4K)+ Then where the picture is drawn and what of it is kept is worked out once (raea_app_layers::plan::picture), as+ blitz-paint draws it: sized by its object-fit, placed by its object-position (render.json's `position` when+ it isn't centred, each axis as px plus a share of the free space), cut where its box or a box it's in cuts it+ And only cuts inside the frame are crops: an edge on or past the frame's cuts nothing, the frame cutting it+ anyway, so an editor reframing the clip finds the rest of the picture there, not a crop+ And each editor's export turns that into its own terms (the XML's motion, CapCut's place)+ And footage composed at its own size (a 4K edit of 4K takes) is at 100 in every editor+ And LA3a composites it back as the render on 11-17 at 35 dB and over, in a 1080 x 1920 and a 2160 x 3840+ composition alike (telluride-layers/positioning-test: a horizontal take covering the frame and panned inside+ it, a contained picture in picture sliding, a phone's take in a card cutting its sides, pushed in, and the split+ close): `RAEA_LAYERS_PROJECT=EDIT.tsx RAEA_LAYERS_COMPOSITION=ID cargo test -p raea-app-layers composite -- --ignored`+Scenario: LA4b. The CapCut export reads itThen `raea export capcut` exports the composition in layers into out/capcut/NAME (raea-app-layers) and writeslayers.json as a CapCut draft (apps/capcut from_layers.rs): its tracks bottom first, the footage CapCut's main@@ -156,7 +181,7 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaRule: LA5. Premiere Pro and DaVinci Resolve take the same XMLScenario: LA5a. `raea export xml EDIT.tsx` writes an FCP7 XML project- Then it writes a folder: NAME.xml (xmeml version 5), the layers' movies, the .srt (LA2b) and reference.mp4,+ Then it writes a folder: NAME.premiere.xml and NAME.resolve.xml (xmeml version 5), the layers' movies, the .srt (LA2b) and reference.mp4,which the sequence doesn't useAnd the sequence has the composition's frame rate and size, its video tracks bottom to top under, footage(main, then each picture in picture on a track above), graphics, captions, and its audio tracks below@@ -173,6 +198,33 @@ Feature: A render in layers: captions, graphics, footage and sound apart, for CaAnd each channel of a stereo file is panned to its side by an Audio Pan on its clip (-1 left, 1 right), asResolve and FCP7 write it: without it both editors import the channels centred, and a stereo track plays asmono; Premiere's own track pan (PannerCurrentValue) was tried, and neither editor read it+ And footage with keys (LA4c) is keyframed: Basic Motion's scale and centre, its crop (what object-fit and its+ clip cut) and Opacity, each a value where it holds and a keyframe at each key where it changes, timed in the+ source's frames as FCP7 times a clip's filters; a key a straight line between its neighbours already gives+ (to a tenth of a pixel) is left out, so a steady move is its two ends+ And a clip raea plays at another speed is placed at its own (FCP7's speed isn't written) and said: as many source+ frames as it lasts, its keys timed at that speed+ And the crop is written as each editor writes it, read from an XML each exported of a clip it keyframed (11-17):+ Premiere's as Basic Motion's leftcrop, topcrop, rightcrop and bottomcrop; Resolve's as FCP7's Crop filter. One+ XML can't be both, so the folder holds NAME.premiere.xml and NAME.resolve.xml, the same but for that+ And a file stored turned (a phone's take: its container's display matrix stands it upright; layers.json's+ `rotation`) is cropped as Resolve cuts it: on 11-17 each editor rendered a timeline cropping one picture+ stored at 0, 90, -90 and 180 (top 25, then left 25). Premiere 26.2.2 cut the upright picture's named side at+ each; Resolve 21.2.0 cut it mirrored, top and bottom swapped at 90, left and right at -90, both at 180, so+ Resolve's sides are written swapped to match+ And footage's Scale is as each editor reads it: Premiere's of the media's own pixels, Resolve's of the media+ already fitted to the timeline (its default, "scale entire image to fit": a 4K take on a 1080 timeline is+ Premiere's 50, Resolve's 100), read from the XML Resolve exported on 11-17; the earlier tests' media were the+ timeline's size, where the two agree. Resolve's export says so when footage isn't the timeline's size: with+ another Input Scaling, that footage comes in at another size+ And footage's Center is as each editor reads it: Resolve's in the frame's width and height, Premiere's in the+ media's own pixels, upright and unscaled (read on 11-17 from the Position Premiere gave the Telluride close:+ Center vert -0.120370 at y 497.8 on a 1920-high sequence, 462.2 px up, 0.120370 of 3840); a 2160 x 3840 take+ risen 260 px on a 1080 x 1920 timeline is Resolve's -260 / 1920, Premiere's -260 / 3840+ And a layer's movie has its alpha from its first frame in one sample description (depth 32), even when it opens+ on a full-frame card: VideoToolbox encodes leading opaque frames without alpha and starts a second description+ where the alpha starts, which Premiere 26.2.2 won't import ("the importer reported a generic error") and+ Resolve 21.2.0 shows opaque (the Telluride graphics, 11-17)And a command of an editor's own (`raea export premiere`, `raea export resolve`) is added only where LA5b findsthat editor reading the XML differently: none is, on 11-16diff --git a/engine/page/src/motion/manifest.rs b/engine/page/src/motion/manifest.rsindex a990aed6..8333a453 100644--- a/engine/page/src/motion/manifest.rs+++ b/engine/page/src/motion/manifest.rs@@ -44,6 +44,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});+ // what of the box shows when a box it's in clips it (an `overflow: hidden` parent cropping it):+ // the exports crop the clip to it; one clipped away entirely isn't shown+ if let Some([x0, y0, x1, y1]) = clip(doc, n) {+ let c = [x0.max(b.x), y0.max(b.y), x1.min(b.x + b.width), y1.min(b.y + b.height)];+ if c[2] - c[0] < 0.5 || c[3] - c[1] < 0.5 {+ continue;+ }+ if (c[0] - b.x).abs() > 0.05 || (c[1] - b.y).abs() > 0.05 || (c[2] - b.x - b.width).abs() > 0.05 || (c[3] - b.y - b.height).abs() > 0.05 {+ v["clip"] = json!([r(c[0]), r(c[1]), r(c[2] - c[0]), r(c[3] - c[1])]);+ }+ }// 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;@@ -54,6 +65,21 @@ impl BlitzPage {Fit::None => "none",Fit::ScaleDown => "scale-down",});+ // where the picture sits in what its box leaves free (object-position), when not centred: each+ // axis as px plus a share of the free space ([x px, x share, y px, y share]), keywords and calc()+ // alike, as blitz-paint places it+ use style::values::computed::Length;+ let p = s.clone_object_position();+ let lin = |lp: &style::values::computed::LengthPercentage| {+ let (a, b) = (lp.resolve(Length::new(0.0)).px() as f64, lp.resolve(Length::new(1000.0)).px() as f64);+ (a, (b - a) / 1000.0)+ };+ let ((xp, xs), (yp, ys)) = (lin(&p.horizontal), lin(&p.vertical));+ if xp.abs() > 0.01 || yp.abs() > 0.01 || (xs - 0.5).abs() > 0.001 || (ys - 0.5).abs() > 0.001 {+ // a share to a millionth: of a 4K picture's free space, well under a pixel+ let share = |v: f64| (v * 1e6).round() / 1e6;+ v["position"] = json!([r(xp), share(xs), r(yp), share(ys)]);+ }}stamps(n, &mut v);videos.push(v);@@ -210,6 +236,40 @@ impl BlitzPage {}}+/// The part of the page an element can show in, as the boxes that clip it leave it: the padding boxes, on the axes they+/// clip, of each `overflow` other than visible along its containing blocks (the clips blitz-paint draws it under; the+/// root element's overflow is the viewport's and clips nothing), as [left, top, right, bottom]. None when none clips it.+fn clip(doc: &blitz_dom::BaseDocument, n: blitz_dom::NodeId) -> Option<[f64; 4]> {+ use style::values::computed::Overflow;+ let mut out: Option<[f64; 4]> = None;+ let mut up = doc.get_node(n).and_then(|x| x.containing_block());+ while let Some(id) = up {+ let Some(node) = doc.get_node(id) else { break };+ up = node.containing_block();+ let is_root_element = node.parent.and_then(|p| doc.get_node(p)).is_some_and(|p| p.parent.is_none());+ if !node.is_element() || node.parent.is_none() || is_root_element {+ continue;+ }+ let Some(s) = node.primary_styles() else { continue };+ let (cx, cy) = (!matches!(s.clone_overflow_x(), Overflow::Visible), !matches!(s.clone_overflow_y(), Overflow::Visible));+ if !(cx || cy) {+ continue;+ }+ let Some(b) = doc.get_client_bounding_rect(id) else { continue };+ let bd = node.final_layout().border;+ let o = out.get_or_insert([f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY]);+ if cx {+ o[0] = o[0].max(b.x + bd.left as f64);+ o[2] = o[2].min(b.x + b.width - bd.right as f64);+ }+ if cy {+ o[1] = o[1].max(b.y + bd.top as f64);+ o[3] = o[3].min(b.y + b.height - bd.bottom as f64);+ }+ }+ out+}+/// An element's own opacity times its parents', 0 when it or one of them isn't shown.fn alpha(doc: &blitz_dom::BaseDocument, n: blitz_dom::NodeId) -> f64 {use style::computed_values::visibility::T as Visibility;diff --git a/io/alpha/src/apple.rs b/io/alpha/src/apple.rsindex ba1e74ed..f4709d86 100644--- a/io/alpha/src/apple.rs+++ b/io/alpha/src/apple.rs@@ -88,6 +88,14 @@ impl Writer {row[x * 4..x * 4 + 4].copy_from_slice(&[src[x * 4 + 2], src[x * 4 + 1], src[x * 4], src[x * 4 + 3]]);}}+ // VideoToolbox describes the movie by its first frames: until a frame has alpha it encodes them without+ // (depth 24), then starts a second sample description with alpha (depth 32), which Premiere won't import+ // ("generic error") and Resolve reads as all opaque. So a first frame that's opaque everywhere (a layer that+ // opens on a full-frame card) gets one corner pixel at 254 of 255: the movie has alpha from its first frame+ // and keeps one description (it never goes back to 24 for opaque frames after)+ if self.n == 0 && w > 0 && h > 0 && rgba.as_chunks::<4>().0.iter().all(|p| p[3] == 255) {+ *base.add((h - 1) * bpr + (w - 1) * 4 + 3) = 254;+ }CVPixelBufferUnlockBaseAddress(&pb, CVPixelBufferLockFlags(0));pb.set_attachment(kCVImageBufferAlphaChannelModeKey, kCVImageBufferAlphaChannelMode_StraightAlpha, CVAttachmentMode::ShouldPropagate);let t = CMTime::with_seconds(self.n as f64 / self.fps, 6000);diff --git a/io/alpha/src/tests.rs b/io/alpha/src/tests.rsindex 29fa028e..287634ed 100644--- a/io/alpha/src/tests.rs+++ b/io/alpha/src/tests.rs@@ -142,3 +142,24 @@ fn videotoolbox_writes_both_alpha_codecs() {let _ = std::fs::remove_file(&out);}}++/// A movie that opens on frames opaque everywhere (a full-frame card) and then lets the picture through is still one+/// movie with alpha: one sample description, at depth 32. VideoToolbox left alone describes it by its first frames, at+/// 24 (no alpha), and starts a second description where its alpha starts, which Premiere won't import and Resolve+/// reads as opaque throughout (the Telluride test's graphics, 11-17).+#[cfg(target_vendor = "apple")]+#[test]+fn prores_that_opens_opaque_keeps_its_alpha_in_one_description() {+ let out = tmp("opens-opaque.mov");+ let mut m = Writer::create(&out, Codec::ProRes, 64, 64, 24.0, 0.9).unwrap();+ for k in 0..6 {+ m.push(&if k < 3 { [5u8, 20, 31, 255].repeat(64 * 64) } else { frame(64, 64, k) }).unwrap();+ }+ m.finish().unwrap();+ let d = std::fs::read(&out).unwrap();+ let i = d.windows(4).rposition(|w| w == b"stsd").unwrap();+ assert_eq!(u32::from_be_bytes(d[i + 8..i + 12].try_into().unwrap()), 1, "one sample description");+ let entry = &d[i + 12..];+ assert_eq!(u16::from_be_bytes(entry[82..84].try_into().unwrap()), 32, "depth 32: colour and alpha");+ let _ = std::fs::remove_file(&out);+}diff --git a/io/capcut/src/build.rs b/io/capcut/src/build.rsindex 8af511ad..68e0f210 100644--- a/io/capcut/src/build.rs+++ b/io/capcut/src/build.rs@@ -39,9 +39,36 @@ 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.+/// A picture's centre as CapCut has it: across and up from the canvas's centre, in half-canvas units.+fn offset(p: &Place, w: f64, h: f64) -> [f64; 2] {+ [(p.x - w / 2.0) / (w / 2.0), (h / 2.0 - p.y) / (h / 2.0)]+}++/// A picture's clip: its centre (offset), scale and opacity.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))}})+ let [x, y] = offset(p, w, h);+ 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(x), "y": r6(y)}})+}++/// A picture's keyframes as CapCut keeps them on its segment (common_keyframes): a group a property (its centre across+/// and up, its scale across and up alike, its opacity), each key at its time from the segment's start in microseconds,+/// straight lines between ("Line"), read from published accounts of the draft (capcut-cli's draft schema,+/// pyJianYingDraft). Every property is keyed while any is: CapCut sets the clip's own values aside when there are keys.+fn keyframes_json(keys: &[(i64, Place)], w: f64, h: f64, fps: f64) -> Value {+ const PROPERTIES: [&str; 5] = ["KFTypePositionX", "KFTypePositionY", "KFTypeScaleX", "KFTypeScaleY", "KFTypeAlpha"];+ // a place's values, in PROPERTIES' order+ let values = |p: &Place| {+ let [x, y] = offset(p, w, h);+ [x, y, p.scale, p.scale, p.opacity]+ };+ let group = |(k, kind): (usize, &&str)| {+ let list: Vec<Value> = keys+ .iter()+ .map(|(f, p)| json!({"curveType": "Line", "graphID": "", "id": uid(), "left_control": {"x": 0.0, "y": 0.0}, "right_control": {"x": 0.0, "y": 0.0}, "string_value": "", "time_offset": us(*f, fps), "values": [r6(values(p)[k])]}))+ .collect();+ json!({"id": uid(), "keyframe_list": list, "material_id": "", "property_type": kind})+ };+ Value::Array(PROPERTIES.iter().enumerate().map(group).collect())}pub fn build(tl: &Timeline, markers: &Markers) -> R<Built> {@@ -124,6 +151,9 @@ pub fn build(tl: &Timeline, markers: &Markers) -> R<Built> {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);+ if !c.keys.is_empty() {+ seg["common_keyframes"] = keyframes_json(&c.keys, w, h, fps);+ }} else {mats.entry("audios").or_default().push(json!({"app_id": 0, "category_id": "", "category_name": "local", "check_flag": 1, "copyright_limit_type": "none",diff --git a/io/capcut/src/lib.rs b/io/capcut/src/lib.rsindex 4d72fb8e..1d2017c6 100644--- a/io/capcut/src/lib.rs+++ b/io/capcut/src/lib.rs@@ -74,6 +74,9 @@ pub struct Clip {pub fade_in: f64,pub fade_out: f64,pub place: Place,+ /// a picture that moves, scales or fades: its place at frames from its first (its first frame's first), a+ /// straight line between two; its crop is its first's throughout (CapCut's crop isn't keyed). None when it holds+ pub keys: Vec<(i64, Place)>,}/// Where a picture sits: its centre in canvas pixels from the top left, its scale against the media fitted inside@@ -96,7 +99,7 @@ impl Place {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] } }+ 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] }, keys: Vec::new() }}}diff --git a/io/capcut/src/tests.rs b/io/capcut/src/tests.rsindex ad3a6cef..f69ea37e 100644--- a/io/capcut/src/tests.rs+++ b/io/capcut/src/tests.rs@@ -158,3 +158,29 @@ fn ids_are_uuid_shaped_and_distinct() {assert_eq!(a.iter().collect::<std::collections::HashSet<_>>().len(), 1000);assert!(a.iter().all(|i| i.len() == 36 && i.as_bytes()[14] == b'4'));}++/// CC2f: a picture's keys are its segment's common_keyframes, a group each for its centre across and up, its scale+/// across and up and its opacity, each key at microseconds from the segment's start, straight lines between; a picture+/// without keys has none+#[test]+fn a_keyed_picture_carries_its_keyframes_on_its_segment() {+ let d = tmp("keys");+ let mut tl = timeline(&d);+ let from = Place { x: 840.0, y: 380.0, scale: 0.3333, opacity: 1.0, crop: [0.0, 0.0, 1.0, 1.0] };+ tl.tracks[1].clips[0].keys = vec![(0, from), (15, Place { x: 540.0, y: 960.0, scale: 0.5, opacity: 0.5, ..from })];+ let b = build(&tl, &Markers::default()).unwrap();+ let seg = &b.info["tracks"][1]["segments"][0];+ let groups = seg["common_keyframes"].as_array().unwrap();+ let kinds: Vec<&str> = groups.iter().map(|g| g["property_type"].as_str().unwrap()).collect();+ assert_eq!(kinds, ["KFTypePositionX", "KFTypePositionY", "KFTypeScaleX", "KFTypeScaleY", "KFTypeAlpha"]);+ let at = |g: usize, k: usize| &groups[g]["keyframe_list"][k];+ // 15 frames at 30 fps from the segment's start; the centre from (840, 380), right of and above the canvas's+ // centre, to the canvas's centre+ assert_eq!((at(0, 0)["time_offset"].as_i64(), at(0, 1)["time_offset"].as_i64()), (Some(0), Some(500_000)));+ assert!((at(0, 0)["values"][0].as_f64().unwrap() - 300.0 / 540.0).abs() < 1e-5 && (at(1, 0)["values"][0].as_f64().unwrap() - 580.0 / 960.0).abs() < 1e-5);+ assert_eq!((at(0, 1)["values"][0].as_f64(), at(1, 1)["values"][0].as_f64()), (Some(0.0), Some(0.0)));+ assert_eq!((at(2, 1)["values"][0].as_f64(), at(3, 1)["values"][0].as_f64(), at(4, 1)["values"][0].as_f64()), (Some(0.5), Some(0.5), Some(0.5)));+ assert!(groups.iter().all(|g| g["material_id"] == "" && g["keyframe_list"].as_array().unwrap().iter().all(|k| k["curveType"] == "Line")));+ assert_eq!(b.info["tracks"][0]["segments"][0]["common_keyframes"], serde_json::json!([]));+ let _ = std::fs::remove_dir_all(&d);+}