Hello community, here is the log from the commit of package python-python-mpv for openSUSE:Factory checked in at 2017-11-27 22:15:49 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Comparing /work/SRC/openSUSE:Factory/python-python-mpv (Old) and /work/SRC/openSUSE:Factory/.python-python-mpv.new (New) ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Package is "python-python-mpv" Mon Nov 27 22:15:49 2017 rev:2 rq:545232 version:0.3.6 Changes: -------- --- /work/SRC/openSUSE:Factory/python-python-mpv/python-python-mpv.changes 2017-08-08 11:58:31.390078000 +0200 +++ /work/SRC/openSUSE:Factory/.python-python-mpv.new/python-python-mpv.changes 2017-11-27 22:15:52.572155349 +0100 @@ -1,0 +2,35 @@ +Fri Nov 24 14:03:25 UTC 2017 - [email protected] + +- Update to version 0.3.6 + * Fixed TypeError: _handle_key_binding_message() signature + incompatibility with mpv < v0.15.0 + * Nicer API names for add/multiply/cycle property + * Wrap all docstrings to 120 char line width + * Reformat doctrings to follow PEP 257 and use reStructuredText + * Fix add, cycle and multiply command. + * README: loop -> loop_playlist + * Add on_key_press + * Fix key binding registration for bound methods, add unit tests + * Fix window dragging while using custom key bindings + * mpv, mpv-test: Fix vim mode lines + * setup.py: Add pillow extra dependency + * Restore compatibility with older libmpv versions + * Re-nerf property observer tests + * mpv-test.py: Add more thorough property tests + * mpv.py: Un-break property write access + * Add pillow-based screenshot_raw command + * Move to fully FORMAT_NODE-based API + * mpv module: Remove load_lua + * MPV constructor: Add loglevel argument + * Fix register_event_callback to work with methods + * Remove debug hack accidentially left in the code + * Fix message handler registration and advanced README example + * setup.py: Small syntax fixes + * tests: Add test for multi-valued property-mapped options + * Add support for string-array options + * Fix racy property tests + * README: Add version compatibility blurb + +- Spec cleanup + +------------------------------------------------------------------- Old: ---- python-mpv-0.2.3.tar.gz New: ---- python-mpv-0.3.6.tar.gz ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Other differences: ------------------ ++++++ python-python-mpv.spec ++++++ --- /var/tmp/diff_new_pack.E5ijRZ/_old 2017-11-27 22:15:53.632116873 +0100 +++ /var/tmp/diff_new_pack.E5ijRZ/_new 2017-11-27 22:15:53.644116438 +0100 @@ -18,19 +18,18 @@ %{?!python_module:%define python_module() python-%{**} python3-%{**}} Name: python-python-mpv -Version: 0.2.3 +Version: 0.3.6 Release: 0 Summary: Python interface to the mpv media player License: AGPL-3.0+ Group: Development/Languages/Python -Url: https://github.com/jaseg/python-mpv +URL: https://github.com/jaseg/python-mpv Source0: https://files.pythonhosted.org/packages/source/p/python-mpv/python-mpv-%{version}.tar.gz Source99: %{name}-rpmlintrc BuildRequires: %{python_module devel} BuildRequires: %{python_module setuptools} BuildRequires: python-rpm-macros Requires: libmpv1 -BuildRoot: %{_tmppath}/%{name}-%{version}-build BuildArch: noarch %python_subpackages @@ -49,10 +48,7 @@ %python_install %files %{python_files} -%defattr(-,root,root) %doc README.rst -%{python_sitelib}/mpv.py -%pycache_only %{python_sitelib}/__pycache__ -%{python_sitelib}/python_mpv-%{version}-py%{python_version}.egg-info +%{python_sitelib}/* %changelog ++++++ python-mpv-0.2.3.tar.gz -> python-mpv-0.3.6.tar.gz ++++++ diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/python-mpv-0.2.3/PKG-INFO new/python-mpv-0.3.6/PKG-INFO --- old/python-mpv-0.2.3/PKG-INFO 2017-05-26 18:03:16.000000000 +0200 +++ new/python-mpv-0.3.6/PKG-INFO 2017-09-19 12:12:54.000000000 +0200 @@ -1,6 +1,6 @@ Metadata-Version: 1.1 Name: python-mpv -Version: 0.2.3 +Version: 0.3.6 Summary: A python interface to the mpv media player Home-page: https://github.com/jaseg/python-mpv Author: jaseg diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/python-mpv-0.2.3/README.rst new/python-mpv-0.3.6/README.rst --- old/python-mpv-0.2.3/README.rst 2017-05-26 14:17:26.000000000 +0200 +++ new/python-mpv-0.3.6/README.rst 2017-08-23 09:06:47.000000000 +0200 @@ -16,6 +16,26 @@ ...though you can also realistically just copy `mpv.py`_ into your project as it's all nicely contained in one file. +Requirements +~~~~~~~~~~~~ + +libmpv (no kidding!) +.................... +``libmpv.so`` either locally (in your current working directory) or somewhere in your system library search path. This +module is somewhat lenient as far as ``libmpv`` versions are concerned but since ``libmpv`` is changing quite frequently +you'll only get all the newest features when using an up-to-date version of this module. The unit tests for this module +do some basic automatic version compatibility checks. If you discover anything missing here, please open an `issue`_ or +submit a `pull request`_ on github. + +Python 2.7, 3.5 or 3.6 (officially) +................................... +The ``master`` branch officially only supports recent python releases (3.5 onwards), but there is the somewhat outdated +but functional `py2compat branch`_ providing Python 2 compatibility. + +.. _`py2compat branch`: https://github.com/jaseg/python-mpv/tree/py2compat +.. _`issue`: https://github.com/jaseg/python-mpv/issues +.. _`pull request`: https://github.com/jaseg/python-mpv/pulls + Usage ----- @@ -58,17 +78,21 @@ def time_observer(_name, value): # Here, _value is either None if nothing is playing or a float containing # fractional seconds since the beginning of the file. - print('Now playing at {:.2f}s'.format(value))) + print('Now playing at {:.2f}s'.format(value)) player.fullscreen = True - player.loop = 'inf' + player.loop_playlist = 'inf' # Option access, in general these require the core to reinitialize player['vo'] = 'opengl' - def my_q_binding(state, key): - if state[0] == 'd': - print('THERE IS NO ESCAPE') - player.register_key_binding('q', my_q_binding) + @player.on_key_press('q') + def my_q_binding(): + print('THERE IS NO ESCAPE') + + @player.on_key_press('s') + def my_s_binding(): + pillow_img = player.screenshot_raw() + pillow_img.save('screenshot.png') player.play('https://youtu.be/DLzxrzFCyOs') player.wait_for_playback() diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/python-mpv-0.2.3/mpv.py new/python-mpv-0.3.6/mpv.py --- old/python-mpv-0.2.3/mpv.py 2017-05-26 14:00:57.000000000 +0200 +++ new/python-mpv-0.3.6/mpv.py 2017-09-19 12:11:39.000000000 +0200 @@ -1,20 +1,19 @@ # -*- coding: utf-8 -*- +# vim: ts=4 sw=4 et # # Python MPV library module # Copyright (C) 2017 Sebastian Götte <[email protected]> # -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. +# This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General +# Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any +# later version. # -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. +# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied +# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more +# details. # -# You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. +# You should have received a copy of the GNU Affero General Public License along with this program. If not, see +# <http://www.gnu.org/licenses/>. # from ctypes import * @@ -28,8 +27,6 @@ import re import traceback -# vim: ts=4 sw=4 et - if os.name == 'nt': backend = CDLL('mpv-1.dll') fs_enc = 'utf-8' @@ -61,7 +58,7 @@ pass class ErrorCode(object): - """ For documentation on these, see mpv's libmpv/client.h """ + """For documentation on these, see mpv's libmpv/client.h.""" SUCCESS = 0 EVENT_QUEUE_FULL = -1 NOMEM = -2 @@ -170,34 +167,49 @@ return getattr(kls, s.upper().replace('-', '_')) +identity_decoder = lambda b: b +strict_decoder = lambda b: b.decode('utf-8') +def lazy_decoder(b): + try: + return b.decode('utf-8') + except UnicodeDecodeError: + return b + class MpvNodeList(Structure): - def array_value(self, decode_str=False): - return [ self.values[i].node_value(decode_str) for i in range(self.num) ] + def array_value(self, decoder=identity_decoder): + return [ self.values[i].node_value(decoder) for i in range(self.num) ] + + def dict_value(self, decoder=identity_decoder): + return { self.keys[i].decode('utf-8'): + self.values[i].node_value(decoder) for i in range(self.num) } + +class MpvByteArray(Structure): + _fields_ = [('data', c_void_p), + ('size', c_size_t)] - def dict_value(self, decode_str=False): - return { self.keys[i].decode('utf-8'): self.values[i].node_value(decode_str) for i in range(self.num) } + def bytes_value(self): + return cast(self.data, POINTER(c_char))[:self.size] class MpvNode(Structure): _fields_ = [('val', c_longlong), ('format', MpvFormat)] - def node_value(self, decode_str=False): - return MpvNode.node_cast_value(byref(c_void_p(self.val)), self.format.value, decode_str) + def node_value(self, decoder=identity_decoder): + return MpvNode.node_cast_value(byref(c_void_p(self.val)), self.format.value, decoder) @staticmethod - def node_cast_value(v, fmt, decode_str=False): - dwrap = lambda s: s.decode('utf-8') if decode_str else s + def node_cast_value(v, fmt=MpvFormat.NODE, decoder=identity_decoder): return { MpvFormat.NONE: lambda v: None, - MpvFormat.STRING: lambda v: dwrap(cast(v, POINTER(c_char_p)).contents.value), + MpvFormat.STRING: lambda v: decoder(cast(v, POINTER(c_char_p)).contents.value), MpvFormat.OSD_STRING: lambda v: cast(v, POINTER(c_char_p)).contents.value.decode('utf-8'), MpvFormat.FLAG: lambda v: bool(cast(v, POINTER(c_int)).contents.value), MpvFormat.INT64: lambda v: cast(v, POINTER(c_longlong)).contents.value, MpvFormat.DOUBLE: lambda v: cast(v, POINTER(c_double)).contents.value, - MpvFormat.NODE: lambda v: cast(v, POINTER(MpvNode)).contents.node_value(decode_str), - MpvFormat.NODE_ARRAY: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.array_value(decode_str), - MpvFormat.NODE_MAP: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.dict_value(decode_str), - MpvFormat.BYTE_ARRAY: lambda v: cast(v, POINTER(c_char_p)).contents.value, + MpvFormat.NODE: lambda v: cast(v, POINTER(MpvNode)).contents.node_value(decoder), + MpvFormat.NODE_ARRAY: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.array_value(decoder), + MpvFormat.NODE_MAP: lambda v: cast(v, POINTER(POINTER(MpvNodeList))).contents.contents.dict_value(decoder), + MpvFormat.BYTE_ARRAY: lambda v: cast(v, POINTER(POINTER(MpvByteArray))).contents.contents.bytes_value(), }[fmt](v) MpvNodeList._fields_ = [('num', c_int), @@ -213,7 +225,7 @@ ('reply_userdata', c_ulonglong), ('data', c_void_p)] - def as_dict(self): + def as_dict(self, decoder=identity_decoder): dtype = {MpvEventID.END_FILE: MpvEventEndFile, MpvEventID.PROPERTY_CHANGE: MpvEventProperty, MpvEventID.GET_PROPERTY_REPLY: MpvEventProperty, @@ -224,15 +236,14 @@ return {'event_id': self.event_id.value, 'error': self.error, 'reply_userdata': self.reply_userdata, - 'event': cast(self.data, POINTER(dtype)).contents.as_dict() if dtype else None} + 'event': cast(self.data, POINTER(dtype)).contents.as_dict(decoder=decoder) if dtype else None} class MpvEventProperty(Structure): _fields_ = [('name', c_char_p), ('format', MpvFormat), ('data', c_void_p)] - def as_dict(self, decode_str=False): - proptype, _access = ALL_PROPERTIES.get(self.name, (str, None)) - value = MpvNode.node_cast_value(self.data, self.format.value, decode_str or proptype in (str, _commalist)) + def as_dict(self, decoder=identity_decoder): + value = MpvNode.node_cast_value(self.data, self.format.value, decoder) return {'name': self.name.decode('utf-8'), 'format': self.format, 'data': self.data, @@ -243,10 +254,10 @@ ('level', c_char_p), ('text', c_char_p)] - def as_dict(self): + def as_dict(self, decoder=identity_decoder): return { 'prefix': self.prefix.decode('utf-8'), 'level': self.level.decode('utf-8'), - 'text': self.text.decode('utf-8').rstrip() } + 'text': decoder(self.text).rstrip() } class MpvEventEndFile(c_int): EOF_OR_INIT_FAILURE = 0 @@ -254,21 +265,21 @@ ABORTED = 2 QUIT = 3 - def as_dict(self): + def as_dict(self, decoder=identity_decoder): return {'reason': self.value} class MpvEventScriptInputDispatch(Structure): _fields_ = [('arg0', c_int), ('type', c_char_p)] - def as_dict(self): + def as_dict(self, decoder=identity_decoder): pass # TODO class MpvEventClientMessage(Structure): _fields_ = [('num_args', c_int), ('args', POINTER(c_char_p))] - def as_dict(self): + def as_dict(self, decoder=identity_decoder): return { 'args': [ self.args[i].decode('utf-8') for i in range(self.num_args) ] } WakeupCallback = CFUNCTYPE(None, c_void_p) @@ -322,8 +333,6 @@ _handle_func('mpv_detach_destroy', [], None, errcheck=None) _handle_func('mpv_terminate_destroy', [], None, errcheck=None) _handle_func('mpv_load_config_file', [c_char_p], c_int, ec_errcheck) -_handle_func('mpv_suspend', [], None, errcheck=None) -_handle_func('mpv_resume', [], None, errcheck=None) _handle_func('mpv_get_time_us', [], c_ulonglong, errcheck=None) _handle_func('mpv_set_option', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck) @@ -332,6 +341,8 @@ _handle_func('mpv_command', [POINTER(c_char_p)], c_int, ec_errcheck) _handle_func('mpv_command_string', [c_char_p, c_char_p], c_int, ec_errcheck) _handle_func('mpv_command_async', [c_ulonglong, POINTER(c_char_p)], c_int, ec_errcheck) +_handle_func('mpv_command_node', [POINTER(MpvNode), POINTER(MpvNode)], c_int, ec_errcheck) +_handle_func('mpv_command_async', [c_ulonglong, POINTER(MpvNode)], c_int, ec_errcheck) _handle_func('mpv_set_property', [c_char_p, MpvFormat, c_void_p], c_int, ec_errcheck) _handle_func('mpv_set_property_string', [c_char_p, c_char_p], c_int, ec_errcheck) @@ -363,8 +374,47 @@ _handle_gl_func('mpv_opengl_cb_uninit_gl', [], c_int) -def _ensure_encoding(possibly_bytes): - return possibly_bytes.decode('utf-8') if type(possibly_bytes) is bytes else possibly_bytes +def _mpv_coax_proptype(value, proptype=str): + """Intelligently coax the given python value into something that can be understood as a proptype property.""" + if type(value) is bytes: + return value; + elif type(value) is bool: + return b'yes' if value else b'no' + elif proptype in (str, int, float): + return str(proptype(value)).encode('utf-8') + else: + raise TypeError('Cannot coax value of type {} into property type {}'.format(type(value), proptype)) + +def _make_node_str_list(l): + """Take a list of python objects and make a MPV string node array from it. + + As an example, the python list ``l = [ "foo", 23, false ]`` will result in the following MPV node object:: + + struct mpv_node { + .format = MPV_NODE_ARRAY, + .u.list = *(struct mpv_node_array){ + .num = len(l), + .keys = NULL, + .values = struct mpv_node[len(l)] { + { .format = MPV_NODE_STRING, .u.string = l[0] }, + { .format = MPV_NODE_STRING, .u.string = l[1] }, + ... + } + } + } + """ + char_ps = [ c_char_p(_mpv_coax_proptype(e, str)) for e in l ] + node_list = MpvNodeList( + num=len(l), + keys=None, + values=( MpvNode * len(l))( *[ MpvNode( + format=MpvFormat.STRING, + val=cast(pointer(p), POINTER(c_longlong)).contents) # NOTE: ctypes is kinda crappy here + for p in char_ps ])) + node = MpvNode( + format=MpvFormat.NODE_ARRAY, + val=addressof(node_list)) + return char_ps, node_list, node, cast(pointer(node), c_void_p) def _event_generator(handle): @@ -374,16 +424,11 @@ raise StopIteration() yield event -def load_lua(): - """ Use this function if you intend to use mpv's built-in lua interpreter. This is e.g. needed for playback of - youtube urls. """ - CDLL('liblua.so', mode=RTLD_GLOBAL) - def _event_loop(event_handle, playback_cond, event_callbacks, message_handlers, property_handlers, log_handler): for event in _event_generator(event_handle): try: - devent = event.as_dict() # copy data from ctypes + devent = event.as_dict(decoder=lazy_decoder) # copy data from ctypes eid = devent['event_id'] for callback in event_callbacks: callback(devent) @@ -392,9 +437,9 @@ playback_cond.notify_all() if eid == MpvEventID.PROPERTY_CHANGE: pc = devent['event'] - name, value, fmt = pc['name'], pc['value'], pc['format'] + name, value, _fmt = pc['name'], pc['value'], pc['format'] - for handler in property_handlers[name][fmt]: + for handler in property_handlers[name]: handler(name, value) if eid == MpvEventID.LOG_MESSAGE and log_handler is not None: ev = devent['event'] @@ -410,21 +455,68 @@ except Exception as e: traceback.print_exc() -class OSDPropertyProxy: +_py_to_mpv = lambda name: name.replace('_', '-') +_mpv_to_py = lambda name: name.replace('-', '_') + +class _Proxy: def __init__(self, mpv): - self.mpv = mpv + super().__setattr__('mpv', mpv) + +class _PropertyProxy(_Proxy): + def __dir__(self): + return super().__dir__() + [ name.replace('-', '_') for name in self.mpv.property_list ] + +class _FileLocalProxy(_Proxy): + def __getitem__(self, name): + return self.mpv.__getitem__(name, file_local=True) + + def __setitem__(self, name, value): + return self.mpv.__setitem__(name, value, file_local=True) + + def __iter__(self): + return iter(self.mpv) + +class _OSDPropertyProxy(_PropertyProxy): + def __getattr__(self, name): + return self.mpv._get_property(_py_to_mpv(name), fmt=MpvFormat.OSD_STRING) + + def __setattr__(self, _name, _value): + raise AttributeError('OSD properties are read-only. Please use the regular property API for writing.') + +class _DecoderPropertyProxy(_PropertyProxy): + def __init__(self, mpv, decoder): + super().__init__(mpv) + super().__setattr__('_decoder', decoder) + + def __getattr__(self, name): + return self.mpv._get_property(_py_to_mpv(name), decoder=self._decoder) + + def __setattr__(self, name, value): + setattr(self.mpv, _py_to_mpv(name), value) class MPV(object): - """ See man mpv(1) for the details of the implemented commands. All mpv - properties can be accessed as ```my_mpv.some_property``` and all mpv - options can be accessed as ```my_mpv['some-option']```. """ - def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, **extra_mpv_opts): - """ Create an MPV instance. + """See man mpv(1) for the details of the implemented commands. All mpv properties can be accessed as + ``my_mpv.some_property`` and all mpv options can be accessed as ``my_mpv['some-option']``. - Extra arguments and extra keyword arguments will be passed to mpv as options. """ + By default, properties are returned as decoded ``str`` and an error is thrown if the value does not contain valid + utf-8. To get a decoded ``str`` if possibly but ``bytes`` instead of an error if not, use + ``my_mpv.lazy.some_property``. To always get raw ``bytes``, use ``my_mpv.raw.some_property``. To access a + property's decoded OSD value, use ``my_mpv.osd.some_property``. + + To get API information on an option, use ``my_mpv.option_info('option-name')``. To get API information on a + property, use ``my_mpv.properties['property-name']``. Take care to use mpv's dashed-names instead of the + underscore_names exposed on the python object. + + To make your program not barf hard the first time its used on a weird file system **always** access properties + containing file names or file tags through ``MPV.raw``. """ + def __init__(self, *extra_mpv_flags, log_handler=None, start_event_thread=True, loglevel=None, **extra_mpv_opts): + """Create an MPV instance. + + Extra arguments and extra keyword arguments will be passed to mpv as options. + """ - self._event_thread = None self.handle = _mpv_create() + self._event_thread = None _mpv_set_option_string(self.handle, b'audio-display', b'no') istr = lambda o: ('yes' if o else 'no') if type(o) is bool else str(o) @@ -436,15 +528,22 @@ finally: _mpv_initialize(self.handle) - self.osd = OSDPropertyProxy(self) + self.osd = _OSDPropertyProxy(self) + self.file_local = _FileLocalProxy(self) + self.raw = _DecoderPropertyProxy(self, identity_decoder) + self.strict = _DecoderPropertyProxy(self, strict_decoder) + self.lazy = _DecoderPropertyProxy(self, lazy_decoder) + self._event_callbacks = [] - self._property_handlers = collections.defaultdict(lambda: collections.defaultdict(lambda: [])) + self._property_handlers = collections.defaultdict(lambda: []) self._message_handlers = {} self._key_binding_handlers = {} self._playback_cond = threading.Condition() self._event_handle = _mpv_create_client(self.handle, b'py_event_handler') self._loop = partial(_event_loop, self._event_handle, self._playback_cond, self._event_callbacks, self._message_handlers, self._property_handlers, log_handler) + if loglevel is not None or log_handler is not None: + self.set_loglevel(loglevel or 'terminal-default') if start_event_thread: self._event_thread = threading.Thread(target=self._loop, name='MPVEventHandlerThread') self._event_thread.setDaemon(True) @@ -452,19 +551,15 @@ else: self._event_thread = None - if log_handler is not None: - self.set_loglevel('terminal-default') - def wait_for_playback(self): - """ Waits until playback of the current title is paused or done """ + """Waits until playback of the current title is paused or done.""" with self._playback_cond: self._playback_cond.wait() def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True): - """ Waits until ```cond``` evaluates to a truthy value on the named - property. This can be used to wait for properties such as - ```idle_active``` indicating the player is done with regular playback - and just idling around """ + """Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for + properties such as ``idle_active`` indicating the player is done with regular playback and just idling around + """ sema = threading.Semaphore(value=0) def observer(name, val): if cond(val): @@ -479,9 +574,9 @@ self.terminate() def terminate(self): - """ Pröperly terminates this player instance. Preferably use this - instead of relying on python's garbage collector to cause this to be - called from the object's destructor. """ + """Properly terminates this player instance. Preferably use this instead of relying on python's garbage + collector to cause this to be called from the object's destructor. + """ self.handle, handle = None, self.handle if threading.current_thread() is self._event_thread: # Handle special case to allow event handle to be detached. @@ -494,60 +589,88 @@ self._event_thread.join() def set_loglevel(self, level): - """ Set MPV's log level. This adjusts which output will be sent to this - object's log handlers. If you just want mpv's regular terminal output, - you don't need to adjust this but just need to pass a log handler to - the MPV constructur such as ```MPV(log_handler=print)```. + """Set MPV's log level. This adjusts which output will be sent to this object's log handlers. If you just want + mpv's regular terminal output, you don't need to adjust this but just need to pass a log handler to the MPV + constructur such as ``MPV(log_handler=print)``. - Valid log levels are "no", "fatal", "error", "warn", "info", "v" - "debug" and "trace". For details see your mpv's client.h header file """ + Valid log levels are "no", "fatal", "error", "warn", "info", "v" "debug" and "trace". For details see your mpv's + client.h header file. + """ _mpv_request_log_messages(self._event_handle, level.encode('utf-8')) def command(self, name, *args): - """ Execute a raw command """ + """Execute a raw command.""" args = [name.encode('utf-8')] + [ (arg if type(arg) is bytes else str(arg).encode('utf-8')) for arg in args if arg is not None ] + [None] _mpv_command(self.handle, (c_char_p*len(args))(*args)) + def node_command(self, name, *args, decoder=strict_decoder): + _1, _2, _3, pointer = _make_node_str_list([name, *args]) + out = cast(create_string_buffer(sizeof(MpvNode)), POINTER(MpvNode)) + outptr = out #byref(out) + ppointer = cast(pointer, POINTER(MpvNode)) + _mpv_command_node(self.handle, ppointer, outptr) + rv = MpvNode.node_cast_value(outptr, MpvFormat.NODE, decoder) + _mpv_free_node_contents(outptr) + return rv + def seek(self, amount, reference="relative", precision="default-precise"): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv seek command, see man mpv(1).""" self.command('seek', amount, reference, precision) def revert_seek(self): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv revert_seek command, see man mpv(1).""" self.command('revert_seek'); def frame_step(self): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv frame_step command, see man mpv(1).""" self.command('frame_step') def frame_back_step(self): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv frame_back_step command, see man mpv(1).""" self.command('frame_back_step') - def _add_property(self, name, value=None): - self.command('add_property', name, value) - - def _cycle_property(self, name, direction='up'): - self.command('cycle_property', name, direction) + def property_add(self, name, value=1): + """Add the given value to the property's value. On overflow or underflow, clamp the property to the maximum. If + ``value`` is omitted, assume ``1``. + """ + self.command('add', name, value) - def _multiply_property(self, name, factor): - self.command('multiply_property', name, factor) + def property_multiply(self, name, factor): + """Multiply the value of a property with a numeric factor.""" + self.command('multiply', name, factor) + + def cycle(self, name, direction='up'): + """Cycle the given property. ``up`` and ``down`` set the cycle direction. On overflow, set the property back to + the minimum, on underflow set it to the maximum. If ``up`` or ``down`` is omitted, assume ``up``. + """ + self.command('cycle', name, direction) def screenshot(self, includes='subtitles', mode='single'): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv screenshot command, see man mpv(1).""" self.command('screenshot', includes, mode) def screenshot_to_file(self, filename, includes='subtitles'): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv screenshot_to_file command, see man mpv(1).""" self.command('screenshot_to_file', filename.encode(fs_enc), includes) + def screenshot_raw(self, includes='subtitles'): + """Mapped mpv screenshot_raw command, see man mpv(1). Returns a pillow Image object.""" + from PIL import Image + res = self.node_command('screenshot-raw', includes) + if res['format'] != 'bgr0': + raise ValueError('Screenshot in unknown format "{}". Currently, only bgr0 is supported.' + .format(res['format'])) + img = Image.frombytes('RGBA', (res['w'], res['h']), res['data']) + b,g,r,a = img.split() + return Image.merge('RGB', (r,g,b)) + def playlist_next(self, mode='weak'): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv playlist_next command, see man mpv(1).""" self.command('playlist_next', mode) def playlist_prev(self, mode='weak'): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv playlist_prev command, see man mpv(1).""" self.command('playlist_prev', mode) @staticmethod @@ -555,196 +678,179 @@ return ','.join('{}={}'.format(str(key), str(val)) for key, val in options.items()) def loadfile(self, filename, mode='replace', **options): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv loadfile command, see man mpv(1).""" self.command('loadfile', filename.encode(fs_enc), mode, MPV._encode_options(options)) def loadlist(self, playlist, mode='replace'): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv loadlist command, see man mpv(1).""" self.command('loadlist', playlist.encode(fs_enc), mode) def playlist_clear(self): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv playlist_clear command, see man mpv(1).""" self.command('playlist_clear') def playlist_remove(self, index='current'): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv playlist_remove command, see man mpv(1).""" self.command('playlist_remove', index) def playlist_move(self, index1, index2): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv playlist_move command, see man mpv(1).""" self.command('playlist_move', index1, index2) def run(self, command, *args): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv run command, see man mpv(1).""" self.command('run', command, *args) def quit(self, code=None): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv quit command, see man mpv(1).""" self.command('quit', code) def quit_watch_later(self, code=None): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv quit_watch_later command, see man mpv(1).""" self.command('quit_watch_later', code) def sub_add(self, filename): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv sub_add command, see man mpv(1).""" self.command('sub_add', filename.encode(fs_enc)) def sub_remove(self, sub_id=None): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv sub_remove command, see man mpv(1).""" self.command('sub_remove', sub_id) def sub_reload(self, sub_id=None): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv sub_reload command, see man mpv(1).""" self.command('sub_reload', sub_id) def sub_step(self, skip): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv sub_step command, see man mpv(1).""" self.command('sub_step', skip) def sub_seek(self, skip): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv sub_seek command, see man mpv(1).""" self.command('sub_seek', skip) def toggle_osd(self): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv osd command, see man mpv(1).""" self.command('osd') def show_text(self, string, duration='-', level=None): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv show_text command, see man mpv(1).""" self.command('show_text', string, duration, level) def show_progress(self): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv show_progress command, see man mpv(1).""" self.command('show_progress') def discnav(self, command): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv discnav command, see man mpv(1).""" self.command('discnav', command) def write_watch_later_config(self): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv write_watch_later_config command, see man mpv(1).""" self.command('write_watch_later_config') def overlay_add(self, overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv overlay_add command, see man mpv(1).""" self.command('overlay_add', overlay_id, x, y, file_or_fd, offset, fmt, w, h, stride) def overlay_remove(self, overlay_id): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv overlay_remove command, see man mpv(1).""" self.command('overlay_remove', overlay_id) def script_message(self, *args): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv script_message command, see man mpv(1).""" self.command('script_message', *args) def script_message_to(self, target, *args): - """ Mapped mpv seek command, see man mpv(1). """ + """Mapped mpv script_message_to command, see man mpv(1).""" self.command('script_message_to', target, *args) - def observe_property(self, name, handler, *, force_fmt=None): - """ Register an observer on the named property. An observer is a function that is called with the new property - value every time the property's value is changed. The basic function signature is ```fun(property_name, - new_value)``` with new_value being the decoded property value as a python object. This function can be used as a + def observe_property(self, name, handler): + """Register an observer on the named property. An observer is a function that is called with the new property + value every time the property's value is changed. The basic function signature is ``fun(property_name, + new_value)`` with new_value being the decoded property value as a python object. This function can be used as a function decorator if no handler is given. - By default, you'll get whatever return type you'd get if you asked the regular property access API. To override - this behavior, you can specify a forced return type from ```MpvFormat``` in force_fmt + To unregister the observer, call either of ``mpv.unobserve_property(name, handler)``, + ``mpv.unobserve_all_properties(handler)`` or the handler's ``unregister_mpv_properties`` attribute:: - To uunregister the observer, call either of ```mpv.unobserve_property(name, handler)```, - ```mpv.unobserve_all_properties(handler)``` or the handler's ```unregister_mpv_properties``` attribute: + @player.observe_property('volume') + def my_handler(new_volume, *): + print("It's loud!", volume) - ``` - @player.observe_property('volume') - def my_handler(new_volume, *): - print("It's loud!", volume) - - my_handler.unregister_mpv_properties() - ``` """ - fmt = force_fmt or MpvFormat.NODE - self._property_handlers[name][fmt].append(handler) - _mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), fmt) + my_handler.unregister_mpv_properties() + """ + self._property_handlers[name].append(handler) + _mpv_observe_property(self._event_handle, hash(name)&0xffffffffffffffff, name.encode('utf-8'), MpvFormat.NODE) - def property_observer(self, name, *, force_fmt=None): - """ Function decorator to register a property observer. See ```MPV.observe_property``` for details. """ + def property_observer(self, name): + """Function decorator to register a property observer. See ``MPV.observe_property`` for details.""" def wrapper(fun): - self.observe_property(name, fun, force_fmt=force_fmt) - fun.unobserve_mpv_properties = lambda: self.unobserve_property(None, fun) + self.observe_property(name, fun) + fun.unobserve_mpv_properties = lambda: self.unobserve_property(name, fun) return fun return wrapper def unobserve_property(self, name, handler): - """ Unregister a property observer. This requires both the observed property's name and the handler function - that was originally registered as one handler could be registered for several properties. To unregister a - handler from *all* observed properties see ```unobserve_all_properties```. """ - fmts = self._property_handlers[name] - for fmt, handlers in fmts.items(): - handlers.remove(handler) - - # remove all properties that have no handlers - empty_props = [ - fmt for fmt, handler in fmts.items() if not handler - ] - - for fmt in empty_props: - del fmts[fmt] - - if not fmts: + """Unregister a property observer. This requires both the observed property's name and the handler function that + was originally registered as one handler could be registered for several properties. To unregister a handler + from *all* observed properties see ``unobserve_all_properties``. + """ + self._property_handlers[name].remove(handler) + if not self._property_handlers[name]: _mpv_unobserve_property(self._event_handle, hash(name)&0xffffffffffffffff) def unobserve_all_properties(self, handler): - """ Unregister a property observer from *all* observed properties. """ + """Unregister a property observer from *all* observed properties.""" for name in self._property_handlers: self.unobserve_property(name, handler) def register_message_handler(self, target, handler=None): - """ Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the + """Register a mpv script message handler. This can be used to communicate with embedded lua scripts. Pass the script message target name this handler should be listening to and the handler function. WARNING: Only one handler can be registered at a time for any given target. - To unregister the message handler, call its unregister_mpv_messages function: + To unregister the message handler, call its ``unregister_mpv_messages`` function:: - ``` - player = mpv.MPV() - @player.message_handler('foo') - def my_handler(some, args): - print(args) + player = mpv.MPV() + @player.message_handler('foo') + def my_handler(some, args): + print(args) - my_handler.unregister_mpv_messages() - ``` """ + my_handler.unregister_mpv_messages() + """ self._register_message_handler_internal(target, handler) - def _register_script_message_handler_internal(self, target, handler): - handler.mpv_message_targets = getattr(handler, 'mpv_script_message_targets', []) + [target] + def _register_message_handler_internal(self, target, handler): self._message_handlers[target] = handler def unregister_message_handler(self, target_or_handler): - """ Unregister a mpv script message handler for the given script message target name. + """Unregister a mpv script message handler for the given script message target name. - You can also call the ```unregister_mpv_messages``` function attribute set on the handler function when it is - registered. """ - if isinstance(target, str): - del self._message_handlers[target] + You can also call the ``unregister_mpv_messages`` function attribute set on the handler function when it is + registered. + """ + if isinstance(target_or_handler, str): + del self._message_handlers[target_or_handler] else: for key, val in self._message_handlers.items(): if val == target_or_handler: del self._message_handlers[key] def message_handler(self, target): - """ Decorator to register a mpv script message handler. + """Decorator to register a mpv script message handler. WARNING: Only one handler can be registered at a time for any given target. - To unregister the message handler, call its unregister_mpv_messages function: + To unregister the message handler, call its ``unregister_mpv_messages`` function:: - ``` - player = mpv.MPV() - @player.message_handler('foo') - def my_handler(some, args): - print(args) + player = mpv.MPV() + @player.message_handler('foo') + def my_handler(some, args): + print(args) - my_handler.unregister_mpv_messages() + my_handler.unregister_mpv_messages() """ def register(handler): self._register_message_handler_internal(target, handler) @@ -753,40 +859,37 @@ return register def register_event_callback(self, callback): - """ Register a blanket event callback receiving all event types. + """Register a blanket event callback receiving all event types. - To unregister the event callback, call its unregister_mpv_events function: + To unregister the event callback, call its ``unregister_mpv_events`` function:: - ``` - player = mpv.MPV() - @player.event_callback('shutdown') - def my_handler(event): - print('It ded.') + player = mpv.MPV() + @player.event_callback('shutdown') + def my_handler(event): + print('It ded.') - my_handler.unregister_mpv_events() + my_handler.unregister_mpv_events() """ - callback.unregister_mpv_events = partial(self.unregister_event_callback, callback) self._event_callbacks.append(callback) def unregister_event_callback(self, callback): - """ Unregiser an event callback. """ + """Unregiser an event callback.""" self._event_callbacks.remove(callback) def event_callback(self, *event_types): - """ Function decorator to register a blanket event callback for the given event types. Event types can be given + """Function decorator to register a blanket event callback for the given event types. Event types can be given as str (e.g. 'start-file'), integer or MpvEventID object. WARNING: Due to the way this is filtering events, this decorator cannot be chained with itself. - To unregister the event callback, call its unregister_mpv_events function: + To unregister the event callback, call its ``unregister_mpv_events`` function:: - ``` - player = mpv.MPV() - @player.event_callback('shutdown') - def my_handler(event): - print('It ded.') + player = mpv.MPV() + @player.event_callback('shutdown') + def my_handler(event): + print('It ded.') - my_handler.unregister_mpv_events() + my_handler.unregister_mpv_events() """ def register(callback): types = [MpvEventID.from_str(t) if isinstance(t, str) else t for t in event_types] or MpvEventID.ANY @@ -803,55 +906,83 @@ def _binding_name(callback_or_cmd): return 'py_kb_{:016x}'.format(hash(callback_or_cmd)&0xffffffffffffffff) + def on_key_press(self, keydef, mode='force'): + """Function decorator to register a simplified key binding. The callback is called whenever the key given is + *pressed*. + + To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute:: + + player = mpv.MPV() + @player.on_key_press('Q') + def binding(): + print('blep') + + binding.unregister_mpv_key_bindings() + + WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register + a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So + don't do that. + + The BIG FAT WARNING regarding untrusted keydefs from the key_binding method applies here as well. + """ + def register(fun): + @self.key_binding(keydef, mode) + @wraps(fun) + def wrapper(state='p-', name=None): + if state[0] in ('d', 'p'): + fun() + return wrapper + return register + def key_binding(self, keydef, mode='force'): - """ Function decorator to register a key binding. + """Function decorator to register a low-level key binding. - The callback function signature is ```fun(key_state, key_name)``` where ```key_state``` is either ```'U'``` for - "key up" or ```'D'``` for "key down". + The callback function signature is ``fun(key_state, key_name)`` where ``key_state`` is either ``'U'`` for "key + up" or ``'D'`` for "key down". - The keydef format is: ```[Shift+][Ctrl+][Alt+][Meta+]<key>``` where ```<key>``` is either the literal character - the key produces (ASCII or Unicode character), or a symbolic name (as printed by ```mpv --input-keylist```) + The keydef format is: ``[Shift+][Ctrl+][Alt+][Meta+]<key>`` where ``<key>`` is either the literal character the + key produces (ASCII or Unicode character), or a symbolic name (as printed by ``mpv --input-keylist``). - To unregister the callback function, you can call its ```unregister_mpv_key_bindings``` attribute: + To unregister the callback function, you can call its ``unregister_mpv_key_bindings`` attribute:: - ``` - player = mpv.MPV() - @player.key_binding('Q') - def binding(state, name): - print('blep') + player = mpv.MPV() + @player.key_binding('Q') + def binding(state, name): + print('blep') - binding.unregister_mpv_key_bindings() - ``` + binding.unregister_mpv_key_bindings() WARNING: For a single keydef only a single callback/command can be registered at the same time. If you register a binding multiple times older bindings will be overwritten and there is a possibility of references leaking. So don't do that. - BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary - code exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in - the first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, - this is completely fine--but, if you are about to pass untrusted input into this parameter, better double-check - whether this is secure in your case. """ + BIG FAT WARNING: mpv's key binding mechanism is pretty powerful. This means, you essentially get arbitrary code + exectution through key bindings. This interface makes some limited effort to sanitize the keydef given in the + first parameter, but YOU SHOULD NOT RELY ON THIS IN FOR SECURITY. If your input comes from config files, this is + completely fine--but, if you are about to pass untrusted input into this parameter, better double-check whether + this is secure in your case. + """ + def register(fun): + fun.mpv_key_bindings = getattr(fun, 'mpv_key_bindings', []) + [keydef] + def unregister_all(): + for keydef in fun.mpv_key_bindings: + self.unregister_key_binding(keydef) + fun.unregister_mpv_key_bindings = unregister_all - def wrapper(fun): self.register_key_binding(keydef, fun, mode) return fun - return wrapper + return register def register_key_binding(self, keydef, callback_or_cmd, mode='force'): - """ Register a key binding. This takes an mpv keydef and either a string containing a mpv - command or a python callback function. See ```MPV.key_binding``` for details. """ + """Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python + callback function. See ``MPV.key_binding`` for details. + """ if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\w+)', keydef): raise ValueError('Invalid keydef. Expected format: [Shift+][Ctrl+][Alt+][Meta+]<key>\n' '<key> is either the literal character the key produces (ASCII or Unicode character), or a ' 'symbolic name (as printed by --input-keylist') binding_name = MPV._binding_name(keydef) if callable(callback_or_cmd): - callback_or_cmd.mpv_key_bindings = getattr(callback_or_cmd, 'mpv_key_bindings', []) + [keydef] - def unregister_all(): - for keydef in callback_or_cmd.mpv_key_bindings: - self.unregister_key_binding(keydef) - callback_or_cmd.unregister_mpv_key_bindings = unregister_all self._key_binding_handlers[binding_name] = callback_or_cmd self.register_message_handler('key-binding', self._handle_key_binding_message) self.command('define-section', @@ -860,13 +991,13 @@ self.command('define-section', binding_name, '{} {}'.format(keydef, callback_or_cmd), mode) else: raise TypeError('register_key_binding expects either an str with an mpv command or a python callable.') - self.command('enable-section', binding_name) + self.command('enable-section', binding_name, 'allow-hide-cursor+allow-vo-dragging') - def _handle_key_binding_message(self, binding_name, key_state, key_name): + def _handle_key_binding_message(self, binding_name, key_state, key_name=None): self._key_binding_handlers[binding_name](key_state, key_name) def unregister_key_binding(self, keydef): - """ Unregister a key binding by keydef """ + """Unregister a key binding by keydef.""" binding_name = MPV._binding_name(keydef) self.command('disable-section', binding_name) self.command('define-section', binding_name, '') @@ -877,300 +1008,77 @@ # Convenience functions def play(self, filename): - """ Play a path or URL (requires ```ytdl``` option to be set) """ + """Play a path or URL (requires ``ytdl`` option to be set).""" self.loadfile(filename) @property def playlist_filenames(self): - """ Return all playlist item file names/URLs as a list of strs """ + """Return all playlist item file names/URLs as a list of strs.""" return [element['filename'] for element in self.playlist] def playlist_append(self, filename, **options): - """ Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use - ```MPV.loadfile(filename, 'append-play')```. """ + """Append a path or URL to the playlist. This does not start playing the file automatically. To do that, use + ``MPV.loadfile(filename, 'append-play')``.""" self.loadfile(filename, 'append', **options) # Property accessors - def _get_property(self, name, proptype=str, decode_str=False, force_format=None): - fmt = force_format or {int: MpvFormat.INT64, - float: MpvFormat.DOUBLE, - bool: MpvFormat.FLAG, - str: MpvFormat.STRING, - bytes: MpvFormat.STRING, - _commalist: MpvFormat.STRING, - MpvFormat.NODE: MpvFormat.NODE}[proptype] - + def _get_property(self, name, decoder=strict_decoder, fmt=MpvFormat.NODE): out = cast(create_string_buffer(sizeof(c_void_p)), c_void_p) outptr = byref(out) try: cval = _mpv_get_property(self.handle, name.encode('utf-8'), fmt, outptr) - rv = MpvNode.node_cast_value(outptr, fmt, decode_str or proptype in (str, _commalist)) - - if proptype is _commalist: - rv = proptype(rv) - - if proptype is str: - _mpv_free(out) - elif proptype is MpvFormat.NODE: + rv = MpvNode.node_cast_value(outptr, fmt, decoder) + if fmt is MpvFormat.NODE: _mpv_free_node_contents(outptr) - return rv except PropertyUnavailableError as ex: return None - def _set_property(self, name, value, proptype=str): + def _set_property(self, name, value): ename = name.encode('utf-8') - if type(value) is bytes: - _mpv_set_property_string(self.handle, ename, value) - elif type(value) is bool: - _mpv_set_property_string(self.handle, ename, b'yes' if value else b'no') - elif proptype in (str, int, float): - _mpv_set_property_string(self.handle, ename, str(proptype(value)).encode('utf-8')) + if isinstance(value, (list, set, dict)): + _1, _2, _3, pointer = _make_node_str_list(value) + _mpv_set_property(self.handle, ename, MpvFormat.NODE, pointer) else: - raise TypeError('Cannot set {} property {} to value of type {}'.format(proptype, name, type(value))) + _mpv_set_property_string(self.handle, ename, _mpv_coax_proptype(value)) + + def __getattr__(self, name): + return self._get_property(_py_to_mpv(name), lazy_decoder) + + def __setattr__(self, name, value): + try: + if name != 'handle' and not name.startswith('_'): + self._set_property(_py_to_mpv(name), value) + else: + super().__setattr__(name, value) + except AttributeError: + super().__setattr__(name, value) + + def __dir__(self): + return super().__dir__() + [ name.replace('-', '_') for name in self.property_list ] + + @property + def properties(self): + return { name: self.option_info(name) for name in self.property_list } # Dict-like option access def __getitem__(self, name, file_local=False): - """ Get an option value """ + """Get an option value.""" prefix = 'file-local-options/' if file_local else 'options/' - return self._get_property(prefix+name) + return self._get_property(prefix+name, lazy_decoder) def __setitem__(self, name, value, file_local=False): - """ Set an option value """ + """Set an option value.""" prefix = 'file-local-options/' if file_local else 'options/' return self._set_property(prefix+name, value) def __iter__(self): - """ Iterate over all option names """ + """Iterate over all option names.""" return iter(self.options) def option_info(self, name): - """ Get information on the given option """ - return self._get_property('option-info/'+name) - -def _commalist(propval=''): - return str(propval).split(',') - -_node = MpvFormat.NODE - -ALL_PROPERTIES = { - 'osd-level': (int, 'rw'), - 'osd-scale': (float, 'rw'), - 'loop': (str, 'rw'), - 'loop-file': (str, 'rw'), - 'speed': (float, 'rw'), - 'filename': (bytes, 'r'), - 'file-size': (int, 'r'), - 'path': (bytes, 'r'), - 'media-title': (bytes, 'r'), - 'stream-pos': (int, 'rw'), - 'stream-end': (int, 'r'), - 'length': (float, 'r'), # deprecated for ages now - 'duration': (float, 'r'), - 'avsync': (float, 'r'), - 'total-avsync-change': (float, 'r'), -# 'drop-frame-count': (int, 'r'), - 'decoder-frame-drop-count': (int, 'r'), - 'percent-pos': (float, 'rw'), -# 'ratio-pos': (float, 'rw'), - 'audio-pts': (float, 'r'), - 'time-pos': (float, 'rw'), - 'time-start': (float, 'r'), - 'time-remaining': (float, 'r'), - 'playtime-remaining': (float, 'r'), - 'chapter': (int, 'rw'), - 'edition': (str, 'rw'), - 'disc-titles': (int, 'r'), - 'disc-title': (str, 'rw'), -# 'disc-menu-active': (bool, 'r'), - 'chapters': (int, 'r'), - 'editions': (int, 'r'), - 'angle': (int, 'rw'), - 'pause': (bool, 'rw'), - 'core-idle': (bool, 'r'), - 'cache': (str, 'r'), - 'cache-size': (int, 'rw'), - 'cache-free': (int, 'r'), - 'cache-used': (int, 'r'), - 'cache-speed': (int, 'r'), - 'cache-idle': (bool, 'r'), - 'cache-buffering-state': (int, 'r'), - 'paused-for-cache': (bool, 'r'), -# 'pause-for-cache': (bool, 'r'), - 'eof-reached': (bool, 'r'), -# 'pts-association-mode': (str, 'rw'), - 'hr-seek': (str, 'rw'), - 'volume': (float, 'rw'), - 'volume-max': (int, 'rw'), - 'ao-volume': (float, 'rw'), - 'mute': (bool, 'rw'), - 'ao-mute': (bool, 'rw'), - 'audio-speed-correction': (float, 'r'), - 'audio-delay': (float, 'rw'), - 'audio-format': (str, 'r'), - 'audio-codec': (str, 'r'), - 'audio-codec-name': (str, 'r'), - 'audio-bitrate': (float, 'r'), - 'packet-audio-bitrate': (float, 'r'), - 'audio-samplerate': (int, 'r'), - 'audio-channels': (str, 'r'), - 'aid': (str, 'rw'), - 'audio': (str, 'rw'), # alias for aid - 'balance': (int, 'rw'), - 'fullscreen': (bool, 'rw'), - 'deinterlace': (str, 'rw'), - 'colormatrix': (str, 'rw'), - 'colormatrix-input-range': (str, 'rw'), -# 'colormatrix-output-range': (str, 'rw'), - 'colormatrix-primaries': (str, 'rw'), - 'ontop': (bool, 'rw'), - 'border': (bool, 'rw'), - 'framedrop': (str, 'rw'), - 'gamma': (float, 'rw'), - 'brightness': (int, 'rw'), - 'contrast': (int, 'rw'), - 'saturation': (int, 'rw'), - 'hue': (int, 'rw'), - 'hwdec': (str, 'rw'), - 'panscan': (float, 'rw'), - 'video-format': (str, 'r'), - 'video-codec': (str, 'r'), - 'video-bitrate': (float, 'r'), - 'packet-video-bitrate': (float, 'r'), - 'width': (int, 'r'), - 'height': (int, 'r'), - 'dwidth': (int, 'r'), - 'dheight': (int, 'r'), - 'container-fps': (float, 'r'), - 'estimated-vf-fps': (float, 'r'), - 'window-scale': (float, 'rw'), - 'video-aspect': (str, 'rw'), - 'osd-width': (int, 'r'), - 'osd-height': (int, 'r'), - 'osd-par': (float, 'r'), - 'vid': (str, 'rw'), - 'video': (str, 'rw'), # alias for vid - 'video-align-x': (float, 'rw'), - 'video-align-y': (float, 'rw'), - 'video-pan-x': (float, 'rw'), - 'video-pan-y': (float, 'rw'), - 'video-zoom': (float, 'rw'), - 'video-unscaled': (bool, 'w'), - 'video-speed-correction': (float, 'r'), - 'program': (int, 'w'), - 'sid': (str, 'rw'), - 'sub': (str, 'rw'), # alias for sid - 'secondary-sid': (str, 'rw'), - 'sub-delay': (float, 'rw'), - 'sub-pos': (int, 'rw'), - 'sub-visibility': (bool, 'rw'), - 'sub-forced-only': (bool, 'rw'), - 'sub-scale': (float, 'rw'), - 'sub-bitrate': (float, 'r'), - 'sub-text': (str, 'r'), - 'packet-sub-bitrate': (float, 'r'), -# 'ass-use-margins': (bool, 'rw'), - 'ass-vsfilter-aspect-compat': (bool, 'rw'), - 'ass-style-override': (str, 'rw'), -# 'stream-capture': (str, 'rw'), - 'tv-brightness': (int, 'rw'), - 'tv-contrast': (int, 'rw'), - 'tv-saturation': (int, 'rw'), - 'tv-hue': (int, 'rw'), - 'playlist-pos': (int, 'rw'), - 'playlist-pos-1': (int, 'rw'), # ugh. - 'playlist-count': (int, 'r'), -# 'quvi-format': (str, 'rw'), - 'seekable': (bool, 'r'), - 'seeking': (bool, 'r'), - 'partially-seekable': (bool, 'r'), - 'playback-abort': (bool, 'r'), - 'cursor-autohide': (str, 'rw'), - 'audio-device': (str, 'rw'), - 'current-vo': (str, 'r'), - 'current-ao': (str, 'r'), - 'audio-out-detected-device': (str, 'r'), - 'protocol-list': (str, 'r'), - 'mpv-version': (str, 'r'), - 'mpv-configuration': (str, 'r'), - 'ffmpeg-version': (str, 'r'), - 'display-sync-active': (bool, 'r'), - 'stream-open-filename': (bytes, 'rw'), # Undocumented - 'file-format': (_commalist,'r'), # Be careful with this one. - 'mistimed-frame-count': (int, 'r'), - 'vsync-ratio': (float, 'r'), -# 'vo-drop-frame-count': (int, 'r'), - 'frame-drop-count': (int, 'r'), - 'vo-delayed-frame-count': (int, 'r'), - 'playback-time': (float, 'rw'), - 'demuxer-cache-duration': (float, 'r'), - 'demuxer-cache-time': (float, 'r'), - 'demuxer-cache-idle': (bool, 'r'), - 'demuxer-start-time': (float, 'r'), - 'demuxer-via-network': (bool, 'r'), -# 'idle': (bool, 'r'), - 'idle-active': (bool, 'r'), # dat name - 'disc-title-list': (_commalist,'r'), - 'field-dominance': (str, 'rw'), - 'taskbar-progress': (bool, 'rw'), - 'on-all-workspaces': (bool, 'rw'), - 'video-output-levels': (str, 'r'), - 'vo-configured': (bool, 'r'), - 'hwdec-current': (str, 'r'), - 'hwdec-interop': (str, 'r'), - 'estimated-frame-count': (int, 'r'), - 'estimated-frame-number': (int, 'r'), - 'sub-use-margins': (bool, 'rw'), - 'ass-force-margins': (bool, 'rw'), - 'video-rotate': (str, 'rw'), - 'video-stereo-mode': (str, 'rw'), - 'ab-loop-a': (str, 'r'), # What a mess... - 'ab-loop-b': (str, 'r'), - 'dvb-channel': (str, 'w'), - 'dvb-channel-name': (str, 'rw'), - 'window-minimized': (bool, 'r'), - 'display-names': (_commalist, 'r'), - 'display-fps': (float, 'r'), # access apparently misdocumented in the manpage - 'estimated-display-fps': (float, 'r'), - 'vsync-jitter': (float, 'r'), - 'profile-list': (_node, 'r', False), - 'video-params': (_node, 'r', True), - 'video-dec-params': (_node, 'r', True), - 'video-out-params': (_node, 'r', True), - 'track-list': (_node, 'r', False), - 'playlist': (_node, 'r', False), - 'chapter-list': (_node, 'r', False), - 'vo-performance': (_node, 'r', True), - 'filtered-metadata': (_node, 'r', False), - 'metadata': (_node, 'r', False), - 'chapter-metadata': (_node, 'r', False), - 'vf-metadata': (_node, 'r', False), - 'af-metadata': (_node, 'r', False), - 'edition-list': (_node, 'r', False), - 'disc-titles': (_node, 'r', False), - 'audio-params': (_node, 'r', True), - 'audio-out-params': (_node, 'r', True), - 'audio-device-list': (_node, 'r', True), - 'video-frame-info': (_node, 'r', True), - 'decoder-list': (_node, 'r', True), - 'encoder-list': (_node, 'r', True), - 'vf': (_node, 'r', True), - 'af': (_node, 'r', True), - 'options': (_node, 'r', True), - 'file-local-options': (_node, 'r', True), - 'property-list': (_commalist,'r')} - -def _bindproperty(MPV, name, proptype, access, decode_str=False): - getter = lambda self: self._get_property(name, proptype, decode_str) - osdgetter = lambda osdself: osdself.mpv._get_property(name, force_format=MpvFormat.OSD_STRING) - setter = lambda self, value: self._set_property(name, value, proptype) - - def barf(*args): - raise NotImplementedError('Access denied') - - setattr(MPV, name.replace('-', '_'), property(getter if 'r' in access else barf, setter if 'w' in access else barf)) - setattr(OSDPropertyProxy, name.replace('-', '_'), property(osdgetter if 'r' in access else barf, barf)) - -for name, (proptype, access, *args) in ALL_PROPERTIES.items(): - _bindproperty(MPV, name, proptype, access, *args) - + """Get information on the given option.""" + try: + return self._get_property('option-info/'+name) + except AttributeError: + return None diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/python-mpv-0.2.3/python_mpv.egg-info/PKG-INFO new/python-mpv-0.3.6/python_mpv.egg-info/PKG-INFO --- old/python-mpv-0.2.3/python_mpv.egg-info/PKG-INFO 2017-05-26 18:03:16.000000000 +0200 +++ new/python-mpv-0.3.6/python_mpv.egg-info/PKG-INFO 2017-09-19 12:12:54.000000000 +0200 @@ -1,6 +1,6 @@ Metadata-Version: 1.1 Name: python-mpv -Version: 0.2.3 +Version: 0.3.6 Summary: A python interface to the mpv media player Home-page: https://github.com/jaseg/python-mpv Author: jaseg diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/python-mpv-0.2.3/python_mpv.egg-info/SOURCES.txt new/python-mpv-0.3.6/python_mpv.egg-info/SOURCES.txt --- old/python-mpv-0.2.3/python_mpv.egg-info/SOURCES.txt 2017-05-26 18:03:16.000000000 +0200 +++ new/python-mpv-0.3.6/python_mpv.egg-info/SOURCES.txt 2017-09-19 12:12:54.000000000 +0200 @@ -5,4 +5,5 @@ python_mpv.egg-info/PKG-INFO python_mpv.egg-info/SOURCES.txt python_mpv.egg-info/dependency_links.txt +python_mpv.egg-info/requires.txt python_mpv.egg-info/top_level.txt \ No newline at end of file diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/python-mpv-0.2.3/python_mpv.egg-info/requires.txt new/python-mpv-0.3.6/python_mpv.egg-info/requires.txt --- old/python-mpv-0.2.3/python_mpv.egg-info/requires.txt 1970-01-01 01:00:00.000000000 +0100 +++ new/python-mpv-0.3.6/python_mpv.egg-info/requires.txt 2017-09-19 12:12:54.000000000 +0200 @@ -0,0 +1,3 @@ + +[screenshot_raw] +Pillow diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/python-mpv-0.2.3/setup.cfg new/python-mpv-0.3.6/setup.cfg --- old/python-mpv-0.2.3/setup.cfg 2017-05-26 18:03:16.000000000 +0200 +++ new/python-mpv-0.3.6/setup.cfg 2017-09-19 12:12:54.000000000 +0200 @@ -3,6 +3,5 @@ [egg_info] tag_build = -tag_svn_revision = 0 tag_date = 0 diff -urN '--exclude=CVS' '--exclude=.cvsignore' '--exclude=.svn' '--exclude=.svnignore' old/python-mpv-0.2.3/setup.py new/python-mpv-0.3.6/setup.py --- old/python-mpv-0.2.3/setup.py 2017-05-26 18:02:28.000000000 +0200 +++ new/python-mpv-0.3.6/setup.py 2017-09-19 12:12:10.000000000 +0200 @@ -1,15 +1,18 @@ #!/usr/bin/env python3 -from setuptools import setup, find_packages +from setuptools import setup setup( name = 'python-mpv', - version = '0.2.3', + version = '0.3.6', py_modules = ['mpv'], - description = ('A python interface to the mpv media player'), + description = 'A python interface to the mpv media player', url = 'https://github.com/jaseg/python-mpv', author = 'jaseg', author_email = '[email protected]', license = 'AGPLv3+', + extras_require = { + 'screenshot_raw': ['Pillow'] + }, keywords = ['mpv', 'library', 'video', 'audio', 'player', 'display', 'multimedia'], classifiers = [ @@ -25,5 +28,5 @@ 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.5', 'Topic :: Multimedia :: Sound/Audio :: Players', - 'Topic :: Multimedia :: Video :: Display' ] + 'Topic :: Multimedia :: Video :: Display'] )
