1361 lines
45 KiB
Rust
1361 lines
45 KiB
Rust
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, PulseOutput, 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 default_output(&mut self) -> Result<Option<PulseOutput>, PulseError>;
|
|
fn output(&mut self, index: u32) -> Result<PulseOutput, 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>;
|
|
fn set_output_volume(
|
|
&mut self,
|
|
index: u32,
|
|
channels: &fader_core::ChannelGains,
|
|
) -> Result<PulseOutput, PulseError>;
|
|
fn set_output_mute(
|
|
&mut self,
|
|
index: u32,
|
|
muted: fader_core::Mute,
|
|
) -> Result<PulseOutput, 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 default_output(&mut self) -> Result<Option<PulseOutput>, PulseError> {
|
|
Self::default_output(self)
|
|
}
|
|
|
|
fn output(&mut self, index: u32) -> Result<PulseOutput, PulseError> {
|
|
Self::output(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)
|
|
}
|
|
|
|
fn set_output_volume(
|
|
&mut self,
|
|
index: u32,
|
|
channels: &fader_core::ChannelGains,
|
|
) -> Result<PulseOutput, PulseError> {
|
|
Self::set_output_volume(self, index, channels)
|
|
}
|
|
|
|
fn set_output_mute(
|
|
&mut self,
|
|
index: u32,
|
|
muted: fader_core::Mute,
|
|
) -> Result<PulseOutput, PulseError> {
|
|
Self::set_output_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)
|
|
}
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct OutputTracker {
|
|
epoch: BackendEpoch,
|
|
next_incarnation: u64,
|
|
current: Option<(u32, StreamHandle)>,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
struct ExpectedEcho {
|
|
channels: fader_core::ChannelGains,
|
|
muted: fader_core::Mute,
|
|
operation: fader_core::OperationId,
|
|
remaining: usize,
|
|
}
|
|
|
|
#[derive(Debug, Default)]
|
|
struct ExpectedEchoes(BTreeMap<StreamHandle, ExpectedEcho>);
|
|
|
|
impl ExpectedEchoes {
|
|
fn record(
|
|
&mut self,
|
|
stream: StreamHandle,
|
|
channels: fader_core::ChannelGains,
|
|
muted: fader_core::Mute,
|
|
operation: fader_core::OperationId,
|
|
) {
|
|
let remaining = self
|
|
.0
|
|
.get(&stream)
|
|
.map_or(1, |echo| echo.remaining.saturating_add(1));
|
|
self.0.insert(
|
|
stream,
|
|
ExpectedEcho {
|
|
channels,
|
|
muted,
|
|
operation,
|
|
remaining,
|
|
},
|
|
);
|
|
}
|
|
|
|
fn correlate(
|
|
&mut self,
|
|
stream: StreamHandle,
|
|
channels: &fader_core::ChannelGains,
|
|
muted: fader_core::Mute,
|
|
) -> Option<fader_core::OperationId> {
|
|
let echo = self.0.get_mut(&stream)?;
|
|
if echo.channels != *channels || echo.muted != muted {
|
|
self.0.remove(&stream);
|
|
return None;
|
|
}
|
|
let operation = echo.operation;
|
|
echo.remaining -= 1;
|
|
if echo.remaining == 0 {
|
|
self.0.remove(&stream);
|
|
}
|
|
Some(operation)
|
|
}
|
|
|
|
fn remove(&mut self, stream: StreamHandle) {
|
|
self.0.remove(&stream);
|
|
}
|
|
}
|
|
|
|
impl OutputTracker {
|
|
fn new(epoch: BackendEpoch) -> Self {
|
|
Self {
|
|
epoch,
|
|
next_incarnation: 1,
|
|
current: None,
|
|
}
|
|
}
|
|
|
|
fn replace(
|
|
&mut self,
|
|
index: u32,
|
|
) -> Result<(Option<StreamHandle>, StreamHandle), &'static str> {
|
|
if let Some((current_index, handle)) = self.current
|
|
&& current_index == index
|
|
{
|
|
return Ok((None, handle));
|
|
}
|
|
let removed = self.current.map(|(_, handle)| handle);
|
|
let incarnation = self.next_incarnation;
|
|
self.next_incarnation = self
|
|
.next_incarnation
|
|
.checked_add(1)
|
|
.ok_or("Pulse output incarnation counter exhausted")?;
|
|
let handle = StreamHandle::new(self.epoch, (1_u64 << 63) | u64::from(index), incarnation);
|
|
self.current = Some((index, handle));
|
|
Ok((removed, handle))
|
|
}
|
|
|
|
fn remove(&mut self, index: u32) -> Option<StreamHandle> {
|
|
if self.current.is_some_and(|(current, _)| current == index) {
|
|
self.current.take().map(|(_, handle)| handle)
|
|
} else {
|
|
None
|
|
}
|
|
}
|
|
|
|
fn clear(&mut self) -> Option<StreamHandle> {
|
|
self.current.take().map(|(_, handle)| handle)
|
|
}
|
|
|
|
fn resolve(&self, handle: StreamHandle) -> Option<u32> {
|
|
self.current
|
|
.filter(|(_, current)| *current == handle)
|
|
.map(|(index, _)| 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 with independent bounded command and event lanes.
|
|
///
|
|
/// A small command lane enables upstream coalescing without constraining
|
|
/// the burst of metadata and observations emitted by an initial snapshot.
|
|
#[must_use]
|
|
pub fn spawn_with_capacities(
|
|
epoch: BackendEpoch,
|
|
command_capacity: usize,
|
|
event_capacity: usize,
|
|
) -> Self {
|
|
Self::spawn_with_capacities_and_poll_interval(
|
|
epoch,
|
|
command_capacity,
|
|
event_capacity,
|
|
NOTIFICATION_POLL,
|
|
)
|
|
}
|
|
|
|
/// Starts a worker with independent lane capacities and a configured wait
|
|
/// between native command/notification polls.
|
|
#[must_use]
|
|
pub fn spawn_with_capacities_and_poll_interval(
|
|
epoch: BackendEpoch,
|
|
command_capacity: usize,
|
|
event_capacity: usize,
|
|
poll_interval: Duration,
|
|
) -> Self {
|
|
Self::spawn_connected_with_capacities_and_poll_interval(
|
|
epoch,
|
|
command_capacity,
|
|
event_capacity,
|
|
poll_interval,
|
|
PulseClient::connect,
|
|
)
|
|
}
|
|
|
|
/// 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,
|
|
{
|
|
Self::spawn_connected_with_capacities_and_poll_interval(
|
|
epoch,
|
|
capacity,
|
|
capacity,
|
|
NOTIFICATION_POLL,
|
|
connect,
|
|
)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
fn spawn_connected_with_capacities<C, F>(
|
|
epoch: BackendEpoch,
|
|
command_capacity: usize,
|
|
event_capacity: usize,
|
|
connect: F,
|
|
) -> Self
|
|
where
|
|
C: PulseConnection,
|
|
F: FnOnce() -> Result<C, PulseError> + Send + 'static,
|
|
{
|
|
Self::spawn_connected_with_capacities_and_poll_interval(
|
|
epoch,
|
|
command_capacity,
|
|
event_capacity,
|
|
NOTIFICATION_POLL,
|
|
connect,
|
|
)
|
|
}
|
|
|
|
fn spawn_connected_with_capacities_and_poll_interval<C, F>(
|
|
epoch: BackendEpoch,
|
|
command_capacity: usize,
|
|
event_capacity: usize,
|
|
poll_interval: Duration,
|
|
connect: F,
|
|
) -> Self
|
|
where
|
|
C: PulseConnection,
|
|
F: FnOnce() -> Result<C, PulseError> + Send + 'static,
|
|
{
|
|
let (command_sender, command_receiver) = mpsc::sync_channel(command_capacity.max(1));
|
|
let (event_sender, event_receiver) = mpsc::sync_channel(event_capacity.max(1));
|
|
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,
|
|
poll_interval,
|
|
&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)
|
|
}
|
|
|
|
/// Receives one already-buffered event without blocking the state owner.
|
|
pub fn try_receive(&self) -> Result<WorkerEvent, TryRecvError> {
|
|
self.events.try_recv()
|
|
}
|
|
|
|
/// 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>,
|
|
notification_poll: Duration,
|
|
events: &EventLane,
|
|
) -> Result<(), PulseError> {
|
|
connection.subscribe()?;
|
|
if !events.emit(WorkerEvent::Ready {
|
|
epoch,
|
|
capabilities: AdapterCapabilities {
|
|
application_streams: true,
|
|
hardware_targets: false,
|
|
volume: true,
|
|
mute: true,
|
|
subscriptions: true,
|
|
},
|
|
}) || !events.emit(WorkerEvent::SnapshotBegin(epoch))
|
|
{
|
|
return Ok(());
|
|
}
|
|
|
|
let mut tracker = StreamTracker::new(epoch);
|
|
let mut output_tracker = OutputTracker::new(epoch);
|
|
let mut expected_echoes = ExpectedEchoes::default();
|
|
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(());
|
|
}
|
|
}
|
|
if let Some(output) = connection.default_output()? {
|
|
let (_, handle) = output_tracker
|
|
.replace(output.index)
|
|
.map_err(|message| PulseError::Volume(message.to_owned()))?;
|
|
if !emit_output(events, handle, output, None) {
|
|
return Ok(());
|
|
}
|
|
}
|
|
while let Some(notification) = connection.poll_notification(Duration::ZERO)? {
|
|
if !process_notification(
|
|
notification,
|
|
&mut tracker,
|
|
&mut output_tracker,
|
|
&mut expected_echoes,
|
|
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,
|
|
&mut output_tracker,
|
|
&mut expected_echoes,
|
|
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,
|
|
&mut output_tracker,
|
|
&mut expected_echoes,
|
|
events,
|
|
)?
|
|
{
|
|
return Ok(());
|
|
}
|
|
}
|
|
}
|
|
|
|
fn process_notification(
|
|
notification: PulseNotification,
|
|
tracker: &mut StreamTracker,
|
|
output_tracker: &mut OutputTracker,
|
|
expected_echoes: &mut ExpectedEchoes,
|
|
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()))?;
|
|
let operation = expected_echoes.correlate(handle, &stream.channels, stream.muted);
|
|
Ok(emit_stream(events, handle, stream, operation))
|
|
}
|
|
PulseNotification::Removed(index) => {
|
|
let Some(stream) = tracker.remove(index) else {
|
|
return Ok(true);
|
|
};
|
|
expected_echoes.remove(stream);
|
|
Ok(events.emit(WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream })))
|
|
}
|
|
PulseNotification::OutputChanged(output) => {
|
|
if output_tracker
|
|
.current
|
|
.is_none_or(|(index, _)| index != output.index)
|
|
{
|
|
return Ok(true);
|
|
}
|
|
let (_, handle) = output_tracker
|
|
.replace(output.index)
|
|
.map_err(|message| PulseError::Volume(message.to_owned()))?;
|
|
let operation = expected_echoes.correlate(handle, &output.channels, output.muted);
|
|
Ok(emit_output(events, handle, output, operation))
|
|
}
|
|
PulseNotification::OutputRemoved(index) => {
|
|
let Some(stream) = output_tracker.remove(index) else {
|
|
return Ok(true);
|
|
};
|
|
expected_echoes.remove(stream);
|
|
Ok(events.emit(WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream })))
|
|
}
|
|
PulseNotification::DefaultOutputChanged(output) => {
|
|
if let Some(output) = output.as_ref()
|
|
&& output_tracker
|
|
.current
|
|
.is_some_and(|(index, _)| index == output.index)
|
|
{
|
|
let (_, handle) = output_tracker
|
|
.replace(output.index)
|
|
.map_err(|message| PulseError::Volume(message.to_owned()))?;
|
|
let operation = expected_echoes.correlate(handle, &output.channels, output.muted);
|
|
return Ok(emit_output(events, handle, output.clone(), operation));
|
|
}
|
|
let removed = output_tracker.clear();
|
|
if let Some(stream) = removed {
|
|
expected_echoes.remove(stream);
|
|
if !events.emit(WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream })) {
|
|
return Ok(false);
|
|
}
|
|
}
|
|
let Some(output) = output else {
|
|
return Ok(true);
|
|
};
|
|
let (_, handle) = output_tracker
|
|
.replace(output.index)
|
|
.map_err(|message| PulseError::Volume(message.to_owned()))?;
|
|
Ok(emit_output(events, handle, output, None))
|
|
}
|
|
}
|
|
}
|
|
|
|
fn process_command<C: PulseConnection>(
|
|
command: AdapterCommand,
|
|
connection: &mut C,
|
|
tracker: &mut StreamTracker,
|
|
output_tracker: &mut OutputTracker,
|
|
expected_echoes: &mut ExpectedEchoes,
|
|
events: &EventLane,
|
|
) -> bool {
|
|
let (operation, handle) = match &command {
|
|
AdapterCommand::SetVolume {
|
|
operation, stream, ..
|
|
}
|
|
| AdapterCommand::SetMute {
|
|
operation, stream, ..
|
|
}
|
|
| AdapterCommand::Readback { operation, stream } => (*operation, *stream),
|
|
};
|
|
let is_readback = matches!(command, AdapterCommand::Readback { .. });
|
|
if let Some(index) = tracker.resolve(handle) {
|
|
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),
|
|
};
|
|
return match result {
|
|
Ok(stream) => {
|
|
if !is_readback
|
|
&& !events.emit(WorkerEvent::Adapter(AdapterEvent::WriteAccepted {
|
|
operation,
|
|
}))
|
|
{
|
|
return false;
|
|
}
|
|
if !is_readback {
|
|
expected_echoes.record(
|
|
handle,
|
|
stream.channels.clone(),
|
|
stream.muted,
|
|
operation,
|
|
);
|
|
}
|
|
emit_stream(events, handle, stream, Some(operation))
|
|
}
|
|
Err(error) => emit_failure(events, operation, error.to_string()),
|
|
};
|
|
}
|
|
let Some(index) = output_tracker.resolve(handle) else {
|
|
return emit_failure(events, operation, "stream handle is stale or unavailable");
|
|
};
|
|
let result = match command {
|
|
AdapterCommand::SetVolume { channels, .. } => {
|
|
connection.set_output_volume(index, &channels)
|
|
}
|
|
AdapterCommand::SetMute { muted, .. } => connection.set_output_mute(index, muted),
|
|
AdapterCommand::Readback { .. } => connection.output(index),
|
|
};
|
|
match result {
|
|
Ok(output) => {
|
|
if !is_readback
|
|
&& !events.emit(WorkerEvent::Adapter(AdapterEvent::WriteAccepted {
|
|
operation,
|
|
}))
|
|
{
|
|
return false;
|
|
}
|
|
if !is_readback {
|
|
expected_echoes.record(handle, output.channels.clone(), output.muted, operation);
|
|
}
|
|
emit_output(events, handle, output, Some(operation))
|
|
}
|
|
Err(error) => emit_failure(events, operation, error.to_string()),
|
|
}
|
|
}
|
|
|
|
fn emit_output(
|
|
events: &EventLane,
|
|
handle: StreamHandle,
|
|
output: PulseOutput,
|
|
operation: Option<OperationId>,
|
|
) -> bool {
|
|
events.emit(WorkerEvent::OutputMetadata {
|
|
stream: handle,
|
|
label: output.label,
|
|
volume_writable: true,
|
|
}) && events.emit(WorkerEvent::Adapter(AdapterEvent::Observed {
|
|
stream: handle,
|
|
channels: output.channels,
|
|
muted: output.muted,
|
|
operation,
|
|
}))
|
|
}
|
|
|
|
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>>>,
|
|
output: Arc<Mutex<Option<PulseOutput>>>,
|
|
reject_writes: Arc<AtomicBool>,
|
|
last_poll_timeout: Arc<Mutex<Option<Duration>>>,
|
|
}
|
|
|
|
impl FakeControl {
|
|
fn notify(&self, notification: PulseNotification) {
|
|
match ¬ification {
|
|
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);
|
|
}
|
|
PulseNotification::OutputChanged(output) => {
|
|
*self.output.lock().expect("fake output lock") = Some(output.clone());
|
|
}
|
|
PulseNotification::OutputRemoved(index) => {
|
|
let mut output = self.output.lock().expect("fake output lock");
|
|
if output.as_ref().is_some_and(|output| output.index == *index) {
|
|
*output = None;
|
|
}
|
|
}
|
|
PulseNotification::DefaultOutputChanged(output) => {
|
|
*self.output.lock().expect("fake output lock") = output.clone();
|
|
}
|
|
}
|
|
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)),
|
|
output: Arc::new(Mutex::new(None)),
|
|
reject_writes: Arc::new(AtomicBool::new(false)),
|
|
last_poll_timeout: Arc::new(Mutex::new(None)),
|
|
};
|
|
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 default_output(&mut self) -> Result<Option<PulseOutput>, PulseError> {
|
|
Ok(self
|
|
.control
|
|
.output
|
|
.lock()
|
|
.expect("fake output lock")
|
|
.clone())
|
|
}
|
|
|
|
fn output(&mut self, index: u32) -> Result<PulseOutput, PulseError> {
|
|
self.control
|
|
.output
|
|
.lock()
|
|
.expect("fake output lock")
|
|
.clone()
|
|
.filter(|output| output.index == index)
|
|
.ok_or(PulseError::MissingOutput)
|
|
}
|
|
|
|
fn poll_notification(
|
|
&mut self,
|
|
timeout: Duration,
|
|
) -> Result<Option<PulseNotification>, PulseError> {
|
|
*self
|
|
.control
|
|
.last_poll_timeout
|
|
.lock()
|
|
.expect("fake poll timeout lock") = Some(timeout);
|
|
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 set_output_volume(
|
|
&mut self,
|
|
index: u32,
|
|
channels: &ChannelGains,
|
|
) -> Result<PulseOutput, PulseError> {
|
|
let mut output = self.control.output.lock().expect("fake output lock");
|
|
let output = output
|
|
.as_mut()
|
|
.filter(|output| output.index == index)
|
|
.ok_or(PulseError::MissingOutput)?;
|
|
output.channels = channels.clone();
|
|
Ok(output.clone())
|
|
}
|
|
|
|
fn set_output_mute(&mut self, index: u32, muted: Mute) -> Result<PulseOutput, PulseError> {
|
|
let mut output = self.control.output.lock().expect("fake output lock");
|
|
let output = output
|
|
.as_mut()
|
|
.filter(|output| output.index == index)
|
|
.ok_or(PulseError::MissingOutput)?;
|
|
output.muted = muted;
|
|
Ok(output.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 output(index: u32, values: &[f64], muted: Mute) -> PulseOutput {
|
|
PulseOutput {
|
|
index,
|
|
name: format!("output-{index}"),
|
|
label: "Fixture output".to_owned(),
|
|
channels: channels(values),
|
|
muted,
|
|
}
|
|
}
|
|
|
|
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 configured_notification_poll_interval_reaches_the_owner_loop() {
|
|
let (connection, control, _) = FakeConnection::new(Vec::new());
|
|
let expected = Duration::from_millis(3);
|
|
let mut worker = PulseWorker::spawn_connected_with_capacities_and_poll_interval(
|
|
BackendEpoch::new(4),
|
|
4,
|
|
32,
|
|
expected,
|
|
move || Ok(connection),
|
|
);
|
|
initial_snapshot(&worker);
|
|
|
|
let deadline = std::time::Instant::now() + Duration::from_secs(1);
|
|
loop {
|
|
if *control
|
|
.last_poll_timeout
|
|
.lock()
|
|
.expect("fake poll timeout lock")
|
|
== Some(expected)
|
|
{
|
|
break;
|
|
}
|
|
assert!(
|
|
std::time::Instant::now() < deadline,
|
|
"worker did not adopt the configured poll interval"
|
|
);
|
|
std::thread::yield_now();
|
|
}
|
|
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 subscription_echoes_keep_the_originating_operation() {
|
|
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;
|
|
let operation = OperationId::new(10);
|
|
let written = stream(3, &[0.3, 0.6], Mute::Unmuted);
|
|
|
|
worker
|
|
.try_submit(AdapterCommand::SetVolume {
|
|
operation,
|
|
stream: handle,
|
|
channels: written.channels.clone(),
|
|
})
|
|
.expect("queued volume write");
|
|
assert!(matches!(
|
|
receive(&worker),
|
|
WorkerEvent::Adapter(AdapterEvent::WriteAccepted { operation: actual })
|
|
if actual == operation
|
|
));
|
|
let _metadata = receive(&worker);
|
|
let _confirmed = receive(&worker);
|
|
|
|
control.notify(PulseNotification::Changed(written));
|
|
let _metadata = receive(&worker);
|
|
assert!(matches!(
|
|
receive(&worker),
|
|
WorkerEvent::Adapter(AdapterEvent::Observed {
|
|
operation: Some(actual),
|
|
..
|
|
}) if actual == operation
|
|
));
|
|
|
|
control.notify(PulseNotification::Changed(stream(
|
|
3,
|
|
&[0.45, 0.9],
|
|
Mute::Unmuted,
|
|
)));
|
|
let _metadata = receive(&worker);
|
|
assert!(matches!(
|
|
receive(&worker),
|
|
WorkerEvent::Adapter(AdapterEvent::Observed {
|
|
operation: None,
|
|
..
|
|
})
|
|
));
|
|
assert!(worker.shutdown());
|
|
}
|
|
|
|
#[test]
|
|
fn default_output_is_distinct_and_accepts_confirmed_writes() {
|
|
let (connection, control, _) = FakeConnection::new(Vec::new());
|
|
let mut worker = PulseWorker::spawn_with(BackendEpoch::new(6), 32, move || Ok(connection));
|
|
initial_snapshot(&worker);
|
|
|
|
control.notify(PulseNotification::DefaultOutputChanged(Some(output(
|
|
3,
|
|
&[0.3, 0.6],
|
|
Mute::Unmuted,
|
|
))));
|
|
assert!(matches!(
|
|
receive(&worker),
|
|
WorkerEvent::OutputMetadata { label, .. } if label == "Fixture output"
|
|
));
|
|
let handle = match receive(&worker) {
|
|
WorkerEvent::Adapter(AdapterEvent::Observed { stream, .. }) => stream,
|
|
event => panic!("unexpected event: {event:?}"),
|
|
};
|
|
assert!(handle.backend_id() > u64::from(u32::MAX));
|
|
|
|
worker
|
|
.try_submit(AdapterCommand::SetVolume {
|
|
operation: OperationId::new(20),
|
|
stream: handle,
|
|
channels: channels(&[0.2, 0.4]),
|
|
})
|
|
.expect("queued output write");
|
|
assert!(matches!(
|
|
receive(&worker),
|
|
WorkerEvent::Adapter(AdapterEvent::WriteAccepted { operation })
|
|
if operation == OperationId::new(20)
|
|
));
|
|
let _metadata = receive(&worker);
|
|
assert!(matches!(
|
|
receive(&worker),
|
|
WorkerEvent::Adapter(AdapterEvent::Observed {
|
|
stream,
|
|
channels: actual,
|
|
operation: Some(operation),
|
|
..
|
|
}) if stream == handle
|
|
&& actual == channels(&[0.2, 0.4])
|
|
&& operation == OperationId::new(20)
|
|
));
|
|
|
|
control.notify(PulseNotification::DefaultOutputChanged(Some(output(
|
|
4,
|
|
&[0.7, 0.7],
|
|
Mute::Unmuted,
|
|
))));
|
|
assert!(matches!(
|
|
receive(&worker),
|
|
WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream }) if stream == handle
|
|
));
|
|
let _metadata = receive(&worker);
|
|
let replacement = match receive(&worker) {
|
|
WorkerEvent::Adapter(AdapterEvent::Observed { stream, .. }) => stream,
|
|
event => panic!("unexpected event: {event:?}"),
|
|
};
|
|
assert_ne!(replacement, handle);
|
|
worker
|
|
.try_submit(AdapterCommand::Readback {
|
|
operation: OperationId::new(21),
|
|
stream: handle,
|
|
})
|
|
.expect("queued stale output readback");
|
|
assert!(matches!(
|
|
receive(&worker),
|
|
WorkerEvent::Adapter(AdapterEvent::WriteFailed { operation, .. })
|
|
if operation == OperationId::new(21)
|
|
));
|
|
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());
|
|
}
|
|
|
|
#[test]
|
|
fn one_slot_command_backpressure_keeps_a_full_snapshot_event_lane() {
|
|
let (connection, _, _) = FakeConnection::new(vec![stream(1, &[0.2], Mute::Unmuted)]);
|
|
let mut worker =
|
|
PulseWorker::spawn_connected_with_capacities(BackendEpoch::new(11), 1, 16, move || {
|
|
Ok(connection)
|
|
});
|
|
|
|
let events = initial_snapshot(&worker);
|
|
assert!(events.len() > 2);
|
|
assert!(!worker.event_overflowed());
|
|
assert!(worker.shutdown());
|
|
}
|
|
}
|