boris-behav-obs 9.7.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of boris-behav-obs might be problematic. Click here for more details.

Files changed (109) hide show
  1. boris/__init__.py +26 -0
  2. boris/__main__.py +25 -0
  3. boris/about.py +143 -0
  4. boris/add_modifier.py +635 -0
  5. boris/add_modifier_ui.py +303 -0
  6. boris/advanced_event_filtering.py +455 -0
  7. boris/analysis_plugins/__init__.py +0 -0
  8. boris/analysis_plugins/_latency.py +59 -0
  9. boris/analysis_plugins/irr_cohen_kappa.py +109 -0
  10. boris/analysis_plugins/irr_cohen_kappa_with_modifiers.py +112 -0
  11. boris/analysis_plugins/irr_weighted_cohen_kappa.py +157 -0
  12. boris/analysis_plugins/irr_weighted_cohen_kappa_with_modifiers.py +162 -0
  13. boris/analysis_plugins/list_of_dataframe_columns.py +22 -0
  14. boris/analysis_plugins/number_of_occurences.py +22 -0
  15. boris/analysis_plugins/number_of_occurences_by_independent_variable.py +54 -0
  16. boris/analysis_plugins/time_budget.py +61 -0
  17. boris/behav_coding_map_creator.py +1110 -0
  18. boris/behavior_binary_table.py +305 -0
  19. boris/behaviors_coding_map.py +239 -0
  20. boris/boris_cli.py +340 -0
  21. boris/cmd_arguments.py +49 -0
  22. boris/coding_pad.py +280 -0
  23. boris/config.py +785 -0
  24. boris/config_file.py +356 -0
  25. boris/connections.py +409 -0
  26. boris/converters.py +333 -0
  27. boris/converters_ui.py +225 -0
  28. boris/cooccurence.py +250 -0
  29. boris/core.py +5901 -0
  30. boris/core_qrc.py +15958 -0
  31. boris/core_ui.py +1107 -0
  32. boris/db_functions.py +324 -0
  33. boris/dev.py +134 -0
  34. boris/dialog.py +1108 -0
  35. boris/duration_widget.py +238 -0
  36. boris/edit_event.py +245 -0
  37. boris/edit_event_ui.py +233 -0
  38. boris/event_operations.py +1040 -0
  39. boris/events_cursor.py +61 -0
  40. boris/events_snapshots.py +596 -0
  41. boris/exclusion_matrix.py +141 -0
  42. boris/export_events.py +1006 -0
  43. boris/export_observation.py +1203 -0
  44. boris/external_processes.py +332 -0
  45. boris/geometric_measurement.py +941 -0
  46. boris/gui_utilities.py +135 -0
  47. boris/image_overlay.py +72 -0
  48. boris/import_observations.py +242 -0
  49. boris/ipc_mpv.py +325 -0
  50. boris/irr.py +634 -0
  51. boris/latency.py +244 -0
  52. boris/measurement_widget.py +161 -0
  53. boris/media_file.py +115 -0
  54. boris/menu_options.py +213 -0
  55. boris/modifier_coding_map_creator.py +1013 -0
  56. boris/modifiers_coding_map.py +157 -0
  57. boris/mpv.py +2016 -0
  58. boris/mpv2.py +2193 -0
  59. boris/observation.py +1453 -0
  60. boris/observation_operations.py +2538 -0
  61. boris/observation_ui.py +679 -0
  62. boris/observations_list.py +337 -0
  63. boris/otx_parser.py +442 -0
  64. boris/param_panel.py +201 -0
  65. boris/param_panel_ui.py +305 -0
  66. boris/player_dock_widget.py +198 -0
  67. boris/plot_data_module.py +536 -0
  68. boris/plot_events.py +634 -0
  69. boris/plot_events_rt.py +237 -0
  70. boris/plot_spectrogram_rt.py +316 -0
  71. boris/plot_waveform_rt.py +230 -0
  72. boris/plugins.py +431 -0
  73. boris/portion/__init__.py +31 -0
  74. boris/portion/const.py +95 -0
  75. boris/portion/dict.py +365 -0
  76. boris/portion/func.py +52 -0
  77. boris/portion/interval.py +581 -0
  78. boris/portion/io.py +181 -0
  79. boris/preferences.py +510 -0
  80. boris/preferences_ui.py +770 -0
  81. boris/project.py +2007 -0
  82. boris/project_functions.py +2041 -0
  83. boris/project_import_export.py +1096 -0
  84. boris/project_ui.py +794 -0
  85. boris/qrc_boris.py +10389 -0
  86. boris/qrc_boris5.py +2579 -0
  87. boris/select_modifiers.py +312 -0
  88. boris/select_observations.py +210 -0
  89. boris/select_subj_behav.py +286 -0
  90. boris/state_events.py +197 -0
  91. boris/subjects_pad.py +106 -0
  92. boris/synthetic_time_budget.py +290 -0
  93. boris/time_budget_functions.py +1136 -0
  94. boris/time_budget_widget.py +1039 -0
  95. boris/transitions.py +365 -0
  96. boris/utilities.py +1810 -0
  97. boris/version.py +24 -0
  98. boris/video_equalizer.py +159 -0
  99. boris/video_equalizer_ui.py +248 -0
  100. boris/video_operations.py +310 -0
  101. boris/view_df.py +104 -0
  102. boris/view_df_ui.py +75 -0
  103. boris/write_event.py +538 -0
  104. boris_behav_obs-9.7.7.dist-info/METADATA +139 -0
  105. boris_behav_obs-9.7.7.dist-info/RECORD +109 -0
  106. boris_behav_obs-9.7.7.dist-info/WHEEL +5 -0
  107. boris_behav_obs-9.7.7.dist-info/entry_points.txt +2 -0
  108. boris_behav_obs-9.7.7.dist-info/licenses/LICENSE.TXT +674 -0
  109. boris_behav_obs-9.7.7.dist-info/top_level.txt +1 -0
