Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

#223: Effect Controls shows the audio of a linked video clip

Oskar7a922ab1395c
diff --git a/crates/ui-egui/src/panels/effect_controls.rs b/crates/ui-egui/src/panels/effect_controls.rs
index e3ae049c4..7bd42b6cf 100644
--- a/crates/ui-egui/src/panels/effect_controls.rs
+++ b/crates/ui-egui/src/panels/effect_controls.rs
@@ -3,7 +3,7 @@
//! keyframe lane on the right. Also hosts the Lumetri Color panel body (same editor, grouped).
use egui::{Align2, Color32, Pos2, Rect, Sense, Stroke, pos2, vec2};
-use filmcraft_project::{ClipId, EffectInstance, ParamKind, ParamValue, TrackItem};
+use filmcraft_project::{ClipId, EffectInstance, ParamKind, ParamValue, TrackItem, TrackKind};
use filmcraft_time::Tick;
use serde_json::{Value, json};
@@ -28,24 +28,37 @@ fn timeline_time_of(it: &TrackItem, m: Tick) -> Tick {
it.start + Tick(((m - it.source_in).0 as f64 / it.speed.abs().max(1e-6)) as i64)
}
-fn selected_clip(app: &FilmcraftApp) -> Option<(ClipId, TrackItem, filmcraft_project::TrackKind)> {
- let seq = app.session.active_sequence()?;
- let mut best = None;
- for c in &app.session.state.selection {
- if let Some((tid, it)) = seq.find_item(*c) {
- let kind = seq.track(tid)?.kind;
- if kind == filmcraft_project::TrackKind::Video {
- return Some((*c, it.clone(), kind));
- }
- best.get_or_insert((*c, it.clone(), kind));
- }
+fn selected_clip(app: &FilmcraftApp) -> Option<(ClipId, TrackItem, TrackKind)> {
+ selected_clips(app).into_iter().next()
+}
+
+/// The selected clip (video first) and, for a video clip, the selected audio linked to it.
+fn selected_clips(app: &FilmcraftApp) -> Vec<(ClipId, TrackItem, TrackKind)> {
+ let Some(seq) = app.session.active_sequence() else { return Vec::new() };
+ let picked: Vec<(ClipId, &TrackItem, TrackKind)> = app
+ .session
+ .state
+ .selection
+ .iter()
+ .filter_map(|c| {
+ let (tid, it) = seq.find_item(*c)?;
+ Some((*c, it, seq.track(tid)?.kind))
+ })
+ .collect();
+ let Some(&(clip, it, kind)) = picked.iter().find(|p| p.2 == TrackKind::Video).or(picked.first()) else { return Vec::new() };
+ let mut out = vec![(clip, it.clone(), kind)];
+ if kind == TrackKind::Video
+ && let Some(&(ac, ai, ak)) = picked.iter().find(|p| p.2 == TrackKind::Audio && p.1.link.is_some() && p.1.link == it.link)
+ {
+ out.push((ac, ai.clone(), ak));
}
- best
+ out
}
pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let t = app.tokens;
- let Some((clip, it, kind)) = selected_clip(app) else {
+ let clips = selected_clips(app);
+ let Some((clip, it, _)) = clips.first().cloned() else {
crate::dock::placeholder(ui, rect, &t, tl!("(no clip selected)"));
return;
};
@@ -97,90 +110,93 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
let mut actions: Vec<(String, Value)> = Vec::new();
let mut bui = ui.new_child(egui::UiBuilder::new().max_rect(body).id_salt("ec-body"));
bui.set_clip_rect(Rect::from_min_max(body.min, pos2(rect.max.x, body.max.y)));
- let mt_now = it.source_time_at(ph.clamp(it.start, it.end() - Tick(1)));
- let heading = if kind == filmcraft_project::TrackKind::Video { tl!("Video") } else { tl!("Audio") };
- bui.painter().text(pos2(body.min.x + 8.0, body.min.y + 8.0), Align2::LEFT_CENTER, heading, Tokens::semibold(11.5), t.text_dim);
- bui.add_space(18.0);
- // Premiere lists the fixed effects (Motion, Opacity, Time Remapping / Volume…) first.
- let mut order: Vec<usize> = (0..it.effects.len()).collect();
- order.sort_by_key(|i| !it.effects[*i].def().is_some_and(|d| d.intrinsic));
let scroll_out = egui::ScrollArea::vertical().id_salt("ec-scroll").auto_shrink([false, false]).show(&mut bui, |bui| {
- for idx in order {
- let e = &it.effects[idx];
- let Some(def) = e.def() else { continue };
- let key = format!("{}:{}", clip.0, idx);
- let open = !app.ui.collapsed_fx.contains(&key);
- let (r, resp) = bui.allocate_exact_size(vec2(body.width(), ROW_H), Sense::click());
- if resp.hovered() {
- bui.painter().rect_filled(r, 0.0, t.hover);
- }
- icons::paint(
- bui.painter(),
- Rect::from_center_size(pos2(r.min.x + 10.0, r.center().y), vec2(10.0, 10.0)),
- if open { Icon::ChevronDown } else { Icon::ChevronRight },
- t.text_dim,
- );
- // fx enable toggle
- let fxr = Rect::from_center_size(pos2(r.min.x + 28.0, r.center().y), vec2(18.0, 14.0));
- let fxresp = bui.interact(fxr, egui::Id::new(("fxen", clip.0, idx)), Sense::click());
- bui.painter().text(fxr.center(), Align2::CENTER_CENTER, "fx", Tokens::semibold(10.5), if e.enabled { t.text } else { t.text_faint });
- if !e.enabled {
- bui.painter().line_segment([fxr.left_bottom(), fxr.right_top()], Stroke::new(1.0, t.text_faint));
- }
- if fxresp.clicked() {
- actions.push(("effects.toggleEnabled".into(), json!({"clip": clip.0, "index": idx})));
- }
- bui.painter().text(pos2(r.min.x + 42.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::t(def.name), Tokens::ui(12.0), t.text);
- // reset button
- let rr = Rect::from_center_size(pos2(r.max.x - 14.0, r.center().y), vec2(16.0, 16.0));
- let rresp = bui.interact(rr, egui::Id::new(("fxreset", clip.0, idx)), Sense::click()).on_hover_text(tl!("Reset Effect"));
- icons::paint(bui.painter(), rr.shrink(2.0), Icon::Reset, if rresp.hovered() { t.text } else { t.text_dim });
- if rresp.clicked() {
- actions.push(("effects.reset".into(), json!({"clip": clip.0, "index": idx})));
- }
- app.auto.add(&format!("effectControls.effect.{}", e.effect), r, def.name);
- if resp.clicked() && !fxresp.clicked() && !rresp.clicked() {
- if open {
- app.ui.collapsed_fx.push(key.clone());
- } else {
- app.ui.collapsed_fx.retain(|k| *k != key);
+ for (clip, it, kind) in &clips {
+ let clip = *clip;
+ let (hr, _) = bui.allocate_exact_size(vec2(body.width(), 18.0), Sense::hover());
+ let heading = if *kind == TrackKind::Video { tl!("Video") } else { tl!("Audio") };
+ bui.painter().text(pos2(hr.min.x + 8.0, hr.center().y), Align2::LEFT_CENTER, heading, Tokens::semibold(11.5), t.text_dim);
+ let mt_now = it.source_time_at(ph.clamp(it.start, (it.end() - Tick(1)).max(it.start)));
+ // Premiere lists the fixed effects (Motion, Opacity, Time Remapping / Volume…) first.
+ let mut order: Vec<usize> = (0..it.effects.len()).collect();
+ order.sort_by_key(|i| !it.effects[*i].def().is_some_and(|d| d.intrinsic));
+ for idx in order {
+ let e = &it.effects[idx];
+ let Some(def) = e.def() else { continue };
+ let key = format!("{}:{}", clip.0, idx);
+ let open = !app.ui.collapsed_fx.contains(&key);
+ let (r, resp) = bui.allocate_exact_size(vec2(body.width(), ROW_H), Sense::click());
+ if resp.hovered() {
+ bui.painter().rect_filled(r, 0.0, t.hover);
}
- }
- let mut save_preset = false;
- let fx_id = e.effect.clone();
- resp.context_menu(|ui| {
- let sp = ui.button(tl!("Save Preset…"));
- app.auto.add(&format!("effectControls.effect.{fx_id}.savePreset"), sp.rect, "Save Preset…");
- if sp.clicked() {
- save_preset = true;
- ui.close();
+ icons::paint(
+ bui.painter(),
+ Rect::from_center_size(pos2(r.min.x + 10.0, r.center().y), vec2(10.0, 10.0)),
+ if open { Icon::ChevronDown } else { Icon::ChevronRight },
+ t.text_dim,
+ );
+ // fx enable toggle
+ let fxr = Rect::from_center_size(pos2(r.min.x + 28.0, r.center().y), vec2(18.0, 14.0));
+ let fxresp = bui.interact(fxr, egui::Id::new(("fxen", clip.0, idx)), Sense::click());
+ bui.painter().text(fxr.center(), Align2::CENTER_CENTER, "fx", Tokens::semibold(10.5), if e.enabled { t.text } else { t.text_faint });
+ if !e.enabled {
+ bui.painter().line_segment([fxr.left_bottom(), fxr.right_top()], Stroke::new(1.0, t.text_faint));
}
- if !def.intrinsic && ui.button(tl!("Clear")).clicked() {
- actions.push(("effects.remove".into(), json!({"clip": clip.0, "index": idx})));
- ui.close();
+ if fxresp.clicked() {
+ actions.push(("effects.toggleEnabled".into(), json!({"clip": clip.0, "index": idx})));
}
- });
- if save_preset {
- crate::panels::presets::open_save(app, clip.0, vec![idx], def.name);
- }
- if !open {
- continue;
- }
- if crate::panels::audio_fx_editor::has_editor(&e.effect) {
- custom_setup_row(app, bui, body, clip, idx, &e.effect);
- }
- for pd in &def.params {
- param_row(app, bui, body, clip, idx, e, None, pd, mt_now, &mut actions, &lane, &lx, &it);
- if app.ui.expanded_fx.contains(&graph_key(clip, idx, pd.id))
- && let Some(param) = e.params.get(pd.id)
- && param.is_animated()
- && matches!(param.value, ParamValue::Float(_))
- {
- graph_rows(app, bui, body, clip, idx, None, pd, param, &lane, &it, &mut actions);
+ bui.painter().text(pos2(r.min.x + 42.0, r.center().y), Align2::LEFT_CENTER, crate::i18n::t(def.name), Tokens::ui(12.0), t.text);
+ // reset button
+ let rr = Rect::from_center_size(pos2(r.max.x - 14.0, r.center().y), vec2(16.0, 16.0));
+ let rresp = bui.interact(rr, egui::Id::new(("fxreset", clip.0, idx)), Sense::click()).on_hover_text(tl!("Reset Effect"));
+ icons::paint(bui.painter(), rr.shrink(2.0), Icon::Reset, if rresp.hovered() { t.text } else { t.text_dim });
+ if rresp.clicked() {
+ actions.push(("effects.reset".into(), json!({"clip": clip.0, "index": idx})));
+ }
+ app.auto.add(&format!("effectControls.effect.{}", e.effect), r, def.name);
+ if resp.clicked() && !fxresp.clicked() && !rresp.clicked() {
+ if open {
+ app.ui.collapsed_fx.push(key.clone());
+ } else {
+ app.ui.collapsed_fx.retain(|k| *k != key);
+ }
+ }
+ let mut save_preset = false;
+ let fx_id = e.effect.clone();
+ resp.context_menu(|ui| {
+ let sp = ui.button(tl!("Save Preset…"));
+ app.auto.add(&format!("effectControls.effect.{fx_id}.savePreset"), sp.rect, "Save Preset…");
+ if sp.clicked() {
+ save_preset = true;
+ ui.close();
+ }
+ if !def.intrinsic && ui.button(tl!("Clear")).clicked() {
+ actions.push(("effects.remove".into(), json!({"clip": clip.0, "index": idx})));
+ ui.close();
+ }
+ });
+ if save_preset {
+ crate::panels::presets::open_save(app, clip.0, vec![idx], def.name);
+ }
+ if !open {
+ continue;
+ }
+ if crate::panels::audio_fx_editor::has_editor(&e.effect) {
+ custom_setup_row(app, bui, body, clip, idx, &e.effect);
+ }
+ for pd in &def.params {
+ param_row(app, bui, body, clip, idx, e, None, pd, mt_now, &mut actions, &lane, &lx, it);
+ if app.ui.expanded_fx.contains(&graph_key(clip, idx, pd.id))
+ && let Some(param) = e.params.get(pd.id)
+ && param.is_animated()
+ && matches!(param.value, ParamValue::Float(_))
+ {
+ graph_rows(app, bui, body, clip, idx, None, pd, param, &lane, it, &mut actions);
+ }
+ }
+ if crate::panels::masks::maskable(e) {
+ crate::panels::masks::effect_rows(app, bui, body, clip, idx, e, mt_now, &mut actions, &lane, &lx, it);
}
- }
- if crate::panels::masks::maskable(e) {
- crate::panels::masks::effect_rows(app, bui, body, clip, idx, e, mt_now, &mut actions, &lane, &lx, &it);
}
}
});
diff --git a/crates/ui-egui/tests/clip_audio_ui.rs b/crates/ui-egui/tests/clip_audio_ui.rs
new file mode 100644
index 000000000..1e8dbc8a7
--- /dev/null
+++ b/crates/ui-egui/tests/clip_audio_ui.rs
@@ -0,0 +1,114 @@
+//! Audio of video clips (#223): a selected video clip shows the Volume, Channel Volume and Panner
+//! of the audio linked to it as well, as in Premiere.
+
+use std::sync::mpsc::{Sender, channel};
+
+use egui_kittest::Harness;
+use filmcraft_engine::Session;
+use filmcraft_project::{ClipId, TrackItem};
+use filmcraft_ui_egui::FilmcraftApp;
+use filmcraft_ui_egui::control::ControlRequest;
+use serde_json::{Value, json};
+
+struct Driver {
+ harness: Harness<'static, FilmcraftApp>,
+ tx: Sender<ControlRequest>,
+}
+
+/// The demo's first clip: its video on V1 and the audio linked to it on A1.
+struct Pair {
+ video: u64,
+ audio: u64,
+}
+
+impl Driver {
+ fn demo(panels: &[&str]) -> (Self, Pair) {
+ let mut session = Session::default();
+ session.execute("file.openDemoProject", json!({})).expect("demo project");
+ let (tx, rx) = channel();
+ let app = FilmcraftApp::new(session).with_control(rx);
+ let harness = Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).with_max_steps(10_000).build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx };
+ d.frames(4);
+ let seq = d.exec("sequence.inspect", json!({}));
+ let v = &seq["video"][0]["items"][0];
+ let a = seq["audio"][0]["items"].as_array().unwrap().iter().find(|a| a["link"] == v["link"]).expect("linked audio").clone();
+ let pair = Pair { video: v["clip"].as_u64().unwrap(), audio: a["clip"].as_u64().unwrap() };
+ for panel in panels {
+ d.ok("ui.panel.show", json!({"panel": panel}));
+ }
+ d.frames(3);
+ (d, pair)
+ }
+ fn frames(&mut self, n: usize) {
+ for _ in 0..n {
+ let ctx = self.harness.ctx.clone();
+ let mut raw = std::mem::take(self.harness.input_mut());
+ eframe::App::raw_input_hook(self.harness.state_mut(), &ctx, &mut raw);
+ *self.harness.input_mut() = raw;
+ self.harness.step();
+ }
+ }
+ fn call(&mut self, method: &str, params: Value) -> Value {
+ let (req, reply) = ControlRequest::new(method, params.clone());
+ self.tx.send(req).unwrap();
+ for _ in 0..600 {
+ self.frames(1);
+ if let Ok(v) = reply.try_recv() {
+ return v;
+ }
+ }
+ panic!("no reply to {method} {params}");
+ }
+ fn ok(&mut self, method: &str, params: Value) -> Value {
+ let r = self.call(method, params.clone());
+ assert_eq!(r["ok"], true, "{method} {params}: {r}");
+ r["result"].clone()
+ }
+ fn exec(&mut self, command: &str, params: Value) -> Value {
+ self.ok("engine.execute", json!({"command": command, "params": params}))
+ }
+ fn find(&mut self, id: &str) -> Option<[f64; 4]> {
+ self.frames(2);
+ let v = self.ok("ui.elements", json!({"prefix": id}));
+ let e = v.as_array().unwrap().iter().find(|e| e["id"] == id)?;
+ let r: Vec<f64> = e["rect"].as_array().unwrap().iter().map(|x| x.as_f64().unwrap()).collect();
+ Some([r[0], r[1], r[2], r[3]])
+ }
+ fn rect(&mut self, id: &str) -> [f64; 4] {
+ self.find(id).unwrap_or_else(|| panic!("no element {id}"))
+ }
+ fn click(&mut self, id: &str) {
+ self.rect(id);
+ self.ok("ui.click", json!({"id": id}));
+ self.frames(3);
+ }
+ fn item(&self, clip: u64) -> TrackItem {
+ self.harness.state().session.active_sequence().unwrap().find_item(ClipId(clip)).unwrap().1.clone()
+ }
+}
+
+#[test]
+fn effect_controls_show_the_audio_of_a_video_clip() {
+ let (mut d, pair) = Driver::demo(&["EffectControls"]);
+ d.exec("timeline.select", json!({"clips": [pair.video]}));
+ let motion = d.rect("effectControls.effect.motion");
+ let volume = d.rect("effectControls.effect.volume");
+ assert!(volume[1] > motion[1], "Audio comes after Video: {volume:?} {motion:?}");
+ d.rect("effectControls.effect.channel_volume");
+ d.rect("effectControls.effect.panner");
+
+ // the audio rows edit the audio clip
+ for fx in ["motion", "opacity", "time_remap"] {
+ d.click(&format!("effectControls.effect.{fx}"));
+ }
+ d.click("effectControls.volume.level.stopwatch");
+ assert!(d.item(pair.audio).effect("volume").unwrap().param("level").unwrap().is_animated());
+ assert!(d.item(pair.video).effect("volume").is_none());
+
+ // only the video selected: no audio
+ d.exec("sequence.linkedSelection", json!({"on": false}));
+ d.exec("timeline.select", json!({"clips": [pair.video]}));
+ assert!(d.find("effectControls.effect.volume").is_none());
+ d.rect("effectControls.effect.motion");
+}