The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
Keyframes, and an Animation tab of named shapes on them
Jareerbc9727b67a77
diff --git a/engine/crates/concat-core/src/animate.rs b/engine/crates/concat-core/src/animate.rsnew file mode 100644index 00000000..ad3bf6e2--- /dev/null+++ b/engine/crates/concat-core/src/animate.rs@@ -0,0 +1,212 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! Placement that changes over a clip.+//!+//! A clip's transform and opacity are one value each. An *animation* is a+//! set of keys on top of them: for each of scale, the two offsets, rotation+//! and opacity, a list of `(at, value)` with `at` a fraction of the clip's+//! length, eased between neighbours. The values are relative to the clip's+//! own - a scale key is a factor, an offset key an addition, an opacity key+//! a factor - so the same animation means the same motion on any clip, and+//! a preset never has to know where the clip sits.+//!+//! This is the one place the per-frame arithmetic lives; the plan asks the+//! clip, and the clip asks here.++use crate::timeline::Transform;++/// How a key is approached from the one before it.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]+pub enum Ease {+ /// Straight line.+ #[default]+ Linear,+ /// Starts slow, arrives fast.+ In,+ /// Starts fast, arrives slow.+ Out,+ /// Slow at both ends.+ InOut,+}++impl Ease {+ /// The eased fraction for a linear one.+ pub fn apply(self, t: f64) -> f64 {+ let t = t.clamp(0.0, 1.0);+ match self {+ Ease::Linear => t,+ Ease::In => t * t,+ Ease::Out => 1.0 - (1.0 - t) * (1.0 - t),+ Ease::InOut => {+ if t < 0.5 {+ 2.0 * t * t+ } else {+ 1.0 - (-2.0 * t + 2.0).powi(2) / 2.0+ }+ }+ }+ }+}++/// One key of one property.+#[derive(Clone, Copy, PartialEq, Debug)]+pub struct Key {+ /// Where in the clip, `0..=1`.+ pub at: f64,+ /// The value there, in the property's relative terms.+ pub value: f64,+ /// How this key is approached from the previous one.+ pub ease: Ease,+}++/// The keys of one property, sorted by `at`.+#[derive(Clone, PartialEq, Debug, Default)]+pub struct Track {+ keys: Vec<Key>,+}++impl Track {+ /// A track through these keys, sorted.+ pub fn new(mut keys: Vec<Key>) -> Track {+ keys.retain(|key| key.at.is_finite() && key.value.is_finite());+ for key in &mut keys {+ key.at = key.at.clamp(0.0, 1.0);+ }+ keys.sort_by(|a, b| a.at.total_cmp(&b.at));+ Track { keys }+ }++ /// The keys, sorted.+ pub fn keys(&self) -> &[Key] {+ &self.keys+ }++ /// True with no keys: the property is the clip's own.+ pub fn is_empty(&self) -> bool {+ self.keys.is_empty()+ }++ /// The value at `x`: `rest` with no keys, the first key's before it,+ /// the last key's after it, and eased between neighbours.+ pub fn value_at(&self, x: f64, rest: f64) -> f64 {+ let Some(first) = self.keys.first() else {+ return rest;+ };+ if x <= first.at {+ return first.value;+ }+ for pair in self.keys.windows(2) {+ let (a, b) = (pair[0], pair[1]);+ if x <= b.at {+ if b.at <= a.at {+ return b.value;+ }+ let t = b.ease.apply((x - a.at) / (b.at - a.at));+ return a.value + (b.value - a.value) * t;+ }+ }+ self.keys[self.keys.len() - 1].value+ }+}++/// Every animatable property's keys.+#[derive(Clone, PartialEq, Debug, Default)]+pub struct Animation {+ /// A factor on the clip's scale; 1 is as placed.+ pub scale: Track,+ /// Added to the clip's horizontal offset, in frame widths.+ pub offset_x: Track,+ /// Added to the clip's vertical offset, in frame heights.+ pub offset_y: Track,+ /// Added to the clip's rotation, in degrees.+ pub rotation: Track,+ /// A factor on the clip's opacity; 1 is as set.+ pub opacity: Track,+}++impl Animation {+ /// True when no property has a key.+ pub fn is_empty(&self) -> bool {+ self.scale.is_empty()+ && self.offset_x.is_empty()+ && self.offset_y.is_empty()+ && self.rotation.is_empty()+ && self.opacity.is_empty()+ }++ /// The clip's transform at `x`, a fraction of its length.+ pub fn transform_at(&self, base: Transform, x: f64) -> Transform {+ Transform {+ scale: (base.scale * self.scale.value_at(x, 1.0)).max(0.001),+ offset_x: base.offset_x + self.offset_x.value_at(x, 0.0),+ offset_y: base.offset_y + self.offset_y.value_at(x, 0.0),+ rotation: base.rotation + self.rotation.value_at(x, 0.0),+ }+ }++ /// The clip's opacity at `x`.+ pub fn opacity_at(&self, base: f32, x: f64) -> f32 {+ (f64::from(base) * self.opacity.value_at(x, 1.0)).clamp(0.0, 1.0) as f32+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn key(at: f64, value: f64, ease: Ease) -> Key {+ Key { at, value, ease }+ }++ #[test]+ fn a_track_holds_its_ends_and_eases_between() {+ let track = Track::new(vec![+ key(0.5, 1.0, Ease::Linear),+ key(0.0, 0.0, Ease::Linear),+ ]);+ assert_eq!(track.value_at(-1.0, 7.0), 0.0);+ assert_eq!(track.value_at(0.25, 7.0), 0.5);+ assert_eq!(track.value_at(0.9, 7.0), 1.0);+ assert_eq!(Track::default().value_at(0.5, 7.0), 7.0);++ let eased = Track::new(vec![key(0.0, 0.0, Ease::Linear), key(1.0, 1.0, Ease::Out)]);+ assert!(eased.value_at(0.5, 0.0) > 0.5);+ let eased = Track::new(vec![key(0.0, 0.0, Ease::Linear), key(1.0, 1.0, Ease::In)]);+ assert!(eased.value_at(0.5, 0.0) < 0.5);+ }++ #[test]+ fn an_animation_is_relative_to_the_clip() {+ let animation = Animation {+ scale: Track::new(vec![+ key(0.0, 0.5, Ease::Linear),+ key(1.0, 1.0, Ease::Linear),+ ]),+ offset_x: Track::new(vec![+ key(0.0, 0.5, Ease::Linear),+ key(1.0, 0.0, Ease::Linear),+ ]),+ opacity: Track::new(vec![+ key(0.0, 0.0, Ease::Linear),+ key(0.5, 1.0, Ease::Linear),+ ]),+ ..Animation::default()+ };+ let base = Transform {+ scale: 2.0,+ offset_x: 0.1,+ offset_y: -0.2,+ rotation: 10.0,+ };+ let mid = animation.transform_at(base, 0.5);+ assert!((mid.scale - 1.5).abs() < 1e-12);+ assert!((mid.offset_x - 0.35).abs() < 1e-12);+ assert_eq!(mid.offset_y, -0.2);+ assert_eq!(mid.rotation, 10.0);+ assert!((animation.opacity_at(0.8, 0.25) - 0.4).abs() < 1e-6);+ assert_eq!(animation.opacity_at(0.8, 0.9), 0.8);+ assert!(!animation.is_empty());+ assert!(Animation::default().is_empty());+ }+}diff --git a/engine/crates/concat-core/src/lib.rs b/engine/crates/concat-core/src/lib.rsindex 310820c9..6b19f272 100644--- a/engine/crates/concat-core/src/lib.rs+++ b/engine/crates/concat-core/src/lib.rs@@ -16,6 +16,7 @@//! If you are about to add a dependency to this crate, the thing you are adding//! probably belongs in `concat-media` or `concat-render` instead.+pub mod animate;pub mod arena;pub mod frame;pub mod retime;diff --git a/engine/crates/concat-core/src/timeline.rs b/engine/crates/concat-core/src/timeline.rsindex 530cf485..af6aaf13 100644--- a/engine/crates/concat-core/src/timeline.rs+++ b/engine/crates/concat-core/src/timeline.rs@@ -12,6 +12,7 @@use std::path::{Path, PathBuf};+use crate::animate::Animation;use crate::arena::{Arena, Id};use crate::retime::SpeedCurve;use crate::time::{FrameRate, Rational, TimeRange};@@ -91,6 +92,9 @@ pub struct Clip {/// Played backwards: the source is consumed from its far end towards/// `source_start`.pub reverse: bool,+ /// Keys over the clip's placement and opacity, when it has any. See+ /// [`Animation`].+ pub animation: Option<Animation>,}/// A clip's placement in the output frame.@@ -147,6 +151,34 @@ impl Clip {transform: Transform::IDENTITY,retime: None,reverse: false,+ animation: None,+ }+ }++ /// Where in the clip `time` falls, `0..=1`; zero outside it.+ pub fn fraction_at(&self, time: Rational) -> f64 {+ if self.duration.is_zero() {+ return 0.0;+ }+ ((time - self.start) / self.duration)+ .as_f64()+ .clamp(0.0, 1.0)+ }++ /// The placement at `time`: the clip's own, moved by its animation.+ pub fn transform_at(&self, time: Rational) -> Transform {+ match &self.animation {+ Some(animation) => animation.transform_at(self.transform, self.fraction_at(time)),+ None => self.transform,+ }+ }++ /// The opacity at `time`, before the fade ramps: the clip's own, scaled+ /// by its animation.+ pub fn opacity_at(&self, time: Rational) -> f32 {+ match &self.animation {+ Some(animation) => animation.opacity_at(self.opacity, self.fraction_at(time)),+ None => self.opacity,}}diff --git a/engine/crates/concat-export/src/flatten.rs b/engine/crates/concat-export/src/flatten.rsindex 6b00dee0..e1a3ef77 100644--- a/engine/crates/concat-export/src/flatten.rs+++ b/engine/crates/concat-export/src/flatten.rs@@ -16,7 +16,7 @@use concat_project::model::{ClipKind as ModelClipKind, Project, Timeline};use crate::chains::{audio_filter_chain, video_effect_chain};-use crate::{ClipKind, ExportClip, TransitionSpec};+use crate::{ClipKind, ExportClip, ExportKey, TransitionSpec};/// Flattens one timeline of `project` for the exporter - the active one/// when `timeline_id` is `None`. Text clips are excluded (they rasterise@@ -60,6 +60,7 @@ pub fn flatten_timeline(project: &Project, timeline_id: Option<&str>) -> Vec<Exppreserve_pitch: true,speed_curve: Vec::new(),reverse: false,+ animation: Vec::new(),scale: 1.0,offset_x: 0.0,offset_y: 0.0,@@ -106,6 +107,7 @@ pub fn flatten_timeline(project: &Project, timeline_id: Option<&str>) -> Vec<Exp.map(|point| (point.at, point.speed)).collect(),reverse: clip.reverse,+ animation: export_keys(clip),scale: clip.scale,offset_x: clip.offset_x,offset_y: clip.offset_y,@@ -144,6 +146,39 @@ fn pick_timeline<'a>(project: &'a Project, timeline_id: Option<&str>) -> Option<.or_else(|| project.timelines.first())}+/// The clip's animation presets, materialised for its current length as+/// the keys the engine plays. See `concat_project::animation`.+pub fn export_keys(clip: &concat_project::model::Clip) -> Vec<ExportKey> {+ use concat_core::animate::Ease;+ let Some(animation) = concat_project::animation::animation_of(clip) else {+ return Vec::new();+ };+ let mut out = Vec::new();+ for (property, track) in [+ ("scale", &animation.scale),+ ("offsetX", &animation.offset_x),+ ("offsetY", &animation.offset_y),+ ("rotation", &animation.rotation),+ ("opacity", &animation.opacity),+ ] {+ for key in track.keys() {+ out.push(ExportKey {+ property: property.to_owned(),+ at: key.at,+ value: key.value,+ ease: match key.ease {+ Ease::Linear => "linear",+ Ease::In => "in",+ Ease::Out => "out",+ Ease::InOut => "inOut",+ }+ .to_owned(),+ });+ }+ }+ out+}+#[cfg(test)]mod tests {use std::collections::BTreeMap;diff --git a/engine/crates/concat-export/src/lib.rs b/engine/crates/concat-export/src/lib.rsindex 8d76ab47..928841ed 100644--- a/engine/crates/concat-export/src/lib.rs+++ b/engine/crates/concat-export/src/lib.rs@@ -28,6 +28,7 @@ use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use concat_core::SpeedCurve;+use concat_core::animate::Animation;use concat_core::frame::Frame;use concat_core::time::{FrameRate, Rational};use concat_core::timeline::{Clip, ClipId, MediaRef, Timeline, Track, TrackKind, Transform};@@ -105,6 +106,10 @@ pub struct ExportClip {/// Played backwards.#[serde(default)]pub reverse: bool,+ /// Keys over the clip's placement and opacity, resolved by the UI from+ /// its animation presets. Empty for none.+ #[serde(default)]+ pub animation: Vec<ExportKey>,/// Multiplier over the fitted size. 1 fills the frame, preserving aspect.#[serde(default = "unity")]pub scale: f64,@@ -149,6 +154,22 @@ pub struct ExportClip {pub has_audio: Option<bool>,}+/// One animation key, as the flattener hands it over.+#[derive(Deserialize, Clone, Debug, PartialEq)]+#[serde(rename_all = "camelCase")]+pub struct ExportKey {+ /// "scale", "offsetX", "offsetY", "rotation" or "opacity".+ pub property: String,+ /// Where in the clip, `0..=1`.+ pub at: f64,+ /// The value there, relative to the clip's own; see the engine's+ /// `animate` module.+ pub value: f64,+ /// "linear", "in", "out" or "inOut".+ #[serde(default)]+ pub ease: String,+}+/// A transition on the cut into a clip.#[derive(Deserialize, Clone)]#[serde(rename_all = "camelCase")]@@ -890,6 +911,7 @@ fn build_timeline(engine_clip.retime = SpeedCurve::new(&clip.speed_curve);engine_clip.reverse = clip.reverse;}+ engine_clip.animation = animation_of(&clip.animation);engine_clip.transform = Transform {scale: clip.scale,offset_x: clip.offset_x,@@ -925,6 +947,44 @@ fn build_timeline(}}+/// The engine's keys for a flattened clip's animation, or None for none.+fn animation_of(keys: &[ExportKey]) -> Option<Animation> {+ use concat_core::animate::{Ease, Key, Track};+ if keys.is_empty() {+ return None;+ }+ let mut tracks: [Vec<Key>; 5] = Default::default();+ for key in keys {+ let slot = match key.property.as_str() {+ "scale" => 0,+ "offsetX" => 1,+ "offsetY" => 2,+ "rotation" => 3,+ "opacity" => 4,+ _ => continue,+ };+ tracks[slot].push(Key {+ at: key.at,+ value: key.value,+ ease: match key.ease.as_str() {+ "in" => Ease::In,+ "out" => Ease::Out,+ "inOut" => Ease::InOut,+ _ => Ease::Linear,+ },+ });+ }+ let [scale, x, y, rotation, opacity] = tracks;+ let animation = Animation {+ scale: Track::new(scale),+ offset_x: Track::new(x),+ offset_y: Track::new(y),+ rotation: Track::new(rotation),+ opacity: Track::new(opacity),+ };+ (!animation.is_empty()).then_some(animation)+}+/// The source's contain-fitted size inside the output frame, or `None` when/// the UI never learnt the source's dimensions.fn fitted_size(request: &ExportRequest, clip: &ExportClip) -> Option<(u32, u32)> {@@ -1285,6 +1345,7 @@ mod tests {preserve_pitch: true,speed_curve: Vec::new(),reverse: false,+ animation: Vec::new(),scale: 1.0,offset_x: 0.0,offset_y: 0.0,diff --git a/engine/crates/concat-host/src/titles.rs b/engine/crates/concat-host/src/titles.rsindex 524eba8a..bbc6a916 100644--- a/engine/crates/concat-host/src/titles.rs+++ b/engine/crates/concat-host/src/titles.rs@@ -112,6 +112,7 @@ impl Titles {preserve_pitch: true,speed_curve: Vec::new(),reverse: false,+ animation: concat_export::flatten::export_keys(clip),scale: clip.scale,offset_x: clip.offset_x,offset_y: clip.offset_y,diff --git a/engine/crates/concat-project/src/animation.rs b/engine/crates/concat-project/src/animation.rsnew file mode 100644index 00000000..75c2660a--- /dev/null+++ b/engine/crates/concat-project/src/animation.rs@@ -0,0 +1,331 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! Animation presets: the named ways a clip comes in, goes out, or moves+//! for its whole length, as keys the engine can play.+//!+//! The document stores a name and a length per slot, not keys: a preset+//! re-materialises for the clip's current length every time it is asked+//! for, so trimming a clip keeps its half-second fade a half-second. The+//! shapes are relative to the clip's own placement (see the engine's+//! `animate` module), so a preset never has to know where the clip sits.++use concat_core::animate::{Animation, Ease, Key, Track};++use crate::model::{AnimationSlot, Clip, ClipAnimation};++/// One shape: what it is called, and its keys over the slot as `(property,+/// at-within-slot, value, ease)`.+struct Shape {+ name: &'static str,+ keys: &'static [(Prop, f64, f64, Ease)],+}++#[derive(Clone, Copy)]+enum Prop {+ Scale,+ X,+ Y,+ Rotation,+ Opacity,+}++use Prop::{Opacity, Rotation, Scale, X, Y};++/// The In shapes, in the order a menu lists them.+const IN: &[Shape] = &[+ Shape {+ name: "Fade",+ keys: &[+ (Opacity, 0.0, 0.0, Ease::Linear),+ (Opacity, 1.0, 1.0, Ease::Out),+ ],+ },+ Shape {+ name: "Zoom In",+ keys: &[+ (Scale, 0.0, 0.5, Ease::Linear),+ (Scale, 1.0, 1.0, Ease::Out),+ (Opacity, 0.0, 0.0, Ease::Linear),+ (Opacity, 1.0, 1.0, Ease::Out),+ ],+ },+ Shape {+ name: "Zoom Out",+ keys: &[+ (Scale, 0.0, 1.6, Ease::Linear),+ (Scale, 1.0, 1.0, Ease::Out),+ (Opacity, 0.0, 0.0, Ease::Linear),+ (Opacity, 1.0, 1.0, Ease::Out),+ ],+ },+ Shape {+ name: "Slide Up",+ keys: &[(Y, 0.0, 0.6, Ease::Linear), (Y, 1.0, 0.0, Ease::Out)],+ },+ Shape {+ name: "Slide Down",+ keys: &[(Y, 0.0, -0.6, Ease::Linear), (Y, 1.0, 0.0, Ease::Out)],+ },+ Shape {+ name: "Slide Left",+ keys: &[(X, 0.0, 0.6, Ease::Linear), (X, 1.0, 0.0, Ease::Out)],+ },+ Shape {+ name: "Slide Right",+ keys: &[(X, 0.0, -0.6, Ease::Linear), (X, 1.0, 0.0, Ease::Out)],+ },+ Shape {+ name: "Spin",+ keys: &[+ (Rotation, 0.0, -180.0, Ease::Linear),+ (Rotation, 1.0, 0.0, Ease::Out),+ (Scale, 0.0, 0.3, Ease::Linear),+ (Scale, 1.0, 1.0, Ease::Out),+ (Opacity, 0.0, 0.0, Ease::Linear),+ (Opacity, 1.0, 1.0, Ease::Out),+ ],+ },+];++/// The Out shapes: the In shapes run backwards, and eased in rather than+/// out, which is what leaving looks like.+const OUT: &[Shape] = &[+ Shape {+ name: "Fade",+ keys: &[+ (Opacity, 0.0, 1.0, Ease::Linear),+ (Opacity, 1.0, 0.0, Ease::In),+ ],+ },+ Shape {+ name: "Zoom In",+ keys: &[+ (Scale, 0.0, 1.0, Ease::Linear),+ (Scale, 1.0, 1.6, Ease::In),+ (Opacity, 0.0, 1.0, Ease::Linear),+ (Opacity, 1.0, 0.0, Ease::In),+ ],+ },+ Shape {+ name: "Zoom Out",+ keys: &[+ (Scale, 0.0, 1.0, Ease::Linear),+ (Scale, 1.0, 0.5, Ease::In),+ (Opacity, 0.0, 1.0, Ease::Linear),+ (Opacity, 1.0, 0.0, Ease::In),+ ],+ },+ Shape {+ name: "Slide Up",+ keys: &[(Y, 0.0, 0.0, Ease::Linear), (Y, 1.0, -0.6, Ease::In)],+ },+ Shape {+ name: "Slide Down",+ keys: &[(Y, 0.0, 0.0, Ease::Linear), (Y, 1.0, 0.6, Ease::In)],+ },+ Shape {+ name: "Slide Left",+ keys: &[(X, 0.0, 0.0, Ease::Linear), (X, 1.0, -0.6, Ease::In)],+ },+ Shape {+ name: "Slide Right",+ keys: &[(X, 0.0, 0.0, Ease::Linear), (X, 1.0, 0.6, Ease::In)],+ },+ Shape {+ name: "Spin",+ keys: &[+ (Rotation, 0.0, 0.0, Ease::Linear),+ (Rotation, 1.0, 180.0, Ease::In),+ (Scale, 0.0, 1.0, Ease::Linear),+ (Scale, 1.0, 0.3, Ease::In),+ (Opacity, 0.0, 1.0, Ease::Linear),+ (Opacity, 1.0, 0.0, Ease::In),+ ],+ },+];++/// The Combo shapes: over the whole clip.+const COMBO: &[Shape] = &[+ Shape {+ name: "Pulse",+ keys: &[+ (Scale, 0.0, 1.0, Ease::Linear),+ (Scale, 0.5, 1.08, Ease::InOut),+ (Scale, 1.0, 1.0, Ease::InOut),+ ],+ },+ Shape {+ name: "Shake",+ keys: &[+ (X, 0.0, 0.0, Ease::Linear),+ (X, 0.1, 0.02, Ease::Linear),+ (X, 0.2, -0.02, Ease::Linear),+ (X, 0.3, 0.02, Ease::Linear),+ (X, 0.4, -0.02, Ease::Linear),+ (X, 0.5, 0.02, Ease::Linear),+ (X, 0.6, -0.02, Ease::Linear),+ (X, 0.7, 0.02, Ease::Linear),+ (X, 0.8, -0.02, Ease::Linear),+ (X, 0.9, 0.02, Ease::Linear),+ (X, 1.0, 0.0, Ease::Linear),+ ],+ },+ Shape {+ name: "Spin",+ keys: &[+ (Rotation, 0.0, 0.0, Ease::Linear),+ (Rotation, 1.0, 360.0, Ease::Linear),+ ],+ },+ Shape {+ name: "Bounce",+ keys: &[+ (Y, 0.0, 0.0, Ease::Linear),+ (Y, 0.25, -0.06, Ease::Out),+ (Y, 0.5, 0.0, Ease::In),+ (Y, 0.75, -0.03, Ease::Out),+ (Y, 1.0, 0.0, Ease::In),+ ],+ },+ Shape {+ name: "Drift",+ keys: &[+ (Scale, 0.0, 1.0, Ease::Linear),+ (Scale, 1.0, 1.12, Ease::Linear),+ ],+ },+];++fn shapes(slot: AnimationSlot) -> &'static [Shape] {+ match slot {+ AnimationSlot::In => IN,+ AnimationSlot::Out => OUT,+ AnimationSlot::Combo => COMBO,+ }+}++/// The names a slot offers, in menu order.+pub fn names(slot: AnimationSlot) -> Vec<&'static str> {+ shapes(slot).iter().map(|shape| shape.name).collect()+}++/// Where a name sits in its slot's menu, or None for a name the slot does+/// not know.+pub fn index_of(slot: AnimationSlot, name: &str) -> Option<usize> {+ shapes(slot).iter().position(|shape| shape.name == name)+}++/// The engine's keys for everything set on `clip`, over its current+/// length, or None when nothing is set. In and Out keys are placed over+/// their slot's seconds at the head and tail; a Combo runs the whole clip.+/// A slot longer than the clip is squeezed to it, and a head and tail that+/// would overlap share the clip in half.+pub fn animation_of(clip: &Clip) -> Option<Animation> {+ let duration = clip.duration.max(1e-6);+ let mut tracks: [Vec<Key>; 5] = Default::default();+ let mut any = false;++ let mut lay =+ |slot: AnimationSlot, set: &Option<ClipAnimation>, other: &Option<ClipAnimation>| {+ let Some(set) = set else { return };+ let Some(shape) = shapes(slot).iter().find(|shape| shape.name == set.preset) else {+ return;+ };+ // The slot's share of the clip, as a fraction of its length.+ let mut span = (set.duration.max(0.05) / duration).min(1.0);+ if let Some(other) = other {+ let both = span + (other.duration.max(0.05) / duration).min(1.0);+ if both > 1.0 {+ span /= both;+ }+ }+ let (from, to) = match slot {+ AnimationSlot::In => (0.0, span),+ AnimationSlot::Out => (1.0 - span, 1.0),+ AnimationSlot::Combo => (0.0, 1.0),+ };+ for &(prop, at, value, ease) in shape.keys {+ let key = Key {+ at: from + (to - from) * at,+ value,+ ease,+ };+ tracks[match prop {+ Scale => 0,+ X => 1,+ Y => 2,+ Rotation => 3,+ Opacity => 4,+ }]+ .push(key);+ any = true;+ }+ };+ lay(AnimationSlot::In, &clip.animation_in, &clip.animation_out);+ lay(AnimationSlot::Out, &clip.animation_out, &clip.animation_in);+ lay(AnimationSlot::Combo, &clip.animation_combo, &None);+ if !any {+ return None;+ }+ let [scale, x, y, rotation, opacity] = tracks;+ Some(Animation {+ scale: Track::new(scale),+ offset_x: Track::new(x),+ offset_y: Track::new(y),+ rotation: Track::new(rotation),+ opacity: Track::new(opacity),+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{Command, Editor};++ #[test]+ fn every_slot_names_its_shapes_and_finds_them_again() {+ for slot in [AnimationSlot::In, AnimationSlot::Out, AnimationSlot::Combo] {+ let names = names(slot);+ assert!(!names.is_empty());+ for (index, name) in names.iter().enumerate() {+ assert_eq!(index_of(slot, name), Some(index));+ }+ assert_eq!(index_of(slot, "Nothing"), None);+ }+ }++ #[test]+ fn a_fade_in_lands_over_its_seconds_at_the_head() {+ let mut editor = Editor::new();+ let id = editor+ .apply(Command::AddTextClip {+ track_id: None,+ start: 0.0,+ style: None,+ duration: Some(4.0),+ offset_y: None,+ })+ .unwrap()+ .created_id+ .unwrap();+ editor+ .apply(Command::SetClipAnimation {+ clip_id: id.clone(),+ slot: AnimationSlot::In,+ animation: Some(ClipAnimation {+ preset: "Fade".to_owned(),+ duration: 1.0,+ }),+ })+ .unwrap();+ let clip = editor.project().active().clip(&id).unwrap();+ let animation = animation_of(clip).expect("a fade is set");+ // A second of a four-second clip: the fade is done by a quarter.+ assert!((animation.opacity_at(1.0, 0.0) - 0.0).abs() < 1e-9);+ assert!(animation.opacity_at(1.0, 0.125) > 0.0 && animation.opacity_at(1.0, 0.125) < 1.0);+ assert!((animation.opacity_at(1.0, 0.25) - 1.0).abs() < 1e-9);+ assert!((animation.opacity_at(1.0, 0.9) - 1.0).abs() < 1e-9);+ assert_eq!(animation.transform_at(Default::default(), 0.1).scale, 1.0);+ }+}diff --git a/engine/crates/concat-project/src/commands.rs b/engine/crates/concat-project/src/commands.rsindex 1530368a..931bb859 100644--- a/engine/crates/concat-project/src/commands.rs+++ b/engine/crates/concat-project/src/commands.rs@@ -12,8 +12,8 @@ use std::collections::HashSet;use serde::{Deserialize, Serialize};use crate::model::{- AppliedFilter, Clip, ClipKind, CustomFont, MediaItem, MediaKind, Project, SpeedPoint,- TextStyle, Timeline, Track, Transition,+ AnimationSlot, AppliedFilter, Clip, ClipAnimation, ClipKind, CustomFont, MediaItem, MediaKind,+ Project, SpeedPoint, TextStyle, Timeline, Track, Transition,};/// Fallback length for media whose container reports no duration.@@ -278,6 +278,15 @@ pub enum Command {/// The curve, or None for a constant rate at the current mean.curve: Option<Vec<SpeedPoint>>,},+ /// Sets or clears the animation on one slot of a clip.+ SetClipAnimation {+ /// The clip.+ clip_id: String,+ /// Which end, or the whole.+ slot: AnimationSlot,+ /// The shape and its seconds, or None to take it off.+ animation: Option<ClipAnimation>,+ },/// Repositions any number of clips in one edit - one undo step for a/// whole multi-selection drag. Unknown clips and tracks are tolerated/// per [`ClipMove`].@@ -573,6 +582,9 @@ fn default_clip(id: String, track_id: String, media: &MediaItem, start: f64) ->preserve_pitch: true,speed_curve: None,reverse: false,+ animation_in: None,+ animation_out: None,+ animation_combo: None,filters: Vec::new(),video_effects: Vec::new(),muted: None,@@ -907,6 +919,9 @@ pub fn apply(preserve_pitch: true,speed_curve: None,reverse: false,+ animation_in: None,+ animation_out: None,+ animation_combo: None,filters: Vec::new(),video_effects: Vec::new(),muted: None,@@ -964,6 +979,9 @@ pub fn apply(preserve_pitch: true,speed_curve: None,reverse: false,+ animation_in: None,+ animation_out: None,+ animation_combo: None,filters: Vec::new(),video_effects: vec![AppliedFilter {id: effect_id,@@ -1201,6 +1219,33 @@ pub fn apply(})}+ Command::SetClipAnimation {+ clip_id,+ slot,+ animation,+ } => {+ let timeline = project.active_mut();+ let Some(clip) = timeline.clip_mut(&clip_id) else {+ return Ok(Outcome::default());+ };+ let animation = animation+ .filter(|set| crate::animation::index_of(slot, &set.preset).is_some())+ .map(|set| ClipAnimation {+ preset: set.preset,+ duration: set.duration.clamp(0.05, 60.0),+ });+ let field = match slot {+ AnimationSlot::In => &mut clip.animation_in,+ AnimationSlot::Out => &mut clip.animation_out,+ AnimationSlot::Combo => &mut clip.animation_combo,+ };+ let applied = assign(field, animation);+ Ok(Outcome {+ created_id: None,+ applied,+ })+ }+Command::SetClipSpeedCurve { clip_id, curve } => {let timeline = project.active_mut();let Some(clip) = timeline.clip_mut(&clip_id) else {diff --git a/engine/crates/concat-project/src/doc.rs b/engine/crates/concat-project/src/doc.rsindex fb8d1ed0..05bff22e 100644--- a/engine/crates/concat-project/src/doc.rs+++ b/engine/crates/concat-project/src/doc.rs@@ -21,8 +21,8 @@use serde_json::{Map, Value, json};use crate::model::{- AppliedFilter, Clip, ClipKind, CustomFont, MediaItem, MediaKind, Project, SpeedPoint,- TextAlign, TextStyle, Timeline, Track, Transition,+ AppliedFilter, Clip, ClipAnimation, ClipKind, CustomFont, MediaItem, MediaKind, Project,+ SpeedPoint, TextAlign, TextStyle, Timeline, Track, Transition,};/// Bumped only when a change cannot be absorbed by defaulting.@@ -230,6 +230,9 @@ fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec(!points.is_empty()).then_some(points)}),reverse: flag(entry.get("reverse"), false),+ animation_in: read_animation(entry.get("animationIn")),+ animation_out: read_animation(entry.get("animationOut")),+ animation_combo: read_animation(entry.get("animationCombo")),preserve_pitch: flag(entry.get("preservePitch"), true),filters: read_filters(entry.get("filters")),video_effects: read_filters(entry.get("videoEffects")),@@ -384,3 +387,16 @@ pub fn to_document(settings: &DocumentSettings, project: &Project) -> Value {document.insert("activeTimelineId".into(), json!(project.active_timeline_id));Value::Object(document)}++/// A named animation on a slot, or None when the entry says nothing usable.+fn read_animation(value: Option<&Value>) -> Option<ClipAnimation> {+ let value = value?;+ let preset = value.get("preset")?.as_str()?.trim().to_owned();+ if preset.is_empty() {+ return None;+ }+ Some(ClipAnimation {+ preset,+ duration: number(value.get("duration"), 0.5).max(0.0),+ })+}diff --git a/engine/crates/concat-project/src/lib.rs b/engine/crates/concat-project/src/lib.rsindex 8156c7b5..57b5dcbf 100644--- a/engine/crates/concat-project/src/lib.rs+++ b/engine/crates/concat-project/src/lib.rs@@ -21,6 +21,7 @@//! document model needs serde, and concat-core's zero-dependency rule is worth//! more than the adjacency.+pub mod animation;pub mod commands;pub mod doc;pub mod editor;diff --git a/engine/crates/concat-project/src/model.rs b/engine/crates/concat-project/src/model.rsindex d2bbdc59..1ebbc606 100644--- a/engine/crates/concat-project/src/model.rs+++ b/engine/crates/concat-project/src/model.rs@@ -139,6 +139,30 @@ fn yes() -> bool {true}+/// Which end of a clip an animation belongs to, or the whole of it.+#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum AnimationSlot {+ /// The first seconds.+ In,+ /// The last seconds.+ Out,+ /// The whole clip.+ Combo,+}++/// A named animation on one slot. The keys are made from the name for the+/// clip's current length whenever they are needed; see the `animation`+/// module.+#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ClipAnimation {+ /// The shape's name, e.g. "Fade".+ pub preset: String,+ /// Seconds the shape takes, for In and Out; ignored by a Combo.+ pub duration: f64,+}+/// One point of a speed curve.#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]@@ -289,6 +313,15 @@ pub struct Clip {/// Played backwards.#[serde(default, skip_serializing_if = "is_false")]pub reverse: bool,+ /// How the clip comes in: a named shape over its first seconds.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub animation_in: Option<ClipAnimation>,+ /// How it goes out: a named shape over its last seconds.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub animation_out: Option<ClipAnimation>,+ /// A shape over its whole length.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub animation_combo: Option<ClipAnimation>,/// Keep voices at their natural pitch when `speed` is not 1. On by/// default; off gives the tape-machine chipmunk/slow-motion sound.pub preserve_pitch: bool,diff --git a/engine/crates/concat-render/src/plan.rs b/engine/crates/concat-render/src/plan.rsindex e31de458..6c9046b4 100644--- a/engine/crates/concat-render/src/plan.rs+++ b/engine/crates/concat-render/src/plan.rs@@ -87,8 +87,8 @@ pub fn plan_frame(timeline: &Timeline, time: Rational) -> FramePlan {speed: clip.speed,// The fade ramp multiplies in here, so the compositor only ever// sees a per-frame opacity - it has no idea fades exist.- opacity: (clip.opacity * clip.video_fade_factor(time)).clamp(0.0, 1.0),- transform: clip.transform,+ opacity: (clip.opacity_at(time) * clip.video_fade_factor(time)).clamp(0.0, 1.0),+ transform: clip.transform_at(time),paced: clip.is_paced(),});}diff --git a/engine/crates/concat/src/studio.rs b/engine/crates/concat/src/studio.rsindex a89b1767..48bcd2b7 100644--- a/engine/crates/concat/src/studio.rs+++ b/engine/crates/concat/src/studio.rs@@ -643,6 +643,40 @@ fn format_of(unit: &str) -> ParamFormat {}}+/// The menu row of a slot's animation: -1 for none.+fn slot_index(+ slot: concat_project::model::AnimationSlot,+ set: &Option<concat_project::model::ClipAnimation>,+) -> i32 {+ set.as_ref()+ .and_then(|set| concat_project::animation::index_of(slot, &set.preset))+ .map(|index| index as i32)+ .unwrap_or(-1)+}++/// A slot set from its menu row: -1 takes it off, else the row's shape at+/// the length already set or `seconds`.+fn set_slot(+ slot: concat_project::model::AnimationSlot,+ field: &mut Option<concat_project::model::ClipAnimation>,+ row: f64,+ seconds: f64,+) {+ if row < 0.0 {+ *field = None;+ return;+ }+ let names = concat_project::animation::names(slot);+ let Some(name) = names.get(row as usize) else {+ return;+ };+ let duration = field.as_ref().map(|set| set.duration).unwrap_or(seconds);+ *field = Some(concat_project::model::ClipAnimation {+ preset: (*name).to_owned(),+ duration,+ });+}+/// The built-in colour package's id; see `adjust_rows` and `Studio::adjust_set`.const ADJUST_ID: &str = "concat.adjust";@@ -2138,6 +2172,34 @@ impl Studio {}ClipField::PreservePitch => clip.preserve_pitch = value != 0.0,ClipField::Reverse => clip.reverse = value != 0.0,+ ClipField::AnimIn => set_slot(+ concat_project::model::AnimationSlot::In,+ &mut clip.animation_in,+ value,+ 0.5,+ ),+ ClipField::AnimOut => set_slot(+ concat_project::model::AnimationSlot::Out,+ &mut clip.animation_out,+ value,+ 0.5,+ ),+ ClipField::AnimCombo => set_slot(+ concat_project::model::AnimationSlot::Combo,+ &mut clip.animation_combo,+ value,+ clip.duration,+ ),+ ClipField::AnimInDuration => {+ if let Some(set) = clip.animation_in.as_mut() {+ set.duration = value.clamp(0.05, 60.0);+ }+ }+ ClipField::AnimOutDuration => {+ if let Some(set) = clip.animation_out.as_mut() {+ set.duration = value.clamp(0.05, 60.0);+ }+ }ClipField::SpeedCurve => {// The same arithmetic as the command: the source covered is// held, so the length follows the curve's mean.@@ -2294,6 +2356,31 @@ impl Studio {if after.reverse != before.reverse {patch.reverse = Some(after.reverse);}+ for (slot, now, was) in [+ (+ concat_project::model::AnimationSlot::In,+ &after.animation_in,+ &before.animation_in,+ ),+ (+ concat_project::model::AnimationSlot::Out,+ &after.animation_out,+ &before.animation_out,+ ),+ (+ concat_project::model::AnimationSlot::Combo,+ &after.animation_combo,+ &before.animation_combo,+ ),+ ] {+ if now != was {+ commands.push(Command::SetClipAnimation {+ clip_id: id.clone(),+ slot,+ animation: now.clone(),+ });+ }+ }if after.text != before.text {patch.text = Some(after.text.clone());}@@ -2379,12 +2466,28 @@ impl Studio {None => (clip.scale, clip.scale),}};- Footprint {- cx: 0.5 + clip.offset_x,- cy: 0.5 + clip.offset_y,- w,- h,+ // The placement at the playhead: the clip's own, moved by its+ // animation, so the box follows a slide or a spin.+ let base = concat_core::timeline::Transform {+ scale: clip.scale,+ offset_x: clip.offset_x,+ offset_y: clip.offset_y,rotation: clip.rotation,+ };+ let placed = match concat_project::animation::animation_of(clip) {+ Some(animation) if clip.duration > 0.0 => {+ let x = ((f64::from(self.playhead) - clip.start) / clip.duration).clamp(0.0, 1.0);+ animation.transform_at(base, x)+ }+ _ => base,+ };+ let factor = placed.scale / clip.scale.max(1e-6);+ Footprint {+ cx: 0.5 + placed.offset_x,+ cy: 0.5 + placed.offset_y,+ w: w * factor,+ h: h * factor,+ rotation: placed.rotation,}}@@ -3706,6 +3809,25 @@ impl Studio {.unwrap_or(concat_project::speed::PRESETS.len() as i32),},reverse: clip.reverse,+ anim_in: slot_index(concat_project::model::AnimationSlot::In, &clip.animation_in),+ anim_out: slot_index(+ concat_project::model::AnimationSlot::Out,+ &clip.animation_out,+ ),+ anim_combo: slot_index(+ concat_project::model::AnimationSlot::Combo,+ &clip.animation_combo,+ ),+ anim_in_duration: clip+ .animation_in+ .as_ref()+ .map(|set| set.duration as f32)+ .unwrap_or(0.5),+ anim_out_duration: clip+ .animation_out+ .as_ref()+ .map(|set| set.duration as f32)+ .unwrap_or(0.5),fade_in: clip.fade_in as f32,fade_out: clip.fade_out as f32,content: text.content.as_str().into(),diff --git a/engine/crates/concat/ui/inspector/clip-inspector.slint b/engine/crates/concat/ui/inspector/clip-inspector.slintindex 6a3d1a39..9dd2623e 100644--- a/engine/crates/concat/ui/inspector/clip-inspector.slint+++ b/engine/crates/concat/ui/inspector/clip-inspector.slint@@ -611,6 +611,105 @@ export component SpeedPanel inherits VerticalLayout {}}+/// Animation: how the clip comes in, goes out, and moves in between. Each+/// slot is a named shape from Rust's list and, for the head and tail, the+/// seconds it takes. The shapes are keys on the clip's own placement, so+/// the stage box follows them at the playhead.+export component AnimationPanel inherits VerticalLayout {+ in property <SelectedClipData> selected;++ callback set(field: ClipField, value: float);+ callback commit();++ property <[string]> in-shapes: ["None", "Fade", "Zoom In", "Zoom Out",+ "Slide Up", "Slide Down", "Slide Left", "Slide Right", "Spin"];+ property <[string]> out-shapes: ["None", "Fade", "Zoom In", "Zoom Out",+ "Slide Up", "Slide Down", "Slide Left", "Slide Right", "Spin"];+ property <[string]> combo-shapes: ["None", "Pulse", "Shake", "Spin", "Bounce", "Drift"];++ property <float> in-seconds;+ property <float> out-seconds;+ function seed() {+ root.in-seconds = root.selected.anim-in-duration;+ root.out-seconds = root.selected.anim-out-duration;+ }+ init => { root.seed(); }+ changed selected => { root.seed(); }++ /// The longest a head or tail shape may take: half the clip, so the+ /// two cannot cross.+ property <float> limit: Math.max(0.1, Math.min(10, root.selected.duration / 2));+ property <bool> help;++ Section {+ first: true;+ SectionHeader {+ title: "In";+ HelpButton {+ open: root.help;+ toggled => { root.help = self.open; }+ }+ }+ if root.help: Note {+ text: "In and Out play over the clip's first and last seconds;"+ + " Combo runs its whole length. Each moves the clip from"+ + " where you placed it, so position it first.";+ }+ Row {+ label: "Shape";+ Select {+ options: root.in-shapes;+ current: root.selected.anim-in + 1;+ changed(index) => { root.set(ClipField.anim-in, index - 1); root.commit(); }+ }+ }+ if root.selected.anim-in >= 0: Param {+ label: "Length";+ value <=> root.in-seconds;+ minimum: 0.1;+ maximum: root.limit;+ step: 0.05;+ default-value: 0.5;+ fmt: ParamFormat.seconds2;+ changed(v) => { root.set(ClipField.anim-in-duration, v); root.commit(); }+ }+ }++ Section {+ SectionHeader { title: "Out"; }+ Row {+ label: "Shape";+ Select {+ options: root.out-shapes;+ current: root.selected.anim-out + 1;+ changed(index) => { root.set(ClipField.anim-out, index - 1); root.commit(); }+ }+ }+ if root.selected.anim-out >= 0: Param {+ label: "Length";+ value <=> root.out-seconds;+ minimum: 0.1;+ maximum: root.limit;+ step: 0.05;+ default-value: 0.5;+ fmt: ParamFormat.seconds2;+ changed(v) => { root.set(ClipField.anim-out-duration, v); root.commit(); }+ }+ }++ Section {+ SectionHeader { title: "Combo"; }+ Row {+ label: "Shape";+ Select {+ options: root.combo-shapes;+ current: root.selected.anim-combo + 1;+ changed(index) => { root.set(ClipField.anim-combo, index - 1); root.commit(); }+ }+ }+ }+}+/// Adjust: the manual colour panel. Every knob is a parameter of the one/// built-in `concat.adjust` package, which Rust puts at the head of the/// picture's chain the first time a knob moves; until then the rows show thediff --git a/engine/crates/concat/ui/timeline/model.slint b/engine/crates/concat/ui/timeline/model.slintindex 709ab546..12e9dec6 100644--- a/engine/crates/concat/ui/timeline/model.slint+++ b/engine/crates/concat/ui/timeline/model.slint@@ -152,6 +152,7 @@ export enum TextAlignment { left, center, right }export enum ClipField {scale, offset-x, offset-y, rotation, opacity,volume, speed, preserve-pitch, speed-curve, reverse, fade-in, fade-out,+ anim-in, anim-out, anim-combo, anim-in-duration, anim-out-duration,font-size, font-weight, italic, text-opacity, align,stroke-width, shadow, line-height, tracking,}@@ -192,6 +193,14 @@ export struct SelectedClipData {/// presets' count for a custom shape.speed-curve: int,reverse: bool,++ // animation — a shape per slot, as an index into the slot's list, or+ // -1 for none; the seconds the head and tail shapes take+ anim-in: int,+ anim-out: int,+ anim-combo: int,+ anim-in-duration: float,+ anim-out-duration: float,fade-in: float,fade-out: float,diff --git a/engine/crates/concat/ui/workspace/config-pane.slint b/engine/crates/concat/ui/workspace/config-pane.slintindex eaeb0799..5a4e71f2 100644--- a/engine/crates/concat/ui/workspace/config-pane.slint+++ b/engine/crates/concat/ui/workspace/config-pane.slint@@ -6,7 +6,7 @@ import { Pane, PaneBody, PaneScroll } from "pane.slint";import { PaneKind, PaneSwitcher } from "pane-switcher.slint";import { EffectData } from "../demo/effects-panel.slint";import {- AdjustPanel, AppliedEntryData, AppliedParamData, AudioPanel,+ AdjustPanel, AnimationPanel, AppliedEntryData, AppliedParamData, AudioPanel,CatalogueEntryData, FilterPanel, PresetStack, SpeedPanel, VideoPanel,} from "../inspector/clip-inspector.slint";import { TextPanel } from "../inspector/text-panel.slint";@@ -168,11 +168,11 @@ export component ConfigPane inherits Rectangle {/// it has no transform, no gain and no rate, and every other tab could/// only say "nothing here".property <bool> is-layer: root.selected.kind == ClipKind.filter;- property <[string]> tabs: root.is-text ? ["Text"]+ property <[string]> tabs: root.is-text ? ["Text", "Animation"]: root.is-layer ? ["Filter"]- : root.is-image ? ["Video", "Adjust", "Filters", "Effects"]+ : root.is-image ? ["Video", "Animation", "Adjust", "Filters", "Effects"]: root.is-audio ? ["Audio", "Speed"]- : ["Video", "Audio", "Speed", "Adjust", "Filters", "Effects"];+ : ["Video", "Audio", "Speed", "Animation", "Adjust", "Filters", "Effects"];/// A one-segment segmented control is a label wearing a costume, so a lone/// tab renders as the panel's plain heading instead.property <bool> single: root.tabs.length < 2;@@ -392,6 +392,12 @@ export component ConfigPane inherits Rectangle {commit => { root.clip-commit(); }}+ if root.showing == "Animation": AnimationPanel {+ selected: root.selected;+ set(field, value) => { root.clip-set(field, value); }+ commit => { root.clip-commit(); }+ }+if root.showing == "Speed": SpeedPanel {selected: root.selected;set(field, value) => { root.clip-set(field, value); }