diff --git a/.github/workflows/cpal.yml b/.github/workflows/cpal.yml index 8b23ef9..d1ffc16 100644 --- a/.github/workflows/cpal.yml +++ b/.github/workflows/cpal.yml @@ -73,6 +73,8 @@ jobs: run: sudo apt update - name: Install alsa run: sudo apt-get install libasound2-dev + - name: Install libjack + run: sudo apt-get install libjack-jackd2-dev libjack-jackd2-0 - name: Install stable uses: actions-rs/toolchain@v1 with: diff --git a/Cargo.toml b/Cargo.toml index f306b20..29762a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ keywords = ["audio", "sound"] [features] asio = ["asio-sys", "num-traits"] # Only available on Windows. See README for setup instructions. + [dependencies] thiserror = "1.0.2" @@ -30,6 +31,7 @@ lazy_static = "1.3" alsa = "0.4.1" nix = "0.15.0" libc = "0.2.65" +jack = { version = "0.6.5", optional = true } [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] coreaudio-rs = { version = "0.9.1", default-features = false, features = ["audio_unit", "core_audio"] } diff --git a/examples/beep.rs b/examples/beep.rs index dec1fdf..2f36f3f 100644 --- a/examples/beep.rs +++ b/examples/beep.rs @@ -4,7 +4,33 @@ extern crate cpal; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; fn main() -> Result<(), anyhow::Error> { + // Conditionally compile with jack if the feature is specified. + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + // Manually check for flags. Can be passed through cargo with -- e.g. + // cargo run --release --example beep --features jack -- --jack + let host = if std::env::args() + .collect::() + .contains(&String::from("--jack")) + { + cpal::host_from_id(cpal::available_hosts() + .into_iter() + .find(|id| *id == cpal::HostId::Jack) + .expect( + "make sure --features jack is specified. only works on OSes where jack is available", + )).expect("jack host unavailable") + } else { + cpal::default_host() + }; + + #[cfg(any( + not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")), + not(feature = "jack") + ))] let host = cpal::default_host(); + let device = host .default_output_device() .expect("failed to find a default output device"); diff --git a/examples/feedback.rs b/examples/feedback.rs index e44f2d0..72b5841 100644 --- a/examples/feedback.rs +++ b/examples/feedback.rs @@ -16,6 +16,31 @@ use ringbuf::RingBuffer; const LATENCY_MS: f32 = 150.0; fn main() -> Result<(), anyhow::Error> { + // Conditionally compile with jack if the feature is specified. + #[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" + ))] + // Manually check for flags. Can be passed through cargo with -- e.g. + // cargo run --release --example beep --features jack -- --jack + let host = if std::env::args() + .collect::() + .contains(&String::from("--jack")) + { + cpal::host_from_id(cpal::available_hosts() + .into_iter() + .find(|id| *id == cpal::HostId::Jack) + .expect( + "make sure --features jack is specified. only works on OSes where jack is available", + )).expect("jack host unavailable") + } else { + cpal::default_host() + }; + + #[cfg(any( + not(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd")), + not(feature = "jack") + ))] let host = cpal::default_host(); // Default devices. diff --git a/src/host/jack/device.rs b/src/host/jack/device.rs new file mode 100644 index 0000000..a98d813 --- /dev/null +++ b/src/host/jack/device.rs @@ -0,0 +1,275 @@ +use crate::{ + BackendSpecificError, BuildStreamError, Data, DefaultStreamConfigError, DeviceNameError, + InputCallbackInfo, OutputCallbackInfo, SampleFormat, SampleRate, StreamConfig, StreamError, + SupportedBufferSize, SupportedStreamConfig, SupportedStreamConfigRange, + SupportedStreamConfigsError, +}; +use std::hash::{Hash, Hasher}; +use traits::DeviceTrait; + +use super::stream::Stream; +use super::JACK_SAMPLE_FORMAT; + +pub type SupportedInputConfigs = std::vec::IntoIter; +pub type SupportedOutputConfigs = std::vec::IntoIter; + +const DEFAULT_NUM_CHANNELS: u16 = 2; +const DEFAULT_SUPPORTED_CHANNELS: [u16; 10] = [1, 2, 4, 6, 8, 16, 24, 32, 48, 64]; + +/// If a device is for input or output. +/// Until we have duplex stream support JACK clients and CPAL devices for JACK will be either input or output. +#[derive(Clone, Debug)] +pub enum DeviceType { + InputDevice, + OutputDevice, +} +#[derive(Clone, Debug)] +pub struct Device { + name: String, + sample_rate: SampleRate, + buffer_size: SupportedBufferSize, + device_type: DeviceType, + start_server_automatically: bool, + connect_ports_automatically: bool, +} + +impl Device { + fn new_device( + name: String, + connect_ports_automatically: bool, + start_server_automatically: bool, + device_type: DeviceType, + ) -> Result { + // ClientOptions are bit flags that you can set with the constants provided + let client_options = super::get_client_options(start_server_automatically); + + // Create a dummy client to find out the sample rate of the server to be able to provide it as a possible config. + // This client will be dropped and a new one will be created when making the stream. + // This is a hack due to the fact that the Client must be moved to create the AsyncClient. + match super::get_client(&name, client_options) { + Ok(client) => Ok(Device { + // The name given to the client by JACK, could potentially be different from the name supplied e.g.if there is a name collision + name: client.name().to_string(), + sample_rate: SampleRate(client.sample_rate() as u32), + buffer_size: SupportedBufferSize::Range { + min: client.buffer_size(), + max: client.buffer_size(), + }, + device_type, + start_server_automatically, + connect_ports_automatically, + }), + Err(e) => Err(e), + } + } + + pub fn default_output_device( + name: &str, + connect_ports_automatically: bool, + start_server_automatically: bool, + ) -> Result { + let output_client_name = format!("{}_out", name); + Device::new_device( + output_client_name, + connect_ports_automatically, + start_server_automatically, + DeviceType::OutputDevice, + ) + } + + pub fn default_input_device( + name: &str, + connect_ports_automatically: bool, + start_server_automatically: bool, + ) -> Result { + let input_client_name = format!("{}_in", name); + Device::new_device( + input_client_name, + connect_ports_automatically, + start_server_automatically, + DeviceType::InputDevice, + ) + } + + pub fn default_config(&self) -> Result { + let channels = DEFAULT_NUM_CHANNELS; + let sample_rate = self.sample_rate; + let buffer_size = self.buffer_size.clone(); + // The sample format for JACK audio ports is always "32 bit float mono audio" in the current implementation. + // Custom formats are allowed within JACK, but this is of niche interest. + // The format can be found programmatically by calling jack::PortSpec::port_type() on a created port. + let sample_format = JACK_SAMPLE_FORMAT; + Ok(SupportedStreamConfig { + channels, + sample_rate, + buffer_size, + sample_format, + }) + } + + pub fn supported_configs(&self) -> Vec { + let f = match self.default_config() { + Err(_) => return vec![], + Ok(f) => f, + }; + + let mut supported_configs = vec![]; + + for &channels in DEFAULT_SUPPORTED_CHANNELS.iter() { + supported_configs.push(SupportedStreamConfigRange { + channels, + min_sample_rate: f.sample_rate, + max_sample_rate: f.sample_rate, + buffer_size: f.buffer_size.clone(), + sample_format: f.sample_format.clone(), + }); + } + supported_configs + } + + pub fn is_input(&self) -> bool { + match self.device_type { + DeviceType::InputDevice => true, + _ => false, + } + } + + pub fn is_output(&self) -> bool { + match self.device_type { + DeviceType::OutputDevice => true, + _ => false, + } + } +} + +impl DeviceTrait for Device { + type SupportedInputConfigs = SupportedInputConfigs; + type SupportedOutputConfigs = SupportedOutputConfigs; + type Stream = Stream; + + fn name(&self) -> Result { + Ok(self.name.clone()) + } + + fn supported_input_configs( + &self, + ) -> Result { + Ok(self.supported_configs().into_iter()) + } + + fn supported_output_configs( + &self, + ) -> Result { + Ok(self.supported_configs().into_iter()) + } + + /// Returns the default input config + /// The sample format for JACK audio ports is always "32 bit float mono audio" unless using a custom type. + /// The sample rate is set by the JACK server. + fn default_input_config(&self) -> Result { + self.default_config() + } + + /// Returns the default output config + /// The sample format for JACK audio ports is always "32 bit float mono audio" unless using a custom type. + /// The sample rate is set by the JACK server. + fn default_output_config(&self) -> Result { + self.default_config() + } + + fn build_input_stream_raw( + &self, + conf: &StreamConfig, + sample_format: SampleFormat, + data_callback: D, + error_callback: E, + ) -> Result + where + D: FnMut(&Data, &InputCallbackInfo) + Send + 'static, + E: FnMut(StreamError) + Send + 'static, + { + if let DeviceType::OutputDevice = &self.device_type { + // Trying to create an input stream from an output device + return Err(BuildStreamError::StreamConfigNotSupported); + } + if conf.sample_rate != self.sample_rate || sample_format != JACK_SAMPLE_FORMAT { + return Err(BuildStreamError::StreamConfigNotSupported); + } + // The settings should be fine, create a Client + let client_options = super::get_client_options(self.start_server_automatically); + let client; + match super::get_client(&self.name, client_options) { + Ok(c) => client = c, + Err(e) => { + return Err(BuildStreamError::BackendSpecific { + err: BackendSpecificError { + description: e.to_string(), + }, + }) + } + }; + let mut stream = Stream::new_input(client, conf.channels, data_callback, error_callback); + + if self.connect_ports_automatically { + stream.connect_to_system_inputs(); + } + + Ok(stream) + } + + fn build_output_stream_raw( + &self, + conf: &StreamConfig, + sample_format: SampleFormat, + data_callback: D, + error_callback: E, + ) -> Result + where + D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static, + E: FnMut(StreamError) + Send + 'static, + { + if let DeviceType::InputDevice = &self.device_type { + // Trying to create an output stream from an input device + return Err(BuildStreamError::StreamConfigNotSupported); + } + if conf.sample_rate != self.sample_rate || sample_format != JACK_SAMPLE_FORMAT { + return Err(BuildStreamError::StreamConfigNotSupported); + } + + // The settings should be fine, create a Client + let client_options = super::get_client_options(self.start_server_automatically); + let client; + match super::get_client(&self.name, client_options) { + Ok(c) => client = c, + Err(e) => { + return Err(BuildStreamError::BackendSpecific { + err: BackendSpecificError { + description: e.to_string(), + }, + }) + } + }; + let mut stream = Stream::new_output(client, conf.channels, data_callback, error_callback); + + if self.connect_ports_automatically { + stream.connect_to_system_outputs(); + } + + Ok(stream) + } +} + +impl PartialEq for Device { + fn eq(&self, other: &Self) -> bool { + // Device::name() can never fail in this implementation + self.name().unwrap() == other.name().unwrap() + } +} + +impl Eq for Device {} + +impl Hash for Device { + fn hash(&self, state: &mut H) { + self.name().unwrap().hash(state); + } +} diff --git a/src/host/jack/mod.rs b/src/host/jack/mod.rs new file mode 100644 index 0000000..d52624f --- /dev/null +++ b/src/host/jack/mod.rs @@ -0,0 +1,180 @@ +extern crate jack; + +use crate::{DevicesError, SampleFormat, SupportedStreamConfigRange}; +use traits::HostTrait; + +mod device; +pub use self::device::Device; +pub use self::stream::Stream; +mod stream; + +const JACK_SAMPLE_FORMAT: SampleFormat = SampleFormat::F32; + +pub type SupportedInputConfigs = std::vec::IntoIter; +pub type SupportedOutputConfigs = std::vec::IntoIter; +pub type Devices = std::vec::IntoIter; + +/// The JACK Host type +#[derive(Debug)] +pub struct Host { + /// The name that the client will have in JACK. + /// Until we have duplex streams two clients will be created adding "out" or "in" to the name + /// since names have to be unique. + name: String, + /// If ports are to be connected to the system (soundcard) ports automatically (default is true). + connect_ports_automatically: bool, + /// If the JACK server should be started automatically if it isn't already when creating a Client (default is false). + start_server_automatically: bool, + /// A list of the devices that have been created from this Host. + devices_created: Vec, +} + +impl Host { + pub fn new() -> Result { + let mut host = Host { + name: "cpal_client".to_owned(), + connect_ports_automatically: true, + start_server_automatically: false, + devices_created: vec![], + }; + // Devices don't exist for JACK, they have to be created + host.initialize_default_devices(); + Ok(host) + } + /// Set whether the ports should automatically be connected to system + /// (default is true) + pub fn set_connect_automatically(&mut self, do_connect: bool) { + self.connect_ports_automatically = do_connect; + } + /// Set whether a JACK server should be automatically started if it isn't already. + /// (default is false) + pub fn set_start_server_automatically(&mut self, do_start_server: bool) { + self.start_server_automatically = do_start_server; + } + + pub fn input_device_with_name(&mut self, name: &str) -> Option { + self.name = name.to_owned(); + self.default_input_device() + } + + pub fn output_device_with_name(&mut self, name: &str) -> Option { + self.name = name.to_owned(); + self.default_output_device() + } + + fn initialize_default_devices(&mut self) { + let in_device_res = Device::default_input_device( + &self.name, + self.connect_ports_automatically, + self.start_server_automatically, + ); + + match in_device_res { + Ok(device) => self.devices_created.push(device), + Err(err) => { + println!("{}", err); + } + } + + let out_device_res = Device::default_output_device( + &self.name, + self.connect_ports_automatically, + self.start_server_automatically, + ); + match out_device_res { + Ok(device) => self.devices_created.push(device), + Err(err) => { + println!("{}", err); + } + } + } +} + +impl HostTrait for Host { + type Device = Device; + type Devices = Devices; + + /// JACK is available if + /// - the jack feature flag is set + /// - libjack is installed (wouldn't compile without it) + /// - the JACK server can be started + /// + /// If the code compiles the necessary jack libraries are installed. + /// There is no way to know if the user has set up a correct JACK configuration e.g. with qjackctl. + /// Users can choose to automatically start the server if it isn't already started when creating a client + /// so checking if the server is running could give a false negative in some use cases. + /// For these reasons this function should always return true. + fn is_available() -> bool { + true + } + + fn devices(&self) -> Result { + Ok(self.devices_created.clone().into_iter()) + } + + fn default_input_device(&self) -> Option { + for device in &self.devices_created { + if device.is_input() { + return Some(device.clone()); + } + } + None + } + + fn default_output_device(&self) -> Option { + for device in &self.devices_created { + if device.is_output() { + return Some(device.clone()); + } + } + None + } +} + +fn get_client_options(start_server_automatically: bool) -> jack::ClientOptions { + let mut client_options = jack::ClientOptions::empty(); + client_options.set( + jack::ClientOptions::NO_START_SERVER, + !start_server_automatically, + ); + client_options +} + +fn get_client(name: &str, client_options: jack::ClientOptions) -> Result { + let c_res = jack::Client::new(name, client_options); + match c_res { + Ok((client, status)) => { + // The ClientStatus can tell us many things + if status.intersects(jack::ClientStatus::SERVER_ERROR) { + return Err(String::from( + "There was an error communicating with the JACK server!", + )); + } else if status.intersects(jack::ClientStatus::SERVER_FAILED) { + return Err(String::from("Could not connect to the JACK server!")); + } else if status.intersects(jack::ClientStatus::VERSION_ERROR) { + return Err(String::from( + "Error connecting to JACK server: Client's protocol version does not match!", + )); + } else if status.intersects(jack::ClientStatus::INIT_FAILURE) { + return Err(String::from( + "Error connecting to JACK server: Unable to initialize client!", + )); + } else if status.intersects(jack::ClientStatus::SHM_FAILURE) { + return Err(String::from( + "Error connecting to JACK server: Unable to access shared memory!", + )); + } else if status.intersects(jack::ClientStatus::NO_SUCH_CLIENT) { + return Err(String::from( + "Error connecting to JACK server: Requested client does not exist!", + )); + } else if status.intersects(jack::ClientStatus::INVALID_OPTION) { + return Err(String::from("Error connecting to JACK server: The operation contained an invalid or unsupported option!")); + } + + return Ok(client); + } + Err(e) => { + return Err(format!("Failed to open client because of error: {:?}", e)); + } + } +} diff --git a/src/host/jack/stream.rs b/src/host/jack/stream.rs new file mode 100644 index 0000000..6086302 --- /dev/null +++ b/src/host/jack/stream.rs @@ -0,0 +1,481 @@ +use crate::ChannelCount; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use traits::StreamTrait; + +use crate::{ + BackendSpecificError, Data, InputCallbackInfo, OutputCallbackInfo, PauseStreamError, + PlayStreamError, SampleRate, StreamError, +}; + +use super::JACK_SAMPLE_FORMAT; +pub struct Stream { + // TODO: It might be faster to send a message when playing/pausing than to check this every iteration + playing: Arc, + async_client: jack::AsyncClient, + // Port names are stored in order to connect them to other ports in jack automatically + input_port_names: Vec, + output_port_names: Vec, +} + +impl Stream { + // TODO: Return error messages + pub fn new_input( + client: jack::Client, + channels: ChannelCount, + data_callback: D, + mut error_callback: E, + ) -> Stream + where + D: FnMut(&Data, &InputCallbackInfo) + Send + 'static, + E: FnMut(StreamError) + Send + 'static, + { + let mut ports = vec![]; + let mut port_names: Vec = vec![]; + // Create ports + for i in 0..channels { + let port_try = client.register_port(&format!("in_{}", i), jack::AudioIn::default()); + match port_try { + Ok(port) => { + // Get the port name in order to later connect it automatically + if let Ok(port_name) = port.name() { + port_names.push(port_name); + } + // Store the port into a Vec to move to the ProcessHandler + ports.push(port); + } + Err(e) => { + // If port creation failed, send the error back via the error_callback + error_callback( + BackendSpecificError { + description: e.to_string(), + } + .into(), + ); + } + } + } + + let playing = Arc::new(AtomicBool::new(true)); + + let input_process_handler = LocalProcessHandler::new( + vec![], + ports, + SampleRate(client.sample_rate() as u32), + Some(Box::new(data_callback)), + None, + playing.clone(), + client.buffer_size() as usize, + ); + + let notification_handler = JackNotificationHandler::new(error_callback); + + let async_client = client + .activate_async(notification_handler, input_process_handler) + .unwrap(); + + Stream { + playing, + async_client, + input_port_names: port_names, + output_port_names: vec![], + } + } + + pub fn new_output( + client: jack::Client, + channels: ChannelCount, + data_callback: D, + mut error_callback: E, + ) -> Stream + where + D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static, + E: FnMut(StreamError) + Send + 'static, + { + let mut ports = vec![]; + let mut port_names: Vec = vec![]; + // Create ports + for i in 0..channels { + let port_try = client.register_port(&format!("out_{}", i), jack::AudioOut::default()); + match port_try { + Ok(port) => { + // Get the port name in order to later connect it automatically + if let Ok(port_name) = port.name() { + port_names.push(port_name); + } + // Store the port into a Vec to move to the ProcessHandler + ports.push(port); + } + Err(e) => { + // If port creation failed, send the error back via the error_callback + error_callback( + BackendSpecificError { + description: e.to_string(), + } + .into(), + ); + } + } + } + + let playing = Arc::new(AtomicBool::new(true)); + + let output_process_handler = LocalProcessHandler::new( + ports, + vec![], + SampleRate(client.sample_rate() as u32), + None, + Some(Box::new(data_callback)), + playing.clone(), + client.buffer_size() as usize, + ); + + let notification_handler = JackNotificationHandler::new(error_callback); + + let async_client = client + .activate_async(notification_handler, output_process_handler) + .unwrap(); + + Stream { + playing, + async_client, + input_port_names: vec![], + output_port_names: port_names, + } + } + + /// Connect to the standard system outputs in jack, system:playback_1 and system:playback_2 + /// This has to be done after the client is activated, doing it just after creating the ports doesn't work. + pub fn connect_to_system_outputs(&mut self) { + // Get the system ports + let system_ports = self.async_client.as_client().ports( + Some("system:playback_.*"), + None, + jack::PortFlags::empty(), + ); + + // Connect outputs from this client to the system playback inputs + for i in 0..self.output_port_names.len() { + if i >= system_ports.len() { + break; + } + match self + .async_client + .as_client() + .connect_ports_by_name(&self.output_port_names[i], &system_ports[i]) + { + Ok(_) => (), + Err(e) => println!("Unable to connect to port with error {}", e), + } + } + } + + /// Connect to the standard system outputs in jack, system:capture_1 and system:capture_2 + /// This has to be done after the client is activated, doing it just after creating the ports doesn't work. + pub fn connect_to_system_inputs(&mut self) { + // Get the system ports + let system_ports = self.async_client.as_client().ports( + Some("system:capture_.*"), + None, + jack::PortFlags::empty(), + ); + + // Connect outputs from this client to the system playback inputs + for i in 0..self.input_port_names.len() { + if i >= system_ports.len() { + break; + } + match self + .async_client + .as_client() + .connect_ports_by_name(&system_ports[i], &self.input_port_names[i]) + { + Ok(_) => (), + Err(e) => println!("Unable to connect to port with error {}", e), + } + } + } +} + +impl StreamTrait for Stream { + fn play(&self) -> Result<(), PlayStreamError> { + self.playing.store(true, Ordering::SeqCst); + Ok(()) + } + + fn pause(&self) -> Result<(), PauseStreamError> { + self.playing.store(false, Ordering::SeqCst); + Ok(()) + } +} + +struct LocalProcessHandler { + /// No new ports are allowed to be created after the creation of the LocalProcessHandler as that would invalidate the buffer sizes + out_ports: Vec>, + in_ports: Vec>, + + sample_rate: SampleRate, + input_data_callback: Option>, + output_data_callback: Option>, + + temp_input_buffer: Vec, + + // JACK audio samples are 32 bit float (unless you do some custom dark magic) + temp_output_buffer: Vec, + /// The number of frames in the temp_output_buffer + temp_output_buffer_size_in_frames: usize, + temp_output_buffer_frames_index: usize, + playing: Arc, + creation_timestamp: std::time::Instant, +} + +impl LocalProcessHandler { + fn new( + out_ports: Vec>, + in_ports: Vec>, + sample_rate: SampleRate, + input_data_callback: Option>, + output_data_callback: Option< + Box, + >, + playing: Arc, + buffer_size: usize, + ) -> Self { + // buffer_size is the maximum number of samples per port JACK can request/provide in a single call + // If it can be fewer than that per call the temp_input_buffer needs to be the smallest multiple of that. + let temp_input_buffer = vec![0.0; in_ports.len() * buffer_size]; + + let temp_output_buffer = vec![0.0; out_ports.len() * buffer_size]; + + // let out_port_buffers = Vec::with_capacity(out_ports.len()); + // let in_port_buffers = Vec::with_capacity(in_ports.len()); + + LocalProcessHandler { + out_ports, + in_ports, + // out_port_buffers, + // in_port_buffers, + sample_rate, + input_data_callback, + output_data_callback, + temp_input_buffer, + temp_output_buffer, + temp_output_buffer_size_in_frames: buffer_size, + temp_output_buffer_frames_index: 0, + playing, + creation_timestamp: std::time::Instant::now(), + } + } +} + +fn temp_output_buffer_to_data(temp_output_buffer: &mut Vec) -> Data { + let data = temp_output_buffer.as_mut_ptr() as *mut (); + let len = temp_output_buffer.len(); + let data = unsafe { Data::from_parts(data, len, JACK_SAMPLE_FORMAT) }; + data +} + +fn temp_input_buffer_to_data(temp_input_buffer: &mut Vec, total_buffer_size: usize) -> Data { + let slice = &temp_input_buffer[0..total_buffer_size]; + let data = slice.as_ptr() as *mut (); + let len = total_buffer_size; + let data = unsafe { Data::from_parts(data, len, JACK_SAMPLE_FORMAT) }; + data +} + +impl jack::ProcessHandler for LocalProcessHandler { + fn process(&mut self, _: &jack::Client, process_scope: &jack::ProcessScope) -> jack::Control { + if !self.playing.load(Ordering::SeqCst) { + return jack::Control::Continue; + } + + let current_frame_count = process_scope.n_frames() as usize; + + // Get timestamp data + let cycle_times = process_scope.cycle_times(); + let current_start_usecs = match cycle_times { + Ok(times) => times.current_usecs, + Err(_) => { + // jack was unable to get the current time information + // Fall back to using Instants + let now = std::time::Instant::now(); + let duration = now.duration_since(self.creation_timestamp); + duration.as_micros() as u64 + } + }; + let start_cycle_instant = micros_to_stream_instant(current_start_usecs); + let start_callback_instant = start_cycle_instant + .add(frames_to_duration( + process_scope.frames_since_cycle_start() as usize, + self.sample_rate, + )) + .expect("`playback` occurs beyond representation supported by `StreamInstant`"); + + if let Some(input_callback) = &mut self.input_data_callback { + // Let's get the data from the input ports and run the callback + + let num_in_channels = self.in_ports.len(); + + // Read the data from the input ports into the temporary buffer + // Go through every channel and store its data in the temporary input buffer + for ch_ix in 0..num_in_channels { + let input_channel = &self.in_ports[ch_ix].as_slice(process_scope); + for i in 0..current_frame_count { + self.temp_input_buffer[ch_ix + i * num_in_channels] = input_channel[i]; + } + } + // Create a slice of exactly current_frame_count frames + let data = temp_input_buffer_to_data( + &mut self.temp_input_buffer, + current_frame_count * num_in_channels, + ); + // Create timestamp + let frames_since_cycle_start = process_scope.frames_since_cycle_start() as usize; + let duration_since_cycle_start = + frames_to_duration(frames_since_cycle_start, self.sample_rate); + let callback = start_callback_instant + .add(duration_since_cycle_start) + .expect("`playback` occurs beyond representation supported by `StreamInstant`"); + let capture = start_callback_instant; + let timestamp = crate::InputStreamTimestamp { callback, capture }; + let info = crate::InputCallbackInfo { timestamp }; + input_callback(&data, &info); + } + + if let Some(output_callback) = &mut self.output_data_callback { + let num_out_channels = self.out_ports.len(); + + // Run the output callback on the temporary output buffer until we have filled the output ports + // JACK ports each provide a mutable slice to be filled with samples whereas CPAL uses interleaved + // channels. The formats therefore have to be bridged. + for i in 0..current_frame_count { + // Check if we have gotten all of the frames from the temp_output_buffer + if self.temp_output_buffer_frames_index == self.temp_output_buffer_size_in_frames { + // Get new samples if the temporary buffer is depleted. This can theoretically happen + // several times per cycle or once every few cycles if the buffer size changes, but in practice + // it should generally happen once per cycle if the buffer size is not changed. + let mut data = temp_output_buffer_to_data(&mut self.temp_output_buffer); + // Create timestamp + let frames_since_cycle_start = + process_scope.frames_since_cycle_start() as usize; + let duration_since_cycle_start = + frames_to_duration(frames_since_cycle_start, self.sample_rate); + let callback = start_callback_instant + .add(duration_since_cycle_start) + .expect( + "`playback` occurs beyond representation supported by `StreamInstant`", + ); + let buffer_duration = frames_to_duration(current_frame_count, self.sample_rate); + let playback = start_cycle_instant.add(buffer_duration).expect( + "`playback` occurs beyond representation supported by `StreamInstant`", + ); + let timestamp = crate::OutputStreamTimestamp { callback, playback }; + let info = crate::OutputCallbackInfo { timestamp }; + output_callback(&mut data, &info); + self.temp_output_buffer_frames_index = 0; + } + // Write the interleaved samples e.g. [l0, r0, l1, r1, ..] to each output buffer + for ch_ix in 0..num_out_channels { + // TODO: It should be marginally faster to store pointers to these slices, but I don't know how + // to avoid lifetime issues and allocation + let output_channel = &mut self.out_ports[ch_ix].as_mut_slice(process_scope); + output_channel[i] = self.temp_output_buffer + [ch_ix + self.temp_output_buffer_frames_index * num_out_channels]; + } + // Count the number of frames that have been read from the temp buffer + self.temp_output_buffer_frames_index += 1; + } + } + + // Continue as normal + jack::Control::Continue + } +} + +fn micros_to_stream_instant(micros: u64) -> crate::StreamInstant { + let nanos = micros * 1000; + let secs = nanos / 1_000_000; + let subsec_nanos = nanos - secs * 1_000_000_000; + crate::StreamInstant::new(secs as i64, subsec_nanos as u32) +} + +// Convert the given duration in frames at the given sample rate to a `std::time::Duration`. +fn frames_to_duration(frames: usize, rate: crate::SampleRate) -> std::time::Duration { + let secsf = frames as f64 / rate.0 as f64; + let secs = secsf as u64; + let nanos = ((secsf - secs as f64) * 1_000_000_000.0) as u32; + std::time::Duration::new(secs, nanos) +} + +/// Receives notifications from the JACK server. It is unclear if this may be run concurrent with itself under JACK2 specs +/// so it needs to be Sync. +struct JackNotificationHandler { + error_callback_ptr: Arc>>, + init_block_size_flag: Arc, + init_sample_rate_flag: Arc, +} + +impl JackNotificationHandler { + pub fn new(error_callback: E) -> Self + where + E: FnMut(StreamError) + Send + 'static, + { + JackNotificationHandler { + error_callback_ptr: Arc::new(Mutex::new(Box::new(error_callback))), + init_block_size_flag: Arc::new(AtomicBool::new(false)), + init_sample_rate_flag: Arc::new(AtomicBool::new(false)), + } + } + + fn send_error(&mut self, description: String) { + // This thread isn't the audio thread, it's fine to block + if let Ok(mut mutex_guard) = self.error_callback_ptr.lock() { + let err = &mut *mutex_guard; + err(BackendSpecificError { description }.into()); + } + } +} + +impl jack::NotificationHandler for JackNotificationHandler { + fn shutdown(&mut self, _status: jack::ClientStatus, reason: &str) { + self.send_error(format!("JACK was shut down for reason: {}", reason)); + } + + fn sample_rate(&mut self, _: &jack::Client, srate: jack::Frames) -> jack::Control { + match self.init_sample_rate_flag.load(Ordering::SeqCst) { + false => { + // One of these notifications is sent every time a client is started. + self.init_sample_rate_flag.store(true, Ordering::SeqCst); + jack::Control::Continue + } + true => { + self.send_error(format!("sample rate changed to: {}", srate)); + // Since CPAL currently has no way of signaling a sample rate change in order to make + // all necessary changes that would bring we choose to quit. + jack::Control::Quit + } + } + } + + fn buffer_size(&mut self, _: &jack::Client, size: jack::Frames) -> jack::Control { + match self.init_block_size_flag.load(Ordering::SeqCst) { + false => { + // One of these notifications is sent every time a client is started. + self.init_block_size_flag.store(true, Ordering::SeqCst) + } + true => { + self.send_error(format!("buffer size changed to: {}", size)); + } + } + + // The current implementation should work even if the buffer size changes, although + // potentially with poorer performance. However, reallocating the temporary processing + // buffers would be expensive so we choose to just continue in this case. + jack::Control::Continue + } + + fn xrun(&mut self, _: &jack::Client) -> jack::Control { + self.send_error(String::from("xrun (buffer over or under run)")); + jack::Control::Continue + } +} diff --git a/src/host/mod.rs b/src/host/mod.rs index 9c70253..534939a 100644 --- a/src/host/mod.rs +++ b/src/host/mod.rs @@ -6,6 +6,11 @@ pub(crate) mod asio; pub(crate) mod coreaudio; #[cfg(target_os = "emscripten")] pub(crate) mod emscripten; +#[cfg(all( + any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd"), + feature = "jack" +))] +pub(crate) mod jack; pub(crate) mod null; #[cfg(windows)] pub(crate) mod wasapi; diff --git a/src/platform/mod.rs b/src/platform/mod.rs index 6cc4171..311a902 100644 --- a/src/platform/mod.rs +++ b/src/platform/mod.rs @@ -453,7 +453,17 @@ mod platform_impl { SupportedInputConfigs as AlsaSupportedInputConfigs, SupportedOutputConfigs as AlsaSupportedOutputConfigs, }; + #[cfg(feature = "jack")] + pub use crate::host::jack::{ + Device as JackDevice, Devices as JackDevices, Host as JackHost, Stream as JackStream, + SupportedInputConfigs as JackSupportedInputConfigs, + SupportedOutputConfigs as JackSupportedOutputConfigs, + }; + #[cfg(feature = "jack")] + impl_platform_host!(Jack jack "JACK", Alsa alsa "ALSA"); + + #[cfg(not(feature = "jack"))] impl_platform_host!(Alsa alsa "ALSA"); /// The default host for the current compilation target platform.