Plays folders of videos on a loop from boot, with a controller menu, per-video on/off, play settings, a logo boot splash and a nightly YouTube sync. Tested on a Raspberry Pi 4; x86 paths are untested. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1539 lines
59 KiB
Python
Executable File
1539 lines
59 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Never-ending enrichment video player for a Raspberry Pi.
|
|
|
|
Plays every video in one folder of ~/enrichment_videos on a loop. The chosen
|
|
folder survives reboots; if it is gone, another is picked at random. Anyone can
|
|
switch folders with a game controller (or keyboard) using an on-screen menu.
|
|
|
|
One long-lived mpv draws straight to the display (no desktop needed). This
|
|
process supervises it over its IPC socket: folder changes never restart mpv, so
|
|
the screen never drops to the console, and if mpv dies or freezes it is replaced.
|
|
"""
|
|
|
|
import argparse
|
|
import glob
|
|
import json
|
|
import os
|
|
import random
|
|
import re
|
|
import select
|
|
import shutil
|
|
import signal
|
|
import socket
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unicodedata
|
|
from pathlib import Path
|
|
|
|
import evdev
|
|
from evdev import ecodes as e
|
|
|
|
VIDEO_EXTENSIONS = {
|
|
".mp4", ".m4v", ".mkv", ".mov", ".avi", ".webm",
|
|
".mpg", ".mpeg", ".ts", ".wmv", ".flv",
|
|
}
|
|
|
|
MENU_TIMEOUT = 30.0 # seconds of no input before the menu closes itself
|
|
MENU_ROWS = 9 # folders visible at once; the list scrolls past this
|
|
STALL_LIMIT = 30.0 # seconds without playback progress before replacing mpv
|
|
HEALTH_INTERVAL = 1.0
|
|
RESCAN_INTERVAL = 5.0 # how often to look for videos when nothing is playable
|
|
LOGO_FILE = Path(__file__).resolve().parent / "boot" / "logo.bgra"
|
|
LOGO_WIDTH, LOGO_HEIGHT, LOGO_Y = 1056, 390, 306 # same place as the boot splash
|
|
FIRST_FRAME_TIMEOUT = 15.0 # how long the logo may wait for the first video frame
|
|
FAILED_START_SECONDS = 30.0 # a session shorter than this counts as a failed start
|
|
RETRY_INTERVAL = 10.0 # how often to retry a folder none of whose files play
|
|
REPEAT_DELAY = 0.45 # holding a direction: wait, then repeat
|
|
REPEAT_RATE = 0.15
|
|
|
|
# Logitech pads report different buttons depending on the X/D switch underneath:
|
|
# XInput mode uses the standard names, DirectInput ("Dual Action") uses the
|
|
# generic joystick ones. Both map to the same actions so the switch can't matter.
|
|
CONFIRM_BUTTONS = {
|
|
e.BTN_SOUTH, # X mode: A
|
|
e.BTN_THUMB, # D mode: A
|
|
e.KEY_ENTER, e.KEY_KPENTER,
|
|
}
|
|
CANCEL_BUTTONS = {
|
|
e.BTN_EAST, e.BTN_SELECT, # X mode: B, Back
|
|
e.BTN_THUMB2, e.BTN_BASE3, # D mode: B, Back
|
|
e.KEY_ESC, e.KEY_BACKSPACE,
|
|
}
|
|
UP_BUTTONS = {e.BTN_DPAD_UP, e.KEY_UP}
|
|
DOWN_BUTTONS = {e.BTN_DPAD_DOWN, e.KEY_DOWN}
|
|
RIGHT_BUTTONS = {e.BTN_DPAD_RIGHT, e.KEY_RIGHT}
|
|
LEFT_BUTTONS = {e.BTN_DPAD_LEFT, e.KEY_LEFT}
|
|
TOGGLE_BUTTONS = {
|
|
e.BTN_X, # X mode: X (the kernel's BTN_NORTH)
|
|
e.BTN_TRIGGER, # D mode: X
|
|
e.KEY_SPACE,
|
|
}
|
|
NEXT_BUTTONS = {e.BTN_TR, e.BTN_PINKIE, e.KEY_N} # RB
|
|
JUMP_BUTTONS = {e.BTN_TL, e.BTN_TOP2, e.KEY_R} # LB
|
|
SETTINGS_BUTTONS = {e.BTN_START, e.BTN_BASE4, e.KEY_S} # Start
|
|
|
|
# Each setting: key, label, and its (value, text) choices. The first is the default.
|
|
OFF_ON = ((False, "Off"), (True, "On"))
|
|
SETTINGS = (
|
|
("shuffle", "Shuffle play order", OFF_ON),
|
|
("max_minutes", "Max time per video",
|
|
((0, "No limit"), (5, "5 minutes"), (10, "10 minutes"), (15, "15 minutes"),
|
|
(30, "30 minutes"), (60, "1 hour"), (120, "2 hours"))),
|
|
("random_start", "Start videos at a random spot", OFF_ON),
|
|
("volume", "Volume",
|
|
((100, "100%"), (75, "75%"), (50, "50%"), (25, "25%"), (0, "Muted"))),
|
|
)
|
|
|
|
|
|
# --------------------------------------------------------------- library ----
|
|
|
|
def natural_key(name):
|
|
"""Sort so 'clip2' comes before 'clip10'."""
|
|
return [int(p) if p.isdigit() else p.casefold() for p in re.split(r"(\d+)", name)]
|
|
|
|
|
|
def is_video(entry):
|
|
# Hidden files include the '._clip.mp4' junk macOS leaves on USB sticks.
|
|
return (not entry.name.startswith(".")
|
|
and Path(entry.name).suffix.lower() in VIDEO_EXTENSIONS
|
|
and entry.is_file())
|
|
|
|
|
|
def list_videos(folder):
|
|
try:
|
|
with os.scandir(folder) as it:
|
|
names = [entry.name for entry in it if is_video(entry)]
|
|
except OSError:
|
|
return []
|
|
return [str(Path(folder) / n) for n in sorted(names, key=natural_key)]
|
|
|
|
|
|
def list_folders(root):
|
|
"""Return {folder name: video count} for folders with something to play."""
|
|
try:
|
|
with os.scandir(root) as it:
|
|
dirs = [d.name for d in it if d.is_dir() and not d.name.startswith(".")]
|
|
except OSError:
|
|
return {}
|
|
counts = {name: len(list_videos(Path(root) / name)) for name in dirs}
|
|
return {n: counts[n] for n in sorted(dirs, key=natural_key) if counts[n]}
|
|
|
|
|
|
def random_video(files, last_name):
|
|
"""Any of `files` other than the one called `last_name`, if there is a choice."""
|
|
others = [f for f in files if Path(f).name != last_name]
|
|
return random.choice(others or files) if files else None
|
|
|
|
|
|
def video_duration(path):
|
|
"""Length of a video in seconds, or None if it can't be read."""
|
|
try:
|
|
result = subprocess.run(
|
|
["ffprobe", "-v", "error", "-show_entries", "format=duration",
|
|
"-of", "csv=p=0", str(path)],
|
|
capture_output=True, text=True, timeout=10, check=False)
|
|
return float(result.stdout.strip())
|
|
except (OSError, ValueError, subprocess.TimeoutExpired):
|
|
return None
|
|
|
|
|
|
def load_last_folder(state_file):
|
|
try:
|
|
return Path(state_file).read_text(encoding="utf-8").strip() or None
|
|
except (OSError, UnicodeDecodeError):
|
|
return None
|
|
|
|
|
|
def save_text(path, text):
|
|
"""Atomic and fsynced: the Pi may lose power at any moment."""
|
|
path = Path(path)
|
|
try:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = path.with_suffix(".tmp")
|
|
with open(tmp, "w", encoding="utf-8") as f:
|
|
f.write(text)
|
|
f.flush()
|
|
os.fsync(f.fileno())
|
|
os.replace(tmp, path)
|
|
except OSError as err:
|
|
log(f"could not save {path.name}: {err}") # keep playing regardless
|
|
|
|
|
|
def save_last_folder(state_file, folder):
|
|
save_text(state_file, folder + "\n")
|
|
|
|
|
|
def load_disabled(path):
|
|
"""Return {folder: set of disabled file names}."""
|
|
try:
|
|
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
return {folder: set(names) for folder, names in data.items()}
|
|
except (OSError, ValueError, AttributeError, TypeError):
|
|
return {}
|
|
|
|
|
|
def save_disabled(path, disabled):
|
|
kept = {folder: sorted(names) for folder, names in disabled.items() if names}
|
|
save_text(path, json.dumps(kept, indent=2, ensure_ascii=False) + "\n")
|
|
|
|
|
|
def load_settings(path):
|
|
"""Saved settings, with the default for anything missing or not a valid choice."""
|
|
try:
|
|
saved = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
saved = {}
|
|
if not isinstance(saved, dict):
|
|
saved = {}
|
|
values = {}
|
|
for key, _, choices in SETTINGS:
|
|
allowed = [value for value, _ in choices]
|
|
values[key] = saved[key] if saved.get(key) in allowed else allowed[0]
|
|
return values
|
|
|
|
|
|
def save_settings(path, values):
|
|
save_text(path, json.dumps(values, indent=2) + "\n")
|
|
|
|
|
|
def enabled_videos(root, folder, disabled):
|
|
"""The videos to play. If only disabled files remain, play those: never nothing."""
|
|
videos = list_videos(Path(root) / folder)
|
|
off = disabled.get(folder, ())
|
|
return [v for v in videos if Path(v).name not in off] or videos
|
|
|
|
|
|
def choose_folder(root, state_file):
|
|
"""The last picked folder if it still has videos, otherwise a random one."""
|
|
folders = list_folders(root)
|
|
if not folders:
|
|
return None
|
|
last = load_last_folder(state_file)
|
|
if last in folders:
|
|
return last
|
|
choice = random.choice(list(folders))
|
|
save_last_folder(state_file, choice)
|
|
return choice
|
|
|
|
|
|
# ----------------------------------------------------------------- input ----
|
|
|
|
class Translator:
|
|
"""Turns one input device's raw events into 'up'/'down'/'next'/'jump'/...
|
|
|
|
Sticks and d-pads are treated alike. Holding up or down repeats; nothing
|
|
else does, so a lingering push can't skip through a whole folder.
|
|
"""
|
|
|
|
def __init__(self, dev=None):
|
|
self.axes = {} # axis code -> -1, 0 or 1
|
|
self.ranges = {} # axis code -> (min, max)
|
|
self.next_repeat = None
|
|
self.sideways = {} # axis code -> -1 (left), 0 or 1 (right)
|
|
if dev is not None:
|
|
for code, info in dev.capabilities().get(e.EV_ABS, []):
|
|
self.ranges[code] = (info.min, info.max)
|
|
|
|
def _direction(self):
|
|
return next((v for v in self.axes.values() if v), 0)
|
|
|
|
def _position(self, code, value):
|
|
low, high = self.ranges.get(code, (-1, 1))
|
|
span = (high - low) or 1
|
|
return 2 * (value - low) / span - 1
|
|
|
|
def _axis(self, code, value, now):
|
|
position = self._position(code, value)
|
|
current = self.axes.get(code, 0)
|
|
# Hysteresis stops a stick resting near the threshold from chattering.
|
|
if abs(position) > 0.6:
|
|
new = 1 if position > 0 else -1
|
|
elif abs(position) < 0.3:
|
|
new = 0
|
|
else:
|
|
new = current
|
|
before = self._direction()
|
|
self.axes[code] = new
|
|
after = self._direction()
|
|
if after == before:
|
|
return []
|
|
self.next_repeat = now + REPEAT_DELAY if after else None
|
|
if after:
|
|
return ["down" if after > 0 else "up"]
|
|
return []
|
|
|
|
def _sideways_axis(self, code, value):
|
|
position = self._position(code, value)
|
|
current = self.sideways.get(code, 0)
|
|
if abs(position) > 0.6:
|
|
new = 1 if position > 0 else -1
|
|
elif abs(position) < 0.3:
|
|
new = 0
|
|
else:
|
|
new = current
|
|
self.sideways[code] = new
|
|
if new == current or new == 0:
|
|
return []
|
|
return ["right"] if new > 0 else ["left"]
|
|
|
|
def feed(self, event, now):
|
|
if event.type == e.EV_ABS and event.code in (e.ABS_Y, e.ABS_HAT0Y):
|
|
return self._axis(event.code, event.value, now)
|
|
if event.type == e.EV_ABS and event.code in (e.ABS_X, e.ABS_HAT0X):
|
|
return self._sideways_axis(event.code, event.value)
|
|
if event.type != e.EV_KEY or event.value == 0:
|
|
return []
|
|
if event.code in UP_BUTTONS:
|
|
return ["up"]
|
|
if event.code in DOWN_BUTTONS:
|
|
return ["down"]
|
|
if event.value == 2: # keyboard auto-repeat only matters for up/down
|
|
return []
|
|
for buttons, action in ((RIGHT_BUTTONS, "right"), (LEFT_BUTTONS, "left"),
|
|
(TOGGLE_BUTTONS, "toggle"), (NEXT_BUTTONS, "next"),
|
|
(JUMP_BUTTONS, "jump"), (SETTINGS_BUTTONS, "settings")):
|
|
if event.code in buttons:
|
|
return [action]
|
|
if event.code in CONFIRM_BUTTONS:
|
|
return ["confirm"]
|
|
if event.code in CANCEL_BUTTONS:
|
|
return ["cancel"]
|
|
if e.BTN_JOYSTICK <= event.code <= e.BTN_THUMBR:
|
|
return ["any"] # any other pad button still opens the menu
|
|
return []
|
|
|
|
def tick(self, now):
|
|
if self.next_repeat is not None and now >= self.next_repeat:
|
|
self.next_repeat = now + REPEAT_RATE
|
|
return ["down" if self._direction() > 0 else "up"]
|
|
return []
|
|
|
|
|
|
def is_supported_device(dev):
|
|
caps = dev.capabilities()
|
|
keys = set(caps.get(e.EV_KEY, []))
|
|
pad = any(e.BTN_JOYSTICK <= k <= e.BTN_THUMBR for k in keys)
|
|
keyboard = {e.KEY_UP, e.KEY_DOWN, e.KEY_ENTER} <= keys
|
|
return pad or keyboard
|
|
|
|
|
|
class Inputs:
|
|
"""Every usable input device; controllers may come and go at any time."""
|
|
|
|
def __init__(self):
|
|
self.devices = {} # fd -> (InputDevice, Translator)
|
|
self.ignored = set()
|
|
self.next_scan = 0.0
|
|
|
|
def _scan(self):
|
|
known = {dev.path for dev, _ in self.devices.values()} | self.ignored
|
|
present = set(evdev.list_devices())
|
|
self.ignored &= present
|
|
for path in present - known:
|
|
try:
|
|
dev = evdev.InputDevice(path)
|
|
if is_supported_device(dev):
|
|
self.devices[dev.fd] = (dev, Translator(dev))
|
|
log(f"input connected: {dev.name}")
|
|
else:
|
|
dev.close()
|
|
self.ignored.add(path)
|
|
except OSError:
|
|
pass
|
|
|
|
def _drop(self, fd):
|
|
dev, _ = self.devices.pop(fd)
|
|
log(f"input disconnected: {dev.name}")
|
|
try:
|
|
dev.close()
|
|
except OSError:
|
|
pass
|
|
|
|
def poll(self, timeout):
|
|
now = time.monotonic()
|
|
if now >= self.next_scan:
|
|
self.next_scan = now + 2.0
|
|
self._scan()
|
|
ready = []
|
|
if self.devices:
|
|
ready = select.select(list(self.devices), [], [], timeout)[0]
|
|
else:
|
|
time.sleep(timeout)
|
|
now = time.monotonic()
|
|
actions = []
|
|
for fd in ready:
|
|
dev, translator = self.devices[fd]
|
|
try:
|
|
for event in dev.read():
|
|
actions += translator.feed(event, now)
|
|
except BlockingIOError:
|
|
pass
|
|
except OSError:
|
|
self._drop(fd) # unplugged
|
|
for _, translator in self.devices.values():
|
|
actions += translator.tick(now)
|
|
return actions
|
|
|
|
|
|
# ------------------------------------------------------------------ menu ----
|
|
|
|
def video_title(path):
|
|
"""A readable title: no extension, YouTube id, or characters the font lacks."""
|
|
title = re.sub(r"\s*\[[\w-]{11}\]$", "", Path(path).stem)
|
|
title = unicodedata.normalize("NFKC", title)
|
|
return " ".join("".join(c for c in title if ord(c) <= 0xFFFF).split())
|
|
|
|
|
|
SETTINGS_ITEM = "\0settings" # the Settings row; no folder can have this name
|
|
|
|
|
|
class Menu:
|
|
"""Two levels: the list of folders, and the videos inside one folder."""
|
|
|
|
def __init__(self):
|
|
self.open = False
|
|
self.folder = None # None while showing the folder list
|
|
self.folders = {} # folder name -> text shown beside it
|
|
self.current = None
|
|
self.items = [] # folder names, or video paths
|
|
self.off = set() # paths of disabled videos
|
|
self.index = 0
|
|
self.closes_at = 0.0
|
|
|
|
def show(self, folders, current, now):
|
|
self.open = True
|
|
self.folder = None
|
|
self.folders = folders
|
|
self.current = current
|
|
self.off = set()
|
|
self.items = list(folders) + [SETTINGS_ITEM]
|
|
self.index = self.items.index(current) if current in folders else 0
|
|
self.closes_at = now + MENU_TIMEOUT
|
|
|
|
def enter(self, folder, videos, off, playing):
|
|
self.folder = folder
|
|
self.items = videos
|
|
self.off = off
|
|
self.index = videos.index(playing) if playing in videos else 0
|
|
|
|
def back(self):
|
|
names = list(self.folders)
|
|
self.index = names.index(self.folder) if self.folder in names else 0
|
|
self.folder = None
|
|
self.items = names + [SETTINGS_ITEM]
|
|
self.off = set()
|
|
|
|
def close(self):
|
|
self.open = False
|
|
|
|
def extend(self, now):
|
|
self.closes_at = now + MENU_TIMEOUT
|
|
|
|
def handle(self, action, now):
|
|
"""Apply one action while open. Returns what the player must do, if anything:
|
|
('open', folder), ('play_folder', folder), ('play_video', path),
|
|
('toggle', path), ('is_off', path) or ('settings', None).
|
|
"""
|
|
self.extend(now)
|
|
selected = self.items[self.index] if self.items else None
|
|
if action in ("up", "down") and self.items:
|
|
step = 1 if action == "down" else -1
|
|
self.index = (self.index + step) % len(self.items)
|
|
elif self.folder is None:
|
|
if action == "cancel":
|
|
self.close()
|
|
elif action in ("right", "confirm") and selected == SETTINGS_ITEM:
|
|
return ("settings", None)
|
|
elif action == "right" and selected:
|
|
return ("open", selected)
|
|
elif action == "confirm":
|
|
self.close()
|
|
if selected:
|
|
return ("play_folder", selected)
|
|
else:
|
|
if action in ("cancel", "left"):
|
|
self.back()
|
|
elif action == "toggle" and selected:
|
|
return ("toggle", selected)
|
|
elif action == "confirm" and selected:
|
|
if selected in self.off:
|
|
return ("is_off", selected)
|
|
self.close()
|
|
return ("play_video", selected)
|
|
return None
|
|
|
|
|
|
class SettingsWindow:
|
|
def __init__(self):
|
|
self.open = False
|
|
self.from_menu = False
|
|
self.index = 0
|
|
self.closes_at = 0.0
|
|
|
|
def show(self, now, from_menu=False):
|
|
self.open = True
|
|
self.from_menu = from_menu
|
|
self.index = 0
|
|
self.closes_at = now + MENU_TIMEOUT
|
|
|
|
def close(self):
|
|
self.open = False
|
|
|
|
def extend(self, now):
|
|
self.closes_at = now + MENU_TIMEOUT
|
|
|
|
def handle(self, action, values, now):
|
|
"""Apply one action while open. Returns the key of a changed setting."""
|
|
self.extend(now)
|
|
if action in ("up", "down"):
|
|
step = 1 if action == "down" else -1
|
|
self.index = (self.index + step) % len(SETTINGS)
|
|
elif action in ("left", "right", "confirm"):
|
|
key, _, choices = SETTINGS[self.index]
|
|
options = [value for value, _ in choices]
|
|
step = -1 if action == "left" else 1
|
|
values[key] = options[(options.index(values[key]) + step) % len(options)]
|
|
return key
|
|
return None
|
|
|
|
|
|
def ass_escape(text):
|
|
return (text.replace("\\", "\\\\").replace("{", "\\{").replace("}", "\\}")
|
|
.replace("\n", " "))
|
|
|
|
|
|
def ass_rect(x, y, w, h, color, alpha):
|
|
return (rf"{{\an7\pos(0,0)\bord0\shad0\1c&H{color}&\1a&H{alpha}&\p1}}"
|
|
f"m {x} {y} l {x + w} {y} {x + w} {y + h} {x} {y + h}{{\\p0}}")
|
|
|
|
|
|
def ass_text(x, y, text, size, color="FFFFFF", align=4, border=2, bold=False):
|
|
weight = r"\b1" if bold else ""
|
|
return (rf"{{\an{align}\pos({x},{y})\fs{size}\bord{border}\shad0\1c&H{color}&{weight}}}"
|
|
+ ass_escape(text))
|
|
|
|
|
|
def clip(text, length):
|
|
return text if len(text) <= length else text[:length - 1] + "…"
|
|
|
|
|
|
def short_titles(titles, length):
|
|
"""Shorten titles while keeping them different from each other.
|
|
|
|
Where a long title shares its opening with another, the text resumes at the
|
|
point they differ, so 'Island Paradise | Part 1' and '| Part 2' stay distinct.
|
|
"""
|
|
shortened = []
|
|
for title in titles:
|
|
shared = max((len(os.path.commonprefix([title, other]))
|
|
for other in titles if other != title), default=0)
|
|
if len(title) <= length:
|
|
shortened.append(title)
|
|
elif shared > length // 2:
|
|
head = title[:length // 2].rstrip()
|
|
shortened.append(head + "…" + title[shared:][:length - len(head) - 1].lstrip())
|
|
else:
|
|
tail = length // 3
|
|
shortened.append(title[:length - tail - 1].rstrip() + "…" + title[-tail:].lstrip())
|
|
return shortened
|
|
|
|
|
|
def ass_shape(path, color, alpha="00", outline=None):
|
|
"""A filled vector shape in absolute screen coordinates."""
|
|
edge = rf"\bord2\3c&H{outline}&\3a&H{alpha}&" if outline else r"\bord0"
|
|
return rf"{{\an7\pos(0,0){edge}\shad0\1c&H{color}&\1a&H{alpha}&\p1}}{path}{{\p0}}"
|
|
|
|
|
|
def rounded_path(x, y, w, h, r):
|
|
right, bottom = x + w, y + h
|
|
return (f"m {x + r} {y} l {right - r} {y} b {right} {y} {right} {y} {right} {y + r} "
|
|
f"l {right} {bottom - r} b {right} {bottom} {right} {bottom} {right - r} {bottom} "
|
|
f"l {x + r} {bottom} b {x} {bottom} {x} {bottom} {x} {bottom - r} "
|
|
f"l {x} {y + r} b {x} {y} {x} {y} {x + r} {y}")
|
|
|
|
|
|
def circle_path(cx, cy, r):
|
|
k = round(r * 0.55)
|
|
return (f"m {cx} {cy - r} b {cx + k} {cy - r} {cx + r} {cy - k} {cx + r} {cy} "
|
|
f"b {cx + r} {cy + k} {cx + k} {cy + r} {cx} {cy + r} "
|
|
f"b {cx - k} {cy + r} {cx - r} {cy + k} {cx - r} {cy} "
|
|
f"b {cx - r} {cy - k} {cx - k} {cy - r} {cx} {cy - r}")
|
|
|
|
|
|
GREEN, RED, BLUE, YELLOW, PALE = "40C840", "3838E8", "E89038", "30D0F8", "E8E8E8"
|
|
PLAYING_GREEN = "2E8B2E"
|
|
FACE_BUTTONS = ( # key, label, colour, x, y within the drawing
|
|
("y", "Y", YELLOW, 390, 80),
|
|
("x", "X", BLUE, 360, 110),
|
|
("b", "B", RED, 420, 110),
|
|
("a", "A", GREEN, 390, 140),
|
|
)
|
|
GUIDES = { # the action printed beside each working button
|
|
"folders": {"up": "Move up", "down": "Move down", "right": "Open folder",
|
|
"a": "Play folder", "b": "Close menu", "rb": "Next video",
|
|
"lb": "Random spot", "start": "Settings"},
|
|
"videos": {"up": "Move up", "down": "Move down", "left": "Back", "a": "Play video",
|
|
"x": "Turn on/off", "b": "Back",
|
|
"rb": "Next video", "lb": "Random spot", "start": "Settings"},
|
|
"settings_row": {"up": "Move up", "down": "Move down", "right": "Open settings",
|
|
"a": "Open settings", "b": "Close menu", "rb": "Next video",
|
|
"lb": "Random spot", "start": "Settings"},
|
|
"settings": {"up": "Move up", "down": "Move down", "left": "Change", "right": "Change",
|
|
"b": "Close", "rb": "Next video", "lb": "Random spot", "start": "Close"},
|
|
}
|
|
# The main actions on a screen, labelled larger and in colour.
|
|
HIGHLIGHTED = {"folders": {"right": "66DDFF", "a": GREEN},
|
|
"videos": {"a": GREEN, "x": BLUE}}
|
|
# Each label's line, from the button out to the text, as points in drawing
|
|
# coordinates, then the text's anchor and its ASS alignment.
|
|
CALLOUTS = {
|
|
"up": (((115, 68), (-30, 68)), (-38, 68), 6),
|
|
"left": (((88, 110), (-30, 110)), (-38, 110), 6),
|
|
"down": (((115, 152), (-30, 152)), (-38, 152), 6),
|
|
"right": (((158, 125), (158, 335)), (158, 345), 8),
|
|
"x": (((360, 127), (360, 335)), (345, 345), 7),
|
|
"b": (((437, 110), (550, 110)), (558, 110), 4),
|
|
"a": (((390, 157), (390, 175), (550, 175)), (558, 175), 4),
|
|
"lb": (((140, 4), (140, -40)), (170, -44), 3),
|
|
"rb": (((380, 4), (380, -40)), (350, -44), 1),
|
|
"start": (((292, 92), (292, -85)), (292, -90), 2),
|
|
}
|
|
GUIDE_SCALE = 0.8
|
|
|
|
|
|
def scaled(ox, oy, x, y):
|
|
return round(ox + x * GUIDE_SCALE), round(oy + y * GUIDE_SCALE)
|
|
|
|
|
|
def render_controller(ox, oy, lit):
|
|
"""An outline of the gamepad with the `lit` buttons bright."""
|
|
def point(x, y):
|
|
return "{} {}".format(*scaled(ox, oy, x, y))
|
|
|
|
def box(x, y, w, h, r):
|
|
left, top = scaled(ox, oy, x, y)
|
|
return rounded_path(left, top, round(w * GUIDE_SCALE), round(h * GUIDE_SCALE),
|
|
round(r * GUIDE_SCALE))
|
|
|
|
def dot(x, y, r):
|
|
return circle_path(*scaled(ox, oy, x, y), round(r * GUIDE_SCALE))
|
|
|
|
def label(x, y, text, size, color="000000"):
|
|
return ass_text(*scaled(ox, oy, x, y), text, round(size * GUIDE_SCALE), color,
|
|
align=5, border=0)
|
|
|
|
def alpha(*keys):
|
|
return "00" if lit.intersection(keys) else "B0"
|
|
|
|
body = (f"m {point(260, 30)} l {point(130, 30)} "
|
|
f"b {point(70, 30)} {point(40, 60)} {point(30, 110)} "
|
|
f"b {point(15, 180)} {point(0, 270)} {point(40, 290)} "
|
|
f"b {point(75, 305)} {point(110, 250)} {point(140, 215)} "
|
|
f"b {point(150, 205)} {point(165, 195)} {point(190, 195)} "
|
|
f"l {point(330, 195)} "
|
|
f"b {point(355, 195)} {point(370, 205)} {point(380, 215)} "
|
|
f"b {point(410, 250)} {point(445, 305)} {point(480, 290)} "
|
|
f"b {point(520, 270)} {point(505, 180)} {point(490, 110)} "
|
|
f"b {point(480, 60)} {point(450, 30)} {point(390, 30)} "
|
|
f"l {point(260, 30)}")
|
|
out = []
|
|
for key, x in (("lb", 85), ("rb", 325)):
|
|
out.append(ass_shape(box(x, 4, 110, 34, 12), PALE, alpha(key)))
|
|
out.append(ass_shape(body, "3A3A3A", outline="909090"))
|
|
for text, x in (("LB", 140), ("RB", 380)):
|
|
out.append(label(x, 17, text, 22))
|
|
# D-pad, one shape for each direction
|
|
arms = (("up", 115, 68, 30, 27, "▲", 130, 81), ("down", 115, 125, 30, 27, "▼", 130, 139),
|
|
("left", 88, 95, 27, 30, "◀", 101, 110), ("right", 145, 95, 27, 30, "▶", 159, 110))
|
|
out.append(ass_shape(box(115, 95, 30, 30, 2), "606060"))
|
|
for key, x, y, w, h, glyph, gx, gy in arms:
|
|
out.append(ass_shape(box(x, y, w, h, 3), PALE, alpha(key)))
|
|
out.append(label(gx, gy, glyph, 18))
|
|
# Sticks
|
|
for x in (190, 330):
|
|
out.append(ass_shape(dot(x, 160, 28), PALE, "B0"))
|
|
out.append(ass_shape(dot(x, 160, 18), "606060"))
|
|
# Back and Start
|
|
out.append(ass_shape(box(208, 92, 40, 16, 7), PALE, "B0"))
|
|
out.append(ass_shape(box(272, 92, 40, 16, 7), PALE, alpha("start")))
|
|
out.append(label(228, 78, "BACK", 15, "C0C0C0"))
|
|
for key, text, color, x, y in FACE_BUTTONS:
|
|
out.append(ass_shape(dot(x, y, 17), color, alpha(key)))
|
|
out.append(label(x, y, text, 22))
|
|
return out
|
|
|
|
|
|
def render_callout(ox, oy, key, action, color=None):
|
|
points, anchor, align = CALLOUTS[key]
|
|
thickness = 4 if color else 2
|
|
out = []
|
|
for start, end in zip(points, points[1:]):
|
|
(x1, y1), (x2, y2) = scaled(ox, oy, *start), scaled(ox, oy, *end)
|
|
left, top = min(x1, x2), min(y1, y2)
|
|
out.append(ass_rect(left, top, max(abs(x2 - x1), thickness),
|
|
max(abs(y2 - y1), thickness) + thickness * (x1 == x2),
|
|
color or "FFFFFF", "00"))
|
|
out.append(ass_text(*scaled(ox, oy, *anchor), action, 36 if color else 28,
|
|
color or "FFFFFF", align=align, bold=bool(color)))
|
|
return out
|
|
|
|
|
|
def render_guide(screen):
|
|
"""The controller, with what each working button does written beside it."""
|
|
guide = GUIDES[screen]
|
|
x, y, w, h = 1000, 45, 890, 460
|
|
ox, oy = x + 190, y + 115
|
|
out = [ass_rect(x, y, w, h, "000000", "28")]
|
|
out += render_controller(ox, oy, set(guide))
|
|
highlighted = HIGHLIGHTED.get(screen, {})
|
|
for key, action in guide.items():
|
|
out += render_callout(ox, oy, key, action, highlighted.get(key))
|
|
return out
|
|
|
|
|
|
def render_folder_buttons(right, mid):
|
|
"""On the selected folder's row: which button plays it and which opens it."""
|
|
return [
|
|
ass_shape(circle_path(right - 262, mid, 22), GREEN),
|
|
ass_text(right - 262, mid, "A", 28, "000000", align=5, border=0),
|
|
ass_text(right - 232, mid, "Play", 32, "000000", border=0, bold=True),
|
|
ass_shape(rounded_path(right - 132, mid - 22, 44, 44, 8), "202020"),
|
|
ass_text(right - 110, mid, "▶", 24, "FFFFFF", align=5, border=0),
|
|
ass_text(right - 80, mid, "Open", 32, "000000", border=0, bold=True),
|
|
]
|
|
|
|
|
|
def render_video_buttons(right, mid, off):
|
|
"""On the selected video's row: which buttons play it and turn it on or off."""
|
|
out = [
|
|
ass_shape(circle_path(right - 170, mid, 20), BLUE),
|
|
ass_text(right - 170, mid, "X", 26, "000000", align=5, border=0),
|
|
ass_text(right - 140, mid, "Turn on" if off else "Turn off", 30, "000000",
|
|
border=0, bold=True),
|
|
]
|
|
if not off:
|
|
out.append(ass_shape(circle_path(right - 318, mid, 20), GREEN))
|
|
out.append(ass_text(right - 318, mid, "A", 26, "000000", align=5, border=0))
|
|
out.append(ass_text(right - 290, mid, "Play", 30, "000000", border=0, bold=True))
|
|
return out
|
|
|
|
|
|
def full_name_size(text):
|
|
"""Largest small-print size that keeps the whole name on one row."""
|
|
return max(14, min(20, 1560 // max(len(text), 1)))
|
|
|
|
|
|
def render_menu(menu, playing):
|
|
"""Build the ASS overlay (1920x1080 space), one event per line.
|
|
|
|
`playing` is the folder name in the folder list, the file path in a folder.
|
|
"""
|
|
x, y, w = 30, 45, 960
|
|
row_h = 80
|
|
rows = min(MENU_ROWS, max(len(menu.items), 1))
|
|
h = 150 + rows * row_h + 30
|
|
in_folder = menu.folder is not None
|
|
if in_folder:
|
|
heading = clip(menu.folder, 22)
|
|
else:
|
|
heading = "Choose a video folder" if menu.folders else "No videos found"
|
|
out = [
|
|
ass_rect(x, y, w, h, "000000", "28"),
|
|
ass_text(x + 50, y + 70, heading, 56, "66DDFF"),
|
|
]
|
|
if len(menu.items) > rows:
|
|
out.append(ass_text(x + w - 60, y + 70, f"{menu.index + 1} of {len(menu.items)}",
|
|
34, "CCCCCC", align=6))
|
|
top = max(0, min(menu.index - rows // 2, len(menu.items) - rows))
|
|
row_y = y + 150
|
|
names = [video_title(v) for v in menu.items] if in_folder else []
|
|
titles, narrow_titles = short_titles(names, 42), short_titles(names, 27)
|
|
for i, item in enumerate(menu.items[top:top + rows], start=top):
|
|
selected = i == menu.index
|
|
off = item in menu.off
|
|
now_playing = item == playing
|
|
if selected:
|
|
out.append(ass_rect(x + 30, row_y, w - 60, row_h - 8, "66DDFF", "00"))
|
|
elif now_playing:
|
|
out.append(ass_rect(x + 30, row_y, w - 60, row_h - 8, PLAYING_GREEN, "20"))
|
|
if now_playing: # also shows through when the selection is on this row
|
|
out.append(ass_rect(x + 30, row_y, 16, row_h - 8, PLAYING_GREEN, "00"))
|
|
color, border = ("000000", 0) if selected else ("FFFFFF", 2)
|
|
if off and not selected:
|
|
color = "888888"
|
|
full_name = None
|
|
if item == SETTINGS_ITEM:
|
|
label, detail, size = "⚙ Settings", "", 40
|
|
elif in_folder:
|
|
label, detail, size = titles[i], "OFF" if off else "ON", 32
|
|
if now_playing:
|
|
detail = "PLAYING"
|
|
if selected: # the buttons take the place of the detail
|
|
label, detail = narrow_titles[i], ""
|
|
full_name = names[i] if label != names[i] else None
|
|
elif selected:
|
|
label, detail, size = clip(item, 22), "", 40
|
|
else:
|
|
label, detail, size = clip(item, 26), f"{menu.folders[item]} ▶", 40
|
|
mid = row_y + (row_h - 8) // 2
|
|
if full_name: # room for the whole name in small print underneath
|
|
mid -= 11
|
|
out.append(ass_text(x + 60, row_y + 57, full_name, full_name_size(full_name),
|
|
color, border=min(border, 1)))
|
|
out.append(ass_text(x + 60, mid, ("▶ " if now_playing else "") + label, size, color,
|
|
border=border))
|
|
out.append(ass_text(x + w - 60, mid, detail, 34, color, align=6, border=border))
|
|
if selected and in_folder:
|
|
out += render_video_buttons(x + w - 70, mid, off)
|
|
elif selected and item != SETTINGS_ITEM:
|
|
out += render_folder_buttons(x + w - 70, mid)
|
|
row_y += row_h
|
|
if in_folder:
|
|
out += render_guide("videos")
|
|
elif menu.items[menu.index] == SETTINGS_ITEM:
|
|
out += render_guide("settings_row")
|
|
else:
|
|
out += render_guide("folders")
|
|
return "\n".join(out)
|
|
|
|
|
|
def render_settings(window, values):
|
|
x, y, w = 30, 45, 960
|
|
row_h = 80
|
|
h = 150 + len(SETTINGS) * row_h + 30
|
|
out = [
|
|
ass_rect(x, y, w, h, "000000", "28"),
|
|
ass_text(x + 50, y + 70, "Play settings", 56, "66DDFF"),
|
|
]
|
|
row_y = y + 150
|
|
for i, (key, label, choices) in enumerate(SETTINGS):
|
|
selected = i == window.index
|
|
if selected:
|
|
out.append(ass_rect(x + 30, row_y, w - 60, row_h - 8, "66DDFF", "00"))
|
|
color, border = ("000000", 0) if selected else ("FFFFFF", 2)
|
|
text = dict(choices)[values[key]]
|
|
mid = row_y + (row_h - 8) // 2
|
|
out.append(ass_text(x + 60, mid, label, 36, color, border=border))
|
|
out.append(ass_text(x + w - 60, mid, f"◀ {text} ▶" if selected else text, 34,
|
|
color, align=6, border=border))
|
|
row_y += row_h
|
|
out += render_guide("settings")
|
|
return "\n".join(out)
|
|
|
|
|
|
def format_time(seconds):
|
|
minutes, secs = divmod(int(seconds), 60)
|
|
hours, minutes = divmod(minutes, 60)
|
|
return f"{hours}:{minutes:02}:{secs:02}" if hours else f"{minutes}:{secs:02}"
|
|
|
|
|
|
def render_starting():
|
|
"""Matches the boot splash, so the hand-over to mpv can't be seen."""
|
|
return ass_text(960, 795, "Starting", 38, align=5, border=0)
|
|
|
|
|
|
def render_notice(text):
|
|
return ass_text(960, 795, text, 38, "4D4DFF", align=5, bold=True)
|
|
|
|
|
|
# ---------------------------------------------------------------- splash ----
|
|
|
|
def plymouth(*args):
|
|
"""Talk to the boot splash. It only accepts root, and may not be running."""
|
|
try:
|
|
return subprocess.run(["sudo", "-n", "/usr/bin/plymouth", *args], check=False,
|
|
stdin=subprocess.DEVNULL, capture_output=True,
|
|
timeout=5).returncode == 0
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return False
|
|
|
|
|
|
def splash_active():
|
|
return plymouth("--ping")
|
|
|
|
|
|
def splash_message(text):
|
|
log(f"splash: {text}")
|
|
plymouth("display-message", f"--text={text}")
|
|
|
|
|
|
def splash_release():
|
|
"""Let mpv have the display while the logo stays on screen.
|
|
|
|
Quitting instead would hand the screen back to the text console until mpv opens.
|
|
"""
|
|
if splash_active():
|
|
plymouth("deactivate")
|
|
|
|
|
|
def splash_finish():
|
|
if splash_active():
|
|
plymouth("quit", "--retain-splash")
|
|
plymouth("--wait")
|
|
|
|
|
|
def splash_error(text):
|
|
"""Bring the splash back: with mpv failing, it is the only way to show a message."""
|
|
if splash_active():
|
|
plymouth("reactivate") # released for an mpv that then failed
|
|
else:
|
|
try:
|
|
subprocess.run(["sudo", "-n", "/usr/sbin/plymouthd", "--mode=boot",
|
|
"--kernel-command-line=quiet splash",
|
|
"--pid-file=/run/plymouth/pid"], check=False,
|
|
stdin=subprocess.DEVNULL, capture_output=True, timeout=5)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
pass
|
|
plymouth("show-splash")
|
|
splash_message(f"ERROR: {text}")
|
|
|
|
|
|
# --------------------------------------------------------------- display ----
|
|
|
|
def is_raspberry_pi():
|
|
try:
|
|
return "Raspberry Pi" in Path("/proc/device-tree/model").read_text(errors="replace")
|
|
except OSError:
|
|
return False
|
|
|
|
|
|
def video_options():
|
|
"""How mpv decodes and shows video on this machine."""
|
|
if is_raspberry_pi():
|
|
# Hardware decoding, with frames sent straight to a display plane.
|
|
# Going through the GPU instead drops 10+ frames a second at 1080p60. The
|
|
# OSD plane sits above the video so the menu stays visible. Formats with
|
|
# no hardware decoder (e.g. VP9) fall back to software.
|
|
return ["--hwdec=v4l2m2m,drm", "--profile=fast",
|
|
"--gpu-hwdec-interop=drmprime-overlay",
|
|
"--drm-draw-plane=overlay", "--drm-drmprime-video-plane=primary"]
|
|
return ["--hwdec=auto-safe"] # x86: let mpv find VAAPI or similar
|
|
|
|
|
|
def connectors(sysfs="/sys/class/drm"):
|
|
"""{connector name: True if a real screen answered} for each display port."""
|
|
found = {}
|
|
for path in sorted(glob.glob(f"{sysfs}/card*-*")):
|
|
name = re.sub(r"^card\d+-", "", Path(path).name)
|
|
if name.startswith("Writeback"):
|
|
continue
|
|
try:
|
|
found[name] = bool((Path(path) / "edid").read_bytes())
|
|
except OSError:
|
|
found[name] = False
|
|
return found
|
|
|
|
|
|
def choose_connector(display_file, sysfs="/sys/class/drm"):
|
|
"""The HDMI port to use.
|
|
|
|
Both ports are forced on at boot so a TV that is off or asleep can't stop the
|
|
player, which means both claim to be connected. Only a real screen answers
|
|
with its details, so trust that, and otherwise use the last port that did.
|
|
"""
|
|
ports = connectors(sysfs)
|
|
live = [name for name, has_screen in ports.items() if has_screen]
|
|
if live:
|
|
if load_last_folder(display_file) != live[0]:
|
|
save_last_folder(display_file, live[0])
|
|
return live[0]
|
|
remembered = load_last_folder(display_file)
|
|
if remembered in ports:
|
|
return remembered
|
|
return next(reversed(ports), None)
|
|
|
|
|
|
# ------------------------------------------------------------------- mpv ----
|
|
|
|
class MpvGone(Exception):
|
|
"""mpv exited or stopped answering."""
|
|
|
|
|
|
def hdmi_audio_device(connector):
|
|
"""Send sound to the same HDMI port as the picture."""
|
|
if connector and connector.startswith("HDMI-A-"):
|
|
index = int(connector.rsplit("-", 1)[1]) - 1
|
|
if Path(f"/proc/asound/vc4hdmi{index}").exists():
|
|
return f"alsa/hdmi:CARD=vc4hdmi{index},DEV=0"
|
|
return "auto"
|
|
|
|
|
|
class Mpv:
|
|
def __init__(self, connector=None):
|
|
self.dir = tempfile.mkdtemp(prefix="enrichment-player-")
|
|
self.socket_path = os.path.join(self.dir, "mpv.sock")
|
|
self.request_id = 0
|
|
self.sock = None
|
|
self.reader = None
|
|
self.process = subprocess.Popen([
|
|
"mpv",
|
|
"--no-config", "--load-scripts=no", "--load-stats-overlay=no",
|
|
"--load-osd-console=no", "--load-auto-profiles=no", "--osc=no",
|
|
"--no-input-default-bindings", "--no-input-terminal",
|
|
"--input-vo-keyboard=no", "--no-input-cursor",
|
|
"--quiet", "--msg-level=all=warn",
|
|
f"--input-ipc-server={self.socket_path}",
|
|
# Draw directly to the display, keep it alive between files, and
|
|
# stay up with an empty playlist so messages can still be shown.
|
|
"--vo=gpu", "--gpu-context=drm", "--gpu-api=opengl",
|
|
*([f"--drm-connector={connector}"] if connector else []),
|
|
"--idle=yes", "--force-window=immediate", "--fullscreen",
|
|
*video_options(),
|
|
"--loop-playlist=inf", "--sid=no", "--framedrop=vo",
|
|
f"--audio-device={hdmi_audio_device(connector)}", "--audio-fallback-to-null=yes",
|
|
"--osd-font=DejaVu Sans", "--osd-bar=no", "--osd-on-seek=no",
|
|
], stdin=subprocess.DEVNULL)
|
|
self._connect()
|
|
|
|
def _connect(self):
|
|
deadline = time.monotonic() + 15
|
|
while True:
|
|
if self.process.poll() is not None:
|
|
raise MpvGone(f"mpv exited with code {self.process.returncode}")
|
|
try:
|
|
sock = socket.socket(socket.AF_UNIX)
|
|
sock.settimeout(5)
|
|
sock.connect(self.socket_path)
|
|
break
|
|
except OSError:
|
|
sock.close()
|
|
if time.monotonic() > deadline:
|
|
raise MpvGone("mpv socket never appeared")
|
|
time.sleep(0.1)
|
|
self.sock = sock
|
|
self.reader = sock.makefile("r", encoding="utf-8", errors="replace")
|
|
self.command("disable_event", "all")
|
|
|
|
def _send(self, command):
|
|
self.request_id += 1
|
|
message = {"command": command, "request_id": self.request_id}
|
|
try:
|
|
self.sock.sendall((json.dumps(message) + "\n").encode())
|
|
while True:
|
|
line = self.reader.readline()
|
|
if not line:
|
|
raise MpvGone("mpv closed its socket")
|
|
reply = json.loads(line)
|
|
if reply.get("request_id") == self.request_id:
|
|
return reply
|
|
except (OSError, ValueError) as err:
|
|
raise MpvGone(f"mpv stopped answering: {err}") from err
|
|
|
|
def command(self, *args):
|
|
return self._send(list(args))
|
|
|
|
def get(self, name):
|
|
return self._send(["get_property", name]).get("data")
|
|
|
|
def logo(self, show):
|
|
"""Show the logo above any notice, or remove it."""
|
|
if not show:
|
|
self.command("overlay-remove", 1)
|
|
elif LOGO_FILE.exists():
|
|
self.command("overlay-add", 1, (1920 - LOGO_WIDTH) // 2, LOGO_Y, str(LOGO_FILE), 0,
|
|
"bgra", LOGO_WIDTH, LOGO_HEIGHT, LOGO_WIDTH * 4)
|
|
|
|
def overlay(self, ass):
|
|
"""Show ASS text over the video, or clear it with None."""
|
|
self._send({"name": "osd-overlay", "id": 1, "res_x": 1920, "res_y": 1080,
|
|
"format": "ass-events" if ass else "none", "data": ass or ""})
|
|
|
|
def play(self, order):
|
|
self.command("loadfile", order[0], "replace")
|
|
for path in order[1:]:
|
|
self.command("loadfile", path, "append")
|
|
|
|
def stop(self):
|
|
if self.sock:
|
|
self.sock.close()
|
|
if self.process.poll() is None:
|
|
self.process.terminate()
|
|
try:
|
|
self.process.wait(2)
|
|
except subprocess.TimeoutExpired:
|
|
self.process.kill()
|
|
self.process.wait()
|
|
shutil.rmtree(self.dir, ignore_errors=True)
|
|
|
|
|
|
# ---------------------------------------------------------------- player ----
|
|
|
|
class Player:
|
|
def __init__(self, root, state_file):
|
|
self.root = Path(root)
|
|
self.state_file = state_file
|
|
self.disabled_file = Path(state_file).with_name("disabled.json")
|
|
self.disabled = load_disabled(self.disabled_file)
|
|
self.display_file = Path(state_file).with_name("display")
|
|
self.last_video_file = Path(state_file).with_name("last_video")
|
|
self.connector = None
|
|
self.settings_file = Path(state_file).with_name("settings.json")
|
|
self.settings = load_settings(self.settings_file)
|
|
self.window = SettingsWindow()
|
|
self.durations = {} # path -> seconds
|
|
self.playing = None # path of the current video
|
|
self.video_started = 0.0
|
|
self.reshuffled = False
|
|
self.folder = None # kept across mpv restarts
|
|
self.inputs = Inputs()
|
|
self.menu = Menu()
|
|
self.mpv = None
|
|
self.files = []
|
|
self.loaded_at = 0.0
|
|
self.progress = None
|
|
self.progress_at = 0.0
|
|
self.notice = None
|
|
|
|
def _set_notice(self, text):
|
|
if text != self.notice:
|
|
self.notice = text
|
|
self._draw()
|
|
|
|
def _draw(self):
|
|
self.mpv.logo(bool(self.notice) and not (self.window.open or self.menu.open))
|
|
if self.window.open:
|
|
self.mpv.overlay(render_settings(self.window, self.settings))
|
|
elif self.menu.open:
|
|
playing = self.mpv.get("path") if self.menu.folder else self.folder
|
|
self.mpv.overlay(render_menu(self.menu, playing))
|
|
else:
|
|
self.mpv.overlay(render_notice(self.notice) if self.notice else None)
|
|
|
|
def _load(self, folder, start_at=None):
|
|
files = enabled_videos(self.root, folder, self.disabled)
|
|
if not files:
|
|
return False
|
|
log(f"playing {folder!r} ({len(files)} videos)")
|
|
self.folder, self.files = folder, files
|
|
self.loaded_at = time.monotonic()
|
|
self.progress_at = self.loaded_at
|
|
self.playing = None
|
|
order = self._play_order(start_at or files[0])
|
|
self._prepare_start(order[0])
|
|
self.mpv.play(order)
|
|
self._set_notice(None)
|
|
return True
|
|
|
|
def _play_order(self, first):
|
|
"""The folder's order, or a shuffle of it, beginning with `first`."""
|
|
start = self.files.index(first) if first in self.files else 0
|
|
order = self.files[start:] + self.files[:start]
|
|
if self.settings["shuffle"]:
|
|
rest = order[1:]
|
|
random.shuffle(rest)
|
|
order = order[:1] + rest
|
|
return order
|
|
|
|
def _arrange(self, order):
|
|
"""Reorder the playlist without interrupting the current video."""
|
|
current = [entry["filename"] for entry in self.mpv.get("playlist") or []]
|
|
for target, path in enumerate(order):
|
|
if path in current and current.index(path) != target:
|
|
index = current.index(path)
|
|
self.mpv.command("playlist-move", index, target)
|
|
current.insert(target, current.pop(index))
|
|
|
|
def _duration(self, path):
|
|
if path not in self.durations:
|
|
duration = video_duration(path)
|
|
if duration is None:
|
|
return None # not remembered: it may still be being copied
|
|
self.durations[path] = duration
|
|
return self.durations[path]
|
|
|
|
def _random_spot(self, path):
|
|
"""Where to start `path`, as a percentage, or None for the beginning.
|
|
|
|
With a time limit shorter than the video, anywhere that leaves the whole
|
|
limit to play: 1 hour of a 9 hour video starts between 0 and 8 hours in.
|
|
"""
|
|
limit = self.settings["max_minutes"] * 60
|
|
duration = self._duration(path) if limit else None
|
|
if limit and duration and duration > limit:
|
|
return random.uniform(0, duration - limit) / duration * 100
|
|
return random.uniform(2, 95) if self.settings["random_start"] else None
|
|
|
|
def _prepare_start(self, path):
|
|
"""Tell mpv where `path`, the next video to load, should begin."""
|
|
spot = self._random_spot(path) if path else None
|
|
self.mpv.command("set_property", "start", "none" if spot is None else f"{spot:.4f}%")
|
|
|
|
def _upcoming(self):
|
|
"""The video that will play after the current one."""
|
|
entries = self.mpv.get("playlist") or []
|
|
position = self.mpv.get("playlist-pos")
|
|
if not entries or position is None:
|
|
return None
|
|
return entries[(position + 1) % len(entries)]["filename"]
|
|
|
|
def _apply_setting(self, key):
|
|
if key == "volume":
|
|
self.mpv.command("set_property", "volume", self.settings["volume"])
|
|
elif key == "shuffle" and self.files:
|
|
playing = self.mpv.get("path")
|
|
if playing in self.files:
|
|
self._arrange(self._play_order(playing))
|
|
if key != "volume":
|
|
self._prepare_start(self._upcoming())
|
|
|
|
def _next_or_keep_going(self):
|
|
"""The max time ran out. With one video, only moving elsewhere in it helps."""
|
|
log(f"max time reached, moving on from {self.playing}")
|
|
if len(self.files) > 1:
|
|
self.mpv.command("playlist-next")
|
|
return
|
|
spot = self._random_spot(self.playing)
|
|
if spot is not None:
|
|
self.mpv.command("seek", spot, "absolute-percent+keyframes")
|
|
|
|
def _pick_and_load(self):
|
|
folder = choose_folder(self.root, self.state_file)
|
|
first = None
|
|
if folder:
|
|
first = random_video(enabled_videos(self.root, folder, self.disabled),
|
|
load_last_folder(self.last_video_file))
|
|
if folder is None or not self._load(folder, start_at=first):
|
|
self.folder, self.files = None, []
|
|
self.mpv.command("stop")
|
|
self._set_notice(f"No videos found in {self.root}")
|
|
|
|
def _toast(self, text):
|
|
self.mpv.command("show-text", text, 3000)
|
|
|
|
def _next_video(self):
|
|
count = len(self.files)
|
|
if count < 2:
|
|
# Skipping would just restart the only video from the beginning.
|
|
self._toast("Only 1 video to play in this folder")
|
|
return
|
|
playing = self.mpv.get("path")
|
|
position = self.files.index(playing) if playing in self.files else -1
|
|
self.mpv.command("playlist-next")
|
|
self._toast(f"Video {(position + 1) % count + 1} of {count}")
|
|
|
|
def _jump_to_random_spot(self):
|
|
duration = self.mpv.get("duration")
|
|
if not duration:
|
|
return # nothing is playing
|
|
percent = random.uniform(2, 95)
|
|
self.mpv.command("seek", percent, "absolute-percent+keyframes")
|
|
spot = format_time(duration * percent / 100)
|
|
self._toast(f"Jumped to {spot} of {format_time(duration)}")
|
|
|
|
def _folder_details(self):
|
|
details = {}
|
|
for name, total in list_folders(self.root).items():
|
|
on = len(enabled_videos(self.root, name, self.disabled))
|
|
details[name] = (f"{on} of {total} on" if on < total
|
|
else f"{total} video{'s' * (total != 1)}")
|
|
return details
|
|
|
|
def _open_folder(self, folder):
|
|
videos = list_videos(self.root / folder)
|
|
off = {str(self.root / folder / n) for n in self.disabled.get(folder, ())}
|
|
self.menu.enter(folder, videos, off, self.mpv.get("path"))
|
|
|
|
def _playlist_index(self, path):
|
|
for index, entry in enumerate(self.mpv.get("playlist") or []):
|
|
if entry.get("filename") == path:
|
|
return index
|
|
return None
|
|
|
|
def _toggle_video(self, path):
|
|
folder, name = self.menu.folder, Path(path).name
|
|
off = self.disabled.setdefault(folder, set())
|
|
playing_here = folder == self.folder
|
|
if name in off:
|
|
off.discard(name)
|
|
save_disabled(self.disabled_file, self.disabled)
|
|
self.menu.off.discard(path)
|
|
if playing_here and path not in self.files:
|
|
self.files = enabled_videos(self.root, folder, self.disabled)
|
|
if self.settings["shuffle"]:
|
|
# Anywhere still to come, so it plays this pass and only once.
|
|
position = self.mpv.get("playlist-pos") or 0
|
|
count = len(self.mpv.get("playlist") or [])
|
|
index = random.randint(position + 1, count)
|
|
else:
|
|
# Back into its place, before the video that follows it.
|
|
after = self.files[(self.files.index(path) + 1) % len(self.files)]
|
|
index = self._playlist_index(after) or 0
|
|
self.mpv.command("loadfile", path, "insert-at", index)
|
|
self._prepare_start(self._upcoming())
|
|
return
|
|
if len(enabled_videos(self.root, folder, self.disabled)) <= 1: # keep one
|
|
self._toast("At least one video must stay on")
|
|
return
|
|
off.add(name)
|
|
save_disabled(self.disabled_file, self.disabled)
|
|
self.menu.off.add(path)
|
|
if playing_here:
|
|
self.files = enabled_videos(self.root, folder, self.disabled)
|
|
index = self._playlist_index(path)
|
|
if index is not None:
|
|
self.mpv.command("playlist-remove", index) # moves on if it was playing
|
|
self._prepare_start(self._upcoming())
|
|
|
|
def _pick_folder(self, folder):
|
|
if folder != self.folder and self._load(folder):
|
|
save_last_folder(self.state_file, folder)
|
|
self._toast(f"Now playing: {folder}")
|
|
|
|
def _pick_video(self, path):
|
|
folder = self.menu.folder
|
|
if self._load(folder, start_at=path):
|
|
save_last_folder(self.state_file, folder)
|
|
self._toast(f"Now playing: {clip(video_title(path), 60)}")
|
|
|
|
def _open_settings(self, now):
|
|
came_from_menu = self.menu.open
|
|
self.menu.close()
|
|
self.window.show(now, from_menu=came_from_menu)
|
|
|
|
def _close_settings(self, now):
|
|
self.window.close()
|
|
if self.window.from_menu:
|
|
self.menu.show(self._folder_details(), self.folder, now)
|
|
self.menu.index = len(self.menu.items) - 1 # back on the Settings row
|
|
|
|
def _handle_menu(self, action, now):
|
|
what, item = self.menu.handle(action, now) or (None, None)
|
|
if what == "settings":
|
|
self._open_settings(now)
|
|
elif what == "open":
|
|
self._open_folder(item)
|
|
elif what == "play_folder":
|
|
self._pick_folder(item)
|
|
elif what == "play_video":
|
|
self._pick_video(item)
|
|
elif what == "toggle":
|
|
self._toggle_video(item)
|
|
elif what == "is_off":
|
|
self._toast("This video is off. Press X to turn it on")
|
|
|
|
def _handle(self, actions, now):
|
|
for action in actions:
|
|
log(f"control: {action}")
|
|
if not self.menu.open and not self.window.open:
|
|
# Nothing but opening a window works until one is open, so a stray
|
|
# press can't change what the animals are watching.
|
|
if action == "settings":
|
|
self.window.show(now)
|
|
elif action not in ("left", "right"):
|
|
self.menu.show(self._folder_details(), self.folder, now)
|
|
else:
|
|
continue
|
|
elif action in ("next", "jump"):
|
|
self.menu.extend(now)
|
|
self.window.extend(now)
|
|
if action == "next":
|
|
self._next_video()
|
|
else:
|
|
self._jump_to_random_spot()
|
|
elif action == "settings":
|
|
if self.window.open:
|
|
self._close_settings(now)
|
|
else:
|
|
self._open_settings(now)
|
|
elif self.window.open and action == "cancel":
|
|
self._close_settings(now)
|
|
elif self.window.open:
|
|
key = self.window.handle(action, self.settings, now)
|
|
if key:
|
|
save_settings(self.settings_file, self.settings)
|
|
self._apply_setting(key)
|
|
else:
|
|
self._handle_menu(action, now)
|
|
self._draw()
|
|
if self.menu.open and now >= self.menu.closes_at:
|
|
self.menu.close()
|
|
self._draw()
|
|
if self.window.open and now >= self.window.closes_at:
|
|
self.window.close()
|
|
self._draw()
|
|
|
|
def _check_health(self, now):
|
|
if choose_connector(self.display_file) != self.connector:
|
|
raise MpvGone("the screen moved to the other HDMI port")
|
|
|
|
if self.folder is None:
|
|
if now - self.loaded_at >= RESCAN_INTERVAL:
|
|
self.loaded_at = now
|
|
self._pick_and_load()
|
|
return
|
|
|
|
if self.mpv.get("idle-active"):
|
|
# mpv gives up looping when every file in the playlist fails.
|
|
if now - self.loaded_at >= RETRY_INTERVAL:
|
|
files = enabled_videos(self.root, self.folder, self.disabled)
|
|
if files:
|
|
self._load(self.folder)
|
|
self._set_notice(f"Cannot play the videos in {self.folder}")
|
|
else:
|
|
self._pick_and_load()
|
|
return
|
|
|
|
position, elapsed = self.mpv.get("playlist-pos"), self.mpv.get("time-pos")
|
|
path = self.mpv.get("path")
|
|
changed = path != self.playing
|
|
if changed:
|
|
self.playing = path
|
|
self.video_started = now
|
|
if path:
|
|
save_last_folder(self.last_video_file, Path(path).name)
|
|
self._prepare_start(self._upcoming())
|
|
if self.menu.open:
|
|
self._draw() # keep the playing highlight on the right row
|
|
|
|
limit = self.settings["max_minutes"] * 60
|
|
if limit and now - self.video_started >= limit:
|
|
self.video_started = now
|
|
self._next_or_keep_going()
|
|
|
|
# Shuffle: as the last video of a pass plays, draw a new order for the next
|
|
# pass. It stays last, so it can't come straight back round.
|
|
last = len(self.files) - 1
|
|
if position is not None and position < last:
|
|
self.reshuffled = False
|
|
elif self.settings["shuffle"] and last > 1 and position == last and not self.reshuffled:
|
|
self.reshuffled = True
|
|
others = [f for f in self.files if f != path]
|
|
random.shuffle(others)
|
|
self._arrange(others + [path])
|
|
self._prepare_start(self._upcoming())
|
|
|
|
# Pick up added or removed files as each pass through the folder begins.
|
|
if position == 0 and (changed or (elapsed is not None and elapsed < 2)):
|
|
files = enabled_videos(self.root, self.folder, self.disabled)
|
|
if not files:
|
|
self._pick_and_load()
|
|
elif files != self.files:
|
|
self._load(self.folder)
|
|
|
|
if (position, elapsed) != self.progress:
|
|
self.progress = (position, elapsed)
|
|
self.progress_at = now
|
|
elif now - self.progress_at >= STALL_LIMIT:
|
|
raise MpvGone(f"playback frozen for {STALL_LIMIT:.0f}s")
|
|
|
|
def _announce_start(self):
|
|
"""Report on the boot splash, then hand the display over."""
|
|
if not splash_active():
|
|
return
|
|
splash_message("Starting: finding videos")
|
|
folder = choose_folder(self.root, self.state_file)
|
|
if folder:
|
|
splash_message(f"Starting: opening {folder}")
|
|
self._warm_up(folder)
|
|
else:
|
|
splash_message(f"ERROR: No videos found in {self.root}")
|
|
time.sleep(5)
|
|
|
|
def _warm_up(self, folder):
|
|
"""Run mpv once behind the logo.
|
|
|
|
On a cold boot nothing is in memory, so mpv takes seconds to load, and the
|
|
real one blanks the screen as soon as it opens the display.
|
|
"""
|
|
videos = enabled_videos(self.root, folder, self.disabled)
|
|
try:
|
|
subprocess.run(["mpv", "--no-config", "--vo=null", "--ao=null", "--frames=1",
|
|
"--really-quiet", videos[0]], check=False, timeout=15,
|
|
stdin=subprocess.DEVNULL)
|
|
except (OSError, IndexError, subprocess.TimeoutExpired):
|
|
pass
|
|
|
|
def _wait_for_first_frame(self):
|
|
# time-pos appears before anything is on screen. Once it moves, video is showing.
|
|
deadline = time.monotonic() + FIRST_FRAME_TIMEOUT
|
|
start = None
|
|
while self.folder and time.monotonic() < deadline:
|
|
position = self.mpv.get("time-pos")
|
|
if start is None:
|
|
start = position
|
|
elif position is not None and position != start:
|
|
log("first video frame")
|
|
return
|
|
time.sleep(0.05)
|
|
|
|
def _session(self):
|
|
splash_release()
|
|
self.connector = choose_connector(self.display_file)
|
|
log(f"using display {self.connector}")
|
|
log("display handed to mpv")
|
|
self.mpv = Mpv(self.connector)
|
|
self.mpv.logo(True) # no black screen while the first video loads
|
|
self.mpv.overlay(render_starting())
|
|
self.notice = None
|
|
self.progress = None
|
|
self.mpv.command("set_property", "volume", self.settings["volume"])
|
|
if self.folder is None or not self._load(self.folder):
|
|
self._pick_and_load()
|
|
self._wait_for_first_frame()
|
|
splash_finish()
|
|
self._draw()
|
|
next_health = 0.0
|
|
while True:
|
|
actions = self.inputs.poll(0.1)
|
|
now = time.monotonic()
|
|
self._handle(actions, now)
|
|
if now >= next_health:
|
|
next_health = now + HEALTH_INTERVAL
|
|
if self.mpv.process.poll() is not None:
|
|
raise MpvGone(f"mpv exited with code {self.mpv.process.returncode}")
|
|
self._check_health(now)
|
|
|
|
def run(self):
|
|
"""Never returns: whatever goes wrong, start again."""
|
|
self._announce_start()
|
|
failed_starts = 0
|
|
while True:
|
|
started = time.monotonic()
|
|
problem = ""
|
|
try:
|
|
self._session()
|
|
except MpvGone as err:
|
|
problem = str(err)
|
|
log(f"restarting mpv: {err}")
|
|
except Exception as err: # a bug must not leave a blank screen
|
|
problem = repr(err)
|
|
log(f"restarting after error: {err!r}")
|
|
finally:
|
|
if self.mpv:
|
|
self.mpv.stop()
|
|
self.mpv = None
|
|
failed = time.monotonic() - started < FAILED_START_SECONDS
|
|
failed_starts = failed_starts + 1 if failed else 0
|
|
if failed_starts >= 2:
|
|
splash_error(f"Video player problem, retrying: {clip(problem, 60)}")
|
|
time.sleep(10)
|
|
else:
|
|
time.sleep(2)
|
|
|
|
|
|
def log(message):
|
|
print(message, flush=True)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
parser.add_argument("--videos", default="~/enrichment_videos",
|
|
help="folder containing one sub-folder per playlist")
|
|
parser.add_argument("--state", default="~/.local/state/enrichment_player/last_folder",
|
|
help="file remembering the last picked folder")
|
|
args = parser.parse_args()
|
|
|
|
def terminate(*_):
|
|
sys.exit(0)
|
|
signal.signal(signal.SIGTERM, terminate)
|
|
|
|
root = Path(args.videos).expanduser()
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
Player(root, Path(args.state).expanduser()).run()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|