anki/qt/aqt/mpv.py

606 lines
20 KiB
Python
Raw Normal View History

2017-09-30 07:41:32 +02:00
# ------------------------------------------------------------------------------
#
# mpv.py - Control mpv from Python using JSON IPC
#
# Copyright (c) 2015 Lars Gustäbel <lars@gustaebel.de>
#
# 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.
#
# ------------------------------------------------------------------------------
2020-08-31 04:04:14 +02:00
# pylint: disable=raise-missing-from
2019-12-20 10:19:03 +01:00
import inspect
2017-09-30 07:41:32 +02:00
import json
2019-12-20 10:19:03 +01:00
import os
2017-09-30 07:41:32 +02:00
import select
2019-12-20 10:19:03 +01:00
import socket
import subprocess
import sys
2017-09-30 07:41:32 +02:00
import tempfile
import threading
2019-12-20 10:19:03 +01:00
import time
2019-12-23 01:34:10 +01:00
from distutils.spawn import ( # pylint: disable=import-error,no-name-in-module
find_executable,
)
2019-12-20 10:19:03 +01:00
from queue import Empty, Full, Queue
from typing import Optional
2019-12-20 10:19:03 +01:00
from anki.utils import isWin
2017-09-30 07:41:32 +02:00
class MPVError(Exception):
pass
2019-12-23 01:34:10 +01:00
2017-09-30 07:41:32 +02:00
class MPVProcessError(MPVError):
pass
2019-12-23 01:34:10 +01:00
2017-09-30 07:41:32 +02:00
class MPVCommunicationError(MPVError):
pass
2019-12-23 01:34:10 +01:00
2017-09-30 07:41:32 +02:00
class MPVCommandError(MPVError):
pass
2019-12-23 01:34:10 +01:00
2017-09-30 07:41:32 +02:00
class MPVTimeoutError(MPVError):
pass
2019-12-23 01:34:10 +01:00
if isWin:
# pylint: disable=import-error
import pywintypes
import win32file # pytype: disable=import-error
import win32pipe
import winerror
2019-12-23 01:34:10 +01:00
2017-09-30 07:41:32 +02:00
class MPVBase:
"""Base class for communication with the mpv media player via unix socket
2020-08-31 05:29:28 +02:00
based JSON IPC.
2017-09-30 07:41:32 +02:00
"""
executable = find_executable("mpv")
popenEnv: Optional[dict[str, str]] = None
2017-09-30 07:41:32 +02:00
default_argv = [
"--idle",
"--no-terminal",
"--force-window=no",
"--ontop",
2017-10-05 06:35:58 +02:00
"--audio-display=no",
2018-04-08 18:18:34 +02:00
"--keep-open=no",
2020-07-23 13:28:47 +02:00
"--autoload-files=no",
"--gapless-audio=no",
2017-09-30 07:41:32 +02:00
]
def __init__(self, window_id=None, debug=False):
2017-09-30 07:41:32 +02:00
self.window_id = window_id
self.debug = debug
self._prepare_socket()
self._prepare_process()
self._start_process()
self._start_socket()
self._prepare_thread()
self._start_thread()
def __del__(self):
2017-09-30 07:41:32 +02:00
self._stop_thread()
self._stop_process()
self._stop_socket()
def _thread_id(self):
2017-09-30 07:41:32 +02:00
return threading.get_ident()
#
# Process
#
def _prepare_process(self):
2020-08-31 05:29:28 +02:00
"""Prepare the argument list for the mpv process."""
2017-09-30 07:41:32 +02:00
self.argv = [self.executable]
self.argv += self.default_argv
self.argv += [f"--input-ipc-server={self._sock_filename}"]
2017-09-30 07:41:32 +02:00
if self.window_id is not None:
self.argv += [f"--wid={str(self.window_id)}"]
2017-09-30 07:41:32 +02:00
def _start_process(self):
2020-08-31 05:29:28 +02:00
"""Start the mpv process."""
self._proc = subprocess.Popen(self.argv, env=self.popenEnv)
2017-09-30 07:41:32 +02:00
def _stop_process(self):
2020-08-31 05:29:28 +02:00
"""Stop the mpv process."""
2017-09-30 07:41:32 +02:00
if hasattr(self, "_proc"):
try:
self._proc.terminate()
2017-12-11 08:26:25 +01:00
self._proc.wait()
2017-09-30 07:41:32 +02:00
except ProcessLookupError:
pass
#
# Socket communication
#
def _prepare_socket(self):
2017-09-30 07:41:32 +02:00
"""Create a random socket filename which we pass to mpv with the
2020-08-31 05:29:28 +02:00
--input-unix-socket option.
2017-09-30 07:41:32 +02:00
"""
if isWin:
self._sock_filename = "ankimpv"
return
2017-09-30 07:41:32 +02:00
fd, self._sock_filename = tempfile.mkstemp(prefix="mpv.")
os.close(fd)
os.remove(self._sock_filename)
def _start_socket(self):
2017-09-30 07:41:32 +02:00
"""Wait for the mpv process to create the unix socket and finish
2020-08-31 05:29:28 +02:00
startup.
2017-09-30 07:41:32 +02:00
"""
start = time.time()
2019-12-23 01:34:10 +01:00
while self.is_running() and time.time() < start + 10:
2017-09-30 07:41:32 +02:00
time.sleep(0.1)
if isWin:
# named pipe
try:
2019-12-23 01:34:10 +01:00
self._sock = win32file.CreateFile(
r"\\.\pipe\ankimpv",
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
0,
None,
win32file.OPEN_EXISTING,
0,
None,
)
win32pipe.SetNamedPipeHandleState(
self._sock, 1, None, None # PIPE_NOWAIT
)
except pywintypes.error as err:
if err.args[0] == winerror.ERROR_FILE_NOT_FOUND:
pass
else:
break
else:
break
else:
# unix socket
try:
self._sock = socket.socket(socket.AF_UNIX)
2020-06-09 02:20:16 +02:00
self._sock.connect(self._sock_filename)
except (FileNotFoundError, ConnectionRefusedError):
2017-12-11 08:26:25 +01:00
self._sock.close()
continue
else:
break
2017-09-30 07:41:32 +02:00
else:
raise MPVProcessError("unable to start process")
def _stop_socket(self):
2020-08-31 05:29:28 +02:00
"""Clean up the socket."""
2017-12-11 08:26:25 +01:00
if hasattr(self, "_sock"):
self._sock.close()
2017-09-30 07:41:32 +02:00
if hasattr(self, "_sock_filename"):
try:
os.remove(self._sock_filename)
except OSError:
pass
def _prepare_thread(self):
2020-08-31 05:29:28 +02:00
"""Set up the queues for the communication threads."""
2017-09-30 07:41:32 +02:00
self._request_queue = Queue(1)
self._response_queues = {}
self._event_queue = Queue()
self._stop_event = threading.Event()
def _start_thread(self):
2020-08-31 05:29:28 +02:00
"""Start up the communication threads."""
2017-09-30 07:41:32 +02:00
self._thread = threading.Thread(target=self._reader)
self._thread.daemon = True
2017-09-30 07:41:32 +02:00
self._thread.start()
def _stop_thread(self):
2020-08-31 05:29:28 +02:00
"""Stop the communication threads."""
2017-09-30 07:41:32 +02:00
if hasattr(self, "_stop_event"):
self._stop_event.set()
if hasattr(self, "_thread"):
self._thread.join()
def _reader(self):
2017-09-30 07:41:32 +02:00
"""Read the incoming json messages from the unix socket that is
2020-08-31 05:29:28 +02:00
connected to the mpv process. Pass them on to the message handler.
2017-09-30 07:41:32 +02:00
"""
buf = b""
while not self._stop_event.is_set():
if isWin:
try:
(n, b) = win32file.ReadFile(self._sock, 4096)
buf += b
except pywintypes.error as err:
if err.args[0] == winerror.ERROR_NO_DATA:
time.sleep(0.1)
continue
elif err.args[0] == winerror.ERROR_BROKEN_PIPE:
return
else:
raise
else:
r, w, e = select.select([self._sock], [], [], 1)
if r:
2020-06-26 21:24:44 +02:00
try:
b = self._sock.recv(1024)
if not b:
break
buf += b
except ConnectionResetError:
return
2017-09-30 07:41:32 +02:00
newline = buf.find(b"\n")
while newline >= 0:
2019-12-23 01:34:10 +01:00
data = buf[: newline + 1]
buf = buf[newline + 1 :]
2017-09-30 07:41:32 +02:00
if self.debug:
sys.stdout.write(f"<<< {data.decode('utf8', 'replace')}")
2017-09-30 07:41:32 +02:00
message = self._parse_message(data)
self._handle_message(message)
newline = buf.find(b"\n")
#
# Message handling
#
def _compose_message(self, message):
2020-08-31 05:29:28 +02:00
"""Return a json representation from a message dictionary."""
2017-09-30 07:41:32 +02:00
# XXX may be strict is too strict ;-)
data = json.dumps(message)
2017-09-30 07:41:32 +02:00
return data.encode("utf8", "strict") + b"\n"
def _parse_message(self, data):
2020-08-31 05:29:28 +02:00
"""Return a message dictionary from a json representation."""
2017-09-30 07:41:32 +02:00
# XXX may be strict is too strict ;-)
data = data.decode("utf8", "strict")
return json.loads(data)
def _handle_message(self, message):
2017-09-30 07:41:32 +02:00
"""Handle different types of incoming messages, i.e. responses to
2020-08-31 05:29:28 +02:00
commands or asynchronous events.
2017-09-30 07:41:32 +02:00
"""
if "error" in message:
# This message is a reply to a request.
try:
thread_id = self._request_queue.get(timeout=1)
except Empty:
raise MPVCommunicationError("got a response without a pending request")
self._response_queues[thread_id].put(message)
elif "event" in message:
# This message is an asynchronous event.
self._event_queue.put(message)
else:
raise MPVCommunicationError(f"invalid message {message!r}")
2017-09-30 07:41:32 +02:00
def _send_message(self, message, timeout=None):
2017-09-30 07:41:32 +02:00
"""Send a message/command to the mpv process, message must be a
2020-08-31 05:29:28 +02:00
dictionary of the form {"command": ["arg1", "arg2", ...]}. Responses
from the mpv process must be collected using _get_response().
2017-09-30 07:41:32 +02:00
"""
data = self._compose_message(message)
if self.debug:
sys.stdout.write(f">>> {data.decode('utf8', 'replace')}")
2017-09-30 07:41:32 +02:00
# Request/response cycles are coordinated across different threads, so
# that they don't get mixed up. This makes it possible to use commands
# (e.g. fetch properties) from event callbacks that run in a different
# thread context.
thread_id = self._thread_id()
if thread_id not in self._response_queues:
# Prepare a response queue for the thread to wait on.
self._response_queues[thread_id] = Queue()
# Put the id of the current thread on the request queue. This id is
# later used to associate responses from the mpv process with this
# request.
try:
self._request_queue.put(thread_id, block=True, timeout=timeout)
except Full:
raise MPVTimeoutError("unable to put request")
# Write the message data to the socket.
if isWin:
win32file.WriteFile(self._sock, data)
else:
while data:
size = self._sock.send(data)
if size == 0:
raise MPVCommunicationError("broken sender socket")
data = data[size:]
2017-09-30 07:41:32 +02:00
def _get_response(self, timeout=None):
2017-09-30 07:41:32 +02:00
"""Collect the response message to a previous request. If there was an
2020-08-31 05:29:28 +02:00
error a MPVCommandError exception is raised, otherwise the command
specific data is returned.
2017-09-30 07:41:32 +02:00
"""
try:
2019-12-23 01:34:10 +01:00
message = self._response_queues[self._thread_id()].get(
block=True, timeout=timeout
)
2017-09-30 07:41:32 +02:00
except Empty:
raise MPVTimeoutError("unable to get response")
if message["error"] != "success":
raise MPVCommandError(message["error"])
else:
return message.get("data")
def _get_event(self, timeout=None):
2017-09-30 07:41:32 +02:00
"""Collect a single event message that has been received out-of-band
2020-08-31 05:29:28 +02:00
from the mpv process. If a timeout is specified and there have not
been any events during that period, None is returned.
2017-09-30 07:41:32 +02:00
"""
try:
return self._event_queue.get(block=timeout is not None, timeout=timeout)
except Empty:
return None
def _send_request(self, message, timeout=None, _retry=1):
2020-08-31 05:29:28 +02:00
"""Send a command to the mpv process and collect the result."""
self.ensure_running()
2017-09-30 07:41:32 +02:00
try:
self._send_message(message, timeout)
2017-09-30 07:41:32 +02:00
return self._get_response(timeout)
except MPVCommandError as e:
raise MPVCommandError(f"{message['command']!r}: {e}")
2020-06-26 21:24:44 +02:00
except Exception as e:
if _retry:
print("mpv timed out, restarting")
self._stop_process()
2019-12-23 01:34:10 +01:00
return self._send_request(message, timeout, _retry - 1)
else:
raise
2017-09-30 07:41:32 +02:00
def _register_callbacks(self):
"""Will be called after mpv restart to reinitialize callbacks
2020-08-31 05:29:28 +02:00
defined in MPV subclass
"""
2017-09-30 07:41:32 +02:00
#
# Public API
#
def is_running(self):
2020-08-31 05:29:28 +02:00
"""Return True if the mpv process is still active."""
2017-09-30 07:41:32 +02:00
return self._proc.poll() is None
def ensure_running(self):
if not self.is_running():
self._stop_thread()
self._stop_process()
self._stop_socket()
self._prepare_socket()
self._prepare_process()
self._start_process()
self._start_socket()
self._prepare_thread()
self._start_thread()
2020-06-26 21:24:44 +02:00
self._register_callbacks()
def close(self):
2020-08-31 05:29:28 +02:00
"""Shutdown the mpv process and our communication setup."""
2017-09-30 07:41:32 +02:00
if self.is_running():
self._send_request({"command": ["quit"]}, timeout=1)
self._stop_process()
self._stop_thread()
self._stop_socket()
2017-12-11 08:26:25 +01:00
self._stop_process()
2017-09-30 07:41:32 +02:00
class MPV(MPVBase):
"""Class for communication with the mpv media player via unix socket
2020-08-31 05:29:28 +02:00
based JSON IPC. It adds a few usable methods and a callback API.
2017-09-30 07:41:32 +02:00
2020-08-31 05:29:28 +02:00
To automatically register methods as event callbacks, subclass this
class and define specially named methods as follows:
2017-09-30 07:41:32 +02:00
2020-08-31 05:29:28 +02:00
def on_file_loaded(self):
# This is called for every 'file-loaded' event.
...
2017-09-30 07:41:32 +02:00
2020-08-31 05:29:28 +02:00
def on_property_time_pos(self, position):
# This is called whenever the 'time-pos' property is updated.
...
2017-09-30 07:41:32 +02:00
2020-08-31 05:29:28 +02:00
Please note that callbacks are executed inside a separate thread. The
MPV class itself is completely thread-safe. Requests from different
threads to the same MPV instance are synchronized.
2017-09-30 07:41:32 +02:00
"""
def __init__(self, *args, **kwargs):
self._callbacks_queue = Queue()
self._callbacks_initialized = False
2017-09-30 07:41:32 +02:00
super().__init__(*args, **kwargs)
2020-06-26 21:24:44 +02:00
self._register_callbacks()
def _register_callbacks(self):
2017-09-30 07:41:32 +02:00
self._callbacks = {}
self._property_serials = {}
self._new_serial = iter(range(sys.maxsize))
# Enumerate all methods and auto-register callbacks for
# events and property-changes.
for method_name, method in inspect.getmembers(self):
if not inspect.ismethod(method):
continue
# Bypass MPVError: no such event 'init'
if method_name == "on_init":
continue
2017-09-30 07:41:32 +02:00
if method_name.startswith("on_property_"):
name = method_name[12:]
name = name.replace("_", "-")
self.register_property_callback(name, method)
elif method_name.startswith("on_"):
name = method_name[3:]
name = name.replace("_", "-")
self.register_callback(name, method)
self._callbacks_initialized = True
while True:
try:
message = self._callbacks_queue.get_nowait()
except Empty:
break
self._handle_event(message)
2017-09-30 07:41:32 +02:00
# Simulate an init event when the process and all callbacks have been
# completely set up.
if hasattr(self, "on_init"):
# pylint: disable=no-member
2017-09-30 07:41:32 +02:00
self.on_init()
#
# Socket communication
#
def _start_thread(self):
2020-08-31 05:29:28 +02:00
"""Start up the communication threads."""
2017-09-30 07:41:32 +02:00
super()._start_thread()
2020-06-26 21:24:44 +02:00
if not hasattr(self, "_event_thread"):
self._event_thread = threading.Thread(target=self._event_reader)
self._event_thread.daemon = True
self._event_thread.start()
2017-09-30 07:41:32 +02:00
#
# Event/callback API
#
def _event_reader(self):
2020-08-31 05:29:28 +02:00
"""Collect incoming event messages and call the event handler."""
2020-06-26 21:24:44 +02:00
while True:
2017-09-30 07:41:32 +02:00
message = self._get_event(timeout=1)
if message is None:
continue
self._handle_event(message)
def _handle_event(self, message):
2020-08-31 05:29:28 +02:00
"""Lookup and call the callbacks for a particular event message."""
if not self._callbacks_initialized:
self._callbacks_queue.put(message)
return
2017-09-30 07:41:32 +02:00
if message["event"] == "property-change":
name = f"property-{message['name']}"
2017-09-30 07:41:32 +02:00
else:
name = message["event"]
for callback in self._callbacks.get(name, []):
if "data" in message:
callback(message["data"])
else:
callback()
def register_callback(self, name, callback):
2020-08-31 05:29:28 +02:00
"""Register a function `callback` for the event `name`."""
2017-09-30 07:41:32 +02:00
try:
self.command("enable_event", name)
except MPVCommandError:
raise MPVError(f"no such event {name!r}")
2017-09-30 07:41:32 +02:00
self._callbacks.setdefault(name, []).append(callback)
def unregister_callback(self, name, callback):
2017-09-30 07:41:32 +02:00
"""Unregister a previously registered function `callback` for the event
2020-08-31 05:29:28 +02:00
`name`.
2017-09-30 07:41:32 +02:00
"""
try:
callbacks = self._callbacks[name]
except KeyError:
raise MPVError(f"no callbacks registered for event {name!r}")
2017-09-30 07:41:32 +02:00
try:
callbacks.remove(callback)
except ValueError:
raise MPVError(f"callback {callback!r} not registered for event {name!r}")
2017-09-30 07:41:32 +02:00
def register_property_callback(self, name, callback):
2017-09-30 07:41:32 +02:00
"""Register a function `callback` for the property-change event on
2020-08-31 05:29:28 +02:00
property `name`.
2017-09-30 07:41:32 +02:00
"""
# Property changes are normally not sent over the connection unless they
# are requested using the 'observe_property' command.
# XXX We manually have to check for the existence of the property name.
# Apparently observe_property does not check it :-(
proplist = self.command("get_property", "property-list", timeout=5)
2017-09-30 07:41:32 +02:00
if name not in proplist:
raise MPVError(f"no such property {name!r}")
2017-09-30 07:41:32 +02:00
self._callbacks.setdefault(f"property-{name}", []).append(callback)
2017-09-30 07:41:32 +02:00
# 'observe_property' expects some kind of id which can be used later
# for unregistering with 'unobserve_property'.
serial = next(self._new_serial)
self.command("observe_property", serial, name)
self._property_serials[(name, callback)] = serial
return serial
def unregister_property_callback(self, name, callback):
2017-09-30 07:41:32 +02:00
"""Unregister a previously registered function `callback` for the
2020-08-31 05:29:28 +02:00
property-change event on property `name`.
2017-09-30 07:41:32 +02:00
"""
try:
callbacks = self._callbacks[f"property-{name}"]
2017-09-30 07:41:32 +02:00
except KeyError:
raise MPVError(f"no callbacks registered for property {name!r}")
2017-09-30 07:41:32 +02:00
try:
callbacks.remove(callback)
except ValueError:
2019-12-23 01:34:10 +01:00
raise MPVError(
f"callback {callback!r} not registered for property {name!r}"
2019-12-23 01:34:10 +01:00
)
2017-09-30 07:41:32 +02:00
serial = self._property_serials.pop((name, callback))
self.command("unobserve_property", serial)
#
# Public API
#
def command(self, *args, timeout=1):
2020-08-31 05:29:28 +02:00
"""Execute a single command on the mpv process and return the result."""
2017-09-30 07:41:32 +02:00
return self._send_request({"command": list(args)}, timeout=timeout)
def get_property(self, name):
2020-08-31 05:29:28 +02:00
"""Return the value of property `name`."""
2017-09-30 07:41:32 +02:00
return self.command("get_property", name)
def set_property(self, name, value):
2020-08-31 05:29:28 +02:00
"""Set the value of property `name`."""
2017-09-30 07:41:32 +02:00
return self.command("set_property", name, value)
# alias this module for backwards compat
sys.modules["anki.mpv"] = sys.modules["aqt.mpv"]