Fix MPRIS player detection: browsers, relaunched and slow players

Players were silently lost, so the Playing tab showed no controls:

- Chromium and Brave answer MPRIS calls but return an empty introspection,
  which made dbus-next fail with "interface not found". The MPRIS interfaces
  are now described statically (MPRIS 2 spec) instead of read from the player.
- A player relaunched under the same bus name (Dragon Player, Celluloid...)
  left its old object subscribed to PropertiesChanged; that signal cancelled
  the pending attach of the new one. Player.close() now unsubscribes.
- A player may take its name long before it answers (objects exported later,
  or a main loop busy opening a file read over the network). Attaching is now
  retried while the name stays on the bus, with a per-attempt timeout, and is
  cancelled when the player leaves. MprisManager.stop() cancels everything.

tests/test_mpris.py runs on a private dbus-daemon and covers each case; the
relaunch, empty-introspection and late-player tests fail without the fixes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Denis
2026-10-26 16:28:08 +01:00
parent 5921b7c414
commit cd4a8a797b
2 changed files with 340 additions and 26 deletions
+120 -23
View File
@@ -4,12 +4,14 @@ from __future__ import annotations
import asyncio import asyncio
import hashlib import hashlib
import itertools
import logging import logging
from collections.abc import Callable from collections.abc import Callable
from typing import Any from typing import Any
from dbus_next.signature import Variant from dbus_next.signature import Variant
from dbus_next.aio.message_bus import MessageBus from dbus_next.aio.message_bus import MessageBus
from dbus_next.introspection import Node
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@@ -32,6 +34,65 @@ _METADATA_KEYS = {
_LOOP_VALUES = ("None", "Track", "Playlist") _LOOP_VALUES = ("None", "Track", "Playlist")
# Description des interfaces MPRIS (spécification MPRIS 2), utilisée à la place de l'introspection du lecteur :
# Chromium et Brave répondent aux méthodes et aux propriétés mais renvoient une introspection vide, ce qui empêchait
# dbus-next de construire un proxy (« interface not found on this object »).
_INTROSPECTION = Node.parse("""<node>
<interface name="org.freedesktop.DBus.Properties">
<method name="Get"><arg direction="in" type="s"/><arg direction="in" type="s"/><arg direction="out" type="v"/></method>
<method name="Set"><arg direction="in" type="s"/><arg direction="in" type="s"/><arg direction="in" type="v"/></method>
<method name="GetAll"><arg direction="in" type="s"/><arg direction="out" type="a{sv}"/></method>
<signal name="PropertiesChanged"><arg type="s"/><arg type="a{sv}"/><arg type="as"/></signal>
</interface>
<interface name="org.mpris.MediaPlayer2">
<method name="Raise"/>
<method name="Quit"/>
<property name="CanQuit" type="b" access="read"/>
<property name="Fullscreen" type="b" access="readwrite"/>
<property name="CanSetFullscreen" 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>
<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>
</node>""")
# Un lecteur peut prendre son nom de bus bien avant de répondre (objets exportés plus tard, ou boucle occupée à charger
# un fichier lu par le réseau) : pauses avant les premières tentatives de rattachement, puis une tentative toutes
# les RETRY_EVERY secondes tant qu'il reste sur le bus. Chaque tentative a un délai maximal.
ATTACH_PAUSES = (0.3, 0.5, 1.0, 2.0, 4.0)
RETRY_EVERY = 3.0
ATTACH_TIMEOUT = 5.0
def unwrap(value: Any) -> Any: def unwrap(value: Any) -> Any:
"""Convertit récursivement les Variant D-Bus en types Python natifs.""" """Convertit récursivement les Variant D-Bus en types Python natifs."""
@@ -72,6 +133,20 @@ class Player:
self.state: dict[str, Any] = {} self.state: dict[str, Any] = {}
self.position_us = 0 self.position_us = 0
self.position_stamp = 0.0 self.position_stamp = 0.0
self._unsubscribers: list[Callable[[], None]] = []
def on_close(self, unsubscribe: Callable[[], None]) -> None:
"""Enregistre le désabonnement d'un signal, exécuté par close()."""
self._unsubscribers.append(unsubscribe)
def close(self) -> None:
"""Se désabonne des signaux : un lecteur relancé sous le même nom ne doit pas réveiller l'ancien objet."""
unsubscribers, self._unsubscribers = self._unsubscribers, []
for unsubscribe in unsubscribers:
try:
unsubscribe()
except Exception as exc: # noqa: BLE001 - le bus peut déjà être fermé
log.debug("cannot unsubscribe from %s: %s", self.bus_name, exc)
@property @property
def art_url(self) -> str | None: def art_url(self) -> str | None:
@@ -184,7 +259,12 @@ class MprisManager:
def _on_name_owner_changed(self, name: str, old_owner: str, new_owner: str) -> None: def _on_name_owner_changed(self, name: str, old_owner: str, new_owner: str) -> None:
if not name.startswith(MPRIS_PREFIX): if not name.startswith(MPRIS_PREFIX):
return return
if old_owner and name in self._players: if old_owner:
# Le lecteur a quitté le bus : plus rien à rattacher (ajout en attente) ni à suivre
pending = self._pending.pop(name, None)
if pending is not None:
pending.cancel()
if name in self._players:
self._remove(name) self._remove(name)
if new_owner: if new_owner:
# Laisse le lecteur publier son objet avant l'introspection # Laisse le lecteur publier son objet avant l'introspection
@@ -205,18 +285,30 @@ class MprisManager:
task.add_done_callback(on_done) task.add_done_callback(on_done)
async def _add(self, name: str, delay: float = 0.0) -> None: async def _add(self, name: str, delay: float = 0.0) -> None:
if delay: """Rattache un lecteur, en réessayant tant qu'il reste sur le bus (la tâche est annulée à son départ)."""
await asyncio.sleep(delay) pauses = itertools.chain((delay,), ATTACH_PAUSES, itertools.repeat(RETRY_EVERY))
attempts = 0
for pause in pauses:
if pause:
await asyncio.sleep(pause)
attempts += 1
try: try:
introspection = await self._bus.introspect(name, MPRIS_PATH) player = await asyncio.wait_for(self._attach(name), ATTACH_TIMEOUT)
proxy = self._bus.get_proxy_object(name, MPRIS_PATH, introspection) except Exception as exc: # noqa: BLE001 - lecteur au D-Bus défaillant ou pas encore prêt
log.debug("MPRIS player %s not ready (attempt %d): %s", name, attempts, exc)
if attempts == len(ATTACH_PAUSES) + 1:
log.warning("MPRIS player %s does not answer yet (%r), still trying", name, exc)
continue
self._players[name] = player
log.info("MPRIS player added: %s", name)
self._on_change()
return
async def _attach(self, name: str) -> Player:
proxy = self._bus.get_proxy_object(name, MPRIS_PATH, _INTROSPECTION)
root: Any = proxy.get_interface(ROOT_IFACE) root: Any = proxy.get_interface(ROOT_IFACE)
player_iface: Any = proxy.get_interface(PLAYER_IFACE) player_iface: Any = proxy.get_interface(PLAYER_IFACE)
props: Any = proxy.get_interface(PROPS_IFACE) props: Any = proxy.get_interface(PROPS_IFACE)
except Exception as exc: # noqa: BLE001 - lecteur au D-Bus défaillant
log.warning("cannot attach MPRIS player %s: %s", name, exc)
return
player = Player(name, root, player_iface, props) player = Player(name, root, player_iface, props)
def on_properties_changed(interface: str, _changed: dict[str, Any], _invalidated: list[str]) -> None: def on_properties_changed(interface: str, _changed: dict[str, Any], _invalidated: list[str]) -> None:
@@ -229,21 +321,15 @@ class MprisManager:
self._on_change() self._on_change()
props.on_properties_changed(on_properties_changed) props.on_properties_changed(on_properties_changed)
# dbus-next ne génère on_seeked que si le signal figure dans l'introspection : player.on_close(lambda: props.off_properties_changed(on_properties_changed))
# certains lecteurs (navigateurs) ne le déclarent pas, la position est alors relue à la demande player_iface.on_seeked(on_seeked)
subscribe_seeked = getattr(player_iface, "on_seeked", None) player.on_close(lambda: player_iface.off_seeked(on_seeked))
if subscribe_seeked is not None:
subscribe_seeked(on_seeked)
else:
log.debug("MPRIS player %s does not declare the Seeked signal", name)
try: try:
await player.refresh() await player.refresh()
except Exception as exc: # noqa: BLE001 except BaseException:
log.warning("cannot read MPRIS player %s: %s", name, exc) player.close()
return raise
self._players[name] = player return player
log.info("MPRIS player added: %s", name)
self._on_change()
async def _refresh(self, player: Player) -> None: async def _refresh(self, player: Player) -> None:
# Regroupe les rafales de PropertiesChanged # Regroupe les rafales de PropertiesChanged
@@ -255,8 +341,19 @@ class MprisManager:
return return
self._on_change() self._on_change()
def stop(self) -> None:
"""Annule les rattachements en attente et se désabonne de tous les lecteurs."""
for task in self._pending.values():
task.cancel()
self._pending.clear()
for player in self._players.values():
player.close()
self._players.clear()
def _remove(self, name: str) -> None: def _remove(self, name: str) -> None:
self._players.pop(name, None) player = self._players.pop(name, None)
if player is not None:
player.close()
log.info("MPRIS player removed: %s", name) log.info("MPRIS player removed: %s", name)
self._on_change() self._on_change()
+217
View File
@@ -0,0 +1,217 @@
"""Tests de la découverte MPRIS sur un bus de session privé (dbus-daemon). Ignorés sans dbus-daemon."""
import asyncio
import logging
import shutil
import subprocess
import unittest
import warnings
from unittest import mock
from collections.abc import Awaitable, Callable
from typing import Any
from dbus_next.message import Message
from dbus_next.aio.message_bus import MessageBus
from dbus_next.constants import PropertyAccess
from dbus_next.service import ServiceInterface, dbus_property, method
from dbus_next.signature import Variant
from mediadeck import mpris
from mediadeck.mpris import MPRIS_PATH, MPRIS_PREFIX, MprisManager
DBUS_DAEMON = shutil.which("dbus-daemon")
NAME = MPRIS_PREFIX + "fixedname" # nom fixe, comme Dragon Player, Celluloid ou VLC
class FakeRoot(ServiceInterface):
def __init__(self) -> None:
super().__init__("org.mpris.MediaPlayer2")
@dbus_property(access=PropertyAccess.READ)
def Identity(self) -> "s": # type: ignore[name-defined] # noqa: F821
return "Fake"
@method()
def Raise(self) -> None:
pass
class FakePlayer(ServiceInterface):
def __init__(self, title: str) -> None:
super().__init__("org.mpris.MediaPlayer2.Player")
self.title = title
@dbus_property(access=PropertyAccess.READ)
def PlaybackStatus(self) -> "s": # type: ignore[name-defined] # noqa: F821
return "Playing"
@dbus_property(access=PropertyAccess.READ)
def Metadata(self) -> "a{sv}": # type: ignore[name-defined] # noqa: F821
return {"xesam:title": Variant("s", self.title)}
@dbus_property(access=PropertyAccess.READ)
def Position(self) -> "x": # type: ignore[name-defined] # noqa: F821
return 0
@dbus_property(access=PropertyAccess.READ)
def CanPlay(self) -> "b": # type: ignore[name-defined] # noqa: F821
return True
@method()
def PlayPause(self) -> None:
pass
def empty_introspection(message: Message) -> Message | None:
if message.interface == "org.freedesktop.DBus.Introspectable" and message.member == "Introspect":
return Message.new_method_return(message, "s", ["<node></node>"])
return None
@unittest.skipUnless(DBUS_DAEMON, "dbus-daemon not installed")
class MprisDiscoveryTest(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
assert DBUS_DAEMON
# dbus-next ferme ses flux mais pas l'objet socket de ses connexions : le ramasse-miettes s'en plaint
warnings.filterwarnings("ignore", message="unclosed <socket", category=ResourceWarning)
self.daemon = subprocess.Popen(
[DBUS_DAEMON, "--session", "--nofork", "--print-address=1"],
stdout=subprocess.PIPE,
text=True,
)
assert self.daemon.stdout is not None
self.address = self.daemon.stdout.readline().strip()
self.buses: list[MessageBus] = []
self.manager_bus = await self.connect()
self.manager = MprisManager(self.manager_bus, lambda: None)
await self.manager.start()
async def asyncTearDown(self) -> None:
self.manager.stop()
for bus in self.buses:
bus.disconnect()
await bus.wait_for_disconnect()
self.daemon.terminate()
self.daemon.wait()
assert self.daemon.stdout is not None
self.daemon.stdout.close()
async def connect(self) -> MessageBus:
bus = await MessageBus(bus_address=self.address).connect()
self.buses.append(bus)
return bus
async def open_player(
self, title: str, introspectable: bool = True, export_after: float = 0.0
) -> tuple[MessageBus, FakePlayer]:
"""Lecteur qui prend son nom puis annonce aussitôt ses propriétés, comme un vrai lecteur qui charge un fichier.
``introspectable=False`` imite Chromium et Brave : les propriétés et les méthodes répondent, mais
Introspect renvoie un nœud vide. ``export_after`` : le nom est pris tout de suite mais les objets ne sont
exportés que plus tard (lecteur occupé à charger un fichier)."""
bus = await self.connect()
if not introspectable:
bus.add_message_handler(empty_introspection)
player = FakePlayer(title)
if export_after:
await bus.request_name(NAME)
await asyncio.sleep(export_after)
bus.export(MPRIS_PATH, FakeRoot())
bus.export(MPRIS_PATH, player)
if not export_after:
await bus.request_name(NAME)
player.emit_properties_changed({"PlaybackStatus": "Playing"})
return bus, player
async def titles(self) -> list[str]:
snapshot: dict[str, Any] = await self.manager.snapshot()
return [player["metadata"].get("title") for player in snapshot["players"]]
async def until(self, condition: Callable[[], Awaitable[bool]], seconds: float = 4.0) -> bool:
for _ in range(int(seconds / 0.1)):
if await condition():
return True
await asyncio.sleep(0.1)
return await condition()
async def test_player_appearing_after_start_is_listed(self) -> None:
await self.open_player("first")
self.assertTrue(await self.until(self.has_title("first")))
async def test_player_restarted_under_the_same_name_is_listed_again(self) -> None:
# Fermé puis relancé : l'ancien objet ne doit ni rester abonné ni annuler l'ajout du nouveau
bus, _player = await self.open_player("first")
self.assertTrue(await self.until(self.has_title("first")))
bus.disconnect()
self.assertTrue(await self.until(self.is_empty))
for round_number in range(3):
title = f"second-{round_number}"
bus, _player = await self.open_player(title)
self.assertTrue(await self.until(self.has_title(title)), f"player not listed on restart {round_number}")
bus.disconnect()
self.assertTrue(await self.until(self.is_empty))
async def test_changes_of_the_restarted_player_are_followed(self) -> None:
bus, _player = await self.open_player("first")
self.assertTrue(await self.until(self.has_title("first")))
bus.disconnect()
self.assertTrue(await self.until(self.is_empty))
_bus, player = await self.open_player("second")
self.assertTrue(await self.until(self.has_title("second")))
player.title = "third"
player.emit_properties_changed({"Metadata": {"xesam:title": Variant("s", "third")}})
self.assertTrue(await self.until(self.has_title("third")))
async def test_player_with_empty_introspection_is_listed_and_controlled(self) -> None:
# Chromium et Brave n'exposent aucune introspection : il faut décrire les interfaces MPRIS soi-même
_bus, _player = await self.open_player("browser", introspectable=False)
self.assertTrue(await self.until(self.has_title("browser")))
snapshot: dict[str, Any] = await self.manager.snapshot()
name = snapshot["players"][0]["name"]
await self.manager.get(name).execute("play_pause", None) # ne doit pas lever d'erreur
def silence_expected_errors(self) -> None:
"""Les appels reçus avant l'export des objets sont journalisés par dbus-next côté faux lecteur : attendu ici."""
logging.disable(logging.ERROR)
self.addCleanup(logging.disable, logging.NOTSET)
async def test_player_ready_long_after_taking_its_name_is_listed(self) -> None:
# Celluloid qui ouvre un fichier lu par le réseau : le nom est pris, les objets suivent bien plus tard
self.silence_expected_errors()
with (
mock.patch.object(mpris, "ATTACH_PAUSES", (0.05, 0.05)),
mock.patch.object(mpris, "RETRY_EVERY", 0.1),
):
_bus, _player = await self.open_player("slow", export_after=1.0)
self.assertTrue(await self.until(self.has_title("slow")))
async def test_waiting_for_a_player_stops_when_it_leaves_the_bus(self) -> None:
self.silence_expected_errors()
with (
mock.patch.object(mpris, "ATTACH_PAUSES", (0.05,)),
mock.patch.object(mpris, "RETRY_EVERY", 0.05),
):
bus = await self.connect()
await bus.request_name(NAME) # prend son nom, n'exporte jamais rien
self.assertTrue(await self.until(self.is_waiting))
bus.disconnect()
self.assertTrue(await self.until(self.is_idle))
async def is_waiting(self) -> bool:
return bool(self.manager._pending) # noqa: SLF001 - tâche de rattachement en attente
async def is_idle(self) -> bool:
return not self.manager._pending # noqa: SLF001
def has_title(self, title: str) -> Callable[[], Awaitable[bool]]:
async def check() -> bool:
return await self.titles() == [title]
return check
async def is_empty(self) -> bool:
return await self.titles() == []
if __name__ == "__main__":
unittest.main()