#!/usr/bin/env python3 """GNOME idle Aerial screensaver — AC-only, lid-aware, multi-monitor mpv.""" from __future__ import annotations import logging import os import subprocess import sys import threading import time from pathlib import Path from gi.repository import Gio, GLib CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "aerial-screensaver" CONFIG_FILE = CONFIG_DIR / "config" DEFAULT_VIDEO_DIR = Path.home() / "Videos" / "Screensavers" / "Aerial" DEFAULT_IDLE_SECONDS = 300 LID_STATE_CANDIDATES = ( "/proc/acpi/button/lid/LID0/state", "/proc/acpi/button/lid/LID/state", ) IPC_SOCKET_PREFIX = "/tmp/mpv_aerial_" LOG_PATH = Path.home() / "aerial_debug.log" def _load_config() -> dict[str, str]: cfg: dict[str, str] = {} if CONFIG_FILE.is_file(): for line in CONFIG_FILE.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) cfg[key.strip()] = value.strip().strip('"').strip("'") # Environment overrides config for key in ("VIDEO_DIR", "IDLE_TIMEOUT_SECONDS", "VAAPI_DEVICE", "REQUIRE_AC"): env = os.environ.get(f"AERIAL_{key}") if env: cfg[key] = env return cfg def _pci_attrs_for_render(render: Path) -> tuple[str, str]: """Return (pci_class, vendor) hex strings for a render node.""" try: device = Path("/sys/class/drm") / render.name / "device" cls = (device / "class").read_text(encoding="utf-8").strip() if (device / "class").is_file() else "" vendor = (device / "vendor").read_text(encoding="utf-8").strip() if (device / "vendor").is_file() else "" return cls, vendor except OSError: return "", "" def find_vaapi_device(preferred: str | None = None) -> str | None: """Pick a DRM render node for VAAPI. Prefer iGPU (Intel / AMD display).""" if preferred and Path(preferred).exists(): return preferred renders: list[Path] = [] by_path = Path("/dev/dri/by-path") if by_path.is_dir(): for path in sorted(by_path.glob("*-render")): if "usb" in path.name.lower(): continue renders.append(path.resolve() if path.exists() else path) if not renders: renders = sorted(Path("/dev/dri").glob("renderD*")) if not renders: return None # Lower score wins: Intel (T480) / AMD display-class, then other, then dGPU/NVIDIA. scored: list[tuple[int, str]] = [] for node in renders: cls, vendor = _pci_attrs_for_render(node) if vendor == "0x8086": score = 0 elif cls.startswith("0x038"): score = 0 elif vendor == "0x10de": score = 3 elif cls.startswith("0x030"): score = 2 else: score = 1 scored.append((score, str(node))) scored.sort() return scored[0][1] def setup_logging() -> None: logging.basicConfig( level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", handlers=[ logging.FileHandler(LOG_PATH), logging.StreamHandler(sys.stdout), ], ) class AerialScreensaver: def __init__(self) -> None: setup_logging() cfg = _load_config() self.video_dir = Path(cfg.get("VIDEO_DIR", str(DEFAULT_VIDEO_DIR))).expanduser() self.idle_timeout_seconds = int(cfg.get("IDLE_TIMEOUT_SECONDS", DEFAULT_IDLE_SECONDS)) self.require_ac = cfg.get("REQUIRE_AC", "1").lower() not in ("0", "false", "no") self.vaapi_device = find_vaapi_device(cfg.get("VAAPI_DEVICE") or None) self.processes: list[subprocess.Popen] = [] self.idle_monitor = None self.watch_id = None self.lid_state_file = next( (p for p in LID_STATE_CANDIDATES if os.path.exists(p)), LID_STATE_CANDIDATES[0], ) logging.info( "Initializing Aerial Screensaver " "(mpv lite, AC=%s, lid-aware, multi-screen, vaapi=%s)...", self.require_ac, self.vaapi_device or "auto", ) self._connect_idle_monitor() def _connect_idle_monitor(self) -> None: connected = False while not connected: try: self.idle_monitor = Gio.DBusProxy.new_for_bus_sync( Gio.BusType.SESSION, Gio.DBusProxyFlags.NONE, None, "org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "org.gnome.Mutter.IdleMonitor", None, ) reply = self.idle_monitor.call_sync( "AddIdleWatch", GLib.Variant("(t)", (self.idle_timeout_seconds * 1000,)), Gio.DBusCallFlags.NONE, -1, None, ) self.watch_id = reply.unpack()[0] logging.info( "Added IdleWatch with ID: %s for %ss", self.watch_id, self.idle_timeout_seconds, ) self.idle_monitor.connect("g-signal", self.on_dbus_signal) connected = True except Exception as e: logging.error("Failed to connect to IdleMonitor: %s", e) logging.info("Retrying in 5 seconds...") time.sleep(5) self.idle_monitor = None def is_on_ac(self) -> bool: if not self.require_ac: return True try: for ac in os.listdir("/sys/class/power_supply/"): if ac.startswith("AC"): with open(f"/sys/class/power_supply/{ac}/online", "r", encoding="utf-8") as f: if f.read().strip() == "1": return True # Desktops often have no AC* supply — treat as on AC. supplies = os.listdir("/sys/class/power_supply/") if not any(s.startswith("AC") for s in supplies): return True return False except Exception as e: logging.error("Error checking AC status: %s", e) return False def is_lid_open(self) -> bool: try: if not os.path.exists(self.lid_state_file): return True with open(self.lid_state_file, "r", encoding="utf-8") as f: return "open" in f.read().strip() except Exception as e: logging.error("Error checking lid status: %s", e) return True def get_screen_count(self) -> int: """Return active GNOME logical monitor count (fallback: 1).""" try: proxy = Gio.DBusProxy.new_for_bus_sync( Gio.BusType.SESSION, Gio.DBusProxyFlags.NONE, None, "org.gnome.Mutter.DisplayConfig", "/org/gnome/Mutter/DisplayConfig", "org.gnome.Mutter.DisplayConfig", None, ) reply = proxy.call_sync( "GetCurrentState", None, Gio.DBusCallFlags.NONE, -1, None, ) _serial, _monitors, logical_monitors, _props = reply.unpack() return max(1, len(logical_monitors)) except Exception as e: logging.error("Error detecting screens, defaulting to 1: %s", e) return 1 def on_dbus_signal(self, proxy, sender_name, signal_name, parameters) -> None: if signal_name != "WatchFired": return watch_id = parameters.unpack()[0] if watch_id != self.watch_id: return if self.is_on_ac() and self.is_lid_open(): logging.info("Idle threshold reached, on AC and lid is OPEN. Starting mpv.") self.start_screensaver() else: logging.info( "Idle threshold reached but skip (AC: %s, Lid Open: %s)", self.is_on_ac(), self.is_lid_open(), ) def _collect_videos(self) -> list[str]: if not self.video_dir.is_dir(): return [] return sorted( str(self.video_dir / f) for f in os.listdir(self.video_dir) if f.lower().endswith((".mov", ".mp4", ".mkv")) and not f.startswith("_test") and not f.startswith(".") and ".partial." not in f.lower() ) def _mpv_base_command(self) -> list[str]: cmd = [ "nice", "-n", "19", "mpv", "--fullscreen", "--no-stop-screensaver", "--loop-playlist=inf", "--shuffle", "--hwdec=vaapi", "--vo=gpu", "--gpu-context=wayland", "--gpu-api=opengl", "--scale=bilinear", "--cscale=bilinear", "--dscale=bilinear", "--dither=no", "--correct-downscaling=no", "--sigmoid-upscaling=no", "--video-sync=audio", "--framedrop=vo", "--vf=fps=24", "--no-osc", "--no-osd-bar", "--osd-level=0", "--cursor-autohide=always", "--no-audio", "--playlist=-", ] if self.vaapi_device: cmd.insert(cmd.index("--hwdec=vaapi") + 1, f"--vaapi-device={self.vaapi_device}") return cmd def _any_running(self) -> bool: return any(p.poll() is None for p in self.processes) def start_screensaver(self) -> None: if self._any_running(): return try: videos = self._collect_videos() if not videos: logging.error("No video files found in %s", self.video_dir) return screen_count = self.get_screen_count() logging.info( "Using %s clips from %s on %s screen(s)", len(videos), self.video_dir, screen_count, ) urls = "\n".join(videos) base = self._mpv_base_command() self.processes = [] for screen in range(screen_count): ipc = f"{IPC_SOCKET_PREFIX}{screen}" try: os.unlink(ipc) except FileNotFoundError: pass cmd = base + [ f"--input-ipc-server={ipc}", f"--screen={screen}", f"--fs-screen={screen}", ] proc = subprocess.Popen( cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, text=True, ) if proc.stdin: proc.stdin.write(urls) proc.stdin.close() self.processes.append(proc) logging.info("mpv started on screen %s with PID: %s", screen, proc.pid) threading.Thread(target=self.monitor_activity, daemon=True).start() except Exception as e: logging.error("Error starting mpv: %s", e) self.stop_screensaver() def monitor_activity(self) -> None: while self._any_running(): time.sleep(1) try: if not self.is_lid_open(): logging.info("Lid closed during playback. Stopping mpv.") self.stop_screensaver() break reply = self.idle_monitor.call_sync( "GetIdletime", None, Gio.DBusCallFlags.NONE, -1, None, ) if reply.unpack()[0] < 1000: self.stop_screensaver() break if not self.is_on_ac(): self.stop_screensaver() break except Exception as e: logging.error("Error in monitor_activity: %s", e) break def stop_screensaver(self) -> None: for proc in self.processes: if proc.poll() is None: proc.terminate() try: proc.wait(timeout=2) except subprocess.TimeoutExpired: proc.kill() self.processes = [] for i in range(8): try: os.unlink(f"{IPC_SOCKET_PREFIX}{i}") except FileNotFoundError: pass def run(self) -> None: loop = GLib.MainLoop() try: loop.run() except KeyboardInterrupt: pass if __name__ == "__main__": AerialScreensaver().run()