FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Follow-ups to #3240: alpha upload table, duplicate markers off the UI thread, cut drag over the clips (#3243)
aiongga504f3c5adc4
diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rsindex e3818ed61..1153a3570 100644--- a/crates/ui-egui/src/frames.rs+++ b/crates/ui-egui/src/frames.rs@@ -99,18 +99,37 @@ impl Rgba {/// A frame pixel (sRGB of the linear color premultiplied by alpha) as egui's color, which is the/// sRGB of the straight color multiplied by alpha.fn gamma_premultiplied([r, g, b, a]: [u8; 4]) -> egui::Color32 {- use egui::ecolor::{gamma_u8_from_linear_f32, linear_f32_from_gamma_u8};match a {255 => egui::Color32::from_rgb(r, g, b),0 => egui::Color32::TRANSPARENT,_ => {- let k = f32::from(a) / 255.0;- let straight = |v: u8| gamma_u8_from_linear_f32((linear_f32_from_gamma_u8(v) / k).min(1.0));+ let straight = |v: u8| straight_srgb(a, v);egui::Color32::from_rgba_unmultiplied(straight(r), straight(g), straight(b), a)}}}+/// The sRGB of the straight color whose premultiplied value is sRGB `v` at alpha `a`, from a table+/// made on first use: a frame with partial alpha would otherwise take two `powf` per channel per+/// pixel on every upload.+fn straight_srgb(a: u8, v: u8) -> u8 {+ static TABLE: std::sync::OnceLock<Vec<u8>> = std::sync::OnceLock::new();+ let table = TABLE.get_or_init(|| {+ use egui::ecolor::{gamma_u8_from_linear_f32, linear_f32_from_gamma_u8};+ let mut t = vec![0u8; 256 * 256];+ for a in 1..=255u8 {+ let k = f32::from(a) / 255.0;+ for v in 0..=255u8 {+ if let Some(x) = t.get_mut(usize::from(a) * 256 + usize::from(v)) {+ *x = gamma_u8_from_linear_f32((linear_f32_from_gamma_u8(v) / k).min(1.0));+ }+ }+ }+ t+ });+ table.get(usize::from(a) * 256 + usize::from(v)).copied().unwrap_or(v)+}+struct Job {key: FrameKey,queued: Instant,@@ -1027,6 +1046,17 @@ mod tests {assert!(!background_work(50, Target::SequencePlan(ItemId(1))));}+ #[test]+ fn the_straight_color_table_matches_the_formula() {+ use egui::ecolor::{gamma_u8_from_linear_f32, linear_f32_from_gamma_u8};+ for a in 1..=255u8 {+ for v in 0..=255u8 {+ let want = gamma_u8_from_linear_f32((linear_f32_from_gamma_u8(v) / (f32::from(a) / 255.0)).min(1.0));+ assert_eq!(super::straight_srgb(a, v), want, "a {a} v {v}");+ }+ }+ }+#[test]fn a_frame_goes_up_opaque_or_with_its_alpha() {use egui::Color32;diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rsindex 75df395d7..8e984d28c 100644--- a/crates/ui-egui/src/panels/timeline.rs+++ b/crates/ui-egui/src/panels/timeline.rs@@ -79,24 +79,50 @@ pub struct TlState {thumb_pps: Option<f64>,/// Show Duplicate Frame Markers: the markers of a sequence, with the session revision, the/// sequence and the project they were worked out for.- duplicates: Option<(DuplicatesKey, Arc<HashMap<ClipId, DuplicateFrames>>)>,+ duplicates: Option<(DuplicatesKey, DuplicateMarkers)>,+ /// The markers being worked out on a background thread, and where the thread leaves them.+ duplicates_pending: Option<DuplicatesKey>,+ duplicates_done: Arc<Mutex<Option<(DuplicatesKey, DuplicateMarkers)>>>,}/// (session revision, sequence, project address)type DuplicatesKey = (u64, ItemId, usize);+type DuplicateMarkers = Arc<HashMap<ClipId, DuplicateFrames>>;-/// The duplicate frame markers of sequence `seq_id`, worked out again only after the project-/// changes.-fn duplicate_markers(app: &mut FilmcraftApp, seq_id: ItemId, seq: &Sequence) -> Arc<HashMap<ClipId, DuplicateFrames>> {+/// The duplicate frame markers of sequence `seq_id`, worked out again on a background thread+/// after the project changes: a long sequence takes too long for a frame. Until the new markers+/// are ready, the last ones of the same sequence are shown.+fn duplicate_markers(app: &mut FilmcraftApp, ctx: &egui::Context, seq_id: ItemId, seq: &Sequence) -> DuplicateMarkers {let key = (app.session.revision, seq_id, Arc::as_ptr(&app.session.project) as usize);- if let Some((k, d)) = &app.tl.duplicates- && *k == key+ let done = app.tl.duplicates_done.lock().unwrap_or_else(|e| e.into_inner()).take();+ // a job that finishes after a newer one leaves the newer markers in place+ if let Some((k, d)) = done+ && app.tl.duplicates.as_ref().is_none_or(|(have, _)| *have != key){- return d.clone();+ app.tl.duplicates = Some((k, d));+ }+ match &app.tl.duplicates {+ Some((k, d)) if *k == key => return d.clone(),+ _ => {}+ }+ if app.tl.duplicates_pending != Some(key) {+ app.tl.duplicates_pending = Some(key);+ let (project, seq, slot, ctx) = (app.session.project.clone(), seq.clone(), app.tl.duplicates_done.clone(), ctx.clone());+ let run = move || {+ // a panic in the comparison must not take the app down: it leaves no markers+ let d = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| duplicate_frames(&project, &seq))).unwrap_or_default();+ *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some((key, Arc::new(d.into_iter().map(|d| (d.clip, d)).collect())));+ ctx.request_repaint();+ };+ #[cfg(not(target_arch = "wasm32"))]+ std::thread::spawn(run);+ #[cfg(target_arch = "wasm32")]+ run();+ }+ match &app.tl.duplicates {+ Some(((_, s, _), d)) if *s == seq_id => d.clone(),+ _ => Arc::default(),}- let d: Arc<HashMap<ClipId, DuplicateFrames>> = Arc::new(duplicate_frames(&app.session.project, seq).into_iter().map(|d| (d.clip, d)).collect());- app.tl.duplicates = Some((key, d.clone()));- d}impl TlState {@@ -109,6 +135,9 @@ impl TlState {self.seq_peak_keys = Default::default();self.seq_keys_seen.clear();self.peak_max.clear();+ self.duplicates = None;+ self.duplicates_pending = None;+ self.duplicates_done = Default::default();}}@@ -537,7 +566,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect) {if copying {ctx.set_cursor_icon(CursorIcon::Copy);}- let duplicates = if app.session.state.show_duplicate_frame_markers { duplicate_markers(app, seq_id, seq) } else { Arc::default() };+ let duplicates = if app.session.state.show_duplicate_frame_markers { duplicate_markers(app, &ctx, seq_id, seq) } else { Arc::default() };for r in &rows {let Some(tr) = seq.track(r.track) else { continue };let clip_rect = if r.kind == TrackKind::Video { vclip } else { aclip };diff --git a/crates/ui-egui/src/panels/transition_controls.rs b/crates/ui-egui/src/panels/transition_controls.rsindex 38a439776..2035e75da 100644--- a/crates/ui-egui/src/panels/transition_controls.rs+++ b/crates/ui-egui/src/panels/transition_controls.rs@@ -11,9 +11,10 @@//! [`trn::drag_span`]); each drag is one undo step. Clicking or dragging the ruler moves the//! playhead. The divider between the settings and the timeline is the clip view's.//!-//! Dragging the cut line where it crosses the transition moves the cut and the transition-//! together, as Premiere's Move a cut and transition together describes it: one `timeline.roll`-//! on release, so the clips' In and Out points change and the sequence keeps its length.+//! Dragging the cut line, over the transition or where it crosses clip A or B, moves the cut and+//! the transition together, as Premiere's Move a cut and transition together describes it: one+//! `timeline.roll` on release, so the clips' In and Out points change and the sequence keeps its+//! length.//!//! Not here yet: the A/B preview thumbnails with their Start / End sliders, Show Actual Sources,//! and a rolling edit by dragging clip A or B in the transition's timeline.@@ -24,7 +25,8 @@//! `effectControls.transition.timeline`, `.timeline.ruler`, `.timeline.a` / `.timeline.b` (the//! clips, labelled with their names), `.timeline.span` (the transition) with its ends//! `.timeline.span.in` / `.timeline.span.out`, `.timeline.cut` (the cut line over the transition,-//! between two clips), `.timeline.playhead`; `effectControls.divider`;+//! between two clips) and `.timeline.cut.a` / `.timeline.cut.b` (where it crosses the clips),+//! `.timeline.playhead`; `effectControls.divider`;//! the dialog's `transitionDuration.value`, `.ok`, `.cancel`.use egui::{Align2, Pos2, Rect, RichText, Sense, Stroke, pos2, vec2};@@ -319,6 +321,20 @@ fn timeline(app: &mut FilmcraftApp, ui: &mut egui::Ui, lane: Rect, id: Transitioif let Some(z) = cut_zone {elems.push(("effectControls.transition.timeline.cut".into(), z, "cut".into()));}+ // and where it crosses the clips' rows, which also holds when the cut is at the transition's+ // edge (Start or End at Cut) or the transition is too narrow for the zone over it+ let cut_rows: Vec<Rect> = if two_sided {+ [(row_a, "a"), (row_b, "b")]+ .into_iter()+ .map(|(r, k)| {+ let z = Rect::from_min_max(pos2(cx - CUT_PX, r.min.y), pos2(cx + CUT_PX, r.max.y));+ elems.push((format!("effectControls.transition.timeline.cut.{k}"), z, "cut".into()));+ z+ })+ .collect()+ } else {+ Vec::new()+ };// the playhead, while it is in viewlet ph = app.session.playhead();if ph >= v.0 && ph <= v.1 {@@ -350,6 +366,9 @@ fn timeline(app: &mut FilmcraftApp, ui: &mut egui::Ui, lane: Rect, id: Transitio}};let sresp = ui.interact(span, egui::Id::new(("tr-ec-span", id.0)), Sense::click_and_drag());+ let cresp = cut_rows.iter().enumerate().map(|(i, z)| ui.interact(*z, egui::Id::new(("tr-ec-cut", id.0, i)), Sense::drag())).reduce(|a, b| a.union(b));+ // the transition's drag or the cut's, whichever is going on+ let resp = cresp.as_ref().map_or_else(|| sresp.clone(), |c| sresp.union(c.clone()));if let Some(h) = sresp.hover_pos() {ui.ctx().set_cursor_icon(if grab(h.x).is_some() { egui::CursorIcon::ResizeColumn } else { egui::CursorIcon::Grab });}@@ -359,11 +378,17 @@ fn timeline(app: &mut FilmcraftApp, ui: &mut egui::Ui, lane: Rect, id: Transitiolet cut = edge.is_none() && on_cut(from);drag = Some(LaneDrag { edge, cut, roll: Tick::ZERO, start: x.start, duration: x.duration, view: v, from_x: from, begun: false });}+ if let Some(c) = &cresp+ && c.drag_started()+ {+ let from = ui.input(|i| i.pointer.press_origin()).or(c.interact_pointer_pos()).map_or(cx, |p: Pos2| p.x);+ drag = Some(LaneDrag { edge: None, cut: true, roll: Tick::ZERO, start: x.start, duration: x.duration, view: v, from_x: from, begun: false });+ }let mut change = None;- if sresp.dragged()+ if resp.dragged()&& let Some(d) = drag.as_mut()&& d.cut- && let (Some(pos), Some(a), Some(b)) = (sresp.interact_pointer_pos(), x.from, x.to)+ && let (Some(pos), Some(a), Some(b)) = (resp.interact_pointer_pos(), x.from, x.to){// as far as `timeline.roll` will move it on release; 0 when the roll would faild.roll = filmcraft_engine::commands::roll_delta(&app.session, a, b, rate.snap_nearest(ticks_for(lane, d.view, pos.x - d.from_x))).unwrap_or(Tick::ZERO);@@ -382,16 +407,16 @@ fn timeline(app: &mut FilmcraftApp, ui: &mut egui::Ui, lane: Rect, id: Transitio}}// over the cut line (and not an end), the pointer shows that it moves the cut- if sresp.hover_pos().is_some_and(|h| grab(h.x).is_none() && on_cut(h.x)) || drag.is_some_and(|d| d.cut) {+ if sresp.hover_pos().is_some_and(|h| grab(h.x).is_none() && on_cut(h.x)) || cresp.as_ref().is_some_and(|c| c.hovered()) || drag.is_some_and(|d| d.cut) {ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);}// a drag of the cut is one rolling edit, made when it is releasedlet rolled = match (drag, x.from, x.to) {- (Some(d), Some(a), Some(b)) if sresp.drag_stopped() && d.cut && d.roll != Tick::ZERO => Some((a, b, d.roll)),+ (Some(d), Some(a), Some(b)) if resp.drag_stopped() && d.cut && d.roll != Tick::ZERO => Some((a, b, d.roll)),_ => None,};// released, or a drag that lost its transition (deleted, deselected) while it went on- if !sresp.dragged() && !sresp.drag_started() {+ if !resp.dragged() && !resp.drag_started() {drag = None;}if let Some(tk) = seek {diff --git a/crates/ui-egui/tests/it/sequence_ui.rs b/crates/ui-egui/tests/it/sequence_ui.rsindex 701426a49..3003e0431 100644--- a/crates/ui-egui/tests/it/sequence_ui.rs+++ b/crates/ui-egui/tests/it/sequence_ui.rs@@ -133,6 +133,20 @@ impl Driver {self.frames(3);}+ /// The ids under `prefix` once `done` holds for them: the timeline works out duplicate frame+ /// markers on a background thread.+ fn ids_once(&mut self, prefix: &str, mut done: impl FnMut(&[String]) -> bool) -> Vec<String> {+ let t0 = std::time::Instant::now();+ loop {+ let ids = self.ids(prefix);+ if done(&ids) || t0.elapsed().as_secs() >= 30 {+ return ids;+ }+ self.frames(1);+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ }+fn ids(&mut self, prefix: &str) -> Vec<String> {let v = self.ok("ui.elements", json!({"prefix": prefix}));v.as_array().unwrap().iter().filter_map(|e| e["id"].as_str().map(str::to_string)).collect()@@ -330,23 +344,21 @@ fn duplicate_frame_markers_are_drawn_on_repeated_clips() {assert!(d.ids("timeline.duplicateFrames.").is_empty(), "hidden until Show Duplicate Frame Markers");d.click("timeline.toggle.settings");d.click("timeline.settings.showDuplicateFrameMarkers");- d.frames(3);assert!(d.app().session.state.show_duplicate_frame_markers);- let marks = d.ids("timeline.duplicateFrames.");+ let has = |marks: &[String], clip: u64| marks.contains(&format!("timeline.duplicateFrames.{clip}.0"));+ let marks = d.ids_once("timeline.duplicateFrames.", |m| has(m, first) && has(m, copy));for clip in [first, copy] {- assert!(marks.contains(&format!("timeline.duplicateFrames.{clip}.0")), "clip {clip}: {marks:?}");+ assert!(has(&marks, clip), "clip {clip}: {marks:?}");}// the markers follow edits: without the copy the first clip repeats nothing (the demo// repeats frames of another clip elsewhere, and those markers stay)let ours = |marks: &[String]| marks.iter().filter(|m| [first, copy].iter().any(|c| m.starts_with(&format!("timeline.duplicateFrames.{c}.")))).count();d.exec("edit.undo", json!({}));- d.frames(3);- let marks = d.ids("timeline.duplicateFrames.");+ let marks = d.ids_once("timeline.duplicateFrames.", |m| ours(m) == 0);assert_eq!(ours(&marks), 0, "the copy is gone: {marks:?}");assert!(!marks.is_empty(), "the demo's own repeat: {marks:?}");d.exec("edit.redo", json!({}));- d.frames(3);- assert_eq!(ours(&d.ids("timeline.duplicateFrames.")), 2, "the copy is back");+ assert_eq!(ours(&d.ids_once("timeline.duplicateFrames.", |m| ours(m) == 2)), 2, "the copy is back");// at 200 % the copy shows every other frame of the original, so the original repeats in// single framesd.app()@@ -363,9 +375,9 @@ fn duplicate_frame_markers_are_drawn_on_repeated_clips() {let (scroll, pps) = (d.app().ui.timeline.scroll, d.app().ui.timeline.pps);let middle = (start + duration / 2) as f64 / filmcraft_time::TICKS_PER_SECOND as f64;(d.app().ui.timeline.scroll, d.app().ui.timeline.target_scroll) = (middle, middle);- d.frames(3);- let marks = d.ids(&format!("timeline.duplicateFrames.{first}."));- assert!(!marks.is_empty() && !marks.contains(&format!("timeline.duplicateFrames.{first}.0")), "{marks:?}");+ let scrolled = |m: &[String]| !m.is_empty() && !m.contains(&format!("timeline.duplicateFrames.{first}.0"));+ let marks = d.ids_once(&format!("timeline.duplicateFrames.{first}."), scrolled);+ assert!(scrolled(&marks), "{marks:?}");(d.app().ui.timeline.scroll, d.app().ui.timeline.target_scroll) = (scroll, scroll);// zoomed far out, the single frames make one stripe(d.app().ui.timeline.pps, d.app().ui.timeline.target_pps) = (1.0, 1.0);diff --git a/crates/ui-egui/tests/it/timeline_trim_ui.rs b/crates/ui-egui/tests/it/timeline_trim_ui.rsindex 1368a4ff9..a72802dd7 100644--- a/crates/ui-egui/tests/it/timeline_trim_ui.rs+++ b/crates/ui-egui/tests/it/timeline_trim_ui.rs@@ -204,6 +204,12 @@ fn duplicate_frame_markers_stay_inside_a_clip_being_trimmed() {.map(|e| (e["rect"][0].as_f64().expect("x") + e["rect"][2].as_f64().expect("w")) as f32).fold(f32::MIN, f32::max)};+ // the markers are worked out on a background thread+ let t0 = std::time::Instant::now();+ while stripe_right(&mut d) == f32::MIN && t0.elapsed().as_secs() < 30 {+ d.frames(1);+ std::thread::sleep(std::time::Duration::from_millis(5));+ }assert!((stripe_right(&mut d) - x1).abs() <= 2.0, "the stripe runs to the Out edge");// press on the Out edge and move half the clip inward, without releasinglet push = |d: &mut Driver, e: egui::Event| d.harness.input_mut().events.push(e);diff --git a/crates/ui-egui/tests/it/transitions_ui.rs b/crates/ui-egui/tests/it/transitions_ui.rsindex 7de14823d..603aedff5 100644--- a/crates/ui-egui/tests/it/transitions_ui.rs+++ b/crates/ui-egui/tests/it/transitions_ui.rs@@ -383,3 +383,42 @@ fn dragging_the_cut_in_effect_controls_moves_it_with_the_transition() {let back = d.transition(c.id).unwrap();assert_eq!((back["start"].as_i64(), back["duration"].as_i64()), (Some(c.start), Some(c.duration)));}++/// With Start at Cut the cut is at the transition's edge, where a press over the transition grabs+/// its In end, so the cut line is grabbed where it crosses clip A. A drag past what the clips+/// allow stops where `timeline.roll` stops.+#[test]+fn the_cut_is_grabbed_over_the_clips_and_stops_at_the_rolls_limit() {+ let mut d = Driver::demo();+ let c = d.crossing();+ d.click(&format!("timeline.transition.{}", c.id));+ let x = d.transition(c.id).unwrap();+ let (from, to) = (x["from"].as_u64().unwrap(), x["to"].as_u64().unwrap());+ d.exec("sequence.setTransition", json!({"transition": c.id, "align": "start"}));+ d.frames(3);+ let cut_of = |d: &mut Driver| {+ let q = d.exec("sequence.inspect", json!({}));+ q["video"].as_array().unwrap().iter().flat_map(|t| t["items"].as_array().unwrap().clone()).find(|i| i["clip"] == to).unwrap()["start"].as_i64().unwrap()+ };+ let start_of = |d: &mut Driver| d.transition(c.id).unwrap()["start"].as_i64().unwrap();+ let drag_cut = |d: &mut Driver, by: f64| {+ let (x0, y0, w, h, _) = d.find("effectControls.transition.timeline.cut.a").expect("the cut line over clip A");+ let (cx, cy) = (x0 + w / 2.0, y0 + h / 2.0);+ d.ok("ui.drag", json!({"from": {"x": cx, "y": cy}, "to": {"x": cx + by, "y": cy}, "steps": 8}));+ d.frames(3);+ };+ let (cut0, start0) = (cut_of(&mut d), start_of(&mut d));+ assert_eq!(start0, cut0, "Start at Cut");+ drag_cut(&mut d, 20.0);+ let (cut1, start1) = (cut_of(&mut d), start_of(&mut d));+ let moved = cut1 - cut0;+ assert!(moved > 0, "the cut moved right: {cut0} -> {cut1}");+ assert_eq!(start1, cut1, "the transition still starts at the cut");+ // far to the right: the cut stops at the roll's limit+ let far = filmcraft_time::Tick(3600 * filmcraft_time::TICKS_PER_SECOND);+ let limit =+ filmcraft_engine::commands::roll_delta(&d.harness.state().session, filmcraft_project::ClipId(from), filmcraft_project::ClipId(to), far).unwrap();+ assert!(0 < limit.0 && limit < far, "the roll has a limit: {limit:?}");+ drag_cut(&mut d, limit.0 as f64 / moved as f64 * 20.0 + 200.0);+ assert_eq!(cut_of(&mut d), cut1 + limit.0, "stopped at the limit");+}diff --git a/docs/monitors.md b/docs/monitors.mdindex bb6e520ae..d26fd3c09 100644--- a/docs/monitors.md+++ b/docs/monitors.md@@ -11,7 +11,7 @@ focused monitor (Program by default). Code: `crates/ui-egui/src/panels/monitor_v| `view.playbackRes.<full\|half\|quarter\|eighth\|sixteenth>` | View ▸ Playback Resolution | render scale while playing || `view.pausedRes.<…>` | View ▸ Paused Resolution | render scale while stopped (default Full) || `view.highQualityPlayback` | View ▸ High Quality Playback | play at the paused resolution when it is higher |-| `view.display.<composite\|alpha\|red\|green\|blue>` | View ▸ Display Mode | composite, or one channel as greyscale (colour channels premultiplied) |+| `view.display.<composite\|alpha\|red\|green\|blue>` | View ▸ Display Mode | composite, or one channel as greyscale (colour channels premultiplied). The channel modes render on the CPU instead of the GPU compositor, and Alpha renders the sequence live instead of using render previews (they are flattened over black), so playback in them is slower || `view.display.multicam` | Display Mode ▸ Multi-Camera | the Program's multi-camera view (`multicam.toggleView`) || `view.display.audioWaveform`, `view.display.videoAndWaveform` | Display Mode ▸ Audio Waveform / Video and Audio Waveform Split | Source Monitor: the clip's waveform (click to move the source playhead); audio-only clips always show it || `view.display.comparison` | Display Mode ▸ Comparison View | Program: the reference frame (left) beside the current frame; the reference starts at the playhead and is stepped or reset with the buttons under it, or `view.compare.setReference {time\|seconds}` |