diff --git a/apps/capcut/src/from_layers.rs b/apps/capcut/src/from_layers.rs index 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) { + let mut notes = Vec::new(); let media: Vec = 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 there let own = c.link.as_deref().and_then(|id| all().find(|a| a.id == id)); - Clip { volume: own.map_or(0.0, |a| 10f64.powf(a.gain_db / 20.0)), place, ..base } + 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.rs index 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 { 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 { 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.rs index 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) { - 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.rs index 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 after assert_eq!(tl.tracks.iter().map(|t| t.name.as_str()).collect::>(), ["", "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.rs index 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 { 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 = 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.rs index 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 = Result; 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> { @@ -50,7 +51,7 @@ pub fn cli(args: &[String]) -> Option> { fn export_xml(args: &[String]) -> R { 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 { } 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 = 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> { - 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> { - // 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> { + // 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 it let covered: Vec = 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 = 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 time if 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 { 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 { pub fn sound(path: &Path) -> R { 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 { + 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::().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.rs index 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, + /// 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 frame pub 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, /// 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, } +/// 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 { + 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.rs index 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, 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, +} + +/// 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) -> Vec { + 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 { 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 { 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 { done.append(&mut open); // the rate over the whole run (source times are whole milliseconds, so one step's can be 1% off), to hundredths for r in &mut done { + 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 { .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 +///