boris/mpv2.py ADDED
@@ -0,0 +1,2193 @@
1
+ # -*- coding: utf-8 -*-
2
+ # vim: ts=4 sw=4 et
3
+ #
4
+ # Python MPV library module
5
+ # Copyright (C) 2017-2024 Sebastian Götte <code@jaseg.net>
6
+ #
7
+ # python-mpv inherits the underlying libmpv's license, which can be either GPLv2 or later (default) or LGPLv2.1 or
8
+ # later. For details, see the mpv copyright page here: https://github.com/mpv-player/mpv/blob/master/Copyright
9
+ #
10
+ # You may copy, modify, and redistribute this file under the terms of the GNU General Public License version 2 (or, at
11
+ # your option, any later version), or the GNU Lesser General Public License as published by the Free Software
12
+ # Foundation; either version 2.1 of the License, or (at your option) any later version.
13
+ #
14
+ # This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
15
+ # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License and the GNU
16
+ # Lesser General Public License for more details.
17
+ #
18
+ # You can find copies of the GPLv2 and LGPLv2.1 licenses in the project repository's LICENSE.GPL and LICENSE.LGPL files.
19
+
20
+ __version__ = '1.0.7'
21
+
22
+ from ctypes import *
23
+ import ctypes.util
24
+ import threading
25
+ import queue
26
+ import os
27
+ import os.path
28
+ import sys
29
+ from warnings import warn
30
+ from functools import partial, wraps
31
+ from contextlib import contextmanager
32
+ from concurrent.futures import Future, InvalidStateError
33
+ import collections
34
+ import re
35
+ import traceback
36
+
37
+ if os.name == 'nt':
38
+ # Note: mpv-2.dll with API version 2 corresponds to mpv v0.35.0. Most things should work with the fallback, too.
39
+ names = ['mpv-2.dll', 'libmpv-2.dll', 'mpv-1.dll']
40
+ for name in names:
41
+ dll = ctypes.util.find_library(name)
42
+ if dll:
43
+ break
44
+ else:
45
+ for name in names:
46
+ dll = os.path.join(os.path.dirname(__file__), name)
47
+ if os.path.isfile(dll):
48
+ break
49
+ else:
50
+ raise OSError('Cannot find mpv-1.dll, mpv-2.dll or libmpv-2.dll in your system %PATH%. One way to deal with this is to ship the dll with your script and put the directory your script is in into %PATH% before "import mpv": os.environ["PATH"] = os.path.dirname(__file__) + os.pathsep + os.environ["PATH"] If mpv-1.dll is located elsewhere, you can add that path to os.environ["PATH"].')
51
+
52
+ try:
53
+ # flags argument: LOAD_LIBRARY_SEARCH_DEFAULT_DIRS | LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR
54
+ # cf. https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa
55
+ backend = CDLL(dll, 0x00001000 | 0x00000100)
56
+ except Exception as e:
57
+ if not os.path.isabs(dll): # can only be find_library, not the "look next to mpv.py" thing
58
+ raise OSError(f'ctypes.find_library found mpv.dll at {dll}, but ctypes.CDLL could not load it. It looks like find_library found mpv.dll under a relative path entry in %PATH%. Please make sure all paths in %PATH% are absolute. Instead of trying to load mpv.dll from the current working directory, put it somewhere next to your script and add that path to %PATH% using os.environ["PATH"] = os.path.dirname(__file__) + os.pathsep + os.environ["PATH"]') from e
59
+ else:
60
+ raise OSError(f'ctypes.find_library found mpv.dll at {dll}, but ctypes.CDLL could not load it.') from e
61
+ fs_enc = 'utf-8'
62
+
63
+ else:
64
+ import locale
65
+ lc, enc = locale.getlocale(locale.LC_NUMERIC)
66
+ # libmpv requires LC_NUMERIC to be set to "C". Since messing with global variables everyone else relies upon is
67
+ # still better than segfaulting, we are setting LC_NUMERIC to "C".
68
+ locale.setlocale(locale.LC_NUMERIC, 'C')
69
+
70
+ sofile = ctypes.util.find_library('mpv')
71
+ if sofile is None:
72
+ raise OSError("Cannot find libmpv in the usual places. Depending on your distro, you may try installing an mpv-devel or mpv-libs package. If you have libmpv around but this script can't find it, consult the documentation for ctypes.util.find_library which this script uses to look up the library filename.")
73
+ backend = CDLL(sofile)
74
+ fs_enc = sys.getfilesystemencoding()
75
+
76
+
77
+ class ShutdownError(SystemError):
78
+ pass
79
+
80
+ class EventOverflowError(SystemError):
81
+ pass
82
+
83
+ class MpvHandle(c_void_p):
84
+ pass
85
+
86
+ class MpvRenderCtxHandle(c_void_p):
87
+ pass
88
+
89
+ class PropertyUnavailableError(AttributeError):
90
+ pass
91
+
92
+ class ErrorCode(object):
93
+ """For documentation on these, see mpv's libmpv/client.h."""
94
+ SUCCESS = 0
95
+ EVENT_QUEUE_FULL = -1
96
+ NOMEM = -2
97
+ UNINITIALIZED = -3
98
+ INVALID_PARAMETER = -4
99
+ OPTION_NOT_FOUND = -5
100
+ OPTION_FORMAT = -6
101
+ OPTION_ERROR = -7
102
+ PROPERTY_NOT_FOUND = -8
103
+ PROPERTY_FORMAT = -9
104
+ PROPERTY_UNAVAILABLE = -10
105
+ PROPERTY_ERROR = -11
106
+ COMMAND = -12
107
+ LOADING_FAILED = -13
108
+ AO_INIT_FAILED = -14
109
+ VO_INIT_FAILED = -15
110
+ NOTHING_TO_PLAY = -16
111
+ UNKNOWN_FORMAT = -17
112
+ UNSUPPORTED = -18
113
+ NOT_IMPLEMENTED = -19
114
+ GENERIC = -20
115
+
116
+ EXCEPTION_DICT = {
117
+ 0: None,
118
+ -1: lambda *a: MemoryError('mpv event queue full', *a),
119
+ -2: lambda *a: MemoryError('mpv cannot allocate memory', *a),
120
+ -3: lambda *a: ValueError('Uninitialized mpv handle used', *a),
121
+ -4: lambda *a: ValueError('Invalid value for mpv parameter', *a),
122
+ -5: lambda *a: AttributeError('mpv option does not exist', *a),
123
+ -6: lambda *a: TypeError('Tried to set mpv option using wrong format', *a),
124
+ -7: lambda *a: ValueError('Invalid value for mpv option', *a),
125
+ -8: lambda *a: AttributeError('mpv property does not exist', *a),
126
+ # Currently (mpv 0.18.1) there is a bug causing a PROPERTY_FORMAT error to be returned instead of
127
+ # INVALID_PARAMETER when setting a property-mapped option to an invalid value.
128
+ -9: lambda *a: TypeError('Tried to get/set mpv property using wrong format, or passed invalid value', *a),
129
+ -10: lambda *a: PropertyUnavailableError('mpv property is not available', *a),
130
+ -11: lambda *a: RuntimeError('Generic error getting or setting mpv property', *a),
131
+ -12: lambda *a: SystemError('Error running mpv command', *a),
132
+ -14: lambda *a: RuntimeError('Initializing the audio output failed', *a),
133
+ -15: lambda *a: RuntimeError('Initializing the video output failed'),
134
+ -16: lambda *a: RuntimeError('There was no audio or video data to play. This also happens if the file '
135
+ 'was recognized, but did not contain any audio or video streams, or no '
136
+ 'streams were selected.'),
137
+ -17: lambda *a: RuntimeError('When trying to load the file, the file format could not be determined, '
138
+ 'or the file was too broken to open it'),
139
+ -18: lambda *a: ValueError('Generic error for signaling that certain system requirements are not fulfilled'),
140
+ -19: lambda *a: NotImplementedError('The API function which was called is a stub only'),
141
+ -20: lambda *a: RuntimeError('Unspecified error') }
142
+
143
+ @staticmethod
144
+ def human_readable(ec):
145
+ return _mpv_error_string(ec).decode('utf-8')
146
+
147
+ @staticmethod
148
+ def default_error_handler(ec, *args):
149
+ return ValueError(ErrorCode.human_readable(ec), ec, *args)
150
+
151
+ @classmethod
152
+ def exception_for_ec(kls, ec, *args):
153
+ ec = 0 if ec > 0 else ec
154
+ ex = kls.EXCEPTION_DICT.get(ec, kls.default_error_handler)
155
+ if ex:
156
+ return ex(ec, *args)
157
+
158
+ @classmethod
159
+ def raise_for_ec(kls, ec, func, *args):
160
+ ex = kls.exception_for_ec(ec, *args)
161
+ if ex:
162
+ raise ex
163
+
164
+ MpvGlGetProcAddressFn = CFUNCTYPE(c_void_p, c_void_p, c_char_p)
165
+ class MpvOpenGLInitParams(Structure):
166
+ _fields_ = [('get_proc_address', MpvGlGetProcAddressFn),
167
+ ('get_proc_address_ctx', c_void_p),
168
+ ('extra_exts', c_void_p)]
169
+
170
+ def __init__(self, get_proc_address):
171
+ self.get_proc_address = get_proc_address
172
+ self.get_proc_address_ctx = None
173
+ self.extra_exts = None
174
+
175
+ class MpvOpenGLFBO(Structure):
176
+ _fields_ = [('fbo', c_int),
177
+ ('w', c_int),
178
+ ('h', c_int),
179
+ ('internal_format', c_int)]
180
+
181
+ def __init__(self, w, h, fbo=0, internal_format=0):
182
+ self.w, self.h = w, h
183
+ self.fbo = fbo
184
+ self.internal_format = internal_format
185
+
186
+ class MpvRenderFrameInfo(Structure):
187
+ _fields_ = [('flags', c_int64),
188
+ ('target_time', c_int64)]
189
+
190
+ def as_dict(self):
191
+ return {'flags': self.flags,
192
+ 'target_time': self.target_time}
193
+
194
+ class MpvOpenGLDRMParams(Structure):
195
+ _fields_ = [('fd', c_int),
196
+ ('crtc_id', c_int),
197
+ ('connector_id', c_int),
198
+ ('atomic_request_ptr', c_void_p),
199
+ ('render_fd', c_int)]
200
+
201
+ class MpvOpenGLDRMDrawSurfaceSize(Structure):
202
+ _fields_ = [('width', c_int), ('height', c_int)]
203
+
204
+ class MpvOpenGLDRMParamsV2(Structure):
205
+ _fields_ = [('fd', c_int),
206
+ ('crtc_id', c_int),
207
+ ('connector_id', c_int),
208
+ ('atomic_request_ptr', c_void_p),
209
+ ('render_fd', c_int)]
210
+
211
+ def __init__(self, crtc_id, connector_id, atomic_request_ptr, fd=-1, render_fd=-1):
212
+ self.crtc_id, self.connector_id = crtc_id, connector_id
213
+ self.atomic_request_ptr = atomic_request_ptr
214
+ self.fd, self.render_fd = fd, render_fd
215
+
216
+
217
+ class MpvRenderParam(Structure):
218
+ _fields_ = [('type_id', c_int),
219
+ ('data', c_void_p)]
220
+
221
+ # maps human-readable type name to (type_id, argtype) tuple.
222
+ # The type IDs come from libmpv/render.h
223
+ TYPES = {"invalid" :(0, None),
224
+ "api_type" :(1, str),
225
+ "opengl_init_params" :(2, MpvOpenGLInitParams),
226
+ "opengl_fbo" :(3, MpvOpenGLFBO),
227
+ "flip_y" :(4, bool),
228
+ "depth" :(5, int),
229
+ "icc_profile" :(6, bytes),
230
+ "ambient_light" :(7, int),
231
+ "x11_display" :(8, c_void_p),
232
+ "wl_display" :(9, c_void_p),
233
+ "advanced_control" :(10, bool),
234
+ "next_frame_info" :(11, MpvRenderFrameInfo),
235
+ "block_for_target_time" :(12, bool),
236
+ "skip_rendering" :(13, bool),
237
+ "drm_display" :(14, MpvOpenGLDRMParams),
238
+ "drm_draw_surface_size" :(15, MpvOpenGLDRMDrawSurfaceSize),
239
+ "drm_display_v2" :(16, MpvOpenGLDRMParamsV2)}
240
+
241
+ def __init__(self, name, value=None):
242
+ if name not in self.TYPES:
243
+ raise ValueError('unknown render param type "{}"'.format(name))
244
+ self.type_id, cons = self.TYPES[name]
245
+ if cons is None:
246
+ self.value = None
247
+ self.data = c_void_p()
248
+ elif cons is str:
249
+ self.value = value
250
+ self.data = cast(c_char_p(value.encode('utf-8')), c_void_p)
251
+ elif cons is bytes:
252
+ self.value = MpvByteArray(value)
253
+ self.data = cast(pointer(self.value), c_void_p)
254
+ elif cons is bool:
255
+ self.value = c_int(int(bool(value)))
256
+ self.data = cast(pointer(self.value), c_void_p)
257
+ elif cons is c_void_p:
258
+ self.value = value
259
+ self.data = cast(self.value, c_void_p)
260
+ else:
261
+ self.value = cons(**value)
262
+ self.data = cast(pointer(self.value), c_void_p)
263
+
264
+ def kwargs_to_render_param_array(kwargs):
265
+ t = MpvRenderParam * (len(kwargs)+1)
266
+ return t(*kwargs.items(), ('invalid', None))
267
+
268
+ class MpvFormat(c_int):
269
+ NONE = 0
270
+ STRING = 1
271
+ OSD_STRING = 2
272
+ FLAG = 3
273
+ INT64 = 4
274
+ DOUBLE = 5
275
+ NODE = 6
276
+ NODE_ARRAY = 7
277
+ NODE_MAP = 8
278
+ BYTE_ARRAY = 9
279
+
280
+ def __eq__(self, other):
281
+ return self is other or self.value == other or self.value == int(other)
282
+
283
+ def __repr__(self):
284
+ return ['NONE', 'STRING', 'OSD_STRING', 'FLAG', 'INT64', 'DOUBLE', 'NODE', 'NODE_ARRAY', 'NODE_MAP',
285
+ 'BYTE_ARRAY'][self.value]
286
+
287
+ def __hash__(self):
288
+ return self.value
289
+
290
+
291
+ class MpvEventID(c_int):
292
+ NONE = 0
293
+ SHUTDOWN = 1
294
+ LOG_MESSAGE = 2
295
+ GET_PROPERTY_REPLY = 3
296
+ SET_PROPERTY_REPLY = 4
297
+ COMMAND_REPLY = 5
298
+ START_FILE = 6
299
+ END_FILE = 7
300
+ FILE_LOADED = 8
301
+ CLIENT_MESSAGE = 16
302
+ VIDEO_RECONFIG = 17
303
+ AUDIO_RECONFIG = 18
304
+ SEEK = 20
305
+ PLAYBACK_RESTART = 21
306
+ PROPERTY_CHANGE = 22
307
+ QUEUE_OVERFLOW = 24
308
+ HOOK = 25
309
+
310
+ ANY = ( SHUTDOWN, LOG_MESSAGE, GET_PROPERTY_REPLY, SET_PROPERTY_REPLY, COMMAND_REPLY, START_FILE, END_FILE,
311
+ FILE_LOADED, CLIENT_MESSAGE, VIDEO_RECONFIG, AUDIO_RECONFIG, SEEK, PLAYBACK_RESTART, PROPERTY_CHANGE)
312
+
313
+ def __repr__(self):
314
+ return f'<MpvEventID {self.value} {_mpv_event_name(self.value).decode("utf-8")}>'
315
+
316
+ @classmethod
317
+ def from_str(kls, s):
318
+ return getattr(kls, s.upper().replace('-', '_'))
319
+
320
+
321
+ identity_decoder = lambda b: b
322
+ strict_decoder = lambda b: b.decode('utf-8')
323
+ def lazy_decoder(b):
324
+ try:
325
+ return b.decode('utf-8')
326
+ except UnicodeDecodeError:
327
+ return b
328
+
329
+ class MpvNodeList(Structure):
330
+ def array_value(self, decoder=identity_decoder):
331
+ return [ self.values[i].node_value(decoder) for i in range(self.num) ]
332
+
333
+ def dict_value(self, decoder=identity_decoder):
334
+ return { self.keys[i].decode('utf-8'):
335
+ self.values[i].node_value(decoder) for i in range(self.num) }
336
+
337
+ class MpvByteArray(Structure):
338
+ _fields_ = [('data', c_void_p),
339
+ ('size', c_size_t)]
340
+
341
+ def __init__(self, value):
342
+ self._value = value
343
+ self.data = cast(c_char_p(value), c_void_p)
344
+ self.size = len(value)
345
+
346
+ def bytes_value(self):
347
+ return cast(self.data, POINTER(c_char))[:self.size]
348
+
349
+ class MpvNode(Structure):
350
+ def node_value(self, decoder=identity_decoder):
351
+ return MpvNode.node_cast_value(self.val, self.format.value, decoder)
352
+
353
+ @staticmethod
354
+ def node_cast_value(v, fmt=MpvFormat.NODE, decoder=identity_decoder):
355
+ if fmt == MpvFormat.NONE:
356
+ return None
357
+ elif fmt == MpvFormat.STRING:
358
+ return decoder(v.string)
359
+ elif fmt == MpvFormat.OSD_STRING:
360
+ return v.string.decode('utf-8')
361
+ elif fmt == MpvFormat.FLAG:
362
+ return bool(v.flag)
363
+ elif fmt == MpvFormat.INT64:
364
+ return v.int64
365
+ elif fmt == MpvFormat.DOUBLE:
366
+ return v.double
367
+ else:
368
+ if not v.node: # Check for null pointer
369
+ return None
370
+ if fmt == MpvFormat.NODE:
371
+ return v.node.contents.node_value(decoder)
372
+ elif fmt == MpvFormat.NODE_ARRAY:
373
+ return v.list.contents.array_value(decoder)
374
+ elif fmt == MpvFormat.NODE_MAP:
375
+ return v.map.contents.dict_value(decoder)
376
+ elif fmt == MpvFormat.BYTE_ARRAY:
377
+ return v.byte_array.contents.bytes_value()
378
+ else:
379
+ raise TypeError('Unknown MPV node format {}. Please submit a bug report.'.format(fmt))
380
+
381
+ class MpvNodeUnion(Union):
382
+ _fields_ = [('string', c_char_p),
383
+ ('flag', c_int),
384
+ ('int64', c_int64),
385
+ ('double', c_double),
386
+ ('node', POINTER(MpvNode)),
387
+ ('list', POINTER(MpvNodeList)),
388
+ ('map', POINTER(MpvNodeList)),
389
+ ('byte_array', POINTER(MpvByteArray))]
390
+
391
+ MpvNode._fields_ = [('val', MpvNodeUnion),
392
+ ('format', MpvFormat)]
393
+
394
+ MpvNodeList._fields_ = [('num', c_int),
395
+ ('values', POINTER(MpvNode)),
396
+ ('keys', POINTER(c_char_p))]
397
+
398
+ class MpvEvent(Structure):
399
+ _fields_ = [('event_id', MpvEventID),
400
+ ('error', c_int),
401
+ ('reply_userdata', c_ulonglong),
402
+ ('_data', c_void_p)]
403
+
404
+ @property
405
+ def data(self):
406
+ dtype = {
407
+ MpvEventID.GET_PROPERTY_REPLY: MpvEventProperty,
408
+ MpvEventID.PROPERTY_CHANGE: MpvEventProperty,
409
+ MpvEventID.LOG_MESSAGE: MpvEventLogMessage,
410
+ MpvEventID.CLIENT_MESSAGE: MpvEventClientMessage,
411
+ MpvEventID.START_FILE: MpvEventStartFile,
412
+ MpvEventID.END_FILE: MpvEventEndFile,
413
+ MpvEventID.HOOK: MpvEventHook,
414
+ MpvEventID.COMMAND_REPLY: MpvEventCommand,
415
+ }.get(self.event_id.value)
416
+ return cast(self._data, POINTER(dtype)).contents if dtype else None
417
+
418
+ def as_dict(self, decoder=identity_decoder):
419
+ out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
420
+ _mpv_event_to_node(out, pointer(self))
421
+ rv = out.contents.node_value(decoder=decoder)
422
+ _mpv_free_node_contents(out)
423
+ return rv
424
+
425
+ def __str__(self):
426
+ d = self.data
427
+ return f'<{type(d).__name__} ({self.event_id.value}) err={self.error} p={self.reply_userdata:016x} d={self.as_dict()}>'
428
+
429
+ class MpvEventProperty(Structure):
430
+ _fields_ = [('_name', c_char_p),
431
+ ('format', MpvFormat),
432
+ ('data', MpvNodeUnion)]
433
+
434
+ @property
435
+ def name(self):
436
+ return self._name.decode("utf-8")
437
+
438
+ @property
439
+ def value(self):
440
+ return MpvNode.node_cast_value(self.data, self.format.value, decoder=lazy_decoder)
441
+
442
+ class MpvEventLogMessage(Structure):
443
+ _fields_ = [('_prefix', c_char_p),
444
+ ('_level', c_char_p),
445
+ ('_text', c_char_p)]
446
+
447
+ @property
448
+ def prefix(self):
449
+ return self._prefix.decode("utf-8")
450
+
451
+ @property
452
+ def level(self):
453
+ return self._level.decode("utf-8")
454
+
455
+ @property
456
+ def text(self):
457
+ return lazy_decoder(self._text)
458
+
459
+ class MpvEventEndFile(Structure):
460
+ _fields_ = [
461
+ ('reason', c_int),
462
+ ('error', c_int),
463
+ ('playlist_entry_id', c_ulonglong),
464
+ ('playlist_insert_id', c_ulonglong),
465
+ ('playlist_insert_num_entries', c_int),
466
+ ]
467
+
468
+ EOF = 0
469
+ RESTARTED = 1
470
+ ABORTED = 2
471
+ QUIT = 3
472
+ ERROR = 4
473
+ REDIRECT = 5
474
+
475
+ class MpvEventStartFile(Structure):
476
+ _fields_ = [('playlist_entry_id', c_ulonglong),]
477
+
478
+ class MpvEventClientMessage(Structure):
479
+ _fields_ = [('_num_args', c_int),
480
+ ('_args', POINTER(c_char_p))]
481
+
482
+ @property
483
+ def args(self):
484
+ return [ self._args[i] for i in range(self._num_args) ]
485
+
486
+ class MpvEventCommand(Structure):
487
+ _fields_ = [('_result', MpvNode)]
488
+
489
+ def unpack(self, decoder=identity_decoder):
490
+ return self._result.node_value(decoder=decoder)
491
+
492
+ @property
493
+ def result(self):
494
+ return self.unpack()
495
+
496
+ class MpvEventHook(Structure):
497
+ _fields_ = [('_name', c_char_p),
498
+ ('id', c_ulonglong),]
499
+
500
+
501
+ @property
502
+ def name(self):
503
+ return self._name.decode("utf-8")
504
+
505
+ StreamReadFn = CFUNCTYPE(c_int64, c_void_p, POINTER(c_char), c_uint64)
506
+ StreamSeekFn = CFUNCTYPE(c_int64, c_void_p, c_int64)
507
+ StreamSizeFn = CFUNCTYPE(c_int64, c_void_p)
508
+ StreamCloseFn = CFUNCTYPE(None, c_void_p)
509
+ StreamCancelFn = CFUNCTYPE(None, c_void_p)
510
+
511
+ class StreamCallbackInfo(Structure):
512
+ _fields_ = [('cookie', c_void_p),
513
+ ('read', StreamReadFn),
514
+ ('seek', StreamSeekFn),
515
+ ('size', StreamSizeFn),
516
+ ('close', StreamCloseFn),
517
+ ('cancel', StreamCancelFn)]
518
+
519
+ StreamOpenFn = CFUNCTYPE(c_int, c_void_p, c_char_p, POINTER(StreamCallbackInfo))
520
+
521
+ WakeupCallback = CFUNCTYPE(None, c_void_p)
522
+
523
+ RenderUpdateFn = CFUNCTYPE(None, c_void_p)
524
+
525
+ def _handle_func(name, args, restype, errcheck, ctx=MpvHandle, deprecated=False):
526
+ func = getattr(backend, name)
527
+ func.argtypes = [ctx] + args if ctx else args
528
+ if restype is not None:
529
+ func.restype = restype
530
+ if errcheck is not None:
531
+ func.errcheck = errcheck
532
+ if deprecated:
533
+ @wraps(func)
534
+ def wrapper(*args, **kwargs):
535
+ if not wrapper.warned: # Only warn on first invocation to prevent spamming
536
+ warn("Backend C api has been deprecated: " + name, DeprecationWarning, stacklevel=2)
537
+ wrapper.warned = True
538
+ return func(*args, **kwargs)
539
+ wrapper.warned = False
540
+
541
+ globals()['_'+name] = wrapper
542
+ else:
543
+ globals()['_'+name] = func
544
+
545
+ def bytes_free_errcheck(res, func, *args):
546
+ notnull_errcheck(res, func, *args)
547
+ rv = cast(res, c_void_p).value
548
+ _mpv_free(res)
549
+ return rv
550
+
551
+ def notnull_errcheck(res, func, *args):
552
+ if res is None:
553
+ raise RuntimeError('Underspecified error in MPV when calling {} with args {!r}: NULL pointer returned.'\
554
+ 'Please consult your local debugger.'.format(func.__name__, args))
555
+ return res
556
+
557
+ ec_errcheck = ErrorCode.raise_for_ec
558
+
559
+ backend.mpv_client_api_version.restype = c_ulong
560
+ def _mpv_client_api_version():
561
+ ver = backend.mpv_client_api_version()
562
+ return ver>>16, ver&0xFFFF
563
+
564
+ MPV_VERSION = _mpv_client_api_version()
565
+ if MPV_VERSION < (1, 108):
566
+ ver = '.'.join(str(num) for num in MPV_VERSION)
567
+ raise RuntimeError(f"python-mpv requires libmpv with an API version of 1.108 or higher (libmpv >= 0.33), but you have an older version ({ver}).")
568
+
569
+ backend.mpv_free.argtypes = [c_void_p]
570
+ _mpv_free = backend.mpv_free
571
+
572
+ backend.mpv_free_node_contents.argtypes = [c_void_p]
573
+ _mpv_free_node_contents = backend.mpv_free_node_contents
574
+
575
+ backend.mpv_create.restype = MpvHandle
576
+ _mpv_create = backend.mpv_create
577
+
578
+ _handle_func('mpv_create_client', [c_char_p], MpvHandle, notnull_errcheck)
579
+ _handle_func('mpv_create_weak_client', [c_char_p], MpvHandle, notnull_errcheck)
580
+ _handle_func('mpv_client_name', [], c_char_p, errcheck=None)
581
+ _handle_func('mpv_initialize', [], c_int, ec_errcheck)
582
+ _handle_func('mpv_destroy', [], None, errcheck=None)
583
+ _handle_func('mpv_terminate_destroy', [], None, errcheck=None)
584
+ _handle_func('mpv_load_config_file', [c_char_p], c_int, ec_errcheck)
585
+ _handle_func('mpv_get_time_us', [], c_ulonglong, errcheck=None)
586
+
587
+ _handle_func('mpv_set_option', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
588
+ _handle_func('mpv_set_option_string', [c_char_p, c_char_p], c_int, ec_errcheck)
589
+
590
+ _handle_func('mpv_command', [POINTER(c_char_p)], c_int, ec_errcheck)
591
+ _handle_func('mpv_command_string', [c_char_p, c_char_p], c_int, ec_errcheck)
592
+ _handle_func('mpv_command_async', [c_ulonglong, POINTER(c_char_p)], c_int, ec_errcheck)
593
+ _handle_func('mpv_command_node', [POINTER(MpvNode), POINTER(MpvNode)], c_int, ec_errcheck)
594
+ _handle_func('mpv_command_node_async', [c_ulonglong, POINTER(MpvNode)], c_int, ec_errcheck)
595
+ _handle_func('mpv_abort_async_command', [c_ulonglong], None, errcheck=None)
596
+
597
+ _handle_func('mpv_set_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
598
+ _handle_func('mpv_set_property_string', [c_char_p, c_char_p], c_int, ec_errcheck)
599
+ _handle_func('mpv_set_property_async', [c_ulonglong, c_char_p, MpvFormat,c_void_p],c_int, ec_errcheck)
600
+ _handle_func('mpv_get_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
601
+ _handle_func('mpv_get_property_string', [c_char_p], c_void_p, bytes_free_errcheck)
602
+ _handle_func('mpv_get_property_osd_string', [c_char_p], c_void_p, bytes_free_errcheck)
603
+ _handle_func('mpv_get_property_async', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
604
+ _handle_func('mpv_observe_property', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
605
+ _handle_func('mpv_unobserve_property', [c_ulonglong], c_int, ec_errcheck)
606
+
607
+ _handle_func('mpv_event_name', [c_int], c_char_p, errcheck=None, ctx=None)
608
+ _handle_func('mpv_event_to_node', [POINTER(MpvNode), POINTER(MpvEvent)], c_int, ec_errcheck, ctx=None)
609
+ _handle_func('mpv_error_string', [c_int], c_char_p, errcheck=None, ctx=None)
610
+
611
+ _handle_func('mpv_request_event', [MpvEventID, c_int], c_int, ec_errcheck)
612
+ _handle_func('mpv_request_log_messages', [c_char_p], c_int, ec_errcheck)
613
+ _handle_func('mpv_wait_event', [c_double], POINTER(MpvEvent), errcheck=None)
614
+ _handle_func('mpv_wakeup', [], None, errcheck=None)
615
+ _handle_func('mpv_set_wakeup_callback', [WakeupCallback, c_void_p], None, errcheck=None)
616
+
617
+ _handle_func('mpv_stream_cb_add_ro', [c_char_p, c_void_p, StreamOpenFn], c_int, ec_errcheck)
618
+
619
+ _handle_func('mpv_render_context_create', [MpvRenderCtxHandle, MpvHandle, POINTER(MpvRenderParam)], c_int, ec_errcheck, ctx=None)
620
+ _handle_func('mpv_render_context_set_parameter', [MpvRenderParam], c_int, ec_errcheck, ctx=MpvRenderCtxHandle)
621
+ _handle_func('mpv_render_context_get_info', [MpvRenderParam], c_int, ec_errcheck, ctx=MpvRenderCtxHandle)
622
+ _handle_func('mpv_render_context_set_update_callback', [RenderUpdateFn, c_void_p], None, errcheck=None, ctx=MpvRenderCtxHandle)
623
+ _handle_func('mpv_render_context_update', [], c_int64, errcheck=None, ctx=MpvRenderCtxHandle)
624
+ _handle_func('mpv_render_context_render', [POINTER(MpvRenderParam)], c_int, ec_errcheck, ctx=MpvRenderCtxHandle)
625
+ _handle_func('mpv_render_context_report_swap', [], None, errcheck=None, ctx=MpvRenderCtxHandle)
626
+ _handle_func('mpv_render_context_free', [], None, errcheck=None, ctx=MpvRenderCtxHandle)
627
+
628
+
629
+ def _mpv_coax_proptype(value, proptype=str):
630
+ """Intelligently coax the given python value into something that can be understood as a proptype property."""
631
+ if type(value) is bytes:
632
+ return value;
633
+ elif type(value) is bool:
634
+ return b'yes' if value else b'no'
635
+ elif proptype in (str, int, float):
636
+ return str(proptype(value)).encode('utf-8')
637
+ else:
638
+ raise TypeError('Cannot coax value of type {} into property type {}'.format(type(value), proptype))
639
+
640
+ def _make_node_str_list(l):
641
+ """Take a list of python objects and make a MPV string node array from it.
642
+
643
+ As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object::
644
+
645
+ struct mpv_node {
646
+ .format = MPV_NODE_ARRAY,
647
+ .u.list = *(struct mpv_node_array){
648
+ .num = len(l),
649
+ .keys = NULL,
650
+ .values = struct mpv_node[len(l)] {
651
+ { .format = MPV_NODE_STRING, .u.string = l[0] },
652
+ { .format = MPV_NODE_STRING, .u.string = l[1] },
653
+ ...
654
+ }
655
+ }
656
+ }
657
+ """
658
+ char_ps = [ c_char_p(_mpv_coax_proptype(e, str)) for e in l ]
659
+ node_list = MpvNodeList(
660
+ num=len(l),
661
+ keys=None,
662
+ values=( MpvNode * len(l))( *[ MpvNode(
663
+ format=MpvFormat.STRING,
664
+ val=MpvNodeUnion(string=p))
665
+ for p in char_ps ]))
666
+ node = MpvNode(
667
+ format=MpvFormat.NODE_ARRAY,
668
+ val=MpvNodeUnion(list=pointer(node_list)))
669
+ return char_ps, node_list, node, cast(pointer(node), c_void_p)
670
+
671
+ def _make_node_str_map(d):
672
+ """Take a dict of python objects and make a MPV string node map from it. """
673
+ char_ps = [ (c_char_p(k.encode('utf-8')), c_char_p(_mpv_coax_proptype(v, str))) for k, v in d.items() ]
674
+ node_list = MpvNodeList(
675
+ num=len(d),
676
+ keys=( c_char_p * len(d))( *[k for k, v in char_ps] ),
677
+ values=( MpvNode * len(d))( *[ MpvNode(
678
+ format=MpvFormat.STRING,
679
+ val=MpvNodeUnion(string=v))
680
+ for k, v in char_ps ]))
681
+ node = MpvNode(
682
+ format=MpvFormat.NODE_MAP,
683
+ val=MpvNodeUnion(map=pointer(node_list)))
684
+ return char_ps, node_list, node, cast(pointer(node), c_void_p)
685
+
686
+
687
+ def _event_generator(handle):
688
+ while True:
689
+ event = _mpv_wait_event(handle, -1).contents
690
+ if event.event_id.value == MpvEventID.NONE:
691
+ raise StopIteration()
692
+ yield event
693
+
694
+
695
+ def _create_null_term_cmd_arg_array(name, args):
696
+ args = [name.encode('utf-8')] + [(arg if type(arg) is bytes else str(arg).encode('utf-8'))
697
+ for arg in args if arg is not None] + [None]
698
+ return (c_char_p * len(args))(*args)
699
+
700
+
701
+ _py_to_mpv = lambda name: name.replace('_', '-')
702
+ _mpv_to_py = lambda name: name.replace('-', '_')
703
+
704
+ _drop_nones = lambda *args: [ arg for arg in args if arg is not None ]
705
+
706
+ class _Proxy:
707
+ def __init__(self, mpv):
708
+ super().__setattr__('mpv', mpv)
709
+
710
+ class _PropertyProxy(_Proxy):
711
+ def __dir__(self):
712
+ return super().__dir__() + [ name.replace('-', '_') for name in self.mpv.property_list ]
713
+
714
+ class _FileLocalProxy(_Proxy):
715
+ def __getitem__(self, name):
716
+ return self.mpv.__getitem__(name, file_local=True)
717
+
718
+ def __setitem__(self, name, value):
719
+ return self.mpv.__setitem__(name, value, file_local=True)
720
+
721
+ def __iter__(self):
722
+ return iter(self.mpv)
723
+
724
+ class _OSDPropertyProxy(_PropertyProxy):
725
+ def __getattr__(self, name):
726
+ return self.mpv._get_property(_py_to_mpv(name), fmt=MpvFormat.OSD_STRING)
727
+
728
+ def __setattr__(self, _name, _value):
729
+ raise AttributeError('OSD properties are read-only. Please use the regular property API for writing.')
730
+
731
+ class _DecoderPropertyProxy(_PropertyProxy):
732
+ def __init__(self, mpv, decoder):
733
+ super().__init__(mpv)
734
+ super().__setattr__('_decoder', decoder)
735
+
736
+ def __getattr__(self, name):
737
+ return self.mpv._get_property(_py_to_mpv(name), decoder=self._decoder)
738
+
739
+ def __setattr__(self, name, value):
740
+ setattr(self.mpv, _py_to_mpv(name), value)
741
+
742
+ class GeneratorStream:
743
+ """Transform a python generator into an mpv-compatible stream object. The total size of the file can be indicated to
744
+ mpv using the size argument to __init__. Seeking is not supported.
745
+ """
746
+
747
+ def __init__(self, generator_fun, size=None):
748
+ self._generator_fun = generator_fun
749
+ self.size = size
750
+
751
+ def seek(self, offset):
752
+ self._read_iter = iter(self._generator_fun())
753
+ self._read_chunk = b''
754
+ return 0 # We only support seeking to the first byte atm
755
+ # implementation in case seeking to arbitrary offsets would be necessary
756
+ # while offset > 0:
757
+ # offset -= len(self.read(offset))
758
+ # return offset
759
+
760
+ def read(self, size):
761
+ if not self._read_chunk:
762
+ try:
763
+ self._read_chunk += next(self._read_iter)
764
+ except StopIteration:
765
+ return b''
766
+ rv, self._read_chunk = self._read_chunk[:size], self._read_chunk[size:]
767
+ return rv
768
+
769
+ def close(self):
770
+ self._read_iter = iter([]) # make next read() call return EOF
771
+
772
+ def cancel(self):
773
+ self._read_iter = iter([]) # make next read() call return EOF
774
+
775
+
776
+ class ImageOverlay:
777
+ def __init__(self, m, overlay_id, img=None, pos=(0, 0)):
778
+ self.m = m
779
+ self.overlay_id = overlay_id
780
+ self.pos = pos
781
+ self._size = None
782
+ if img is not None:
783
+ self.update(img)
784
+
785
+ def update(self, img=None, pos=None):
786
+ from PIL import Image
787
+ if img is not None:
788
+ self.img = img
789
+ img = self.img
790
+
791
+ w, h = img.size
792
+ stride = w*4
793
+
794
+ if pos is not None:
795
+ self.pos = pos
796
+ x, y = self.pos
797
+
798
+ # Pre-multiply alpha channel
799
+ bg = Image.new('RGBA', (w, h), (0, 0, 0, 0))
800
+ out = Image.alpha_composite(bg, img)
801
+
802
+ # Copy image to ctypes buffer
803
+ if img.size != self._size:
804
+ self._buf = create_string_buffer(w*h*4)
805
+ self._size = img.size
806
+
807
+ ctypes.memmove(self._buf, out.tobytes('raw', 'BGRA'), w*h*4)
808
+ source = '&' + str(addressof(self._buf))
809
+
810
+ self.m.overlay_add(self.overlay_id, x, y, source, 0, 'bgra', w, h, stride)
811
+
812
+ def remove(self):
813
+ self.m.remove_overlay(self.overlay_id)
814
+
815
+
816
+ class FileOverlay:
817
+ def __init__(self, m, overlay_id, filename=None, size=None, stride=None, pos=(0,0)):
818
+ self.m = m
819
+ self.overlay_id = overlay_id
820
+ self.pos = pos
821
+ self.size = size
822
+ self.stride = stride
823
+ if filename is not None:
824
+ self.update(filename)
825
+
826
+ def update(self, filename=None, size=None, stride=None, pos=None):
827
+ if filename is not None:
828
+ self.filename = filename
829
+
830
+ if pos is not None:
831
+ self.pos = pos
832
+
833
+ if size is not None:
834
+ self.size = size
835
+
836
+ if stride is not None:
837
+ self.stride = stride
838
+
839
+ x, y = self.pos
840
+ w, h = self.size
841
+ stride = self.stride or 4*w
842
+
843
+ self.m.overlay_add(self, self.overlay_id, x, y, self.filename, 0, 'bgra', w, h, stride)
844
+
845
+ def remove(self):
846
+ self.m.remove_overlay(self.overlay_id)
847
+
848
+
849
+ class MPV(object):
850
+ """See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
851
+ ``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
852
+
853
+ By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
854
+ utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
855
+ ``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
856
+ property's decoded OSD value, use ``my_mpv.osd.some_property``.
857
+
858
+ To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
859
+ property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
860
+ underscore_names exposed on the python object.
861
+
862
+ To make your program not barf hard the first time its used on a weird file system **always** access properties
863
+ containing file names or file tags through ``MPV.raw``. """
864
+
865
+ def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
866
+ """Create an MPV instance.
867
+
868
+ Extra arguments and extra keyword arguments will be passed to mpv as options.
869
+ """
870
+
871
+ self.handle = _mpv_create()
872
+ self._event_thread = None
873
+ self._core_shutdown = False
874
+
875
+ _mpv_set_option_string(self.handle, b'audio-display', b'no')
876
+ istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
877
+ try:
878
+ for flag in extra_mpv_flags:
879
+ _mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
880
+ for k,v in extra_mpv_opts.items():
881
+ _mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
882
+ finally:
883
+ _mpv_initialize(self.handle)
884
+
885
+ self.osd = _OSDPropertyProxy(self)
886
+ self.file_local = _FileLocalProxy(self)
887
+ self.raw = _DecoderPropertyProxy(self, identity_decoder)
888
+ self.strict = _DecoderPropertyProxy(self, strict_decoder)
889
+ self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
890
+
891
+ self._event_callbacks = []
892
+ self._command_reply_callbacks = {}
893
+ self._event_handler_lock = threading.Lock()
894
+ self._property_handlers = collections.defaultdict(lambda: [])
895
+ self._quit_handlers = set()
896
+ self._message_handlers = {}
897
+ self._key_binding_handlers = {}
898
+ self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
899
+ self._log_handler = log_handler
900
+ self._stream_protocol_cbs = {}
901
+ self._stream_protocol_frontends = collections.defaultdict(lambda: {})
902
+ self.register_stream_protocol('python', self._python_stream_open)
903
+ self._python_streams = {}
904
+ self._python_stream_catchall = None
905
+ self._exception_futures = set()
906
+ self.overlay_ids = set()
907
+ self.overlays = {}
908
+ if loglevel is not None or log_handler is not None:
909
+ self.set_loglevel(loglevel or 'terminal-default')
910
+ if start_event_thread:
911
+ self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
912
+ self._event_thread.daemon = True
913
+ self._event_thread.start()
914
+ else:
915
+ self._event_thread = None
916
+ if (m := re.search(r'(\d+)\.(\d+)\.(\d+)', self.mpv_version)):
917
+ self.mpv_version_tuple = tuple(map(int, m.groups()))
918
+
919
+ @contextmanager
920
+ def _enqueue_exceptions(self):
921
+ try:
922
+ yield
923
+ except Exception as e:
924
+ for fut in self._exception_futures:
925
+ try:
926
+ fut.set_exception(e)
927
+ break
928
+ except InvalidStateError:
929
+ pass
930
+ else:
931
+ warn(f'Unhandled exception on python-mpv event loop: {e}\n{traceback.format_exc()}', RuntimeWarning)
932
+
933
+ def _loop(self):
934
+ for event in _event_generator(self._event_handle):
935
+ try:
936
+ eid = event.event_id.value
937
+
938
+ with self._event_handler_lock:
939
+ if eid == MpvEventID.SHUTDOWN:
940
+ self._core_shutdown = True
941
+
942
+ for callback in self._event_callbacks:
943
+ with self._enqueue_exceptions():
944
+ callback(event)
945
+
946
+ if eid == MpvEventID.PROPERTY_CHANGE:
947
+ pc = event.data
948
+ name, value, _fmt = pc.name, pc.value, pc.format
949
+ for handler in self._property_handlers[name]:
950
+ with self._enqueue_exceptions():
951
+ handler(name, value)
952
+
953
+ if eid == MpvEventID.LOG_MESSAGE and self._log_handler is not None:
954
+ ev = event.data
955
+ with self._enqueue_exceptions():
956
+ self._log_handler(ev.level, ev.prefix, ev.text)
957
+
958
+ if eid == MpvEventID.CLIENT_MESSAGE:
959
+ # {'event': {'args': ['key-binding', 'foo', 'u-', 'g']}, 'reply_userdata': 0, 'error': 0, 'event_id': 16}
960
+ target, *args = event.data.args
961
+ target = target.decode("utf-8")
962
+ if target in self._message_handlers:
963
+ with self._enqueue_exceptions():
964
+ self._message_handlers[target](*args)
965
+
966
+ if eid == MpvEventID.COMMAND_REPLY:
967
+ key = event.reply_userdata
968
+ callback = self._command_reply_callbacks.pop(key, None)
969
+ if callback:
970
+ with self._enqueue_exceptions():
971
+ callback(ErrorCode.exception_for_ec(event.error), event.data)
972
+
973
+ if eid == MpvEventID.QUEUE_OVERFLOW:
974
+ # cache list, since error handlers will unregister themselves
975
+ for cb in list(self._command_reply_callbacks.values()):
976
+ with self._enqueue_exceptions():
977
+ cb(EventOverflowError('libmpv event queue has flown over because events have not been processed fast enough'), None)
978
+
979
+ if eid == MpvEventID.SHUTDOWN:
980
+ _mpv_destroy(self._event_handle)
981
+ for cb in list(self._command_reply_callbacks.values()):
982
+ with self._enqueue_exceptions():
983
+ cb(ShutdownError('libmpv core has been shutdown'), None)
984
+ return
985
+
986
+ except Exception as e:
987
+ warn(f'Unhandled {e} inside python-mpv event loop!\n{traceback.format_exc()}', RuntimeWarning)
988
+
989
+ @property
990
+ def core_shutdown(self):
991
+ """Property indicating whether the core has been shut down. Possible causes for this are e.g. the `quit` command
992
+ or a user closing the mpv window."""
993
+ return self._core_shutdown
994
+
995
+ def check_core_alive(self):
996
+ """ This method can be used as a sanity check to tests whether the core is still alive at the time it is
997
+ called."""
998
+ if self._core_shutdown:
999
+ raise ShutdownError('libmpv core has been shutdown')
1000
+
1001
+ def wait_until_paused(self, timeout=None, catch_errors=True):
1002
+ """Waits until playback of the current title is paused or done. Raises a ShutdownError if the core is shutdown while
1003
+ waiting."""
1004
+ self.wait_for_property('core-idle', timeout=timeout, catch_errors=catch_errors)
1005
+
1006
+ def wait_for_playback(self, timeout=None, catch_errors=True):
1007
+ """Waits until playback of the current title is finished. Raises a ShutdownError if the core is shutdown while
1008
+ waiting.
1009
+ """
1010
+ self.wait_for_event('end_file', timeout=timeout, catch_errors=catch_errors)
1011
+
1012
+ def wait_until_playing(self, timeout=None, catch_errors=True):
1013
+ """Waits until playback of the current title has started. Raises a ShutdownError if the core is shutdown while
1014
+ waiting."""
1015
+ self.wait_for_property('core-idle', lambda idle: not idle, timeout=timeout, catch_errors=catch_errors)
1016
+
1017
+ def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True, timeout=None, catch_errors=True):
1018
+ """Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
1019
+ properties such as ``idle_active`` indicating the player is done with regular playback and just idling around.
1020
+ Raises a ShutdownError when the core is shutdown while waiting.
1021
+ """
1022
+ with self.prepare_and_wait_for_property(name, cond, level_sensitive, timeout=timeout, catch_errors=catch_errors) as result:
1023
+ pass
1024
+ return result.result()
1025
+
1026
+ def wait_for_shutdown(self, timeout=None, catch_errors=True):
1027
+ '''Wait for core to shutdown (e.g. through quit() or terminate()).'''
1028
+ try:
1029
+ self.wait_for_event(None, timeout=timeout, catch_errors=catch_errors)
1030
+ except ShutdownError:
1031
+ return
1032
+
1033
+ def _set_error_handler(self, future):
1034
+ @self.event_callback('shutdown', 'queue-overflow')
1035
+ def shutdown_handler(event):
1036
+ nonlocal future
1037
+ try:
1038
+ if event.event_id.value == MpvEventID.SHUTDOWN:
1039
+ future.set_exception(ShutdownError('libmpv core has been shutdown'))
1040
+ else:
1041
+ future.set_exception(EventOverflowError('libmpv event queue has flown over because events have not been processed fast enough'))
1042
+ except InvalidStateError:
1043
+ pass
1044
+ return shutdown_handler.unregister_mpv_events
1045
+
1046
+ @contextmanager
1047
+ def prepare_and_wait_for_property(self, name, cond=lambda val: val, level_sensitive=True, timeout=None, catch_errors=True):
1048
+ """Context manager that waits until ``cond`` evaluates to a truthy value on the named property. See
1049
+ prepare_and_wait_for_event for usage.
1050
+ Raises a ShutdownError when the core is shutdown while waiting. Re-raises any errors inside ``cond``.
1051
+ """
1052
+ result = Future()
1053
+
1054
+ def observer(name, val):
1055
+ try:
1056
+ rv = cond(val)
1057
+ if rv:
1058
+ result.set_result(rv)
1059
+
1060
+ except InvalidStateError:
1061
+ pass
1062
+
1063
+ except Exception as e:
1064
+ try:
1065
+ result.set_exception(e)
1066
+ except:
1067
+ pass
1068
+
1069
+ try:
1070
+ result.set_running_or_notify_cancel()
1071
+
1072
+ self.observe_property(name, observer)
1073
+ err_unregister = self._set_error_handler(result)
1074
+ if catch_errors:
1075
+ self._exception_futures.add(result)
1076
+
1077
+ yield result
1078
+
1079
+ if level_sensitive:
1080
+ rv = cond(getattr(self, name.replace('-', '_')))
1081
+ if rv:
1082
+ result.set_result(rv)
1083
+ return
1084
+
1085
+ self.check_core_alive()
1086
+ result.result(timeout)
1087
+
1088
+ except InvalidStateError:
1089
+ pass
1090
+
1091
+ finally:
1092
+ err_unregister()
1093
+ self.unobserve_property(name, observer)
1094
+ self._exception_futures.discard(result)
1095
+
1096
+ def wait_for_event(self, *event_types, cond=lambda evt: True, timeout=None, catch_errors=True):
1097
+ """Waits for the indicated event(s). If cond is given, waits until cond(event) is true. Raises a ShutdownError
1098
+ if the core is shutdown while waiting. This also happens when 'shutdown' is in event_types. Re-raises any error
1099
+ inside ``cond``.
1100
+ """
1101
+ with self.prepare_and_wait_for_event(*event_types, cond=cond, timeout=timeout, catch_errors=catch_errors) as result:
1102
+ pass
1103
+ return result.result()
1104
+
1105
+ @contextmanager
1106
+ def prepare_and_wait_for_event(self, *event_types, cond=lambda evt: True, timeout=None, catch_errors=True):
1107
+ """Context manager that waits for the indicated event(s) like wait_for_event after running. If cond is given,
1108
+ waits until cond(event) is true. Raises a ShutdownError if the core is shutdown while waiting. This also happens
1109
+ when 'shutdown' is in event_types. Re-raises any error inside ``cond``.
1110
+
1111
+ Compared to wait_for_event this handles the case where a thread waits for an event it itself causes in a
1112
+ thread-safe way. An example from the testsuite is:
1113
+
1114
+ with self.m.prepare_and_wait_for_event('client_message'):
1115
+ self.m.keypress(key)
1116
+
1117
+ Using just wait_for_event it would be impossible to ensure the event is caught since it may already have been
1118
+ handled in the interval between keypress(...) running and a subsequent wait_for_event(...) call.
1119
+ """
1120
+ result = Future()
1121
+
1122
+ @self.event_callback(*event_types)
1123
+ def target_handler(evt):
1124
+ try:
1125
+ rv = cond(evt)
1126
+ if rv:
1127
+ result.set_result(rv)
1128
+ except Exception as e:
1129
+ try:
1130
+ result.set_exception(e)
1131
+ except InvalidStateError:
1132
+ pass
1133
+ except InvalidStateError:
1134
+ pass
1135
+
1136
+ err_unregister = self._set_error_handler(result)
1137
+
1138
+ try:
1139
+ result.set_running_or_notify_cancel()
1140
+ if catch_errors:
1141
+ self._exception_futures.add(result)
1142
+
1143
+ yield result
1144
+
1145
+ self.check_core_alive()
1146
+ result.result(timeout)
1147
+
1148
+ finally:
1149
+ err_unregister()
1150
+ target_handler.unregister_mpv_events()
1151
+ self._exception_futures.discard(result)
1152
+
1153
+ def __del__(self):
1154
+ if self.handle:
1155
+ self.terminate()
1156
+
1157
+ def terminate(self):
1158
+ """Properly terminates this player instance. Preferably use this instead of relying on python's garbage
1159
+ collector to cause this to be called from the object's destructor.
1160
+
1161
+ This method will detach the main libmpv handle and wait for mpv to shut down and the event thread to finish.
1162
+ """
1163
+ self.handle, handle = None, self.handle
1164
+ if threading.current_thread() is self._event_thread:
1165
+ raise UserWarning('terminate() should not be called from event thread (e.g. from a callback function). If '
1166
+ 'you want to terminate mpv from here, please call quit() instead, then sync the main thread '
1167
+ 'against the event thread using e.g. wait_for_shutdown(), then terminate() from the main thread. '
1168
+ 'This call has been transformed into a call to quit().')
1169
+ self.quit()
1170
+ else:
1171
+ _mpv_terminate_destroy(handle)
1172
+ if self._event_thread:
1173
+ self._event_thread.join()
1174
+
1175
+ def set_loglevel(self, level):
1176
+ """Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
1177
+ mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
1178
+ constructur such as ``MPV(log_handler=print)``.
1179
+
1180
+ Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
1181
+ client.h header file.
1182
+ """
1183
+ _mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
1184
+
1185
+ def string_command(self, name, *args):
1186
+ """Execute a raw command."""
1187
+ args = _create_null_term_cmd_arg_array(name, args)
1188
+ _mpv_command(self.handle, args)
1189
+
1190
+ def command_async(self, name, *args, callback=None, decoder=lazy_decoder, **kwargs):
1191
+ """Same as mpv_command, but run the command asynchronously. If you provide a callback, that callback will be
1192
+ called after completion or on error. This method returns a future that evaluates to the result of the callback
1193
+ (if given), and the result of the libmpv call otherwise.
1194
+
1195
+ Usage example:
1196
+
1197
+ future = player.command_async(...)
1198
+ try:
1199
+ print('The result was', future.result())
1200
+ except Exception as e:
1201
+ print('mpv returned an error:', e)
1202
+ """
1203
+
1204
+ future = Future()
1205
+ future.set_running_or_notify_cancel()
1206
+
1207
+ if callback is None:
1208
+ def callback(error, result):
1209
+ if error:
1210
+ raise error
1211
+ return result
1212
+
1213
+ def wrapper(error, result):
1214
+ try:
1215
+ result = result.unpack(decoder)
1216
+ future.set_result(callback(error, result))
1217
+ except Exception as e:
1218
+ try:
1219
+ future.set_exception(e)
1220
+ except InvalidStateError:
1221
+ pass
1222
+
1223
+ def abort():
1224
+ _mpv_abort_async_command(self._event_handle, id(future))
1225
+ del self._command_reply_callbacks[id(future)]
1226
+ future.cancel = abort
1227
+
1228
+ self._command_reply_callbacks[id(future)] = wrapper
1229
+
1230
+ if kwargs:
1231
+ if args:
1232
+ raise ValueError('Can only call mpv commands either using positional or using named arguments, not a mix of both.')
1233
+ kwargs['name'] = name
1234
+ _1, _2, _3, pointer = _make_node_str_map(kwargs)
1235
+ else:
1236
+ _1, _2, _3, pointer = _make_node_str_list([name, *args])
1237
+
1238
+ ppointer = cast(pointer, POINTER(MpvNode))
1239
+ _mpv_command_node_async(self._event_handle, id(future), ppointer)
1240
+ return future
1241
+
1242
+
1243
+ def node_command(self, name, *args, decoder=strict_decoder):
1244
+ self.command(name, *args, decoder=decoder)
1245
+
1246
+ def command(self, name, *args, decoder=strict_decoder, **kwargs):
1247
+ if kwargs:
1248
+ if args:
1249
+ raise ValueError('Can only call mpv commands either using positional or using named arguments, not a mix of both.')
1250
+ kwargs['name'] = name
1251
+ _1, _2, _3, pointer = _make_node_str_map(kwargs)
1252
+ else:
1253
+ _1, _2, _3, pointer = _make_node_str_list([name, *args])
1254
+
1255
+ out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
1256
+ ppointer = cast(pointer, POINTER(MpvNode))
1257
+ _mpv_command_node(self.handle, ppointer, out)
1258
+ rv = out.contents.node_value(decoder=decoder)
1259
+ _mpv_free_node_contents(out)
1260
+ return rv
1261
+
1262
+ def seek(self, amount, reference="relative", precision="keyframes"):
1263
+ """Mapped mpv seek command, see man mpv(1)."""
1264
+ self.command('seek', amount, reference, precision)
1265
+
1266
+ def revert_seek(self):
1267
+ """Mapped mpv revert_seek command, see man mpv(1)."""
1268
+ self.command('revert_seek');
1269
+
1270
+ def frame_step(self):
1271
+ """Mapped mpv frame-step command, see man mpv(1)."""
1272
+ self.command('frame-step')
1273
+
1274
+ def frame_back_step(self):
1275
+ """Mapped mpv frame_back_step command, see man mpv(1)."""
1276
+ self.command('frame_back_step')
1277
+
1278
+ def property_add(self, name, value=1):
1279
+ """Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
1280
+ ``value`` is omitted, assume ``1``.
1281
+ """
1282
+ self.command('add', name, value)
1283
+
1284
+ def property_multiply(self, name, factor):
1285
+ """Multiply the value of a property with a numeric factor."""
1286
+ self.command('multiply', name, factor)
1287
+
1288
+ def cycle(self, name, direction='up'):
1289
+ """Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
1290
+ the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
1291
+ """
1292
+ self.command('cycle', name, direction)
1293
+
1294
+ def screenshot(self, includes='subtitles', mode='single'):
1295
+ """Mapped mpv screenshot command, see man mpv(1)."""
1296
+ self.command('screenshot', includes, mode)
1297
+
1298
+ def screenshot_to_file(self, filename, includes='subtitles'):
1299
+ """Mapped mpv screenshot_to_file command, see man mpv(1)."""
1300
+ self.command('screenshot_to_file', filename.encode(fs_enc), includes)
1301
+
1302
+ def screenshot_raw(self, includes='subtitles'):
1303
+ """Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
1304
+ from PIL import Image
1305
+ res = self.command('screenshot-raw', includes)
1306
+ if res['format'] != 'bgr0':
1307
+ raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
1308
+ .format(res['format']))
1309
+ img = Image.frombytes('RGBA', (res['stride']//4, res['h']), res['data'])
1310
+ b,g,r,a = img.split()
1311
+ return Image.merge('RGB', (r,g,b))
1312
+
1313
+ def allocate_overlay_id(self):
1314
+ free_ids = set(range(64)) - self.overlay_ids
1315
+ if not free_ids:
1316
+ raise IndexError('All overlay IDs are in use')
1317
+ next_id, *_ = sorted(free_ids)
1318
+ self.overlay_ids.add(next_id)
1319
+ return next_id
1320
+
1321
+ def free_overlay_id(self, overlay_id):
1322
+ self.overlay_ids.remove(overlay_id)
1323
+
1324
+ def create_file_overlay(self, filename=None, size=None, stride=None, pos=(0,0)):
1325
+ overlay_id = self.allocate_overlay_id()
1326
+ overlay = FileOverlay(self, overlay_id, filename, size, stride, pos)
1327
+ self.overlays[overlay_id] = overlay
1328
+ return overlay
1329
+
1330
+ def create_image_overlay(self, img=None, pos=(0,0)):
1331
+ overlay_id = self.allocate_overlay_id()
1332
+ overlay = ImageOverlay(self, overlay_id, img, pos)
1333
+ self.overlays[overlay_id] = overlay
1334
+ return overlay
1335
+
1336
+ def remove_overlay(self, overlay_id):
1337
+ self.overlay_remove(overlay_id)
1338
+ self.free_overlay_id(overlay_id)
1339
+ del self.overlays[overlay_id]
1340
+
1341
+ def playlist_next(self, mode='weak'):
1342
+ """Mapped mpv playlist_next command, see man mpv(1)."""
1343
+ self.command('playlist_next', mode)
1344
+
1345
+ def playlist_prev(self, mode='weak'):
1346
+ """Mapped mpv playlist_prev command, see man mpv(1)."""
1347
+ self.command('playlist_prev', mode)
1348
+
1349
+ def playlist_play_index(self, idx):
1350
+ """Mapped mpv playlist-play-index command, see man mpv(1)."""
1351
+ self.command('playlist-play-index', idx)
1352
+
1353
+ @staticmethod
1354
+ def _encode_options(options):
1355
+ return ','.join('{}={}'.format(_py_to_mpv(str(key)), str(val)) for key, val in options.items())
1356
+
1357
+ def loadfile(self, filename, mode='replace', index=None, **options):
1358
+ """Mapped mpv loadfile command, see man mpv(1)."""
1359
+ if self.mpv_version_tuple >= (0, 38, 0):
1360
+ if index is None:
1361
+ index = -1
1362
+ self.command('loadfile', filename.encode(fs_enc), mode, index, MPV._encode_options(options))
1363
+ else:
1364
+ if index is not None:
1365
+ warn(f'The index argument to the loadfile command is only supported on mpv >= 0.38.0')
1366
+ self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
1367
+
1368
+ def loadlist(self, playlist, mode='replace'):
1369
+ """Mapped mpv loadlist command, see man mpv(1)."""
1370
+ self.command('loadlist', playlist.encode(fs_enc), mode)
1371
+
1372
+ def playlist_clear(self):
1373
+ """Mapped mpv playlist_clear command, see man mpv(1)."""
1374
+ self.command('playlist_clear')
1375
+
1376
+ def playlist_remove(self, index='current'):
1377
+ """Mapped mpv playlist_remove command, see man mpv(1)."""
1378
+ self.command('playlist_remove', index)
1379
+
1380
+ def playlist_move(self, index1, index2):
1381
+ """Mapped mpv playlist_move command, see man mpv(1)."""
1382
+ self.command('playlist_move', index1, index2)
1383
+
1384
+ def playlist_shuffle(self):
1385
+ """Mapped mpv playlist-shuffle command, see man mpv(1)."""
1386
+ self.command('playlist-shuffle')
1387
+
1388
+ def playlist_unshuffle(self):
1389
+ """Mapped mpv playlist-unshuffle command, see man mpv(1)."""
1390
+ self.command('playlist-unshuffle')
1391
+
1392
+ def run(self, command, *args):
1393
+ """Mapped mpv run command, see man mpv(1)."""
1394
+ self.command('run', command, *args)
1395
+
1396
+ def quit(self, code=None):
1397
+ """Mapped mpv quit command, see man mpv(1)."""
1398
+ if code is not None:
1399
+ self.command('quit', code)
1400
+ else:
1401
+ self.command('quit')
1402
+
1403
+ def quit_watch_later(self, code=None):
1404
+ """Mapped mpv quit_watch_later command, see man mpv(1)."""
1405
+ if code is not None:
1406
+ self.command('quit_watch_later', code)
1407
+ else:
1408
+ self.command('quit_watch_later')
1409
+
1410
+ def stop(self, keep_playlist=False):
1411
+ """Mapped mpv stop command, see man mpv(1)."""
1412
+ if keep_playlist:
1413
+ self.command('stop', 'keep-playlist')
1414
+ else:
1415
+ self.command('stop')
1416
+
1417
+ def audio_add(self, url, flags='select', title=None, lang=None):
1418
+ """Mapped mpv audio_add command, see man mpv(1)."""
1419
+ self.command('audio_add', url.encode(fs_enc), *_drop_nones(flags, title, lang))
1420
+
1421
+ def audio_remove(self, audio_id=None):
1422
+ """Mapped mpv audio_remove command, see man mpv(1)."""
1423
+ self.command('audio_remove', audio_id)
1424
+
1425
+ def audio_reload(self, audio_id=None):
1426
+ """Mapped mpv audio_reload command, see man mpv(1)."""
1427
+ self.command('audio_reload', audio_id)
1428
+
1429
+ def video_add(self, url, flags='select', title=None, lang=None, albumart=None):
1430
+ """Mapped mpv video_add command, see man mpv(1)."""
1431
+ self.command('video_add', url.encode(fs_enc), *_drop_nones(flags, title, lang, albumart))
1432
+
1433
+ def video_remove(self, video_id=None):
1434
+ """Mapped mpv video_remove command, see man mpv(1)."""
1435
+ self.command('video_remove', video_id)
1436
+
1437
+ def video_reload(self, video_id=None):
1438
+ """Mapped mpv video_reload command, see man mpv(1)."""
1439
+ self.command('video_reload', video_id)
1440
+
1441
+ def sub_add(self, url, flags='select', title=None, lang=None):
1442
+ """Mapped mpv sub_add command, see man mpv(1)."""
1443
+ self.command('sub_add', url.encode(fs_enc), *_drop_nones(flags, title, lang))
1444
+
1445
+ def sub_remove(self, sub_id=None):
1446
+ """Mapped mpv sub_remove command, see man mpv(1)."""
1447
+ self.command('sub_remove', sub_id)
1448
+
1449
+ def sub_reload(self, sub_id=None):
1450
+ """Mapped mpv sub_reload command, see man mpv(1)."""
1451
+ self.command('sub_reload', sub_id)
1452
+
1453
+ def sub_step(self, skip):
1454
+ """Mapped mpv sub_step command, see man mpv(1)."""
1455
+ self.command('sub_step', skip)
1456
+
1457
+ def sub_seek(self, skip):
1458
+ """Mapped mpv sub_seek command, see man mpv(1)."""
1459
+ self.command('sub_seek', skip)
1460
+
1461
+ def toggle_osd(self):
1462
+ """Mapped mpv osd command, see man mpv(1)."""
1463
+ self.command('osd')
1464
+
1465
+ def print_text(self, text):
1466
+ """Mapped mpv print-text command, see man mpv(1)."""
1467
+ self.command('print-text', text)
1468
+
1469
+ def show_text(self, string, duration='-1', level=0):
1470
+ """Mapped mpv show_text command, see man mpv(1)."""
1471
+ self.command('show_text', string, duration, level)
1472
+
1473
+ def expand_text(self, text):
1474
+ """Mapped mpv expand-text command, see man mpv(1)."""
1475
+ return self.command('expand-text', text)
1476
+
1477
+ def expand_path(self, path):
1478
+ """Mapped mpv expand-path command, see man mpv(1)."""
1479
+ return self.command('expand-path', path)
1480
+
1481
+ def show_progress(self):
1482
+ """Mapped mpv show_progress command, see man mpv(1)."""
1483
+ self.command('show_progress')
1484
+
1485
+ def rescan_external_files(self, mode='reselect'):
1486
+ """Mapped mpv rescan-external-files command, see man mpv(1)."""
1487
+ self.command('rescan-external-files', mode)
1488
+
1489
+ def discnav(self, command):
1490
+ """Mapped mpv discnav command, see man mpv(1)."""
1491
+ self.command('discnav', command)
1492
+
1493
+ def mouse(self, x, y, button=None, mode='single'):
1494
+ """Mapped mpv mouse command, see man mpv(1)."""
1495
+ if button is None:
1496
+ self.command('mouse', x, y, mode)
1497
+ else:
1498
+ self.command('mouse', x, y, button, mode)
1499
+
1500
+ def keypress(self, name):
1501
+ """Mapped mpv keypress command, see man mpv(1)."""
1502
+ self.command('keypress', name)
1503
+
1504
+ def keydown(self, name):
1505
+ """Mapped mpv keydown command, see man mpv(1)."""
1506
+ self.command('keydown', name)
1507
+
1508
+ def keyup(self, name=None):
1509
+ """Mapped mpv keyup command, see man mpv(1)."""
1510
+ if name is None:
1511
+ self.command('keyup')
1512
+ else:
1513
+ self.command('keyup', name)
1514
+
1515
+ def keybind(self, name, command):
1516
+ """Mapped mpv keybind command, see man mpv(1)."""
1517
+ self.command('keybind', name, command)
1518
+
1519
+ def write_watch_later_config(self):
1520
+ """Mapped mpv write_watch_later_config command, see man mpv(1)."""
1521
+ self.command('write_watch_later_config')
1522
+
1523
+ def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
1524
+ """Mapped mpv overlay_add command, see man mpv(1)."""
1525
+ self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
1526
+
1527
+ def overlay_remove(self, overlay_id):
1528
+ """Mapped mpv overlay_remove command, see man mpv(1)."""
1529
+ self.command('overlay_remove', overlay_id)
1530
+
1531
+ def osd_overlay(self, overlay_id, data, res_x=0, res_y=720, z=0, hidden=False):
1532
+ self.command('osd_overlay', id=overlay_id, data=data, res_x=res_x, res_y=res_Y, z=z, hidden=hidden,
1533
+ format='ass-events')
1534
+
1535
+ def osd_overlay_remove(self, overlay_id):
1536
+ self.command('osd_overlay', id=overlay_id, format='none')
1537
+
1538
+ def script_message(self, *args):
1539
+ """Mapped mpv script_message command, see man mpv(1)."""
1540
+ self.command('script_message', *args)
1541
+
1542
+ def script_message_to(self, target, *args):
1543
+ """Mapped mpv script_message_to command, see man mpv(1)."""
1544
+ self.command('script_message_to', target, *args)
1545
+
1546
+ def drop_buffers(self):
1547
+ self.command('drop_buffers')
1548
+
1549
+ def vf_command(self, label, command, argument):
1550
+ self.command('vf_command', label, command, argument)
1551
+
1552
+ def af_command(self, label, command, argument):
1553
+ self.command('af_command', label, command, argument)
1554
+
1555
+ def observe_property(self, name, handler):
1556
+ """Register an observer on the named property. An observer is a function that is called with the new property
1557
+ value every time the property's value is changed. The basic function signature is ``fun(property_name,
1558
+ new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
1559
+ function decorator if no handler is given.
1560
+
1561
+ To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
1562
+ ``mpv.unobserve_all_properties(handler)`` or the handler's ``unobserve_mpv_properties`` attribute::
1563
+
1564
+ @player.property_observer('volume')
1565
+ def my_handler(property_name, new_volume):
1566
+ print("It's loud!", new_volume)
1567
+
1568
+ my_handler.unobserve_mpv_properties()
1569
+
1570
+ exit_handler is a function taking no arguments that is called when the underlying mpv handle is terminated (e.g.
1571
+ from calling MPV.terminate() or issuing a "quit" input command).
1572
+ """
1573
+ self._property_handlers[name].append(handler)
1574
+ _mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
1575
+
1576
+ def property_observer(self, name):
1577
+ """Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
1578
+ def wrapper(fun):
1579
+ self.observe_property(name, fun)
1580
+ fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
1581
+ return fun
1582
+ return wrapper
1583
+
1584
+ def unobserve_property(self, name, handler):
1585
+ """Unregister a property observer. This requires both the observed property's name and the handler function that
1586
+ was originally registered as one handler could be registered for several properties. To unregister a handler
1587
+ from *all* observed properties see ``unobserve_all_properties``.
1588
+ """
1589
+ self._property_handlers[name].remove(handler)
1590
+ if not self._property_handlers[name]:
1591
+ _mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
1592
+
1593
+ def unobserve_all_properties(self, handler):
1594
+ """Unregister a property observer from *all* observed properties."""
1595
+ for name in self._property_handlers:
1596
+ self.unobserve_property(name, handler)
1597
+
1598
+ def register_message_handler(self, target, handler=None):
1599
+ """Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
1600
+ script message target name this handler should be listening to and the handler function.
1601
+
1602
+ WARNING: Only one handler can be registered at a time for any given target.
1603
+
1604
+ To unregister the message handler, call its ``unregister_mpv_messages`` function::
1605
+
1606
+ player = mpv.MPV()
1607
+ @player.message_handler('foo')
1608
+ def my_handler(some, args):
1609
+ print(args)
1610
+
1611
+ my_handler.unregister_mpv_messages()
1612
+ """
1613
+ self._register_message_handler_internal(target, handler)
1614
+
1615
+ def _register_message_handler_internal(self, target, handler):
1616
+ self._message_handlers[target] = handler
1617
+
1618
+ def unregister_message_handler(self, target_or_handler):
1619
+ """Unregister a mpv script message handler for the given script message target name.
1620
+
1621
+ You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
1622
+ registered.
1623
+ """
1624
+ if isinstance(target_or_handler, str):
1625
+ del self._message_handlers[target_or_handler]
1626
+ else:
1627
+ for key, val in self._message_handlers.items():
1628
+ if val == target_or_handler:
1629
+ del self._message_handlers[key]
1630
+
1631
+ def message_handler(self, target):
1632
+ """Decorator to register a mpv script message handler.
1633
+
1634
+ WARNING: Only one handler can be registered at a time for any given target.
1635
+
1636
+ To unregister the message handler, call its ``unregister_mpv_messages`` function::
1637
+
1638
+ player = mpv.MPV()
1639
+ @player.message_handler('foo')
1640
+ def my_handler(some, args):
1641
+ print(args)
1642
+
1643
+ my_handler.unregister_mpv_messages()
1644
+ """
1645
+ def register(handler):
1646
+ self._register_message_handler_internal(target, handler)
1647
+ handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
1648
+ return handler
1649
+ return register
1650
+
1651
+ def register_event_callback(self, callback):
1652
+ """Register a blanket event callback receiving all event types.
1653
+
1654
+ To unregister the event callback, call its ``unregister_mpv_events`` function::
1655
+
1656
+ player = mpv.MPV()
1657
+ @player.event_callback('shutdown')
1658
+ def my_handler(event):
1659
+ print('It ded.')
1660
+
1661
+ my_handler.unregister_mpv_events()
1662
+ """
1663
+ self._event_callbacks.append(callback)
1664
+
1665
+ def unregister_event_callback(self, callback):
1666
+ """Unregiser an event callback."""
1667
+ self._event_callbacks.remove(callback)
1668
+
1669
+ def event_callback(self, *event_types):
1670
+ """Function decorator to register a blanket event callback for the given event types. Event types can be given
1671
+ as str (e.g. 'start-file'), integer or MpvEventID object.
1672
+
1673
+ WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
1674
+
1675
+ To unregister the event callback, call its ``unregister_mpv_events`` function::
1676
+
1677
+ player = mpv.MPV()
1678
+ @player.event_callback('shutdown')
1679
+ def my_handler(event):
1680
+ print('It ded.')
1681
+
1682
+ my_handler.unregister_mpv_events()
1683
+ """
1684
+ def register(callback):
1685
+ with self._event_handler_lock:
1686
+ self.check_core_alive()
1687
+ types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
1688
+ @wraps(callback)
1689
+ def wrapper(event, *args, **kwargs):
1690
+ if event.event_id.value in types:
1691
+ callback(event, *args, **kwargs)
1692
+ self._event_callbacks.append(wrapper)
1693
+ wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
1694
+ return wrapper
1695
+ return register
1696
+
1697
+ @staticmethod
1698
+ def _binding_name(callback_or_cmd):
1699
+ return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
1700
+
1701
+ def on_key_press(self, keydef, mode='force'):
1702
+ """Function decorator to register a simplified key binding. The callback is called whenever the key given is
1703
+ *pressed*.
1704
+
1705
+ To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
1706
+
1707
+ player = mpv.MPV()
1708
+ @player.on_key_press('Q')
1709
+ def binding():
1710
+ print('blep')
1711
+
1712
+ binding.unregister_mpv_key_bindings()
1713
+
1714
+ WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
1715
+ a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
1716
+ don't do that.
1717
+
1718
+ The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
1719
+ """
1720
+ def register(fun):
1721
+ @self.key_binding(keydef, mode)
1722
+ @wraps(fun)
1723
+ def wrapper(state='p-', name=None, char=None):
1724
+ if state[0] in ('d', 'p'):
1725
+ fun()
1726
+ return wrapper
1727
+ return register
1728
+
1729
+ def key_binding(self, keydef, mode='force'):
1730
+ """Function decorator to register a low-level key binding.
1731
+
1732
+ The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
1733
+ up" or ``'D'`` for "key down".
1734
+
1735
+ The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
1736
+ key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
1737
+
1738
+ To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
1739
+
1740
+ player = mpv.MPV()
1741
+ @player.key_binding('Q')
1742
+ def binding(state, name, char):
1743
+ print('blep')
1744
+
1745
+ binding.unregister_mpv_key_bindings()
1746
+
1747
+ WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
1748
+ a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
1749
+ don't do that.
1750
+
1751
+ BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
1752
+ exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
1753
+ first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
1754
+ completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
1755
+ this is secure in your case.
1756
+ """
1757
+ def register(fun):
1758
+ fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
1759
+ def unregister_all():
1760
+ for keydef in fun.mpv_key_bindings:
1761
+ self.unregister_key_binding(keydef)
1762
+ fun.unregister_mpv_key_bindings = unregister_all
1763
+
1764
+ self.register_key_binding(keydef, fun, mode)
1765
+ return fun
1766
+ return register
1767
+
1768
+ def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
1769
+ """Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
1770
+ callback function. See ``MPV.key_binding`` for details.
1771
+ """
1772
+ if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
1773
+ raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
1774
+ '<key> is either the literal character the key produces (ASCII or Unicode character), or a '
1775
+ 'symbolic name (as printed by --input-keylist')
1776
+ binding_name = MPV._binding_name(keydef)
1777
+ if callable(callback_or_cmd):
1778
+ self._key_binding_handlers[binding_name] = callback_or_cmd
1779
+ self.register_message_handler('key-binding', self._handle_key_binding_message)
1780
+ self.command('define-section',
1781
+ binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
1782
+ elif isinstance(callback_or_cmd, str):
1783
+ self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
1784
+ else:
1785
+ raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
1786
+ self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
1787
+
1788
+ def _handle_key_binding_message(self, binding_name, key_state, key_name=None, key_char=None):
1789
+ binding_name = binding_name.decode('utf-8')
1790
+ key_state = key_state.decode('utf-8')
1791
+ key_name = key_name.decode('utf-8') if key_name is not None else None
1792
+ key_char = key_char.decode('utf-8') if key_char is not None else None
1793
+ self._key_binding_handlers[binding_name](key_state, key_name, key_char)
1794
+
1795
+ def unregister_key_binding(self, keydef):
1796
+ """Unregister a key binding by keydef."""
1797
+ binding_name = MPV._binding_name(keydef)
1798
+ self.command('disable-section', binding_name)
1799
+ self.command('define-section', binding_name, '')
1800
+ if binding_name in self._key_binding_handlers:
1801
+ del self._key_binding_handlers[binding_name]
1802
+ if not self._key_binding_handlers:
1803
+ self.unregister_message_handler('key-binding')
1804
+
1805
+ def register_stream_protocol(self, proto, open_fn=None):
1806
+ """ Register a custom stream protocol as documented in libmpv/stream_cb.h:
1807
+ https://github.com/mpv-player/mpv/blob/master/libmpv/stream_cb.h
1808
+
1809
+ proto is the protocol scheme, e.g. "foo" for "foo://" urls.
1810
+
1811
+ This function can either be used with two parameters or it can be used as a decorator on the target
1812
+ function.
1813
+
1814
+ open_fn is a function taking an URI string and returning an mpv stream object.
1815
+ open_fn may raise a ValueError to signal libmpv the URI could not be opened.
1816
+
1817
+ The mpv stream protocol is as follows:
1818
+ class Stream:
1819
+ @property
1820
+ def size(self):
1821
+ return None # unknown size
1822
+ return size # int with size in bytes
1823
+
1824
+ def read(self, size):
1825
+ ...
1826
+ return read # non-empty bytes object with input
1827
+ return b'' # empty byte object signals permanent EOF
1828
+
1829
+ def seek(self, pos): # optional
1830
+ return new_offset # integer with new byte offset. The new offset may be before the requested offset
1831
+ in case an exact seek is inconvenient.
1832
+
1833
+ def close(self): # optional
1834
+ ...
1835
+
1836
+ def cancel(self): # optional
1837
+ Abort a running read() or seek() operation
1838
+ ...
1839
+
1840
+ """
1841
+
1842
+ def decorator(open_fn):
1843
+ @StreamOpenFn
1844
+ def open_backend(_userdata, uri, cb_info):
1845
+ try:
1846
+ frontend = open_fn(uri.decode('utf-8'))
1847
+ except ValueError:
1848
+ return ErrorCode.LOADING_FAILED
1849
+ except Exception as e:
1850
+ for fut in self._exception_futures:
1851
+ try:
1852
+ fut.set_exception(e)
1853
+ break
1854
+ except InvalidStateError:
1855
+ pass
1856
+ else:
1857
+ warnings.warn(f'Unhandled exception {e} inside stream open callback for URI {uri}\n{traceback.format_exc()}')
1858
+ return ErrorCode.LOADING_FAILED
1859
+
1860
+ cb_info.contents.cookie = None
1861
+
1862
+ def read_backend(_userdata, buf, bufsize):
1863
+ with self._enqueue_exceptions():
1864
+ data = frontend.read(bufsize)
1865
+ for i in range(len(data)):
1866
+ buf[i] = data[i]
1867
+ return len(data)
1868
+ return -1
1869
+ read = cb_info.contents.read = StreamReadFn(read_backend)
1870
+
1871
+ def close_backend(_userdata):
1872
+ with self._enqueue_exceptions():
1873
+ del self._stream_protocol_frontends[proto][uri]
1874
+ if hasattr(frontend, 'close'):
1875
+ frontend.close()
1876
+ close = cb_info.contents.close = StreamCloseFn(close_backend)
1877
+
1878
+ seek, size, cancel = None, None, None
1879
+
1880
+ if hasattr(frontend, 'seek'):
1881
+ def seek_backend(_userdata, offx):
1882
+ with self._enqueue_exceptions():
1883
+ return frontend.seek(offx)
1884
+ return ErrorCode.GENERIC
1885
+ seek = cb_info.contents.seek = StreamSeekFn(seek_backend)
1886
+
1887
+ if hasattr(frontend, 'size') and frontend.size is not None:
1888
+ def size_backend(_userdata):
1889
+ with self._enqueue_exceptions():
1890
+ return frontend.size
1891
+ return 0
1892
+ size = cb_info.contents.size = StreamSizeFn(size_backend)
1893
+
1894
+ if hasattr(frontend, 'cancel'):
1895
+ def cancel_backend(_userdata):
1896
+ with self._enqueue_exceptions():
1897
+ frontend.cancel()
1898
+ cancel = cb_info.contents.cancel = StreamCancelFn(cancel_backend)
1899
+
1900
+ # keep frontend and callbacks in memory until closed
1901
+ frontend._registered_callbacks = [read, close, seek, size, cancel]
1902
+ self._stream_protocol_frontends[proto][uri] = frontend
1903
+ return 0
1904
+
1905
+ if proto in self._stream_protocol_cbs:
1906
+ raise KeyError('Stream protocol already registered')
1907
+ # keep backend in memory forever
1908
+ self._stream_protocol_cbs[proto] = [open_backend]
1909
+ _mpv_stream_cb_add_ro(self.handle, proto.encode('utf-8'), c_void_p(), open_backend)
1910
+
1911
+ return open_fn
1912
+
1913
+ if open_fn is not None:
1914
+ decorator(open_fn)
1915
+ return decorator
1916
+
1917
+ # Convenience functions
1918
+ def play(self, filename):
1919
+ """Play a path or URL (requires ``ytdl`` option to be set)."""
1920
+ self.loadfile(filename)
1921
+
1922
+ @property
1923
+ def playlist_filenames(self):
1924
+ """Return all playlist item file names/URLs as a list of strs."""
1925
+ return [element['filename'] for element in self.playlist]
1926
+
1927
+ def playlist_append(self, filename, **options):
1928
+ """Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
1929
+ ``MPV.loadfile(filename, 'append-play')``."""
1930
+ self.loadfile(filename, 'append', **options)
1931
+
1932
+ # "Python stream" logic. This is some porcelain for directly playing data from python generators.
1933
+
1934
+ def _python_stream_open(self, uri):
1935
+ """Internal handler for python:// protocol streams registered through @python_stream(...) and
1936
+ @python_stream_catchall
1937
+ """
1938
+ name, = re.fullmatch('python://(.*)', uri).groups()
1939
+
1940
+ if name in self._python_streams:
1941
+ generator_fun, size = self._python_streams[name]
1942
+ else:
1943
+ if self._python_stream_catchall is not None:
1944
+ generator_fun, size = self._python_stream_catchall(name)
1945
+ else:
1946
+ raise ValueError('Python stream name not found and no catch-all defined')
1947
+
1948
+ return GeneratorStream(generator_fun, size)
1949
+
1950
+ def python_stream(self, name=None, size=None):
1951
+ """Register a generator for the python stream with the given name.
1952
+
1953
+ name is the name, i.e. the part after the "python://" in the URI, that this generator is registered as.
1954
+ size is the total number of bytes in the stream (if known).
1955
+
1956
+ Any given name can only be registered once. The catch-all can also only be registered once. To unregister a
1957
+ stream, call the .unregister function set on the callback.
1958
+
1959
+ The generator signals EOF by returning, manually raising StopIteration or by yielding b'', an empty bytes
1960
+ object.
1961
+
1962
+ The generator may be called multiple times if libmpv seeks or loops.
1963
+
1964
+ See also: @mpv.python_stream_catchall
1965
+
1966
+ @mpv.python_stream('foobar')
1967
+ def reader():
1968
+ for chunk in chunks:
1969
+ yield chunk
1970
+ mpv.play('python://foobar')
1971
+ mpv.wait_for_playback()
1972
+ reader.unregister()
1973
+ """
1974
+ def register(cb):
1975
+ if name in self._python_streams:
1976
+ raise KeyError('Python stream name "{}" is already registered'.format(name))
1977
+ self._python_streams[name] = (cb, size)
1978
+ def unregister():
1979
+ if name not in self._python_streams or\
1980
+ self._python_streams[name][0] is not cb: # This is just a basic sanity check
1981
+ raise RuntimeError('Python stream has already been unregistered')
1982
+ del self._python_streams[name]
1983
+ cb.unregister = unregister
1984
+ return cb
1985
+ return register
1986
+
1987
+ @contextmanager
1988
+ def play_context(self):
1989
+ """ Context manager for streaming bytes straight into libmpv.
1990
+
1991
+ This is a convenience wrapper around python_stream. play_context returns a write method, which you can use in
1992
+ the body of the context manager to feed libmpv bytes. All bytes you feed in with write() in the body of a single
1993
+ call of this context manager are treated as one single file. A queue is used internally, so this function is
1994
+ thread-safe. The queue is unlimited, so it cannot block and is safe to call from async code. You can use this
1995
+ function to stream chunked data, e.g. from the network.
1996
+
1997
+ Use it like this:
1998
+
1999
+ with m.play_context() as write:
2000
+ with open(TESTVID, 'rb') as f:
2001
+ while (chunk := f.read(65536)): # Get some chunks of bytes
2002
+ write(chunk)
2003
+ """
2004
+ q = queue.Queue()
2005
+
2006
+ frame = sys._getframe()
2007
+ stream_name = f'__python_mpv_play_generator_{hash(frame)}'
2008
+ EOF = frame # Get some unique object as EOF marker
2009
+ @self.python_stream(stream_name)
2010
+ def reader():
2011
+ while (chunk := q.get()) is not EOF:
2012
+ if chunk:
2013
+ yield chunk
2014
+ reader.unregister()
2015
+
2016
+ def write(chunk):
2017
+ q.put(chunk)
2018
+
2019
+ # Start playback before yielding, the first call to reader() will block until write is called at least once.
2020
+ self.play(f'python://{stream_name}')
2021
+ yield write
2022
+ q.put(EOF)
2023
+
2024
+ def play_bytes(self, data):
2025
+ """ Play the given bytes object as a single file. """
2026
+ frame = sys._getframe()
2027
+ stream_name = f'__python_mpv_play_generator_{hash(frame)}'
2028
+
2029
+ @self.python_stream(stream_name)
2030
+ def reader():
2031
+ yield data
2032
+ reader.unregister() # unregister itself
2033
+
2034
+ self.play(f'python://{stream_name}')
2035
+
2036
+ def python_stream_catchall(self, cb):
2037
+ """ Register a catch-all python stream to be called when no name matches can be found. Use this decorator on a
2038
+ function that takes a name argument and returns a (generator, size) tuple (with size being None if unknown).
2039
+
2040
+ An invalid URI can be signalled to libmpv by raising a ValueError inside the callback.
2041
+
2042
+ See also: @mpv.python_stream(name, size)
2043
+
2044
+ @mpv.python_stream_catchall
2045
+ def catchall(name):
2046
+ if not name.startswith('foo'):
2047
+ raise ValueError('Unknown Name')
2048
+
2049
+ def foo_reader():
2050
+ with open(name, 'rb') as f:
2051
+ while True:
2052
+ chunk = f.read(1024)
2053
+ if not chunk:
2054
+ break
2055
+ yield chunk
2056
+ return foo_reader, None
2057
+ mpv.play('python://foo23')
2058
+ mpv.wait_for_playback()
2059
+ catchall.unregister()
2060
+ """
2061
+ if self._python_stream_catchall is not None:
2062
+ raise KeyError('A catch-all python stream is already registered')
2063
+
2064
+ self._python_stream_catchall = cb
2065
+ def unregister():
2066
+ if self._python_stream_catchall is not cb:
2067
+ raise RuntimeError('This catch-all python stream has already been unregistered')
2068
+ self._python_stream_catchall = None
2069
+ cb.unregister = unregister
2070
+ return cb
2071
+
2072
+ # Property accessors
2073
+ def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
2074
+ self.check_core_alive()
2075
+ out = create_string_buffer(sizeof(MpvNode))
2076
+ try:
2077
+ cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, out)
2078
+
2079
+ if fmt is MpvFormat.OSD_STRING:
2080
+ return cast(out, POINTER(c_char_p)).contents.value.decode('utf-8')
2081
+ elif fmt is MpvFormat.NODE:
2082
+ rv = cast(out, POINTER(MpvNode)).contents.node_value(decoder=decoder)
2083
+ _mpv_free_node_contents(out)
2084
+ return rv
2085
+ else:
2086
+ raise TypeError('_get_property only supports NODE and OSD_STRING formats.')
2087
+ except PropertyUnavailableError as ex:
2088
+ return None
2089
+
2090
+ def _set_property(self, name, value):
2091
+ self.check_core_alive()
2092
+ ename = name.encode('utf-8')
2093
+ if isinstance(value, dict):
2094
+ _1, _2, _3, pointer = _make_node_str_map(value)
2095
+ _mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
2096
+ elif isinstance(value, (list, set)):
2097
+ _1, _2, _3, pointer = _make_node_str_list(value)
2098
+ _mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
2099
+ else:
2100
+ _mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
2101
+
2102
+ def __getattr__(self, name):
2103
+ return self._get_property(_py_to_mpv(name), lazy_decoder)
2104
+
2105
+ def __setattr__(self, name, value):
2106
+ try:
2107
+ if name != 'handle' and not name.startswith('_'):
2108
+ self._set_property(_py_to_mpv(name), value)
2109
+ else:
2110
+ super().__setattr__(name, value)
2111
+ except AttributeError:
2112
+ super().__setattr__(name, value)
2113
+
2114
+ def __dir__(self):
2115
+ return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
2116
+
2117
+ @property
2118
+ def properties(self):
2119
+ return { name: self.option_info(name) for name in self.property_list }
2120
+
2121
+ # Dict-like option access
2122
+ def __getitem__(self, name, file_local=False):
2123
+ """Get an option value."""
2124
+ prefix = 'file-local-options/' if file_local else 'options/'
2125
+ return self._get_property(prefix+name, lazy_decoder)
2126
+
2127
+ def __setitem__(self, name, value, file_local=False):
2128
+ """Set an option value."""
2129
+ prefix = 'file-local-options/' if file_local else 'options/'
2130
+ return self._set_property(prefix+name, value)
2131
+
2132
+ def __iter__(self):
2133
+ """Iterate over all option names."""
2134
+ return iter(self.options)
2135
+
2136
+ def option_info(self, name):
2137
+ """Get information on the given option."""
2138
+ try:
2139
+ return self._get_property('option-info/'+name)
2140
+ except AttributeError:
2141
+ return None
2142
+
2143
+
2144
+ class MpvRenderContext:
2145
+ def __init__(self, mpv, api_type, **kwargs):
2146
+ self._mpv = mpv
2147
+ kwargs['api_type'] = api_type
2148
+
2149
+ buf = cast(create_string_buffer(sizeof(MpvRenderCtxHandle)), POINTER(MpvRenderCtxHandle))
2150
+ _mpv_render_context_create(buf, mpv.handle, kwargs_to_render_param_array(kwargs))
2151
+ self._handle = buf.contents
2152
+
2153
+ def free(self):
2154
+ _mpv_render_context_free(self._handle)
2155
+
2156
+ def __setattr__(self, name, value):
2157
+ if name.startswith('_'):
2158
+ super().__setattr__(name, value)
2159
+
2160
+ elif name == 'update_cb':
2161
+ func = value if value else (lambda: None)
2162
+ self._update_cb = value
2163
+ self._update_fn_wrapper = RenderUpdateFn(lambda _userdata: func())
2164
+ _mpv_render_context_set_update_callback(self._handle, self._update_fn_wrapper, None)
2165
+
2166
+ else:
2167
+ param = MpvRenderParam(name, value)
2168
+ _mpv_render_context_set_parameter(self._handle, param)
2169
+
2170
+ def __getattr__(self, name):
2171
+ if name == 'update_cb':
2172
+ return self._update_cb
2173
+
2174
+ elif name == 'handle':
2175
+ return self._handle
2176
+
2177
+ param = MpvRenderParam(name)
2178
+ data_type = type(param.data.contents)
2179
+ buf = cast(create_string_buffer(sizeof(data_type)), POINTER(data_type))
2180
+ param.data = buf
2181
+ _mpv_render_context_get_info(self._handle, param)
2182
+ return buf.contents.as_dict()
2183
+
2184
+ def update(self):
2185
+ """ Calls mpv_render_context_update and returns the MPV_RENDER_UPDATE_FRAME flag (see render.h) """
2186
+ return bool(_mpv_render_context_update(self._handle) & 1)
2187
+
2188
+ def render(self, **kwargs):
2189
+ _mpv_render_context_render(self._handle, kwargs_to_render_param_array(kwargs))
2190
+
2191
+ def report_swap(self):
2192
+ _mpv_render_context_report_swap(self._handle)
2193
+