fader_master/sound/src/lib.rs

397 lines
11 KiB
Rust

//! Audio adapter workers for fader_master.
#![forbid(unsafe_code)]
mod policy;
#[cfg(feature = "pulse")]
mod pulse;
#[cfg(feature = "pulse")]
mod pulse_worker;
pub use policy::{
AdapterAuthority, AdapterChoice, AdapterProbe, AudioBackend, Capability, CompiledAdapterProbe,
ProbeDiagnostic, ProbeOutcome, ReconnectAttempt, SelectedAdapter, SelectionError,
SelectionPolicy, SelectionPolicyError, TargetRequirements, TargetScope, select_adapter,
};
#[cfg(feature = "pulse")]
pub use pulse::{
PulseClient, PulseError, PulseNotification, PulseOutput, PulseServerIdentity, PulseStream,
};
#[cfg(feature = "pulse")]
pub use pulse_worker::PulseWorker;
use std::{
collections::{BTreeMap, VecDeque},
sync::mpsc::{self, Receiver, SyncSender, TrySendError},
thread::{self, JoinHandle},
};
use fader_core::{AdapterCommand, AdapterEvent, BackendEpoch, ChannelGains, Mute, StreamHandle};
/// Capabilities reported before an adapter becomes authoritative.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AdapterCapabilities {
pub application_streams: bool,
pub hardware_targets: bool,
pub volume: bool,
pub mute: bool,
pub subscriptions: bool,
}
/// 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,
},
OutputMetadata {
stream: StreamHandle,
label: String,
volume_writable: bool,
},
Adapter(AdapterEvent),
SnapshotEnd(BackendEpoch),
Disconnected {
epoch: BackendEpoch,
message: String,
},
}
#[derive(Clone, Debug)]
struct FakeStream {
channels: ChannelGains,
muted: Mute,
}
/// Deterministic, hardware-free implementation of the audio worker contract.
#[derive(Debug)]
pub struct FakeAdapter {
epoch: BackendEpoch,
streams: BTreeMap<StreamHandle, FakeStream>,
snapshot: Option<BTreeMap<StreamHandle, FakeStream>>,
during_snapshot: Vec<AdapterEvent>,
}
/// Result of enqueueing work into the bounded adapter lane.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Enqueue {
Queued,
/// An unsent volume operation was replaced by a newer one.
Coalesced {
superseded: fader_core::OperationId,
},
/// An event could not be retained; callers must expose a fault and resync.
Overflow,
}
/// Bounded ordered dispatch with volume-only coalescing.
#[derive(Debug)]
pub struct AdapterQueue {
capacity: usize,
commands: VecDeque<AdapterCommand>,
faulted: bool,
}
/// Bounded exponential reconnect timing, independent of a runtime clock.
#[derive(Clone, Copy, Debug)]
pub struct RetrySchedule {
initial_ms: u64,
maximum_ms: u64,
next_ms: u64,
}
struct WorkerRequest(AdapterCommand);
/// Joined owner thread for the fake adapter, using a bounded command channel.
#[derive(Debug)]
pub struct FakeWorker {
commands: Option<SyncSender<WorkerRequest>>,
events: Receiver<AdapterEvent>,
thread: Option<JoinHandle<()>>,
}
impl FakeWorker {
#[must_use]
pub fn spawn(mut adapter: FakeAdapter, capacity: usize) -> Self {
let (command_sender, command_receiver) = mpsc::sync_channel::<WorkerRequest>(capacity);
let (event_sender, event_receiver) = mpsc::channel();
let thread = thread::spawn(move || {
while let Ok(request) = command_receiver.recv() {
for event in adapter.execute(request.0) {
if event_sender.send(event).is_err() {
return;
}
}
}
});
Self {
commands: Some(command_sender),
events: event_receiver,
thread: Some(thread),
}
}
/// Nonblocking submission; a full lane is an explicit caller-visible fault.
pub fn try_submit(&self, command: AdapterCommand) -> Result<(), AdapterCommand> {
let Some(sender) = &self.commands else {
return Err(command);
};
match sender.try_send(WorkerRequest(command)) {
Ok(()) => Ok(()),
Err(TrySendError::Full(WorkerRequest(command)))
| Err(TrySendError::Disconnected(WorkerRequest(command))) => Err(command),
}
}
pub fn receive(&self) -> Result<AdapterEvent, mpsc::RecvError> {
self.events.recv()
}
/// Requests cancellation and does not return until the owner thread exits.
pub fn shutdown(&mut self) -> bool {
if let Some(sender) = self.commands.take() {
drop(sender);
}
self.thread
.take()
.is_none_or(|thread| thread.join().is_ok())
}
}
impl Drop for FakeWorker {
fn drop(&mut self) {
let _ = self.shutdown();
}
}
impl RetrySchedule {
#[must_use]
pub fn new(initial_ms: u64, maximum_ms: u64) -> Self {
Self {
initial_ms,
maximum_ms,
next_ms: initial_ms.min(maximum_ms),
}
}
pub fn next_delay_ms(&mut self) -> u64 {
let delay = self.next_ms;
self.next_ms = self.next_ms.saturating_mul(2).min(self.maximum_ms);
delay
}
pub fn reset(&mut self) {
self.next_ms = self.initial_ms.min(self.maximum_ms);
}
}
impl AdapterQueue {
#[must_use]
pub fn new(capacity: usize) -> Self {
Self {
capacity,
commands: VecDeque::with_capacity(capacity),
faulted: false,
}
}
pub fn push(&mut self, command: AdapterCommand) -> Enqueue {
if let AdapterCommand::SetVolume {
operation: _,
stream,
..
} = &command
&& let Some(index) = self.commands.iter().position(|queued| {
matches!(queued, AdapterCommand::SetVolume { stream: queued_stream, .. } if queued_stream == stream)
})
&& let Some(AdapterCommand::SetVolume {
operation: superseded,
..
}) = self.commands.remove(index)
{
self.commands.insert(index, command);
return Enqueue::Coalesced { superseded };
}
if self.commands.len() >= self.capacity {
self.faulted = true;
return Enqueue::Overflow;
}
self.commands.push_back(command);
Enqueue::Queued
}
pub fn pop(&mut self) -> Option<AdapterCommand> {
self.commands.pop_front()
}
/// Borrows the next command without removing it, so a busy worker can
/// retain backpressure without losing or reordering the command.
#[must_use]
pub fn front(&self) -> Option<&AdapterCommand> {
self.commands.front()
}
#[must_use]
pub fn len(&self) -> usize {
self.commands.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.commands.is_empty()
}
#[must_use]
pub const fn faulted(&self) -> bool {
self.faulted
}
pub fn clear_fault(&mut self) {
self.faulted = false;
}
}
impl FakeAdapter {
#[must_use]
pub fn new(epoch: BackendEpoch) -> Self {
Self {
epoch,
streams: BTreeMap::new(),
snapshot: None,
during_snapshot: Vec::new(),
}
}
#[must_use]
pub const fn capabilities(&self) -> AdapterCapabilities {
AdapterCapabilities {
application_streams: true,
hardware_targets: false,
volume: true,
mute: true,
subscriptions: true,
}
}
pub fn begin_snapshot(&mut self) -> WorkerEvent {
self.snapshot = Some(self.streams.clone());
self.during_snapshot.clear();
WorkerEvent::SnapshotBegin(self.epoch)
}
pub fn finish_snapshot(&mut self) -> Vec<WorkerEvent> {
let snapshot = self.snapshot.take().unwrap_or_default();
let mut events = snapshot
.into_iter()
.map(|(stream, state)| {
WorkerEvent::Adapter(AdapterEvent::Observed {
stream,
channels: state.channels,
muted: state.muted,
operation: None,
})
})
.collect::<Vec<_>>();
events.extend(self.during_snapshot.drain(..).map(WorkerEvent::Adapter));
events.push(WorkerEvent::SnapshotEnd(self.epoch));
events
}
pub fn upsert(
&mut self,
stream: StreamHandle,
channels: ChannelGains,
muted: Mute,
) -> Option<AdapterEvent> {
self.streams.insert(
stream,
FakeStream {
channels: channels.clone(),
muted,
},
);
let event = AdapterEvent::Observed {
stream,
channels,
muted,
operation: None,
};
if self.snapshot.is_some() {
self.during_snapshot.push(event);
None
} else {
Some(event)
}
}
pub fn remove(&mut self, stream: StreamHandle) -> Option<AdapterEvent> {
self.streams.remove(&stream)?;
let event = AdapterEvent::StreamRemoved { stream };
if self.snapshot.is_some() {
self.during_snapshot.push(event);
None
} else {
Some(event)
}
}
#[must_use]
pub fn execute(&mut self, command: AdapterCommand) -> Vec<AdapterEvent> {
match command {
AdapterCommand::SetVolume {
operation,
stream,
channels,
} => match self.streams.get_mut(&stream) {
Some(state) => {
state.channels = channels;
vec![AdapterEvent::WriteAccepted { operation }]
}
None => vec![AdapterEvent::WriteFailed {
operation,
message: "stream disappeared before volume write".into(),
}],
},
AdapterCommand::SetMute {
operation,
stream,
muted,
} => match self.streams.get_mut(&stream) {
Some(state) => {
state.muted = muted;
vec![AdapterEvent::WriteAccepted { operation }]
}
None => vec![AdapterEvent::WriteFailed {
operation,
message: "stream disappeared before mute write".into(),
}],
},
AdapterCommand::Readback { operation, stream } => self
.streams
.get(&stream)
.map(|state| {
vec![AdapterEvent::Observed {
stream,
channels: state.channels.clone(),
muted: state.muted,
operation: Some(operation),
}]
})
.unwrap_or_else(|| {
vec![AdapterEvent::WriteFailed {
operation,
message: "stream disappeared before readback".into(),
}]
}),
}
}
}