feat(M4.2): own Pulse sessions in a worker
Rust CI fader_master failed CI.
MadGobblins/fader_master/pipeline/head There was a failure building this commit Details

Keep libpulse handles on a dedicated owner thread, bound command and event lanes, frame subscribe-before-enumerate snapshots, copy metadata and observations, and protect reused sink-input IDs with per-epoch incarnations. Add hardware-free contract coverage and a real-session worker-watch checklist.

Tests: cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features --locked; cargo test --workspace --all-targets --all-features --locked; cargo test --workspace --doc --all-features --locked; cargo clippy --workspace --all-targets --all-features --locked -- -D warnings; cargo build --workspace --release --all-features --locked; cargo check --workspace --all-targets --no-default-features --locked; cargo test --workspace --all-targets --no-default-features --locked; cargo run --locked -p volume_lib --example pulse_fixture -- worker-watch 1 (PipeWire 1.6.9)
This commit is contained in:
Dandaedre 2026-10-14 21:46:39 +02:00
parent efc1981c03
commit 35a50e06e4
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
6 changed files with 842 additions and 10 deletions

View File

@ -67,6 +67,24 @@ Replace `INDEX` below with the selected sink-input index.
- [ ] Report the `Server Name` shown by `pactl info` and any unchecked or failed
item, including the fixture's exact error text.
## Owned Pulse worker milestone
These checks exercise the new bounded worker path rather than the direct client
used by the earlier commands.
- [ ] Start playback, then run
`cargo run --locked -p volume_lib --example pulse_fixture -- worker-watch 30`.
- [ ] Confirm the output starts with `Ready`, contains one `SnapshotBegin` and
one `SnapshotEnd`, and reports the playing stream through copied
`StreamMetadata` and `Observed` events.
- [ ] During the watch, change volume and mute in your desktop mixer and confirm
new `Observed` events contain the updated channel values and mute state.
- [ ] Stop and restart playback during another watch. Confirm `StreamRemoved` is
followed by a newly observed handle; if PipeWire reuses the numeric backend
ID, its `incarnation` must differ.
- [ ] Confirm the command exits normally without `Disconnected`, event-lane
overflow, or an owner-thread panic.
The main TUI is still explicitly backed by demo state at this milestone. Passing
this checklist validates the real Pulse control boundary that will feed the
server and live multi-application/group TUI; it does not yet validate MIDI or

View File

@ -1,11 +1,15 @@
use std::{error::Error, io, time::Duration};
use std::{error::Error, io, sync::mpsc::RecvTimeoutError, time::Duration};
use fader_core::{Gain, MetadataField, Mute};
use volume_lib::{PulseClient, PulseNotification, PulseStream};
use fader_core::{BackendEpoch, Gain, MetadataField, Mute};
use volume_lib::{PulseClient, PulseNotification, PulseStream, PulseWorker, WorkerEvent};
fn main() -> Result<(), Box<dyn Error>> {
let mut arguments = std::env::args().skip(1);
let command = arguments.next().unwrap_or_else(|| "list".to_owned());
if command == "worker-watch" {
let seconds = arguments.next().as_deref().unwrap_or("15").parse::<u64>()?;
return worker_watch(Duration::from_secs(seconds));
}
let mut client = PulseClient::connect()?;
match command.as_str() {
@ -35,13 +39,39 @@ fn main() -> Result<(), Box<dyn Error>> {
}
_ => {
return Err(invalid_input(
"usage: pulse_fixture [list|watch [SECONDS]|volume INDEX GAIN|mute INDEX on|off]",
"usage: pulse_fixture [list|watch [SECONDS]|worker-watch [SECONDS]|volume INDEX GAIN|mute INDEX on|off]",
));
}
}
Ok(())
}
fn worker_watch(duration: Duration) -> Result<(), Box<dyn Error>> {
let mut worker = PulseWorker::spawn(BackendEpoch::new(1), 256);
let deadline = std::time::Instant::now() + duration;
while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) {
match worker.receive_timeout(remaining.min(Duration::from_millis(250))) {
Ok(event) => {
let disconnected = matches!(event, WorkerEvent::Disconnected { .. });
println!("{event:?}");
if disconnected {
return Err(invalid_input("Pulse worker disconnected"));
}
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => break,
}
}
let stopped = worker.shutdown();
if worker.event_overflowed() {
return Err(invalid_input("Pulse worker event lane overflowed"));
}
if !stopped {
return Err(invalid_input("Pulse worker owner thread panicked"));
}
Ok(())
}
fn list(client: &mut PulseClient) -> Result<(), Box<dyn Error>> {
for stream in client.streams()? {
print_stream(&stream);
@ -55,7 +85,9 @@ fn watch(client: &mut PulseClient, duration: Duration) -> Result<(), Box<dyn Err
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::Added(stream) | PulseNotification::Changed(stream)) => {
print_stream(&stream);
}
Some(PulseNotification::Removed(index)) => println!("removed index={index}"),
None => {}
}

