### Sample Trait Examples Source: https://docs.rs/cpal/0.17.0/cpal/trait.Sample.html Illustrative examples demonstrating the usage of the Sample trait's methods and constants. ```APIDOC ## §Example ```rust use dasp_sample::{I24, Sample}; fn main() { assert_eq!((-1.0).to_sample::(), 0); assert_eq!(0.0.to_sample::(), 128); assert_eq!(0i32.to_sample::(), 2_147_483_648); assert_eq!(I24::new(0).unwrap(), Sample::from_sample(0.0)); assert_eq!(0.0, Sample::EQUILIBRIUM); } ``` ## Required Associated Constants§ #### const EQUILIBRIUM: Self ##### §Example ```rust use dasp_sample::Sample; fn main() { assert_eq!(0.0, f32::EQUILIBRIUM); assert_eq!(0, i32::EQUILIBRIUM); assert_eq!(128, u8::EQUILIBRIUM); assert_eq!(32_768_u16, Sample::EQUILIBRIUM); } ``` ## Provided Associated Constants§ #### const IDENTITY: Self::Float = ::IDENTITY ##### §Example ```rust use dasp_sample::{Sample, U48}; fn main() { assert_eq!(1.0, f32::IDENTITY); assert_eq!(1.0, i8::IDENTITY); assert_eq!(1.0, u8::IDENTITY); assert_eq!(1.0, U48::IDENTITY); } ``` ## Provided Methods§ #### fn to_sample(self) -> S ##### §Example ```rust use dasp_sample::Sample; fn main() { assert_eq!(0.0.to_sample::(), 0); assert_eq!(0.0.to_sample::(), 128); assert_eq!((-1.0).to_sample::(), 0); } ``` #### fn from_sample(s: S) -> Self ##### §Example ```rust use dasp_sample::{Sample, I24}; fn main() { assert_eq!(f32::from_sample(128_u8), 0.0); assert_eq!(i8::from_sample(-1.0), -128); assert_eq!(I24::from_sample(0.0), I24::new(0).unwrap()); } ``` ``` -------------------------------- ### Example Usage of BufferSize Source: https://docs.rs/cpal/0.17.0/cpal/enum.BufferSize.html Demonstrates how to query supported buffer sizes and set a fixed buffer size for low latency. ```APIDOC ### §Example ```rust use cpal::traits::{DeviceTrait, HostTrait}; use cpal::{BufferSize, SupportedBufferSize}; let host = cpal::default_host(); let device = host.default_output_device().unwrap(); let config = device.default_output_config().unwrap(); // Check supported buffer size range match config.buffer_size() { SupportedBufferSize::Range { min, max } => { println!("Buffer size range: {} - {}", min, max); // Request a small buffer for low latency let mut stream_config = config.config(); stream_config.buffer_size = BufferSize::Fixed(256); } SupportedBufferSize::Unknown => { // Platform doesn't expose buffer size control println!("Buffer size cannot be queried on this platform"); } } ``` ``` -------------------------------- ### Get Sample Format Source: https://docs.rs/cpal/0.17.0/cpal/struct.Data.html Returns the sample format of the internal audio data. ```rust pub fn sample_format(&self) -> SampleFormat ``` -------------------------------- ### Sample Trait Usage Example Source: https://docs.rs/cpal/0.17.0/cpal/trait.Sample.html Demonstrates basic usage of the Sample trait for conversions and equilibrium checks. ```rust use dasp_sample::{I24, Sample}; fn main() { assert_eq!((-1.0).to_sample::(), 0); assert_eq!(0.0.to_sample::(), 128); assert_eq!(0i32.to_sample::(), 2_147_483_648); assert_eq!(I24::new(0).unwrap(), Sample::from_sample(0.0)); assert_eq!(0.0, Sample::EQUILIBRIUM); } ``` -------------------------------- ### Play Stream Source: https://docs.rs/cpal/0.17.0/cpal/index.html Starts the audio stream playback. ```rust stream.play().unwrap(); ``` -------------------------------- ### Configure Server Auto-Start Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Configures whether the JACK server should automatically start if not already running. When enabled, attempting to create a JACK client will start the JACK server if it’s not running. When disabled (default), client creation fails if the server is not running. ```rust pub fn set_start_server_automatically(&mut self, do_start_server: bool) ``` -------------------------------- ### Get Supported Output Configurations Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Returns an iterator over all supported output stream formats for the device. This can fail if the device becomes invalid. ```rust fn supported_output_configs( &self, ) -> Result ``` -------------------------------- ### HostTrait::default_input_device() Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Gets the system's default audio input device. Returns None if no input device is available. ```rust fn default_input_device(&self) -> Option; ``` -------------------------------- ### Requesting a Fixed Buffer Size Source: https://docs.rs/cpal/0.17.0/cpal/enum.BufferSize.html Example of checking the supported buffer size range and requesting a fixed size for low-latency audio. ```rust use cpal::traits::{DeviceTrait, HostTrait}; use cpal::{BufferSize, SupportedBufferSize}; let host = cpal::default_host(); let device = host.default_output_device().unwrap(); let config = device.default_output_config().unwrap(); // Check supported buffer size range match config.buffer_size() { SupportedBufferSize::Range { min, max } => { println!("Buffer size range: {} - {}", min, max); // Request a small buffer for low latency let mut stream_config = config.config(); stream_config.buffer_size = BufferSize::Fixed(256); } SupportedBufferSize::Unknown => { // Platform doesn't expose buffer size control println!("Buffer size cannot be queried on this platform"); } } ``` -------------------------------- ### HostTrait::default_output_device() Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Gets the system's default audio output device. Returns None if no output device is available. ```rust fn default_output_device(&self) -> Option; ``` -------------------------------- ### Get Supported Input Configurations Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Returns an iterator over all supported input stream formats for the device. This can fail if the device becomes invalid. ```rust fn supported_input_configs( &self, ) -> Result ``` -------------------------------- ### Get Output Device by Name Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Retrieves an output audio device by its name. Returns `None` if no device with the specified name is found. ```rust pub fn output_device_with_name(&mut self, name: &str) -> Option ``` -------------------------------- ### Play Stream Method Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.StreamTrait.html Runs the audio stream. It's important to call `play` after stream creation if immediate playback is expected, as not all platforms automatically start streams. ```rust fn play(&self) -> Result<(), PlayStreamError>; ``` -------------------------------- ### Get Input Device by Name Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Retrieves an input audio device by its name. Returns `None` if no device with the specified name is found. ```rust pub fn input_device_with_name(&mut self, name: &str) -> Option ``` -------------------------------- ### Get Available Devices Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Returns an iterator over all `Device`s currently available to the JACK host on the system. This operation can fail, returning a `DevicesError`. ```rust fn devices(&self) -> Result ``` -------------------------------- ### Get Default Output Device Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Retrieves the default output audio device on the system. Returns `None` if no default output device is found. ```rust fn default_output_device(&self) -> Option ``` -------------------------------- ### Get Default Input Device Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Retrieves the default input audio device on the system. Returns `None` if no default input device is found. ```rust fn default_input_device(&self) -> Option ``` -------------------------------- ### Get Default Output Configuration Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Retrieves the default output stream format for the audio device. This method may return an error if the device is no longer valid. ```rust fn default_output_config( &self, ) -> Result ``` -------------------------------- ### Convert CustomHost to Host Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.CustomHost.html Demonstrates how to initialize a CustomHost and convert it into a standard cpal::Host. ```rust let custom = cpal::platform::CustomHost::from_host(/* ... */); let host = cpal::Host::from(custom); ``` -------------------------------- ### Convert CustomDevice to Device Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.CustomDevice.html Demonstrates how to instantiate a CustomDevice and convert it into a standard cpal::Device. ```rust let custom = cpal::platform::CustomDevice::from_device(/* ... */); let device = cpal::Device::from(custom); ``` ```rust let custom = cpal::platform::CustomDevice::from_device(/* ... */); let device = cpal::Device::from(custom); let stream_builder = rodio::OutputStreamBuilder::from_device(device).expect("failed to build stream"); ``` -------------------------------- ### Initialize Host Source: https://docs.rs/cpal/0.17.0/cpal/index.html Initializes the default audio host for the system. ```rust use cpal::traits::HostTrait; let host = cpal::default_host(); ``` -------------------------------- ### FromSample Implementations for I24 Source: https://docs.rs/cpal/0.17.0/cpal/struct.I24.html Demonstrates how I24 can be created from various sample types (f32, f64, i16, i32, i64, i8, u16, u32, u64, u8). ```APIDOC ## FromSample Implementations for I24 ### `impl FromSample for I24` #### `fn from_sample_(s: f32) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: f64) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: i16) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: i32) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: i64) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: i8) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: u16) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: u32) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: u64) -> I24` ### `impl FromSample for I24` #### `fn from_sample_(s: u8) -> I24` ``` -------------------------------- ### Get Device by ID Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Fetches a `Device` based on its `DeviceId`, if available. Returns `None` if no device matches the provided ID. ```rust fn device_by_id(&self, id: &DeviceId) -> Option ``` -------------------------------- ### Sample Implementations Source: https://docs.rs/cpal/0.17.0/cpal/trait.Sample.html Details on how the Sample trait is implemented for various data types. ```APIDOC ### impl Sample for f32 #### const EQUILIBRIUM: f32 = 0f32 #### type Signed = f32 #### type Float = f32 ``` ```APIDOC ### impl Sample for f64 #### const EQUILIBRIUM: f64 = 0f64 #### type Signed = f64 #### type Float = f64 ``` ```APIDOC ### impl Sample for i8 #### const EQUILIBRIUM: i8 = 0i8 #### type Signed = i8 #### type Float = f32 ``` ```APIDOC ### impl Sample for i16 #### const EQUILIBRIUM: i16 = 0i16 #### type Signed = i16 #### type Float = f32 ``` ```APIDOC ### impl Sample for i32 #### const EQUILIBRIUM: i32 = 0i32 #### type Signed = i32 #### type Float = f32 ``` ```APIDOC ### impl Sample for i64 #### const EQUILIBRIUM: i64 = 0i64 #### type Signed = i64 #### type Float = f64 ``` ```APIDOC ### impl Sample for u8 #### const EQUILIBRIUM: u8 = 128u8 #### type Signed = i8 #### type Float = f32 ``` ```APIDOC ### impl Sample for u16 #### const EQUILIBRIUM: u16 = 32_768u16 #### type Signed = i16 #### type Float = f32 ``` ```APIDOC ### impl Sample for u32 #### const EQUILIBRIUM: u32 = 2_147_483_648u32 #### type Signed = i32 #### type Float = f32 ``` ```APIDOC ### impl Sample for u64 #### const EQUILIBRIUM: u64 = 9_223_372_036_854_775_808u64 #### type Signed = i64 #### type Float = f64 ``` ```APIDOC ### impl Sample for I48 #### const EQUILIBRIUM: I48 = types::i48::EQUILIBRIUM #### type Signed = I48 #### type Float = f64 ``` ```APIDOC ### impl Sample for U48 #### const EQUILIBRIUM: U48 = types::u48::EQUILIBRIUM #### type Signed = i64 #### type Float = f64 ``` ```APIDOC ### impl Sample for I24 #### const EQUILIBRIUM: I24 = types::i24::EQUILIBRIUM #### type Signed = I24 #### type Float = f32 ``` ```APIDOC ### impl Sample for U24 #### const EQUILIBRIUM: U24 = types::u24::EQUILIBRIUM #### type Signed = i32 #### type Float = f32 ``` -------------------------------- ### Sample Trait Implementations for I24 Source: https://docs.rs/cpal/0.17.0/cpal/struct.I24.html Details the `Sample` trait implementations for I24, including constants and conversion methods. ```APIDOC ## Sample Trait Implementations for I24 ### `impl Sample for I24` #### `const EQUILIBRIUM: I24 = types::i24::EQUILIBRIUM` The equilibrium value for the wave that this `Sample` type represents. #### `type Signed = I24` Represents the signed format for addition. #### `type Float = f32` Represents the floating-point format for multiplication. #### `const IDENTITY: Self::Float = ::IDENTITY` The multiplicative identity of the signal. #### `fn to_sample(self) -> S` where Self: ToSample, Convert `self` to any type that implements `FromSample`. #### `fn from_sample(s: S) -> Self` where Self: FromSample, Create a `Self` from any type that implements `ToSample`. #### `fn to_signed_sample(self) -> Self::Signed` Converts `self` to the equivalent `Sample` in the associated `Signed` format. #### `fn to_float_sample(self) -> Self::Float` Converts `self` to the equivalent `Sample` in the associated `Float` format. #### `fn add_amp(self, amp: Self::Signed) -> Self` Adds (or offsets) the amplitude of the `Sample` by the given signed amplitude. ``` -------------------------------- ### HostTrait::is_available() Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Checks if the audio host is available on the current system. Call this before attempting to access devices. ```rust fn is_available() -> bool; ``` -------------------------------- ### Stream Audio with Sample Format Handling Source: https://docs.rs/cpal/0.17.0/cpal/index.html Builds an output stream while handling different sample formats and filling buffers with silence. ```rust use cpal::{Data, Sample, SampleFormat, FromSample}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; let err_fn = |err| eprintln!("an error occurred on the output audio stream: {}", err); let sample_format = supported_config.sample_format(); let config = supported_config.into(); let stream = match sample_format { SampleFormat::F32 => device.build_output_stream(&config, write_silence::, err_fn, None), SampleFormat::I16 => device.build_output_stream(&config, write_silence::, err_fn, None), SampleFormat::U16 => device.build_output_stream(&config, write_silence::, err_fn, None), sample_format => panic!("Unsupported sample format '{sample_format}'") }.unwrap(); fn write_silence(data: &mut [T], _: &cpal::OutputCallbackInfo) { for sample in data.iter_mut() { *sample = Sample::EQUILIBRIUM; } } ``` -------------------------------- ### Get Inner Value of I24 Source: https://docs.rs/cpal/0.17.0/cpal/struct.I24.html Returns the internal i32 value representing the I24 sample. This method consumes the I24 instance. ```rust pub fn inner(self) -> i32 ``` -------------------------------- ### JackHost Configuration Methods Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Methods for configuring the behavior of the JACK host, specifically regarding port connections and server startup. ```APIDOC ## fn set_connect_automatically ### Description Configures whether created ports should automatically connect to system playback/capture ports. ### Parameters #### Request Body - **do_connect** (bool) - Required - When enabled (default), output streams connect to system playback ports and input streams connect to system capture ports automatically. --- ## fn set_start_server_automatically ### Description Configures whether the JACK server should automatically start if not already running. ### Parameters #### Request Body - **do_start_server** (bool) - Required - When enabled, attempting to create a JACK client will start the JACK server if it’s not running. Default is false. ``` -------------------------------- ### Create Samples using from_sample Source: https://docs.rs/cpal/0.17.0/cpal/trait.Sample.html Creates a sample from another type using the from_sample method. ```rust use dasp_sample::{Sample, I24}; fn main() { assert_eq!(f32::from_sample(128_u8), 0.0); assert_eq!(i8::from_sample(-1.0), -128); assert_eq!(I24::from_sample(0.0), I24::new(0).unwrap()); } ``` -------------------------------- ### Select Default Output Device Source: https://docs.rs/cpal/0.17.0/cpal/index.html Retrieves the default output device, panicking if none are available. ```rust let device = host.default_output_device().expect("no output device available"); ``` -------------------------------- ### DeviceDescriptionBuilder Methods Source: https://docs.rs/cpal/0.17.0/cpal/device_description/struct.DeviceDescriptionBuilder.html Methods for initializing and configuring a DeviceDescriptionBuilder instance. ```APIDOC ## DeviceDescriptionBuilder ### Description Builder for constructing a `DeviceDescription`. This is primarily used by host implementations and custom hosts to gradually build up device descriptions with available metadata. ### Methods - **new(name: impl Into) -> Self**: Creates a new builder with the device name (required). - **manufacturer(self, manufacturer: impl Into) -> Self**: Sets the manufacturer name. - **driver(self, driver: impl Into) -> Self**: Sets the driver name. - **device_type(self, device_type: DeviceType) -> Self**: Sets the device type. - **interface_type(self, interface_type: InterfaceType) -> Self**: Sets the interface type. - **direction(self, direction: DeviceDirection) -> Self**: Sets the device direction. - **address(self, address: impl Into) -> Self**: Sets the physical address. - **extended(self, lines: Vec) -> Self**: Sets the description lines. - **add_extended_line(self, line: impl Into) -> Self**: Adds a single description line. - **build(self) -> DeviceDescription**: Builds the `DeviceDescription`. ``` -------------------------------- ### Get Buffer Length Source: https://docs.rs/cpal/0.17.0/cpal/struct.Data.html Returns the full length of the buffer in samples. This is the same length as the slice of type `T` that would be returned via `as_slice`. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Functions for Host Management Source: https://docs.rs/cpal/0.17.0/cpal/platform/index.html API functions to discover and initialize audio hosts available on the current system. ```APIDOC ## Functions for Host Management ### Description Functions to retrieve available audio hosts and the default host for the current platform. ### Functions - **available_hosts()**: Produces a list of hosts that are currently available on the system. - **default_host()**: Returns the default host for the current compilation target platform. - **host_from_id(id: HostId)**: Initialises and produces the host associated with the provided unique identifier if it is available. ``` -------------------------------- ### Build Output Stream Source: https://docs.rs/cpal/0.17.0/cpal/index.html Creates an output stream from a device using a provided configuration and callback closures. ```rust use cpal::Data; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; let stream = device.build_output_stream( &config, move |data: &mut [f32], _: &cpal::OutputCallbackInfo| { // react to stream events and read or write stream data here. }, move |err| { // react to errors here. }, None // None=blocking, Some(Duration)=timeout ); ``` -------------------------------- ### Get Device ID Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Obtains a unique and stable identifier for the audio device. This ID should remain consistent across different runs and system states. ```rust fn id(&self) -> Result ``` -------------------------------- ### Get Output Devices Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Returns an iterator over all `Device`s available to the system that support one or more output stream formats. This operation can fail, returning a `DevicesError`. ```rust fn output_devices(&self) -> Result, DevicesError> ``` -------------------------------- ### HostTrait Methods Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Methods available on the HostTrait for interacting with audio hardware. ```APIDOC ## HostTrait Methods ### is_available - **Description**: Checks if the host is available on the system. - **Returns**: bool ### devices - **Description**: Returns an iterator yielding all devices currently available to the host. - **Returns**: Result ### default_input_device - **Description**: Returns the default input audio device on the system. - **Returns**: Option ### default_output_device - **Description**: Returns the default output audio device on the system. - **Returns**: Option ### device_by_id - **Description**: Fetches a specific device based on a DeviceId. - **Parameters**: id (DeviceId) - **Returns**: Option ### input_devices - **Description**: Returns an iterator yielding all devices that support input stream formats. - **Returns**: Result, DevicesError> ### output_devices - **Description**: Returns an iterator yielding all devices that support output stream formats. - **Returns**: Result, DevicesError> ``` -------------------------------- ### Get Input Devices Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Returns an iterator over all `Device`s available to the system that support one or more input stream formats. This operation can fail, returning a `DevicesError`. ```rust fn input_devices(&self) -> Result, DevicesError> ``` -------------------------------- ### Build Raw Input Stream Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Constructs an input stream with raw audio data. Requires specifying stream configuration, sample format, and callback functions for data and errors. ```rust fn build_input_stream_raw( &self, config: &StreamConfig, sample_format: SampleFormat, data_callback: D, error_callback: E, timeout: Option, ) -> Result where D: FnMut(&Data, &InputCallbackInfo) + Send + 'static, E: FnMut(StreamError) + Send + 'static ``` -------------------------------- ### Get Default Input Configuration Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Retrieves the default input stream format for the audio device. This method may return an error if the device is no longer valid. ```rust fn default_input_config( &self, ) -> Result ``` -------------------------------- ### I24 Sample Conversions Source: https://docs.rs/cpal/0.17.0/cpal/struct.I24.html Details the conversions from and to the I24 sample format using the `FromSample` trait, enabling interoperability with various other audio sample types. ```APIDOC ### impl FromSample for I48 #### fn from_sample_(s: I24) -> I48 ### impl FromSample for U24 #### fn from_sample_(s: I24) -> U24 ### impl FromSample for U48 #### fn from_sample_(s: I24) -> U48 ### impl FromSample for f32 #### fn from_sample_(s: I24) -> f32 ### impl FromSample for f64 #### fn from_sample_(s: I24) -> f64 ### impl FromSample for i16 #### fn from_sample_(s: I24) -> i16 ### impl FromSample for i32 #### fn from_sample_(s: I24) -> i32 ### impl FromSample for i64 #### fn from_sample_(s: I24) -> i64 ### impl FromSample for i8 #### fn from_sample_(s: I24) -> i8 ### impl FromSample for u16 #### fn from_sample_(s: I24) -> u16 ### impl FromSample for u32 #### fn from_sample_(s: I24) -> u32 ### impl FromSample for u64 #### fn from_sample_(s: I24) -> u64 ### impl FromSample for u8 #### fn from_sample_(s: I24) -> u8 ### impl FromSample for I24 #### fn from_sample_(s: I48) -> I24 ### impl FromSample for I24 #### fn from_sample_(s: U24) -> I24 ### impl FromSample for I24 #### fn from_sample_(s: U48) -> I24 ``` -------------------------------- ### Get Device Description Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Retrieves a structured description of the audio device, including metadata like name and manufacturer. Use `.to_string()` or `.name()` for simpler string representations. ```rust fn description(&self) -> Result ``` -------------------------------- ### Get Raw Bytes Slice Source: https://docs.rs/cpal/0.17.0/cpal/struct.Data.html Returns the raw slice of memory representing the underlying audio data as a slice of bytes. The interpretation of this slice depends on `Data::sample_format`. ```rust pub fn bytes(&self) -> &[u8] ``` -------------------------------- ### Construct Data from Parts Source: https://docs.rs/cpal/0.17.0/cpal/struct.Data.html Constructor for host implementations to use. The `data` pointer must point to the first sample, `len` must be the number of samples, and `sample_format` must correctly represent the underlying data. ```rust pub unsafe fn from_parts( data: *mut (), len: usize, sample_format: SampleFormat, ) -> Self ``` -------------------------------- ### Implement Error trait for DevicesError Source: https://docs.rs/cpal/0.17.0/cpal/enum.DevicesError.html Provides methods for error handling, including getting the source of the error and a deprecated description method. The provide method is a nightly-only experimental API. ```rust impl Error for DevicesError { fn source(&self) -> Option<&(dyn Error + 'static)> { // Implementation details omitted for brevity } fn description(&self) -> &str { // Implementation details omitted for brevity } fn cause(&self) -> Option<&dyn Error> { // Implementation details omitted for brevity } fn provide<'a>(&'a self, request: &mut Request<'a>) { // Implementation details omitted for brevity } } ``` -------------------------------- ### I24 Construction Methods Source: https://docs.rs/cpal/0.17.0/cpal/struct.I24.html Provides methods for constructing I24 samples, including a safe constructor that checks for value range and an unchecked version for performance-critical scenarios. ```APIDOC ## impl I24 ### pub fn new(val: i32) -> Option Construct a new sample if the given value is within range. Returns `None` if `val` is out of range. ### pub fn new_unchecked(s: i32) -> I24 Constructs a new sample without checking for overflowing. This should _only_ be used if the user can guarantee the sample will be within range and they require the extra performance. If this function is used, the sample crate can’t guarantee that the returned sample or any interacting samples will remain within their MIN and MAX bounds. ``` -------------------------------- ### Get Mutable Raw Bytes Slice Source: https://docs.rs/cpal/0.17.0/cpal/struct.Data.html Returns a mutable raw slice of memory representing the underlying audio data as a slice of bytes. The interpretation of this slice depends on `Data::sample_format`. ```rust pub fn bytes_mut(&mut self) -> &mut [u8] ``` -------------------------------- ### Query Supported Configurations Source: https://docs.rs/cpal/0.17.0/cpal/index.html Queries supported output configurations and selects one with the maximum sample rate. ```rust use cpal::traits::{DeviceTrait, HostTrait}; let mut supported_configs_range = device.supported_output_configs() .expect("error while querying configs"); let supported_config = supported_configs_range.next() .expect("no supported config?!") .with_max_sample_rate(); ``` -------------------------------- ### Define FrameCount Type Alias Source: https://docs.rs/cpal/0.17.0/cpal/type.FrameCount.html Defines FrameCount as an alias for u32. A frame represents one sample for each channel. For example, with stereo audio, one frame contains two samples (left and right channels). ```rust pub type FrameCount = u32; ``` -------------------------------- ### available_hosts Source: https://docs.rs/cpal/0.17.0/cpal/platform/fn.available_hosts.html Retrieves a list of all audio hosts currently available on the system. ```APIDOC ## available_hosts ### Description Produces a list of hosts that are currently available on the system. ### Method GET ### Endpoint /cpal/platform/available_hosts ### Parameters None ### Request Example None ### Response #### Success Response (200) - **hosts** (Vec) - A vector containing the IDs of all available audio hosts. #### Response Example ```json { "hosts": [ "wasapi", "directsound", "asio", "coreaudio", "alsa", "pulseaudio", "jack" ] } ``` ``` -------------------------------- ### Host Management Functions Source: https://docs.rs/cpal/0.17.0/cpal/all.html Functions for retrieving available audio hosts and the default system host. ```APIDOC ## platform::available_hosts ### Description Returns a list of all available audio hosts on the current platform. ## platform::default_host ### Description Returns the default audio host for the current platform. ## platform::host_from_id ### Description Retrieves a specific host based on its unique identifier. ``` -------------------------------- ### Build Raw Output Stream Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Constructs an output stream for raw audio data. Requires specifying stream configuration, sample format, and callback functions for data and errors. ```rust fn build_output_stream_raw( &self, config: &StreamConfig, sample_format: SampleFormat, data_callback: D, error_callback: E, timeout: Option, ) -> Result where D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static, E: FnMut(StreamError) + Send + 'static ``` -------------------------------- ### Host Implementation Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html A generic Host implementation, likely a wrapper or default, available on Linux, DragonFly BSD, FreeBSD, and NetBSD. ```rust impl HostTrait for cpal::platform::Host { type Devices = Devices; type Device = Device; } ``` -------------------------------- ### Sample Conversion Traits (FromSample, ToSample, Duplex) Source: https://docs.rs/cpal/0.17.0/cpal/struct.BackendSpecificError.html Documents traits for converting between sample types, facilitating data transformations. ```APIDOC ## Sample Conversion Traits ### Description This section outlines traits related to sample conversions, enabling transformations between different sample types. It includes `FromSample`, `ToSample`, and the combined `Duplex` trait. ### Implementations #### `impl FromSample for S` - **Description**: Trait for creating a sample from another sample. - **Methods**: - `fn from_sample_(s: S) -> S`: Creates a sample from another sample. #### `impl ToSample for T` where `T: FromSample` - **Description**: Trait for converting a type into a sample. - **Methods**: - `fn to_sample_(self) -> S`: Converts the type into a sample. #### `impl Duplex for T` where `T: FromSample + ToSample` - **Description**: A combined trait for types that can be converted to and from a sample type. - **Requirements**: - `T` must implement `FromSample`. - `T` must implement `ToSample`. ``` -------------------------------- ### JackHost Implementation Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Implementation of HostTrait for JACK audio connection kit, requiring the 'jack' feature flag. Uses IntoIter for device enumeration. ```rust impl HostTrait for cpal::platform::JackHost { type Devices = IntoIter; type Device = Device; } ``` -------------------------------- ### Stream Configuration and Creation Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.Device.html Methods for querying supported stream configurations and building input/output streams. ```APIDOC ## Stream Management Methods ### Description Methods to query supported stream formats and initialize audio streams for input or output. ### Methods - **supported_input_configs()**: Returns an iterator of supported input formats. - **supported_output_configs()**: Returns an iterator of supported output formats. - **default_input_config()**: Returns the default input stream configuration. - **default_output_config()**: Returns the default output stream configuration. - **build_input_stream()**: Creates an input stream with a provided data callback. - **build_output_stream()**: Creates an output stream with a provided data callback. ``` -------------------------------- ### HostTrait::device_by_id() Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Fetches a specific audio device by its ID. Returns None if no device matches the provided ID. ```rust fn device_by_id(&self, id: &DeviceId) -> Option { ... } ``` -------------------------------- ### AlsaHost Implementation Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Implementation of HostTrait for ALSA, available on Linux, DragonFly BSD, FreeBSD, and NetBSD. ```rust impl HostTrait for cpal::platform::AlsaHost { type Devices = Devices; type Device = Device; } ``` -------------------------------- ### From Implementations for Device Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.Device.html Conversions from host-specific device types and internal device representations to the Device type. ```APIDOC ## From Implementations ### Description Converts various host-specific device types or internal device representations into the `Device` type. ### Methods - `from(h: ::Device) -> Self` (Available on Linux, DragonFly BSD, FreeBSD, NetBSD) - `from(h: ::Device) -> Self` (Available on Linux, DragonFly BSD, FreeBSD, NetBSD with `custom` feature) - `from(d: DeviceInner) -> Self` (Available on Linux, DragonFly BSD, FreeBSD, NetBSD) ``` -------------------------------- ### Memory and Conversion Utilities Source: https://docs.rs/cpal/0.17.0/cpal/platform/enum.HostId.html Documentation for memory cloning and standard type conversion traits. ```APIDOC ## unsafe fn clone_to_uninit(&self, dest: *mut u8) ### Description Performs copy-assignment from self to a destination pointer. This is a nightly-only experimental API. ### Parameters - **dest** (*mut u8) - Required - The destination pointer to copy data into. ## impl From for T ### Description Returns the argument unchanged. ## impl Into for T ### Description Performs a conversion from type T to type U by calling U::from(self). ## impl TryFrom for T ### Description Performs a fallible conversion from type U to type T. ### Response - **Error** (Infallible) - The type returned in the event of a conversion error. ``` -------------------------------- ### Initialize host from ID Source: https://docs.rs/cpal/0.17.0/cpal/platform/fn.host_from_id.html Initializes a host given a unique identifier. Returns a Result containing the Host or a HostUnavailable error. ```rust pub fn host_from_id(id: HostId) -> Result ``` -------------------------------- ### HostTrait::input_devices() Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Retrieves an iterator for all audio devices capable of input. Returns an empty iterator if no input devices are available. ```rust fn input_devices( &self, ) -> Result, DevicesError> { ... } ``` -------------------------------- ### Sample Conversion Methods Source: https://docs.rs/cpal/0.17.0/cpal/trait.Sample.html Methods for converting samples to different formats. ```APIDOC ## fn to_signed_sample(self) -> Self::Signed ### Description Converts `self` to the equivalent `Sample` in the associated `Signed` format. This is a simple wrapper around `Sample::to_sample` which may provide extra convenience in some cases, particularly for assisting type inference. ### Method `to_signed_sample` ### Example ```rust use dasp_sample::Sample; fn main() { assert_eq!(128_u8.to_signed_sample(), 0i8); } ``` ``` ```APIDOC ## fn to_float_sample(self) -> Self::Float ### Description Converts `self` to the equivalent `Sample` in the associated `Float` format. This is a simple wrapper around `Sample::to_sample` which may provide extra convenience in some cases, particularly for assisting type inference. ### Method `to_float_sample` ### Example ```rust use dasp_sample::Sample; fn main() { assert_eq!(128_u8.to_float_sample(), 0.0); } ``` ``` -------------------------------- ### Create New JackHost Instance Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.JackHost.html Constructs a new JackHost instance. This function returns a Result, indicating success or failure if the host is unavailable. ```rust pub fn new() -> Result ``` -------------------------------- ### Define a CustomDevice Source: https://docs.rs/cpal/0.17.0/cpal/platform/struct.CustomDevice.html Shows the basic structure definition for CustomDevice. ```rust pub struct CustomDevice(/* private fields */); ``` -------------------------------- ### HostTrait::devices() Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Retrieves an iterator for all audio devices supported by the host. Returns an empty iterator if no devices are found or audio is not supported. ```rust fn devices(&self) -> Result; ``` -------------------------------- ### Cross-Platform Host String Handling in Rust Source: https://docs.rs/cpal/0.17.0/cpal/platform/enum.HostId.html Demonstrates how to handle host strings for cross-platform matching and parsing using `cpal::HostId`. String matching works on all platforms, but parsing may fail if the host is not available on the current platform. ```rust use cpal::HostId; use std::str::FromStr; fn handle_host_string(host_string: &str) { // String matching works on all platforms match host_string { "alsa" => println!("ALSA host"), "coreaudio" => println!("CoreAudio host"), "jack" => println!("JACK host"), "wasapi" => println!("WASAPI host"), "asio" => println!("ASIO host"), "aaudio" => println!("AAudio host"), _ => println!("Other host"), } // Parse host string (may fail if host is not available on this platform) if let Ok(host_id) = HostId::from_str(host_string) { println!("Successfully parsed: {}", host_id); } } ``` -------------------------------- ### HostTrait::output_devices() Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.HostTrait.html Retrieves an iterator for all audio devices capable of output. Returns an empty iterator if no output devices are available. ```rust fn output_devices( &self, ) -> Result, DevicesError> { ... } ``` -------------------------------- ### U24 Construction Methods Source: https://docs.rs/cpal/0.17.0/cpal/struct.U24.html Provides methods for constructing U24 samples, including a safe constructor that checks for range and an unchecked version for performance-critical scenarios. ```APIDOC ## impl U24 ### pub fn new(val: i32) -> Option Construct a new sample if the given value is within range. Returns `None` if `val` is out of range. ### pub fn new_unchecked(s: i32) -> U24 Constructs a new sample without checking for overflowing. This should _only_ be used if the user can guarantee the sample will be within range and they require the extra performance. If this function is used, the sample crate can’t guarantee that the returned sample or any interacting samples will remain within their MIN and MAX bounds. ``` -------------------------------- ### DeviceTrait Methods Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Methods for retrieving device metadata, identifiers, and supported audio configurations. ```APIDOC ## DeviceTrait Methods ### description() Returns a `DeviceDescription` containing structured information about the device, including name, manufacturer, and metadata. ### id() Returns a `DeviceId` that uniquely identifies the device on the host. ### supported_input_configs() Returns an iterator yielding formats supported by the backend for input streams. ### supported_output_configs() Returns an iterator yielding output stream formats supported by the device. ### default_input_config() Returns the default input stream format for the device. ### default_output_config() Returns the default output stream format for the device. ``` -------------------------------- ### CloneToUninit (Nightly-only) Source: https://docs.rs/cpal/0.17.0/cpal/enum.SupportedBufferSize.html Experimental nightly-only API for performing copy-assignment to uninitialized memory. ```rust unsafe fn clone_to_uninit(&self, dest: *mut u8) ``` -------------------------------- ### Blanket Implementations for Generic Types Source: https://docs.rs/cpal/0.17.0/cpal/enum.DevicesError.html Demonstrates blanket implementations for generic types, such as Any, Borrow, BorrowMut, CloneToUninit, From for T, FromSample for S, Into for T, ToOwned, ToSample for T, ToString, TryFrom for T, and TryInto for T. These apply to DevicesError where applicable. ```rust impl Any for T where T: 'static + ?Sized { fn type_id(&self) -> TypeId { // Implementation details omitted for brevity } } impl Borrow for T where T: ?Sized { fn borrow(&self) -> &T { // Implementation details omitted for brevity } } impl BorrowMut for T where T: ?Sized { fn borrow_mut(&mut self) -> &mut T { // Implementation details omitted for brevity } } impl CloneToUninit for T where T: Clone { unsafe fn clone_to_uninit(&self, dest: *mut u8) { // Implementation details omitted for brevity } } impl From for T { fn from(t: T) -> T { // Implementation details omitted for brevity } } impl FromSample for S { fn from_sample_(s: S) -> S { // Implementation details omitted for brevity } } impl Into for T where U: From { fn into(self) -> U { // Implementation details omitted for brevity } } impl ToOwned for T where T: Clone { type Owned = T; fn to_owned(&self) -> T { // Implementation details omitted for brevity } fn clone_into(&self, target: &mut T) { // Implementation details omitted for brevity } } impl ToSample for T where U: FromSample { fn to_sample_(self) -> U { // Implementation details omitted for brevity } } impl ToString for T where T: Display + ?Sized { fn to_string(&self) -> String { // Implementation details omitted for brevity } } impl TryFrom for T where U: Into { type Error = Infallible; fn try_from(value: U) -> Result>::Error> { // Implementation details omitted for brevity } } impl TryInto for T where U: TryFrom { // Implementation details omitted for brevity } ``` -------------------------------- ### Build Output Stream (Generic) Source: https://docs.rs/cpal/0.17.0/cpal/traits/trait.DeviceTrait.html Constructs an output stream with generic sample types. This is a convenience method over `build_output_stream_raw`. ```rust fn build_output_stream( &self, config: &StreamConfig, data_callback: D, error_callback: E, timeout: Option, ) -> Result where T: SizedSample, D: FnMut(&mut [T], &OutputCallbackInfo) + Send + 'static, E: FnMut(StreamError) + Send + 'static ``` -------------------------------- ### SampleFormat Clone Implementation Source: https://docs.rs/cpal/0.17.0/cpal/enum.SampleFormat.html Provides methods for cloning SampleFormat values. ```rust fn clone(&self) -> SampleFormat ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Data Constructor Source: https://docs.rs/cpal/0.17.0/cpal/struct.Data.html Provides a constructor for host implementations to create `Data` instances. ```APIDOC ## pub unsafe fn from_parts( data: *mut (), len: usize, sample_format: SampleFormat, ) -> Self ### Description Constructor for host implementations to use. ### Safety - The `data` pointer must point to the first sample in the slice containing all samples. - The `len` must describe the length of the buffer as a number of samples in the expected format specified via the `sample_format` argument. - The `sample_format` must correctly represent the underlying sample data delivered/expected by the stream. ### Parameters - **data** (*mut () ) - Pointer to the audio data buffer. - **len** (usize) - The number of samples in the buffer. - **sample_format** (SampleFormat) - The format of the audio samples. ``` -------------------------------- ### Function: host_from_id Source: https://docs.rs/cpal/0.17.0/cpal/platform/fn.host_from_id.html Initializes and returns a host instance based on the provided HostId. ```APIDOC ## Function: host_from_id ### Description Given a unique host identifier, initialise and produce the host if it is available. ### Signature `pub fn host_from_id(id: HostId) -> Result` ### Parameters - **id** (HostId) - Required - The unique identifier for the audio host. ### Response - **Result** - Returns the initialized Host if successful, or a HostUnavailable error if the host cannot be initialized. ```