commit 8993f026d3632fb03f5e59d4ddedc47c8400e09e Author: Hermenix Date: Mon Sep 28 05:01:41 2026 +0000 buzz: initial mirror diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5ed6c40 --- /dev/null +++ b/.gitignore @@ -0,0 +1,68 @@ +result +__pycache__/ +*.pyc +.pytest_cache/ + +# --- managed by buzz-git-publish --- +# Managed ignore block for Buzz-hosted mirrors (buzz-git-publish). +# +# Two layers of defence: +# 1. this block keeps the obvious junk out of `git add -A` +# 2. publish.sh additionally refuses to stage any single file larger than +# BUZZ_MAX_FILE_BYTES (default 5 MiB) unless --include-large is passed, +# so a new 1 GB artefact never sneaks into a repo unpushed. +# +# Generated outputs (audio/PDFs/images/archives) belong in a Buzz Blossom +# upload (`buzz upload file`), not in the git mirror. +.venv/ +venv/ +env/ +node_modules/ +.devenv/ +.direnv/ +__pycache__/ +*.py[cod] +.cache/ +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +result +result-* +.tmp/ +*.log +*.m4b +*.mp3 +*.wav +*.flac +*.ogg +*.mp4 +*.mkv +*.zip +*.tar +*.tar.* +*.7z +*.iso +*.img +*.qcow2 +*.pdf +*.png +*.jpg +*.jpeg +*.webp +*.tif +*.tiff +*.psd +*.blend +*.stl +*.step +*.stp +*.glb +*.gltf +*.obj +*.npy +*.npz +*.pt +*.onnx +*.parquet +*.sqlite +*.db \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..865e110 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# hyprland-headless-stream-plugin + +A Nix flake that runs a **headless Hyprland session** and publishes its frames on +a **persistent Unix socket**, so any process that can open a socket can see the +screen without owning a display. + +Two parts: + +- **NixOS module** — `services.hyprland-headless-stream`: starts Hyprland with + no physical monitor, and a small frame server beside it. +- **Package** — `hhstream` — the frame server (publishes frames) and its client + (reads them). Pure Python standard library. + +```nix +{ + inputs.hhstream.url = "git+https:///git//hyprland-headless-stream-plugin.git"; + + # in your host config + imports = [ inputs.hhstream.nixosModules.default ]; + services.hyprland-headless-stream = { + enable = true; + outputs = [ { name = "HEADLESS-1"; width = 1280; height = 720; refresh = 30; } ]; + }; +} +``` + +Then any consumer: + +```bash +hhstream-client --socket /run/hyprland-headless-stream/stream.sock --count 1 --out frame.png +``` + +The socket is a plain file descriptor: the server serves every client that +connects, and keeps running when one disconnects. + +| Document | What it is | +|---|---| +| `docs/CONTRACT.md` | the wire protocol and the module surface — the interface other people build against | +| `docs/ARCHITECTURE.md` | how the pieces fit: compositor, capture, server, client | +| `README.dev.md` | how to build, test and hack on it | + +Status: work in progress — the module and the test suite are being built. \ No newline at end of file diff --git a/docs/CONTRACT.md b/docs/CONTRACT.md new file mode 100644 index 0000000..fef3bb4 --- /dev/null +++ b/docs/CONTRACT.md @@ -0,0 +1,87 @@ +# Wire contract (v1) + +This file is the interface. Code on either side may change freely; **this +document may not**, without bumping the version. + +## Socket + +- Transport: `AF_UNIX`, `SOCK_STREAM`. +- Path: whatever `services.hyprland-headless-stream.socketPath` says. + Default `/run/hyprland-headless-stream/stream.sock`. +- Ownership: the service user (`user` option, default `hhstream`), mode `0660`. +- The server accepts **any number of concurrent clients**. Each client gets its + own copy of the header and of every subsequent frame. A client disconnecting + (or dying mid-frame) must never take the server down and must never disturb + the other clients. +- The server runs whether or not anyone is connected. No client is privileged. +- The socket path is removed and recreated on start; a stale socket file must + not prevent startup. + +## Message sequence + +**1. Hello.** Immediately on connect, the server writes exactly one UTF-8 JSON +object followed by a single `\n`: + +```json +{"magic":"HHS1","width":1280,"height":720,"format":"image/png","fps":30} +``` + +Fields: `magic` (protocol tag, `HHS1`), `width`/`height` (pixels of the captured +output), `format` (`image/png` or `image/jpeg`), `fps` (target capture rate, +advisory — the server does not buffer to keep up). + +**2. Frames.** Then, forever, one frame per message: + +``` +<0x0A> +``` + +`payload` is one complete, independently decodable image in `format`. + +Notes: + +- Byte length counts the payload only, never the length prefix. +- The length prefix is plain ASCII digits; no leading zeros, no `+`, no spaces. +- Frames are never split, merged or interleaved on the wire. One length, one + payload. +- A client that stalls or reads slowly is *slowed*, not queued: the server drops + frames for that client rather than buffering them. Backpressure must never + grow unbounded memory. +- Shutdown: either side closes the socket. Nothing else is negotiated. + +## Client → server direction + +Reserved. In v1 a client sends **nothing**; any bytes received from a client are +read and ignored. (This leaves room to add a control channel later without +breaking v1 readers, which never expect inbound data.) + +## Failure semantics + +- Compositor not running / capture tool erroring: the server keeps the socket up + and retries; it does **not** exit and it does **not** send partial frames. +- If a Hello cannot be produced (no output size known yet), the server waits + until it can, then sends it. It never sends a Hello with zero size. + +## NixOS module surface + +Namespace: `services.hyprland-headless-stream` + +| Option | Type | Default | Meaning | +|---|---|---|---| +| `enable` | bool | `false` | turn everything on | +| `socketPath` | str | `/run/hyprland-headless-stream/stream.sock` | published socket | +| `user` / `group` | str | `hhstream` | owner of the session and the socket | +| `frameRate` | int | `30` | capture target, becomes `fps` in Hello | +| `format` | enum `png`/`jpeg` | `png` | frame encoding | +| `outputs` | list of attrsets | one 1280×720@30 `HEADLESS-1` | virtual monitors: `name`, `width`, `height`, `refresh`, `scale` | +| `extraConfig` | str | `""` | extra lines appended to `hyprland.conf` | +| `hyprlandPackage` | package | `pkgs.hyprland` | which compositor | +| `package` | package | the flake's own build | the frame server/client | +| `captureCommand` | list of str | `[ "grim" … ]` | override the capture backend — used by tests | + +Services (names are part of the contract, tests refer to them): + +- `hyprland-headless.service` — the compositor, running as `user`, on a private + `XDG_RUNTIME_DIR`, with no physical output. +- `hyprland-headless-stream.service` — the frame server, `After=` the compositor, + with `Restart=always`, connected to the same session. \ No newline at end of file diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..be79c24 --- /dev/null +++ b/flake.lock @@ -0,0 +1,25 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1790463110, + "narHash": "sha256-hKlVl12B1dF0Q5vd9dY3lIJM5mFGWYSlXwSLAqHZ1+s=", + "rev": "e158d9ed9b51c98974c5e66e1ba1c9e0255fecaa", + "revCount": 1080189, + "type": "tarball", + "url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.1.1080189%2Brev-e158d9ed9b51c98974c5e66e1ba1c9e0255fecaa/01a0e11c-b69f-7483-9ae1-5e0a537af8a9/source.tar.gz" + }, + "original": { + "type": "tarball", + "url": "https://flakehub.com/f/NixOS/nixpkgs/0.1" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..4a09c7e --- /dev/null +++ b/flake.nix @@ -0,0 +1,27 @@ +{ + description = "Stream a headless Hyprland session to a persistent Unix socket"; + + # Matches the nixpkgs this was developed against; consumers can override with + # inputs.nixpkgs.follows = "nixpkgs" and nothing breaks. + inputs.nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/0.1"; + + outputs = { self, nixpkgs, ... }: let + systems = [ "x86_64-linux" "aarch64-linux" ]; + forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f (import nixpkgs { inherit system; })); + in { + packages = forAllSystems (pkgs: rec { + hhstream = pkgs.callPackage ./nix/package.nix {}; + default = hhstream; + }); + + nixosModules = rec { + hyprland-headless-stream = import ./nix/module.nix; + default = hyprland-headless-stream; + }; + + # `checks` (unit tests + the VM integration test) and `devShells` are owned + # by the test-harness workstream -- see docs/CONTRACT.md for the interface. + + formatter = forAllSystems (pkgs: pkgs.alejandra); + }; +} \ No newline at end of file diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 0000000..fde036c --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,91 @@ +{ lib, config, pkgs, ... }: + +# Interface only: every option in docs/CONTRACT.md is declared here so tests and +# consumers can be written against a stable surface. The systemd wiring is the +# next piece of work (see docs/CONTRACT.md -> "Services"). +let + cfg = config.services.hyprland-headless-stream; +in { + options.services.hyprland-headless-stream = { + enable = lib.mkEnableOption "a headless Hyprland session streamed to a Unix socket"; + + socketPath = lib.mkOption { + type = lib.types.str; + default = "/run/hyprland-headless-stream/stream.sock"; + description = "Where the frame server publishes frames."; + }; + + user = lib.mkOption { + type = lib.types.str; + default = "hhstream"; + description = "User the compositor and frame server run as."; + }; + + group = lib.mkOption { + type = lib.types.str; + default = "hhstream"; + description = "Group owning the socket."; + }; + + frameRate = lib.mkOption { + type = lib.types.ints.positive; + default = 30; + description = "Target capture rate; becomes `fps` in the protocol Hello."; + }; + + format = lib.mkOption { + type = lib.types.enum [ "png" "jpeg" ]; + default = "png"; + description = "Frame encoding."; + }; + + outputs = lib.mkOption { + type = lib.types.listOf (lib.types.submodule { + options = { + name = lib.mkOption { type = lib.types.str; }; + width = lib.mkOption { type = lib.types.ints.positive; default = 1280; }; + height = lib.mkOption { type = lib.types.ints.positive; default = 720; }; + refresh = lib.mkOption { type = lib.types.ints.positive; default = 30; }; + scale = lib.mkOption { type = lib.types.positive; default = 1.0; }; + }; + }); + default = [ { name = "HEADLESS-1"; width = 1280; height = 720; refresh = 30; scale = 1.0; } ]; + description = "Virtual monitors the compositor should create."; + }; + + extraConfig = lib.mkOption { + type = lib.types.lines; + default = ""; + description = "Extra lines appended to hyprland.conf."; + }; + + hyprlandPackage = lib.mkOption { + type = lib.types.package; + default = pkgs.hyprland; + defaultText = lib.literalExpression "pkgs.hyprland"; + description = "Compositor to run."; + }; + + package = lib.mkOption { + type = lib.types.package; + description = "The frame server / client package."; + }; + + captureCommand = lib.mkOption { + type = lib.types.listOf lib.types.str; + default = [ "grim" "-t" "png" "-" ]; + description = "Command that writes one frame to stdout; overridable for tests."; + }; + }; + + config = lib.mkIf cfg.enable { + # TODO(module): user/group, runtime dir, hyprland.conf rendering, the two + # systemd units named in docs/CONTRACT.md. + assertions = [ + { + assertion = cfg.outputs != [ ]; + message = "services.hyprland-headless-stream.outputs must not be empty."; + } + ]; + }; +} \ No newline at end of file diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..db38247 --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,24 @@ +{ + lib, + python3, + ... +}: +python3.pkgs.buildPythonApplication { + pname = "hhstream"; + version = "0.1.0"; + pyproject = true; + + src = ../.; + + build-system = [ python3.pkgs.setuptools ]; + + # Unit tests are wired up in the flake's `checks` so they can run without + # installing the package; see docs/CONTRACT.md. + doCheck = false; + + meta = { + description = "Publish a headless Hyprland session's frames on a Unix socket"; + license = lib.licenses.mit; + mainProgram = "hhstream-server"; + }; +} \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..92f2bca --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,17 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "hhstream" +version = "0.1.0" +description = "Publish a headless Hyprland session's frames on a Unix socket" +requires-python = ">=3.11" +dependencies = [] + +[project.scripts] +hhstream-server = "hhstream.server:main" +hhstream-client = "hhstream.client:main" + +[tool.setuptools.packages.find] +where = ["src"] \ No newline at end of file diff --git a/src/hhstream/__init__.py b/src/hhstream/__init__.py new file mode 100644 index 0000000..50ef56a --- /dev/null +++ b/src/hhstream/__init__.py @@ -0,0 +1,9 @@ +"""hhstream -- publish a headless Hyprland session's frames on a Unix socket. + +The wire format is specified in docs/CONTRACT.md; that document is authoritative +and this package must not drift from it. +""" + +__version__ = "0.1.0" + +MAGIC = "HHS1" \ No newline at end of file diff --git a/src/hhstream/capture.py b/src/hhstream/capture.py new file mode 100644 index 0000000..ebd8b71 --- /dev/null +++ b/src/hhstream/capture.py @@ -0,0 +1,38 @@ +"""Capture backends: how one frame is obtained from the running compositor. + +The backend is injected so tests never need a real compositor: the module option +`captureCommand` (see docs/CONTRACT.md) picks the program, and a fake command +produces frames in a unit test. +""" + +from __future__ import annotations + +import subprocess +from typing import Protocol + + +class CaptureBackend(Protocol): + def grab(self) -> bytes: + """Return one complete encoded frame. Raise on failure.""" + ... + + def size(self) -> tuple[int, int]: + """Pixel size of the captured output, for the Hello.""" + ... + + +class CommandCapture: + """Runs a helper that writes one frame to stdout (default: grim).""" + + def __init__(self, argv: list[str], env: dict[str, str] | None = None, + timeout: float = 5.0) -> None: + raise NotImplementedError + + def grab(self) -> bytes: + raise NotImplementedError + + def size(self) -> tuple[int, int]: + raise NotImplementedError + + +__all__ = ["CaptureBackend", "CommandCapture", "subprocess"] \ No newline at end of file diff --git a/src/hhstream/client.py b/src/hhstream/client.py new file mode 100644 index 0000000..136d85a --- /dev/null +++ b/src/hhstream/client.py @@ -0,0 +1,24 @@ +"""The client: connect, read the Hello, then read frames.""" + +from __future__ import annotations + +import argparse +from typing import Iterable + +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 + + +def build_parser() -> argparse.ArgumentParser: + raise NotImplementedError + + +def main(argv: Iterable[str] | None = None) -> int: + raise NotImplementedError + + +__all__ = ["fetch", "DEFAULT_SOCKET", "build_parser", "main"] \ No newline at end of file diff --git a/src/hhstream/protocol.py b/src/hhstream/protocol.py new file mode 100644 index 0000000..0bef7c3 --- /dev/null +++ b/src/hhstream/protocol.py @@ -0,0 +1,46 @@ +"""Framing: the bytes on the socket. See docs/CONTRACT.md. + +Pure functions, no I/O -- this is the part that earns unit tests. +""" + +from __future__ import annotations + +import json +from typing import BinaryIO + +from . import MAGIC + + +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 + + +def parse_hello(line: bytes) -> dict: + """Inverse of `hello`: validate `magic` and required fields, or raise.""" + raise NotImplementedError + + +def frame(payload: bytes) -> bytes: + """`\\n` for one complete image.""" + raise NotImplementedError + + +def read_frame(stream: BinaryIO) -> bytes | None: + """Read one framed payload from `stream`. + + 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 + + +def read_hello(stream: BinaryIO) -> dict: + """Read and parse the Hello line from `stream`.""" + raise NotImplementedError + + +__all__ = ["json", "hello", "parse_hello", "frame", "read_frame", "read_hello", "MAGIC"] \ No newline at end of file diff --git a/src/hhstream/server.py b/src/hhstream/server.py new file mode 100644 index 0000000..63c3ffb --- /dev/null +++ b/src/hhstream/server.py @@ -0,0 +1,38 @@ +"""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 socket +from typing import Iterable + +from .capture import CaptureBackend, CommandCapture + +DEFAULT_SOCKET = "/run/hyprland-headless-stream/stream.sock" + + +class FrameServer: + def __init__(self, socket_path: str, capture: CaptureBackend, fps: int, + fmt: str = "image/png") -> None: + raise NotImplementedError + + def serve_forever(self) -> None: + """Bind, then serve until stopped. A stale socket file is replaced.""" + raise NotImplementedError + + +def build_parser() -> argparse.ArgumentParser: + raise NotImplementedError + + +def main(argv: Iterable[str] | None = None) -> int: + raise NotImplementedError + + +__all__ = ["FrameServer", "DEFAULT_SOCKET", "CaptureBackend", "CommandCapture", + "socket", "build_parser", "main"] \ No newline at end of file