diff --git a/MCP.md b/MCP.md index 26fda00..687340e 100644 --- a/MCP.md +++ b/MCP.md @@ -353,10 +353,11 @@ 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 | +| `effect_keys` | **clip**, **effect**, **keys**, clear | sets the whole key list of any effect at stack position `effect`, over the clip's own time. Every numeric parameter can be keyed, named as the effect names it (a blur's `radius`, a vignette's `amount` and `softness`, a chroma_key's `tolerance`, a pixelate's `size`, a mask's `x`, `y`, `width`, `height`, `feather`). Each key is `{at, ?: value, ease?}`. A switch or a choice (a blend's `mode`, a mask's `invert`) is refused by name. A parameter a key leaves out takes the value the effect shows at that time. Keys sort by time and the values are clamped; up to 256 keys; `ease` as in `mask_keys`. `clear:true` takes the keys off. | | `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 | +| `list` | clip | the stack with each effect's position, kind, on/off and named values, and `keys=N` for a keyed effect; 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. +Effects are static, one value for the whole clip, unless keyed: any numeric parameter moves between the keys of `effect_keys` (and a mask's position between its `mask_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. Recipes: *Vignette plus soft blur* -- `effect {op:"add", clip:"V1#0", kind:"vignette", params:{amount:0.6}}`, then `effect {op:"add", clip:"V1#0", kind:"blur", params:{radius:4}}`. *Green screen over a background lane* -- background on V1, the green-screen take on V2: `effect {op:"add", clip:"V2#0", kind:"chroma_key", color:"#00ff00", params:{tolerance:0.35, softness:0.1, spill:0.5}}`; the keyed-out part shows V1. diff --git a/crates/app/src/player/effects.rs b/crates/app/src/player/effects.rs index a155355..1fbf2ae 100644 --- a/crates/app/src/player/effects.rs +++ b/crates/app/src/player/effects.rs @@ -5,7 +5,7 @@ use crate::*; use crate::player::cards::{bar_fraction, value_at}; -use engine::effects::{BlendMode, Effect, EffectKind, MAX_EFFECTS, MAX_PARAMS, MaskKey, ParamSpec}; +use engine::effects::{BlendMode, Effect, EffectKey, EffectKind, MAX_EFFECTS, MAX_PARAMS, ParamSpec}; use engine::transform::KeyEase; /// How a parameter is drawn: a bar, an on/off switch (a step of 1 over 0..1), or the @@ -83,31 +83,26 @@ pub(crate) fn param_display(kind: EffectKind, spec: &ParamSpec, value: f32) -> S } /// The plain word for a blend mode. -/// The mask key a mask effect holds at source frame `at`: the shape it shows there, as a key of its own. -fn mask_key_at(e: &Effect, at: u32) -> MaskKey { - let base = e.posed(f64::from(at)).into_owned(); - let v = base.values; - MaskKey { at, x: v[0], y: v[1], width: v[2], height: v[3], feather: v[4], ease: KeyEase::Linear } +/// The key an effect holds at source frame `at`: every parameter as the effect shows it there, +/// as a key of its own. +fn effect_key_at(e: &Effect, at: u32) -> EffectKey { + let values = e.posed(f64::from(at)).values; + EffectKey { at, values, ease: KeyEase::Linear } } -/// Writes parameter `p` of `e`. A keyed mask takes the change on its key at source frame -/// `at`, made there from what it shows when none is, so an edit at the playhead animates; any -/// other effect, or an unkeyed mask, takes it as its static value. +/// Writes parameter `p` of `e`. A keyed effect takes the change on its key at source frame +/// `at` for a keyable parameter, the key made there from what the effect shows when none is, +/// so an edit at the playhead animates; a switch or a choice, an unkeyed effect, or no playhead +/// takes it as its static value. fn write_param(e: &mut Effect, p: usize, v: f32, at: Option) { - let mask = matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) && p < 5; + let keyable = e.kind.params().get(p).is_some_and(|s| s.keyable()); match at { - Some(at) if mask && !e.keys.is_empty() => { + Some(at) if keyable && !e.keys.is_empty() => { let mut key = match e.keys.iter().position(|k| k.at == at) { Some(i) => e.keys[i], - None => mask_key_at(e, at), + None => effect_key_at(e, at), }; - match p { - 0 => key.x = v, - 1 => key.y = v, - 2 => key.width = v, - 3 => key.height = v, - _ => key.feather = v, - } + key.values[p] = v; match e.keys.binary_search_by_key(&at, |k| k.at) { Ok(i) => e.keys[i] = key, Err(i) => e.keys.insert(i, key), @@ -192,27 +187,29 @@ impl Player { }) } - /// The keyframe diamond on a mask row: a key for the mask's shape at the playhead, or that - /// key taken off. Taking off the last key leaves the shape it had there as the static one. - pub(crate) fn toggle_mask_key(&mut self, i: usize, cx: &mut Context) { + /// The keyframe diamond on an effect's row: a key for the effect's parameters at the + /// playhead, or that key taken off. Taking off the last key leaves the values it had there + /// as the static ones (the switches and choices keep theirs). + pub(crate) fn toggle_effect_key(&mut self, i: usize, cx: &mut Context) { let Some(at) = self.effects_src() else { self.notify_user("The playhead is not on this clip".into()); cx.notify(); return; }; let mut stack = self.effects_shown(); - if let Some(e) = stack.get_mut(i) - && matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) - { + if let Some(e) = stack.get_mut(i) { match e.keys.binary_search_by_key(&at, |k| k.at) { Ok(pos) => { let key = e.keys.remove(pos); if e.keys.is_empty() { - e.values[..5].copy_from_slice(&[key.x, key.y, key.width, key.height, key.feather]); + let specs = e.kind.params(); + for (j, _) in specs.iter().enumerate().filter(|(_, s)| s.keyable()) { + e.values[j] = key.values[j]; + } } } Err(pos) => { - let key = mask_key_at(e, at); + let key = effect_key_at(e, at); e.keys.insert(pos, key); } } diff --git a/crates/app/src/ui/cards/effects.rs b/crates/app/src/ui/cards/effects.rs index cdc0b50..05532e2 100644 --- a/crates/app/src/ui/cards/effects.rs +++ b/crates/app/src/ui/cards/effects.rs @@ -69,7 +69,7 @@ impl Player { let (lane, idx) = self.effects_open?; let session = self.session.as_ref()?; let on_picture = lane.kind == LaneKind::Video && session.lane_clips(lane).get(idx).is_some(); - // The rows show what each effect is at the playhead: a keyed mask's shape there. + // The rows show what each effect is at the playhead: a keyed effect's values there. let at = self.effects_src().unwrap_or(0); let stack: Vec = self.effects_shown().iter().map(|e| e.posed(f64::from(at)).into_owned()).collect(); let count = stack.len(); @@ -396,10 +396,15 @@ impl Player { .into_any_element() } }; - // A mask's position and size rows carry the keyframe diamond: a key for the shape at the - // playhead. It sits above the slider whether or not a key is there, so nothing moves. - let mask_row = matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) && (p == 0 || p == 2); - if mask_row { + // An effect's keyframe diamond sits on its first keyable row (a mask's position and size + // rows) and keys the whole effect at the playhead. It sits above the slider whether or + // not a key is there, so nothing moves. + let mask = matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask); + let key_row = match mask { + true => p == 0 || p == 2, + false => spec.keyable() && e.kind.params()[..p].iter().all(|s| !s.keyable()), + }; + if key_row { let here = self.effects_src(); let filled = here.is_some_and(|at| e.keys.iter().any(|k| k.at == at)); let t = crate::ui::theme::tokens(); @@ -418,7 +423,7 @@ impl Player { "", None, )) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| this.toggle_mask_key(i, cx))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| this.toggle_effect_key(i, cx))) .child(super::keys::diamond(12., if filled { t.accent } else { t.ink3 }, filled)); controls.push( div() diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 20feea0..eb3804e 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -226,6 +226,14 @@ //! none) and `frames` how long each takes. A project with none is the bytes a v53 one was bar the //! version line. //! +//! **Version 56** animates any effect parameter: an `ekeys video ::,,...` +//! line per effect with keys, the keys in source order, with one value for each of the effect's +//! parameters ([`crate::effects::EffectKind::params`]) and the ease of the segment that leaves each +//! key (a custom bezier is written as [`KeyEase::token`] gives it). A parameter that cannot be +//! keyed (a switch or a choice) holds its static value. A v53 file's `mkeys` lines, which keyed +//! only a mask's position, size and soft edge, are still read. A project with none is the bytes a +//! v55 one was bar the version line. +//! //! A `cueadd` line is one cue added to a subtitle track, which no file has: //! `cueadd `, the track by its position in //! the `subtitle` lines, the times in microseconds on the track's own clock, and @@ -807,13 +815,12 @@ pub fn encode_flagged( || lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.mark.is_default())); // ...and one with a clip pan or a lane pan is v50. let panned = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pan != 0)) || flags.iter().any(|f| f.pan != 0.0); - // ...and one with a mask's keys is v53. - let masked = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.effects.iter().any(|e| !e.keys.is_empty()))); + // ...and one with an effect's keys is v56 (`ekeys`), as is one with a custom bezier key easing. + let keyed = 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)); - // ...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 curved = keyed || lanes.iter().any(|(_, clips)| clips.iter().any(has_bezier)); + if curved || pitched || titled || 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 curved { MAGIC @@ -821,8 +828,6 @@ pub fn encode_flagged( MAGIC_V55 } else if titled { MAGIC_V54 - } else if masked { - MAGIC_V53 } else if panned { MAGIC_V50 } else if styled { @@ -872,7 +877,7 @@ pub fn encode_flagged( bytes.extend_from_slice(&opacity_key_lines(lanes)); bytes.extend_from_slice(&color_key_lines(lanes)); bytes.extend_from_slice(&effect_lines(lanes)); - bytes.extend_from_slice(&mask_key_lines(lanes)); + bytes.extend_from_slice(&effect_key_lines(lanes)); bytes.extend_from_slice(&look_lines(color, dir)); bytes.extend_from_slice(&stab_lines(lanes)); bytes.extend_from_slice(&deint_lines(lanes)); @@ -890,7 +895,7 @@ pub fn encode_flagged( /// such a project is the bytes it was before v51. /// `current` (a file's first line, without its newline) with `candidate` in its place when /// `candidate` is a newer dialect, else `current` untouched. The library and notes lines raise -/// the header to what they need and never lower it, so a file with mask keys (v53) keeps v53. +/// the header to what they need and never lower it, so a file with effect keys (v56) keeps v56. fn raise_header(current: &[u8], candidate: &[u8]) -> Vec { let version = |h: &[u8]| { std::str::from_utf8(h).ok().and_then(|l| l.strip_prefix("edith ")).and_then(|n| n.parse::().ok()).unwrap_or(0) @@ -1652,10 +1657,10 @@ fn effect_lines(lanes: &[(LaneKind, Vec)]) -> Vec { out.into_bytes() } -/// The `mkeys` lines (v53): `mkeys video ::,,,, ...`, -/// the keys of the rect or ellipse mask at stack position `slot`, in source order. Only a -/// mask with keys gets a line. -fn mask_key_lines(lanes: &[(LaneKind, Vec)]) -> Vec { +/// The `ekeys` lines (v56): `ekeys video ::,,... ...`, +/// the keys of the effect at stack position `slot`, in source order, with one value for each +/// of its [`crate::effects::EffectKind::params`]. Only an effect with keys gets a line. +fn effect_key_lines(lanes: &[(LaneKind, Vec)]) -> Vec { let mut out = String::new(); let mut video = 0u32; for (kind, clips) in lanes { @@ -1668,9 +1673,11 @@ fn mask_key_lines(lanes: &[(LaneKind, Vec)]) -> Vec { if e.keys.is_empty() { continue; } - out += &format!("mkeys video {video} {idx} {slot}"); + out += &format!("ekeys video {video} {idx} {slot}"); + let count = e.kind.params().len(); for k in &e.keys { - out += &format!(" {}:{}:{},{},{},{},{}", k.at, k.ease.token(), k.x, k.y, k.width, k.height, k.feather); + let values: Vec = k.values[..count].iter().map(|v| v.to_string()).collect(); + out += &format!(" {}:{}:{}", k.at, k.ease.token(), values.join(",")); } out.push('\n'); } @@ -2955,8 +2962,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { })?; clip.stabilise = Some(crate::stabilise::Stabilise::new(strength, crop)); } + // A v53 mask's keys: five values, the mask's invert stays at its static value. b"mkeys" if v53 => { - use crate::effects::{EffectKind, MaskKey}; + use crate::effects::EffectKind; let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect(); if f.len() < 5 || f[0] != b"video" { return Err(format!("line {n}: mkeys wants a video clip, a slot and a key").into()); @@ -2972,38 +2980,6 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { .ok_or_else(|| format!("line {n}: mkeys names a lane that is not there"))?; let idx = number(f[2], n)? as usize; let slot = number(f[3], n)? as usize; - let points = &f[4..]; - if points.len() > MAX_TRANSFORM_KEYS { - return Err(format!("line {n}: mkeys has more than {MAX_TRANSFORM_KEYS} keys").into()); - } - let r = EffectKind::RectMask.params(); - let mut keys: Vec = Vec::new(); - for point in points { - let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect(); - if parts.len() != 3 { - return Err(format!("line {n}: mkeys key wants at:ease:values").into()); - } - 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()); - } - let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect(); - if v.len() != 5 { - return Err(format!("line {n}: mkeys key wants 5 values").into()); - } - let mut val = [0.0f32; 5]; - for (i, (x, field)) in val.iter_mut().zip(&v).enumerate() { - *x = float(field, n)?; - if !(r[i].min..=r[i].max).contains(x) { - return Err(format!("line {n}: mkeys {} is out of its range", r[i].name).into()); - } - } - let [x, y, width, height, feather] = val; - keys.push(MaskKey { at: at_frame, x, y, width, height, feather, ease }); - } let clip = doc.lanes[at] .1 .get_mut(idx) @@ -3013,6 +2989,45 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { .get_mut(slot) .filter(|e| matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask)) .ok_or_else(|| format!("line {n}: mkeys names an effect that is not a mask"))?; + let invert = effect.values[5]; + let mut keys = read_effect_keys("mkeys", &f[4..], &EffectKind::RectMask.params()[..5], n, v56)?; + for k in &mut keys { + k.values[5] = invert; + } + effect.keys = keys; + } + b"ekeys" if v56 => { + let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect(); + if f.len() < 4 || f[0] != b"video" { + return Err(format!("line {n}: ekeys wants a video clip, a slot and a key").into()); + } + let ord = number(f[1], n)?; + let at = doc + .lanes + .iter() + .enumerate() + .filter(|(_, (k, _))| *k == LaneKind::Video) + .nth(ord.saturating_sub(1) as usize) + .map(|(at, _)| at) + .ok_or_else(|| format!("line {n}: ekeys names a lane that is not there"))?; + let idx = number(f[2], n)? as usize; + let slot = number(f[3], n)? as usize; + let clip = doc.lanes[at] + .1 + .get_mut(idx) + .ok_or_else(|| format!("line {n}: ekeys names clip {idx}, which the lane does not have"))?; + let effect = clip + .effects + .get_mut(slot) + .ok_or_else(|| format!("line {n}: ekeys names an effect the clip does not have"))?; + let specs = effect.kind.params(); + let mut keys = read_effect_keys("ekeys", &f[4..], specs, n, v56)?; + // A parameter that cannot be keyed (a switch or a choice) keeps its static value. + for k in &mut keys { + for (i, _) in specs.iter().enumerate().filter(|(_, s)| !s.keyable()) { + k.values[i] = effect.values[i]; + } + } effect.keys = keys; } b"okeys" | b"ckeys" if v39 => { @@ -4586,6 +4601,49 @@ fn band(field: &[u8], line: usize) -> crate::Result { }) } +/// The `at:ease:values` points of an `mkeys` or `ekeys` line (`name`), in source order. +/// Each point holds one value per spec in `specs`, each within that spec's range, and the +/// rest of the key is zero. A custom bezier ease is read only from v56 on, and at most +/// [`MAX_TRANSFORM_KEYS`] points are read. +fn read_effect_keys( + name: &str, + points: &[&[u8]], + specs: &[crate::effects::ParamSpec], + n: usize, + v56: bool, +) -> crate::Result> { + if points.len() > MAX_TRANSFORM_KEYS { + return Err(format!("line {n}: {name} has more than {MAX_TRANSFORM_KEYS} keys").into()); + } + let mut keys: Vec = Vec::new(); + for point in points { + let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect(); + if parts.len() != 3 { + return Err(format!("line {n}: {name} key wants at:ease:values").into()); + } + let at = 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, hold or a bezier curve"))?; + if keys.last().is_some_and(|k| k.at >= at) { + return Err(format!("line {n}: {name} keys are not in source order").into()); + } + let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect(); + if v.len() != specs.len() { + return Err(format!("line {n}: {name} key wants {} values", specs.len()).into()); + } + let mut values = [0.0f32; crate::effects::MAX_PARAMS]; + for (i, (x, field)) in values.iter_mut().zip(&v).enumerate() { + *x = float(field, n)?; + if !(specs[i].min..=specs[i].max).contains(x) { + return Err(format!("line {n}: {name} {} is out of its range", specs[i].name).into()); + } + } + keys.push(crate::effects::EffectKey { at, values, ease }); + } + Ok(keys) +} + /// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity /// and NaN are refused rather than carried -- they are the values a coefficient /// cannot be built from, and the ones that would not compare equal to @@ -7069,7 +7127,7 @@ mod tests { /// The v51 library lines: bins, filed sources and starred ones round-trip; a project with /// none keeps its v50 bytes; the lines are refused in v50 and bad ones by name. #[test] - fn library_lines_round_trip_with_mask_keys_in_v53() { + fn library_lines_round_trip_with_effect_keys_in_v56() { use crate::project::Bin; let dir = std::env::temp_dir().join(format!("edith-bins-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); @@ -7080,8 +7138,8 @@ mod tests { ]; let mut lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]); let mut mask = crate::effects::Effect::new(crate::effects::EffectKind::EllipseMask); - mask.keys = vec![crate::effects::MaskKey { - at: 0, x: 0.5, y: 0.5, width: 0.4, height: 0.4, feather: 0.02, ease: KeyEase::Linear, + mask.keys = vec![crate::effects::EffectKey { + at: 0, values: [0.5, 0.5, 0.4, 0.4, 0.02, 0.0], ease: KeyEase::Linear, }]; lanes[0].1[0].effects = vec![mask]; let save = |src: &[Source], bins: &[Bin]| { @@ -7105,11 +7163,11 @@ mod tests { src[1].fav = true; src[1].bin = 1; let text = save(&src, &bins); - // A mask key is v53, and the library and the notes lines keep it there. - assert!(text.starts_with("edith 53\n"), "{text}"); + // An effect key is v56, and the library and the notes lines keep it there. + assert!(text.starts_with("edith 56\n"), "{text}"); assert!(text.contains("\nsrcbin 0 3\n") && text.contains("\nsrcfav 1\n"), "{text}"); - assert!(text.contains("\nmkeys video ") && text.contains("\nnotes Two cuts\n"), "{text}"); - let back = load(&path).expect("v53 loads"); + assert!(text.contains("\nekeys video 1 0 0 0:lin:0.5,0.5,0.4,0.4,0.02,0\n") && text.contains("\nnotes Two cuts\n"), "{text}"); + let back = load(&path).expect("v56 loads"); assert_eq!(back.notes, "Two cuts"); assert_eq!(back.bins, bins); assert_eq!((back.sources[0].bin, back.sources[0].fav), (3, false)); diff --git a/crates/engine/src/effects.rs b/crates/engine/src/effects.rs index 0ef8296..76a5c75 100644 --- a/crates/engine/src/effects.rs +++ b/crates/engine/src/effects.rs @@ -17,9 +17,9 @@ //! reach) are pixels *of a 1080-line frame* and scale with the frame's height, so //! a preview at a smaller size shows the effect at the size the export will. //! -//! The parameters are static (one value for the whole clip), except the two masks' -//! position, size and soft edge, which take keys ([`MaskKey`]) at source frames and -//! are read at the frame shown ([`Effect::posed`]). A pixelate is a filter; a mask +//! The parameters are static (one value for the whole clip) unless the effect has +//! keys ([`EffectKey`]) at source frames: then every keyable parameter (not a switch +//! or a choice such as a blend mode) is read at the frame shown ([`Effect::posed`]). A pixelate is a filter; a mask //! placed right after it limits it to that mask's shape, and that mask then does //! not cut the clip's coverage. An empty list, and a list whose every effect is //! switched off, is no effect at all -- not a sample is touched and no path changes @@ -166,6 +166,15 @@ pub struct ParamSpec { pub step: f32, } +impl ParamSpec { + /// Whether the parameter can take keys. A switch or a choice (a whole-number step + /// over a short range, such as a blend mode or an invert) cannot be eased between + /// two values, so it stays at its static value; every other parameter can. + pub fn keyable(&self) -> bool { + !(self.step >= 1.0 && self.max - self.min <= 10.0) + } +} + /// How a clip is laid over the lanes beneath it. Defined on RGB, as every /// editor defines them, and worked per pixel through the output's matrix. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] @@ -228,24 +237,21 @@ impl BlendMode { } } -/// One point of a mask's animation ([`Effect::keys`]): the shape's centre, size and -/// soft edge at source frame `at`, with the ease of the segment that leaves it. The -/// fields are the mask's [`EffectKind::params`] in order, so [`Effect::posed`] reads -/// them like the static values. +/// One point of an effect's animation ([`Effect::keys`]): every parameter of the +/// effect at source frame `at`, with the ease of the segment that leaves it. The +/// values are in [`EffectKind::params`] order and the unused tail is zero, so +/// [`Effect::posed`] reads them like the static values. A parameter that is not +/// [`ParamSpec::keyable`] holds the effect's static value in every key. #[derive(Clone, Copy, Debug, PartialEq)] -pub struct MaskKey { +pub struct EffectKey { /// Source frame of the key. pub at: u32, - pub x: f32, - pub y: f32, - pub width: f32, - pub height: f32, - pub feather: f32, + pub values: [f32; MAX_PARAMS], /// The easing of the segment that leaves this key. pub ease: KeyEase, } -impl Keyed for MaskKey { +impl Keyed for EffectKey { fn at(&self) -> u32 { self.at } @@ -256,29 +262,21 @@ impl Keyed for MaskKey { Self { at, ease, ..self } } fn mix(a: &Self, b: &Self, t: f32) -> Self { - let l = |x: f32, y: f32| x + (y - x) * t; - Self { - x: l(a.x, b.x), - y: l(a.y, b.y), - width: l(a.width, b.width), - height: l(a.height, b.height), - feather: l(a.feather, b.feather), - ..*a - } + Self { values: std::array::from_fn(|i| a.values[i] + (b.values[i] - a.values[i]) * t), ..*a } } } /// One effect of a stack: what it is, whether it is switched on, and its -/// parameters in [`EffectKind::params`] order (the unused tail is zero). A mask -/// may carry [`MaskKey`]s, which replace its position, size and soft edge. +/// parameters in [`EffectKind::params`] order (the unused tail is zero). Any +/// keyable parameter may be animated by [`EffectKey`]s in `keys`. #[derive(Clone, Debug, PartialEq)] pub struct Effect { pub kind: EffectKind, pub on: bool, pub values: [f32; MAX_PARAMS], - /// The mask's animation, sorted by [`MaskKey::at`] with no two alike. Empty is - /// the static values. Only a rect or ellipse mask has keys. - pub keys: Vec, + /// The effect's animation, sorted by [`EffectKey::at`] with no two alike. Empty is + /// the static values. + pub keys: Vec, } impl Effect { @@ -291,15 +289,20 @@ impl Effect { Effect { kind, on: true, values, keys: Vec::new() } } - /// The effect as it draws at source frame `src`: a keyed mask with its - /// position, size and soft edge interpolated from its keys; anything else as it - /// is, borrowed. + /// The effect as it draws at source frame `src`: each keyable parameter + /// interpolated from its keys (rounded when its step is a whole number), the + /// others as they are. An effect with no keys is borrowed as it is. pub fn posed(&self, src: f64) -> Cow<'_, Effect> { match sample(&self.keys, src) { None => Cow::Borrowed(self), Some(k) => { let mut e = self.clone(); - e.values[..5].copy_from_slice(&[k.x, k.y, k.width, k.height, k.feather]); + for (i, spec) in self.kind.params().iter().enumerate().filter(|(_, s)| s.keyable()) { + e.values[i] = match spec.step >= 1.0 { + true => k.values[i].round(), + false => k.values[i], + }; + } Cow::Owned(e) } } @@ -1143,15 +1146,17 @@ mod tests { } #[test] - fn a_mask_key_track_is_interpolated_at_the_frame_shown() { - use crate::transform::KeyEase; - let key = |at, x| MaskKey { at, x, y: 0.5, width: 0.2, height: 0.2, feather: 0.0, ease: KeyEase::Linear }; - let mut fx = Effect::new(EffectKind::RectMask); - fx.keys = vec![key(0, 0.2), key(100, 0.8)]; - assert!((fx.posed(50.0).get("x").unwrap() - 0.5).abs() < 1e-6, "halfway between the keys"); - assert_eq!(fx.posed(-5.0).get("x"), Some(0.2), "held before the first key"); - assert_eq!(fx.posed(300.0).get("x"), Some(0.8), "held after the last key"); - assert!(animated(std::slice::from_ref(&fx)), "a keyed mask redraws as the frames change"); + fn a_keyed_blur_is_interpolated_and_a_blend_mode_is_not() { + let key = |at, radius: f32, mode: f32| EffectKey { at, values: [radius, mode, 0.0, 0.0, 0.0, 0.0], ease: KeyEase::Linear }; + let mut blur = Effect::new(EffectKind::Blur); + blur.keys = vec![key(0, 2.0, 0.0), key(100, 10.0, 0.0)]; + assert!((blur.posed(50.0).get("radius").unwrap() - 6.0).abs() < 1e-6, "halfway between the keys"); + assert_eq!(blur.posed(-5.0).get("radius"), Some(2.0), "held before the first key"); + assert!(animated(std::slice::from_ref(&blur)), "a keyed effect redraws as the frames change"); + let mut blend = Effect::new(EffectKind::Blend); + blend.set("mode", 1.0).unwrap(); + blend.keys = vec![key(0, 0.0, 0.0), key(100, 0.0, 6.0)]; + assert_eq!(blend.posed(50.0).get("mode"), Some(1.0), "a switch keeps its static value"); } #[test] diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index fb1ade1..2bf31c2 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -5002,15 +5002,15 @@ impl PlaybackSession { self.project.effects_of(lane, idx) } - /// The keys of the mask at stack position `slot` ([`Project::mask_keys_of`]). - pub fn mask_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::MaskKey] { - self.project.mask_keys_of(lane, idx, slot) + /// The keys of the effect at stack position `slot` ([`Project::effect_keys_of`]). + pub fn effect_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::EffectKey] { + self.project.effect_keys_of(lane, idx, slot) } - /// Replaces the keys of the mask at stack position `slot`, or clears them with an - /// empty list ([`Project::set_mask_keys`]). One undo step and one reseek. - pub fn set_mask_keys(&mut self, lane: Lane, idx: usize, slot: usize, keys: Vec) -> bool { - self.edit(Dirty::Picture, |p| p.set_mask_keys(lane, idx, slot, keys)) + /// Replaces the keys of the effect at stack position `slot`, or clears them with an + /// empty list ([`Project::set_effect_keys`]). One undo step and one reseek. + pub fn set_effect_keys(&mut self, lane: Lane, idx: usize, slot: usize, keys: Vec) -> bool { + self.edit(Dirty::Picture, |p| p.set_effect_keys(lane, idx, slot, keys)) } /// Replaces the clip's effects stack ([`Project::set_effects`]). One undo @@ -5553,7 +5553,7 @@ impl PlaybackSession { /// values they have at each frame. Keys inside the tracked frames are replaced and /// keys outside them stay. Returns how many keys were written. One undo step. pub fn track_mask_apply(&mut self, job: &TrackJob, track: &crate::track::Track) -> Result { - use crate::effects::MaskKey; + use crate::effects::EffectKey; use crate::track::{KEY_TOLERANCE, simplify}; use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS}; let Some(&(_, x0, y0)) = track.points.first() else { @@ -5566,8 +5566,8 @@ impl PlaybackSession { .collect(); pts.sort_by_key(|p| p.0); let (first, last) = (pts[0].0, pts[pts.len() - 1].0); - let outside: Vec = - self.mask_keys_of(job.lane, job.idx, job.slot).iter().filter(|k| k.at < first || k.at > last).copied().collect(); + let outside: Vec = + self.effect_keys_of(job.lane, job.idx, job.slot).iter().filter(|k| k.at < first || k.at > last).copied().collect(); let room = MAX_TRANSFORM_KEYS.saturating_sub(outside.len()).max(2); let mut tolerance = KEY_TOLERANCE; let mut kept = simplify(&pts, tolerance); @@ -5585,15 +5585,17 @@ impl PlaybackSession { kept.iter() .map(|&i| { let (f, x, y) = pts[i]; - let v = e.posed(f64::from(f)); - MaskKey { at: f, x, y, width: v.values[2], height: v.values[3], feather: v.values[4], ease: KeyEase::Linear } + let mut values = e.posed(f64::from(f)).values; + values[0] = x; + values[1] = y; + EffectKey { at: f, values, ease: KeyEase::Linear } }) .collect::>() }; keys.extend(outside); keys.sort_by_key(|k| k.at); let count = keys.len(); - if !self.set_mask_keys(job.lane, job.idx, job.slot, keys) { + if !self.set_effect_keys(job.lane, job.idx, job.slot, keys) { return Err("the engine refused the keys (is the mask still there?)".into()); } Ok(count) diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 84c1997..e851722 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1161,8 +1161,8 @@ fn rekey_trimmed(c: &mut Clip, old: &Clip, edge: Edge, still: bool) { if !old.color_keys.is_empty() { c.color_keys = rekey(&old.color_keys, old, c, edge, still); } - // A mask's keys follow its stack position: the same effect, rekeyed the same way. - let masks: Vec>> = old + // An effect's keys follow its stack position: the same effect, rekeyed the same way. + let masks: Vec>> = old .effects .iter() .map(|e| (!e.keys.is_empty()).then(|| rekey(&e.keys, old, c, edge, still))) @@ -6048,38 +6048,44 @@ impl Project { true } - /// The keys of the mask at stack position `slot` of the clip at `idx` of `lane` - /// ([`crate::effects::Effect::keys`]); empty for anything else. - pub fn mask_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::MaskKey] { + /// The keys of the effect at stack position `slot` of the clip at `idx` of `lane` + /// ([`crate::effects::Effect::keys`]); empty for an effect with none. + pub fn effect_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::EffectKey] { self.lane(lane).get(idx).and_then(|c| c.effects.get(slot)).map_or(&[], |e| &e.keys) } - /// Replaces the keys of the mask at stack position `slot` of the clip at `idx` of - /// `lane`; an empty list clears them. Keys are source-frame keyed, sorted here with - /// no two alike, each field clamped into the mask's range. Refused for a clip that is - /// not a picture clip on a video lane, a slot that is not a rect or ellipse mask, - /// more than [`MAX_TRANSFORM_KEYS`] keys, or a list equal to the current one. One undo step. - pub fn set_mask_keys(&mut self, lane: Lane, idx: usize, slot: usize, mut keys: Vec) -> bool { - use crate::effects::{EffectKind, MaskKey}; + /// Replaces the keys of the effect at stack position `slot` of the clip at `idx` of + /// `lane`; an empty list clears them. Keys are source-frame keyed and sorted here with + /// no two alike. Each value is clamped into its parameter's range, a parameter that is + /// not keyable (a switch or a choice) takes the effect's static value, and the unused + /// tail is zeroed. Refused for a clip that is not a picture clip on a video lane, more + /// than [`MAX_TRANSFORM_KEYS`] keys, a non-finite value, or a list equal to the current + /// one. One undo step. + pub fn set_effect_keys(&mut self, lane: Lane, idx: usize, slot: usize, mut keys: Vec) -> bool { if lane.kind != LaneKind::Video || keys.len() > MAX_TRANSFORM_KEYS { return false; } - if keys.iter().any(|k| ![k.x, k.y, k.width, k.height, k.feather].iter().all(|v| v.is_finite())) { - return false; - } keys.sort_by_key(|k| k.at); if keys.windows(2).any(|w| w[0].at == w[1].at) { return false; } - let r = EffectKind::RectMask.params(); - for k in &mut keys { - let c = |v: f32, i: usize| v.clamp(r[i].min, r[i].max); - *k = MaskKey { x: c(k.x, 0), y: c(k.y, 1), width: c(k.width, 2), height: c(k.height, 3), feather: c(k.feather, 4), ..*k }; - } let Some(current) = self.lane(lane).get(idx).and_then(|c| c.effects.get(slot)) else { return false; }; - if !matches!(current.kind, EffectKind::RectMask | EffectKind::EllipseMask) || current.keys == keys { + let specs = current.kind.params(); + if keys.iter().any(|k| k.values[..specs.len()].iter().any(|v| !v.is_finite())) { + return false; + } + for k in &mut keys { + for (i, v) in k.values.iter_mut().enumerate() { + *v = match specs.get(i) { + Some(s) if s.keyable() => v.clamp(s.min, s.max), + Some(_) => current.values[i], + None => 0.0, + }; + } + } + if current.keys == keys { return false; } self.snapshot(); @@ -11354,7 +11360,7 @@ fn mirror_keys(c: &mut Clip) { c.opacity_keys = mirrored(&c.opacity_keys, top, |k| k.at, |k| k.ease, |k, at, ease| OpacityKey { at, ease, ..*k }); c.color_keys = mirrored(&c.color_keys, top, |k| k.at, |k| k.ease, |k, at, ease| ColorKey { at, ease, ..*k }); for e in &mut c.effects { - e.keys = mirrored(&e.keys, top, |k| k.at, |k| k.ease, |k, at, ease| crate::effects::MaskKey { at, ease, ..*k }); + e.keys = mirrored(&e.keys, top, |k| k.at, |k| k.ease, |k, at, ease| crate::effects::EffectKey { at, ease, ..*k }); } } diff --git a/crates/mcp/src/help.rs b/crates/mcp/src/help.rs index 1954e03..3c0c6d0 100644 --- a/crates/mcp/src/help.rs +++ b/crates/mcp/src/help.rs @@ -730,6 +730,15 @@ const OP_TEXTS: &[(&str, &str)] = &[ stays censored as it moves. clear:true takes the keys off. Up to 256 keys, sorted and clamped like opacity_keys. \ edit {ops:[{op:\"mask_keys\", clip:\"V1@0\", effect:1, keys:[{at:\"0s\", x:0.3, y:0.5}, {at:\"2s\", x:0.7}]}]}.", ), + ( + "effect_keys", + "effect_keys {clip, effect, keys:[{at, ?, ease?}], clear?} — animates any numeric parameter of the effect at stack \ + position effect over the clip's own time: every effect's parameters can be keyed (a blur's radius, a vignette's amount and \ + softness, a glow's threshold, a pixelate's size, a chroma key's tolerance, a mask's x, y, width, height and feather), named as \ + the effect names them. A switch or a choice (a blend's mode, a mask's invert) cannot be keyed. A parameter a key leaves out \ + takes the value the effect shows at that time. Up to 256 keys, sorted and clamped. \ + edit {ops:[{op:\"effect_keys\", clip:\"V1@0\", effect:0, keys:[{at:\"0s\", radius:2}, {at:\"3s\", radius:20, ease:\"ease_in_out\"}]}]}.", + ), ( "opacity_keys", "opacity_keys {clip, keys:[{at, opacity, ease?}], clear?} — the clip's opacity over its own time, 0 (clear) to 1 (opaque): \ diff --git a/crates/mcp/src/tools/edit.rs b/crates/mcp/src/tools/edit.rs index 76d789a..cf515a9 100644 --- a/crates/mcp/src/tools/edit.rs +++ b/crates/mcp/src/tools/edit.rs @@ -38,7 +38,7 @@ const OWN_OPS: &[&str] = &[ /// Ops `edit_fx` answers. const FX_OPS: &[&str] = &[ - "color", "lut", "wheels", "curves", "look", "auto_color", "transform", "transform_keys", "opacity_keys", "mask_keys", "color_keys", "fit", "eq", "gain", "gain_keys", "gain_key", "gain_key_remove", "gain_ramp", + "color", "lut", "wheels", "curves", "look", "auto_color", "transform", "transform_keys", "opacity_keys", "mask_keys", "effect_keys", "color_keys", "fit", "eq", "gain", "gain_keys", "gain_key", "gain_key_remove", "gain_ramp", "gain_dip", "lane_gain", "pan", "pitch", "lane_pan", "limiter", "lane_add", "lane_remove", "lane_move", "lane_flags", "lane_name", "deinterlace", "group", "ungroup", "subtitles_import", "duck", "dynamics", "stabilize", "reframe", "nest", "break_apart", "place_sequence", "angle", "title_add", "title_set", "title_remove", "generator_add", "generator_set", "adjustment_add", "label", "enable", @@ -115,6 +115,7 @@ transform {clip, x?, y?, scale?, rotate?, crop?:[l,r,t,b], opacity?, reset?} — 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. +effect_keys {clip, effect, keys?:[{at, ?: value, ease?}...], clear?} — animates any numeric parameter of the effect at stack position effect over the clip's own time, named as the effect names it (a blur's radius, a vignette's amount and softness, a mask's x, y, width, height and feather). A switch or a choice (a blend's mode, a mask's invert) cannot be keyed. A parameter a key leaves out takes the value the effect shows at that time. ease as transform_keys. 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. fit {clip, policy: fit|fill|stretch|center} — canvas fit. deinterlace {clip, mode: frame|field|off} — how a video clip's interlaced source is made progressive (default frame); stored on the clip, and only matters for an interlaced source (media_probe says interlaced). field (double rate) and off are stored; the render acts on frame for now. @@ -298,7 +299,7 @@ fn accepted_keys(name: &str) -> Option<&'static [&'static str]> { "transform" => &["clip", "x", "y", "corner", "margin", "scale", "rotate", "crop", "reset", "opacity"], "transform_keys" => &["clip", "keys", "clear"], "opacity_keys" | "color_keys" => &["clip", "keys", "clear"], - "mask_keys" => &["clip", "effect", "keys", "clear"], + "mask_keys" | "effect_keys" => &["clip", "effect", "keys", "clear"], "fit" => &["clip", "policy"], "eq" => &["clip", "bands", "reset"], "gain" => &["clip", "db", "add_db"], diff --git a/crates/mcp/src/tools/edit_fx.rs b/crates/mcp/src/tools/edit_fx.rs index 1b7c382..9ff6eca 100644 --- a/crates/mcp/src/tools/edit_fx.rs +++ b/crates/mcp/src/tools/edit_fx.rs @@ -9,7 +9,7 @@ use std::path::Path; use engine::color::ColorParams; -use engine::effects::{EffectKind, MaskKey}; +use engine::effects::{EffectKey, EffectKind, ParamSpec}; use engine::duck::{ Duck, MAX_ATTACK_MS, MAX_DEPTH_DB, MAX_RELEASE_MS, MAX_THRESHOLD_DB, MIN_DEPTH_DB, MIN_THRESHOLD_DB, MIN_TIME_MS, @@ -51,6 +51,7 @@ pub fn apply(s: &mut PlaybackSession, op: &Value, fps: f64) -> Option transform_keys(s, op, fps), "opacity_keys" => opacity_keys(s, op, fps), "mask_keys" => mask_keys(s, op, fps), + "effect_keys" => effect_keys(s, op, fps), "color_keys" => color_keys(s, op, fps), "lut" => lut(s, op), "wheels" => wheels(s, op), @@ -853,21 +854,16 @@ fn mask_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result return Err(format!("{who}: missing `effect`: the mask's stack position, 0 for the first effect")), - Some(v) => v.as_u64().ok_or_else(|| format!("{who}: effect must be a stack position, 0 for the first"))? as usize, - }; - let e = c.effects.get(slot).ok_or_else(|| { - format!("{who}: effect {slot} is out of range: the clip has {} effects", c.effects.len()) - })?; + let slot = effect_slot(&who, op, &c)?; + let e = &c.effects[slot]; if !matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) { return Err(format!("{who}: effect {slot} is {}, and only a rect or ellipse mask takes keys", e.kind.name())); } if flag(op, "clear")? { - if s.mask_keys_of(lane, idx, slot).is_empty() { + if s.effect_keys_of(lane, idx, slot).is_empty() { return Ok(done(format!("{who} → already no keys"), Vec::new())); } - if !s.set_mask_keys(lane, idx, slot, Vec::new()) { + if !s.set_effect_keys(lane, idx, slot, Vec::new()) { return Err(refused(&who)); } return Ok(done(format!("{who} → cleared (0 keys)"), vec![(lane, start)])); @@ -893,48 +889,131 @@ fn mask_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result = keys.iter().map(|k| k.at).collect(); clash_check(&who, &c, &at, &timed, start, fps)?; - let text = format!("{who} → {}", mask_keys_text(&c, fps, &keys)); - if keys == s.mask_keys_of(lane, idx, slot) { - return Ok(done(format!("{who} → already {}", mask_keys_text(&c, fps, &keys)), Vec::new())); + let text = format!("{who} → {}", effect_keys_text(&c, fps, r, &keys)); + if keys == s.effect_keys_of(lane, idx, slot) { + return Ok(done(format!("{who} → already {}", effect_keys_text(&c, fps, r, &keys)), Vec::new())); + } + if !s.set_effect_keys(lane, idx, slot, keys) { + return Err(refused(&who)); + } + Ok(done(text, vec![(lane, start)])) +} + +/// `effect_keys {clip, effect, keys:[{at, ?: n, ease?}], clear?}`: animates any numeric +/// parameter of the effect at stack position `effect` over the clip's own time. The parameter +/// names are the effect's own (a blur's `radius`, a vignette's `amount` and `softness`, a mask's +/// `x`, `y`, `width`, `height` and `feather`). A switch or a choice (a blend's `mode`, a mask's +/// `invert`) cannot be keyed and is refused by name. A key leaves each parameter it does not name +/// at the value the effect shows at that time. `clear:true` takes the keys off. +fn effect_keys(s: &mut PlaybackSession, op: &Value, fps: f64) -> Result { + let (lane, idx, raw, start) = clip_arg(s, op)?; + let who = format!("effect_keys {raw}"); + if lane.kind != LaneKind::Video { + return Err(format!("{who}: {raw} is on an audio lane; effect keys belong to a picture clip")); + } + let c = s.lane_clips(lane).get(idx).cloned().ok_or_else(|| refused(&who))?; + let slot = effect_slot(&who, op, &c)?; + let e = c.effects[slot].clone(); + let specs = e.kind.params(); + if flag(op, "clear")? { + if s.effect_keys_of(lane, idx, slot).is_empty() { + return Ok(done(format!("{who} → already no keys"), Vec::new())); + } + if !s.set_effect_keys(lane, idx, slot, Vec::new()) { + return Err(refused(&who)); + } + return Ok(done(format!("{who} → cleared (0 keys)"), vec![(lane, start)])); + } + let list = match op.get("keys") { + Some(Value::Array(a)) => a, + None | Some(Value::Null) => { + return Err(format!("{who}: missing `keys`: a list of {{at, , ease?}} objects, or clear:true")) + } + Some(v) => return Err(format!("{who}: keys must be a list of {{at, , ease?}} objects, got {}", kind_of(v))), + }; + for k in list.iter().filter_map(Value::as_object) { + for spec in specs.iter().filter(|p| !p.keyable()) { + if k.contains_key(spec.name) { + return Err(format!("{who}: {} cannot be keyed: a switch or a choice holds its static value", spec.name)); + } + } + } + let keyable: Vec<&str> = specs.iter().filter(|p| p.keyable()).map(|p| p.name).collect(); + let end = parse::session_end(s); + let timed = timed_keys(&who, list, &keyable, &c, fps, end, MAX_TRANSFORM_KEYS)?; + let mut keys = Vec::with_capacity(timed.len()); + for (i, (off, k)) in timed.iter().enumerate() { + let n = i + 1; + let at = src_at(&c, start + off); + // A parameter the key does not name holds the value the effect shows at that frame. + let mut values = e.posed(f64::from(at)).values; + for (j, spec) in specs.iter().enumerate().filter(|(_, p)| p.keyable()) { + if let Some(v) = num_of(k, spec.name)? { + values[j] = ranged(&who, spec.name, v, f64::from(spec.min), f64::from(spec.max))?; + } + } + keys.push(EffectKey { at, values, ease: ease_of(&who, n, k)? }); + } + let at: Vec = keys.iter().map(|k| k.at).collect(); + clash_check(&who, &c, &at, &timed, start, fps)?; + let text = format!("{who} → {}", effect_keys_text(&c, fps, specs, &keys)); + if keys == s.effect_keys_of(lane, idx, slot) { + return Ok(done(format!("{who} → already {}", effect_keys_text(&c, fps, specs, &keys)), Vec::new())); } - if !s.set_mask_keys(lane, idx, slot, keys) { + if !s.set_effect_keys(lane, idx, slot, keys) { return Err(refused(&who)); } Ok(done(text, vec![(lane, start)])) } -/// The mask keys as timeline times: at most twelve, then `(+N more)`. -fn mask_keys_text(c: &Clip, fps: f64, keys: &[MaskKey]) -> String { +/// The stack position a keys op names with `effect`, checked to be on the clip. +fn effect_slot(who: &str, op: &Value, c: &Clip) -> Result { + let slot = match op.get("effect") { + None | Some(Value::Null) => { + return Err(format!("{who}: missing `effect`: the effect's stack position, 0 for the first")) + } + Some(v) => v.as_u64().ok_or_else(|| format!("{who}: effect must be a stack position, 0 for the first"))? as usize, + }; + if slot >= c.effects.len() { + return Err(format!("{who}: effect {slot} is out of range: the clip has {} effects", c.effects.len())); + } + Ok(slot) +} + +/// One keyed value as a reply prints it: whole for a stepped parameter, else to two or three places. +fn value_text(v: f32, spec: &ParamSpec) -> String { + if spec.step >= 1.0 { + format!("{v:.0}") + } else if spec.step >= 0.01 { + format!("{v:.2}") + } else { + format!("{v:.3}") + } +} + +/// The effect keys as timeline times, each with its keyable parameters' values: at most twelve, +/// then `(+N more)`. +fn effect_keys_text(c: &Clip, fps: f64, specs: &[ParamSpec], keys: &[EffectKey]) -> String { const SHOWN: usize = 12; if keys.is_empty() { return "cleared (0 keys)".to_string(); } + let keyed: Vec<(usize, &ParamSpec)> = specs.iter().enumerate().filter(|(_, p)| p.keyable()).collect(); let mut parts: Vec = keys .iter() .take(SHOWN) .map(|k| { - format!( - "{} x {:.2} y {:.2} w {:.2} h {:.2} feather {:.3}{}", - tsec(timeline_of(c, k.at), fps), - k.x, - k.y, - k.width, - k.height, - k.feather, - ease_suffix(k.ease) - ) + let values: Vec = + keyed.iter().map(|(i, p)| format!("{} {}", p.name, value_text(k.values[*i], p))).collect(); + format!("{} {}{}", tsec(timeline_of(c, k.at), fps), values.join(" "), ease_suffix(k.ease)) }) .collect(); if keys.len() > SHOWN { diff --git a/crates/mcp/src/tools/effects.rs b/crates/mcp/src/tools/effects.rs index ce16f2d..dca46a4 100644 --- a/crates/mcp/src/tools/effects.rs +++ b/crates/mcp/src/tools/effects.rs @@ -20,7 +20,7 @@ const EFFECT_DOC: &str = r##"A video clip's effects stack: ops add, set, remove, - remove {clip, index} · move {clip, from, to} (stack positions; `to` is where it lands). - list {clip}: the stack with each effect's position, kind, on/off and named values. list with no clip: the kinds with their parameters and ranges. params is {name: number}; a number outside a range is clamped and the reply says so. color:"#rrggbb" sets a chroma_key's red, green and blue; mode:"screen" sets a blend's mode (normal, multiply, screen, overlay, add, darken, lighten). Masks take invert as 1/0 or true/false. -Effects are static: one value for the whole clip, except a rect or ellipse mask's position, size and soft edge, which take keys through edit's mask_keys (the stack position is the effect index), or follow a picture feature through the clip with track {clip, effect_index}. Distances (blur radius, shake amount, pixelate block size) are pixels at 1080 lines and scale with the frame height, so preview and export agree at any size. Ken Burns stays in transform_keys. Pixelate (size 2..200) makes mosaic blocks; a mask placed right after it limits the mosaic to that mask's shape and does not cut the clip, so an ellipse after a pixelate censors a face. Without a mask the whole picture is mosaiced. A stack that is empty or all switched off changes nothing. chroma_key and the masks reveal the lanes below; blend picks how the clip lies over them."##; +Effects are static: one value for the whole clip, unless keyed. Every numeric parameter of every effect can take keys through edit's effect_keys (the stack position is the effect index); a switch or a choice, such as a blend's mode or a mask's invert, stays static. A rect or ellipse mask's position can also follow a picture feature through the clip with track {clip, effect_index}. Distances (blur radius, shake amount, pixelate block size) are pixels at 1080 lines and scale with the frame height, so preview and export agree at any size. Ken Burns stays in transform_keys. Pixelate (size 2..200) makes mosaic blocks; a mask placed right after it limits the mosaic to that mask's shape and does not cut the clip, so an ellipse after a pixelate censors a face. Without a mask the whole picture is mosaiced. A stack that is empty or all switched off changes nothing. chroma_key and the masks reveal the lanes below; blend picks how the clip lies over them."##; pub fn tools() -> Vec { vec![Tool { name: "effect", description: EFFECT_DOC, schema: effect_schema, run: run_effect }] diff --git a/crates/mcp/src/tools/look.rs b/crates/mcp/src/tools/look.rs index b101065..405dfd3 100644 --- a/crates/mcp/src/tools/look.rs +++ b/crates/mcp/src/tools/look.rs @@ -13,6 +13,7 @@ use engine::project::{Edge, Lane, LaneKind, Title, TrimWalls}; use engine::scale::FitPolicy; use engine::color::ColorKey; use engine::transform::{OpacityKey, TransformKey}; +use engine::effects::Effect; use engine::{Clip, PlaybackSession}; use super::edit::audio_tracks; @@ -946,6 +947,61 @@ fn color_key_lines(c: &Clip, fps: f64, keys: &[ColorKey]) -> Vec { .collect() } +/// An effect's keys, one line each: the clip time and the timeline time, then each keyed +/// parameter by name with its value, and the ease that leaves the key. +fn effect_key_lines(c: &Clip, fps: f64, e: &Effect) -> Vec { + e.keys + .iter() + .map(|k| { + let at = timeline_of(c, k.at); + let values: String = e + .kind + .params() + .iter() + .enumerate() + .filter(|(_, p)| p.keyable()) + .map(|(i, p)| format!(" {} {}", p.name, num(f64::from(k.values[i])))) + .collect(); + format!( + " at clip {:.3}s (timeline {:.3}s){values} ease {}", + (at - f64::from(c.start)) / fps, + at / fps, + k.ease.name() + ) + }) + .collect() +} + +/// The keyed effects as JSON: each one's stack position and kind, then its keys with the +/// timeline time, the source frame, every keyed parameter by name, and the ease. +fn effect_keys_json(c: &Clip, fps: f64, effects: &[Effect]) -> Value { + Value::Array( + effects + .iter() + .enumerate() + .filter(|(_, e)| !e.keys.is_empty()) + .map(|(slot, e)| { + let keys: Vec = e + .keys + .iter() + .map(|k| { + let mut v = json!({ + "time": timeline_of(c, k.at) / fps, + "source_frame": k.at, + "ease": k.ease.name(), + }); + for (i, p) in e.kind.params().iter().enumerate().filter(|(_, p)| p.keyable()) { + v[p.name] = json!(k.values[i]); + } + v + }) + .collect(); + json!({ "index": slot, "kind": e.kind.name(), "keys": keys }) + }) + .collect(), + ) +} + fn opacity_keys_json(c: &Clip, fps: f64, keys: &[OpacityKey]) -> Value { Value::Array( keys.iter() @@ -1249,6 +1305,11 @@ fn media_info(s: &PlaybackSession, lane: Lane, idx: usize, fps: f64) -> Reply { lines.push(format!("color keys: {}", ckeys.len())); lines.extend(color_key_lines(c, fps, ckeys)); } + // Each effect with keys: its keyed values at every key, with the ease that leaves it. + for (slot, e) in s.effects_of(lane, idx).iter().enumerate().filter(|(_, e)| !e.keys.is_empty()) { + lines.push(format!("effect {slot} {} keys: {}", e.kind.name(), e.keys.len())); + lines.extend(effect_key_lines(c, fps, e)); + } if let Some(n) = engine::project::label_name(c.mark.label) { lines.push(format!("label {n}")); } @@ -1328,6 +1389,7 @@ fn media_info(s: &PlaybackSession, lane: Lane, idx: usize, fps: f64) -> Reply { "transform_keys": transform_keys_json(c, fps, keys), "opacity_keys": opacity_keys_json(c, fps, okeys), "color_keys": color_keys_json(c, fps, ckeys), + "effect_keys": effect_keys_json(c, fps, s.effects_of(lane, idx)), "trim_walls": { "start": walls_json(walls_start), "end": walls_json(walls_end),