- KDE/Windows accent-driven Material 3 theme, live updating - Library, tabbed playlists, smart/saved lists, queue, ratings - mpv and Qt Multimedia engines, EQ, ReplayGain, gapless - Synced lyrics (LRCLIB, NetEase, local .lrc), covers, MusicBrainz tags - Last.fm/ListenBrainz scrobbling, MPRIS, Windows media keys - Audio CD playback and ripping - PyInstaller, Inno Setup and AppImage builds via GitHub Actions Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01J7imThHV9BMkG24GaxPDeq
350 lines
12 KiB
Python
350 lines
12 KiB
Python
"""MPRIS2 D-Bus interface so Plasma's media controls, KDE Connect, media keys
|
|
and shell widgets (Quickshell, etc.) see and control Mulberry."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from PyQt6.QtCore import QMetaType, QObject, pyqtClassInfo, pyqtProperty, pyqtSignal, pyqtSlot
|
|
from PyQt6.QtDBus import (QDBusAbstractAdaptor, QDBusArgument, QDBusConnection, QDBusMessage,
|
|
QDBusObjectPath)
|
|
|
|
from .config import APP_ID, APP_NAME
|
|
|
|
PATH = "/org/mpris/MediaPlayer2"
|
|
ROOT_XML = """
|
|
<interface name="org.mpris.MediaPlayer2">
|
|
<method name="Raise"/><method name="Quit"/>
|
|
<property name="CanQuit" type="b" access="read"/>
|
|
<property name="CanRaise" type="b" access="read"/>
|
|
<property name="HasTrackList" type="b" access="read"/>
|
|
<property name="Identity" type="s" access="read"/>
|
|
<property name="DesktopEntry" type="s" access="read"/>
|
|
<property name="SupportedUriSchemes" type="as" access="read"/>
|
|
<property name="SupportedMimeTypes" type="as" access="read"/>
|
|
</interface>"""
|
|
PLAYER_XML = """
|
|
<interface name="org.mpris.MediaPlayer2.Player">
|
|
<method name="Next"/><method name="Previous"/><method name="Pause"/>
|
|
<method name="PlayPause"/><method name="Stop"/><method name="Play"/>
|
|
<method name="Seek"><arg direction="in" type="x" name="Offset"/></method>
|
|
<method name="SetPosition"><arg direction="in" type="o" name="TrackId"/><arg direction="in" type="x" name="Position"/></method>
|
|
<method name="OpenUri"><arg direction="in" type="s" name="Uri"/></method>
|
|
<signal name="Seeked"><arg type="x" name="Position"/></signal>
|
|
<property name="PlaybackStatus" type="s" access="read"/>
|
|
<property name="LoopStatus" type="s" access="readwrite"/>
|
|
<property name="Rate" type="d" access="readwrite"/>
|
|
<property name="Shuffle" type="b" access="readwrite"/>
|
|
<property name="Metadata" type="a{sv}" access="read"/>
|
|
<property name="Volume" type="d" access="readwrite"/>
|
|
<property name="Position" type="x" access="read"/>
|
|
<property name="MinimumRate" type="d" access="read"/>
|
|
<property name="MaximumRate" type="d" access="read"/>
|
|
<property name="CanGoNext" type="b" access="read"/>
|
|
<property name="CanGoPrevious" type="b" access="read"/>
|
|
<property name="CanPlay" type="b" access="read"/>
|
|
<property name="CanPause" type="b" access="read"/>
|
|
<property name="CanSeek" type="b" access="read"/>
|
|
<property name="CanControl" type="b" access="read"/>
|
|
</interface>"""
|
|
|
|
|
|
@pyqtClassInfo("D-Bus Interface", "org.mpris.MediaPlayer2")
|
|
@pyqtClassInfo("D-Bus Introspection", ROOT_XML)
|
|
class RootAdaptor(QDBusAbstractAdaptor):
|
|
def __init__(self, parent, window):
|
|
super().__init__(parent)
|
|
self.window = window
|
|
self.setAutoRelaySignals(False)
|
|
|
|
@pyqtProperty(bool)
|
|
def CanQuit(self):
|
|
return True
|
|
|
|
@pyqtProperty(bool)
|
|
def CanRaise(self):
|
|
return True
|
|
|
|
@pyqtProperty(bool)
|
|
def HasTrackList(self):
|
|
return False
|
|
|
|
@pyqtProperty(str)
|
|
def Identity(self):
|
|
return APP_NAME
|
|
|
|
@pyqtProperty(str)
|
|
def DesktopEntry(self):
|
|
return APP_ID
|
|
|
|
@pyqtProperty("QStringList")
|
|
def SupportedUriSchemes(self):
|
|
return ["file", "http", "https", "cdda"]
|
|
|
|
@pyqtProperty("QStringList")
|
|
def SupportedMimeTypes(self):
|
|
return ["audio/mpeg", "audio/flac", "audio/ogg", "audio/x-vorbis+ogg", "audio/opus",
|
|
"audio/mp4", "audio/aac", "audio/x-wav", "audio/x-ms-wma", "audio/x-ape",
|
|
"audio/x-wavpack", "audio/x-musepack", "audio/x-aiff", "audio/x-mpegurl",
|
|
"audio/x-scpls", "application/xspf+xml"]
|
|
|
|
@pyqtSlot()
|
|
def Raise(self):
|
|
w = self.window
|
|
w.show()
|
|
w.raise_()
|
|
w.activateWindow()
|
|
|
|
@pyqtSlot()
|
|
def Quit(self):
|
|
self.window.quit_app()
|
|
|
|
|
|
@pyqtClassInfo("D-Bus Interface", "org.mpris.MediaPlayer2.Player")
|
|
@pyqtClassInfo("D-Bus Introspection", PLAYER_XML)
|
|
class PlayerAdaptor(QDBusAbstractAdaptor):
|
|
Seeked = pyqtSignal("qlonglong")
|
|
|
|
def __init__(self, parent, player, mgr):
|
|
super().__init__(parent)
|
|
self.player, self.mgr = player, mgr
|
|
self.setAutoRelaySignals(False)
|
|
|
|
@pyqtProperty(str)
|
|
def PlaybackStatus(self):
|
|
return {"playing": "Playing", "paused": "Paused"}.get(self.player.state, "Stopped")
|
|
|
|
@pyqtProperty(str)
|
|
def LoopStatus(self):
|
|
return {"track": "Track", "playlist": "Playlist"}.get(self.mgr.repeat, "None")
|
|
|
|
@LoopStatus.setter
|
|
def LoopStatus(self, v):
|
|
self.mgr.set_repeat({"Track": "track", "Playlist": "playlist"}.get(v, "off"))
|
|
self.parent().repeat_changed_external()
|
|
|
|
@pyqtProperty(float)
|
|
def Rate(self):
|
|
return 1.0
|
|
|
|
@Rate.setter
|
|
def Rate(self, v):
|
|
pass
|
|
|
|
@pyqtProperty(bool)
|
|
def Shuffle(self):
|
|
return bool(self.mgr.shuffle)
|
|
|
|
@Shuffle.setter
|
|
def Shuffle(self, v):
|
|
self.mgr.set_shuffle(bool(v))
|
|
self.parent().repeat_changed_external()
|
|
|
|
@pyqtProperty("QVariantMap")
|
|
def Metadata(self):
|
|
return self.parent().metadata()
|
|
|
|
@pyqtProperty(float)
|
|
def Volume(self):
|
|
return self.player.volume / 100.0
|
|
|
|
@Volume.setter
|
|
def Volume(self, v):
|
|
self.player.set_volume(int(round(v * 100)))
|
|
|
|
@pyqtProperty("qlonglong")
|
|
def Position(self):
|
|
return int(self.player.pos * 1_000_000)
|
|
|
|
@pyqtProperty(float)
|
|
def MinimumRate(self):
|
|
return 1.0
|
|
|
|
@pyqtProperty(float)
|
|
def MaximumRate(self):
|
|
return 1.0
|
|
|
|
@pyqtProperty(bool)
|
|
def CanGoNext(self):
|
|
return True
|
|
|
|
@pyqtProperty(bool)
|
|
def CanGoPrevious(self):
|
|
return True
|
|
|
|
@pyqtProperty(bool)
|
|
def CanPlay(self):
|
|
return True
|
|
|
|
@pyqtProperty(bool)
|
|
def CanPause(self):
|
|
return True
|
|
|
|
@pyqtProperty(bool)
|
|
def CanSeek(self):
|
|
return self.player.song is not None and not self.player.song.is_stream
|
|
|
|
@pyqtProperty(bool)
|
|
def CanControl(self):
|
|
return True
|
|
|
|
@pyqtSlot()
|
|
def Next(self):
|
|
self.player.next()
|
|
|
|
@pyqtSlot()
|
|
def Previous(self):
|
|
self.player.prev()
|
|
|
|
@pyqtSlot()
|
|
def Pause(self):
|
|
self.player.pause()
|
|
|
|
@pyqtSlot()
|
|
def PlayPause(self):
|
|
self.player.play_pause()
|
|
|
|
@pyqtSlot()
|
|
def Stop(self):
|
|
self.player.stop()
|
|
|
|
@pyqtSlot()
|
|
def Play(self):
|
|
self.player.play()
|
|
|
|
@pyqtSlot("qlonglong")
|
|
def Seek(self, offset):
|
|
self.player.seek_relative(offset / 1_000_000)
|
|
|
|
@pyqtSlot(QDBusObjectPath, "qlonglong")
|
|
def SetPosition(self, track, pos):
|
|
self.player.seek(pos / 1_000_000)
|
|
|
|
@pyqtSlot(str)
|
|
def OpenUri(self, uri):
|
|
from .playlist import url_to_path
|
|
p = url_to_path(uri)
|
|
if os.path.exists(p):
|
|
self.mgr.add_paths([p], play=True)
|
|
|
|
|
|
class Mpris(QObject):
|
|
def __init__(self, window, player, mgr):
|
|
super().__init__()
|
|
self.player, self.mgr, self.window = player, mgr, window
|
|
self.ok = False
|
|
bus = QDBusConnection.sessionBus()
|
|
if not bus.isConnected():
|
|
return
|
|
self.root = RootAdaptor(self, window)
|
|
self.padaptor = PlayerAdaptor(self, player, mgr)
|
|
if not bus.registerObject(PATH, self):
|
|
return
|
|
name = "org.mpris.MediaPlayer2." + APP_ID
|
|
if not bus.registerService(name):
|
|
bus.registerService(f"{name}.instance{os.getpid()}")
|
|
self.ok = True
|
|
player.state_changed.connect(lambda *_: self._changed(["PlaybackStatus", "CanSeek"]))
|
|
player.song_changed.connect(lambda *_: self._changed(["Metadata", "CanSeek"]))
|
|
player.volume_changed.connect(lambda *_: self._changed(["Volume"]))
|
|
player.seeked.connect(lambda s: self._emit_seeked(s))
|
|
|
|
def repeat_changed_external(self):
|
|
self._changed(["LoopStatus", "Shuffle"])
|
|
if hasattr(self.window, "sync_modes"):
|
|
self.window.sync_modes()
|
|
|
|
def modes_changed(self):
|
|
self._changed(["LoopStatus", "Shuffle"])
|
|
|
|
def metadata(self) -> dict:
|
|
s = self.player.song
|
|
if s is None:
|
|
return {"mpris:trackid": QDBusObjectPath("/org/mpris/MediaPlayer2/TrackList/NoTrack")}
|
|
title = s.display_title()
|
|
artist = s.display_artist()
|
|
if s.is_stream:
|
|
st = s.stream_title
|
|
if st and " - " in st:
|
|
artist, title = [x.strip() for x in st.split(" - ", 1)]
|
|
else:
|
|
title = st or s.title or s.url
|
|
artist = artist or s.title
|
|
tid = QDBusObjectPath(f"/org/{APP_ID}/track/{abs(hash(s.key())) % 10**12}")
|
|
md = {
|
|
"mpris:trackid": tid,
|
|
"mpris:length": _i64(int(max(self.player.dur, s.duration()) * 1_000_000)),
|
|
"xesam:title": title,
|
|
"xesam:album": s.album,
|
|
"xesam:artist": _as([artist] if artist else []),
|
|
"xesam:albumArtist": _as([s.effective_albumartist()] if s.effective_albumartist() else []),
|
|
"xesam:genre": _as([s.genre] if s.genre else []),
|
|
"xesam:trackNumber": s.track,
|
|
"xesam:discNumber": s.disc,
|
|
"xesam:useCount": s.playcount,
|
|
"xesam:userRating": s.rating / 5.0,
|
|
"xesam:url": Path(s.path).as_uri() if s.is_local and os.path.isabs(s.path) else s.url,
|
|
}
|
|
art = getattr(self.window, "current_art_path", "") or s.art
|
|
if art and os.path.exists(art):
|
|
md["mpris:artUrl"] = Path(art).as_uri()
|
|
if s.year:
|
|
md["xesam:contentCreated"] = f"{s.year:04d}-01-01T00:00:00"
|
|
return md
|
|
|
|
def _changed(self, props):
|
|
if not self.ok:
|
|
return
|
|
changed = {}
|
|
for p in props:
|
|
if p == "Metadata":
|
|
changed[p] = self.metadata()
|
|
else:
|
|
changed[p] = getattr(self.padaptor, p)
|
|
msg = QDBusMessage.createSignal(PATH, "org.freedesktop.DBus.Properties", "PropertiesChanged")
|
|
msg.setArguments(["org.mpris.MediaPlayer2.Player", changed,
|
|
QDBusArgument([], QMetaType.Type.QStringList.value)])
|
|
QDBusConnection.sessionBus().send(msg)
|
|
|
|
def art_changed(self):
|
|
self._changed(["Metadata"])
|
|
|
|
def _emit_seeked(self, sec):
|
|
if not self.ok:
|
|
return
|
|
msg = QDBusMessage.createSignal(PATH, "org.mpris.MediaPlayer2.Player", "Seeked")
|
|
arg = QDBusArgument()
|
|
arg.add(int(sec * 1_000_000), QMetaType.Type.LongLong.value)
|
|
msg.setArguments([arg])
|
|
QDBusConnection.sessionBus().send(msg)
|
|
|
|
|
|
def _as(items: list[str]) -> QDBusArgument:
|
|
"""Marshal as D-Bus 'as' (plain Python lists would become 'av', which
|
|
many MPRIS clients ignore — they then show 'Unknown artist')."""
|
|
return QDBusArgument([str(i) for i in items], QMetaType.Type.QStringList.value)
|
|
|
|
|
|
def _i64(v: int) -> QDBusArgument:
|
|
a = QDBusArgument()
|
|
a.add(int(v), QMetaType.Type.LongLong.value)
|
|
return a
|
|
|
|
|
|
def notify(summary: str, body: str, icon_path: str = "", replaces: int = 0) -> None:
|
|
"""Desktop notification via org.freedesktop.Notifications (async)."""
|
|
bus = QDBusConnection.sessionBus()
|
|
if not bus.isConnected():
|
|
return
|
|
msg = QDBusMessage.createMethodCall("org.freedesktop.Notifications", "/org/freedesktop/Notifications",
|
|
"org.freedesktop.Notifications", "Notify")
|
|
hints = {"desktop-entry": APP_ID, "transient": True}
|
|
if icon_path:
|
|
hints["image-path"] = Path(icon_path).as_uri()
|
|
rid = QDBusArgument()
|
|
rid.add(int(replaces), QMetaType.Type.UInt.value)
|
|
timeout = QDBusArgument()
|
|
timeout.add(5000, QMetaType.Type.Int.value)
|
|
msg.setArguments([APP_NAME, rid, icon_path or "audio-x-generic", summary, body,
|
|
QDBusArgument([], QMetaType.Type.QStringList.value), hints, timeout])
|
|
bus.asyncCall(msg)
|