Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

feat(start): a launch that dies while starting is followed by one that draws in software (#339, #378, #389, #242)

Jareerb5e6c08686b0
diff --git a/src/crates/concat-host/Cargo.toml b/src/crates/concat-host/Cargo.toml
index 36d4b987..2fa88ed5 100644
--- a/src/crates/concat-host/Cargo.toml
+++ b/src/crates/concat-host/Cargo.toml
@@ -63,6 +63,8 @@ windows-sys = { version = "0.61", features = [
"Win32_System_LibraryLoader",
# machine.rs: the Windows version and the CPU's name.
"Win32_System_Registry",
+ # jobs.rs: whether the process that left a mark is still running.
+ "Win32_System_Threading",
] }
[lints]
diff --git a/src/crates/concat-host/src/jobs.rs b/src/crates/concat-host/src/jobs.rs
index 6c7b064a..c9d0fcac 100644
--- a/src/crates/concat-host/src/jobs.rs
+++ b/src/crates/concat-host/src/jobs.rs
@@ -138,10 +138,25 @@ impl Tripwire {
Tripwire { path }
}
- /// Whether a job on `dir` was running when the process last died.
- /// Only meaningful while no job on `dir` is running in this process.
+ /// The mark's own file.
+ pub fn path(&self) -> &std::path::Path {
+ &self.path
+ }
+
+ /// Whether a job on `dir` was running when its process died: the mark
+ /// is there and the process that left it is not running any more. A
+ /// second Concat open beside the first sees the first's mark as a job
+ /// running, not as a death. Only meaningful while no job on `dir` is
+ /// running in this process.
pub fn tripped(dir: &std::path::Path) -> bool {
- dir.join(Self::FILE).exists()
+ let Ok(text) = std::fs::read_to_string(dir.join(Self::FILE)) else {
+ return false;
+ };
+ match text.trim().parse::<u32>() {
+ Ok(pid) => pid == std::process::id() || !alive(pid),
+ // A mark with no process in it was left by a death.
+ Err(_) => true,
+ }
}
}
@@ -151,10 +166,68 @@ impl Drop for Tripwire {
}
}
+/// Whether process `pid` is running.
+#[cfg(unix)]
+fn alive(pid: u32) -> bool {
+ let Ok(pid) = libc::pid_t::try_from(pid) else {
+ return false;
+ };
+ // SAFETY: signal 0 sends nothing; it only asks whether `pid` could be
+ // signalled, and touches no memory of ours.
+ let answer = unsafe { libc::kill(pid, 0) };
+ answer == 0 || std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
+}
+
+/// Whether process `pid` is running.
+#[cfg(windows)]
+fn alive(pid: u32) -> bool {
+ use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
+ use windows_sys::Win32::System::Threading::{
+ GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
+ };
+ // SAFETY: a handle opened here, read once and closed once; a null one
+ // (no such process, or one we may not open) is never used.
+ unsafe {
+ let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if process.is_null() {
+ return false;
+ }
+ let mut code = 0u32;
+ let read = GetExitCodeProcess(process, &mut code);
+ CloseHandle(process);
+ read != 0 && code == STILL_ACTIVE as u32
+ }
+}
+
+#[cfg(not(any(unix, windows)))]
+fn alive(_pid: u32) -> bool {
+ false
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn a_mark_left_by_a_running_process_is_not_a_death() {
+ let dir =
+ std::env::temp_dir().join(format!("concat-tripwire-alive-{}", std::process::id()));
+ let _ = std::fs::create_dir_all(&dir);
+ // This test's own parent is running; pid 1 always is on a unix.
+ let running = if cfg!(unix) {
+ 1
+ } else {
+ std::process::id() + 0
+ };
+ std::fs::write(dir.join("running"), running.to_string()).expect("writes");
+ if cfg!(unix) {
+ assert!(!Tripwire::tripped(&dir), "a live process's mark");
+ }
+ std::fs::write(dir.join("running"), "not a pid").expect("writes");
+ assert!(Tripwire::tripped(&dir), "a mark with no process in it");
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
#[test]
fn a_tripwire_is_left_only_by_a_job_that_never_ended() {
let dir = std::env::temp_dir().join(format!("concat-tripwire-{}", std::process::id()));
diff --git a/src/crates/concat-render/src/gpu.rs b/src/crates/concat-render/src/gpu.rs
index 3f233c0c..c4f9d78a 100644
--- a/src/crates/concat-render/src/gpu.rs
+++ b/src/crates/concat-render/src/gpu.rs
@@ -720,6 +720,12 @@ impl WgpuCompositor {
/// then every API wgpu was built with. `software_only` leaves the
/// hardware adapters out.
fn own_api_first(software_only: bool) -> Option<Self> {
+ // CONCAT_GPU=software - set by hand, or by a safe start after a
+ // launch the GPU's driver killed - keeps the compositor off the GPU
+ // too, so an export or a card does not meet that driver either.
+ let software_only = software_only
+ || std::env::var("CONCAT_GPU")
+ .is_ok_and(|value| value.trim().eq_ignore_ascii_case("software"));
let own = if cfg!(target_vendor = "apple") {
wgpu::Backends::METAL
} else if cfg!(windows) {
diff --git a/src/crates/concat/locales/en.json b/src/crates/concat/locales/en.json
index a20f72b4..5303d31c 100644
--- a/src/crates/concat/locales/en.json
+++ b/src/crates/concat/locales/en.json
@@ -401,6 +401,9 @@
"settings.playhead": "Playhead",
"settings.proxies": "Proxies",
"settings.proxiesHint": "Off, playback reads your files as they are. On, each video larger than HD gets a smaller copy, made once in the background, for smoother playback at Half and Quarter.",
+ "settings.gpu": "Draw on the GPU",
+ "settings.gpuHint": "Off, the window and the preview draw in software: slower, but out of the way of a graphics driver that closes Concat. It turns off by itself if Concat closes while starting. Takes effect the next time Concat starts.",
+ "settings.gpuNextStart": "Concat will draw this way from the next time it starts.",
"settings.rose": "Rose",
"settings.runsLocally": "Runs locally",
"settings.scale": "Scale",
@@ -476,6 +479,7 @@
"speech.voice": "Voice",
"speech.voiceAddedTimeline": "Voice added to the timeline",
"speech.voiceFrom": "Voice from",
+ "start.safeMode": "Concat closed while starting last time, so it is drawing in software now: slower, but it opens. To try the graphics card again, turn on Draw on the GPU in Settings > General.",
"start.choose": "Choose…",
"start.chooseAFolder": "Choose a folder",
"start.chooseWhereProjectFolder": "Choose where the project folder should go",
diff --git a/src/crates/concat/src/lib.rs b/src/crates/concat/src/lib.rs
index 1f47a1ff..bbb29375 100644
--- a/src/crates/concat/src/lib.rs
+++ b/src/crates/concat/src/lib.rs
@@ -204,6 +204,8 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
}
}
+ let (startup_mark, safe) = safe_start();
+
// The shell doesn't exist yet - it needs the window the backend is about
// to help create - but `Shell::with` is a no-op until `Shell::install`
// runs, and by the time an OS drop can actually happen, it has. Import
@@ -251,6 +253,9 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
// first thing the window says.
let mut studio = Studio::new(host);
studio.set_phone(phone);
+ if safe {
+ studio.notify(&i18n::t("start.safeMode"), false);
+ }
studio.reload_packages(false);
studio.watch_packages();
let dark = studio.prefs.dark.unwrap_or(true);
@@ -1637,6 +1642,9 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
app.on_settings_proxies_changed(on_window!(|state, on: bool| {
state.handle(Msg::Settings(SettingsMsg::ProxiesChanged(on)));
}));
+ app.on_settings_gpu_changed(on_window!(|state, on: bool| {
+ state.handle(Msg::Settings(SettingsMsg::GpuChanged(on)));
+ }));
app.on_settings_magnetic_changed(on_window!(|state, on: bool| {
state.handle(Msg::Settings(SettingsMsg::MagneticChanged(on)));
}));
@@ -2072,6 +2080,15 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
},
);
+ // A launch that has run this long was not killed by its start; the
+ // mark goes, so the next one is not started safe for nothing.
+ let started = startup_mark.as_ref().map(|mark| mark.path().to_owned());
+ slint::Timer::single_shot(SAFE_AFTER, move || {
+ if let Some(path) = started {
+ let _ = std::fs::remove_file(path);
+ }
+ });
+
let result = app.run();
drop(reader_sweep);
log::info!("close: event loop exited (ok={})", result.is_ok());
@@ -2081,11 +2098,54 @@ fn start(project: Option<std::path::PathBuf>, smoke: bool) -> Result<(), slint::
// anything else can end the process, and the exit says it failed.
if let Err(error) = &result {
log::error!("close: the window could not run: {error}");
+ // The mark stays: the next launch starts safe.
+ std::mem::forget(startup_mark);
leave(1);
}
+ drop(startup_mark);
leave(0);
}
+/// How long a launch runs before it counts as having started.
+const SAFE_AFTER: std::time::Duration = std::time::Duration::from_secs(15);
+
+/// Safe start: whether this launch draws on the software rasteriser
+/// because the last one died while starting, and the mark that says this
+/// one is starting.
+///
+/// Every recent release met a Windows driver that closed the app in its
+/// first seconds - a new one each time (#339, #378, #389, #242) - and a
+/// launch check on a CI machine meets none of them. A launch that dies
+/// before [`SAFE_AFTER`] leaves its mark; the next one finds it, draws on
+/// WARP or lavapipe instead of the GPU, and keeps doing so - a driver that
+/// killed one launch kills the next, and starting on the GPU every other
+/// time would crash every other time. Slower, and it opens. Settings >
+/// General's GPU switch goes back. Only on Windows and Linux, which have a
+/// software rasteriser to draw on; a Mac has none, and a phone's backend
+/// picks its own way to draw.
+fn safe_start() -> (Option<concat_host::jobs::Tripwire>, bool) {
+ if !cfg!(any(windows, target_os = "linux")) {
+ return (None, false);
+ }
+ let Ok(dirs) = concat_host::AppDirs::locate() else {
+ return (None, false);
+ };
+ let mark = dirs.data.join("startup");
+ let mut preferences = prefs::Preferences::load(&dirs);
+ let safe = concat_host::jobs::Tripwire::tripped(&mark) && !preferences.software_gpu;
+ if safe {
+ log::warn!("start: the last launch closed while starting; drawing in software from now on");
+ preferences.software_gpu = true;
+ preferences.save(&dirs);
+ }
+ if preferences.software_gpu && std::env::var_os("CONCAT_GPU").is_none() {
+ // SAFETY: the process is single-threaded here, as for the scale
+ // above: nothing reads the environment concurrently.
+ unsafe { std::env::set_var("CONCAT_GPU", "software") };
+ }
+ (Some(concat_host::jobs::Tripwire::arm(&mark)), safe)
+}
+
/// Ends the process with `code`, the log flushed first, and the threads
/// still running - the GPU's, the engine's, the audio output's - not
/// waited on.
diff --git a/src/crates/concat/src/panes/settings.rs b/src/crates/concat/src/panes/settings.rs
index 1472f601..4943145b 100644
--- a/src/crates/concat/src/panes/settings.rs
+++ b/src/crates/concat/src/panes/settings.rs
@@ -46,6 +46,9 @@ pub enum SettingsMsg {
PlayheadStopsChanged(bool),
/// The proxies switch: whether large files get a smaller copy to play.
ProxiesChanged(bool),
+ /// The GPU switch: on, the window and the compositor draw on the GPU;
+ /// off, in software. Read at the next launch.
+ GpuChanged(bool),
/// The magnetic timeline switch; the tray's button is the same fact.
MagneticChanged(bool),
DownloadSourceChanged(i32),
@@ -281,6 +284,11 @@ impl SettingsPane {
// straight away (refresh_art's stamp holds the switch);
// off, playback reads the files from the next frame.
}
+ SettingsMsg::GpuChanged(on) => {
+ studio.prefs.software_gpu = !on;
+ studio.prefs.save(&studio.host.dirs);
+ studio.notify(&t("settings.gpuNextStart"), false);
+ }
SettingsMsg::MagneticChanged(on) => {
studio.prefs.magnetic = on;
studio.prefs.save(&studio.host.dirs);
@@ -772,6 +780,8 @@ impl SettingsPane {
.unwrap_or(2) as i32,
playhead_stops: self.playhead_stops,
proxies: studio.prefs.proxies,
+ gpu: !studio.prefs.software_gpu,
+ gpu_switchable: cfg!(any(windows, target_os = "linux")),
magnetic: studio.prefs.magnetic,
download_source: self.download_source as i32,
download_base: self.download_base.as_str().into(),
diff --git a/src/crates/concat/src/prefs.rs b/src/crates/concat/src/prefs.rs
index 0d625e58..537e34ea 100644
--- a/src/crates/concat/src/prefs.rs
+++ b/src/crates/concat/src/prefs.rs
@@ -64,6 +64,11 @@ pub struct Preferences {
/// may not take (an HDR one opened NVENC first), and the person who
/// wants one for smoother playback turns it on in Settings.
pub proxies: bool,
+ /// Drawing in software: the window and the compositor on the
+ /// platform's software rasteriser (WARP, lavapipe) instead of the GPU.
+ /// Set by itself when a launch died while starting (see `safe_start`),
+ /// and turned off again in Settings > General. Read at launch.
+ pub software_gpu: bool,
/// The magnetic timeline: a delete and a trim close the gap they would
/// leave, on the lane they happen on. Off by default, because a gap is
/// sometimes the point; ⇧⌫ ripples either way.
diff --git a/src/crates/concat/ui/app.slint b/src/crates/concat/ui/app.slint
index e0839338..936440fc 100644
--- a/src/crates/concat/ui/app.slint
+++ b/src/crates/concat/ui/app.slint
@@ -249,6 +249,7 @@ export component App inherits Window {
callback settings-scale-changed(index: int);
callback settings-playhead-stops-changed(on: bool);
callback settings-proxies-changed(on: bool);
+ callback settings-gpu-changed(on: bool);
callback settings-magnetic-changed(on: bool);
callback settings-download-source-changed(index: int);
callback settings-download-base-edited(text: string);
@@ -793,6 +794,7 @@ export component App inherits Window {
scale-changed(index) => { root.settings-scale-changed(index); }
playhead-stops-changed(on) => { root.settings-playhead-stops-changed(on); }
proxies-changed(on) => { root.settings-proxies-changed(on); }
+ gpu-changed(on) => { root.settings-gpu-changed(on); }
magnetic-changed(on) => { root.settings-magnetic-changed(on); }
download-source-changed(index) => { root.settings-download-source-changed(index); }
download-base-edited(text) => { root.settings-download-base-edited(text); }
diff --git a/src/crates/concat/ui/dialogs/settings.slint b/src/crates/concat/ui/dialogs/settings.slint
index 5513e9d7..310e345d 100644
--- a/src/crates/concat/ui/dialogs/settings.slint
+++ b/src/crates/concat/ui/dialogs/settings.slint
@@ -59,6 +59,10 @@ export struct SettingsData {
playhead-stops: bool,
/// large files get a smaller copy for playback
proxies: bool,
+ /// the window and the compositor draw on the GPU, not in software
+ gpu: bool,
+ /// there is a software rasteriser to draw on instead: Windows, Linux
+ gpu-switchable: bool,
/// the magnetic timeline: deleting and trimming close the gap
magnetic: bool,
/// where model downloads look first: automatic, Concat's mirror,
@@ -488,6 +492,7 @@ export component SettingsDialog inherits Modal {
callback scale-changed(index: int);
callback playhead-stops-changed(on: bool);
callback proxies-changed(on: bool);
+ callback gpu-changed(on: bool);
callback magnetic-changed(on: bool);
callback download-source-changed(index: int);
callback download-base-edited(text: string);
@@ -802,6 +807,20 @@ export component SettingsDialog inherits Modal {
switched(on) => { root.proxies-changed(on); }
}
+ // Off, the window and the compositor draw in software:
+ // slower, but out of the way of a graphics driver that
+ // closes the app. A launch that dies while starting turns
+ // it off by itself. Read when Concat starts. Only where
+ // there is a software rasteriser: WARP, lavapipe.
+ if root.data.gpu-switchable: DialogSection {
+ title: I18n.t("settings.gpu");
+ hint: I18n.t("settings.gpuHint");
+ switchable: true;
+ on: root.data.gpu;
+ open: false;
+ switched(on) => { root.gpu-changed(on); }
+ }
+
}
// Read straight off the Theme global rather than through