Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

Speed curves and reverse

Jareer6d9289c0d455
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index d828f0eb..eb38d830 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -1178,6 +1178,7 @@ dependencies = [
name = "concat-project"
version = "0.2.0"
dependencies = [
+ "concat-core",
"serde",
"serde_json",
"thiserror 2.0.20",
diff --git a/engine/crates/concat-core/src/lib.rs b/engine/crates/concat-core/src/lib.rs
index 36dd6948..310820c9 100644
--- a/engine/crates/concat-core/src/lib.rs
+++ b/engine/crates/concat-core/src/lib.rs
@@ -18,9 +18,11 @@
pub mod arena;
pub mod frame;
+pub mod retime;
pub mod time;
pub mod timeline;
pub use frame::Frame;
+pub use retime::SpeedCurve;
pub use time::{FrameRate, Rational, TimeRange};
pub use timeline::{Clip, ClipId, Project, Timeline, Track, TrackId, TrackKind};
diff --git a/engine/crates/concat-core/src/retime.rs b/engine/crates/concat-core/src/retime.rs
new file mode 100644
index 00000000..238de2b4
--- /dev/null
+++ b/engine/crates/concat-core/src/retime.rs
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! Speed that changes over a clip.
+//!
+//! A constant speed is one number. A *curve* is speed as a function of where
+//! in the clip you are: a handful of points, `(x, speed)` with `x` the
+//! fraction of the clip's timeline length, joined by straight lines. The
+//! source time at any instant is then the area under that line up to it -
+//! which is why the curve lives here, beside the clip's affine map: it is the
+//! same fact, and every renderer has to agree with it.
+//!
+//! The units are deliberately relative. A curve stored as fractions means
+//! the same thing after the clip is trimmed or the project re-timed, and a
+//! preset can be applied to any clip without knowing how long it is.
+
+/// Speed over a clip, as points joined by straight lines.
+#[derive(Clone, PartialEq, Debug)]
+pub struct SpeedCurve {
+ /// `(x, speed)` with `x` in `0..=1` ascending and speed positive.
+ points: Vec<(f64, f64)>,
+}
+
+impl SpeedCurve {
+ /// The floor a curve's speed is held at: a stop would consume no source
+ /// and the map would stop being invertible.
+ pub const MIN_SPEED: f64 = 0.0625;
+ /// And the ceiling, matching the constant rate's.
+ pub const MAX_SPEED: f64 = 16.0;
+
+ /// A curve through these points, tidied: sorted by `x`, clamped into the
+ /// unit interval and the speed range, and anchored at both ends so the
+ /// line covers the whole clip. Fewer than one point is `None`.
+ pub fn new(points: &[(f64, f64)]) -> Option<SpeedCurve> {
+ let mut points: Vec<(f64, f64)> = points
+ .iter()
+ .filter(|(x, speed)| x.is_finite() && speed.is_finite())
+ .map(|&(x, speed)| {
+ (
+ x.clamp(0.0, 1.0),
+ speed.clamp(Self::MIN_SPEED, Self::MAX_SPEED),
+ )
+ })
+ .collect();
+ if points.is_empty() {
+ return None;
+ }
+ points.sort_by(|a, b| a.0.total_cmp(&b.0));
+ if points[0].0 > 0.0 {
+ points.insert(0, (0.0, points[0].1));
+ }
+ if points[points.len() - 1].0 < 1.0 {
+ points.push((1.0, points[points.len() - 1].1));
+ }
+ Some(SpeedCurve { points })
+ }
+
+ /// The points, as tidied.
+ pub fn points(&self) -> &[(f64, f64)] {
+ &self.points
+ }
+
+ /// Speed at `x`, a fraction of the clip's length.
+ pub fn speed_at(&self, x: f64) -> f64 {
+ let x = x.clamp(0.0, 1.0);
+ for pair in self.points.windows(2) {
+ let (x0, v0) = pair[0];
+ let (x1, v1) = pair[1];
+ if x <= x1 {
+ if x1 <= x0 {
+ return v1;
+ }
+ return v0 + (v1 - v0) * (x - x0) / (x1 - x0);
+ }
+ }
+ self.points[self.points.len() - 1].1
+ }
+
+ /// The area under the curve from the start to `x`: how much of the
+ /// source, as a fraction of the clip's timeline length, has been consumed
+ /// by then. Each segment is a trapezoid, so this is exact.
+ pub fn consumed(&self, x: f64) -> f64 {
+ let x = x.clamp(0.0, 1.0);
+ let mut area = 0.0;
+ for pair in self.points.windows(2) {
+ let (x0, v0) = pair[0];
+ let x1 = pair[1].0;
+ if x <= x0 {
+ break;
+ }
+ let end = x.min(x1);
+ let v_end = self.speed_at(end);
+ area += (end - x0) * (v0 + v_end) / 2.0;
+ if x <= x1 {
+ break;
+ }
+ }
+ area
+ }
+
+ /// The average speed: source seconds consumed per timeline second over
+ /// the whole clip.
+ pub fn mean(&self) -> f64 {
+ self.consumed(1.0).max(Self::MIN_SPEED)
+ }
+
+ /// The clip cut into `count` equal timeline pieces, each `(x0, x1,
+ /// consumed_at_x0, mean_speed)` - the constant-rate approximation a
+ /// sound path that can only change tempo in steps needs.
+ pub fn pieces(&self, count: usize) -> Vec<(f64, f64, f64, f64)> {
+ let count = count.max(1);
+ (0..count)
+ .map(|index| {
+ let x0 = index as f64 / count as f64;
+ let x1 = (index + 1) as f64 / count as f64;
+ let from = self.consumed(x0);
+ let to = self.consumed(x1);
+ (x0, x1, from, ((to - from) / (x1 - x0)).max(Self::MIN_SPEED))
+ })
+ .collect()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_flat_curve_is_a_constant_speed() {
+ let curve = SpeedCurve::new(&[(0.0, 2.0), (1.0, 2.0)]).unwrap();
+ assert_eq!(curve.speed_at(0.3), 2.0);
+ assert!((curve.consumed(0.5) - 1.0).abs() < 1e-12);
+ assert!((curve.mean() - 2.0).abs() < 1e-12);
+ }
+
+ #[test]
+ fn the_ends_are_anchored_and_the_area_is_exact() {
+ // Speed ramps from 1 to 3 over the clip: the area is the trapezoid.
+ let curve = SpeedCurve::new(&[(0.25, 1.0), (0.75, 3.0)]).unwrap();
+ assert_eq!(curve.points()[0], (0.0, 1.0));
+ assert_eq!(curve.points()[curve.points().len() - 1], (1.0, 3.0));
+ assert!((curve.speed_at(0.5) - 2.0).abs() < 1e-12);
+ // 0..0.25 at 1, 0.25..0.75 averaging 2, 0.75..1 at 3.
+ assert!((curve.mean() - (0.25 + 1.0 + 0.75)).abs() < 1e-12);
+ assert!((curve.consumed(0.5) - (0.25 + 0.25 * 1.5)).abs() < 1e-12);
+ }
+
+ #[test]
+ fn pieces_add_up_to_the_whole() {
+ let curve = SpeedCurve::new(&[(0.0, 0.5), (0.5, 4.0), (1.0, 0.5)]).unwrap();
+ let pieces = curve.pieces(8);
+ assert_eq!(pieces.len(), 8);
+ let total: f64 = pieces
+ .iter()
+ .map(|(x0, x1, _, mean)| (x1 - x0) * mean)
+ .sum();
+ assert!((total - curve.mean()).abs() < 1e-9);
+ assert!((pieces[3].2 - curve.consumed(3.0 / 8.0)).abs() < 1e-12);
+ }
+
+ #[test]
+ fn nonsense_is_tidied_or_refused() {
+ assert!(SpeedCurve::new(&[]).is_none());
+ let curve = SpeedCurve::new(&[(2.0, 0.0), (-1.0, 100.0)]).unwrap();
+ assert_eq!(curve.points()[0], (0.0, SpeedCurve::MAX_SPEED));
+ assert_eq!(curve.points()[1], (1.0, SpeedCurve::MIN_SPEED));
+ }
+}
diff --git a/engine/crates/concat-core/src/timeline.rs b/engine/crates/concat-core/src/timeline.rs
index b6b3d471..530cf485 100644
--- a/engine/crates/concat-core/src/timeline.rs
+++ b/engine/crates/concat-core/src/timeline.rs
@@ -13,6 +13,7 @@
use std::path::{Path, PathBuf};
use crate::arena::{Arena, Id};
+use crate::retime::SpeedCurve;
use crate::time::{FrameRate, Rational, TimeRange};
/// Handle to a [`Track`].
@@ -83,6 +84,13 @@ pub struct Clip {
pub video_fade_out: Rational,
/// How the picture sits in the frame. Identity is fitted and centred.
pub transform: Transform,
+ /// Speed as it changes over the clip, when it does. Overrides `speed`
+ /// for the time map; `speed` is then the curve's mean, kept so a sound
+ /// path that needs one number has one. See [`SpeedCurve`].
+ pub retime: Option<SpeedCurve>,
+ /// Played backwards: the source is consumed from its far end towards
+ /// `source_start`.
+ pub reverse: bool,
}
/// A clip's placement in the output frame.
@@ -137,6 +145,8 @@ impl Clip {
video_fade_in: Rational::ZERO,
video_fade_out: Rational::ZERO,
transform: Transform::IDENTITY,
+ retime: None,
+ reverse: false,
}
}
@@ -177,13 +187,47 @@ impl Clip {
/// piece of arithmetic that every trim, ripple, slip and retime operation
/// ultimately has to agree with, so it lives in exactly one place.
pub fn source_time_at(&self, time: Rational) -> Option<Rational> {
- self.contains(time)
- .then(|| self.source_start + (time - self.start) * self.speed)
+ if !self.contains(time) {
+ return None;
+ }
+ let forward = match &self.retime {
+ // The area under the curve, in fractions of the clip's length,
+ // scaled back to seconds. Approximated to a rational at the end
+ // so the rest of the arithmetic stays exact.
+ Some(curve) => {
+ let x = ((time - self.start) / self.duration).as_f64();
+ let consumed = curve.consumed(x) * self.duration.as_f64();
+ Rational::approximate(consumed).unwrap_or(Rational::ZERO)
+ }
+ None => (time - self.start) * self.speed,
+ };
+ Some(if self.reverse {
+ // From the far end back: the last instant lands on the first
+ // source frame, and the first on the frame just short of the
+ // end, which is the one a forward play would have shown last.
+ let span = self.source_duration();
+ let back = span - forward;
+ self.source_start + back.clamp_to(Rational::ZERO, span)
+ } else {
+ self.source_start + forward
+ })
+ }
+
+ /// How much of the source this clip consumes: `duration * speed`, or the
+ /// area under the curve when there is one.
+ pub fn source_duration(&self) -> Rational {
+ match &self.retime {
+ Some(curve) => Rational::approximate(curve.mean() * self.duration.as_f64())
+ .unwrap_or(self.duration),
+ None => self.duration * self.speed,
+ }
}
- /// How much of the source this clip consumes: `duration * speed`.
- pub fn source_duration(&self) -> Rational {
- self.duration * self.speed
+ /// Whether a decoder can be paced at one rate for this clip: false when
+ /// the speed changes over it or it runs backwards, in which case every
+ /// frame has to be sought by its own source time.
+ pub fn is_paced(&self) -> bool {
+ self.retime.is_none() && !self.reverse
}
}
@@ -376,6 +420,7 @@ impl Project {
#[cfg(test)]
mod tests {
use super::*;
+ use crate::retime::SpeedCurve;
fn seconds(value: i64) -> Rational {
Rational::from_int(value)
@@ -408,6 +453,38 @@ mod tests {
);
}
+ /// A curve makes the map the area under the speed line, and a reverse
+ /// walks it from the far end; both keep the source covered the same.
+ #[test]
+ fn a_curve_bends_the_map_and_a_reverse_walks_it_backwards() {
+ let mut clip = Clip::new(
+ MediaRef::new("a.mp4"),
+ Rational::ZERO,
+ Rational::from_int(10),
+ );
+ // Half speed for the first half, double for the second: 2.5 s of
+ // source in the first 5 s of timeline, 10 s in the second.
+ clip.retime = SpeedCurve::new(&[(0.0, 0.5), (0.5, 0.5), (0.5, 2.0), (1.0, 2.0)]);
+ fn at(clip: &Clip, seconds: i64) -> f64 {
+ clip.source_time_at(Rational::from_int(seconds))
+ .unwrap()
+ .as_f64()
+ }
+ assert!((at(&clip, 5) - 2.5).abs() < 1e-6);
+ assert!((at(&clip, 9) - 10.5).abs() < 1e-3);
+ assert!((clip.source_duration().as_f64() - 12.5).abs() < 1e-6);
+ assert!(!clip.is_paced());
+
+ clip.retime = None;
+ clip.speed = Rational::from_int(2);
+ clip.reverse = true;
+ // Backwards at 2x over 10 s covers 20 s of source: the start shows
+ // the far end, the middle the middle.
+ assert!((at(&clip, 0) - 20.0).abs() < 1e-9);
+ assert!((at(&clip, 5) - 10.0).abs() < 1e-9);
+ assert!(!clip.is_paced());
+ }
+
#[test]
fn speed_scales_the_source_time_map() {
let (mut timeline, _, id) = fixture();
diff --git a/engine/crates/concat-export/src/flatten.rs b/engine/crates/concat-export/src/flatten.rs
index 23415c9b..6b00dee0 100644
--- a/engine/crates/concat-export/src/flatten.rs
+++ b/engine/crates/concat-export/src/flatten.rs
@@ -58,6 +58,8 @@ pub fn flatten_timeline(project: &Project, timeline_id: Option<&str>) -> Vec<Exp
filter_chain: String::new(),
speed: 1.0,
preserve_pitch: true,
+ speed_curve: Vec::new(),
+ reverse: false,
scale: 1.0,
offset_x: 0.0,
offset_y: 0.0,
@@ -96,6 +98,14 @@ pub fn flatten_timeline(project: &Project, timeline_id: Option<&str>) -> Vec<Exp
filter_chain: audio_filter_chain(&clip.filters),
speed: clip.speed,
preserve_pitch: clip.preserve_pitch,
+ speed_curve: clip
+ .speed_curve
+ .as_deref()
+ .unwrap_or(&[])
+ .iter()
+ .map(|point| (point.at, point.speed))
+ .collect(),
+ reverse: clip.reverse,
scale: clip.scale,
offset_x: clip.offset_x,
offset_y: clip.offset_y,
diff --git a/engine/crates/concat-export/src/lib.rs b/engine/crates/concat-export/src/lib.rs
index 59554f3e..8d76ab47 100644
--- a/engine/crates/concat-export/src/lib.rs
+++ b/engine/crates/concat-export/src/lib.rs
@@ -27,6 +27,7 @@ use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
+use concat_core::SpeedCurve;
use concat_core::frame::Frame;
use concat_core::time::{FrameRate, Rational};
use concat_core::timeline::{Clip, ClipId, MediaRef, Timeline, Track, TrackKind, Transform};
@@ -97,6 +98,13 @@ pub struct ExportClip {
/// False lets pitch rise with the rate, like tape.
#[serde(default = "yes")]
pub preserve_pitch: bool,
+ /// Speed over the clip as `(at, speed)` points, `at` a fraction of the
+ /// clip's length; empty for the constant `speed`. See `SpeedCurve`.
+ #[serde(default)]
+ pub speed_curve: Vec<(f64, f64)>,
+ /// Played backwards.
+ #[serde(default)]
+ pub reverse: bool,
/// Multiplier over the fitted size. 1 fills the frame, preserving aspect.
#[serde(default = "unity")]
pub scale: f64,
@@ -422,7 +430,7 @@ pub fn render(request: &ExportRequest, mut reporter: Reporter<'_>) -> Result<Str
reporter.cancelled()?;
reporter.emit(0, total_frames, "mixing audio");
- let mix: Vec<AudioClip> = sound.iter().map(|clip| audio_clip(clip)).collect();
+ let mix: Vec<AudioClip> = sound.iter().flat_map(|clip| audio_pieces(clip)).collect();
audio::mix_to_file(&mix, timeline_end, &mixed).map_err(|error| error.to_string())?;
reporter.cancelled()?;
@@ -436,20 +444,72 @@ pub fn render(request: &ExportRequest, mut reporter: Reporter<'_>) -> Result<Str
result.map(|()| output.to_string_lossy().into_owned())
}
-/// The engine's view of one audible clip.
-fn audio_clip(clip: &ExportClip) -> AudioClip {
- AudioClip {
- path: PathBuf::from(&clip.path),
- start: clip.start,
- duration: clip.duration,
- source_start: clip.source_start,
- speed: audio::clamp_speed(clip.speed),
- preserve_pitch: clip.preserve_pitch,
- volume: clip.volume,
- fade_in: clip.fade_in,
- fade_out: clip.fade_out,
- filter_chain: clip.filter_chain.clone(),
+/// The engine's view of one audible clip - or several, when its speed
+/// changes over it. Sound can only change tempo in steps, so a curve is cut
+/// into pieces of constant rate, each at the mean of its stretch of the
+/// curve and starting where the curve says the source had got to. A reverse
+/// runs the pieces' sound backwards, and the pieces themselves in reverse
+/// order of source, which is what playing the clip backwards means.
+pub fn audio_pieces(clip: &ExportClip) -> Vec<AudioClip> {
+ let mut chain = clip.filter_chain.clone();
+ if clip.reverse {
+ chain = if chain.is_empty() {
+ "areverse".to_owned()
+ } else {
+ format!("areverse,{chain}")
+ };
}
+ let Some(curve) = SpeedCurve::new(&clip.speed_curve) else {
+ return vec![AudioClip {
+ path: PathBuf::from(&clip.path),
+ start: clip.start,
+ duration: clip.duration,
+ source_start: clip.source_start,
+ speed: audio::clamp_speed(clip.speed),
+ preserve_pitch: clip.preserve_pitch,
+ volume: clip.volume,
+ fade_in: clip.fade_in,
+ fade_out: clip.fade_out,
+ filter_chain: chain,
+ }];
+ };
+ // Pieces a tenth of a second long, or eight at least: fine enough that
+ // a tempo step is not heard, coarse enough that the graph stays small.
+ let count = ((clip.duration / 0.1).ceil() as usize).clamp(8, 400);
+ let span = curve.mean() * clip.duration;
+ curve
+ .pieces(count)
+ .into_iter()
+ .map(|(x0, x1, consumed, mean)| {
+ let piece_duration = (x1 - x0) * clip.duration;
+ let forward = consumed * clip.duration;
+ let source_start = if clip.reverse {
+ // Backwards: this piece plays the source that ends where the
+ // forward map had got to, so it starts one piece earlier.
+ clip.source_start + (span - forward - mean * piece_duration).max(0.0)
+ } else {
+ clip.source_start + forward
+ };
+ let piece_start = clip.start + x0 * clip.duration;
+ let piece_end = piece_start + piece_duration;
+ // The clip's fades, as they fall on this piece.
+ let fade_in = (clip.fade_in - x0 * clip.duration).clamp(0.0, piece_duration);
+ let fade_out_from = clip.start + clip.duration - clip.fade_out;
+ let fade_out = (piece_end - fade_out_from.max(piece_start)).clamp(0.0, piece_duration);
+ AudioClip {
+ path: PathBuf::from(&clip.path),
+ start: piece_start,
+ duration: piece_duration,
+ source_start,
+ speed: audio::clamp_speed(mean),
+ preserve_pitch: clip.preserve_pitch,
+ volume: clip.volume,
+ fade_in: if clip.fade_in > 0.0 { fade_in } else { 0.0 },
+ fade_out: if clip.fade_out > 0.0 { fade_out } else { 0.0 },
+ filter_chain: chain.clone(),
+ }
+ })
+ .collect()
}
/// The fraction-to-pixel placement of one composited layer: fitted and
@@ -532,6 +592,10 @@ fn render_picture(
// output frame keeps each of them in step with the plan's source times
// without any seeking - including retimed clips.
let mut decoders: HashMap<ClipId, Decoder> = HashMap::new();
+ // A clip whose speed changes, or runs backwards, cannot be followed by a
+ // paced decoder: each of its frames is sought by its own source time,
+ // through a pool that keeps the reader rolling where it can.
+ let sought = concat_media::ReaderPool::with_defaults();
for index in 0..total_frames {
reporter.cancelled()?;
@@ -542,6 +606,30 @@ fn render_picture(
let mut sources: Vec<(Frame, f32, Transform, usize)> =
Vec::with_capacity(plan.layers.len());
for layer in &plan.layers {
+ if !layer.paced {
+ let (decode_width, decode_height) = decode_sizes
+ .get(&layer.clip)
+ .copied()
+ .unwrap_or((request.width, request.height));
+ let chain = filter_chains.get(&layer.clip).map(String::as_str);
+ if let Ok(frame) = sought.frame_at(
+ &layer.media,
+ layer.source_time,
+ decode_width,
+ decode_height,
+ stills.contains(&layer.clip),
+ chain,
+ ) {
+ let track = tracks.get(&layer.clip).copied().unwrap_or(0);
+ sources.push((
+ frame.as_ref().clone(),
+ layer.opacity,
+ layer.transform,
+ track,
+ ));
+ }
+ continue;
+ }
let decoder = match decoders.entry(layer.clip) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
std::collections::hash_map::Entry::Vacant(entry) => {
@@ -799,6 +887,8 @@ fn build_timeline(
if clip.kind != ClipKind::Image {
engine_clip.speed =
Rational::approximate(audio::clamp_speed(clip.speed)).unwrap_or(Rational::ONE);
+ engine_clip.retime = SpeedCurve::new(&clip.speed_curve);
+ engine_clip.reverse = clip.reverse;
}
engine_clip.transform = Transform {
scale: clip.scale,
@@ -1130,7 +1220,7 @@ mod tests {
8,
Rational::from_int(1),
&sources,
- &[negate.clone()],
+ std::slice::from_ref(&negate),
);
// Red negated is cyan where nothing sits on top...
let at = |x: usize, y: usize| &out.pixels()[(y * 8 + x) * 4..(y * 8 + x) * 4 + 3];
@@ -1193,6 +1283,8 @@ mod tests {
filter_chain: String::new(),
speed: 1.0,
preserve_pitch: true,
+ speed_curve: Vec::new(),
+ reverse: false,
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.rs
index 46e0d43d..524eba8a 100644
--- a/engine/crates/concat-host/src/titles.rs
+++ b/engine/crates/concat-host/src/titles.rs
@@ -110,6 +110,8 @@ impl Titles {
filter_chain: String::new(),
speed: 1.0,
preserve_pitch: true,
+ speed_curve: Vec::new(),
+ reverse: false,
scale: clip.scale,
offset_x: clip.offset_x,
offset_y: clip.offset_y,
diff --git a/engine/crates/concat-project/Cargo.toml b/engine/crates/concat-project/Cargo.toml
index 3160a7a8..f0e51d3f 100644
--- a/engine/crates/concat-project/Cargo.toml
+++ b/engine/crates/concat-project/Cargo.toml
@@ -7,6 +7,8 @@ license.workspace = true
description = "The edit itself: the project document, its operations, and undo. The engine's ownership of the model."
[dependencies]
+# The speed curve's arithmetic lives with the engine's time map.
+concat-core.workspace = true
serde = { version = "1", features = ["derive"] }
serde_json.workspace = true
thiserror.workspace = true
diff --git a/engine/crates/concat-project/src/commands.rs b/engine/crates/concat-project/src/commands.rs
index a2d3f8a3..1530368a 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, TextStyle, Timeline,
- Track, Transition,
+ AppliedFilter, Clip, ClipKind, CustomFont, MediaItem, MediaKind, Project, SpeedPoint,
+ TextStyle, Timeline, Track, Transition,
};
/// Fallback length for media whose container reports no duration.
@@ -90,6 +90,9 @@ pub struct ClipPatch {
pub opacity: Option<f64>,
/// New pitch-preservation setting, taken as sent.
pub preserve_pitch: Option<bool>,
+ /// Play backwards.
+ #[serde(default)]
+ pub reverse: Option<bool>,
/// Wholesale replacement of the audio filter chain - the UI sends the
/// full list, not a diff.
pub filters: Option<Vec<AppliedFilter>>,
@@ -266,6 +269,15 @@ pub enum Command {
/// What the lane calls it.
name: String,
},
+ /// Gives a clip a speed curve, or takes it away. The source covered is
+ /// held constant, as a speed change does, so the clip's timeline length
+ /// follows the curve's mean; `speed` is kept at that mean.
+ SetClipSpeedCurve {
+ /// The clip to retime.
+ clip_id: String,
+ /// The curve, or None for a constant rate at the current mean.
+ curve: Option<Vec<SpeedPoint>>,
+ },
/// 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`].
@@ -559,6 +571,8 @@ fn default_clip(id: String, track_id: String, media: &MediaItem, start: f64) ->
opacity: 1.0,
speed: 1.0,
preserve_pitch: true,
+ speed_curve: None,
+ reverse: false,
filters: Vec::new(),
video_effects: Vec::new(),
muted: None,
@@ -891,6 +905,8 @@ pub fn apply(
opacity: 1.0,
speed: 1.0,
preserve_pitch: true,
+ speed_curve: None,
+ reverse: false,
filters: Vec::new(),
video_effects: Vec::new(),
muted: None,
@@ -946,6 +962,8 @@ pub fn apply(
opacity: 1.0,
speed: 1.0,
preserve_pitch: true,
+ speed_curve: None,
+ reverse: false,
filters: Vec::new(),
video_effects: vec![AppliedFilter {
id: effect_id,
@@ -1026,6 +1044,21 @@ pub fn apply(
let Some(index) = timeline.clips.iter().position(|clip| clip.id == clip_id) else {
continue;
};
+ {
+ // A curve or a reverse does not survive a cut in halves:
+ // the map from here to the source is not affine, so both
+ // halves go to the constant mean, which is what they
+ // averaged.
+ let clip = &mut timeline.clips[index];
+ let offset = time - clip.start;
+ if offset > MIN_CLIP_DURATION
+ && offset < clip.duration - MIN_CLIP_DURATION
+ && (clip.speed_curve.is_some() || clip.reverse)
+ {
+ clip.speed_curve = None;
+ clip.reverse = false;
+ }
+ }
let clip = &timeline.clips[index];
let offset = time - clip.start;
if offset <= MIN_CLIP_DURATION || offset >= clip.duration - MIN_CLIP_DURATION {
@@ -1120,6 +1153,9 @@ pub fn apply(
if let Some(preserve) = patch.preserve_pitch {
applied |= assign(&mut clip.preserve_pitch, preserve);
}
+ if let Some(reverse) = patch.reverse {
+ applied |= assign(&mut clip.reverse, reverse);
+ }
if let Some(filters) = patch.filters {
applied |= assign(&mut clip.filters, filters);
}
@@ -1151,11 +1187,37 @@ pub fn apply(
// makes this a speed change rather than a trim.
let next = speed.clamp(MIN_SPEED, MAX_SPEED);
let source_covered = clip.duration * clip.speed;
- // Bitwise so no assignment is short-circuited away.
+ // Bitwise so no assignment is short-circuited away. A rate set
+ // by hand is a constant rate: the curve goes.
let applied = assign(&mut clip.speed, next)
| assign(
&mut clip.duration,
(source_covered / next).max(MIN_CLIP_DURATION),
+ )
+ | assign(&mut clip.speed_curve, None);
+ 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 {
+ return Ok(Outcome::default());
+ };
+ let curve = curve.filter(|points| crate::speed::curve_of(points).is_some());
+ let source_covered = clip.duration * clip.speed;
+ let mean = curve
+ .as_ref()
+ .map(|points| crate::speed::mean_of(points))
+ .unwrap_or(clip.speed)
+ .clamp(MIN_SPEED, MAX_SPEED);
+ let applied = assign(&mut clip.speed_curve, curve)
+ | assign(&mut clip.speed, mean)
+ | assign(
+ &mut clip.duration,
+ (source_covered / mean).max(MIN_CLIP_DURATION),
);
Ok(Outcome {
created_id: None,
diff --git a/engine/crates/concat-project/src/doc.rs b/engine/crates/concat-project/src/doc.rs
index 7d92caba..fb8d1ed0 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, TextAlign, TextStyle,
- Timeline, Track, Transition,
+ AppliedFilter, Clip, ClipKind, CustomFont, MediaItem, MediaKind, Project, SpeedPoint,
+ TextAlign, TextStyle, Timeline, Track, Transition,
};
/// Bumped only when a change cannot be absorbed by defaulting.
@@ -217,6 +217,19 @@ fn read_clips(raw: Option<&Value>, tracks: &[Track], media: &[MediaItem]) -> Vec
// the preview clamps it on screen.
opacity: number(entry.get("opacity"), 1.0).clamp(0.0, 1.0),
speed: number(entry.get("speed"), 1.0).clamp(0.0625, 16.0),
+ speed_curve: entry.get("speedCurve").and_then(|value| {
+ let points: Vec<SpeedPoint> = value
+ .as_array()?
+ .iter()
+ .map(|point| SpeedPoint {
+ at: number(point.get("at"), -1.0),
+ speed: number(point.get("speed"), 1.0),
+ })
+ .filter(|point| (0.0..=1.0).contains(&point.at))
+ .collect();
+ (!points.is_empty()).then_some(points)
+ }),
+ reverse: flag(entry.get("reverse"), false),
preserve_pitch: flag(entry.get("preservePitch"), true),
filters: read_filters(entry.get("filters")),
video_effects: read_filters(entry.get("videoEffects")),
diff --git a/engine/crates/concat-project/src/lib.rs b/engine/crates/concat-project/src/lib.rs
index b1dd0269..8156c7b5 100644
--- a/engine/crates/concat-project/src/lib.rs
+++ b/engine/crates/concat-project/src/lib.rs
@@ -25,6 +25,7 @@ pub mod commands;
pub mod doc;
pub mod editor;
pub mod model;
+pub mod speed;
pub use commands::{Command, CommandError, Outcome, why_not_merge};
pub use doc::{DocumentSettings, from_document, to_document};
diff --git a/engine/crates/concat-project/src/model.rs b/engine/crates/concat-project/src/model.rs
index 159ab841..d2bbdc59 100644
--- a/engine/crates/concat-project/src/model.rs
+++ b/engine/crates/concat-project/src/model.rs
@@ -139,6 +139,16 @@ fn yes() -> bool {
true
}
+/// One point of a speed curve.
+#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct SpeedPoint {
+ /// Where in the clip, as a fraction of its timeline length, 0..=1.
+ pub at: f64,
+ /// Source seconds per timeline second there.
+ pub speed: f64,
+}
+
/// A transition on the cut into a clip.
#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -269,8 +279,16 @@ pub struct Clip {
pub rotation: f64,
/// Blend strength over whatever is beneath, in 0..1.
pub opacity: f64,
- /// Playback rate. 1 is normal.
+ /// Playback rate. 1 is normal. With a curve set this is the curve's
+ /// mean, kept in step by the commands that set either.
pub speed: f64,
+ /// Speed as it changes over the clip: points of `(at, speed)`, `at` a
+ /// fraction of the clip's timeline length. None is the constant rate.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub speed_curve: Option<Vec<SpeedPoint>>,
+ /// Played backwards.
+ #[serde(default, skip_serializing_if = "is_false")]
+ pub reverse: bool,
/// 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-project/src/speed.rs b/engine/crates/concat-project/src/speed.rs
new file mode 100644
index 00000000..b4fb50ed
--- /dev/null
+++ b/engine/crates/concat-project/src/speed.rs
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! Speed curves: the presets, and the arithmetic the commands share.
+//!
+//! The shapes are the ones editors' users know by name. Each is a handful
+//! of `(at, speed)` points over the clip, joined by straight lines; the
+//! engine's [`SpeedCurve`] turns them into a time map.
+
+use concat_core::SpeedCurve;
+
+use crate::model::SpeedPoint;
+
+/// The named shapes, in the order a menu lists them.
+pub const PRESETS: &[(&str, &[(f64, f64)])] = &[
+ // Fast, then a breath, then fast again, twice: a cut that keeps moving.
+ (
+ "Montage",
+ &[
+ (0.0, 1.0),
+ (0.2, 2.0),
+ (0.35, 0.5),
+ (0.5, 2.0),
+ (0.65, 0.5),
+ (0.8, 2.0),
+ (1.0, 1.0),
+ ],
+ ),
+ // Normal in, a held slow moment in the middle, normal out.
+ (
+ "Hero",
+ &[
+ (0.0, 1.0),
+ (0.35, 1.0),
+ (0.5, 0.25),
+ (0.65, 1.0),
+ (1.0, 1.0),
+ ],
+ ),
+ // Fast, slammed to slow, snapped back to fast.
+ (
+ "Bullet",
+ &[(0.0, 3.0), (0.4, 3.0), (0.5, 0.3), (0.6, 3.0), (1.0, 3.0)],
+ ),
+ // Normal with a skip through the middle.
+ (
+ "Jump Cut",
+ &[(0.0, 1.0), (0.45, 1.0), (0.5, 6.0), (0.55, 1.0), (1.0, 1.0)],
+ ),
+ // Rushes in, settles to normal.
+ (
+ "Flash In",
+ &[(0.0, 4.0), (0.2, 4.0), (0.35, 1.0), (1.0, 1.0)],
+ ),
+ // Normal, then rushes out.
+ (
+ "Flash Out",
+ &[(0.0, 1.0), (0.65, 1.0), (0.8, 4.0), (1.0, 4.0)],
+ ),
+];
+
+/// The preset at `index`, or None past the end.
+pub fn preset(index: usize) -> Option<Vec<SpeedPoint>> {
+ PRESETS.get(index).map(|(_, points)| {
+ points
+ .iter()
+ .map(|&(at, speed)| SpeedPoint { at, speed })
+ .collect()
+ })
+}
+
+/// Which preset `curve` is, or None for a custom shape.
+pub fn preset_of(curve: &[SpeedPoint]) -> Option<usize> {
+ PRESETS.iter().position(|(_, points)| {
+ points.len() == curve.len()
+ && points.iter().zip(curve).all(|(&(at, speed), point)| {
+ (point.at - at).abs() < 1e-9 && (point.speed - speed).abs() < 1e-9
+ })
+ })
+}
+
+/// The engine's curve for these points, or None when they make no curve.
+pub fn curve_of(points: &[SpeedPoint]) -> Option<SpeedCurve> {
+ let raw: Vec<(f64, f64)> = points
+ .iter()
+ .map(|point: &SpeedPoint| (point.at, point.speed))
+ .collect();
+ SpeedCurve::new(&raw)
+}
+
+/// Source seconds per timeline second over a whole clip with these points;
+/// the constant rate's equivalent for a curve.
+pub fn mean_of(points: &[SpeedPoint]) -> f64 {
+ curve_of(points).map(|curve| curve.mean()).unwrap_or(1.0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn presets_round_trip_and_average_sensibly() {
+ for (index, (name, _)) in PRESETS.iter().enumerate() {
+ let points = preset(index).expect("in range");
+ assert_eq!(preset_of(&points), Some(index), "{name}");
+ let mean = mean_of(&points);
+ assert!(mean > 0.2 && mean < 4.0, "{name} averages {mean}");
+ }
+ assert!(preset(PRESETS.len()).is_none());
+ assert_eq!(
+ preset_of(&[SpeedPoint {
+ at: 0.0,
+ speed: 7.0
+ }]),
+ None
+ );
+ }
+}
diff --git a/engine/crates/concat-render/src/plan.rs b/engine/crates/concat-render/src/plan.rs
index 7ecdcc59..e31de458 100644
--- a/engine/crates/concat-render/src/plan.rs
+++ b/engine/crates/concat-render/src/plan.rs
@@ -33,6 +33,9 @@ pub struct PlannedLayer {
pub opacity: f32,
/// The clip's placement in the frame, resolution-independent.
pub transform: Transform,
+ /// Whether one decoder paced at `output rate / speed` follows this clip;
+ /// false for a curve or a reverse, where each frame is sought.
+ pub paced: bool,
}
/// Everything needed to draw one output frame.
@@ -86,6 +89,7 @@ pub fn plan_frame(timeline: &Timeline, time: Rational) -> FramePlan {
// 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,
+ paced: clip.is_paced(),
});
}
diff --git a/engine/crates/concat/src/studio.rs b/engine/crates/concat/src/studio.rs
index 1a288e49..a89b1767 100644
--- a/engine/crates/concat/src/studio.rs
+++ b/engine/crates/concat/src/studio.rs
@@ -1094,17 +1094,20 @@ impl Studio {
|| (clip.kind == concat_export::ClipKind::Video
&& clip.has_audio.unwrap_or(true)))
})
- .map(|clip| ClipSpec {
- path: clip.path.clone(),
- start: clip.start,
- duration: clip.duration,
- source_start: clip.source_start,
- volume: clip.volume as f32,
- fade_in: clip.fade_in,
- fade_out: clip.fade_out,
- speed: clip.speed,
- preserve_pitch: clip.preserve_pitch,
- chain: clip.filter_chain.clone(),
+ // Through the exporter's own cut into pieces, so a curve or a
+ // reverse sounds in the window as it will in the file.
+ .flat_map(concat_export::audio_pieces)
+ .map(|piece| ClipSpec {
+ path: piece.path.to_string_lossy().into_owned(),
+ start: piece.start,
+ duration: piece.duration,
+ source_start: piece.source_start,
+ volume: piece.volume as f32,
+ fade_in: piece.fade_in,
+ fade_out: piece.fade_out,
+ speed: piece.speed,
+ preserve_pitch: piece.preserve_pitch,
+ chain: piece.filter_chain,
})
.collect();
self.host
@@ -2134,6 +2137,25 @@ impl Studio {
clip.speed = speed;
}
ClipField::PreservePitch => clip.preserve_pitch = value != 0.0,
+ ClipField::Reverse => clip.reverse = value != 0.0,
+ ClipField::SpeedCurve => {
+ // The same arithmetic as the command: the source covered is
+ // held, so the length follows the curve's mean.
+ let curve = if value < 0.0 {
+ None
+ } else {
+ concat_project::speed::preset(value as usize)
+ };
+ let covered = clip.duration * clip.speed;
+ let mean = curve
+ .as_ref()
+ .map(|points| concat_project::speed::mean_of(points))
+ .unwrap_or(clip.speed)
+ .clamp(0.0625, 16.0);
+ clip.speed_curve = curve;
+ clip.speed = mean;
+ clip.duration = (covered / mean).max(f64::from(MIN_DURATION));
+ }
ClipField::FadeIn => clip.fade_in = value.clamp(0.0, clip.duration / 2.0),
ClipField::FadeOut => clip.fade_out = value.clamp(0.0, clip.duration / 2.0),
ClipField::FontSize => text.font_size = value.clamp(0.01, 0.5),
@@ -2239,7 +2261,12 @@ impl Studio {
rotation: Some(after.rotation),
});
}
- if after.speed != before.speed {
+ if after.speed_curve != before.speed_curve {
+ commands.push(Command::SetClipSpeedCurve {
+ clip_id: id.clone(),
+ curve: after.speed_curve.clone(),
+ });
+ } else if after.speed != before.speed {
commands.push(Command::SetClipSpeed {
clip_id: id.clone(),
speed: after.speed,
@@ -2264,6 +2291,9 @@ impl Studio {
if after.preserve_pitch != before.preserve_pitch {
patch.preserve_pitch = Some(after.preserve_pitch);
}
+ if after.reverse != before.reverse {
+ patch.reverse = Some(after.reverse);
+ }
if after.text != before.text {
patch.text = Some(after.text.clone());
}
@@ -3669,6 +3699,13 @@ impl Studio {
volume: clip.volume as f32,
speed: clip.speed as f32,
preserve_pitch: clip.preserve_pitch,
+ speed_curve: match &clip.speed_curve {
+ None => -1,
+ Some(points) => concat_project::speed::preset_of(points)
+ .map(|index| index as i32)
+ .unwrap_or(concat_project::speed::PRESETS.len() as i32),
+ },
+ reverse: clip.reverse,
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.slint
index c34ecdf6..6a3d1a39 100644
--- a/engine/crates/concat/ui/inspector/clip-inspector.slint
+++ b/engine/crates/concat/ui/inspector/clip-inspector.slint
@@ -5,6 +5,7 @@ import { Theme } from "../theme/theme.slint";
import { Glyph, Icon } from "../icons.slint";
import { IconButton, Row, Section, SectionHeader } from "../primitives/panel.slint";
import { SegmentedControl } from "../primitives/segmented-control.slint";
+import { Select } from "../primitives/select.slint";
import {
Fader, HelpButton, InspectorFmt, InspectorSearch, Note, Param, ParamFormat,
SearchField, Switch, SwitchRow,
@@ -513,8 +514,7 @@ export component AudioPanel inherits VerticalLayout {
}
}
-/// Speed: the rate, and whether pitch follows it. Curves come later and
-/// will live here too.
+/// Speed: the rate or a curve, whether pitch follows it, and backwards.
export component SpeedPanel inherits VerticalLayout {
in property <SelectedClipData> selected;
@@ -527,6 +527,11 @@ export component SpeedPanel inherits VerticalLayout {
changed selected => { root.seed(); }
property <bool> speed-help;
+ /// The Select's rows: the constant rate first, then the shapes in the
+ /// order Rust keeps them, then Custom for a shape that is none of them.
+ property <[string]> curves: ["Normal", "Montage", "Hero", "Bullet",
+ "Jump Cut", "Flash In", "Flash Out", "Custom"];
+ property <bool> curved: root.selected.speed-curve >= 0;
Section {
first: true;
@@ -544,12 +549,35 @@ export component SpeedPanel inherits VerticalLayout {
if root.speed-help: Note {
text: "Rate re-times the clip in place, so the timeline length"
- + " changes with it. Trim afterwards, not before.";
+ + " changes with it. Trim afterwards, not before. A curve"
+ + " varies the rate over the clip; the same footage plays,"
+ + " faster here and slower there.";
+ }
+
+ Row {
+ label: "Curve";
+ Select {
+ options: root.curves;
+ // Custom is one past the presets; Rust says so with their
+ // count, which lands on the same row.
+ current: root.curved ? Math.min(root.selected.speed-curve + 1,
+ root.curves.length - 1) : 0;
+ changed(index) => {
+ // Custom cannot be chosen, only arrived at.
+ if (index < root.curves.length - 1) {
+ root.set(ClipField.speed-curve, index - 1);
+ root.commit();
+ }
+ }
+ }
}
Param {
label: "Rate";
value <=> root.speed;
+ // With a curve the rate is the curve's mean, read-only: the
+ // shape decides it.
+ enabled: !root.curved;
// The engine's full range. The track is linear, so the useful
// 0.25-4x band sits left of centre and the number field beside it
// is how the extremes are actually dialled in.
@@ -570,6 +598,15 @@ export component SpeedPanel inherits VerticalLayout {
}
}
+ SwitchRow {
+ label: "Reverse";
+ checked: root.selected.reverse;
+ toggled(on) => {
+ root.set(ClipField.reverse, on ? 1 : 0);
+ root.commit();
+ }
+ }
+
}
}
}
diff --git a/engine/crates/concat/ui/timeline/model.slint b/engine/crates/concat/ui/timeline/model.slint
index fc4f2992..709ab546 100644
--- a/engine/crates/concat/ui/timeline/model.slint
+++ b/engine/crates/concat/ui/timeline/model.slint
@@ -151,7 +151,7 @@ export enum TextAlignment { left, center, right }
/// one per control.
export enum ClipField {
scale, offset-x, offset-y, rotation, opacity,
- volume, speed, preserve-pitch, fade-in, fade-out,
+ volume, speed, preserve-pitch, speed-curve, reverse, fade-in, fade-out,
font-size, font-weight, italic, text-opacity, align,
stroke-width, shadow, line-height, tracking,
}
@@ -188,6 +188,10 @@ export struct SelectedClipData {
volume: float,
speed: float,
preserve-pitch: bool,
+ /// Which preset shape the speed curve is: -1 for a constant rate, the
+ /// presets' count for a custom shape.
+ speed-curve: int,
+ reverse: bool,
fade-in: float,
fade-out: float,