From 6f3426c481f03f5beeed9171b3280f0070798844 Mon Sep 17 00:00:00 2001 From: Christopher Warner Date: Tue, 13 Oct 2026 15:07:53 -0400 Subject: feat: package portable Aerial screensaver for sharing Add install/uninstall scripts, XDG config, portable VAAPI detection, fetch-aerial-recent helper, and a LocalSend-ready zip without Apple video assets. Co-authored-by: Cursor --- .gitignore | 11 ++ LICENSE | 21 +++ README.md | 137 ++++++++++++++++--- aerial-screensaver.service | 5 +- aerial_screensaver.py | 318 +++++++++++++++++++++++++++------------------ bin/encode-aerial-lite | 130 ++++++++++++++++++ bin/fetch-aerial-recent | 112 ++++++++++++++++ install.sh | 88 +++++++++++++ test_screensaver.py | 75 +++++++---- uninstall.sh | 16 +++ 10 files changed, 740 insertions(+), 173 deletions(-) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100755 bin/encode-aerial-lite create mode 100755 bin/fetch-aerial-recent create mode 100755 install.sh create mode 100755 uninstall.sh diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..28695a1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ +*.partial.mp4 +*.mov +*.mp4 +*.mkv +/dist/ +/*.zip +.env +*.log diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..dfaa91e --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Aerial screensaver for Linux contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index fc71976..ecc39ee 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,121 @@ -# Aerial Screensaver for Linux +# Aerial Screensaver for Linux (GNOME) -A high-performance, power-efficient Apple Aerial screensaver implementation for Linux, optimized for the Framework 16 and AMD graphics. +Idle screensaver that plays Apple Aerial–style clips with **mpv**, on **every connected monitor**. Designed to be quiet on battery and dual-GPU laptops: AC-only by default, lid-aware, VAAPI decode, low CPU niceness. + +> This package is the **player + tooling**. Apple’s video assets are not redistributed here — download them yourself (helper included). ## Features -- **Power Efficient**: Only runs when connected to AC power. -- **Low Impact**: Runs with `nice 19` priority and `idle` scheduling. -- **Hardware Accelerated**: Uses VA-API on the Integrated GPU to keep the Discrete GPU asleep. -- **Smooth Playback**: Optimized for local 4K HEVC files with frame-dropping logic for 60Hz displays. -- **Systemd Integration**: Runs as a background user service. + +- Starts after idle (default 5 minutes) via GNOME Mutter IdleMonitor +- Fullscreen **one mpv per logical monitor** +- AC-only (optional) and skips / stops when the laptop lid is closed +- VAAPI HEVC playback; lite encoder for 1080p24 library files +- systemd user service ## Requirements -- `mpv` -- `python3` -- `python3-gobject` (for GNOME IdleMonitor access) -- `systemd` - -## Installation -1. Place your Aerial videos in `~/Videos/Screensavers/Aerial`. -2. Copy `aerial-screensaver.py` to `~/.local/bin/aerial-screensaver`. -3. Copy `aerial-screensaver.service` to `~/.config/systemd/user/`. -4. Enable the service: - ```bash - systemctl --user daemon-reload - systemctl --user enable --now aerial-screensaver - ``` + +| Package | Why | +|---|---| +| GNOME (Wayland) | IdleMonitor + DisplayConfig | +| `python3` + PyGObject (`python3-gobject` / `python3-gi`) | Daemon | +| `mpv` | Playback | +| `ffmpeg` (VAAPI HEVC) | Optional encode | +| `aria2c`, `curl`, `jq`/`python3` | Optional fetch helper | +| `systemd --user` | Autostart | + +Fedora / CachyOS example: + +```bash +sudo dnf install mpv ffmpeg python3-gobject aria2 curl +``` + +## Quick install + +```bash +git clone https://git.kernelcode.com/aerial-screensaver-linux +# or unzip the LocalSend archive, then: +cd aerial-screensaver-linux +./install.sh +``` + +`install.sh` installs: + +- `~/.local/bin/aerial-screensaver` +- `~/.local/bin/encode-aerial-lite` +- `~/.local/bin/fetch-aerial-recent` +- `~/.config/systemd/user/aerial-screensaver.service` +- `~/.config/aerial-screensaver/config` + +Enable is done for you. Check: + +```bash +systemctl --user status aerial-screensaver +``` + +## Get videos + +### Option A — fetch recent Apple pack (recommended) + +Tahoe / Sequoia / Sonoma / Cazadero from Apple’s public macOS catalog: + +```bash +fetch-aerial-recent --encode +``` + +Downloads masters, then encodes lite 1080p24 clips into `~/Videos/Screensavers/Aerial`. + +### Option B — your own files + +```bash +mkdir -p ~/Videos/Screensavers/Aerial +# copy .mp4 / .mov / .mkv there +``` + +### Option C — encode masters you already have + +```bash +encode-aerial-lite /path/to/4k-masters +``` + +## Config + +Edit `~/.config/aerial-screensaver/config`: + +```ini +VIDEO_DIR=/home/YOU/Videos/Screensavers/Aerial +IDLE_TIMEOUT_SECONDS=300 +REQUIRE_AC=1 +VAAPI_DEVICE=/dev/dri/by-path/pci-XXXX:XX:XX.X-render +``` + +On dual-GPU machines, set `VAAPI_DEVICE` to the **iGPU** render node so the discrete GPU stays asleep. `install.sh` writes a detected default; override if needed. + +Environment overrides (prefix `AERIAL_`): `AERIAL_VIDEO_DIR`, `AERIAL_IDLE_TIMEOUT_SECONDS`, `AERIAL_VAAPI_DEVICE`, `AERIAL_REQUIRE_AC`. + +## Uninstall + +```bash +./uninstall.sh +``` + +Videos and `~/.config/aerial-screensaver/` are left in place. + +## Sharing + +| Method | What to send | +|---|---| +| **Git** | This repo (no videos) | +| **LocalSend** | `aerial-screensaver-linux.zip` from `dist/` (no videos) | +| **LocalSend + clips** | Also send `~/Videos/Screensavers/Aerial` separately (~1GB lite) | + +Do not commit or publish Apple’s `.mov` masters — fetch them per machine. + +## Tests + +```bash +python3 test_screensaver.py -v +``` + +## License + +MIT (this software only). Aerial video content remains Apple’s. diff --git a/aerial-screensaver.service b/aerial-screensaver.service index 9286643..58258a6 100644 --- a/aerial-screensaver.service +++ b/aerial-screensaver.service @@ -4,7 +4,8 @@ PartOf=graphical-session.target After=graphical-session.target [Service] -ExecStart=/usr/bin/python3 /home/christopherwarner/.local/bin/aerial_screensaver +ExecStartPre=/usr/bin/sleep 10 +ExecStart=/usr/bin/python3 %h/.local/bin/aerial-screensaver Restart=on-failure RestartSec=5s Nice=19 @@ -12,4 +13,4 @@ CPUSchedulingPolicy=idle IOSchedulingClass=idle [Install] -WantedBy=graphical-session.target \ No newline at end of file +WantedBy=graphical-session.target diff --git a/aerial_screensaver.py b/aerial_screensaver.py index 3c93086..5275dad 100755 --- a/aerial_screensaver.py +++ b/aerial_screensaver.py @@ -1,68 +1,102 @@ #!/usr/bin/env python3 -import time -import subprocess +"""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 logging +import time +from pathlib import Path + 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) - ] +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", ) - -# 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=-", -] +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 find_vaapi_device(preferred: str | None = None) -> str | None: + """Pick a DRM render node for VAAPI. Prefer an explicit path when set.""" + if preferred and Path(preferred).exists(): + return preferred + by_path = Path("/dev/dri/by-path") + if by_path.is_dir(): + # Prefer integrated / non-USB render nodes; stable by-path names. + candidates = sorted(by_path.glob("*-render")) + for path in candidates: + name = path.name.lower() + if "usb" in name: + continue + return str(path) + if candidates: + return str(candidates[0]) + renders = sorted(Path("/dev/dri").glob("renderD*")) + return str(renders[0]) if renders else None + + +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): - self.processes = [] + 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 - - logging.info("Initializing Aerial Screensaver (mpv Lite Backend, AC-only, Lid-Aware, multi-screen)...") - + 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: @@ -73,52 +107,58 @@ class AerialScreensaver: "org.gnome.Mutter.IdleMonitor", "/org/gnome/Mutter/IdleMonitor/Core", "org.gnome.Mutter.IdleMonitor", - None + None, ) - reply = self.idle_monitor.call_sync( "AddIdleWatch", - GLib.Variant("(t)", (IDLE_TIMEOUT_SECONDS * 1000,)), + GLib.Variant("(t)", (self.idle_timeout_seconds * 1000,)), Gio.DBusCallFlags.NONE, -1, - None + None, ) self.watch_id = reply.unpack()[0] - logging.info(f"Added IdleWatch with ID: {self.watch_id} for {IDLE_TIMEOUT_SECONDS}s") - + 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(f"Failed to connect to IdleMonitor: {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): + 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') as f: - if f.read().strip() == '1': + 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(f"Error checking AC status: {e}") + logging.error("Error checking AC status: %s", e) return False - def is_lid_open(self): + def is_lid_open(self) -> bool: try: - if not os.path.exists(LID_STATE_FILE): + if not os.path.exists(self.lid_state_file): return True - with open(LID_STATE_FILE, 'r') as f: - content = f.read().strip() - return "open" in content + with open(self.lid_state_file, "r", encoding="utf-8") as f: + return "open" in f.read().strip() except Exception as e: - logging.error(f"Error checking lid status: {e}") + logging.error("Error checking lid status: %s", e) return True - def get_screen_count(self): + def get_screen_count(self) -> int: """Return active GNOME logical monitor count (fallback: 1).""" try: proxy = Gio.DBusProxy.new_for_bus_sync( @@ -128,63 +168,104 @@ class AerialScreensaver: "org.gnome.Mutter.DisplayConfig", "/org/gnome/Mutter/DisplayConfig", "org.gnome.Mutter.DisplayConfig", - None + None, ) reply = proxy.call_sync( "GetCurrentState", None, Gio.DBusCallFlags.NONE, -1, - None + None, ) _serial, _monitors, logical_monitors, _props = reply.unpack() - count = len(logical_monitors) - if count < 1: - return 1 - return count + return max(1, len(logical_monitors)) except Exception as e: - logging.error(f"Error detecting screens, defaulting to 1: {e}") + logging.error("Error detecting screens, defaulting to 1: %s", 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 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): - if not os.path.isdir(VIDEO_DIR): + def _collect_videos(self) -> list[str]: + if not self.video_dir.is_dir(): return [] - return [ - os.path.join(VIDEO_DIR, f) - for f in os.listdir(VIDEO_DIR) + 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): + def _any_running(self) -> bool: return any(p.poll() is None for p in self.processes) - def start_screensaver(self): + def start_screensaver(self) -> None: if self._any_running(): return - try: videos = self._collect_videos() if not videos: - logging.error(f"No video files found in {VIDEO_DIR}") + logging.error("No video files found in %s", self.video_dir) return screen_count = self.get_screen_count() - logging.info(f"Using {len(videos)} clips from {VIDEO_DIR} on {screen_count} screen(s)") + 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}" @@ -192,8 +273,7 @@ class AerialScreensaver: os.unlink(ipc) except FileNotFoundError: pass - - cmd = MPV_BASE_COMMAND + [ + cmd = base + [ f"--input-ipc-server={ipc}", f"--screen={screen}", f"--fs-screen={screen}", @@ -203,21 +283,19 @@ class AerialScreensaver: stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, - text=True + 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}") - + 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(f"Error starting mpv: {e}") + logging.error("Error starting mpv: %s", e) self.stop_screensaver() - def monitor_activity(self): + def monitor_activity(self) -> None: while self._any_running(): time.sleep(1) try: @@ -225,29 +303,24 @@ class AerialScreensaver: 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 + None, ) - idle_time = reply.unpack()[0] - - if idle_time < 1000: + 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(f"Error in monitor_activity: {e}") + logging.error("Error in monitor_activity: %s", e) break - def stop_screensaver(self): + def stop_screensaver(self) -> None: for proc in self.processes: if proc.poll() is None: proc.terminate() @@ -256,15 +329,13 @@ class AerialScreensaver: except subprocess.TimeoutExpired: proc.kill() self.processes = [] - for path in ( - f"{IPC_SOCKET_PREFIX}{i}" for i in range(8) - ): + for i in range(8): try: - os.unlink(path) + os.unlink(f"{IPC_SOCKET_PREFIX}{i}") except FileNotFoundError: pass - def run(self): + def run(self) -> None: loop = GLib.MainLoop() try: loop.run() @@ -273,5 +344,4 @@ class AerialScreensaver: if __name__ == "__main__": - app = AerialScreensaver() - app.run() + AerialScreensaver().run() diff --git a/bin/encode-aerial-lite b/bin/encode-aerial-lite new file mode 100755 index 0000000..58976af --- /dev/null +++ b/bin/encode-aerial-lite @@ -0,0 +1,130 @@ +#!/usr/bin/env bash +# Downsample Aerial masters into ~/Videos/Screensavers/Aerial: +# 1920x1080, 24fps, 8-bit HEVC via VAAPI (~2 Mb/s). +# +# Usage: +# encode-aerial-lite /path/to/4k-sources +# SRC_DIR=/path/to/4k DST_DIR=~/Videos/Screensavers/Aerial encode-aerial-lite +set -euo pipefail + +SRC_DIR="${1:-${SRC_DIR:-}}" +DST_DIR="${DST_DIR:-$HOME/Videos/Screensavers/Aerial}" +CONFIG_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/aerial-screensaver/config" +BITRATE="${BITRATE:-2M}" +MAXRATE="${MAXRATE:-2.5M}" + +detect_vaapi() { + if [[ -n "${VAAPI_DEVICE:-}" && -e "$VAAPI_DEVICE" ]]; then + printf '%s\n' "$VAAPI_DEVICE" + return 0 + fi + if [[ -f "$CONFIG_FILE" ]]; then + local from_cfg + from_cfg="$(awk -F= '/^VAAPI_DEVICE=/{print $2; exit}' "$CONFIG_FILE" | tr -d '"' || true)" + if [[ -n "$from_cfg" && -e "$from_cfg" ]]; then + printf '%s\n' "$from_cfg" + return 0 + fi + fi + local p + if [[ -d /dev/dri/by-path ]]; then + for p in /dev/dri/by-path/*-render; do + [[ -e "$p" ]] || continue + [[ "$(basename "$p")" == *usb* ]] && continue + printf '%s\n' "$p" + return 0 + done + fi + for p in /dev/dri/renderD*; do + [[ -e "$p" ]] || continue + printf '%s\n' "$p" + return 0 + done + return 1 +} + +if [[ -z "$SRC_DIR" ]]; then + echo "Usage: encode-aerial-lite /path/to/4k-source-folder" >&2 + echo "Encodes into: $DST_DIR" >&2 + exit 1 +fi + +VAAPI_DEVICE="$(detect_vaapi)" || { + echo "No VAAPI render node found. Set VAAPI_DEVICE=/dev/dri/renderD128" >&2 + exit 1 +} + +mkdir -p "$DST_DIR" +shopt -s nullglob nocaseglob + +encode_one() { + local src="$1" + local base dest tmp + base="$(basename "$src")" + base="${base%.*}" + dest="$DST_DIR/${base}.mp4" + + if [[ -f "$dest" ]]; then + echo "SKIP $base (exists)" + return 0 + fi + + echo "ENCODE $base" + tmp="$DST_DIR/.${base}.partial.mp4" + rm -f "$tmp" + + if ffmpeg -y -hide_banner -loglevel error -stats \ + -hwaccel vaapi -hwaccel_device "$VAAPI_DEVICE" -hwaccel_output_format vaapi \ + -i "$src" \ + -vf "fps=24,scale_vaapi=w=1920:h=1080:format=nv12" \ + -c:v hevc_vaapi -b:v "$BITRATE" -maxrate "$MAXRATE" -bufsize 4M \ + -an -movflags +faststart \ + "$tmp"; then + mv -f "$tmp" "$dest" + echo "OK $base ($(du -h "$dest" | cut -f1))" + else + echo "FAIL $base — retrying with software decode" >&2 + rm -f "$tmp" + if ffmpeg -y -hide_banner -loglevel error -stats \ + -vaapi_device "$VAAPI_DEVICE" \ + -i "$src" \ + -vf "fps=24,scale=1920:1080:flags=bicubic,format=nv12,hwupload" \ + -c:v hevc_vaapi -b:v "$BITRATE" -maxrate "$MAXRATE" -bufsize 4M \ + -an -movflags +faststart \ + "$tmp"; then + mv -f "$tmp" "$dest" + echo "OK $base (sw-decode, $(du -h "$dest" | cut -f1))" + else + rm -f "$tmp" + echo "FAIL $base" >&2 + return 1 + fi + fi +} + +shopt -u nocaseglob +mapfile -t files < <(find "$SRC_DIR" -maxdepth 1 -type f \( -iname '*.mov' -o -iname '*.mp4' -o -iname '*.mkv' \) | sort) +if [[ ${#files[@]} -eq 0 ]]; then + echo "No source videos in $SRC_DIR" >&2 + exit 1 +fi + +echo "Source: $SRC_DIR (${#files[@]} files)" +echo "Dest: $DST_DIR" +echo "Device: $VAAPI_DEVICE" +echo + +failures=0 +for f in "${files[@]}"; do + if ! encode_one "$f"; then + failures=$((failures + 1)) + fi +done + +rm -f "$DST_DIR/_test_lite.mp4" "$DST_DIR"/.*.partial.mp4 + +echo +echo "Done. Lite library:" +ls -lh "$DST_DIR" +du -sh "$DST_DIR" +exit "$failures" diff --git a/bin/fetch-aerial-recent b/bin/fetch-aerial-recent new file mode 100755 index 0000000..852bee8 --- /dev/null +++ b/bin/fetch-aerial-recent @@ -0,0 +1,112 @@ +#!/usr/bin/env bash +# Download the recent macOS Aerial pack (Tahoe / Sequoia / Sonoma / Cazadero) +# from Apple's public catalog, then optionally encode to lite 1080p24. +# +# Usage: +# fetch-aerial-recent # download masters only +# fetch-aerial-recent --encode # download + encode-aerial-lite +set -euo pipefail + +ENCODE=0 +for arg in "$@"; do + case "$arg" in + --encode) ENCODE=1 ;; + -h|--help) + echo "Usage: fetch-aerial-recent [--encode]" + exit 0 + ;; + esac +done + +MASTER_DIR="${AERIAL_MASTER_DIR:-$HOME/Videos/Screensavers/Aerial-masters}" +LITE_DIR="${DST_DIR:-$HOME/Videos/Screensavers/Aerial}" +CATALOG_DIR="${TMPDIR:-/tmp}/aerial-catalog-$$" +CONFIG_URL="https://configuration.apple.com/configurations/internetservices/aerials/resources-config-26-0.plist" +WANT_LABELS=( + "Tahoe Day" "Tahoe Morning" "Tahoe Evening" "Tahoe Night" + "Sequoia Sunrise" "Sequoia Morning" "Sequoia Night" + "Cazadero" + "Sonoma Evening" "Sonoma Clouds" "Sonoma from Above" "Sonoma River" +) + +need() { command -v "$1" >/dev/null 2>&1 || { echo "Missing dependency: $1" >&2; exit 1; }; } +need curl +need python3 +need aria2c +need tar + +mkdir -p "$MASTER_DIR" "$CATALOG_DIR" +trap 'rm -rf "$CATALOG_DIR"' EXIT + +echo "Resolving macOS Aerial catalog..." +RESOURCES_URL="$(curl -fsSL --max-time 30 "$CONFIG_URL" | python3 -c ' +import sys,re +text=sys.stdin.read() +m=re.search(r"resources-url\s*([^<]+)", text) +if not m: raise SystemExit("resources-url not found in plist") +print(m.group(1)) +')" + +echo "Catalog: $RESOURCES_URL" +curl -kfsSL --max-time 120 -o "$CATALOG_DIR/resources.tar" "$RESOURCES_URL" +tar -xf "$CATALOG_DIR/resources.tar" -C "$CATALOG_DIR" 2>/dev/null || true +ENTRIES_JSON="$(find "$CATALOG_DIR" -name entries.json -type f | head -n1)" +if [[ -z "$ENTRIES_JSON" ]]; then + echo "entries.json not found in catalog tar" >&2 + exit 1 +fi + +python3 - "$ENTRIES_JSON" "$CATALOG_DIR/urls.txt" <<'PY' +import json, os, sys +entries_path, urls_path = sys.argv[1], sys.argv[2] +want = { + "Tahoe Day", "Tahoe Morning", "Tahoe Evening", "Tahoe Night", + "Sequoia Sunrise", "Sequoia Morning", "Sequoia Night", + "Cazadero", + "Sonoma Evening", "Sonoma Clouds", "Sonoma from Above", "Sonoma River", +} +data = json.load(open(entries_path, encoding="utf-8")) +found = [] +with open(urls_path, "w", encoding="utf-8") as out: + for asset in data.get("assets", []): + label = asset.get("accessibilityLabel") or "" + if label not in want: + continue + url = asset.get("url-4K-SDR-240FPS") or asset.get("url-4K-SDR") + if not url: + continue + base = os.path.basename(url.split("?", 1)[0]) + out.write(f"{url}\n out={base}\n") + found.append((label, base)) +if len(found) != len(want): + missing = want - {l for l, _ in found} + print(f"warning: missing labels: {sorted(missing)}", file=sys.stderr) +print(f"Queued {len(found)} clips:") +for label, base in sorted(found): + print(f" {label}: {base}") +PY + +echo +echo "Downloading into $MASTER_DIR ..." +aria2c --check-certificate=false -c -x 4 -s 4 -j 3 \ + -i "$CATALOG_DIR/urls.txt" \ + -d "$MASTER_DIR" \ + --auto-file-renaming=false + +echo +echo "Masters ready: $(du -sh "$MASTER_DIR" | cut -f1)" + +if [[ "$ENCODE" -eq 1 ]]; then + SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + ENCODER="$SCRIPT_DIR/encode-aerial-lite" + if [[ ! -x "$ENCODER" ]]; then + ENCODER="$(command -v encode-aerial-lite || true)" + fi + if [[ -z "$ENCODER" ]]; then + echo "encode-aerial-lite not found; masters left in $MASTER_DIR" >&2 + exit 1 + fi + DST_DIR="$LITE_DIR" "$ENCODER" "$MASTER_DIR" +fi + +echo "Done." diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..63a1554 --- /dev/null +++ b/install.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Install Aerial screensaver user service + helpers. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +BIN_DIR="${XDG_BIN_HOME:-$HOME/.local/bin}" +UNIT_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user" +CFG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/aerial-screensaver" +VIDEO_DIR="${VIDEO_DIR:-$HOME/Videos/Screensavers/Aerial}" + +need() { + if ! command -v "$1" >/dev/null 2>&1; then + echo "Missing dependency: $1" >&2 + MISSING=1 + fi +} + +MISSING=0 +need python3 +need mpv +need systemctl +# PyGObject (gi) is required +if ! python3 -c 'from gi.repository import Gio, GLib' 2>/dev/null; then + echo "Missing dependency: PyGObject (python3-gobject / python3-gi)" >&2 + MISSING=1 +fi +if [[ "$MISSING" -ne 0 ]]; then + echo "Install the packages above, then re-run ./install.sh" >&2 + exit 1 +fi + +detect_vaapi() { + local p + if [[ -n "${VAAPI_DEVICE:-}" && -e "$VAAPI_DEVICE" ]]; then + printf '%s\n' "$VAAPI_DEVICE" + return 0 + fi + if [[ -d /dev/dri/by-path ]]; then + for p in /dev/dri/by-path/*-render; do + [[ -e "$p" ]] || continue + [[ "$(basename "$p")" == *usb* ]] && continue + printf '%s\n' "$p" + return 0 + done + fi + for p in /dev/dri/renderD*; do + [[ -e "$p" ]] || continue + printf '%s\n' "$p" + return 0 + done + return 1 +} + +VAAPI="$(detect_vaapi || true)" + +mkdir -p "$BIN_DIR" "$UNIT_DIR" "$CFG_DIR" "$VIDEO_DIR" + +install -m 0755 "$ROOT/aerial_screensaver.py" "$BIN_DIR/aerial-screensaver" +install -m 0755 "$ROOT/bin/encode-aerial-lite" "$BIN_DIR/encode-aerial-lite" +install -m 0755 "$ROOT/bin/fetch-aerial-recent" "$BIN_DIR/fetch-aerial-recent" +install -m 0644 "$ROOT/aerial-screensaver.service" "$UNIT_DIR/aerial-screensaver.service" + +if [[ ! -f "$CFG_DIR/config" ]]; then + cat > "$CFG_DIR/config" </dev/null || true +rm -f "$UNIT_DIR/aerial-screensaver.service" +rm -f "$BIN_DIR/aerial-screensaver" "$BIN_DIR/encode-aerial-lite" "$BIN_DIR/fetch-aerial-recent" +systemctl --user daemon-reload 2>/dev/null || true + +echo "Removed service and helpers." +echo "Config left in place: $CFG_DIR (delete manually if desired)" +echo "Videos left in place: ~/Videos/Screensavers/Aerial" -- cgit v1.2.3