forge
Explore
Log in

Don't you dare go Hollow

✨ Custom bezier easing for every key: KeyEase::Bezier, format v56, MCP bezier(x1,y1,x2,y2)

Browse files at this commit

70d1130e3ea9731c4e8ddd8d8046d7b32bee4018Ahmet Kaan GümüşParent: f178286
MCP.mdmodified+4 -3
@@ -353,7 +353,7 @@ Also: `undo {steps?=1}`, `redo {steps?=1}` (an edit clears redo history).
353353 | `set` | **clip**, **index**, params, on, color, mode | changes the effect at `index`; unnamed values keep theirs; `on:false` switches it off and keeps its settings. Out-of-range numbers are clamped and the reply says so |
354354 | `remove` | **clip**, **index** | takes the effect out |
355355 | `move` | **clip**, **from**, **to** | moves an effect within the stack |
356-| `mask_keys` | **clip**, **effect**, **keys**, clear | sets the whole key list of a rect_mask or ellipse_mask at stack position `effect`. Each key is `{at, x?, y?, w?, h?, feather?, ease?}`: `at` a time, `x`/`y` the centre and `w`/`h` the size as fractions of the frame, `feather` the soft edge, `ease` the move into the next key (linear, ease_in, ease_out, ease_in_out, hold). Keys sort by time; a key that names no field holds the previous key's values, and the first key the mask's own. Between keys the mask moves smoothly; before the first and after the last it holds. Up to 256 keys. `clear:true` takes the keys off and the mask goes back to its static values. Refused on any other kind |
356+| `mask_keys` | **clip**, **effect**, **keys**, clear | sets the whole key list of a rect_mask or ellipse_mask at stack position `effect`. Each key is `{at, x?, y?, w?, h?, feather?, ease?}`: `at` a time, `x`/`y` the centre and `w`/`h` the size as fractions of the frame, `feather` the soft edge, `ease` the move into the next key (linear, ease_in, ease_out, ease_in_out, hold, or bezier(x1,y1,x2,y2)). Keys sort by time; a key that names no field holds the previous key's values, and the first key the mask's own. Between keys the mask moves smoothly; before the first and after the last it holds. Up to 256 keys. `clear:true` takes the keys off and the mask goes back to its static values. Refused on any other kind |
357357 | `list` | clip | the stack with each effect's position, kind, on/off and named values, and `keys=N` for a keyed mask; with no `clip`, every kind with its parameters and ranges |
358358
359359 Effects are static, one value for the whole clip, except a mask with `mask_keys`, which moves between its keys; Ken Burns stays in `transform_keys`. A pixelate is limited by the first rect_mask or ellipse_mask after it (that mask only shapes the pixelation and does not cut the clip), so an ellipse after a pixelate censors a region. Distances (blur radius, shake amount) are pixels at 1080 lines and scale with the frame height. The stack applies in order on the clip's placed picture in preview and export; chroma_key and the masks reveal the lanes below, `blend` picks how the clip lies over them. An empty or all-off stack changes nothing. Setting what is already there is no undo step. Errors are specific: an unknown kind lists the kinds, an unknown parameter lists the parameters, a bad position gives the valid range, an audio lane is refused, a 17th effect is refused.
@@ -497,8 +497,9 @@ written for each clip whose gain is not unity.
497497 envelope.
498498 - **Keys animate transform, opacity, colour and gain.** `transform_keys`,
499499 `opacity_keys`, `color_keys` and the gain points take `ease` per key (`linear`,
500- `ease_in`, `ease_out`, `ease_in_out`, `hold`; linear by default, and a file with no
501- eases saves as before). Opacity keys replace the placement's opacity while they exist
500+ `ease_in`, `ease_out`, `ease_in_out`, `hold`, or a custom cubic curve
501+ `bezier(x1,y1,x2,y2)` / `[x1,y1,x2,y2]` with each point from 0 to 1; linear by default,
502+ and a file with no eases saves as before, while a file with a custom curve needs v56). Opacity keys replace the placement's opacity while they exist
502503 and the fades multiply on top; colour keys replace the single grade, and `color`
503504 refuses while they exist. Keys sit in source frames, so they follow trims, splits and
504505 ripple. Speed keys have no ease yet. A source plays its first sound
crates/app/src/export_ui.rsmodified+1 -0
@@ -329,6 +329,7 @@ pub(crate) fn ease_label(ease: engine::transform::KeyEase) -> &'static str {
329329 KeyEase::EaseOut => "Ease out",
330330 KeyEase::Ease => "Ease in-out",
331331 KeyEase::Hold => "Hold",
332+ KeyEase::Bezier(_) => "Custom curve",
332333 }
333334 }
334335
crates/app/src/ui/cards/keys.rsmodified+1 -0
@@ -27,6 +27,7 @@ fn ease_text(ease: KeyEase) -> &'static str {
2727 KeyEase::EaseOut => "Ease out",
2828 KeyEase::Ease => "Smooth",
2929 KeyEase::Hold => "Hold",
30+ KeyEase::Bezier(_) => "Custom",
3031 }
3132 }
3233
crates/engine/src/edith.rsmodified+45 -9
@@ -430,11 +430,12 @@ use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, Tr
430430 /// The newest project format version: the `N` in the `edith N` first line that
431431 /// [`save`] writes for a project that uses the newest features. A reader refuses any
432432 /// higher version by name.
433-pub const NEWEST_VERSION: u32 = 55;
433+pub const NEWEST_VERSION: u32 = 56;
434434
435435 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
436436 /// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`].
437-const MAGIC: &[u8] = b"edith 55";
437+const MAGIC: &[u8] = b"edith 56";
438+const MAGIC_V55: &[u8] = b"edith 55";
438439 const MAGIC_V54: &[u8] = b"edith 54";
439440 const MAGIC_V53: &[u8] = b"edith 53";
440441 const MAGIC_V52: &[u8] = b"edith 52";
@@ -810,10 +811,14 @@ pub fn encode_flagged(
810811 let masked = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.effects.iter().any(|e| !e.keys.is_empty())));
811812 // ...and one with a clip's pitch shift is v55.
812813 let pitched = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pitch != 0));
813- if pitched || titled || masked || panned || styled || marked || angled || named || deinterlaced || steadied || looked || effected || voiced || captioned || animated || reversed || transitioned || ramped || !chapters.is_empty() || !markers.is_empty() {
814+ // ...and one with a custom bezier key easing is v56.
815+ let curved = lanes.iter().any(|(_, clips)| clips.iter().any(has_bezier));
816+ if curved || pitched || titled || masked || panned || styled || marked || angled || named || deinterlaced || steadied || looked || effected || voiced || captioned || animated || reversed || transitioned || ramped || !chapters.is_empty() || !markers.is_empty() {
814817 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
815- let header = if pitched {
818+ let header = if curved {
816819 MAGIC
820+ } else if pitched {
821+ MAGIC_V55
817822 } else if titled {
818823 MAGIC_V54
819824 } else if masked {
@@ -1031,7 +1036,8 @@ pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[Se
10311036 // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46
10321037 // when a part is v46; a newer-only line under an older header is refused.
10331038 let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n');
1034- let v55 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC));
1039+ let v56 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC));
1040+ let v55 = v56 || is(&bytes, MAGIC_V55) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V55));
10351041 let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54));
10361042 let v53 = v54 || is(&bytes, MAGIC_V53) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V53));
10371043 let v52 = v53 || is(&bytes, MAGIC_V52) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V52));
@@ -1041,7 +1047,7 @@ pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[Se
10411047 let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48));
10421048 let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47));
10431049 let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46));
1044- let header = if v55 { MAGIC } else if v54 { MAGIC_V54 } else if v53 { MAGIC_V53 } else if v52 { MAGIC_V52 } else if v51 { MAGIC_V51 } else if v50 { MAGIC_V50 } else if v49 { MAGIC_V49 } else if v48 { MAGIC_V48 } else if v47 { MAGIC_V47 } else if v46 { MAGIC_V46 } else { MAGIC_V45 };
1050+ let header = if v56 { MAGIC } else if v55 { MAGIC_V55 } else if v54 { MAGIC_V54 } else if v53 { MAGIC_V53 } else if v52 { MAGIC_V52 } else if v51 { MAGIC_V51 } else if v50 { MAGIC_V50 } else if v49 { MAGIC_V49 } else if v48 { MAGIC_V48 } else if v47 { MAGIC_V47 } else if v46 { MAGIC_V46 } else { MAGIC_V45 };
10451051 bytes.splice(..first_end, header.iter().copied());
10461052 bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes());
10471053 escape_text(active.1, &mut bytes);
@@ -1433,6 +1439,17 @@ fn needs_v39(c: &Clip) -> bool {
14331439 .any(|k| matches!(k.ease, KeyEase::EaseIn | KeyEase::EaseOut | KeyEase::Hold))
14341440 }
14351441
1442+/// Whether a clip has a key with a custom bezier easing, which only v56 can
1443+/// hold: a placement, opacity, colour, volume or mask key.
1444+fn has_bezier(c: &Clip) -> bool {
1445+ let bezier = |e: KeyEase| matches!(e, KeyEase::Bezier(_));
1446+ c.transform_keys.iter().any(|k| bezier(k.ease))
1447+ || c.opacity_keys.iter().any(|k| bezier(k.ease))
1448+ || c.color_keys.iter().any(|k| bezier(k.ease))
1449+ || c.gain_keys.iter().any(|k| bezier(k.ease))
1450+ || c.effects.iter().any(|e| e.keys.iter().any(|k| bezier(k.ease)))
1451+}
1452+
14361453 /// One line per video clip that `points` returns something for, as
14371454 /// `<name> video <ord> <index>{points}`: the shape of the `okeys` and `ckeys` lines.
14381455 fn video_key_lines(
@@ -2254,7 +2271,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
22542271 // The one that carries a clip's placement animation, as `tkeys` lines...
22552272 // The one that carries a clip's stabilisation, as `stab` lines...
22562273 // The one that carries a clip's pitch shift, as `pitch` lines...
2257- let v55 = first == MAGIC;
2274+ let v56 = first == MAGIC;
2275+ let v55 = v56 || first == MAGIC_V55;
22582276 let v54 = v55 || first == MAGIC_V54;
22592277 let v53 = v54 || first == MAGIC_V53;
22602278 let v52 = v53 || first == MAGIC_V52;
@@ -2816,6 +2834,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
28162834 }
28172835 let ease = KeyEase::from_token(parts[1])
28182836 .filter(|e| v39 || matches!(e, KeyEase::Linear | KeyEase::Ease))
2837+ .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
28192838 .ok_or_else(|| format!("line {n}: tkeys ease is lin, in, out, ease or hold"))?;
28202839 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
28212840 if v.len() != 9 {
@@ -2966,6 +2985,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
29662985 }
29672986 let at_frame = number(parts[0], n)?;
29682987 let ease = KeyEase::from_token(parts[1])
2988+ .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
29692989 .ok_or_else(|| format!("line {n}: mkeys ease is lin, in, out, ease or hold"))?;
29702990 if keys.last().is_some_and(|k| k.at >= at_frame) {
29712991 return Err(format!("line {n}: mkeys keys are not in source order").into());
@@ -3026,6 +3046,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
30263046 }
30273047 let at_frame = number(parts[0], n)?;
30283048 let ease = KeyEase::from_token(parts[1])
3049+ .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
30293050 .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease or hold"))?;
30303051 let last = if colour { ckeys.last().map(|k| k.at) } else { okeys.last().map(|k| k.at) };
30313052 if last.is_some_and(|l| l >= at_frame) {
@@ -3116,6 +3137,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
31163137 Some(c) if v39 => (
31173138 &d[..c],
31183139 KeyEase::from_token(&d[c + 1..])
3140+ .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
31193141 .ok_or_else(|| format!("line {n}: gainkeys ease is lin, in, out, ease or hold"))?,
31203142 ),
31213143 _ => (d, KeyEase::Linear),
@@ -6984,6 +7006,20 @@ mod tests {
69847006 }
69857007
69867008
7009+ /// A custom bezier ease is a v56 word: a v56 file loads it and a v55 file naming one is refused.
7010+ #[test]
7011+ fn bezier_ease_is_a_v56_word() {
7012+ let dirp = PathBuf::from("/proj");
7013+ let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7014+ video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7015+ let line = "tkeys video 1 0 0:lin:0,0,1,0,0,0,0,0,1 20:b420_0_580_1000:0,0,2,0,0,0,0,0,0.5\n";
7016+ let doc = parse(format!("edith 56\n{head}{line}").as_bytes(), &dirp).expect("a v56 file loads");
7017+ let bezier = crate::transform::Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap();
7018+ assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Bezier(bezier));
7019+ let err = parse(format!("edith 55\n{head}{line}").as_bytes(), &dirp).unwrap_err().to_string();
7020+ assert!(err.contains("tkeys ease"), "{err}");
7021+ }
7022+
69877023 /// The v55 pitch lines: a clip's semitones round-trip and a project with none is the bytes a
69887024 /// v51 one was; an out-of-range, unknown-lane or unknown-clip pitch is refused by name, and a
69897025 /// pitch line under an older header is refused as unknown.
@@ -7273,10 +7309,10 @@ mod tests {
72737309 #[test]
72747310 fn a_wrong_first_line_is_refused_by_name() {
72757311 let dir = PathBuf::from("/proj");
7276- let err = parse(b"edith 56\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
7312+ let err = parse(b"edith 999\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
72777313 .unwrap_err()
72787314 .to_string();
7279- assert_eq!(err, "line 1: unsupported version 56");
7315+ assert_eq!(err, "line 1: unsupported version 999");
72807316 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
72817317 assert_eq!(
72827318 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/transform.rsmodified+180 -21
@@ -8,6 +8,8 @@
88 //! [`crate::scale::transformed_dst_rect`]), so a deserializer can hand this
99 //! over unchecked, exactly as [`ColorParams`](crate::color::ColorParams) can.
1010
11+use std::borrow::Cow;
12+
1113 /// One clip's placement on the project canvas, on top of whatever
1214 /// [`crate::scale::FitPolicy`] already does.
1315 #[derive(Debug, Clone, Copy, PartialEq)]
@@ -84,7 +86,8 @@ pub const MAX_TRANSFORM_KEYS: usize = 256;
8486 /// starts slowly and ends at speed (cubic), `EaseOut` starts at speed and
8587 /// lands gently (cubic), and `Hold` keeps the key's value until the next key
8688 /// and then jumps (a step). The last key has no segment after it, so its own
87-/// ease is never read. One shape for every key type ([`ease_shape`]).
89+/// ease is never read. `Bezier` is a custom CSS-style cubic curve
90+/// ([`Bezier`]). One shape for every key type ([`ease_shape`]).
8891 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8992 pub enum KeyEase {
9093 #[default]
@@ -93,10 +96,90 @@ pub enum KeyEase {
9396 EaseIn,
9497 EaseOut,
9598 Hold,
99+ /// A custom cubic curve from `(0, 0)` to `(1, 1)`.
100+ Bezier(Bezier),
101+}
102+
103+/// A CSS-style cubic bezier easing curve from `(0, 0)` to `(1, 1)` through
104+/// two control points. Each coordinate is stored in thousandths, so the type
105+/// stays `Eq` and `Hash`. Every coordinate lies in `0..=1`, which keeps the
106+/// curve from overshooting: every interpolated value stays inside the range
107+/// of its two keys.
108+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
109+pub struct Bezier {
110+ x1: u16,
111+ y1: u16,
112+ x2: u16,
113+ y2: u16,
114+}
115+
116+impl Bezier {
117+ /// A curve through the control points `(x1, y1)` and `(x2, y2)`, rounded
118+ /// to thousandths. `None` unless every coordinate is finite and within `0..=1`.
119+ pub fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Option<Bezier> {
120+ let q = |v: f32| -> Option<u16> {
121+ if v.is_finite() && (0.0..=1.0).contains(&v) {
122+ Some((v * 1000.0).round() as u16)
123+ } else {
124+ None
125+ }
126+ };
127+ Some(Bezier {
128+ x1: q(x1)?,
129+ y1: q(y1)?,
130+ x2: q(x2)?,
131+ y2: q(y2)?,
132+ })
133+ }
134+
135+ /// The control coordinates `[x1, y1, x2, y2]` as fractions in `0..=1`.
136+ pub fn points(self) -> [f32; 4] {
137+ [self.x1, self.y1, self.x2, self.y2].map(|v| f32::from(v) / 1000.0)
138+ }
139+
140+ /// A curve from thousandths counts, as a token holds them. `None` if any count is above 1000.
141+ fn from_thousandths(x1: u16, y1: u16, x2: u16, y2: u16) -> Option<Bezier> {
142+ let ok = [x1, y1, x2, y2].iter().all(|v| *v <= 1000);
143+ ok.then_some(Bezier { x1, y1, x2, y2 })
144+ }
145+}
146+
147+/// A thousandths count written as a short decimal: `420` is `0.42`, `1000` is `1`.
148+fn thousandths_text(v: u16) -> String {
149+ let (whole, frac) = (v / 1000, v % 1000);
150+ if frac == 0 {
151+ whole.to_string()
152+ } else {
153+ format!("{whole}.{}", format!("{frac:03}").trim_end_matches('0'))
154+ }
155+}
156+
157+/// Reads `bezier(x1,y1,x2,y2)`, spaces allowed, back into a curve.
158+fn bezier_from_name(name: &str) -> Option<Bezier> {
159+ let inner = name.trim().strip_prefix("bezier(")?.strip_suffix(')')?;
160+ let values: Option<Vec<f32>> = inner.split(',').map(|s| s.trim().parse::<f32>().ok()).collect();
161+ match values?.as_slice() {
162+ &[x1, y1, x2, y2] => Bezier::new(x1, y1, x2, y2),
163+ _ => None,
164+ }
165+}
166+
167+/// Reads `b<x1>_<y1>_<x2>_<y2>` in thousandths back into a curve.
168+fn bezier_from_token(token: &[u8]) -> Option<Bezier> {
169+ let rest = token.strip_prefix(b"b")?;
170+ let mut parts = rest.split(|b| *b == b'_').map(|p| {
171+ std::str::from_utf8(p).ok()?.parse::<u16>().ok()
172+ });
173+ let (x1, y1, x2, y2) = (parts.next()??, parts.next()??, parts.next()??, parts.next()??);
174+ if parts.next().is_some() {
175+ return None;
176+ }
177+ Bezier::from_thousandths(x1, y1, x2, y2)
96178 }
97179
98180 impl KeyEase {
99- /// Every ease, in the order a picker lists them.
181+ /// Every preset ease, in the order a picker lists them. A custom
182+ /// [`Bezier`](KeyEase::Bezier) is not one of them.
100183 pub const ALL: [KeyEase; 5] = [
101184 KeyEase::Linear,
102185 KeyEase::EaseIn,
@@ -106,14 +189,18 @@ impl KeyEase {
106189 ];
107190
108191 /// The name the tools and the GUI use: `linear`, `ease_in`, `ease_out`,
109- /// `ease_in_out` or `hold`.
110- pub fn name(self) -> &'static str {
192+ /// `ease_in_out`, `hold`, or `bezier(x1,y1,x2,y2)` for a custom curve.
193+ pub fn name(self) -> Cow<'static, str> {
111194 match self {
112- KeyEase::Linear => "linear",
113- KeyEase::EaseIn => "ease_in",
114- KeyEase::EaseOut => "ease_out",
115- KeyEase::Ease => "ease_in_out",
116- KeyEase::Hold => "hold",
195+ KeyEase::Linear => Cow::Borrowed("linear"),
196+ KeyEase::EaseIn => Cow::Borrowed("ease_in"),
197+ KeyEase::EaseOut => Cow::Borrowed("ease_out"),
198+ KeyEase::Ease => Cow::Borrowed("ease_in_out"),
199+ KeyEase::Hold => Cow::Borrowed("hold"),
200+ KeyEase::Bezier(b) => {
201+ let [x1, y1, x2, y2] = [b.x1, b.y1, b.x2, b.y2].map(thousandths_text);
202+ Cow::Owned(format!("bezier({x1},{y1},{x2},{y2})"))
203+ }
117204 }
118205 }
119206
@@ -125,18 +212,20 @@ impl KeyEase {
125212 "ease_out" => KeyEase::EaseOut,
126213 "ease_in_out" | "ease" => KeyEase::Ease,
127214 "hold" => KeyEase::Hold,
128- _ => return None,
215+ _ => return bezier_from_name(name).map(KeyEase::Bezier),
129216 })
130217 }
131218
132- /// The token a project file writes (`lin`, `in`, `out`, `ease`, `hold`).
133- pub fn token(self) -> &'static str {
219+ /// The token a project file writes (`lin`, `in`, `out`, `ease`, `hold`), or
220+ /// `b<x1>_<y1>_<x2>_<y2>` in thousandths for a custom curve.
221+ pub fn token(self) -> Cow<'static, str> {
134222 match self {
135- KeyEase::Linear => "lin",
136- KeyEase::EaseIn => "in",
137- KeyEase::EaseOut => "out",
138- KeyEase::Ease => "ease",
139- KeyEase::Hold => "hold",
223+ KeyEase::Linear => Cow::Borrowed("lin"),
224+ KeyEase::EaseIn => Cow::Borrowed("in"),
225+ KeyEase::EaseOut => Cow::Borrowed("out"),
226+ KeyEase::Ease => Cow::Borrowed("ease"),
227+ KeyEase::Hold => Cow::Borrowed("hold"),
228+ KeyEase::Bezier(b) => Cow::Owned(format!("b{}_{}_{}_{}", b.x1, b.y1, b.x2, b.y2)),
140229 }
141230 }
142231
@@ -148,13 +237,16 @@ impl KeyEase {
148237 b"out" => KeyEase::EaseOut,
149238 b"ease" => KeyEase::Ease,
150239 b"hold" => KeyEase::Hold,
151- _ => return None,
240+ _ => return bezier_from_token(token).map(KeyEase::Bezier),
152241 })
153242 }
154243
155- /// The next ease in [`ALL`](Self::ALL), wrapping: what a "cycle the easing" button does.
244+ /// The next preset in [`ALL`](Self::ALL), wrapping: what a "cycle the easing"
245+ /// button does. A custom curve goes to `Linear`, the first preset.
156246 pub fn next(self) -> KeyEase {
157- let i = Self::ALL.iter().position(|e| *e == self).unwrap_or(0);
247+ let Some(i) = Self::ALL.iter().position(|e| *e == self) else {
248+ return KeyEase::Linear;
249+ };
158250 Self::ALL[(i + 1) % Self::ALL.len()]
159251 }
160252 }
@@ -179,9 +271,59 @@ pub fn ease_shape(ease: KeyEase, t: f32) -> f32 {
179271 0.0
180272 }
181273 }
274+ KeyEase::Bezier(b) => bezier_height(b, t),
182275 }
183276 }
184277
278+/// The height of a custom curve where its horizontal position is `t`. The
279+/// curve's parameter is found by a few Newton steps, with bisection as the
280+/// fallback when the slope is too flat for Newton.
281+fn bezier_height(b: Bezier, t: f32) -> f32 {
282+ if t <= 0.0 {
283+ return 0.0;
284+ }
285+ if t >= 1.0 {
286+ return 1.0;
287+ }
288+ let [x1, y1, x2, y2] = b.points();
289+ // One coordinate of the cubic from 0 to 1 with control points `p1` and `p2`, at parameter `s`.
290+ let coord = |p1: f32, p2: f32, s: f32| {
291+ let u = 1.0 - s;
292+ 3.0 * u * u * s * p1 + 3.0 * u * s * s * p2 + s * s * s
293+ };
294+ // The slope of `coord` with respect to `s`.
295+ let slope = |p1: f32, p2: f32, s: f32| {
296+ let u = 1.0 - s;
297+ 3.0 * u * u * p1 + 6.0 * u * s * (p2 - p1) + 3.0 * s * s * (1.0 - p2)
298+ };
299+ let mut s = t;
300+ let mut found = false;
301+ for _ in 0..8 {
302+ let err = coord(x1, x2, s) - t;
303+ if err.abs() < 1e-6 {
304+ found = true;
305+ break;
306+ }
307+ let d = slope(x1, x2, s);
308+ if d.abs() < 1e-6 {
309+ break;
310+ }
311+ s = (s - err / d).clamp(0.0, 1.0);
312+ }
313+ if !found {
314+ let (mut lo, mut hi) = (0.0f32, 1.0f32);
315+ for _ in 0..32 {
316+ s = 0.5 * (lo + hi);
317+ if coord(x1, x2, s) < t {
318+ lo = s;
319+ } else {
320+ hi = s;
321+ }
322+ }
323+ }
324+ coord(y1, y2, s)
325+}
326+
185327 /// One point of a clip's transform animation ([`crate::project::Clip::transform_keys`]):
186328 /// the whole [`TransformParams`] at source frame `at`. `at` is an absolute
187329 /// source frame, numbered as `in_frame` is, so a trim leaves every key on the
@@ -529,6 +671,23 @@ pub fn corner_of(t: &TransformParams, src: (u32, u32), canvas: (u32, u32), margi
529671 mod tests {
530672 use super::*;
531673
674+ #[test]
675+ fn bezier_round_trips_and_eases_monotonically() {
676+ let b = Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap();
677+ let ease = KeyEase::Bezier(b);
678+ assert_eq!(ease.name(), "bezier(0.42,0,0.58,1)");
679+ assert_eq!(ease.token(), "b420_0_580_1000");
680+ assert_eq!(KeyEase::from_name("bezier( 0.42, 0,0.58 ,1)"), Some(ease));
681+ assert_eq!(KeyEase::from_token(b"b420_0_580_1000"), Some(ease));
682+ assert_eq!(KeyEase::from_token(b"b420_0_580"), None);
683+ assert_eq!(Bezier::new(0.5, 1.5, 0.0, 0.0), None);
684+ assert!((ease_shape(ease, 0.5) - 0.5).abs() < 1e-3);
685+ let samples: Vec<f32> = (0..=10).map(|i| ease_shape(ease, i as f32 / 10.0)).collect();
686+ assert!(samples.windows(2).all(|w| w[0] <= w[1]));
687+ assert_eq!(ease_shape(ease, 0.0), 0.0);
688+ assert_eq!(ease_shape(ease, 1.0), 1.0);
689+ }
690+
532691 #[test]
533692 fn default_is_identity() {
534693 assert!(TransformParams::default().is_identity());
@@ -711,7 +870,7 @@ mod tests {
711870 #[test]
712871 fn names_and_tokens_round_trip_and_cycle() {
713872 for e in KeyEase::ALL {
714- assert_eq!(KeyEase::from_name(e.name()), Some(e));
873+ assert_eq!(KeyEase::from_name(&e.name()), Some(e));
715874 assert_eq!(KeyEase::from_token(e.token().as_bytes()), Some(e));
716875 }
717876 assert_eq!(KeyEase::from_name("ease"), Some(KeyEase::Ease), "the older spelling");
crates/mcp/src/help.rsmodified+2 -1
@@ -672,6 +672,7 @@ const OP_TEXTS: &[(&str, &str)] = &[
672672 clip, or \"end\". Between two keys every field moves in a straight line unless the key has an ease, which shapes \
673673 the stretch that leaves it (the last key has no stretch): linear (the default), ease_in (slow start), ease_out \
674674 (slow landing), ease_in_out (slow both ends; \"ease\" is the older name for it) or hold (keep this key's value until the next key, then jump). \
675+ A custom curve is ease:\"bezier(x1,y1,x2,y2)\" or ease:[x1,y1,x2,y2], two control points each from 0 to 1 (no overshoot). \
675676 The same ease works on opacity_keys, color_keys and the gain points. A key leaves a field it does not name held from the \
676677 previous key, and the first key from the clip's own transform. The reply lists the keys in timeline time. \
677678 clear:true takes the animation off, back to the clip's single transform. A keyed clip refuses transform: change \
@@ -733,7 +734,7 @@ const OP_TEXTS: &[(&str, &str)] = &[
733734 "opacity_keys",
734735 "opacity_keys {clip, keys:[{at, opacity, ease?}], clear?} — the clip's opacity over its own time, 0 (clear) to 1 (opaque): \
735736 a fade-in of an overlay, a pulse. Video clips only. at is clip-relative as in transform_keys (\"0s\", \"50%\", \"end\"). A key that \
736- names no opacity holds the previous key's, and the first the clip's own. ease (linear, ease_in, ease_out, ease_in_out, hold) \
737+ names no opacity holds the previous key's, and the first the clip's own. ease (linear, ease_in, ease_out, ease_in_out, hold, or bezier(x1,y1,x2,y2)) \
737738 shapes the stretch that leaves the key. While a clip has opacity keys they give its opacity (transform's opacity is refused); \
738739 the clip's fades multiply on top, so a fade-in over a half-opaque clip reaches half. clear:true takes them off. Up to 256 keys; \
739740 trims, splits and moves carry them as they do transform_keys. A layer above another shows the one beneath through it as it \
crates/mcp/src/tools/edit.rsmodified+1 -1
@@ -112,7 +112,7 @@ wheels {clip, lift?, gamma?, gain?, reset?} — lift (blacks), gamma (mids), gai
112112 curves {clip, master?, red?, green?, blue?, reset?} — each up to 16 [input, output] points in 0..1, inputs rising, joined by a monotone spline; [] straightens one. After the wheels.
113113 lut {clip, path?, mix?, clear?} — a .cube file (1D or 3D, size up to 65) after the curves, mix 0..1 (default 1); a missing or broken file is refused. lut {relink, path} points every clip using LUT `relink` at `path`. The four color sliders run last.
114114 transform {clip, x?, y?, scale?, rotate?, crop?:[l,r,t,b], opacity?, reset?} — position, size, crop, opacity (0 clear to 1 opaque).
115-transform_keys {clip, keys?:[{at, x?, y?, scale?, rotate?, opacity?, ease?}...], clear?} — animates the transform over the clip's own time (at is a clip-relative time, e.g. "0s" or "end"); clear:true takes the keys off, back to the single transform. ease (on every kind of key, the segment that leaves the key): linear (default), ease_in, ease_out, ease_in_out, hold (a step).
115+transform_keys {clip, keys?:[{at, x?, y?, scale?, rotate?, opacity?, ease?}...], clear?} — animates the transform over the clip's own time (at is a clip-relative time, e.g. "0s" or "end"); clear:true takes the keys off, back to the single transform. ease (on every kind of key, the segment that leaves the key): linear (default), ease_in, ease_out, ease_in_out, hold (a step), or bezier(x1,y1,x2,y2) / [x1,y1,x2,y2] for a custom curve (each point 0 to 1).
116116 opacity_keys {clip, keys?:[{at, opacity, ease?}...], clear?} — opacity (0..1) over the clip's own time; the fades multiply on top.
117117 mask_keys {clip, effect, keys?:[{at, x?, y?, w?, h?, feather?, ease?}...], clear?} — a rect or ellipse mask's position, size and soft edge over the clip's own time; effect is its stack position.
118118 color_keys {clip, keys?:[{at, brightness?, contrast?, saturation?, tint?, ease?}...], clear?} — the grade over the clip's own time; fields a key leaves out keep the previous key's value.
crates/mcp/src/tools/edit_fx.rsmodified+31 -3
@@ -23,7 +23,7 @@ use engine::project::{
2323 use engine::scale::FitPolicy;
2424 use engine::text::{layout_share, missing_glyphs, Align, HPlace, Outline, Place, TextStyle, Weight, SIZE_RANGE};
2525 use engine::color::{ColorKey, MAX_COLOR_KEYS};
26-use engine::transform::{Corner, KeyEase, OpacityKey, TransformKey, TransformParams, MAX_TRANSFORM_KEYS};
26+use engine::transform::{Bezier, Corner, KeyEase, OpacityKey, TransformKey, TransformParams, MAX_TRANSFORM_KEYS};
2727 use engine::titleanim::TitleAnim;
2828 use engine::PlaybackSession;
2929 use serde_json::{json, Value};
@@ -668,19 +668,47 @@ fn transform_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result<Appli
668668 }
669669
670670 /// The `ease` of key `n` (a JSON object): one of the names [`KeyEase::from_name`]
671-/// takes, `linear` when absent.
671+/// takes, `linear` when absent. A custom curve is `bezier(x1,y1,x2,y2)` or `[x1,y1,x2,y2]`.
672672 fn ease_of(who: &str, n: usize, key: &Value) -> Result<KeyEase, String> {
673673 match key.get("ease") {
674674 None | Some(Value::Null) => Ok(KeyEase::Linear),
675+ Some(Value::String(name)) if name.trim_start().starts_with("bezier") => {
676+ let values = name
677+ .trim()
678+ .strip_prefix("bezier(")
679+ .and_then(|s| s.strip_suffix(')'))
680+ .and_then(|s| s.split(',').map(|p| p.trim().parse::<f64>().ok()).collect::<Option<Vec<f64>>>());
681+ match values {
682+ Some(v) => bezier_of(who, n, &v),
683+ None => Err(format!("{who}: key {n} bezier wants bezier(x1,y1,x2,y2), got {name:?}")),
684+ }
685+ }
675686 Some(Value::String(name)) => KeyEase::from_name(name).ok_or_else(|| {
676687 format!("{who}: key {n} ease is {EASES}, got {name:?}")
677688 }),
689+ Some(Value::Array(points)) => {
690+ let values: Vec<f64> = points.iter().map(|p| p.as_f64().unwrap_or(f64::NAN)).collect();
691+ bezier_of(who, n, &values)
692+ }
678693 Some(v) => Err(format!("{who}: key {n} ease must be a name ({EASES}), got {}", kind_of(v))),
679694 }
680695 }
681696
697+/// The custom curve through four control coordinates `[x1, y1, x2, y2]`, each from `0` to `1`.
698+/// A coordinate outside that range is refused, because a curve that overshoots would push an
699+/// interpolated value past the two keys it runs between.
700+fn bezier_of(who: &str, n: usize, v: &[f64]) -> Result<KeyEase, String> {
701+ let refuse = || format!("{who}: key {n} bezier points are x1,y1,x2,y2, each from 0 to 1, got {v:?}");
702+ let &[x1, y1, x2, y2] = v else {
703+ return Err(refuse());
704+ };
705+ Bezier::new(x1 as f32, y1 as f32, x2 as f32, y2 as f32)
706+ .map(KeyEase::Bezier)
707+ .ok_or_else(refuse)
708+}
709+
682710 /// The ease names, for the refusals that list them.
683-const EASES: &str = "\"linear\", \"ease_in\", \"ease_out\", \"ease_in_out\" or \"hold\"";
711+const EASES: &str = "\"linear\", \"ease_in\", \"ease_out\", \"ease_in_out\", \"hold\", \"bezier(x1,y1,x2,y2)\" or [x1,y1,x2,y2]";
684712
685713 /// ` ease_in` for a reply, nothing for linear.
686714 fn ease_suffix(ease: KeyEase) -> String {