feat(M4.1): establish the Pulse protocol boundary

Pin feature-gated libpulse bindings, document native prerequisites and MSRV/license checks, and add a no-autospawn client for sink-input enumeration, normalized metadata, linear multichannel conversion, volume/mute writes, and confirmed readback. Leave M4.1 open pending isolated-daemon subscription verification.

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:39:36 +02:00
parent 4f3eb4f279
commit 90ba84a802
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
8 changed files with 426 additions and 8 deletions

46
Cargo.lock generated
View File

@ -326,6 +326,33 @@ version = "0.2.190"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
[[package]]
name = "libpulse-binding"
version = "2.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "909eb3049e16e373680fe65afe6e2a722ace06b671250cc4849557bc57d6a397"
dependencies = [
"bitflags",
"libc",
"libpulse-sys",
"num-derive",
"num-traits",
"winapi",
]
[[package]]
name = "libpulse-sys"
version = "1.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d74371848b22e989f829cc1621d2ebd74960711557d8b45cfe740f60d0a05e61"
dependencies = [
"libc",
"num-derive",
"num-traits",
"pkg-config",
"winapi",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@ -393,6 +420,17 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@ -446,6 +484,12 @@ version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
[[package]]
name = "pkg-config"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
[[package]]
name = "powerfmt"
version = "0.2.0"
@ -952,6 +996,8 @@ name = "volume_lib"
version = "0.1.0"
dependencies = [
"fader-core",
"libpulse-binding",
"thiserror",
]
[[package]]

View File

@ -14,6 +14,7 @@ publish = false
fader-config = { path = "config" }
fader-core = { path = "core" }
midi = { path = "midi" }
libpulse-binding = "2.30.1"
proptest = "1.11.0"
ratatui = { version = "0.29.0", features = ["all-widgets", "serde"] }
regex = "1.13.1"

View File

@ -63,6 +63,13 @@ LLVM-exception OR Apache-2.0 OR MIT) for safe effective-user checks and
same-directory temporary files. Neither adds a native system-library
prerequisite, and both compile on the pinned toolchain.
M4 begins with `libpulse-binding 2.30.1` and `libpulse-sys 1.23.0`. Both
declare Rust 1.63 and MIT OR Apache-2.0, compile on the pinned Rust 1.88.0,
and require libpulse development files through pkg-config. The default
compatibility feature targets PulseAudio 8 or newer. The adapter uses the
asynchronous protocol API on an owned mainloop, deep-copies callback data, and
converts software volumes through `VolumeLinear`; it does not parse `pactl`.
## Purpose and scope
Run a per-user Linux server that receives controls from multiple USB MIDI surfaces, records requested state, resolves virtual application/group targets, and dispatches volume/mute commands through one selected audio adapter. Observe external audio changes and send confirmed state to every relevant TUI and MIDI output.

View File

@ -5,12 +5,11 @@ minimum supported Rust version (MSRV) and the repository-pinned development
toolchain. `rustup` reads `rust-toolchain.toml` and installs the required
`rustfmt`, Clippy, and LLVM tools components.
The current scaffold needs a C compiler and linker for transitive Rust system
crates, but it does not yet link to an audio daemon or MIDI library. On a
Debian-family Linux system, the foundation prerequisites are:
The default build includes the PulseAudio protocol adapter and links to
libpulse. On a Debian-family Linux system, install:
```sh
sudo apt-get install build-essential pkg-config
sudo apt-get install build-essential pkg-config libpulse-dev
rustup toolchain install 1.88.0 \
--profile minimal \
--component rustfmt \
@ -18,10 +17,16 @@ rustup toolchain install 1.88.0 \
--component llvm-tools-preview
```
Future PulseAudio, PipeWire, ALSA, MIDI, and udev adapters will add native
development packages. Their exact package names and feature-specific build
commands must be documented when those adapters are introduced; the scaffold
does not claim those dependencies yet.
The Pulse adapter works with PulseAudio and PipeWire's pipewire-pulse
compatibility service. A build that deliberately excludes native audio
dependencies remains available:
```sh
cargo build --workspace --no-default-features --locked
```
Future native PipeWire, ALSA, MIDI, and udev adapters will add their own
feature-gated development packages.
From a fresh checkout, use the tracked lockfile for reproducible resolution:

