mpv.py 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. # -*- coding: utf-8 -*-
  2. # vim: ts=4 sw=4 et
  3. #
  4. # Python MPV library module
  5. # Copyright (C) 2017 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. from ctypes import *
  19. import ctypes.util
  20. import threading
  21. import os
  22. import sys
  23. from warnings import warn
  24. from functools import partial, wraps
  25. import collections
  26. import re
  27. import traceback
  28. if os.name == 'nt':
  29. backend = CDLL('mpv-1.dll')
  30. fs_enc = 'utf-8'
  31. else:
  32. import locale
  33. lc, enc = locale.getlocale(locale.LC_NUMERIC)
  34. # libmpv requires LC_NUMERIC to be set to "C". Since messing with global variables everyone else relies upon is
  35. # still better than segfaulting, we are setting LC_NUMERIC to "C".
  36. locale.setlocale(locale.LC_NUMERIC, 'C')
  37. sofile = ctypes.util.find_library('mpv')
  38. if sofile is None:
  39. raise OSError("Cannot find libmpv in the usual places. Depending on your distro, you may try installing an "
  40. "mpv-devel or mpv-libs package. If you have libmpv around but this script can't find it, maybe consult "
  41. "the documentation for ctypes.util.find_library which this script uses to look up the library "
  42. "filename.")
  43. backend = CDLL(sofile)
  44. fs_enc = sys.getfilesystemencoding()
  45. class MpvHandle(c_void_p):
  46. pass
  47. class MpvOpenGLCbContext(c_void_p):
  48. pass
  49. class PropertyUnavailableError(AttributeError):
  50. pass
  51. class ErrorCode(object):
  52. """For documentation on these, see mpv's libmpv/client.h."""
  53. SUCCESS = 0
  54. EVENT_QUEUE_FULL = -1
  55. NOMEM = -2
  56. UNINITIALIZED = -3
  57. INVALID_PARAMETER = -4
  58. OPTION_NOT_FOUND = -5
  59. OPTION_FORMAT = -6
  60. OPTION_ERROR = -7
  61. PROPERTY_NOT_FOUND = -8
  62. PROPERTY_FORMAT = -9
  63. PROPERTY_UNAVAILABLE = -10
  64. PROPERTY_ERROR = -11
  65. COMMAND = -12
  66. EXCEPTION_DICT = {
  67. 0: None,
  68. -1: lambda *a: MemoryError('mpv event queue full', *a),
  69. -2: lambda *a: MemoryError('mpv cannot allocate memory', *a),
  70. -3: lambda *a: ValueError('Uninitialized mpv handle used', *a),
  71. -4: lambda *a: ValueError('Invalid value for mpv parameter', *a),
  72. -5: lambda *a: AttributeError('mpv option does not exist', *a),
  73. -6: lambda *a: TypeError('Tried to set mpv option using wrong format', *a),
  74. -7: lambda *a: ValueError('Invalid value for mpv option', *a),
  75. -8: lambda *a: AttributeError('mpv property does not exist', *a),
  76. # Currently (mpv 0.18.1) there is a bug causing a PROPERTY_FORMAT error to be returned instead of
  77. # INVALID_PARAMETER when setting a property-mapped option to an invalid value.
  78. -9: lambda *a: TypeError('Tried to get/set mpv property using wrong format, or passed invalid value', *a),
  79. -10: lambda *a: PropertyUnavailableError('mpv property is not available', *a),
  80. -11: lambda *a: RuntimeError('Generic error getting or setting mpv property', *a),
  81. -12: lambda *a: SystemError('Error running mpv command', *a) }
  82. @staticmethod
  83. def default_error_handler(ec, *args):
  84. return ValueError(_mpv_error_string(ec).decode('utf-8'), ec, *args)
  85. @classmethod
  86. def raise_for_ec(kls, ec, func, *args):
  87. ec = 0 if ec > 0 else ec
  88. ex = kls.EXCEPTION_DICT.get(ec , kls.default_error_handler)
  89. if ex:
  90. raise ex(ec, *args)
  91. class MpvFormat(c_int):
  92. NONE = 0
  93. STRING = 1
  94. OSD_STRING = 2
  95. FLAG = 3
  96. INT64 = 4
  97. DOUBLE = 5
  98. NODE = 6
  99. NODE_ARRAY = 7
  100. NODE_MAP = 8
  101. BYTE_ARRAY = 9
  102. def __eq__(self, other):
  103. return self is other or self.value == other or self.value == int(other)
  104. def __repr__(self):
  105. return ['NONE', 'STRING', 'OSD_STRING', 'FLAG', 'INT64', 'DOUBLE', 'NODE', 'NODE_ARRAY', 'NODE_MAP',
  106. 'BYTE_ARRAY'][self.value]
  107. def __hash__(self):
  108. return self.value
  109. class MpvEventID(c_int):
  110. NONE = 0
  111. SHUTDOWN = 1
  112. LOG_MESSAGE = 2
  113. GET_PROPERTY_REPLY = 3
  114. SET_PROPERTY_REPLY = 4
  115. COMMAND_REPLY = 5
  116. START_FILE = 6
  117. END_FILE = 7
  118. FILE_LOADED = 8
  119. TRACKS_CHANGED = 9
  120. TRACK_SWITCHED = 10
  121. IDLE = 11
  122. PAUSE = 12
  123. UNPAUSE = 13
  124. TICK = 14
  125. SCRIPT_INPUT_DISPATCH = 15
  126. CLIENT_MESSAGE = 16
  127. VIDEO_RECONFIG = 17
  128. AUDIO_RECONFIG = 18
  129. METADATA_UPDATE = 19
  130. SEEK = 20
  131. PLAYBACK_RESTART = 21
  132. PROPERTY_CHANGE = 22
  133. CHAPTER_CHANGE = 23
  134. ANY = ( SHUTDOWN, LOG_MESSAGE, GET_PROPERTY_REPLY, SET_PROPERTY_REPLY, COMMAND_REPLY, START_FILE, END_FILE,
  135. FILE_LOADED, TRACKS_CHANGED, TRACK_SWITCHED, IDLE, PAUSE, UNPAUSE, TICK, SCRIPT_INPUT_DISPATCH,
  136. CLIENT_MESSAGE, VIDEO_RECONFIG, AUDIO_RECONFIG, METADATA_UPDATE, SEEK, PLAYBACK_RESTART, PROPERTY_CHANGE,
  137. CHAPTER_CHANGE )
  138. def __repr__(self):
  139. return ['NONE', 'SHUTDOWN', 'LOG_MESSAGE', 'GET_PROPERTY_REPLY', 'SET_PROPERTY_REPLY', 'COMMAND_REPLY',
  140. 'START_FILE', 'END_FILE', 'FILE_LOADED', 'TRACKS_CHANGED', 'TRACK_SWITCHED', 'IDLE', 'PAUSE', 'UNPAUSE',
  141. 'TICK', 'SCRIPT_INPUT_DISPATCH', 'CLIENT_MESSAGE', 'VIDEO_RECONFIG', 'AUDIO_RECONFIG',
  142. 'METADATA_UPDATE', 'SEEK', 'PLAYBACK_RESTART', 'PROPERTY_CHANGE', 'CHAPTER_CHANGE'][self.value]
  143. @classmethod
  144. def from_str(kls, s):
  145. return getattr(kls, s.upper().replace('-', '_'))
  146. identity_decoder = lambda b: b
  147. strict_decoder = lambda b: b.decode('utf-8')
  148. def lazy_decoder(b):
  149. try:
  150. return b.decode('utf-8')
  151. except UnicodeDecodeError:
  152. return b
  153. class MpvNodeList(Structure):
  154. def array_value(self, decoder=identity_decoder):
  155. return [ self.values[i].node_value(decoder) for i in range(self.num) ]
  156. def dict_value(self, decoder=identity_decoder):
  157. return { self.keys[i].decode('utf-8'):
  158. self.values[i].node_value(decoder) for i in range(self.num) }
  159. class MpvByteArray(Structure):
  160. _fields_ = [('data', c_void_p),
  161. ('size', c_size_t)]
  162. def bytes_value(self):
  163. return cast(self.data, POINTER(c_char))[:self.size]
  164. class MpvNode(Structure):
  165. _fields_ = [('val', c_longlong),
  166. ('format', MpvFormat)]
  167. def node_value(self, decoder=identity_decoder):
  168. return MpvNode.node_cast_value(byref(c_void_p(self.val)), self.format.value, decoder)
  169. @staticmethod
  170. def node_cast_value(v, fmt=MpvFormat.NODE, decoder=identity_decoder):
  171. return {
  172. MpvFormat.NONE: lambda v: None,
  173. MpvFormat.STRING: lambda v: decoder(cast(v, POINTER(c_char_p)).contents.value),
  174. MpvFormat.OSD_STRING: lambda v: cast(v, POINTER(c_char_p)).contents.value.decode('utf-8'),
  175. MpvFormat.FLAG: lambda v: bool(cast(v, POINTER(c_int)).contents.value),
  176. MpvFormat.INT64: lambda v: cast(v, POINTER(c_longlong)).contents.value,
  177. MpvFormat.DOUBLE: lambda v: cast(v, POINTER(c_double)).contents.value,
  178. MpvFormat.NODE: lambda v: cast(v, POINTER(MpvNode)).contents.node_value(decoder),
  179. MpvFormat.NODE_ARRAY: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.array_value(decoder),
  180. MpvFormat.NODE_MAP: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.dict_value(decoder),
  181. MpvFormat.BYTE_ARRAY: lambda v: cast(v, POINTER(POINTER(MpvByteArray))).contents.contents.bytes_value(),
  182. }[fmt](v)
  183. MpvNodeList._fields_ = [('num', c_int),
  184. ('values', POINTER(MpvNode)),
  185. ('keys', POINTER(c_char_p))]
  186. class MpvSubApi(c_int):
  187. MPV_SUB_API_OPENGL_CB = 1
  188. class MpvEvent(Structure):
  189. _fields_ = [('event_id', MpvEventID),
  190. ('error', c_int),
  191. ('reply_userdata', c_ulonglong),
  192. ('data', c_void_p)]
  193. def as_dict(self, decoder=identity_decoder):
  194. dtype = {MpvEventID.END_FILE: MpvEventEndFile,
  195. MpvEventID.PROPERTY_CHANGE: MpvEventProperty,
  196. MpvEventID.GET_PROPERTY_REPLY: MpvEventProperty,
  197. MpvEventID.LOG_MESSAGE: MpvEventLogMessage,
  198. MpvEventID.SCRIPT_INPUT_DISPATCH: MpvEventScriptInputDispatch,
  199. MpvEventID.CLIENT_MESSAGE: MpvEventClientMessage
  200. }.get(self.event_id.value, None)
  201. return {'event_id': self.event_id.value,
  202. 'error': self.error,
  203. 'reply_userdata': self.reply_userdata,
  204. 'event': cast(self.data, POINTER(dtype)).contents.as_dict(decoder=decoder) if dtype else None}
  205. class MpvEventProperty(Structure):
  206. _fields_ = [('name', c_char_p),
  207. ('format', MpvFormat),
  208. ('data', c_void_p)]
  209. def as_dict(self, decoder=identity_decoder):
  210. value = MpvNode.node_cast_value(self.data, self.format.value, decoder)
  211. return {'name': self.name.decode('utf-8'),
  212. 'format': self.format,
  213. 'data': self.data,
  214. 'value': value}
  215. class MpvEventLogMessage(Structure):
  216. _fields_ = [('prefix', c_char_p),
  217. ('level', c_char_p),
  218. ('text', c_char_p)]
  219. def as_dict(self, decoder=identity_decoder):
  220. return { 'prefix': self.prefix.decode('utf-8'),
  221. 'level': self.level.decode('utf-8'),
  222. 'text': decoder(self.text).rstrip() }
  223. class MpvEventEndFile(c_int):
  224. EOF_OR_INIT_FAILURE = 0
  225. RESTARTED = 1
  226. ABORTED = 2
  227. QUIT = 3
  228. def as_dict(self, decoder=identity_decoder):
  229. return {'reason': self.value}
  230. class MpvEventScriptInputDispatch(Structure):
  231. _fields_ = [('arg0', c_int),
  232. ('type', c_char_p)]
  233. def as_dict(self, decoder=identity_decoder):
  234. pass # TODO
  235. class MpvEventClientMessage(Structure):
  236. _fields_ = [('num_args', c_int),
  237. ('args', POINTER(c_char_p))]
  238. def as_dict(self, decoder=identity_decoder):
  239. return { 'args': [ self.args[i].decode('utf-8') for i in range(self.num_args) ] }
  240. WakeupCallback = CFUNCTYPE(None, c_void_p)
  241. OpenGlCbUpdateFn = CFUNCTYPE(None, c_void_p)
  242. OpenGlCbGetProcAddrFn = CFUNCTYPE(None, c_void_p, c_char_p)
  243. def _handle_func(name, args, restype, errcheck, ctx=MpvHandle):
  244. func = getattr(backend, name)
  245. func.argtypes = [ctx] + args if ctx else args
  246. if restype is not None:
  247. func.restype = restype
  248. if errcheck is not None:
  249. func.errcheck = errcheck
  250. globals()['_'+name] = func
  251. def bytes_free_errcheck(res, func, *args):
  252. notnull_errcheck(res, func, *args)
  253. rv = cast(res, c_void_p).value
  254. _mpv_free(res)
  255. return rv
  256. def notnull_errcheck(res, func, *args):
  257. if res is None:
  258. raise RuntimeError('Underspecified error in MPV when calling {} with args {!r}: NULL pointer returned.'\
  259. 'Please consult your local debugger.'.format(func.__name__, args))
  260. return res
  261. ec_errcheck = ErrorCode.raise_for_ec
  262. def _handle_gl_func(name, args=[], restype=None):
  263. _handle_func(name, args, restype, errcheck=None, ctx=MpvOpenGLCbContext)
  264. backend.mpv_client_api_version.restype = c_ulong
  265. def _mpv_client_api_version():
  266. ver = backend.mpv_client_api_version()
  267. return ver>>16, ver&0xFFFF
  268. backend.mpv_free.argtypes = [c_void_p]
  269. _mpv_free = backend.mpv_free
  270. backend.mpv_free_node_contents.argtypes = [c_void_p]
  271. _mpv_free_node_contents = backend.mpv_free_node_contents
  272. backend.mpv_create.restype = MpvHandle
  273. _mpv_create = backend.mpv_create
  274. _handle_func('mpv_create_client', [c_char_p], MpvHandle, notnull_errcheck)
  275. _handle_func('mpv_client_name', [], c_char_p, errcheck=None)
  276. _handle_func('mpv_initialize', [], c_int, ec_errcheck)
  277. _handle_func('mpv_detach_destroy', [], None, errcheck=None)
  278. _handle_func('mpv_terminate_destroy', [], None, errcheck=None)
  279. _handle_func('mpv_load_config_file', [c_char_p], c_int, ec_errcheck)
  280. _handle_func('mpv_get_time_us', [], c_ulonglong, errcheck=None)
  281. _handle_func('mpv_set_option', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
  282. _handle_func('mpv_set_option_string', [c_char_p, c_char_p], c_int, ec_errcheck)
  283. _handle_func('mpv_command', [POINTER(c_char_p)], c_int, ec_errcheck)
  284. _handle_func('mpv_command_string', [c_char_p, c_char_p], c_int, ec_errcheck)
  285. _handle_func('mpv_command_async', [c_ulonglong, POINTER(c_char_p)], c_int, ec_errcheck)
  286. _handle_func('mpv_command_node', [POINTER(MpvNode), POINTER(MpvNode)], c_int, ec_errcheck)
  287. _handle_func('mpv_command_async', [c_ulonglong, POINTER(MpvNode)], c_int, ec_errcheck)
  288. _handle_func('mpv_set_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
  289. _handle_func('mpv_set_property_string', [c_char_p, c_char_p], c_int, ec_errcheck)
  290. _handle_func('mpv_set_property_async', [c_ulonglong, c_char_p, MpvFormat,c_void_p],c_int, ec_errcheck)
  291. _handle_func('mpv_get_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck)
  292. _handle_func('mpv_get_property_string', [c_char_p], c_void_p, bytes_free_errcheck)
  293. _handle_func('mpv_get_property_osd_string', [c_char_p], c_void_p, bytes_free_errcheck)
  294. _handle_func('mpv_get_property_async', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
  295. _handle_func('mpv_observe_property', [c_ulonglong, c_char_p, MpvFormat], c_int, ec_errcheck)
  296. _handle_func('mpv_unobserve_property', [c_ulonglong], c_int, ec_errcheck)
  297. _handle_func('mpv_event_name', [c_int], c_char_p, errcheck=None, ctx=None)
  298. _handle_func('mpv_error_string', [c_int], c_char_p, errcheck=None, ctx=None)
  299. _handle_func('mpv_request_event', [MpvEventID, c_int], c_int, ec_errcheck)
  300. _handle_func('mpv_request_log_messages', [c_char_p], c_int, ec_errcheck)
  301. _handle_func('mpv_wait_event', [c_double], POINTER(MpvEvent), errcheck=None)
  302. _handle_func('mpv_wakeup', [], None, errcheck=None)
  303. _handle_func('mpv_set_wakeup_callback', [WakeupCallback, c_void_p], None, errcheck=None)
  304. _handle_func('mpv_get_wakeup_pipe', [], c_int, errcheck=None)
  305. _handle_func('mpv_get_sub_api', [MpvSubApi], c_void_p, notnull_errcheck)
  306. _handle_gl_func('mpv_opengl_cb_set_update_callback', [OpenGlCbUpdateFn, c_void_p])
  307. _handle_gl_func('mpv_opengl_cb_init_gl', [c_char_p, OpenGlCbGetProcAddrFn, c_void_p], c_int)
  308. _handle_gl_func('mpv_opengl_cb_draw', [c_int, c_int, c_int], c_int)
  309. _handle_gl_func('mpv_opengl_cb_render', [c_int, c_int], c_int)
  310. _handle_gl_func('mpv_opengl_cb_report_flip', [c_ulonglong], c_int)
  311. _handle_gl_func('mpv_opengl_cb_uninit_gl', [], c_int)
  312. def _mpv_coax_proptype(value, proptype=str):
  313. """Intelligently coax the given python value into something that can be understood as a proptype property."""
  314. if type(value) is bytes:
  315. return value;
  316. elif type(value) is bool:
  317. return b'yes' if value else b'no'
  318. elif proptype in (str, int, float):
  319. return str(proptype(value)).encode('utf-8')
  320. else:
  321. raise TypeError('Cannot coax value of type {} into property type {}'.format(type(value), proptype))
  322. def _make_node_str_list(l):
  323. """Take a list of python objects and make a MPV string node array from it.
  324. As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object::
  325. struct mpv_node {
  326. .format = MPV_NODE_ARRAY,
  327. .u.list = *(struct mpv_node_array){
  328. .num = len(l),
  329. .keys = NULL,
  330. .values = struct mpv_node[len(l)] {
  331. { .format = MPV_NODE_STRING, .u.string = l[0] },
  332. { .format = MPV_NODE_STRING, .u.string = l[1] },
  333. ...
  334. }
  335. }
  336. }
  337. """
  338. char_ps = [ c_char_p(_mpv_coax_proptype(e, str)) for e in l ]
  339. node_list = MpvNodeList(
  340. num=len(l),
  341. keys=None,
  342. values=( MpvNode * len(l))( *[ MpvNode(
  343. format=MpvFormat.STRING,
  344. val=cast(pointer(p), POINTER(c_longlong)).contents) # NOTE: ctypes is kinda crappy here
  345. for p in char_ps ]))
  346. node = MpvNode(
  347. format=MpvFormat.NODE_ARRAY,
  348. val=addressof(node_list))
  349. return char_ps, node_list, node, cast(pointer(node), c_void_p)
  350. def _event_generator(handle):
  351. while True:
  352. event = _mpv_wait_event(handle, -1).contents
  353. if event.event_id.value == MpvEventID.NONE:
  354. raise StopIteration()
  355. yield event
  356. def _event_loop(event_handle, playback_cond, event_callbacks, message_handlers, property_handlers, log_handler):
  357. for event in _event_generator(event_handle):
  358. try:
  359. devent = event.as_dict(decoder=lazy_decoder) # copy data from ctypes
  360. eid = devent['event_id']
  361. for callback in event_callbacks:
  362. callback(devent)
  363. if eid in (MpvEventID.SHUTDOWN, MpvEventID.END_FILE):
  364. with playback_cond:
  365. playback_cond.notify_all()
  366. if eid == MpvEventID.PROPERTY_CHANGE:
  367. pc = devent['event']
  368. name, value, _fmt = pc['name'], pc['value'], pc['format']
  369. for handler in property_handlers[name]:
  370. handler(name, value)
  371. if eid == MpvEventID.LOG_MESSAGE and log_handler is not None:
  372. ev = devent['event']
  373. log_handler(ev['level'], ev['prefix'], ev['text'])
  374. if eid == MpvEventID.CLIENT_MESSAGE:
  375. # {'event': {'args': ['key-binding', 'foo', 'u-', 'g']}, 'reply_userdata': 0, 'error': 0, 'event_id': 16}
  376. target, *args = devent['event']['args']
  377. if target in message_handlers:
  378. message_handlers[target](*args)
  379. if eid == MpvEventID.SHUTDOWN:
  380. _mpv_detach_destroy(event_handle)
  381. return
  382. except Exception as e:
  383. traceback.print_exc()
  384. _py_to_mpv = lambda name: name.replace('_', '-')
  385. _mpv_to_py = lambda name: name.replace('-', '_')
  386. class _Proxy:
  387. def __init__(self, mpv):
  388. super().__setattr__('mpv', mpv)
  389. class _PropertyProxy(_Proxy):
  390. def __dir__(self):
  391. return super().__dir__() + [ name.replace('-', '_') for name in self.mpv.property_list ]
  392. class _FileLocalProxy(_Proxy):
  393. def __getitem__(self, name):
  394. return self.mpv.__getitem__(name, file_local=True)
  395. def __setitem__(self, name, value):
  396. return self.mpv.__setitem__(name, value, file_local=True)
  397. def __iter__(self):
  398. return iter(self.mpv)
  399. class _OSDPropertyProxy(_PropertyProxy):
  400. def __getattr__(self, name):
  401. return self.mpv._get_property(_py_to_mpv(name), fmt=MpvFormat.OSD_STRING)
  402. def __setattr__(self, _name, _value):
  403. raise AttributeError('OSD properties are read-only. Please use the regular property API for writing.')
  404. class _DecoderPropertyProxy(_PropertyProxy):
  405. def __init__(self, mpv, decoder):
  406. super().__init__(mpv)
  407. super().__setattr__('_decoder', decoder)
  408. def __getattr__(self, name):
  409. return self.mpv._get_property(_py_to_mpv(name), decoder=self._decoder)
  410. def __setattr__(self, name, value):
  411. setattr(self.mpv, _py_to_mpv(name), value)
  412. class MPV(object):
  413. """See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as
  414. ``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``.
  415. By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid
  416. utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use
  417. ``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a
  418. property's decoded OSD value, use ``my_mpv.osd.some_property``.
  419. To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a
  420. property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the
  421. underscore_names exposed on the python object.
  422. To make your program not barf hard the first time its used on a weird file system **always** access properties
  423. containing file names or file tags through ``MPV.raw``. """
  424. def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts):
  425. """Create an MPV instance.
  426. Extra arguments and extra keyword arguments will be passed to mpv as options.
  427. """
  428. self.handle = _mpv_create()
  429. self._event_thread = None
  430. _mpv_set_option_string(self.handle, b'audio-display', b'no')
  431. istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o)
  432. try:
  433. for flag in extra_mpv_flags:
  434. _mpv_set_option_string(self.handle, flag.encode('utf-8'), b'')
  435. for k,v in extra_mpv_opts.items():
  436. _mpv_set_option_string(self.handle, k.replace('_', '-').encode('utf-8'), istr(v).encode('utf-8'))
  437. finally:
  438. _mpv_initialize(self.handle)
  439. self.osd = _OSDPropertyProxy(self)
  440. self.file_local = _FileLocalProxy(self)
  441. self.raw = _DecoderPropertyProxy(self, identity_decoder)
  442. self.strict = _DecoderPropertyProxy(self, strict_decoder)
  443. self.lazy = _DecoderPropertyProxy(self, lazy_decoder)
  444. self._event_callbacks = []
  445. self._property_handlers = collections.defaultdict(lambda: [])
  446. self._message_handlers = {}
  447. self._key_binding_handlers = {}
  448. self._playback_cond = threading.Condition()
  449. self._event_handle = _mpv_create_client(self.handle, b'py_event_handler')
  450. self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks,
  451. self._message_handlers, self._property_handlers, log_handler)
  452. if loglevel is not None or log_handler is not None:
  453. self.set_loglevel(loglevel or 'terminal-default')
  454. if start_event_thread:
  455. self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread')
  456. self._event_thread.setDaemon(True)
  457. self._event_thread.start()
  458. else:
  459. self._event_thread = None
  460. def wait_for_playback(self):
  461. """Waits until playback of the current title is paused or done."""
  462. with self._playback_cond:
  463. self._playback_cond.wait()
  464. def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True):
  465. """Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for
  466. properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
  467. """
  468. sema = threading.Semaphore(value=0)
  469. def observer(name, val):
  470. if cond(val):
  471. sema.release()
  472. self.observe_property(name, observer)
  473. if not level_sensitive or not cond(getattr(self, name.replace('-', '_'))):
  474. sema.acquire()
  475. self.unobserve_property(name, observer)
  476. def __del__(self):
  477. if self.handle:
  478. self.terminate()
  479. def terminate(self):
  480. """Properly terminates this player instance. Preferably use this instead of relying on python's garbage
  481. collector to cause this to be called from the object's destructor.
  482. """
  483. self.handle, handle = None, self.handle
  484. if threading.current_thread() is self._event_thread:
  485. # Handle special case to allow event handle to be detached.
  486. # This is necessary since otherwise the event thread would deadlock itself.
  487. grim_reaper = threading.Thread(target=lambda: _mpv_terminate_destroy(handle))
  488. grim_reaper.start()
  489. else:
  490. _mpv_terminate_destroy(handle)
  491. if self._event_thread:
  492. self._event_thread.join()
  493. def set_loglevel(self, level):
  494. """Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want
  495. mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV
  496. constructur such as ``MPV(log_handler=print)``.
  497. Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's
  498. client.h header file.
  499. """
  500. _mpv_request_log_messages(self._event_handle, level.encode('utf-8'))
  501. def command(self, name, *args):
  502. """Execute a raw command."""
  503. args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8'))
  504. for arg in args if arg is not None ] + [None]
  505. _mpv_command(self.handle, (c_char_p*len(args))(*args))
  506. def node_command(self, name, *args, decoder=strict_decoder):
  507. _1, _2, _3, pointer = _make_node_str_list([name, *args])
  508. out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode))
  509. outptr = out #byref(out)
  510. ppointer = cast(pointer, POINTER(MpvNode))
  511. _mpv_command_node(self.handle, ppointer, outptr)
  512. rv = MpvNode.node_cast_value(outptr, MpvFormat.NODE, decoder)
  513. _mpv_free_node_contents(outptr)
  514. return rv
  515. def seek(self, amount, reference="relative", precision="default-precise"):
  516. """Mapped mpv seek command, see man mpv(1)."""
  517. self.command('seek', amount, reference, precision)
  518. def revert_seek(self):
  519. """Mapped mpv revert_seek command, see man mpv(1)."""
  520. self.command('revert_seek');
  521. def frame_step(self):
  522. """Mapped mpv frame_step command, see man mpv(1)."""
  523. self.command('frame_step')
  524. def frame_back_step(self):
  525. """Mapped mpv frame_back_step command, see man mpv(1)."""
  526. self.command('frame_back_step')
  527. def property_add(self, name, value=1):
  528. """Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If
  529. ``value`` is omitted, assume ``1``.
  530. """
  531. self.command('add', name, value)
  532. def property_multiply(self, name, factor):
  533. """Multiply the value of a property with a numeric factor."""
  534. self.command('multiply', name, factor)
  535. def cycle(self, name, direction='up'):
  536. """Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to
  537. the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``.
  538. """
  539. self.command('cycle', name, direction)
  540. def screenshot(self, includes='subtitles', mode='single'):
  541. """Mapped mpv screenshot command, see man mpv(1)."""
  542. self.command('screenshot', includes, mode)
  543. def screenshot_to_file(self, filename, includes='subtitles'):
  544. """Mapped mpv screenshot_to_file command, see man mpv(1)."""
  545. self.command('screenshot_to_file', filename.encode(fs_enc), includes)
  546. def screenshot_raw(self, includes='subtitles'):
  547. """Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object."""
  548. from PIL import Image
  549. res = self.node_command('screenshot-raw', includes)
  550. if res['format'] != 'bgr0':
  551. raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.'
  552. .format(res['format']))
  553. img = Image.frombytes('RGBA', (res['w'], res['h']), res['data'])
  554. b,g,r,a = img.split()
  555. return Image.merge('RGB', (r,g,b))
  556. def playlist_next(self, mode='weak'):
  557. """Mapped mpv playlist_next command, see man mpv(1)."""
  558. self.command('playlist_next', mode)
  559. def playlist_prev(self, mode='weak'):
  560. """Mapped mpv playlist_prev command, see man mpv(1)."""
  561. self.command('playlist_prev', mode)
  562. @staticmethod
  563. def _encode_options(options):
  564. return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items())
  565. def loadfile(self, filename, mode='replace', **options):
  566. """Mapped mpv loadfile command, see man mpv(1)."""
  567. self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options))
  568. def loadlist(self, playlist, mode='replace'):
  569. """Mapped mpv loadlist command, see man mpv(1)."""
  570. self.command('loadlist', playlist.encode(fs_enc), mode)
  571. def playlist_clear(self):
  572. """Mapped mpv playlist_clear command, see man mpv(1)."""
  573. self.command('playlist_clear')
  574. def playlist_remove(self, index='current'):
  575. """Mapped mpv playlist_remove command, see man mpv(1)."""
  576. self.command('playlist_remove', index)
  577. def playlist_move(self, index1, index2):
  578. """Mapped mpv playlist_move command, see man mpv(1)."""
  579. self.command('playlist_move', index1, index2)
  580. def run(self, command, *args):
  581. """Mapped mpv run command, see man mpv(1)."""
  582. self.command('run', command, *args)
  583. def quit(self, code=None):
  584. """Mapped mpv quit command, see man mpv(1)."""
  585. self.command('quit', code)
  586. def quit_watch_later(self, code=None):
  587. """Mapped mpv quit_watch_later command, see man mpv(1)."""
  588. self.command('quit_watch_later', code)
  589. def sub_add(self, filename):
  590. """Mapped mpv sub_add command, see man mpv(1)."""
  591. self.command('sub_add', filename.encode(fs_enc))
  592. def sub_remove(self, sub_id=None):
  593. """Mapped mpv sub_remove command, see man mpv(1)."""
  594. self.command('sub_remove', sub_id)
  595. def sub_reload(self, sub_id=None):
  596. """Mapped mpv sub_reload command, see man mpv(1)."""
  597. self.command('sub_reload', sub_id)
  598. def sub_step(self, skip):
  599. """Mapped mpv sub_step command, see man mpv(1)."""
  600. self.command('sub_step', skip)
  601. def sub_seek(self, skip):
  602. """Mapped mpv sub_seek command, see man mpv(1)."""
  603. self.command('sub_seek', skip)
  604. def toggle_osd(self):
  605. """Mapped mpv osd command, see man mpv(1)."""
  606. self.command('osd')
  607. def show_text(self, string, duration='-', level=None):
  608. """Mapped mpv show_text command, see man mpv(1)."""
  609. self.command('show_text', string, duration, level)
  610. def show_progress(self):
  611. """Mapped mpv show_progress command, see man mpv(1)."""
  612. self.command('show_progress')
  613. def discnav(self, command):
  614. """Mapped mpv discnav command, see man mpv(1)."""
  615. self.command('discnav', command)
  616. def write_watch_later_config(self):
  617. """Mapped mpv write_watch_later_config command, see man mpv(1)."""
  618. self.command('write_watch_later_config')
  619. def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride):
  620. """Mapped mpv overlay_add command, see man mpv(1)."""
  621. self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride)
  622. def overlay_remove(self, overlay_id):
  623. """Mapped mpv overlay_remove command, see man mpv(1)."""
  624. self.command('overlay_remove', overlay_id)
  625. def script_message(self, *args):
  626. """Mapped mpv script_message command, see man mpv(1)."""
  627. self.command('script_message', *args)
  628. def script_message_to(self, target, *args):
  629. """Mapped mpv script_message_to command, see man mpv(1)."""
  630. self.command('script_message_to', target, *args)
  631. def observe_property(self, name, handler):
  632. """Register an observer on the named property. An observer is a function that is called with the new property
  633. value every time the property's value is changed. The basic function signature is ``fun(property_name,
  634. new_value)`` with new_value being the decoded property value as a python object. This function can be used as a
  635. function decorator if no handler is given.
  636. To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``,
  637. ``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute::
  638. @player.observe_property('volume')
  639. def my_handler(new_volume, *):
  640. print("It's loud!", volume)
  641. my_handler.unregister_mpv_properties()
  642. """
  643. self._property_handlers[name].append(handler)
  644. _mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE)
  645. def property_observer(self, name):
  646. """Function decorator to register a property observer. See ``MPV.observe_property`` for details."""
  647. def wrapper(fun):
  648. self.observe_property(name, fun)
  649. fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun)
  650. return fun
  651. return wrapper
  652. def unobserve_property(self, name, handler):
  653. """Unregister a property observer. This requires both the observed property's name and the handler function that
  654. was originally registered as one handler could be registered for several properties. To unregister a handler
  655. from *all* observed properties see ``unobserve_all_properties``.
  656. """
  657. self._property_handlers[name].remove(handler)
  658. if not self._property_handlers[name]:
  659. _mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff)
  660. def unobserve_all_properties(self, handler):
  661. """Unregister a property observer from *all* observed properties."""
  662. for name in self._property_handlers:
  663. self.unobserve_property(name, handler)
  664. def register_message_handler(self, target, handler=None):
  665. """Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the
  666. script message target name this handler should be listening to and the handler function.
  667. WARNING: Only one handler can be registered at a time for any given target.
  668. To unregister the message handler, call its ``unregister_mpv_messages`` function::
  669. player = mpv.MPV()
  670. @player.message_handler('foo')
  671. def my_handler(some, args):
  672. print(args)
  673. my_handler.unregister_mpv_messages()
  674. """
  675. self._register_message_handler_internal(target, handler)
  676. def _register_message_handler_internal(self, target, handler):
  677. self._message_handlers[target] = handler
  678. def unregister_message_handler(self, target_or_handler):
  679. """Unregister a mpv script message handler for the given script message target name.
  680. You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is
  681. registered.
  682. """
  683. if isinstance(target_or_handler, str):
  684. del self._message_handlers[target_or_handler]
  685. else:
  686. for key, val in self._message_handlers.items():
  687. if val == target_or_handler:
  688. del self._message_handlers[key]
  689. def message_handler(self, target):
  690. """Decorator to register a mpv script message handler.
  691. WARNING: Only one handler can be registered at a time for any given target.
  692. To unregister the message handler, call its ``unregister_mpv_messages`` function::
  693. player = mpv.MPV()
  694. @player.message_handler('foo')
  695. def my_handler(some, args):
  696. print(args)
  697. my_handler.unregister_mpv_messages()
  698. """
  699. def register(handler):
  700. self._register_message_handler_internal(target, handler)
  701. handler.unregister_mpv_messages = lambda: self.unregister_message_handler(handler)
  702. return handler
  703. return register
  704. def register_event_callback(self, callback):
  705. """Register a blanket event callback receiving all event types.
  706. To unregister the event callback, call its ``unregister_mpv_events`` function::
  707. player = mpv.MPV()
  708. @player.event_callback('shutdown')
  709. def my_handler(event):
  710. print('It ded.')
  711. my_handler.unregister_mpv_events()
  712. """
  713. self._event_callbacks.append(callback)
  714. def unregister_event_callback(self, callback):
  715. """Unregiser an event callback."""
  716. self._event_callbacks.remove(callback)
  717. def event_callback(self, *event_types):
  718. """Function decorator to register a blanket event callback for the given event types. Event types can be given
  719. as str (e.g. 'start-file'), integer or MpvEventID object.
  720. WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself.
  721. To unregister the event callback, call its ``unregister_mpv_events`` function::
  722. player = mpv.MPV()
  723. @player.event_callback('shutdown')
  724. def my_handler(event):
  725. print('It ded.')
  726. my_handler.unregister_mpv_events()
  727. """
  728. def register(callback):
  729. types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY
  730. @wraps(callback)
  731. def wrapper(event, *args, **kwargs):
  732. if event['event_id'] in types:
  733. callback(event, *args, **kwargs)
  734. self._event_callbacks.append(wrapper)
  735. wrapper.unregister_mpv_events = partial(self.unregister_event_callback, wrapper)
  736. return wrapper
  737. return register
  738. @staticmethod
  739. def _binding_name(callback_or_cmd):
  740. return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff)
  741. def on_key_press(self, keydef, mode='force'):
  742. """Function decorator to register a simplified key binding. The callback is called whenever the key given is
  743. *pressed*.
  744. To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
  745. player = mpv.MPV()
  746. @player.on_key_press('Q')
  747. def binding():
  748. print('blep')
  749. binding.unregister_mpv_key_bindings()
  750. WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
  751. a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
  752. don't do that.
  753. The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well.
  754. """
  755. def register(fun):
  756. @self.key_binding(keydef, mode)
  757. @wraps(fun)
  758. def wrapper(state='p-', name=None):
  759. if state[0] in ('d', 'p'):
  760. fun()
  761. return wrapper
  762. return register
  763. def key_binding(self, keydef, mode='force'):
  764. """Function decorator to register a low-level key binding.
  765. The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key
  766. up" or ``'D'`` for "key down".
  767. The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the
  768. key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``).
  769. To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute::
  770. player = mpv.MPV()
  771. @player.key_binding('Q')
  772. def binding(state, name):
  773. print('blep')
  774. binding.unregister_mpv_key_bindings()
  775. WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register
  776. a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So
  777. don't do that.
  778. BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code
  779. exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the
  780. first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is
  781. completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether
  782. this is secure in your case.
  783. """
  784. def register(fun):
  785. fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef]
  786. def unregister_all():
  787. for keydef in fun.mpv_key_bindings:
  788. self.unregister_key_binding(keydef)
  789. fun.unregister_mpv_key_bindings = unregister_all
  790. self.register_key_binding(keydef, fun, mode)
  791. return fun
  792. return register
  793. def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
  794. """Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
  795. callback function. See ``MPV.key_binding`` for details.
  796. """
  797. if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef):
  798. raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n'
  799. '<key> is either the literal character the key produces (ASCII or Unicode character), or a '
  800. 'symbolic name (as printed by --input-keylist')
  801. binding_name = MPV._binding_name(keydef)
  802. if callable(callback_or_cmd):
  803. self._key_binding_handlers[binding_name] = callback_or_cmd
  804. self.register_message_handler('key-binding', self._handle_key_binding_message)
  805. self.command('define-section',
  806. binding_name, '{} script-binding py_event_handler/{}'.format(keydef, binding_name), mode)
  807. elif isinstance(callback_or_cmd, str):
  808. self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode)
  809. else:
  810. raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.')
  811. self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging')
  812. def _handle_key_binding_message(self, binding_name, key_state, key_name=None):
  813. self._key_binding_handlers[binding_name](key_state, key_name)
  814. def unregister_key_binding(self, keydef):
  815. """Unregister a key binding by keydef."""
  816. binding_name = MPV._binding_name(keydef)
  817. self.command('disable-section', binding_name)
  818. self.command('define-section', binding_name, '')
  819. if binding_name in self._key_binding_handlers:
  820. del self._key_binding_handlers[binding_name]
  821. if not self._key_binding_handlers:
  822. self.unregister_message_handler('key-binding')
  823. # Convenience functions
  824. def play(self, filename):
  825. """Play a path or URL (requires ``ytdl`` option to be set)."""
  826. self.loadfile(filename)
  827. @property
  828. def playlist_filenames(self):
  829. """Return all playlist item file names/URLs as a list of strs."""
  830. return [element['filename'] for element in self.playlist]
  831. def playlist_append(self, filename, **options):
  832. """Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use
  833. ``MPV.loadfile(filename, 'append-play')``."""
  834. self.loadfile(filename, 'append', **options)
  835. # Property accessors
  836. def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE):
  837. out = cast(create_string_buffer(sizeof(c_void_p)), c_void_p)
  838. outptr = byref(out)
  839. try:
  840. cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, outptr)
  841. rv = MpvNode.node_cast_value(outptr, fmt, decoder)
  842. if fmt is MpvFormat.NODE:
  843. _mpv_free_node_contents(outptr)
  844. return rv
  845. except PropertyUnavailableError as ex:
  846. return None
  847. def _set_property(self, name, value):
  848. ename = name.encode('utf-8')
  849. if isinstance(value, (list, set, dict)):
  850. _1, _2, _3, pointer = _make_node_str_list(value)
  851. _mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer)
  852. else:
  853. _mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value))
  854. def __getattr__(self, name):
  855. return self._get_property(_py_to_mpv(name), lazy_decoder)
  856. def __setattr__(self, name, value):
  857. try:
  858. if name != 'handle' and not name.startswith('_'):
  859. self._set_property(_py_to_mpv(name), value)
  860. else:
  861. super().__setattr__(name, value)
  862. except AttributeError:
  863. super().__setattr__(name, value)
  864. def __dir__(self):
  865. return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ]
  866. @property
  867. def properties(self):
  868. return { name: self.option_info(name) for name in self.property_list }
  869. # Dict-like option access
  870. def __getitem__(self, name, file_local=False):
  871. """Get an option value."""
  872. prefix = 'file-local-options/' if file_local else 'options/'
  873. return self._get_property(prefix+name, lazy_decoder)
  874. def __setitem__(self, name, value, file_local=False):
  875. """Set an option value."""
  876. prefix = 'file-local-options/' if file_local else 'options/'
  877. return self._set_property(prefix+name, value)
  878. def __iter__(self):
  879. """Iterate over all option names."""
  880. return iter(self.options)
  881. def option_info(self, name):
  882. """Get information on the given option."""
  883. try:
  884. return self._get_property('option-info/'+name)
  885. except AttributeError:
  886. return None