Introduce polymorphic stream constructors

This commit is contained in:
Benjamin Saunders 2020-01-21 22:01:49 -08:00
parent 78df791377
commit 076b814a15
5 changed files with 142 additions and 44 deletions

View file

@ -59,10 +59,10 @@
//! use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
//! # let host = cpal::default_host();
//! # let device = host.default_output_device().unwrap();
//! # let format = device.default_output_format().unwrap();
//! let stream = device.build_output_stream_raw(
//! &format,
//! move |data: &mut Data| {
//! # let shape = device.default_output_format().unwrap().shape();
//! let stream = device.build_output_stream(
//! &shape,
//! move |data: &mut [f32]| {
//! // react to stream events and read or write stream data here.
//! },
//! move |err| {
@ -93,15 +93,14 @@
//! # let device = host.default_output_device().unwrap();
//! # let format = device.default_output_format().unwrap();
//! let err_fn = |err| eprintln!("an error occurred on the output audio stream: {}", err);
//! let data_fn = move |data: &mut Data| match data.sample_format() {
//! SampleFormat::F32 => write_silence::<f32>(data),
//! SampleFormat::I16 => write_silence::<i16>(data),
//! SampleFormat::U16 => write_silence::<u16>(data),
//! };
//! let stream = device.build_output_stream_raw(&format, data_fn, err_fn).unwrap();
//! let shape = format.shape();
//! let stream = match format.data_type {
//! SampleFormat::F32 => device.build_output_stream(&shape, write_silence::<f32>, err_fn),
//! SampleFormat::I16 => device.build_output_stream(&shape, write_silence::<i16>, err_fn),
//! SampleFormat::U16 => device.build_output_stream(&shape, write_silence::<u16>, err_fn),
//! }.unwrap();
//!
//! fn write_silence<T: Sample>(data: &mut Data) {
//! let data = data.as_slice_mut::<T>().unwrap();
//! fn write_silence<T: Sample>(data: &mut [T]) {
//! for sample in data.iter_mut() {
//! *sample = Sample::from(&0.0);
//! }
@ -181,6 +180,38 @@ pub struct Format {
pub data_type: SampleFormat,
}
impl Format {
/// Construct a format having a particular `shape` and `data_type`.
pub fn with_shape(shape: &Shape, data_type: SampleFormat) -> Self {
Self {
channels: shape.channels,
sample_rate: shape.sample_rate,
data_type,
}
}
/// Extract aspects of the format independent of the data type.
pub fn shape(&self) -> Shape {
self.clone().into()
}
}
/// The properties of an input or output audio stream excluding its data type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Shape {
pub channels: ChannelCount,
pub sample_rate: SampleRate,
}
impl From<Format> for Shape {
fn from(x: Format) -> Self {
Self {
channels: x.channels,
sample_rate: x.sample_rate,
}
}
}
/// Describes a range of supported stream formats.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SupportedFormat {
@ -193,9 +224,10 @@ pub struct SupportedFormat {
pub data_type: SampleFormat,
}
/// Represents a buffer of audio data, delivered via a user's stream data callback function.
/// A buffer of dynamically typed audio data, passed to raw stream callbacks.
///
/// Input stream callbacks receive `&Data`, while output stream callbacks expect `&mut Data`.
/// Raw input stream callbacks receive `&Data`, while raw output stream callbacks expect `&mut
/// Data`.
#[derive(Debug)]
pub struct Data {
data: *mut (),

View file

@ -2,8 +2,8 @@
use {
BuildStreamError, Data, DefaultFormatError, DeviceNameError, DevicesError, Format,
InputDevices, OutputDevices, PauseStreamError, PlayStreamError, StreamError, SupportedFormat,
SupportedFormatsError,
InputDevices, OutputDevices, PauseStreamError, PlayStreamError, Sample, Shape, StreamError,
SupportedFormat, SupportedFormatsError,
};
/// A **Host** provides access to the available audio devices on the system.
@ -113,6 +113,54 @@ pub trait DeviceTrait {
fn default_output_format(&self) -> Result<Format, DefaultFormatError>;
/// Create an input stream.
fn build_input_stream<T, D, E>(
&self,
shape: &Shape,
mut data_callback: D,
error_callback: E,
) -> Result<Self::Stream, BuildStreamError>
where
T: Sample,
D: FnMut(&[T]) + Send + 'static,
E: FnMut(StreamError) + Send + 'static,
{
self.build_input_stream_raw(
&Format::with_shape(shape, T::FORMAT),
move |data| {
data_callback(
data.as_slice()
.expect("host supplied incorrect sample type"),
)
},
error_callback,
)
}
/// Create an output stream.
fn build_output_stream<T, D, E>(
&self,
shape: &Shape,
mut data_callback: D,
error_callback: E,
) -> Result<Self::Stream, BuildStreamError>
where
T: Sample,
D: FnMut(&mut [T]) + Send + 'static,
E: FnMut(StreamError) + Send + 'static,
{
self.build_output_stream_raw(
&Format::with_shape(shape, T::FORMAT),
move |data| {
data_callback(
data.as_slice_mut()
.expect("host supplied incorrect sample type"),
)
},
error_callback,
)
}
/// Create a dynamically typed input stream.
fn build_input_stream_raw<D, E>(
&self,
format: &Format,
@ -123,7 +171,7 @@ pub trait DeviceTrait {
D: FnMut(&Data) + Send + 'static,
E: FnMut(StreamError) + Send + 'static;
/// Create an output stream.
/// Create a dynamically typed output stream.
fn build_output_stream_raw<D, E>(
&self,
format: &Format,