View File

@ -7,5 +7,11 @@ license-file.workspace = true
repository.workspace = true
publish.workspace = true
[features]
default = ["pulse"]
pulse = ["dep:libpulse-binding"]
[dependencies]
fader-core.workspace = true
libpulse-binding = { workspace = true, optional = true }
thiserror.workspace = true

View File

@ -2,6 +2,12 @@
#![forbid(unsafe_code)]
#[cfg(feature = "pulse")]
mod pulse;
#[cfg(feature = "pulse")]
pub use pulse::{PulseClient, PulseError, PulseStream};
use std::{
collections::{BTreeMap, VecDeque},
sync::mpsc::{self, Receiver, SyncSender, TrySendError},

342
sound/src/pulse.rs Normal file
View File

@ -0,0 +1,342 @@
use std::{
cell::RefCell,
rc::Rc,
thread,
time::{Duration, Instant},
};
use fader_core::{ChannelGains, Gain, Mute, StreamMetadata};
use libpulse_binding as pulse;
use pulse::{
callbacks::ListResult,
context::{Context, FlagSet, State},
mainloop::standard::{IterateResult, Mainloop},
proplist::properties,
volume::{ChannelVolumes, Volume, VolumeLinear},
};
use thiserror::Error;
const OPERATION_TIMEOUT: Duration = Duration::from_secs(3);
/// Copied PulseAudio playback-stream information.
#[derive(Clone, Debug, PartialEq)]
pub struct PulseStream {
pub index: u32,
pub metadata: StreamMetadata,
pub channels: ChannelGains,
pub muted: Mute,
pub volume_writable: bool,
}
/// Failures at the Pulse protocol boundary.
#[derive(Debug, Error)]
pub enum PulseError {
#[error("could not create the PulseAudio mainloop")]
MainloopCreation,
#[error("could not create a PulseAudio context")]
ContextCreation,
#[error("PulseAudio connection failed: {0}")]
Connect(String),
#[error("PulseAudio context entered state {0:?}")]
ContextState(State),
#[error("PulseAudio operation timed out")]
Timeout,
#[error("PulseAudio mainloop failed: {0}")]
Mainloop(String),
#[error("PulseAudio introspection failed")]
Introspection,
#[error("sink input {0} is unavailable")]
MissingStream(u32),
#[error("sink input {0} does not expose writable volume")]
ReadOnlyStream(u32),
#[error("PulseAudio rejected the operation")]
Rejected,
#[error("invalid PulseAudio channel volume: {0}")]
Volume(String),
}
/// Blocking facade over one asynchronous Pulse context.
///
/// The value owns both context and mainloop and must remain on its owner thread.
pub struct PulseClient {
mainloop: Mainloop,
context: Context,
}
impl PulseClient {
/// Connects to the default PulseAudio-compatible server without autospawning one.
pub fn connect() -> Result<Self, PulseError> {
Self::connect_to(None)
}
/// Connects to an explicit server for isolated fixtures and diagnostics.
pub fn connect_to(server: Option<&str>) -> Result<Self, PulseError> {
let mainloop = Mainloop::new().ok_or(PulseError::MainloopCreation)?;
let mut context =
Context::new(&mainloop, "fader_master").ok_or(PulseError::ContextCreation)?;
context
.connect(server, FlagSet::NOAUTOSPAWN, None)
.map_err(|error| PulseError::Connect(format!("{error:?}")))?;
let mut client = Self { mainloop, context };
client.wait_until_ready()?;
Ok(client)
}
/// 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()));
let callback = Rc::clone(&result);
self.context
.introspect()
.get_sink_input_info_list(move |item| match item {
ListResult::Item(info) => match copy_stream(info) {
Ok(stream) => callback.borrow_mut().items.push(stream),
Err(error) => callback.borrow_mut().error = Some(error),
},
ListResult::End => callback.borrow_mut().done = true,
ListResult::Error => {
let mut callback = callback.borrow_mut();
callback.error = Some(PulseError::Introspection);
callback.done = true;
}
});
self.wait_for(|| result.borrow().done)?;
let mut result = result.borrow_mut();
if let Some(error) = result.error.take() {
return Err(error);
}
Ok(std::mem::take(&mut result.items))
}
/// Reads one sink input after a write or subscription notification.
pub fn stream(&mut self, index: u32) -> Result<PulseStream, PulseError> {
let result = Rc::new(RefCell::new(ListState::<PulseStream>::default()));
let callback = Rc::clone(&result);
self.context
.introspect()
.get_sink_input_info(index, move |item| match item {
ListResult::Item(info) => match copy_stream(info) {
Ok(stream) => callback.borrow_mut().items.push(stream),
Err(error) => callback.borrow_mut().error = Some(error),
},
ListResult::End => callback.borrow_mut().done = true,
ListResult::Error => {
let mut callback = callback.borrow_mut();
callback.error = Some(PulseError::MissingStream(index));
callback.done = true;
}
});
self.wait_for(|| result.borrow().done)?;
let mut result = result.borrow_mut();
if let Some(error) = result.error.take() {
return Err(error);
}
result.items.pop().ok_or(PulseError::MissingStream(index))
}
/// Writes per-channel linear software gain, then reads the confirmed state.
pub fn set_volume(
&mut self,
index: u32,
channels: &ChannelGains,
) -> Result<PulseStream, PulseError> {
let native = to_native_channels(channels)?;
let result = Rc::new(RefCell::new(None));
let callback = Rc::clone(&result);
self.context.introspect().set_sink_input_volume(
index,
&native,
Some(Box::new(move |success| {
*callback.borrow_mut() = Some(success)
})),
);
self.wait_for(|| result.borrow().is_some())?;
if result.borrow().is_none_or(|success| !success) {
return Err(PulseError::Rejected);
}
self.stream(index)
}
/// Writes mute independently of gain, then reads the confirmed state.
pub fn set_mute(&mut self, index: u32, muted: Mute) -> Result<PulseStream, PulseError> {
let result = Rc::new(RefCell::new(None));
let callback = Rc::clone(&result);
self.context.introspect().set_sink_input_mute(
index,
muted == Mute::Muted,
Some(Box::new(move |success| {
*callback.borrow_mut() = Some(success)
})),
);
self.wait_for(|| result.borrow().is_some())?;
if result.borrow().is_none_or(|success| !success) {
return Err(PulseError::Rejected);
}
self.stream(index)
}
fn wait_until_ready(&mut self) -> Result<(), PulseError> {
let deadline = Instant::now() + OPERATION_TIMEOUT;
loop {
match self.context.get_state() {
State::Ready => return Ok(()),
State::Failed | State::Terminated => {
return Err(PulseError::ContextState(self.context.get_state()));
}
_ => self.iterate(deadline)?,
}
}
}
fn wait_for(&mut self, complete: impl Fn() -> bool) -> Result<(), PulseError> {
let deadline = Instant::now() + OPERATION_TIMEOUT;
while !complete() {
match self.context.get_state() {
State::Failed | State::Terminated => {
return Err(PulseError::ContextState(self.context.get_state()));
}
_ => self.iterate(deadline)?,
}
}
Ok(())
}
fn iterate(&mut self, deadline: Instant) -> Result<(), PulseError> {
if Instant::now() >= deadline {
return Err(PulseError::Timeout);
}
match self.mainloop.iterate(false) {
IterateResult::Success(_) => {
thread::sleep(Duration::from_millis(2));
Ok(())
}
IterateResult::Quit(value) => Err(PulseError::Mainloop(format!("quit with {value:?}"))),
IterateResult::Err(error) => Err(PulseError::Mainloop(format!("{error:?}"))),
}
}
}
impl Drop for PulseClient {
fn drop(&mut self) {
self.context.disconnect();
}
}
struct ListState<T> {
items: Vec<T>,
done: bool,
error: Option<PulseError>,
}
impl<T> Default for ListState<T> {
fn default() -> Self {
Self {
items: Vec::new(),
done: false,
error: None,
}
}
}
fn copy_stream(
info: &pulse::context::introspect::SinkInputInfo<'_>,
) -> Result<PulseStream, PulseError> {
let metadata = [
(
properties::APPLICATION_NAME,
info.proplist.get_str(properties::APPLICATION_NAME),
),
(
properties::APPLICATION_ID,
info.proplist.get_str(properties::APPLICATION_ID),
),
(
properties::APPLICATION_PROCESS_BINARY,
info.proplist
.get_str(properties::APPLICATION_PROCESS_BINARY),
),
(
properties::MEDIA_NAME,
info.proplist.get_str(properties::MEDIA_NAME),
),
]
.into_iter()
.fold(StreamMetadata::new(), |metadata, (key, value)| {
let Some(value) = value else {
return metadata;
};
match key {
properties::APPLICATION_NAME => metadata.with_application_name(value),
properties::APPLICATION_ID => metadata.with_application_id(value),
properties::APPLICATION_PROCESS_BINARY => metadata.with_process_binary(value),
properties::MEDIA_NAME => metadata.with_media_name(value),
_ => metadata,
}
});
let gains = info
.volume
.get()
.iter()
.copied()
.map(|volume| Gain::new(VolumeLinear::from(volume).0))
.collect::<Result<Vec<_>, _>>()
.map_err(|error| PulseError::Volume(error.to_string()))?;
let channels =
ChannelGains::new(gains).map_err(|error| PulseError::Volume(error.to_string()))?;
Ok(PulseStream {
index: info.index,
metadata,
channels,
muted: if info.mute {
Mute::Muted
} else {
Mute::Unmuted
},
volume_writable: info.has_volume && info.volume_writable,
})
}
fn to_native_channels(channels: &ChannelGains) -> Result<ChannelVolumes, PulseError> {
let count = u8::try_from(channels.as_slice().len())
.map_err(|error| PulseError::Volume(error.to_string()))?;
if count > ChannelVolumes::CHANNELS_MAX {
return Err(PulseError::Volume(format!(
"{count} channels exceeds PulseAudio maximum {}",
ChannelVolumes::CHANNELS_MAX
)));
}
let mut native = ChannelVolumes::default();
native.set_len(count);
for (native, gain) in native.get_mut().iter_mut().zip(channels.as_slice()) {
*native = Volume::from(VolumeLinear(gain.get()));
}
Ok(native)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn linear_conversion_preserves_balance_and_endpoints() {
let channels =
ChannelGains::new(vec![Gain::SILENCE, Gain::new(0.25).unwrap(), Gain::UNITY]).unwrap();
let native = to_native_channels(&channels).unwrap();
let round_trip = native
.get()
.iter()
.map(|volume| VolumeLinear::from(*volume).0)
.collect::<Vec<_>>();
assert_eq!(round_trip[0], 0.0);
assert!((round_trip[1] - 0.25).abs() < 0.000_1);
assert_eq!(round_trip[2], 1.0);
}
#[test]
fn unavailable_daemon_is_a_normal_connection_error() {
let result =
PulseClient::connect_to(Some("unix:/tmp/fader-master-test/nonexistent-pulse-socket"));
assert!(result.is_err());
}
}

