extern crate alloc;
mod pcm;
use self::alloc::{
string::{String, ToString},
sync::Arc,
vec::Vec,
};
use crate::{Block, Capture, DeviceHost, Direction, Endpoint, Playback, Submission};
use ::cpal::{
Device, DeviceDirection, DeviceId, ErrorKind, HostId, SupportedStreamConfig,
SupportedStreamConfigRange,
traits::{DeviceTrait, HostTrait},
};
use core::{
cell::RefCell,
fmt,
num::NonZeroU32,
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
};
use std::{collections::HashMap, io};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Id(usize);
impl fmt::Display for Id {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Devices {
endpoints: Vec<Endpoint<Id, String>>,
configs: Vec<(DeviceId, SupportedStreamConfig)>,
defaults: [Option<Id>; 2],
pub default_input: Option<String>,
pub default_output: Option<String>,
}
struct Selection<'a> {
id: Id,
native: &'a DeviceId,
config: SupportedStreamConfig,
channels: (usize, usize),
}
impl Devices {
#[must_use]
pub fn endpoints(&self) -> &[Endpoint<Id, String>] {
&self.endpoints
}
fn resolve(&self, route: Route, direction: Direction) -> Option<Selection<'_>> {
let id = match route {
Route::Default => self.defaults[index(direction)]?,
Route::Device(id, _) => id,
};
let i = self
.endpoints
.iter()
.position(|e| e.id == id && e.direction == direction)?;
let (native, config) = &self.configs[i];
let channels = match route {
Route::Default if config.channels() == 1 => Channels::Mono(0),
Route::Default => Channels::Pair(0),
Route::Device(_, channels) => channels,
};
Some(Selection {
id,
native,
config: *config,
channels: channels.indices(config.channels())?,
})
}
}
impl AsRef<[Endpoint<Id, String>]> for Devices {
fn as_ref(&self) -> &[Endpoint<Id, String>] {
self.endpoints()
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Route {
Default,
Device(Id, Channels),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Channels {
Mono(u16),
Pair(u16),
}
impl Channels {
fn indices(self, width: u16) -> Option<(usize, usize)> {
let (l, r) = match self {
Self::Mono(i) => (i, i),
Self::Pair(i) => (i, i.checked_add(1)?),
};
(r < width).then_some((usize::from(l), usize::from(r)))
}
}
fn index(direction: Direction) -> usize {
match direction {
Direction::Input => 0,
Direction::Output => 1,
}
}
#[derive(Debug)]
struct Known {
id: Id,
device: Device,
configs: [Option<SupportedStreamConfig>; 2],
}
pub struct Host {
backend: ::cpal::Host,
known: RefCell<HashMap<DeviceId, Known>>,
}
impl fmt::Debug for Host {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Host").field(&self.backend.id()).finish()
}
}
impl Host {
pub fn new() -> io::Result<Self> {
#[cfg(target_os = "linux")]
let id = HostId::Alsa;
#[cfg(target_os = "macos")]
let id = HostId::CoreAudio;
#[cfg(windows)]
let id = HostId::Wasapi;
Ok(Self {
backend: ::cpal::host_from_id(id).map_err(io::Error::other)?,
known: RefCell::default(),
})
}
fn default_device(&self, direction: Direction) -> Option<Device> {
match direction {
Direction::Input => self.backend.default_input_device(),
Direction::Output => self.backend.default_output_device(),
}
}
}
impl DeviceHost for Host {
type Id = Id;
type Name = String;
type Devices = Devices;
type Error = io::Error;
fn devices(&self) -> io::Result<Devices> {
static NEXT_ID: AtomicUsize = AtomicUsize::new(1);
let defaults = [
self.backend.default_input_device(),
self.backend.default_output_device(),
];
let default_ids = defaults
.each_ref()
.map(|d| d.as_ref().and_then(|d| d.id().ok()));
let mut snapshot = Devices::default();
let mut entries = Vec::new();
let mut previous = self.known.borrow_mut();
let mut current = HashMap::new();
let devices = self.backend.devices().map_err(io::Error::other)?;
for device in devices.chain(defaults.into_iter().flatten()) {
let Ok(native) = device.id() else { continue };
if current.contains_key(&native) {
continue;
}
let Ok(description) = device.description() else {
continue;
};
let mut known = match previous.remove(&native) {
Some(known) => Known { device, ..known },
None => Known {
id: Id(NEXT_ID.fetch_add(1, Ordering::Relaxed)),
device,
configs: [None; 2],
},
};
for direction in [Direction::Input, Direction::Output] {
let i = index(direction);
if matches!(
(description.direction(), direction),
(DeviceDirection::Input, Direction::Output)
| (DeviceDirection::Output, Direction::Input)
) {
known.configs[i] = None;
continue;
}
let cached = known.configs[i];
let config = if cfg!(target_os = "linux") && cached.is_some() {
cached
} else {
match configuration(&known.device, direction) {
Ok(c) if c.channels() > 0 && c.sample_rate() > 0 => Some(c),
Err(e) if e.kind() == ErrorKind::DeviceBusy => cached,
_ => None,
}
};
known.configs[i] = config;
let Some(config) = config else { continue };
let name = description.name().to_string();
if default_ids[i].as_ref() == Some(&native) {
snapshot.defaults[i] = Some(known.id);
match direction {
Direction::Input => snapshot.default_input = Some(name.clone()),
Direction::Output => snapshot.default_output = Some(name.clone()),
}
}
entries.push((
Endpoint {
id: known.id,
name,
direction,
channels: config.channels(),
rate: (config.sample_rate(), 1),
},
(native.clone(), config),
));
}
current.insert(native, known);
}
*previous = current;
entries.sort_by_key(|(e, _)| (e.id.0, index(e.direction)));
(snapshot.endpoints, snapshot.configs) = entries.into_iter().unzip();
Ok(snapshot)
}
}
fn configuration(
device: &Device,
direction: Direction,
) -> Result<SupportedStreamConfig, ::cpal::Error> {
let default = match direction {
Direction::Input => device.default_input_config(),
Direction::Output => device.default_output_config(),
};
if cfg!(target_os = "macos") {
let ranges: Vec<_> = match direction {
Direction::Input => device.supported_input_configs().map(Iterator::collect),
Direction::Output => device.supported_output_configs().map(Iterator::collect),
}
.unwrap_or_default();
if let Ok(c) = &default {
if let Some(wider) = ranges
.iter()
.filter(|r| r.channels() > c.channels())
.filter_map(|r| r.try_with_sample_rate(c.sample_rate()))
.max_by_key(|c| c.channels())
{
return Ok(wider);
}
} else if let Some(r) = ranges
.into_iter()
.max_by(SupportedStreamConfigRange::cmp_default_heuristics)
{
return Ok(r
.try_with_standard_sample_rate()
.unwrap_or_else(|| r.with_max_sample_rate()));
}
}
default
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Status {
Opened,
Running,
Offline,
}
struct Link<Q> {
_stream: ::cpal::Stream,
queue: Q,
failed: Arc<AtomicBool>,
route: Route,
id: Id,
config: SupportedStreamConfig,
}
struct Port<Q> {
rate: NonZeroU32,
link: Option<Link<Q>>,
}
impl<Q> Port<Q> {
fn sync(
&mut self,
host: &Host,
devices: &Devices,
route: Route,
direction: Direction,
open: impl FnOnce(
&Device,
SupportedStreamConfig,
(usize, usize),
NonZeroU32,
Arc<AtomicBool>,
) -> io::Result<(::cpal::Stream, Q)>,
) -> io::Result<Status> {
let Some(Selection {
id,
native,
config,
channels,
}) = devices.resolve(route, direction)
else {
self.link = None;
return Ok(Status::Offline);
};
if self.link.as_ref().is_some_and(|link| {
link.id == id
&& link.route == route
&& link.config == config
&& !link.failed.load(Ordering::Relaxed)
}) {
return Ok(Status::Running);
}
self.link = None;
let device = match route {
Route::Default => host
.default_device(direction)
.filter(|d| d.id().ok().as_ref() == Some(native)),
Route::Device(_, _) => host
.known
.borrow()
.get(native)
.filter(|k| k.id == id)
.map(|k| k.device.clone()),
};
let Some(device) = device else {
return Ok(Status::Offline);
};
let failed = Arc::new(AtomicBool::new(false));
let (stream, queue) = open(&device, config, channels, self.rate, failed.clone())
.inspect_err(|_| {
if let Some(k) = host.known.borrow_mut().get_mut(native) {
k.configs[index(direction)] = None;
}
})?;
self.link = Some(Link {
_stream: stream,
queue,
failed,
route,
id,
config,
});
Ok(Status::Opened)
}
fn queue(&mut self) -> io::Result<Option<&mut Q>> {
if self
.link
.as_ref()
.is_some_and(|link| link.failed.load(Ordering::Relaxed))
{
self.link = None;
return Err(io::Error::other("audio stream stopped"));
}
Ok(self.link.as_mut().map(|link| &mut link.queue))
}
}
pub struct Output(Port<pcm::OutputQueue>);
pub struct Input(Port<pcm::InputQueue>);
macro_rules! port {
($ty:ty, $direction:expr, $open:path) => {
impl $ty {
#[must_use]
pub fn new(rate: NonZeroU32) -> Self {
Self(Port { rate, link: None })
}
pub fn sync(
&mut self,
host: &Host,
devices: &Devices,
route: Route,
) -> io::Result<Status> {
self.0.sync(host, devices, route, $direction, $open)
}
}
impl fmt::Debug for $ty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct(stringify!($ty))
.field("route", &self.0.link.as_ref().map(|l| l.route))
.finish()
}
}
};
}
port!(Output, Direction::Output, pcm::open_output);
port!(Input, Direction::Input, pcm::open_input);
impl Playback for Output {
type Error = io::Error;
type Timing = ();
fn render(&mut self, render: impl FnOnce(&mut Block, ())) -> io::Result<Submission> {
match self.0.queue()? {
Some(queue) => queue.render(render),
None => Ok(Submission::WouldBlock),
}
}
}
impl Capture for Input {
type Error = io::Error;
fn read(&mut self, out: &mut Block) -> io::Result<bool> {
match self.0.queue()? {
Some(queue) => queue.read(out),
None => Ok(false),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::FRAMES;
use core::time::Duration;
use std::time::Instant;
#[test]
fn pair_must_fit_the_endpoint() {
assert_eq!(Channels::Pair(2).indices(4), Some((2, 3)));
assert_eq!(Channels::Pair(3).indices(4), None);
assert_eq!(Channels::Pair(u16::MAX).indices(4), None);
assert_eq!(Channels::Mono(0).indices(0), None);
}
#[test]
fn default_moves_by_identity_and_pinned_pair_stays_put() {
use ::cpal::{SampleFormat, SupportedBufferSize};
let mut devices = Devices::default();
let direction = Direction::Output;
for (n, width) in [(1, 4), (2, 1)] {
let config = SupportedStreamConfig::new(
width,
48_000,
SupportedBufferSize::Unknown,
SampleFormat::F32,
);
devices.endpoints.push(Endpoint {
id: Id(n),
name: "USB Audio".into(),
direction,
channels: width,
rate: (48_000, 1),
});
devices
.configs
.push((DeviceId::new(::cpal::ALL_HOSTS[0], n.to_string()), config));
}
devices.defaults[index(direction)] = Some(Id(1));
let first = devices
.resolve(Route::Default, direction)
.expect("first output");
assert_eq!((first.id, first.channels), (Id(1), (0, 1)));
devices.defaults[index(direction)] = Some(Id(2));
let second = devices
.resolve(Route::Default, direction)
.expect("mono output");
assert_eq!((second.id, second.channels), (Id(2), (0, 0)));
let pinned = Route::Device(Id(1), Channels::Pair(2));
assert_eq!(
devices
.resolve(pinned, direction)
.expect("pinned pair")
.channels,
(2, 3)
);
assert!(devices.resolve(pinned, Direction::Input).is_none());
}
#[test]
#[ignore = "requires a virtual default recording and playback device"]
fn duplex_and_route_removal() -> io::Result<()> {
let host = Host::new()?;
let devices = host.devices()?;
let rate = NonZeroU32::new(44_100).expect("positive rate");
let mut output = Output::new(rate);
let mut input = Input::new(rate);
let id = devices.defaults[index(Direction::Output)].expect("virtual default output");
let route = Route::Device(id, Channels::Mono(0));
assert_eq!(output.sync(&host, &devices, route)?, Status::Opened);
assert_eq!(
output.sync(&host, &host.devices()?, route)?,
Status::Running
);
assert_eq!(
output.render(|block, ()| block.fill([42; 2]))?,
Submission::Written
);
assert_eq!(
output.sync(&host, &Devices::default(), route)?,
Status::Offline
);
assert_eq!(
output.render(|_, ()| unreachable!())?,
Submission::WouldBlock
);
assert_eq!(
output.sync(&host, &devices, Route::Default)?,
Status::Opened
);
assert_eq!(input.sync(&host, &devices, Route::Default)?, Status::Opened);
let mut block = [[42; 2]; FRAMES];
let start = Instant::now();
while !input.read(&mut block)? {
assert_eq!(block, [[42; 2]; FRAMES]);
assert!(start.elapsed() < Duration::from_secs(5));
std::thread::sleep(Duration::from_millis(1));
}
assert_eq!(
input.sync(&host, &Devices::default(), Route::Default)?,
Status::Offline
);
assert!(!input.read(&mut block)?);
Ok(())
}
}