From 99403534ae1c3abb98cddddf0ea2fdcca3f04776 Mon Sep 17 00:00:00 2001 From: Alex Date: Tue, 24 Nov 2026 06:45:44 +0000 Subject: [PATCH] core: window source plan (--source window), parse_source, run_enhance_plan, supervise/stop, with tests --- crates/summit-core/src/engine.rs | 143 ++++++++++++++++++++++++++++++- 1 file changed, 141 insertions(+), 2 deletions(-) diff --git a/crates/summit-core/src/engine.rs b/crates/summit-core/src/engine.rs index 5598607..7a07d66 100644 --- a/crates/summit-core/src/engine.rs +++ b/crates/summit-core/src/engine.rs @@ -11,10 +11,23 @@ pub enum Source { Ps5, /// V4L2/DirectShow capture card by name or index. Capture(String), - /// Another app's window. + /// Another app's window, live: part of its title, or `pid:`, `class:`, `xid:` (engine/framegen/window_x11.py). Window(String), } +/// `summit enhance `: `ps5`, `capture:`, `window:`, else a video file. +pub fn parse_source(s: &str) -> Result { + if s == "ps5" { return Ok(Source::Ps5); } + if let Some(n) = s.strip_prefix("capture:") { + return if n.is_empty() { Err("capture: needs a device name or index, e.g. capture:0".into()) } else { Ok(Source::Capture(n.into())) }; + } + if let Some(w) = s.strip_prefix("window:") { + return if w.trim().is_empty() { Err("window: needs part of the window's title, e.g. window:Voidrunner".into()) } else { Ok(Source::Window(w.into())) }; + } + if s.is_empty() { return Err("no source given".into()); } + Ok(Source::File(s.into())) +} + /// Where the engine lives: $SUMMIT_ENGINE, else /../share/summit/engine, else ./engine. pub fn find_engine() -> Option { let mut c: Vec = vec![]; @@ -53,7 +66,7 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option Source::File(f) => a.push(f.to_string_lossy().into_owned()), Source::Ps5 => a.push("--chiaki".into()), Source::Capture(n) => { a.push("--capture".into()); a.push(n.clone()); } - Source::Window(n) => { a.push("--window".into()); a.push(n.clone()); } + Source::Window(n) => { a.extend(["--source".into(), "window".into(), "--window".into(), n.clone()]); } } if p.framegen == "none" { a.push("--off".into()); } if let Some(m) = &p.model { a.push("--model".into()); a.push(m.clone()); } @@ -69,6 +82,74 @@ pub fn plan(engine: &Path, src: &Source, p: &Profile, display: bool, out: Option a } +/// Options for enhancing a live game window (`summit run --enhance`, `summit enhance window:...`). +#[derive(Debug, Clone, PartialEq)] +pub struct Live { + /// How long the engine waits for the game's window to open, in seconds (0: it must be there already). + pub wait_secs: u32, + /// The "summit - git.molberg.cloud/alex/summit" line in a corner. None leaves the engine's saved setting (on by default). + pub watermark: Option, +} +impl Default for Live { fn default() -> Self { Self { wait_secs: 60, watermark: None } } } + +/// Extra engine flags for a live window, after `plan()`'s. +pub fn live_args(l: &Live) -> Vec { + let mut a = vec![]; + if l.wait_secs > 0 { a.push("--window-wait".to_string()); a.push(l.wait_secs.to_string()); } + if let Some(w) = l.watermark { a.push("--watermark".into()); a.push(if w { "on" } else { "off" }.into()); } + a +} + +/// The window of a game Summit started itself: the process `pid` or anything it started (a launch script's game). +pub fn window_of_pid(pid: u32) -> Source { Source::Window(format!("pid:{pid}")) } + +/// argv (after the python executable) to enhance the live window of the game process `game_pid` on screen, with the +/// game's profile: monitor, fullscreen, upscaler, frame generation on/off, model and target_hz. +/// `window` overrides which window to take (for games whose window belongs to another process, e.g. started through Steam). +pub fn run_enhance_plan(engine: &Path, game_pid: u32, window: Option<&str>, p: &Profile, l: &Live) -> Vec { + let src = match window { Some(w) => Source::Window(w.into()), None => window_of_pid(game_pid) }; + let mut a = plan(engine, &src, p, true, None, None); + a.extend(live_args(l)); + a +} + +/// More engine flags from `SUMMIT_ENGINE_ARGS` (split on spaces), for testing: e.g. `--no-graph` on a GPU short of memory. +pub fn extra_args(env: Option<&str>) -> Vec { + env.map(|v| v.split_whitespace().map(String::from).collect()).unwrap_or_default() +} + +/// Which of the two processes of `summit run --enhance` ended first. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Ended { Game, Engine } + +/// Wait until the game or the engine exits, then stop the other one: SIGTERM first (the engine closes its window and +/// prints its summary; a game saves), SIGKILL if it is still there after `grace`. Returns who ended first and the +/// game's exit status. +pub fn supervise(game: &mut std::process::Child, engine: &mut std::process::Child, grace: std::time::Duration) -> std::io::Result<(Ended, std::process::ExitStatus)> { + let poll = std::time::Duration::from_millis(100); + let first = loop { + if game.try_wait()?.is_some() { break Ended::Game; } + if engine.try_wait()?.is_some() { break Ended::Engine; } + std::thread::sleep(poll); + }; + let other = match first { Ended::Game => &mut *engine, Ended::Engine => &mut *game }; + stop(other, grace)?; + Ok((first, game.wait()?)) +} + +/// SIGTERM, then SIGKILL after `grace` if the process has not gone. Fine to call on one that already exited. +pub fn stop(child: &mut std::process::Child, grace: std::time::Duration) -> std::io::Result<()> { + if child.try_wait()?.is_some() { return Ok(()); } + let _ = std::process::Command::new("kill").args(["-TERM", &child.id().to_string()]).status(); + let until = std::time::Instant::now() + grace; + while std::time::Instant::now() < until { + if child.try_wait()?.is_some() { return Ok(()); } + std::thread::sleep(std::time::Duration::from_millis(50)); + } + let _ = child.kill(); + child.wait().map(|_| ()) +} + /// Instant replay flags for the engine, from the launcher's clip settings. /// The engine only accepts 15, 30, 60, 180, 300 or 600 seconds, and a save is never longer than the buffer. pub fn clip_args(replay_seconds: u32, clip_seconds: u32) -> Vec { @@ -98,6 +179,64 @@ mod tests { assert_eq!(clip_args(30, 300).join(" "), "--replay 30 --clip-length 30"); assert!(clip_args(45, 15).is_empty()); } + #[test] fn window_plan_names_the_source() { + let pr = Profile { framegen: "rife".into(), upscaler: "fsr".into(), ..Default::default() }; + let a = plan(Path::new("/e"), &Source::Window("Voidrunner".into()), &pr, true, None, None); + assert_eq!(a[1..].join(" "), "--source window --window Voidrunner --scaler fsr --display --hz 60"); + } + #[test] fn parse_source_kinds() { + assert_eq!(parse_source("ps5"), Ok(Source::Ps5)); + assert_eq!(parse_source("capture:0"), Ok(Source::Capture("0".into()))); + assert_eq!(parse_source("window:Void runner"), Ok(Source::Window("Void runner".into()))); + assert_eq!(parse_source("window:pid:4242"), Ok(Source::Window("pid:4242".into()))); + assert_eq!(parse_source("clip.mp4"), Ok(Source::File("clip.mp4".into()))); + assert!(parse_source("window:").is_err()); + assert!(parse_source("window: ").is_err()); + assert!(parse_source("capture:").is_err()); + assert!(parse_source("").is_err()); + } + #[test] fn run_enhance_applies_the_profile() { + let a = run_enhance_plan(Path::new("/e"), 4242, None, &p(), &Live::default()); + assert_eq!(a[0], "/e/run.py"); + assert_eq!(a[1..].join(" "), "--source window --window pid:4242 --model 4.25 --scaler vsr --display --hz 120 --fullscreen --monitor HDMI-A-1 --window-wait 60"); + } + #[test] fn run_enhance_window_override_and_watermark_off() { + let pr = Profile { framegen: "none".into(), upscaler: "fsr".into(), ..Default::default() }; + let a = run_enhance_plan(Path::new("/e"), 1, Some("class:steam_app_620"), &pr, &Live { wait_secs: 0, watermark: Some(false) }); + assert_eq!(a[1..].join(" "), "--source window --window class:steam_app_620 --off --scaler fsr --display --hz 60 --watermark off"); + } + #[test] fn live_args_leave_the_saved_watermark_alone_by_default() { + assert_eq!(live_args(&Live::default()).join(" "), "--window-wait 60"); + assert_eq!(live_args(&Live { wait_secs: 5, watermark: Some(true) }).join(" "), "--window-wait 5 --watermark on"); + } + #[test] fn extra_args_split_on_spaces() { + assert_eq!(extra_args(Some(" --no-graph --fp32 ")), vec!["--no-graph", "--fp32"]); + assert!(extra_args(None).is_empty()); + } + fn sh(script: &str) -> std::process::Child { std::process::Command::new("sh").args(["-c", script]).spawn().unwrap() } + #[test] fn supervise_stops_the_engine_when_the_game_exits() { + let (mut game, mut eng) = (sh("exit 3"), sh("exec sleep 30")); + let t = std::time::Instant::now(); + let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5)).unwrap(); + assert_eq!(who, Ended::Game); + assert_eq!(status.code(), Some(3)); + assert!(eng.try_wait().unwrap().is_some(), "engine was stopped"); + assert!(t.elapsed() < std::time::Duration::from_secs(5)); + } + #[test] fn supervise_stops_the_game_when_the_engine_exits() { + let (mut game, mut eng) = (sh("exec sleep 30"), sh("exit 0")); + let (who, status) = supervise(&mut game, &mut eng, std::time::Duration::from_secs(5)).unwrap(); + assert_eq!(who, Ended::Engine); + assert!(!status.success(), "the game was terminated, not left running"); + } + #[test] fn stop_kills_what_ignores_sigterm() { + let mut c = sh("trap '' TERM; sleep 30 & wait"); + std::thread::sleep(std::time::Duration::from_millis(200)); + let t = std::time::Instant::now(); + stop(&mut c, std::time::Duration::from_millis(300)).unwrap(); + assert!(c.try_wait().unwrap().is_some()); + assert!(t.elapsed() < std::time::Duration::from_secs(5)); + } #[test] fn dlss_is_not_an_engine_scaler() { assert_eq!(scaler_arg("dlss"), None); } #[test] fn framegen_none_turns_interp_off() { let pr = Profile { framegen: "none".into(), ..Default::default() };