diff --git a/Cargo.lock b/Cargo.lock index 76f75ce..cc9b22c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -403,6 +403,7 @@ name = "fader-config" version = "0.1.0-rc.2" dependencies = [ "fader-core", + "media", "rustix 1.1.5", "serde", "tempfile", @@ -784,6 +785,16 @@ dependencies = [ "hashbrown 0.15.5", ] +[[package]] +name = "media" +version = "0.1.0-rc.2" +dependencies = [ + "fader-core", + "regex", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "memchr" version = "2.8.3" diff --git a/Cargo.toml b/Cargo.toml index 55c48ba..8990ef7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["config", "core", "fader_master", "midi", "sound", "tui"] +members = ["config", "core", "fader_master", "media", "midi", "sound", "tui"] resolver = "3" [workspace.package] @@ -11,6 +11,7 @@ repository = "https://proxy.dandaedre.com/gitea/MadGobblins/fader_master" publish = false [workspace.dependencies] +media = { path = "media" } alsa = "0.12.1" anyhow = "1.0.104" clap = { version = "4.6.7", features = ["derive"] } diff --git a/architecture.md b/architecture.md index 4ab401a..3e6a339 100644 --- a/architecture.md +++ b/architecture.md @@ -192,6 +192,15 @@ fader-table scope, applied on configuration Save, including explicit mappings. The protocol boundary follows the [MPRIS Player interface](https://specifications.freedesktop.org/mpris/latest/Player_Interface.html). +The hardware-free `media` crate defines player selectors, capability-aware +actions, observed playback state, configuration entries and MIDI feedback rules. +`[[media]]` entries have stable IDs, labels, a selector, a default-enabled feedback +gate, and controls with stable IDs/actions/optional bindings. Configuration +validates selectors, limits, references and input collisions with mixer bindings +before activation. Entry editing is transactional; removing a surface unbinds its +media controls without deleting entries. Runtime/UI integration follows this +schema slice; it is not yet evidence of a functioning D-Bus adapter. + ## 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. diff --git a/config/Cargo.toml b/config/Cargo.toml index fd81c26..cb82ddb 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -8,6 +8,7 @@ repository.workspace = true publish.workspace = true [dependencies] +media.workspace = true fader-core.workspace = true rustix.workspace = true serde.workspace = true diff --git a/config/src/document.rs b/config/src/document.rs index b571007..931d9f6 100644 --- a/config/src/document.rs +++ b/config/src/document.rs @@ -212,7 +212,29 @@ pickup_tolerance = 0.02 /// Removes a MIDI surface and all configuration that references it. pub fn remove_surface(&mut self, id: &str) -> Result<(), ConfigError> { + let mut updates = Vec::new(); + for mut entry in self.preview()?.media().iter().cloned() { + if entry + .controls + .iter() + .any(|c| c.binding.as_ref().is_some_and(|b| b.surface == id)) + { + for control in &mut entry.controls { + if control.binding.as_ref().is_some_and(|b| b.surface == id) { + control.binding = None; + } + } + let mut table = DocumentMut::from_str(&toml::to_string(&entry)?)? + .as_table() + .clone(); + clear_table_positions(&mut table); + updates.push((entry.id, table)); + } + } self.transaction(|document| { + for (entry, table) in updates { + *find_table_mut(document, "media", &entry)? = table; + } remove_table_entry(document, "surfaces", id)?; if let Some(bindings) = document .get_mut("bindings") @@ -300,6 +322,37 @@ pickup_tolerance = 0.02 }) } + /// Creates or updates one validated media entry atomically. + pub fn set_media_entry(&mut self, entry: &media::Entry) -> Result<(), ConfigError> { + let serialized = toml::to_string(entry)?; + let mut replacement = DocumentMut::from_str(&serialized)?.as_table().clone(); + clear_table_positions(&mut replacement); + self.transaction(|document| { + let entries = array_of_tables_mut(document, "media")?; + if let Some(existing) = entries + .iter_mut() + .find(|t| t.get("id").and_then(Item::as_str) == Some(entry.id.as_str())) + { + *existing = replacement; + } else { + entries.push(replacement); + } + Ok(()) + }) + } + + pub fn remove_media_entry(&mut self, id: &str) -> Result<(), ConfigError> { + self.transaction(|document| { + let entries = array_of_tables_mut(document, "media")?; + let index = entries + .iter() + .position(|t| t.get("id").and_then(Item::as_str) == Some(id)) + .ok_or_else(|| ConfigError::validation("media", "unknown media entry"))?; + entries.remove(index); + Ok(()) + }) + } + /// Sets the global or per-fader MIDI feedback gate transactionally. pub fn set_feedback_enabled( &mut self, @@ -882,6 +935,24 @@ fn find_table_mut<'a>( .ok_or_else(|| ConfigError::validation(section, format!("unknown {section} entry {id:?}"))) } +fn clear_table_positions(table: &mut Table) { + let mut unpositioned = Table::new(); + for (key, item) in table.iter() { + unpositioned.insert(key, item.clone()); + } + *table = unpositioned; + for (_, item) in table.iter_mut() { + if let Some(child) = item.as_table_mut() { + clear_table_positions(child); + } + if let Some(children) = item.as_array_of_tables_mut() { + for child in children.iter_mut() { + clear_table_positions(child); + } + } + } +} + fn array_of_tables_mut<'a>( document: &'a mut DocumentMut, section: &str, diff --git a/config/src/profile.rs b/config/src/profile.rs index 6c082c6..7de1edc 100644 --- a/config/src/profile.rs +++ b/config/src/profile.rs @@ -390,6 +390,8 @@ pub struct Binding { #[derive(Clone, Debug, Deserialize, PartialEq, Serialize)] #[serde(deny_unknown_fields)] struct RawProfile { + #[serde(default, skip_serializing_if = "Vec::is_empty")] + media: Vec, #[serde(default = "enabled")] feedback_enabled: bool, schema_version: u16, @@ -424,6 +426,9 @@ pub struct Profile { } impl Profile { + pub fn media(&self) -> &[media::Entry] { + &self.raw.media + } /// Master gate for every MIDI output message generated as feedback. pub const fn feedback_enabled(&self) -> bool { self.raw.feedback_enabled @@ -436,6 +441,7 @@ impl Profile { validate_runtime(&raw.runtime)?; validate_audio(&raw.audio)?; validate_profile_members(&raw)?; + validate_media(&raw)?; let mixer_layout = effective_mixer_layout(&raw); Ok(Self { raw, @@ -569,6 +575,52 @@ impl Profile { } } +fn validate_media(raw: &RawProfile) -> Result<(), ConfigError> { + let invalid = |message: String| ConfigError::validation("media", message); + if raw.media.len() > 128 { + return Err(invalid("at most 128 media entries".into())); + } + let mut ids = BTreeSet::new(); + let mut inputs = BTreeSet::new(); + for binding in &raw.bindings { + inputs.insert(( + binding.surface.as_str(), + binding.message.kind == MessageKind::Note, + binding.message.channel, + binding.message.number, + )); + } + for entry in &raw.media { + entry.validate().map_err(|e| invalid(e.to_string()))?; + if !ids.insert(&entry.id) { + return Err(invalid("duplicate media entry ID".into())); + } + for control in &entry.controls { + if let Some(binding) = &control.binding { + let surface = raw + .surfaces + .iter() + .find(|s| s.id == binding.surface) + .ok_or_else(|| invalid(format!("unknown surface {}", binding.surface)))?; + if binding.feedback.is_some() && surface.output_port.is_none() { + return Err(invalid("media feedback needs an output port".into())); + } + if !inputs.insert(( + binding.surface.as_str(), + binding.message.kind == media::MessageKind::Note, + binding.message.channel, + binding.message.number, + )) { + return Err(invalid( + "MIDI input is already bound to another action".into(), + )); + } + } + } + } + Ok(()) +} + impl Audio { /// Configured automatic or manual adapter choice. #[must_use] diff --git a/config/tests/schema.rs b/config/tests/schema.rs index e2d6907..130bac0 100644 --- a/config/tests/schema.rs +++ b/config/tests/schema.rs @@ -6,6 +6,41 @@ const EXAMPLE: &str = include_str!("../../examples/profiles/desktop.toml"); const ARCH_PIPEWIRE: &str = include_str!("../../examples/profiles/arch-pipewire.toml"); const ARCHITECTURE: &str = include_str!("../../architecture.md"); +#[test] +fn media_entries_round_trip_and_validate_selectors_and_midi_collisions() { + let extra = r#" +[[media]] +id = "qbz" +label = "QBZ" +feedback_enabled = false +selector = { field = "bus_name", pattern = "org.mpris.MediaPlayer2.com.blitzfc.qbz" } +controls = [{ id = "play", action = { kind = "play" }, binding = { surface = "desk-left", message = { kind = "note", channel = 1, number = 40 } } }] +"#; + let source = format!("{EXAMPLE}\n{extra}"); + let profile = Profile::parse(&source).unwrap(); + let mut document = fader_config::ProfileDocument::parse(&source).unwrap(); + let mut entry = profile.media()[0].clone(); + entry.label = "Renamed QBZ".into(); + document.set_media_entry(&entry).unwrap(); + assert_eq!(document.preview().unwrap().media()[0].label, "Renamed QBZ"); + document.remove_surface("desk-left").unwrap(); + assert!( + document.preview().unwrap().media()[0].controls[0] + .binding + .is_none() + ); + document.remove_media_entry("qbz").unwrap(); + assert!(document.preview().unwrap().media().is_empty()); + assert_eq!( + profile, + Profile::parse(&profile.to_toml().unwrap()).unwrap() + ); + assert!(Profile::parse(&source.replace("number = 40", "number = 32")).is_err()); + assert!( + Profile::parse(&source.replace("field = \"bus_name\"", "field = \"unknown\"")).is_err() + ); +} + #[test] fn feedback_switches_override_explicit_and_default_output() { for source in [ diff --git a/docs/configuration.md b/docs/configuration.md index f92bd4e..ab255c0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -116,7 +116,7 @@ disable only that fader. Config and Edit fader expose these switches. Save the configuration to apply them. Disabled feedback sends nothing, even light-off messages; lights may retain their previous state until re-enabled and refreshed. -Selectors are ORed. Each selector chooses exactly one supported metadata field +Selectors are ORed by default. Each selector chooses exactly one supported metadata field and exactly one matching mode: ```toml diff --git a/media/Cargo.toml b/media/Cargo.toml new file mode 100644 index 0000000..dd02926 --- /dev/null +++ b/media/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "media" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license-file.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +fader-core.workspace = true +serde.workspace = true +regex.workspace = true +thiserror.workspace = true diff --git a/media/src/lib.rs b/media/src/lib.rs new file mode 100644 index 0000000..af63236 --- /dev/null +++ b/media/src/lib.rs @@ -0,0 +1,399 @@ +//! 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, +} + +impl PlayerSelector { + pub fn compile(&self) -> Result { + 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, + pub desktop_entry: Option, + pub playback: Option, + 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, + pub duration_ms: Option, + pub track_id: Option, + pub shuffle: Option, + pub repeat: Option, + pub playlists: Vec, + pub active_playlist: Option, + pub error: Option, +} + +#[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, + pub players: Vec, +} + +#[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, +} + +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, +} + +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, +} + +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)); + } +} diff --git a/task.md b/task.md index dcb63cc..52f18a6 100644 --- a/task.md +++ b/task.md @@ -627,6 +627,8 @@ Approved implementation slices for M13.3 (each independently tested/committed): - [ ] **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. + Hardware-free contracts and validated transactional profile entries are in + place; discovery, live editing and MIDI routing integration follow. - [ ] **M13.3d Media tab:** server-advertised availability, A/E/D editing, validated Save and exit, MIDI Learn with U to unbind; retain offline entries. Support Play, Pause, Stop, PlayPause, Next and Previous with capability checks.