summaryrefslogtreecommitdiff
path: root/aerial_screensaver.py
blob: 4bc27c769e6214a443977c4ff90bcdd71128056f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/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_class_for_render(render: Path) -> str | None:
    """Return PCI class hex for a render node, e.g. '0x038000'."""
    try:
        device = Path("/sys/class/drm") / render.name / "device"
        class_file = device / "class"
        if class_file.is_file():
            return class_file.read_text(encoding="utf-8").strip()
    except OSError:
        return None
    return None


def find_vaapi_device(preferred: str | None = None) -> str | None:
    """Pick a DRM render node for VAAPI. Prefer iGPU when hybrid AMD/Intel."""
    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

    # Prefer PCI Display controller (0x038000) over VGA (0x030000) — iGPU on
    # AMD Framework / Strix hybrids. Fall back to first non-USB node.
    scored: list[tuple[int, str]] = []
    for node in renders:
        cls = _pci_class_for_render(node) or ""
        if cls.startswith("0x038"):
            score = 0
        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()