Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

#172: sequence.settings scales Motion with the frame size and takes timecode, render quality and colour

swillunderscore1f6f7d4c7da8
diff --git a/Cargo.lock b/Cargo.lock
index 900806b98..513d6b9c1 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1843,6 +1843,7 @@ dependencies = [
name = "filmcraft-edit"
version = "0.4.0"
dependencies = [
+ "filmcraft-geom",
"filmcraft-media",
"filmcraft-project",
"filmcraft-time",
diff --git a/crates/edit/Cargo.toml b/crates/edit/Cargo.toml
index fcecc05a3..bcf354768 100644
--- a/crates/edit/Cargo.toml
+++ b/crates/edit/Cargo.toml
@@ -16,5 +16,6 @@ thiserror = { workspace = true }
[dev-dependencies]
proptest = { workspace = true }
+filmcraft-geom = { workspace = true }
filmcraft-media = { workspace = true }
serde_json = { workspace = true }
diff --git a/crates/edit/src/frame_size.rs b/crates/edit/src/frame_size.rs
new file mode 100644
index 000000000..607cfe40d
--- /dev/null
+++ b/crates/edit/src/frame_size.rs
@@ -0,0 +1,212 @@
+//! Sequence Settings ▸ "Scale motion effects proportionally when changing frame size".
+//!
+//! Motion's Position is in sequence pixels and its Scale is relative to the source, so a new frame
+//! size leaves every clip where it was in pixels: smaller and off-centre in a larger frame, cropped
+//! in a smaller one. With the option on, the whole picture scales instead, by one factor about the
+//! frame centre. On an aspect change (16:9 → 9:16) that factor is the one that fits the old frame
+//! inside the new one (`min(W1/W0, H1/H0)`), so nothing is cropped and the old composition sits
+//! centred, letterboxed or pillarboxed, rather than filling the new frame.
+
+use filmcraft_project::{ParamValue, Sequence, TrackKind};
+
+/// Motion Scale's upper bound (the parameter's range, in %).
+const MAX_SCALE: f64 = 10_000.0;
+
+/// The uniform factor `k` and the old and new frame centres for `from` → `to`, or `None` for an
+/// empty frame on either side.
+fn fit(from: (u32, u32), to: (u32, u32)) -> Option<(f64, (f64, f64), (f64, f64))> {
+ if from.0 == 0 || from.1 == 0 || to.0 == 0 || to.1 == 0 {
+ return None;
+ }
+ let (w0, h0, w1, h1) = (f64::from(from.0), f64::from(from.1), f64::from(to.0), f64::from(to.1));
+ let k = (w1 / w0).min(h1 / h0);
+ (k.is_finite() && k > 0.0).then_some((k, (w0 / 2.0, h0 / 2.0), (w1 / 2.0, h1 / 2.0)))
+}
+
+/// Rescale the Motion of every video clip in `seq` for a frame-size change from `from` to `to`:
+/// static values and every keyframe. Returns how many clips were rescaled (0 when the size does not
+/// change).
+///
+/// - Position maps through `p' = c1 + k·(p − c0)`. An automatic (NaN) position stays automatic: it
+/// follows the frame centre on its own.
+/// - Scale and Scale Width are multiplied by `k`, up to the parameter's 10 000 %. A clip with Scale to
+/// Frame Size keeps its Scale, because the renderer refits it to the new frame anyway.
+/// - Anchor Point (source pixels) and Rotation do not depend on the frame size and stay as they are.
+/// - Only the intrinsic Motion effect changes, as the option's name says: the points of standard
+/// effects (a Mirror centre, the Transform effect's Position) keep their pixel values.
+pub fn scale_motion(seq: &mut Sequence, from: (u32, u32), to: (u32, u32)) -> usize {
+ if from == to {
+ return 0;
+ }
+ let Some((k, c0, c1)) = fit(from, to) else { return 0 };
+ let mut n = 0;
+ for track in seq.all_tracks_mut().filter(|t| t.kind == TrackKind::Video) {
+ for item in &mut track.items {
+ let refits = item.scale_to_frame;
+ let Some(motion) = item.effect_mut("motion") else { continue };
+ if let Some(p) = motion.param_mut("position") {
+ p.map_values(|v| match v {
+ ParamValue::Vec2(mut v) => {
+ v.x = c1.0 + k * (v.x - c0.0);
+ v.y = c1.1 + k * (v.y - c0.1);
+ ParamValue::Vec2(v)
+ }
+ other => other,
+ });
+ }
+ if !refits {
+ for id in ["scale", "scale_width"] {
+ if let Some(p) = motion.param_mut(id) {
+ p.map_values(|v| match v {
+ ParamValue::Float(s) => ParamValue::Float((s * k).clamp(0.0, MAX_SCALE)),
+ other => other,
+ });
+ }
+ }
+ }
+ n += 1;
+ }
+ }
+ n
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use filmcraft_project::{ClipId, ItemId, Keyframe, Label, Project, SequenceSettings, TrackItem, find_effect};
+ use filmcraft_time::Tick;
+
+ fn seq_with(items: Vec<TrackItem>) -> Sequence {
+ let mut p = Project::new("t");
+ let s = p.new_sequence("s", SequenceSettings::default(), 2, 1, None);
+ let mut seq = p.sequence(s).unwrap().clone();
+ seq.video_tracks[0].items = items;
+ seq
+ }
+
+ fn clip(id: u64, pos: (f64, f64), scale: f64) -> TrackItem {
+ let mut motion = find_effect("motion").unwrap().instance();
+ motion.param_mut("position").unwrap().value = ParamValue::Vec2(filmcraft_geom::Vec2::new(pos.0, pos.1));
+ motion.param_mut("scale").unwrap().value = ParamValue::Float(scale);
+ TrackItem {
+ id: ClipId(id),
+ item: ItemId(1),
+ name: format!("c{id}"),
+ label: Label::Iris,
+ start: Tick(id as i64 * 1_000_000_000_000),
+ duration: Tick(1_000_000_000_000),
+ source_in: Tick::ZERO,
+ speed: 1.0,
+ reverse: false,
+ enabled: true,
+ link: None,
+ group: None,
+ effects: vec![motion],
+ markers: vec![],
+ gain_db: 0.0,
+ frame_hold: None,
+ scale_to_frame: false,
+ essential: None,
+ multicam: None,
+ time_interpolation: Default::default(),
+ hold_filters: false,
+ field_options: None,
+ source_channels: Vec::new(),
+ graphic: None,
+ }
+ }
+
+ fn pos(seq: &Sequence, i: usize) -> (f64, f64) {
+ match seq.video_tracks[0].items[i].effect("motion").unwrap().param("position").unwrap().value {
+ ParamValue::Vec2(v) => (v.x, v.y),
+ _ => panic!("position is a point"),
+ }
+ }
+
+ fn scale(seq: &Sequence, i: usize) -> f64 {
+ match seq.video_tracks[0].items[i].effect("motion").unwrap().param("scale").unwrap().value {
+ ParamValue::Float(s) => s,
+ _ => panic!("scale is a number"),
+ }
+ }
+
+ fn close(a: (f64, f64), b: (f64, f64)) -> bool {
+ (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9
+ }
+
+ #[test]
+ fn same_aspect_scales_position_and_scale_together() {
+ let mut seq = seq_with(vec![clip(1, (960.0, 540.0), 100.0), clip(2, (300.0, 90.0), 50.0)]);
+ assert_eq!(scale_motion(&mut seq, (1920, 1080), (1280, 720)), 2);
+ assert!(close(pos(&seq, 0), (640.0, 360.0)), "{:?}", pos(&seq, 0));
+ assert!(close(pos(&seq, 1), (200.0, 60.0)), "{:?}", pos(&seq, 1));
+ assert!((scale(&seq, 0) - 100.0 * 2.0 / 3.0).abs() < 1e-9);
+ assert!((scale(&seq, 1) - 50.0 * 2.0 / 3.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn aspect_change_fits_the_old_frame_inside_the_new_one() {
+ // 1920x1080 -> 1080x1920: k = min(1080/1920, 1920/1080) = 0.5625, centred
+ let mut seq = seq_with(vec![clip(1, (960.0, 540.0), 100.0), clip(2, (0.0, 0.0), 100.0)]);
+ scale_motion(&mut seq, (1920, 1080), (1080, 1920));
+ assert!(close(pos(&seq, 0), (540.0, 960.0)), "{:?}", pos(&seq, 0));
+ // the old top-left corner lands on the new frame's left edge, letterboxed vertically
+ assert!(close(pos(&seq, 1), (0.0, 960.0 - 0.5625 * 540.0)), "{:?}", pos(&seq, 1));
+ assert!((scale(&seq, 0) - 56.25).abs() < 1e-9);
+ }
+
+ #[test]
+ fn keyframes_scale_too() {
+ let mut c = clip(1, (960.0, 540.0), 100.0);
+ let m = c.effect_mut("motion").unwrap();
+ m.param_mut("position").unwrap().keyframes = vec![
+ Keyframe::new(Tick::ZERO, ParamValue::Vec2(filmcraft_geom::Vec2::new(0.0, 0.0))),
+ Keyframe::new(Tick(10), ParamValue::Vec2(filmcraft_geom::Vec2::new(1920.0, 1080.0))),
+ ];
+ m.param_mut("scale").unwrap().keyframes = vec![Keyframe::new(Tick::ZERO, ParamValue::Float(100.0)), Keyframe::new(Tick(10), ParamValue::Float(200.0))];
+ let mut seq = seq_with(vec![c]);
+ scale_motion(&mut seq, (1920, 1080), (3840, 2160));
+ let m = seq.video_tracks[0].items[0].effect("motion").unwrap();
+ let kp: Vec<_> = m.param("position").unwrap().keyframes.iter().map(|k| k.value.clone()).collect();
+ assert_eq!(kp, vec![ParamValue::Vec2(filmcraft_geom::Vec2::new(0.0, 0.0)), ParamValue::Vec2(filmcraft_geom::Vec2::new(3840.0, 2160.0))]);
+ let ks: Vec<_> = m.param("scale").unwrap().keyframes.iter().map(|k| k.value.clone()).collect();
+ assert_eq!(ks, vec![ParamValue::Float(200.0), ParamValue::Float(400.0)]);
+ }
+
+ #[test]
+ fn automatic_position_stays_automatic() {
+ let mut seq = seq_with(vec![clip(1, (f64::NAN, f64::NAN), 100.0)]);
+ scale_motion(&mut seq, (1920, 1080), (1280, 720));
+ let (x, y) = pos(&seq, 0);
+ assert!(x.is_nan() && y.is_nan());
+ assert!((scale(&seq, 0) - 100.0 * 2.0 / 3.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn scale_to_frame_clips_keep_their_scale_but_move() {
+ let mut c = clip(1, (480.0, 270.0), 100.0);
+ c.scale_to_frame = true;
+ let mut seq = seq_with(vec![c]);
+ scale_motion(&mut seq, (1920, 1080), (3840, 2160));
+ assert!(close(pos(&seq, 0), (960.0, 540.0)), "{:?}", pos(&seq, 0));
+ assert_eq!(scale(&seq, 0), 100.0);
+ }
+
+ #[test]
+ fn scale_is_capped_at_the_parameter_range() {
+ let mut seq = seq_with(vec![clip(1, (1.0, 1.0), 5000.0)]);
+ scale_motion(&mut seq, (2, 2), (8, 8));
+ assert_eq!(scale(&seq, 0), MAX_SCALE);
+ }
+
+ #[test]
+ fn same_size_or_empty_frame_changes_nothing() {
+ let mut seq = seq_with(vec![clip(1, (100.0, 100.0), 100.0)]);
+ let before = seq.clone();
+ assert_eq!(scale_motion(&mut seq, (1920, 1080), (1920, 1080)), 0);
+ assert_eq!(scale_motion(&mut seq, (0, 1080), (1280, 720)), 0);
+ assert_eq!(scale_motion(&mut seq, (1920, 1080), (1280, 0)), 0);
+ // Debug, not ==: the automatic anchor is NaN, which never equals itself
+ assert_eq!(format!("{:?}", seq.video_tracks[0].items[0].effects), format!("{:?}", before.video_tracks[0].items[0].effects));
+ }
+}
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs
index 67937f854..ed66f951a 100644
--- a/crates/edit/src/lib.rs
+++ b/crates/edit/src/lib.rs
@@ -18,6 +18,7 @@
#![cfg_attr(not(test), deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable))]
pub mod captions;
+pub mod frame_size;
pub mod multicam;
pub mod through;
pub mod transcript;
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index acdccda75..cd4b25cfe 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -1513,41 +1513,70 @@ fn build() -> Vec<CommandSpec> {
"Sequence Settings…",
["Sequence"],
None,
- r#"{"width":u32?,"height":u32?,"fps":f64?,"name":str?,"sampleRate":u32?,"mix":"Stereo|Mono|5.1|Adaptive"?}"#,
+ r#"{"width":u32?,"height":u32?,"fps":f64?,"name":str?,"sampleRate":u32?,"mix":"Stereo|Mono|5.1|Adaptive"?,"dropFrame":bool?,"maxRenderQuality":bool?,"workingSpace":"rec709"|"rec2100-pq"|"rec2100-hlg"?,"wideGamut":bool?,"autoToneMap":bool?,"scaleMotion":bool=false}"#,
has_seq,
|s, p| {
+ const CMD: &str = "sequence.settings";
let id = s.state.active_sequence.ok_or(EngineError::NoSequence)?;
- let fps = fps_p(p, "sequence.settings")?;
+ let fps = fps_p(p, CMD)?;
let mix = match str_p(p, "mix") {
- Some(m) => Some(
- crate::mixer::channels_from(m).ok_or_else(|| bad("sequence.settings", format!("unknown mix `{m}` (Stereo, Mono, 5.1, Adaptive)")))?,
- ),
+ Some(m) => Some(crate::mixer::channels_from(m).ok_or_else(|| bad(CMD, format!("unknown mix `{m}` (Stereo, Mono, 5.1, Adaptive)")))?),
+ None => None,
+ };
+ let working = match str_p(p, "workingSpace") {
+ Some(w) => Some(filmcraft_color::WorkingSpace::parse(w).ok_or_else(|| bad(CMD, format!("unknown working space `{w}`")))?),
None => None,
};
+ let drop_frame = bool_p(p, "dropFrame");
+ let rate = fps.or_else(|| s.active_sequence().map(|q| q.settings.frame_rate)).unwrap_or(FrameRate::FPS_23_976);
+ if drop_frame == Some(true) && !rate.supports_drop_frame() {
+ return Err(bad(CMD, format!("drop-frame timecode needs a 29.97, 59.94 or 119.88 fps timebase, not {rate}")));
+ }
+ let scale_motion = bool_p(p, "scaleMotion").unwrap_or(false);
let p = p.clone();
- s.edit("Sequence Settings", |pr, _| {
+ let scaled = s.edit("Sequence Settings", |pr, _| {
if let Some(n) = str_p(&p, "name") {
pr.item_mut(id).ok_or(EngineError::NoSequence)?.name = n.to_string();
}
let q = pr.sequence_mut(id).ok_or(EngineError::NoSequence)?;
- if let Some(w) = checked_u32_p(&p, "width", "sequence.settings")? {
+ let old_size = (q.settings.width, q.settings.height);
+ if let Some(w) = checked_u32_p(&p, "width", CMD)? {
q.settings.width = w;
}
- if let Some(h) = checked_u32_p(&p, "height", "sequence.settings")? {
+ if let Some(h) = checked_u32_p(&p, "height", CMD)? {
q.settings.height = h;
}
if let Some(f) = fps {
q.settings.frame_rate = f;
}
- if let Some(sr) = checked_u32_p(&p, "sampleRate", "sequence.settings")? {
+ if let Some(sr) = checked_u32_p(&p, "sampleRate", CMD)? {
q.settings.sample_rate = sr;
}
if let Some(m) = mix {
q.settings.audio_master = m;
}
- q.settings.validate().map_err(|e| bad("sequence.settings", e))
+ if let Some(df) = drop_frame {
+ q.settings.drop_frame = df;
+ }
+ if let Some(v) = bool_p(&p, "maxRenderQuality") {
+ q.settings.max_render_quality = v;
+ }
+ let c = &mut q.settings.color;
+ if let Some(w) = working {
+ c.working = w;
+ }
+ if let Some(v) = bool_p(&p, "wideGamut") {
+ c.wide_gamut = v;
+ }
+ if let Some(v) = bool_p(&p, "autoToneMap") {
+ c.auto_tone_map = v;
+ }
+ q.settings.working_space = q.settings.color.working.label().into();
+ q.settings.validate().map_err(|e| bad(CMD, e))?;
+ let new_size = (q.settings.width, q.settings.height);
+ Ok(if scale_motion { edit::frame_size::scale_motion(q, old_size, new_size) } else { 0 })
})?;
- Ok(Value::Null)
+ Ok(json!({"scaledClips": scaled}))
}
),
cmd!("sequence.renderEffectsInToOut", "Render Effects In to Out", ["Sequence"], Some("Enter"), r#"{"wait":bool=false}"#, has_seq, |s, p| {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 4193afe93..1a9d17d69 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -144,6 +144,73 @@ fn sequence_parameters_are_bounded_and_failed_changes_are_atomic() {
assert_eq!(s.active_sequence().unwrap().settings.height, 8192, "a 16384x8192 panorama is accepted");
}
+/// The first video clip's Motion Position and Scale (static values).
+fn first_motion(s: &Session) -> (u64, (f64, f64), f64) {
+ let q = s.active_sequence().unwrap();
+ let it = q.video_tracks.iter().flat_map(|t| &t.items).find(|i| i.effect("motion").is_some()).unwrap();
+ let m = it.effect("motion").unwrap();
+ let p = match m.param("position").unwrap().value {
+ filmcraft_project::ParamValue::Vec2(v) => (v.x, v.y),
+ _ => panic!("position is a point"),
+ };
+ let sc = match m.param("scale").unwrap().value {
+ filmcraft_project::ParamValue::Float(v) => v,
+ _ => panic!("scale is a number"),
+ };
+ (it.id.0, p, sc)
+}
+
+#[test]
+fn sequence_settings_scales_motion_with_the_frame_size_in_one_undo_step() {
+ let mut s = demo();
+ let before = (*s.project).clone();
+ let (id, p0, s0) = first_motion(&s);
+ assert_eq!((s.active_sequence().unwrap().settings.width, s.active_sequence().unwrap().settings.height), (1920, 1080));
+ let r = s.execute("sequence.settings", json!({"width":1280,"height":720,"scaleMotion":true})).unwrap();
+ assert!(r["scaledClips"].as_u64().unwrap() >= 1, "{r}");
+ let (id1, p1, s1) = first_motion(&s);
+ assert_eq!(id1, id);
+ assert!((p1.0 - p0.0 * 2.0 / 3.0).abs() < 1e-9 && (p1.1 - p0.1 * 2.0 / 3.0).abs() < 1e-9, "{p0:?} -> {p1:?}");
+ assert!((s1 - s0 * 2.0 / 3.0).abs() < 1e-9, "{s0} -> {s1}");
+ let after = (*s.project).clone();
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, before, "size and Motion come back in one undo step");
+ s.execute("edit.redo", json!({})).unwrap();
+ assert_eq!(*s.project, after);
+ // without the option the frame size changes alone (the command's default, as before)
+ let r = s.execute("sequence.settings", json!({"width":3840,"height":2160})).unwrap();
+ assert_eq!(r["scaledClips"], json!(0));
+ assert_eq!(first_motion(&s), (id, p1, s1));
+ assert_eq!(s.active_sequence().unwrap().settings.width, 3840);
+}
+
+#[test]
+fn sequence_settings_timecode_render_quality_and_colour() {
+ let mut s = demo();
+ s.execute("sequence.settings", json!({"fps":29.97,"dropFrame":true,"maxRenderQuality":true})).unwrap();
+ let st = s.active_sequence().unwrap().settings.clone();
+ assert_eq!(st.frame_rate, FrameRate::FPS_29_97);
+ assert!(st.drop_frame && st.max_render_quality);
+ s.execute("sequence.settings", json!({"dropFrame":false})).unwrap();
+ assert!(!s.active_sequence().unwrap().settings.drop_frame);
+ // drop-frame only exists for the NTSC rates; a refused change leaves everything as it was
+ let before = (*s.project).clone();
+ let history = s.history.undo.len();
+ for params in [json!({"fps":25,"dropFrame":true}), json!({"workingSpace":"rec2020-log"}), json!({"fps":25,"dropFrame":true,"width":1280})] {
+ assert!(s.execute("sequence.settings", params.clone()).is_err(), "{params}");
+ assert_eq!(*s.project, before, "{params}");
+ assert_eq!(s.history.undo.len(), history);
+ }
+ s.execute("sequence.settings", json!({"workingSpace":"rec2100-pq","wideGamut":true,"autoToneMap":true})).unwrap();
+ let st = s.active_sequence().unwrap().settings.clone();
+ assert_eq!(st.color.working, filmcraft_color::WorkingSpace::Rec2100Pq);
+ assert!(st.color.wide_gamut && st.color.auto_tone_map);
+ assert_eq!(st.working_space, "Rec. 2100 PQ");
+ // disabled without a sequence
+ let mut empty = Session::default();
+ assert!(empty.execute("sequence.settings", json!({"width":1280})).is_err());
+}
+
#[test]
fn zero_fps_is_refused() {
let mut s = demo();