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

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