diff --git a/record-daemon/Cargo.lock b/record-daemon/Cargo.lock index ad0c5e0..25ac5d5 100644 --- a/record-daemon/Cargo.lock +++ b/record-daemon/Cargo.lock @@ -2398,6 +2398,7 @@ dependencies = [ "directories", "display-info", "futures", + "libc", "libobs", "libobs-bootstrapper", "libobs-simple", diff --git a/record-daemon/Cargo.toml b/record-daemon/Cargo.toml index cd8c062..9e4d437 100644 --- a/record-daemon/Cargo.toml +++ b/record-daemon/Cargo.toml @@ -74,6 +74,7 @@ display-info = "0.5" # Signal handling for graceful shutdown (Unix only) [target.'cfg(unix)'.dependencies] +libc = "0.2" signal-hook = "0.4" signal-hook-tokio = { version = "0.4", features = ["futures-v0_3"] } diff --git a/record-daemon/src/instance.rs b/record-daemon/src/instance.rs new file mode 100644 index 0000000..db3fed2 --- /dev/null +++ b/record-daemon/src/instance.rs @@ -0,0 +1,110 @@ +//! One recorder per machine. +//! +//! A second copy brings its own OBS along, and the two fight over the game's capture hook and +//! over the process audio. The result is two files for one game: one with the picture and the +//! other with the microphone. Both the app and the tray can start a daemon, so the daemon claims +//! a lock file on startup and leaves when somebody else holds it. + +use std::path::{Path, PathBuf}; + +use crate::error::Result; + +/// The lock, held for as long as the daemon runs. +#[derive(Debug)] +pub struct InstanceLock { + path: PathBuf, + file: std::fs::File, +} + +impl InstanceLock { + /// Take the lock, or report that another daemon already holds it. + pub fn claim(path: &Path) -> Result> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let file = match lock_file(path) { + Ok(file) => file, + Err(e) if is_held(&e) => return Ok(None), + Err(e) => return Err(e.into()), + }; + Ok(Some(Self { + path: path.to_path_buf(), + file, + })) + } + + /// The file the lock lives in, for log lines. + pub fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for InstanceLock { + fn drop(&mut self) { + // Closing the handle releases the lock; the file itself is harmless to leave behind. + let _ = &self.file; + #[cfg(unix)] + let _ = std::fs::remove_file(&self.path); + } +} + +#[cfg(windows)] +fn lock_file(path: &Path) -> std::io::Result { + use std::os::windows::fs::OpenOptionsExt; + + // A share mode of 0 means the next open fails while this handle is alive. + std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .share_mode(0) + .open(path) +} + +#[cfg(windows)] +fn is_held(error: &std::io::Error) -> bool { + // ERROR_SHARING_VIOLATION: the other daemon holds this file open. + error.raw_os_error() == Some(32) +} + +#[cfg(unix)] +fn lock_file(path: &Path) -> std::io::Result { + use std::os::unix::io::AsRawFd; + + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(path)?; + let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; + if result == 0 { + Ok(file) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(unix)] +fn is_held(error: &std::io::Error) -> bool { + error.raw_os_error() == Some(libc::EWOULDBLOCK) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_second_claim_is_refused_while_the_first_holds_the_file() { + let dir = std::env::temp_dir().join(format!("instance-lock-{}", std::process::id())); + let path = dir.join("record-daemon.lock"); + let first = InstanceLock::claim(&path).expect("first claim"); + assert!(first.is_some(), "the first claim takes the lock"); + let second = InstanceLock::claim(&path).expect("second claim runs"); + assert!(second.is_none(), "the second claim finds the file held"); + drop(first); + let third = InstanceLock::claim(&path).expect("third claim runs"); + assert!(third.is_some(), "the lock is free once the holder exits"); + drop(third); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/record-daemon/src/lib.rs b/record-daemon/src/lib.rs index 56ea420..3188997 100644 --- a/record-daemon/src/lib.rs +++ b/record-daemon/src/lib.rs @@ -6,6 +6,7 @@ pub mod config; pub mod error; +pub mod instance; pub mod ipc; pub mod lqp; pub mod recording; diff --git a/record-daemon/src/main.rs b/record-daemon/src/main.rs index 28c4cf6..77496ab 100644 --- a/record-daemon/src/main.rs +++ b/record-daemon/src/main.rs @@ -673,6 +673,22 @@ async fn main() -> Result<()> { info!("Record Daemon v{} starting", record_daemon::VERSION); + // One daemon per machine. A second one splits the capture: it wins neither the game's + // hook nor its audio, and the user ends up with two half-recordings. + let lock_path = config::get_config_dir() + .unwrap_or_else(|| std::path::PathBuf::from(".")) + .join("record-daemon.lock"); + let _instance = match record_daemon::instance::InstanceLock::claim(&lock_path)? { + Some(lock) => lock, + None => { + error!( + "Another record-daemon holds {}; this one exits", + lock_path.display() + ); + return Ok(()); + } + }; + // Bootstrap OBS - download and extract if needed info!("Bootstrapping OBS..."); let bootstrap_options = ObsBootstrapperOptions::default().set_update(true);