View File

@ -4,9 +4,13 @@
#[cfg(feature = "pulse")]
mod pulse;
#[cfg(feature = "pulse")]
mod pulse_worker;
#[cfg(feature = "pulse")]
pub use pulse::{PulseClient, PulseError, PulseNotification, PulseStream};
#[cfg(feature = "pulse")]
pub use pulse_worker::PulseWorker;
use std::{
collections::{BTreeMap, VecDeque},
@ -27,9 +31,22 @@ pub struct AdapterCapabilities {
/// Snapshot framing and copied adapter events.
#[derive(Clone, Debug, PartialEq)]
pub enum WorkerEvent {
Ready {
epoch: BackendEpoch,
capabilities: AdapterCapabilities,
},
SnapshotBegin(BackendEpoch),
StreamMetadata {
stream: StreamHandle,
metadata: fader_core::StreamMetadata,
volume_writable: bool,
},
Adapter(AdapterEvent),
SnapshotEnd(BackendEpoch),
Disconnected {
epoch: BackendEpoch,
message: String,
},
}
#[derive(Clone, Debug)]

View File

@ -33,7 +33,8 @@ pub struct PulseStream {
/// One subscribed playback-stream change.
#[derive(Clone, Debug, PartialEq)]
pub enum PulseNotification {
Upsert(PulseStream),
Added(PulseStream),
Changed(PulseStream),
Removed(u32),
}
@ -142,9 +143,16 @@ impl PulseClient {
};
match operation {
Operation::Removed => Ok(Some(PulseNotification::Removed(index))),
Operation::New | Operation::Changed => {
self.stream(index).map(PulseNotification::Upsert).map(Some)
}
Operation::New => match self.stream(index) {
Ok(stream) => Ok(Some(PulseNotification::Added(stream))),
Err(PulseError::MissingStream(_)) => Ok(Some(PulseNotification::Removed(index))),
Err(error) => Err(error),
},
Operation::Changed => match self.stream(index) {
Ok(stream) => Ok(Some(PulseNotification::Changed(stream))),
Err(PulseError::MissingStream(_)) => Ok(Some(PulseNotification::Removed(index))),
Err(error) => Err(error),
},
}
}

742
sound/src/pulse_worker.rs Normal file
View File

@ -0,0 +1,742 @@
use std::{
collections::BTreeMap,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TryRecvError, TrySendError},
},
thread::{self, JoinHandle},
time::Duration,
};
use fader_core::{AdapterCommand, AdapterEvent, BackendEpoch, OperationId, StreamHandle};
use crate::{
AdapterCapabilities, PulseClient, PulseError, PulseNotification, PulseStream, WorkerEvent,
};
const NOTIFICATION_POLL: Duration = Duration::from_millis(10);
trait PulseConnection {
fn subscribe(&mut self) -> Result<(), PulseError>;
fn streams(&mut self) -> Result<Vec<PulseStream>, PulseError>;
fn stream(&mut self, index: u32) -> Result<PulseStream, PulseError>;
fn poll_notification(
&mut self,
timeout: Duration,
) -> Result<Option<PulseNotification>, PulseError>;
fn set_volume(
&mut self,
index: u32,
channels: &fader_core::ChannelGains,
) -> Result<PulseStream, PulseError>;
fn set_mute(&mut self, index: u32, muted: fader_core::Mute) -> Result<PulseStream, PulseError>;
}
impl PulseConnection for PulseClient {
fn subscribe(&mut self) -> Result<(), PulseError> {
Self::subscribe(self)
}
fn streams(&mut self) -> Result<Vec<PulseStream>, PulseError> {
Self::streams(self)
}
fn stream(&mut self, index: u32) -> Result<PulseStream, PulseError> {
Self::stream(self, index)
}
fn poll_notification(
&mut self,
timeout: Duration,
) -> Result<Option<PulseNotification>, PulseError> {
Self::poll_notification(self, timeout)
}
fn set_volume(
&mut self,
index: u32,
channels: &fader_core::ChannelGains,
) -> Result<PulseStream, PulseError> {
Self::set_volume(self, index, channels)
}
fn set_mute(&mut self, index: u32, muted: fader_core::Mute) -> Result<PulseStream, PulseError> {
Self::set_mute(self, index, muted)
}
}
struct EventLane {
sender: SyncSender<WorkerEvent>,
overflowed: Arc<AtomicBool>,
}
impl EventLane {
fn emit(&self, event: WorkerEvent) -> bool {
match self.sender.try_send(event) {
Ok(()) => true,
Err(TrySendError::Full(_)) => {
self.overflowed.store(true, Ordering::Release);
false
}
Err(TrySendError::Disconnected(_)) => false,
}
}
}
#[derive(Debug)]
struct StreamTracker {
epoch: BackendEpoch,
next_incarnation: u64,
handles: BTreeMap<u32, StreamHandle>,
}
impl StreamTracker {
fn new(epoch: BackendEpoch) -> Self {
Self {
epoch,
next_incarnation: 1,
handles: BTreeMap::new(),
}
}
fn current_or_insert(&mut self, index: u32) -> Result<StreamHandle, &'static str> {
if let Some(handle) = self.handles.get(&index) {
return Ok(*handle);
}
self.insert(index)
}
fn insert(&mut self, index: u32) -> Result<StreamHandle, &'static str> {
let incarnation = self.next_incarnation;
self.next_incarnation = self
.next_incarnation
.checked_add(1)
.ok_or("Pulse stream incarnation counter exhausted")?;
let handle = StreamHandle::new(self.epoch, u64::from(index), incarnation);
self.handles.insert(index, handle);
Ok(handle)
}
fn remove(&mut self, index: u32) -> Option<StreamHandle> {
self.handles.remove(&index)
}
fn resolve(&self, handle: StreamHandle) -> Option<u32> {
let index = u32::try_from(handle.backend_id()).ok()?;
self.handles
.get(&index)
.filter(|current| **current == handle)
.map(|_| index)
}
}
/// Pulse adapter whose native context and mainloop remain on one owner thread.
#[derive(Debug)]
pub struct PulseWorker {
commands: Option<SyncSender<AdapterCommand>>,
events: Receiver<WorkerEvent>,
overflowed: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
impl PulseWorker {
/// Starts a worker against the default PulseAudio-compatible server.
#[must_use]
pub fn spawn(epoch: BackendEpoch, capacity: usize) -> Self {
Self::spawn_to(epoch, capacity, None)
}
/// Starts a worker against an explicit server, primarily for isolated fixtures.
#[must_use]
pub fn spawn_to(epoch: BackendEpoch, capacity: usize, server: Option<String>) -> Self {
Self::spawn_with(epoch, capacity, move || {
PulseClient::connect_to(server.as_deref())
})
}
fn spawn_with<C, F>(epoch: BackendEpoch, capacity: usize, connect: F) -> Self
where
C: PulseConnection,
F: FnOnce() -> Result<C, PulseError> + Send + 'static,
{
let capacity = capacity.max(1);
let (command_sender, command_receiver) = mpsc::sync_channel(capacity);
let (event_sender, event_receiver) = mpsc::sync_channel(capacity);
let overflowed = Arc::new(AtomicBool::new(false));
let worker_overflowed = Arc::clone(&overflowed);
let thread = thread::spawn(move || {
let events = EventLane {
sender: event_sender,
overflowed: worker_overflowed,
};
let mut connection = match connect() {
Ok(connection) => connection,
Err(error) => {
events.emit(WorkerEvent::Disconnected {
epoch,
message: error.to_string(),
});
return;
}
};
if let Err(error) = run_connection(&mut connection, epoch, &command_receiver, &events) {
events.emit(WorkerEvent::Disconnected {
epoch,
message: error.to_string(),
});
}
});
Self {
commands: Some(command_sender),
events: event_receiver,
overflowed,
thread: Some(thread),
}
}
/// Attempts to enqueue one ordered adapter command without blocking the caller.
pub fn try_submit(&self, command: AdapterCommand) -> Result<(), AdapterCommand> {
let Some(sender) = &self.commands else {
return Err(command);
};
match sender.try_send(command) {
Ok(()) => Ok(()),
Err(TrySendError::Full(command) | TrySendError::Disconnected(command)) => Err(command),
}
}
/// Receives one copied worker event, bounded by `timeout`.
pub fn receive_timeout(&self, timeout: Duration) -> Result<WorkerEvent, RecvTimeoutError> {
self.events.recv_timeout(timeout)
}
/// Reports that the bounded event lane overflowed and the worker stopped for resync.
#[must_use]
pub fn event_overflowed(&self) -> bool {
self.overflowed.load(Ordering::Acquire)
}
/// Stops accepting commands and joins the native owner thread.
pub fn shutdown(&mut self) -> bool {
self.commands.take();
self.thread
.take()
.is_none_or(|thread| thread.join().is_ok())
}
}
impl Drop for PulseWorker {
fn drop(&mut self) {
let _ = self.shutdown();
}
}
fn run_connection<C: PulseConnection>(
connection: &mut C,
epoch: BackendEpoch,
commands: &Receiver<AdapterCommand>,
events: &EventLane,
) -> Result<(), PulseError> {
connection.subscribe()?;
if !events.emit(WorkerEvent::Ready {
epoch,
capabilities: AdapterCapabilities {
volume: true,
mute: true,
subscriptions: true,
},
}) || !events.emit(WorkerEvent::SnapshotBegin(epoch))
{
return Ok(());
}
let mut tracker = StreamTracker::new(epoch);
for stream in connection.streams()? {
let handle = tracker
.current_or_insert(stream.index)
.map_err(|message| PulseError::Volume(message.to_owned()))?;
if !emit_stream(events, handle, stream, None) {
return Ok(());
}
}
while let Some(notification) = connection.poll_notification(Duration::ZERO)? {
if !process_notification(notification, &mut tracker, events)? {
return Ok(());
}
}
if !events.emit(WorkerEvent::SnapshotEnd(epoch)) {
return Ok(());
}
loop {
match commands.try_recv() {
Ok(command) => {
if !process_command(command, connection, &mut tracker, events) {
return Ok(());
}
}
Err(TryRecvError::Disconnected) => return Ok(()),
Err(TryRecvError::Empty) => {}
}
if let Some(notification) = connection.poll_notification(NOTIFICATION_POLL)?
&& !process_notification(notification, &mut tracker, events)?
{
return Ok(());
}
}
}
fn process_notification(
notification: PulseNotification,
tracker: &mut StreamTracker,
events: &EventLane,
) -> Result<bool, PulseError> {
match notification {
PulseNotification::Added(stream) => {
// A stream created between subscribe and enumeration is present in
// both the snapshot and the queued New notification. Preserve its
// incarnation; a real index reuse is preceded by Removed.
let handle = tracker
.current_or_insert(stream.index)
.map_err(|message| PulseError::Volume(message.to_owned()))?;
Ok(emit_stream(events, handle, stream, None))
}
PulseNotification::Changed(stream) => {
let handle = tracker
.current_or_insert(stream.index)
.map_err(|message| PulseError::Volume(message.to_owned()))?;
Ok(emit_stream(events, handle, stream, None))
}
PulseNotification::Removed(index) => {
let Some(stream) = tracker.remove(index) else {
return Ok(true);
};
Ok(events.emit(WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream })))
}
}
}
fn process_command<C: PulseConnection>(
command: AdapterCommand,
connection: &mut C,
tracker: &mut StreamTracker,
events: &EventLane,
) -> bool {
let (operation, handle) = match &command {
AdapterCommand::SetVolume {
operation, stream, ..
}
| AdapterCommand::SetMute {
operation, stream, ..
}
| AdapterCommand::Readback { operation, stream } => (*operation, *stream),
};
let Some(index) = tracker.resolve(handle) else {
return emit_failure(events, operation, "stream handle is stale or unavailable");
};
let is_readback = matches!(command, AdapterCommand::Readback { .. });
let result = match command {
AdapterCommand::SetVolume { channels, .. } => connection.set_volume(index, &channels),
AdapterCommand::SetMute { muted, .. } => connection.set_mute(index, muted),
AdapterCommand::Readback { .. } => connection.stream(index),
};
match result {
Ok(stream) => {
if !is_readback
&& !events.emit(WorkerEvent::Adapter(AdapterEvent::WriteAccepted {
operation,
}))
{
return false;
}
emit_stream(events, handle, stream, Some(operation))
}
Err(error) => emit_failure(events, operation, error.to_string()),
}
}
fn emit_failure(events: &EventLane, operation: OperationId, message: impl Into<String>) -> bool {
events.emit(WorkerEvent::Adapter(AdapterEvent::WriteFailed {
operation,
message: message.into(),
}))
}
fn emit_stream(
events: &EventLane,
handle: StreamHandle,
stream: PulseStream,
operation: Option<OperationId>,
) -> bool {
events.emit(WorkerEvent::StreamMetadata {
stream: handle,
metadata: stream.metadata,
volume_writable: stream.volume_writable,
}) && events.emit(WorkerEvent::Adapter(AdapterEvent::Observed {
stream: handle,
channels: stream.channels,
muted: stream.muted,
operation,
}))
}
#[cfg(test)]
mod tests {
use std::{
collections::VecDeque,
sync::{Mutex, atomic::AtomicBool},
thread::ThreadId,
};
use fader_core::{ChannelGains, Gain, MetadataField, Mute, StreamMetadata};
use super::*;
#[derive(Clone)]
struct FakeControl {
notifications: Arc<Mutex<VecDeque<PulseNotification>>>,
streams: Arc<Mutex<BTreeMap<u32, PulseStream>>>,
reject_writes: Arc<AtomicBool>,
}
impl FakeControl {
fn notify(&self, notification: PulseNotification) {
match &notification {
PulseNotification::Added(stream) | PulseNotification::Changed(stream) => {
self.streams
.lock()
.expect("fake stream lock")
.insert(stream.index, stream.clone());
}
PulseNotification::Removed(index) => {
self.streams.lock().expect("fake stream lock").remove(index);
}
}
self.notifications
.lock()
.expect("fake notification lock")
.push_back(notification);
}
}
struct FakeConnection {
initial: Vec<PulseStream>,
control: FakeControl,
owner_thread: Arc<Mutex<Option<ThreadId>>>,
}
impl FakeConnection {
fn new(initial: Vec<PulseStream>) -> (Self, FakeControl, Arc<Mutex<Option<ThreadId>>>) {
let streams = initial
.iter()
.cloned()
.map(|stream| (stream.index, stream))
.collect();
let control = FakeControl {
notifications: Arc::new(Mutex::new(VecDeque::new())),
streams: Arc::new(Mutex::new(streams)),
reject_writes: Arc::new(AtomicBool::new(false)),
};
let owner_thread = Arc::new(Mutex::new(None));
(
Self {
initial,
control: control.clone(),
owner_thread: Arc::clone(&owner_thread),
},
control,
owner_thread,
)
}
fn checked_stream(&self, index: u32) -> Result<PulseStream, PulseError> {
self.control
.streams
.lock()
.expect("fake stream lock")
.get(&index)
.cloned()
.ok_or(PulseError::MissingStream(index))
}
}
impl PulseConnection for FakeConnection {
fn subscribe(&mut self) -> Result<(), PulseError> {
*self.owner_thread.lock().expect("owner thread lock") = Some(thread::current().id());
Ok(())
}
fn streams(&mut self) -> Result<Vec<PulseStream>, PulseError> {
Ok(self.initial.clone())
}
fn stream(&mut self, index: u32) -> Result<PulseStream, PulseError> {
self.checked_stream(index)
}
fn poll_notification(
&mut self,
_timeout: Duration,
) -> Result<Option<PulseNotification>, PulseError> {
Ok(self
.control
.notifications
.lock()
.expect("fake notification lock")
.pop_front())
}
fn set_volume(
&mut self,
index: u32,
channels: &ChannelGains,
) -> Result<PulseStream, PulseError> {
if self.control.reject_writes.load(Ordering::Acquire) {
return Err(PulseError::Rejected);
}
let mut streams = self.control.streams.lock().expect("fake stream lock");
let stream = streams
.get_mut(&index)
.ok_or(PulseError::MissingStream(index))?;
stream.channels = channels.clone();
Ok(stream.clone())
}
fn set_mute(&mut self, index: u32, muted: Mute) -> Result<PulseStream, PulseError> {
if self.control.reject_writes.load(Ordering::Acquire) {
return Err(PulseError::Rejected);
}
let mut streams = self.control.streams.lock().expect("fake stream lock");
let stream = streams
.get_mut(&index)
.ok_or(PulseError::MissingStream(index))?;
stream.muted = muted;
Ok(stream.clone())
}
}
fn channels(values: &[f64]) -> ChannelGains {
ChannelGains::new(
values
.iter()
.map(|value| Gain::new(*value).expect("valid test gain"))
.collect(),
)
.expect("nonempty test channels")
}
fn stream(index: u32, values: &[f64], muted: Mute) -> PulseStream {
PulseStream {
index,
metadata: StreamMetadata::new()
.with_application_name(format!("application-{index}"))
.with_process_binary("fixture"),
channels: channels(values),
muted,
volume_writable: true,
}
}
fn receive(worker: &PulseWorker) -> WorkerEvent {
worker
.receive_timeout(Duration::from_secs(1))
.expect("worker event")
}
fn initial_snapshot(worker: &PulseWorker) -> Vec<WorkerEvent> {
let mut events = Vec::new();
loop {
let event = receive(worker);
let complete = matches!(event, WorkerEvent::SnapshotEnd(_));
events.push(event);
if complete {
return events;
}
}
}
fn observed(events: &[WorkerEvent]) -> Vec<(StreamHandle, ChannelGains, Mute)> {
events
.iter()
.filter_map(|event| match event {
WorkerEvent::Adapter(AdapterEvent::Observed {
stream,
channels,
muted,
..
}) => Some((*stream, channels.clone(), *muted)),
_ => None,
})
.collect()
}
#[test]
fn owner_thread_copies_snapshot_and_reconciles_a_queued_add() {
let caller = thread::current().id();
let original = stream(7, &[0.2, 0.4], Mute::Unmuted);
let changed = stream(7, &[0.3, 0.6], Mute::Muted);
let (connection, control, owner) = FakeConnection::new(vec![original]);
control.notify(PulseNotification::Added(changed));
let mut worker = PulseWorker::spawn_with(BackendEpoch::new(4), 32, move || Ok(connection));
let events = initial_snapshot(&worker);
let observations = observed(&events);
assert_eq!(observations.len(), 2);
assert_eq!(observations[0].0, observations[1].0);
assert_eq!(observations[0].1, channels(&[0.2, 0.4]));
assert_eq!(observations[1].1, channels(&[0.3, 0.6]));
assert_eq!(observations[1].2, Mute::Muted);
let metadata = events.iter().find_map(|event| match event {
WorkerEvent::StreamMetadata { metadata, .. } => Some(metadata),
_ => None,
});
assert_eq!(
metadata.and_then(|value| value.value(MetadataField::ApplicationName)),
Some("application-7")
);
assert_ne!(
owner.lock().expect("owner thread lock").as_ref(),
Some(&caller)
);
assert!(worker.shutdown());
}
#[test]
fn notifications_cover_external_change_removal_and_backend_id_reuse() {
let (connection, control, _) = FakeConnection::new(Vec::new());
let mut worker = PulseWorker::spawn_with(BackendEpoch::new(2), 32, move || Ok(connection));
initial_snapshot(&worker);
control.notify(PulseNotification::Added(stream(
9,
&[0.1, 0.2],
Mute::Unmuted,
)));
let _metadata = receive(&worker);
let first = match receive(&worker) {
WorkerEvent::Adapter(AdapterEvent::Observed { stream, .. }) => stream,
event => panic!("unexpected event: {event:?}"),
};
control.notify(PulseNotification::Changed(stream(
9,
&[0.4, 0.8],
Mute::Muted,
)));
let _metadata = receive(&worker);
assert!(matches!(
receive(&worker),
WorkerEvent::Adapter(AdapterEvent::Observed {
stream,
muted: Mute::Muted,
..
}) if stream == first
));
control.notify(PulseNotification::Removed(9));
assert!(matches!(
receive(&worker),
WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream }) if stream == first
));
control.notify(PulseNotification::Added(stream(
9,
&[0.5, 0.7],
Mute::Unmuted,
)));
let _metadata = receive(&worker);
let replacement = match receive(&worker) {
WorkerEvent::Adapter(AdapterEvent::Observed { stream, .. }) => stream,
event => panic!("unexpected event: {event:?}"),
};
assert_eq!(first.backend_id(), replacement.backend_id());
assert_ne!(first.incarnation(), replacement.incarnation());
assert!(worker.shutdown());
}
#[test]
fn writes_preserve_multichannel_values_and_surface_failures() {
let (connection, control, _) =
FakeConnection::new(vec![stream(3, &[0.2, 0.4], Mute::Unmuted)]);
let mut worker = PulseWorker::spawn_with(BackendEpoch::new(5), 32, move || Ok(connection));
let initial = initial_snapshot(&worker);
let handle = observed(&initial)[0].0;
worker
.try_submit(AdapterCommand::SetVolume {
operation: OperationId::new(10),
stream: handle,
channels: channels(&[0.1, 0.2, 0.4, 0.8]),
})
.expect("queued volume write");
assert!(matches!(
receive(&worker),
WorkerEvent::Adapter(AdapterEvent::WriteAccepted {
operation
}) if operation == OperationId::new(10)
));
let _metadata = receive(&worker);
assert!(matches!(
receive(&worker),
WorkerEvent::Adapter(AdapterEvent::Observed { channels: actual, operation: Some(operation), .. })
if actual == channels(&[0.1, 0.2, 0.4, 0.8]) && operation == OperationId::new(10)
));
control.reject_writes.store(true, Ordering::Release);
worker
.try_submit(AdapterCommand::SetMute {
operation: OperationId::new(11),
stream: handle,
muted: Mute::Muted,
})
.expect("queued mute write");
assert!(matches!(
receive(&worker),
WorkerEvent::Adapter(AdapterEvent::WriteFailed { operation, .. })
if operation == OperationId::new(11)
));
worker
.try_submit(AdapterCommand::Readback {
operation: OperationId::new(12),
stream: StreamHandle::new(BackendEpoch::new(5), 3, 99),
})
.expect("queued stale readback");
assert!(matches!(
receive(&worker),
WorkerEvent::Adapter(AdapterEvent::WriteFailed { operation, .. })
if operation == OperationId::new(12)
));
assert!(worker.shutdown());
}
#[test]
fn unavailable_server_and_reconnect_epochs_are_explicit() {
let unavailable =
PulseWorker::spawn_with::<FakeConnection, _>(BackendEpoch::new(8), 4, || {
Err(PulseError::Connect("fixture unavailable".into()))
});
assert!(matches!(
receive(&unavailable),
WorkerEvent::Disconnected { epoch, message }
if epoch == BackendEpoch::new(8) && message.contains("fixture unavailable")
));
let (first_connection, _, _) = FakeConnection::new(vec![stream(1, &[0.2], Mute::Unmuted)]);
let mut first =
PulseWorker::spawn_with(BackendEpoch::new(9), 16, move || Ok(first_connection));
let first_handle = observed(&initial_snapshot(&first))[0].0;
assert!(first.shutdown());
let (next_connection, _, _) = FakeConnection::new(vec![stream(1, &[0.7], Mute::Unmuted)]);
let mut next =
PulseWorker::spawn_with(BackendEpoch::new(10), 16, move || Ok(next_connection));
let next_handle = observed(&initial_snapshot(&next))[0].0;
assert_ne!(first_handle.epoch(), next_handle.epoch());
assert!(next.shutdown());
}
#[test]
fn event_lane_overflow_stops_the_worker_and_requests_resync() {
let (connection, _, _) = FakeConnection::new(Vec::new());
let mut worker = PulseWorker::spawn_with(BackendEpoch::new(1), 1, move || Ok(connection));
let _ready = receive(&worker);
assert!(worker.shutdown());
assert!(worker.event_overflowed());
}
}

