platypush/platypush/plugins/media/mpv.py

410 lines
12 KiB
Python
Raw Normal View History

2019-02-18 01:17:21 +01:00
import os
2019-02-19 00:15:03 +01:00
import re
2019-02-18 01:17:21 +01:00
import threading
from platypush.context import get_bus, get_plugin
from platypush.plugins.media import PlayerState, MediaPlugin
from platypush.message.event.media import MediaPlayEvent, MediaPlayRequestEvent, \
MediaPauseEvent, MediaStopEvent, NewPlayingMediaEvent
from platypush.plugins import action
class MediaMpvPlugin(MediaPlugin):
"""
Plugin to control MPV instances
Requires:
* **python-mpv** (``pip install python-mpv``)
* **mpv** executable on your system
"""
2019-02-19 00:15:03 +01:00
_default_mpv_args = {
'ytdl': True,
'start_event_thread': True,
}
def __init__(self, args=None, *argv, **kwargs):
2019-02-18 01:17:21 +01:00
"""
Create the MPV wrapper.
:param args: Default arguments that will be passed to the mpv executable
2019-02-19 00:15:03 +01:00
as a key-value dict (names without the `--` prefix). See `man mpv`
for available options.
:type args: dict[str, str]
2019-02-18 01:17:21 +01:00
"""
super().__init__(*argv, **kwargs)
2019-02-19 00:15:03 +01:00
self.args = self._default_mpv_args
if args:
self.args.update(args)
2019-02-18 01:17:21 +01:00
self._player = None
self._is_playing_torrent = False
2019-02-19 00:15:03 +01:00
self._mpv_stopped_event = threading.Event()
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
def _init_mpv(self, args=None):
import mpv
2019-02-18 01:17:21 +01:00
if self._player:
try:
2019-02-19 00:15:03 +01:00
self.quit()
except Exception as e:
self.logger.debug('Failed to quit mpv before play: {}'.
format(str(e)))
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
mpv_args = self.args.copy()
if args:
mpv_args.update(args)
2019-02-18 01:17:21 +01:00
2019-02-19 01:02:07 +01:00
for k,v in self._env.items():
os.environ[k] = v
2019-02-19 00:15:03 +01:00
self._player = mpv.MPV(**mpv_args)
self._player.register_event_callback(self._event_callback())
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
def _event_callback(self):
playback_rebounce_event = threading.Event()
2019-02-19 00:15:03 +01:00
def callback(event):
from mpv import MpvEventID as Event
self.logger.info('Received mpv event: {}'.format(event))
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
evt = event.get('event_id')
if not evt:
return
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
bus = get_bus()
if evt == Event.FILE_LOADED or evt == Event.START_FILE:
playback_rebounce_event.set()
2019-02-19 00:15:03 +01:00
self._mpv_stopped_event.clear()
bus.post(NewPlayingMediaEvent(resource=self._get_current_resource()))
bus.post(MediaPlayEvent(resource=self._get_current_resource()))
elif evt == Event.PAUSE:
bus.post(MediaPauseEvent(resource=self._get_current_resource()))
elif evt == Event.UNPAUSE:
bus.post(MediaPlayEvent(resource=self._get_current_resource()))
elif evt == Event.SHUTDOWN:
playback_rebounced = playback_rebounce_event.wait(timeout=2)
if playback_rebounced:
playback_rebounce_event.clear()
return
self._player = None
2019-02-19 00:15:03 +01:00
self._mpv_stopped_event.set()
bus.post(MediaStopEvent())
return callback
def _get_youtube_link(self, resource):
base_url = 'https://youtu.be/'
regexes = ['^https://(www\.)?youtube.com/watch\?v=([^?&#]+)',
'^https://(www\.)?youtu.be.com/([^?&#]+)',
'^(youtube:video):([^?&#]+)']
for regex in regexes:
m = re.search(regex, resource)
if m: return base_url + m.group(2)
return None
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def execute(self, cmd, **args):
2019-02-18 01:17:21 +01:00
"""
Execute a raw mpv command.
"""
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
return self._player.command(cmd, *args)
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def play(self, resource, subtitles=None, **args):
2019-02-18 01:17:21 +01:00
"""
Play a resource.
:param resource: Resource to play - can be a local file or a remote URL
:type resource: str
:param subtitles: Path to optional subtitle file
:type subtitles: str
2019-02-19 00:15:03 +01:00
:param args: Extra runtime arguments that will be passed to the
mpv executable as a key-value dict (keys without `--` prefix)
:type args: dict[str,str]
2019-02-18 01:17:21 +01:00
"""
get_bus().post(MediaPlayRequestEvent(resource=resource))
2019-02-19 00:15:03 +01:00
self._init_mpv(args)
2019-02-18 01:17:21 +01:00
if subtitles:
2019-02-19 00:15:03 +01:00
args['sub_file'] = self.get_subtitles_file(subtitles)
2019-02-18 01:17:21 +01:00
resource = self._get_resource(resource)
if resource.startswith('file://'):
resource = resource[7:]
elif resource.startswith('magnet:?'):
self._is_playing_torrent = True
return get_plugin('media.webtorrent').play(resource)
2019-02-19 00:15:03 +01:00
else:
yt_resource = self._get_youtube_link(resource)
if yt_resource: resource = yt_resource
2019-02-18 01:17:21 +01:00
self._is_playing_torrent = False
2019-02-19 00:15:03 +01:00
ret = self._player.play(resource)
return self.status()
2019-02-18 01:17:21 +01:00
@action
def pause(self):
""" Toggle the paused state """
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
self._player.pause = not self._player.pause
return self.status()
2019-02-18 01:17:21 +01:00
def _stop_torrent(self):
if self._is_playing_torrent:
try:
get_plugin('media.webtorrent').quit()
except:
self.logger.warning('Cannot quit the webtorrent instance: {}'.
format(str(e)))
@action
def quit(self):
2019-02-19 00:15:03 +01:00
""" Quit the player (same as `stop`) """
2019-02-18 01:17:21 +01:00
self._stop_torrent()
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
self._player.quit()
self._player = None
# self._player.terminate()
return { 'state': PlayerState.STOP.value }
@action
def stop(self):
""" Stop the application (same as `quit`) """
return self.quit()
2019-02-18 01:17:21 +01:00
@action
def voldown(self, step=10.0):
""" Volume down by (default: 10)% """
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
return self.set_volume(self._player.volume-step)
2019-02-18 01:17:21 +01:00
@action
def volup(self, step=10.0):
""" Volume up by (default: 10)% """
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
return self.set_volume(self._player.volume+step)
@action
def set_volume(self, volume):
"""
Set the volume
:param volume: Volume value between 0 and 100
:type volume: float
"""
if not self._player:
return (None, 'No mpv instance is running')
volume = max(0, min(self._player.volume_max, volume))
self._player.volume = volume
return { 'volume': volume }
@action
def seek(self, position):
"""
Seek backward/forward by the specified number of seconds
:param relative_position: Number of seconds relative to the current cursor
:type relative_position: int
"""
if not self._player:
return (None, 'No mpv instance is running')
if not self._player.seekable:
return (None, 'The resource is not seekable')
pos = min(self._player.time_pos+self._player.time_remaining,
max(0, position))
self._player.time_pos = pos
return { 'position': pos }
2019-02-18 01:17:21 +01:00
@action
def back(self, offset=60.0):
""" Back by (default: 60) seconds """
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
if not self._player.seekable:
return (None, 'The resource is not seekable')
pos = max(0, self._player.time_pos-offset)
return self.seek(pos)
2019-02-18 01:17:21 +01:00
@action
def forward(self, offset=60.0):
""" Forward by (default: 60) seconds """
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
if not self._player.seekable:
return (None, 'The resource is not seekable')
pos = min(self._player.time_pos+self._player.time_remaining,
self._player.time_pos+offset)
return self.seek(pos)
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def next(self):
""" Play the next item in the queue """
if not self._player:
return (None, 'No mpv instance is running')
self._player.playlist_next()
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def prev(self):
""" Play the previous item in the queue """
if not self._player:
return (None, 'No mpv instance is running')
self._player.playlist_prev()
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def toggle_subtitles(self, visibile=None):
""" Toggle the subtitles visibility """
return self.toggle_property('sub_visibility')
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def toggle_fullscreen(self, fullscreen=None):
""" Toggle the fullscreen mode """
return self.toggle_property('fullscreen')
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def toggle_property(self, property):
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
Toggle or sets the value of an mpv property (e.g. fullscreen,
sub_visibility etc.). See ``man mpv`` for a full list of properties
:param property: Property to toggle
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
if not hasattr(self._player, property):
self.logger.warning('No such mpv property: {}'.format(property))
value = not getattr(self._player, property)
setattr(self._player, property, value)
return { property: value }
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def get_property(self, property):
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
Get a player property (e.g. pause, fullscreen etc.). See
``man mpv`` for a full list of the available properties
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
return getattr(self._player, property)
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def set_property(self, **props):
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
Set the value of an mpv property (e.g. fullscreen, sub_visibility
etc.). See ``man mpv`` for a full list of properties
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
:param props: Key-value args for the properties to set
:type props: dict
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
if not self._player:
return (None, 'No mpv instance is running')
2019-02-19 01:09:53 +01:00
for k,v in props.items():
2019-02-19 00:15:03 +01:00
setattr(self._player, k, v)
return props
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def set_subtitles(self, filename):
""" Sets media subtitles from filename """
return self.set_property(subfile=filename, sub_visibility=True)
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
@action
def remove_subtitles(self):
""" Removes (hides) the subtitles """
if not self._player:
return (None, 'No mpv instance is running')
self._player.sub_visibility = False
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def is_playing(self):
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
:returns: True if it's playing, False otherwise
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
if not self._player:
return False
return not self._player.pause
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def load(self, resource, **args):
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
Load/queue a resource/video to the player
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
if not self._player:
return self.play(resource, **args)
return self.loadfile(resource, mode='append-play', **args)
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
@action
def mute(self):
""" Toggle mute state """
if not self._player:
return (None, 'No mpv instance is running')
mute = not self._player.mute
self._player.mute = mute
return { 'muted': mute }
2019-02-18 01:17:21 +01:00
@action
2019-02-19 00:15:03 +01:00
def set_position(self, position):
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
Seek backward/forward to the specified absolute position (same as ``seek``)
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
return self.seek(position)
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
@action
def status(self):
"""
Get the current player state.
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
:returns: A dictionary containing the current state.
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
Example::
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
output = {
"filename": "filename or stream URL",
"state": "play" # or "stop" or "pause"
}
2019-02-18 01:17:21 +01:00
"""
2019-02-19 00:15:03 +01:00
if not self._player or not hasattr(self._player, 'pause'):
return { 'state': PlayerState.STOP.value }
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
return {
'filename': self._get_current_resource(),
'state': (PlayerState.PAUSE.value if self._player.pause else
PlayerState.PLAY.value),
}
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
def _get_current_resource(self):
if not self._player or not self._player.stream_path:
return
2019-02-18 01:17:21 +01:00
2019-02-19 00:15:03 +01:00
return ('file://' if os.path.isfile(self._player.stream_path)
else '') + self._player.stream_path
2019-02-18 01:17:21 +01:00
# vim:sw=4:ts=4:et: