400 lines
12 KiB
Rust
400 lines
12 KiB
Rust
//! Hardware-free MPRIS matching, action and feedback contracts.
|
||
#![forbid(unsafe_code)]
|
||
|
||
use serde::{Deserialize, Serialize};
|
||
use thiserror::Error;
|
||
|
||
#[derive(Debug, Error)]
|
||
pub enum MediaError {
|
||
#[error("player offline")]
|
||
Offline,
|
||
#[error("selector matches multiple players; narrow the selector")]
|
||
Ambiguous,
|
||
#[error("unsupported player action")]
|
||
Unsupported,
|
||
#[error("invalid media configuration: {0}")]
|
||
Invalid(String),
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(rename_all = "snake_case")]
|
||
pub enum PlayerField {
|
||
#[default]
|
||
BusName,
|
||
DesktopEntry,
|
||
Identity,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct PlayerSelector {
|
||
pub field: PlayerField,
|
||
pub pattern: String,
|
||
#[serde(default)]
|
||
pub regex: bool,
|
||
}
|
||
|
||
#[derive(Clone, Debug)]
|
||
pub struct PlayerMatcher {
|
||
selector: PlayerSelector,
|
||
regex: Option<regex::Regex>,
|
||
}
|
||
|
||
impl PlayerSelector {
|
||
pub fn compile(&self) -> Result<PlayerMatcher, MediaError> {
|
||
if self.pattern.is_empty() || self.pattern.len() > 256 {
|
||
return Err(MediaError::Invalid(
|
||
"selector must contain 1–256 bytes".into(),
|
||
));
|
||
}
|
||
let regex = if self.regex {
|
||
Some(
|
||
regex::RegexBuilder::new(&self.pattern)
|
||
.size_limit(1 << 20)
|
||
.build()
|
||
.map_err(|e| MediaError::Invalid(e.to_string()))?,
|
||
)
|
||
} else {
|
||
None
|
||
};
|
||
Ok(PlayerMatcher {
|
||
selector: self.clone(),
|
||
regex,
|
||
})
|
||
}
|
||
}
|
||
|
||
impl PlayerMatcher {
|
||
pub fn matches(&self, player: &Player) -> bool {
|
||
let value = match self.selector.field {
|
||
PlayerField::BusName => Some(player.bus_name.as_str()),
|
||
PlayerField::DesktopEntry => player.desktop_entry.as_deref(),
|
||
PlayerField::Identity => player.identity.as_deref(),
|
||
};
|
||
value.is_some_and(|value| {
|
||
self.regex
|
||
.as_ref()
|
||
.map_or_else(|| value == self.selector.pattern, |re| re.is_match(value))
|
||
})
|
||
}
|
||
pub fn resolve<'a>(&self, players: &'a [Player]) -> Result<&'a Player, MediaError> {
|
||
let mut matches = players.iter().filter(|p| self.matches(p));
|
||
let first = matches.next().ok_or(MediaError::Offline)?;
|
||
if matches.next().is_some() {
|
||
return Err(MediaError::Ambiguous);
|
||
}
|
||
Ok(first)
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
pub enum Playback {
|
||
Playing,
|
||
Paused,
|
||
Stopped,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||
pub enum Repeat {
|
||
#[default]
|
||
None,
|
||
Track,
|
||
Playlist,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||
pub enum Action {
|
||
Play,
|
||
Pause,
|
||
Stop,
|
||
PlayPause,
|
||
Next,
|
||
Previous,
|
||
Seek { offset_ms: i64 },
|
||
SetPosition { position_ms: u64 },
|
||
ShuffleToggle,
|
||
Shuffle { enabled: bool },
|
||
RepeatCycle,
|
||
Repeat { mode: Repeat },
|
||
Playlist { id: String },
|
||
}
|
||
|
||
impl Action {
|
||
pub fn validate(&self) -> Result<(), MediaError> {
|
||
match self {
|
||
Self::Seek { offset_ms } if offset_ms.unsigned_abs() > 86_400_000 => {
|
||
Err(MediaError::Invalid("seek offset exceeds one day".into()))
|
||
}
|
||
Self::SetPosition { position_ms } if *position_ms > 86_400_000 => {
|
||
Err(MediaError::Invalid("position exceeds one day".into()))
|
||
}
|
||
Self::Playlist { id } if !valid_object_path(id) => {
|
||
Err(MediaError::Invalid("invalid playlist object path".into()))
|
||
}
|
||
_ => Ok(()),
|
||
}
|
||
}
|
||
pub fn supported(&self, p: &Player) -> bool {
|
||
if !p.can_control {
|
||
return false;
|
||
}
|
||
match self {
|
||
Self::Play => p.can_play,
|
||
Self::Pause => p.can_pause,
|
||
Self::PlayPause => match p.playback {
|
||
Some(Playback::Playing) => p.can_pause,
|
||
Some(_) => p.can_play,
|
||
None => false,
|
||
},
|
||
Self::Stop => true,
|
||
Self::Next => p.can_next,
|
||
Self::Previous => p.can_previous,
|
||
Self::Seek { .. } => p.can_seek,
|
||
Self::SetPosition { position_ms } => {
|
||
p.can_seek
|
||
&& p.track_id.is_some()
|
||
&& p.duration_ms.is_some_and(|length| *position_ms <= length)
|
||
}
|
||
Self::ShuffleToggle | Self::Shuffle { .. } => p.shuffle.is_some(),
|
||
Self::RepeatCycle | Self::Repeat { .. } => p.repeat.is_some(),
|
||
Self::Playlist { id } => p.playlists.iter().any(|playlist| &playlist.id == id),
|
||
}
|
||
}
|
||
/// State indicators are observations, never acknowledgements of a command.
|
||
pub fn feedback(&self, player: Option<&Player>) -> bool {
|
||
let Some(p) = player else {
|
||
return false;
|
||
};
|
||
match self {
|
||
Self::Play | Self::PlayPause => p.playback == Some(Playback::Playing),
|
||
Self::Pause => p.playback == Some(Playback::Paused),
|
||
Self::Stop => p.playback == Some(Playback::Stopped),
|
||
Self::ShuffleToggle => p.shuffle == Some(true),
|
||
Self::Shuffle { enabled } => p.shuffle == Some(*enabled),
|
||
Self::RepeatCycle => matches!(p.repeat, Some(Repeat::Track | Repeat::Playlist)),
|
||
Self::Repeat { mode } => p.repeat == Some(*mode),
|
||
Self::Playlist { id } => p.active_playlist.as_ref() == Some(id),
|
||
_ => false,
|
||
}
|
||
}
|
||
}
|
||
|
||
fn valid_object_path(value: &str) -> bool {
|
||
value == "/"
|
||
|| (value.len() <= 1024
|
||
&& value.starts_with('/')
|
||
&& value.split('/').skip(1).all(|part| {
|
||
!part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||
}))
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||
pub struct Player {
|
||
pub bus_name: String,
|
||
/// Unique D-Bus owner; commands must never jump to a replacement instance.
|
||
pub owner: String,
|
||
pub identity: Option<String>,
|
||
pub desktop_entry: Option<String>,
|
||
pub playback: Option<Playback>,
|
||
pub can_control: bool,
|
||
pub can_play: bool,
|
||
pub can_pause: bool,
|
||
pub can_next: bool,
|
||
pub can_previous: bool,
|
||
pub can_seek: bool,
|
||
pub position_ms: Option<u64>,
|
||
pub duration_ms: Option<u64>,
|
||
pub track_id: Option<String>,
|
||
pub shuffle: Option<bool>,
|
||
pub repeat: Option<Repeat>,
|
||
pub playlists: Vec<Playlist>,
|
||
pub active_playlist: Option<String>,
|
||
pub error: Option<String>,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
pub struct Playlist {
|
||
pub id: String,
|
||
pub name: String,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||
pub struct Snapshot {
|
||
pub available: bool,
|
||
pub error: Option<String>,
|
||
pub players: Vec<Player>,
|
||
}
|
||
|
||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(rename_all = "snake_case")]
|
||
pub enum MessageKind {
|
||
Note,
|
||
Cc,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct Message {
|
||
pub kind: MessageKind,
|
||
pub channel: u16,
|
||
pub number: u16,
|
||
}
|
||
|
||
impl Message {
|
||
pub fn validate(&self) -> Result<(), MediaError> {
|
||
fader_core::MidiChannel::new(self.channel)
|
||
.map_err(|e| MediaError::Invalid(e.to_string()))?;
|
||
fader_core::MidiData::new(self.number).map_err(|e| MediaError::Invalid(e.to_string()))?;
|
||
Ok(())
|
||
}
|
||
pub fn bytes(&self, value: u8) -> Option<[u8; 3]> {
|
||
self.validate().ok()?;
|
||
let status = match self.kind {
|
||
MessageKind::Note => 0x90,
|
||
MessageKind::Cc => 0xb0,
|
||
};
|
||
Some([
|
||
status | u8::try_from(self.channel - 1).ok()?,
|
||
u8::try_from(self.number).ok()?,
|
||
value,
|
||
])
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct Feedback {
|
||
pub message: Message,
|
||
pub on: u8,
|
||
pub off: u8,
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct Binding {
|
||
pub surface: String,
|
||
pub message: Message,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub feedback: Option<Feedback>,
|
||
}
|
||
|
||
impl Binding {
|
||
pub fn feedback_bytes(&self, on: bool) -> Option<[u8; 3]> {
|
||
if let Some(feedback) = &self.feedback {
|
||
feedback
|
||
.message
|
||
.bytes(if on { feedback.on } else { feedback.off })
|
||
} else if self.message.kind == MessageKind::Note {
|
||
self.message.bytes(if on { 127 } else { 0 })
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct Control {
|
||
pub id: String,
|
||
pub action: Action,
|
||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||
pub binding: Option<Binding>,
|
||
}
|
||
|
||
const fn enabled() -> bool {
|
||
true
|
||
}
|
||
|
||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||
#[serde(deny_unknown_fields)]
|
||
pub struct Entry {
|
||
pub id: String,
|
||
pub label: String,
|
||
pub selector: PlayerSelector,
|
||
#[serde(default = "enabled")]
|
||
pub feedback_enabled: bool,
|
||
#[serde(default)]
|
||
pub controls: Vec<Control>,
|
||
}
|
||
|
||
impl Entry {
|
||
pub fn validate(&self) -> Result<(), MediaError> {
|
||
fader_core::ApplicationId::new(&self.id).map_err(|e| MediaError::Invalid(e.to_string()))?;
|
||
if self.label.trim().is_empty()
|
||
|| self.label.len() > 128
|
||
|| self.label.chars().any(char::is_control)
|
||
{
|
||
return Err(MediaError::Invalid("invalid media label".into()));
|
||
}
|
||
self.selector.compile()?;
|
||
if self.controls.len() > 64 {
|
||
return Err(MediaError::Invalid("at most 64 controls per entry".into()));
|
||
}
|
||
let mut ids = std::collections::BTreeSet::new();
|
||
for control in &self.controls {
|
||
fader_core::FaderId::new(&control.id)
|
||
.map_err(|e| MediaError::Invalid(e.to_string()))?;
|
||
if !ids.insert(&control.id) {
|
||
return Err(MediaError::Invalid("duplicate control ID".into()));
|
||
}
|
||
control.action.validate()?;
|
||
if let Some(binding) = &control.binding {
|
||
binding.message.validate()?;
|
||
if let Some(feedback) = &binding.feedback {
|
||
feedback.message.validate()?;
|
||
if feedback.on > 127 || feedback.off > 127 {
|
||
return Err(MediaError::Invalid("feedback values must be 0–127".into()));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn matching_is_explicit_and_never_picks_an_ambiguous_player() {
|
||
let selector = PlayerSelector {
|
||
field: PlayerField::BusName,
|
||
pattern: "org.mpris.MediaPlayer2.com.blitzfc.qbz".into(),
|
||
regex: false,
|
||
};
|
||
let matcher = selector.compile().unwrap();
|
||
let qbz = Player {
|
||
bus_name: selector.pattern.clone(),
|
||
owner: ":1.4".into(),
|
||
..Player::default()
|
||
};
|
||
assert!(matches!(matcher.resolve(&[]), Err(MediaError::Offline)));
|
||
assert_eq!(
|
||
matcher.resolve(std::slice::from_ref(&qbz)).unwrap().owner,
|
||
":1.4"
|
||
);
|
||
assert!(matches!(
|
||
matcher.resolve(&[qbz.clone(), qbz]),
|
||
Err(MediaError::Ambiguous)
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn feedback_tracks_observation_not_intent() {
|
||
for status in [Playback::Playing, Playback::Paused, Playback::Stopped] {
|
||
let player = Player {
|
||
playback: Some(status),
|
||
..Player::default()
|
||
};
|
||
let on = [Action::Play, Action::Pause, Action::Stop]
|
||
.iter()
|
||
.filter(|a| a.feedback(Some(&player)))
|
||
.count();
|
||
assert_eq!(on, 1);
|
||
}
|
||
assert!(!Action::Play.feedback(None));
|
||
}
|
||
}
|