FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
Program monitor: the picture follows a value that is dragged
justjohn12345d09e95663c0a
diff --git a/crates/ui-egui/src/frames.rs b/crates/ui-egui/src/frames.rsindex 6e0ef1ef0..32205a596 100644--- a/crates/ui-egui/src/frames.rs+++ b/crates/ui-egui/src/frames.rs@@ -535,10 +535,15 @@ impl FrameServer {// A new frame on screen for this view replaces the one asked for before: scrubbing// asks for one per refresh, and without this the oldest position would decode// first (or keep a decoder busy seeking to it) while the newest waits.+ //+ // A job already running for the same frame at an older revision (a value being+ // dragged asks for a new revision per refresh) is left to finish: it needs the same+ // source frames, so it holds no decoder back, and when frames take longer than a+ // refresh, cancelling each one for the next would show nothing until the mouse rests.let same_view = |k: &FrameKey| k.target == key.target && k.size == key.size;q.retain(|j| !(j.prio == 0 && !j.prefetch && same_view(&j.key)));for (k, c, prefetch) in self.shared.in_flight.lock().unwrap_or_else(|e| e.into_inner()).iter() {- if !prefetch && *k != key && same_view(k) {+ if !prefetch && same_view(k) && k.frame != key.frame {c.store(true, Ordering::Relaxed);}}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 461aa36ea..9720232be 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -200,6 +200,11 @@ pub struct FilmcraftApp {/// A paused monitor drew a stand-in (nearest cached) picture last frame: its exact frame is/// still decoding.pub(crate) monitor_inexact: bool,+ /// Per monitor: the frames it asked for on its latest paused passes, oldest first (stand-ins+ /// while the newest renders, see `panels::monitor`).+ pub(crate) monitor_asked: HashMap<String, std::collections::VecDeque<FrameKey>>,+ /// The frame whose picture the Program monitor drew last: the frame due, or its stand-in.+ pub(crate) program_shown: Option<FrameKey>,/// Consecutive frames the timeline zoom / scroll has been at rest. `ui.elements` answers from/// the frame before the last one, so its timeline rects are final from 2 on.pub(crate) timeline_still: u32,@@ -396,6 +401,8 @@ impl FilmcraftApp {pending_screenshots: Vec::new(),queued_screenshots: Vec::new(),monitor_inexact: false,+ monitor_asked: HashMap::new(),+ program_shown: None,timeline_still: 0,input_waiters: Vec::new(),next_token: 1,@@ -892,6 +899,17 @@ impl FilmcraftApp {self.textures.get(name).map(|(_, t)| (t.id(), t.size_vec2()))}+ /// The frame a named texture shows.+ pub fn texture_key(&self, name: &str) -> Option<FrameKey> {+ self.textures.get(name).map(|(k, _)| *k)+ }++ /// The frame whose picture the Program monitor drew last: the frame due at the playhead, or+ /// the stand-in shown while that one renders (`perf.stats`, tests).+ pub fn program_picture(&self) -> Option<FrameKey> {+ self.program_shown+ }+/// Get a thumbnail texture for an item at a media time (requested at low priority)./// Cache revision of a project item's own frames: media changes only when its file does/// (relink, Make Offline, proxies on/off), so its frames survive unrelated edits; other itemsdiff --git a/crates/ui-egui/src/panels/monitor.rs b/crates/ui-egui/src/panels/monitor.rsindex d98b9b4db..95ff8f7f2 100644--- a/crates/ui-egui/src/panels/monitor.rs+++ b/crates/ui-egui/src/panels/monitor.rs@@ -3,7 +3,9 @@//! Frames come from the background [`FrameServer`](crate::frames::FrameServer) at the *smaller* of//! the playback resolution and the on-screen resolution (so a small monitor never pays for 4K).//! While playing we prefetch the next frames in priority order; while scrubbing the exact frame is-//! requested first and the nearest cached frame is shown until it arrives (no black flashes).+//! requested first and the nearest cached frame is shown until it arrives (no black flashes), or+//! failing that the frame asked for a refresh earlier, so the picture follows a scrub or a value+//! that is dragged instead of waiting for the mouse to rest.use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};use filmcraft_project::ItemKind;@@ -175,18 +177,26 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)} else {app.frames.request(key, rate.tick_of(frame), scale, &project, 0);}+ let asked = asked_before(app, prefix, key, playing);let tex_name = if channel { format!("monitor-{prefix}-{display:?}") } else { format!("monitor-{prefix}") };- let (shown, exact) = if use_gpu {- let exact = app.frames.get_plan(&key).map(|p| (key, p));- let is_exact = exact.is_some();- let tex = match exact.or_else(|| app.frames.nearest_plan(key, 6)) {- Some((k, plan)) => app.gpu_present(k, &plan).map(|(id, _)| id),- None => app.gpu.as_ref().and_then(|g| g.texture),- };- (tex, is_exact)+ let (shown, on_screen) = if use_gpu {+ let found = app+ .frames+ .get_plan(&key)+ .map(|p| (key, p))+ .or_else(|| app.frames.nearest_plan(key, 6))+ .or_else(|| asked.iter().find_map(|k| app.frames.get_plan(k).map(|p| (*k, p))));+ match found {+ Some((k, plan)) => (app.gpu_present(k, &plan).map(|(id, _)| id), Some(k)),+ None => (app.gpu.as_ref().and_then(|g| g.texture), app.gpu.as_ref().and_then(|g| g.last_key)),+ }} else {- cpu_texture(app, &ctx, &tex_name, key, display)+ cpu_texture(app, &ctx, &tex_name, key, &asked, display)};+ let exact = on_screen == Some(key);+ if which == Which::Program {+ app.program_shown = on_screen;+ }if !playing && !exact {app.monitor_inexact = true;}@@ -207,7 +217,7 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)app.frames.request(rkey, rate.tick_of(rf), scale, &project, 1);let rpic = fit(ra, frame_size.0 as f32, frame_size.1 as f32);ui.painter().rect_filled(rpic, 0.0, t.monitor_bg);- if let (Some(tex), _) = cpu_texture(app, &ctx, &format!("monitor-{prefix}-ref"), rkey, DisplayMode::Composite) {+ if let (Some(tex), _) = cpu_texture(app, &ctx, &format!("monitor-{prefix}-ref"), rkey, &[], DisplayMode::Composite) {ui.painter().image(tex, rpic, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);}app.auto.add("program.compare.reference", rpic, "reference frame");@@ -342,20 +352,63 @@ pub fn show(app: &mut FilmcraftApp, ui: &mut egui::Ui, rect: Rect, which: Which)transport(app, ui, row3, which);}-/// A monitor texture from the CPU frame path: the exact frame, else the nearest cached one, with-/// the display mode's channel mapping. Returns (texture, exact).-fn cpu_texture(app: &mut FilmcraftApp, ctx: &egui::Context, name: &str, key: FrameKey, mode: DisplayMode) -> (Option<egui::TextureId>, bool) {- let upload = |app: &mut FilmcraftApp, k: FrameKey, img: &crate::frames::Rgba| {- if mode.is_channel() { app.texture_for_mapped(ctx, name, k, img, |i| monitor_view::channel_view(i, mode)) } else { app.texture_for(ctx, name, k, img) }- };- if let Some(img) = app.frames.get(&key) {- return (Some(upload(app, key, &img)), true);+/// How many of a paused monitor's latest requests are remembered ([`asked_before`]): about a+/// second of refreshes, so a frame that took several refreshes to render is still known when it+/// is ready.+const ASKED_KEYS: usize = 64;++/// Note that the monitor `prefix` asks for `key`, and return the frames it asked for on the passes+/// before, newest first: the stand-ins for `key` while it renders.+///+/// A value that is dragged asks for a new revision on every pass, and a scrub for a new frame, so+/// the frame asked for is never the one that is ready; the one asked for a pass earlier usually+/// is, and showing it keeps the picture one pass behind the mouse instead of frozen until the+/// mouse rests. Playback has its own schedule and remembers nothing (what was on screen before+/// Play is no stand-in for where it stopped).+fn asked_before(app: &mut FilmcraftApp, prefix: &str, key: FrameKey, playing: bool) -> Vec<FrameKey> {+ let asked = app.monitor_asked.entry(prefix.to_string()).or_default();+ if playing {+ asked.clear();+ return Vec::new();+ }+ // another sequence or clip: its pictures are not this one's+ asked.retain(|k| k.target == key.target && *k != key);+ let before: Vec<FrameKey> = asked.iter().rev().copied().collect();+ asked.push_back(key);+ while asked.len() > ASKED_KEYS {+ asked.pop_front();+ }+ before+}++/// A monitor texture from the CPU frame path: the exact frame, else the nearest cached one before+/// it, else the newest ready one of `asked` (see [`asked_before`]), with the display mode's+/// channel mapping. Returns the texture and the frame it shows.+fn cpu_texture(+ app: &mut FilmcraftApp,+ ctx: &egui::Context,+ name: &str,+ key: FrameKey,+ asked: &[FrameKey],+ mode: DisplayMode,+) -> (Option<egui::TextureId>, Option<FrameKey>) {+ let found = app+ .frames+ .get(&key)+ .map(|img| (key, img))+ .or_else(|| (1..=6).map(|d| FrameKey { frame: key.frame.saturating_sub(d), ..key }).find_map(|k| app.frames.get(&k).map(|img| (k, img))))+ .or_else(|| asked.iter().find_map(|k| app.frames.get(k).map(|img| (*k, img))));+ match found {+ Some((k, img)) => {+ let tex = if mode.is_channel() {+ app.texture_for_mapped(ctx, name, k, &img, |i| monitor_view::channel_view(i, mode))+ } else {+ app.texture_for(ctx, name, k, &img)+ };+ (Some(tex), Some(k))+ }+ None => (app.texture_existing(name).map(|(id, _)| id), app.texture_key(name)),}- let tex = match app.frames.nearest(key.target, key.frame, key.size, key.revision, 6) {- Some(img) => Some(upload(app, FrameKey { frame: key.frame - 1, ..key }, &img)),- None => app.texture_existing(name).map(|(id, _)| id),- };- (tex, false)}pub fn quantize_scale(s: f32) -> f32 {diff --git a/crates/ui-egui/src/perf.rs b/crates/ui-egui/src/perf.rsindex 79df3c52c..b5b44f1b3 100644--- a/crates/ui-egui/src/perf.rs+++ b/crates/ui-egui/src/perf.rs@@ -31,6 +31,13 @@ pub fn stats(app: &FilmcraftApp) -> Value {frames["renderCostMs"] = json!(app.frames.render_cost() * 1e3);frames["cache"] = json!({"images": images, "imageMB": image_bytes as f64 / 1e6, "plans": plans, "planMB": plan_bytes as f64 / 1e6});v["frames"] = frames;+ // the Program monitor's picture against what is due: how far a drag or a scrub is ahead of it+ v["monitor"] = json!({+ "frame": app.program_picture().map(|k| k.frame),+ "revision": app.program_picture().map(|k| k.revision),+ "projectRevision": app.session.revision,+ "playheadFrame": app.session.active_sequence().map(|q| q.settings.frame_rate.frame_at(app.session.playhead())),+ });v["ui"] = json!({"fps": app.fps, "frameMs": if app.fps > 0.0 { 1000.0 / app.fps as f64 } else { 0.0 }});v["process"] = json!({"cpuS": crate::frames::process_cpu_time().map(|d| d.as_secs_f64())});vdiff --git a/crates/ui-egui/tests/perf_ui.rs b/crates/ui-egui/tests/perf_ui.rsindex 55b52874c..5b9d6c845 100644--- a/crates/ui-egui/tests/perf_ui.rs+++ b/crates/ui-egui/tests/perf_ui.rs@@ -1,6 +1,7 @@//! `perf.stats` through the control channel (headless app under `egui_kittest`): the control//! method and the command id (what MCP `command_run` sends) both return the engine's decode-//! counters plus playback, frame-worker and UI timings.+//! counters plus playback, frame-worker and UI timings. Also how closely the Program monitor's+//! picture follows a value that is dragged and a scrub.use std::sync::mpsc::{Sender, channel};@@ -8,6 +9,7 @@ use egui_kittest::Harness;use filmcraft_engine::Session;use filmcraft_ui_egui::FilmcraftApp;use filmcraft_ui_egui::control::ControlRequest;+use filmcraft_ui_egui::frames::{FrameKey, Target};use serde_json::{Value, json};struct Driver {@@ -49,6 +51,42 @@ impl Driver {}panic!("no reply to {method}");}++ fn exec(&mut self, command: &str, params: Value) -> Value {+ self.ok("engine.execute", json!({"command": command, "params": params}))+ }++ /// The frame due in the Program monitor: `shown` at the project's revision and the playhead.+ fn due(&self, shown: FrameKey) -> FrameKey {+ let s = &self.harness.state().session;+ let frame = s.active_sequence().unwrap().settings.frame_rate.frame_at(s.playhead());+ FrameKey { frame, revision: s.revision, ..shown }+ }++ /// Wait (without a UI pass) until the frame workers have `key` ready.+ fn ready(&self, key: FrameKey) {+ for _ in 0..2000 {+ if self.harness.state().frames.is_ready(&key) {+ return;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ panic!("{key:?} was never rendered");+ }++ /// The Program monitor at rest: the picture of the frame due is on screen.+ fn settled(&mut self) -> FrameKey {+ for _ in 0..2000 {+ self.frames(1);+ if let Some(k) = self.harness.state().program_picture()+ && k == self.due(k)+ {+ return k;+ }+ std::thread::sleep(std::time::Duration::from_millis(5));+ }+ panic!("the Program monitor never showed its frame");+ }}#[test]@@ -77,3 +115,78 @@ fn perf_stats_reports_playback_frames_and_decode() {let c = d.ok("engine.execute", json!({"command": "perf.stats"}));assert!(c["frames"]["workers"].as_u64().unwrap() >= 1 && c["decode"].is_object(), "{c}");}++/// A value dragged in Effect Controls changes on every UI pass, so the frame the monitor asks for+/// is never ready on the pass that asks. The monitor shows the frame of the pass before (ready by+/// then) and stays one pass behind the mouse; it used to keep the picture from before the drag+/// until the mouse rested.+#[test]+fn program_monitor_follows_a_value_that_changes_every_pass() {+ let mut d = Driver::demo();+ let clip = d.exec("sequence.inspect", json!({}))["video"][0]["items"][0]["clip"].as_u64().unwrap();+ d.exec("playhead.set", json!({"seconds": 1.0}));+ let at_rest = d.settled();+ let mut before = at_rest;+ for i in 1..=12 {+ // one change and one UI pass, as a mouse move while dragging the value+ d.exec("effects.setParam", json!({"clip": clip, "effect": "motion", "param": "scale", "value": 100.0 - i as f64}));+ let due = d.due(at_rest);+ assert_ne!(due.revision, before.revision, "each change is a new revision");+ let shown = d.harness.state().program_picture().unwrap();+ assert!(shown.revision >= before.revision, "change {i}: the picture is at most one change behind, shown {shown:?}, due {due:?}");+ d.ready(due);+ before = due;+ }+ assert_eq!(d.settled().revision, before.revision, "at rest the picture is the frame due");+}++/// The same for a scrub, backwards: every pass asks for an earlier frame, and no cached frame+/// lies before it.+#[test]+fn program_monitor_follows_a_backward_scrub() {+ let mut d = Driver::demo();+ d.exec("playhead.set", json!({"frame": 60}));+ let at_rest = d.settled();+ let mut before = at_rest;+ for i in 1..=12 {+ d.exec("playhead.set", json!({"frame": 60 - i * 3}));+ let due = d.due(at_rest);+ assert_eq!(due.frame, 60 - i * 3);+ let shown = d.harness.state().program_picture().unwrap();+ assert!(shown.frame <= before.frame, "step {i}: the picture is at most one step behind, shown {shown:?}, due {due:?}");+ d.ready(due);+ before = due;+ }+ assert_eq!(d.settled().frame, before.frame);+}++/// A frame being rendered is kept when the same frame is asked for at a newer revision: frames+/// that take longer than a refresh (CPU effects) were each cancelled by the next step of a drag,+/// so none was ever shown until the mouse rested.+#[test]+fn a_newer_revision_keeps_the_frame_being_rendered() {+ let d = Driver::demo();+ let app = d.harness.state();+ let idle = || {+ for _ in 0..200_000 {+ if app.frames.queue_len() == 0 {+ return;+ }+ std::thread::sleep(std::time::Duration::from_micros(50));+ }+ panic!("the frame queue never emptied");+ };+ // the clip with Lumetri Color at full resolution: tens of milliseconds on the CPU+ let seq = app.session.state.active_sequence.unwrap();+ let rate = app.session.active_sequence().unwrap().settings.frame_rate;+ let frame = rate.frame_at(filmcraft_time::Tick::from_seconds_f64(15.0));+ let key = |revision| FrameKey { target: Target::Sequence(seq), frame, size: 1000, revision, draft: false };+ let project = app.session.project.clone();+ idle();+ app.frames.request(key(9001), rate.tick_of(frame), 1.0, &project, 0);+ idle(); // a worker has taken it+ app.frames.request(key(9002), rate.tick_of(frame), 1.0, &project, 0);+ // both arrive, in either order: the one that was rendering was not cancelled for the newer+ d.ready(key(9002));+ d.ready(key(9001));+}diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex 6419e154a..ff86fb3bd 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -39,7 +39,7 @@ Methods (handlers in `crates/ui-egui/src/control.rs`):| `ui.playback` | `{action: play|stop|toggle, speed?}` | || `ui.screenshot` | `{path?, panel?}` | PNG of the window or one panel; fails after 10 s when no frame is presented (window hidden, display asleep) || `ui.resize`, `ui.focus`, `app.quit` | | `ui.focus` is the only request that activates the app and takes keyboard focus |-| `perf.stats` | – | performance counters (also the command `perf.stats`, so `engine.execute` and MCP `command_run` reach it; headless sessions return the engine part). `decode`: GOP-cache requests / hits / `cacheHitRate`, decoder seeks, samples decoded and skipped while catching up, `draftFrames` (decoded in draft mode), `h264Threads` (frame-threading workers per H.264 decoder), `liveDecoders` (sources holding a decoder now), `cacheMB` / `cacheBudgetMB` (decoded frames all sources hold, and the shared budget), `planePoolMB` / `planesReused` (idle plane buffers of evicted frames, and planes decoded into a recycled one), decoder ms (total and per sample), `framesDecoded`, `hardware` (Settings ▸ Playback ▸ Hardware decoding: `enabled`, pictures from hardware decoders `frames` vs `softwareFrames`, `sessions`, `declined` streams, mid-stream `fallbacks`); `playback`: playing, shown / dropped frames and `dropRate` of the current or last play, resolution, `draftDecode` (Settings ▸ Playback ▸ Draft decoding), `audio` (desktop: sound is mixed 200 ms ahead of the device; device `callbacks`, `underruns` and `missingFrames` played as silence because the mixer fell behind, `minLeadMs` the least sound left buffered); `frames`: frame-worker jobs, cancelled, `requestHitRate`, `decodeMs` / `renderMs` (mean, p50, p95 of the last 256 jobs), queue, render-cost estimate, cache use; `ui`: fps and frame ms; `process`: CPU seconds; `media`, `jobs`. Counters are cumulative: diff two readings to measure an interval ([performance.md](performance.md)) |+| `perf.stats` | – | performance counters (also the command `perf.stats`, so `engine.execute` and MCP `command_run` reach it; headless sessions return the engine part). `decode`: GOP-cache requests / hits / `cacheHitRate`, decoder seeks, samples decoded and skipped while catching up, `draftFrames` (decoded in draft mode), `h264Threads` (frame-threading workers per H.264 decoder), `liveDecoders` (sources holding a decoder now), `cacheMB` / `cacheBudgetMB` (decoded frames all sources hold, and the shared budget), `planePoolMB` / `planesReused` (idle plane buffers of evicted frames, and planes decoded into a recycled one), decoder ms (total and per sample), `framesDecoded`, `hardware` (Settings ▸ Playback ▸ Hardware decoding: `enabled`, pictures from hardware decoders `frames` vs `softwareFrames`, `sessions`, `declined` streams, mid-stream `fallbacks`); `playback`: playing, shown / dropped frames and `dropRate` of the current or last play, resolution, `draftDecode` (Settings ▸ Playback ▸ Draft decoding), `audio` (desktop: sound is mixed 200 ms ahead of the device; device `callbacks`, `underruns` and `missingFrames` played as silence because the mixer fell behind, `minLeadMs` the least sound left buffered); `frames`: frame-worker jobs, cancelled, `requestHitRate`, `decodeMs` / `renderMs` (mean, p50, p95 of the last 256 jobs), queue, render-cost estimate, cache use; `monitor`: the `frame` and `revision` of the picture the Program monitor shows against `playheadFrame` and `projectRevision` (how far a drag or a scrub is ahead of the picture); `ui`: fps and frame ms; `process`: CPU seconds; `media`, `jobs`. Counters are cumulative: diff two readings to measure an interval ([performance.md](performance.md)) |**Selection or explicit targets.** A command that acts on the selection is "not available right now" whennothing is selected. When `params` name the targets under a key the command documents (`clips` /diff --git a/docs/testing.md b/docs/testing.mdindex a1640bbbf..eb5f7fc1b 100644--- a/docs/testing.md+++ b/docs/testing.md@@ -33,6 +33,7 @@ FILMCRAFT_REQUIRE_ORACLES=1 cargo test --workspace # CI: missing ffmpeg fails| Remix | `crates/audio-dsp/src/remix.rs`, `crates/render/src/remix.rs`, `crates/engine/src/remix_tests.rs`, `crates/ui-egui/tests/remix_ui.rs` | generated rhythmic music (Rust-synthesised drums, bass, chord sections at 90–128 BPM, 22.05/44.1/48 kHz): tempo within 0.3 BPM, every beat within 10 ms (measured ≤ 8.9 ms); remix targets from 0.4× to 2.2× the source within one beat (measured ≤ 12 ms at default sliders), every cut on a detected beat, intro and outro kept, pieces ≥ 4 beats, deterministic; silence, tone and noise refused; rendering independent of request cuts, source-exact outside the 20 ms equal-power crossfades, no clicks; the engine's mix equals the source pieces (< 1e-5); undo, redo and revert exact; overlaps refused; Remix Properties dialog and Remix tool drag driven by automation id || Oracle | `crates/*/tests/*oracle*.rs`, `conformance.rs` | compare with ffmpeg/ffprobe (§2) || Robustness / fuzz | `*/tests/robustness.rs`, `*/tests/fuzz.rs` | seeded mutation and truncation of real and synthetic files; nothing may panic |+| Program monitor while dragging | `crates/ui-egui/tests/perf_ui.rs` | headless: a parameter changed on every UI pass (a value dragged in Effect Controls or Properties) and a backward scrub leave the Program monitor's picture at most one step behind (it shows the frame asked for the pass before while the frame due renders; it used to freeze until the mouse rested); a frame still rendering is kept when the same frame is asked for at a newer revision, so frames slower than a refresh (CPU effects) are shown too; `perf.stats` reports the picture's frame and revision against the playhead and the project || Performance | `*/tests/perf.rs` (`#[ignore]`) | §5 |Commit `*.proptest-regressions` files so failing cases are re-run.