feat: add bounded M13.3b MPRIS worker and native adapter
Use pinned dbus 0.9.12 on a joined worker with bounded command queue, expiry, finite method timeouts, unique-owner targeting and configuration fences. Discover playback capabilities, position, shuffle, repeat and playlists independently of audio. Verification: Rust 1.88 build; media_runtime fake-adapter tests; dbus-run-session -- cargo test -p fader_master private_bus_discovers -- --ignored --nocapture passed; clippy all-targets/all-features and no-default-features check passed. License and native prerequisites documented.
This commit is contained in:
parent
fb937ef6ae
commit
5d0126abff
|
|
@ -360,6 +360,17 @@ dependencies = [
|
|||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dbus"
|
||||
version = "0.9.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"libdbus-sys",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
|
|
@ -427,8 +438,10 @@ version = "0.1.0-rc.2"
|
|||
dependencies = [
|
||||
"anyhow",
|
||||
"clap",
|
||||
"dbus",
|
||||
"fader-config",
|
||||
"fader-core",
|
||||
"media",
|
||||
"midi",
|
||||
"rustix 1.1.5",
|
||||
"serde",
|
||||
|
|
@ -702,6 +715,15 @@ version = "0.2.190"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||
|
||||
[[package]]
|
||||
name = "libdbus-sys"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
|
||||
dependencies = [
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.7.4"
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ repository = "https://proxy.dandaedre.com/gitea/MadGobblins/fader_master"
|
|||
publish = false
|
||||
|
||||
[workspace.dependencies]
|
||||
dbus = "=0.9.12"
|
||||
media = { path = "media" }
|
||||
alsa = "0.12.1"
|
||||
anyhow = "1.0.104"
|
||||
|
|
|
|||
|
|
@ -3,4 +3,4 @@ passthrough = ["RUSTUP_TOOLCHAIN"]
|
|||
|
||||
[target.x86_64-unknown-linux-gnu]
|
||||
image = "ghcr.io/cross-rs/x86_64-unknown-linux-gnu:0.2.5"
|
||||
pre-build = ["apt-get update && apt-get install --assume-yes --no-install-recommends pkg-config libasound2-dev libpulse-dev libudev-dev"]
|
||||
pre-build = ["apt-get update && apt-get install --assume-yes --no-install-recommends pkg-config libasound2-dev libpulse-dev libudev-dev libdbus-1-dev"]
|
||||
|
|
|
|||
|
|
@ -201,6 +201,18 @@ before activation. Entry editing is transactional; removing a surface unbinds it
|
|||
media controls without deleting entries. Runtime/UI integration follows this
|
||||
schema slice; it is not yet evidence of a functioning D-Bus adapter.
|
||||
|
||||
The MPRIS adapter uses pinned `dbus` 0.9.12 (MIT/Apache-2.0) and system
|
||||
libdbus-1; its upstream manifest does not declare an MSRV, so compatibility is
|
||||
verified by building with the repository's Rust 1.88 toolchain. A dedicated
|
||||
joined thread owns the blocking connection. Calls have 200 ms timeouts, polling
|
||||
uses 250 ms intervals, and the command queue holds at most 32 requests. Discovery
|
||||
limits player count to 32 and playlist choices to 256 per player. Exhausted
|
||||
discovery bounds fail closed rather than selecting from an incomplete result.
|
||||
Commands resolve a fresh snapshot and address a unique bus owner, not a reusable
|
||||
well-known name; feedback comes only from readback. Missing optional properties
|
||||
remain unavailable. Connection failure triggers reconnect; configuration
|
||||
activation fences queued and in-flight work before replacing the active profile.
|
||||
|
||||
## Volume and mute semantics
|
||||
|
||||
The core stores finite, non-negative linear amplitude gain; `1.0` is unity, `0.0` is silence. Adapters convert native representations explicitly; PulseAudio volume numbers and PipeWire linear gain must not be treated as interchangeable percentages. Preserve per-channel balance by scaling channel gains relative to their maximum. If all channels are zero, an explicit nonzero command initializes them equally. Tests cover silence, clipping, NaN/infinity rejection, and round trips.
|
||||
|
|
|
|||
|
|
@ -6,10 +6,10 @@ toolchain. `rustup` reads `rust-toolchain.toml` and installs the required
|
|||
`rustfmt`, Clippy, and LLVM tools components.
|
||||
|
||||
The default build includes the PulseAudio protocol adapter and links to
|
||||
libpulse. On a Debian-family Linux system, install:
|
||||
libpulse. MPRIS is enabled by default and also links to libdbus-1. On a Debian-family Linux system, install:
|
||||
|
||||
```sh
|
||||
sudo apt-get install build-essential pkg-config libasound2-dev libpulse-dev libudev-dev
|
||||
sudo apt-get install build-essential pkg-config libasound2-dev libpulse-dev libudev-dev libdbus-1-dev
|
||||
rustup toolchain install 1.88.0 \
|
||||
--profile minimal \
|
||||
--component rustfmt \
|
||||
|
|
@ -21,10 +21,20 @@ On Arch Linux with PipeWire, install the client library, build tools, and the
|
|||
PulseAudio-compatible PipeWire service:
|
||||
|
||||
```sh
|
||||
sudo pacman -S --needed base-devel pkgconf alsa-lib libpulse systemd-libs pipewire-audio pipewire-pulse wireplumber
|
||||
sudo pacman -S --needed base-devel pkgconf alsa-lib libpulse systemd-libs dbus pipewire-audio pipewire-pulse wireplumber
|
||||
pactl info
|
||||
```
|
||||
|
||||
The executable's `mpris` feature can be omitted with
|
||||
`cargo build -p fader_master --no-default-features`; this disables only MPRIS,
|
||||
not the existing audio/MIDI backends. MPRIS runtime requires access to the user's
|
||||
session bus, not playerctl. CI native runners need libdbus development files too.
|
||||
The hardware-free protocol fixture runs with:
|
||||
|
||||
```sh
|
||||
dbus-run-session -- cargo test -p fader_master private_bus_discovers -- --ignored
|
||||
```
|
||||
|
||||
The `Server Name` reported by the last command should contain `PulseAudio (on
|
||||
PipeWire ...)`. Arch packages the headers with `libpulse`, rather than in a
|
||||
separate development package. The application communicates with PipeWire
|
||||
|
|
|
|||
|
|
@ -56,7 +56,8 @@ Rust toolchain and Cargo.lock constrain Rust builds. The container tag and apt
|
|||
repositories are not digest/snapshot pinned, so bit-for-bit reproducibility
|
||||
and the minimum supported runtime glibc version are not yet established.
|
||||
Artifacts are dynamically linked: recipient systems need ALSA, libpulse and
|
||||
libudev runtime libraries and a running Pulse-compatible audio service.
|
||||
libudev runtime libraries and a running Pulse-compatible audio service. Builds
|
||||
with the default MPRIS feature also require libdbus-1 and a user session bus.
|
||||
|
||||
## Credentials and invocation
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ pkg-fmt = "tgz"
|
|||
bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
|
||||
|
||||
[dependencies]
|
||||
media.workspace = true
|
||||
dbus = { workspace = true, optional = true }
|
||||
anyhow.workspace = true
|
||||
clap.workspace = true
|
||||
fader-config.workspace = true
|
||||
|
|
@ -28,3 +30,7 @@ volume_lib.workspace = true
|
|||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["mpris"]
|
||||
mpris = ["dep:dbus"]
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ mod editor;
|
|||
pub mod ipc;
|
||||
pub mod live;
|
||||
pub mod local;
|
||||
pub mod media_runtime;
|
||||
pub mod midi_runtime;
|
||||
pub mod tui_client;
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,235 @@
|
|||
//! Bounded MPRIS worker. Native connection ownership never leaves its thread.
|
||||
use media::{Action, Player, PlayerSelector, Snapshot};
|
||||
use std::{
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicBool, AtomicU64, Ordering},
|
||||
mpsc::{self, SyncSender},
|
||||
},
|
||||
thread::{self, JoinHandle},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
trait Adapter {
|
||||
fn discover(&mut self) -> Result<Vec<Player>, String>;
|
||||
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String>;
|
||||
}
|
||||
|
||||
fn execute_selected(
|
||||
adapter: &mut impl Adapter,
|
||||
selector: &PlayerSelector,
|
||||
action: &Action,
|
||||
) -> Result<Vec<Player>, String> {
|
||||
action.validate().map_err(|e| e.to_string())?;
|
||||
let players = adapter.discover()?;
|
||||
let matcher = selector.compile().map_err(|e| e.to_string())?;
|
||||
let player = matcher.resolve(&players).map_err(|e| e.to_string())?;
|
||||
if !action.supported(player) {
|
||||
return Err(media::MediaError::Unsupported.to_string());
|
||||
}
|
||||
adapter.execute(player, action)?;
|
||||
adapter.discover()
|
||||
}
|
||||
|
||||
struct Command {
|
||||
generation: u64,
|
||||
selector: PlayerSelector,
|
||||
action: Action,
|
||||
expires: Instant,
|
||||
}
|
||||
|
||||
enum Work {
|
||||
Action(Command),
|
||||
Fence(SyncSender<()>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct MediaRuntime {
|
||||
sender: SyncSender<Work>,
|
||||
generation: Arc<AtomicU64>,
|
||||
snapshot: Arc<Mutex<Snapshot>>,
|
||||
stop: Arc<AtomicBool>,
|
||||
worker: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl MediaRuntime {
|
||||
pub fn start() -> std::io::Result<Self> {
|
||||
let (sender, receiver) = mpsc::sync_channel::<Work>(32);
|
||||
let generation = Arc::new(AtomicU64::new(0));
|
||||
let current_generation = Arc::clone(&generation);
|
||||
let snapshot = Arc::new(Mutex::new(Snapshot {
|
||||
error: Some("MPRIS initializing".into()),
|
||||
..Snapshot::default()
|
||||
}));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let latest = Arc::clone(&snapshot);
|
||||
let cancelled = Arc::clone(&stop);
|
||||
let worker = thread::Builder::new().name("mpris".into()).spawn(move || {
|
||||
#[cfg(feature = "mpris")]
|
||||
let mut adapter = native::DbusAdapter::default();
|
||||
#[cfg(not(feature = "mpris"))]
|
||||
let mut adapter = Disabled;
|
||||
let mut command_error = None;
|
||||
while !cancelled.load(Ordering::Acquire) {
|
||||
let command = receiver.recv_timeout(Duration::from_millis(250));
|
||||
let is_command = command.is_ok();
|
||||
if cancelled.load(Ordering::Acquire) {
|
||||
break;
|
||||
}
|
||||
let result = match command {
|
||||
Ok(Work::Fence(done)) => {
|
||||
let _ = done.try_send(());
|
||||
continue;
|
||||
}
|
||||
Ok(Work::Action(command))
|
||||
if command.generation != current_generation.load(Ordering::Acquire) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Ok(Work::Action(command)) if Instant::now() <= command.expires => {
|
||||
execute_selected(&mut adapter, &command.selector, &command.action)
|
||||
}
|
||||
Ok(_) => Err("media command expired; press again".into()),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => adapter.discover(),
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
};
|
||||
if let Ok(mut state) = latest.lock() {
|
||||
match result {
|
||||
Ok(players) => {
|
||||
if is_command {
|
||||
command_error = None;
|
||||
}
|
||||
state.available = true;
|
||||
state.players = players;
|
||||
state.error = command_error.clone();
|
||||
}
|
||||
Err(error) => {
|
||||
if is_command {
|
||||
command_error = Some(error.clone());
|
||||
}
|
||||
// Do not retain stale observed states after any failed read/write.
|
||||
state.players.clear();
|
||||
state.error = Some(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Self {
|
||||
sender,
|
||||
generation,
|
||||
snapshot,
|
||||
stop,
|
||||
worker: Some(worker),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
self.snapshot
|
||||
.lock()
|
||||
.map(|s| s.clone())
|
||||
.unwrap_or_else(|_| Snapshot {
|
||||
error: Some("MPRIS state unavailable".into()),
|
||||
..Snapshot::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn command(&self, selector: PlayerSelector, action: Action) -> Result<(), String> {
|
||||
self.sender
|
||||
.try_send(Work::Action(Command {
|
||||
generation: self.generation.load(Ordering::Acquire),
|
||||
selector,
|
||||
action,
|
||||
expires: Instant::now() + Duration::from_secs(2),
|
||||
}))
|
||||
.map_err(|e| format!("MPRIS queue unavailable: {e}"))
|
||||
}
|
||||
|
||||
/// Invalidate queued work and drain the one in-flight call before changing
|
||||
/// profiles. A failed barrier must abort activation rather than race a write.
|
||||
pub fn fence(&self) -> Result<(), String> {
|
||||
self.generation.fetch_add(1, Ordering::AcqRel);
|
||||
let (done, wait) = mpsc::sync_channel(1);
|
||||
self.sender
|
||||
.try_send(Work::Fence(done))
|
||||
.map_err(|e| e.to_string())?;
|
||||
wait.recv_timeout(Duration::from_secs(10))
|
||||
.map_err(|e| format!("MPRIS drain failed: {e}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MediaRuntime {
|
||||
fn drop(&mut self) {
|
||||
self.stop.store(true, Ordering::Release);
|
||||
if let Some(worker) = self.worker.take() {
|
||||
let _ = worker.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "mpris"))]
|
||||
struct Disabled;
|
||||
#[cfg(not(feature = "mpris"))]
|
||||
impl Adapter for Disabled {
|
||||
fn discover(&mut self) -> Result<Vec<Player>, String> {
|
||||
Err("MPRIS support not compiled in".into())
|
||||
}
|
||||
fn execute(&mut self, _: &Player, _: &Action) -> Result<(), String> {
|
||||
Err("MPRIS support not compiled in".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "mpris")]
|
||||
mod native;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
struct Fake {
|
||||
players: Vec<Player>,
|
||||
calls: Vec<(String, Action)>,
|
||||
fail: bool,
|
||||
}
|
||||
impl Adapter for Fake {
|
||||
fn discover(&mut self) -> Result<Vec<Player>, String> {
|
||||
Ok(self.players.clone())
|
||||
}
|
||||
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String> {
|
||||
self.calls.push((player.owner.clone(), action.clone()));
|
||||
if self.fail {
|
||||
Err("timed out".into())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn targeted_commands_never_select_ambiguous_or_unsupported_players() {
|
||||
let selector = PlayerSelector {
|
||||
field: media::PlayerField::Identity,
|
||||
pattern: "QBZ".into(),
|
||||
regex: false,
|
||||
};
|
||||
let p = Player {
|
||||
identity: Some("QBZ".into()),
|
||||
owner: ":1.42".into(),
|
||||
can_control: true,
|
||||
can_play: true,
|
||||
..Player::default()
|
||||
};
|
||||
let mut adapter = Fake {
|
||||
players: vec![p.clone(), p.clone()],
|
||||
calls: vec![],
|
||||
fail: false,
|
||||
};
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_err());
|
||||
assert!(adapter.calls.is_empty());
|
||||
adapter.players.pop();
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Pause).is_err());
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_ok());
|
||||
assert_eq!(adapter.calls[0].0, ":1.42");
|
||||
adapter.fail = true;
|
||||
assert!(execute_selected(&mut adapter, &selector, &Action::Play).is_err());
|
||||
assert_eq!(adapter.players[0].playback, None);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,335 @@
|
|||
use super::*;
|
||||
use dbus::{
|
||||
Path,
|
||||
arg::{PropMap, RefArg},
|
||||
blocking::{Connection, stdintf::org_freedesktop_dbus::Properties},
|
||||
};
|
||||
use media::{Playback, Playlist, Repeat};
|
||||
|
||||
const PLAYER: &str = "org.mpris.MediaPlayer2.Player";
|
||||
const ROOT: &str = "org.mpris.MediaPlayer2";
|
||||
const PLAYLISTS: &str = "org.mpris.MediaPlayer2.Playlists";
|
||||
const PATH: &str = "/org/mpris/MediaPlayer2";
|
||||
const TIMEOUT: Duration = Duration::from_millis(200);
|
||||
type WirePlaylist = (Path<'static>, String, String);
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct DbusAdapter {
|
||||
connection: Option<Connection>,
|
||||
}
|
||||
|
||||
fn text(properties: &PropMap, key: &str) -> Option<String> {
|
||||
properties
|
||||
.get(key)?
|
||||
.0
|
||||
.as_str()
|
||||
.map(|s| s.chars().filter(|c| !c.is_control()).take(1024).collect())
|
||||
}
|
||||
fn flag(properties: &PropMap, key: &str) -> Option<bool> {
|
||||
properties.get(key)?.0.as_u64().map(|value| value != 0)
|
||||
}
|
||||
|
||||
impl DbusAdapter {
|
||||
fn connection(&mut self) -> Result<&Connection, String> {
|
||||
if self.connection.is_none() {
|
||||
self.connection = Some(Connection::new_session().map_err(|e| e.to_string())?);
|
||||
}
|
||||
self.connection
|
||||
.as_ref()
|
||||
.ok_or_else(|| "session bus unavailable".into())
|
||||
}
|
||||
|
||||
fn read_player(
|
||||
connection: &Connection,
|
||||
bus_name: String,
|
||||
owner: String,
|
||||
) -> Result<Player, String> {
|
||||
let proxy = connection.with_proxy(owner.clone(), PATH, TIMEOUT);
|
||||
let root = proxy.get_all(ROOT).map_err(|e| e.to_string())?;
|
||||
let props = proxy.get_all(PLAYER).map_err(|e| e.to_string())?;
|
||||
let playback = match text(&props, "PlaybackStatus").as_deref() {
|
||||
Some("Playing") => Some(Playback::Playing),
|
||||
Some("Paused") => Some(Playback::Paused),
|
||||
Some("Stopped") => Some(Playback::Stopped),
|
||||
_ => None,
|
||||
};
|
||||
let repeat = match text(&props, "LoopStatus").as_deref() {
|
||||
Some("None") => Some(Repeat::None),
|
||||
Some("Track") => Some(Repeat::Track),
|
||||
Some("Playlist") => Some(Repeat::Playlist),
|
||||
_ => None,
|
||||
};
|
||||
let metadata: PropMap = proxy.get(PLAYER, "Metadata").unwrap_or_default();
|
||||
let duration_ms = metadata
|
||||
.get("mpris:length")
|
||||
.and_then(|v| v.0.as_i64())
|
||||
.and_then(|n| u64::try_from(n).ok())
|
||||
.map(|n| n / 1000);
|
||||
let position_ms = props
|
||||
.get("Position")
|
||||
.and_then(|v| v.0.as_i64())
|
||||
.and_then(|n| u64::try_from(n).ok())
|
||||
.map(|n| n / 1000);
|
||||
let track_id = text(&metadata, "mpris:trackid")
|
||||
.filter(|id| id != "/org/mpris/MediaPlayer2/TrackList/NoTrack");
|
||||
let mut playlists = Vec::new();
|
||||
let mut active_playlist = None;
|
||||
if let Ok(playlist_props) = proxy.get_all(PLAYLISTS) {
|
||||
let count = playlist_props
|
||||
.get("PlaylistCount")
|
||||
.and_then(|v| v.0.as_u64())
|
||||
.unwrap_or(0)
|
||||
.min(256) as u32;
|
||||
let orderings: Vec<String> = proxy.get(PLAYLISTS, "Orderings").unwrap_or_default();
|
||||
if let Some(order) = orderings.first() {
|
||||
let result: Result<(Vec<WirePlaylist>,), _> = proxy.method_call(
|
||||
PLAYLISTS,
|
||||
"GetPlaylists",
|
||||
(0u32, count, order.as_str(), false),
|
||||
);
|
||||
if let Ok((items,)) = result {
|
||||
playlists = items
|
||||
.into_iter()
|
||||
.take(256)
|
||||
.map(|(id, name, _)| Playlist {
|
||||
id: id.to_string(),
|
||||
name: name.chars().filter(|c| !c.is_control()).take(256).collect(),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
let active: Result<(bool, WirePlaylist), _> = proxy.get(PLAYLISTS, "ActivePlaylist");
|
||||
if let Ok((true, (id, _, _))) = active {
|
||||
active_playlist = Some(id.to_string());
|
||||
}
|
||||
}
|
||||
Ok(Player {
|
||||
bus_name,
|
||||
owner,
|
||||
identity: text(&root, "Identity"),
|
||||
desktop_entry: text(&root, "DesktopEntry"),
|
||||
playback,
|
||||
can_control: flag(&props, "CanControl").unwrap_or(false),
|
||||
can_play: flag(&props, "CanPlay").unwrap_or(false),
|
||||
can_pause: flag(&props, "CanPause").unwrap_or(false),
|
||||
can_next: flag(&props, "CanGoNext").unwrap_or(false),
|
||||
can_previous: flag(&props, "CanGoPrevious").unwrap_or(false),
|
||||
can_seek: flag(&props, "CanSeek").unwrap_or(false),
|
||||
position_ms,
|
||||
duration_ms,
|
||||
track_id,
|
||||
shuffle: flag(&props, "Shuffle"),
|
||||
repeat,
|
||||
playlists,
|
||||
active_playlist,
|
||||
error: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Adapter for DbusAdapter {
|
||||
fn discover(&mut self) -> Result<Vec<Player>, String> {
|
||||
let connection = self.connection()?;
|
||||
let bus = connection.with_proxy("org.freedesktop.DBus", "/org/freedesktop/DBus", TIMEOUT);
|
||||
let names: Result<(Vec<String>,), _> =
|
||||
bus.method_call("org.freedesktop.DBus", "ListNames", ());
|
||||
let (names,) = match names {
|
||||
Ok(names) => names,
|
||||
Err(error) => {
|
||||
self.connection = None;
|
||||
return Err(error.to_string());
|
||||
}
|
||||
};
|
||||
let names = names
|
||||
.into_iter()
|
||||
.filter(|name| name.starts_with("org.mpris.MediaPlayer2."))
|
||||
.collect::<Vec<_>>();
|
||||
if names.len() > 32 {
|
||||
return Err("more than 32 MPRIS players; refusing incomplete discovery".into());
|
||||
}
|
||||
let started = Instant::now();
|
||||
let mut players = Vec::new();
|
||||
for name in names {
|
||||
if started.elapsed() > Duration::from_secs(2) {
|
||||
return Err("MPRIS discovery timed out".into());
|
||||
}
|
||||
let owner: Result<(String,), _> =
|
||||
bus.method_call("org.freedesktop.DBus", "GetNameOwner", (name.as_str(),));
|
||||
let Ok((owner,)) = owner else {
|
||||
continue;
|
||||
};
|
||||
match Self::read_player(connection, name.clone(), owner.clone()) {
|
||||
Ok(player) => players.push(player),
|
||||
Err(error) => players.push(Player {
|
||||
bus_name: name,
|
||||
owner,
|
||||
error: Some(error),
|
||||
..Player::default()
|
||||
}),
|
||||
}
|
||||
}
|
||||
Ok(players)
|
||||
}
|
||||
|
||||
fn execute(&mut self, player: &Player, action: &Action) -> Result<(), String> {
|
||||
let proxy = self
|
||||
.connection()?
|
||||
.with_proxy(player.owner.clone(), PATH, TIMEOUT);
|
||||
let result: Result<(), dbus::Error> = match action {
|
||||
Action::Play => proxy.method_call(PLAYER, "Play", ()),
|
||||
Action::Pause => proxy.method_call(PLAYER, "Pause", ()),
|
||||
Action::Stop => proxy.method_call(PLAYER, "Stop", ()),
|
||||
Action::PlayPause => proxy.method_call(PLAYER, "PlayPause", ()),
|
||||
Action::Next => proxy.method_call(PLAYER, "Next", ()),
|
||||
Action::Previous => proxy.method_call(PLAYER, "Previous", ()),
|
||||
Action::Seek { offset_ms } => {
|
||||
proxy.method_call(PLAYER, "Seek", (offset_ms.saturating_mul(1000),))
|
||||
}
|
||||
Action::SetPosition { position_ms } => {
|
||||
let track = player
|
||||
.track_id
|
||||
.as_deref()
|
||||
.ok_or("track identity unavailable")?;
|
||||
let path = Path::new(track).map_err(|e| e.to_string())?;
|
||||
let position = i64::try_from(*position_ms)
|
||||
.map_err(|e| e.to_string())?
|
||||
.saturating_mul(1000);
|
||||
proxy.method_call(PLAYER, "SetPosition", (path, position))
|
||||
}
|
||||
Action::Shuffle { enabled } => proxy.set(PLAYER, "Shuffle", *enabled),
|
||||
Action::ShuffleToggle => proxy.set(
|
||||
PLAYER,
|
||||
"Shuffle",
|
||||
!player.shuffle.ok_or("shuffle unavailable")?,
|
||||
),
|
||||
Action::Repeat { mode } => proxy.set(PLAYER, "LoopStatus", format!("{mode:?}")),
|
||||
Action::RepeatCycle => {
|
||||
let next = match player.repeat.ok_or("repeat unavailable")? {
|
||||
Repeat::None => "Track",
|
||||
Repeat::Track => "Playlist",
|
||||
Repeat::Playlist => "None",
|
||||
};
|
||||
proxy.set(PLAYER, "LoopStatus", next)
|
||||
}
|
||||
Action::Playlist { id } => proxy.method_call(
|
||||
PLAYLISTS,
|
||||
"ActivatePlaylist",
|
||||
(Path::new(id.clone()).map_err(|e| e.to_string())?,),
|
||||
),
|
||||
};
|
||||
result.map_err(|e| e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use dbus::{
|
||||
arg::Variant,
|
||||
channel::{MatchingReceiver, Sender},
|
||||
message::MatchRule,
|
||||
};
|
||||
|
||||
#[test]
|
||||
#[ignore = "run inside dbus-run-session; uses only a fake player"]
|
||||
fn private_bus_discovers_paused_player_and_confirms_play() {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let worker_stop = Arc::clone(&stop);
|
||||
let (ready_tx, ready_rx) = mpsc::sync_channel(1);
|
||||
let worker = thread::spawn(move || {
|
||||
let connection = Connection::new_session().unwrap();
|
||||
connection
|
||||
.request_name("org.mpris.MediaPlayer2.fader_fixture", false, true, false)
|
||||
.unwrap();
|
||||
let playing = Arc::new(AtomicBool::new(false));
|
||||
connection.start_receive(
|
||||
MatchRule::new_method_call(),
|
||||
Box::new(move |message, connection| {
|
||||
let reply = message.method_return();
|
||||
let member = message.member().map(|m| m.to_string()).unwrap_or_default();
|
||||
let interface = message
|
||||
.interface()
|
||||
.map(|m| m.to_string())
|
||||
.unwrap_or_default();
|
||||
let reply = if member == "GetAll" {
|
||||
let requested: String = message.read1().unwrap();
|
||||
let mut props: PropMap = PropMap::new();
|
||||
if requested == ROOT {
|
||||
props
|
||||
.insert("Identity".into(), Variant(Box::new("Fixture".to_owned())));
|
||||
}
|
||||
if requested == PLAYER {
|
||||
props.insert(
|
||||
"PlaybackStatus".into(),
|
||||
Variant(Box::new(
|
||||
if playing.load(Ordering::Relaxed) {
|
||||
"Playing"
|
||||
} else {
|
||||
"Paused"
|
||||
}
|
||||
.to_owned(),
|
||||
)),
|
||||
);
|
||||
for name in ["CanControl", "CanPlay", "CanPause"] {
|
||||
props.insert(name.into(), Variant(Box::new(true)));
|
||||
}
|
||||
}
|
||||
reply.append1(props)
|
||||
} else if member == "Get" {
|
||||
let (_, name): (String, String) = message.read2().unwrap();
|
||||
if name == "Metadata" {
|
||||
reply.append1(Variant(PropMap::new()))
|
||||
} else if name == "Orderings" {
|
||||
reply.append1(Variant(Vec::<String>::new()))
|
||||
} else {
|
||||
reply.append1(Variant((
|
||||
false,
|
||||
(Path::new("/").unwrap(), String::new(), String::new()),
|
||||
)))
|
||||
}
|
||||
} else {
|
||||
if interface == PLAYER && member == "Play" {
|
||||
playing.store(true, Ordering::Relaxed);
|
||||
}
|
||||
reply
|
||||
};
|
||||
connection.send(reply).unwrap();
|
||||
true
|
||||
}),
|
||||
);
|
||||
ready_tx.send(()).unwrap();
|
||||
while !worker_stop.load(Ordering::Acquire) {
|
||||
connection.process(Duration::from_millis(10)).unwrap();
|
||||
}
|
||||
});
|
||||
ready_rx.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||
let mut adapter = DbusAdapter::default();
|
||||
let selector = PlayerSelector {
|
||||
field: media::PlayerField::BusName,
|
||||
pattern: "org.mpris.MediaPlayer2.fader_fixture".into(),
|
||||
regex: false,
|
||||
};
|
||||
let before = adapter.discover();
|
||||
let after = execute_selected(&mut adapter, &selector, &Action::Play);
|
||||
stop.store(true, Ordering::Release);
|
||||
worker.join().unwrap();
|
||||
assert_eq!(
|
||||
selector
|
||||
.compile()
|
||||
.unwrap()
|
||||
.resolve(&before.unwrap())
|
||||
.unwrap()
|
||||
.playback,
|
||||
Some(Playback::Paused)
|
||||
);
|
||||
assert_eq!(
|
||||
selector
|
||||
.compile()
|
||||
.unwrap()
|
||||
.resolve(&after.unwrap())
|
||||
.unwrap()
|
||||
.playback,
|
||||
Some(Playback::Playing)
|
||||
);
|
||||
}
|
||||
}
|
||||
3
task.md
3
task.md
|
|
@ -624,6 +624,9 @@ Approved implementation slices for M13.3 (each independently tested/committed):
|
|||
- [ ] **M13.3b MPRIS adapter:** session-bus discovery independent of audio streams,
|
||||
bounded calls, capability reporting, owner-change handling and reconnects.
|
||||
Verify dependency license, native prerequisites and Rust 1.88 compatibility.
|
||||
Worker and native adapter implemented with pinned dbus 0.9.12; fake-adapter
|
||||
tests and isolated dbus-run-session discovery/Play readback fixture pass.
|
||||
Live-server wiring and final workspace qualification follow.
|
||||
- [ ] **M13.3c Media entries:** stable IDs, labels, exact/regex selectors on bus
|
||||
name, desktop entry or identity; live picker plus manual entry; reject ambiguous
|
||||
targets rather than selecting arbitrarily. Persist MIDI action bindings.
|
||||
|
|
|
|||
Loading…
Reference in New Issue