~naglis/aio_mpv_ipc

ref: 288c388039c210cb3f85a2a4bb68ab4bf2cfd270 aio_mpv_ipc/aio_mpv_ipc/_client.py -rw-r--r-- 6.4 KiB
288c3880Naglis Jonaitis Add a few more commands 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import asyncio
import collections
import contextlib
import json
import logging
import pathlib
import types
import typing

from aio_mpv_ipc.exceptions import (
    AioMpvIPCException,
    IPCConnectionException,
    IPCException,
    MpvStartException,
)

logger = logging.getLogger("aio_mpv_ipc")

IPC_ENCODING = "utf-8"


def _json_serialize_default(o):
    if isinstance(o, pathlib.Path):
        return str(o)
    return o


def _default_json_loads(s: bytes):
    return json.loads(s.decode(encoding=IPC_ENCODING))


def _default_json_dumps(obj: typing.Any) -> str:
    return json.dumps(obj, default=_json_serialize_default)


@contextlib.asynccontextmanager
async def start_mpv(
    socket_path: typing.Union[pathlib.Path, str],
    *mpv_args: str,
    mpv_path: typing.Union[pathlib.Path, str] = "mpv",
    terminate: bool = False,
    loop: typing.Optional[asyncio.AbstractEventLoop] = None,
):
    if isinstance(socket_path, pathlib.Path):
        socket_path = str(socket_path.resolve(strict=False))
    if isinstance(mpv_path, pathlib.Path):
        mpv_path = str(mpv_path)
    if loop is None:
        loop = asyncio.get_running_loop()

    mpv = await asyncio.create_subprocess_exec(
        mpv_path, "--input-ipc-server", socket_path, *mpv_args, loop=loop
    )
    logger.debug("Started mpv process with PID: %d", mpv.pid)

    try:
        yield mpv
    except IPCConnectionException as exc:
        if mpv.returncode is not None:
            raise MpvStartException(
                f"mpv exited with status code: {mpv.returncode}"
            ) from exc
        else:
            raise
    except Exception:
        logger.exception("An unexpected error occurred while executing mpv")
    finally:
        if terminate and mpv.returncode is None:
            mpv.terminate()
        await mpv.wait()


class MpvClient:
    def __init__(
        self,
        socket_path: pathlib.Path,
        *,
        max_connect_attempts: int = 5,
        connect_sleep_timeout: float = 0.5,
        json_loads=_default_json_loads,
        json_dumps=_default_json_dumps,
        loop: typing.Optional[asyncio.AbstractEventLoop] = None,
    ) -> None:
        self._socket_path = socket_path
        self._reader, self._writer = None, None
        self._max_connect_attempts = max_connect_attempts
        self._connect_sleep_timeout = connect_sleep_timeout
        self._json_loads, self._json_dumps = json_loads, json_dumps
        self._loop = loop or asyncio.get_running_loop()
        self._poll_task = None

        self._request_counter = 0

        self._futures: typing.Dict[str, asyncio.Future] = {}
        self._event_subscribers: typing.Dict[
            str, typing.Set[asyncio.Queue]
        ] = collections.defaultdict(set)

    def subscribe(self, event_name: str, queue: asyncio.Queue):
        self._event_subscribers[event_name].add(queue)

    def unsubscribe(self, event_name: str, queue: asyncio.Queue):
        self._event_subscribers[event_name].remove(queue)

    async def __aenter__(self):
        attempt = 0
        while True:
            attempt += 1
            try:
                self._reader, self._writer = await asyncio.open_unix_connection(
                    self._socket_path, loop=self._loop
                )
                break
            except ConnectionRefusedError as exc:
                if attempt >= self._max_connect_attempts:
                    raise IPCConnectionException("Failed to connect to mpv") from exc
                logger.debug(
                    "%d connection attempt failed, will retry after %f seconds",
                    attempt,
                    self._connect_sleep_timeout,
                )
                await asyncio.sleep(self._connect_sleep_timeout, loop=self._loop)

        self._poll_task = self._loop.create_task(self._poll())

        return self

    async def __aexit__(
        self,
        exc_type: typing.Optional[typing.Type[BaseException]] = None,
        exc_value: typing.Optional[BaseException] = None,
        traceback: typing.Optional[types.TracebackType] = None,
    ):
        if self._writer is not None:
            self._writer.close()

        if self._poll_task is not None:
            self._poll_task.cancel()
            try:
                await self._poll_task
            except asyncio.CancelledError:
                pass

    async def _poll(self):
        while True:
            data = await self._reader.readline()
            if data:
                response = self._json_loads(data.rstrip(b"\n"))

                logger.debug("Response from mpv: %r", response)

                event_name = response.get("event")
                if event_name is not None:
                    # This is an event notification, notify subscribers (if any).
                    if event_name in self._event_subscribers:
                        for queue in self._event_subscribers[event_name]:
                            queue.put_nowait(response)
                else:
                    status = response.get("error")
                    is_error = status and status != "success"
                    if is_error:
                        logger.error("mpv returned an error: %r", response)

                    request_id = response.get("request_id")
                    if request_id:
                        fut = self._futures.pop(request_id)
                        if is_error:
                            fut.set_exception(IPCException(status, response))
                        else:
                            fut.set_result(response.get("data"))

            if self._reader.at_eof():
                logger.debug("EOF received, stopping polling")
                break

    async def ipc(
        self, command_name: str, *params, nowait: bool = False
    ) -> typing.Optional[typing.Any]:
        if self._writer is None:
            raise AioMpvIPCException("Socket writer was not initialized")

        self._request_counter += 1

        payload = {"command": [command_name, *params]}

        fut = None
        if not nowait:
            request_id = self._request_counter
            fut = self._loop.create_future()
            payload.update(request_id=request_id)
            self._futures.update({request_id: fut})

        logger.debug("mpv IPC payload (nowait=%r): %s", nowait, payload)

        data = self._json_dumps(payload)
        self._writer.write(data.encode(encoding=IPC_ENCODING))
        self._writer.write(b"\n")
        await self._writer.drain()

        if not nowait:
            return await fut