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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
|
#!/usr/bin/env python3
"""GNOME idle Aerial screensaver — AC-only, lid-aware, multi-monitor mpv."""
from __future__ import annotations
import logging
import os
import re
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",
)
# Built-in panel connectors (clamshell = lid closed + non-builtin still active).
BUILTIN_CONNECTOR_PREFIXES = ("eDP", "LVDS", "DSI")
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",
"ALLOW_CLAMSHELL",
):
env = os.environ.get(f"AERIAL_{key}")
if env:
cfg[key] = env
return cfg
def _connector_is_builtin(connector: str) -> bool:
return connector.startswith(BUILTIN_CONNECTOR_PREFIXES)
def xrandr_geometry(connector: str) -> str | None:
"""Return mpv --geometry string (WxH+X+Y) for a connector via xrandr."""
try:
out = subprocess.check_output(
["xrandr", "--listmonitors"],
text=True,
stderr=subprocess.DEVNULL,
)
except (FileNotFoundError, subprocess.CalledProcessError):
return None
# Example: 0: +*DP-1 6144/700x3456/390+0+0 DP-1
pat = re.compile(
r"(\d+)/\d+x(\d+)/\d+\+(\d+)\+(\d+)\s+" + re.escape(connector) + r"\s*$"
)
for line in out.splitlines():
m = pat.search(line.strip())
if m:
w, h, x, y = m.group(1), m.group(2), m.group(3), m.group(4)
return f"{w}x{h}+{x}+{y}"
return None
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")
# Lid closed + external display (docked / clamshell) is allowed by default.
self.allow_clamshell = cfg.get("ALLOW_CLAMSHELL", "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, clamshell=%s, multi-screen, vaapi=%s)...",
self.require_ac,
self.allow_clamshell,
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 list_logical_screens(self) -> list[dict]:
"""Active GNOME logical monitors as mpv screen targets.
Each item: {index, connector, primary, builtin}.
Index matches Mutter logical-monitor order (what mpv --screen uses).
"""
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()
# connector -> (width, height) of current mode
mode_size: dict[str, tuple[int, int]] = {}
for mon in monitors:
try:
connector = mon[0][0]
for mode in mon[1]:
props = mode[6] if len(mode) > 6 else {}
if isinstance(props, dict) and props.get("is-current"):
mode_size[connector] = (int(mode[1]), int(mode[2]))
break
except (IndexError, TypeError, ValueError):
continue
screens: list[dict] = []
for index, lm in enumerate(logical_monitors):
# (x, y, scale, transform, primary, monitors, properties)
primary = bool(lm[4])
connectors = [mon[0] for mon in lm[5]]
connector = connectors[0] if connectors else f"screen-{index}"
builtin = any(_connector_is_builtin(c) for c in connectors)
width, height = mode_size.get(connector, (1920, 1080))
# Prefer Mutter logical coords (Wayland). xrandr uses physical
# pixels under fractional scaling and mis-places secondary outputs.
geom = f"{width}x{height}+{int(lm[0])}+{int(lm[1])}"
xrandr_geom = xrandr_geometry(connector)
screens.append(
{
"index": index,
"connector": connector,
"primary": primary,
"builtin": builtin,
"geometry": geom,
"xrandr_geometry": xrandr_geom,
"product": lm[5][0][2] if lm[5] else "",
}
)
return screens
except Exception as e:
logging.error("Error detecting displays: %s", e)
return []
def get_screen_count(self) -> int:
"""Return active GNOME logical monitor count (fallback: 1)."""
screens = self.list_logical_screens()
return max(1, len(screens)) if screens else 1
def has_external_display(self) -> bool:
return any(not s["builtin"] for s in self.list_logical_screens())
def display_ok(self) -> bool:
"""Lid open, or clamshell (lid closed + external display) when allowed."""
if self.is_lid_open():
return True
if self.allow_clamshell and self.has_external_display():
return True
return False
def screens_for_playback(self) -> list[dict]:
"""Which screens should show the screensaver.
Lid open: every logical monitor.
Lid closed (clamshell): only external (non-eDP) monitors, primary first.
"""
screens = self.list_logical_screens()
if not screens:
return [{"index": 0, "connector": "unknown", "primary": True, "builtin": False}]
if self.is_lid_open():
return screens
external = [s for s in screens if not s["builtin"]]
if not external:
# No external detected — fall back to primary rather than a blank lid panel.
primary = [s for s in screens if s["primary"]]
return primary or screens[:1]
external.sort(key=lambda s: (not s["primary"], s["index"]))
return external
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
on_ac = self.is_on_ac()
display_ok = self.display_ok()
if on_ac and display_ok:
lid = "open" if self.is_lid_open() else "closed (clamshell/external)"
logging.info(
"Idle threshold reached, on AC, display ok (lid %s). Starting mpv.",
lid,
)
self.start_screensaver()
else:
logging.info(
"Idle threshold reached but skip (AC: %s, Lid Open: %s, External: %s)",
on_ac,
self.is_lid_open(),
self.has_external_display(),
)
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 _session_env(self) -> dict[str, str]:
env = os.environ.copy()
runtime = env.get("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}")
if not env.get("WAYLAND_DISPLAY"):
for name in ("wayland-0", "wayland-1"):
if Path(runtime, name).exists():
env["WAYLAND_DISPLAY"] = name
break
if not env.get("DISPLAY"):
env["DISPLAY"] = ":0"
return env
def _mpv_base_command(self, gpu_context: str = "wayland") -> list[str]:
cmd = [
"nice",
"-n",
"19",
"mpv",
"--force-window=immediate",
"--fullscreen",
"--no-stop-screensaver",
"--loop-playlist=inf",
"--shuffle",
"--hwdec=vaapi",
"--vo=gpu",
f"--gpu-context={gpu_context}",
"--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",
"--msg-level=vo=v,cplayer=status,wayland=v,x11=v",
"--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 _mpv_log_path(self, connector: str) -> Path:
safe = re.sub(r"[^\w.-]+", "_", connector)
return Path.home() / f"aerial_mpv_{safe}.log"
def _spawn_mpv(
self,
urls: str,
target: dict,
gpu_context: str,
use_screen_name: bool,
) -> subprocess.Popen:
connector = target["connector"]
screen = int(target["index"])
# x11egl prefers xrandr physical pixels; wayland wants Mutter logical.
if gpu_context == "x11egl" and target.get("xrandr_geometry"):
geometry = target["xrandr_geometry"]
else:
geometry = target.get("geometry") or "1920x1080+0+0"
ipc = f"{IPC_SOCKET_PREFIX}{screen}"
mpv_log = self._mpv_log_path(connector)
try:
os.unlink(ipc)
except FileNotFoundError:
pass
try:
mpv_log.unlink()
except FileNotFoundError:
pass
cmd = self._mpv_base_command(gpu_context) + [
f"--input-ipc-server={ipc}",
f"--log-file={mpv_log}",
f"--geometry={geometry}",
]
# Never pass --screen/--fs-screen integers (Mutter order ≠ mpv wl_output).
if use_screen_name:
cmd += [
f"--screen-name={connector}",
f"--fs-screen-name={connector}",
]
proc = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
text=True,
env=self._session_env(),
)
if proc.stdin:
proc.stdin.write(urls)
proc.stdin.close()
logging.info(
"mpv spawn connector=%s geometry=%s context=%s screen-name=%s PID=%s log=%s",
connector,
geometry,
gpu_context,
use_screen_name,
proc.pid,
mpv_log,
)
return proc
def _mpv_landed_on_target(self, connector: str, log_path: Path) -> bool:
"""True when mpv log shows the window on the requested connector."""
if not log_path.is_file() or log_path.stat().st_size == 0:
return False
text = log_path.read_text(encoding="utf-8", errors="replace")
# Wayland: "Surface entered output … (DP-1)"
if f"({connector})" in text and "Surface entered output" in text:
# Prefer the last enter event (can move between outputs during setup)
last_enter = ""
for line in text.splitlines():
if "Surface entered output" in line and "(" in line:
last_enter = line
if last_enter and f"({connector})" in last_enter:
return True
if last_enter:
return False
# Explicit failure of --screen-name / --fs-screen-name
if "Falling back to screen 0" in text:
return _connector_is_builtin(connector)
# X11/XWayland: listed our display and completed a vo reconfig
if f"({connector})" in text and "reconfig to" in text:
return True
# Geometry-only spawn with no name: accept a living vo reconfig
return "reconfig to" in text and "Falling back to screen 0" not in text
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
targets = self.screens_for_playback()
logging.info(
"Using %s clips from %s on %s screen(s): %s",
len(videos),
self.video_dir,
len(targets),
", ".join(
f"{t['connector']}(geom={t.get('geometry')},primary={t['primary']})"
for t in targets
),
)
urls = "\n".join(videos)
self.processes = []
for target in targets:
connector = target["connector"]
log_path = self._mpv_log_path(connector)
# 1) Wayland + geometry + connector name
proc = self._spawn_mpv(urls, target, "wayland", use_screen_name=True)
self.processes.append(proc)
time.sleep(1.2)
if proc.poll() is not None:
logging.error(
"mpv exited early on %s (code %s). See %s",
connector,
proc.returncode,
log_path,
)
self.processes.remove(proc)
continue
if self._mpv_landed_on_target(connector, log_path):
logging.info("mpv confirmed on %s (wayland)", connector)
continue
# 2) Retry with X11/XWayland + geometry only (reliable on GNOME)
logging.warning(
"wayland placement uncertain for %s; retrying via x11egl+geometry. Log: %s",
connector,
log_path,
)
proc.terminate()
try:
proc.wait(timeout=2)
except subprocess.TimeoutExpired:
proc.kill()
self.processes.remove(proc)
proc = self._spawn_mpv(urls, target, "x11egl", use_screen_name=False)
self.processes.append(proc)
time.sleep(1.2)
if proc.poll() is not None:
logging.error(
"mpv x11egl exited early on %s (code %s). See %s",
connector,
proc.returncode,
log_path,
)
self.processes.remove(proc)
continue
if self._mpv_landed_on_target(connector, log_path):
logging.info("mpv confirmed on %s (x11egl)", connector)
else:
# Dump a short hint into the main debug log
tail = ""
if log_path.is_file():
lines = log_path.read_text(errors="replace").splitlines()
tail = "\n".join(lines[-30:])
logging.error(
"mpv still not confirmed on %s; last log lines:\n%s",
connector,
tail,
)
if not self.processes:
logging.error("No mpv instances running after start attempts")
return
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.display_ok():
logging.info(
"No usable display (lid closed without external). 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()
|