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)
This commit is contained in:
Dandaedre 2026-10-14 19:40:52 +02:00
parent 90ba84a802
commit e7067e277f
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
4 changed files with 173 additions and 2 deletions

View File

@ -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"]

View File

@ -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<dyn Error>> {
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::<u64>()?;
watch(&mut client, Duration::from_secs(seconds))?;
}
"volume" => {
let index = parse_required(&mut arguments, "sink-input index")?.parse::<u32>()?;
let gain = Gain::new(parse_required(&mut arguments, "linear gain")?.parse::<f64>()?)?;
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::<u32>()?;
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<dyn Error>> {
for stream in client.streams()? {
print_stream(&stream);
}
Ok(())
}
fn watch(client: &mut PulseClient, duration: Duration) -> Result<(), Box<dyn Error>> {
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("<unknown application>");
let binary = stream
.metadata
.value(MetadataField::ProcessBinary)
.unwrap_or("<unknown binary>");
let gains = stream
.channels
.as_slice()
.iter()
.map(|gain| format!("{:.4}", gain.get()))
.collect::<Vec<_>>()
.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<Item = String>,
name: &str,
) -> Result<String, Box<dyn Error>> {
arguments
.next()
.ok_or_else(|| invalid_input(&format!("missing {name}")))
}
fn invalid_input(message: &str) -> Box<dyn Error> {
Box::new(io::Error::new(io::ErrorKind::InvalidInput, message))
}

View File

@ -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},

View File

@ -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<RefCell<std::collections::VecDeque<(Operation, u32)>>>;
/// 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<NotificationQueue>,
}
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(&notifications);
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<Option<PulseNotification>, 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<Vec<PulseStream>, PulseError> {
let result = Rc::new(RefCell::new(ListState::<PulseStream>::default()));