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
|
2021-10-03 10:59:42 +02:00
|
|
|
from typing import Optional
|
2019-12-20 07:33:49 +01:00
|
|
|
|
2021-11-25 00:06:16 +01:00
|
|
|
from anki.utils import is_win
|
2019-12-20 10:19:03 +01:00
|
|
|
|
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
|
|
|
|
2021-11-25 00:06:16 +01:00
|
|
|
if is_win:
|
2019-03-04 02:22:40 +01:00
|
|
|
# pylint: disable=import-error
|
2020-08-31 04:05:36 +02:00
|
|
|
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")
|
2021-10-03 10:59:42 +02:00
|
|
|
popenEnv: Optional[dict[str, str]] = None
|
2017-09-30 07:41:32 +02:00
|
|
|
|
|
|
|
default_argv = [
|
|
|
|
"--idle",
|
2017-09-30 11:32:48 +02:00
|
|
|
"--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",
|
2021-06-07 00:45:59 +02:00
|
|
|
"--gapless-audio=no",
|
2017-09-30 07:41:32 +02:00
|
|
|
]
|
|
|
|
|
2023-01-03 02:59:39 +01:00
|
|
|
if is_win:
|
|
|
|
default_argv += ["--af-add=lavfi=[apad=pad_dur=0.150]"]
|
|
|
|
|
2019-12-20 07:33:49 +01: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()
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
def __del__(self):
|
2017-09-30 07:41:32 +02:00
|
|
|
self._stop_thread()
|
|
|
|
self._stop_process()
|
|
|
|
self._stop_socket()
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
def _thread_id(self):
|
2017-09-30 07:41:32 +02:00
|
|
|
return threading.get_ident()
|
|
|
|
|
|
|
|
#
|
|
|
|
# Process
|
|
|
|
#
|
2019-12-20 07:33:49 +01:00
|
|
|
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
|
2021-02-11 01:09:06 +01:00
|
|
|
self.argv += [f"--input-ipc-server={self._sock_filename}"]
|
2017-09-30 07:41:32 +02:00
|
|
|
if self.window_id is not None:
|
2021-02-11 01:09:06 +01:00
|
|
|
self.argv += [f"--wid={str(self.window_id)}"]
|
2017-09-30 07:41:32 +02:00
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
def _start_process(self):
|
2020-08-31 05:29:28 +02:00
|
|
|
"""Start the mpv process."""
|
2017-10-02 08:37:52 +02:00
|
|
|
self._proc = subprocess.Popen(self.argv, env=self.popenEnv)
|
2017-09-30 07:41:32 +02:00
|
|
|
|
2019-12-20 07:33:49 +01: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
|
|
|
|
#
|
2019-12-20 07:33:49 +01:00
|
|
|
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
|
|
|
"""
|
2021-11-25 00:06:16 +01:00
|
|
|
if is_win:
|
2023-01-03 02:59:39 +01:00
|
|
|
self._sock_filename = "ankimpv{}".format(os.getpid())
|
2017-09-30 11:32:48 +02:00
|
|
|
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)
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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
|
|
|
"""
|
2017-10-13 04:14:40 +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)
|
2021-11-25 00:06:16 +01:00
|
|
|
if is_win:
|
2017-10-13 04:14:40 +02:00
|
|
|
# named pipe
|
|
|
|
try:
|
2019-12-23 01:34:10 +01:00
|
|
|
self._sock = win32file.CreateFile(
|
2023-01-03 02:59:39 +01:00
|
|
|
r"\\.\pipe\{}".format(self._sock_filename),
|
2019-12-23 01:34:10 +01:00
|
|
|
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
|
|
|
|
0,
|
|
|
|
None,
|
|
|
|
win32file.OPEN_EXISTING,
|
|
|
|
0,
|
|
|
|
None,
|
|
|
|
)
|
|
|
|
win32pipe.SetNamedPipeHandleState(
|
|
|
|
self._sock, 1, None, None # PIPE_NOWAIT
|
|
|
|
)
|
2017-10-13 04:14:40 +02:00
|
|
|
except pywintypes.error as err:
|
|
|
|
if err.args[0] == winerror.ERROR_FILE_NOT_FOUND:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
break
|
2017-09-30 11:32:48 +02:00
|
|
|
else:
|
2017-10-13 04:14:40 +02:00
|
|
|
break
|
|
|
|
else:
|
|
|
|
# unix socket
|
|
|
|
try:
|
2017-09-30 11:32:48 +02:00
|
|
|
self._sock = socket.socket(socket.AF_UNIX)
|
2020-06-09 02:20:16 +02:00
|
|
|
self._sock.connect(self._sock_filename)
|
2017-10-13 04:14:40 +02:00
|
|
|
except (FileNotFoundError, ConnectionRefusedError):
|
2017-12-11 08:26:25 +01:00
|
|
|
self._sock.close()
|
2017-10-13 04:14:40 +02:00
|
|
|
continue
|
|
|
|
else:
|
|
|
|
break
|
2017-09-30 07:41:32 +02:00
|
|
|
else:
|
|
|
|
raise MPVProcessError("unable to start process")
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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()
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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)
|
2019-04-29 06:36:44 +02:00
|
|
|
self._thread.daemon = True
|
2017-09-30 07:41:32 +02:00
|
|
|
self._thread.start()
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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()
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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():
|
2021-11-25 00:06:16 +01:00
|
|
|
if is_win:
|
2017-09-30 11:32:48 +02:00
|
|
|
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:
|
2021-02-11 01:09:06 +01:00
|
|
|
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
|
|
|
|
#
|
2019-12-20 07:33:49 +01:00
|
|
|
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 ;-)
|
2019-12-16 08:54:40 +01:00
|
|
|
data = json.dumps(message)
|
2017-09-30 07:41:32 +02:00
|
|
|
return data.encode("utf8", "strict") + b"\n"
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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)
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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:
|
2021-02-11 01:09:06 +01:00
|
|
|
raise MPVCommunicationError(f"invalid message {message!r}")
|
2017-09-30 07:41:32 +02:00
|
|
|
|
2019-12-20 07:33:49 +01: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:
|
2021-02-11 01:09:06 +01:00
|
|
|
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.
|
2021-11-25 00:06:16 +01:00
|
|
|
if is_win:
|
2017-09-30 11:32:48 +02:00
|
|
|
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
|
|
|
|
2019-12-20 07:33:49 +01: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")
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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."""
|
2017-09-30 09:24:34 +02:00
|
|
|
self.ensure_running()
|
2017-09-30 07:41:32 +02:00
|
|
|
try:
|
catch full mpv request queue
presumably happening if multiple requests are sent before previous
response fetch times out
Caught exception:
File "aqt/webview.py", line 314, in handler
File "aqt/editor.py", line 351, in <lambda>
File "aqt/addcards.py", line 225, in afterSave
File "aqt/addcards.py", line 231, in doClose
File "aqt/addcards.py", line 210, in _reject
File "anki/sound.py", line 417, in clearAudioQueue
File "anki/sound.py", line 117, in clearQueue
File "anki/mpv.py", line 558, in command
File "anki/mpv.py", line 352, in _send_request
File "anki/mpv.py", line 311, in _send_message
<class 'anki.mpv.MPVTimeoutError'>: unable to put request
2019-04-21 10:56:11 +02:00
|
|
|
self._send_message(message, timeout)
|
2017-09-30 07:41:32 +02:00
|
|
|
return self._get_response(timeout)
|
|
|
|
except MPVCommandError as e:
|
2021-02-11 01:09:06 +01:00
|
|
|
raise MPVCommandError(f"{message['command']!r}: {e}")
|
2020-06-26 21:24:44 +02:00
|
|
|
except Exception as e:
|
2018-12-13 12:30:17 +01:00
|
|
|
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)
|
2018-12-13 12:30:17 +01:00
|
|
|
else:
|
|
|
|
raise
|
2017-09-30 07:41:32 +02:00
|
|
|
|
2020-06-27 11:31:58 +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
|
2020-06-27 11:31:58 +02:00
|
|
|
"""
|
|
|
|
|
2017-09-30 07:41:32 +02:00
|
|
|
#
|
|
|
|
# Public API
|
|
|
|
#
|
2019-12-20 07:33:49 +01:00
|
|
|
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
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
def ensure_running(self):
|
2017-09-30 09:24:34 +02:00
|
|
|
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()
|
2017-09-30 09:24:34 +02:00
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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
|
|
|
"""
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
2020-05-27 01:19:20 +02:00
|
|
|
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
|
|
|
|
|
2020-06-26 19:36:58 +02:00
|
|
|
# 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)
|
|
|
|
|
2020-05-27 01:19:20 +02:00
|
|
|
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"):
|
2019-03-04 02:22:40 +01:00
|
|
|
# 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
|
|
|
|
#
|
2019-12-20 07:33:49 +01:00
|
|
|
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)
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
def _handle_event(self, message):
|
2020-08-31 05:29:28 +02:00
|
|
|
"""Lookup and call the callbacks for a particular event message."""
|
2020-05-27 01:19:20 +02:00
|
|
|
if not self._callbacks_initialized:
|
|
|
|
self._callbacks_queue.put(message)
|
|
|
|
return
|
|
|
|
|
2017-09-30 07:41:32 +02:00
|
|
|
if message["event"] == "property-change":
|
2021-02-11 01:09:06 +01:00
|
|
|
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()
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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:
|
2021-02-11 01:09:06 +01:00
|
|
|
raise MPVError(f"no such event {name!r}")
|
2017-09-30 07:41:32 +02:00
|
|
|
|
|
|
|
self._callbacks.setdefault(name, []).append(callback)
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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:
|
2021-02-11 01:09:06 +01:00
|
|
|
raise MPVError(f"no callbacks registered for event {name!r}")
|
2017-09-30 07:41:32 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
callbacks.remove(callback)
|
|
|
|
except ValueError:
|
2021-02-11 01:09:06 +01:00
|
|
|
raise MPVError(f"callback {callback!r} not registered for event {name!r}")
|
2017-09-30 07:41:32 +02:00
|
|
|
|
2019-12-20 07:33:49 +01: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 :-(
|
2021-08-17 23:47:04 +02:00
|
|
|
proplist = self.command("get_property", "property-list", timeout=5)
|
2017-09-30 07:41:32 +02:00
|
|
|
if name not in proplist:
|
2021-02-11 01:09:06 +01:00
|
|
|
raise MPVError(f"no such property {name!r}")
|
2017-09-30 07:41:32 +02:00
|
|
|
|
2021-02-11 01:09:06 +01: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
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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:
|
2021-02-11 01:09:06 +01:00
|
|
|
callbacks = self._callbacks[f"property-{name}"]
|
2017-09-30 07:41:32 +02:00
|
|
|
except KeyError:
|
2021-02-11 01:09:06 +01:00
|
|
|
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(
|
2021-02-11 01:09:06 +01:00
|
|
|
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
|
|
|
|
#
|
2019-12-20 07:33:49 +01:00
|
|
|
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)
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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)
|
|
|
|
|
2019-12-20 07:33:49 +01:00
|
|
|
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)
|
2020-01-02 10:43:19 +01:00
|
|
|
|
|
|
|
|
|
|
|
# alias this module for backwards compat
|
|
|
|
sys.modules["anki.mpv"] = sys.modules["aqt.mpv"]
|