Skip to content

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

#430: transitions can be selected, removed, resized and moved (engine)

swillunderscored4d1830d994b
diff --git a/crates/edit/src/lib.rs b/crates/edit/src/lib.rs
index ed66f951a..7cfb7006b 100644
--- a/crates/edit/src/lib.rs
+++ b/crates/edit/src/lib.rs
@@ -22,6 +22,7 @@ pub mod frame_size;
pub mod multicam;
pub mod through;
pub mod transcript;
+pub mod transitions;
use std::collections::HashMap;
diff --git a/crates/edit/src/transitions.rs b/crates/edit/src/transitions.rs
new file mode 100644
index 000000000..d28c7f7f9
--- /dev/null
+++ b/crates/edit/src/transitions.rs
@@ -0,0 +1,406 @@
+//! Applied transitions: where one may sit over its cut, its alignment, and moving / resizing /
+//! removing one (Effect Controls' Duration and Alignment, dragging its edges or its middle in the
+//! Timeline, Delete).
+//!
+//! Premiere (Align transitions; Change transition duration): a transition between two clips stays
+//! over their cut, "Center at Cut", "Start at Cut", "End at Cut" or, once dragged off-centre,
+//! "Custom Start". Changing its duration moves both ends equally for Center at Cut / Custom Start,
+//! only the end for Start at Cut and only the beginning for End at Cut. A one-sided transition (a
+//! fade from or to nothing) starts or ends at its clip's edge.
+//!
+//! Premiere limits a transition by the media its clips have beyond the cut (handles). FilmCraft
+//! does not check handles when applying one, so here a transition may cover at most the clips it
+//! joins: from the outgoing clip's start to the incoming clip's end.
+
+use filmcraft_project::{Sequence, Track, Transition, TransitionAlign, TransitionId};
+use filmcraft_time::Tick;
+
+use crate::{Edge, EditError, Result};
+
+/// How a transition sits on its cut, as Effect Controls' Alignment menu shows it.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Alignment {
+ Center,
+ Start,
+ End,
+ /// Premiere's "Custom Start": dragged to a place over the cut that is none of the others.
+ Custom,
+}
+
+impl Alignment {
+ pub const MENU: [Alignment; 3] = [Alignment::Center, Alignment::Start, Alignment::End];
+
+ pub fn id(self) -> &'static str {
+ match self {
+ Alignment::Center => "center",
+ Alignment::Start => "start",
+ Alignment::End => "end",
+ Alignment::Custom => "custom",
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Alignment::Center => "Center at Cut",
+ Alignment::Start => "Start at Cut",
+ Alignment::End => "End at Cut",
+ Alignment::Custom => "Custom Start",
+ }
+ }
+
+ /// `center`, `start` or `end` (Custom Start is reached by moving a transition, not chosen).
+ pub fn parse(s: &str) -> Option<Alignment> {
+ Alignment::MENU.into_iter().find(|a| a.id().eq_ignore_ascii_case(s) || a.label().eq_ignore_ascii_case(s))
+ }
+}
+
+/// Where a transition may be: `(earliest start, cut, latest end)`. Between two clips that is the
+/// outgoing clip's start, the cut and the incoming clip's end; for a fade to or from nothing the cut
+/// is its clip's edge. `None` when its clips are gone.
+pub fn bounds(track: &Track, tr: &Transition) -> Option<(Tick, Tick, Tick)> {
+ let from = tr.from.and_then(|c| track.item(c));
+ let to = tr.to.and_then(|c| track.item(c));
+ match (from, to) {
+ (Some(f), Some(t)) => Some((f.start, t.start, t.end())),
+ (None, Some(t)) => Some((t.start, t.start, t.end())),
+ (Some(f), None) => Some((f.start, f.end(), f.end())),
+ (None, None) => None,
+ }
+}
+
+/// A transition's alignment on `cut`. Centred means within half a `frame` of the cut, as
+/// centring an odd number of frames lands on a frame boundary.
+pub fn alignment(tr: &Transition, cut: Tick, frame: Tick) -> Alignment {
+ match (tr.from, tr.to) {
+ (None, Some(_)) => return Alignment::Start,
+ (Some(_), None) => return Alignment::End,
+ _ => {}
+ }
+ if tr.start == cut {
+ Alignment::Start
+ } else if tr.end() == cut {
+ Alignment::End
+ } else if (tr.start.0.saturating_mul(2).saturating_add(tr.duration.0) - cut.0.saturating_mul(2)).abs() <= frame.0.max(0) {
+ Alignment::Center
+ } else {
+ Alignment::Custom
+ }
+}
+
+fn find(seq: &Sequence, id: TransitionId) -> Option<(&Track, &Transition)> {
+ seq.all_tracks().find_map(|t| t.transitions.iter().find(|x| x.id == id).map(|x| (t, x)))
+}
+
+/// Where a transition would start for `duration` and `align`, keeping its cut (and, for Center
+/// at Cut / Custom Start, its centre; `snap` puts a centred start on a frame).
+pub fn start_for(seq: &Sequence, id: TransitionId, duration: Tick, align: Alignment, frame: Tick, snap: impl Fn(Tick) -> Tick) -> Option<Tick> {
+ let (track, tr) = find(seq, id)?;
+ let (_, cut, _) = bounds(track, tr)?;
+ let one_sided = alignment(tr, cut, frame);
+ let align = match one_sided {
+ Alignment::Start | Alignment::End if tr.from.is_none() || tr.to.is_none() => one_sided,
+ _ => align,
+ };
+ Some(match align {
+ Alignment::Start => cut,
+ Alignment::End => cut - duration,
+ Alignment::Center => snap(cut - duration.mul_ratio(1, 2)),
+ // Custom Start: the ends move equally, around where it is now
+ Alignment::Custom => snap(tr.start + tr.duration.mul_ratio(1, 2) - duration.mul_ratio(1, 2)),
+ })
+}
+
+/// Move / resize a transition to cover `start .. start + duration`. Refused (leaving the sequence
+/// as it was) when its track is locked, it would be shorter than `min`, it would leave its clips,
+/// or it would no longer touch its cut (a one-sided one must keep its edge).
+pub fn set_span(seq: &mut Sequence, id: TransitionId, start: Tick, duration: Tick, min: Tick, frame: Tick) -> Result<()> {
+ let (track, tr) = find(seq, id).ok_or_else(|| EditError::Other(format!("no transition {}", id.0)))?;
+ if track.locked {
+ return Err(EditError::Locked);
+ }
+ let (lo, cut, hi) = bounds(track, tr).ok_or_else(|| EditError::Other("the transition's clips are gone".into()))?;
+ if duration < min.max(Tick(1)) {
+ return Err(EditError::Other("a transition lasts at least one frame".into()));
+ }
+ let end = start.0.checked_add(duration.0).map(Tick).ok_or_else(|| EditError::Other("transition out of range".into()))?;
+ if start < lo || end > hi {
+ return Err(EditError::Other("a transition can't extend past the clips it joins".into()));
+ }
+ let on_cut = match (tr.from, tr.to) {
+ (None, Some(_)) => start == cut,
+ (Some(_), None) => end == cut,
+ _ => start <= cut && cut <= end,
+ };
+ if !on_cut {
+ return Err(EditError::Other(if tr.from.is_some() && tr.to.is_some() {
+ "a transition between two clips must stay over their cut".into()
+ } else {
+ "a one-sided transition stays on its clip's edge".into()
+ }));
+ }
+ let tid = track.id;
+ let Some(x) = seq.track_mut(tid).and_then(|t| t.transitions.iter_mut().find(|x| x.id == id)) else {
+ return Err(EditError::Other(format!("no transition {}", id.0)));
+ };
+ x.start = start;
+ x.duration = duration;
+ // the stored alignment (interchange): Custom Start has no variant, its span says it all
+ x.align = match alignment(x, cut, frame) {
+ Alignment::Start => TransitionAlign::StartAtCut,
+ Alignment::End => TransitionAlign::EndAtCut,
+ Alignment::Center | Alignment::Custom => TransitionAlign::CenterAtCut,
+ };
+ Ok(())
+}
+
+/// Where dragging a transition by `delta` in the Timeline puts it, as `(start, duration)`. Its
+/// middle (`edge` None) slides it over the cut. An end changes its duration: a Center at Cut
+/// transition grows or shrinks on both sides and stays centred on the cut (its alignment says how
+/// it changes length), any other keeps its other end where it is. A fade to or from nothing keeps
+/// its clip-edge end, and does not slide. Always clamped to where it may be ([`bounds`], over the
+/// cut, at least one `frame`); `snap` puts a centred start on a frame. `None` when its clips are gone.
+pub fn drag_span(track: &Track, tr: &Transition, edge: Option<Edge>, delta: Tick, frame: Tick, snap: impl Fn(Tick) -> Tick) -> Option<(Tick, Tick)> {
+ let (lo, cut, hi) = bounds(track, tr)?;
+ let frame = frame.max(Tick(1));
+ let (s0, e0, d0) = (tr.start, tr.end(), tr.duration);
+ let one_sided = tr.from.is_none() || tr.to.is_none();
+ let unchanged = Some((s0, d0));
+ match edge {
+ None if one_sided => unchanged,
+ None => {
+ let (min_s, max_s) = (lo.max(cut - d0), (hi - d0).min(cut));
+ if min_s > max_s { unchanged } else { Some(((s0 + delta).clamp(min_s, max_s), d0)) }
+ }
+ Some(e) if !one_sided && alignment(tr, cut, frame) == Alignment::Center => {
+ // dragging an end by n frames moves both ends by n: the duration changes by 2n
+ let grow = if e == Edge::In { Tick(0) - delta } else { delta };
+ let max_d = Tick((cut - lo).min(hi - cut).0.saturating_mul(2));
+ let d = Tick(d0.0.saturating_add(grow.0.saturating_mul(2))).clamp(frame, max_d.max(frame));
+ Some((snap(cut - d.mul_ratio(1, 2)), d))
+ }
+ Some(Edge::In) if tr.from.is_none() => unchanged,
+ Some(Edge::In) => {
+ let max_s = cut.min(e0 - frame).max(lo);
+ let st = (s0 + delta).clamp(lo, max_s);
+ Some((st, e0 - st))
+ }
+ Some(Edge::Out) if tr.to.is_none() => unchanged,
+ Some(Edge::Out) => {
+ let min_e = cut.max(s0 + frame).min(hi);
+ let en = (e0 + delta).clamp(min_e, hi);
+ Some((s0, en - s0))
+ }
+ }
+}
+
+/// Remove transitions (on unlocked tracks). Returns how many went.
+pub fn remove(seq: &mut Sequence, ids: &[TransitionId]) -> Result<usize> {
+ if seq.all_tracks().any(|t| t.locked && t.transitions.iter().any(|x| ids.contains(&x.id))) {
+ return Err(EditError::Locked);
+ }
+ let mut n = 0;
+ for t in seq.all_tracks_mut() {
+ let before = t.transitions.len();
+ t.transitions.retain(|x| !ids.contains(&x.id));
+ n += before - t.transitions.len();
+ }
+ if n == 0 { Err(EditError::Nothing) } else { Ok(n) }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use filmcraft_project::{ClipId, ItemId, Label, Project, SequenceSettings, TrackItem, find_effect};
+ use filmcraft_time::FrameRate;
+
+ const R: FrameRate = FrameRate::FPS_24;
+
+ fn f(n: i64) -> Tick {
+ R.tick_of(n)
+ }
+
+ fn clip(id: u64, start: i64, dur: i64) -> TrackItem {
+ TrackItem {
+ id: ClipId(id),
+ item: ItemId(1),
+ name: format!("c{id}"),
+ label: Label::Iris,
+ start: f(start),
+ duration: f(dur),
+ source_in: Tick::ZERO,
+ speed: 1.0,
+ reverse: false,
+ enabled: true,
+ link: None,
+ group: None,
+ effects: vec![],
+ 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(),
+ audio_stream: 0,
+ graphic: None,
+ }
+ }
+
+ fn transition(id: u64, start: i64, dur: i64, from: Option<u64>, to: Option<u64>) -> Transition {
+ // any effect: these tests are about where the transition sits
+ let effect = find_effect("opacity").unwrap().instance();
+ Transition {
+ id: TransitionId(id),
+ effect,
+ start: f(start),
+ duration: f(dur),
+ from: from.map(ClipId),
+ to: to.map(ClipId),
+ align: TransitionAlign::CenterAtCut,
+ reverse: false,
+ }
+ }
+
+ /// V1: c1 0..48, c2 48..96, c3 96..144; a centred 24-frame transition on 48 (id 1), a fade in
+ /// at 0 (id 2) and a fade out at 144 (id 3).
+ fn seq() -> Sequence {
+ let mut p = Project::new("t");
+ let s = p.new_sequence("s", SequenceSettings { frame_rate: R, ..Default::default() }, 1, 0, None);
+ let mut q = p.sequence(s).unwrap().clone();
+ let t = &mut q.video_tracks[0];
+ t.items = vec![clip(1, 0, 48), clip(2, 48, 48), clip(3, 96, 48)];
+ t.transitions = vec![transition(1, 36, 24, Some(1), Some(2)), transition(2, 0, 12, None, Some(1)), transition(3, 132, 12, Some(3), None)];
+ q
+ }
+
+ fn span(q: &Sequence, id: u64) -> (Tick, Tick) {
+ let x = q.video_tracks[0].transitions.iter().find(|x| x.id.0 == id).unwrap();
+ (x.start, x.duration)
+ }
+
+ fn align(q: &Sequence, id: u64) -> Alignment {
+ let (t, x) = find(q, TransitionId(id)).unwrap();
+ let (_, cut, _) = bounds(t, x).unwrap();
+ alignment(x, cut, f(1))
+ }
+
+ #[test]
+ fn alignment_reads_the_span() {
+ let mut q = seq();
+ assert_eq!((align(&q, 1), align(&q, 2), align(&q, 3)), (Alignment::Center, Alignment::Start, Alignment::End));
+ set_span(&mut q, TransitionId(1), f(48), f(24), f(1), f(1)).unwrap();
+ assert_eq!(align(&q, 1), Alignment::Start);
+ set_span(&mut q, TransitionId(1), f(24), f(24), f(1), f(1)).unwrap();
+ assert_eq!(align(&q, 1), Alignment::End);
+ set_span(&mut q, TransitionId(1), f(40), f(24), f(1), f(1)).unwrap();
+ assert_eq!(align(&q, 1), Alignment::Custom);
+ // an odd centred duration sits half a frame off the cut and is still Center at Cut
+ set_span(&mut q, TransitionId(1), f(42), f(13), f(1), f(1)).unwrap();
+ assert_eq!(align(&q, 1), Alignment::Center);
+ }
+
+ #[test]
+ fn duration_changes_follow_the_alignment() {
+ let q = seq();
+ let snap = |t: Tick| R.snap(t);
+ // Center at Cut: both ends move
+ assert_eq!(start_for(&q, TransitionId(1), f(36), Alignment::Center, f(1), snap), Some(f(30)));
+ // Start at Cut: only the end moves; End at Cut: only the beginning
+ assert_eq!(start_for(&q, TransitionId(1), f(36), Alignment::Start, f(1), snap), Some(f(48)));
+ assert_eq!(start_for(&q, TransitionId(1), f(36), Alignment::End, f(1), snap), Some(f(12)));
+ // a one-sided transition keeps its edge whatever is asked
+ assert_eq!(start_for(&q, TransitionId(2), f(20), Alignment::Center, f(1), snap), Some(f(0)));
+ assert_eq!(start_for(&q, TransitionId(3), f(20), Alignment::Center, f(1), snap), Some(f(124)));
+ }
+
+ #[test]
+ fn custom_start_resizes_around_its_middle() {
+ let mut q = seq();
+ set_span(&mut q, TransitionId(1), f(40), f(20), f(1), f(1)).unwrap();
+ assert_eq!(start_for(&q, TransitionId(1), f(10), Alignment::Custom, f(1), |t| R.snap(t)), Some(f(45)));
+ }
+
+ #[test]
+ fn spans_stay_on_the_cut_and_inside_the_clips() {
+ let mut q = seq();
+ let before = q.clone();
+ for (id, start, dur) in [
+ (1, -1, 24), // before the outgoing clip
+ (1, 40, 60), // past the incoming clip's end
+ (1, 10, 20), // entirely before the cut
+ (1, 50, 10), // entirely after it
+ (1, 40, 0), // empty
+ (2, 1, 12), // a fade in must start at its clip's start
+ (3, 120, 12), // a fade out must end at its clip's end
+ (9, 0, 12), // no such transition
+ ] {
+ assert!(set_span(&mut q, TransitionId(id), f(start), f(dur), f(1), f(1)).is_err(), "{id} {start} {dur}");
+ assert_eq!(q, before, "refused changes leave the sequence as it was");
+ }
+ // the whole of both clips is allowed
+ set_span(&mut q, TransitionId(1), f(0), f(96), f(1), f(1)).unwrap();
+ assert_eq!(span(&q, 1), (f(0), f(96)));
+ // Tick::MAX never overflows
+ assert!(set_span(&mut q, TransitionId(1), Tick(i64::MAX - 1), Tick(i64::MAX), f(1), f(1)).is_err());
+ }
+
+ fn drag(q: &Sequence, id: u64, edge: Option<Edge>, frames: i64) -> (i64, i64) {
+ let (t, x) = find(q, TransitionId(id)).unwrap();
+ let (st, d) = drag_span(t, x, edge, f(frames), f(1), |t| R.snap(t)).unwrap();
+ (R.frame_at(st), R.frame_at(d))
+ }
+
+ #[test]
+ fn dragging_a_transition() {
+ let mut q = seq();
+ // centred (36..60 over the cut at 48): an end grows / shrinks it on both sides
+ assert_eq!(drag(&q, 1, Some(Edge::In), -4), (32, 32));
+ assert_eq!(drag(&q, 1, Some(Edge::Out), -10), (46, 4));
+ assert_eq!(drag(&q, 1, Some(Edge::Out), -100), (47, 1), "at least a frame (centred: it starts on the frame before the cut)");
+ assert_eq!(drag(&q, 1, Some(Edge::Out), 100), (0, 96), "at most both clips");
+ // the middle slides it, staying over the cut and inside the clips
+ assert_eq!(drag(&q, 1, None, 5), (41, 24));
+ assert_eq!(drag(&q, 1, None, 100), (48, 24));
+ assert_eq!(drag(&q, 1, None, -100), (24, 24));
+ // not centred: the other end stays
+ set_span(&mut q, TransitionId(1), f(40), f(20), f(1), f(1)).unwrap();
+ assert_eq!(drag(&q, 1, Some(Edge::In), -4), (36, 24));
+ assert_eq!(drag(&q, 1, Some(Edge::In), 100), (48, 12), "the start stops at the cut");
+ assert_eq!(drag(&q, 1, Some(Edge::Out), 6), (40, 26));
+ assert_eq!(drag(&q, 1, Some(Edge::Out), -100), (40, 8), "the end stops at the cut");
+ // a fade in keeps its start, a fade out its end; neither slides
+ assert_eq!(drag(&q, 2, Some(Edge::In), 3), (0, 12));
+ assert_eq!(drag(&q, 2, Some(Edge::Out), 3), (0, 15));
+ assert_eq!(drag(&q, 2, None, 3), (0, 12));
+ assert_eq!(drag(&q, 3, Some(Edge::Out), 3), (132, 12));
+ assert_eq!(drag(&q, 3, Some(Edge::In), -3), (129, 15));
+ // whatever comes out is a span set_span accepts
+ for (id, edge, n) in [(1, Some(Edge::In), -70), (1, None, 33), (2, Some(Edge::Out), 99), (3, Some(Edge::In), -99)] {
+ let (t, x) = find(&q, TransitionId(id)).unwrap();
+ let (st, d) = drag_span(t, x, edge, f(n), f(1), |t| R.snap(t)).unwrap();
+ let mut c = q.clone();
+ set_span(&mut c, TransitionId(id), st, d, f(1), f(1)).unwrap();
+ }
+ }
+
+ #[test]
+ fn locked_tracks_refuse() {
+ let mut q = seq();
+ q.video_tracks[0].locked = true;
+ assert_eq!(set_span(&mut q, TransitionId(1), f(40), f(20), f(1), f(1)), Err(EditError::Locked));
+ assert_eq!(remove(&mut q, &[TransitionId(1)]), Err(EditError::Locked));
+ }
+
+ #[test]
+ fn remove_takes_only_the_named_transitions() {
+ let mut q = seq();
+ assert_eq!(remove(&mut q, &[TransitionId(1), TransitionId(3)]), Ok(2));
+ let left: Vec<u64> = q.video_tracks[0].transitions.iter().map(|x| x.id.0).collect();
+ assert_eq!(left, vec![2]);
+ assert_eq!(q.video_tracks[0].items.len(), 3, "the clips stay");
+ assert_eq!(remove(&mut q, &[TransitionId(1)]), Err(EditError::Nothing));
+ }
+}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index b5e4c847a..cfb203101 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -81,6 +81,15 @@ pub(crate) fn has_selection(s: &Session) -> std::result::Result<(), String> {
}
/// Clips or captions selected (Clear / Ripple Delete work on either).
fn has_any_selection(s: &Session) -> std::result::Result<(), String> {
+ has_seq(s)?;
+ if s.state.selection.is_empty() && s.state.caption_selection.is_empty() && s.state.transition_selection.is_empty() {
+ Err("nothing selected".into())
+ } else {
+ Ok(())
+ }
+}
+/// Clips or captions selected (Ripple Delete: a transition has no length of its own to close).
+fn has_clip_or_caption_selection(s: &Session) -> std::result::Result<(), String> {
has_seq(s)?;
if s.state.selection.is_empty() && s.state.caption_selection.is_empty() { Err("nothing selected".into()) } else { Ok(()) }
}
@@ -1187,6 +1196,11 @@ fn build() -> Vec<CommandSpec> {
cmd!("edit.pasteInsert", "Paste Insert", ["Edit"], Some("Cmd+Shift+V"), "{}", has_clipboard, |s, _| paste(s, true)),
cmd!("edit.clear", "Clear", ["Edit"], Some("Backspace"), r#"{"clips":[id]?}"#, has_any_selection, |s, p| {
if p.get("clips").is_none() && p.get("clip").is_none() && s.state.selection.is_empty() {
+ // a selected transition (clicked in the Timeline) goes, as a clip would
+ if !s.state.transition_selection.is_empty() {
+ let ids = s.state.transition_selection.clone();
+ return remove_transitions(s, &ids, "Clear");
+ }
let caps = s.state.caption_selection.clone();
return crate::captions::delete(s, &caps, false);
}
@@ -1198,7 +1212,7 @@ fn build() -> Vec<CommandSpec> {
})?;
Ok(Value::Null)
}),
- cmd!("edit.rippleDelete", "Ripple Delete", ["Edit"], Some("Shift+Delete"), r#"{"clips":[id]?}"#, has_any_selection, |s, p| {
+ cmd!("edit.rippleDelete", "Ripple Delete", ["Edit"], Some("Shift+Delete"), r#"{"clips":[id]?}"#, has_clip_or_caption_selection, |s, p| {
if p.get("clips").is_none() && p.get("clip").is_none() && s.state.selection.is_empty() {
let caps = s.state.caption_selection.clone();
return crate::captions::delete(s, &caps, true);
@@ -1536,10 +1550,20 @@ fn build() -> Vec<CommandSpec> {
"Edit Transition Settings",
[],
None,
- r#"{"transition":id,"params":{param:value}?,"reverse":bool?,"reset":bool?}"#,
+ r#"{"transition":id,"params":{param:value}?,"reverse":bool?,"reset":bool?,"duration":ticks?|"frames":n?,"align":"center"|"start"|"end"?|"start":ticks?,"merge":bool?,"begin":bool?}"#,
has_seq,
set_transition
),
+ cmd!("sequence.removeTransition", "Clear Transition", [], None, r#"{"transitions":[id]?}"#, has_seq, |s, p| {
+ let ids: Vec<TransitionId> = match p.get("transitions").or_else(|| p.get("transition")) {
+ Some(v) => transition_ids_p(v).ok_or_else(|| bad("sequence.removeTransition", "`transitions` is a list of transition ids"))?,
+ None => s.state.transition_selection.clone(),
+ };
+ if ids.is_empty() {
+ return Err(bad("sequence.removeTransition", "no transition given or selected"));
+ }
+ remove_transitions(s, &ids, "Clear Transition")
+ }),
cmd!("sequence.closeGap", "Close Gap", ["Sequence"], None, r#"{"track":"V1"|id,"time":ticks}"#, has_seq, |s, p| {
let tr = track_p(s, p, "track", "sequence.closeGap")?.ok_or_else(|| bad("sequence.closeGap", "need `track`"))?;
let t = time_p(s, p, "").unwrap_or(s.playhead());
@@ -2019,13 +2043,18 @@ fn build() -> Vec<CommandSpec> {
Ok(json!({"clips": ids.iter().map(|c| c.0).collect::<Vec<_>>()}))
}
),
- cmd!("timeline.select", "Select Clips", [], None, r#"{"clips":[id],"add":bool,"toggle":bool}"#, has_seq, |s, p| {
+ cmd!("timeline.select", "Select Clips", [], None, r#"{"clips":[id],"transitions":[id]?,"add":bool,"toggle":bool}"#, has_seq, |s, p| {
+ if let Some(ids) = p.get("transitions") {
+ return select_transitions(s, ids, bool_p(p, "add").unwrap_or(false), bool_p(p, "toggle").unwrap_or(false));
+ }
let clips: Vec<ClipId> =
p.get("clips").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_u64().map(ClipId)).collect()).unwrap_or_default();
let clips = with_links(s, &clips);
// selecting clips leaves trim mode (Premiere: clip and edit point selections are exclusive)
s.state.edit_points.clear();
s.state.trim_shift = Default::default();
+ // and a clip selection replaces a transition one
+ s.state.transition_selection.clear();
if bool_p(p, "toggle").unwrap_or(false) {
for c in clips {
if let Some(i) = s.state.selection.iter().position(|x| *x == c) {
@@ -3151,13 +3180,109 @@ fn set_transition_params(e: &mut filmcraft_project::EffectInstance, params: &Val
Ok(())
}
-/// `sequence.setTransition`: edit an applied transition's settings (Effect Controls).
+/// A JSON list of transition ids (or one id).
+fn transition_ids_p(v: &Value) -> Option<Vec<TransitionId>> {
+ match v {
+ Value::Array(a) => a.iter().map(|x| x.as_u64().map(TransitionId)).collect(),
+ x => x.as_u64().map(|i| vec![TransitionId(i)]),
+ }
+}
+
+/// `timeline.select {"transitions": […]}`: select transitions (clicking one in the Timeline). It
+/// replaces the clip, edit point and caption selections, as a clip selection replaces it.
+fn select_transitions(s: &mut Session, ids: &Value, add: bool, toggle: bool) -> Result<Value> {
+ const CMD: &str = "timeline.select";
+ let ids = transition_ids_p(ids).ok_or_else(|| bad(CMD, "`transitions` is a list of transition ids"))?;
+ let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
+ if let Some(missing) = ids.iter().find(|id| !q.all_tracks().any(|t| t.transitions.iter().any(|x| x.id == **id))) {
+ return Err(bad(CMD, format!("no transition {}", missing.0)));
+ }
+ if toggle {
+ for id in ids {
+ match s.state.transition_selection.iter().position(|x| *x == id) {
+ Some(i) => {
+ s.state.transition_selection.remove(i);
+ }
+ None => s.state.transition_selection.push(id),
+ }
+ }
+ } else if add {
+ for id in ids {
+ if !s.state.transition_selection.contains(&id) {
+ s.state.transition_selection.push(id);
+ }
+ }
+ } else {
+ s.state.transition_selection = ids;
+ }
+ s.state.selection.clear();
+ s.state.caption_selection.clear();
+ s.state.edit_points.clear();
+ s.state.trim_shift = Default::default();
+ Ok(json!({"selection": [], "transitionSelection": s.state.transition_selection.iter().map(|t| t.0).collect::<Vec<_>>()}))
+}
+
+/// Remove transitions in one undo step and drop them from the selection.
+fn remove_transitions(s: &mut Session, ids: &[TransitionId], label: &str) -> Result<Value> {
+ let ids = ids.to_vec();
+ let n = s.edit_sequence(label, |q, _, st| {
+ let n = edit::transitions::remove(q, &ids)?;
+ st.transition_selection.retain(|x| !ids.contains(x));
+ Ok(n)
+ })?;
+ Ok(json!({"removed": n}))
+}
+
+/// `sequence.setTransition`: edit an applied transition (Effect Controls, the Timeline): its
+/// settings, Reverse, and where it sits. `duration` / `frames` resize it the way its alignment
+/// says (Center at Cut and Custom Start: both ends; Start at Cut: the end; End at Cut: the
+/// beginning), `align` re-aligns it on its cut, `start` moves it (dragging it over the cut; with
+/// `duration`, dragging one edge). One undo step; with `merge`, a drag's steps share one.
fn set_transition(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "sequence.setTransition";
let id = p.get("transition").and_then(Value::as_u64).ok_or_else(|| bad(CMD, "need `transition`"))?;
+ let tid = TransitionId(id);
let q = s.active_sequence().ok_or(EngineError::NoSequence)?;
- let found = q.video_tracks.iter().chain(q.audio_tracks.iter()).find_map(|tr| tr.transitions.iter().find(|x| x.id.0 == id)).cloned();
- let mut cur = found.ok_or_else(|| bad(CMD, format!("no transition {id}")))?;
+ let rate = q.settings.frame_rate.sane();
+ let frame = rate.frame_duration();
+ let found = q.all_tracks().find_map(|tr| tr.transitions.iter().find(|x| x.id == tid).map(|x| (tr, x)));
+ let (track, cur) = found.ok_or_else(|| bad(CMD, format!("no transition {id}")))?;
+ let mut cur = cur.clone();
+ let (lo, cut, hi) = edit::transitions::bounds(track, &cur).ok_or_else(|| bad(CMD, "the transition's clips are gone"))?;
+ // times outside the clips it joins are refused before any frame arithmetic (hostile input)
+ let room = Tick(hi.0.saturating_sub(lo.0));
+ let duration = match (p.get("frames").and_then(Value::as_i64), p.get("duration").and_then(Value::as_i64)) {
+ (Some(_), Some(_)) => return Err(bad(CMD, "give `duration` or `frames`, not both")),
+ (Some(f), None) if (1..=10_000_000).contains(&f) && rate.tick_of(f) <= room => Some(rate.tick_of(f)),
+ (None, Some(d)) if d > 0 && d <= room.0 => Some(rate.snap_nearest(Tick(d)).max(frame)),
+ (Some(_), None) | (None, Some(_)) => return Err(bad(CMD, "a transition lasts at least one frame and can't extend past the clips it joins")),
+ (None, None) => None,
+ };
+ let align = match str_p(p, "align") {
+ Some(a) => Some(edit::transitions::Alignment::parse(a).ok_or_else(|| bad(CMD, format!("`align` is center, start or end, not `{a}`")))?),
+ None => None,
+ };
+ let start = match p.get("start").and_then(Value::as_i64) {
+ Some(t) if (lo.0..=hi.0).contains(&t) => Some(rate.snap_nearest(Tick(t))),
+ Some(_) => return Err(bad(CMD, "a transition can't extend past the clips it joins")),
+ None => None,
+ };
+ if start.is_some() && align.is_some() {
+ return Err(bad(CMD, "give `start` or `align`, not both"));
+ }
+ let span = if duration.is_some() || align.is_some() || start.is_some() {
+ let d = duration.unwrap_or(cur.duration);
+ let st = match start {
+ Some(st) => st,
+ None => {
+ let al = align.unwrap_or_else(|| edit::transitions::alignment(&cur, cut, frame));
+ edit::transitions::start_for(q, tid, d, al, frame, |t| rate.snap(t)).ok_or_else(|| bad(CMD, format!("no transition {id}")))?
+ }
+ };
+ Some((st, d))
+ } else {
+ None
+ };
if p.get("reset").and_then(Value::as_bool).unwrap_or(false)
&& let Some(def) = cur.effect.def()
{
@@ -3170,16 +3295,32 @@ fn set_transition(s: &mut Session, p: &Value) -> Result<Value> {
cur.reverse = r;
}
let name = cur.effect.def().map_or("Transition", |d| d.name).to_string();
- s.edit_sequence(&format!("Edit {name}"), |q, _, _| {
+ if bool_p(p, "begin").unwrap_or(false) {
+ s.history.merge_key = None;
+ }
+ let merge = bool_p(p, "merge").unwrap_or(false).then(|| format!("setTransition:{id}"));
+ let after = s.edit_sequence_as(&format!("Edit {name}"), merge.as_deref(), |q, _, _| {
+ if let Some((st, d)) = span {
+ edit::transitions::set_span(q, tid, st, d, frame, frame)?;
+ }
+ let mut after = None;
for tr in q.video_tracks.iter_mut().chain(q.audio_tracks.iter_mut()) {
- if let Some(x) = tr.transitions.iter_mut().find(|x| x.id.0 == id) {
+ if let Some(x) = tr.transitions.iter_mut().find(|x| x.id == tid) {
x.effect = cur.effect.clone();
x.reverse = cur.reverse;
+ after = Some((x.start, x.duration));
}
}
- Ok(())
+ Ok(after)
})?;
- Ok(json!({"transition": id, "effect": cur.effect.effect, "reverse": cur.reverse}))
+ let (st, d) = after.unwrap_or((cur.start, cur.duration));
+ let al = s
+ .active_sequence()
+ .and_then(|q| {
+ q.all_tracks().find_map(|tr| tr.transitions.iter().find(|x| x.id == tid).and_then(|x| edit::transitions::bounds(tr, x).map(|b| (x.clone(), b.1))))
+ })
+ .map(|(x, cut)| edit::transitions::alignment(&x, cut, frame).id());
+ Ok(json!({"transition": id, "effect": cur.effect.effect, "reverse": cur.reverse, "start": st.0, "duration": d.0, "align": al}))
}
fn apply_transition(s: &mut Session, p: &Value, kind: TrackKind) -> Result<Value> {
@@ -3285,7 +3426,7 @@ pub fn inspect_sequence(s: &Session, id: ItemId, q: &filmcraft_project::Sequence
"enabled": i.enabled, "link": i.link, "label": i.label.name(),
"effects": i.effects.iter().map(|e| json!({"effect": e.effect, "enabled": e.enabled, "masks": e.masks.len(), "params": e.params.iter().map(|(k, p)| (k.clone(), json!({"value": format!("{:?}", p.value), "keyframes": p.keyframes.len()}))).collect::<serde_json::Map<_, _>>()})).collect::<Vec<_>>(),
})).collect::<Vec<_>>(),
- "transitions": t.transitions.iter().map(|x| json!({"id": x.id.0, "effect": x.effect.effect, "start": x.start.0, "duration": x.duration.0, "from": x.from.map(|c| c.0), "to": x.to.map(|c| c.0), "reverse": x.reverse, "params": x.effect.params.iter().map(|(k, v)| (k.clone(), serde_json::to_value(&v.value).unwrap_or_default())).collect::<serde_json::Map<_, _>>()})).collect::<Vec<_>>(),
+ "transitions": t.transitions.iter().map(|x| json!({"id": x.id.0, "effect": x.effect.effect, "start": x.start.0, "duration": x.duration.0, "from": x.from.map(|c| c.0), "to": x.to.map(|c| c.0), "reverse": x.reverse, "align": filmcraft_edit::transitions::bounds(t, x).map(|b| filmcraft_edit::transitions::alignment(x, b.1, rate.frame_duration()).id()), "params": x.effect.params.iter().map(|(k, v)| (k.clone(), serde_json::to_value(&v.value).unwrap_or_default())).collect::<serde_json::Map<_, _>>()})).collect::<Vec<_>>(),
})
};
json!({
@@ -3302,6 +3443,7 @@ pub fn inspect_sequence(s: &Session, id: ItemId, q: &filmcraft_project::Sequence
"video": q.video_tracks.iter().map(tr).collect::<Vec<_>>(),
"audio": q.audio_tracks.iter().map(tr).collect::<Vec<_>>(),
"selection": s.state.selection.iter().map(|c| c.0).collect::<Vec<_>>(),
+ "transitionSelection": s.state.transition_selection.iter().map(|t| t.0).collect::<Vec<_>>(),
})
}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 2578420b5..26ee2bacb 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -260,6 +260,10 @@ pub struct EditorState {
/// Selected captions (caption tracks / Captions panel).
#[serde(default)]
pub caption_selection: Vec<ClipId>,
+ /// Selected transitions (clicked in the Timeline): Effect Controls shows one, Delete removes
+ /// them. Selecting clips clears it and selecting transitions clears the clip selection.
+ #[serde(default)]
+ pub transition_selection: Vec<filmcraft_project::TransitionId>,
/// Selected layers (indices among the graphic layers, 0 = back) of the selected graphic clip.
#[serde(default)]
pub graphic_layers: Vec<usize>,
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 01d5b8133..380519cf8 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -641,3 +641,111 @@ fn dragging_an_effect_parameter_is_one_undo_step() {
s.undo();
assert_eq!(opacity(&s), start, "and then the whole first one");
}
+
+/// The demo's first video transition between two clips: (id, start, duration, cut).
+fn demo_crossing(s: &Session) -> (u64, Tick, Tick, Tick) {
+ let q = s.active_sequence().unwrap();
+ q.video_tracks
+ .iter()
+ .find_map(|t| {
+ t.transitions.iter().find(|x| x.from.is_some() && x.to.is_some()).map(|x| (x.id.0, x.start, x.duration, t.item(x.to.unwrap()).unwrap().start))
+ })
+ .expect("the demo has a transition between two clips")
+}
+
+fn transition_ids(s: &Session) -> Vec<u64> {
+ s.active_sequence().unwrap().all_tracks().flat_map(|t| t.transitions.iter().map(|x| x.id.0)).collect()
+}
+
+/// #430: a transition can be selected (it replaces the clip selection and back), Delete removes
+/// it and leaves its clips, undo brings it back; Ripple Delete is not for a transition alone.
+#[test]
+fn transitions_select_and_delete() {
+ let mut s = demo();
+ let (tid, ..) = demo_crossing(&s);
+ let clips = s.active_sequence().unwrap().all_tracks().map(|t| t.items.len()).sum::<usize>();
+ let some_clip = s.active_sequence().unwrap().video_tracks[0].items[0].id.0;
+ s.execute("timeline.select", json!({"clips": [some_clip]})).unwrap();
+ let r = s.execute("timeline.select", json!({"transitions": [tid]})).unwrap();
+ assert_eq!(r["transitionSelection"], json!([tid]));
+ assert!(s.state.selection.is_empty(), "selecting a transition replaces the clip selection");
+ assert!(s.execute("timeline.select", json!({"transitions": [987_654]})).is_err(), "unknown ids are refused");
+ assert!(s.execute("edit.rippleDelete", json!({})).is_err(), "Ripple Delete needs clips");
+ let before = (*s.project).clone();
+ s.execute("edit.clear", json!({})).unwrap();
+ assert!(!transition_ids(&s).contains(&tid), "Delete removes the selected transition");
+ assert_eq!(s.active_sequence().unwrap().all_tracks().map(|t| t.items.len()).sum::<usize>(), clips, "and leaves the clips");
+ assert!(s.state.transition_selection.is_empty());
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, before, "one undo step");
+ // selecting clips clears a transition selection
+ s.execute("timeline.select", json!({"transitions": [tid]})).unwrap();
+ s.execute("timeline.select", json!({"clips": [some_clip]})).unwrap();
+ assert!(s.state.transition_selection.is_empty());
+ // by id, without a selection
+ s.execute("sequence.removeTransition", json!({"transitions": [tid]})).unwrap();
+ assert!(!transition_ids(&s).contains(&tid));
+ assert!(s.execute("sequence.removeTransition", json!({"transitions": [tid]})).is_err(), "nothing left to remove");
+ assert!(s.execute("sequence.removeTransition", json!({})).is_err(), "nothing given or selected");
+}
+
+/// #224 / Effect Controls: Duration follows the alignment, Alignment re-aligns on the cut, Start
+/// moves it (Custom Start), all within the clips it joins; a drag is one undo step.
+#[test]
+fn transition_duration_alignment_and_position() {
+ let mut s = demo();
+ let rate = s.sequence_rate();
+ let f = |n: i64| rate.tick_of(n);
+ let (tid, _, _, cut) = demo_crossing(&s);
+ let set = |s: &mut Session, p: Value| {
+ let mut p = p;
+ p["transition"] = json!(tid);
+ s.execute("sequence.setTransition", p)
+ };
+ let r = set(&mut s, json!({"align": "start"})).unwrap();
+ assert_eq!((r["start"].as_i64(), r["align"].as_str()), (Some(cut.0), Some("start")));
+ // Start at Cut: only the end moves
+ let r = set(&mut s, json!({"frames": 10})).unwrap();
+ assert_eq!((r["start"].as_i64(), r["duration"].as_i64()), (Some(cut.0), Some(f(10).0)));
+ // End at Cut: only the beginning moves
+ let r = set(&mut s, json!({"align": "end", "frames": 8})).unwrap();
+ assert_eq!((r["start"].as_i64(), r["duration"].as_i64(), r["align"].as_str()), (Some((cut - f(8)).0), Some(f(8).0), Some("end")));
+ // Center at Cut: both ends
+ let r = set(&mut s, json!({"align": "center", "frames": 12})).unwrap();
+ assert_eq!((r["start"].as_i64(), r["align"].as_str()), (Some((cut - f(6)).0), Some("center")));
+ // dragging it over the cut: Custom Start; then a new duration keeps its middle
+ let r = set(&mut s, json!({"start": (cut - f(3)).0})).unwrap();
+ assert_eq!(r["align"], json!("custom"));
+ let r = set(&mut s, json!({"frames": 6})).unwrap();
+ assert_eq!((r["start"].as_i64(), r["duration"].as_i64()), (Some(cut.0), Some(f(6).0)), "centre at cut + 3 frames, 6 frames long");
+ // dragging one edge: start and duration together
+ let r = set(&mut s, json!({"start": (cut - f(4)).0, "duration": f(10).0})).unwrap();
+ assert_eq!((r["start"].as_i64(), r["duration"].as_i64()), (Some((cut - f(4)).0), Some(f(10).0)));
+ // refused, and nothing changes
+ let before = (*s.project).clone();
+ let history = s.history.undo.len();
+ for p in [
+ json!({"frames": 0}),
+ json!({"frames": 100_000_000}),
+ json!({"duration": -5}),
+ json!({"duration": i64::MAX}),
+ json!({"frames": 10, "duration": f(10).0}),
+ json!({"align": "middle"}),
+ json!({"align": "start", "start": cut.0}),
+ json!({"start": i64::MIN}),
+ json!({"start": (cut + f(1)).0, "duration": f(1).0}),
+ ] {
+ assert!(set(&mut s, p.clone()).is_err(), "{p}");
+ assert_eq!(*s.project, before, "{p}");
+ assert_eq!(s.history.undo.len(), history, "{p}");
+ }
+ assert!(s.execute("sequence.setTransition", json!({"transition": 987_654, "frames": 5})).is_err());
+ // a drag (merge) is one undo step
+ let history = s.history.undo.len();
+ for (i, n) in [11, 12, 13, 14].into_iter().enumerate() {
+ set(&mut s, json!({"frames": n, "merge": true, "begin": i == 0})).unwrap();
+ }
+ assert_eq!(s.history.undo.len(), history + 1);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(*s.project, before);
+}