Skip to content

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

#223: drag the clip volume line and its keyframes in the timeline

Oskarb4b4ea631787
diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs
index 807b9b654..70a18c30c 100644
--- a/crates/ui-egui/src/panels/timeline.rs
+++ b/crates/ui-egui/src/panels/timeline.rs
@@ -114,6 +114,8 @@ pub enum Drag {
clip: ClipId,
delta: Tick,
},
+ /// An audio clip's Volume line (see [`super::timeline_volume`]).
+ Volume(super::timeline_volume::LineDrag),
Stretch {
clip: ClipId,
edge: filmcraft_edit::Edge,
@@ -150,6 +152,8 @@ pub struct Row {
pub kind: TrackKind,
pub index: usize,
pub rect: Rect,
+ /// An audio track showing a track keyframe lane, which hides its clips' Volume lines.
+ pub lane: bool,
}
#[derive(Clone, Debug)]
@@ -315,14 +319,16 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
app.ui.timeline.v_scroll = app.ui.timeline.v_scroll.clamp(0.0, max_vs);
for (i, tr) in seq.video_tracks.iter().enumerate() {
let top = video_area.min.y + v_off + (nv - 1 - i) as f32 * vh - (max_vs - app.ui.timeline.v_scroll);
- rows.push(Row { track: tr.id, kind: TrackKind::Video, index: i, rect: Rect::from_min_max(pos2(content.min.x, top), pos2(content.max.x, top + vh)) });
+ let rect = Rect::from_min_max(pos2(content.min.x, top), pos2(content.max.x, top + vh));
+ rows.push(Row { track: tr.id, kind: TrackKind::Video, index: i, rect, lane: false });
}
let na = seq.audio_tracks.len();
let max_as = (na as f32 * ah - audio_area.height()).max(0.0);
app.ui.timeline.a_scroll = app.ui.timeline.a_scroll.clamp(0.0, max_as);
for (i, tr) in seq.audio_tracks.iter().enumerate() {
let top = audio_area.min.y + i as f32 * ah - app.ui.timeline.a_scroll;
- rows.push(Row { track: tr.id, kind: TrackKind::Audio, index: i, rect: Rect::from_min_max(pos2(content.min.x, top), pos2(content.max.x, top + ah)) });
+ let rect = Rect::from_min_max(pos2(content.min.x, top), pos2(content.max.x, top + ah));
+ rows.push(Row { track: tr.id, kind: TrackKind::Audio, index: i, rect, lane: app.ui.timeline.track_lanes.contains_key(&tr.id.0) });
}
let layout = Layout { content, ruler, rows: rows.clone(), pps, scroll, split_y };
app.tl.layout = Some(layout.clone());
@@ -363,8 +369,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
continue;
}
let p = painter.with_clip_rect(Rect::from_min_max(pos2(content.min.x, row.min.y), pos2(content.max.x, row.max.y)));
- // a track showing a track keyframe lane hides the clips' lines
- let volume_line = r.kind == TrackKind::Audio && !app.ui.timeline.track_lanes.contains_key(&r.track.0);
+ let volume_line = r.kind == TrackKind::Audio && !r.lane;
for it in &tr.items {
let (start, dur, moved_track) = previews.get(&it.id).copied().unwrap_or((it.start, it.duration, None));
if moved_track.is_some_and(|m| m != r.track) {
@@ -515,6 +520,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {
// ---- interaction
interact(app, ui, &seq, &layout, rect);
+ super::timeline_volume::interact(app, ui, &seq, &layout, aclip);
// track keyframes (drawn and edited on top of the clips)
super::timeline_automation::show(app, ui, &seq, &layout, aclip);
if cap_n > 0 {
@@ -1451,6 +1457,7 @@ pub fn hit_json(app: &FilmcraftApp, pos: Pos2, mods: egui::Modifiers) -> Value {
let grab = grab_at(seq, layout, pos, app.ui.tool, mods, app.session.prefs.trim.selection_tool_roll_ripple);
let kind = match grab {
Grab::Edge { kind, .. } => json!(kind.name()),
+ Grab::Volume { .. } => json!("volume"),
Grab::Other(_) => Value::Null,
};
match grab.hit() {
@@ -1728,6 +1735,8 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
let g = grab_at(seq, layout, p, tool, mods, roll_ripple);
let cur = match (tool, g) {
(_, Grab::Edge { .. }) => CursorIcon::ResizeColumn,
+ (_, Grab::Volume { .. }) if tool == Tool::Pen || mods.command => CursorIcon::Crosshair,
+ (_, Grab::Volume { .. }) => CursorIcon::ResizeVertical,
(Tool::Razor, Grab::Other(Hit::Clip { .. })) => CursorIcon::Crosshair,
(Tool::Slip | Tool::Slide, Grab::Other(Hit::Clip { .. })) => CursorIcon::ResizeHorizontal,
(Tool::Hand, _) => CursorIcon::Grab,
@@ -1761,7 +1770,13 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
}
};
let (p, t) = (pressed.pos, pressed.tick);
- let started = match (tool, pressed.grab) {
+ let adding = tool == Tool::Pen || mods.command;
+ // a plain click on a Volume line selects the clip, as anywhere else on it
+ let grab = match pressed.grab {
+ Grab::Volume { .. } if resp.clicked() && !adding => Grab::Other(pressed.grab.hit()),
+ g => g,
+ };
+ let started = match (tool, grab) {
(_, Grab::Other(Hit::Ruler)) => Some(Drag::Scrub),
(Tool::Hand, _) => Some(Drag::Pan { last: p }),
(Tool::Zoom, _) => {
@@ -1822,6 +1837,11 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
EdgeKind::Stretch => Drag::Stretch { clip, edge, delta: Tick::ZERO, from: t },
EdgeKind::Remix => Drag::Remix { clip, delta: Tick::ZERO, from: t },
}),
+ (_, Grab::Volume { clip, .. }) if resp.drag_started() => super::timeline_volume::start(seq, layout, clip, p).map(Drag::Volume),
+ (_, Grab::Volume { clip, .. }) => {
+ super::timeline_volume::add_keyframe(app, seq, layout, clip, p.x);
+ None
+ }
(Tool::Slip, Grab::Other(Hit::Clip { clip, .. })) => Some(Drag::Slip { clip, delta: Tick::ZERO }),
(Tool::Slide, Grab::Other(Hit::Clip { clip, .. })) => Some(Drag::Slide { clip, delta: Tick::ZERO }),
(_, Grab::Other(Hit::Clip { clip, track, .. })) => {
@@ -1937,6 +1957,7 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
let origin = ctx.input(|i| i.pointer.press_origin()).map(|o| layout.tick_at(o.x)).unwrap_or(t_here);
Some(Drag::Slide { clip, delta: rate.snap_nearest(t_here - origin) })
}
+ Drag::Volume(v) => Some(Drag::Volume(super::timeline_volume::drag(app, ui, seq, layout, v, p.y))),
Drag::Marquee { start } => {
let r = Rect::from_two_pos(start, p);
ui.painter().rect_filled(r, 0.0, Color32::from_white_alpha(18));
@@ -1947,7 +1968,7 @@ fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &
};
app.tl.drag = new;
// auto-scroll when dragging near the edges
- if !matches!(app.tl.drag, Some(Drag::Pan { .. }) | Some(Drag::ZoomBar { .. })) {
+ if !matches!(app.tl.drag, Some(Drag::Pan { .. }) | Some(Drag::ZoomBar { .. }) | Some(Drag::Volume(_))) {
let v = &mut app.ui.timeline;
if p.x > layout.content.max.x - 20.0 {
v.target_scroll += 6.0 / v.pps;
diff --git a/crates/ui-egui/src/panels/timeline_hit.rs b/crates/ui-egui/src/panels/timeline_hit.rs
index fa536c774..1716649fe 100644
--- a/crates/ui-egui/src/panels/timeline_hit.rs
+++ b/crates/ui-egui/src/panels/timeline_hit.rs
@@ -173,6 +173,12 @@ pub enum Grab {
edge: Edge,
kind: EdgeKind,
},
+ /// An audio clip's Volume line (Selection and Pen tools): a drag changes the level, a Pen or
+ /// Cmd/Ctrl click adds a keyframe.
+ Volume {
+ track: TrackId,
+ clip: ClipId,
+ },
/// Not an edge this tool trims: a clip body, a transition, an empty track, the ruler or
/// nothing. A clip's `edge` may still be set, for tools that do something else there (Razor,
/// Slip…).
@@ -184,6 +190,7 @@ impl Grab {
pub fn hit(self) -> Hit {
match self {
Grab::Edge { track, clip, edge, .. } => Hit::Clip { track, clip, edge: Some(edge) },
+ Grab::Volume { track, clip } => Hit::Clip { track, clip, edge: None },
Grab::Other(h) => h,
}
}
@@ -194,6 +201,12 @@ impl Grab {
/// Selection tool to choose Roll and Ripple trims without modifier key".
pub fn grab_at(seq: &Sequence, layout: &Layout, pos: Pos2, tool: Tool, mods: Modifiers, roll_ripple: bool) -> Grab {
let h = hit(seq, layout, pos);
+ if let Hit::Clip { track, clip, edge: None } = h
+ && matches!(tool, Tool::Selection | Tool::Pen)
+ && super::timeline_volume::on_line(seq, layout, clip, pos)
+ {
+ return Grab::Volume { track, clip };
+ }
let Hit::Clip { track, clip, edge: Some(edge) } = h else { return Grab::Other(h) };
let kind = match tool {
Tool::Selection => {
@@ -288,7 +301,7 @@ mod tests {
let layout = Layout {
content: row,
ruler: Rect::from_min_max(pos2(0.0, 0.0), pos2(2000.0, 40.0)),
- rows: vec![Row { track, kind: TrackKind::Video, index: 0, rect: row }],
+ rows: vec![Row { track, kind: TrackKind::Video, index: 0, rect: row, lane: false }],
pps: 100.0,
scroll: 0.0,
split_y: TOP + 60.0,
diff --git a/crates/ui-egui/src/panels/timeline_volume.rs b/crates/ui-egui/src/panels/timeline_volume.rs
index 50e666289..3b679a872 100644
--- a/crates/ui-egui/src/panels/timeline_volume.rs
+++ b/crates/ui-egui/src/panels/timeline_volume.rs
@@ -1,12 +1,25 @@
//! The Volume line on audio clips (#223): the clip's Volume level over time, with its keyframes,
-//! on the same scale as the track faders.
+//! on the same scale as the track faders. As in Premiere, drag the line up or down to change the
+//! level (with keyframes: the stretch between the two around the pointer), Cmd/Ctrl-click it or
+//! click it with the Pen tool to add a keyframe, drag keyframes, right-click one to delete it.
+//! Presses on the line go through the Timeline's own hit-testing ([`super::timeline_hit`]), so a
+//! right-click on it still opens the clip menu.
+//!
+//! Automation ids: `timeline.clip.<id>.volume` (a point on the line),
+//! `timeline.clip.<id>.volume.kf.<n>` (the keyframes) and `….kf.<n>.delete` (their menu).
-use egui::{Color32, Pos2, Rect, Stroke, pos2, vec2};
-use filmcraft_project::{Param, TrackItem};
+use egui::{Color32, CursorIcon, Pos2, Rect, Sense, Stroke, pos2, vec2};
+use filmcraft_project::mixer::{FADER_MAX_DB, FADER_MIN_DB};
+use filmcraft_project::{ClipId, Param, Sequence, TrackItem, TrackKind};
use filmcraft_time::Tick;
+use serde_json::{Value, json};
-use super::mixer::db_to_pos;
+use super::mixer::{db_to_pos, pos_to_db};
+use super::timeline::{Layout, Row};
+use super::timeline_hit::EDGE_PX;
+use crate::FilmcraftApp;
use crate::icons::{self, Icon};
+use crate::state::Tool;
const KEY_COL: Color32 = Color32::from_rgb(0xc8, 0xc8, 0xc8);
@@ -71,15 +84,217 @@ pub fn paint(p: &egui::Painter, body: Rect, it: &TrackItem) {
let pts = line(it, body, vis.min.x, vis.max.x);
p.add(egui::Shape::line(pts.iter().map(|q| *q + vec2(0.0, 1.0)).collect(), Stroke::new(1.0, Color32::BLACK)));
p.add(egui::Shape::line(pts, Stroke::new(1.0, Color32::WHITE)));
- for (_, c) in keys(it, body) {
+ for (_, c) in keys(it, body).into_iter().filter(|(_, c)| vis.expand(6.0).contains(*c)) {
icons::paint(&p, Rect::from_center_size(c, vec2(9.0, 9.0)), Icon::Keyframe, KEY_COL);
}
}
+/// A drag of a clip's Volume line, pressed at height `y` where the line was at `from` dB. `keys`
+/// are the keyframes on either side of that point, which move with it (none: the level is not
+/// animated). `last` is the level sent last: the first change starts the drag's undo step.
+#[derive(Clone, Debug)]
+pub struct LineDrag {
+ clip: ClipId,
+ from: f64,
+ y: f32,
+ keys: [Option<(Tick, f64)>; 2],
+ last: Option<f64>,
+}
+
+fn find<'a>(seq: &'a Sequence, layout: &'a Layout, clip: ClipId) -> Option<(&'a Row, &'a TrackItem)> {
+ let (tid, it) = seq.find_item(clip)?;
+ Some((layout.rows.iter().find(|r| r.track == tid)?, it))
+}
+
+fn body(layout: &Layout, r: &Row, it: &TrackItem) -> Rect {
+ Rect::from_min_max(pos2(layout.x_of(it.start), r.rect.min.y + 1.0), pos2(layout.x_of(it.end()), r.rect.max.y - 1.0))
+}
+
+/// Whether `pos` is on `clip`'s Volume line, within 4 px.
+pub fn on_line(seq: &Sequence, layout: &Layout, clip: ClipId, pos: Pos2) -> bool {
+ let Some((r, it)) = find(seq, layout, clip) else { return false };
+ if r.kind != TrackKind::Audio || r.lane || seq.track(r.track).is_none_or(|t| t.locked) {
+ return false;
+ }
+ let body = body(layout, r, it);
+ band(body).height() >= 6.0 && (pos.y - y_of(body, level_at(it, t_at(it, body, pos.x)))).abs() <= 4.0
+}
+
+/// A press on `clip`'s line at `at` that became a drag.
+pub fn start(seq: &Sequence, layout: &Layout, clip: ClipId, at: Pos2) -> Option<LineDrag> {
+ let (r, it) = find(seq, layout, clip)?;
+ let t = t_at(it, body(layout, r, it), at.x);
+ let m = it.source_time_at(t);
+ let keys = level(it).filter(|p| p.is_animated()).map_or([None, None], |p| {
+ let i = p.keyframes.partition_point(|k| k.time <= m);
+ let kv = |j: Option<usize>| j.and_then(|j| p.keyframes.get(j)).map(|k| (k.time, k.value.as_f64().unwrap_or(0.0)));
+ [kv(i.checked_sub(1)), kv(Some(i))]
+ });
+ Some(LineDrag { clip, from: level_at(it, t), y: at.y, keys, last: None })
+}
+
+/// Follow the pointer, now at height `y`. The clip changes as the line moves, so it is heard.
+pub fn drag(app: &mut FilmcraftApp, ui: &egui::Ui, seq: &Sequence, layout: &Layout, mut d: LineDrag, y: f32) -> LineDrag {
+ let Some((r, it)) = find(seq, layout, d.clip) else { return d };
+ let db = pos_to_db(db_to_pos(d.from) + (d.y - y) / band(body(layout, r, it)).height().max(1.0));
+ tip(ui, db);
+ if d.last == Some(db) {
+ return d;
+ }
+ let begin = d.last.is_none();
+ let mut acts = Vec::new();
+ if d.keys.iter().all(Option::is_none) {
+ acts.push(("effects.setParam", json!({"clip": d.clip.0, "effect": "volume", "param": "level", "value": db, "merge": true, "begin": begin})));
+ }
+ for (n, (m, v)) in d.keys.iter().flatten().enumerate() {
+ let v = (v + db - d.from).clamp(FADER_MIN_DB, FADER_MAX_DB);
+ let p = json!({"clip": d.clip.0, "effect": "volume", "param": "level", "mediaTime": m.0, "value": v, "merge": true, "begin": begin && n == 0});
+ acts.push(("effects.setKeyframe", p));
+ }
+ run(app, acts);
+ d.last = Some(db);
+ d
+}
+
+/// The Pen tool or a Cmd/Ctrl-click on `clip`'s line at `x`: a keyframe there.
+pub fn add_keyframe(app: &mut FilmcraftApp, seq: &Sequence, layout: &Layout, clip: ClipId, x: f32) {
+ let Some((r, it)) = find(seq, layout, clip) else { return };
+ let t = seq.settings.frame_rate.snap_nearest(t_at(it, body(layout, r, it), x));
+ run(app, vec![("effects.addKeyframe", json!({"clip": clip.0, "effect": "volume", "param": "level", "time": t.0}))]);
+}
+
+fn run(app: &mut FilmcraftApp, acts: Vec<(&str, Value)>) {
+ for (id, p) in acts {
+ if let Err(e) = app.session.execute(id, p) {
+ app.ui.status = e.to_string();
+ }
+ }
+}
+
+fn tip(ui: &egui::Ui, db: f64) {
+ egui::Tooltip::always_open(ui.ctx().clone(), ui.layer_id(), egui::Id::new("tl-volume-tip"), egui::PopupAnchor::Pointer).show(|ui| {
+ ui.label(format!("{db:.2} dB"));
+ });
+}
+
+/// A keyframe being dragged: `index` of `clip`, grabbed `grab` away from its centre.
+#[derive(Clone, Copy)]
+struct KeyDrag {
+ clip: ClipId,
+ index: usize,
+ grab: egui::Vec2,
+ begun: bool,
+}
+
+fn key_drag_id() -> egui::Id {
+ egui::Id::new("tl-volume-key-drag")
+}
+
+/// The keyframes on the lines of the audio clips in view: drag one in time and level, right-click
+/// it to delete it. Runs after the timeline's own interaction, so they are above the clip.
+pub fn interact(app: &mut FilmcraftApp, ui: &mut egui::Ui, seq: &Sequence, layout: &Layout, aclip: Rect) {
+ let held: Option<KeyDrag> = ui.data(|d| d.get_temp(key_drag_id()));
+ if held.is_none() && (app.tl.drag.is_some() || !matches!(app.ui.tool, Tool::Selection | Tool::Pen)) {
+ return;
+ }
+ let area = aclip.intersect(layout.content);
+ let pointer = ui.input(|i| i.pointer.interact_pos());
+ let rate = seq.settings.frame_rate;
+ let mut next = held;
+ let mut acts: Vec<(&str, Value)> = Vec::new();
+ for r in layout.rows.iter().filter(|r| r.kind == TrackKind::Audio && !r.lane) {
+ let Some(tr) = seq.track(r.track).filter(|t| !t.locked) else { continue };
+ let row = r.rect.intersect(area);
+ if row.height() <= 0.0 {
+ continue;
+ }
+ for it in &tr.items {
+ let body = body(layout, r, it);
+ let vis = body.intersect(row);
+ if vis.width() <= 0.0 || band(body).height() < 6.0 {
+ continue;
+ }
+ // a point on the line for agents, away from the trim zones at the edges
+ let edge = EDGE_PX.min(body.width() / 3.0);
+ let (x0, x1) = (vis.min.x.max(body.min.x + edge), vis.max.x.min(body.max.x - edge));
+ if x1 > x0 {
+ let xm = (x0 + x1) / 2.0;
+ let c = pos2(xm, y_of(body, level_at(it, t_at(it, body, xm))));
+ app.auto.add(&format!("timeline.clip.{}.volume", it.id.0), Rect::from_center_size(c, vec2(12.0, 8.0)), "Volume");
+ }
+ let ks = keys(it, body);
+ for (i, &(time, c)) in ks.iter().enumerate() {
+ if !vis.expand2(vec2(5.0, 0.0)).contains(c) {
+ continue;
+ }
+ let kr = Rect::from_center_size(c, vec2(11.0, 11.0));
+ let resp = ui.interact(kr, egui::Id::new(("tl-volume-kf", it.id.0, i)), Sense::click_and_drag());
+ app.auto.add(&format!("timeline.clip.{}.volume.kf.{i}", it.id.0), kr, "Volume keyframe");
+ let mine = held.filter(|h| h.clip == it.id && h.index == i);
+ if resp.hovered() || mine.is_some() {
+ icons::paint(&ui.painter().with_clip_rect(area), Rect::from_center_size(c, vec2(9.0, 9.0)), Icon::Keyframe, Color32::WHITE);
+ ui.ctx().set_cursor_icon(CursorIcon::Move);
+ }
+ if resp.drag_started()
+ && let Some(p) = pointer
+ {
+ next = Some(KeyDrag { clip: it.id, index: i, grab: p - c, begun: false });
+ }
+ if let (Some(h), Some(p)) = (mine, pointer)
+ && resp.dragged()
+ {
+ let q = p - h.grab;
+ // on a frame, at least a frame away from the keyframes on either side
+ let fd = rate.frame_duration();
+ let now = timeline_time(it, time);
+ let (mut lo, mut hi) = (it.start, Tick(it.end().0.saturating_sub(fd.0)));
+ for j in [i.checked_sub(1), i.checked_add(1)].into_iter().flatten() {
+ if let Some(&(m, _)) = ks.get(j) {
+ let n = timeline_time(it, m);
+ if n < now {
+ lo = lo.max(Tick(n.0.saturating_add(fd.0)));
+ } else {
+ hi = hi.min(Tick(n.0.saturating_sub(fd.0)));
+ }
+ }
+ }
+ let t = if lo <= hi { rate.snap_nearest(t_at(it, body, q.x)).max(lo).min(hi) } else { now };
+ let db = pos_to_db((band(body).max.y - q.y) / band(body).height());
+ if resp.drag_delta() != egui::Vec2::ZERO {
+ let to = it.moving_source_time_at(t);
+ let p = json!({"clip": h.clip.0, "effect": "volume", "param": "level", "mediaTime": time.0, "to": to.0, "value": db, "merge": true, "begin": !h.begun});
+ acts.push(("effects.moveKeyframe", p));
+ next = Some(KeyDrag { begun: true, ..h });
+ }
+ tip(ui, db);
+ }
+ resp.context_menu(|ui| {
+ let b = ui.button(tl!("Delete"));
+ app.auto.add(&format!("timeline.clip.{}.volume.kf.{i}.delete", it.id.0), b.rect, "Delete");
+ if b.clicked() {
+ acts.push(("effects.deleteKeyframe", json!({"clip": it.id.0, "effect": "volume", "param": "level", "mediaTime": time.0})));
+ ui.close();
+ }
+ });
+ }
+ }
+ }
+ if !ui.input(|i| i.pointer.any_down()) {
+ next = None;
+ }
+ match next {
+ Some(h) => ui.data_mut(|d| {
+ d.insert_temp(key_drag_id(), h);
+ }),
+ None => ui.data_mut(|d| d.remove::<KeyDrag>(key_drag_id())),
+ }
+ run(app, acts);
+}
+
#[cfg(test)]
mod tests {
use super::*;
- use filmcraft_project::{ClipId, ItemId, Label};
+ use filmcraft_project::{ItemId, Label};
fn clip(speed: f64, reverse: bool) -> TrackItem {
TrackItem {
@@ -122,6 +337,18 @@ mod tests {
}
}
+ #[test]
+ fn damaged_keyframe_times_do_not_panic() {
+ for (speed, reverse) in [(1.0, false), (1e-12, true), (f64::NAN, false), (-3.0, true)] {
+ let mut it = clip(speed, reverse);
+ let p = it.effect_mut("volume").and_then(|e| e.param_mut("level")).unwrap();
+ p.put_keyframe(Tick(i64::MIN), filmcraft_project::ParamValue::Float(f64::NAN));
+ p.put_keyframe(Tick(i64::MAX), filmcraft_project::ParamValue::Float(1e300));
+ let body = Rect::from_min_max(pos2(0.0, 0.0), pos2(400.0, 80.0));
+ assert_eq!(keys(&it, body).len(), 2);
+ }
+ }
+
#[test]
fn the_line_follows_the_level() {
let mut it = clip(1.0, false);
diff --git a/crates/ui-egui/tests/clip_audio_ui.rs b/crates/ui-egui/tests/clip_audio_ui.rs
index 6258905ee..3ca87a33b 100644
--- a/crates/ui-egui/tests/clip_audio_ui.rs
+++ b/crates/ui-egui/tests/clip_audio_ui.rs
@@ -1,5 +1,8 @@
//! 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.
+//! of the audio linked to it as well, as in Premiere, and the Volume line on audio clips in the
+//! timeline can be dragged and keyframed.
+//!
+//! With `FILMCRAFT_UI_SHOTS=<dir>` the tests also render the UI with wgpu and write PNGs there.
use std::sync::mpsc::{Sender, channel};
@@ -13,6 +16,7 @@ use serde_json::{Value, json};
struct Driver {
harness: Harness<'static, FilmcraftApp>,
tx: Sender<ControlRequest>,
+ shots: Option<std::path::PathBuf>,
}
/// The demo's first clip: its video on V1 and the audio linked to it on A1.
@@ -27,8 +31,13 @@ impl Driver {
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 };
+ let shots = std::env::var_os("FILMCRAFT_UI_SHOTS").map(std::path::PathBuf::from);
+ let mut b = Harness::builder().with_size(egui::vec2(1600.0, 1100.0)).with_max_steps(10_000);
+ if shots.is_some() {
+ b = b.wgpu().with_pixels_per_point(1.0);
+ }
+ let harness = b.build_eframe(move |_cc| app);
+ let mut d = Driver { harness, tx, shots };
d.frames(4);
let seq = d.exec("sequence.inspect", json!({}));
let v = &seq["video"][0]["items"][0];
@@ -86,6 +95,27 @@ impl Driver {
fn item(&self, clip: u64) -> TrackItem {
self.harness.state().session.active_sequence().unwrap().find_item(ClipId(clip)).unwrap().1.clone()
}
+ /// The clip's Volume level: its value and its keyframes (media time, dB).
+ fn level(&self, clip: u64) -> (f64, Vec<(i64, f64)>) {
+ let it = self.item(clip);
+ let p = it.effect("volume").unwrap().param("level").unwrap().clone();
+ (p.value.as_f64().unwrap(), p.keyframes.iter().map(|k| (k.time.0, k.value.as_f64().unwrap())).collect())
+ }
+ fn drag(&mut self, from: (f64, f64), by: (f64, f64)) {
+ self.ok("ui.drag", json!({"from": {"x": from.0, "y": from.1}, "to": {"x": from.0 + by.0, "y": from.1 + by.1}, "steps": 6}));
+ self.frames(3);
+ }
+ fn shot(&mut self, name: &str) {
+ let Some(dir) = self.shots.clone() else { return };
+ self.frames(10);
+ let img = self.harness.render().expect("wgpu render");
+ std::fs::create_dir_all(&dir).unwrap();
+ img.save(dir.join(format!("{name}.png"))).unwrap();
+ }
+}
+
+fn centre(r: [f64; 4]) -> (f64, f64) {
+ (r[0] + r[2] / 2.0, r[1] + r[3] / 2.0)
}
#[test]
@@ -128,3 +158,79 @@ fn properties_show_the_audio_of_a_video_clip() {
d.rect("properties.volume.level.addKeyframe");
assert!(d.find("properties.motion.scale.addKeyframe").is_none());
}
+
+#[test]
+fn dragging_the_volume_line_changes_the_level() {
+ let (mut d, pair) = Driver::demo(&[]);
+ let start = d.item(pair.audio).start;
+ let (before, _) = d.level(pair.audio);
+ d.shot("volume-line");
+ let line = d.rect(&format!("timeline.clip.{}.volume", pair.audio));
+ d.drag(centre(line), (0.0, -12.0));
+ let (after, keys) = d.level(pair.audio);
+ assert!(after > before + 1.0, "{before} dB → {after} dB");
+ assert!(keys.is_empty());
+ assert_eq!(d.item(pair.audio).start, start, "the clip did not move");
+ let moved = d.rect(&format!("timeline.clip.{}.volume", pair.audio));
+ assert!(moved[1] < line[1] - 8.0, "the line went up with the pointer: {line:?} → {moved:?}");
+ d.shot("volume-line-dragged");
+ d.exec("edit.undo", json!({}));
+ assert_eq!(d.level(pair.audio).0, before, "the drag was one undo step");
+}
+
+/// The line belongs to the clip: a click on it selects the clip and a right-click opens the clip
+/// menu, only a drag (or the Pen tool) edits the level.
+#[test]
+fn clicks_on_the_volume_line_still_reach_the_clip() {
+ let (mut d, pair) = Driver::demo(&[]);
+ let (x, y) = centre(d.rect(&format!("timeline.clip.{}.volume", pair.audio)));
+ assert_eq!(d.ok("ui.timeline.hit", json!({"x": x, "y": y}))["kind"], "volume");
+ d.ok("ui.click", json!({"x": x, "y": y}));
+ d.frames(3);
+ assert!(d.harness.state().session.state.selection.contains(&ClipId(pair.audio)));
+ d.ok("ui.click", json!({"x": x, "y": y, "button": "right"}));
+ d.frames(3);
+ d.rect("timeline.clipMenu.clip.link");
+ assert!(d.level(pair.audio).1.is_empty());
+}
+
+#[test]
+fn volume_keyframes_on_the_timeline() {
+ let (mut d, pair) = Driver::demo(&[]);
+ let id = format!("timeline.clip.{}.volume", pair.audio);
+ let clip = d.rect(&format!("timeline.clip.{}", pair.audio));
+ let (_, y) = centre(d.rect(&id));
+ // the Pen tool adds keyframes on the line
+ d.ok("ui.set", json!({"tool": "Pen"}));
+ for f in [0.3, 0.7] {
+ d.ok("ui.click", json!({"x": clip[0] + clip[2] * f, "y": y}));
+ d.frames(3);
+ }
+ let (_, keys) = d.level(pair.audio);
+ assert_eq!(keys.len(), 2, "{keys:?}");
+ d.ok("ui.set", json!({"tool": "Selection"}));
+
+ // the line between them takes both down
+ d.drag((clip[0] + clip[2] * 0.5, y), (0.0, 10.0));
+ let (_, low) = d.level(pair.audio);
+ assert_eq!(low.iter().map(|k| k.0).collect::<Vec<_>>(), keys.iter().map(|k| k.0).collect::<Vec<_>>());
+ assert!(low[0].1 < keys[0].1 - 1.0 && (low[0].1 - low[1].1).abs() < 1e-9, "{keys:?} → {low:?}");
+ d.exec("edit.undo", json!({}));
+ assert_eq!(d.level(pair.audio).1, keys);
+
+ // a keyframe moves in time and level
+ let k = d.rect(&format!("{id}.kf.1"));
+ d.drag(centre(k), (40.0, -10.0));
+ let (_, moved) = d.level(pair.audio);
+ assert_eq!(moved[0], keys[0]);
+ assert!(moved[1].0 > keys[1].0 && moved[1].1 > keys[1].1, "{keys:?} → {moved:?}");
+ d.shot("volume-keyframes");
+ d.exec("edit.undo", json!({}));
+ assert_eq!(d.level(pair.audio).1, keys, "the keyframe drag was one undo step");
+
+ // right-click ▸ Delete
+ d.ok("ui.click", json!({"id": format!("{id}.kf.0"), "button": "right"}));
+ d.frames(3);
+ d.click(&format!("{id}.kf.0.delete"));
+ assert_eq!(d.level(pair.audio).1, keys[1..]);
+}