View File

@ -97,6 +97,11 @@ volume intent converging through fake write acceptance and readback.
Dependencies: M3.
- [ ] **M4.1 Bounded API spike:** verify libpulse-binding event loop, sink-input enumeration/properties, native volume conversion, change subscriptions and readback on PulseAudio and pipewire-pulse. Record native prerequisites and visibility limitations. Acceptance: isolated test streams are discovered and volume/mute changes are observed in both directions; no shell parsing in the production path.
The pinned binding now compiles against libpulse 17 on Rust 1.88, with
feature-gated no-backend builds. A no-autospawn client implements sink-input
enumeration, normalized metadata copies, linear multichannel conversion,
volume/mute writes, and mandatory readback. Keep this item open until the
isolated daemon fixture verifies subscriptions and both server variants.
- [ ] **M4.2 Implement worker:** own native handles on their loop thread; copy callback data; reconcile enumeration races. Contract tests: add/remove/change, operation error, unavailable daemon, reconnect, balanced stereo and multichannel conversion, external mixer edit.
- [ ] **M4.3 Adapter policy:** configured/CLI override, auto probe order/capabilities, diagnostics and feature errors. Tests: manual failure never falls back; auto chooses one authority, skips incapable candidates and never substitutes ALSA Master for applications; disconnect follows retry policy.
- [ ] **M4.4 Real-daemon fixture:** isolated playback streams and external control client. Acceptance: server command and external change both converge to the observed value/mute; stream churn and daemon restart recover. Document commands and opt-in fixture requirements; do not label mocks as hardware verification.