diff --git a/CHANGELOG.md b/CHANGELOG.md index 70a8d9ac9..e072bdc84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Migrated to Rust 2024. - Bump minimum Windows version to 10 (since 0.17.2). - Bump `audio_thread_priority` dependency to 0.36. +- Normalized thread and client naming across all backends. - `DeviceTrait` and `StreamTrait` now require `Send + Sync` as supertrait bounds. - `StreamTrait::play` is renamed to `start`. - `InputCallbackInfo`/`OutputCallbackInfo` merged into `CallbackInfo`. diff --git a/examples/enumerate.rs b/examples/enumerate.rs index 6e2680961..9135043cc 100644 --- a/examples/enumerate.rs +++ b/examples/enumerate.rs @@ -45,7 +45,7 @@ fn main() -> Result<(), anyhow::Error> { .id() .map_or("Unknown ID".to_string(), |id| id.to_string()); if let Ok(desc) = device.description() { - println!(" {}. {id} ({})", device_index + 1, desc); + println!(" {}. {id} ({desc})", device_index + 1); } else { println!(" {}. {id}", device_index + 1); } @@ -65,10 +65,9 @@ fn main() -> Result<(), anyhow::Error> { println!(" All supported input stream configs:"); for (config_index, config) in input_configs.into_iter().enumerate() { println!( - " {}.{}. {:?}", + " {}.{}. {config:?}", device_index + 1, config_index + 1, - config ); } } @@ -88,10 +87,9 @@ fn main() -> Result<(), anyhow::Error> { println!(" All supported output stream configs:"); for (config_index, config) in output_configs.into_iter().enumerate() { println!( - " {}.{}. {:?}", + " {}.{}. {config:?}", device_index + 1, config_index + 1, - config ); } } diff --git a/src/duplex.rs b/src/duplex.rs index b98394f18..8da26f42c 100644 --- a/src/duplex.rs +++ b/src/duplex.rs @@ -40,3 +40,31 @@ pub struct DuplexStreamConfig { /// The desired buffer size, in frames per callback. pub buffer_size: BufferSize, } + +#[cfg(all( + feature = "jack", + any( + target_os = "linux", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "netbsd", + target_os = "macos", + target_os = "windows", + ) +))] +/// Applies [`validate_stream_config`] to each direction of a duplex configuration. +pub(crate) fn validate_duplex_config(config: &DuplexStreamConfig) -> Result<(), crate::Error> { + let input = crate::StreamConfig { + channels: config.input_channels, + sample_rate: config.sample_rate, + buffer_size: config.buffer_size, + }; + crate::validate_stream_config(&input)?; + + let output = crate::StreamConfig { + channels: config.output_channels, + sample_rate: config.sample_rate, + buffer_size: config.buffer_size, + }; + crate::validate_stream_config(&output) +} diff --git a/src/error.rs b/src/error.rs index b6242a056..4f6ddb396 100644 --- a/src/error.rs +++ b/src/error.rs @@ -194,7 +194,6 @@ impl From for Error { ))] impl From for Error { fn from(err: audio_thread_priority::AudioThreadPriorityError) -> Self { - use std::error::Error as StdError; let msg = match err.source() { Some(inner) => { format!("Failed to promote audio thread to real-time priority: {err}: {inner}") diff --git a/src/host.rs b/src/host.rs index 56ec2d68b..9c8c17811 100644 --- a/src/host.rs +++ b/src/host.rs @@ -197,7 +197,7 @@ pub(crate) use error_emit::emit_error; #[cfg(any( target_vendor = "apple", - target_os = "android", + all(target_os = "android", feature = "realtime",), all( feature = "jack", any( diff --git a/src/host/aaudio.rs b/src/host/aaudio.rs index 2de6551bb..9f00560a5 100644 --- a/src/host/aaudio.rs +++ b/src/host/aaudio.rs @@ -22,8 +22,9 @@ use crate::{ traits::{DeviceTrait, HostTrait, StreamTrait}, }; -extern crate ndk; -use self::ndk::audio::AudioStream; +use ndk::audio::AudioStream; + +#[cfg(feature = "realtime")] use crate::host::try_emit_error; mod convert; @@ -577,7 +578,7 @@ impl DeviceTrait for Device { let device_type: DeviceType = info.device_type.into(); let name = match device_type { DeviceType::Unknown => info.product_name.clone(), - _ => format!("{} ({})", info.product_name, device_type), + _ => format!("{} ({device_type})", info.product_name), }; let mut builder = DeviceDescriptionBuilder::new(name) .device_type(device_type) diff --git a/src/host/aaudio/convert.rs b/src/host/aaudio/convert.rs index 0b54a4e76..1b2c496ff 100644 --- a/src/host/aaudio/convert.rs +++ b/src/host/aaudio/convert.rs @@ -1,7 +1,5 @@ //! Time-conversion helpers for the AAudio backend. -extern crate ndk; - use crate::{Error, ErrorKind, StreamInstant}; /// Returns a [`StreamInstant`] for the current moment. @@ -58,27 +56,17 @@ pub fn input_stream_instant(stream: &ndk::audio::AudioStream, sample_rate: u32) impl From for Error { fn from(error: ndk::audio::AudioError) -> Self { use ndk::audio::AudioError::*; - match error { - Disconnected | Unavailable | NoService | InvalidHandle => { - Error::with_message(ErrorKind::DeviceNotAvailable, error.to_string()) - } - NoFreeHandles | NoMemory => { - Error::with_message(ErrorKind::ResourceExhausted, error.to_string()) - } - WouldBlock | Timeout => Error::with_message(ErrorKind::DeviceBusy, error.to_string()), - InvalidFormat | InvalidRate => { - Error::with_message(ErrorKind::UnsupportedConfig, error.to_string()) - } - IllegalArgument | Null | OutOfRange => { - Error::with_message(ErrorKind::InvalidInput, error.to_string()) - } - Internal | InvalidState => { - Error::with_message(ErrorKind::StreamInvalidated, error.to_string()) - } - Unimplemented => { - Error::with_message(ErrorKind::UnsupportedOperation, error.to_string()) - } - _ => Error::with_message(ErrorKind::BackendError, error.to_string()), - } + let kind = match error { + Disconnected | Unavailable | NoService | InvalidHandle => ErrorKind::DeviceNotAvailable, + NoFreeHandles | NoMemory => ErrorKind::ResourceExhausted, + WouldBlock | Timeout => ErrorKind::DeviceBusy, + InvalidFormat | InvalidRate => ErrorKind::UnsupportedConfig, + IllegalArgument | Null | OutOfRange => ErrorKind::InvalidInput, + Internal | InvalidState => ErrorKind::StreamInvalidated, + Unimplemented => ErrorKind::UnsupportedOperation, + _ => ErrorKind::BackendError, + }; + + Error::with_message(kind, error.to_string()) } } diff --git a/src/host/alsa.rs b/src/host/alsa.rs index 8898e3b4a..bf6d201b0 100644 --- a/src/host/alsa.rs +++ b/src/host/alsa.rs @@ -2,20 +2,13 @@ //! //! Default backend on Linux and BSD systems. -extern crate alsa; -#[cfg(feature = "realtime")] -extern crate alsa_sys; -extern crate libc; - use std::{ mem, sync::{Arc, Mutex}, time::Duration, }; -pub use self::device::Device; -pub use self::enumerate::Devices; -pub use self::stream::Stream; +pub use self::{device::Device, enumerate::Devices, stream::Stream}; use crate::{ DeviceDirection, DeviceId, Error, ErrorKind, traits::{DeviceTrait, HostTrait}, diff --git a/src/host/alsa/device.rs b/src/host/alsa/device.rs index 8c251980b..771ef862a 100644 --- a/src/host/alsa/device.rs +++ b/src/host/alsa/device.rs @@ -1,3 +1,4 @@ +use alsa::poll::Descriptors; use std::{ collections::HashMap, fmt, @@ -7,8 +8,7 @@ use std::{ }; use super::{ - AlsaContext, DEFAULT_PERIODS, Stream, alsa, - alsa::poll::Descriptors, + AlsaContext, DEFAULT_PERIODS, Stream, hw_params::{ StartThreshold, set_hw_params_from_format, set_sw_params_from_format, supported_period_size_range, @@ -105,13 +105,13 @@ impl DeviceTrait for Device { let data_callback = crate::host::monotonic_input_callback(data_callback); let stream_inner = self.build_stream_inner(conf, sample_format, alsa::Direction::Capture)?; - let stream = Self::Stream::new_input( + + Self::Stream::new_input( Arc::new(stream_inner), data_callback, error_callback, timeout, - ); - Ok(stream) + ) } fn build_output_stream_raw( @@ -131,13 +131,13 @@ impl DeviceTrait for Device { let data_callback = crate::host::monotonic_output_callback(data_callback); let stream_inner = self.build_stream_inner(conf, sample_format, alsa::Direction::Playback)?; - let stream = Self::Stream::new_output( + + Self::Stream::new_output( Arc::new(stream_inner), data_callback, error_callback, timeout, - ); - Ok(stream) + ) } fn build_duplex_stream_raw( @@ -155,13 +155,13 @@ impl DeviceTrait for Device { { let stream_inner = self.build_duplex_stream_inner(config, input_sample_format, output_sample_format)?; - let stream = Self::Stream::new_duplex( + + Self::Stream::new_duplex( Arc::new(stream_inner), data_callback, error_callback, timeout, - ); - Ok(stream) + ) } } diff --git a/src/host/alsa/duplex.rs b/src/host/alsa/duplex.rs index ee8a24a8e..d23d96e8a 100644 --- a/src/host/alsa/duplex.rs +++ b/src/host/alsa/duplex.rs @@ -1,12 +1,5 @@ -use std::{ - sync::{Arc, atomic::Ordering}, - time::Duration, -}; - use super::{ - DEFAULT_PERIODS, alsa, - alsa::poll::Descriptors, - poll_timeout_millis, + DEFAULT_PERIODS, poll_timeout_millis, stream::{DuplexDataCallback, DuplexStreamInner, ErrorCallback}, timestamp::{callback_instant_for, status_with_timestamp}, trigger::TriggerReceiver, @@ -15,6 +8,11 @@ use crate::{ CallbackInfo, Data, DuplexCallbackInfo, Error, ErrorKind, FrameCount, StreamInstant, StreamTimestamp, host::frames_to_duration, }; +use alsa::poll::Descriptors; +use std::{ + sync::{Arc, atomic::Ordering}, + time::Duration, +}; pub(super) fn start_duplex(stream: &DuplexStreamInner) -> Result<(), Error> { match stream.capture.handle.state() { diff --git a/src/host/alsa/enumerate.rs b/src/host/alsa/enumerate.rs index 8d076b20a..4ad01ced9 100644 --- a/src/host/alsa/enumerate.rs +++ b/src/host/alsa/enumerate.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use super::{Device, Host, alsa}; +use super::{Device, Host}; use crate::{DeviceDirection, Error}; const HW_PREFIX: &str = "hw"; @@ -57,8 +57,8 @@ impl Host { for phys_dev in physical_devices { for prefix in [HW_PREFIX, PLUGHW_PREFIX] { let pcm_id = format!( - "{}:CARD={},DEV={}", - prefix, phys_dev.card_index, phys_dev.device_index + "{prefix}:CARD={},DEV={}", + phys_dev.card_index, phys_dev.device_index ); if seen_pcm_ids.insert(pcm_id.clone()) { @@ -80,7 +80,7 @@ impl Host { fn format_device_description(phys_dev: &PhysicalDevice, prefix: &str) -> String { // "Card Name, Device Name" or variations let first_line = match (&phys_dev.card_name, &phys_dev.device_name) { - (Some(card), Some(device)) => format!("{}, {}", card, device), + (Some(card), Some(device)) => format!("{card}, {device}"), (Some(card), None) => card.clone(), (None, Some(device)) => device.clone(), (None, None) => format!("Card {}", phys_dev.card_index), @@ -100,7 +100,7 @@ fn physical_devices() -> Vec { let mut devices = Vec::new(); for card in alsa::card::Iter::new().filter_map(Result::ok) { let card_index = card.get_index() as u32; - let ctl = match alsa::Ctl::new(&format!("{}:{}", HW_PREFIX, card_index), false) { + let ctl = match alsa::Ctl::new(&format!("{HW_PREFIX}:{card_index}"), false) { Ok(ctl) => ctl, Err(_) => continue, }; diff --git a/src/host/alsa/hw_params.rs b/src/host/alsa/hw_params.rs index 22a13be17..7f5231188 100644 --- a/src/host/alsa/hw_params.rs +++ b/src/host/alsa/hw_params.rs @@ -1,4 +1,4 @@ -use super::{DEFAULT_PERIODS, alsa}; +use super::DEFAULT_PERIODS; use crate::{ BufferSize, ChannelCount, Error, ErrorKind, FrameCount, SampleFormat, StreamConfig, SupportedBufferSize, diff --git a/src/host/alsa/stream.rs b/src/host/alsa/stream.rs index bcba11e87..652397a86 100644 --- a/src/host/alsa/stream.rs +++ b/src/host/alsa/stream.rs @@ -1,23 +1,13 @@ -use std::{ - sync::{ - Arc, - atomic::{AtomicBool, Ordering}, - }, - thread::{self, JoinHandle}, - time::{Duration, Instant}, -}; - use super::{ - AlsaContext, POLL_INFINITE, alsa, - alsa::poll::Descriptors, + AlsaContext, POLL_INFINITE, duplex::{duplex_stream_worker, start_duplex}, timestamp::{callback_instant_for, status_with_timestamp}, trigger::{TriggerReceiver, TriggerSender, trigger}, worker::{input_stream_worker, output_stream_worker}, }; use crate::{ - CallbackInfo, Data, DeviceDirection, DuplexCallbackInfo, Error, FrameCount, SampleFormat, - SampleRate, StreamInstant, + CallbackInfo, Data, DeviceDirection, DuplexCallbackInfo, Error, ErrorKind, FrameCount, + SampleFormat, SampleRate, StreamInstant, host::{ Notify, equilibrium::{DSD_EQUILIBRIUM_BYTE, U8_EQUILIBRIUM_BYTE, fill_equilibrium}, @@ -25,6 +15,15 @@ use crate::{ }, traits::StreamTrait, }; +use alsa::poll::Descriptors; +use std::{ + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + thread::{self, JoinHandle}, + time::{Duration, Instant}, +}; pub(super) type InputDataCallback = dyn FnMut(&Data, &CallbackInfo) + Send + 'static; pub(super) type OutputDataCallback = dyn FnMut(&mut Data, &CallbackInfo) + Send + 'static; @@ -82,7 +81,7 @@ impl Stream { mut data_callback: D, mut error_callback: E, timeout: Option, - ) -> Stream + ) -> Result where D: FnMut(&Data, &CallbackInfo) + Send + 'static, E: FnMut(Error) + Send + 'static, @@ -108,16 +107,21 @@ impl Stream { timeout, ); }) - .unwrap(); + .map_err(|e| { + Error::with_message( + ErrorKind::ResourceExhausted, + format!("Failed to create ALSA input worker thread: {e}"), + ) + })?; latch.add_thread(thread.thread().clone()); - Self { + Ok(Self { thread: Some(thread), kind: StreamKind::Single(inner), trigger: tx, _rx: rx, latch, - } + }) } pub(super) fn new_output( @@ -125,7 +129,7 @@ impl Stream { mut data_callback: D, mut error_callback: E, timeout: Option, - ) -> Stream + ) -> Result where D: FnMut(&mut Data, &CallbackInfo) + Send + 'static, E: FnMut(Error) + Send + 'static, @@ -151,16 +155,21 @@ impl Stream { timeout, ); }) - .unwrap(); + .map_err(|e| { + Error::with_message( + ErrorKind::ResourceExhausted, + format!("Failed to create ALSA output worker thread: {e}"), + ) + })?; latch.add_thread(thread.thread().clone()); - Self { + Ok(Self { thread: Some(thread), kind: StreamKind::Single(inner), trigger: tx, _rx: rx, latch, - } + }) } pub(super) fn new_duplex( @@ -168,7 +177,7 @@ impl Stream { mut data_callback: D, mut error_callback: E, timeout: Option, - ) -> Stream + ) -> Result where D: FnMut(&Data, &mut Data, &DuplexCallbackInfo) + Send + 'static, E: FnMut(Error) + Send + 'static, @@ -183,7 +192,7 @@ impl Stream { let waiter = latch.waiter(); let thread = thread::Builder::new() - .name("cpal_alsa_duplex".to_owned()) + .name("cpal_alsa_dup".to_owned()) .spawn(move || { waiter.wait(); duplex_stream_worker( @@ -194,16 +203,21 @@ impl Stream { timeout, ); }) - .unwrap(); + .map_err(|e| { + Error::with_message( + ErrorKind::ResourceExhausted, + format!("Failed to create ALSA duplex worker thread: {e}"), + ) + })?; latch.add_thread(thread.thread().clone()); - Self { + Ok(Self { thread: Some(thread), kind: StreamKind::Duplex(inner), trigger: tx, _rx: rx, latch, - } + }) } fn suspend_pcm(&self, inner: &StreamInner) -> Result<(), Error> { diff --git a/src/host/alsa/timestamp.rs b/src/host/alsa/timestamp.rs index 59dfc4957..8ca6c7138 100644 --- a/src/host/alsa/timestamp.rs +++ b/src/host/alsa/timestamp.rs @@ -1,4 +1,4 @@ -use super::{alsa, stream::TimestampMode}; +use super::stream::TimestampMode; use crate::{Error, StreamInstant}; #[inline] diff --git a/src/host/alsa/worker.rs b/src/host/alsa/worker.rs index e35795c7b..ff257b204 100644 --- a/src/host/alsa/worker.rs +++ b/src/host/alsa/worker.rs @@ -1,11 +1,4 @@ -use std::{ - sync::{Arc, atomic::Ordering}, - time::Duration, -}; - use super::{ - alsa, - alsa::poll::Descriptors, poll_timeout_millis, stream::{ErrorCallback, InputDataCallback, OutputDataCallback, StreamInner}, timestamp::status_with_timestamp, @@ -15,6 +8,11 @@ use crate::{ CallbackInfo, Data, Error, ErrorKind, FrameCount, StreamInstant, StreamTimestamp, host::frames_to_duration, }; +use alsa::poll::Descriptors; +use std::{ + sync::{Arc, atomic::Ordering}, + time::Duration, +}; pub(super) fn input_stream_worker( rx: Arc, diff --git a/src/host/asio.rs b/src/host/asio.rs index 055fa7125..caeaae885 100644 --- a/src/host/asio.rs +++ b/src/host/asio.rs @@ -3,7 +3,7 @@ //! ASIO is available on Windows with the `asio` feature. //! See the project README for setup instructions. -extern crate asio_sys as sys; +use asio_sys as sys; use std::{ sync::{Arc, OnceLock}, diff --git a/src/host/asio/stream.rs b/src/host/asio/stream.rs index 505ad1c87..3c1b07828 100644 --- a/src/host/asio/stream.rs +++ b/src/host/asio/stream.rs @@ -1,5 +1,4 @@ -extern crate asio_sys as sys; -extern crate num_traits; +use asio_sys as sys; use std::{ sync::{ @@ -10,7 +9,6 @@ use std::{ time::Duration, }; -use self::num_traits::{FromPrimitive, PrimInt}; use super::Device; use crate::{ BufferSize, CallbackInfo, Data, Error, ErrorKind, FrameCount, I24, Sample, SampleFormat, @@ -20,6 +18,7 @@ use crate::{ wait_for_drain, }, }; +use num_traits::{FromPrimitive, PrimInt}; /// Shared state for extending the 32-bit `timeGetTime()` millisecond counter into a /// monotonic 64-bit nanosecond value, shared between `now()` and audio callbacks. @@ -1022,7 +1021,7 @@ impl Device { let (timer_tx, timer_rx) = mpsc::channel::(); let error_cb_for_timer = Arc::clone(&error_callback_shared); std::thread::Builder::new() - .name("cpal-asio-event-timer".into()) + .name("cpal_asio_event_timer".into()) .spawn(move || { let mut pending: Option = None; loop { diff --git a/src/host/coreaudio/macos.rs b/src/host/coreaudio/macos.rs index 2dc242448..77f1f58c1 100644 --- a/src/host/coreaudio/macos.rs +++ b/src/host/coreaudio/macos.rs @@ -312,7 +312,7 @@ impl DisconnectManager { let mut latch = Latch::new(); spawn_delivery_thread( - "cpal-coreaudio-disconnect", + "cpal_coreaudio_disconnect", &mut latch, disconnect_rx, stream_weak, @@ -435,7 +435,7 @@ impl DefaultOutputMonitor { let mut latch = Latch::new(); spawn_delivery_thread( - "cpal-coreaudio-default-output", + "cpal_coreaudio_default_out", &mut latch, change_rx, stream_weak, diff --git a/src/host/jack.rs b/src/host/jack.rs index 1315aeda2..42f5fa1da 100644 --- a/src/host/jack.rs +++ b/src/host/jack.rs @@ -2,8 +2,6 @@ //! //! Available on all platforms with the `jack` feature. Requires JACK server and client libraries. -extern crate jack; - use crate::{Error, ErrorKind, SampleFormat, traits::HostTrait}; mod device; @@ -46,7 +44,7 @@ pub struct Host { impl Host { pub fn new() -> Result { let mut host = Host { - name: format!("cpal_client_{}", std::process::id()), + name: format!("cpal_jack_client_{}", std::process::id()), connect_ports_automatically: true, start_server_automatically: false, devices_created: vec![], @@ -178,35 +176,27 @@ fn get_client_options(start_server_automatically: bool) -> jack::ClientOptions { impl From for Error { fn from(err: jack::Error) -> Self { - let msg = format!("{err}"); - match err { + let kind = match err { jack::Error::ClientError(_) | jack::Error::ClientActivationError | jack::Error::ClientDeactivationError | jack::Error::LibraryError(_) | jack::Error::WeakFunctionNotFound(_) - | jack::Error::RingbufferCreateFailed => { - Error::with_message(ErrorKind::DeviceNotAvailable, msg) - } + | jack::Error::RingbufferCreateFailed => ErrorKind::DeviceNotAvailable, jack::Error::ClientIsNoLongerAlive | jack::Error::ClientPanicked => { - Error::with_message(ErrorKind::StreamInvalidated, msg) + ErrorKind::StreamInvalidated } - jack::Error::SetBufferSizeError | jack::Error::NotEnoughSpace => { - Error::with_message(ErrorKind::UnsupportedConfig, msg) + ErrorKind::UnsupportedConfig } - jack::Error::InvalidDeactivation | jack::Error::FreewheelError => { - Error::with_message(ErrorKind::UnsupportedOperation, msg) + ErrorKind::UnsupportedOperation } - - jack::Error::PortNamingError | jack::Error::PortAliasError => { - Error::with_message(ErrorKind::InvalidInput, msg) - } - - _ => Error::with_message(ErrorKind::BackendError, msg), - } + jack::Error::PortNamingError | jack::Error::PortAliasError => ErrorKind::InvalidInput, + _ => ErrorKind::BackendError, + }; + Error::with_message(kind, format!("{err}")) } } diff --git a/src/host/jack/device.rs b/src/host/jack/device.rs index e4940f832..dccc3eb9a 100644 --- a/src/host/jack/device.rs +++ b/src/host/jack/device.rs @@ -10,7 +10,7 @@ use crate::{ BufferSize, CallbackInfo, ChannelCount, Data, DeviceDescription, DeviceDescriptionBuilder, DeviceDirection, DeviceId, DuplexCallbackInfo, DuplexStreamConfig, Error, ErrorKind, SampleFormat, SampleRate, StreamConfig, SupportedBufferSize, SupportedStreamConfig, - SupportedStreamConfigRange, traits::DeviceTrait, + SupportedStreamConfigRange, duplex::validate_duplex_config, traits::DeviceTrait, }; const DEFAULT_NUM_CHANNELS: ChannelCount = 2; @@ -351,7 +351,9 @@ impl DeviceTrait for Device { "Device does not support duplex streams", )); } - validate_duplex_stream_config(&config, input_sample_format, output_sample_format)?; + validate_duplex_config(&config)?; + validate_sample_format(input_sample_format)?; + validate_sample_format(output_sample_format)?; // Keep both `capture` and `playback` monotonic: re-patching cpal's ports to a // different hardware port can move either direction's latency, pulling `device` @@ -440,25 +442,6 @@ fn build_with_timeout( }) } -/// Applies the sample rate/buffer size/channel checks from [`crate::validate_stream_config`] to -/// each direction of a duplex configuration, and checks each direction's sample format. -fn validate_duplex_stream_config( - config: &DuplexStreamConfig, - input_sample_format: SampleFormat, - output_sample_format: SampleFormat, -) -> Result<(), Error> { - let per_direction = |channels| StreamConfig { - channels, - sample_rate: config.sample_rate, - buffer_size: config.buffer_size, - }; - crate::validate_stream_config(&per_direction(config.input_channels))?; - validate_sample_format(input_sample_format)?; - crate::validate_stream_config(&per_direction(config.output_channels))?; - validate_sample_format(output_sample_format)?; - Ok(()) -} - fn validate_sample_format(sample_format: SampleFormat) -> Result<(), Error> { if sample_format != JACK_SAMPLE_FORMAT { return Err(Error::with_message( diff --git a/src/host/jack/stream.rs b/src/host/jack/stream.rs index 83f1b17ce..45fd94194 100644 --- a/src/host/jack/stream.rs +++ b/src/host/jack/stream.rs @@ -4,11 +4,10 @@ use std::sync::{ }; use super::JACK_SAMPLE_FORMAT; -use crate::host::try_emit_error; use crate::{ CallbackInfo, ChannelCount, Data, DuplexCallbackInfo, Error, ErrorKind, FrameCount, ResultExt, Sample, SampleRate, StreamInstant, StreamTimestamp, - host::{ErrorCallbackArc, emit_error, frames_to_duration, wait_for_drain}, + host::{ErrorCallbackArc, emit_error, frames_to_duration, try_emit_error, wait_for_drain}, traits::StreamTrait, }; diff --git a/src/host/pipewire/device.rs b/src/host/pipewire/device.rs index a57503f78..c014ca37a 100644 --- a/src/host/pipewire/device.rs +++ b/src/host/pipewire/device.rs @@ -175,7 +175,7 @@ impl Device { // preventing phase drift between simultaneous input/output streams. properties.insert( *pw::keys::NODE_GROUP, - format!("cpal-{}", std::process::id()), + format!("cpal_pw_node_{}", std::process::id()), ); properties.insert(*pw::keys::NODE_RATE, format!("1/{}", config.sample_rate)); @@ -385,7 +385,7 @@ impl DeviceTrait for Device { let data_callback = crate::host::monotonic_input_callback(data_callback); let start = std::time::Instant::now(); let handle = thread::Builder::new() - .name("pw_in".to_owned()) + .name("cpal_pw_in".to_owned()) .spawn(move || { let _pw = PwInitGuard::new(); let properties = device.pw_properties(DeviceDirection::Input, &config); @@ -583,7 +583,7 @@ impl DeviceTrait for Device { let data_callback = crate::host::monotonic_output_callback(data_callback); let start = std::time::Instant::now(); let handle = thread::Builder::new() - .name("pw_out".to_owned()) + .name("cpal_pw_out".to_owned()) .spawn(move || { let _pw = PwInitGuard::new(); let properties = device.pw_properties(DeviceDirection::Output, &config); diff --git a/src/host/pipewire/rt_promote.rs b/src/host/pipewire/rt_promote.rs index 43aeffab3..528906c21 100644 --- a/src/host/pipewire/rt_promote.rs +++ b/src/host/pipewire/rt_promote.rs @@ -39,7 +39,7 @@ impl RtPromoter { let error_callback_bg = error_callback.clone(); let join = thread::Builder::new() - .name("cpal_rt_promote".to_owned()) + .name("cpal_pw_rt_prom".to_owned()) .spawn(move || { let mut promoted = false; loop { diff --git a/src/host/pipewire/stream.rs b/src/host/pipewire/stream.rs index 3946d1e61..cb4d22fb0 100644 --- a/src/host/pipewire/stream.rs +++ b/src/host/pipewire/stream.rs @@ -738,7 +738,7 @@ where let rate = config.sample_rate as _; let stream = StreamRc::new( core.clone(), - &format!("cpal-playback-{}", std::process::id()), + &format!("cpal_pw_out_{}", std::process::id()), properties, )?; @@ -1013,7 +1013,7 @@ where let rate = config.sample_rate as _; let stream = StreamRc::new( core.clone(), - &format!("cpal-capture-{}", std::process::id()), + &format!("cpal_pw_in_{}", std::process::id()), properties, )?; let listener = stream diff --git a/src/host/pulseaudio.rs b/src/host/pulseaudio.rs index 6a0280b78..c82346fd8 100644 --- a/src/host/pulseaudio.rs +++ b/src/host/pulseaudio.rs @@ -134,7 +134,8 @@ impl Host { // returns, fall through to the next host with no other option than to leak the thread. let (tx, rx) = mpsc::channel(); std::thread::spawn(move || { - let name = CString::new(format!("cpal-pulseaudio-{}", std::process::id())).unwrap(); + let name = + CString::new(format!("cpal_pulseaudio_client_{}", std::process::id())).unwrap(); let _ = tx.send(pulseaudio::Client::from_env(&name)); }); let client = rx diff --git a/src/host/wasapi/stream.rs b/src/host/wasapi/stream.rs index 80169fd71..b62f35ee9 100644 --- a/src/host/wasapi/stream.rs +++ b/src/host/wasapi/stream.rs @@ -379,7 +379,7 @@ impl Stream { .map_err(|e| { Error::with_message( ErrorKind::ResourceExhausted, - format!("Failed to create audio thread: {e}"), + format!("Failed to create WASAPI input worker thread: {e}"), ) })?; @@ -455,7 +455,7 @@ impl Stream { .map_err(|e| { Error::with_message( ErrorKind::ResourceExhausted, - format!("Failed to create audio thread: {e}"), + format!("Failed to create WASAPI output worker thread: {e}"), ) })?; diff --git a/src/host/webaudio.rs b/src/host/webaudio.rs index 422fa26de..1388782c3 100644 --- a/src/host/webaudio.rs +++ b/src/host/webaudio.rs @@ -2,10 +2,6 @@ //! //! Default backend on WebAssembly. -extern crate js_sys; -extern crate wasm_bindgen; -extern crate web_sys; - #[cfg(target_feature = "atomics")] use std::sync::atomic::AtomicU64; use std::{ @@ -37,15 +33,14 @@ type CaptureGraphResult = Result< JsValue, >; +use wasm_bindgen::{JsCast, prelude::*}; #[cfg(not(target_feature = "atomics"))] -use self::web_sys::MediaStream; -use self::{ - wasm_bindgen::{JsCast, prelude::*}, - web_sys::{ - AudioContext, AudioContextOptions, AudioProcessingEvent, GainNode, - MediaStreamAudioSourceNode, ScriptProcessorNode, - }, +use web_sys::MediaStream; +use web_sys::{ + AudioContext, AudioContextOptions, AudioProcessingEvent, GainNode, MediaStreamAudioSourceNode, + ScriptProcessorNode, }; + use crate::{ BufferSize, CallbackInfo, ChannelCount, Data, DeviceDescription, DeviceDescriptionBuilder, DeviceDirection, DeviceId, DuplexCallbackInfo, DuplexStreamConfig, Error, ErrorKind, @@ -588,8 +583,8 @@ impl DeviceTrait for Device { Error::with_message( ErrorKind::UnsupportedConfig, format!( - "Buffer size {} * channel count {} overflows on this platform", - buffer_size_frames, config.channels + "Buffer size {buffer_size_frames} * channel count {} overflows on this platform", + config.channels ), ) })?; diff --git a/src/lib.rs b/src/lib.rs index 1ece644f3..d697c3e60 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -195,26 +195,6 @@ #![cfg_attr(docsrs, feature(doc_cfg))] -// Extern crate declarations with `#[macro_use]` must unfortunately be at crate root. -#[cfg(all( - target_arch = "wasm32", - any(target_os = "emscripten", target_os = "unknown"), - feature = "wasm-bindgen" -))] -extern crate js_sys; -#[cfg(all( - target_arch = "wasm32", - any(target_os = "emscripten", target_os = "unknown"), - feature = "wasm-bindgen" -))] -extern crate wasm_bindgen; -#[cfg(all( - target_arch = "wasm32", - any(target_os = "emscripten", target_os = "unknown"), - feature = "wasm-bindgen" -))] -extern crate web_sys; - pub use device_description::{ DeviceDescription, DeviceDescriptionBuilder, DeviceDirection, DeviceType, InterfaceType, }; diff --git a/src/timestamp.rs b/src/timestamp.rs index a6a961210..4f35fa0e7 100644 --- a/src/timestamp.rs +++ b/src/timestamp.rs @@ -61,6 +61,7 @@ pub struct StreamTimestamp { /// | Same-cycle | AAudio, ALSA, PipeWire, WASAPI (capture) | /// | Next-cycle | CoreAudio | /// | No ordering guarantee | ASIO, JACK | +/// | No reporting | PulseAudio, iOS, WebAudio, AudioWorklet | #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub struct CallbackInfo { pub(crate) timestamp: StreamTimestamp,