Skip to content

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

feat(speed): a speed curve on the Speed tab, drawn, from a preset, smooth or straight (#322)

Eric Benz80561bd273d0
diff --git a/src/crates/concat-core/src/retime.rs b/src/crates/concat-core/src/retime.rs
index 238de2b4..004ffba1 100644
--- a/src/crates/concat-core/src/retime.rs
+++ b/src/crates/concat-core/src/retime.rs
@@ -5,20 +5,32 @@
//!
//! 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.
+//! fraction of the clip's timeline length, joined by straight lines - or,
+//! when the points carry slopes, by smooth cubic bends. 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.
+//!
+//! A smooth curve is a cubic Hermite spline: each point has a slope, the
+//! speed's rate of change there, shared by the two stretches either side so
+//! the bend is seamless. A slope of zero eases in and out of the point, the
+//! shape speed ramps are usually drawn with. Slopes are held to what keeps
+//! each stretch monotone (Fritsch-Carlson), so a bend never overshoots the
+//! speeds it joins and never dips below the floor; and a stretch cut in two
+//! is still the same cubic, so a split or a trim keeps the curve exactly.
-/// Speed over a clip, as points joined by straight lines.
+/// Speed over a clip, as points joined by straight lines or smooth bends.
#[derive(Clone, PartialEq, Debug)]
pub struct SpeedCurve {
/// `(x, speed)` with `x` in `0..=1` ascending and speed positive.
points: Vec<(f64, f64)>,
+ /// A slope per point, speed per unit of `x`, for a smooth curve; None
+ /// joins the points with straight lines.
+ slopes: Option<Vec<f64>>,
}
impl SpeedCurve {
@@ -28,31 +40,53 @@ impl SpeedCurve {
/// 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`.
+ /// A curve through these points, joined by straight lines, 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
+ SpeedCurve::with_slopes(points, None)
+ }
+
+ /// A curve through these points, smooth when `slopes` gives one for
+ /// every point and straight otherwise, tidied as [`SpeedCurve::new`]
+ /// tidies and with the slopes held to monotone stretches.
+ pub fn with_slopes(points: &[(f64, f64)], slopes: Option<&[f64]>) -> Option<SpeedCurve> {
+ let slopes = slopes.filter(|slopes| slopes.len() == points.len());
+ let mut knots: Vec<(f64, f64, f64)> = points
.iter()
- .filter(|(x, speed)| x.is_finite() && speed.is_finite())
- .map(|&(x, speed)| {
+ .enumerate()
+ .filter(|(_, (x, speed))| x.is_finite() && speed.is_finite())
+ .map(|(index, &(x, speed))| {
+ let slope = slopes
+ .map(|slopes| slopes[index])
+ .filter(|slope| slope.is_finite())
+ .unwrap_or(0.0);
(
x.clamp(0.0, 1.0),
speed.clamp(Self::MIN_SPEED, Self::MAX_SPEED),
+ slope,
)
})
.collect();
- if points.is_empty() {
+ if knots.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));
+ knots.sort_by(|a, b| a.0.total_cmp(&b.0));
+ if knots[0].0 > 0.0 {
+ knots.insert(0, (0.0, knots[0].1, 0.0));
+ }
+ if knots[knots.len() - 1].0 < 1.0 {
+ knots.push((1.0, knots[knots.len() - 1].1, 0.0));
}
- if points[points.len() - 1].0 < 1.0 {
- points.push((1.0, points[points.len() - 1].1));
+ let smooth = slopes.is_some();
+ if smooth {
+ monotone(&mut knots);
}
- Some(SpeedCurve { points })
+ Some(SpeedCurve {
+ points: knots.iter().map(|&(x, speed, _)| (x, speed)).collect(),
+ slopes: smooth.then(|| knots.iter().map(|&(_, _, slope)| slope).collect()),
+ })
}
/// The points, as tidied.
@@ -60,42 +94,127 @@ impl SpeedCurve {
&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];
+ /// The slopes, one a point, for a smooth curve; None for straight
+ /// lines.
+ pub fn slopes(&self) -> Option<&[f64]> {
+ self.slopes.as_deref()
+ }
+
+ /// The stretch `x` falls in, as the index of the point that starts it,
+ /// and how far along it `x` is, `0..=1`. Points sharing an `x` make a
+ /// step, whose stretch has no width.
+ fn stretch(&self, x: f64) -> (usize, f64) {
+ let last = self.points.len() - 1;
+ for index in 0..last {
+ let (x0, x1) = (self.points[index].0, self.points[index + 1].0);
if x <= x1 {
if x1 <= x0 {
- return v1;
+ return (index, 1.0);
}
- return v0 + (v1 - v0) * (x - x0) / (x1 - x0);
+ return (index, (x - x0) / (x1 - x0));
}
}
- self.points[self.points.len() - 1].1
+ (last.saturating_sub(1), 1.0)
+ }
+
+ /// The ends of stretch `index`: width, speeds and, for a smooth curve,
+ /// the slopes scaled to the stretch (speed per unit of `u`).
+ fn ends(&self, index: usize) -> (f64, f64, f64, Option<(f64, f64)>) {
+ let (x0, v0) = self.points[index];
+ let (x1, v1) = self.points[index + 1];
+ let width = x1 - x0;
+ let slopes = self
+ .slopes
+ .as_ref()
+ .map(|slopes| (slopes[index] * width, slopes[index + 1] * width));
+ (width, v0, v1, slopes)
+ }
+
+ /// Speed at `x`, a fraction of the clip's length.
+ pub fn speed_at(&self, x: f64) -> f64 {
+ if self.points.len() < 2 {
+ return self.points[0].1;
+ }
+ let x = x.clamp(0.0, 1.0);
+ let (index, u) = self.stretch(x);
+ let (_, v0, v1, slopes) = self.ends(index);
+ match slopes {
+ Some((m0, m1)) => {
+ let (u2, u3) = (u * u, u * u * u);
+ (2.0 * u3 - 3.0 * u2 + 1.0) * v0
+ + (u3 - 2.0 * u2 + u) * m0
+ + (-2.0 * u3 + 3.0 * u2) * v1
+ + (u3 - u2) * m1
+ }
+ None => v0 + (v1 - v0) * u,
+ }
+ }
+
+ /// How fast the speed is changing at `x`: speed per unit of `x`. Zero
+ /// past the ends, where the speed holds, and on a step.
+ pub fn slope_at(&self, x: f64) -> f64 {
+ if self.points.len() < 2 || !(0.0..=1.0).contains(&x) {
+ return 0.0;
+ }
+ let (index, u) = self.stretch(x);
+ let (width, v0, v1, slopes) = self.ends(index);
+ if width <= 0.0 {
+ return 0.0;
+ }
+ let per_u = match slopes {
+ Some((m0, m1)) => {
+ let u2 = u * u;
+ (6.0 * u2 - 6.0 * u) * v0
+ + (3.0 * u2 - 4.0 * u + 1.0) * m0
+ + (-6.0 * u2 + 6.0 * u) * v1
+ + (3.0 * u2 - 2.0 * u) * m1
+ }
+ None => v1 - v0,
+ };
+ per_u / width
+ }
+
+ /// The area under stretch `index` from its start to `u` of the way
+ /// along it.
+ fn area(&self, index: usize, u: f64) -> f64 {
+ let (width, v0, v1, slopes) = self.ends(index);
+ let shape = match slopes {
+ // The integrals of the four Hermite basis functions.
+ Some((m0, m1)) => {
+ let (u2, u3, u4) = (u * u, u * u * u, u * u * u * u);
+ (u - u3 + u4 / 2.0) * v0
+ + (u4 / 4.0 - 2.0 * u3 / 3.0 + u2 / 2.0) * m0
+ + (u3 - u4 / 2.0) * v1
+ + (u4 / 4.0 - u3 / 3.0) * m1
+ }
+ // The trapezoid up to `u`.
+ None => u * (v0 + (v0 + (v1 - v0) * u)) / 2.0,
+ };
+ width * shape
}
/// 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.
+ /// by then. Exact for both joins: a trapezoid a straight stretch, the
+ /// cubic's integral a smooth one.
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;
+ let mut total = 0.0;
+ for index in 0..self.points.len().saturating_sub(1) {
+ let (x0, x1) = (self.points[index].0, self.points[index + 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 x1 <= x0 {
+ continue;
+ }
+ let u = ((x - x0) / (x1 - x0)).min(1.0);
+ total += self.area(index, u);
if x <= x1 {
break;
}
}
- area
+ total
}
/// The average speed: source seconds consumed per timeline second over
@@ -121,6 +240,33 @@ impl SpeedCurve {
}
}
+/// Holds each stretch's slopes to a monotone cubic (Fritsch-Carlson): a
+/// slope against the stretch's direction, or on a flat stretch, is zero,
+/// and a pair too steep for the rise is scaled down until the cubic cannot
+/// overshoot. Steps - points sharing an `x` - have no stretch to hold.
+fn monotone(knots: &mut [(f64, f64, f64)]) {
+ for index in 0..knots.len().saturating_sub(1) {
+ let (x0, v0, _) = knots[index];
+ let (x1, v1, _) = knots[index + 1];
+ let width = x1 - x0;
+ if width <= 0.0 {
+ continue;
+ }
+ let rise = (v1 - v0) / width;
+ if rise.abs() < 1e-12 {
+ knots[index].2 = 0.0;
+ knots[index + 1].2 = 0.0;
+ continue;
+ }
+ let alpha = (knots[index].2 / rise).max(0.0);
+ let beta = (knots[index + 1].2 / rise).max(0.0);
+ let length = (alpha * alpha + beta * beta).sqrt();
+ let tau = if length > 3.0 { 3.0 / length } else { 1.0 };
+ knots[index].2 = tau * alpha * rise;
+ knots[index + 1].2 = tau * beta * rise;
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -165,4 +311,68 @@ mod tests {
assert_eq!(curve.points()[0], (0.0, SpeedCurve::MAX_SPEED));
assert_eq!(curve.points()[1], (1.0, SpeedCurve::MIN_SPEED));
}
+ #[test]
+ fn a_smooth_curve_eases_through_its_points_and_its_area_is_exact() {
+ // Zero slopes: each stretch is the smoothstep between its speeds.
+ let curve = SpeedCurve::with_slopes(&[(0.0, 1.0), (1.0, 3.0)], Some(&[0.0, 0.0])).unwrap();
+ assert!((curve.speed_at(0.5) - 2.0).abs() < 1e-12);
+ assert!(
+ curve.speed_at(0.1) < 1.0 + 2.0 * 0.1,
+ "it leaves the point gently"
+ );
+ assert!(curve.slope_at(0.0).abs() < 1e-12 && curve.slope_at(1.0).abs() < 1e-12);
+ // The smoothstep's area is the straight line's: symmetric about it.
+ assert!((curve.mean() - 2.0).abs() < 1e-12);
+ // And the area up to any point is the integral, checked by sums.
+ let steps = 20_000;
+ let mut sum = 0.0;
+ for step in 0..steps {
+ let x = (step as f64 + 0.5) / steps as f64 * 0.37;
+ sum += curve.speed_at(x) * 0.37 / steps as f64;
+ }
+ assert!((curve.consumed(0.37) - sum).abs() < 1e-7);
+ }
+
+ #[test]
+ fn a_smooth_bend_never_overshoots() {
+ // Slopes far too steep for the rise are held back.
+ let curve = SpeedCurve::with_slopes(
+ &[(0.0, 1.0), (0.5, 4.0), (1.0, 1.0)],
+ Some(&[40.0, 40.0, -40.0]),
+ )
+ .unwrap();
+ for step in 0..=200 {
+ let speed = curve.speed_at(step as f64 / 200.0);
+ assert!((1.0 - 1e-9..=4.0 + 1e-9).contains(&speed), "{speed}");
+ }
+ // A peak's slope is flat: the bend turns there.
+ assert!(curve.slope_at(0.5).abs() < 1e-9);
+ }
+
+ #[test]
+ fn a_smooth_stretch_cut_in_two_is_the_same_cubic() {
+ let whole = SpeedCurve::with_slopes(&[(0.0, 0.5), (1.0, 4.0)], Some(&[0.0, 0.0])).unwrap();
+ // The piece over 0.3..1 of the whole, as a split's tail holds it:
+ // the cut's speed and slope, re-expressed over the piece's length.
+ let (a, b) = (0.3, 1.0);
+ let piece = SpeedCurve::with_slopes(
+ &[(0.0, whole.speed_at(a)), (1.0, whole.speed_at(b))],
+ Some(&[whole.slope_at(a) * (b - a), whole.slope_at(b) * (b - a)]),
+ )
+ .unwrap();
+ for step in 0..=10 {
+ let u = step as f64 / 10.0;
+ let x = a + u * (b - a);
+ assert!((piece.speed_at(u) - whole.speed_at(x)).abs() < 1e-9);
+ }
+ let consumed = (whole.consumed(b) - whole.consumed(a)) / (b - a);
+ assert!((piece.mean() - consumed).abs() < 1e-9);
+ }
+
+ #[test]
+ fn slopes_that_do_not_match_the_points_make_straight_lines() {
+ let curve = SpeedCurve::with_slopes(&[(0.0, 1.0), (1.0, 3.0)], Some(&[0.0])).unwrap();
+ assert!(curve.slopes().is_none());
+ assert!((curve.speed_at(0.25) - 1.5).abs() < 1e-12);
+ }
}
diff --git a/src/crates/concat-export/src/flatten.rs b/src/crates/concat-export/src/flatten.rs
index 9a692e71..e783b366 100644
--- a/src/crates/concat-export/src/flatten.rs
+++ b/src/crates/concat-export/src/flatten.rs
@@ -106,6 +106,14 @@ pub fn flatten_timeline_in(
.iter()
.map(|point| (point.at, point.speed))
.collect(),
+ speed_slopes: clip
+ .speed_curve
+ .as_deref()
+ .filter(|points| concat_project::speed::is_smooth(points))
+ .unwrap_or(&[])
+ .iter()
+ .filter_map(|point| point.slope)
+ .collect(),
animation: export_keys(clip),
flip_h: clip.flip_h,
flip_v: clip.flip_v,
diff --git a/src/crates/concat-export/src/lib.rs b/src/crates/concat-export/src/lib.rs
index 821eef7c..1777ec50 100644
--- a/src/crates/concat-export/src/lib.rs
+++ b/src/crates/concat-export/src/lib.rs
@@ -126,6 +126,10 @@ pub struct ExportClip {
/// clip's length; empty for the constant `speed`. See `SpeedCurve`.
#[serde(default)]
pub speed_curve: Vec<(f64, f64)>,
+ /// A slope for each of `speed_curve`'s points when the curve bends
+ /// smoothly between them; empty for straight lines.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub speed_slopes: Vec<f64>,
/// Keys over the clip's placement and opacity, resolved by the UI from
/// Empty for none.
#[serde(default)]
@@ -290,6 +294,13 @@ impl ExportBackdrop {
}
impl ExportClip {
+ /// The engine's curve for the clip's speed, smooth when it carries
+ /// slopes; None for a constant rate.
+ pub fn retime(&self) -> Option<SpeedCurve> {
+ let slopes = (!self.speed_slopes.is_empty()).then_some(self.speed_slopes.as_slice());
+ SpeedCurve::with_slopes(&self.speed_curve, slopes)
+ }
+
/// A clip with nothing set but what places it: no file, unity gain,
/// scale and speed, no fades, chains, keys or masks. Every literal in
/// the workspace starts here and sets the few fields it means to, so a
@@ -313,6 +324,7 @@ impl ExportClip {
speed: 1.0,
preserve_pitch: true,
speed_curve: Vec::new(),
+ speed_slopes: Vec::new(),
animation: Vec::new(),
flip_h: false,
flip_v: false,
@@ -965,6 +977,7 @@ fn last_frame_held(clip: &ExportClip, start: f64, length: f64, frame: f64) -> Ex
}
hold.speed = 1.0;
hold.speed_curve.clear();
+ hold.speed_slopes.clear();
hold.muted = true;
hold.has_audio = Some(false);
hold.volume = 0.0;
@@ -1280,7 +1293,7 @@ fn track_slice(track: &AnimTrack, x0: f64, x1: f64) -> AnimTrack {
pub fn audio_pieces(clip: &ExportClip) -> Vec<AudioClip> {
let chain = clip.filter_chain.clone();
let track = volume_track(clip);
- let Some(curve) = SpeedCurve::new(&clip.speed_curve) else {
+ let Some(curve) = clip.retime() else {
return vec![AudioClip {
path: PathBuf::from(&clip.path),
stream: clip.audio_stream.map(|index| index as usize),
diff --git a/src/crates/concat-export/src/resolve.rs b/src/crates/concat-export/src/resolve.rs
index a52872b2..be36e3b0 100644
--- a/src/crates/concat-export/src/resolve.rs
+++ b/src/crates/concat-export/src/resolve.rs
@@ -320,7 +320,7 @@ pub(crate) 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.retime = clip.retime();
}
engine_clip.animation = animation_of(&clip.animation);
engine_clip.blend = concat_core::timeline::Blend::parse(&clip.blend);
diff --git a/src/crates/concat-host/tests/export.rs b/src/crates/concat-host/tests/export.rs
index 9b78fb12..ce54386a 100644
--- a/src/crates/concat-host/tests/export.rs
+++ b/src/crates/concat-host/tests/export.rs
@@ -1451,6 +1451,7 @@ fn every_edit_still_exports() {
// on a curve, then undone back to half speed.
studio.apply(Command::SetClipSpeed {
clip_id: tail.clone(),
+ ripple: false,
speed: 2.0,
});
let exported = studio.export("double speed");
@@ -1471,6 +1472,7 @@ fn every_edit_still_exports() {
});
studio.apply(Command::SetClipSpeed {
clip_id: tail.clone(),
+ ripple: false,
speed: 0.5,
});
let exported = studio.export("half speed");
@@ -1480,14 +1482,17 @@ fn every_edit_still_exports() {
studio.apply(Command::SetClipSpeedCurve {
clip_id: tail.clone(),
+ ripple: false,
curve: Some(vec![
SpeedPoint {
at: 0.0,
speed: 0.5,
+ slope: None,
},
SpeedPoint {
at: 1.0,
speed: 2.0,
+ slope: None,
},
]),
});
@@ -1918,6 +1923,7 @@ fn the_edges_export_too() {
});
studio.apply(Command::SetClipSpeed {
clip_id: clip.clone(),
+ ripple: false,
speed: 0.125,
});
let start = studio.clip(&clip).start;
@@ -2017,6 +2023,7 @@ fn an_export_decodes_on_the_hardware_when_preferred() {
// as it does the CPU.
studio.apply(Command::SetClipSpeed {
clip_id: clip.clone(),
+ ripple: false,
speed: 2.0,
});
let start = studio.clip(&clip).start;
diff --git a/src/crates/concat-project/src/commands/clips.rs b/src/crates/concat-project/src/commands/clips.rs
index 0da125f0..f9fb5ba4 100644
--- a/src/crates/concat-project/src/commands/clips.rs
+++ b/src/crates/concat-project/src/commands/clips.rs
@@ -291,6 +291,7 @@ pub(super) fn apply(
let applied = assign(&mut clip.duration, duration);
if applied {
clip.rewindow_keys(old, 0.0, duration);
+ crate::speed::rewindow_clip(clip, old, 0.0, duration);
}
(applied, duration - old, old_end - JOIN_EPSILON)
}
@@ -298,9 +299,15 @@ pub(super) fn apply(
// Dragging the head moves the in-point too, so the pixels
// under the remaining part of the clip do not slide. The
// head cannot reach before the source begins.
+ // Under a curve the head extends at the speed it starts at.
+ let lead = clip
+ .speed_curve
+ .as_deref()
+ .and_then(crate::speed::curve_of)
+ .map_or(clip.speed, |curve| curve.speed_at(0.0));
let shift = delta
.min(clip.duration - MIN_CLIP_DURATION)
- .max(-clip.source_start / clip.speed);
+ .max(-clip.source_start / lead);
// A magnetic head trim never moves the clip, so the
// timeline's own start is no limit to it; a plain one
// stops at zero.
@@ -311,14 +318,22 @@ pub(super) fn apply(
};
let moved = start - clip.start;
let duration = clip.duration - moved;
- let source_start = (clip.source_start + moved * clip.speed).max(0.0);
let old = clip.duration;
+ // The source the head took with it: a constant rate's
+ // share, or under a curve the curve's own. Worked on a
+ // copy, so a trim that changes nothing changes nothing.
+ let mut retimed = Clip::clone(clip);
+ let consumed = crate::speed::rewindow_clip(&mut retimed, old, moved, old)
+ .unwrap_or(moved * clip.speed);
+ let source_start = (clip.source_start + consumed).max(0.0);
// Bitwise so no assignment is short-circuited away.
let applied = assign(&mut clip.start, start)
| assign(&mut clip.duration, duration)
| assign(&mut clip.source_start, source_start);
if applied {
clip.rewindow_keys(old, moved, old);
+ clip.speed = retimed.speed;
+ clip.speed_curve = retimed.speed_curve;
}
if ripple {
// The in-point moved; the clip stays put, and the
@@ -348,28 +363,21 @@ pub(super) fn apply(
let Some(index) = timeline.clips.iter().position(|clip| clip.id == clip_id) else {
continue;
};
- {
- // A curve 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 = timeline.clip_at_mut(index);
- let offset = time - clip.start;
- if offset > MIN_CLIP_DURATION
- && offset < clip.duration - MIN_CLIP_DURATION
- && clip.speed_curve.is_some()
- {
- clip.speed_curve = None;
- }
- }
let clip: &Clip = &timeline.clips[index];
let offset = time - clip.start;
if offset <= MIN_CLIP_DURATION || offset >= clip.duration - MIN_CLIP_DURATION {
continue;
}
- let (head_source, tail_source) =
+ let (head_source, mut tail_source) =
split_source(clip.source_start, clip.speed, offset);
let whole = clip.duration;
let mut tail = clip.clone();
+ // Under a curve each half keeps its share of it, and the
+ // tail starts where the curve had got to in the source.
+ if let Some(consumed) = crate::speed::rewindow_clip(&mut tail, whole, offset, whole)
+ {
+ tail_source = clip.source_start + consumed;
+ }
tail.id = mint.next("c");
tail.start = clip.start + offset;
tail.duration = clip.duration - offset;
@@ -383,6 +391,7 @@ pub(super) fn apply(
tail.rewindow_keys(whole, offset, whole);
created = Some(tail.id.clone());
let head = timeline.clip_at_mut(index);
+ crate::speed::rewindow_clip(head, whole, 0.0, offset);
head.duration = offset;
head.source_start = head_source;
head.fade_out = 0.0;
@@ -566,13 +575,15 @@ pub(super) fn apply(
return Ok(Outcome::default());
};
// The cut is a split's, so it leaves the pieces as a split does:
- // under a curve the map is not affine, and the in-point below
- // assumes it is, so both pieces go to the constant mean they
- // averaged.
- timeline.clip_at_mut(index).speed_curve = None;
+ // under a curve each keeps its share of it.
let offset = time - start;
- let (head_source, tail_source) = split_source(source_start, speed, offset);
+ let (head_source, mut tail_source) = split_source(source_start, speed, offset);
let mut tail = Clip::clone(&timeline.clips[index]);
+ if let Some(consumed) =
+ crate::speed::rewindow_clip(&mut tail, clip_duration, offset, clip_duration)
+ {
+ tail_source = source_start + consumed;
+ }
tail.id = mint.next("c");
tail.start = time;
tail.duration = clip_duration - offset;
@@ -581,6 +592,7 @@ pub(super) fn apply(
tail.fade_in = 0.0;
tail.rewindow_keys(clip_duration, offset, clip_duration);
let head = timeline.clip_at_mut(index);
+ crate::speed::rewindow_clip(head, clip_duration, 0.0, offset);
head.duration = offset;
head.source_start = head_source;
head.fade_out = 0.0;
diff --git a/src/crates/concat-project/src/commands/mod.rs b/src/crates/concat-project/src/commands/mod.rs
index 078088fb..dbfaf0ae 100644
--- a/src/crates/concat-project/src/commands/mod.rs
+++ b/src/crates/concat-project/src/commands/mod.rs
@@ -422,6 +422,13 @@ pub enum Command {
clip_id: String,
/// The curve, or None for a constant rate at the current mean.
curve: Option<Vec<SpeedPoint>>,
+ /// When true - the magnetic timeline - the clips after it on its
+ /// lane move by however far its end moved, either way, so a clip
+ /// sped up closes up behind it as a magnetic trim does. False
+ /// leaves the gap; later clips then only move out of the way of a
+ /// clip that grew over them.
+ #[serde(default)]
+ ripple: bool,
},
/// Puts a key on one property at one point of a clip, replacing
/// whichever key on that property was already within a hair of it.
@@ -663,6 +670,13 @@ pub enum Command {
clip_id: String,
/// The new rate, clamped into 0.0625..=16 (the engine's range).
speed: f64,
+ /// When true - the magnetic timeline - the clips after it on its
+ /// lane move by however far its end moved, either way, so a clip
+ /// sped up closes up behind it as a magnetic trim does. False
+ /// leaves the gap; later clips then only move out of the way of a
+ /// clip that grew over them.
+ #[serde(default)]
+ ripple: bool,
},
/// Adjusts the picture's placement. Each field is optional so a drag
/// can send just the axis it moved; absent fields stay put.
diff --git a/src/crates/concat-project/src/commands/properties.rs b/src/crates/concat-project/src/commands/properties.rs
index c54adfdb..44d7d398 100644
--- a/src/crates/concat-project/src/commands/properties.rs
+++ b/src/crates/concat-project/src/commands/properties.rs
@@ -93,7 +93,11 @@ pub(super) fn apply(
})
}
- Command::SetClipSpeed { clip_id, speed } => {
+ Command::SetClipSpeed {
+ clip_id,
+ speed,
+ ripple,
+ } => {
let timeline = project.active_mut();
let Some(clip) = timeline.clip_mut(&clip_id) else {
return Ok(Outcome::default());
@@ -111,20 +115,7 @@ pub(super) fn apply(
(source_covered / next).max(MIN_CLIP_DURATION),
)
| assign(&mut clip.speed_curve, None);
- // Slowed down, the clip grows into what follows it: the rest of
- // the lane moves along by the growth, as a freeze frame's does,
- // rather than being covered.
- let (track_id, start, duration) = (clip.track_id.clone(), clip.start, clip.duration);
- let grow = start + duration - old_end;
- if grow > 0.0 && !timeline.is_free(&track_id, start, duration, &[&clip_id]) {
- for other in timeline.clips_where(|other| {
- other.id != clip_id
- && other.track_id == track_id
- && other.start >= old_end - crate::placement::TOUCH
- }) {
- other.start += grow;
- }
- }
+ make_room(timeline, &clip_id, old_end, ripple);
Ok(Outcome {
created_id: None,
applied,
@@ -309,13 +300,18 @@ pub(super) fn apply(
})
}
- Command::SetClipSpeedCurve { clip_id, curve } => {
+ Command::SetClipSpeedCurve {
+ clip_id,
+ curve,
+ ripple,
+ } => {
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 old_end = clip.start + clip.duration;
let mean = curve
.as_ref()
.map(|points| crate::speed::mean_of(points))
@@ -327,6 +323,7 @@ pub(super) fn apply(
&mut clip.duration,
(source_covered / mean).max(MIN_CLIP_DURATION),
);
+ make_room(timeline, &clip_id, old_end, ripple);
Ok(Outcome {
created_id: None,
applied,
@@ -409,3 +406,27 @@ pub(super) fn apply(
_ => unreachable!("commands::apply routes only this module's commands here"),
}
}
+
+/// What a retimed clip does to the lane behind it. One that ends later
+/// than `old_end` and would cover what follows it pushes the rest of the
+/// lane along by the growth, as a freeze frame's does. On the magnetic
+/// timeline (`ripple`) the lane follows the clip's end either way, so a
+/// clip sped up leaves no gap, as a magnetic trim leaves none. Shared by
+/// the constant rate and the curve, which both stretch a clip.
+fn make_room(timeline: &mut Timeline, clip_id: &str, old_end: f64, ripple: bool) {
+ let Some(clip) = timeline.clip(clip_id) else {
+ return;
+ };
+ let (track_id, start, duration) = (clip.track_id.clone(), clip.start, clip.duration);
+ let moved = start + duration - old_end;
+ let pushed = moved > 0.0 && !timeline.is_free(&track_id, start, duration, &[clip_id]);
+ if (ripple && moved != 0.0) || pushed {
+ for other in timeline.clips_where(|other| {
+ other.id != clip_id
+ && other.track_id == track_id
+ && other.start >= old_end - crate::placement::TOUCH
+ }) {
+ other.start = (other.start + moved).max(0.0);
+ }
+ }
+}
diff --git a/src/crates/concat-project/src/lib.rs b/src/crates/concat-project/src/lib.rs
index e7188813..b8e05308 100644
--- a/src/crates/concat-project/src/lib.rs
+++ b/src/crates/concat-project/src/lib.rs
@@ -795,6 +795,7 @@ mod tests {
editor
.apply(Command::SetClipSpeed {
clip_id: first,
+ ripple: false,
speed: 0.5,
})
.expect("retimes");
@@ -1724,22 +1725,25 @@ mod tests {
}
/// A freeze cuts the clip the way a split does, so a curved clip has to
- /// come out of it the way a split leaves one: both pieces at the curve's
- /// constant mean, meeting at the frozen source time.
+ /// come out of it the way a split leaves one: each piece with its share
+ /// of the curve, meeting at the frozen source time.
#[test]
fn freeze_frame_on_a_curved_clip_keeps_the_pieces_continuous() {
let (mut editor, _, clip_id) = fixture();
editor
.apply(Command::SetClipSpeedCurve {
clip_id: clip_id.clone(),
+ ripple: false,
curve: Some(vec![
crate::model::SpeedPoint {
at: 0.0,
speed: 0.5,
+ slope: None,
},
crate::model::SpeedPoint {
at: 1.0,
speed: 2.0,
+ slope: None,
},
]),
})
@@ -1778,18 +1782,226 @@ mod tests {
.find(|clip| clip.id != clip_id && clip.id != freeze_id)
.expect("tail");
for piece in [head, tail] {
- assert!(
- piece.speed_curve.is_none(),
- "a piece kept a curve its in-point was not computed for"
- );
+ assert!(piece.speed_curve.is_some(), "a piece lost its ramp");
}
- assert_eq!(
- head.source_start + head.duration * head.speed,
- tail.source_start,
+ assert!(
+ (head.source_start + head.duration * head.speed - tail.source_start).abs() < 1e-9,
"the tail picks up where the head ends"
);
}
+ /// The fixture's ten-second clip under a ramp from half speed to double.
+ fn ramped() -> (Editor, String) {
+ let (mut editor, _, clip_id) = fixture();
+ editor
+ .apply(Command::SetClipSpeedCurve {
+ clip_id: clip_id.clone(),
+ ripple: false,
+ curve: Some(vec![
+ crate::model::SpeedPoint {
+ at: 0.0,
+ speed: 0.5,
+ slope: None,
+ },
+ crate::model::SpeedPoint {
+ at: 1.0,
+ speed: 2.0,
+ slope: None,
+ },
+ ]),
+ })
+ .expect("curves");
+ (editor, clip_id)
+ }
+
+ /// Source seconds `t` seconds into a placed clip, as the engine maps it.
+ fn source_at(clip: &crate::model::Clip, t: f64) -> f64 {
+ match clip.speed_curve.as_deref().and_then(crate::speed::curve_of) {
+ Some(curve) => clip.source_start + clip.duration * curve.consumed(t / clip.duration),
+ None => clip.source_start + t * clip.speed,
+ }
+ }
+
+ #[test]
+ fn a_split_ramp_plays_on_in_both_halves() {
+ let (mut editor, clip_id) = ramped();
+ let whole = editor.project().active().clip(&clip_id).unwrap().clone();
+ let cut = whole.duration * 0.3;
+ editor
+ .apply(Command::SplitClips {
+ clip_ids: vec![clip_id.clone()],
+ time: cut,
+ })
+ .expect("splits");
+ let clips = &editor.project().active().clips;
+ let (head, tail) = (&clips[0], &clips[1]);
+ assert!(head.speed_curve.is_some() && tail.speed_curve.is_some());
+ for t in [0.0, cut / 2.0, cut] {
+ assert!((source_at(head, t) - source_at(&whole, t)).abs() < 1e-9);
+ }
+ for t in [0.0, 1.0, tail.duration] {
+ assert!((source_at(tail, t) - source_at(&whole, cut + t)).abs() < 1e-9);
+ }
+ }
+
+ #[test]
+ fn trimming_a_ramp_cuts_it_rather_than_squeezing_it() {
+ let (mut editor, clip_id) = ramped();
+ let whole = editor.project().active().clip(&clip_id).unwrap().clone();
+ editor
+ .apply(Command::TrimClip {
+ clip_id: clip_id.clone(),
+ edge: TrimEdge::Start,
+ delta: 2.0,
+ ripple: false,
+ })
+ .expect("trims the head");
+ editor
+ .apply(Command::TrimClip {
+ clip_id: clip_id.clone(),
+ edge: TrimEdge::End,
+ delta: -1.0,
+ ripple: false,
+ })
+ .expect("trims the tail");
+ let trimmed = editor.project().active().clip(&clip_id).unwrap();
+ assert!((trimmed.start - 2.0).abs() < 1e-9);
+ // What is left plays exactly what that stretch played before.
+ for t in [0.0, 1.0, trimmed.duration] {
+ assert!((source_at(trimmed, t) - source_at(&whole, 2.0 + t)).abs() < 1e-9);
+ }
+ }
+
+ #[test]
+ fn a_ramp_that_slows_a_clip_moves_the_lane_along() {
+ let (mut editor, _, clip_id) = fixture();
+ let media_id = editor
+ .project()
+ .active()
+ .clip(&clip_id)
+ .unwrap()
+ .media_id
+ .clone();
+ let track_id = editor.project().active().tracks[0].id.clone();
+ let next = editor
+ .apply(Command::AddClip {
+ media_id,
+ track_id,
+ start: 10.0,
+ ripple: false,
+ })
+ .expect("adds")
+ .created_id
+ .expect("id");
+ editor
+ .apply(Command::SetClipSpeedCurve {
+ clip_id: clip_id.clone(),
+ ripple: false,
+ curve: Some(vec![
+ crate::model::SpeedPoint {
+ at: 0.0,
+ speed: 1.0,
+ slope: None,
+ },
+ crate::model::SpeedPoint {
+ at: 0.5,
+ speed: 0.25,
+ slope: None,
+ },
+ crate::model::SpeedPoint {
+ at: 1.0,
+ speed: 1.0,
+ slope: None,
+ },
+ ]),
+ })
+ .expect("curves");
+ let timeline = editor.project().active();
+ let ramped = timeline.clip(&clip_id).unwrap();
+ let next = timeline.clip(&next).unwrap();
+ assert!(ramped.duration > 10.0, "the slow middle lengthens the clip");
+ assert!(
+ next.start >= ramped.start + ramped.duration - 1e-9,
+ "the clip after it is moved along, not covered"
+ );
+ }
+
+ #[test]
+ fn a_magnetic_speed_up_closes_the_lane_behind_it_and_a_plain_one_leaves_the_gap() {
+ for ripple in [true, false] {
+ let (mut editor, _, clip_id) = fixture();
+ let media_id = editor
+ .project()
+ .active()
+ .clip(&clip_id)
+ .unwrap()
+ .media_id
+ .clone();
+ let track_id = editor.project().active().tracks[0].id.clone();
+ let mut add = |start| {
+ editor
+ .apply(Command::AddClip {
+ media_id: media_id.clone(),
+ track_id: track_id.clone(),
+ start,
+ ripple: false,
+ })
+ .expect("adds")
+ .created_id
+ .expect("id")
+ };
+ // One clip touching it, and one past a gap of its own.
+ let next = add(10.0);
+ let later = add(25.0);
+ let before = editor.project().clone();
+ editor
+ .apply(Command::SetClipSpeed {
+ clip_id: clip_id.clone(),
+ ripple,
+ speed: 2.0,
+ })
+ .expect("speeds up");
+ editor
+ .apply(Command::SetClipSpeedCurve {
+ clip_id: clip_id.clone(),
+ ripple,
+ curve: Some(vec![
+ crate::model::SpeedPoint {
+ at: 0.0,
+ speed: 4.0,
+ slope: Some(0.0),
+ },
+ crate::model::SpeedPoint {
+ at: 1.0,
+ speed: 1.0,
+ slope: Some(0.0),
+ },
+ ]),
+ })
+ .expect("curves");
+ let timeline = editor.project().active();
+ let ramped = timeline.clip(&clip_id).unwrap();
+ let end = ramped.start + ramped.duration;
+ let (next, later) = (
+ timeline.clip(&next).unwrap().start,
+ timeline.clip(&later).unwrap().start,
+ );
+ assert!(end < 5.0, "the clip got shorter");
+ if ripple {
+ assert!((next - end).abs() < 1e-9, "the next clip closes up");
+ assert!(
+ (later - next - 15.0).abs() < 1e-9,
+ "a gap further down the lane is kept"
+ );
+ } else {
+ assert_eq!((next, later), (10.0, 25.0), "a plain retime leaves the gap");
+ }
+ assert!(editor.undo(), "undoes");
+ assert!(editor.undo(), "undoes");
+ assert_eq!(editor.project(), &before, "undo puts the lane back");
+ }
+ }
+
#[test]
fn split_produces_source_continuous_halves_and_merge_rejoins_them() {
let (mut editor, _, clip_id) = fixture();
@@ -1905,6 +2117,7 @@ mod tests {
for command in [
Command::SetClipSpeed {
clip_id: clip_id.clone(),
+ ripple: false,
speed: f64::NAN,
},
Command::SplitClips {
@@ -2602,6 +2815,7 @@ mod tests {
editor
.apply(Command::SetClipSpeed {
clip_id: clip_id.clone(),
+ ripple: false,
speed: 2.0,
})
.expect("ok");
@@ -2630,6 +2844,7 @@ mod tests {
editor
.apply(Command::SetClipSpeed {
clip_id: clip_id.clone(),
+ ripple: false,
speed: 100.0,
})
.expect("ok");
@@ -2637,6 +2852,7 @@ mod tests {
editor
.apply(Command::SetClipSpeed {
clip_id,
+ ripple: false,
speed: 0.0,
})
.expect("ok");
@@ -3452,6 +3668,7 @@ mod tests {
},
Command::SetClipSpeed {
clip_id,
+ ripple: false,
speed: 2.0,
},
],
@@ -3917,6 +4134,7 @@ mod tests {
},
Command::SetClipSpeed {
clip_id,
+ ripple: false,
speed: 2.0,
},
],
@@ -4527,6 +4745,7 @@ mod tests {
},
Command::SetClipSpeed {
clip_id: "c1".to_owned(),
+ ripple: false,
speed: 2.0,
},
Command::SetClipTransform {
diff --git a/src/crates/concat-project/src/model.rs b/src/crates/concat-project/src/model.rs
index 3f7de152..f15b7280 100644
--- a/src/crates/concat-project/src/model.rs
+++ b/src/crates/concat-project/src/model.rs
@@ -1284,6 +1284,12 @@ pub struct SpeedPoint {
pub at: f64,
/// Source seconds per timeline second there.
pub speed: f64,
+ /// How fast the speed is changing there, speed per unit of `at`, for a
+ /// curve with smooth bends: present on every point of such a curve and
+ /// absent on every point of one joined by straight lines. See
+ /// `concat_core::SpeedCurve`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub slope: Option<f64>,
}
/// A clip's Enhance, once it has a copy: see [`Clip::enhanced`].
@@ -2012,6 +2018,7 @@ impl Clip {
.map(|point| SpeedPoint {
at: point.at,
speed: finite(point.speed, 1.0).clamp(MIN_SPEED, MAX_SPEED),
+ slope: point.slope.filter(|slope| slope.is_finite()),
})
.collect();
(!points.is_empty()).then_some(points)
diff --git a/src/crates/concat-project/src/speed.rs b/src/crates/concat-project/src/speed.rs
index a483b68c..54789937 100644
--- a/src/crates/concat-project/src/speed.rs
+++ b/src/crates/concat-project/src/speed.rs
@@ -8,15 +8,23 @@
use concat_core::SpeedCurve;
-use crate::model::SpeedPoint;
+use crate::model::ranges::{MAX_SPEED, MIN_SPEED};
+use crate::model::{Clip, SpeedPoint};
/// The engine's curve for these points, or None when they make no curve.
+/// Smooth when every point carries a slope, straight otherwise.
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)
+ let slopes: Option<Vec<f64>> = points.iter().map(|point| point.slope).collect();
+ SpeedCurve::with_slopes(&raw, slopes.as_deref())
+}
+
+/// Whether these points bend smoothly rather than meet in straight lines.
+pub fn is_smooth(points: &[SpeedPoint]) -> bool {
+ !points.is_empty() && points.iter().all(|point| point.slope.is_some())
}
/// Source seconds per timeline second over a whole clip with these points;
@@ -24,3 +32,309 @@ pub fn curve_of(points: &[SpeedPoint]) -> Option<SpeedCurve> {
pub fn mean_of(points: &[SpeedPoint]) -> f64 {
curve_of(points).map(|curve| curve.mean()).unwrap_or(1.0)
}
+
+/// A shape a clip's speed can be given in one go: points over the clip's
+/// length, so the same preset fits a clip of any length. Choosing one
+/// writes ordinary points, which are the clip's own from then on.
+pub struct SpeedPreset {
+ /// The name the window looks its label up by.
+ pub id: &'static str,
+ /// `(at, speed)`, ascending. Straight lines join them, so a bend that
+ /// should read as smooth is given a point either side of it.
+ pub points: &'static [(f64, f64)],
+}
+
+/// The presets, in the order the window lists them. The names are the
+/// ones people bring from other editors.
+pub const PRESETS: &[SpeedPreset] = &[
+ // Slow, fast, slow, fast: a rhythm for a sequence of shots.
+ SpeedPreset {
+ id: "montage",
+ points: &[
+ (0.0, 0.6),
+ (0.15, 0.6),
+ (0.3, 3.0),
+ (0.45, 0.6),
+ (0.6, 0.6),
+ (0.75, 3.0),
+ (0.9, 0.6),
+ (1.0, 0.6),
+ ],
+ },
+ // Fast in, a long slow moment in the middle, fast out.
+ SpeedPreset {
+ id: "hero",
+ points: &[
+ (0.0, 2.5),
+ (0.25, 2.5),
+ (0.38, 0.5),
+ (0.62, 0.5),
+ (0.75, 2.5),
+ (1.0, 2.5),
+ ],
+ },
+ // Fast, then nearly stopped, then fast: the bullet-time moment.
+ SpeedPreset {
+ id: "bullet",
+ points: &[
+ (0.0, 3.0),
+ (0.3, 3.0),
+ (0.42, 0.2),
+ (0.58, 0.2),
+ (0.7, 3.0),
+ (1.0, 3.0),
+ ],
+ },
+ // Normal, a short burst very fast through the middle, normal.
+ SpeedPreset {
+ id: "jump-cut",
+ points: &[
+ (0.0, 1.0),
+ (0.38, 1.0),
+ (0.45, 8.0),
+ (0.55, 8.0),
+ (0.62, 1.0),
+ (1.0, 1.0),
+ ],
+ },
+ // Rushing in, settling to normal.
+ SpeedPreset {
+ id: "flash-in",
+ points: &[(0.0, 8.0), (0.12, 4.0), (0.3, 1.0), (1.0, 1.0)],
+ },
+ // Normal, then rushing out.
+ SpeedPreset {
+ id: "flash-out",
+ points: &[(0.0, 1.0), (0.7, 1.0), (0.88, 4.0), (1.0, 8.0)],
+ },
+];
+
+/// The points of the preset called `id`, smooth - easing in and out of
+/// every point, the way ramps are drawn - or None for a name there is no
+/// preset by.
+pub fn preset(id: &str) -> Option<Vec<SpeedPoint>> {
+ PRESETS.iter().find(|preset| preset.id == id).map(|preset| {
+ preset
+ .points
+ .iter()
+ .map(|&(at, speed)| SpeedPoint {
+ at,
+ speed,
+ slope: Some(0.0),
+ })
+ .collect()
+ })
+}
+
+/// Which preset these points are, unchanged but for smooth or straight,
+/// or None for a curve of the clip's own: what the window's picker shows
+/// as chosen.
+pub fn preset_of(points: &[SpeedPoint]) -> Option<&'static str> {
+ PRESETS
+ .iter()
+ .find(|preset| {
+ preset.points.len() == points.len()
+ && preset
+ .points
+ .iter()
+ .zip(points)
+ .all(|(&(at, speed), point)| {
+ (at - point.at).abs() < 1e-9 && (speed - point.speed).abs() < 1e-9
+ })
+ })
+ .map(|preset| preset.id)
+}
+
+/// A clip's curve after its span changed, so each stretch of it plays the
+/// speed it played before - the curve's counterpart of
+/// [`Clip::rewindow_keys`], and called with the same arguments: `old` is
+/// the length the curve was drawn over, `[from, to]` the window of it the
+/// clip now covers, in seconds from its old start. A window past either end
+/// holds the end's speed. The clip's `speed` becomes the new curve's mean.
+///
+/// Returns the source seconds the curve consumed between the old start and
+/// `from` - negative for a window that starts earlier - which is how far
+/// the in-point moves when the head goes; None, and nothing changed, for a
+/// clip with no curve or a window that makes no sense.
+pub fn rewindow_clip(clip: &mut Clip, old: f64, from: f64, to: f64) -> Option<f64> {
+ let sane = old.is_finite() && old > 0.0 && from.is_finite() && to.is_finite() && to > from;
+ if !sane {
+ return None;
+ }
+ let curve = curve_of(clip.speed_curve.as_deref()?)?;
+ let (a, b) = (from / old, to / old);
+ // A smooth curve keeps its slopes, re-expressed over the window's
+ // length, and gets the curve's own slope at a cut: the piece is then
+ // the same cubic the whole was.
+ let slopes = curve.slopes();
+ let slope = |at: f64| slopes.map(|_| curve.slope_at(at) * (b - a));
+ let mut points = vec![SpeedPoint {
+ at: 0.0,
+ speed: curve.speed_at(a),
+ slope: slope(a),
+ }];
+ points.extend(
+ curve
+ .points()
+ .iter()
+ .enumerate()
+ .filter(|(_, (at, _))| *at > a && *at < b)
+ .map(|(index, &(at, speed))| SpeedPoint {
+ at: (at - a) / (b - a),
+ speed,
+ slope: slopes.map(|slopes| slopes[index] * (b - a)),
+ }),
+ );
+ points.push(SpeedPoint {
+ at: 1.0,
+ speed: curve.speed_at(b),
+ slope: slope(b),
+ });
+ let consumed = if a >= 0.0 {
+ old * curve.consumed(a)
+ } else {
+ from * curve.speed_at(0.0)
+ };
+ clip.speed = mean_of(&points).clamp(MIN_SPEED, MAX_SPEED);
+ clip.speed_curve = Some(points);
+ Some(consumed)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::model::ClipKind;
+
+ fn points(raw: &[(f64, f64)]) -> Vec<SpeedPoint> {
+ raw.iter()
+ .map(|&(at, speed)| SpeedPoint {
+ at,
+ speed,
+ slope: None,
+ })
+ .collect()
+ }
+
+ fn curved(raw: &[(f64, f64)], duration: f64) -> Clip {
+ let mut clip = Clip::blank("c1", "v1", ClipKind::Video, "clip", 0.0, duration);
+ clip.speed_curve = Some(points(raw));
+ clip.speed = mean_of(clip.speed_curve.as_deref().unwrap());
+ clip
+ }
+
+ /// Source seconds at `t` seconds into a clip, the way the engine maps it.
+ fn source_at(clip: &Clip, t: f64) -> f64 {
+ let curve = curve_of(clip.speed_curve.as_deref().unwrap()).unwrap();
+ clip.source_start + clip.duration * curve.consumed(t / clip.duration)
+ }
+
+ #[test]
+ fn every_preset_is_a_curve_inside_the_engine_range() {
+ for preset in PRESETS {
+ let points = super::preset(preset.id).unwrap();
+ assert!(curve_of(&points).is_some(), "{}", preset.id);
+ assert_eq!(points.first().map(|p| p.at), Some(0.0), "{}", preset.id);
+ assert_eq!(points.last().map(|p| p.at), Some(1.0), "{}", preset.id);
+ assert!(
+ points.windows(2).all(|pair| pair[0].at <= pair[1].at),
+ "{} is not in order",
+ preset.id
+ );
+ assert!(
+ points
+ .iter()
+ .all(|p| (MIN_SPEED..=MAX_SPEED).contains(&p.speed)),
+ "{}",
+ preset.id
+ );
+ assert_eq!(preset_of(&points), Some(preset.id));
+ }
+ assert!(super::preset("no such preset").is_none());
+ }
+
+ #[test]
+ fn a_moved_point_is_no_longer_the_preset() {
+ let mut points = preset("hero").unwrap();
+ points[2].speed = 0.7;
+ assert_eq!(preset_of(&points), None);
+ }
+
+ #[test]
+ fn the_two_halves_of_a_split_play_what_the_whole_played() {
+ let whole = curved(&[(0.0, 0.5), (0.4, 4.0), (1.0, 1.0)], 10.0);
+ let cut = 3.0;
+ let mut head = whole.clone();
+ let mut tail = whole.clone();
+ assert_eq!(rewindow_clip(&mut head, 10.0, 0.0, cut), Some(0.0));
+ head.duration = cut;
+ let shift = rewindow_clip(&mut tail, 10.0, cut, 10.0).unwrap();
+ tail.source_start += shift;
+ tail.duration = 10.0 - cut;
+ for t in [0.0, 1.0, 2.5, 3.0] {
+ assert!(
+ (source_at(&head, t) - source_at(&whole, t)).abs() < 1e-9,
+ "head at {t}"
+ );
+ }
+ for t in [0.0, 0.5, 4.0, 7.0] {
+ assert!(
+ (source_at(&tail, t) - source_at(&whole, cut + t)).abs() < 1e-9,
+ "tail at {t}"
+ );
+ }
+ // Each piece's rate is its own share of the curve, and together
+ // they cover the source the whole did.
+ let covered = head.duration * head.speed + tail.duration * tail.speed;
+ assert!((covered - whole.duration * whole.speed).abs() < 1e-9);
+ }
+
+ #[test]
+ fn a_smooth_ramp_split_in_two_plays_what_the_whole_played() {
+ let mut whole = curved(&[(0.0, 0.5), (0.4, 4.0), (1.0, 1.0)], 10.0);
+ for point in whole.speed_curve.as_mut().unwrap() {
+ point.slope = Some(0.0);
+ }
+ whole.speed = mean_of(whole.speed_curve.as_deref().unwrap());
+ let cut = 2.7;
+ let mut head = whole.clone();
+ let mut tail = whole.clone();
+ rewindow_clip(&mut head, 10.0, 0.0, cut);
+ head.duration = cut;
+ tail.source_start += rewindow_clip(&mut tail, 10.0, cut, 10.0).unwrap();
+ tail.duration = 10.0 - cut;
+ assert!(is_smooth(head.speed_curve.as_deref().unwrap()));
+ assert!(is_smooth(tail.speed_curve.as_deref().unwrap()));
+ for t in [0.0, 1.3, cut] {
+ assert!(
+ (source_at(&head, t) - source_at(&whole, t)).abs() < 1e-9,
+ "head at {t}"
+ );
+ }
+ for t in [0.0, 0.9, 4.0, 7.3] {
+ assert!(
+ (source_at(&tail, t) - source_at(&whole, cut + t)).abs() < 1e-9,
+ "tail at {t}"
+ );
+ }
+ }
+
+ #[test]
+ fn a_window_past_the_end_holds_the_end_speed() {
+ let mut clip = curved(&[(0.0, 1.0), (1.0, 2.0)], 4.0);
+ let shift = rewindow_clip(&mut clip, 4.0, -1.0, 6.0).unwrap();
+ // A second before the old start at the start's speed.
+ assert!((shift + 1.0).abs() < 1e-12);
+ let curve = clip.speed_curve.unwrap();
+ assert_eq!(curve.first().map(|p| p.speed), Some(1.0));
+ assert_eq!(curve.last().map(|p| p.speed), Some(2.0));
+ }
+
+ #[test]
+ fn a_clip_without_a_curve_is_left_alone() {
+ let mut clip = Clip::blank("c1", "v1", ClipKind::Video, "clip", 0.0, 4.0);
+ clip.speed = 2.0;
+ assert_eq!(rewindow_clip(&mut clip, 4.0, 1.0, 4.0), None);
+ assert_eq!(clip.speed, 2.0);
+ assert!(clip.speed_curve.is_none());
+ }
+}
diff --git a/src/crates/concat/locales/ar.json b/src/crates/concat/locales/ar.json
index 66ef93b2..643485c9 100644
--- a/src/crates/concat/locales/ar.json
+++ b/src/crates/concat/locales/ar.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "تمت إضافة الصوت إلى المخطط الزمني",
"speech.voiceFrom": "الصوت من",
"speech.voiceName": "سمِّ هذا الصوت",
+ "speedRamp.bends": "الانحناءات",
+ "speedRamp.bullet": "رصاصة",
+ "speedRamp.constant": "ثابت",
+ "speedRamp.curve": "منحنى",
+ "speedRamp.custom": "مخصص",
+ "speedRamp.fastest": "الأسرع",
+ "speedRamp.flashIn": "وميض للداخل",
+ "speedRamp.flashOut": "وميض للخارج",
+ "speedRamp.hero": "بطل",
+ "speedRamp.howTo": "انقر على الرسم لإضافة نقطة، واسحبها لتشكيل المنحدر، وانقر عليها نقرًا مزدوجًا لإزالتها.",
+ "speedRamp.jumpCut": "قفزة",
+ "speedRamp.montage": "مونتاج",
+ "speedRamp.shape": "الشكل",
+ "speedRamp.slowest": "الأبطأ",
+ "speedRamp.smooth": "ناعم",
+ "speedRamp.straight": "مستقيم",
"start.choose": "اختيار…",
"start.chooseAFolder": "اختيار مجلد",
"start.chooseWhereProjectFolder": "اختر مكان مجلد المشروع",
diff --git a/src/crates/concat/locales/bn.json b/src/crates/concat/locales/bn.json
index 10a0c150..3cf937d6 100644
--- a/src/crates/concat/locales/bn.json
+++ b/src/crates/concat/locales/bn.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "টাইমলাইনে কণ্ঠ যোগ হয়েছে",
"speech.voiceFrom": "কণ্ঠ:",
"speech.voiceName": "এই কণ্ঠের নাম দিন",
+ "speedRamp.bends": "বাঁক",
+ "speedRamp.bullet": "বুলেট",
+ "speedRamp.constant": "স্থির",
+ "speedRamp.curve": "বক্ররেখা",
+ "speedRamp.custom": "নিজস্ব",
+ "speedRamp.fastest": "দ্রুততম",
+ "speedRamp.flashIn": "ফ্ল্যাশ ইন",
+ "speedRamp.flashOut": "ফ্ল্যাশ আউট",
+ "speedRamp.hero": "হিরো",
+ "speedRamp.howTo": "একটি বিন্দু যোগ করতে গ্রাফে ক্লিক করুন, র‍্যাম্পের আকার দিতে টেনে আনুন, সরাতে ডাবল-ক্লিক করুন।",
+ "speedRamp.jumpCut": "জাম্প কাট",
+ "speedRamp.montage": "মন্তাজ",
+ "speedRamp.shape": "আকার",
+ "speedRamp.slowest": "ধীরতম",
+ "speedRamp.smooth": "মসৃণ",
+ "speedRamp.straight": "সোজা",
"start.choose": "বেছে নিন…",
"start.chooseAFolder": "একটি ফোল্ডার বেছে নিন",
"start.chooseWhereProjectFolder": "প্রকল্প ফোল্ডার কোথায় যাবে তা বেছে নিন",
diff --git a/src/crates/concat/locales/de.json b/src/crates/concat/locales/de.json
index e59c85ce..3a810136 100644
--- a/src/crates/concat/locales/de.json
+++ b/src/crates/concat/locales/de.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Stimme zur Zeitleiste hinzugefügt",
"speech.voiceFrom": "Stimme aus",
"speech.voiceName": "Name der Stimme",
+ "speedRamp.bends": "Verlauf",
+ "speedRamp.bullet": "Kugel",
+ "speedRamp.constant": "Konstant",
+ "speedRamp.curve": "Kurve",
+ "speedRamp.custom": "Eigene",
+ "speedRamp.fastest": "Schnellste Stelle",
+ "speedRamp.flashIn": "Blitz rein",
+ "speedRamp.flashOut": "Blitz raus",
+ "speedRamp.hero": "Held",
+ "speedRamp.howTo": "Klicke in die Grafik, um einen Punkt zu setzen, ziehe ihn, um die Rampe zu formen, und doppelklicke ihn, um ihn zu entfernen.",
+ "speedRamp.jumpCut": "Sprungschnitt",
+ "speedRamp.montage": "Montage",
+ "speedRamp.shape": "Form",
+ "speedRamp.slowest": "Langsamste Stelle",
+ "speedRamp.smooth": "Weich",
+ "speedRamp.straight": "Gerade",
"start.choose": "Wählen…",
"start.chooseAFolder": "Ordner wählen",
"start.chooseWhereProjectFolder": "Wähle, wohin der Projektordner soll",
diff --git a/src/crates/concat/locales/en.json b/src/crates/concat/locales/en.json
index 4f7f5852..6e297265 100644
--- a/src/crates/concat/locales/en.json
+++ b/src/crates/concat/locales/en.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Voice added to the timeline",
"speech.voiceFrom": "Voice from",
"speech.voiceName": "Name this voice",
+ "speedRamp.bends": "Bends",
+ "speedRamp.bullet": "Bullet",
+ "speedRamp.constant": "Constant",
+ "speedRamp.curve": "Curve",
+ "speedRamp.custom": "Custom",
+ "speedRamp.fastest": "Fastest",
+ "speedRamp.flashIn": "Flash in",
+ "speedRamp.flashOut": "Flash out",
+ "speedRamp.hero": "Hero",
+ "speedRamp.howTo": "Click the graph to add a point, drag it to shape the ramp, double-click it to take it away.",
+ "speedRamp.jumpCut": "Jump cut",
+ "speedRamp.montage": "Montage",
+ "speedRamp.shape": "Shape",
+ "speedRamp.slowest": "Slowest",
+ "speedRamp.smooth": "Smooth",
+ "speedRamp.straight": "Straight",
"start.choose": "Choose…",
"start.chooseAFolder": "Choose a folder",
"start.chooseWhereProjectFolder": "Choose where the project folder should go",
diff --git a/src/crates/concat/locales/es.json b/src/crates/concat/locales/es.json
index 3ca1d820..016bb13e 100644
--- a/src/crates/concat/locales/es.json
+++ b/src/crates/concat/locales/es.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Voz añadida a la línea de tiempo",
"speech.voiceFrom": "Voz de",
"speech.voiceName": "Nombre de la voz",
+ "speedRamp.bends": "Curvas",
+ "speedRamp.bullet": "Bala",
+ "speedRamp.constant": "Constante",
+ "speedRamp.curve": "Curva",
+ "speedRamp.custom": "Personalizado",
+ "speedRamp.fastest": "Lo más rápido",
+ "speedRamp.flashIn": "Destello de entrada",
+ "speedRamp.flashOut": "Destello de salida",
+ "speedRamp.hero": "Héroe",
+ "speedRamp.howTo": "Haz clic en el gráfico para añadir un punto, arrástralo para dar forma a la rampa y haz doble clic para quitarlo.",
+ "speedRamp.jumpCut": "Corte en salto",
+ "speedRamp.montage": "Montaje",
+ "speedRamp.shape": "Forma",
+ "speedRamp.slowest": "Lo más lento",
+ "speedRamp.smooth": "Suave",
+ "speedRamp.straight": "Recta",
"start.choose": "Elegir…",
"start.chooseAFolder": "Elige una carpeta",
"start.chooseWhereProjectFolder": "Elige dónde irá la carpeta del proyecto",
diff --git a/src/crates/concat/locales/fa.json b/src/crates/concat/locales/fa.json
index 0c9fcb3a..00df898a 100644
--- a/src/crates/concat/locales/fa.json
+++ b/src/crates/concat/locales/fa.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "صدا به تایم‌لاین اضافه شد",
"speech.voiceFrom": "صدا از",
"speech.voiceName": "نامی برای این صدا",
+ "speedRamp.bends": "خمیدگی‌ها",
+ "speedRamp.bullet": "گلوله",
+ "speedRamp.constant": "ثابت",
+ "speedRamp.curve": "منحنی",
+ "speedRamp.custom": "سفارشی",
+ "speedRamp.fastest": "سریع‌ترین",
+ "speedRamp.flashIn": "فلش ورود",
+ "speedRamp.flashOut": "فلش خروج",
+ "speedRamp.hero": "قهرمان",
+ "speedRamp.howTo": "برای افزودن نقطه روی نمودار کلیک کنید، برای شکل‌دادن به شیب آن را بکشید و برای حذف دوبار کلیک کنید.",
+ "speedRamp.jumpCut": "برش پرشی",
+ "speedRamp.montage": "مونتاژ",
+ "speedRamp.shape": "شکل",
+ "speedRamp.slowest": "کندترین",
+ "speedRamp.smooth": "نرم",
+ "speedRamp.straight": "مستقیم",
"start.choose": "انتخاب…",
"start.chooseAFolder": "انتخاب پوشه",
"start.chooseWhereProjectFolder": "محل ذخیره پوشه پروژه را انتخاب کنید",
diff --git a/src/crates/concat/locales/fr.json b/src/crates/concat/locales/fr.json
index 05271a15..9fef2281 100644
--- a/src/crates/concat/locales/fr.json
+++ b/src/crates/concat/locales/fr.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Voix ajoutée à la timeline",
"speech.voiceFrom": "Voix depuis",
"speech.voiceName": "Nom de la voix",
+ "speedRamp.bends": "Courbes",
+ "speedRamp.bullet": "Balle",
+ "speedRamp.constant": "Constante",
+ "speedRamp.curve": "Courbe",
+ "speedRamp.custom": "Personnalisé",
+ "speedRamp.fastest": "Le plus rapide",
+ "speedRamp.flashIn": "Flash d'entrée",
+ "speedRamp.flashOut": "Flash de sortie",
+ "speedRamp.hero": "Héros",
+ "speedRamp.howTo": "Cliquez sur le graphique pour ajouter un point, faites-le glisser pour modeler la rampe, double-cliquez dessus pour le retirer.",
+ "speedRamp.jumpCut": "Jump cut",
+ "speedRamp.montage": "Montage",
+ "speedRamp.shape": "Forme",
+ "speedRamp.slowest": "Le plus lent",
+ "speedRamp.smooth": "Douce",
+ "speedRamp.straight": "Droite",
"start.choose": "Choisir…",
"start.chooseAFolder": "Choisir un dossier",
"start.chooseWhereProjectFolder": "Choisissez où placer le dossier du projet",
diff --git a/src/crates/concat/locales/he.json b/src/crates/concat/locales/he.json
index 3e55d288..f7c9f97c 100644
--- a/src/crates/concat/locales/he.json
+++ b/src/crates/concat/locales/he.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "הקול נוסף לציר הזמן",
"speech.voiceFrom": "קול מתוך",
"speech.voiceName": "שם לקול",
+ "speedRamp.bends": "עיקולים",
+ "speedRamp.bullet": "קליע",
+ "speedRamp.constant": "קבוע",
+ "speedRamp.curve": "עקומה",
+ "speedRamp.custom": "מותאם אישית",
+ "speedRamp.fastest": "המהיר ביותר",
+ "speedRamp.flashIn": "הבזק פנימה",
+ "speedRamp.flashOut": "הבזק החוצה",
+ "speedRamp.hero": "גיבור",
+ "speedRamp.howTo": "לחצו על הגרף כדי להוסיף נקודה, גררו אותה כדי לעצב את השיפוע, ולחצו עליה פעמיים כדי להסיר אותה.",
+ "speedRamp.jumpCut": "קפיצת חיתוך",
+ "speedRamp.montage": "מונטאז'",
+ "speedRamp.shape": "צורה",
+ "speedRamp.slowest": "האיטי ביותר",
+ "speedRamp.smooth": "חלק",
+ "speedRamp.straight": "ישר",
"start.choose": "בחירה…",
"start.chooseAFolder": "בחירת תיקייה",
"start.chooseWhereProjectFolder": "בחירת המיקום של תיקיית הפרויקט",
diff --git a/src/crates/concat/locales/hi.json b/src/crates/concat/locales/hi.json
index c4b4da81..46ef37a3 100644
--- a/src/crates/concat/locales/hi.json
+++ b/src/crates/concat/locales/hi.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "आवाज़ टाइमलाइन में जोड़ी गई",
"speech.voiceFrom": "आवाज़ का स्रोत",
"speech.voiceName": "इस आवाज़ का नाम",
+ "speedRamp.bends": "मोड़",
+ "speedRamp.bullet": "बुलेट",
+ "speedRamp.constant": "स्थिर",
+ "speedRamp.curve": "वक्र",
+ "speedRamp.custom": "कस्टम",
+ "speedRamp.fastest": "सबसे तेज़",
+ "speedRamp.flashIn": "फ़्लैश इन",
+ "speedRamp.flashOut": "फ़्लैश आउट",
+ "speedRamp.hero": "हीरो",
+ "speedRamp.howTo": "बिंदु जोड़ने के लिए ग्राफ़ पर क्लिक करें, रैम्प को आकार देने के लिए उसे खींचें, हटाने के लिए डबल-क्लिक करें।",
+ "speedRamp.jumpCut": "जंप कट",
+ "speedRamp.montage": "मोंटाज",
+ "speedRamp.shape": "आकार",
+ "speedRamp.slowest": "सबसे धीमा",
+ "speedRamp.smooth": "सहज",
+ "speedRamp.straight": "सीधा",
"start.choose": "चुनें…",
"start.chooseAFolder": "फ़ोल्डर चुनें",
"start.chooseWhereProjectFolder": "चुनें कि प्रोजेक्ट फ़ोल्डर कहां रखा जाए",
diff --git a/src/crates/concat/locales/hr.json b/src/crates/concat/locales/hr.json
index aa5165c5..1a4a13f1 100644
--- a/src/crates/concat/locales/hr.json
+++ b/src/crates/concat/locales/hr.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Glas dodan na vremensku liniju",
"speech.voiceFrom": "Glas iz",
"speech.voiceName": "Ime glasa",
+ "speedRamp.bends": "Zavoji",
+ "speedRamp.bullet": "Metak",
+ "speedRamp.constant": "Konstantno",
+ "speedRamp.curve": "Krivulja",
+ "speedRamp.custom": "Prilagođeno",
+ "speedRamp.fastest": "Najbrže",
+ "speedRamp.flashIn": "Bljesak unutra",
+ "speedRamp.flashOut": "Bljesak van",
+ "speedRamp.hero": "Junak",
+ "speedRamp.howTo": "Kliknite na graf da dodate točku, povucite je da oblikujete rampu, dvaput kliknite da je uklonite.",
+ "speedRamp.jumpCut": "Skokoviti rez",
+ "speedRamp.montage": "Montaža",
+ "speedRamp.shape": "Oblik",
+ "speedRamp.slowest": "Najsporije",
+ "speedRamp.smooth": "Glatko",
+ "speedRamp.straight": "Ravno",
"start.choose": "Odaberi…",
"start.chooseAFolder": "Odaberite mapu",
"start.chooseWhereProjectFolder": "Odaberite kamo će mapa projekta",
diff --git a/src/crates/concat/locales/id.json b/src/crates/concat/locales/id.json
index 6c4dfe23..40817510 100644
--- a/src/crates/concat/locales/id.json
+++ b/src/crates/concat/locales/id.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Suara ditambahkan ke linimasa",
"speech.voiceFrom": "Suara dari",
"speech.voiceName": "Nama suara ini",
+ "speedRamp.bends": "Lengkungan",
+ "speedRamp.bullet": "Peluru",
+ "speedRamp.constant": "Konstan",
+ "speedRamp.curve": "Kurva",
+ "speedRamp.custom": "Kustom",
+ "speedRamp.fastest": "Paling cepat",
+ "speedRamp.flashIn": "Kilat masuk",
+ "speedRamp.flashOut": "Kilat keluar",
+ "speedRamp.hero": "Pahlawan",
+ "speedRamp.howTo": "Klik grafik untuk menambah titik, seret untuk membentuk ramp, klik dua kali untuk menghapusnya.",
+ "speedRamp.jumpCut": "Jump cut",
+ "speedRamp.montage": "Montase",
+ "speedRamp.shape": "Bentuk",
+ "speedRamp.slowest": "Paling lambat",
+ "speedRamp.smooth": "Halus",
+ "speedRamp.straight": "Lurus",
"start.choose": "Pilih…",
"start.chooseAFolder": "Pilih folder",
"start.chooseWhereProjectFolder": "Pilih lokasi folder proyek",
diff --git a/src/crates/concat/locales/it.json b/src/crates/concat/locales/it.json
index bdb08dc6..63374bad 100644
--- a/src/crates/concat/locales/it.json
+++ b/src/crates/concat/locales/it.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Voce aggiunta alla timeline",
"speech.voiceFrom": "Voce da",
"speech.voiceName": "Nome della voce",
+ "speedRamp.bends": "Curvature",
+ "speedRamp.bullet": "Proiettile",
+ "speedRamp.constant": "Costante",
+ "speedRamp.curve": "Curva",
+ "speedRamp.custom": "Personalizzato",
+ "speedRamp.fastest": "Più veloce",
+ "speedRamp.flashIn": "Flash in entrata",
+ "speedRamp.flashOut": "Flash in uscita",
+ "speedRamp.hero": "Eroe",
+ "speedRamp.howTo": "Fai clic sul grafico per aggiungere un punto, trascinalo per modellare la rampa, fai doppio clic per toglierlo.",
+ "speedRamp.jumpCut": "Jump cut",
+ "speedRamp.montage": "Montaggio",
+ "speedRamp.shape": "Forma",
+ "speedRamp.slowest": "Più lento",
+ "speedRamp.smooth": "Morbida",
+ "speedRamp.straight": "Dritta",
"start.choose": "Scegli…",
"start.chooseAFolder": "Scegli una cartella",
"start.chooseWhereProjectFolder": "Scegli dove mettere la cartella del progetto",
diff --git a/src/crates/concat/locales/ja.json b/src/crates/concat/locales/ja.json
index 40590451..947da963 100644
--- a/src/crates/concat/locales/ja.json
+++ b/src/crates/concat/locales/ja.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "音声をタイムラインに追加しました",
"speech.voiceFrom": "声の元",
"speech.voiceName": "ボイスの名前",
+ "speedRamp.bends": "カーブの形",
+ "speedRamp.bullet": "バレット",
+ "speedRamp.constant": "一定",
+ "speedRamp.curve": "カーブ",
+ "speedRamp.custom": "カスタム",
+ "speedRamp.fastest": "最速",
+ "speedRamp.flashIn": "フラッシュイン",
+ "speedRamp.flashOut": "フラッシュアウト",
+ "speedRamp.hero": "ヒーロー",
+ "speedRamp.howTo": "グラフをクリックして点を追加し、ドラッグしてランプの形を整え、ダブルクリックで削除します。",
+ "speedRamp.jumpCut": "ジャンプカット",
+ "speedRamp.montage": "モンタージュ",
+ "speedRamp.shape": "形",
+ "speedRamp.slowest": "最遅",
+ "speedRamp.smooth": "なめらか",
+ "speedRamp.straight": "直線",
"start.choose": "選択…",
"start.chooseAFolder": "フォルダーを選択",
"start.chooseWhereProjectFolder": "プロジェクトフォルダーの保存先を選んでください",
diff --git a/src/crates/concat/locales/ko.json b/src/crates/concat/locales/ko.json
index 92962b1f..23a82469 100644
--- a/src/crates/concat/locales/ko.json
+++ b/src/crates/concat/locales/ko.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "음성을 타임라인에 추가했습니다",
"speech.voiceFrom": "목소리 출처",
"speech.voiceName": "목소리 이름",
+ "speedRamp.bends": "곡선 형태",
+ "speedRamp.bullet": "총알",
+ "speedRamp.constant": "일정",
+ "speedRamp.curve": "곡선",
+ "speedRamp.custom": "사용자 지정",
+ "speedRamp.fastest": "가장 빠르게",
+ "speedRamp.flashIn": "플래시 인",
+ "speedRamp.flashOut": "플래시 아웃",
+ "speedRamp.hero": "히어로",
+ "speedRamp.howTo": "그래프를 클릭해 점을 추가하고, 드래그해 램프 모양을 만들고, 더블클릭해 제거하세요.",
+ "speedRamp.jumpCut": "점프 컷",
+ "speedRamp.montage": "몽타주",
+ "speedRamp.shape": "모양",
+ "speedRamp.slowest": "가장 느리게",
+ "speedRamp.smooth": "부드럽게",
+ "speedRamp.straight": "직선",
"start.choose": "선택…",
"start.chooseAFolder": "폴더 선택",
"start.chooseWhereProjectFolder": "프로젝트 폴더를 둘 위치를 선택하세요",
diff --git a/src/crates/concat/locales/nl.json b/src/crates/concat/locales/nl.json
index c0fededb..11a8603f 100644
--- a/src/crates/concat/locales/nl.json
+++ b/src/crates/concat/locales/nl.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Stem toegevoegd aan de tijdlijn",
"speech.voiceFrom": "Stem uit",
"speech.voiceName": "Naam van de stem",
+ "speedRamp.bends": "Bochten",
+ "speedRamp.bullet": "Kogel",
+ "speedRamp.constant": "Constant",
+ "speedRamp.curve": "Curve",
+ "speedRamp.custom": "Aangepast",
+ "speedRamp.fastest": "Snelst",
+ "speedRamp.flashIn": "Flits in",
+ "speedRamp.flashOut": "Flits uit",
+ "speedRamp.hero": "Held",
+ "speedRamp.howTo": "Klik op de grafiek om een punt toe te voegen, sleep het om de ramp te vormen, dubbelklik om het te verwijderen.",
+ "speedRamp.jumpCut": "Jump cut",
+ "speedRamp.montage": "Montage",
+ "speedRamp.shape": "Vorm",
+ "speedRamp.slowest": "Traagst",
+ "speedRamp.smooth": "Vloeiend",
+ "speedRamp.straight": "Recht",
"start.choose": "Kiezen…",
"start.chooseAFolder": "Kies een map",
"start.chooseWhereProjectFolder": "Kies waar de projectmap moet komen",
diff --git a/src/crates/concat/locales/pl.json b/src/crates/concat/locales/pl.json
index 5d4f8839..98b98faf 100644
--- a/src/crates/concat/locales/pl.json
+++ b/src/crates/concat/locales/pl.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Głos dodany do osi czasu",
"speech.voiceFrom": "Głos z",
"speech.voiceName": "Nazwa głosu",
+ "speedRamp.bends": "Łuki",
+ "speedRamp.bullet": "Pocisk",
+ "speedRamp.constant": "Stała",
+ "speedRamp.curve": "Krzywa",
+ "speedRamp.custom": "Własna",
+ "speedRamp.fastest": "Najszybciej",
+ "speedRamp.flashIn": "Błysk na wejście",
+ "speedRamp.flashOut": "Błysk na wyjście",
+ "speedRamp.hero": "Bohater",
+ "speedRamp.howTo": "Kliknij wykres, aby dodać punkt, przeciągnij go, aby ukształtować rampę, kliknij dwukrotnie, aby go usunąć.",
+ "speedRamp.jumpCut": "Jump cut",
+ "speedRamp.montage": "Montaż",
+ "speedRamp.shape": "Kształt",
+ "speedRamp.slowest": "Najwolniej",
+ "speedRamp.smooth": "Płynna",
+ "speedRamp.straight": "Prosta",
"start.choose": "Wybierz…",
"start.chooseAFolder": "Wybierz folder",
"start.chooseWhereProjectFolder": "Wybierz, gdzie ma się znaleźć folder projektu",
diff --git a/src/crates/concat/locales/pt-BR.json b/src/crates/concat/locales/pt-BR.json
index cb3b813c..76c6607f 100644
--- a/src/crates/concat/locales/pt-BR.json
+++ b/src/crates/concat/locales/pt-BR.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Voz adicionada à linha do tempo",
"speech.voiceFrom": "Voz de",
"speech.voiceName": "Nome da voz",
+ "speedRamp.bends": "Curvas",
+ "speedRamp.bullet": "Bala",
+ "speedRamp.constant": "Constante",
+ "speedRamp.curve": "Curva",
+ "speedRamp.custom": "Personalizado",
+ "speedRamp.fastest": "Mais rápido",
+ "speedRamp.flashIn": "Flash de entrada",
+ "speedRamp.flashOut": "Flash de saída",
+ "speedRamp.hero": "Herói",
+ "speedRamp.howTo": "Clique no gráfico para adicionar um ponto, arraste-o para moldar a rampa e clique duas vezes para removê-lo.",
+ "speedRamp.jumpCut": "Jump cut",
+ "speedRamp.montage": "Montagem",
+ "speedRamp.shape": "Forma",
+ "speedRamp.slowest": "Mais lento",
+ "speedRamp.smooth": "Suave",
+ "speedRamp.straight": "Reta",
"start.choose": "Escolher…",
"start.chooseAFolder": "Escolha uma pasta",
"start.chooseWhereProjectFolder": "Escolha onde a pasta do projeto deve ficar",
diff --git a/src/crates/concat/locales/ru.json b/src/crates/concat/locales/ru.json
index fb4af32f..94365af3 100644
--- a/src/crates/concat/locales/ru.json
+++ b/src/crates/concat/locales/ru.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Голос добавлен на таймлайн",
"speech.voiceFrom": "Голос из",
"speech.voiceName": "Имя голоса",
+ "speedRamp.bends": "Изгибы",
+ "speedRamp.bullet": "Пуля",
+ "speedRamp.constant": "Постоянная",
+ "speedRamp.curve": "Кривая",
+ "speedRamp.custom": "Своя",
+ "speedRamp.fastest": "Быстрее всего",
+ "speedRamp.flashIn": "Вспышка на входе",
+ "speedRamp.flashOut": "Вспышка на выходе",
+ "speedRamp.hero": "Герой",
+ "speedRamp.howTo": "Щёлкните по графику, чтобы добавить точку, перетащите её, чтобы задать форму, дважды щёлкните, чтобы удалить.",
+ "speedRamp.jumpCut": "Джамп-кат",
+ "speedRamp.montage": "Монтаж",
+ "speedRamp.shape": "Форма",
+ "speedRamp.slowest": "Медленнее всего",
+ "speedRamp.smooth": "Плавно",
+ "speedRamp.straight": "Прямо",
"start.choose": "Выбрать…",
"start.chooseAFolder": "Выберите папку",
"start.chooseWhereProjectFolder": "Выберите, где будет папка проекта",
diff --git a/src/crates/concat/locales/th.json b/src/crates/concat/locales/th.json
index 739ca54c..8ed5140b 100644
--- a/src/crates/concat/locales/th.json
+++ b/src/crates/concat/locales/th.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "เพิ่มเสียงพูดลงไทม์ไลน์แล้ว",
"speech.voiceFrom": "เสียงจาก",
"speech.voiceName": "ตั้งชื่อเสียงพูดนี้",
+ "speedRamp.bends": "ความโค้ง",
+ "speedRamp.bullet": "กระสุน",
+ "speedRamp.constant": "คงที่",
+ "speedRamp.curve": "เส้นโค้ง",
+ "speedRamp.custom": "กำหนดเอง",
+ "speedRamp.fastest": "เร็วที่สุด",
+ "speedRamp.flashIn": "แฟลชเข้า",
+ "speedRamp.flashOut": "แฟลชออก",
+ "speedRamp.hero": "ฮีโร่",
+ "speedRamp.howTo": "คลิกที่กราฟเพื่อเพิ่มจุด ลากเพื่อปรับรูปทรง และดับเบิลคลิกเพื่อลบ",
+ "speedRamp.jumpCut": "จัมพ์คัท",
+ "speedRamp.montage": "มอนทาจ",
+ "speedRamp.shape": "รูปทรง",
+ "speedRamp.slowest": "ช้าที่สุด",
+ "speedRamp.smooth": "นุ่มนวล",
+ "speedRamp.straight": "ตรง",
"start.choose": "เลือก…",
"start.chooseAFolder": "เลือกโฟลเดอร์",
"start.chooseWhereProjectFolder": "เลือกตำแหน่งของโฟลเดอร์โปรเจกต์",
diff --git a/src/crates/concat/locales/tr.json b/src/crates/concat/locales/tr.json
index 3acbd3ff..a93ea5e4 100644
--- a/src/crates/concat/locales/tr.json
+++ b/src/crates/concat/locales/tr.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Ses zaman çizelgesine eklendi",
"speech.voiceFrom": "Ses kaynağı",
"speech.voiceName": "Bu sesin adı",
+ "speedRamp.bends": "Kıvrımlar",
+ "speedRamp.bullet": "Kurşun",
+ "speedRamp.constant": "Sabit",
+ "speedRamp.curve": "Eğri",
+ "speedRamp.custom": "Özel",
+ "speedRamp.fastest": "En hızlı",
+ "speedRamp.flashIn": "Flaş giriş",
+ "speedRamp.flashOut": "Flaş çıkış",
+ "speedRamp.hero": "Kahraman",
+ "speedRamp.howTo": "Nokta eklemek için grafiğe tıklayın, rampayı şekillendirmek için sürükleyin, kaldırmak için çift tıklayın.",
+ "speedRamp.jumpCut": "Atlamalı kesme",
+ "speedRamp.montage": "Montaj",
+ "speedRamp.shape": "Şekil",
+ "speedRamp.slowest": "En yavaş",
+ "speedRamp.smooth": "Yumuşak",
+ "speedRamp.straight": "Düz",
"start.choose": "Seç…",
"start.chooseAFolder": "Bir klasör seçin",
"start.chooseWhereProjectFolder": "Proje klasörünün nereye gideceğini seçin",
diff --git a/src/crates/concat/locales/uk.json b/src/crates/concat/locales/uk.json
index c41a3b99..f80c4767 100644
--- a/src/crates/concat/locales/uk.json
+++ b/src/crates/concat/locales/uk.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Голос додано на часову шкалу",
"speech.voiceFrom": "Джерело голосу",
"speech.voiceName": "Назва голосу",
+ "speedRamp.bends": "Вигини",
+ "speedRamp.bullet": "Куля",
+ "speedRamp.constant": "Стала",
+ "speedRamp.curve": "Крива",
+ "speedRamp.custom": "Власна",
+ "speedRamp.fastest": "Найшвидше",
+ "speedRamp.flashIn": "Спалах на вході",
+ "speedRamp.flashOut": "Спалах на виході",
+ "speedRamp.hero": "Герой",
+ "speedRamp.howTo": "Клацніть на графіку, щоб додати точку, перетягніть її, щоб задати форму, двічі клацніть, щоб видалити.",
+ "speedRamp.jumpCut": "Джамп-кат",
+ "speedRamp.montage": "Монтаж",
+ "speedRamp.shape": "Форма",
+ "speedRamp.slowest": "Найповільніше",
+ "speedRamp.smooth": "Плавно",
+ "speedRamp.straight": "Прямо",
"start.choose": "Вибрати…",
"start.chooseAFolder": "Виберіть папку",
"start.chooseWhereProjectFolder": "Виберіть, де розмістити папку проєкту",
diff --git a/src/crates/concat/locales/ur.json b/src/crates/concat/locales/ur.json
index cc585e83..fb2a7fe0 100644
--- a/src/crates/concat/locales/ur.json
+++ b/src/crates/concat/locales/ur.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "آواز ٹائم لائن میں شامل ہو گئی",
"speech.voiceFrom": "آواز کا ماخذ",
"speech.voiceName": "اس صوت کا نام",
+ "speedRamp.bends": "موڑ",
+ "speedRamp.bullet": "گولی",
+ "speedRamp.constant": "مستقل",
+ "speedRamp.curve": "منحنی",
+ "speedRamp.custom": "حسبِ منشا",
+ "speedRamp.fastest": "سب سے تیز",
+ "speedRamp.flashIn": "فلیش اِن",
+ "speedRamp.flashOut": "فلیش آؤٹ",
+ "speedRamp.hero": "ہیرو",
+ "speedRamp.howTo": "نقطہ شامل کرنے کے لیے گراف پر کلک کریں، ریمپ کی شکل دینے کے لیے اسے گھسیٹیں، ہٹانے کے لیے ڈبل کلک کریں۔",
+ "speedRamp.jumpCut": "جمپ کٹ",
+ "speedRamp.montage": "مونتاژ",
+ "speedRamp.shape": "شکل",
+ "speedRamp.slowest": "سب سے سست",
+ "speedRamp.smooth": "ہموار",
+ "speedRamp.straight": "سیدھا",
"start.choose": "چنیں…",
"start.chooseAFolder": "فولڈر چنیں",
"start.chooseWhereProjectFolder": "چنیں کہ پروجیکٹ فولڈر کہاں جائے",
diff --git a/src/crates/concat/locales/vi.json b/src/crates/concat/locales/vi.json
index 74b19d96..17ade7c1 100644
--- a/src/crates/concat/locales/vi.json
+++ b/src/crates/concat/locales/vi.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "Đã thêm giọng nói vào dòng thời gian",
"speech.voiceFrom": "Giọng từ",
"speech.voiceName": "Đặt tên cho giọng này",
+ "speedRamp.bends": "Đường cong",
+ "speedRamp.bullet": "Viên đạn",
+ "speedRamp.constant": "Không đổi",
+ "speedRamp.curve": "Đường cong tốc độ",
+ "speedRamp.custom": "Tùy chỉnh",
+ "speedRamp.fastest": "Nhanh nhất",
+ "speedRamp.flashIn": "Lóe vào",
+ "speedRamp.flashOut": "Lóe ra",
+ "speedRamp.hero": "Anh hùng",
+ "speedRamp.howTo": "Nhấp vào biểu đồ để thêm điểm, kéo để tạo hình đoạn dốc, nhấp đúp để xóa.",
+ "speedRamp.jumpCut": "Jump cut",
+ "speedRamp.montage": "Montage",
+ "speedRamp.shape": "Hình dạng",
+ "speedRamp.slowest": "Chậm nhất",
+ "speedRamp.smooth": "Mượt",
+ "speedRamp.straight": "Thẳng",
"start.choose": "Chọn…",
"start.chooseAFolder": "Chọn thư mục",
"start.chooseWhereProjectFolder": "Chọn nơi lưu thư mục dự án",
diff --git a/src/crates/concat/locales/zh-Hans.json b/src/crates/concat/locales/zh-Hans.json
index e886bb9a..5eacf02c 100644
--- a/src/crates/concat/locales/zh-Hans.json
+++ b/src/crates/concat/locales/zh-Hans.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "语音已添加到时间线",
"speech.voiceFrom": "语音来源",
"speech.voiceName": "给这个嗓音命名",
+ "speedRamp.bends": "弯曲",
+ "speedRamp.bullet": "子弹",
+ "speedRamp.constant": "恒定",
+ "speedRamp.curve": "曲线",
+ "speedRamp.custom": "自定义",
+ "speedRamp.fastest": "最快",
+ "speedRamp.flashIn": "闪入",
+ "speedRamp.flashOut": "闪出",
+ "speedRamp.hero": "英雄",
+ "speedRamp.howTo": "点击图表添加一个点,拖动它塑造变速,双击将其删除。",
+ "speedRamp.jumpCut": "跳切",
+ "speedRamp.montage": "蒙太奇",
+ "speedRamp.shape": "形状",
+ "speedRamp.slowest": "最慢",
+ "speedRamp.smooth": "平滑",
+ "speedRamp.straight": "直线",
"start.choose": "选择…",
"start.chooseAFolder": "选择文件夹",
"start.chooseWhereProjectFolder": "选择项目文件夹的存放位置",
diff --git a/src/crates/concat/locales/zh-TW.json b/src/crates/concat/locales/zh-TW.json
index a32ca2e3..4acefabf 100644
--- a/src/crates/concat/locales/zh-TW.json
+++ b/src/crates/concat/locales/zh-TW.json
@@ -608,6 +608,22 @@
"speech.voiceAddedTimeline": "語音已加入時間軸",
"speech.voiceFrom": "語音來源",
"speech.voiceName": "為這個嗓音命名",
+ "speedRamp.bends": "彎曲",
+ "speedRamp.bullet": "子彈",
+ "speedRamp.constant": "恆定",
+ "speedRamp.curve": "曲線",
+ "speedRamp.custom": "自訂",
+ "speedRamp.fastest": "最快",
+ "speedRamp.flashIn": "閃入",
+ "speedRamp.flashOut": "閃出",
+ "speedRamp.hero": "英雄",
+ "speedRamp.howTo": "點擊圖表新增一個點,拖曳它塑造變速,按兩下將其移除。",
+ "speedRamp.jumpCut": "跳接",
+ "speedRamp.montage": "蒙太奇",
+ "speedRamp.shape": "形狀",
+ "speedRamp.slowest": "最慢",
+ "speedRamp.smooth": "平滑",
+ "speedRamp.straight": "直線",
"start.choose": "選擇…",
"start.chooseAFolder": "選擇資料夾",
"start.chooseWhereProjectFolder": "選擇專案資料夾的存放位置",
diff --git a/src/crates/concat/src/lib.rs b/src/crates/concat/src/lib.rs
index 03c7bb95..5adb01ff 100644
--- a/src/crates/concat/src/lib.rs
+++ b/src/crates/concat/src/lib.rs
@@ -62,6 +62,7 @@ mod panes;
mod prefs;
mod presets;
mod source;
+mod speed_ramp;
mod studio;
mod sysinfo;
/// Native Wayland file drops, which winit does not report; see the module.
@@ -380,6 +381,9 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
.set_rows(ModelRc::from(models.key_rows.clone()));
app.global::<KeyEditor>()
.set_rows(ModelRc::from(models.key_editor_rows.clone()));
+ let ramp = app.global::<SpeedRamp>();
+ ramp.set_points(ModelRc::from(models.speed_points.clone()));
+ ramp.set_presets(ModelRc::from(models.speed_presets.clone()));
editor.set_key_marks(ModelRc::from(models.key_marks.clone()));
app.global::<Library>()
.set_views(ModelRc::from(models.library_views.clone()));
@@ -1192,6 +1196,30 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
state.frame_selected(fill);
}));
}
+ // The Speed tab's curve. Its own global, like the keyframe cluster's,
+ // since the Speed panel sits in three places; each verb edits the echo
+ // and the panel commits.
+ {
+ let ramp = app.global::<SpeedRamp>();
+ ramp.on_curve(on_lanes!(|state, on: bool| {
+ state.speed_curve_set(on);
+ }));
+ ramp.on_point(on_lanes!(|state, index: i32, x: f32, y: f32| {
+ state.speed_curve_point(index, x, y);
+ }));
+ ramp.on_remove(on_lanes!(|state, index: i32| {
+ state.speed_curve_remove(index);
+ }));
+ ramp.on_preset_chosen(on_lanes!(|state, index: i32| {
+ state.speed_curve_preset(index);
+ }));
+ ramp.on_smoothness(on_lanes!(|state, smooth: bool| {
+ state.speed_curve_smooth(smooth);
+ }));
+ ramp.on_extreme(on_lanes!(|state, faster: bool, speed: f32| {
+ state.speed_curve_extreme(faster, speed);
+ }));
+ }
// The Keyframes panel's verbs; its rows go out with every publish.
{
let editor = app.global::<KeyEditor>();
diff --git a/src/crates/concat/src/speed_ramp.rs b/src/crates/concat/src/speed_ramp.rs
new file mode 100644
index 00000000..db87b518
--- /dev/null
+++ b/src/crates/concat/src/speed_ramp.rs
@@ -0,0 +1,331 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! The Speed tab's curve, as the inspector reads and edits it.
+//!
+//! The document holds a curve as `(at, speed)` points over the clip (see
+//! concat-project's `speed`); the graph shows speed on a scale of
+//! doublings, so a point's height is `log2(speed)` mapped from the engine's
+//! range, 1/16x to 16x, onto `0..1`. Here is the arithmetic between the two
+//! and the edits a drag makes; what the speed does to the picture is the
+//! engine's `SpeedCurve`.
+
+use concat_project::model::SpeedPoint;
+use concat_project::model::ranges::{MAX_SPEED, MIN_SPEED};
+use concat_project::speed::{PRESETS, curve_of, preset_of};
+
+use crate::i18n::t;
+
+/// The two ends' heights on the graph, in doublings either side of 1x.
+const DOUBLINGS: f64 = 4.0;
+/// How close two points may come in time: a hair, so a drag can make the
+/// near-vertical step of a jump without the two swapping places.
+const GAP: f64 = 0.002;
+
+/// Where `speed` sits on the graph, `0..1`.
+pub fn height_of(speed: f64) -> f64 {
+ ((speed.clamp(MIN_SPEED, MAX_SPEED).log2() + DOUBLINGS) / (2.0 * DOUBLINGS)).clamp(0.0, 1.0)
+}
+
+/// The speed at height `y` of the graph.
+pub fn speed_at_height(y: f64) -> f64 {
+ let y = if y.is_finite() {
+ y.clamp(0.0, 1.0)
+ } else {
+ 0.5
+ };
+ (y * 2.0 * DOUBLINGS - DOUBLINGS)
+ .exp2()
+ .clamp(MIN_SPEED, MAX_SPEED)
+}
+
+/// A curve that is one rate the whole way, smooth: what Curve starts
+/// from, so switching to it changes nothing until a point moves.
+pub fn flat(speed: f64) -> Vec<SpeedPoint> {
+ let point = |at| SpeedPoint {
+ at,
+ speed,
+ slope: Some(0.0),
+ };
+ vec![point(0.0), point(1.0)]
+}
+
+/// The curve made smooth - easing in and out of every point - or joined
+/// by straight lines.
+pub fn set_smooth(points: &mut [SpeedPoint], smooth: bool) {
+ for point in points {
+ point.slope = smooth.then_some(0.0);
+ }
+}
+
+/// The fastest the curve goes, when it goes faster than 1x anywhere, or
+/// the slowest, when it goes slower: what the Speed tab's two sliders
+/// show. A curve's extremes are at its points, since no stretch overshoots.
+pub fn extreme(points: &[SpeedPoint], faster: bool) -> Option<f64> {
+ let speeds = points.iter().map(|point| point.speed);
+ if faster {
+ speeds
+ .fold(None, |most: Option<f64>, speed| {
+ Some(most.map_or(speed, |most| most.max(speed)))
+ })
+ .filter(|&most| most > 1.0 + 1e-6)
+ } else {
+ speeds
+ .fold(None, |least: Option<f64>, speed| {
+ Some(least.map_or(speed, |least| least.min(speed)))
+ })
+ .filter(|&least| least < 1.0 - 1e-6)
+ }
+}
+
+/// The nearest a slider may bring its extreme to 1x: the stretch past 1x
+/// is then still there to be shown and pulled out again.
+pub const NEAREST: f64 = 0.1;
+
+/// The fast stretches of the curve (or the slow ones) brought to
+/// `target` at their extreme, the rest of each stretch following in
+/// proportion on the graph's scale: a Flash in that peaks at 8x and is
+/// brought to 4x passes 2.5x where it passed 4x. The speeds at or the other
+/// side of 1x stay as they are. Each point's slope follows its speed, so a
+/// smooth curve keeps its shape.
+pub fn set_extreme(points: &mut [SpeedPoint], faster: bool, target: f64) {
+ let Some(extreme) = extreme(points, faster) else {
+ return;
+ };
+ let target = if faster {
+ target.clamp(1.0 + NEAREST, MAX_SPEED)
+ } else {
+ target.clamp(MIN_SPEED, 1.0 - NEAREST)
+ };
+ if !target.is_finite() {
+ return;
+ }
+ // Speeds on the graph's scale are logarithms, so bringing the extreme
+ // to the target is one power over every speed on its side of 1x.
+ let power = target.ln() / extreme.ln();
+ for point in points {
+ let beyond = if faster {
+ point.speed > 1.0
+ } else {
+ point.speed < 1.0
+ };
+ if !beyond {
+ continue;
+ }
+ let speed = point.speed.powf(power).clamp(MIN_SPEED, MAX_SPEED);
+ point.slope = point
+ .slope
+ .map(|slope| slope * power * point.speed.powf(power - 1.0));
+ point.speed = speed;
+ }
+}
+
+/// Point `index` moved to `(x, y)` on the graph, or a new point put down
+/// there when `index` is negative. The ends stay at the clip's ends and a
+/// point between them stays between its neighbours, so the indices the
+/// graph holds still name the same points mid-drag.
+pub fn set_point(points: &mut Vec<SpeedPoint>, index: i32, x: f64, y: f64) {
+ let speed = speed_at_height(y);
+ let x = if x.is_finite() {
+ x.clamp(0.0, 1.0)
+ } else {
+ 0.5
+ };
+ let Ok(index) = usize::try_from(index) else {
+ // A new point goes in where it falls in time, never on an end.
+ let x = x.clamp(GAP, 1.0 - GAP);
+ let at = points.partition_point(|point| point.at <= x);
+ // It bends as the rest of the curve does.
+ let slope = concat_project::speed::is_smooth(points).then_some(0.0);
+ points.insert(
+ at,
+ SpeedPoint {
+ at: x,
+ speed,
+ slope,
+ },
+ );
+ return;
+ };
+ let last = points.len().saturating_sub(1);
+ if index > last {
+ return;
+ }
+ let at = if index == 0 {
+ 0.0
+ } else if index == last {
+ 1.0
+ } else {
+ x.clamp(points[index - 1].at + GAP, points[index + 1].at - GAP)
+ };
+ points[index] = SpeedPoint {
+ at,
+ speed,
+ slope: points[index].slope,
+ };
+}
+
+/// Point `index` taken off. The two ends stay: a curve spans the clip.
+pub fn remove_point(points: &mut Vec<SpeedPoint>, index: i32) {
+ match usize::try_from(index) {
+ Ok(index) if index > 0 && index + 1 < points.len() => {
+ points.remove(index);
+ }
+ _ => {}
+ }
+}
+
+/// The curve drawn in a unit box, y downwards, on the graph's scale: a
+/// line through its points, and for a smooth curve sixteen steps along
+/// each bend between them.
+pub fn path(points: &[SpeedPoint]) -> String {
+ let Some(curve) = curve_of(points) else {
+ return String::new();
+ };
+ let smooth = curve.slopes().is_some();
+ let knots = curve.points();
+ let mut path = String::new();
+ let mut to = |verb: char, x: f64, speed: f64| {
+ let y = 1.0 - height_of(speed);
+ path.push_str(&format!("{verb} {x:.4} {y:.4} "));
+ };
+ to('M', knots[0].0, knots[0].1);
+ for pair in knots.windows(2) {
+ let ((x0, _), (x1, speed)) = (pair[0], pair[1]);
+ if smooth && x1 > x0 {
+ for step in 1..16 {
+ let x = x0 + (x1 - x0) * f64::from(step) / 16.0;
+ to('L', x, curve.speed_at(x));
+ }
+ }
+ to('L', x1, speed);
+ }
+ path.trim_end().to_owned()
+}
+
+/// The presets' names, in the order [`PRESETS`] lists them.
+pub fn preset_names() -> Vec<String> {
+ PRESETS
+ .iter()
+ .map(|preset| match preset.id {
+ "montage" => t("speedRamp.montage"),
+ "hero" => t("speedRamp.hero"),
+ "bullet" => t("speedRamp.bullet"),
+ "jump-cut" => t("speedRamp.jumpCut"),
+ "flash-in" => t("speedRamp.flashIn"),
+ "flash-out" => t("speedRamp.flashOut"),
+ other => other.to_owned(),
+ })
+ .collect()
+}
+
+/// The preset these points still are, as an index into [`PRESETS`], or -1
+/// once they have been shaped by hand.
+pub fn preset_index(points: &[SpeedPoint]) -> i32 {
+ preset_of(points)
+ .and_then(|id| PRESETS.iter().position(|preset| preset.id == id))
+ .map_or(-1, |index| index as i32)
+}
+
+/// The points of preset `index`, or None for an index past the list.
+pub fn preset_points(index: i32) -> Option<Vec<SpeedPoint>> {
+ let preset = PRESETS.get(usize::try_from(index).ok()?)?;
+ concat_project::speed::preset(preset.id)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_scale_is_doublings_with_one_in_the_middle() {
+ assert!((height_of(1.0) - 0.5).abs() < 1e-12);
+ assert!((height_of(MIN_SPEED)).abs() < 1e-12);
+ assert!((height_of(MAX_SPEED) - 1.0).abs() < 1e-12);
+ assert!((height_of(2.0) - 0.5 - (0.5 - height_of(0.5))).abs() < 1e-12);
+ for speed in [0.1, 0.5, 1.0, 3.0, 12.0] {
+ assert!((speed_at_height(height_of(speed)) - speed).abs() < 1e-9);
+ }
+ }
+
+ #[test]
+ fn the_ends_stay_put_and_the_middle_stays_between() {
+ let mut points = flat(1.0);
+ set_point(&mut points, -1, 0.5, height_of(4.0));
+ assert_eq!(points.len(), 3);
+ assert!((points[1].speed - 4.0).abs() < 1e-9);
+ // An end only moves in speed.
+ set_point(&mut points, 0, 0.4, height_of(2.0));
+ assert_eq!(points[0].at, 0.0);
+ assert!((points[0].speed - 2.0).abs() < 1e-9);
+ // The middle cannot pass an end.
+ set_point(&mut points, 1, 1.0, 0.5);
+ assert!(points[1].at < 1.0);
+ // The ends do not come off; the middle does.
+ remove_point(&mut points, 0);
+ remove_point(&mut points, 2);
+ assert_eq!(points.len(), 3);
+ remove_point(&mut points, 1);
+ assert_eq!(points.len(), 2);
+ }
+
+ #[test]
+ fn a_slider_brings_the_extreme_and_its_side_along() {
+ let mut points = preset_points(4).unwrap(); // Flash in: 8x, 4x, 1x, 1x
+ assert_eq!(extreme(&points, true), Some(8.0));
+ assert_eq!(extreme(&points, false), None, "nothing is slower than 1x");
+ set_extreme(&mut points, true, 4.0);
+ assert!((points[0].speed - 4.0).abs() < 1e-9);
+ // 8x is three doublings and 4x two: every fast speed keeps two
+ // thirds of its doublings, so 4x becomes 2^(4/3).
+ assert!(
+ (points[1].speed - 4f64.powf(2.0 / 3.0)).abs() < 1e-9,
+ "in proportion on the scale"
+ );
+ assert!((points[2].speed - 1.0).abs() < 1e-12, "1x stays");
+ // Absolute, not relative: the same target twice changes nothing.
+ let once = points.clone();
+ set_extreme(&mut points, true, 4.0);
+ for (again, before) in points.iter().zip(&once) {
+ assert!((again.speed - before.speed).abs() < 1e-9);
+ }
+ // It never flattens the stretch away.
+ set_extreme(&mut points, true, 1.0);
+ assert!(extreme(&points, true).is_some());
+ }
+
+ #[test]
+ fn smooth_or_straight_is_every_point_or_none() {
+ let mut points = flat(1.0);
+ assert!(concat_project::speed::is_smooth(&points));
+ set_point(&mut points, -1, 0.5, 0.8);
+ assert!(concat_project::speed::is_smooth(&points));
+ set_smooth(&mut points, false);
+ assert!(points.iter().all(|point| point.slope.is_none()));
+ set_point(&mut points, -1, 0.3, 0.2);
+ assert!(points.iter().all(|point| point.slope.is_none()));
+ // A smooth path bends; a straight one is its points.
+ assert_eq!(path(&points).matches('L').count(), points.len() - 1);
+ set_smooth(&mut points, true);
+ assert!(path(&points).matches('L').count() > points.len() * 8);
+ }
+
+ #[test]
+ fn a_new_point_lands_in_time_order() {
+ let mut points = flat(1.0);
+ set_point(&mut points, -1, 0.7, 0.5);
+ set_point(&mut points, -1, 0.2, 0.5);
+ let ats: Vec<f64> = points.iter().map(|point| point.at).collect();
+ assert_eq!(ats, vec![0.0, 0.2, 0.7, 1.0]);
+ }
+
+ #[test]
+ fn a_preset_is_named_until_it_is_shaped() {
+ let mut points = preset_points(1).unwrap();
+ assert_eq!(preset_index(&points), 1);
+ let at = points[2].at;
+ set_point(&mut points, 2, at, 0.9);
+ assert_eq!(preset_index(&points), -1);
+ assert!(preset_points(99).is_none());
+ }
+}
diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rs
index f5653c0f..4aa661eb 100644
--- a/src/crates/concat/src/studio.rs
+++ b/src/crates/concat/src/studio.rs
@@ -70,6 +70,7 @@ use crate::panes::settings::installed;
use crate::platform;
use crate::prefs::Preferences;
use crate::presets::{self, TextPreset};
+use crate::speed_ramp;
use crate::ui::*;
/// The monitor's output sizes, matching the picker's rows.
@@ -651,6 +652,10 @@ pub struct Models {
pub link_wheels: RefCell<HashMap<i32, Rc<VecModel<WheelData>>>>,
pub link_curves: RefCell<HashMap<i32, Rc<VecModel<CurveData>>>>,
pub curve_points: RefCell<HashMap<(i32, String), Rc<VecModel<CurvePointData>>>>,
+ /// The Speed tab's curve: its points and the presets' names, kept like
+ /// the colour curves' so a point being dragged is not dropped.
+ pub speed_points: Rc<VecModel<CurvePointData>>,
+ pub speed_presets: Rc<VecModel<SharedString>>,
/// The keyframe cluster's rows and the libraries' views: synced like
/// the rest, since a model handed over fresh is unequal to the last by
/// identity and re-evaluates every binding on it.
@@ -734,6 +739,8 @@ impl Models {
link_wheels: RefCell::new(HashMap::new()),
link_curves: RefCell::new(HashMap::new()),
curve_points: RefCell::new(HashMap::new()),
+ speed_points: Rc::new(VecModel::default()),
+ speed_presets: Rc::new(VecModel::default()),
key_rows: Rc::new(VecModel::default()),
key_editor_rows: Rc::new(VecModel::default()),
key_marks: Rc::new(VecModel::default()),
@@ -1508,7 +1515,7 @@ fn command_name(command: &Command) -> String {
/// stabilization, a speed, the
/// keys, and one patch for everything else that differs. Empty when
/// nothing does.
-fn clip_commands(id: &str, before: &Clip, after: &Clip) -> Vec<Command> {
+fn clip_commands(id: &str, before: &Clip, after: &Clip, magnetic: bool) -> Vec<Command> {
let mut commands = Vec::new();
if after.scale != before.scale
|| after.offset_x != before.offset_x
@@ -1539,9 +1546,26 @@ fn clip_commands(id: &str, before: &Clip, after: &Clip) -> Vec<Command> {
stabilize: after.stabilize,
});
}
- if after.speed != before.speed {
+ if after.speed_curve != before.speed_curve {
+ // A curve, changed or new, is one command; a curve taken away is
+ // the constant rate the echo left, which SetClipSpeed sets and
+ // which ends the curve.
+ commands.push(match &after.speed_curve {
+ Some(_) => Command::SetClipSpeedCurve {
+ clip_id: id.to_owned(),
+ ripple: magnetic,
+ curve: after.speed_curve.clone(),
+ },
+ None => Command::SetClipSpeed {
+ clip_id: id.to_owned(),
+ ripple: magnetic,
+ speed: after.speed,
+ },
+ });
+ } else if after.speed != before.speed {
commands.push(Command::SetClipSpeed {
clip_id: id.to_owned(),
+ ripple: magnetic,
speed: after.speed,
});
}
@@ -2104,12 +2128,14 @@ fn copy_commands(source: &Clip, placed: &Clip, track_id: &str, start: f64) -> Ve
if (source.speed - 1.0).abs() > 1e-9 {
commands.push(Command::SetClipSpeed {
clip_id: created.clone(),
+ ripple: false,
speed: source.speed,
});
}
if source.speed_curve.is_some() {
commands.push(Command::SetClipSpeedCurve {
clip_id: created.clone(),
+ ripple: false,
curve: source.speed_curve.clone(),
});
}
@@ -4432,6 +4458,92 @@ impl Studio {
});
}
+ /// The Speed tab's Constant | Curve, on the echo. A curve starts flat
+ /// at the clip's rate and a constant rate is the curve's mean, so the
+ /// clip keeps its length either way until something is shaped.
+ pub fn speed_curve_set(&mut self, on: bool) {
+ self.edit_speed_curve(|points, speed| match (on, points.is_some()) {
+ (true, false) => *points = Some(speed_ramp::flat(speed)),
+ (false, true) => *points = None,
+ _ => {}
+ });
+ }
+
+ /// One point of the Speed tab's curve, on the echo: moved, or put down
+ /// when `point` is negative. `y` is the graph's height for the speed.
+ pub fn speed_curve_point(&mut self, point: i32, x: f32, y: f32) {
+ self.edit_speed_curve(|points, _| {
+ if let Some(points) = points.as_mut() {
+ speed_ramp::set_point(points, point, x.into(), y.into());
+ }
+ });
+ }
+
+ /// One point of the Speed tab's curve taken off, on the echo.
+ pub fn speed_curve_remove(&mut self, point: i32) {
+ self.edit_speed_curve(|points, _| {
+ if let Some(points) = points.as_mut() {
+ speed_ramp::remove_point(points, point);
+ }
+ });
+ }
+
+ /// The Speed tab's curve made smooth or straight, on the echo.
+ pub fn speed_curve_smooth(&mut self, smooth: bool) {
+ self.edit_speed_curve(|points, _| {
+ if let Some(points) = points.as_mut() {
+ speed_ramp::set_smooth(points, smooth);
+ }
+ });
+ }
+
+ /// The Speed tab's curve brought to `speed` at its fastest (or its
+ /// slowest), on the echo: one of the tab's two sliders.
+ pub fn speed_curve_extreme(&mut self, faster: bool, speed: f32) {
+ self.edit_speed_curve(|points, _| {
+ if let Some(points) = points.as_mut() {
+ speed_ramp::set_extreme(points, faster, speed.into());
+ }
+ });
+ }
+
+ /// The Speed tab's curve replaced by preset `index`'s, on the echo.
+ pub fn speed_curve_preset(&mut self, index: i32) {
+ self.edit_speed_curve(|points, _| {
+ if let Some(preset) = speed_ramp::preset_points(index) {
+ *points = Some(preset);
+ }
+ });
+ }
+
+ /// The selected clip's curve on the echo, handed to `edit` with the
+ /// clip's rate; the rate and the length then follow the curve the way
+ /// SetClipSpeedCurve will make them, so the timeline shows the clip
+ /// growing and shrinking under the pointer. Nothing for a clip that has
+ /// no speed - a still, a title.
+ fn edit_speed_curve(&mut self, edit: impl FnOnce(&mut Option<Vec<model::SpeedPoint>>, f64)) {
+ let Some(id) = self.sole_selection() else {
+ return;
+ };
+ self.commit_targets = vec![id.clone()];
+ self.begin_echo();
+ let Some(clip) = self.echo_clip_mut(&id) else {
+ return;
+ };
+ if !matches!(clip.kind, model::ClipKind::Video | model::ClipKind::Audio) {
+ return;
+ }
+ let covered = clip.duration * clip.speed;
+ let mut points = clip.speed_curve.clone();
+ edit(&mut points, clip.speed);
+ if let Some(curve) = points.as_deref() {
+ let mean = concat_project::speed::mean_of(curve).clamp(0.0625, 16.0);
+ clip.speed = mean;
+ clip.duration = (covered / mean).max(f64::from(MIN_DURATION));
+ }
+ clip.speed_curve = points;
+ }
+
/// One point of one of the colour panel's curves, on the echo: moved,
/// or put down when `point` is negative.
pub fn adjust_curve_point(&mut self, key: &str, point: i32, x: f32, y: f32) {
@@ -5169,10 +5281,13 @@ impl Studio {
write_keyable(clip, model::KeyProperty::Volume, value.max(0.0), at)
}
ClipField::Speed => {
+ // A rate set by hand is a constant rate: the curve goes,
+ // as SetClipSpeed takes it.
let speed = value.clamp(0.0625, 16.0);
clip.duration =
(clip.duration * clip.speed / speed).max(f64::from(MIN_DURATION));
clip.speed = speed;
+ clip.speed_curve = None;
}
ClipField::PreservePitch => clip.preserve_pitch = value != 0.0,
ClipField::FlipH => clip.flip_h = value != 0.0,
@@ -5526,7 +5641,7 @@ impl Studio {
) else {
continue;
};
- commands.extend(clip_commands(id, before, after));
+ commands.extend(clip_commands(id, before, after, self.prefs.magnetic));
}
if commands.is_empty() {
return;
@@ -9007,6 +9122,7 @@ impl Studio {
.and_then(|id| self.clip(&id))
.map_or(0.0, |clip| place_in(clip, self.playhead) as f32),
);
+ self.publish_speed_ramp(app, models);
let rows = self.key_rows();
keys.set_available(!rows.is_empty());
sync(&models.key_rows, rows);
@@ -9318,6 +9434,44 @@ impl Studio {
/// Outside is not clamped to an end: a key put on from outside the clip
/// would land on its first or last frame, which is never what the person
/// pressing the diamond meant.
+ /// The Speed tab's curve for the selected clip: its points on the
+ /// graph's scale, the line through them, whether it bends, which preset
+ /// it still is, where the playhead crosses it, and its two extremes.
+ fn publish_speed_ramp(&self, app: &App, models: &Models) {
+ let ramp = app.global::<SpeedRamp>();
+ if models.speed_presets.row_count() == 0 {
+ sync(
+ &models.speed_presets,
+ speed_ramp::preset_names()
+ .into_iter()
+ .map(SharedString::from)
+ .collect(),
+ );
+ }
+ let clip = self.sole_selection().and_then(|id| self.clip(&id));
+ let curve = clip.and_then(|clip| clip.speed_curve.as_deref());
+ let points = curve.unwrap_or_default();
+ sync(
+ &models.speed_points,
+ points
+ .iter()
+ .enumerate()
+ .map(|(index, point)| CurvePointData {
+ index: index as i32,
+ x: point.at as f32,
+ y: speed_ramp::height_of(point.speed) as f32,
+ })
+ .collect(),
+ );
+ ramp.set_curved(curve.is_some());
+ ramp.set_smooth(curve.is_none_or(concat_project::speed::is_smooth));
+ ramp.set_path(speed_ramp::path(points).into());
+ ramp.set_preset(curve.map_or(-1, speed_ramp::preset_index));
+ ramp.set_at(self.key_point().map_or(-1.0, |(_, at)| at as f32));
+ ramp.set_fastest(speed_ramp::extreme(points, true).map_or(-1.0, |speed| speed as f32));
+ ramp.set_slowest(speed_ramp::extreme(points, false).map_or(-1.0, |speed| speed as f32));
+ }
+
pub fn key_point(&self) -> Option<(&Clip, f64)> {
let clip = self.sole_selection().and_then(|id| self.clip(&id))?;
if clip.duration <= 0.0 {
@@ -12133,6 +12287,7 @@ mod tests {
&mut editor,
Command::SetClipSpeed {
clip_id: whole.clone(),
+ ripple: false,
speed,
},
);
@@ -12546,7 +12701,7 @@ mod tests {
let before = document.active().clip(id).expect("clip");
let mut after = before.clone();
crate::batch_volume::set_level(&mut after, before, 0.5, 0.0);
- commands.extend(super::clip_commands(id, before, &after));
+ commands.extend(super::clip_commands(id, before, &after, false));
}
editor.apply(Command::Batch { commands }).expect("applies");
let clip = |editor: &concat_project::Editor, id: &str| {
diff --git a/src/crates/concat/ui/app.slint b/src/crates/concat/ui/app.slint
index d4cc0e27..35876f1d 100644
--- a/src/crates/concat/ui/app.slint
+++ b/src/crates/concat/ui/app.slint
@@ -54,6 +54,7 @@ import {
// Re-exported so main.rs can reach the globals and the struct.
import { KeyEditor, KeyMarkData, KeyRowData } from "workspace/keyframes-pane.slint";
+import { SpeedRamp } from "inspector/speed-ramp.slint";
export {
Curves, Fmt, Focus, Payload, Theme, Bezier, Editor, I18n,
@@ -61,7 +62,7 @@ export {
DockDivider, DockSide, PaneKind, SeatBox,
EffectData, FontSearch, Meters, MediaFilter, MediaItemData, MediaKind, SourcePreview, TextPresetData,
Backdrop, BackdropData, ClipData, ClipField, ClipKeyData, ClipKind, ClipTextField, DropData, Keyframes,
- KeyEditor, KeyMarkData, KeyRowData,
+ KeyEditor, KeyMarkData, KeyRowData, SpeedRamp,
SelectedClipData, SelectedTransitionData, StageGuideData, StageItemData, TextAlignment, TimelineTabData,
TimelineTool, TrackData, TrackSize, MenuItemData, MenuRow, ExportData, ExportPhase, ModelData, SettingsData,
ChipOption, RecentProjectData, StartData, SystemFactData, ToastData, ProjectSheetData,
diff --git a/src/crates/concat/ui/inspector/clip-inspector.slint b/src/crates/concat/ui/inspector/clip-inspector.slint
index 2176630e..7ba65e84 100644
--- a/src/crates/concat/ui/inspector/clip-inspector.slint
+++ b/src/crates/concat/ui/inspector/clip-inspector.slint
@@ -14,6 +14,7 @@ import {
import { Button } from "../primitives/modal.slint";
import { SegmentedControl } from "../primitives/segmented-control.slint";
import { Select } from "../primitives/select.slint";
+import { SpeedGraph, SpeedRamp } from "speed-ramp.slint";
import {
Check,
ColourField,
@@ -2314,9 +2315,9 @@ export component AudioPanel inherits VerticalLayout {
}
}
-/// Speed: the rate, and only the rate. Speed that changes over the clip is
-/// the keyframes' job; whether the sound's pitch follows the rate is the
-/// Audio tab's.
+/// Speed: one rate for the whole clip, or a curve - speed that changes over
+/// the clip, shaped on a graph or picked from a preset (see
+/// speed-ramp.slint). Whether the sound's pitch follows is the Audio tab's.
export component SpeedPanel inherits VerticalLayout {
in property <SelectedClipData> selected;
/// The panel's first section, with no hairline above it; false where
@@ -2327,16 +2328,35 @@ export component SpeedPanel inherits VerticalLayout {
callback commit();
property <float> speed;
- function seed() { root.speed = root.selected.speed; }
+ function seed() {
+ root.speed = root.selected.speed;
+ root.fastest = SpeedRamp.fastest;
+ root.slowest = SpeedRamp.slowest;
+ }
init => { root.seed(); }
changed selected => { root.seed(); }
+ // Rust's word on the mode and the preset.
+ property <bool> curved: SpeedRamp.curved;
+ property <int> preset: SpeedRamp.preset;
+ // The two sliders' values, seeded from Rust's like the rate's: a
+ // slider writes its own value as it is dragged, which would end a
+ // binding.
+ property <float> fastest;
+ property <float> slowest;
+ property <float> fastest-truth: SpeedRamp.fastest;
+ property <float> slowest-truth: SpeedRamp.slowest;
+ changed fastest-truth => { root.fastest = root.fastest-truth; }
+ changed slowest-truth => { root.slowest = root.slowest-truth; }
+
Section {
first: root.first;
speed := SectionHeader {
title: I18n.t("common.speed");
collapsible: true;
- summary: InspectorFmt.format(ParamFormat.rate, root.speed);
+ summary: root.curved
+ ? I18n.t("speedRamp.curve")
+ : InspectorFmt.format(ParamFormat.rate, root.speed);
HelpButton {
text: I18n.t("clipInspector.rateReTimesClip");
}
@@ -2347,7 +2367,99 @@ export component SpeedPanel inherits VerticalLayout {
progress: root.selected.reverse-progress;
}
- Param {
+ HorizontalLayout {
+ padding-left: Theme.pad;
+ padding-right: Theme.pad;
+
+ SegmentedControl {
+ // A press assigns `current` inside the control, which
+ // ends a plain binding: so it is set again from Rust's
+ // word whenever the selection or an undo changes it.
+ property <bool> truth: root.curved;
+ changed truth => { self.current = self.truth ? 1 : 0; }
+
+ options: [I18n.t("speedRamp.constant"), I18n.t("speedRamp.curve")];
+ current: root.curved ? 1 : 0;
+ changed(index) => {
+ SpeedRamp.curve(index == 1);
+ root.commit();
+ }
+ }
+ }
+
+ if root.curved: Row {
+ label: I18n.t("speedRamp.shape");
+ Select {
+ // As the mode's: a pick ends the binding, Rust restores it.
+ property <int> truth: root.preset;
+ changed truth => { self.current = self.truth; }
+
+ options: SpeedRamp.presets;
+ current: root.preset;
+ placeholder: I18n.t("speedRamp.custom");
+ changed(index) => {
+ SpeedRamp.preset-chosen(index);
+ root.commit();
+ }
+ }
+ }
+
+ if root.curved: SpeedGraph {
+ padding-left: Theme.pad;
+ padding-right: Theme.pad;
+ point(index, x, y) => {
+ SpeedRamp.point(index, x, y);
+ root.commit();
+ }
+ remove(index) => {
+ SpeedRamp.remove(index);
+ root.commit();
+ }
+ }
+
+ if root.curved: Row {
+ label: I18n.t("speedRamp.bends");
+ SegmentedControl {
+ // As the mode's: set again from Rust's word.
+ property <bool> truth: SpeedRamp.smooth;
+ changed truth => { self.current = self.truth ? 0 : 1; }
+
+ options: [I18n.t("speedRamp.smooth"), I18n.t("speedRamp.straight")];
+ current: SpeedRamp.smooth ? 0 : 1;
+ changed(index) => {
+ SpeedRamp.smoothness(index == 0);
+ root.commit();
+ }
+ }
+ }
+
+ // The two extremes, for a ramp that is right in shape and too
+ // much or too little in strength: the fastest stretch brought
+ // down to 4x brings the rest of it along.
+ if root.curved && root.fastest > 0: Param {
+ label: I18n.t("speedRamp.fastest");
+ value <=> root.fastest;
+ minimum: 1.1;
+ maximum: 16;
+ step: 0.05;
+ default-value: 2;
+ fmt: ParamFormat.rate;
+ unit: "x";
+ changed(v) => { SpeedRamp.extreme(true, v); root.commit(); }
+ }
+ if root.curved && root.slowest > 0: Param {
+ label: I18n.t("speedRamp.slowest");
+ value <=> root.slowest;
+ minimum: 0.0625;
+ maximum: 0.9;
+ step: 0.01;
+ default-value: 0.5;
+ fmt: ParamFormat.rate;
+ unit: "x";
+ changed(v) => { SpeedRamp.extreme(false, v); root.commit(); }
+ }
+
+ if !root.curved: Param {
label: I18n.t("common.rate");
value <=> root.speed;
// The engine's full range. The track is linear, so the
diff --git a/src/crates/concat/ui/inspector/speed-ramp.slint b/src/crates/concat/ui/inspector/speed-ramp.slint
new file mode 100644
index 00000000..c367974a
--- /dev/null
+++ b/src/crates/concat/ui/inspector/speed-ramp.slint
@@ -0,0 +1,213 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+import { I18n } from "../i18n.slint";
+import { Theme } from "../theme/theme.slint";
+import { CurvePointData } from "grading.slint";
+
+// The Speed tab's curve: speed as it changes over the clip, drawn as a line
+// through a handful of points and shaped by dragging them. The clip runs
+// across, speed up on a scale of doublings - half and double sit the same
+// distance either side of 1x - over the engine's whole range, 1/16x to 16x.
+// The graph draws what Rust publishes and hands every change straight back,
+// so the line moves with the pointer, as the colour curves do.
+
+/// The selected clip's curve and the verbs that shape it. Its own global,
+/// as the keyframe cluster's is, so the Speed panel reads it wherever the
+/// panel is placed - under Video, under a sound clip's Audio, on a phone's
+/// sheet - without a property threaded to each.
+export global SpeedRamp {
+ /// The clip plays on a curve rather than at one rate.
+ in property <bool> curved;
+ /// The curve's points: `x` across the clip, `y` the speed on the
+ /// graph's scale (0 is 1/16x, 0.5 is 1x, 1 is 16x).
+ in property <[CurvePointData]> points;
+ /// The curve as a path in a unit box, y downwards.
+ in property <string> path;
+ /// The presets' names, in the order Rust lists them.
+ in property <[string]> presets;
+ /// The preset the points still are, as an index into `presets`; -1
+ /// once they have been shaped by hand.
+ in property <int> preset: -1;
+ /// The curve bends smoothly through its points rather than meeting
+ /// them in straight lines.
+ in property <bool> smooth: true;
+ /// The playhead in the clip, `0..1`, or -1 when it is outside it.
+ in property <float> at: -1;
+ /// The curve's fastest speed where it goes faster than 1x, and its
+ /// slowest where it goes slower; -1 where it does not.
+ in property <float> fastest: -1;
+ in property <float> slowest: -1;
+
+ /// Constant rate (false) or a curve (true). A curve starts flat at the
+ /// clip's rate; a constant rate keeps the curve's mean, so the clip's
+ /// length does not jump either way.
+ callback curve(on: bool);
+ /// A point moved, or put down when `index` is -1, on the graph's scale.
+ callback point(index: int, x: float, y: float);
+ /// A point taken off. The two ends stay.
+ callback remove(index: int);
+ /// The curve replaced by a preset's points.
+ callback preset-chosen(index: int);
+ /// Smooth bends (true) or straight lines (false) between the points.
+ callback smoothness(smooth: bool);
+ /// The fast stretches (or the slow ones) brought to `speed` at their
+ /// extreme, the rest of them following in proportion.
+ callback extreme(faster: bool, speed: float);
+}
+
+/// One point of the curve: a ring that drags in time and speed. The two
+/// ends only drag in speed - the curve always spans the whole clip - and do
+/// not come off.
+component SpeedHandle inherits TouchArea {
+ in property <float> px;
+ in property <float> py;
+ in property <length> plot-w;
+ in property <length> plot-h;
+ /// An end of the curve: fixed in time, and not removable.
+ in property <bool> end;
+
+ callback dragged(x: float, y: float);
+ callback removed();
+
+ property <float> drag-x: root.px;
+ property <float> drag-y: root.py;
+ property <bool> dragging;
+ property <bool> off;
+
+ x: (self.dragging ? self.drag-x : root.px) * root.plot-w - 8px;
+ y: (1 - (self.dragging ? self.drag-y : root.py)) * root.plot-h - 8px;
+ width: 16px;
+ height: 16px;
+ mouse-cursor: root.end ? MouseCursor.ns-resize : MouseCursor.move;
+
+ Rectangle {
+ x: 3px;
+ y: 3px;
+ width: 10px;
+ height: 10px;
+ border-radius: 5px;
+ background: root.dragging ? Theme.accent : Theme.panel;
+ border-width: 2px;
+ border-color: Theme.accent;
+ opacity: root.off ? 0.35 : 1;
+ }
+
+ moved => {
+ if (self.pressed) {
+ self.dragging = true;
+ let x = root.end ? root.px : root.px + (self.mouse-x - self.pressed-x) / root.plot-w;
+ let y = root.py - (self.mouse-y - self.pressed-y) / root.plot-h;
+ // Well outside the graph, a point between the ends is on its
+ // way off.
+ self.off = !root.end && (x < -0.08 || x > 1.08 || y < -0.08 || y > 1.08);
+ self.drag-x = Math.max(0, Math.min(1, x));
+ self.drag-y = Math.max(0, Math.min(1, y));
+ root.dragged(self.drag-x, self.drag-y);
+ }
+ }
+ pointer-event(event) => {
+ if (event.kind == PointerEventKind.up || event.kind == PointerEventKind.cancel) {
+ if (self.off && event.kind == PointerEventKind.up) {
+ root.removed();
+ }
+ self.dragging = false;
+ self.off = false;
+ }
+ }
+ double-clicked => {
+ if (!root.end) {
+ root.removed();
+ }
+ }
+}
+
+/// The graph: the curve over the clip with its points live - click the
+/// graph to put one down, drag it, double-click it or drag it off to take
+/// it away - the 1x line marked, and the playhead drawn where it crosses
+/// the clip.
+export component SpeedGraph inherits VerticalLayout {
+ in property <bool> enabled: true;
+
+ /// A point moved, or put down when `index` is -1.
+ callback point(index: int, x: float, y: float);
+ callback remove(index: int);
+
+ spacing: 4px;
+ opacity: root.enabled ? 1.0 : 0.45;
+
+ graph := Rectangle {
+ height: self.width * 0.6;
+ background: Theme.well;
+ border-width: 1px;
+ border-color: Theme.line;
+ border-radius: Theme.r-xs;
+
+ // A line a doubling: 1/4x, 1x and 4x labelled, 1x the strongest,
+ // since it is the speed a ramp leaves and comes back to.
+ for step in 7: Rectangle {
+ y: (1 - (step + 1) / 8) * parent.height;
+ width: parent.width;
+ height: 1px;
+ background: step == 3 ? Theme.line-strong : Theme.line;
+ opacity: step == 3 ? 1 : 0.5;
+ }
+ for label[i] in ["4x", "1x", "1/4x"]: Text {
+ x: 4px;
+ y: (1 - (5 - 2 * i) / 8) * parent.height - self.height - 1px;
+ text: label;
+ color: Theme.fg-dim;
+ font-size: Theme.fs-sm;
+ }
+
+ // Clicking the graph away from every point puts one down there.
+ TouchArea {
+ enabled: root.enabled;
+ mouse-cursor: crosshair;
+ clicked => {
+ root.point(-1,
+ Math.max(0, Math.min(1, self.mouse-x / graph.width)),
+ Math.max(0, Math.min(1, 1 - self.mouse-y / graph.height)));
+ }
+ }
+
+ if SpeedRamp.at >= 0: Rectangle {
+ x: SpeedRamp.at * parent.width;
+ width: 1px;
+ height: parent.height;
+ background: Theme.playhead;
+ }
+
+ Path {
+ x: 0;
+ y: 0;
+ width: parent.width;
+ height: parent.height;
+ viewbox-width: 1;
+ viewbox-height: 1;
+ fit: fill;
+ commands: SpeedRamp.path;
+ fill: Colors.transparent;
+ stroke: Theme.accent;
+ stroke-width: 2px;
+ }
+
+ for point in SpeedRamp.points: SpeedHandle {
+ px: point.x;
+ py: point.y;
+ plot-w: graph.width;
+ plot-h: graph.height;
+ end: point.index == 0 || point.index == SpeedRamp.points.length - 1;
+ enabled: root.enabled;
+ dragged(x, y) => { root.point(point.index, x, y); }
+ removed => { root.remove(point.index); }
+ }
+ }
+
+ Text {
+ text: I18n.t("speedRamp.howTo");
+ color: Theme.fg-dim;
+ font-size: Theme.fs-sm;
+ wrap: word-wrap;
+ }
+}