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