{ lib, config, pkgs, ... }: # The option surface below is the interface described in docs/CONTRACT.md # ("NixOS module surface"); the `config` block wires it to the two services # named there. let cfg = config.services.hyprland-headless-stream; # One private runtime directory, shared by both units: it holds the Wayland # socket of the session and, by default, the published frame socket too. # `RuntimeDirectoryPreserve` keeps it (and the Wayland socket) alive across a # restart of either unit. runtimeDirName = "hyprland-headless-stream"; runtimeDir = "/run/${runtimeDirName}"; socketDir = builtins.dirOf cfg.socketPath; # Hyprland refuses `--socket` unless it is paired with `--wayland-fd` (that # pair is the socket-handover path), so the name is not ours to choose: the # compositor calls wl_display_add_socket_auto, which takes the first free # `wayland-N` starting at 0. The runtime directory is private to this # session, so that is always `wayland-0`. waylandDisplay = "wayland-0"; hyprlandConf = pkgs.writeText "hyprland.conf" (import ./hyprland-conf.nix { inherit lib; inherit (cfg) outputs extraConfig; }); # `BindsTo=` already stops the frame server when the compositor goes away, # but the compositor is only *ready* once its Wayland socket is bound. The # compositor unit is `Type=notify`, so this is a second line of defence for # compositor builds that do not sd_notify. waitForSession = pkgs.writeShellScript "hhstream-wait-for-session" '' socket="$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" for _ in $(${lib.getExe' pkgs.coreutils "seq"} 1 300); do if [ -S "$socket" ]; then exit 0 fi ${lib.getExe' pkgs.coreutils "sleep"} 0.1 done echo "no Wayland socket at $socket after 30s; is the compositor up?" >&2 exit 1 ''; serverArgs = [ "--socket" cfg.socketPath "--fps" (toString cfg.frameRate) "--format" cfg.format ] # One occurrence per argv word. The capture command is a list whose words # start with `-` (`grim -t png -`), and repeating the flag is the only # shape that survives that without inventing a quoting convention. # `hhstream.server.build_parser()` is still a stub, so this is the one # place the module guesses at the server's CLI rather than reading it. ++ lib.concatMap (word: ["--capture-command" word]) cfg.captureCommand; # Shared by both units: a private session, no parent display to nest in. sessionEnvironment = { XDG_RUNTIME_DIR = runtimeDir; HOME = runtimeDir; XDG_SESSION_TYPE = "wayland"; }; commonServiceConfig = { User = cfg.user; Group = cfg.group; RuntimeDirectory = runtimeDirName; RuntimeDirectoryMode = "0750"; RuntimeDirectoryPreserve = "yes"; WorkingDirectory = runtimeDir; # docs/CONTRACT.md: the socket is owned by the service user, mode 0660. UMask = "0007"; Restart = "always"; RestartSec = 2; # A GPU render node is the one piece of hardware a headless session still # needs; everything else is virtual. SupplementaryGroups = ["video" "render"]; NoNewPrivileges = true; PrivateTmp = true; ProtectHome = true; ProtectSystem = "strict"; ProtectControlGroups = true; ProtectKernelTunables = true; ProtectKernelModules = true; RestrictSUIDSGID = true; ReadWritePaths = lib.optional (socketDir != runtimeDir) socketDir; }; 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; }; # Was `lib.types.positive`, which does not exist in nixpkgs and made # `outputs` unreadable; `numbers.positive` is the int-or-float type # that name meant. scale = lib.mkOption { type = lib.types.numbers.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 { assertions = [ { assertion = cfg.outputs != []; message = "services.hyprland-headless-stream.outputs must not be empty."; } { assertion = lib.hasPrefix "/" cfg.socketPath; message = "services.hyprland-headless-stream.socketPath must be an absolute path."; } ]; # The flake's own build, as docs/CONTRACT.md says; `mkDefault` so a # consumer (or the test harness) can still point this at its own package. services.hyprland-headless-stream.package = lib.mkDefault (pkgs.callPackage ./package.nix {}); users.users.${cfg.user} = { isSystemUser = true; group = cfg.group; description = "Headless Hyprland stream session"; }; users.groups.${cfg.group} = {}; # Only needed when the socket was moved out of the runtime directory that # `RuntimeDirectory=` already creates for us. systemd.tmpfiles.settings = lib.mkIf (socketDir != runtimeDir) { "10-hyprland-headless-stream".${socketDir}.d = { user = cfg.user; group = cfg.group; mode = "0750"; }; }; systemd.services.hyprland-headless = { description = "Headless Hyprland session"; documentation = ["file://${hyprlandConf}"]; wantedBy = ["multi-user.target"]; # No WAYLAND_DISPLAY and no DISPLAY here on purpose: with either set the # compositor would pick its nested backend and try to connect to a parent # session. With no seat and no DRM device it falls back to headless, # which is exactly what the virtual outputs in hyprland.conf want. environment = sessionEnvironment // { # We are a system service: there is no user bus and no user manager to # import the session environment into. HYPRLAND_NO_SD_VARS = "1"; HYPRLAND_NO_CRASHREPORTER = "1"; # Ignored by aquamarine-era Hyprland, honoured by wlroots-era builds # someone may pin in `hyprlandPackage`. WLR_BACKENDS = "headless"; WLR_LIBINPUT_NO_DEVICES = "1"; WLR_RENDERER_ALLOW_SOFTWARE = "1"; }; serviceConfig = commonServiceConfig // { # Hyprland sends READY=1 once the session is up, so the frame server's # `After=` is an ordering on readiness, not just on fork. Type = "notify"; NotifyAccess = "all"; TimeoutStartSec = 60; ExecStart = lib.escapeShellArgs [ (lib.getExe cfg.hyprlandPackage) "--config" "${hyprlandConf}" ]; }; }; systemd.services.hyprland-headless-stream = { description = "Frame server for the headless Hyprland session"; wantedBy = ["multi-user.target"]; after = ["hyprland-headless.service"]; bindsTo = ["hyprland-headless.service"]; # `captureCommand` defaults to an unqualified `grim`. path = [pkgs.grim]; environment = sessionEnvironment // { WAYLAND_DISPLAY = waylandDisplay; PYTHONUNBUFFERED = "1"; }; serviceConfig = commonServiceConfig // { Type = "simple"; ExecStartPre = "${waitForSession}"; ExecStart = lib.escapeShellArgs ( [(lib.getExe' cfg.package "hhstream-server")] ++ serverArgs ); }; }; }; }