From e7067e277fc860d1fa644854d42d1f00c5d03f45 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Wed, 14 Oct 2026 19:40:52 +0200 Subject: [PATCH] feat(M4.1): subscribe to Pulse stream changes Subscribe before enumeration, retain sink-input notifications across the snapshot window, and expose copied upsert/removal events. Add an opt-in Rust fixture for list, watch, volume, and mute verification without production shell parsing. Tests: cargo fmt --all -- --check; cargo test -p volume_lib --all-targets --all-features --locked; cargo check -p volume_lib --all-targets --no-default-features --locked; cargo clippy -p volume_lib --all-targets --all-features --locked -- -D warnings (all pass) --- sound/Cargo.toml | 4 ++ sound/examples/pulse_fixture.rs | 101 ++++++++++++++++++++++++++++++++ sound/src/lib.rs | 2 +- sound/src/pulse.rs | 68 ++++++++++++++++++++- 4 files changed, 173 insertions(+), 2 deletions(-) create mode 100644 sound/examples/pulse_fixture.rs diff --git a/sound/Cargo.toml b/sound/Cargo.toml index 8f56efa..0187409 100644 --- a/sound/Cargo.toml +++ b/sound/Cargo.toml @@ -15,3 +15,7 @@ pulse = ["dep:libpulse-binding"] fader-core.workspace = true libpulse-binding = { workspace = true, optional = true } thiserror.workspace = true + +[[example]] +name = "pulse_fixture" +required-features = ["pulse"] diff --git a/sound/examples/pulse_fixture.rs b/sound/examples/pulse_fixture.rs new file mode 100644 index 0000000..284eeb9 --- /dev/null +++ b/sound/examples/pulse_fixture.rs @@ -0,0 +1,101 @@ +use std::{error::Error, io, time::Duration}; + +use fader_core::{Gain, MetadataField, Mute}; +use volume_lib::{PulseClient, PulseNotification, PulseStream}; + +fn main() -> Result<(), Box> { + let mut arguments = std::env::args().skip(1); + let command = arguments.next().unwrap_or_else(|| "list".to_owned()); + let mut client = PulseClient::connect()?; + + match command.as_str() { + "list" => list(&mut client)?, + "watch" => { + let seconds = arguments.next().as_deref().unwrap_or("15").parse::()?; + watch(&mut client, Duration::from_secs(seconds))?; + } + "volume" => { + let index = parse_required(&mut arguments, "sink-input index")?.parse::()?; + let gain = Gain::new(parse_required(&mut arguments, "linear gain")?.parse::()?)?; + let current = client.stream(index)?; + if !current.volume_writable { + return Err(invalid_input("selected sink input is not volume-writable")); + } + let channels = current.channels.scaled_to(gain, Gain::new(4.0)?)?; + print_stream(&client.set_volume(index, &channels)?); + } + "mute" => { + let index = parse_required(&mut arguments, "sink-input index")?.parse::()?; + let muted = match parse_required(&mut arguments, "on or off")?.as_str() { + "on" => Mute::Muted, + "off" => Mute::Unmuted, + _ => return Err(invalid_input("mute value must be 'on' or 'off'")), + }; + print_stream(&client.set_mute(index, muted)?); + } + _ => { + return Err(invalid_input( + "usage: pulse_fixture [list|watch [SECONDS]|volume INDEX GAIN|mute INDEX on|off]", + )); + } + } + Ok(()) +} + +fn list(client: &mut PulseClient) -> Result<(), Box> { + for stream in client.streams()? { + print_stream(&stream); + } + Ok(()) +} + +fn watch(client: &mut PulseClient, duration: Duration) -> Result<(), Box> { + client.subscribe()?; + list(client)?; + let deadline = std::time::Instant::now() + duration; + while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) { + match client.poll_notification(remaining.min(Duration::from_millis(250)))? { + Some(PulseNotification::Upsert(stream)) => print_stream(&stream), + Some(PulseNotification::Removed(index)) => println!("removed index={index}"), + None => {} + } + } + Ok(()) +} + +fn print_stream(stream: &PulseStream) { + let application = stream + .metadata + .value(MetadataField::ApplicationName) + .unwrap_or(""); + let binary = stream + .metadata + .value(MetadataField::ProcessBinary) + .unwrap_or(""); + let gains = stream + .channels + .as_slice() + .iter() + .map(|gain| format!("{:.4}", gain.get())) + .collect::>() + .join(","); + println!( + "index={} application={application:?} binary={binary:?} channels=[{gains}] muted={} writable={}", + stream.index, + stream.muted == Mute::Muted, + stream.volume_writable + ); +} + +fn parse_required( + arguments: &mut impl Iterator, + name: &str, +) -> Result> { + arguments + .next() + .ok_or_else(|| invalid_input(&format!("missing {name}"))) +} + +fn invalid_input(message: &str) -> Box { + Box::new(io::Error::new(io::ErrorKind::InvalidInput, message)) +} diff --git a/sound/src/lib.rs b/sound/src/lib.rs index 2865c95..859fae7 100644 --- a/sound/src/lib.rs +++ b/sound/src/lib.rs @@ -6,7 +6,7 @@ mod pulse; #[cfg(feature = "pulse")] -pub use pulse::{PulseClient, PulseError, PulseStream}; +pub use pulse::{PulseClient, PulseError, PulseNotification, PulseStream}; use std::{ collections::{BTreeMap, VecDeque}, diff --git a/sound/src/pulse.rs b/sound/src/pulse.rs index 9f2b9af..7cdad43 100644 --- a/sound/src/pulse.rs +++ b/sound/src/pulse.rs @@ -9,6 +9,7 @@ use fader_core::{ChannelGains, Gain, Mute, StreamMetadata}; use libpulse_binding as pulse; use pulse::{ callbacks::ListResult, + context::subscribe::{Facility, InterestMaskSet, Operation}, context::{Context, FlagSet, State}, mainloop::standard::{IterateResult, Mainloop}, proplist::properties, @@ -17,6 +18,7 @@ use pulse::{ use thiserror::Error; const OPERATION_TIMEOUT: Duration = Duration::from_secs(3); +type NotificationQueue = Rc>>; /// Copied PulseAudio playback-stream information. #[derive(Clone, Debug, PartialEq)] @@ -28,6 +30,13 @@ pub struct PulseStream { pub volume_writable: bool, } +/// One subscribed playback-stream change. +#[derive(Clone, Debug, PartialEq)] +pub enum PulseNotification { + Upsert(PulseStream), + Removed(u32), +} + /// Failures at the Pulse protocol boundary. #[derive(Debug, Error)] pub enum PulseError { @@ -61,6 +70,7 @@ pub enum PulseError { pub struct PulseClient { mainloop: Mainloop, context: Context, + notifications: Option, } impl PulseClient { @@ -77,11 +87,67 @@ impl PulseClient { context .connect(server, FlagSet::NOAUTOSPAWN, None) .map_err(|error| PulseError::Connect(format!("{error:?}")))?; - let mut client = Self { mainloop, context }; + let mut client = Self { + mainloop, + context, + notifications: None, + }; client.wait_until_ready()?; Ok(client) } + /// Subscribes before enumeration so changes observed during a snapshot remain queued. + pub fn subscribe(&mut self) -> Result<(), PulseError> { + let notifications = Rc::new(RefCell::new(std::collections::VecDeque::new())); + let callback = Rc::clone(¬ifications); + self.context + .set_subscribe_callback(Some(Box::new(move |facility, operation, index| { + if facility == Some(Facility::SinkInput) + && let Some(operation) = operation + { + callback.borrow_mut().push_back((operation, index)); + } + }))); + let subscribed = Rc::new(RefCell::new(None)); + let result = Rc::clone(&subscribed); + self.context + .subscribe(InterestMaskSet::SINK_INPUT, move |success| { + *result.borrow_mut() = Some(success); + }); + self.wait_for(|| subscribed.borrow().is_some())?; + if subscribed.borrow().is_none_or(|success| !success) { + return Err(PulseError::Rejected); + } + self.notifications = Some(notifications); + Ok(()) + } + + /// Waits up to the requested duration for one subscription event. + pub fn poll_notification( + &mut self, + timeout: Duration, + ) -> Result, PulseError> { + let Some(notifications) = self.notifications.as_ref().map(Rc::clone) else { + return Ok(None); + }; + let deadline = Instant::now() + timeout; + while notifications.borrow().is_empty() { + if Instant::now() >= deadline { + return Ok(None); + } + self.iterate(deadline)?; + } + let Some((operation, index)) = notifications.borrow_mut().pop_front() else { + return Ok(None); + }; + match operation { + Operation::Removed => Ok(Some(PulseNotification::Removed(index))), + Operation::New | Operation::Changed => { + self.stream(index).map(PulseNotification::Upsert).map(Some) + } + } + } + /// Enumerates current playback sink inputs and deep-copies callback data. pub fn streams(&mut self) -> Result, PulseError> { let result = Rc::new(RefCell::new(ListState::::default()));