- Engine: load pyGLFW's X11 build when the overlay needs XWayland on a Wayland session (its Wayland-only build made the engine fail with "glfw init failed") - Engine: "dir:FOLDER" window rule (a process running from the game's folder, Wine's Z:\ paths included) and "ask:" (wait for a rule picked in the launcher, read live from SUMMIT_WINDOW_FILE while it waits) - Enhance for non-Steam games in Steam, Lutris and Heroic, and native Steam games: window rule from the game's .exe class and install folder - Per-game "window" profile setting (Profile > Game window, `summit profile set --window`), which wins over the automatic rule - Now playing: Enhance status, "Pick the game's window" (W); the picker opens by itself when the engine has no rule or found nothing in 20 s, lists new windows first, and saves the pick to the game's profile and hands it to the engine - `summit windows`: open windows and the rule each one would get - Window placement follows dir: rules too Co-Authored-By: Claude Opus 5.5 <[email protected]>
600 lines
27 KiB
Python
600 lines
27 KiB
Python
"""Window capture on Linux, X11 and XWayland windows (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), "dir:FOLDER" (a process running from the game's folder: games started through Steam, Lutris or Heroic), 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 windows only: on an X11 session any window, on a Wayland session the XWayland ones (read through XWayland's
|
|
DISPLAY; checked on KDE Plasma 6.8 Wayland with an NVIDIA GPU). Native Wayland windows: framegen/window_portal.py.
|
|
- 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 _norm_path(p: str) -> str:
|
|
"""A path to compare by: "/" separators, lower case, no trailing "/". Wine's "Z:\\games\\x.exe" (drive Z: is the
|
|
Linux root) becomes "/games/x.exe"."""
|
|
p = p.strip().strip('"').replace("\\", "/")
|
|
if len(p) > 2 and p[1] == ":" and p[0].lower() == "z":
|
|
p = p[2:]
|
|
return p.rstrip("/").lower()
|
|
|
|
|
|
def under(path: str, folder: str) -> bool:
|
|
"""Whether `path` is `folder` or inside it (Wine paths count, case is ignored: Wine's paths don't keep it)."""
|
|
p, f = _norm_path(path), _norm_path(folder)
|
|
return bool(f) and (p == f or p.startswith(f + "/"))
|
|
|
|
|
|
def pid_in_dir(pid: int, folder: str, proc: str = "/proc") -> bool:
|
|
"""Whether process `pid` belongs to the game in `folder`: it runs from there (its working directory or its
|
|
program is in it) or was started with a file in it (a Wine game's command line names its .exe, often as
|
|
"Z:\\..."). Steam, Lutris and Heroic all start a game in its own folder, so this finds a game they started
|
|
without knowing its window class or process in advance."""
|
|
if pid <= 0:
|
|
return False
|
|
base = os.path.join(proc, str(pid))
|
|
for link in ("cwd", "exe"):
|
|
try:
|
|
if under(os.readlink(os.path.join(base, link)), folder):
|
|
return True
|
|
except OSError:
|
|
pass
|
|
try:
|
|
with open(os.path.join(base, "cmdline"), "rb") as f:
|
|
args = f.read().decode(errors="replace").split("\0")
|
|
except OSError:
|
|
return False
|
|
return any(a and under(a, folder) for a in args)
|
|
|
|
|
|
def pick(query: str, windows: list[XWindow], family=pid_family, in_dir=pid_in_dir) -> XWindow | None:
|
|
"""The window `query` names: "xid:N" (or "hwnd:N"), "pid:N", "class:NAME" (or "exe:NAME"), "dir:FOLDER" (a
|
|
process running from that folder, see pid_in_dir), 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, in_dir))), None)
|
|
q = query.strip()
|
|
low = q.lower()
|
|
if not q or low.startswith("ask:"): # "ask:": no rule yet, the window is picked in Summit (live_query)
|
|
return None
|
|
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("dir:"):
|
|
folder = q[4:].strip()
|
|
matches = [w for w in windows if folder and in_dir(w.pid, folder)]
|
|
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 X11 window capture can't run in this session, or None if it can. On a Wayland session it reads XWayland
|
|
windows (games that run through XWayland: Proton, Wine and most older native games), so it needs DISPLAY there
|
|
too; native Wayland windows go through framegen/window_portal.py instead."""
|
|
if not env.get("DISPLAY"):
|
|
if env.get("XDG_SESSION_TYPE", "").lower() == "wayland" or env.get("WAYLAND_DISPLAY"):
|
|
return "no XWayland in this Wayland session (DISPLAY isn't set), so X11 windows can't be read"
|
|
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")
|
|
|
|
|
|
class LiveQuery:
|
|
"""The --window rule while the engine waits for the game's window, which the player can change from Summit's
|
|
launcher: `summit run` names a file in SUMMIT_WINDOW_FILE, and the launcher writes the rule of the window picked
|
|
there into it (and saves it in the game's profile). Read on every look; a new rule restarts the wait."""
|
|
|
|
def __init__(self, query: str, env=os.environ) -> None:
|
|
self.base, self.path, self.now = query, env.get("SUMMIT_WINDOW_FILE") or "", query
|
|
|
|
def get(self) -> str:
|
|
"""The rule now; when it changed, says so (the launcher reads that line)."""
|
|
q = self.base
|
|
if self.path:
|
|
try:
|
|
with open(self.path, encoding="utf-8") as f:
|
|
q = f.read().strip() or self.base
|
|
except OSError:
|
|
pass
|
|
if q != self.now:
|
|
self.now = q
|
|
print(f"[window] now looking for {q!r} (picked in Summit)", flush=True)
|
|
return q
|
|
|
|
|
|
def waiting_line(query: str, wait_s: float) -> str:
|
|
"""What the engine says while it waits; Summit's launcher looks for "[window] waiting for"."""
|
|
if not query.strip() or query.strip().lower().startswith("ask:"):
|
|
return f"[window] waiting for the game's window to be picked in Summit (up to {wait_s:.0f} s)"
|
|
return f"[window] waiting for a window matching {query!r} (up to {wait_s:.0f} s)"
|
|
|
|
|
|
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
|
|
live = LiveQuery(query)
|
|
while True:
|
|
before, query = live.now, live.get()
|
|
if query != before:
|
|
deadline = time.monotonic() + max(wait_s, 60.0) # a rule picked late still gets its time
|
|
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(waiting_line(query, wait_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())
|