summaryrefslogtreecommitdiff
path: root/aerial_screensaver.py
blob: 3c93086c404b1875a441e88493e6ee2c3360eee0 (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
#!/usr/bin/env python3
import time
import subprocess
import os
import sys
import threading
import logging
from gi.repository import Gio, GLib

# Setup Logging
LOG_PATH = os.path.expanduser("~/aerial_debug.log")
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s: %(message)s',
    handlers=[
        logging.FileHandler(LOG_PATH),
        logging.StreamHandler(sys.stdout)
    ]
)

# Configuration
IDLE_TIMEOUT_SECONDS = 300  # 5 minutes
VIDEO_DIR = os.path.expanduser("~/Videos/Screensavers/Aerial")
LID_STATE_FILE = "/proc/acpi/button/lid/LID0/state"
IPC_SOCKET_PREFIX = "/tmp/mpv_aerial_"

# Quiet playback: iGPU VAAPI decode, cheap scaling, no audio, drop freely.
MPV_BASE_COMMAND = [
    "nice", "-n", "19",
    "mpv",
    "--fullscreen",
    "--no-stop-screensaver",
    "--loop-playlist=inf",
    "--shuffle",
    "--hwdec=vaapi",
    "--vaapi-device=/dev/dri/by-path/pci-0000:c4:00.0-render",
    "--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=-",
]


class AerialScreensaver:
    def __init__(self):
        self.processes = []
        self.idle_monitor = None
        self.watch_id = None

        logging.info("Initializing Aerial Screensaver (mpv Lite Backend, AC-only, Lid-Aware, multi-screen)...")

        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)", (IDLE_TIMEOUT_SECONDS * 1000,)),
                    Gio.DBusCallFlags.NONE,
                    -1,
                    None
                )
                self.watch_id = reply.unpack()[0]
                logging.info(f"Added IdleWatch with ID: {self.watch_id} for {IDLE_TIMEOUT_SECONDS}s")

                self.idle_monitor.connect("g-signal", self.on_dbus_signal)
                connected = True

            except Exception as e:
                logging.error(f"Failed to connect to IdleMonitor: {e}")
                logging.info("Retrying in 5 seconds...")
                time.sleep(5)
                self.idle_monitor = None

    def is_on_ac(self):
        try:
            for ac in os.listdir('/sys/class/power_supply/'):
                if ac.startswith('AC'):
                    with open(f'/sys/class/power_supply/{ac}/online', 'r') as f:
                        if f.read().strip() == '1':
                            return True
            return False
        except Exception as e:
            logging.error(f"Error checking AC status: {e}")
            return False

    def is_lid_open(self):
        try:
            if not os.path.exists(LID_STATE_FILE):
                return True
            with open(LID_STATE_FILE, 'r') as f:
                content = f.read().strip()
                return "open" in content
        except Exception as e:
            logging.error(f"Error checking lid status: {e}")
            return True

    def get_screen_count(self):
        """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()
            count = len(logical_monitors)
            if count < 1:
                return 1
            return count
        except Exception as e:
            logging.error(f"Error detecting screens, defaulting to 1: {e}")
            return 1

    def on_dbus_signal(self, proxy, sender_name, signal_name, parameters):
        if signal_name == "WatchFired":
            watch_id = parameters.unpack()[0]
            if watch_id == self.watch_id:
                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(f"Idle threshold reached but skip (AC: {self.is_on_ac()}, Lid Open: {self.is_lid_open()})")

    def _collect_videos(self):
        if not os.path.isdir(VIDEO_DIR):
            return []
        return [
            os.path.join(VIDEO_DIR, f)
            for f in os.listdir(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 _any_running(self):
        return any(p.poll() is None for p in self.processes)

    def start_screensaver(self):
        if self._any_running():
            return

        try:
            videos = self._collect_videos()
            if not videos:
                logging.error(f"No video files found in {VIDEO_DIR}")
                return

            screen_count = self.get_screen_count()
            logging.info(f"Using {len(videos)} clips from {VIDEO_DIR} on {screen_count} screen(s)")
            urls = "\n".join(videos)

            self.processes = []
            for screen in range(screen_count):
                ipc = f"{IPC_SOCKET_PREFIX}{screen}"
                try:
                    os.unlink(ipc)
                except FileNotFoundError:
                    pass

                cmd = MPV_BASE_COMMAND + [
                    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(f"mpv started on screen {screen} with PID: {proc.pid}")

            threading.Thread(target=self.monitor_activity, daemon=True).start()

        except Exception as e:
            logging.error(f"Error starting mpv: {e}")
            self.stop_screensaver()

    def monitor_activity(self):
        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
                )
                idle_time = reply.unpack()[0]

                if idle_time < 1000:
                    self.stop_screensaver()
                    break

                if not self.is_on_ac():
                    self.stop_screensaver()
                    break

            except Exception as e:
                logging.error(f"Error in monitor_activity: {e}")
                break

    def stop_screensaver(self):
        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 path in (
            f"{IPC_SOCKET_PREFIX}{i}" for i in range(8)
        ):
            try:
                os.unlink(path)
            except FileNotFoundError:
                pass

    def run(self):
        loop = GLib.MainLoop()
        try:
            loop.run()
        except KeyboardInterrupt:
            pass


if __name__ == "__main__":
    app = AerialScreensaver()
    app.run()