17
task.md
View File

@ -105,10 +105,25 @@ Dependencies: M3.
changes, and stream churn against PipeWire 1.6.9 through `pipewire-pulse` on
Arch Linux. Keep this item open until the isolated fixture also verifies a
standalone PulseAudio server.
- [ ] **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.
- [x] **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.
The bounded Pulse worker creates and retains all native objects on its owner
thread, subscribes before snapshotting, replays queued notifications before
the snapshot barrier, and copies metadata and observations across the event
lane. Per-epoch incarnation tracking rejects stale commands and distinguishes
reused sink-input indexes. Contract tests cover connection failure, reconnect
epochs, add/change/remove and external edits, stereo/multichannel writes,
rejected operations, stale handles, and explicit overflow-driven resync.
- [ ] **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.
M4.2 verification on 2026-10-14: the scripted worker contract suite passes
without an audio daemon, and a read-only owner-thread smoke run against PipeWire
1.6.9 through `pipewire-pulse` produced a framed snapshot of live application
streams. Locked workspace formatting, all-target/all-feature checks and tests,
doctests, strict Clippy, release build, and no-default-feature checks/tests pass
on Rust 1.88.0. M4.1 still awaits the standalone PulseAudio fixture, and M0.2
still requires a real Jenkins run.
## M5 — MIDI transport, device identity, and first controller
Dependencies: M3; M4 for full end-to-end acceptance.