"""The frame server: catches each client up, then feeds it every frame. One thread per client is the simple design that satisfies the contract ("a stalled client is slowed, not queued"): a client's socket is written to synchronously, and a slow write blocks only that client. """ from __future__ import annotations import argparse import errno import logging import os import selectors import signal import socket import stat import sys import threading import time from typing import Iterable from . import protocol from .capture import CaptureBackend, CommandCapture DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock" #: Contract: the published socket is mode 0660 (ownership is the unit's job). SOCKET_MODE = 0o660 #: Contract default for `services.hyprland-headless-stream.captureCommand`. DEFAULT_CAPTURE_COMMAND = ["grim", "-t", "png", "-"] _BACKLOG = 64 _WAIT_TICK = 0.2 # how often a blocked client thread re-checks for shutdown log = logging.getLogger("hhstream.server") class FrameServer: """Publishes one capture stream to any number of clients. A single capture thread holds exactly one frame -- the most recent one -- and every client thread sends whatever is in that slot when it is ready for another frame. That is how frames get dropped for a slow client instead of queued: there is no queue, and memory does not grow with the number of stalled clients. """ def __init__(self, socket_path: str, capture: CaptureBackend, fps: int, fmt: str = "image/png") -> None: if isinstance(fps, bool) or not isinstance(fps, int) or fps <= 0: raise ValueError(f"fps must be a positive int, got {fps!r}") self.socket_path = socket_path self.capture = capture self.fps = fps self.fmt = fmt #: set once the socket is bound and listening (tests wait on it) self.ready = threading.Event() self.frames_captured = 0 self.capture_failures = 0 self._cond = threading.Condition() self._frame: bytes | None = None self._seq = 0 self._hello: bytes | None = None self._stop = threading.Event() self._listener: socket.socket | None = None self._bound_inode: tuple[int, int] | None = None self._clients: list[threading.Thread] = [] # Closing a listening socket does not reliably interrupt a blocked # accept(), so the accept loop selects on this pair as well and stop() # pokes it. self._wake_r, self._wake_w = socket.socketpair() # -- serving --------------------------------------------------------- def serve_forever(self) -> None: """Bind, then serve until stopped. A stale socket file is replaced.""" try: self._bind() listener = self._listener assert listener is not None threading.Thread(target=self._capture_loop, name="hhstream-capture", daemon=True).start() log.info("serving %s at %d fps (%s)", self.socket_path, self.fps, self.fmt) self._accept_loop(listener) finally: self.stop() self._wake_r.close() self._wake_w.close() def _accept_loop(self, listener: socket.socket) -> None: with selectors.DefaultSelector() as selector: try: selector.register(listener, selectors.EVENT_READ) selector.register(self._wake_r, selectors.EVENT_READ) except (OSError, ValueError): if self._stop.is_set(): return # stopped between binding and the accept loop raise while not self._stop.is_set(): try: events = selector.select() except OSError as exc: if self._stop.is_set(): return log.warning("select failed: %s", exc) self._stop.wait(0.05) # never spin on a repeating error continue if any(key.fileobj is self._wake_r for key, _ in events): return try: conn, _ = listener.accept() except OSError as exc: if self._stop.is_set(): return log.warning("accept failed: %s", exc) self._stop.wait(0.05) continue self._clients = [t for t in self._clients if t.is_alive()] thread = threading.Thread( target=self._serve_client, args=(conn,), name="hhstream-client", daemon=True, ) self._clients.append(thread) thread.start() def stop(self) -> None: """Ask the accept loop, the capture thread and every client to finish.""" self._stop.set() with self._cond: self._cond.notify_all() try: self._wake_w.send(b"\x00") # unblock the accept loop except OSError: pass listener, self._listener = self._listener, None if listener is not None: try: listener.close() except OSError: pass self._unlink_own_socket() # -- capture --------------------------------------------------------- def _capture_loop(self) -> None: interval = 1.0 / self.fps while not self._stop.is_set(): started = time.monotonic() try: payload = self.capture.grab() width, height = self.capture.size() except Exception as exc: # a backend may raise anything self.capture_failures += 1 # Contract: capture erroring keeps the socket up and retries; it # never exits and never publishes a partial frame. log.warning("capture failed (%d so far): %s", self.capture_failures, exc) else: self._publish(payload, width, height) remaining = interval - (time.monotonic() - started) if remaining > 0: self._stop.wait(remaining) def _publish(self, payload: bytes, width: int, height: int) -> None: with self._cond: if self._hello is None: if width > 0 and height > 0: # Contract: never a Hello with zero size. self._hello = protocol.hello(width, height, self.fmt, self.fps) else: log.warning("ignoring frame with zero size %dx%d", width, height) return self._frame = payload self._seq += 1 self.frames_captured += 1 self._cond.notify_all() # -- one client ------------------------------------------------------ def _serve_client(self, conn: socket.socket) -> None: peer = conn.fileno() drain = threading.Thread( target=self._drain, args=(conn,), name="hhstream-drain", daemon=True ) drain.start() try: hello = self._wait_for_hello() if hello is None: return conn.sendall(hello) last_seq = 0 while not self._stop.is_set(): payload, last_seq = self._wait_for_frame(last_seq) if payload is None: return conn.sendall(protocol.frame(payload)) except OSError as exc: # The whole point: one client dying mid-frame is this thread's # problem and nobody else's. log.info("client %s went away: %s", peer, exc) except Exception: log.exception("client %s failed", peer) finally: try: conn.shutdown(socket.SHUT_RDWR) except OSError: pass try: conn.close() except OSError: pass def _drain(self, conn: socket.socket) -> None: """Read and discard anything a client sends (contract: v1 reserved).""" try: while not self._stop.is_set(): if not conn.recv(4096): return except OSError: return def _wait_for_hello(self) -> bytes | None: """Block until the Hello is known (a frame has been captured).""" with self._cond: while self._hello is None and not self._stop.is_set(): self._cond.wait(_WAIT_TICK) return self._hello def _wait_for_frame(self, last_seq: int) -> tuple[bytes | None, int]: """Block until a frame newer than `last_seq` exists, then take the latest. Everything captured while this client was busy is simply skipped. """ with self._cond: while self._seq == last_seq and not self._stop.is_set(): self._cond.wait(_WAIT_TICK) if self._seq == last_seq: return None, last_seq return self._frame, self._seq # -- socket ---------------------------------------------------------- def _bind(self) -> None: path = self.socket_path parent = os.path.dirname(os.path.abspath(path)) if parent: os.makedirs(parent, exist_ok=True) self._replace_stale(path) listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) try: listener.bind(path) os.chmod(path, SOCKET_MODE) listener.listen(_BACKLOG) except OSError: listener.close() raise self._listener = listener info = os.lstat(path) self._bound_inode = (info.st_dev, info.st_ino) self.ready.set() @staticmethod def _replace_stale(path: str) -> None: """Remove a leftover socket file so a stale one cannot block startup.""" try: info = os.lstat(path) except FileNotFoundError: return if not stat.S_ISSOCK(info.st_mode): raise OSError( errno.EEXIST, f"{path} exists and is not a socket; refusing to remove it", ) os.unlink(path) def _unlink_own_socket(self) -> None: """Tidy the socket file away, but only if it is still the one we bound. A restart that has already put its own socket there must keep it. """ if self._bound_inode is None: return try: info = os.lstat(self.socket_path) if (info.st_dev, info.st_ino) == self._bound_inode: os.unlink(self.socket_path) except OSError: pass self._bound_inode = None # -- CLI ----------------------------------------------------------------- #: `--format png` is the module's spelling; the Hello carries the MIME type. _MIME = {"png": "image/png", "jpeg": "image/jpeg"} _CAPTURE_FLAG = "--capture-command" def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="hhstream-server", description="Publish a headless Hyprland session's frames on a Unix socket.", ) parser.add_argument( "--socket", default=DEFAULT_SOCKET, metavar="PATH", help="socket to publish frames on (default: %(default)s)", ) parser.add_argument( "--fps", type=_positive_int, default=30, metavar="N", help="target capture rate, advertised in the Hello (default: %(default)s)", ) parser.add_argument( "--format", choices=sorted(_MIME), default="png", help="frame encoding (default: %(default)s)", ) parser.add_argument( _CAPTURE_FLAG, action="append", dest="capture_command", metavar="TOKEN", help="one argv token of the capture command; repeat once per token " "(default: %s). Use --capture-command=-t for tokens starting " "with a dash." % " ".join(DEFAULT_CAPTURE_COMMAND), ) return parser def main(argv: Iterable[str] | None = None) -> int: args = build_parser().parse_args(_join_capture_tokens(argv)) logging.basicConfig( level=logging.INFO, stream=sys.stderr, format="%(asctime)s %(levelname)s %(message)s", ) capture_command = args.capture_command or _default_capture_command(args.format) server = FrameServer( args.socket, CommandCapture(capture_command), args.fps, fmt=_MIME[args.format], ) _install_signal_handlers(server) try: server.serve_forever() except KeyboardInterrupt: server.stop() except OSError as exc: log.error("cannot serve on %s: %s", args.socket, exc) return 1 return 0 def _default_capture_command(fmt: str) -> list[str]: return ["grim", "-t", fmt, "-"] def _positive_int(text: str) -> int: value = int(text) if value <= 0: raise argparse.ArgumentTypeError(f"must be positive, got {text!r}") return value def _join_capture_tokens(argv: Iterable[str] | None) -> list[str] | None: """Rewrite `--capture-command X` as `--capture-command=X`. Capture tokens are argv tokens, and real ones start with a dash (`-t`, `-` in the default `grim -t png -`). argparse would read those as options, so the separated form is folded into the `=` form before it sees them. """ if argv is None: argv = sys.argv[1:] tokens = list(argv) out: list[str] = [] i = 0 while i < len(tokens): token = tokens[i] if token == "--": # everything after this is positional; leave it alone out.extend(tokens[i:]) break if token == _CAPTURE_FLAG and i + 1 < len(tokens): out.append(f"{_CAPTURE_FLAG}={tokens[i + 1]}") i += 2 continue out.append(token) i += 1 return out def _install_signal_handlers(server: FrameServer) -> None: def handler(signum, _frame): # pragma: no cover - needs a real signal log.info("signal %d, shutting down", signum) server.stop() for signum in (signal.SIGINT, signal.SIGTERM): try: signal.signal(signum, handler) except ValueError: pass # not the main thread (embedded in a test); nothing to do __all__ = ["FrameServer", "DEFAULT_SOCKET", "CaptureBackend", "CommandCapture", "socket", "build_parser", "main"]