Debian Codegraph @

TOOLS/umpv

raw
1 #!/usr/bin/env python3
2
3 """
4 This script emulates "unique application" functionality. When starting
5 playback with this script, it will try to reuse an already running instance of
6 mpv (but only if that was started with umpv). Other mpv instances (not started
7 by umpv) are ignored, and the script doesn't know about them.
8
9 This only takes filenames as arguments. Custom options can't be used; the script
10 interprets them as filenames. If mpv is already running, the files passed to
11 umpv are appended to mpv's internal playlist. If a file does not exist or is
12 otherwise not playable, mpv will skip the playlist entry when attempting to
13 play it (from the GUI perspective, it's silently ignored).
14
15 If mpv isn't running yet, this script will start mpv and let it control the
16 current terminal. It will not write output to stdout/stderr, because this
17 will typically just fill ~/.xsession-errors with garbage.
18
19 mpv will terminate if there are no more files to play, and running the umpv
20 script after that will start a new mpv instance.
21
22 Note: you can supply custom mpv path and options with the MPV environment
23 variable. The environment variable will be split on whitespace, and the
24 first item is used as path to mpv binary and the rest is passed as options
25 _if_ the script starts mpv. If mpv is not started by the script (i.e. mpv
26 is already running), this will be ignored.
27 """
28
29 import os
30 import shlex
31 import socket
32 import string
33 import subprocess
34 import sys
35 from collections.abc import Iterable
36 from typing import BinaryIO
37
38
39 def is_url(filename: str) -> bool:
40 parts = filename.split("://", 1)
41 if len(parts) < 2:
42 return False
43 # protocol prefix has no special characters => it's an URL
44 allowed_symbols = string.ascii_letters + string.digits + "_"
45 prefix = parts[0]
46 return all(c in allowed_symbols for c in prefix)
47
48 def get_socket_path() -> str:
49 if os.name == "nt":
50 return r"\\.\pipe\umpv"
51
52 base_dir = (
53 os.getenv("UMPV_SOCKET_DIR") or
54 os.getenv("XDG_RUNTIME_DIR") or
55 os.getenv("HOME") or
56 os.getenv("TMPDIR")
57 )
58
59 if not base_dir:
60 raise Exception("Could not determine a base directory for the socket. "
61 "Ensure that one of the following environment variables is set: "
62 "UMPV_SOCKET_DIR, XDG_RUNTIME_DIR, HOME or TMPDIR.")
63
64 return os.path.join(base_dir, ".umpv")
65
66 def send_files_to_mpv(conn: socket.socket | BinaryIO, files: Iterable[str]) -> None:
67 try:
68 send = conn.send if isinstance(conn, socket.socket) else conn.write
69 for f in files:
70 f = f.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
71 send(f'raw loadfile "{f}" append-play\n'.encode())
72 except Exception:
73 print("mpv is terminating or the connection was lost.", file=sys.stderr)
74 sys.exit(1)
75
76 def start_mpv(files: Iterable[str], socket_path: str) -> None:
77 mpv = "mpv" if os.name != "nt" else "mpv.exe"
78 mpv_command = shlex.split(os.getenv("MPV", mpv))
79 mpv_command.extend([
80 "--profile=builtin-pseudo-gui",
81 f"--input-ipc-server={socket_path}",
82 "--",
83 ])
84 mpv_command.extend(files)
85 subprocess.Popen(mpv_command, start_new_session=True)
86
87 def main() -> None:
88 files = (os.path.abspath(f) if not is_url(f) else f for f in sys.argv[1:])
89 socket_path = get_socket_path()
90
91 try:
92 if os.name == "nt":
93 with open(socket_path, "r+b", buffering=0) as pipe:
94 send_files_to_mpv(pipe, files)
95 else:
96 with socket.socket(socket.AF_UNIX) as sock:
97 sock.connect(socket_path)
98 send_files_to_mpv(sock, files)
99 except (FileNotFoundError, ConnectionRefusedError):
100 start_mpv(files, socket_path)
101
102 if __name__ == "__main__":
103 main()