From 70d1130e3ea9731c4e8ddd8d8046d7b32bee4018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 6 Nov 2026 13:44:27 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Custom=20bezier=20easing=20for=20ev?= =?UTF-8?q?ery=20key:=20KeyEase::Bezier,=20format=20v56,=20MCP=20bezier(x1?= =?UTF-8?q?,y1,x2,y2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- MCP.md | 7 +- crates/app/src/export_ui.rs | 1 + crates/app/src/ui/cards/keys.rs | 1 + crates/engine/src/edith.rs | 54 +++++++-- crates/engine/src/transform.rs | 201 ++++++++++++++++++++++++++++---- crates/mcp/src/help.rs | 3 +- crates/mcp/src/tools/edit.rs | 2 +- crates/mcp/src/tools/edit_fx.rs | 34 +++++- 8 files changed, 265 insertions(+), 38 deletions(-) diff --git a/MCP.md b/MCP.md index d09b545..26fda00 100644 --- a/MCP.md +++ b/MCP.md @@ -353,7 +353,7 @@ Also: `undo {steps?=1}`, `redo {steps?=1}` (an edit clears redo history). | `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 | | `remove` | **clip**, **index** | takes the effect out | | `move` | **clip**, **from**, **to** | moves an effect within the stack | -| `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 | +| `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 | | `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 | 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. envelope. - **Keys animate transform, opacity, colour and gain.** `transform_keys`, `opacity_keys`, `color_keys` and the gain points take `ease` per key (`linear`, - `ease_in`, `ease_out`, `ease_in_out`, `hold`; linear by default, and a file with no - eases saves as before). Opacity keys replace the placement's opacity while they exist + `ease_in`, `ease_out`, `ease_in_out`, `hold`, or a custom cubic curve + `bezier(x1,y1,x2,y2)` / `[x1,y1,x2,y2]` with each point from 0 to 1; linear by default, + 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 and the fades multiply on top; colour keys replace the single grade, and `color` refuses while they exist. Keys sit in source frames, so they follow trims, splits and ripple. Speed keys have no ease yet. A source plays its first sound diff --git a/crates/app/src/export_ui.rs b/crates/app/src/export_ui.rs index 9fc8601..c9bea99 100644 --- a/crates/app/src/export_ui.rs +++ b/crates/app/src/export_ui.rs @@ -329,6 +329,7 @@ pub(crate) fn ease_label(ease: engine::transform::KeyEase) -> &'static str { KeyEase::EaseOut => "Ease out", KeyEase::Ease => "Ease in-out", KeyEase::Hold => "Hold", + KeyEase::Bezier(_) => "Custom curve", } } diff --git a/crates/app/src/ui/cards/keys.rs b/crates/app/src/ui/cards/keys.rs index 5dcb2c8..e4e2568 100644 --- a/crates/app/src/ui/cards/keys.rs +++ b/crates/app/src/ui/cards/keys.rs @@ -27,6 +27,7 @@ fn ease_text(ease: KeyEase) -> &'static str { KeyEase::EaseOut => "Ease out", KeyEase::Ease => "Smooth", KeyEase::Hold => "Hold", + KeyEase::Bezier(_) => "Custom", } } diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 25d111e..20feea0 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -430,11 +430,12 @@ use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, Tr /// The newest project format version: the `N` in the `edith N` first line that /// [`save`] writes for a project that uses the newest features. A reader refuses any /// higher version by name. -pub const NEWEST_VERSION: u32 = 55; +pub const NEWEST_VERSION: u32 = 56; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`]. -const MAGIC: &[u8] = b"edith 55"; +const MAGIC: &[u8] = b"edith 56"; +const MAGIC_V55: &[u8] = b"edith 55"; const MAGIC_V54: &[u8] = b"edith 54"; const MAGIC_V53: &[u8] = b"edith 53"; const MAGIC_V52: &[u8] = b"edith 52"; @@ -810,10 +811,14 @@ pub fn encode_flagged( let masked = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.effects.iter().any(|e| !e.keys.is_empty()))); // ...and one with a clip's pitch shift is v55. let pitched = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pitch != 0)); - 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() { + // ...and one with a custom bezier key easing is v56. + let curved = lanes.iter().any(|(_, clips)| clips.iter().any(has_bezier)); + 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() { let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len()); - let header = if pitched { + let header = if curved { MAGIC + } else if pitched { + MAGIC_V55 } else if titled { MAGIC_V54 } else if masked { @@ -1031,7 +1036,8 @@ pub fn sequenced(main: Vec, active: (u32, &str), order: &[u32], blocks: &[Se // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46 // when a part is v46; a newer-only line under an older header is refused. let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n'); - let v55 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC)); + let v56 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC)); + let v55 = v56 || is(&bytes, MAGIC_V55) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V55)); let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54)); let v53 = v54 || is(&bytes, MAGIC_V53) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V53)); 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, active: (u32, &str), order: &[u32], blocks: &[Se let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48)); let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47)); let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46)); - 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 }; + 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 }; bytes.splice(..first_end, header.iter().copied()); bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes()); escape_text(active.1, &mut bytes); @@ -1433,6 +1439,17 @@ fn needs_v39(c: &Clip) -> bool { .any(|k| matches!(k.ease, KeyEase::EaseIn | KeyEase::EaseOut | KeyEase::Hold)) } +/// Whether a clip has a key with a custom bezier easing, which only v56 can +/// hold: a placement, opacity, colour, volume or mask key. +fn has_bezier(c: &Clip) -> bool { + let bezier = |e: KeyEase| matches!(e, KeyEase::Bezier(_)); + c.transform_keys.iter().any(|k| bezier(k.ease)) + || c.opacity_keys.iter().any(|k| bezier(k.ease)) + || c.color_keys.iter().any(|k| bezier(k.ease)) + || c.gain_keys.iter().any(|k| bezier(k.ease)) + || c.effects.iter().any(|e| e.keys.iter().any(|k| bezier(k.ease))) +} + /// One line per video clip that `points` returns something for, as /// ` video {points}`: the shape of the `okeys` and `ckeys` lines. fn video_key_lines( @@ -2254,7 +2271,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The one that carries a clip's placement animation, as `tkeys` lines... // The one that carries a clip's stabilisation, as `stab` lines... // The one that carries a clip's pitch shift, as `pitch` lines... - let v55 = first == MAGIC; + let v56 = first == MAGIC; + let v55 = v56 || first == MAGIC_V55; let v54 = v55 || first == MAGIC_V54; let v53 = v54 || first == MAGIC_V53; let v52 = v53 || first == MAGIC_V52; @@ -2816,6 +2834,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } let ease = KeyEase::from_token(parts[1]) .filter(|e| v39 || matches!(e, KeyEase::Linear | KeyEase::Ease)) + .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_))) .ok_or_else(|| format!("line {n}: tkeys ease is lin, in, out, ease or hold"))?; let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect(); if v.len() != 9 { @@ -2966,6 +2985,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } let at_frame = number(parts[0], n)?; let ease = KeyEase::from_token(parts[1]) + .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_))) .ok_or_else(|| format!("line {n}: mkeys ease is lin, in, out, ease or hold"))?; if keys.last().is_some_and(|k| k.at >= at_frame) { 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 { } let at_frame = number(parts[0], n)?; let ease = KeyEase::from_token(parts[1]) + .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_))) .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease or hold"))?; let last = if colour { ckeys.last().map(|k| k.at) } else { okeys.last().map(|k| k.at) }; if last.is_some_and(|l| l >= at_frame) { @@ -3116,6 +3137,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { Some(c) if v39 => ( &d[..c], KeyEase::from_token(&d[c + 1..]) + .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_))) .ok_or_else(|| format!("line {n}: gainkeys ease is lin, in, out, ease or hold"))?, ), _ => (d, KeyEase::Linear), @@ -6984,6 +7006,20 @@ mod tests { } + /// A custom bezier ease is a v56 word: a v56 file loads it and a v55 file naming one is refused. + #[test] + fn bezier_ease_is_a_v56_word() { + let dirp = PathBuf::from("/proj"); + let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\ + video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n"; + 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"; + let doc = parse(format!("edith 56\n{head}{line}").as_bytes(), &dirp).expect("a v56 file loads"); + let bezier = crate::transform::Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap(); + assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Bezier(bezier)); + let err = parse(format!("edith 55\n{head}{line}").as_bytes(), &dirp).unwrap_err().to_string(); + assert!(err.contains("tkeys ease"), "{err}"); + } + /// The v55 pitch lines: a clip's semitones round-trip and a project with none is the bytes a /// v51 one was; an out-of-range, unknown-lane or unknown-clip pitch is refused by name, and a /// pitch line under an older header is refused as unknown. @@ -7273,10 +7309,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 56\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 999\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 56"); + assert_eq!(err, "line 1: unsupported version 999"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/transform.rs b/crates/engine/src/transform.rs index 51bd557..6f54e2a 100644 --- a/crates/engine/src/transform.rs +++ b/crates/engine/src/transform.rs @@ -8,6 +8,8 @@ //! [`crate::scale::transformed_dst_rect`]), so a deserializer can hand this //! over unchecked, exactly as [`ColorParams`](crate::color::ColorParams) can. +use std::borrow::Cow; + /// One clip's placement on the project canvas, on top of whatever /// [`crate::scale::FitPolicy`] already does. #[derive(Debug, Clone, Copy, PartialEq)] @@ -84,7 +86,8 @@ pub const MAX_TRANSFORM_KEYS: usize = 256; /// starts slowly and ends at speed (cubic), `EaseOut` starts at speed and /// lands gently (cubic), and `Hold` keeps the key's value until the next key /// and then jumps (a step). The last key has no segment after it, so its own -/// ease is never read. One shape for every key type ([`ease_shape`]). +/// ease is never read. `Bezier` is a custom CSS-style cubic curve +/// ([`Bezier`]). One shape for every key type ([`ease_shape`]). #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum KeyEase { #[default] @@ -93,10 +96,90 @@ pub enum KeyEase { EaseIn, EaseOut, Hold, + /// A custom cubic curve from `(0, 0)` to `(1, 1)`. + Bezier(Bezier), +} + +/// A CSS-style cubic bezier easing curve from `(0, 0)` to `(1, 1)` through +/// two control points. Each coordinate is stored in thousandths, so the type +/// stays `Eq` and `Hash`. Every coordinate lies in `0..=1`, which keeps the +/// curve from overshooting: every interpolated value stays inside the range +/// of its two keys. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Bezier { + x1: u16, + y1: u16, + x2: u16, + y2: u16, +} + +impl Bezier { + /// A curve through the control points `(x1, y1)` and `(x2, y2)`, rounded + /// to thousandths. `None` unless every coordinate is finite and within `0..=1`. + pub fn new(x1: f32, y1: f32, x2: f32, y2: f32) -> Option { + let q = |v: f32| -> Option { + if v.is_finite() && (0.0..=1.0).contains(&v) { + Some((v * 1000.0).round() as u16) + } else { + None + } + }; + Some(Bezier { + x1: q(x1)?, + y1: q(y1)?, + x2: q(x2)?, + y2: q(y2)?, + }) + } + + /// The control coordinates `[x1, y1, x2, y2]` as fractions in `0..=1`. + pub fn points(self) -> [f32; 4] { + [self.x1, self.y1, self.x2, self.y2].map(|v| f32::from(v) / 1000.0) + } + + /// A curve from thousandths counts, as a token holds them. `None` if any count is above 1000. + fn from_thousandths(x1: u16, y1: u16, x2: u16, y2: u16) -> Option { + let ok = [x1, y1, x2, y2].iter().all(|v| *v <= 1000); + ok.then_some(Bezier { x1, y1, x2, y2 }) + } +} + +/// A thousandths count written as a short decimal: `420` is `0.42`, `1000` is `1`. +fn thousandths_text(v: u16) -> String { + let (whole, frac) = (v / 1000, v % 1000); + if frac == 0 { + whole.to_string() + } else { + format!("{whole}.{}", format!("{frac:03}").trim_end_matches('0')) + } +} + +/// Reads `bezier(x1,y1,x2,y2)`, spaces allowed, back into a curve. +fn bezier_from_name(name: &str) -> Option { + let inner = name.trim().strip_prefix("bezier(")?.strip_suffix(')')?; + let values: Option> = inner.split(',').map(|s| s.trim().parse::().ok()).collect(); + match values?.as_slice() { + &[x1, y1, x2, y2] => Bezier::new(x1, y1, x2, y2), + _ => None, + } +} + +/// Reads `b___` in thousandths back into a curve. +fn bezier_from_token(token: &[u8]) -> Option { + let rest = token.strip_prefix(b"b")?; + let mut parts = rest.split(|b| *b == b'_').map(|p| { + std::str::from_utf8(p).ok()?.parse::().ok() + }); + let (x1, y1, x2, y2) = (parts.next()??, parts.next()??, parts.next()??, parts.next()??); + if parts.next().is_some() { + return None; + } + Bezier::from_thousandths(x1, y1, x2, y2) } impl KeyEase { - /// Every ease, in the order a picker lists them. + /// Every preset ease, in the order a picker lists them. A custom + /// [`Bezier`](KeyEase::Bezier) is not one of them. pub const ALL: [KeyEase; 5] = [ KeyEase::Linear, KeyEase::EaseIn, @@ -106,14 +189,18 @@ impl KeyEase { ]; /// The name the tools and the GUI use: `linear`, `ease_in`, `ease_out`, - /// `ease_in_out` or `hold`. - pub fn name(self) -> &'static str { + /// `ease_in_out`, `hold`, or `bezier(x1,y1,x2,y2)` for a custom curve. + pub fn name(self) -> Cow<'static, str> { match self { - KeyEase::Linear => "linear", - KeyEase::EaseIn => "ease_in", - KeyEase::EaseOut => "ease_out", - KeyEase::Ease => "ease_in_out", - KeyEase::Hold => "hold", + KeyEase::Linear => Cow::Borrowed("linear"), + KeyEase::EaseIn => Cow::Borrowed("ease_in"), + KeyEase::EaseOut => Cow::Borrowed("ease_out"), + KeyEase::Ease => Cow::Borrowed("ease_in_out"), + KeyEase::Hold => Cow::Borrowed("hold"), + KeyEase::Bezier(b) => { + let [x1, y1, x2, y2] = [b.x1, b.y1, b.x2, b.y2].map(thousandths_text); + Cow::Owned(format!("bezier({x1},{y1},{x2},{y2})")) + } } } @@ -125,18 +212,20 @@ impl KeyEase { "ease_out" => KeyEase::EaseOut, "ease_in_out" | "ease" => KeyEase::Ease, "hold" => KeyEase::Hold, - _ => return None, + _ => return bezier_from_name(name).map(KeyEase::Bezier), }) } - /// The token a project file writes (`lin`, `in`, `out`, `ease`, `hold`). - pub fn token(self) -> &'static str { + /// The token a project file writes (`lin`, `in`, `out`, `ease`, `hold`), or + /// `b___` in thousandths for a custom curve. + pub fn token(self) -> Cow<'static, str> { match self { - KeyEase::Linear => "lin", - KeyEase::EaseIn => "in", - KeyEase::EaseOut => "out", - KeyEase::Ease => "ease", - KeyEase::Hold => "hold", + KeyEase::Linear => Cow::Borrowed("lin"), + KeyEase::EaseIn => Cow::Borrowed("in"), + KeyEase::EaseOut => Cow::Borrowed("out"), + KeyEase::Ease => Cow::Borrowed("ease"), + KeyEase::Hold => Cow::Borrowed("hold"), + KeyEase::Bezier(b) => Cow::Owned(format!("b{}_{}_{}_{}", b.x1, b.y1, b.x2, b.y2)), } } @@ -148,13 +237,16 @@ impl KeyEase { b"out" => KeyEase::EaseOut, b"ease" => KeyEase::Ease, b"hold" => KeyEase::Hold, - _ => return None, + _ => return bezier_from_token(token).map(KeyEase::Bezier), }) } - /// The next ease in [`ALL`](Self::ALL), wrapping: what a "cycle the easing" button does. + /// The next preset in [`ALL`](Self::ALL), wrapping: what a "cycle the easing" + /// button does. A custom curve goes to `Linear`, the first preset. pub fn next(self) -> KeyEase { - let i = Self::ALL.iter().position(|e| *e == self).unwrap_or(0); + let Some(i) = Self::ALL.iter().position(|e| *e == self) else { + return KeyEase::Linear; + }; Self::ALL[(i + 1) % Self::ALL.len()] } } @@ -179,9 +271,59 @@ pub fn ease_shape(ease: KeyEase, t: f32) -> f32 { 0.0 } } + KeyEase::Bezier(b) => bezier_height(b, t), } } +/// The height of a custom curve where its horizontal position is `t`. The +/// curve's parameter is found by a few Newton steps, with bisection as the +/// fallback when the slope is too flat for Newton. +fn bezier_height(b: Bezier, t: f32) -> f32 { + if t <= 0.0 { + return 0.0; + } + if t >= 1.0 { + return 1.0; + } + let [x1, y1, x2, y2] = b.points(); + // One coordinate of the cubic from 0 to 1 with control points `p1` and `p2`, at parameter `s`. + let coord = |p1: f32, p2: f32, s: f32| { + let u = 1.0 - s; + 3.0 * u * u * s * p1 + 3.0 * u * s * s * p2 + s * s * s + }; + // The slope of `coord` with respect to `s`. + let slope = |p1: f32, p2: f32, s: f32| { + let u = 1.0 - s; + 3.0 * u * u * p1 + 6.0 * u * s * (p2 - p1) + 3.0 * s * s * (1.0 - p2) + }; + let mut s = t; + let mut found = false; + for _ in 0..8 { + let err = coord(x1, x2, s) - t; + if err.abs() < 1e-6 { + found = true; + break; + } + let d = slope(x1, x2, s); + if d.abs() < 1e-6 { + break; + } + s = (s - err / d).clamp(0.0, 1.0); + } + if !found { + let (mut lo, mut hi) = (0.0f32, 1.0f32); + for _ in 0..32 { + s = 0.5 * (lo + hi); + if coord(x1, x2, s) < t { + lo = s; + } else { + hi = s; + } + } + } + coord(y1, y2, s) +} + /// One point of a clip's transform animation ([`crate::project::Clip::transform_keys`]): /// the whole [`TransformParams`] at source frame `at`. `at` is an absolute /// 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 mod tests { use super::*; + #[test] + fn bezier_round_trips_and_eases_monotonically() { + let b = Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap(); + let ease = KeyEase::Bezier(b); + assert_eq!(ease.name(), "bezier(0.42,0,0.58,1)"); + assert_eq!(ease.token(), "b420_0_580_1000"); + assert_eq!(KeyEase::from_name("bezier( 0.42, 0,0.58 ,1)"), Some(ease)); + assert_eq!(KeyEase::from_token(b"b420_0_580_1000"), Some(ease)); + assert_eq!(KeyEase::from_token(b"b420_0_580"), None); + assert_eq!(Bezier::new(0.5, 1.5, 0.0, 0.0), None); + assert!((ease_shape(ease, 0.5) - 0.5).abs() < 1e-3); + let samples: Vec = (0..=10).map(|i| ease_shape(ease, i as f32 / 10.0)).collect(); + assert!(samples.windows(2).all(|w| w[0] <= w[1])); + assert_eq!(ease_shape(ease, 0.0), 0.0); + assert_eq!(ease_shape(ease, 1.0), 1.0); + } + #[test] fn default_is_identity() { assert!(TransformParams::default().is_identity()); @@ -711,7 +870,7 @@ mod tests { #[test] fn names_and_tokens_round_trip_and_cycle() { for e in KeyEase::ALL { - assert_eq!(KeyEase::from_name(e.name()), Some(e)); + assert_eq!(KeyEase::from_name(&e.name()), Some(e)); assert_eq!(KeyEase::from_token(e.token().as_bytes()), Some(e)); } assert_eq!(KeyEase::from_name("ease"), Some(KeyEase::Ease), "the older spelling"); diff --git a/crates/mcp/src/help.rs b/crates/mcp/src/help.rs index c195fc6..1954e03 100644 --- a/crates/mcp/src/help.rs +++ b/crates/mcp/src/help.rs @@ -672,6 +672,7 @@ const OP_TEXTS: &[(&str, &str)] = &[ clip, or \"end\". Between two keys every field moves in a straight line unless the key has an ease, which shapes \ the stretch that leaves it (the last key has no stretch): linear (the default), ease_in (slow start), ease_out \ (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). \ + 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). \ 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 \ previous key, and the first key from the clip's own transform. The reply lists the keys in timeline time. \ 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)] = &[ "opacity_keys", "opacity_keys {clip, keys:[{at, opacity, ease?}], clear?} — the clip's opacity over its own time, 0 (clear) to 1 (opaque): \ 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 \ - 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) \ + 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)) \ shapes the stretch that leaves the key. While a clip has opacity keys they give its opacity (transform's opacity is refused); \ 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; \ trims, splits and moves carry them as they do transform_keys. A layer above another shows the one beneath through it as it \ diff --git a/crates/mcp/src/tools/edit.rs b/crates/mcp/src/tools/edit.rs index 7ab6357..76d789a 100644 --- a/crates/mcp/src/tools/edit.rs +++ b/crates/mcp/src/tools/edit.rs @@ -112,7 +112,7 @@ wheels {clip, lift?, gamma?, gain?, reset?} — lift (blacks), gamma (mids), gai 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. 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. transform {clip, x?, y?, scale?, rotate?, crop?:[l,r,t,b], opacity?, reset?} — position, size, crop, opacity (0 clear to 1 opaque). -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). +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). opacity_keys {clip, keys?:[{at, opacity, ease?}...], clear?} — opacity (0..1) over the clip's own time; the fades multiply on top. 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. 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. diff --git a/crates/mcp/src/tools/edit_fx.rs b/crates/mcp/src/tools/edit_fx.rs index 881ac8b..1b7c382 100644 --- a/crates/mcp/src/tools/edit_fx.rs +++ b/crates/mcp/src/tools/edit_fx.rs @@ -23,7 +23,7 @@ use engine::project::{ use engine::scale::FitPolicy; use engine::text::{layout_share, missing_glyphs, Align, HPlace, Outline, Place, TextStyle, Weight, SIZE_RANGE}; use engine::color::{ColorKey, MAX_COLOR_KEYS}; -use engine::transform::{Corner, KeyEase, OpacityKey, TransformKey, TransformParams, MAX_TRANSFORM_KEYS}; +use engine::transform::{Bezier, Corner, KeyEase, OpacityKey, TransformKey, TransformParams, MAX_TRANSFORM_KEYS}; use engine::titleanim::TitleAnim; use engine::PlaybackSession; use serde_json::{json, Value}; @@ -668,19 +668,47 @@ fn transform_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result Result { match key.get("ease") { None | Some(Value::Null) => Ok(KeyEase::Linear), + Some(Value::String(name)) if name.trim_start().starts_with("bezier") => { + let values = name + .trim() + .strip_prefix("bezier(") + .and_then(|s| s.strip_suffix(')')) + .and_then(|s| s.split(',').map(|p| p.trim().parse::().ok()).collect::>>()); + match values { + Some(v) => bezier_of(who, n, &v), + None => Err(format!("{who}: key {n} bezier wants bezier(x1,y1,x2,y2), got {name:?}")), + } + } Some(Value::String(name)) => KeyEase::from_name(name).ok_or_else(|| { format!("{who}: key {n} ease is {EASES}, got {name:?}") }), + Some(Value::Array(points)) => { + let values: Vec = points.iter().map(|p| p.as_f64().unwrap_or(f64::NAN)).collect(); + bezier_of(who, n, &values) + } Some(v) => Err(format!("{who}: key {n} ease must be a name ({EASES}), got {}", kind_of(v))), } } +/// The custom curve through four control coordinates `[x1, y1, x2, y2]`, each from `0` to `1`. +/// A coordinate outside that range is refused, because a curve that overshoots would push an +/// interpolated value past the two keys it runs between. +fn bezier_of(who: &str, n: usize, v: &[f64]) -> Result { + let refuse = || format!("{who}: key {n} bezier points are x1,y1,x2,y2, each from 0 to 1, got {v:?}"); + let &[x1, y1, x2, y2] = v else { + return Err(refuse()); + }; + Bezier::new(x1 as f32, y1 as f32, x2 as f32, y2 as f32) + .map(KeyEase::Bezier) + .ok_or_else(refuse) +} + /// The ease names, for the refusals that list them. -const EASES: &str = "\"linear\", \"ease_in\", \"ease_out\", \"ease_in_out\" or \"hold\""; +const EASES: &str = "\"linear\", \"ease_in\", \"ease_out\", \"ease_in_out\", \"hold\", \"bezier(x1,y1,x2,y2)\" or [x1,y1,x2,y2]"; /// ` ease_in` for a reply, nothing for linear. fn ease_suffix(ease: KeyEase) -> String {