Skip to content

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

Every Adjust knob can be keyed, and a keyed chain is drawn frame by frame

Jareerb8cc446e0df3
diff --git a/engine/crates/concat-effects/src/catalogue.rs b/engine/crates/concat-effects/src/catalogue.rs
index be39f4d2..7ebfcf76 100644
--- a/engine/crates/concat-effects/src/catalogue.rs
+++ b/engine/crates/concat-effects/src/catalogue.rs
@@ -504,19 +504,34 @@ impl Catalogue {
/// entry whose package has a shader. A filter's intensity rides along;
/// an effect is always whole.
pub fn shader_passes(&self, effects: &[AppliedFilter]) -> Vec<ShaderPass> {
+ self.passes_with(effects, |applied| applied.params.clone())
+ }
+
+ /// The same passes at one instant of the clip, `at` in `0..=1`: a
+ /// parameter with keys is worth what its ride says there. What a
+ /// renderer asks for each frame of a clip whose chain rides.
+ pub fn shader_passes_at(&self, effects: &[AppliedFilter], at: f64) -> Vec<ShaderPass> {
+ self.passes_with(effects, |applied| applied.params_at(at))
+ }
+
+ fn passes_with(
+ &self,
+ effects: &[AppliedFilter],
+ params_of: impl Fn(&AppliedFilter) -> BTreeMap<String, f64>,
+ ) -> Vec<ShaderPass> {
effects
.iter()
.filter(|applied| applied.enabled)
.filter_map(|applied| {
let package = self.get(&applied.id)?;
let shader = package.shader()?;
+ let set = params_of(applied);
let intensity = if package.kind() == Kind::Filter {
- (applied.params.get(INTENSITY).copied().unwrap_or(100.0) / 100.0)
- .clamp(0.0, 1.0) as f32
+ (set.get(INTENSITY).copied().unwrap_or(100.0) / 100.0).clamp(0.0, 1.0) as f32
} else {
1.0
};
- let values = package.resolve(&applied.params);
+ let values = package.resolve(&set);
Some(shader.pass(&values, &package.manifest.params, intensity))
})
.collect()
diff --git a/engine/crates/concat-effects/src/lib.rs b/engine/crates/concat-effects/src/lib.rs
index dfcc3bc2..efed4af9 100644
--- a/engine/crates/concat-effects/src/lib.rs
+++ b/engine/crates/concat-effects/src/lib.rs
@@ -70,6 +70,7 @@ mod tests {
.map(|(key, value)| ((*key).to_owned(), *value))
.collect(),
enabled: true,
+ keys: Default::default(),
}
}
diff --git a/engine/crates/concat-export/src/chains.rs b/engine/crates/concat-export/src/chains.rs
index 818c950b..7e19b02d 100644
--- a/engine/crates/concat-export/src/chains.rs
+++ b/engine/crates/concat-export/src/chains.rs
@@ -30,11 +30,7 @@ mod tests {
use super::*;
fn applied(id: &str) -> AppliedFilter {
- AppliedFilter {
- id: id.to_owned(),
- params: Default::default(),
- enabled: true,
- }
+ AppliedFilter::new(id)
}
#[test]
diff --git a/engine/crates/concat-export/src/flatten.rs b/engine/crates/concat-export/src/flatten.rs
index 9b65a0b5..14b7ec21 100644
--- a/engine/crates/concat-export/src/flatten.rs
+++ b/engine/crates/concat-export/src/flatten.rs
@@ -266,7 +266,6 @@ pub fn volume_curve(clip: &concat_project::model::Clip) -> Vec<(f64, f64)> {
#[cfg(test)]
mod tests {
- use std::collections::BTreeMap;
use concat_project::commands::{ClipPatch, NewMedia, TrackFlag};
use concat_project::model::AppliedFilter;
@@ -359,11 +358,7 @@ mod tests {
.apply(Command::UpdateClip {
clip_id,
patch: ClipPatch {
- video_effects: Some(vec![AppliedFilter {
- id: "sepia".into(),
- params: BTreeMap::new(),
- enabled: true,
- }]),
+ video_effects: Some(vec![AppliedFilter::new("sepia")]),
..Default::default()
},
})
diff --git a/engine/crates/concat-export/src/lib.rs b/engine/crates/concat-export/src/lib.rs
index ebd10062..3d108c62 100644
--- a/engine/crates/concat-export/src/lib.rs
+++ b/engine/crates/concat-export/src/lib.rs
@@ -788,6 +788,7 @@ fn render_picture(
treatments,
pre_chains,
passes,
+ riding,
cutouts,
highlight: _,
} = build_timeline(request, rate, visible, gpu);
@@ -820,6 +821,7 @@ fn render_picture(
reporter.cancelled()?;
let time = rate.time_of_frame(index);
+ let frame_seconds = time.as_f64();
let plan = plan_frame(&timeline, time);
let mut sources: Vec<Source<Frame>> = Vec::with_capacity(plan.layers.len());
@@ -850,7 +852,7 @@ fn render_picture(
transform: layer.transform,
track: tracks.get(&layer.clip).copied().unwrap_or(0),
blend: layer.blend,
- passes: passes.get(&layer.clip).cloned().unwrap_or_default(),
+ passes: passes_at(&passes, &riding, layer.clip, frame_seconds),
});
}
continue;
@@ -923,7 +925,7 @@ fn render_picture(
transform: layer.transform,
track: tracks.get(&layer.clip).copied().unwrap_or(0),
blend: layer.blend,
- passes: passes.get(&layer.clip).cloned().unwrap_or_default(),
+ passes: passes_at(&passes, &riding, layer.clip, frame_seconds),
});
}
}
@@ -989,6 +991,10 @@ struct BuiltTimeline {
pre_chains: HashMap<ClipId, String>,
/// The clip's shader passes, on a GPU renderer.
passes: HashMap<ClipId, Vec<ShaderPass>>,
+ /// The clips whose chains ride: a knob with keys is worth something
+ /// different each frame, so their passes are built per frame from the
+ /// chain and the clip's span rather than read from `passes`.
+ riding: HashMap<ClipId, RidingChain>,
/// The clip whose cutout is drawn tinted rather than cut, if one is.
highlight: Option<ClipId>,
/// The layers: treatments over the stack, by span.
@@ -997,6 +1003,33 @@ struct BuiltTimeline {
cutouts: HashMap<ClipId, CutoutJob>,
}
+/// A picture chain with keys on it, and where its clip sits, so a frame's
+/// passes can be built at the right point of the ride.
+struct RidingChain {
+ effects: Vec<AppliedFilter>,
+ start: f64,
+ duration: f64,
+}
+
+/// The shader passes for one clip at one frame: built for the instant when
+/// the chain rides, and the ones built once otherwise.
+fn passes_at(
+ passes: &HashMap<ClipId, Vec<ShaderPass>>,
+ riding: &HashMap<ClipId, RidingChain>,
+ clip: ClipId,
+ seconds: f64,
+) -> Vec<ShaderPass> {
+ if let Some(chain) = riding.get(&clip) {
+ let at = if chain.duration > 0.0 {
+ ((seconds - chain.start) / chain.duration).clamp(0.0, 1.0)
+ } else {
+ 0.0
+ };
+ return Catalogue::builtin().shader_passes_at(&chain.effects, at);
+ }
+ passes.get(&clip).cloned().unwrap_or_default()
+}
+
/// A layer clip, as the compositor needs it: when, over which tracks, what
/// chain, and how hard.
#[derive(Clone, Debug)]
@@ -1129,6 +1162,7 @@ fn build_timeline(
let mut treatments: Vec<Treatment> = Vec::new();
let mut pre_chains: HashMap<ClipId, String> = HashMap::new();
let mut passes: HashMap<ClipId, Vec<ShaderPass>> = HashMap::new();
+ let mut riding: HashMap<ClipId, RidingChain> = HashMap::new();
let mut cutouts: HashMap<ClipId, CutoutJob> = HashMap::new();
let mut highlight: Option<ClipId> = None;
@@ -1213,6 +1247,16 @@ fn build_timeline(
if !clip_passes.is_empty() {
passes.insert(id, clip_passes);
}
+ if clip.effects.iter().any(|link| link.enabled && !link.keys.is_empty()) {
+ riding.insert(
+ id,
+ RidingChain {
+ effects: clip.effects.clone(),
+ start: clip.start,
+ duration: clip.duration,
+ },
+ );
+ }
}
if let Some(job) = CutoutJob::of(clip) {
cutouts.insert(id, job);
@@ -1232,6 +1276,7 @@ fn build_timeline(
treatments,
pre_chains,
passes,
+ riding,
cutouts,
highlight,
}
@@ -1495,10 +1540,12 @@ pub fn preview_sources(
treatments,
pre_chains,
passes,
+ riding,
cutouts,
highlight,
} = preview_timeline(request, rate, gpu);
let time = quantise(request.time, rate);
+ let frame_seconds = time.as_f64();
let plan = plan_frame(&timeline, time);
let mut sources: Vec<Source<std::sync::Arc<Frame>>> = Vec::with_capacity(plan.layers.len());
@@ -1539,7 +1586,7 @@ pub fn preview_sources(
transform: layer.transform,
track: tracks.get(&layer.clip).copied().unwrap_or(0),
blend: layer.blend,
- passes: passes.get(&layer.clip).cloned().unwrap_or_default(),
+ passes: passes_at(&passes, &riding, layer.clip, frame_seconds),
})
}
Err(error) => failures.push(format!("{}: {error}", layer.media.display())),
diff --git a/engine/crates/concat-project/src/commands.rs b/engine/crates/concat-project/src/commands.rs
index 03b7b771..eca5e310 100644
--- a/engine/crates/concat-project/src/commands.rs
+++ b/engine/crates/concat-project/src/commands.rs
@@ -339,6 +339,47 @@ pub enum Command {
/// Which property.
property: KeyProperty,
},
+ /// Puts a key on one parameter of one link of a clip's picture chain,
+ /// replacing whichever key on it was already within a hair of `at`.
+ /// The value is the parameter's own; the package's range is the
+ /// caller's to keep, the model not knowing it.
+ SetEffectKey {
+ /// The clip.
+ clip_id: String,
+ /// Which link, as an index into `video_effects`. Out of range is a
+ /// no-op.
+ entry: usize,
+ /// The parameter's manifest key.
+ key: String,
+ /// Where in the clip, `0..=1`.
+ at: f64,
+ /// The value there.
+ value: f64,
+ /// How the key is approached from the one before it.
+ #[serde(default)]
+ ease: KeyEase,
+ },
+ /// Takes the key at `at` off one parameter of one link, if there is one.
+ ClearEffectKey {
+ /// The clip.
+ clip_id: String,
+ /// Which link, as an index into `video_effects`.
+ entry: usize,
+ /// The parameter's manifest key.
+ key: String,
+ /// Where in the clip the key to remove sits, `0..=1`.
+ at: f64,
+ },
+ /// Takes every key off one parameter of one link, returning it to the
+ /// value it holds.
+ ClearEffectKeys {
+ /// The clip.
+ clip_id: String,
+ /// Which link, as an index into `video_effects`.
+ entry: usize,
+ /// The parameter's manifest key.
+ key: String,
+ },
/// Sets or clears a picture's cutout: the mask that takes its
/// background away. Tidied on the way in; see [`Cutout::tidy`].
SetClipCutout {
@@ -1091,11 +1132,7 @@ pub fn apply(
crop: None,
cutout: None,
filters: Vec::new(),
- video_effects: vec![AppliedFilter {
- id: effect_id,
- params: Default::default(),
- enabled: true,
- }],
+ video_effects: vec![AppliedFilter::new(effect_id)],
muted: None,
detached_from: None,
transition_in: None,
@@ -1464,6 +1501,71 @@ pub fn apply(
})
}
+ Command::SetEffectKey {
+ clip_id,
+ entry,
+ key,
+ at,
+ value,
+ ease,
+ } => {
+ let timeline = project.active_mut();
+ let Some(link) = timeline
+ .clip_mut(&clip_id)
+ .and_then(|clip| clip.video_effects.get_mut(entry))
+ else {
+ return Ok(Outcome::default());
+ };
+ if !at.is_finite() || !value.is_finite() {
+ return Ok(Outcome::default());
+ }
+ let before = link.keys.clone();
+ link.set_key(&key, at, value, ease);
+ Ok(Outcome {
+ created_id: None,
+ applied: link.keys != before,
+ })
+ }
+
+ Command::ClearEffectKey {
+ clip_id,
+ entry,
+ key,
+ at,
+ } => {
+ let timeline = project.active_mut();
+ let Some(link) = timeline
+ .clip_mut(&clip_id)
+ .and_then(|clip| clip.video_effects.get_mut(entry))
+ else {
+ return Ok(Outcome::default());
+ };
+ let applied = link.clear_key(&key, at);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
+ Command::ClearEffectKeys {
+ clip_id,
+ entry,
+ key,
+ } => {
+ let timeline = project.active_mut();
+ let Some(link) = timeline
+ .clip_mut(&clip_id)
+ .and_then(|clip| clip.video_effects.get_mut(entry))
+ else {
+ return Ok(Outcome::default());
+ };
+ let applied = link.clear_keys(&key);
+ Ok(Outcome {
+ created_id: None,
+ applied,
+ })
+ }
+
Command::SetClipSpeedCurve { clip_id, curve } => {
let timeline = project.active_mut();
let Some(clip) = timeline.clip_mut(&clip_id) else {
diff --git a/engine/crates/concat-project/src/doc.rs b/engine/crates/concat-project/src/doc.rs
index a884d564..1d4e0071 100644
--- a/engine/crates/concat-project/src/doc.rs
+++ b/engine/crates/concat-project/src/doc.rs
@@ -18,13 +18,15 @@
//! flat `tracks`/`clips` mirror of the active timeline that keeps documents
//! openable in builds that predate multiple timelines.
+use std::collections::BTreeMap;
+
use serde_json::{Map, Value, json};
use crate::commands::{MAX_STRETCH, MIN_STRETCH};
use crate::model::{
AppliedFilter, Clip, ClipAnimation, ClipKey, ClipKind, Crop, CustomFont, Cutout, KeyEase,
- KeyProperty, MediaItem, MediaKind, Project, SpeedPoint, TextAlign, TextStyle, Timeline, Track,
- Transition, VideoSettings,
+ KeyProperty, MediaItem, MediaKind, ParamKey, Project, SpeedPoint, TextAlign, TextStyle,
+ Timeline, Track, Transition, VideoSettings,
};
/// Bumped only when a change cannot be absorbed by defaulting.
@@ -123,11 +125,40 @@ fn read_filters(raw: Option<&Value>) -> Vec<AppliedFilter> {
.collect()
})
.unwrap_or_default();
- Some(AppliedFilter {
+ let mut filter = AppliedFilter {
id,
params,
enabled: flag(entry.get("enabled"), true),
- })
+ keys: read_param_keys(entry.get("keys")),
+ };
+ filter.sort_keys();
+ Some(filter)
+ })
+ .collect()
+}
+
+/// An effect's parameter keys: a run per parameter name, each key read
+/// with the same tolerance as a clip's own.
+fn read_param_keys(raw: Option<&Value>) -> BTreeMap<String, Vec<ParamKey>> {
+ let Some(runs) = raw.and_then(Value::as_object) else {
+ return BTreeMap::new();
+ };
+ runs.iter()
+ .filter_map(|(name, run)| {
+ let keys: Vec<ParamKey> = run
+ .as_array()?
+ .iter()
+ .filter_map(|entry| {
+ let at = number(entry.get("at"), -1.0);
+ let value = number(entry.get("value"), f64::NAN);
+ ((0.0..=1.0).contains(&at) && value.is_finite()).then_some(ParamKey {
+ at,
+ value,
+ ease: read_ease(entry.get("ease")),
+ })
+ })
+ .collect();
+ (!keys.is_empty()).then(|| (name.clone(), keys))
})
.collect()
}
diff --git a/engine/crates/concat-project/src/lib.rs b/engine/crates/concat-project/src/lib.rs
index 0e2ab305..0994fe63 100644
--- a/engine/crates/concat-project/src/lib.rs
+++ b/engine/crates/concat-project/src/lib.rs
@@ -1558,4 +1558,67 @@ mod tests {
);
assert_eq!(text.opacity, 1.0);
}
+
+ #[test]
+ fn effect_keys_ride_a_knob_and_survive_the_document() {
+ use crate::model::{AppliedFilter, KeyEase};
+ let (mut editor, _, clip_id) = fixture();
+ let mut link = AppliedFilter::new("concat.adjust");
+ link.params.insert("exposure".to_owned(), 1.0);
+ editor
+ .apply(Command::UpdateClip {
+ clip_id: clip_id.clone(),
+ patch: ClipPatch {
+ video_effects: Some(vec![link]),
+ ..ClipPatch::default()
+ },
+ })
+ .expect("applies");
+ for (at, value) in [(0.0, -1.0), (1.0, 1.0)] {
+ editor
+ .apply(Command::SetEffectKey {
+ clip_id: clip_id.clone(),
+ entry: 0,
+ key: "exposure".to_owned(),
+ at,
+ value,
+ ease: KeyEase::LINEAR,
+ })
+ .expect("keys");
+ }
+ let link = &editor.project().active().clip(&clip_id).expect("clip").video_effects[0];
+ assert!(link.is_keyed("exposure"));
+ assert!(!link.is_keyed("contrast"));
+ // Halfway along a straight ride between -1 and 1 is 0; the constant
+ // is what the knob falls back to once the keys come off.
+ assert!((link.value_at("exposure", 0.5, 0.0)).abs() < 1e-9);
+ assert_eq!(link.params_at(0.25).get("exposure").copied(), Some(-0.5));
+ assert_eq!(link.keys_around("exposure", 0.5), (Some(0.0), Some(1.0)));
+ assert!(link.key_at("exposure", 1.0).is_some());
+
+ let document = editor.to_document(&settings());
+ let restored = Editor::from_document(&document).expect("loads");
+ let link = &restored.project().active().clip(&clip_id).expect("clip").video_effects[0];
+ assert_eq!(link.keys_on("exposure").len(), 2);
+
+ let mut editor = restored;
+ editor
+ .apply(Command::ClearEffectKey {
+ clip_id: clip_id.clone(),
+ entry: 0,
+ key: "exposure".to_owned(),
+ at: 1.0,
+ })
+ .expect("clears one");
+ editor
+ .apply(Command::ClearEffectKeys {
+ clip_id: clip_id.clone(),
+ entry: 0,
+ key: "exposure".to_owned(),
+ })
+ .expect("clears the rest");
+ let link = &editor.project().active().clip(&clip_id).expect("clip").video_effects[0];
+ assert!(!link.is_keyed("exposure"));
+ assert_eq!(link.value_at("exposure", 0.5, 0.0), 1.0);
+ }
}
diff --git a/engine/crates/concat-project/src/model.rs b/engine/crates/concat-project/src/model.rs
index bdd019f2..c39dce83 100644
--- a/engine/crates/concat-project/src/model.rs
+++ b/engine/crates/concat-project/src/model.rs
@@ -141,12 +141,166 @@ pub struct AppliedFilter {
/// False bypasses without losing settings. Absent means enabled.
#[serde(default = "yes")]
pub enabled: bool,
+ /// The knobs that ride rather than hold: a sorted run of keys per
+ /// parameter name, each `at` a fraction of the clip like a `ClipKey`'s.
+ /// A parameter with keys is played from them and its `params` entry is
+ /// only what it falls back to with the keys taken off.
+ #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
+ pub keys: BTreeMap<String, Vec<ParamKey>>,
}
fn yes() -> bool {
true
}
+/// One key on one parameter of an applied effect; see `AppliedFilter::keys`.
+#[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ParamKey {
+ /// Where in the clip, as a fraction of its timeline length, `0..=1`.
+ pub at: f64,
+ /// The value there, in the parameter's own units.
+ pub value: f64,
+ /// How this key is approached from the previous one.
+ #[serde(default)]
+ pub ease: KeyEase,
+}
+
+impl AppliedFilter {
+ /// A link with nothing set: the package's defaults, enabled.
+ pub fn new(id: impl Into<String>) -> AppliedFilter {
+ AppliedFilter {
+ id: id.into(),
+ params: BTreeMap::new(),
+ enabled: true,
+ keys: BTreeMap::new(),
+ }
+ }
+
+ /// This parameter's keys, in order; empty for one that holds still.
+ pub fn keys_on(&self, key: &str) -> &[ParamKey] {
+ self.keys.get(key).map_or(&[], Vec::as_slice)
+ }
+
+ /// Whether this parameter rides at all.
+ pub fn is_keyed(&self, key: &str) -> bool {
+ !self.keys_on(key).is_empty()
+ }
+
+ /// The index into this parameter's keys of the one at `at`, within
+ /// `KEY_EPSILON`, choosing the nearest when two are in reach.
+ pub fn key_at(&self, key: &str, at: f64) -> Option<usize> {
+ self.keys_on(key)
+ .iter()
+ .enumerate()
+ .filter(|(_, held)| (held.at - at).abs() <= KEY_EPSILON)
+ .min_by(|(_, a), (_, b)| (a.at - at).abs().total_cmp(&(b.at - at).abs()))
+ .map(|(index, _)| index)
+ }
+
+ /// This parameter's keys as the engine plays them.
+ pub fn track_on(&self, key: &str) -> concat_core::animate::Track {
+ concat_core::animate::Track::new(
+ self.keys_on(key)
+ .iter()
+ .map(|held| concat_core::animate::Key {
+ at: held.at,
+ value: held.value,
+ ease: held.ease.into(),
+ })
+ .collect(),
+ )
+ }
+
+ /// What a parameter is worth at `at`: its ride where it is keyed, and
+ /// otherwise what `params` holds, or `fallback` - the package's default,
+ /// which the model does not know - when that holds nothing either.
+ pub fn value_at(&self, key: &str, at: f64, fallback: f64) -> f64 {
+ let constant = self.params.get(key).copied().unwrap_or(fallback);
+ if !self.is_keyed(key) {
+ return constant;
+ }
+ self.track_on(key).value_at(at, constant)
+ }
+
+ /// Every set parameter at `at`: `params` with each keyed one replaced
+ /// by its ride's value there. What a renderer resolves a frame from.
+ pub fn params_at(&self, at: f64) -> BTreeMap<String, f64> {
+ let mut set = self.params.clone();
+ for (key, held) in &self.keys {
+ if held.is_empty() {
+ continue;
+ }
+ let rest = self.params.get(key).copied().unwrap_or(0.0);
+ set.insert(key.clone(), self.track_on(key).value_at(at, rest));
+ }
+ set
+ }
+
+ /// The nearest key strictly before `at`, and the nearest strictly after;
+ /// see `Clip::keys_around`.
+ pub fn keys_around(&self, key: &str, at: f64) -> (Option<f64>, Option<f64>) {
+ let mut before: Option<f64> = None;
+ let mut after: Option<f64> = None;
+ for held in self.keys_on(key) {
+ if held.at < at - KEY_EPSILON {
+ before = Some(before.map_or(held.at, |seen: f64| seen.max(held.at)));
+ } else if held.at > at + KEY_EPSILON {
+ after = Some(after.map_or(held.at, |seen: f64| seen.min(held.at)));
+ }
+ }
+ (before, after)
+ }
+
+ /// Sets a key, replacing whichever key on that parameter was already
+ /// within `KEY_EPSILON` of `at`. Keeps the run sorted by `at`.
+ pub fn set_key(&mut self, key: &str, at: f64, value: f64, ease: KeyEase) {
+ if !at.is_finite() || !value.is_finite() {
+ return;
+ }
+ let at = at.clamp(0.0, 1.0);
+ let slot = self.key_at(key, at);
+ let run = self.keys.entry(key.to_owned()).or_default();
+ match slot {
+ Some(index) => run[index] = ParamKey { at, value, ease },
+ None => run.push(ParamKey { at, value, ease }),
+ }
+ run.sort_by(|a, b| a.at.total_cmp(&b.at));
+ }
+
+ /// Removes this parameter's key at `at`, if there is one. True when a
+ /// key actually went; the run goes with its last key.
+ pub fn clear_key(&mut self, key: &str, at: f64) -> bool {
+ let Some(index) = self.key_at(key, at) else {
+ return false;
+ };
+ if let Some(run) = self.keys.get_mut(key) {
+ run.remove(index);
+ if run.is_empty() {
+ self.keys.remove(key);
+ }
+ }
+ true
+ }
+
+ /// Takes every key off one parameter. True when there were any.
+ pub fn clear_keys(&mut self, key: &str) -> bool {
+ self.keys.remove(key).is_some_and(|run| !run.is_empty())
+ }
+
+ /// Drops keys that are not finite or not in `0..=1`, empty runs with
+ /// them, and orders what is left. For the document reader.
+ pub fn sort_keys(&mut self) {
+ for run in self.keys.values_mut() {
+ run.retain(|key| {
+ key.at.is_finite() && key.value.is_finite() && (0.0..=1.0).contains(&key.at)
+ });
+ run.sort_by(|a, b| a.at.total_cmp(&b.at));
+ }
+ self.keys.retain(|_, run| !run.is_empty());
+ }
+}
+
/// How a picture's background is taken away when there is no key colour
/// to remove: a person mask found by the cutout model, alone or corrected
/// by hand.
diff --git a/engine/crates/concat/locales/en.json b/engine/crates/concat/locales/en.json
index bfe845a2..fa0c1fd1 100644
--- a/engine/crates/concat/locales/en.json
+++ b/engine/crates/concat/locales/en.json
@@ -171,7 +171,7 @@
"Exported · {0}": "Exported · {0}",
"Export…": "Export…",
"Exposure": "Exposure",
- "Exposure is in stops; the rest is a signed percent of the picture as shot, and zero everywhere is the picture as shot. Double-click a knob to put it back.": "Exposure is in stops; the rest is a signed percent of the picture as shot, and zero everywhere is the picture as shot. Double-click a knob to put it back.",
+ "Exposure is in stops; the rest is a signed percent of the picture as shot, and zero everywhere is the picture as shot. Double-click a label to put it back; the diamond keys the knob at the playhead.": "Exposure is in stops; the rest is a signed percent of the picture as shot, and zero everywhere is the picture as shot. Double-click a label to put it back; the diamond keys the knob at the playhead.",
"Fade": "Fade",
"Fade in": "Fade in",
"Fade out": "Fade out",
diff --git a/engine/crates/concat/src/lib.rs b/engine/crates/concat/src/lib.rs
index f0135457..82ab62f2 100644
--- a/engine/crates/concat/src/lib.rs
+++ b/engine/crates/concat/src/lib.rs
@@ -667,6 +667,17 @@ pub fn run() -> Result<(), slint::PlatformError> {
keys.on_clear(on_lanes!(|state, field: ClipField| {
state.clear_keys_on(field);
}));
+ // The same three verbs for the Adjust panel's knobs, which are
+ // named rather than enumerated.
+ keys.on_toggle_param(on_lanes!(|state, key: SharedString| {
+ state.toggle_adjust_key(key.as_str());
+ }));
+ keys.on_step_param(on_lanes!(|state, key: SharedString, delta: i32| {
+ state.step_adjust_key(key.as_str(), delta);
+ }));
+ keys.on_clear_param(on_lanes!(|state, key: SharedString| {
+ state.clear_adjust_keys(key.as_str());
+ }));
}
// The effect libraries' search, shelves and stars. Rust does the
diff --git a/engine/crates/concat/src/studio.rs b/engine/crates/concat/src/studio.rs
index 5b0f7f55..8dcf0f9d 100644
--- a/engine/crates/concat/src/studio.rs
+++ b/engine/crates/concat/src/studio.rs
@@ -961,9 +961,23 @@ fn set_slot(
/// The built-in colour package's id; see `adjust_rows` and `Studio::adjust_set`.
const ADJUST_ID: &str = "concat.adjust";
+/// The ease a key put on at `at` inherits: that of whichever key it joins
+/// behind, so laying a run of keys down does not alternate between shapes.
+/// The first key on a parameter has nothing to inherit and gets the
+/// straight line.
+fn ease_before(keys: &[model::ParamKey], at: f64) -> model::KeyEase {
+ keys.iter()
+ .rev()
+ .find(|key| key.at < at)
+ .map_or(model::KeyEase::LINEAR, |key| key.ease)
+}
+
/// The colour panel's rows: the adjust package's parameters, at the values
/// the clip's chain holds or at the defaults when the clip carries none.
-fn adjust_rows(chain: &[AppliedFilter]) -> Vec<AppliedParamData> {
+/// Every one can be keyed; `at` is the playhead's place in the clip, `0..=1`,
+/// or None when it is outside - a keyed knob then shows its ride's value
+/// there, and its cluster says whether a key sits under the playhead.
+fn adjust_rows(chain: &[AppliedFilter], at: Option<f64>) -> Vec<AppliedParamData> {
let Some(package) = Catalogue::builtin().get(ADJUST_ID) else {
return Vec::new();
};
@@ -972,24 +986,50 @@ fn adjust_rows(chain: &[AppliedFilter]) -> Vec<AppliedParamData> {
.manifest
.params
.iter()
- .map(|param| AppliedParamData {
- entry: -1,
- key: param.key.as_str().into(),
- label: t(&param.label).into(),
- group: t(&param.group).into(),
- unit: param.unit.as_str().into(),
- min: param.min as f32,
- max: param.max as f32,
- step: if param.step > 0.0 {
- param.step as f32
- } else {
- ((param.max - param.min) / 200.0) as f32
- },
- default_value: param.default as f32,
- value: held
- .and_then(|entry| entry.params.get(&param.key).copied())
- .unwrap_or(param.default) as f32,
- fmt: format_of(&param.unit),
+ .map(|param| {
+ let keyed = held.is_some_and(|entry| entry.is_keyed(&param.key));
+ let (here, prev, next) = match (held, at) {
+ (Some(entry), Some(at)) if keyed => {
+ let (prev, next) = entry.keys_around(&param.key, at);
+ (
+ entry.key_at(&param.key, at).is_some(),
+ prev.is_some(),
+ next.is_some(),
+ )
+ }
+ _ => (false, false, false),
+ };
+ let value = match (held, at) {
+ (Some(entry), Some(at)) => entry.value_at(&param.key, at, param.default),
+ (Some(entry), None) => entry
+ .params
+ .get(&param.key)
+ .copied()
+ .unwrap_or(param.default),
+ (None, _) => param.default,
+ };
+ AppliedParamData {
+ entry: -1,
+ key: param.key.as_str().into(),
+ label: t(&param.label).into(),
+ group: t(&param.group).into(),
+ unit: param.unit.as_str().into(),
+ min: param.min as f32,
+ max: param.max as f32,
+ step: if param.step > 0.0 {
+ param.step as f32
+ } else {
+ ((param.max - param.min) / 200.0) as f32
+ },
+ default_value: param.default as f32,
+ value: value as f32,
+ fmt: format_of(&param.unit),
+ keyable: true,
+ keyed,
+ here,
+ prev,
+ next,
+ }
})
.collect()
}
@@ -1040,6 +1080,11 @@ fn chain_rows(chain: &[AppliedFilter]) -> (Vec<AppliedEntryData>, Vec<AppliedPar
.copied()
.unwrap_or(100.0) as f32,
fmt: ParamFormat::Percent,
+ keyable: false,
+ keyed: false,
+ here: false,
+ prev: false,
+ next: false,
});
}
for param in &package.manifest.params {
@@ -1064,6 +1109,11 @@ fn chain_rows(chain: &[AppliedFilter]) -> (Vec<AppliedEntryData>, Vec<AppliedPar
.copied()
.unwrap_or(param.default) as f32,
fmt: format_of(&param.unit),
+ keyable: false,
+ keyed: false,
+ here: false,
+ prev: false,
+ next: false,
});
}
}
@@ -1539,11 +1589,7 @@ impl Studio {
// frame only, as the layer it would be: over every track, the
// whole way along, at full strength. The timeline is as it was.
if let Some(filter_id) = self.audition.clone() {
- let effects = vec![AppliedFilter {
- id: filter_id,
- params: std::collections::BTreeMap::new(),
- enabled: true,
- }];
+ let effects = vec![AppliedFilter::new(filter_id)];
let video_filter_chain = concat_export::chains::video_effect_chain(&effects);
let track = clips.iter().map(|flat| flat.track).max().map_or(0, |top| top + 1);
clips.push(concat_export::ExportClip {
@@ -2200,11 +2246,7 @@ impl Studio {
self.notify("A still has no sound to filter", true);
return;
}
- let entry = AppliedFilter {
- id: id.to_owned(),
- params: std::collections::BTreeMap::new(),
- enabled: true,
- };
+ let entry = AppliedFilter::new(id);
let patch = if video {
let mut effects = clip.video_effects.clone();
effects.push(entry);
@@ -2400,6 +2442,7 @@ impl Studio {
let Some(id) = self.sole_selection() else {
return;
};
+ let point = self.key_point().map(|(_, at)| at);
self.begin_echo();
let Some(clip) = self.echo_clip_mut(&id) else {
return;
@@ -2407,27 +2450,129 @@ impl Studio {
if !clip.kind.is_visual() {
return;
}
- let at = match clip
+ let entry = match clip
.video_effects
.iter()
.position(|entry| entry.id == ADJUST_ID)
{
- Some(at) => at,
+ Some(entry) => entry,
None => {
- clip.video_effects.insert(
- 0,
- AppliedFilter {
- id: ADJUST_ID.to_owned(),
- params: std::collections::BTreeMap::new(),
- enabled: true,
- },
- );
+ clip.video_effects.insert(0, AppliedFilter::new(ADJUST_ID));
0
}
};
- clip.video_effects[at]
- .params
- .insert(key.to_owned(), f64::from(value));
+ let link = &mut clip.video_effects[entry];
+ match point {
+ // A knob that rides is edited where the playhead is: the value
+ // becomes the key there, put on if there was none. Setting the
+ // constant under a ride would change nothing on screen.
+ Some(at) if link.is_keyed(key) => {
+ let ease = ease_before(link.keys_on(key), at);
+ link.set_key(key, at, f64::from(value), ease);
+ }
+ _ => {
+ link.params.insert(key.to_owned(), f64::from(value));
+ }
+ }
+ }
+
+ /// The colour link of the selected clip - the one the Adjust panel's
+ /// keys go on - by index, with the clip and the playhead's place in it.
+ /// None when nothing is selected, it is not a picture, or the playhead
+ /// is outside it.
+ fn adjust_point(&self) -> Option<(Clip, f64, Option<usize>)> {
+ let (clip, at) = self.key_point()?;
+ if !clip.kind.is_visual() {
+ return None;
+ }
+ let entry = clip
+ .video_effects
+ .iter()
+ .position(|entry| entry.id == ADJUST_ID);
+ Some((clip.clone(), at, entry))
+ }
+
+ /// Puts a key on one Adjust knob at the playhead, or takes off the one
+ /// there. Like `toggle_key`, the new key holds what the knob is worth
+ /// at that instant, so pressing the diamond never moves the picture.
+ pub fn toggle_adjust_key(&mut self, key: &str) {
+ let Some((clip, at, entry)) = self.adjust_point() else {
+ return;
+ };
+ let default = Catalogue::builtin()
+ .get(ADJUST_ID)
+ .and_then(|package| package.manifest.params.iter().find(|p| p.key == key))
+ .map_or(0.0, |param| param.default);
+ let clip_id = clip.id.clone();
+ let Some(entry) = entry else {
+ // No colour link yet: one goes on, then the key on it, as one
+ // edit, so an undo takes both back.
+ let mut effects = clip.video_effects.clone();
+ effects.insert(0, AppliedFilter::new(ADJUST_ID));
+ self.apply(Command::Batch {
+ commands: vec![
+ Command::UpdateClip {
+ clip_id: clip_id.clone(),
+ patch: ClipPatch {
+ video_effects: Some(effects),
+ ..ClipPatch::default()
+ },
+ },
+ Command::SetEffectKey {
+ clip_id,
+ entry: 0,
+ key: key.to_owned(),
+ at,
+ value: default,
+ ease: model::KeyEase::LINEAR,
+ },
+ ],
+ });
+ return;
+ };
+ let link = &clip.video_effects[entry];
+ let command = if link.key_at(key, at).is_some() {
+ Command::ClearEffectKey {
+ clip_id,
+ entry,
+ key: key.to_owned(),
+ at,
+ }
+ } else {
+ Command::SetEffectKey {
+ clip_id,
+ entry,
+ key: key.to_owned(),
+ at,
+ value: link.value_at(key, at, default),
+ ease: ease_before(link.keys_on(key), at),
+ }
+ };
+ self.apply(command);
+ }
+
+ /// Takes every key off one Adjust knob, leaving it the value it holds.
+ pub fn clear_adjust_keys(&mut self, key: &str) {
+ let Some((clip, _, Some(entry))) = self.adjust_point() else {
+ return;
+ };
+ self.apply(Command::ClearEffectKeys {
+ clip_id: clip.id,
+ entry,
+ key: key.to_owned(),
+ });
+ }
+
+ /// Moves the playhead to an Adjust knob's previous (-1) or next (+1) key.
+ pub fn step_adjust_key(&mut self, key: &str, delta: i32) {
+ let Some((clip, at, Some(entry))) = self.adjust_point() else {
+ return;
+ };
+ let (prev, next) = clip.video_effects[entry].keys_around(key, at);
+ let Some(target) = (if delta < 0 { prev } else { next }) else {
+ return;
+ };
+ self.seek((clip.start + target * clip.duration) as f32);
}
// ── gestures ──
@@ -5031,7 +5176,9 @@ impl Studio {
sync(
&models.adjust_params,
match self.sole_selection().and_then(|id| self.clip(&id)) {
- Some(clip) if clip.kind.is_visual() => adjust_rows(&clip.video_effects),
+ Some(clip) if clip.kind.is_visual() => {
+ adjust_rows(&clip.video_effects, self.key_point().map(|(_, at)| at))
+ }
_ => Vec::new(),
},
);
diff --git a/engine/crates/concat/ui/inspector/clip-inspector.slint b/engine/crates/concat/ui/inspector/clip-inspector.slint
index 4663e4bb..cfaa927c 100644
--- a/engine/crates/concat/ui/inspector/clip-inspector.slint
+++ b/engine/crates/concat/ui/inspector/clip-inspector.slint
@@ -126,6 +126,15 @@ export struct AppliedParamData {
default-value: float,
value: float,
fmt: ParamFormat,
+ /// The knob can carry keys - the Adjust panel's can, a chain's cannot
+ /// yet - and, when it can, the same four facts a ClipKeyData holds:
+ /// it rides at all, a key sits under the playhead, and there is one
+ /// behind or ahead to step to.
+ keyable: bool,
+ keyed: bool,
+ here: bool,
+ prev: bool,
+ next: bool,
}
/// The favourites chip: a star that filters the shelf down to what is on it.
@@ -1700,7 +1709,7 @@ export component AdjustPanel inherits VerticalLayout {
}
if root.help: Note {
- text: I18n.t("Exposure is in stops; the rest is a signed percent of the picture as shot, and zero everywhere is the picture as shot. Double-click a knob to put it back.");
+ text: I18n.t("Exposure is in stops; the rest is a signed percent of the picture as shot, and zero everywhere is the picture as shot. Double-click a label to put it back; the diamond keys the knob at the playhead.");
}
// See PresetStack for why each row re-seeds its knob. A subhead
@@ -1727,6 +1736,15 @@ export component AdjustPanel inherits VerticalLayout {
step: p.step;
default-value: p.default-value;
fmt: p.fmt;
+ keyable: p.keyable;
+ key-name: p.key;
+ key-state: {
+ field: ClipField.scale,
+ keyed: p.keyed,
+ here: p.here,
+ prev: p.prev,
+ next: p.next,
+ };
changed(v) => { root.set(p.key, v); root.commit(); }
}
}
diff --git a/engine/crates/concat/ui/inspector/controls.slint b/engine/crates/concat/ui/inspector/controls.slint
index 67ea5455..6ecd1e38 100644
--- a/engine/crates/concat/ui/inspector/controls.slint
+++ b/engine/crates/concat/ui/inspector/controls.slint
@@ -280,16 +280,29 @@ component KeyButton inherits Rectangle {
// arriving at one is how you edit it.
export component KeyCluster inherits HorizontalLayout {
in property <ClipField> field;
+ /// A knob named rather than enumerated - an Adjust row - keys by this
+ /// name instead of `field`, and is handed its state rather than looking
+ /// it up. Empty for a field.
+ in property <string> name;
+ in property <ClipKeyData> state: Keyframes.row(root.field);
- property <ClipKeyData> state: Keyframes.row(root.field);
property <bool> live: Keyframes.available;
+ function toggle() {
+ if (root.name == "") { Keyframes.toggle(root.field); }
+ else { Keyframes.toggle-param(root.name); }
+ }
+ function step(delta: int) {
+ if (root.name == "") { Keyframes.step(root.field, delta); }
+ else { Keyframes.step-param(root.name, delta); }
+ }
+
spacing: 1px;
prev := KeyButton {
glyph: Glyph.chevron-left;
enabled: root.live && root.state.prev;
- clicked => { Keyframes.step(root.field, -1); }
+ clicked => { root.step(-1); }
}
diamond := KeyButton {
@@ -301,13 +314,13 @@ export component KeyCluster inherits HorizontalLayout {
filled: root.state.here;
enabled: root.live;
tint: root.state.here || root.state.keyed ? Theme.accent : Theme.fg-dim;
- clicked => { Keyframes.toggle(root.field); }
+ clicked => { root.toggle(); }
}
next := KeyButton {
glyph: Glyph.chevron-right;
enabled: root.live && root.state.next;
- clicked => { Keyframes.step(root.field, 1); }
+ clicked => { root.step(1); }
}
}
@@ -343,6 +356,9 @@ export component Param inherits VerticalLayout {
/// row would otherwise claim to be keying scale.
in property <bool> keyable: false;
in property <ClipField> field;
+ /// See KeyCluster: a row keyed by name is handed its key state.
+ in property <string> key-name;
+ in property <ClipKeyData> key-state: Keyframes.row(root.field);
callback changed(value: float);
@@ -351,11 +367,21 @@ export component Param inherits VerticalLayout {
spacing: 4px;
HorizontalLayout {
+ // Double-click the label to put the value back. The label rather
+ // than the field, which a double-click would only start typing in.
Text {
text: root.label;
color: Theme.fg-muted;
font-size: Theme.fs;
vertical-alignment: center;
+
+ TouchArea {
+ enabled: root.enabled;
+ double-clicked => {
+ root.value = root.default-value;
+ root.changed(root.default-value);
+ }
+ }
}
Rectangle { horizontal-stretch: 1; }
@@ -394,7 +420,11 @@ export component Param inherits VerticalLayout {
if root.keyable: Rectangle { width: 6px; }
if root.keyable: VerticalLayout {
alignment: center;
- KeyCluster { field: root.field; }
+ KeyCluster {
+ field: root.field;
+ name: root.key-name;
+ state: root.key-state;
+ }
}
}
diff --git a/engine/crates/concat/ui/timeline/model.slint b/engine/crates/concat/ui/timeline/model.slint
index e79d24ad..37c2aee0 100644
--- a/engine/crates/concat/ui/timeline/model.slint
+++ b/engine/crates/concat/ui/timeline/model.slint
@@ -199,6 +199,13 @@ export global Keyframes {
/// person could see.
callback clear(field: ClipField);
+ /// The same three verbs for a knob named rather than enumerated - the
+ /// Adjust panel's, whose rows come from the colour package's manifest
+ /// and carry their own key state; see AppliedParamData.
+ callback toggle-param(key: string);
+ callback step-param(key: string, delta: int);
+ callback clear-param(key: string);
+
/// A row for a field with no keys and nowhere to step.
pure public function blank(field: ClipField) -> ClipKeyData {
return { field: field, keyed: false, here: false, prev: false, next: false };