Skip to content

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

M4.5: fix UI hang after preview render (macOS App Nap starved the hidden app; ui.screenshot waits forever)

Brandon Thomas5110b694d8c9
diff --git a/Cargo.lock b/Cargo.lock
index d9e0f58fc..f57a5227c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1296,6 +1296,7 @@ dependencies = [
"filmcraft-ui-egui",
"log",
"muda",
+ "objc2-foundation 0.3.2",
"rfd",
"serde_json",
]
diff --git a/apps/filmcraft/Cargo.toml b/apps/filmcraft/Cargo.toml
index 2702615fa..c93aee71e 100644
--- a/apps/filmcraft/Cargo.toml
+++ b/apps/filmcraft/Cargo.toml
@@ -22,3 +22,4 @@ chrono = { version = "0.4", default-features = false, features = ["clock"] }
[target.'cfg(target_os = "macos")'.dependencies]
muda = "0.21"
+objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSProcessInfo", "NSString"] }
diff --git a/apps/filmcraft/src/app_nap.rs b/apps/filmcraft/src/app_nap.rs
new file mode 100644
index 000000000..5aaa5f171
--- /dev/null
+++ b/apps/filmcraft/src/app_nap.rs
@@ -0,0 +1,37 @@
+//! Opt out of macOS App Nap.
+//!
+//! When the window is hidden or behind other windows (always the case when the app is driven over
+//! the control channel, and common while previews render or a sequence plays on a second
+//! display), App Nap lowers every thread of the process to background priority (4) and defers
+//! its timers. On a busy machine the app then gets no CPU at all: the UI thread stays runnable
+//! inside the run loop's timer callout, frame workers and the control channel stall, and the app
+//! looks hung (seen after Render In to Out + play: 0 % CPU, every thread at priority 4, recovered
+//! instantly with App Nap off). An editor must keep playing and rendering in the background, so
+//! the process holds a user-initiated, latency-critical activity for its whole lifetime, which
+//! is what `NSAppSleepDisabled` does for an app bundle. Idle system sleep stays allowed.
+
+/// Begin the activity (macOS); returns whether it is held. Call once at startup.
+pub fn disable() -> bool {
+ #[cfg(target_os = "macos")]
+ {
+ use objc2_foundation::{NSActivityOptions, NSProcessInfo, NSString};
+ let options = NSActivityOptions::UserInitiatedAllowingIdleSystemSleep | NSActivityOptions::LatencyCritical;
+ let reason = NSString::from_str("FilmCraft plays and renders video in the background");
+ let token = NSProcessInfo::processInfo().beginActivityWithOptions_reason(options, &reason);
+ // The activity lasts while the token is alive: keep it for the life of the process.
+ std::mem::forget(token);
+ true
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ false
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ #[test]
+ fn app_nap_is_disabled_on_macos() {
+ assert_eq!(super::disable(), cfg!(target_os = "macos"));
+ }
+}
diff --git a/apps/filmcraft/src/main.rs b/apps/filmcraft/src/main.rs
index b4111dd8f..c5f691d66 100644
--- a/apps/filmcraft/src/main.rs
+++ b/apps/filmcraft/src/main.rs
@@ -12,6 +12,7 @@
//! asking, `--no-recover` starts without asking (the changes stay available via File ▸ Recover
//! Unsaved Changes…).
+mod app_nap;
mod audio;
mod control_server;
#[cfg(target_os = "macos")]
@@ -24,6 +25,7 @@ use filmcraft_ui_egui::FilmcraftApp;
use serde_json::json;
fn main() -> eframe::Result {
+ app_nap::disable();
let mut control_port: Option<u16> = std::env::var("FILMCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut files = Vec::new();
let mut demo = true;
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 90fa8668b..595f77652 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -79,6 +79,9 @@ pub struct Playback {
pub meter: frames::PlaybackMeter,
}
+/// How long `ui.screenshot` waits for the window to present the frame.
+const SCREENSHOT_TIMEOUT_S: f64 = 10.0;
+
pub struct FilmcraftApp {
pub session: Session,
pub ui: UiState,
@@ -101,7 +104,8 @@ pub struct FilmcraftApp {
pub(crate) loudness: Option<(filmcraft_audio_dsp::LoudnessMeter, i64)>,
/// Status message last shown and when it first appeared (messages expire after a few seconds).
status_seen: (String, f64),
- pending_screenshots: Vec<(u64, Option<String>, Option<[f32; 4]>, Sender<Value>)>,
+ /// Screenshots waiting for their frame: (token, path, crop, reply, give-up time).
+ pending_screenshots: Vec<(u64, Option<String>, Option<[f32; 4]>, Sender<Value>, f64)>,
queued_screenshots: Vec<(u64, f64, u32)>,
input_waiters: Vec<Sender<Value>>,
next_token: u64,
@@ -576,7 +580,7 @@ impl FilmcraftApp {
self.next_token += 1;
let settle = ctx.input(|i| i.time) + 0.25;
self.queued_screenshots.push((token, settle, 0));
- self.pending_screenshots.push((token, path, crop, reply));
+ self.pending_screenshots.push((token, path, crop, reply, settle + SCREENSHOT_TIMEOUT_S));
}
}
}
@@ -596,8 +600,20 @@ impl FilmcraftApp {
true
}
});
- if any || !self.pending_screenshots.is_empty() {
+ // A hidden window (or a sleeping display) never presents, so its screenshot never
+ // arrives: give up instead of waiting (and repainting) forever.
+ self.pending_screenshots.retain(|(.., reply, deadline)| {
+ if now > *deadline {
+ let _ = reply.send(json!({"ok": false, "error": "no frame was presented (window hidden or display asleep)"}));
+ false
+ } else {
+ true
+ }
+ });
+ if any {
ctx.request_repaint();
+ } else if !self.pending_screenshots.is_empty() {
+ ctx.request_repaint_after(std::time::Duration::from_millis(16));
}
}
@@ -620,7 +636,7 @@ impl FilmcraftApp {
});
for (token, image) in events {
if let Some(i) = self.pending_screenshots.iter().position(|(t, ..)| *t == token) {
- let (_, path, crop, reply) = self.pending_screenshots.remove(i);
+ let (_, path, crop, reply, _) = self.pending_screenshots.remove(i);
let r = control::save_screenshot(ctx, &image, path.as_deref(), crop);
let _ = reply.send(r);
}
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index ecf201357..c54101023 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -2,7 +2,9 @@
## Desktop control channel
`filmcraft --control 9876` (or `FILMCRAFT_CONTROL_PORT`) listens on `127.0.0.1:<port>` (loopback only).
-One JSON request per line → one JSON reply per line:
+One JSON request per line → one JSON reply per line. The app opts out of macOS App Nap
+(`apps/filmcraft/src/app_nap.rs`): a hidden window would otherwise drop the whole process to
+background priority, and on a busy machine it would stop answering.
```json
{"id": 1, "method": "engine.execute", "params": {"command": "sequence.addEdit", "params": {"seconds": 3}}}
@@ -25,7 +27,7 @@ Methods (handlers in `crates/ui-egui/src/control.rs`):
| `ui.key` / `ui.type` | `{key}` (`Cmd+K`, `Space`…) / `{text}` | keyboard |
| `ui.timeline.hit` / `ui.timeline.locate` | `{x,y}` / `{clip, edge?}` | timeline hit-testing |
| `ui.playback` | `{action: play|stop|toggle, speed?}` | |
-| `ui.screenshot` | `{path?, panel?}` | PNG of the window or one panel |
+| `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` | | |
Element ids are stable, e.g. `timeline.clip.<id>`, `timeline.track.V1.lock`, `tools.Razor`,