Avoid calling alsa::PCM::new() multiple times.

Ensures that alsa::PCM::new() is called only once for a given Device so that we are
not rapidly opening and closing ALSA devices.
This commit is contained in:
Alex Moon 2020-11-18 10:22:41 -07:00
parent 296cf5caf7
commit fb30d291ce
3 changed files with 68 additions and 22 deletions

View file

@ -30,6 +30,7 @@ lazy_static = "1.3"
alsa = "0.4.3" alsa = "0.4.3"
nix = "0.15.0" nix = "0.15.0"
libc = "0.2.65" libc = "0.2.65"
parking_lot = "0.11"
jack = { version = "0.6.5", optional = true } jack = { version = "0.6.5", optional = true }
[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]

View file

@ -1,4 +1,5 @@
use super::alsa; use super::alsa;
use super::parking_lot::Mutex;
use super::Device; use super::Device;
use {BackendSpecificError, DevicesError}; use {BackendSpecificError, DevicesError};
@ -48,21 +49,16 @@ impl Iterator for Devices {
}; };
// See if the device has an available output stream. // See if the device has an available output stream.
let has_available_output = { let playback = alsa::pcm::PCM::new(&name, alsa::Direction::Playback, true).ok();
let playback_handle =
alsa::pcm::PCM::new(&name, alsa::Direction::Playback, true);
playback_handle.is_ok()
};
// See if the device has an available input stream. // See if the device has an available input stream.
let has_available_input = { let capture = alsa::pcm::PCM::new(&name, alsa::Direction::Capture, true).ok();
let capture_handle =
alsa::pcm::PCM::new(&name, alsa::Direction::Capture, true);
capture_handle.is_ok()
};
if has_available_output || has_available_input { if playback.is_some() || capture.is_some() {
return Some(Device(name)); return Some(Device {
name,
handles: Mutex::new(super::DeviceHandles { playback, capture }),
});
} }
} }
} }
@ -72,12 +68,24 @@ impl Iterator for Devices {
#[inline] #[inline]
pub fn default_input_device() -> Option<Device> { pub fn default_input_device() -> Option<Device> {
Some(Device("default".to_owned())) Some(Device {
name: "default".to_owned(),
handles: Mutex::new(super::DeviceHandles {
playback: None,
capture: None,
}),
})
} }
#[inline] #[inline]
pub fn default_output_device() -> Option<Device> { pub fn default_output_device() -> Option<Device> {
Some(Device("default".to_owned())) Some(Device {
name: "default".to_owned(),
handles: Mutex::new(super::DeviceHandles {
playback: None,
capture: None,
}),
})
} }
impl From<alsa::Error> for DevicesError { impl From<alsa::Error> for DevicesError {

View file

@ -1,7 +1,9 @@
extern crate alsa; extern crate alsa;
extern crate libc; extern crate libc;
extern crate parking_lot;
use self::alsa::poll::Descriptors; use self::alsa::poll::Descriptors;
use self::parking_lot::Mutex;
use crate::{ use crate::{
BackendSpecificError, BufferSize, BuildStreamError, ChannelCount, Data, BackendSpecificError, BufferSize, BuildStreamError, ChannelCount, Data,
DefaultStreamConfigError, DeviceNameError, DevicesError, InputCallbackInfo, OutputCallbackInfo, DefaultStreamConfigError, DeviceNameError, DevicesError, InputCallbackInfo, OutputCallbackInfo,
@ -163,8 +165,15 @@ impl Drop for TriggerReceiver {
} }
} }
#[derive(Clone, Debug, PartialEq, Eq)] struct DeviceHandles {
pub struct Device(String); playback: Option<alsa::PCM>,
capture: Option<alsa::PCM>,
}
pub struct Device {
name: String,
handles: Mutex<DeviceHandles>,
}
impl Device { impl Device {
fn build_stream_inner( fn build_stream_inner(
@ -173,10 +182,21 @@ impl Device {
sample_format: SampleFormat, sample_format: SampleFormat,
stream_type: alsa::Direction, stream_type: alsa::Direction,
) -> Result<StreamInner, BuildStreamError> { ) -> Result<StreamInner, BuildStreamError> {
let name = &self.0; let name = &self.name;
let handle = match alsa::pcm::PCM::new(name, stream_type, true).map_err(|e| (e, e.errno())) let device_handle = {
{ let mut guard = self.handles.lock();
match stream_type {
alsa::Direction::Playback => guard.playback.take(),
alsa::Direction::Capture => guard.capture.take(),
}
};
let handle_result = Ok(device_handle).transpose().unwrap_or_else(|| {
alsa::pcm::PCM::new(name, stream_type, true).map_err(|e| (e, e.errno()))
});
let handle = match handle_result {
Err((_, Some(nix::errno::Errno::EBUSY))) => { Err((_, Some(nix::errno::Errno::EBUSY))) => {
return Err(BuildStreamError::DeviceNotAvailable) return Err(BuildStreamError::DeviceNotAvailable)
} }
@ -229,16 +249,33 @@ impl Device {
#[inline] #[inline]
fn name(&self) -> Result<String, DeviceNameError> { fn name(&self) -> Result<String, DeviceNameError> {
Ok(self.0.clone()) Ok(self.name.clone())
} }
fn supported_configs( fn supported_configs(
&self, &self,
stream_t: alsa::Direction, stream_t: alsa::Direction,
) -> Result<VecIntoIter<SupportedStreamConfigRange>, SupportedStreamConfigsError> { ) -> Result<VecIntoIter<SupportedStreamConfigRange>, SupportedStreamConfigsError> {
let name = &self.0; let name = &self.name;
let handle = match alsa::pcm::PCM::new(name, stream_t, true).map_err(|e| (e, e.errno())) { let mut guard = self.handles.lock();
let device_handle = match stream_t {
alsa::Direction::Playback => &mut guard.playback,
alsa::Direction::Capture => &mut guard.capture,
};
let handle_result = match device_handle {
Some(handle) => Ok(handle),
None => alsa::pcm::PCM::new(name, stream_t, true)
.map(|handle| {
*device_handle = Some(handle);
device_handle.as_mut().unwrap()
})
.map_err(|e| (e, e.errno())),
};
let handle = match handle_result {
Err((_, Some(nix::errno::Errno::ENOENT))) Err((_, Some(nix::errno::Errno::ENOENT)))
| Err((_, Some(nix::errno::Errno::EBUSY))) => { | Err((_, Some(nix::errno::Errno::EBUSY))) => {
return Err(SupportedStreamConfigsError::DeviceNotAvailable) return Err(SupportedStreamConfigsError::DeviceNotAvailable)