Merge live-capture: live window enhance, watermark
This commit is contained in:
commit
1442346605
14 files changed
+1174
-26
No files matched your search
@@ -70,13 +70,14 @@
|
||||
| Play from the launcher | Steam games are handed to the Steam client (`steam steam://rungameid/<id>`, or `steam://install/<id>` when not installed). Games added by hand go through `summit run`, so the profile is applied and the session tracked. Lutris uses `lutris lutris:rungame/<slug>`. The commands are unit tested; **no game was actually started from the launcher yet** (no Steam on the build machine). Heroic and folders found on disk cannot be started yet and the button says so. |
|
||||
| Covers for 600+ games | Lists only create the rows on screen, and covers are decoded to thumbnails on a worker thread when a card first appears. Rendered headless with a 662-game library. Not profiled on real hardware. |
|
||||
| Instant replay with a PS5-style length picker: keep 15 s to 10 min, save 15 s, 30 s, 1 m, 3 m, 5 m or 10 m with Ctrl+1..6 (R saves the default length) | **Engine working** (tested with a synthetic stream on the 3090: a 15 s save and a 600 s request capped at the 40 s actually buffered). Not tested on a live game. The launcher's settings page stores both lengths in `ui.toml` and `summit enhance` passes them to the engine; that path is unit tested, not run against the engine. Key binds work in the engine's own window only; a global key is not built for Linux yet. |
|
||||
| In-game overlay with a watermark showing the project URL | Planned |
|
||||
| Live enhance: `summit run <id> --enhance` starts the game and runs frame generation + upscaling on its window, no recording step | **Working on X11** (tested on KDE neon X11 with Voidrunner, RTX 3090): the game is launched, its window is found by process id, the enhanced picture sits on top of it (the game keeps keyboard and mouse), and both stop when either exits. **X11 only**: on Wayland it refuses to start (portal/PipeWire capture is not built). No hotkeys for the engine while it sits over a game yet. See [Live enhance](#live-enhance-play-a-game-with-frame-generation-on-top). |
|
||||
| In-game overlay with a watermark showing the project URL | **Working** in the engine's video window: a small `summit - git.molberg.cloud/alex/summit` line in a bottom corner, next to the existing stats. Setting `watermark`, on by default; `--no-watermark` turns it off. Not drawn into saved clips or files. |
|
||||
| One-click "Add to Steam" with SteamGridDB artwork | Planned |
|
||||
| "My PS5" and "Capture Card" entries (Remote Play, capture cards, Moonlight, Sunshine) | Planned. Reuses the SmoovPlay pipeline. |
|
||||
| AI frame generation (RIFE) on file sources: `summit enhance` | **Working.** Measured on an RTX 3090 (KDE neon): a 30 fps 1080p clip became 60 fps, with 14 ms per generated frame (PyTorch, CUDA graphs). |
|
||||
| FSR upscaling in the engine | Selectable (`--scaler fsr`), ran in the test above; the image quality has not been inspected. |
|
||||
| RTX Video Super Resolution (`rtx-vsr`) | Wired to the engine, **not tested** here. |
|
||||
| Live output window (`--display`, 90/120 Hz, fullscreen on a chosen monitor) | Wired, **not tested**. No attended display was available. |
|
||||
| Live output window (`--display`, 90/120 Hz, fullscreen on a chosen monitor) | 60 Hz windowed and fullscreen ran on the test VM (software OpenGL, so slow there). 90/120 Hz and picking a monitor by name are wired, **not tested** (one virtual display only). |
|
||||
| PS5 Remote Play (needs chiaki-ng with SmoovPlay's frame tap) and capture cards | Wired as `ps5` / `capture:<name>` sources, **not tested** without the hardware. |
|
||||
| lsfg-vk frame generation for any game | Planned |
|
||||
| DLSS | Planned. Depends on what each game and driver really supports. |
|
||||
@@ -107,10 +108,41 @@ summit profile set default --framegen rife --upscaler fsr
|
||||
summit enhance clip.mp4 --out smooth.mp4 # file in, 60 fps file out
|
||||
summit enhance ps5 # PS5 Remote Play, live window (untested)
|
||||
summit enhance capture:0 --profile my-console # capture card, live window (untested)
|
||||
summit enhance window:Voidrunner # a running game's window, live (X11)
|
||||
```
|
||||
|
||||
The engine needs an NVIDIA GPU and its own Python environment (`engine/`, torch with CUDA). The installer for that is not built yet.
|
||||
|
||||
### Live enhance: play a game with frame generation on top
|
||||
|
||||
```sh
|
||||
summit add Voidrunner ~/Games/Voidrunner/top_down_shooter
|
||||
summit profile set custom:voidrunner --framegen rife --upscaler fsr --fullscreen true --target-hz 60
|
||||
summit run custom:voidrunner --enhance # start the game and enhance its window, live
|
||||
summit enhance window:Voidrunner # or: enhance a game that is already running, by window title
|
||||
```
|
||||
|
||||
`summit run <id> --enhance` starts the game, waits for its window (up to `--wait` seconds), starts the engine on it with the game's profile (monitor, fullscreen, upscaler, frame generation, model, `target_hz`), and stops both when either one exits. A window can also be named with `--window` (`class:NAME`, `pid:N`, `xid:N` or part of the title) for games whose window belongs to another process.
|
||||
|
||||
How it works (X11): the engine redirects the game's window off screen with the Composite extension and reads it 60 times a second through `ffmpeg`'s x11grab, leaving out grabs where nothing changed, so frames come at the game's own rate. Its output is a borderless window on top of the game that never takes focus and lets clicks through: over the game's window, or over the whole monitor with `fullscreen = true` (that is where the upscaler has something to do). Stats and the watermark `summit - git.molberg.cloud/alex/summit` are drawn in that window; `--no-watermark` hides the watermark.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
| `fullscreen = true`: 720p game, RIFE + FSR to 1080p | `fullscreen = false`: over the game's own window |
|
||||
|
||||
Watermark on (top) and off (bottom): 
|
||||
|
||||
What was measured, and what was not (test VM: RTX 3090 shared with another job, **software OpenGL** (llvmpipe) for the display, Voidrunner drawing about 50 fps itself):
|
||||
|
||||
- Capture: about 60 grabs a second of the 1280x720 window, 12 to 30 % of them unchanged and left out.
|
||||
- RIFE: 8.5 ms per generated frame at 720p (PyTorch, without CUDA graphs: the GPU had too little free memory for them, see `SUMMIT_ENGINE_ARGS` below).
|
||||
- Over the game's window (no upscale): 56 output frames a second, about 50 ms from a game frame to the screen.
|
||||
- Fullscreen with FSR to 1080p: only about 33 output frames a second, because software OpenGL takes 15 ms to draw each one. **On that VM fullscreen is slower than the game itself.** With a real GPU-driven display this step is expected to take well under a millisecond, but that has not been measured.
|
||||
- Not tested: a real 30 fps game (Voidrunner ran at about 50), 90/120 Hz output, two monitors and `--monitor`, a compositor with direct scanout, games started through Steam or Proton, exclusive-fullscreen games, mouse-driven games in fullscreen mode (clicks go through to whatever is under the pointer, and the picture is scaled, so the pointer does not line up).
|
||||
|
||||
Limits: X11 sessions only (on Wayland it stops with a message). Needs the `ffmpeg` program. The grab polls, so it does not know when the game draws: a 60 fps game can show an occasional repeated or skipped frame. While the picture sits over a game the engine has no keys of its own (they all go to the game): close the game to stop. Killing `summit` itself with a signal does not stop the two it started. `SUMMIT_ENGINE_ARGS` passes extra flags to the engine, e.g. `SUMMIT_ENGINE_ARGS=--no-graph` on a GPU short of memory.
|
||||
|
||||
## Clips
|
||||
|
||||
The engine keeps a rolling buffer of what you played (hardware encoded, so it costs little), like the PS5's Share button. Pick how far back to keep with `--replay` (15, 30, 60, 180, 300 or 600 seconds) and what a save writes with `--clip-length`. In the video window, **R** saves the default length and **Ctrl+1 to Ctrl+6** save 15 s, 30 s, 1 m, 3 m, 5 m or 10 m. A clip is never longer than the buffer holds.
|
||||
|
||||
@@ -20,7 +20,21 @@ enum Cmd {
|
||||
/// Top played games from Steam playtime (the Home view)
|
||||
Home { #[arg(short, default_value_t = 10)] n: usize },
|
||||
/// Launch an entry: apply its display profile, run it, track the time played
|
||||
Run { id: String, #[arg(last = true)] cmd: Vec<String> },
|
||||
Run {
|
||||
id: String,
|
||||
/// Also run the frame-gen/upscale engine on the game's window, live (X11), with the game's profile.
|
||||
/// Both stop when either exits.
|
||||
#[arg(long)] enhance: bool,
|
||||
/// With --enhance: which window to take instead of the game process's own
|
||||
/// (part of its title, class:NAME, pid:N or xid:N)
|
||||
#[arg(long)] window: Option<String>,
|
||||
/// With --enhance: seconds to wait for the game's window to open
|
||||
#[arg(long, default_value_t = 60)] wait: u32,
|
||||
/// With --enhance: hide the "summit - git.molberg.cloud/alex/summit" line in the corner
|
||||
#[arg(long)] no_watermark: bool,
|
||||
/// The command to run. Not needed for an entry added with `summit add`.
|
||||
#[arg(last = true)] cmd: Vec<String>,
|
||||
},
|
||||
/// Add a game or app by hand
|
||||
Add { title: String, path: std::path::PathBuf, #[arg(long)] software: bool },
|
||||
/// Add an entry to the Home screen
|
||||
@@ -37,8 +51,10 @@ enum Cmd {
|
||||
Enhance {
|
||||
/// Profile id to take settings from
|
||||
#[arg(long, default_value = "default")] profile: String,
|
||||
/// ps5 | capture:<name|index> | window:<app> | a video file
|
||||
/// ps5 | capture:<name|index> | window:<title, class:NAME, pid:N or xid:N> | a video file
|
||||
source: String,
|
||||
/// Hide the "summit - git.molberg.cloud/alex/summit" line in the corner of the video window
|
||||
#[arg(long)] no_watermark: bool,
|
||||
/// Render to a file instead of a window (needs a file source)
|
||||
#[arg(long)] out: Option<std::path::PathBuf>,
|
||||
#[arg(long)] max_ticks: Option<u32>,
|
||||
@@ -63,6 +79,10 @@ enum ProfileCmd {
|
||||
#[arg(long)] upscaler: Option<String>,
|
||||
#[arg(long)] framegen: Option<String>,
|
||||
#[arg(long)] multiplier: Option<u8>,
|
||||
/// Engine output rate: 60, 90 or 120
|
||||
#[arg(long)] target_hz: Option<u32>,
|
||||
/// RIFE model for the engine, e.g. 4.22.lite
|
||||
#[arg(long)] model: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -105,14 +125,10 @@ fn main() -> Result<()> {
|
||||
st.custom.push(state::Custom { id: id.clone(), title, path: path.canonicalize()?.to_string_lossy().into_owned(), software });
|
||||
state::save(&st)?; println!("added {id}");
|
||||
}
|
||||
Cmd::Enhance { profile, source, out, max_ticks, dry_run } => {
|
||||
Cmd::Enhance { profile, source, no_watermark, out, max_ticks, dry_run } => {
|
||||
let eng = engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: set SUMMIT_ENGINE to the engine/ folder"))?;
|
||||
let src = match source.as_str() {
|
||||
"ps5" => engine::Source::Ps5,
|
||||
s if s.starts_with("capture:") => engine::Source::Capture(s[8..].into()),
|
||||
s if s.starts_with("window:") => engine::Source::Window(s[7..].into()),
|
||||
f => engine::Source::File(f.into()),
|
||||
};
|
||||
let src = engine::parse_source(&source).map_err(|e| anyhow::anyhow!(e))?;
|
||||
anyhow::ensure!(out.is_none() || matches!(src, engine::Source::File(_)), "--out needs a video file as the source");
|
||||
let p = profile::load(&profile)?;
|
||||
let mut args = engine::plan(&eng, &src, &p, out.is_none(), out.as_deref(), max_ticks);
|
||||
// Instant replay only exists while playing on screen. Lengths come from the launcher's settings page;
|
||||
@@ -121,10 +137,12 @@ fn main() -> Result<()> {
|
||||
let ui = summit_core::ui::load();
|
||||
args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds));
|
||||
}
|
||||
if out.is_none() && no_watermark { args.extend(["--watermark".to_string(), "off".to_string()]); }
|
||||
args.extend(engine::extra_args(std::env::var("SUMMIT_ENGINE_ARGS").ok().as_deref()));
|
||||
let py = engine::python(&eng);
|
||||
println!("{} {}", py.display(), args.join(" "));
|
||||
if !dry_run {
|
||||
let st = std::process::Command::new(&py).args(&args).status()?;
|
||||
let st = std::process::Command::new(&py).args(&args).env("SMOOVPLAY_TITLE", "Summit").status()?;
|
||||
anyhow::ensure!(st.success(), "engine exited with {st}");
|
||||
}
|
||||
}
|
||||
@@ -145,9 +163,14 @@ fn main() -> Result<()> {
|
||||
for c in cmds { println!("would run: {}", c.join(" ")); }
|
||||
}
|
||||
}
|
||||
Cmd::Run { id, cmd } => {
|
||||
Cmd::Run { id, enhance, window, wait, no_watermark, mut cmd } => {
|
||||
if cmd.is_empty() { // an entry added with `summit add` knows its own path
|
||||
if let Some(c) = state::load().custom.iter().find(|c| c.id == id) { cmd = vec![c.path.clone()]; }
|
||||
}
|
||||
anyhow::ensure!(!cmd.is_empty(), "give the command after --, e.g. summit run my-game -- ./game.sh");
|
||||
let p = profile::load(&id)?;
|
||||
// Found before the game starts, so a missing engine never leaves a game running without it.
|
||||
let eng = if enhance { Some(engine::find_engine().ok_or_else(|| anyhow::anyhow!("engine not found: set SUMMIT_ENGINE to the engine/ folder"))?) } else { None };
|
||||
let (s, d) = (display::detect_session(), display::detect_desktop());
|
||||
let plan = display::plan(s, d, &p);
|
||||
if plan.is_empty() && p.monitor.is_some() { eprintln!("note: no display control for {s:?}/{d:?}; launching without mode change"); }
|
||||
@@ -155,7 +178,31 @@ fn main() -> Result<()> {
|
||||
let start = std::time::Instant::now();
|
||||
let mut child = std::process::Command::new(&cmd[0]);
|
||||
child.args(&cmd[1..]).args(&p.launch_args).envs(display::launch_env(s, &p));
|
||||
let status = child.status()?;
|
||||
// A game given by its full path is started from its own folder: many look for their data there.
|
||||
if let Some(dir) = std::path::Path::new(&cmd[0]).parent().filter(|d| d.is_absolute() && d.is_dir()) { child.current_dir(dir); }
|
||||
let status = if let Some(eng) = eng {
|
||||
let mut game = child.spawn()?;
|
||||
let live = engine::Live { wait_secs: wait, watermark: if no_watermark { Some(false) } else { None } };
|
||||
let mut args = engine::run_enhance_plan(&eng, game.id(), window.as_deref(), &p, &live);
|
||||
if summit_core::ui::path().map_or(false, |p| p.exists()) {
|
||||
let ui = summit_core::ui::load();
|
||||
args.extend(engine::clip_args(ui.replay_seconds, ui.clip_seconds));
|
||||
}
|
||||
args.extend(engine::extra_args(std::env::var("SUMMIT_ENGINE_ARGS").ok().as_deref()));
|
||||
let py = engine::python(&eng);
|
||||
println!("{} {}", py.display(), args.join(" "));
|
||||
let grace = std::time::Duration::from_secs(8);
|
||||
let mut eng_proc = match std::process::Command::new(&py).args(&args).env("SMOOVPLAY_TITLE", "Summit").spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) => { let _ = engine::stop(&mut game, grace); anyhow::bail!("could not start the engine ({}): {e}", py.display()); }
|
||||
};
|
||||
let (who, status) = engine::supervise(&mut game, &mut eng_proc, grace)?;
|
||||
match who {
|
||||
engine::Ended::Game => println!("the game exited; the engine was stopped"),
|
||||
engine::Ended::Engine => println!("the engine exited ({}); the game was stopped", eng_proc.wait()?),
|
||||
}
|
||||
status
|
||||
} else { child.status()? };
|
||||
let secs = start.elapsed().as_secs();
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_secs();
|
||||
let mut st = state::load(); st.record_session(&id, secs, now); state::save(&st)?;
|
||||
@@ -164,7 +211,7 @@ fn main() -> Result<()> {
|
||||
Cmd::Profile { cmd: ProfileCmd::Show { id } } => {
|
||||
print!("{}", toml::to_string_pretty(&profile::load(&id)?)?);
|
||||
}
|
||||
Cmd::Profile { cmd: ProfileCmd::Set { id, monitor, width, height, refresh, fullscreen, focus, upscaler, framegen, multiplier } } => {
|
||||
Cmd::Profile { cmd: ProfileCmd::Set { id, monitor, width, height, refresh, fullscreen, focus, upscaler, framegen, multiplier, target_hz, model } } => {
|
||||
let mut p = profile::load(&id)?;
|
||||
if monitor.is_some() { p.monitor = monitor; }
|
||||
if width.is_some() { p.width = width; }
|
||||
@@ -175,6 +222,8 @@ fn main() -> Result<()> {
|
||||
if let Some(v) = upscaler { p.upscaler = v; }
|
||||
if let Some(v) = framegen { p.framegen = v; }
|
||||
if let Some(v) = multiplier { p.framegen_multiplier = v; }
|
||||
if let Some(v) = target_hz { anyhow::ensure!([60, 90, 120].contains(&v), "--target-hz is 60, 90 or 120"); p.target_hz = Some(v); }
|
||||
if model.is_some() { p.model = model; }
|
||||
println!("saved {}", profile::save(&id, &p)?.display());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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:<n>`, `class:<name>`, `xid:<n>` (engine/framegen/window_x11.py).
|
||||
Window(String),
|
||||
}
|
||||
|
||||
/// `summit enhance <source>`: `ps5`, `capture:<name|index>`, `window:<title|pid:N|class:NAME|xid:N>`, else a video file.
|
||||
pub fn parse_source(s: &str) -> Result<Source, String> {
|
||||
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 <exe dir>/../share/summit/engine, else ./engine.
|
||||
pub fn find_engine() -> Option<PathBuf> {
|
||||
let mut c: Vec<PathBuf> = 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 <id> --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<bool>,
|
||||
}
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
@@ -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() };
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.9 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 253 KiB |
+93
-2
@@ -306,6 +306,7 @@ WAYLAND = sys.platform.startswith("linux") and os.environ.get("XDG_SESSION_TYPE"
|
||||
MONITOR = os.environ.get("SMOOVPLAY_MONITOR", "")
|
||||
# The window's title (SMOOVPLAY_TITLE): lets a window rule tell launchers apart (the projector one vs. the desktop one).
|
||||
WINDOW_TITLE = os.environ.get("SMOOVPLAY_TITLE", "SmoovPlay")
|
||||
X11 = sys.platform.startswith("linux") and not WAYLAND # window capture's overlay there: framegen/window_x11.py
|
||||
# SMOOVPLAY_SUPERSAMPLE=2: RTX VSR runs even when the window is no bigger than the picture (it renders at 2x and the GPU
|
||||
# shrinks that back), so it cleans up a capture card's compression blocks on a 1080p screen too.
|
||||
try:
|
||||
@@ -705,6 +706,8 @@ class GLWindowSink:
|
||||
(glfw.FOCUSED, glfw.FALSE), (glfw.FOCUS_ON_SHOW, glfw.FALSE),
|
||||
(glfw.MOUSE_PASSTHROUGH, glfw.TRUE)):
|
||||
glfw.window_hint(hint, value)
|
||||
if X11: # shown by _make_overlay, once the window manager has been told to leave it alone
|
||||
glfw.window_hint(glfw.VISIBLE, glfw.FALSE)
|
||||
self.win = self.glwin = glfw.create_window(min(w, 1600), min(h, 900), WINDOW_TITLE, None, None)
|
||||
glfw.default_window_hints()
|
||||
glfw.make_context_current(self.win)
|
||||
@@ -823,6 +826,7 @@ class GLWindowSink:
|
||||
self.menu = Menu(st, allowed=self.allowed, disabled=self.disabled, restart_reasons=restart_reasons)
|
||||
self.menu_panel, self.toast_panel = _Panel(GL, self.hdr10), _Panel(GL, self.hdr10)
|
||||
self.mini_panel, self._mini_state = _Panel(GL, self.hdr10), None
|
||||
self.wm_panel, self._wm_state = _Panel(GL, self.hdr10), None # the Summit watermark
|
||||
self._frametimes, self._last_write, self._graph_drawn, self._gpu = collections.deque(maxlen=480), 0.0, 0.0, None
|
||||
self._menu_top = None # (GL y of the menu's top, the picture's (y0, height) it was placed in) while it's open
|
||||
self._menu_at = None # (x, GL y of the top) the menu was last drawn at, for the mouse
|
||||
@@ -1194,6 +1198,9 @@ class GLWindowSink:
|
||||
and out of the capture, which then sees the app underneath (framegen/window.py)."""
|
||||
import ctypes
|
||||
|
||||
if sys.platform != "win32":
|
||||
self._make_overlay_x11()
|
||||
return
|
||||
from .window import exclude_from_capture
|
||||
hwnd = self.glfw.get_win32_window(self.win)
|
||||
if not exclude_from_capture(hwnd):
|
||||
@@ -1205,10 +1212,56 @@ class GLWindowSink:
|
||||
u32.SetWindowLongW(hwnd, -20, u32.GetWindowLongW(hwnd, -20) | 0x08000000) # GWL_EXSTYLE |= WS_EX_NOACTIVATE
|
||||
self._follow()
|
||||
|
||||
def _make_overlay_x11(self) -> None:
|
||||
"""Window capture on X11 (framegen/window_x11.py): the picture goes over the game as an override-redirect
|
||||
window, one the window manager doesn't manage: no frame, never focused (the game keeps the keys), and above
|
||||
everything, a fullscreen game included. Clicks go through it (GLFW's mouse passthrough). The capture reads
|
||||
the game's own off-screen picture, so this window isn't in it."""
|
||||
import ctypes
|
||||
import ctypes.util
|
||||
glfw = self.glfw
|
||||
self._x11 = None
|
||||
try:
|
||||
class Attrs(ctypes.Structure): # XSetWindowAttributes
|
||||
_fields_ = [("background_pixmap", ctypes.c_ulong), ("background_pixel", ctypes.c_ulong),
|
||||
("border_pixmap", ctypes.c_ulong), ("border_pixel", ctypes.c_ulong),
|
||||
("bit_gravity", ctypes.c_int), ("win_gravity", ctypes.c_int),
|
||||
("backing_store", ctypes.c_int), ("backing_planes", ctypes.c_ulong),
|
||||
("backing_pixel", ctypes.c_ulong), ("save_under", ctypes.c_int),
|
||||
("event_mask", ctypes.c_long), ("do_not_propagate_mask", ctypes.c_long),
|
||||
("override_redirect", ctypes.c_int), ("colormap", ctypes.c_ulong),
|
||||
("cursor", ctypes.c_ulong)]
|
||||
x = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6")
|
||||
dpy = ctypes.cast(glfw.get_x11_display(), ctypes.c_void_p)
|
||||
xid = int(glfw.get_x11_window(self.win))
|
||||
x.XChangeWindowAttributes.argtypes = [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong,
|
||||
ctypes.POINTER(Attrs)]
|
||||
x.XRaiseWindow.argtypes = [ctypes.c_void_p, ctypes.c_ulong]
|
||||
x.XFlush.argtypes = [ctypes.c_void_p]
|
||||
x.XChangeWindowAttributes(dpy, xid, 1 << 9, ctypes.byref(Attrs(override_redirect=1))) # CWOverrideRedirect
|
||||
self._x11 = (x, dpy, xid)
|
||||
except Exception as e: # noqa: BLE001 - still an always-on-top window that takes no focus when it opens
|
||||
print(f"[display] the picture over the game is an ordinary window here ({str(e)[:120]}): if it takes the "
|
||||
"keys, click the game")
|
||||
self._follow()
|
||||
glfw.show_window(self.win)
|
||||
self._raise_x11()
|
||||
|
||||
def _raise_x11(self) -> None:
|
||||
"""Back above everything: a window manager raising the game (a click on it) puts it over an unmanaged window."""
|
||||
if getattr(self, "_x11", None):
|
||||
x, dpy, xid = self._x11
|
||||
x.XRaiseWindow(dpy, xid)
|
||||
x.XFlush(dpy)
|
||||
|
||||
def _start_hotkeys(self, picked: dict | None) -> None:
|
||||
"""Window capture: the overlay never has the keys, so its own come through system-wide shortcuts
|
||||
(framegen/hotkeys.py), registered for this thread, the one that draws (_events takes their messages). Says
|
||||
which it got, over the picture and to the launcher ("[window-keys] ...")."""
|
||||
if sys.platform != "win32": # no system-wide shortcuts off Windows yet: the keys all go to the game
|
||||
self.KEYS_HINT = "Summit is enhancing this game. Close the game to stop."
|
||||
self.toast(self.KEYS_HINT, 6.0)
|
||||
return
|
||||
from .hotkeys import Hotkeys, describe
|
||||
try:
|
||||
self.hotkeys = Hotkeys(picked)
|
||||
@@ -1263,7 +1316,10 @@ class GLWindowSink:
|
||||
if where is None: # minimised: stay put until it's back
|
||||
return
|
||||
client, monitor = where
|
||||
if X11 and self.settings.fullscreen: # the monitor --monitor names, else the one the game is on
|
||||
monitor = self._monitor_rect(client) or monitor
|
||||
r = monitor if self.settings.fullscreen else client
|
||||
self._raise_x11()
|
||||
if self.hotkeys is not None:
|
||||
self._hint_on_hover(r)
|
||||
at = (r.x, r.y, r.w, r.h)
|
||||
@@ -1272,6 +1328,23 @@ class GLWindowSink:
|
||||
self.glfw.set_window_pos(self.win, r.x, r.y)
|
||||
self.glfw.set_window_size(self.win, r.w, r.h)
|
||||
|
||||
def _monitor_rect(self, client):
|
||||
"""Window capture on X11: the monitor the picture covers in fullscreen, as a rectangle in screen pixels: the
|
||||
one --monitor names (io.MONITOR), else the one holding the middle of the game's window. None if GLFW can't say."""
|
||||
glfw = self.glfw
|
||||
try:
|
||||
rects = []
|
||||
for m in glfw.get_monitors():
|
||||
(x, y), mode = glfw.get_monitor_pos(m), glfw.get_video_mode(m)
|
||||
rects.append((m, type(client)(x, y, mode.size.width, mode.size.height)))
|
||||
if MONITOR:
|
||||
want = pick_monitor(glfw)
|
||||
return next(r for m, r in rects if m == want)
|
||||
cx, cy = client.x + client.w // 2, client.y + client.h // 2
|
||||
return next((r for _, r in rects if r.x <= cx < r.x + r.w and r.y <= cy < r.y + r.h), None)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
|
||||
def _set_fullscreen(self, on: bool) -> None:
|
||||
glfw, win = self.glfw, self.win
|
||||
if self.overlay_of is not None: # over the app's monitor, as a borderless window: no fullscreen mode change
|
||||
@@ -1385,8 +1458,11 @@ class GLWindowSink:
|
||||
if self.dx is not None:
|
||||
self.dx.resize(fw, fh) # cheap when the size hasn't changed
|
||||
s = min(fw / self.w, fh / self.h) # letterbox, keep aspect
|
||||
if self.overlay_of is not None: # window capture: the frame is the app's window squeezed to the stream's
|
||||
return fw, fh, s, fw, fh, 0, 0 # size, so it's stretched back over it to fill the overlay exactly
|
||||
if self.overlay_of is not None and not X11: # window capture: the frame is the app's window squeezed to the
|
||||
return fw, fh, s, fw, fh, 0, 0 # stream's size, so it's stretched back over it to fill the overlay exactly
|
||||
if self.overlay_of is not None: # X11: frames keep the game's shape, so fullscreen fits them to the monitor
|
||||
dw, dh = round(self.w * s), round(self.h * s)
|
||||
return fw, fh, s, dw, dh, (fw - dw) // 2, (fh - dh) // 2
|
||||
dw, dh, x0, y0 = layout(self.fill, fw, fh, self.w, self.h) # (Fill the screen: always the same 16:9 picture)
|
||||
return fw, fh, s, dw, dh, x0, y0
|
||||
|
||||
@@ -1571,6 +1647,8 @@ class GLWindowSink:
|
||||
elif self.overlay and text:
|
||||
first, nl, rest = text.partition("\n") # the upscaler goes on the first line; a second is the test line
|
||||
self._blit_text(f"{first} {label}{nl}{rest}", ux, uy + uh, s)
|
||||
if self.settings.watermark:
|
||||
self._draw_watermark(ux, uy, uw, uh)
|
||||
self._draw_ui(ux, uy, uw, uh)
|
||||
self._present()
|
||||
self.settle()
|
||||
@@ -1676,6 +1754,19 @@ class GLWindowSink:
|
||||
self._graph_drawn, self._mini_state = now, key
|
||||
self._blit_corner(self.mini_panel, x0, y0, dw, dh, ui)
|
||||
|
||||
def _draw_watermark(self, x0: int, y0: int, dw: int, dh: int) -> None:
|
||||
"""The Summit watermark (framegen/watermark.py, settings "watermark"): small, in a bottom corner, away from the
|
||||
stats. Drawn again only when its size changes."""
|
||||
from . import watermark as wm
|
||||
ui = max(0.5, dh / 1080)
|
||||
if self._wm_state != round(ui, 3):
|
||||
self.wm_panel.update(wm.render(ui), [wm.BG], wm.OPACITY)
|
||||
self._wm_state = round(ui, 3)
|
||||
p = self.wm_panel
|
||||
x, top = wm.place(wm.corner(self.settings.overlay_corner, bool(self.overlay)), p.w, p.h, x0, y0, dw, dh,
|
||||
int(12 * ui))
|
||||
p.blit(x, top, self._target())
|
||||
|
||||
def _blit_text(self, text: str, x0: int, top: int, s: float) -> None:
|
||||
GL = self.GL
|
||||
if text != self._ov_text:
|
||||
|
||||
@@ -311,6 +311,9 @@ SPECS: tuple[Spec, ...] = (
|
||||
Spec("graph_gpu", "Graph: graphics card", (True, False), True, ON_OFF, group="Display",
|
||||
applies=("overlay_style", ("graphs",)),
|
||||
help="Graphs style: the graphics card's load, power, temperature, clock and memory (needs nvidia-smi)."),
|
||||
Spec("watermark", "Summit watermark", (True, False), True, ON_OFF, group="Display",
|
||||
help="A small line in a corner of the video: summit - git.molberg.cloud/alex/summit. It moves out of the "
|
||||
"stats overlay's way. Only in the video window, never in saved clips or files."),
|
||||
Spec("ui_opacity", "Menu opacity", OPACITY, 0.9, PCT, group="Display",
|
||||
help="How see-through the settings menu and its messages are. Text stays solid."),
|
||||
Spec("ui_scale", "Menu size", (0.6, 0.75, 0.9, 1.0), 1.0, PCT_SIZE, group="Display",
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""The Summit watermark: one small line of text in a corner of the video window (settings "watermark", on by default).
|
||||
Pure drawing with OpenCV, so it is tested without a window."""
|
||||
from __future__ import annotations
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
TEXT = "summit - git.molberg.cloud/alex/summit"
|
||||
BG = (24, 22, 20) # the box behind the text (BGR); drawn see-through by the window
|
||||
FG = (235, 235, 235)
|
||||
OPACITY = 0.45 # of the box; the text stays solid
|
||||
CORNERS = ("top-left", "top-right", "bottom-left", "bottom-right")
|
||||
|
||||
|
||||
def corner(stats_corner: str, stats_on: bool = True) -> str:
|
||||
"""Where it goes: bottom-left, or bottom-right when the stats overlay sits bottom-left (never on top of it;
|
||||
messages appear bottom-right, briefly)."""
|
||||
return "bottom-right" if stats_on and stats_corner == "bottom-left" else "bottom-left"
|
||||
|
||||
|
||||
def render(ui: float = 1.0, text: str = TEXT) -> np.ndarray:
|
||||
"""The watermark as a small BGR image; ui scales it with the picture (1.0 at 1080p)."""
|
||||
fs = 0.42 * max(ui, 0.6)
|
||||
(tw, th), base = cv2.getTextSize(text, cv2.FONT_HERSHEY_SIMPLEX, fs, 1)
|
||||
padx, pady = max(4, int(8 * ui)), max(3, int(5 * ui))
|
||||
img = np.full((th + base + 2 * pady, tw + 2 * padx, 3), BG, np.uint8)
|
||||
cv2.putText(img, text, (padx, pady + th), cv2.FONT_HERSHEY_SIMPLEX, fs, FG, 1, cv2.LINE_AA)
|
||||
return img
|
||||
|
||||
|
||||
def place(corner_: str, pw: int, ph: int, x0: int, y0: int, dw: int, dh: int, margin: int) -> tuple[int, int]:
|
||||
"""(x, GL y of the top edge) for a pw x ph panel in a corner of the picture at (x0, y0, dw, dh); GL y grows up."""
|
||||
x = x0 + dw - pw - margin if corner_.endswith("right") else x0 + margin
|
||||
top = y0 + margin + ph if corner_.startswith("bottom") else y0 + dh - margin
|
||||
return x, top
|
||||
@@ -541,9 +541,9 @@ def main(argv: list[str] | None = None) -> int:
|
||||
ap.add_argument("--list", action="store_true", help="the app windows that could be captured")
|
||||
ap.add_argument("--json", action="store_true")
|
||||
a = ap.parse_args(argv)
|
||||
if sys.platform != "win32":
|
||||
print(json.dumps({"windows": []}) if a.json else "window capture needs Windows")
|
||||
return 0
|
||||
if sys.platform != "win32": # Linux: framegen/window_x11.py
|
||||
from .window_x11 import main as x11_main
|
||||
return x11_main((["--list"] if a.list else []) + (["--json"] if a.json else []))
|
||||
left_out: dict = {}
|
||||
windows = find_windows(left_out)
|
||||
missed = [{"exe": exe, "app": KNOWN[exe], "why": sorted(why)} for exe, why in sorted(left_out.items())]
|
||||
|
||||
@@ -0,0 +1,520 @@
|
||||
"""Window capture on Linux, X11 only (Experimental): frames from a game's (or any app's) window, live.
|
||||
|
||||
python -m framegen.window_x11 --list [--json] # the windows it could capture
|
||||
python run.py --source window --window "Voidrunner" --display
|
||||
python run.py --source window --window pid:4242 --window-wait 60 --display # what `summit run --enhance` does
|
||||
|
||||
How it works:
|
||||
- The window is picked by part of its title, "class:NAME" (its WM_CLASS), "pid:N" (the process that owns it, or one it
|
||||
started), or "xid:N" (its X window id; "hwnd:N" means the same). Windows come from the window manager's list
|
||||
(_NET_CLIENT_LIST), read with Xlib through ctypes: no extra package.
|
||||
- The window is redirected off screen with the Composite extension (XCompositeRedirectWindow, automatic: the X server
|
||||
still paints it as before), so its own picture can be read even while another window covers it. That is what lets
|
||||
the engine's picture sit on top of the game without capturing itself.
|
||||
- FFmpeg's x11grab (`-window_id`) reads that picture 60 times a second, as an `ffmpeg` program of its own that pipes
|
||||
raw frames here. (Not through PyAV: its wheel carries its own libxcb, which crashes next to the system's libX11
|
||||
that the video window uses.) A grab that is the same as the one before is left out, so frames come at the game's
|
||||
own rate, and run.py puts them on a 60 Hz beat (sources.Clock60) as for any variable-rate source.
|
||||
- Frames keep the window's own size (made even). The window is looked at twice a second: if it changed size the
|
||||
capture restarts and frames are scaled to the size the session started with; while it's minimised the last frame
|
||||
stays up; when it closes, the source ends (and so does the engine).
|
||||
|
||||
Limits:
|
||||
- Needs the `ffmpeg` program (with x11grab; any distribution's package has it).
|
||||
- X11 sessions only. On Wayland this refuses to start: capture there needs xdg-desktop-portal's ScreenCast and
|
||||
PipeWire, which isn't built. (XWayland windows can't be read this way either.)
|
||||
- The grab polls at 60 Hz without knowing when the game draws, so a 60 fps game can show an occasional repeated or
|
||||
skipped frame. The mouse pointer isn't captured.
|
||||
- The game plays its own sound, a little ahead of the picture.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import ctypes
|
||||
import ctypes.util
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from ctypes import POINTER, byref, c_char_p, c_int, c_long, c_uint, c_ulong, c_void_p
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
MIN_SIZE = (160, 120) # smaller windows aren't games
|
||||
CHECK_S = 0.5 # how often the window's place is looked at
|
||||
GRAB_HZ = 60
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Rect:
|
||||
x: int
|
||||
y: int
|
||||
w: int
|
||||
h: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class XWindow:
|
||||
xid: int
|
||||
title: str
|
||||
cls: str # WM_CLASS's class, lower case ("" if it has none)
|
||||
pid: int # _NET_WM_PID (0 if the app didn't set it)
|
||||
w: int
|
||||
h: int
|
||||
|
||||
@property
|
||||
def app(self) -> str:
|
||||
return self.title or self.cls or f"window {self.xid:#x}"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- picking (pure: unit tested)
|
||||
def pid_family(pid: int, proc: str = "/proc") -> set[int]:
|
||||
"""`pid` and every process it started (its children, theirs, ...): a launch script's game counts as the script."""
|
||||
parent: dict[int, int] = {}
|
||||
try:
|
||||
names = os.listdir(proc)
|
||||
except OSError:
|
||||
return {pid}
|
||||
for name in names:
|
||||
if not name.isdigit():
|
||||
continue
|
||||
try:
|
||||
with open(os.path.join(proc, name, "stat"), "rb") as f:
|
||||
stat = f.read().decode(errors="replace")
|
||||
parent[int(name)] = int(stat[stat.rindex(")") + 2:].split()[1]) # after "(comm) state": the ppid
|
||||
except (OSError, ValueError, IndexError):
|
||||
continue
|
||||
family, grew = {pid}, True
|
||||
while grew:
|
||||
more = {p for p, pp in parent.items() if pp in family} - family
|
||||
family |= more
|
||||
grew = bool(more)
|
||||
return family
|
||||
|
||||
|
||||
def pick(query: str, windows: list[XWindow], family=pid_family) -> XWindow | None:
|
||||
"""The window `query` names: "xid:N" (or "hwnd:N"), "pid:N", "class:NAME" (or "exe:NAME"), or part of a title.
|
||||
Of several matches, the biggest. Several queries split by "|" are tried in turn."""
|
||||
if "|" in query:
|
||||
return next((w for q in query.split("|") if q.strip() and (w := pick(q, windows, family))), None)
|
||||
q = query.strip()
|
||||
low = q.lower()
|
||||
try:
|
||||
if low.startswith(("xid:", "hwnd:")):
|
||||
xid = int(q.split(":", 1)[1], 0)
|
||||
return next((w for w in windows if w.xid == xid), None)
|
||||
if low.startswith("pid:"):
|
||||
pids = family(int(q[4:]))
|
||||
matches = [w for w in windows if w.pid in pids]
|
||||
elif low.startswith(("class:", "exe:")):
|
||||
name = low.split(":", 1)[1].strip()
|
||||
matches = [w for w in windows if w.cls == name]
|
||||
else:
|
||||
matches = [w for w in windows if low in w.title.lower()]
|
||||
except ValueError:
|
||||
return None
|
||||
return max(matches, key=lambda w: w.w * w.h, default=None)
|
||||
|
||||
|
||||
def even(n: int) -> int:
|
||||
return n & ~1
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- Xlib
|
||||
class _Attrs(ctypes.Structure): # XWindowAttributes
|
||||
_fields_ = [("x", c_int), ("y", c_int), ("width", c_int), ("height", c_int), ("border_width", c_int),
|
||||
("depth", c_int), ("visual", c_void_p), ("root", c_ulong), ("c_class", c_int), ("bit_gravity", c_int),
|
||||
("win_gravity", c_int), ("backing_store", c_int), ("backing_planes", c_ulong),
|
||||
("backing_pixel", c_ulong), ("save_under", c_int), ("colormap", c_ulong), ("map_installed", c_int),
|
||||
("map_state", c_int), ("all_event_masks", c_long), ("your_event_mask", c_long),
|
||||
("do_not_propagate_mask", c_long), ("override_redirect", c_int), ("screen", c_void_p)]
|
||||
|
||||
|
||||
_ERROR_HANDLER = ctypes.CFUNCTYPE(c_int, c_void_p, c_void_p)(lambda _d, _e: 0) # (kept alive here: Xlib holds a pointer)
|
||||
|
||||
|
||||
def session_problem(env=os.environ) -> str | None:
|
||||
"""Why window capture can't run in this session, or None if it can."""
|
||||
if env.get("XDG_SESSION_TYPE", "").lower() == "wayland" or (env.get("WAYLAND_DISPLAY") and not env.get("DISPLAY")):
|
||||
return ("window capture on Linux works in X11 sessions only for now: this is a Wayland session (capture "
|
||||
"there needs xdg-desktop-portal ScreenCast, which isn't built). Log in to an X11 session to use it.")
|
||||
if not env.get("DISPLAY"):
|
||||
return "no X display (DISPLAY isn't set): window capture needs a desktop session"
|
||||
return None
|
||||
|
||||
|
||||
class X:
|
||||
"""One connection to the X server, for looking at windows. Errors (a window that just closed) are swallowed:
|
||||
calls then report failure instead of Xlib ending the program."""
|
||||
|
||||
def __init__(self, display: str | None = None) -> None:
|
||||
self.name = display or os.environ.get("DISPLAY", ":0")
|
||||
self.lib = x = ctypes.CDLL(ctypes.util.find_library("X11") or "libX11.so.6")
|
||||
x.XOpenDisplay.restype, x.XOpenDisplay.argtypes = c_void_p, [c_char_p]
|
||||
x.XDefaultRootWindow.restype, x.XDefaultRootWindow.argtypes = c_ulong, [c_void_p]
|
||||
x.XInternAtom.restype, x.XInternAtom.argtypes = c_ulong, [c_void_p, c_char_p, c_int]
|
||||
x.XGetWindowProperty.argtypes = [c_void_p, c_ulong, c_ulong, c_long, c_long, c_int, c_ulong, POINTER(c_ulong),
|
||||
POINTER(c_int), POINTER(c_ulong), POINTER(c_ulong), POINTER(c_void_p)]
|
||||
x.XFree.argtypes = [c_void_p]
|
||||
x.XGetWindowAttributes.argtypes = [c_void_p, c_ulong, POINTER(_Attrs)]
|
||||
x.XTranslateCoordinates.argtypes = [c_void_p, c_ulong, c_ulong, c_int, c_int, POINTER(c_int), POINTER(c_int),
|
||||
POINTER(c_ulong)]
|
||||
x.XQueryTree.argtypes = [c_void_p, c_ulong, POINTER(c_ulong), POINTER(c_ulong), POINTER(c_void_p),
|
||||
POINTER(c_uint)]
|
||||
x.XSync.argtypes = [c_void_p, c_int]
|
||||
x.XCloseDisplay.argtypes = [c_void_p]
|
||||
x.XSetErrorHandler.restype, x.XSetErrorHandler.argtypes = c_void_p, [c_void_p]
|
||||
self._guard()
|
||||
self.d = x.XOpenDisplay(self.name.encode())
|
||||
if not self.d:
|
||||
raise RuntimeError(f"can't open the X display {self.name}")
|
||||
self.root = x.XDefaultRootWindow(self.d)
|
||||
self._atoms: dict[str, int] = {}
|
||||
|
||||
def _guard(self) -> None:
|
||||
# Set again before each use: GLFW (the video window, same process) puts Xlib's default handler back after its
|
||||
# own checks, and that one ends the program on any error, such as asking about a window that just closed.
|
||||
self.lib.XSetErrorHandler(_ERROR_HANDLER)
|
||||
|
||||
def atom(self, name: str) -> int:
|
||||
if name not in self._atoms:
|
||||
self._atoms[name] = self.lib.XInternAtom(self.d, name.encode(), 0)
|
||||
return self._atoms[name]
|
||||
|
||||
def prop(self, xid: int, name: str):
|
||||
"""A window property: bytes (8-bit data) or a list of ints (32-bit data); None if it isn't there."""
|
||||
self._guard()
|
||||
kind, fmt, n, left, data = c_ulong(), c_int(), c_ulong(), c_ulong(), c_void_p()
|
||||
if self.lib.XGetWindowProperty(self.d, xid, self.atom(name), 0, 1 << 16, 0, 0, byref(kind), byref(fmt),
|
||||
byref(n), byref(left), byref(data)) != 0 or not data.value:
|
||||
return None
|
||||
try:
|
||||
if fmt.value == 32: # (32-bit items come as C longs)
|
||||
return list(ctypes.cast(data, POINTER(c_ulong))[: n.value])
|
||||
if fmt.value == 8:
|
||||
return ctypes.string_at(data, n.value)
|
||||
return None
|
||||
finally:
|
||||
self.lib.XFree(data)
|
||||
|
||||
def geometry(self, xid: int) -> tuple[Rect, bool] | None:
|
||||
"""(the window's picture area on screen, whether it's shown), or None if the window is gone."""
|
||||
self._guard()
|
||||
a = _Attrs()
|
||||
if not self.lib.XGetWindowAttributes(self.d, xid, byref(a)):
|
||||
return None
|
||||
x, y, child = c_int(), c_int(), c_ulong()
|
||||
if not self.lib.XTranslateCoordinates(self.d, xid, self.root, 0, 0, byref(x), byref(y), byref(child)):
|
||||
return None
|
||||
return Rect(x.value, y.value, a.width, a.height), a.map_state == 2 # IsViewable
|
||||
|
||||
def screen(self) -> Rect:
|
||||
g = self.geometry(self.root)
|
||||
return g[0] if g else Rect(0, 0, 1920, 1080)
|
||||
|
||||
def _children(self, xid: int) -> list[int]:
|
||||
root, parent, kids, n = c_ulong(), c_ulong(), c_void_p(), c_uint()
|
||||
if not self.lib.XQueryTree(self.d, xid, byref(root), byref(parent), byref(kids), byref(n)) or not kids.value:
|
||||
return []
|
||||
try:
|
||||
return list(ctypes.cast(kids, POINTER(c_ulong))[: n.value])
|
||||
finally:
|
||||
self.lib.XFree(kids)
|
||||
|
||||
def client_ids(self) -> list[int]:
|
||||
"""App windows: the window manager's list, or (no such list) top-level windows that carry WM_STATE."""
|
||||
ids = self.prop(self.root, "_NET_CLIENT_LIST")
|
||||
if ids:
|
||||
return [int(i) for i in ids]
|
||||
out = []
|
||||
for top in self._children(self.root):
|
||||
for xid in (top, *self._children(top)):
|
||||
if self.prop(xid, "WM_STATE") is not None:
|
||||
out.append(xid)
|
||||
break
|
||||
return out
|
||||
|
||||
def describe(self, xid: int) -> XWindow | None:
|
||||
g = self.geometry(xid)
|
||||
if g is None:
|
||||
return None
|
||||
title = self.prop(xid, "_NET_WM_NAME") or self.prop(xid, "WM_NAME") or b""
|
||||
cls = self.prop(xid, "WM_CLASS") or b""
|
||||
pid = self.prop(xid, "_NET_WM_PID") or [0]
|
||||
return XWindow(xid, title.decode(errors="replace") if isinstance(title, bytes) else "",
|
||||
cls.split(b"\0")[1].decode(errors="replace").lower() if isinstance(cls, bytes) and cls.count(b"\0") >= 2 else "",
|
||||
int(pid[0]) if isinstance(pid, list) and pid else 0, g[0].w, g[0].h)
|
||||
|
||||
def redirect(self, xid: int) -> bool:
|
||||
"""Keeps the window's whole picture off screen (Composite, automatic), so it can be read while covered. Lasts
|
||||
while this connection is open. False without the Composite extension."""
|
||||
self._guard()
|
||||
try:
|
||||
xc = ctypes.CDLL(ctypes.util.find_library("Xcomposite") or "libXcomposite.so.1")
|
||||
except OSError:
|
||||
return False
|
||||
ev, err = c_int(), c_int()
|
||||
xc.XCompositeQueryExtension.argtypes = [c_void_p, POINTER(c_int), POINTER(c_int)]
|
||||
if not xc.XCompositeQueryExtension(self.d, byref(ev), byref(err)):
|
||||
return False
|
||||
xc.XCompositeRedirectWindow.argtypes = [c_void_p, c_ulong, c_int]
|
||||
xc.XCompositeRedirectWindow(self.d, xid, 0) # CompositeRedirectAutomatic
|
||||
self.lib.XSync(self.d, 0)
|
||||
return True
|
||||
|
||||
def close(self) -> None:
|
||||
if self.d:
|
||||
self.lib.XCloseDisplay(self.d)
|
||||
self.d = None
|
||||
|
||||
|
||||
def find_windows(x: X | None = None) -> list[XWindow]:
|
||||
"""Windows that could be a game: on the window manager's list, with a title, big enough, and not this process's."""
|
||||
own_x = x is None
|
||||
x = x or X()
|
||||
try:
|
||||
found = []
|
||||
for xid in x.client_ids():
|
||||
w = x.describe(xid)
|
||||
if w is None or w.pid == os.getpid() or not w.title or w.w < MIN_SIZE[0] or w.h < MIN_SIZE[1]:
|
||||
continue
|
||||
found.append(w)
|
||||
return found
|
||||
finally:
|
||||
if own_x:
|
||||
x.close()
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- the source
|
||||
class FfmpegGrab:
|
||||
"""`ffmpeg -f x11grab -window_id ...` piping raw BGR frames of w x h. read() gives the next one (it waits for
|
||||
it, a 60th of a second at most while all is well), or None when ffmpeg ended (the window closed or changed size)."""
|
||||
|
||||
def __init__(self, display: str, xid: int, hz: int, w: int, h: int, exe: str | None = None, popen=None) -> None:
|
||||
import shutil
|
||||
import subprocess
|
||||
exe = exe or shutil.which("ffmpeg")
|
||||
if not exe:
|
||||
raise RuntimeError("window capture needs the ffmpeg program: install it (e.g. apt install ffmpeg)")
|
||||
self.w, self.h = w, h
|
||||
self.proc = (popen or subprocess.Popen)(grab_argv(exe, display, xid, hz), stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0)
|
||||
try: # a pipe that holds a whole frame, so ffmpeg never waits on us mid-frame (Linux; harmless if refused)
|
||||
import fcntl
|
||||
fcntl.fcntl(self.proc.stdout.fileno(), 1031, 1 << 20) # F_SETPIPE_SZ
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
def read(self):
|
||||
import numpy as np
|
||||
buf = np.empty((self.h, self.w, 3), np.uint8) # a new one each time: frames are never changed once handed on
|
||||
view, got = memoryview(buf).cast("B"), 0
|
||||
while got < len(view):
|
||||
n = self.proc.stdout.readinto(view[got:])
|
||||
if not n:
|
||||
return None
|
||||
got += n
|
||||
return buf
|
||||
|
||||
def error(self) -> str:
|
||||
"""What ffmpeg said as it ended (its last line), for the log."""
|
||||
try:
|
||||
if self.proc.poll() is None:
|
||||
return ""
|
||||
lines = self.proc.stderr.read().decode(errors="replace").strip().splitlines()
|
||||
return lines[-1] if lines else ""
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
self.proc.kill()
|
||||
self.proc.wait(timeout=2)
|
||||
except Exception: # noqa: BLE001 - closing
|
||||
pass
|
||||
for f in (self.proc.stdout, self.proc.stderr):
|
||||
try:
|
||||
f.close()
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
|
||||
def grab_argv(exe: str, display: str, xid: int, hz: int) -> list[str]:
|
||||
"""The ffmpeg command: the window's picture, hz times a second, as raw BGR on stdout, with nothing held back."""
|
||||
return [exe, "-hide_banner", "-loglevel", "error", "-nostdin", "-fflags", "nobuffer", "-flags", "low_delay",
|
||||
"-probesize", "32", "-analyzeduration", "0", "-f", "x11grab", "-window_id", str(xid),
|
||||
"-framerate", str(hz), "-draw_mouse", "0", "-i", display,
|
||||
"-f", "rawvideo", "-pix_fmt", "bgr24", "-fps_mode", "passthrough", "-"]
|
||||
|
||||
|
||||
def _open_grab(display: str, xid: int, hz: int, w: int, h: int):
|
||||
return FfmpegGrab(display, xid, hz, w, h)
|
||||
|
||||
|
||||
class X11WindowSource:
|
||||
"""Ticks from a window, each time its picture changes (a variable rate: wrap it in sources.Clock60). Iterate it
|
||||
once. `where()` says where the engine's picture goes: (the window's picture area, the screen), in screen pixels,
|
||||
or None while the window is minimised or gone."""
|
||||
|
||||
def __init__(self, target: XWindow, x: X | None = None, open_fn=None, hz: int = GRAB_HZ) -> None:
|
||||
from .sources import source_info
|
||||
self.target, self.x, self._hz = target, x or X(), hz
|
||||
self._open = open_fn or _open_grab
|
||||
g = self.x.geometry(target.xid)
|
||||
if g is None:
|
||||
raise RuntimeError(f"the {target.app} window closed")
|
||||
self._client, self._shown = g
|
||||
self.w, self.h = even(self._client.w), even(self._client.h)
|
||||
if self.w < MIN_SIZE[0] or self.h < MIN_SIZE[1]:
|
||||
raise RuntimeError(f"the {target.app} window is too small to capture ({self._client.w}x{self._client.h})")
|
||||
self.covered_ok = self.x.redirect(target.xid)
|
||||
self.info = source_info("window", name=f"{target.app} window", hz=float(hz))
|
||||
self.restarts, self.grabs, self.same = 0, 0, 0
|
||||
self._stop, self._container = False, None
|
||||
print(f"[window] {target.app} (xid {target.xid:#x}, pid {target.pid}): {self._client.w}x{self._client.h} at "
|
||||
f"{self._client.x},{self._client.y}, captured as {self.w}x{self.h}"
|
||||
+ ("" if self.covered_ok else "; no Composite extension, so anything on top of it is captured too"))
|
||||
|
||||
def where(self) -> tuple[Rect, Rect] | None:
|
||||
if self._client is None or not self._shown:
|
||||
return None
|
||||
c = self._client
|
||||
return Rect(c.x, c.y, even(c.w), even(c.h)), self.x.screen()
|
||||
|
||||
def _look(self) -> str:
|
||||
"""Re-reads the window's place: "gone", "hidden" (minimised), "resized" (capture restarts) or "same"."""
|
||||
g = self.x.geometry(self.target.xid)
|
||||
if g is None:
|
||||
return "gone"
|
||||
old = self._client
|
||||
self._client, self._shown = g
|
||||
if not self._shown:
|
||||
return "hidden"
|
||||
return "resized" if old is None or (old.w, old.h) != (g[0].w, g[0].h) else "same"
|
||||
|
||||
def _fit(self, img):
|
||||
"""A grab as a frame of the session's size: cropped to even sizes, scaled if the window changed size."""
|
||||
import numpy as np
|
||||
h, w = img.shape[:2]
|
||||
if (w, h) == (self.w, self.h):
|
||||
return img
|
||||
if (even(w), even(h)) == (self.w, self.h):
|
||||
return np.ascontiguousarray(img[: self.h, : self.w])
|
||||
import cv2
|
||||
return cv2.resize(img, (self.w, self.h), interpolation=cv2.INTER_LINEAR)
|
||||
|
||||
def __iter__(self):
|
||||
import numpy as np
|
||||
|
||||
from .io import Tick
|
||||
n, fails, last = 0, 0, None
|
||||
check = time.perf_counter() + CHECK_S
|
||||
while not self._stop:
|
||||
state = self._look()
|
||||
if state == "gone":
|
||||
print(f"[window] the {self.target.app} window closed")
|
||||
return
|
||||
if state == "hidden": # minimised: the last frame stays up until it's back
|
||||
time.sleep(CHECK_S)
|
||||
continue
|
||||
try:
|
||||
c = self._client
|
||||
self._container = grab = self._open(self.x.name, self.target.xid, self._hz, c.w, c.h)
|
||||
while True:
|
||||
raw = grab.read()
|
||||
now = time.perf_counter()
|
||||
if self._stop:
|
||||
return
|
||||
if raw is None:
|
||||
raise RuntimeError(grab.error() or "ffmpeg's capture ended")
|
||||
img = self._fit(raw)
|
||||
self.grabs += 1
|
||||
if last is not None and np.array_equal(img, last):
|
||||
self.same += 1 # the game drew nothing new since the last grab
|
||||
else:
|
||||
last = img
|
||||
yield Tick(img, now, n, t_ready=time.perf_counter())
|
||||
n += 1
|
||||
fails = 0
|
||||
if now >= check:
|
||||
check = now + CHECK_S
|
||||
state = self._look()
|
||||
if state != "same":
|
||||
self.restarts += state == "resized"
|
||||
break
|
||||
except Exception as e: # noqa: BLE001 - the grab failed (the window closed or changed mid-read): look again
|
||||
if self._stop:
|
||||
return
|
||||
fails += 1
|
||||
if fails >= 5:
|
||||
print(f"[window] capture keeps failing ({str(e)[:160]}); stopping")
|
||||
return
|
||||
if self.x.geometry(self.target.xid) is not None:
|
||||
print(f"[window] capture stopped ({str(e)[:160]}); trying again")
|
||||
time.sleep(CHECK_S)
|
||||
finally:
|
||||
self._close_container()
|
||||
|
||||
def _close_container(self) -> None:
|
||||
c, self._container = self._container, None
|
||||
if c is not None:
|
||||
try:
|
||||
c.close()
|
||||
except Exception: # noqa: BLE001 - closing
|
||||
pass
|
||||
|
||||
def close(self) -> None:
|
||||
"""Stops at the next grab (the capture is closed by the thread reading it)."""
|
||||
self._stop = True
|
||||
print(f"[window] {self.grabs} grabs, {self.same} unchanged (left out); capture restarted "
|
||||
f"{self.restarts} time(s) for a resize")
|
||||
|
||||
|
||||
def open_window(query: str, wait_s: float = 0.0, sleep=time.sleep) -> X11WindowSource:
|
||||
"""--window QUERY: the window, waiting up to wait_s for it to open (a game that was just started), or a clear
|
||||
error naming what was looked for."""
|
||||
why = session_problem()
|
||||
if why:
|
||||
raise RuntimeError(why)
|
||||
x = X()
|
||||
deadline = time.monotonic() + wait_s
|
||||
said = False
|
||||
while True:
|
||||
target = pick(query, find_windows(x))
|
||||
if target is not None:
|
||||
if wait_s: # a game's window often opens small (a splash) and grows: give it a moment to settle
|
||||
sleep(1.0)
|
||||
target = pick(query, find_windows(x)) or target
|
||||
return X11WindowSource(target, x)
|
||||
if time.monotonic() >= deadline:
|
||||
x.close()
|
||||
raise RuntimeError(f"no window matches {query!r}" + (f" after {wait_s:.0f} s" if wait_s else "")
|
||||
+ " (python -m framegen.window_x11 --list shows what's found)")
|
||||
if not said:
|
||||
said = True
|
||||
print(f"[window] waiting for a window matching {query!r} (up to {wait_s:.0f} s)", flush=True)
|
||||
sleep(0.25)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- command line
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--list", action="store_true", help="the windows that could be captured")
|
||||
ap.add_argument("--json", action="store_true")
|
||||
a = ap.parse_args(argv)
|
||||
why = session_problem()
|
||||
if why:
|
||||
print(json.dumps({"windows": [], "why": why}) if a.json else why)
|
||||
return 0
|
||||
windows = find_windows()
|
||||
if a.json:
|
||||
print(json.dumps({"windows": [{**asdict(w), "app": w.app} for w in windows]}))
|
||||
else:
|
||||
for w in windows:
|
||||
print(f"xid:{w.xid:<10} pid:{w.pid:<8} {w.cls:20} {w.w}x{w.h} {w.title}")
|
||||
if not windows:
|
||||
print("no windows found")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+18
-4
@@ -239,6 +239,10 @@ def main() -> int:
|
||||
ap.add_argument("--window", metavar="APP",
|
||||
help="--source window: the app's window, as a preset (ps-remote-play, xbox, moonlight), exe:NAME, "
|
||||
"hwnd:N or part of its title (framegen/window.py, Experimental)")
|
||||
ap.add_argument("--window-wait", metavar="SECONDS", type=float, default=0.0,
|
||||
help="--source window on Linux: wait this long for the window to open (a game just started)")
|
||||
ap.add_argument("--watermark", choices=["on", "off"], default=None,
|
||||
help="the Summit watermark in a corner of the video window. Default: the saved setting (on)")
|
||||
ap.add_argument("--window-keys", metavar="KEYS", default=None,
|
||||
help="--source window: SmoovPlay's shortcuts while the app has the keys, as "
|
||||
'"menu=Ctrl+Alt+K;quit=Ctrl+Alt+End" (actions: menu, quit, fullscreen, stats, smooth; the '
|
||||
@@ -411,9 +415,13 @@ def main() -> int:
|
||||
except ValueError as e:
|
||||
ap.error(f"--window-keys: {e}")
|
||||
from framegen.sources import Clock60
|
||||
from framegen.window import open_window
|
||||
try:
|
||||
src = Clock60(open_window(a.window)) # the app draws when it likes: put it on a 60 Hz beat
|
||||
try: # the app draws when it likes: put it on a 60 Hz beat
|
||||
if sys.platform == "win32":
|
||||
from framegen.window import open_window
|
||||
src = Clock60(open_window(a.window))
|
||||
else: # Linux, X11 (framegen/window_x11.py)
|
||||
from framegen.window_x11 import open_window
|
||||
src = Clock60(open_window(a.window, wait_s=a.window_wait))
|
||||
except RuntimeError as e:
|
||||
print(f"[window] {e}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -430,7 +438,8 @@ def main() -> int:
|
||||
("interp", False if a.off else None), ("vsync", a.vsync), ("fullscreen", a.fullscreen),
|
||||
("minimize_chiaki", a.minimize_chiaki), ("simulate_30", True if a.test_mode else None),
|
||||
("steady_hud", a.steady_hud), ("vfg_quality", a.vfg_quality), ("present", a.present),
|
||||
("hdr", a.hdr), ("fill", a.fill), ("replay", a.replay), ("replay_clip", a.clip_length)):
|
||||
("hdr", a.hdr), ("fill", a.fill), ("replay", a.replay), ("replay_clip", a.clip_length),
|
||||
("watermark", None if a.watermark is None else a.watermark == "on")):
|
||||
if value is not None:
|
||||
settings.override(key, value)
|
||||
if a.look:
|
||||
@@ -627,6 +636,11 @@ def main() -> int:
|
||||
if kind == "chiaki" and hasattr(src, "set_hdr"):
|
||||
src.set_hdr(hdr_out, hdr_peak if hdr10[0] else None, why=hdr_why)
|
||||
sink = MultiSink(window, FileSink(a.out, src.w, src.h) if a.out else None)
|
||||
if window is not None and sys.platform != "win32":
|
||||
# `summit run --enhance` (or anything else) stops the engine with SIGTERM: leave as Esc does, so the window
|
||||
# closes, clips finish saving and the summary is printed.
|
||||
import signal
|
||||
signal.signal(signal.SIGTERM, lambda *_: setattr(window, "cmd", "quit"))
|
||||
settings.watch(model_rows) # before Remote's own watcher, so what it publishes is already up to date
|
||||
model_rows()
|
||||
remote = None
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""The Summit watermark (framegen/watermark.py) and its setting."""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from framegen import watermark as wm
|
||||
from framegen.settings import BY_KEY, Settings
|
||||
|
||||
|
||||
def test_text_and_default():
|
||||
assert wm.TEXT == "summit - git.molberg.cloud/alex/summit"
|
||||
spec = BY_KEY["watermark"]
|
||||
assert spec.default is True and spec.choices == (True, False)
|
||||
s = Settings()
|
||||
assert s.watermark is True
|
||||
s.override("watermark", False)
|
||||
assert s.watermark is False
|
||||
|
||||
|
||||
def test_it_is_small_and_has_text_in_it():
|
||||
img = wm.render(1.0)
|
||||
h, w = img.shape[:2]
|
||||
assert h <= 30 and w <= 360 # a thin strip, well under a fifth of a 1080p picture's width
|
||||
assert (img == wm.BG).all(axis=2).mean() < 0.97 # some pixels are text
|
||||
assert (img[0] == wm.BG).all() and (img[-1] == wm.BG).all() # with a margin of box around it
|
||||
half = wm.render(0.5)
|
||||
assert half.shape[1] < w
|
||||
|
||||
|
||||
def test_corner_keeps_clear_of_the_stats():
|
||||
assert wm.corner("top-left") == "bottom-left"
|
||||
assert wm.corner("bottom-right") == "bottom-left"
|
||||
assert wm.corner("bottom-left") == "bottom-right"
|
||||
assert wm.corner("bottom-left", stats_on=False) == "bottom-left"
|
||||
|
||||
|
||||
def test_place_in_gl_coordinates():
|
||||
# picture at (10, 20), 1000x500; a 100x20 panel with a 12 px margin. GL y grows upwards; `top` is its top edge.
|
||||
assert wm.place("bottom-left", 100, 20, 10, 20, 1000, 500, 12) == (22, 52)
|
||||
assert wm.place("bottom-right", 100, 20, 10, 20, 1000, 500, 12) == (898, 52)
|
||||
assert wm.place("top-left", 100, 20, 10, 20, 1000, 500, 12) == (22, 508)
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Linux window capture (framegen/window_x11.py): picking a window, the ffmpeg command and pipe, and the source's
|
||||
behaviour (unchanged grabs left out, resize, minimise, close), all with a fake X server and a fake ffmpeg."""
|
||||
import io
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from framegen import window_x11 as wx
|
||||
from framegen.window_x11 import Rect, XWindow
|
||||
|
||||
WINS = [XWindow(10, "Voidrunner -- top-down arena shooter", "voidrunner", 500, 1280, 720),
|
||||
XWindow(11, "Voidrunner launcher", "voidrunner", 499, 400, 300),
|
||||
XWindow(12, "~ : bash - Konsole", "konsole", 77, 1920, 1008)]
|
||||
|
||||
|
||||
def test_pick_by_title_takes_the_biggest_match():
|
||||
assert wx.pick("voidrunner", WINS).xid == 10
|
||||
assert wx.pick("KONSOLE", WINS).xid == 12
|
||||
assert wx.pick("nothing like it", WINS) is None
|
||||
|
||||
|
||||
def test_pick_by_xid_class_and_alternatives():
|
||||
assert wx.pick("xid:11", WINS).xid == 11
|
||||
assert wx.pick("hwnd:0xc", WINS).xid == 12
|
||||
assert wx.pick("class:konsole", WINS).xid == 12
|
||||
assert wx.pick("xid:99|class:voidrunner", WINS).xid == 10
|
||||
assert wx.pick("xid:notanumber", WINS) is None
|
||||
|
||||
|
||||
def test_pick_by_pid_includes_processes_it_started():
|
||||
family = lambda pid: {pid, 500} if pid == 400 else {pid} # 400 is a launch script that started 500
|
||||
assert wx.pick("pid:500", WINS, family).xid == 10
|
||||
assert wx.pick("pid:400", WINS, family).xid == 10
|
||||
assert wx.pick("pid:1", WINS, family) is None
|
||||
|
||||
|
||||
def test_pid_family_reads_proc(tmp_path):
|
||||
for pid, ppid, comm in ((100, 1, "sh"), (101, 100, "game (x86) :)"), (102, 101, "helper"), (200, 1, "other")):
|
||||
(tmp_path / str(pid)).mkdir()
|
||||
(tmp_path / str(pid) / "stat").write_text(f"{pid} ({comm}) S {ppid} 0 0 0")
|
||||
(tmp_path / "self").mkdir()
|
||||
assert wx.pid_family(100, str(tmp_path)) == {100, 101, 102}
|
||||
assert wx.pid_family(200, str(tmp_path)) == {200}
|
||||
assert wx.pid_family(5, "/nonexistent-proc") == {5}
|
||||
|
||||
|
||||
def test_wayland_is_refused_with_a_clear_reason():
|
||||
assert "Wayland" in wx.session_problem({"XDG_SESSION_TYPE": "wayland", "DISPLAY": ":0", "WAYLAND_DISPLAY": "wayland-0"})
|
||||
assert "DISPLAY" in wx.session_problem({})
|
||||
assert wx.session_problem({"XDG_SESSION_TYPE": "x11", "DISPLAY": ":0"}) is None
|
||||
|
||||
|
||||
def test_grab_command_names_the_window_and_pipes_raw_bgr():
|
||||
a = wx.grab_argv("ffmpeg", ":0", 0x2E00007, 60)
|
||||
assert a[a.index("-window_id") + 1] == str(0x2E00007)
|
||||
assert a[a.index("-f") + 1] == "x11grab" and a[a.index("-i") + 1] == ":0"
|
||||
assert a[a.index("-pix_fmt") + 1] == "bgr24" and a[-1] == "-"
|
||||
assert a.index("-window_id") < a.index("-i") # input options come before the input
|
||||
|
||||
|
||||
class FakeProc:
|
||||
def __init__(self, data: bytes, chunk: int = 7):
|
||||
self.stdout, self.stderr, self._chunk = io.BytesIO(data), io.BytesIO(b"note\nlast line\n"), chunk
|
||||
raw = self.stdout.readinto
|
||||
self.stdout.readinto = lambda view: raw(view[: self._chunk]) # short reads, as a pipe gives
|
||||
self.stdout.fileno = lambda: -1
|
||||
self.killed = False
|
||||
|
||||
def poll(self):
|
||||
return 0
|
||||
|
||||
def kill(self):
|
||||
self.killed = True
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
|
||||
|
||||
def test_ffmpeg_grab_reads_whole_frames_from_short_reads():
|
||||
frames = [np.full((4, 6, 3), v, np.uint8) for v in (1, 2)]
|
||||
proc = FakeProc(b"".join(f.tobytes() for f in frames) + b"xx") # (a cut-off third frame)
|
||||
g = wx.FfmpegGrab(":0", 1, 60, 6, 4, exe="ffmpeg", popen=lambda *a, **k: proc)
|
||||
assert np.array_equal(g.read(), frames[0]) and np.array_equal(g.read(), frames[1])
|
||||
assert g.read() is None
|
||||
assert g.error() == "last line"
|
||||
g.close()
|
||||
assert proc.killed
|
||||
|
||||
|
||||
def test_ffmpeg_missing_says_so(monkeypatch):
|
||||
monkeypatch.setattr("shutil.which", lambda _: None)
|
||||
with pytest.raises(RuntimeError, match="ffmpeg"):
|
||||
wx.FfmpegGrab(":0", 1, 60, 6, 4)
|
||||
|
||||
|
||||
class FakeX:
|
||||
"""geometry() answers from a script: a list of (Rect, shown) or None (gone); the last one repeats."""
|
||||
name = ":9"
|
||||
|
||||
def __init__(self, script):
|
||||
self.script, self.redirected = list(script), []
|
||||
|
||||
def geometry(self, xid):
|
||||
return self.script.pop(0) if len(self.script) > 1 else self.script[0]
|
||||
|
||||
def redirect(self, xid):
|
||||
self.redirected.append(xid)
|
||||
return True
|
||||
|
||||
def screen(self):
|
||||
return Rect(0, 0, 1920, 1080)
|
||||
|
||||
|
||||
class FakeGrab:
|
||||
def __init__(self, frames):
|
||||
self.frames, self.closed = list(frames), False
|
||||
|
||||
def read(self):
|
||||
return self.frames.pop(0) if self.frames else None
|
||||
|
||||
def error(self):
|
||||
return "ended"
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def frame(v, w=320, h=240):
|
||||
return np.full((h, w, 3), v, np.uint8)
|
||||
|
||||
|
||||
def test_source_leaves_out_unchanged_grabs(monkeypatch):
|
||||
monkeypatch.setattr(wx, "CHECK_S", 0.0)
|
||||
monkeypatch.setattr(wx.time, "sleep", lambda s: None)
|
||||
here = (Rect(100, 50, 320, 240), True)
|
||||
x = FakeX([here, here, here, here, here, here, None]) # open, loop start, 4 checks, then the window closes
|
||||
grab = FakeGrab([frame(1), frame(1), frame(2), frame(2), frame(3)])
|
||||
opened = []
|
||||
src = wx.X11WindowSource(XWindow(7, "Game", "game", 1, 320, 240), x,
|
||||
open_fn=lambda *a: opened.append(a) or grab)
|
||||
assert (src.w, src.h) == (320, 240) and x.redirected == [7]
|
||||
assert src.info.kind == "window" and src.info.rate == "variable"
|
||||
ticks = list(src)
|
||||
assert [int(t.frame[0, 0, 0]) for t in ticks] == [1, 2, 3]
|
||||
assert [t.index for t in ticks] == [0, 1, 2]
|
||||
assert src.grabs == 5 and src.same == 2
|
||||
assert opened[0] == (":9", 7, wx.GRAB_HZ, 320, 240) and grab.closed
|
||||
|
||||
|
||||
def test_source_restarts_and_scales_after_a_resize(monkeypatch):
|
||||
monkeypatch.setattr(wx, "CHECK_S", 0.0)
|
||||
monkeypatch.setattr(wx.time, "sleep", lambda s: None)
|
||||
small, big = (Rect(0, 0, 320, 240), True), (Rect(0, 0, 640, 480), True)
|
||||
x = FakeX([small, small, big, big, big, None])
|
||||
grabs = [FakeGrab([frame(1)]), FakeGrab([frame(2, 640, 480)])]
|
||||
sizes = []
|
||||
src = wx.X11WindowSource(XWindow(7, "Game", "game", 1, 320, 240), x,
|
||||
open_fn=lambda d, xid, hz, w, h: sizes.append((w, h)) or grabs.pop(0))
|
||||
ticks = list(src)
|
||||
assert sizes == [(320, 240), (640, 480)] # ffmpeg is asked for the window's new size
|
||||
assert [t.frame.shape for t in ticks] == [(240, 320, 3), (240, 320, 3)] # frames keep the session's size
|
||||
assert src.restarts == 1
|
||||
|
||||
|
||||
def test_source_odd_sizes_are_cropped_to_even():
|
||||
x = FakeX([(Rect(0, 0, 321, 241), True)])
|
||||
src = wx.X11WindowSource(XWindow(7, "Game", "game", 1, 321, 241), x, open_fn=lambda *a: None)
|
||||
assert (src.w, src.h) == (320, 240)
|
||||
out = src._fit(frame(5, 321, 241))
|
||||
assert out.shape == (240, 320, 3) and out.flags["C_CONTIGUOUS"]
|
||||
where = src.where()
|
||||
assert where[0] == Rect(0, 0, 320, 240) and where[1] == Rect(0, 0, 1920, 1080)
|
||||
|
||||
|
||||
def test_minimised_window_has_no_place_and_tiny_ones_are_refused():
|
||||
x = FakeX([(Rect(0, 0, 320, 240), True), (Rect(0, 0, 320, 240), False)])
|
||||
src = wx.X11WindowSource(XWindow(7, "Game", "game", 1, 320, 240), x, open_fn=lambda *a: None)
|
||||
assert src._look() == "hidden" and src.where() is None
|
||||
with pytest.raises(RuntimeError, match="too small"):
|
||||
wx.X11WindowSource(XWindow(8, "Tip", "tip", 1, 40, 20), FakeX([(Rect(0, 0, 40, 20), True)]))
|
||||
with pytest.raises(RuntimeError, match="closed"):
|
||||
wx.X11WindowSource(XWindow(9, "Gone", "gone", 1, 320, 240), FakeX([None]))
|
||||
|
||||
|
||||
def test_clock60_puts_the_window_on_a_beat():
|
||||
"""The variable-rate window source through sources.Clock60: a beat with no new grab repeats the last frame."""
|
||||
from framegen.io import Tick
|
||||
from framegen.sources import Clock60, source_info
|
||||
|
||||
import threading
|
||||
hold = threading.Event()
|
||||
|
||||
class Src:
|
||||
info = source_info("window")
|
||||
|
||||
def __iter__(self):
|
||||
yield Tick(frame(1), 0.0, 0)
|
||||
hold.wait(5) # the game draws nothing more for a while
|
||||
|
||||
ticks = []
|
||||
for t in Clock60(Src(), sleep=lambda s: None):
|
||||
ticks.append(t)
|
||||
if len(ticks) == 3:
|
||||
break
|
||||
hold.set()
|
||||
assert ticks[0].new_hint is None # a fresh frame: the pipeline compares pictures
|
||||
assert [t.new_hint for t in ticks[1:]] == [False, False] # beats with nothing new are repeats for certain
|
||||
assert all(t.frame is ticks[0].frame for t in ticks)
|
||||
|
||||
|
||||
@pytest.mark.skipif(not os.environ.get("DISPLAY") or os.environ.get("XDG_SESSION_TYPE") == "wayland",
|
||||
reason="needs a real X11 display")
|
||||
def test_real_x_server_lists_windows():
|
||||
x = wx.X()
|
||||
try:
|
||||
assert x.screen().w > 0
|
||||
for w in wx.find_windows(x):
|
||||
assert w.title and w.w >= wx.MIN_SIZE[0]
|
||||
finally:
|
||||
x.close()
|
||||
Reference in new issue
Block a user