forge
Explore
Log in

Don't you dare go Hollow

Two lanes, waveforms, group-scoped selection

Browse files at this commit

591afa3f8af7e9fe9cf91f7c81138db2ec0a89e7Ahmet Kaan GümüşParent: 0f5e259
  • feat
    • two lanes, waveforms, group-scoped selection
Show full message
✨ feat(timeline): two lanes, waveforms, group-scoped selection

V1 and A1 get a fixed header column and a bed of their own, both offset
by the same constants the ruler now is, so one x maps to one moment in
all three rows. Clips are placed at their own start rather than queued
edge to edge: a lift leaves a hole and the bare bed showing through it
is how a gap looks.

Audio clips paint their source's min/max envelope, cached per file and
normalised to its own loudest sample -- the fixtures peak near an eighth
of full scale and would otherwise draw as a flat line. A click marks the
whole group and acts on the half it landed on, which is what makes a
detached half separately deletable.

Two actions the lane model owed a key: Regroup rejoins what a Cut split,
Lift removes one half and leaves the gap. Both auto-list in the
keybindings overlay and are rebindable like the rest.

`PlaybackSession::lane_clips` is the one engine addition: link ids and
source ranges are what a two-lane front-end draws with, and no existing
accessor carries either.
crates/app/src/keymap.rsmodified+17 -3
@@ -44,7 +44,9 @@ pub enum ActionId {
44 Copy,44 Copy,
45 Paste,45 Paste,
46 Cut,46 Cut,
47+ Regroup,
47 Delete,48 Delete,
49+ Lift,
48 Undo,50 Undo,
49 ToggleMute,51 ToggleMute,
50 VolumeUp,52 VolumeUp,
@@ -55,14 +57,16 @@ pub enum ActionId {
55 impl ActionId {57 impl ActionId {
56 /// Display order everywhere -- the editor lists them in it and58 /// Display order everywhere -- the editor lists them in it and
57 /// [`Keymap::defaults`] binds them in it.59 /// [`Keymap::defaults`] binds them in it.
58- pub const ALL: [ActionId; 12] = [60+ pub const ALL: [ActionId; 14] = [
59 ActionId::Play,61 ActionId::Play,
60 ActionId::Export,62 ActionId::Export,
61 ActionId::Save,63 ActionId::Save,
62 ActionId::Copy,64 ActionId::Copy,
63 ActionId::Paste,65 ActionId::Paste,
64 ActionId::Cut,66 ActionId::Cut,
67+ ActionId::Regroup,
65 ActionId::Delete,68 ActionId::Delete,
69+ ActionId::Lift,
66 ActionId::Undo,70 ActionId::Undo,
67 ActionId::ToggleMute,71 ActionId::ToggleMute,
68 ActionId::VolumeUp,72 ActionId::VolumeUp,
@@ -79,7 +83,9 @@ impl ActionId {
79 ActionId::Copy => "Copy",83 ActionId::Copy => "Copy",
80 ActionId::Paste => "Paste",84 ActionId::Paste => "Paste",
81 ActionId::Cut => "Cut",85 ActionId::Cut => "Cut",
86+ ActionId::Regroup => "Regroup",
82 ActionId::Delete => "Delete",87 ActionId::Delete => "Delete",
88+ ActionId::Lift => "Lift (leave a gap)",
83 ActionId::Undo => "Undo",89 ActionId::Undo => "Undo",
84 ActionId::ToggleMute => "Mute / Unmute",90 ActionId::ToggleMute => "Mute / Unmute",
85 ActionId::VolumeUp => "Volume up",91 ActionId::VolumeUp => "Volume up",
@@ -98,7 +104,9 @@ impl ActionId {
98 ActionId::Copy => "copy",104 ActionId::Copy => "copy",
99 ActionId::Paste => "paste",105 ActionId::Paste => "paste",
100 ActionId::Cut => "cut",106 ActionId::Cut => "cut",
107+ ActionId::Regroup => "regroup",
101 ActionId::Delete => "delete",108 ActionId::Delete => "delete",
109+ ActionId::Lift => "lift",
102 ActionId::Undo => "undo",110 ActionId::Undo => "undo",
103 ActionId::ToggleMute => "toggle-mute",111 ActionId::ToggleMute => "toggle-mute",
104 ActionId::VolumeUp => "volume-up",112 ActionId::VolumeUp => "volume-up",
@@ -207,8 +215,12 @@ impl Keymap {
207 b(ActionId::Copy, "c", true),215 b(ActionId::Copy, "c", true),
208 b(ActionId::Paste, "v", true),216 b(ActionId::Paste, "v", true),
209 b(ActionId::Cut, "c", false),217 b(ActionId::Cut, "c", false),
218+ // The two lane keys, on the letters they are named after: both
219+ // were free, and neither is next to a key that edits.
220+ b(ActionId::Regroup, "g", false),
210 b(ActionId::Delete, "x", false),221 b(ActionId::Delete, "x", false),
211 b(ActionId::Delete, "delete", false),222 b(ActionId::Delete, "delete", false),
223+ b(ActionId::Lift, "l", false),
212 b(ActionId::Undo, "z", false),224 b(ActionId::Undo, "z", false),
213 b(ActionId::Undo, "z", true),225 b(ActionId::Undo, "z", true),
214 b(ActionId::ToggleMute, "m", false),226 b(ActionId::ToggleMute, "m", false),
@@ -443,15 +455,17 @@ mod tests {
443 #[test]455 #[test]
444 fn every_default_stroke_reaches_its_action() {456 fn every_default_stroke_reaches_its_action() {
445 let k = Keymap::defaults();457 let k = Keymap::defaults();
446- assert_eq!(k.entries().len(), 14);458+ assert_eq!(k.entries().len(), 16);
447 assert_eq!(k.lookup("space", false), Some(ActionId::Play));459 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
448 assert_eq!(k.lookup("e", false), Some(ActionId::Export));460 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
449 assert_eq!(k.lookup("s", true), Some(ActionId::Save));461 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
450 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));462 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));
451 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));463 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
452 assert_eq!(k.lookup("c", false), Some(ActionId::Cut));464 assert_eq!(k.lookup("c", false), Some(ActionId::Cut));
465+ assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));
453 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));466 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));
454 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));467 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
468+ assert_eq!(k.lookup("l", false), Some(ActionId::Lift));
455 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));469 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
456 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));470 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
457 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));471 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));
@@ -588,7 +602,7 @@ mod tests {
588 );602 );
589 // The label is the editor's column, and never the file's word for it.603 // The label is the editor's column, and never the file's word for it.
590 assert_eq!(ActionId::CancelExport.label(), "Cancel export");604 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
591- assert_eq!(ActionId::ALL.len(), 12);605+ assert_eq!(ActionId::ALL.len(), 14);
592 }606 }
593 607
594 #[test]608 #[test]
crates/app/src/main.rsmodified+590 -52
@@ -3,18 +3,20 @@ mod keymap;
3 use keymap::{ActionId, Keymap};3 use keymap::{ActionId, Keymap};
4 4
5 use std::cell::Cell;5 use std::cell::Cell;
6+use std::collections::HashMap;
6 use std::path::PathBuf;7 use std::path::PathBuf;
7 use std::rc::Rc;8 use std::rc::Rc;
8 use std::sync::Arc;9 use std::sync::Arc;
9 use std::time::{Duration, Instant};10 use std::time::{Duration, Instant};
10 11
11 use engine::export::ExportSettings;12 use engine::export::ExportSettings;
13+use engine::project::Lane;
12 use engine::{Clip, ExportHandle, Frame, PlaybackSession};14 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
13 use gpui::{15 use gpui::{
14 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,16 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,
15- MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage,17+ MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,
16- SharedString, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point,18+ RenderImage, SharedString, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div,
17- prelude::*, px, relative, rgb, rgba, size,19+ img, point, prelude::*, px, relative, rgb, rgba, size,
18 };20 };
19 21
20 /// Editor chrome: three grays and one accent, all darker than the picture so the22 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -48,6 +50,25 @@ const HEADER_H: f32 = 32.;
48 // off the bottom.50 // off the bottom.
49 const PANEL_H: f32 = 220.;51 const PANEL_H: f32 = 220.;
50 const LANE_H: f32 = 48.;52 const LANE_H: f32 = 48.;
53+/// The lane header column: wide enough for `V1`/`A1` and fixed, so both lanes
54+/// and the ruler above them start at the same pixel and are the same width --
55+/// one x-to-time mapping for the whole timeline. `HEADER_GAP` is part of that
56+/// offset and is therefore shared by all three rows.
57+const HEADER_W: f32 = 40.;
58+const HEADER_GAP: f32 = 4.;
59+/// The label row inside a clip; a waveform paints under it, never through it.
60+const LABEL_H: f32 = 15.;
61+/// A clip narrower than this shows no name: two characters and an ellipsis say
62+/// nothing that the tint has not already said, and cost the picture a smear.
63+const LABEL_MIN_W: f32 = 36.;
64+/// Peak buckets per second of source. Fixed and modest on purpose: `peaks`
65+/// allocates one bucket per window, so a rate taken from anything the user can
66+/// influence is an allocation bomb -- and 40 is already finer than the pixels a
67+/// clip is ever given.
68+const WAVE_BPS: u32 = 40;
69+/// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
70+/// and a path with a point per pixel is a path per repaint.
71+const WAVE_COL: f32 = 2.;
51 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px72 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
52 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.73 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.
53 const HIT_MIN: f32 = 24.;74 const HIT_MIN: f32 = 24.;
@@ -155,9 +176,15 @@ struct Player {
155 /// The ruler's own box, recorded at prepaint: a mouse listener is handed176 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
156 /// the window position and nothing else.177 /// the window position and nothing else.
157 ruler: Rc<Cell<Bounds<Pixels>>>,178 ruler: Rc<Cell<Bounds<Pixels>>>,
158- /// Which clip the edit keys act on. Indices move under every edit, so this179+ /// Which clip the edit keys act on: the lane it is in and its index there.
159- /// is cleared by all of them.180+ /// The *clicked* half, not the group -- a group is what gets marked on
160- selected: Option<usize>,181+ /// screen, but Lift has to know which half it was aimed at. Indices move
182+ /// under every edit, so this is cleared by all of them.
183+ selected: Option<(Lane, usize)>,
184+ /// Peaks per source file, taken once and kept. `None` is a source with no
185+ /// audio track, which is an answer and not a miss: it must not be asked
186+ /// again every repaint.
187+ waves: HashMap<PathBuf, Option<Arc<Vec<(f32, f32)>>>>,
161 /// The copied clip. Frame ranges only, so it survives the clip it was taken188 /// The copied clip. Frame ranges only, so it survives the clip it was taken
162 /// from being deleted -- and it outlives the selection.189 /// from being deleted -- and it outlives the selection.
163 clipboard: Option<Clip>,190 clipboard: Option<Clip>,
@@ -321,14 +348,43 @@ impl Player {
321 cx.notify();348 cx.notify();
322 }349 }
323 350
324- /// Drops the selected clip. The engine reseeks itself, so all this owes is351+ /// Rejoins whatever meets under the playhead and puts it back in one group
325- /// the flag reset.352+ /// -- the inverse of [`Player::cut`], and metadata only like it. The engine
353+ /// decides what is joinable; a refusal is worded here, because `false` is
354+ /// all it says and a key that looks broken is worse than one that explains
355+ /// itself.
356+ fn regroup(&mut self, cx: &mut Context<Self>) {
357+ if self.exporting().is_some() {
358+ return;
359+ }
360+ if let Some(session) = &mut self.session {
361+ if session.regroup_at(session.now()) {
362+ self.selected = None;
363+ } else {
364+ self.notice = Some(
365+ "NOTHING TO REGROUP — put the playhead where two clips meet, on frames that were cut apart"
366+ .into(),
367+ );
368+ }
369+ }
370+ cx.notify();
371+ }
372+
373+ /// Drops the selected clip and closes the hole: a whole take goes, both
374+ /// lanes of it, and everything after it moves up. A half with no take under
375+ /// it in the video lane -- what a lift leaves behind -- has nothing to
376+ /// ripple, so that one is lifted instead. The engine reseeks itself, so all
377+ /// this owes is the flag reset.
326 fn delete_selected(&mut self, cx: &mut Context<Self>) {378 fn delete_selected(&mut self, cx: &mut Context<Self>) {
327 if self.exporting().is_some() {379 if self.exporting().is_some() {
328 return;380 return;
329 }381 }
330 let deleted = match (&mut self.session, self.selected.take()) {382 let deleted = match (&mut self.session, self.selected.take()) {
331- (Some(session), Some(i)) => session.delete_clip(i),383+ (Some(session), Some((Lane::Video, idx))) => session.delete_clip(idx),
384+ (Some(session), Some((Lane::Audio, idx))) => match video_half(session, idx) {
385+ Some(video) => session.delete_clip(video),
386+ None => session.lift_clip(Lane::Audio, idx),
387+ },
332 _ => false,388 _ => false,
333 };389 };
334 if deleted {390 if deleted {
@@ -337,14 +393,77 @@ impl Player {
337 cx.notify();393 cx.notify();
338 }394 }
339 395
396+ /// Lifts the selected half out and leaves the hole: black picture there if
397+ /// it was the video lane, silence if it was the audio one, and nothing else
398+ /// moves. What Delete is not.
399+ fn lift_selected(&mut self, cx: &mut Context<Self>) {
400+ if self.exporting().is_some() {
401+ return;
402+ }
403+ match (&mut self.session, self.selected.take()) {
404+ (Some(session), Some((lane, idx))) => {
405+ if session.lift_clip(lane, idx) {
406+ self.reset_after_reseek();
407+ } else {
408+ self.notice = Some("NOTHING LIFTED — the timeline cannot be emptied".into());
409+ }
410+ }
411+ (Some(_), None) => {
412+ self.notice = Some("NOTHING LIFTED — click the half to remove first".into())
413+ }
414+ (None, _) => {}
415+ }
416+ cx.notify();
417+ }
418+
340 /// Copies the selected clip. Nothing on screen changes, so no notify.419 /// Copies the selected clip. Nothing on screen changes, so no notify.
341 fn copy_selected(&mut self) {420 fn copy_selected(&mut self) {
342 let session = self.session.as_ref();421 let session = self.session.as_ref();
343- if let Some(clip) = self.selected.and_then(|i| session?.clip_at(i)) {422+ // Out of the lane it was clicked in: the audio half of a group is a
423+ // different clip from the video one, and copying the wrong lane's
424+ // frames is a paste of the wrong thing.
425+ if let Some(clip) = self
426+ .selected
427+ .and_then(|(lane, idx)| session?.lane_clips(lane).get(idx).copied())
428+ {
344 self.clipboard = Some(clip);429 self.clipboard = Some(clip);
345 }430 }
346 }431 }
347 432
433+ /// Fills the peak cache for every source that has arrived since the last
434+ /// repaint. One call from the render rather than three at the doors,
435+ /// because argv, an import and a project load are all doors and only this
436+ /// one is guaranteed to run after each of them.
437+ ///
438+ /// ponytail: the decode is synchronous, so the first repaint after a long
439+ /// file arrives waits on it -- ~0.3 s for ten minutes at the decoder's
440+ /// ~1700x realtime. Upgrade path is `cx.background_executor().spawn` with
441+ /// the peaks posted back, the way the file chooser already runs off-thread.
442+ fn cache_waves(&mut self) {
443+ let Some(session) = &self.session else {
444+ return;
445+ };
446+ let sources: Vec<PathBuf> = session
447+ .sources()
448+ .iter()
449+ .filter(|path| !self.waves.contains_key(*path))
450+ .cloned()
451+ .collect();
452+ for path in sources {
453+ let peaks = engine::waveform::peaks(&path, WAVE_BPS)
454+ .ok()
455+ .flatten()
456+ .map(|peaks| Arc::new(normalise(peaks)));
457+ self.waves.insert(path, peaks);
458+ }
459+ }
460+
461+ /// The group id of the clicked clip, which is what marks the other half.
462+ fn selected_link(&self) -> Option<u32> {
463+ let (lane, idx) = self.selected?;
464+ self.session.as_ref()?.lane_clips(lane).get(idx)?.link
465+ }
466+
348 /// Drops the copied clip in at the playhead. The engine reseeks itself, so467 /// Drops the copied clip in at the playhead. The engine reseeks itself, so
349 /// like a delete this owes the flag reset -- and the selection, whose index468 /// like a delete this owes the flag reset -- and the selection, whose index
350 /// the insert has just moved.469 /// the insert has just moved.
@@ -709,6 +828,10 @@ impl Render for Player {
709 }828 }
710 self.pump(window);829 self.pump(window);
711 self.poll_export();830 self.poll_export();
831+ // Every way a source can arrive -- argv, an import, a project load --
832+ // has been through a repaint by the time its clips are drawn, so this
833+ // is the one place that has to notice a new one.
834+ self.cache_waves();
712 // No shadow flag: the clock is the only truth about play state.835 // No shadow flag: the clock is the only truth about play state.
713 let playing = self836 let playing = self
714 .session837 .session
@@ -823,7 +946,9 @@ impl Render for Player {
823 Some(ActionId::Copy) => this.copy_selected(),946 Some(ActionId::Copy) => this.copy_selected(),
824 Some(ActionId::Paste) => this.paste(cx),947 Some(ActionId::Paste) => this.paste(cx),
825 Some(ActionId::Cut) => this.cut(cx),948 Some(ActionId::Cut) => this.cut(cx),
949+ Some(ActionId::Regroup) => this.regroup(cx),
826 Some(ActionId::Delete) => this.delete_selected(cx),950 Some(ActionId::Delete) => this.delete_selected(cx),
951+ Some(ActionId::Lift) => this.lift_selected(cx),
827 Some(ActionId::Undo) => this.undo(cx),952 Some(ActionId::Undo) => this.undo(cx),
828 Some(ActionId::ToggleMute) => {953 Some(ActionId::ToggleMute) => {
829 this.set_volume(|volume| volume.muted = !volume.muted, cx)954 this.set_volume(|volume| volume.muted = !volume.muted, cx)
@@ -1125,8 +1250,18 @@ impl Player {
1125 // it can be hit without aiming (WCAG 2.5.8).1250 // it can be hit without aiming (WCAG 2.5.8).
1126 .child(1251 .child(
1127 div()1252 div()
1128- .id("ruler")
1129 .flex_none()1253 .flex_none()
1254+ .flex()
1255+ .gap(px(HEADER_GAP))
1256+ // The lanes' header column, empty here: the ruler's own bar
1257+ // has to start where their beds start, or the playhead
1258+ // would point at a different moment in each row.
1259+ .child(div().flex_none().w(px(HEADER_W)))
1260+ .child(
1261+ div()
1262+ .id("ruler")
1263+ .flex_1()
1264+ .min_w(px(0.))
1130 .h(px(RULER_HIT_H))1265 .h(px(RULER_HIT_H))
1131 .flex()1266 .flex()
1132 .flex_col()1267 .flex_col()
@@ -1159,9 +1294,10 @@ impl Player {
1159 .bg(rgb(ACCENT)),1294 .bg(rgb(ACCENT)),
1160 ),1295 ),
1161 ),1296 ),
1297+ ),
1162 )1298 )
1163- .child(self.clips_lane(duration, cx))1299+ .child(self.lane_row(Lane::Video, "V1", duration, filled, cx))
1164- .child(track_lane())1300+ .child(self.lane_row(Lane::Audio, "A1", duration, filled, cx))
1165 }1301 }
1166 1302
1167 /// A notice holds its own bar, full width, until it is answered: any key1303 /// A notice holds its own bar, full width, until it is answered: any key
@@ -1442,50 +1578,169 @@ impl Player {
1442 )1578 )
1443 }1579 }
1444 1580
1445- /// The edit list made visible: one box per clip, sized by its share of the1581+ /// One lane of the edit list made visible: a fixed header saying which lane
1446- /// timeline. A cut adds a box without moving anything, a delete closes the1582+ /// it is, then a bed with a box per clip, placed and sized by its share of
1447- /// gap. A box has no room for a label at four clips, so the tooltip is where1583+ /// the timeline. A cut adds a box without moving anything, a delete closes
1448- /// it says what clicking it does. Never focusable, so the root keeps focus1584+ /// the hole, a lift leaves one. A clip too narrow for its name says what it
1449- /// and the play binding still works after a click (ledger:182).1585+ /// is by its tint, and the tooltip is where every box says what clicking it
1450- fn clips_lane(&self, duration: f64, cx: &mut Context<Self>) -> impl IntoElement {1586+ /// does. Never focusable, so the root keeps focus and the play binding still
1587+ /// works after a click (ledger:182).
1588+ fn lane_row(
1589+ &self,
1590+ lane: Lane,
1591+ name: &'static str,
1592+ duration: f64,
1593+ filled: f32,
1594+ cx: &mut Context<Self>,
1595+ ) -> impl IntoElement {
1596+ // The bed's own width, measured last repaint off the ruler's bar: the
1597+ // two are laid out identically (same header offset, same `flex_1`), so
1598+ // one probe answers for both. Zero before the first paint, which only
1599+ // costs the labels one frame.
1600+ let bed_w = f32::from(self.ruler.get().size.width);
1601+ let (clips, others) = match &self.session {
1602+ Some(session) => (
1603+ session.lane_clips(lane),
1604+ session.lane_clips(match lane {
1605+ Lane::Video => Lane::Audio,
1606+ Lane::Audio => Lane::Video,
1607+ }),
1608+ ),
1609+ None => (&[][..], &[][..]),
1610+ };
1611+ let sources = self
1612+ .session
1613+ .as_ref()
1614+ .map_or(&[][..], PlaybackSession::sources);
1615+ let (sel, sel_link) = (self.selected, self.selected_link());
1616+ let audio = lane == Lane::Audio;
1617+ let tip: SharedString = format!(
1618+ "Select — {} removes the take, {} leaves a gap, {} rejoins a cut",
1619+ self.keymap.display(ActionId::Delete),
1620+ self.keymap.display(ActionId::Lift),
1621+ self.keymap.display(ActionId::Regroup)
1622+ )
1623+ .into();
1451 div()1624 div()
1452 .flex_none()1625 .flex_none()
1453 .h(px(LANE_H))1626 .h(px(LANE_H))
1454 .flex()1627 .flex()
1455- .gap(px(1.))1628+ .gap(px(HEADER_GAP))
1629+ // The fixed column the ruler above is offset by as well. Full lane
1630+ // height, so it reads as the bed continuing rather than as a chip.
1631+ .child(
1632+ div()
1633+ .flex_none()
1634+ .w(px(HEADER_W))
1635+ .h_full()
1636+ .flex()
1637+ .items_center()
1638+ .justify_center()
1639+ .rounded(px(3.))
1640+ .bg(rgb(SURFACE))
1641+ .text_size(px(11.))
1642+ .text_color(rgb(INK_DIM))
1643+ .child(name),
1644+ )
1645+ .child(
1646+ // Clips are placed at their own start rather than queued edge
1647+ // to edge: a lift leaves a hole in the lane, and the bare bed
1648+ // showing through it *is* how a gap looks.
1649+ div()
1650+ .relative()
1651+ .flex_1()
1652+ .min_w(px(0.))
1653+ .h_full()
1654+ .rounded(px(3.))
1655+ .bg(rgb(LETTERBOX))
1456 .overflow_hidden()1656 .overflow_hidden()
1457- .children(1657+ .children(clips.iter().enumerate().map(|(i, clip)| {
1458- self.session1658+ let (start, len) = (
1459- .as_ref()1659+ f64::from(clip.start) / self.fps,
1460- .map(PlaybackSession::clip_spans_by_source)1660+ f64::from(clip.len()) / self.fps,
1461- .unwrap_or_default()1661+ );
1462- .into_iter()1662+ let on = marked((lane, i), clip.link, sel, sel_link);
1463- .enumerate()1663+ // A group with a half in the other lane wears its tint;
1464- .map(|(i, (_, len, source))| {1664+ // one without is outlined, so a detached half is visible
1465- let selected = self.selected == Some(i);1665+ // as detached before anyone clicks it.
1466- let tint = source_tint(source);1666+ let grouped =
1667+ clip.link.is_some() && others.iter().any(|o| o.link == clip.link);
1668+ let tint = source_tint(clip.source);
1669+ let width = width_frac(len, duration);
1670+ let label = sources.get(clip.source).map(|path| file_name(path));
1671+ let peaks = sources
1672+ .get(clip.source)
1673+ .and_then(|path| self.waves.get(path))
1674+ .cloned()
1675+ .flatten();
1676+ let tip = tip.clone();
1467 div()1677 div()
1468- .id(("clip", i))1678+ .id((if audio { "aclip" } else { "vclip" }, i))
1679+ .absolute()
1680+ .top_0()
1469 .h_full()1681 .h_full()
1470- .w(relative(width_frac(len, duration)))1682+ .left(relative(start_frac(start, duration)))
1683+ .w(relative(width))
1684+ .overflow_hidden()
1471 .rounded(px(3.))1685 .rounded(px(3.))
1472 .border_1()1686 .border_1()
1473- .border_color(rgb(if selected { ACCENT } else { tint }))1687+ .border_color(rgb(if on {
1474- .bg(rgb(if selected { SELECTED } else { tint }))1688+ ACCENT
1689+ } else if grouped {
1690+ tint
1691+ } else {
1692+ INK_DIM
1693+ }))
1694+ .bg(rgb(if on { SELECTED } else { tint }))
1475 .cursor_pointer()1695 .cursor_pointer()
1476 .hover(|s| s.border_color(rgb(ACCENT)))1696 .hover(|s| s.border_color(rgb(ACCENT)))
1477- .tooltip(|_, cx| {1697+ .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
1478- cx.new(|_| Tip("Select clip — Delete removes it".into()))
1479- .into()
1480- })
1481 .on_mouse_down(1698 .on_mouse_down(
1482 MouseButton::Left,1699 MouseButton::Left,
1483 cx.listener(move |this, _: &MouseDownEvent, _, cx| {1700 cx.listener(move |this, _: &MouseDownEvent, _, cx| {
1484- this.selected = Some(i);1701+ this.selected = Some((lane, i));
1485 cx.notify();1702 cx.notify();
1486 }),1703 }),
1487 )1704 )
1488- }),1705+ // Under the label row, never through it.
1706+ .when_some(peaks.filter(|_| audio), |d, peaks| {
1707+ d.child(
1708+ div()
1709+ .absolute()
1710+ .left_0()
1711+ .right_0()
1712+ .top(px(LABEL_H))
1713+ .bottom_0()
1714+ .child(waveform(
1715+ peaks,
1716+ f64::from(clip.in_frame) / self.fps,
1717+ f64::from(clip.out_frame) / self.fps,
1718+ )),
1719+ )
1720+ })
1721+ .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {
1722+ d.child(
1723+ div()
1724+ .relative()
1725+ .h(px(LABEL_H))
1726+ .px(px(4.))
1727+ .truncate()
1728+ .text_size(px(10.))
1729+ .child(label),
1730+ )
1731+ })
1732+ }))
1733+ // Last, so it is over the clips: the same fraction in both
1734+ // lanes, which is the playhead being one line.
1735+ .child(
1736+ div()
1737+ .absolute()
1738+ .top_0()
1739+ .h_full()
1740+ .left(relative(filled))
1741+ .w(px(1.))
1742+ .bg(rgb(ACCENT)),
1743+ ),
1489 )1744 )
1490 }1745 }
1491 }1746 }
@@ -1698,6 +1953,120 @@ fn width_frac(len: f64, total: f64) -> f32 {
1698 if total > 0. { (len / total) as f32 } else { 1. }1953 if total > 0. { (len / total) as f32 } else { 1. }
1699 }1954 }
1700 1955
1956+/// Where along the lane a clip starts, 0..1. Unlike [`width_frac`] a timeline
1957+/// with no length pins this to the left edge -- a full-width offset would push
1958+/// the box out of the lane it belongs to.
1959+fn start_frac(start: f64, total: f64) -> f32 {
1960+ if total > 0. {
1961+ (start / total).clamp(0., 1.) as f32
1962+ } else {
1963+ 0.
1964+ }
1965+}
1966+
1967+/// The video-lane index of the take an audio clip belongs to, if the video lane
1968+/// still holds that half. `None` for a half whose picture was lifted -- which is
1969+/// what makes it a thing of its own to delete.
1970+fn video_half(session: &PlaybackSession, audio: usize) -> Option<usize> {
1971+ let link = session.lane_clips(Lane::Audio).get(audio)?.link?;
1972+ session
1973+ .lane_clips(Lane::Video)
1974+ .iter()
1975+ .position(|clip| clip.link == Some(link))
1976+}
1977+
1978+/// Whether a click marks this clip: the clip that was clicked always, and the
1979+/// other lane's clip of the same group with it. A clip whose group has no other
1980+/// half -- what a lift leaves behind -- marks only itself, which is what makes a
1981+/// detached half separately deletable.
1982+fn marked(
1983+ here: (Lane, usize),
1984+ link: Option<u32>,
1985+ sel: Option<(Lane, usize)>,
1986+ sel_link: Option<u32>,
1987+) -> bool {
1988+ sel == Some(here) || (link.is_some() && link == sel_link)
1989+}
1990+
1991+/// Whether a clip is wide enough to be worth naming.
1992+fn show_label(w: f32) -> bool {
1993+ w >= LABEL_MIN_W
1994+}
1995+
1996+/// Scales an envelope to its own loudest sample, so a quietly mastered source
1997+/// still draws as a shape. The fixtures peak around an eighth of full scale, and
1998+/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
1999+/// that is not.
2000+fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
2001+ let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi));
2002+ if loudest > 0. {
2003+ for (lo, hi) in &mut peaks {
2004+ *lo /= loudest;
2005+ *hi /= loudest;
2006+ }
2007+ }
2008+ peaks
2009+}
2010+
2011+/// The min/max envelope of `peaks` over the source seconds `from..to`, as
2012+/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box
2013+/// -- a clip's waveform cannot paint over its neighbour -- and every column is
2014+/// at least a pixel tall, so silence reads as a line through the middle rather
2015+/// than as a polygon with no area.
2016+fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f32, f32, f32)> {
2017+ if peaks.is_empty() || w <= 0. || h <= 0. {
2018+ return Vec::new();
2019+ }
2020+ let cols = (w / WAVE_COL).ceil().max(1.) as usize;
2021+ let mid = h / 2.;
2022+ (0..=cols)
2023+ .map(|col| {
2024+ let along = col as f64 / cols as f64;
2025+ let at = from + (to - from) * along;
2026+ // Casting a float to an integer saturates in Rust, so a source
2027+ // second past the end of the peaks clamps rather than wrapping.
2028+ let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1);
2029+ let (lo, hi) = peaks[bucket];
2030+ let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5);
2031+ let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5);
2032+ (w * along as f32, top.max(0.), bottom.min(h))
2033+ })
2034+ .collect()
2035+}
2036+
2037+/// One clip's audio, drawn as a filled min/max envelope inside whatever box it
2038+/// is given. Peaks are the source's whole envelope; `from`/`to` are the source
2039+/// seconds this clip plays, so a cut clip shows its own stretch of the file.
2040+fn waveform(peaks: Arc<Vec<(f32, f32)>>, from: f64, to: f64) -> impl IntoElement {
2041+ canvas(
2042+ |_, _, _| (),
2043+ move |bounds, _, window, _| {
2044+ let (o, s) = (bounds.origin, bounds.size);
2045+ let cols = envelope(&peaks, from, to, f32::from(s.width), f32::from(s.height));
2046+ if cols.len() < 2 {
2047+ return;
2048+ }
2049+ // Down the tops and back along the bottoms: one closed outline of
2050+ // the whole envelope, which is one path rather than a path a column.
2051+ let mut points: Vec<Point<Pixels>> = cols
2052+ .iter()
2053+ .map(|&(x, top, _)| point(o.x + px(x), o.y + px(top)))
2054+ .collect();
2055+ points.extend(
2056+ cols.iter()
2057+ .rev()
2058+ .map(|&(x, _, bottom)| point(o.x + px(x), o.y + px(bottom))),
2059+ );
2060+ let mut path = PathBuilder::fill();
2061+ path.add_polygon(&points, true);
2062+ if let Ok(path) = path.build() {
2063+ window.paint_path(path, rgb(INK_DIM));
2064+ }
2065+ },
2066+ )
2067+ .size_full()
2068+}
2069+
1701 /// A toolbar button: its glyph, its name, and its key on hover. `id` only buys2070 /// A toolbar button: its glyph, its name, and its key on hover. `id` only buys
1702 /// `on_click` and the tooltip -- it is still not focusable, so the root's own2071 /// `on_click` and the tooltip -- it is still not focusable, so the root's own
1703 /// key listener keeps working after a press, and the click lands on mouse-up2072 /// key listener keeps working after a press, and the click lands on mouse-up
@@ -1835,15 +2204,6 @@ fn empty_hint() -> impl IntoElement {
1835 )2204 )
1836 }2205 }
1837 2206
1838-/// The second lane: still a placeholder, deliberately empty.
1839-fn track_lane() -> impl IntoElement {
1840- div()
1841- .flex_none()
1842- .h(px(LANE_H))
1843- .rounded(px(3.))
1844- .bg(rgb(SURFACE))
1845-}
1846-
1847 /// Two bars while playing, a triangle while paused. Drawn, so there is no icon2207 /// Two bars while playing, a triangle while paused. Drawn, so there is no icon
1848 /// font and no glyph coverage to depend on.2208 /// font and no glyph coverage to depend on.
1849 fn transport_glyph(playing: bool) -> impl IntoElement {2209 fn transport_glyph(playing: bool) -> impl IntoElement {
@@ -1895,9 +2255,11 @@ fn timecode(t: f64, fps: f64) -> String {
1895 #[cfg(test)]2255 #[cfg(test)]
1896 mod tests {2256 mod tests {
1897 use super::{2257 use super::{
1898- CONTROL_H, HIT_MIN, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LANE_H, Quality, RULER_HIT_H,2258+ ACCENT, CONTROL_H, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H,
1899- SOURCE_TINTS, SURFACE, Volume, cancels_export, export_path, export_settings, frac_along,2259+ KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, Lane, PANEL_H, Quality, RULER_HIT_H,
1900- is_bare_modifier, is_project, keymap, project_path, push_digit, scrub_due, source_tint,2260+ SELECTED, SOURCE_TINTS, SURFACE, Volume, WAVE_BPS, WAVE_COL, cancels_export, envelope,
2261+ export_path, export_settings, frac_along, is_bare_modifier, is_project, keymap, marked,
2262+ normalise, project_path, push_digit, scrub_due, show_label, source_tint, start_frac,
1901 timecode, width_frac,2263 timecode, width_frac,
1902 };2264 };
1903 use gpui::{Bounds, Pixels, point, px, size};2265 use gpui::{Bounds, Pixels, point, px, size};
@@ -2187,6 +2549,181 @@ mod tests {
2187 assert!(LANE_H >= HIT_MIN);2549 assert!(LANE_H >= HIT_MIN);
2188 }2550 }
2189 2551
2552+ /// WCAG 2.1 relative luminance of a packed `0xRRGGBB`.
2553+ fn luminance(colour: u32) -> f64 {
2554+ let channel = |shift: u32| {
2555+ let s = f64::from((colour >> shift) & 0xff) / 255.;
2556+ if s <= 0.03928 {
2557+ s / 12.92
2558+ } else {
2559+ ((s + 0.055) / 1.055).powf(2.4)
2560+ }
2561+ };
2562+ 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0)
2563+ }
2564+
2565+ /// WCAG 2.1 contrast ratio, 1..=21.
2566+ fn contrast(a: u32, b: u32) -> f64 {
2567+ let (a, b) = (luminance(a), luminance(b));
2568+ (a.max(b) + 0.05) / (a.min(b) + 0.05)
2569+ }
2570+
2571+ #[test]
2572+ fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() {
2573+ // The header column is what the ruler is offset by as well, so both
2574+ // numbers are shared rather than repeated per row (A-MUST1/A-MUST2).
2575+ assert!(HEADER_W > 0. && HEADER_GAP >= 0.);
2576+ // Two lanes, a ruler, a button row and the timecode line, inside the
2577+ // panel the window is sized for.
2578+ assert!(
2579+ CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H,
2580+ "the second lane does not fit the panel"
2581+ );
2582+ // Headers and clip boxes are as tall as the lane, and the lane is a
2583+ // click target (WCAG 2.5.8).
2584+ assert!(LANE_H >= HIT_MIN);
2585+ // A label row that ate the whole lane would leave no waveform.
2586+ assert!(LABEL_H < LANE_H / 2.);
2587+ }
2588+
2589+ #[test]
2590+ fn a_click_marks_the_whole_group_and_nothing_else() {
2591+ let (v, a) = ((Lane::Video, 0), (Lane::Audio, 0));
2592+ // Clicking the video half of group 1 marks the audio half with it.
2593+ assert!(marked(v, Some(1), Some(v), Some(1)));
2594+ assert!(marked(a, Some(1), Some(v), Some(1)));
2595+ // Another group's clips stay unmarked, in either lane.
2596+ assert!(!marked((Lane::Video, 1), Some(2), Some(v), Some(1)));
2597+ assert!(!marked((Lane::Audio, 1), Some(2), Some(v), Some(1)));
2598+ // A half a lift left behind has no group: it marks itself only, which
2599+ // is what makes it separately deletable. Two ungrouped clips must not
2600+ // mark each other by both being ungrouped.
2601+ assert!(marked(a, None, Some(a), None));
2602+ assert!(!marked(v, None, Some(a), None));
2603+ // Nothing selected marks nothing.
2604+ assert!(!marked(v, Some(1), None, None));
2605+ }
2606+
2607+ #[test]
2608+ fn a_name_is_dropped_rather_than_smeared_across_a_thin_clip() {
2609+ assert!(show_label(LABEL_MIN_W));
2610+ assert!(show_label(400.));
2611+ assert!(!show_label(LABEL_MIN_W - 0.1));
2612+ // A timeline with no length must not put a box outside its lane.
2613+ assert_eq!(start_frac(3., 0.), 0.);
2614+ assert_eq!(start_frac(1., 4.), 0.25);
2615+ // Past the end clamps rather than running off the bed.
2616+ assert_eq!(start_frac(8., 4.), 1.);
2617+ }
2618+
2619+ #[test]
2620+ fn an_envelope_stays_inside_the_box_it_is_drawn_in() {
2621+ // A ramp: silence at the start, full scale at the end.
2622+ let peaks: Vec<(f32, f32)> = (0..40)
2623+ .map(|i| (-(i as f32) / 39., i as f32 / 39.))
2624+ .collect();
2625+ let (w, h) = (100., 30.);
2626+ let cols = envelope(&peaks, 0., 1., w, h);
2627+ assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1);
2628+ for &(x, top, bottom) in &cols {
2629+ assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}");
2630+ assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}");
2631+ assert!(
2632+ (0. ..=h).contains(&bottom),
2633+ "bottom {bottom} outside 0..{h}"
2634+ );
2635+ // Never inverted, and never a polygon with no area: silence has to
2636+ // read as a line rather than as nothing at all.
2637+ assert!(
2638+ bottom - top >= 1.,
2639+ "column {top}..{bottom} is thinner than a pixel"
2640+ );
2641+ }
2642+ // The ramp is drawn as a ramp: the last column is taller than the first.
2643+ let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
2644+ assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.);
2645+ // Degenerate inputs draw nothing rather than panicking.
2646+ assert!(envelope(&[], 0., 1., w, h).is_empty());
2647+ assert!(envelope(&peaks, 0., 1., 0., h).is_empty());
2648+ // A clip whose range runs past the peaks clamps to the last bucket.
2649+ assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
2650+ }
2651+
2652+ #[test]
2653+ fn a_quiet_source_still_draws_as_a_shape() {
2654+ // An eighth of full scale, which is about where the fixtures sit.
2655+ let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)];
2656+ let loud = normalise(quiet.clone());
2657+ assert_eq!(loud[0], (-1., 1.));
2658+ assert_eq!(loud[1], (-0.5, 0.5));
2659+ // Digital silence has no loudest sample to scale to; it must not divide
2660+ // by zero and must stay flat.
2661+ assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]);
2662+ assert!(normalise(Vec::new()).is_empty());
2663+ }
2664+
2665+ /// The whole waveform path, from the file on disk to the columns that get
2666+ /// painted: what no screenshot can assert about the shape.
2667+ #[test]
2668+ fn the_fixtures_waveform_reaches_the_lane_as_a_shape() {
2669+ let asset = |name: &str| {
2670+ std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2671+ .join("../../assets")
2672+ .join(name)
2673+ };
2674+ let peaks = normalise(
2675+ engine::waveform::peaks(asset("test_av.mp4"), WAVE_BPS)
2676+ .expect("open the fixture")
2677+ .expect("test_av.mp4 has audio"),
2678+ );
2679+ // 5 s of source at the rate the lane asks for.
2680+ assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize);
2681+ let cols = envelope(&peaks, 0., 5., 600., 30.);
2682+ let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
2683+ let tallest = cols.iter().map(height).fold(0., f32::max);
2684+ let flattest = cols.iter().map(height).fold(f32::MAX, f32::min);
2685+ // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in
2686+ // every second, so the drawn envelope is a shape and not a bar.
2687+ assert!(tallest > 25., "loudest column only {tallest} px of 30");
2688+ assert!(
2689+ flattest < 8.,
2690+ "quietest column {flattest} px -- no dips drawn"
2691+ );
2692+ // A video-only source draws no waveform at all rather than a flat fake.
2693+ assert!(
2694+ engine::waveform::peaks(asset("test_baseline.mp4"), WAVE_BPS)
2695+ .expect("open the fixture")
2696+ .is_none()
2697+ );
2698+ }
2699+
2700+ #[test]
2701+ fn every_mark_on_a_clip_is_legible_on_it() {
2702+ for (i, tint) in SOURCE_TINTS.iter().enumerate() {
2703+ // WCAG 1.4.3: the clip's name is body text on its tint.
2704+ assert!(
2705+ contrast(INK, *tint) >= 4.5,
2706+ "source {i}: label contrast {:.2}",
2707+ contrast(INK, *tint)
2708+ );
2709+ // WCAG 1.4.11: the waveform is a non-text graphic on it.
2710+ assert!(
2711+ contrast(INK_DIM, *tint) >= 3.,
2712+ "source {i}: waveform contrast {:.2}",
2713+ contrast(INK_DIM, *tint)
2714+ );
2715+ }
2716+ // A selected clip's bed is the same two marks on a different colour.
2717+ assert!(contrast(INK, SELECTED) >= 4.5);
2718+ assert!(contrast(INK_DIM, SELECTED) >= 3.);
2719+ // The bed a gap shows through has to read as a hole in the lane, and
2720+ // the accent playhead has to be findable on it.
2721+ assert!(contrast(LETTERBOX, SURFACE) >= 1.5);
2722+ assert!(contrast(ACCENT, LETTERBOX) >= 3.);
2723+ // The sanity check on the ratio itself: black on white is 21:1.
2724+ assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01);
2725+ }
2726+
2190 #[test]2727 #[test]
2191 fn source_tints_differ_per_source_and_cycle() {2728 fn source_tints_differ_per_source_and_cycle() {
2192 // The file the session opened with is the unchanged lane colour.2729 // The file the session opened with is the unchanged lane colour.
@@ -2312,6 +2849,7 @@ fn main() {
2312 done: false,2849 done: false,
2313 ruler: Rc::default(),2850 ruler: Rc::default(),
2314 selected: None,2851 selected: None,
2852+ waves: HashMap::new(),
2315 clipboard: None,2853 clipboard: None,
2316 scrubbing: false,2854 scrubbing: false,
2317 last_scrub: Instant::now(),2855 last_scrub: Instant::now(),
crates/engine/src/playback.rsmodified+10 -0
@@ -372,6 +372,16 @@ impl PlaybackSession {
372 .collect()372 .collect()
373 }373 }
374 374
375+ /// Every placement of one lane, in timeline order. What a two-lane
376+ /// front-end draws and nothing
377+ /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip
378+ /// carries its group id (which halves a click marks together) and its
379+ /// source range (where a waveform reads its peaks from) as well as its
380+ /// span. The holes between consecutive clips are the gaps.
381+ pub fn lane_clips(&self, lane: Lane) -> &[Clip] {
382+ self.project.lane(lane)
383+ }
384+
375 /// Splits every lane at `timeline_secs`, so the two sides become two385 /// Splits every lane at `timeline_secs`, so the two sides become two
376 /// groups. Metadata only: a split never changes the timeline->source386 /// groups. Metadata only: a split never changes the timeline->source
377 /// mapping, so the running decoder stays correct and playback does not387 /// mapping, so the running decoder stays correct and playback does not