server, client: implement the v1 frame protocol end to end
Fill in the bodies the skeleton left as NotImplementedError, to docs/CONTRACT.md: - protocol: the `\n`-terminated JSON Hello and the `<ascii length>\n<payload>` frame, both directions. Malformed input raises (ValueError for a bad length prefix, EOFError for a truncated payload), never hangs on endless garbage and never silently truncates; a huge length prefix is not pre-allocated. - capture: CommandCapture runs the configured command and reports a missing binary, a non-zero exit, a timeout and empty output as CaptureError, with the helper's stderr folded into the message so nothing leaks to the server's own stdio. The Hello's pixel size is read from the frame's PNG/JPEG header, so no compositor query is needed and an injected fake command behaves the same. - server: one capture thread holding only the newest frame plus one thread per client, which is what drops frames for a slow client instead of queueing them. Survives a client dying mid-write, keeps the socket up across capture failures, withholds the Hello until a size is known, replaces a stale socket file (but never a non-socket one) and publishes it mode 0660. - client: fetch()/read_stream() and the CLI, with --out suffixing per frame. --capture-command folds its separated form into `--flag=value` before argparse sees it, so the contract's default `grim -t png -` can actually be passed: its tokens start with a dash. Unit tests under tests/unit cover framing round-trips (including a payload containing `\n` and a zero-length frame), truncated and garbage prefixes, a stalled client not blocking a second one, a client dying mid-frame, frames being dropped rather than queued, and every capture failure mode. A fake capture command stands in for grim, so nothing needs a compositor or a GPU. They are deliberately not wired into flake.nix: `checks` belongs to another workstream. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FYJ8ZQ5AZaDErYTwXZe7N9
This commit is contained in:
1 parent
c0a59f5673
commit
4af6f7072a
12 files changed
+1825
-21
No files matched your search
+140
-5
@@ -7,9 +7,24 @@ produces frames in a unit test.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
from typing import Protocol
|
||||
|
||||
#: MIME types the contract allows, and the pixel-size probe for each.
|
||||
_SOF_MARKERS = frozenset(
|
||||
m for m in range(0xC0, 0xD0) if m not in (0xC4, 0xC8, 0xCC)
|
||||
)
|
||||
|
||||
|
||||
class CaptureError(RuntimeError):
|
||||
"""One capture attempt failed; the server catches this and keeps serving.
|
||||
|
||||
Covers every way the helper command can let us down: it is missing, it
|
||||
exits non-zero, it times out, or it writes nothing.
|
||||
"""
|
||||
|
||||
|
||||
class CaptureBackend(Protocol):
|
||||
def grab(self) -> bytes:
|
||||
@@ -22,17 +37,137 @@ class CaptureBackend(Protocol):
|
||||
|
||||
|
||||
class CommandCapture:
|
||||
"""Runs a helper that writes one frame to stdout (default: grim)."""
|
||||
"""Runs a helper that writes one frame to stdout (default: grim).
|
||||
|
||||
`env` is overlaid on the server's own environment (that is how the session
|
||||
variables -- `WAYLAND_DISPLAY`, `XDG_RUNTIME_DIR` -- reach the helper
|
||||
without having to restate `PATH`). The helper's stdout is the frame and its
|
||||
stderr is captured, so a chatty or failing helper never writes to the
|
||||
server's own stdout/stderr; the message ends up in the raised
|
||||
`CaptureError` instead.
|
||||
"""
|
||||
|
||||
def __init__(self, argv: list[str], env: dict[str, str] | None = None,
|
||||
timeout: float = 5.0) -> None:
|
||||
raise NotImplementedError
|
||||
argv = list(argv)
|
||||
if not argv:
|
||||
raise ValueError("capture command must not be empty")
|
||||
if timeout is not None and timeout <= 0:
|
||||
raise ValueError(f"capture timeout must be positive, got {timeout!r}")
|
||||
self.argv = argv
|
||||
self.env = dict(env) if env is not None else None
|
||||
self.timeout = timeout
|
||||
self._size: tuple[int, int] | None = None
|
||||
|
||||
def grab(self) -> bytes:
|
||||
raise NotImplementedError
|
||||
"""Run the helper once and return the bytes it wrote to stdout."""
|
||||
child_env = None
|
||||
if self.env is not None:
|
||||
child_env = dict(os.environ)
|
||||
child_env.update(self.env)
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
self.argv,
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
env=child_env,
|
||||
timeout=self.timeout,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise CaptureError(
|
||||
f"capture command {self.argv!r} timed out after {self.timeout}s"
|
||||
) from exc
|
||||
except OSError as exc:
|
||||
raise CaptureError(
|
||||
f"capture command {self.argv!r} could not be run: {exc}"
|
||||
) from exc
|
||||
if proc.returncode != 0:
|
||||
raise CaptureError(
|
||||
f"capture command {self.argv!r} exited {proc.returncode}: "
|
||||
f"{_tail(proc.stderr)}"
|
||||
)
|
||||
if not proc.stdout:
|
||||
raise CaptureError(
|
||||
f"capture command {self.argv!r} produced no output: "
|
||||
f"{_tail(proc.stderr)}"
|
||||
)
|
||||
measured = image_size(proc.stdout)
|
||||
if measured is not None:
|
||||
self._size = measured
|
||||
return proc.stdout
|
||||
|
||||
def size(self) -> tuple[int, int]:
|
||||
raise NotImplementedError
|
||||
"""Pixel size of the captured output, for the Hello.
|
||||
|
||||
Measured from the frame itself (the PNG/JPEG header), so no compositor
|
||||
query is needed and an injected fake command works the same way. The
|
||||
first successful measurement is remembered; `grab` refreshes it, so
|
||||
after a frame has been captured this costs nothing.
|
||||
"""
|
||||
if self._size is None:
|
||||
self.grab()
|
||||
if self._size is None:
|
||||
raise CaptureError(
|
||||
f"cannot determine pixel size from the output of {self.argv!r} "
|
||||
"(not a PNG or JPEG?)"
|
||||
)
|
||||
return self._size
|
||||
|
||||
|
||||
__all__ = ["CaptureBackend", "CommandCapture", "subprocess"]
|
||||
def image_size(data: bytes) -> tuple[int, int] | None:
|
||||
"""Pixel size of a PNG or JPEG frame, or None if it cannot be read."""
|
||||
return _png_size(data) or _jpeg_size(data)
|
||||
|
||||
|
||||
def _png_size(data: bytes) -> tuple[int, int] | None:
|
||||
if not data.startswith(b"\x89PNG\r\n\x1a\n") or len(data) < 24:
|
||||
return None
|
||||
if data[12:16] != b"IHDR":
|
||||
return None
|
||||
width, height = struct.unpack(">II", data[16:24])
|
||||
return (width, height) if width and height else None
|
||||
|
||||
|
||||
def _jpeg_size(data: bytes) -> tuple[int, int] | None:
|
||||
if not data.startswith(b"\xff\xd8"):
|
||||
return None
|
||||
i, n = 2, len(data)
|
||||
while i + 1 < n:
|
||||
if data[i] != 0xFF:
|
||||
i += 1 # resync on the next marker
|
||||
continue
|
||||
marker = data[i + 1]
|
||||
if marker == 0xFF:
|
||||
i += 1 # fill byte
|
||||
continue
|
||||
if marker in (0x01, 0xD8, 0xD9) or 0xD0 <= marker <= 0xD7:
|
||||
i += 2 # standalone marker, no payload
|
||||
continue
|
||||
if i + 4 > n:
|
||||
return None
|
||||
seglen = int.from_bytes(data[i + 2:i + 4], "big")
|
||||
if seglen < 2:
|
||||
return None
|
||||
if marker in _SOF_MARKERS:
|
||||
if i + 9 > n:
|
||||
return None
|
||||
height = int.from_bytes(data[i + 5:i + 7], "big")
|
||||
width = int.from_bytes(data[i + 7:i + 9], "big")
|
||||
return (width, height) if width and height else None
|
||||
i += 2 + seglen
|
||||
return None
|
||||
|
||||
|
||||
def _tail(stderr: bytes | None, limit: int = 400) -> str:
|
||||
if not stderr:
|
||||
return "no stderr"
|
||||
text = stderr.decode("utf-8", "replace").strip()
|
||||
if len(text) > limit:
|
||||
text = "..." + text[-limit:]
|
||||
return text or "no stderr"
|
||||
|
||||
|
||||
__all__ = ["CaptureBackend", "CommandCapture", "CaptureError", "image_size",
|
||||
"subprocess"]
|
||||
+102
-5
@@ -3,22 +3,119 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import pathlib
|
||||
import socket
|
||||
import sys
|
||||
from typing import Iterable
|
||||
|
||||
from . import protocol
|
||||
|
||||
DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock"
|
||||
|
||||
|
||||
def fetch(socket_path: str, count: int = 1, timeout: float = 10.0) -> list[bytes]:
|
||||
"""Connect and return up to `count` frame payloads (Hello consumed)."""
|
||||
raise NotImplementedError
|
||||
"""Connect and return up to `count` frame payloads (Hello consumed).
|
||||
|
||||
`timeout` bounds each socket operation, not the whole call: at the
|
||||
advertised fps a frame is expected well inside it. Fewer than `count`
|
||||
frames come back if the server closes the connection first.
|
||||
"""
|
||||
return read_stream(socket_path, count, timeout)[1]
|
||||
|
||||
|
||||
def read_stream(socket_path: str, count: int = 1,
|
||||
timeout: float = 10.0) -> tuple[dict, list[bytes]]:
|
||||
"""Like `fetch`, but also returns the parsed Hello."""
|
||||
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
conn.settimeout(timeout)
|
||||
try:
|
||||
conn.connect(socket_path)
|
||||
with conn.makefile("rb") as stream:
|
||||
hello = protocol.read_hello(stream)
|
||||
frames: list[bytes] = []
|
||||
while len(frames) < count:
|
||||
payload = protocol.read_frame(stream)
|
||||
if payload is None:
|
||||
break # server closed; return what we got
|
||||
frames.append(payload)
|
||||
return hello, frames
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
raise NotImplementedError
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="hhstream-client",
|
||||
description="Read frames from a hyprland-headless-stream socket.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--socket", default=DEFAULT_SOCKET, metavar="PATH",
|
||||
help="socket to read from (default: %(default)s)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--count", type=int, default=1, metavar="N",
|
||||
help="how many frames to read (default: %(default)s)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--out", metavar="PATH",
|
||||
help="write each frame here, suffixed when --count > 1; "
|
||||
"'-' writes the payloads to stdout",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--timeout", type=float, default=10.0, metavar="SECONDS",
|
||||
help="per-read socket timeout (default: %(default)s)",
|
||||
)
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: Iterable[str] | None = None) -> int:
|
||||
raise NotImplementedError
|
||||
args = build_parser().parse_args(argv)
|
||||
if args.count < 0:
|
||||
print("--count must not be negative", file=sys.stderr)
|
||||
return 2
|
||||
to_stdout = args.out == "-"
|
||||
# Keep stdout for the payloads when they are going there.
|
||||
report = sys.stderr if to_stdout else sys.stdout
|
||||
|
||||
try:
|
||||
hello, frames = read_stream(args.socket, args.count, args.timeout)
|
||||
except (OSError, EOFError, ValueError) as exc:
|
||||
print(f"hhstream-client: {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print(json.dumps(hello, separators=(",", ":")), file=report)
|
||||
for index, payload in enumerate(frames, start=1):
|
||||
if to_stdout:
|
||||
sys.stdout.buffer.write(payload)
|
||||
sys.stdout.buffer.flush()
|
||||
print(f"frame {index}: {len(payload)} bytes", file=report)
|
||||
elif args.out:
|
||||
target = output_path(args.out, index, args.count)
|
||||
target.write_bytes(payload)
|
||||
print(f"frame {index}: {len(payload)} bytes -> {target}", file=report)
|
||||
else:
|
||||
print(f"frame {index}: {len(payload)} bytes", file=report)
|
||||
report.flush()
|
||||
|
||||
if len(frames) < args.count:
|
||||
print(
|
||||
f"hhstream-client: wanted {args.count} frames, got {len(frames)} "
|
||||
"(server closed the connection)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
__all__ = ["fetch", "DEFAULT_SOCKET", "build_parser", "main"]
|
||||
def output_path(out: str, index: int, count: int) -> pathlib.Path:
|
||||
"""`frame.png` -> itself for one frame, `frame-1.png`, `frame-2.png` beyond."""
|
||||
path = pathlib.Path(out)
|
||||
if count <= 1:
|
||||
return path
|
||||
width = len(str(count))
|
||||
return path.with_name(f"{path.stem}-{index:0{width}d}{path.suffix}")
|
||||
|
||||
|
||||
__all__ = ["fetch", "read_stream", "DEFAULT_SOCKET", "build_parser", "main",
|
||||
"output_path"]
|
||||
+115
-6
@@ -10,23 +10,77 @@ from typing import BinaryIO
|
||||
|
||||
from . import MAGIC
|
||||
|
||||
#: Longest length prefix we will read before giving up. The contract allows
|
||||
#: plain ASCII digits with no bound; 20 digits is past 2**63 and keeps a garbage
|
||||
#: stream from making us read forever.
|
||||
MAX_LENGTH_DIGITS = 20
|
||||
|
||||
#: Longest Hello line we will read before giving up, for the same reason.
|
||||
MAX_HELLO_BYTES = 65536
|
||||
|
||||
_READ_CHUNK = 1 << 20
|
||||
|
||||
|
||||
def hello(width: int, height: int, fmt: str, fps: int) -> bytes:
|
||||
"""The one-line JSON Hello, `\\n`-terminated.
|
||||
|
||||
`fmt` is a MIME type ("image/png" / "image/jpeg").
|
||||
"""
|
||||
raise NotImplementedError
|
||||
for name, value in (("width", width), ("height", height), ("fps", fps)):
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||
raise ValueError(f"{name} must be a positive int, got {value!r}")
|
||||
if not isinstance(fmt, str) or not fmt:
|
||||
raise ValueError(f"format must be a non-empty str, got {fmt!r}")
|
||||
obj = {
|
||||
"magic": MAGIC,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"format": fmt,
|
||||
"fps": fps,
|
||||
}
|
||||
line = json.dumps(obj, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
|
||||
if b"\n" in line:
|
||||
raise ValueError("Hello would contain a newline")
|
||||
return line + b"\n"
|
||||
|
||||
|
||||
def parse_hello(line: bytes) -> dict:
|
||||
"""Inverse of `hello`: validate `magic` and required fields, or raise."""
|
||||
raise NotImplementedError
|
||||
if not isinstance(line, (bytes, bytearray)):
|
||||
raise ValueError(f"Hello must be bytes, got {type(line).__name__}")
|
||||
text = bytes(line)
|
||||
if text.endswith(b"\n"):
|
||||
text = text[:-1]
|
||||
if not text:
|
||||
raise ValueError("empty Hello line")
|
||||
try:
|
||||
obj = json.loads(text.decode("utf-8"))
|
||||
except UnicodeDecodeError as exc:
|
||||
raise ValueError(f"Hello is not UTF-8: {exc}") from exc
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"Hello is not valid JSON: {exc}") from exc
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError(f"Hello must be a JSON object, got {type(obj).__name__}")
|
||||
if obj.get("magic") != MAGIC:
|
||||
raise ValueError(f"bad magic {obj.get('magic')!r}, expected {MAGIC!r}")
|
||||
for name in ("width", "height", "format", "fps"):
|
||||
if name not in obj:
|
||||
raise ValueError(f"Hello is missing {name!r}")
|
||||
for name in ("width", "height", "fps"):
|
||||
value = obj[name]
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
||||
raise ValueError(f"Hello {name} must be a positive int, got {value!r}")
|
||||
if not isinstance(obj["format"], str) or not obj["format"]:
|
||||
raise ValueError(f"Hello format must be a non-empty str, got {obj['format']!r}")
|
||||
return obj
|
||||
|
||||
|
||||
def frame(payload: bytes) -> bytes:
|
||||
"""`<ascii length>\\n<payload>` for one complete image."""
|
||||
raise NotImplementedError
|
||||
if not isinstance(payload, (bytes, bytearray, memoryview)):
|
||||
raise ValueError(f"payload must be bytes, got {type(payload).__name__}")
|
||||
body = bytes(payload)
|
||||
return str(len(body)).encode("ascii") + b"\n" + body
|
||||
|
||||
|
||||
def read_frame(stream: BinaryIO) -> bytes | None:
|
||||
@@ -35,12 +89,67 @@ def read_frame(stream: BinaryIO) -> bytes | None:
|
||||
Returns None on a clean EOF before any byte of the next frame. Raises
|
||||
ValueError on a malformed length prefix and EOFError on a truncated payload.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
digits = bytearray()
|
||||
while True:
|
||||
byte = stream.read(1)
|
||||
if not byte:
|
||||
if not digits:
|
||||
return None # clean EOF between frames
|
||||
raise EOFError(
|
||||
f"EOF in length prefix after {bytes(digits)!r}"
|
||||
)
|
||||
if byte == b"\n":
|
||||
break
|
||||
if not (b"0" <= byte <= b"9"):
|
||||
raise ValueError(
|
||||
f"malformed length prefix: unexpected byte {byte!r} "
|
||||
f"after {bytes(digits)!r}"
|
||||
)
|
||||
digits += byte
|
||||
if len(digits) > MAX_LENGTH_DIGITS:
|
||||
raise ValueError(
|
||||
f"length prefix longer than {MAX_LENGTH_DIGITS} digits"
|
||||
)
|
||||
if not digits:
|
||||
raise ValueError("malformed length prefix: empty")
|
||||
if len(digits) > 1 and digits[:1] == b"0":
|
||||
raise ValueError(f"malformed length prefix: leading zero in {bytes(digits)!r}")
|
||||
length = int(digits)
|
||||
return _read_exactly(stream, length)
|
||||
|
||||
|
||||
def read_hello(stream: BinaryIO) -> dict:
|
||||
"""Read and parse the Hello line from `stream`."""
|
||||
raise NotImplementedError
|
||||
line = bytearray()
|
||||
while True:
|
||||
byte = stream.read(1)
|
||||
if not byte:
|
||||
raise EOFError(f"EOF in Hello line after {len(line)} bytes")
|
||||
if byte == b"\n":
|
||||
break
|
||||
line += byte
|
||||
if len(line) > MAX_HELLO_BYTES:
|
||||
raise ValueError(f"Hello line longer than {MAX_HELLO_BYTES} bytes")
|
||||
return parse_hello(bytes(line))
|
||||
|
||||
|
||||
__all__ = ["json", "hello", "parse_hello", "frame", "read_frame", "read_hello", "MAGIC"]
|
||||
def _read_exactly(stream: BinaryIO, length: int) -> bytes:
|
||||
"""Read exactly `length` bytes or raise EOFError.
|
||||
|
||||
Reads in chunks so a bogus (huge) length prefix cannot make us allocate a
|
||||
buffer for data that is not there.
|
||||
"""
|
||||
if length == 0:
|
||||
return b""
|
||||
out = bytearray()
|
||||
while len(out) < length:
|
||||
chunk = stream.read(min(_READ_CHUNK, length - len(out)))
|
||||
if not chunk:
|
||||
raise EOFError(
|
||||
f"truncated payload: wanted {length} bytes, got {len(out)}"
|
||||
)
|
||||
out += chunk
|
||||
return bytes(out)
|
||||
|
||||
|
||||
__all__ = ["json", "hello", "parse_hello", "frame", "read_frame", "read_hello", "MAGIC"]
|
||||
+369
-5
@@ -8,31 +8,395 @@ 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:
|
||||
raise NotImplementedError
|
||||
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."""
|
||||
raise NotImplementedError
|
||||
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:
|
||||
raise NotImplementedError
|
||||
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:
|
||||
raise NotImplementedError
|
||||
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"]
|
||||
"socket", "build_parser", "main"]
|
||||
Reference in new issue
Block a user