Migrate Sample to dasp_sample (#689)

This commit is contained in:
Kai Giebeler 2022-10-07 14:08:28 +02:00 • committed by est31
parent 8c31e908b0
commit 85d773d59f
17 changed files with 337 additions and 355 deletions

View file

@ -14,6 +14,7 @@ asio = ["asio-sys", "num-traits"] # Only available on Windows. See README for se
[dependencies] [dependencies]
thiserror = "1.0.2" thiserror = "1.0.2"
dasp_sample = "0.11.0"
[dev-dependencies] [dev-dependencies]
anyhow = "1.0.12" anyhow = "1.0.12"

View file

@ -3,7 +3,11 @@
extern crate anyhow; extern crate anyhow;
extern crate cpal; extern crate cpal;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
SizedSample,
};
use cpal::{FromSample, Sample};
#[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "full"))] #[cfg_attr(target_os = "android", ndk_glue::main(backtrace = "full"))]
fn main() { fn main() {
@ -16,15 +20,27 @@ fn main() {
let config = device.default_output_config().unwrap(); let config = device.default_output_config().unwrap();
match config.sample_format() { match config.sample_format() {
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()).unwrap(), cpal::SampleFormat::I8 => run::<i8>(&device, &config.into()).unwrap(),
cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()).unwrap(), cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()).unwrap(),
// cpal::SampleFormat::I24 => run::<I24>(&device, &config.into()).unwrap(),
cpal::SampleFormat::I32 => run::<i32>(&device, &config.into()).unwrap(),
// cpal::SampleFormat::I48 => run::<I48>(&device, &config.into()).unwrap(),
cpal::SampleFormat::I64 => run::<i64>(&device, &config.into()).unwrap(),
cpal::SampleFormat::U8 => run::<u8>(&device, &config.into()).unwrap(),
cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()).unwrap(), cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()).unwrap(),
// cpal::SampleFormat::U24 => run::<U24>(&device, &config.into()).unwrap(),
cpal::SampleFormat::U32 => run::<u32>(&device, &config.into()).unwrap(),
// cpal::SampleFormat::U48 => run::<U48>(&device, &config.into()).unwrap(),
cpal::SampleFormat::U64 => run::<u64>(&device, &config.into()).unwrap(),
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()).unwrap(),
cpal::SampleFormat::F64 => run::<f64>(&device, &config.into()).unwrap(),
sample_format => panic!("Unsupported sample format '{sample_format}'"),
} }
} }
fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error> fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error>
where where
T: cpal::Sample, T: SizedSample + FromSample<f32>,
{ {
let sample_rate = config.sample_rate.0 as f32; let sample_rate = config.sample_rate.0 as f32;
let channels = config.channels as usize; let channels = config.channels as usize;
@ -54,10 +70,10 @@ where
fn write_data<T>(output: &mut [T], channels: usize, next_sample: &mut dyn FnMut() -> f32) fn write_data<T>(output: &mut [T], channels: usize, next_sample: &mut dyn FnMut() -> f32)
where where
T: cpal::Sample, T: Sample + FromSample<f32>,
{ {
for frame in output.chunks_mut(channels) { for frame in output.chunks_mut(channels) {
let value: T = cpal::Sample::from::<f32>(&next_sample()); let value: T = T::from_sample(next_sample());
for sample in frame.iter_mut() { for sample in frame.iter_mut() {
*sample = value; *sample = value;
} }

View file

@ -3,7 +3,11 @@ extern crate clap;
extern crate cpal; extern crate cpal;
use clap::arg; use clap::arg;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
SizedSample,
};
use cpal::{FromSample, Sample};
#[derive(Debug)] #[derive(Debug)]
struct Opt { struct Opt {
@ -84,15 +88,27 @@ fn main() -> anyhow::Result<()> {
println!("Default output config: {:?}", config); println!("Default output config: {:?}", config);
match config.sample_format() { match config.sample_format() {
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()), cpal::SampleFormat::I8 => run::<i8>(&device, &config.into()),
cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()), cpal::SampleFormat::I16 => run::<i16>(&device, &config.into()),
// cpal::SampleFormat::I24 => run::<I24>(&device, &config.into()),
cpal::SampleFormat::I32 => run::<i32>(&device, &config.into()),
// cpal::SampleFormat::I48 => run::<I48>(&device, &config.into()),
cpal::SampleFormat::I64 => run::<i64>(&device, &config.into()),
cpal::SampleFormat::U8 => run::<u8>(&device, &config.into()),
cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()), cpal::SampleFormat::U16 => run::<u16>(&device, &config.into()),
// cpal::SampleFormat::U24 => run::<U24>(&device, &config.into()),
cpal::SampleFormat::U32 => run::<u32>(&device, &config.into()),
// cpal::SampleFormat::U48 => run::<U48>(&device, &config.into()),
cpal::SampleFormat::U64 => run::<u64>(&device, &config.into()),
cpal::SampleFormat::F32 => run::<f32>(&device, &config.into()),
cpal::SampleFormat::F64 => run::<f64>(&device, &config.into()),
sample_format => panic!("Unsupported sample format '{sample_format}'"),
} }
} }
pub fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error> pub fn run<T>(device: &cpal::Device, config: &cpal::StreamConfig) -> Result<(), anyhow::Error>
where where
T: cpal::Sample, T: SizedSample + FromSample<f32>,
{ {
let sample_rate = config.sample_rate.0 as f32; let sample_rate = config.sample_rate.0 as f32;
let channels = config.channels as usize; let channels = config.channels as usize;
@ -122,10 +138,10 @@ where
fn write_data<T>(output: &mut [T], channels: usize, next_sample: &mut dyn FnMut() -> f32) fn write_data<T>(output: &mut [T], channels: usize, next_sample: &mut dyn FnMut() -> f32)
where where
T: cpal::Sample, T: Sample + FromSample<f32>,
{ {
for frame in output.chunks_mut(channels) { for frame in output.chunks_mut(channels) {
let value: T = cpal::Sample::from::<f32>(&next_sample()); let value: T = T::from_sample(next_sample());
for sample in frame.iter_mut() { for sample in frame.iter_mut() {
*sample = value; *sample = value;
} }

View file

@ -9,6 +9,7 @@ extern crate hound;
use clap::arg; use clap::arg;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{FromSample, Sample};
use std::fs::File; use std::fs::File;
use std::io::BufWriter; use std::io::BufWriter;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
@ -112,9 +113,9 @@ fn main() -> Result<(), anyhow::Error> {
}; };
let stream = match config.sample_format() { let stream = match config.sample_format() {
cpal::SampleFormat::F32 => device.build_input_stream( cpal::SampleFormat::I8 => device.build_input_stream(
&config.into(), &config.into(),
move |data, _: &_| write_input_data::<f32, f32>(data, &writer_2), move |data, _: &_| write_input_data::<i8, i8>(data, &writer_2),
err_fn, err_fn,
)?, )?,
cpal::SampleFormat::I16 => device.build_input_stream( cpal::SampleFormat::I16 => device.build_input_stream(
@ -122,11 +123,21 @@ fn main() -> Result<(), anyhow::Error> {
move |data, _: &_| write_input_data::<i16, i16>(data, &writer_2), move |data, _: &_| write_input_data::<i16, i16>(data, &writer_2),
err_fn, err_fn,
)?, )?,
cpal::SampleFormat::U16 => device.build_input_stream( cpal::SampleFormat::I32 => device.build_input_stream(
&config.into(), &config.into(),
move |data, _: &_| write_input_data::<u16, i16>(data, &writer_2), move |data, _: &_| write_input_data::<i32, i32>(data, &writer_2),
err_fn, err_fn,
)?, )?,
cpal::SampleFormat::F32 => device.build_input_stream(
&config.into(),
move |data, _: &_| write_input_data::<f32, f32>(data, &writer_2),
err_fn,
)?,
sample_format => {
return Err(anyhow::Error::msg(format!(
"Unsupported sample format '{sample_format}'"
)))
}
}; };
stream.play()?; stream.play()?;
@ -140,10 +151,10 @@ fn main() -> Result<(), anyhow::Error> {
} }
fn sample_format(format: cpal::SampleFormat) -> hound::SampleFormat { fn sample_format(format: cpal::SampleFormat) -> hound::SampleFormat {
match format { if format.is_float() {
cpal::SampleFormat::U16 => hound::SampleFormat::Int, hound::SampleFormat::Float
cpal::SampleFormat::I16 => hound::SampleFormat::Int, } else {
cpal::SampleFormat::F32 => hound::SampleFormat::Float, hound::SampleFormat::Int
} }
} }
@ -160,13 +171,13 @@ type WavWriterHandle = Arc<Mutex<Option<hound::WavWriter<BufWriter<File>>>>>;
fn write_input_data<T, U>(input: &[T], writer: &WavWriterHandle) fn write_input_data<T, U>(input: &[T], writer: &WavWriterHandle)
where where
T: cpal::Sample, T: Sample,
U: cpal::Sample + hound::Sample, U: Sample + hound::Sample + FromSample<T>,
{ {
if let Ok(mut guard) = writer.try_lock() { if let Ok(mut guard) = writer.try_lock() {
if let Some(writer) = guard.as_mut() { if let Some(writer) = guard.as_mut() {
for &sample in input.iter() { for &sample in input.iter() {
let sample: U = cpal::Sample::from(&sample); let sample: U = U::from_sample(sample);
writer.write_sample(sample).ok(); writer.write_sample(sample).ok();
} }
} }

View file

@ -6,7 +6,11 @@ extern crate anyhow;
extern crate clap; extern crate clap;
extern crate cpal; extern crate cpal;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use cpal::{
traits::{DeviceTrait, HostTrait, StreamTrait},
SizedSample,
};
use cpal::{FromSample, Sample};
fn main() -> anyhow::Result<()> { fn main() -> anyhow::Result<()> {
let stream = stream_setup_for(sample_next)?; let stream = stream_setup_for(sample_next)?;
@ -43,9 +47,23 @@ where
let (_host, device, config) = host_device_setup()?; let (_host, device, config) = host_device_setup()?;
match config.sample_format() { match config.sample_format() {
cpal::SampleFormat::F32 => stream_make::<f32, _>(&device, &config.into(), on_sample), cpal::SampleFormat::I8 => stream_make::<i8, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::I16 => stream_make::<i16, _>(&device, &config.into(), on_sample), cpal::SampleFormat::I16 => stream_make::<i16, _>(&device, &config.into(), on_sample),
// cpal::SampleFormat::I24 => stream_make::<I24, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::I32 => stream_make::<i32, _>(&device, &config.into(), on_sample),
// cpal::SampleFormat::I48 => stream_make::<I48, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::I64 => stream_make::<i64, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::U8 => stream_make::<u8, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::U16 => stream_make::<u16, _>(&device, &config.into(), on_sample), cpal::SampleFormat::U16 => stream_make::<u16, _>(&device, &config.into(), on_sample),
// cpal::SampleFormat::U24 => stream_make::<U24, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::U32 => stream_make::<u32, _>(&device, &config.into(), on_sample),
// cpal::SampleFormat::U48 => stream_make::<U48, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::U64 => stream_make::<u64, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::F32 => stream_make::<f32, _>(&device, &config.into(), on_sample),
cpal::SampleFormat::F64 => stream_make::<f64, _>(&device, &config.into(), on_sample),
sample_format => Err(anyhow::Error::msg(format!(
"Unsupported sample format '{sample_format}'"
))),
} }
} }
@ -70,7 +88,7 @@ pub fn stream_make<T, F>(
on_sample: F, on_sample: F,
) -> Result<cpal::Stream, anyhow::Error> ) -> Result<cpal::Stream, anyhow::Error>
where where
T: cpal::Sample, T: SizedSample + FromSample<f32>,
F: FnMut(&mut SampleRequestOptions) -> f32 + std::marker::Send + 'static + Copy, F: FnMut(&mut SampleRequestOptions) -> f32 + std::marker::Send + 'static + Copy,
{ {
let sample_rate = config.sample_rate.0 as f32; let sample_rate = config.sample_rate.0 as f32;
@ -96,11 +114,11 @@ where
fn on_window<T, F>(output: &mut [T], request: &mut SampleRequestOptions, mut on_sample: F) fn on_window<T, F>(output: &mut [T], request: &mut SampleRequestOptions, mut on_sample: F)
where where
T: cpal::Sample, T: Sample + FromSample<f32>,
F: FnMut(&mut SampleRequestOptions) -> f32 + std::marker::Send + 'static, F: FnMut(&mut SampleRequestOptions) -> f32 + std::marker::Send + 'static,
{ {
for frame in output.chunks_mut(request.nchannels) { for frame in output.chunks_mut(request.nchannels) {
let value: T = cpal::Sample::from::<f32>(&on_sample(request)); let value: T = T::from_sample(on_sample(request));
for sample in frame.iter_mut() { for sample in frame.iter_mut() {
*sample = value; *sample = value;
} }

View file

@ -312,9 +312,9 @@ impl Device {
let hw_params = alsa::pcm::HwParams::any(handle)?; let hw_params = alsa::pcm::HwParams::any(handle)?;
// TODO: check endianness // TODO: check endianness
const FORMATS: [(SampleFormat, alsa::pcm::Format); 3] = [ const FORMATS: [(SampleFormat, alsa::pcm::Format); 8] = [
//SND_PCM_FORMAT_S8, (SampleFormat::I8, alsa::pcm::Format::S8),
//SND_PCM_FORMAT_U8, (SampleFormat::U8, alsa::pcm::Format::U8),
(SampleFormat::I16, alsa::pcm::Format::S16LE), (SampleFormat::I16, alsa::pcm::Format::S16LE),
//SND_PCM_FORMAT_S16_BE, //SND_PCM_FORMAT_S16_BE,
(SampleFormat::U16, alsa::pcm::Format::U16LE), (SampleFormat::U16, alsa::pcm::Format::U16LE),
@ -323,13 +323,13 @@ impl Device {
//SND_PCM_FORMAT_S24_BE, //SND_PCM_FORMAT_S24_BE,
//SND_PCM_FORMAT_U24_LE, //SND_PCM_FORMAT_U24_LE,
//SND_PCM_FORMAT_U24_BE, //SND_PCM_FORMAT_U24_BE,
//SND_PCM_FORMAT_S32_LE, (SampleFormat::I32, alsa::pcm::Format::S32LE),
//SND_PCM_FORMAT_S32_BE, //SND_PCM_FORMAT_S32_BE,
//SND_PCM_FORMAT_U32_LE, (SampleFormat::U32, alsa::pcm::Format::U32LE),
//SND_PCM_FORMAT_U32_BE, //SND_PCM_FORMAT_U32_BE,
(SampleFormat::F32, alsa::pcm::Format::FloatLE), (SampleFormat::F32, alsa::pcm::Format::FloatLE),
//SND_PCM_FORMAT_FLOAT_BE, //SND_PCM_FORMAT_FLOAT_BE,
//SND_PCM_FORMAT_FLOAT64_LE, (SampleFormat::F64, alsa::pcm::Format::Float64LE),
//SND_PCM_FORMAT_FLOAT64_BE, //SND_PCM_FORMAT_FLOAT64_BE,
//SND_PCM_FORMAT_IEC958_SUBFRAME_LE, //SND_PCM_FORMAT_IEC958_SUBFRAME_LE,
//SND_PCM_FORMAT_IEC958_SUBFRAME_BE, //SND_PCM_FORMAT_IEC958_SUBFRAME_BE,
@ -956,15 +956,53 @@ fn set_hw_params_from_format(
let sample_format = if cfg!(target_endian = "big") { let sample_format = if cfg!(target_endian = "big") {
match sample_format { match sample_format {
SampleFormat::I8 => alsa::pcm::Format::S8,
SampleFormat::I16 => alsa::pcm::Format::S16BE, SampleFormat::I16 => alsa::pcm::Format::S16BE,
// SampleFormat::I24 => alsa::pcm::Format::S24BE,
SampleFormat::I32 => alsa::pcm::Format::S32BE,
// SampleFormat::I48 => alsa::pcm::Format::S48BE,
// SampleFormat::I64 => alsa::pcm::Format::S64BE,
SampleFormat::U8 => alsa::pcm::Format::U8,
SampleFormat::U16 => alsa::pcm::Format::U16BE, SampleFormat::U16 => alsa::pcm::Format::U16BE,
// SampleFormat::U24 => alsa::pcm::Format::U24BE,
SampleFormat::U32 => alsa::pcm::Format::U32BE,
// SampleFormat::U48 => alsa::pcm::Format::U48BE,
// SampleFormat::U64 => alsa::pcm::Format::U64BE,
SampleFormat::F32 => alsa::pcm::Format::FloatBE, SampleFormat::F32 => alsa::pcm::Format::FloatBE,
SampleFormat::F64 => alsa::pcm::Format::Float64BE,
sample_format => {
return Err(BackendSpecificError {
description: format!(
"Sample format '{}' is not supported by this backend",
sample_format
),
})
}
} }
} else { } else {
match sample_format { match sample_format {
SampleFormat::I8 => alsa::pcm::Format::S8,
SampleFormat::I16 => alsa::pcm::Format::S16LE, SampleFormat::I16 => alsa::pcm::Format::S16LE,
// SampleFormat::I24 => alsa::pcm::Format::S24LE,
SampleFormat::I32 => alsa::pcm::Format::S32LE,
// SampleFormat::I48 => alsa::pcm::Format::S48LE,
// SampleFormat::I64 => alsa::pcm::Format::S64LE,
SampleFormat::U8 => alsa::pcm::Format::U8,
SampleFormat::U16 => alsa::pcm::Format::U16LE, SampleFormat::U16 => alsa::pcm::Format::U16LE,
// SampleFormat::U24 => alsa::pcm::Format::U24LE,
SampleFormat::U32 => alsa::pcm::Format::U32LE,
// SampleFormat::U48 => alsa::pcm::Format::U48LE,
// SampleFormat::U64 => alsa::pcm::Format::U64LE,
SampleFormat::F32 => alsa::pcm::Format::FloatLE, SampleFormat::F32 => alsa::pcm::Format::FloatLE,
SampleFormat::F64 => alsa::pcm::Format::Float64LE,
sample_format => {
return Err(BackendSpecificError {
description: format!(
"Sample format '{}' is not supported by this backend",
sample_format
),
})
}
} }
}; };

View file

@ -61,7 +61,7 @@ impl Device {
) -> Result<SupportedInputConfigs, SupportedStreamConfigsError> { ) -> Result<SupportedInputConfigs, SupportedStreamConfigsError> {
// Retrieve the default config for the total supported channels and supported sample // Retrieve the default config for the total supported channels and supported sample
// format. // format.
let mut f = match self.default_input_config() { let f = match self.default_input_config() {
Err(_) => return Err(SupportedStreamConfigsError::DeviceNotAvailable), Err(_) => return Err(SupportedStreamConfigsError::DeviceNotAvailable),
Ok(f) => f, Ok(f) => f,
}; };
@ -98,7 +98,7 @@ impl Device {
) -> Result<SupportedOutputConfigs, SupportedStreamConfigsError> { ) -> Result<SupportedOutputConfigs, SupportedStreamConfigsError> {
// Retrieve the default config for the total supported channels and supported sample // Retrieve the default config for the total supported channels and supported sample
// format. // format.
let mut f = match self.default_output_config() { let f = match self.default_output_config() {
Err(_) => return Err(SupportedStreamConfigsError::DeviceNotAvailable), Err(_) => return Err(SupportedStreamConfigsError::DeviceNotAvailable),
Ok(f) => f, Ok(f) => f,
}; };

View file

@ -1,12 +1,12 @@
extern crate asio_sys as sys; extern crate asio_sys as sys;
extern crate parking_lot; extern crate parking_lot;
use crate::traits::{DeviceTrait, HostTrait, StreamTrait};
use crate::{ use crate::{
BuildStreamError, Data, DefaultStreamConfigError, DeviceNameError, DevicesError, BuildStreamError, Data, DefaultStreamConfigError, DeviceNameError, DevicesError,
InputCallbackInfo, OutputCallbackInfo, PauseStreamError, PlayStreamError, SampleFormat, InputCallbackInfo, OutputCallbackInfo, PauseStreamError, PlayStreamError, SampleFormat,
StreamConfig, StreamError, SupportedStreamConfig, SupportedStreamConfigsError, StreamConfig, StreamError, SupportedStreamConfig, SupportedStreamConfigsError,
}; };
use traits::{DeviceTrait, HostTrait, StreamTrait};
pub use self::device::{Device, Devices, SupportedInputConfigs, SupportedOutputConfigs}; pub use self::device::{Device, Devices, SupportedInputConfigs, SupportedOutputConfigs};
pub use self::stream::Stream; pub use self::stream::Stream;

View file

@ -6,24 +6,13 @@ use super::parking_lot::Mutex;
use super::Device; use super::Device;
use crate::{ use crate::{
BackendSpecificError, BufferSize, BuildStreamError, Data, InputCallbackInfo, BackendSpecificError, BufferSize, BuildStreamError, Data, InputCallbackInfo,
OutputCallbackInfo, PauseStreamError, PlayStreamError, Sample, SampleFormat, StreamConfig, OutputCallbackInfo, PauseStreamError, PlayStreamError, SampleFormat, SizedSample, StreamConfig,
StreamError, StreamError,
}; };
use std; use std;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; use std::sync::Arc;
/// Sample types whose constant silent value is known.
trait Silence {
const SILENCE: Self;
}
/// Constraints on the ASIO sample types.
trait AsioSample: Clone + Copy + Silence + std::ops::Add<Self, Output = Self> {
fn to_cpal_sample<T: Sample>(&self) -> T;
fn from_cpal_sample<T: Sample>(_: &T) -> Self;
}
// Used to keep track of whether or not the current asio stream buffer requires // Used to keep track of whether or not the current asio stream buffer requires
// being silencing before summing audio. // being silencing before summing audio.
#[derive(Default)] #[derive(Default)]
@ -103,7 +92,7 @@ impl Device {
/// 1. Write from the ASIO buffer to the interleaved CPAL buffer. /// 1. Write from the ASIO buffer to the interleaved CPAL buffer.
/// 2. Deliver the CPAL buffer to the user callback. /// 2. Deliver the CPAL buffer to the user callback.
unsafe fn process_input_callback<A, B, D, F>( unsafe fn process_input_callback<A, D, F>(
data_callback: &mut D, data_callback: &mut D,
interleaved: &mut [u8], interleaved: &mut [u8],
asio_stream: &sys::AsioStream, asio_stream: &sys::AsioStream,
@ -111,27 +100,26 @@ impl Device {
sample_rate: crate::SampleRate, sample_rate: crate::SampleRate,
from_endianness: F, from_endianness: F,
) where ) where
A: AsioSample, A: SizedSample,
B: Sample,
D: FnMut(&Data, &InputCallbackInfo) + Send + 'static, D: FnMut(&Data, &InputCallbackInfo) + Send + 'static,
F: Fn(A) -> A, F: Fn(A) -> A,
{ {
// 1. Write the ASIO channels to the CPAL buffer. // 1. Write the ASIO channels to the CPAL buffer.
let interleaved: &mut [B] = cast_slice_mut(interleaved); let interleaved: &mut [A] = cast_slice_mut(interleaved);
let n_frames = asio_stream.buffer_size as usize; let n_frames = asio_stream.buffer_size as usize;
let n_channels = interleaved.len() / n_frames; let n_channels = interleaved.len() / n_frames;
let buffer_index = asio_info.buffer_index as usize; let buffer_index = asio_info.buffer_index as usize;
for ch_ix in 0..n_channels { for ch_ix in 0..n_channels {
let asio_channel = asio_channel_slice::<A>(asio_stream, buffer_index, ch_ix); let asio_channel = asio_channel_slice::<A>(asio_stream, buffer_index, ch_ix);
for (frame, s_asio) in interleaved.chunks_mut(n_channels).zip(asio_channel) { for (frame, s_asio) in interleaved.chunks_mut(n_channels).zip(asio_channel) {
frame[ch_ix] = from_endianness(*s_asio).to_cpal_sample(); frame[ch_ix] = from_endianness(*s_asio);
} }
} }
// 2. Deliver the interleaved buffer to the callback. // 2. Deliver the interleaved buffer to the callback.
let data = interleaved.as_mut_ptr() as *mut (); let data = interleaved.as_mut_ptr() as *mut ();
let len = interleaved.len(); let len = interleaved.len();
let data = Data::from_parts(data, len, B::FORMAT); let data = Data::from_parts(data, len, A::FORMAT);
let callback = system_time_to_stream_instant(asio_info.system_time); let callback = system_time_to_stream_instant(asio_info.system_time);
let delay = frames_to_duration(n_frames, sample_rate); let delay = frames_to_duration(n_frames, sample_rate);
let capture = callback let capture = callback
@ -144,7 +132,7 @@ impl Device {
match (&stream_type, sample_format) { match (&stream_type, sample_format) {
(&sys::AsioSampleType::ASIOSTInt16LSB, SampleFormat::I16) => { (&sys::AsioSampleType::ASIOSTInt16LSB, SampleFormat::I16) => {
process_input_callback::<i16, i16, _, _>( process_input_callback::<i16, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
asio_stream, asio_stream,
@ -154,7 +142,7 @@ impl Device {
); );
} }
(&sys::AsioSampleType::ASIOSTInt16MSB, SampleFormat::I16) => { (&sys::AsioSampleType::ASIOSTInt16MSB, SampleFormat::I16) => {
process_input_callback::<i16, i16, _, _>( process_input_callback::<i16, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
asio_stream, asio_stream,
@ -168,7 +156,7 @@ impl Device {
// trait for the `to_le` and `to_be` methods, but this does not support floats. // trait for the `to_le` and `to_be` methods, but this does not support floats.
(&sys::AsioSampleType::ASIOSTFloat32LSB, SampleFormat::F32) (&sys::AsioSampleType::ASIOSTFloat32LSB, SampleFormat::F32)
| (&sys::AsioSampleType::ASIOSTFloat32MSB, SampleFormat::F32) => { | (&sys::AsioSampleType::ASIOSTFloat32MSB, SampleFormat::F32) => {
process_input_callback::<f32, f32, _, _>( process_input_callback::<f32, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
asio_stream, asio_stream,
@ -178,11 +166,8 @@ impl Device {
); );
} }
// TODO: Add support for the following sample formats to CPAL and simplify the (&sys::AsioSampleType::ASIOSTInt32LSB, SampleFormat::I32) => {
// `process_output_callback` function above by removing the unnecessary sample process_input_callback::<i32, _, _>(
// conversion function.
(&sys::AsioSampleType::ASIOSTInt32LSB, SampleFormat::I16) => {
process_input_callback::<i32, i16, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
asio_stream, asio_stream,
@ -191,8 +176,8 @@ impl Device {
from_le, from_le,
); );
} }
(&sys::AsioSampleType::ASIOSTInt32MSB, SampleFormat::I16) => { (&sys::AsioSampleType::ASIOSTInt32MSB, SampleFormat::I32) => {
process_input_callback::<i32, i16, _, _>( process_input_callback::<i32, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
asio_stream, asio_stream,
@ -201,11 +186,12 @@ impl Device {
from_be, from_be,
); );
} }
// TODO: Handle endianness conversion for floats? We currently use the `PrimInt` // TODO: Handle endianness conversion for floats? We currently use the `PrimInt`
// trait for the `to_le` and `to_be` methods, but this does not support floats. // trait for the `to_le` and `to_be` methods, but this does not support floats.
(&sys::AsioSampleType::ASIOSTFloat64LSB, SampleFormat::F32) (&sys::AsioSampleType::ASIOSTFloat64LSB, SampleFormat::F64)
| (&sys::AsioSampleType::ASIOSTFloat64MSB, SampleFormat::F32) => { | (&sys::AsioSampleType::ASIOSTFloat64MSB, SampleFormat::F64) => {
process_input_callback::<f64, f32, _, _>( process_input_callback::<f64, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
asio_stream, asio_stream,
@ -310,7 +296,7 @@ impl Device {
/// 2. If required, silence the ASIO buffer. /// 2. If required, silence the ASIO buffer.
/// 3. Finally, write the interleaved data to the non-interleaved ASIO buffer, /// 3. Finally, write the interleaved data to the non-interleaved ASIO buffer,
/// performing endianness conversions as necessary. /// performing endianness conversions as necessary.
unsafe fn process_output_callback<A, B, D, F>( unsafe fn process_output_callback<A, D, F>(
data_callback: &mut D, data_callback: &mut D,
interleaved: &mut [u8], interleaved: &mut [u8],
silence_asio_buffer: bool, silence_asio_buffer: bool,
@ -319,10 +305,9 @@ impl Device {
sample_rate: crate::SampleRate, sample_rate: crate::SampleRate,
to_endianness: F, to_endianness: F,
) where ) where
A: Sample, A: SizedSample + std::ops::Add<Output = A>,
B: AsioSample,
D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static, D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static,
F: Fn(B) -> B, F: Fn(A) -> A,
{ {
// 1. Render interleaved buffer from callback. // 1. Render interleaved buffer from callback.
let interleaved: &mut [A] = cast_slice_mut(interleaved); let interleaved: &mut [A] = cast_slice_mut(interleaved);
@ -345,26 +330,26 @@ impl Device {
if silence_asio_buffer { if silence_asio_buffer {
for ch_ix in 0..n_channels { for ch_ix in 0..n_channels {
let asio_channel = let asio_channel =
asio_channel_slice_mut::<B>(asio_stream, buffer_index, ch_ix); asio_channel_slice_mut::<A>(asio_stream, buffer_index, ch_ix);
asio_channel asio_channel
.iter_mut() .iter_mut()
.for_each(|s| *s = to_endianness(B::SILENCE)); .for_each(|s| *s = to_endianness(A::EQUILIBRIUM));
} }
} }
// 3. Write interleaved samples to ASIO channels, one channel at a time. // 3. Write interleaved samples to ASIO channels, one channel at a time.
for ch_ix in 0..n_channels { for ch_ix in 0..n_channels {
let asio_channel = let asio_channel =
asio_channel_slice_mut::<B>(asio_stream, buffer_index, ch_ix); asio_channel_slice_mut::<A>(asio_stream, buffer_index, ch_ix);
for (frame, s_asio) in interleaved.chunks(n_channels).zip(asio_channel) { for (frame, s_asio) in interleaved.chunks(n_channels).zip(asio_channel) {
*s_asio = *s_asio + to_endianness(B::from_cpal_sample(&frame[ch_ix])); *s_asio = *s_asio + to_endianness(A::from_sample(frame[ch_ix]));
} }
} }
} }
match (sample_format, &stream_type) { match (sample_format, &stream_type) {
(SampleFormat::I16, &sys::AsioSampleType::ASIOSTInt16LSB) => { (SampleFormat::I16, &sys::AsioSampleType::ASIOSTInt16LSB) => {
process_output_callback::<i16, i16, _, _>( process_output_callback::<i16, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
silence, silence,
@ -375,7 +360,7 @@ impl Device {
); );
} }
(SampleFormat::I16, &sys::AsioSampleType::ASIOSTInt16MSB) => { (SampleFormat::I16, &sys::AsioSampleType::ASIOSTInt16MSB) => {
process_output_callback::<i16, i16, _, _>( process_output_callback::<i16, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
silence, silence,
@ -390,7 +375,7 @@ impl Device {
// trait for the `to_le` and `to_be` methods, but this does not support floats. // trait for the `to_le` and `to_be` methods, but this does not support floats.
(SampleFormat::F32, &sys::AsioSampleType::ASIOSTFloat32LSB) (SampleFormat::F32, &sys::AsioSampleType::ASIOSTFloat32LSB)
| (SampleFormat::F32, &sys::AsioSampleType::ASIOSTFloat32MSB) => { | (SampleFormat::F32, &sys::AsioSampleType::ASIOSTFloat32MSB) => {
process_output_callback::<f32, f32, _, _>( process_output_callback::<f32, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
silence, silence,
@ -401,11 +386,8 @@ impl Device {
); );
} }
// TODO: Add support for the following sample formats to CPAL and simplify the (SampleFormat::I32, &sys::AsioSampleType::ASIOSTInt32LSB) => {
// `process_output_callback` function above by removing the unnecessary sample process_output_callback::<i32, _, _>(
// conversion function.
(SampleFormat::I16, &sys::AsioSampleType::ASIOSTInt32LSB) => {
process_output_callback::<i16, i32, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
silence, silence,
@ -415,8 +397,8 @@ impl Device {
to_le, to_le,
); );
} }
(SampleFormat::I16, &sys::AsioSampleType::ASIOSTInt32MSB) => { (SampleFormat::I32, &sys::AsioSampleType::ASIOSTInt32MSB) => {
process_output_callback::<i16, i32, _, _>( process_output_callback::<i32, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
silence, silence,
@ -426,11 +408,12 @@ impl Device {
to_be, to_be,
); );
} }
// TODO: Handle endianness conversion for floats? We currently use the `PrimInt` // TODO: Handle endianness conversion for floats? We currently use the `PrimInt`
// trait for the `to_le` and `to_be` methods, but this does not support floats. // trait for the `to_le` and `to_be` methods, but this does not support floats.
(SampleFormat::F32, &sys::AsioSampleType::ASIOSTFloat64LSB) (SampleFormat::F64, &sys::AsioSampleType::ASIOSTFloat64LSB)
| (SampleFormat::F32, &sys::AsioSampleType::ASIOSTFloat64MSB) => { | (SampleFormat::F64, &sys::AsioSampleType::ASIOSTFloat64MSB) => {
process_output_callback::<f32, f64, _, _>( process_output_callback::<f64, _, _>(
&mut data_callback, &mut data_callback,
&mut interleaved, &mut interleaved,
silence, silence,
@ -566,62 +549,6 @@ impl Drop for Stream {
} }
} }
impl Silence for i16 {
const SILENCE: Self = 0;
}
impl Silence for i32 {
const SILENCE: Self = 0;
}
impl Silence for f32 {
const SILENCE: Self = 0.0;
}
impl Silence for f64 {
const SILENCE: Self = 0.0;
}
impl AsioSample for i16 {
fn to_cpal_sample<T: Sample>(&self) -> T {
T::from(self)
}
fn from_cpal_sample<T: Sample>(t: &T) -> Self {
Sample::from(t)
}
}
impl AsioSample for i32 {
fn to_cpal_sample<T: Sample>(&self) -> T {
let s = (*self >> 16) as i16;
s.to_cpal_sample()
}
fn from_cpal_sample<T: Sample>(t: &T) -> Self {
let s = i16::from_cpal_sample(t);
(s as i32) << 16
}
}
impl AsioSample for f32 {
fn to_cpal_sample<T: Sample>(&self) -> T {
T::from(self)
}
fn from_cpal_sample<T: Sample>(t: &T) -> Self {
Sample::from(t)
}
}
impl AsioSample for f64 {
fn to_cpal_sample<T: Sample>(&self) -> T {
let f = *self as f32;
f.to_cpal_sample()
}
fn from_cpal_sample<T: Sample>(t: &T) -> Self {
let f = f32::from_cpal_sample(t);
f as f64
}
}
fn asio_ns_to_double(val: sys::bindings::asio_import::ASIOTimeStamp) -> f64 { fn asio_ns_to_double(val: sys::bindings::asio_import::ASIOTimeStamp) -> f64 {
let two_raised_to_32 = 4294967296.0; let two_raised_to_32 = 4294967296.0;
val.lo as f64 + val.hi as f64 * two_raised_to_32 val.lo as f64 + val.hi as f64 * two_raised_to_32
@ -657,7 +584,7 @@ fn check_config(
let StreamConfig { let StreamConfig {
channels, channels,
sample_rate, sample_rate,
buffer_size, buffer_size: _,
} = config; } = config;
// Try and set the sample rate to what the user selected. // Try and set the sample rate to what the user selected.
let sample_rate = sample_rate.0.into(); let sample_rate = sample_rate.0.into();
@ -676,7 +603,7 @@ fn check_config(
// unsigned formats are not supported by asio // unsigned formats are not supported by asio
match sample_format { match sample_format {
SampleFormat::I16 | SampleFormat::F32 => (), SampleFormat::I16 | SampleFormat::F32 => (),
SampleFormat::U16 => return Err(BuildStreamError::StreamConfigNotSupported), _ => return Err(BuildStreamError::StreamConfigNotSupported),
} }
if *channels > num_asio_channels { if *channels > num_asio_channels {
return Err(BuildStreamError::StreamConfigNotSupported); return Err(BuildStreamError::StreamConfigNotSupported);

View file

@ -4,7 +4,7 @@ use std::time::Instant;
extern crate oboe; extern crate oboe;
use super::convert::{stream_instant, to_stream_instant}; use super::convert::{stream_instant, to_stream_instant};
use crate::{Data, InputCallbackInfo, InputStreamTimestamp, Sample, StreamError}; use crate::{Data, InputCallbackInfo, InputStreamTimestamp, SizedSample, StreamError};
pub struct CpalInputCallback<I, C> { pub struct CpalInputCallback<I, C> {
data_cb: Box<dyn FnMut(&Data, &InputCallbackInfo) + Send + 'static>, data_cb: Box<dyn FnMut(&Data, &InputCallbackInfo) + Send + 'static>,
@ -42,7 +42,7 @@ impl<I, C> CpalInputCallback<I, C> {
} }
} }
impl<T: Sample, C: oboe::IsChannelCount> oboe::AudioInputCallback for CpalInputCallback<T, C> impl<T: SizedSample, C: oboe::IsChannelCount> oboe::AudioInputCallback for CpalInputCallback<T, C>
where where
(T, C): oboe::IsFrameType, (T, C): oboe::IsFrameType,
{ {

View file

@ -9,7 +9,7 @@ use crate::traits::{DeviceTrait, HostTrait, StreamTrait};
use crate::{ use crate::{
BackendSpecificError, BufferSize, BuildStreamError, Data, DefaultStreamConfigError, BackendSpecificError, BufferSize, BuildStreamError, Data, DefaultStreamConfigError,
DeviceNameError, DevicesError, InputCallbackInfo, OutputCallbackInfo, PauseStreamError, DeviceNameError, DevicesError, InputCallbackInfo, OutputCallbackInfo, PauseStreamError,
PlayStreamError, Sample, SampleFormat, SampleRate, StreamConfig, StreamError, PlayStreamError, SampleFormat, SampleRate, SizedSample, StreamConfig, StreamError,
SupportedBufferSize, SupportedStreamConfig, SupportedStreamConfigRange, SupportedBufferSize, SupportedStreamConfig, SupportedStreamConfigRange,
SupportedStreamConfigsError, SupportedStreamConfigsError,
}; };
@ -225,7 +225,7 @@ fn build_input_stream<D, E, C, T>(
builder: oboe::AudioStreamBuilder<oboe::Input, C, T>, builder: oboe::AudioStreamBuilder<oboe::Input, C, T>,
) -> Result<Stream, BuildStreamError> ) -> Result<Stream, BuildStreamError>
where where
T: Sample + oboe::IsFormat + Send + 'static, T: SizedSample + oboe::IsFormat + Send + 'static,
C: oboe::IsChannelCount + Send + 'static, C: oboe::IsChannelCount + Send + 'static,
(T, C): oboe::IsFrameType, (T, C): oboe::IsFrameType,
D: FnMut(&Data, &InputCallbackInfo) + Send + 'static, D: FnMut(&Data, &InputCallbackInfo) + Send + 'static,
@ -249,7 +249,7 @@ fn build_output_stream<D, E, C, T>(
builder: oboe::AudioStreamBuilder<oboe::Output, C, T>, builder: oboe::AudioStreamBuilder<oboe::Output, C, T>,
) -> Result<Stream, BuildStreamError> ) -> Result<Stream, BuildStreamError>
where where
T: Sample + oboe::IsFormat + Send + 'static, T: SizedSample + oboe::IsFormat + Send + 'static,
C: oboe::IsChannelCount + Send + 'static, C: oboe::IsChannelCount + Send + 'static,
(T, C): oboe::IsFrameType, (T, C): oboe::IsFrameType,
D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static, D: FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static,
@ -385,8 +385,8 @@ impl DeviceTrait for Device {
.into()) .into())
} }
} }
SampleFormat::U16 => Err(BackendSpecificError { sample_format => Err(BackendSpecificError {
description: "U16 format is not supported on Android.".to_owned(), description: format!("{} format is not supported on Android.", sample_format),
} }
.into()), .into()),
} }
@ -458,8 +458,8 @@ impl DeviceTrait for Device {
.into()) .into())
} }
} }
SampleFormat::U16 => Err(BackendSpecificError { sample_format => Err(BackendSpecificError {
description: "U16 format is not supported on Android.".to_owned(), description: format!("{} format is not supported on Android.", sample_format),
} }
.into()), .into()),
} }

View file

@ -4,7 +4,7 @@ use std::time::Instant;
extern crate oboe; extern crate oboe;
use super::convert::{stream_instant, to_stream_instant}; use super::convert::{stream_instant, to_stream_instant};
use crate::{Data, OutputCallbackInfo, OutputStreamTimestamp, Sample, StreamError}; use crate::{Data, OutputCallbackInfo, OutputStreamTimestamp, SizedSample, StreamError};
pub struct CpalOutputCallback<I, C> { pub struct CpalOutputCallback<I, C> {
data_cb: Box<dyn FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static>, data_cb: Box<dyn FnMut(&mut Data, &OutputCallbackInfo) + Send + 'static>,
@ -42,7 +42,7 @@ impl<I, C> CpalOutputCallback<I, C> {
} }
} }
impl<T: Sample, C: oboe::IsChannelCount> oboe::AudioOutputCallback for CpalOutputCallback<T, C> impl<T: SizedSample, C: oboe::IsChannelCount> oboe::AudioOutputCallback for CpalOutputCallback<T, C>
where where
(T, C): oboe::IsFrameType, (T, C): oboe::IsFrameType,
{ {

View file

@ -6,7 +6,6 @@ use crate::{
SupportedStreamConfigsError, COMMON_SAMPLE_RATES, SupportedStreamConfigsError, COMMON_SAMPLE_RATES,
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use std;
use std::ffi::OsString; use std::ffi::OsString;
use std::fmt; use std::fmt;
use std::mem; use std::mem;
@ -453,10 +452,7 @@ impl Device {
.map_err(windows_err_to_cpal_err::<SupportedStreamConfigsError>)?; .map_err(windows_err_to_cpal_err::<SupportedStreamConfigsError>)?;
// If the default format can't succeed we have no hope of finding other formats. // If the default format can't succeed we have no hope of finding other formats.
assert_eq!( assert!(is_format_supported(client, default_waveformatex_ptr.0)?);
is_format_supported(client, default_waveformatex_ptr.0)?,
true
);
// Copy the format to use as a test format (as to avoid mutating the original format). // Copy the format to use as a test format (as to avoid mutating the original format).
let mut test_format = { let mut test_format = {
@ -496,7 +492,7 @@ impl Device {
// TODO: Test the different sample formats? // TODO: Test the different sample formats?
// Create the supported formats. // Create the supported formats.
let format = match format_from_waveformatex_ptr(default_waveformatex_ptr.0, &client) { let format = match format_from_waveformatex_ptr(default_waveformatex_ptr.0, client) {
Some(fmt) => fmt, Some(fmt) => fmt,
None => { None => {
let description = let description =
@ -509,11 +505,11 @@ impl Device {
let mut supported_formats = Vec::with_capacity(supported_sample_rates.len()); let mut supported_formats = Vec::with_capacity(supported_sample_rates.len());
for rate in supported_sample_rates { for rate in supported_sample_rates {
supported_formats.push(SupportedStreamConfigRange { supported_formats.push(SupportedStreamConfigRange {
channels: format.channels.clone(), channels: format.channels,
min_sample_rate: SampleRate(rate as _), min_sample_rate: SampleRate(rate as _),
max_sample_rate: SampleRate(rate as _), max_sample_rate: SampleRate(rate as _),
buffer_size: format.buffer_size.clone(), buffer_size: format.buffer_size.clone(),
sample_format: format.sample_format.clone(), sample_format: format.sample_format,
}) })
} }
Ok(supported_formats.into_iter()) Ok(supported_formats.into_iter())
@ -1015,7 +1011,7 @@ fn config_to_waveformatextensible(
let format_tag = match sample_format { let format_tag = match sample_format {
SampleFormat::I16 => Audio::WAVE_FORMAT_PCM, SampleFormat::I16 => Audio::WAVE_FORMAT_PCM,
SampleFormat::F32 => KernelStreaming::WAVE_FORMAT_EXTENSIBLE, SampleFormat::F32 => KernelStreaming::WAVE_FORMAT_EXTENSIBLE,
SampleFormat::U16 => return None, _ => return None,
} as u16; } as u16;
let channels = config.channels; let channels = config.channels;
let sample_rate = config.sample_rate.0; let sample_rate = config.sample_rate.0;
@ -1030,7 +1026,7 @@ fn config_to_waveformatextensible(
let ex_size = mem::size_of::<Audio::WAVEFORMATEX>(); let ex_size = mem::size_of::<Audio::WAVEFORMATEX>();
(extensible_size - ex_size) as u16 (extensible_size - ex_size) as u16
} }
SampleFormat::U16 => return None, _ => return None,
}; };
let waveformatex = Audio::WAVEFORMATEX { let waveformatex = Audio::WAVEFORMATEX {
wFormatTag: format_tag, wFormatTag: format_tag,
@ -1048,7 +1044,7 @@ fn config_to_waveformatextensible(
let sub_format = match sample_format { let sub_format = match sample_format {
SampleFormat::I16 => KernelStreaming::KSDATAFORMAT_SUBTYPE_PCM, SampleFormat::I16 => KernelStreaming::KSDATAFORMAT_SUBTYPE_PCM,
SampleFormat::F32 => Multimedia::KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, SampleFormat::F32 => Multimedia::KSDATAFORMAT_SUBTYPE_IEEE_FLOAT,
SampleFormat::U16 => return None, _ => return None,
}; };
let waveformatextensible = Audio::WAVEFORMATEXTENSIBLE { let waveformatextensible = Audio::WAVEFORMATEXTENSIBLE {
Format: waveformatex, Format: waveformatex,

View file

@ -287,7 +287,7 @@ fn run_input(
_ => unreachable!(), _ => unreachable!(),
}; };
match process_input( match process_input(
&mut run_ctxt.stream, &run_ctxt.stream,
capture_client, capture_client,
data_callback, data_callback,
error_callback, error_callback,
@ -314,7 +314,7 @@ fn run_output(
_ => unreachable!(), _ => unreachable!(),
}; };
match process_output( match process_output(
&mut run_ctxt.stream, &run_ctxt.stream,
render_client, render_client,
data_callback, data_callback,
error_callback, error_callback,
@ -439,7 +439,7 @@ fn process_output(
error_callback: &mut dyn FnMut(StreamError), error_callback: &mut dyn FnMut(StreamError),
) -> ControlFlow { ) -> ControlFlow {
// The number of frames available for writing. // The number of frames available for writing.
let frames_available = match get_available_frames(&stream) { let frames_available = match get_available_frames(stream) {
Ok(0) => return ControlFlow::Continue, // TODO: Can this happen? Ok(0) => return ControlFlow::Continue, // TODO: Can this happen?
Ok(n) => n, Ok(n) => n,
Err(err) => { Err(err) => {

View file

@ -88,7 +88,7 @@
//! In this example, we simply fill the given output buffer with silence. //! In this example, we simply fill the given output buffer with silence.
//! //!
//! ```no_run //! ```no_run
//! use cpal::{Data, Sample, SampleFormat}; //! use cpal::{Data, Sample, SampleFormat, FromSample};
//! use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; //! use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
//! # let host = cpal::default_host(); //! # let host = cpal::default_host();
//! # let device = host.default_output_device().unwrap(); //! # let device = host.default_output_device().unwrap();
@ -100,11 +100,12 @@
//! SampleFormat::F32 => device.build_output_stream(&config, write_silence::<f32>, err_fn), //! SampleFormat::F32 => device.build_output_stream(&config, write_silence::<f32>, err_fn),
//! SampleFormat::I16 => device.build_output_stream(&config, write_silence::<i16>, err_fn), //! SampleFormat::I16 => device.build_output_stream(&config, write_silence::<i16>, err_fn),
//! SampleFormat::U16 => device.build_output_stream(&config, write_silence::<u16>, err_fn), //! SampleFormat::U16 => device.build_output_stream(&config, write_silence::<u16>, err_fn),
//! sample_format => panic!("Unsupported sample format '{sample_format}'")
//! }.unwrap(); //! }.unwrap();
//! //!
//! fn write_silence<T: Sample>(data: &mut [T], _: &cpal::OutputCallbackInfo) { //! fn write_silence<T: Sample>(data: &mut [T], _: &cpal::OutputCallbackInfo) {
//! for sample in data.iter_mut() { //! for sample in data.iter_mut() {
//! *sample = Sample::from(&0.0); //! *sample = Sample::EQUILIBRIUM;
//! } //! }
//! } //! }
//! ``` //! ```
@ -154,7 +155,7 @@ pub use platform::{
available_hosts, default_host, host_from_id, Device, Devices, Host, HostId, Stream, available_hosts, default_host, host_from_id, Device, Devices, Host, HostId, Stream,
SupportedInputConfigs, SupportedOutputConfigs, ALL_HOSTS, SupportedInputConfigs, SupportedOutputConfigs, ALL_HOSTS,
}; };
pub use samples_formats::{Sample, SampleFormat}; pub use samples_formats::{FromSample, Sample, SampleFormat, SizedSample, I24, I48, U24, U48};
use std::convert::TryInto; use std::convert::TryInto;
use std::ops::{Div, Mul}; use std::ops::{Div, Mul};
use std::time::Duration; use std::time::Duration;
@ -516,7 +517,7 @@ impl Data {
/// Returns `None` if the sample type does not match the expected sample format. /// Returns `None` if the sample type does not match the expected sample format.
pub fn as_slice<T>(&self) -> Option<&[T]> pub fn as_slice<T>(&self) -> Option<&[T]>
where where
T: Sample, T: SizedSample,
{ {
if T::FORMAT == self.sample_format { if T::FORMAT == self.sample_format {
// The safety of this block relies on correct construction of the `Data` instance. See // The safety of this block relies on correct construction of the `Data` instance. See
@ -532,7 +533,7 @@ impl Data {
/// Returns `None` if the sample type does not match the expected sample format. /// Returns `None` if the sample type does not match the expected sample format.
pub fn as_slice_mut<T>(&mut self) -> Option<&mut [T]> pub fn as_slice_mut<T>(&mut self) -> Option<&mut [T]>
where where
T: Sample, T: SizedSample,
{ {
if T::FORMAT == self.sample_format { if T::FORMAT == self.sample_format {
// The safety of this block relies on correct construction of the `Data` instance. See // The safety of this block relies on correct construction of the `Data` instance. See
@ -762,7 +763,7 @@ impl From<SupportedStreamConfig> for StreamConfig {
// //
// If a rate you desire is missing from this list, feel free to add it! // If a rate you desire is missing from this list, feel free to add it!
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
const COMMON_SAMPLE_RATES: &'static [SampleRate] = &[ const COMMON_SAMPLE_RATES: &[SampleRate] = &[
SampleRate(5512), SampleRate(5512),
SampleRate(8000), SampleRate(8000),
SampleRate(11025), SampleRate(11025),

View file

@ -1,206 +1,164 @@
use std::mem; use std::{fmt::Display, mem};
pub use dasp_sample::{FromSample, Sample, I24, I48, U24, U48};
/// Format that each sample has. /// Format that each sample has.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum SampleFormat { pub enum SampleFormat {
/// The value 0 corresponds to 0. /// `i8` with a valid range of 'u8::MIN..=u8::MAX' with `0` being the origin
I8,
/// `i16` with a valid range of 'u16::MIN..=u16::MAX' with `0` being the origin
I16, I16,
/// The value 0 corresponds to 32768.
// /// `I24` with a valid range of '-(1 << 23)..(1 << 23)' with `0` being the origin
// I24,
/// `i32` with a valid range of 'u32::MIN..=u32::MAX' with `0` being the origin
I32,
// /// `I24` with a valid range of '-(1 << 47)..(1 << 47)' with `0` being the origin
// I48,
/// `i64` with a valid range of 'u64::MIN..=u64::MAX' with `0` being the origin
I64,
/// `u8` with a valid range of 'u8::MIN..=u8::MAX' with `1 << 7 == 128` being the origin
U8,
/// `u16` with a valid range of 'u16::MIN..=u16::MAX' with `1 << 15 == 32768` being the origin
U16, U16,
/// The boundaries are (-1.0, 1.0).
// /// `U24` with a valid range of '0..16777216' with `1 << 23 == 8388608` being the origin
// U24,
/// `u32` with a valid range of 'u32::MIN..=u32::MAX' with `1 << 31` being the origin
U32,
// /// `U48` with a valid range of '0..(1 << 48)' with `1 << 47` being the origin
// U48,
/// `u64` with a valid range of 'u64::MIN..=u64::MAX' with `1 << 63` being the origin
U64,
/// `f32` with a valid range of `-1.0..1.0` with `0.0` being the origin
F32, F32,
/// `f64` with a valid range of -1.0..1.0 with 0.0 being the origin
F64,
} }
impl SampleFormat { impl SampleFormat {
/// Returns the size in bytes of a sample of this format. /// Returns the size in bytes of a sample of this format.
#[inline] #[inline]
#[must_use]
pub fn sample_size(&self) -> usize { pub fn sample_size(&self) -> usize {
match *self { match *self {
SampleFormat::I16 => mem::size_of::<i16>(), SampleFormat::I8 | SampleFormat::U8 => mem::size_of::<i8>(),
SampleFormat::U16 => mem::size_of::<u16>(), SampleFormat::I16 | SampleFormat::U16 => mem::size_of::<i16>(),
// SampleFormat::I24 | SampleFormat::U24 => 3,
SampleFormat::I32 | SampleFormat::U32 => mem::size_of::<i32>(),
// SampleFormat::I48 | SampleFormat::U48 => 6,
SampleFormat::I64 | SampleFormat::U64 => mem::size_of::<i64>(),
SampleFormat::F32 => mem::size_of::<f32>(), SampleFormat::F32 => mem::size_of::<f32>(),
SampleFormat::F64 => mem::size_of::<f64>(),
} }
} }
#[inline]
#[must_use]
pub fn is_int(&self) -> bool {
//matches!(*self, SampleFormat::I8 | SampleFormat::I16 | SampleFormat::I24 | SampleFormat::I32 | SampleFormat::I48 | SampleFormat::I64)
matches!(
*self,
SampleFormat::I8 | SampleFormat::I16 | SampleFormat::I32 | SampleFormat::I64
)
}
#[inline]
#[must_use]
pub fn is_uint(&self) -> bool {
//matches!(*self, SampleFormat::U8 | SampleFormat::U16 | SampleFormat::U24 | SampleFormat::U32 | SampleFormat::U48 | SampleFormat::U64)
matches!(
*self,
SampleFormat::U8 | SampleFormat::U16 | SampleFormat::U32 | SampleFormat::U64
)
}
#[inline]
#[must_use]
pub fn is_float(&self) -> bool {
matches!(*self, SampleFormat::F32 | SampleFormat::F64)
}
} }
/// Trait for containers that contain PCM data. impl Display for SampleFormat {
pub unsafe trait Sample: Copy + Clone { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// The `SampleFormat` corresponding to this data type. match *self {
SampleFormat::I8 => "i8",
SampleFormat::I16 => "i16",
// SampleFormat::I24 => "i24",
SampleFormat::I32 => "i32",
// SampleFormat::I48 => "i48",
SampleFormat::I64 => "i64",
SampleFormat::U8 => "u8",
SampleFormat::U16 => "u16",
// SampleFormat::U24 => "u24",
SampleFormat::U32 => "u32",
// SampleFormat::U48 => "u48",
SampleFormat::U64 => "u64",
SampleFormat::F32 => "f32",
SampleFormat::F64 => "f64",
}
.fmt(f)
}
}
pub trait SizedSample: Sample {
const FORMAT: SampleFormat; const FORMAT: SampleFormat;
/// Turns the sample into its equivalent as a floating-point.
fn to_f32(&self) -> f32;
/// Converts this sample into a standard i16 sample.
fn to_i16(&self) -> i16;
/// Converts this sample into a standard u16 sample.
fn to_u16(&self) -> u16;
/// Converts any sample type to this one by calling `to_i16`, `to_u16` or `to_f32`.
fn from<S>(s: &S) -> Self
where
S: Sample;
} }
unsafe impl Sample for u16 { impl SizedSample for i8 {
const FORMAT: SampleFormat = SampleFormat::U16; const FORMAT: SampleFormat = SampleFormat::I8;
#[inline]
fn to_f32(&self) -> f32 {
self.to_i16().to_f32()
}
#[inline]
fn to_i16(&self) -> i16 {
(*self as i16).wrapping_add(i16::MIN)
}
#[inline]
fn to_u16(&self) -> u16 {
*self
}
#[inline]
fn from<S>(sample: &S) -> Self
where
S: Sample,
{
sample.to_u16()
}
} }
unsafe impl Sample for i16 { impl SizedSample for i16 {
const FORMAT: SampleFormat = SampleFormat::I16; const FORMAT: SampleFormat = SampleFormat::I16;
#[inline]
fn to_f32(&self) -> f32 {
if *self < 0 {
*self as f32 / -(i16::MIN as f32)
} else {
*self as f32 / i16::MAX as f32
}
}
#[inline]
fn to_i16(&self) -> i16 {
*self
}
#[inline]
fn to_u16(&self) -> u16 {
self.wrapping_add(i16::MIN) as u16
}
#[inline]
fn from<S>(sample: &S) -> Self
where
S: Sample,
{
sample.to_i16()
}
} }
const F32_TO_16BIT_INT_MULTIPLIER: f32 = u16::MAX as f32 * 0.5;
unsafe impl Sample for f32 { // impl SizedSample for I24 { const FORMAT: SampleFormat = SampleFormat::I24; }
impl SizedSample for i32 {
const FORMAT: SampleFormat = SampleFormat::I32;
}
// impl SizedSample for I48 { const FORMAT: SampleFormat = SampleFormat::I48; }
impl SizedSample for i64 {
const FORMAT: SampleFormat = SampleFormat::I64;
}
impl SizedSample for u8 {
const FORMAT: SampleFormat = SampleFormat::U8;
}
impl SizedSample for u16 {
const FORMAT: SampleFormat = SampleFormat::U16;
}
// impl SizedSample for U24 { const FORMAT: SampleFormat = SampleFormat::U24; }
impl SizedSample for u32 {
const FORMAT: SampleFormat = SampleFormat::U32;
}
// impl SizedSample for U48 { const FORMAT: SampleFormat = SampleFormat::U48; }
impl SizedSample for u64 {
const FORMAT: SampleFormat = SampleFormat::U64;
}
impl SizedSample for f32 {
const FORMAT: SampleFormat = SampleFormat::F32; const FORMAT: SampleFormat = SampleFormat::F32;
#[inline]
fn to_f32(&self) -> f32 {
*self
}
#[inline]
fn to_i16(&self) -> i16 {
if *self >= 0.0 {
(*self * i16::MAX as f32) as i16
} else {
(-*self * i16::MIN as f32) as i16
}
}
#[inline]
fn to_u16(&self) -> u16 {
self.mul_add(F32_TO_16BIT_INT_MULTIPLIER, F32_TO_16BIT_INT_MULTIPLIER)
.round() as u16
}
#[inline]
fn from<S>(sample: &S) -> Self
where
S: Sample,
{
sample.to_f32()
}
} }
#[cfg(test)] impl SizedSample for f64 {
mod test { const FORMAT: SampleFormat = SampleFormat::F64;
use super::Sample;
#[test]
fn i16_to_i16() {
assert_eq!(0i16.to_i16(), 0);
assert_eq!((-467i16).to_i16(), -467);
assert_eq!(32767i16.to_i16(), 32767);
assert_eq!((-32768i16).to_i16(), -32768);
}
#[test]
fn i16_to_u16() {
assert_eq!(0i16.to_u16(), 32768);
assert_eq!((-16384i16).to_u16(), 16384);
assert_eq!(32767i16.to_u16(), 65535);
assert_eq!((-32768i16).to_u16(), 0);
}
#[test]
fn i16_to_f32() {
assert_eq!(0i16.to_f32(), 0.0);
assert_eq!((-16384i16).to_f32(), -0.5);
assert_eq!(32767i16.to_f32(), 1.0);
assert_eq!((-32768i16).to_f32(), -1.0);
}
#[test]
fn u16_to_i16() {
assert_eq!(32768u16.to_i16(), 0);
assert_eq!(16384u16.to_i16(), -16384);
assert_eq!(65535u16.to_i16(), 32767);
assert_eq!(0u16.to_i16(), -32768);
}
#[test]
fn u16_to_u16() {
assert_eq!(0u16.to_u16(), 0);
assert_eq!(467u16.to_u16(), 467);
assert_eq!(32767u16.to_u16(), 32767);
assert_eq!(65535u16.to_u16(), 65535);
}
#[test]
fn u16_to_f32() {
assert_eq!(0u16.to_f32(), -1.0);
assert_eq!(32768u16.to_f32(), 0.0);
assert_eq!(65535u16.to_f32(), 1.0);
}
#[test]
fn f32_to_i16() {
assert_eq!(0.0f32.to_i16(), 0);
assert_eq!((-0.5f32).to_i16(), i16::MIN / 2);
assert_eq!(1.0f32.to_i16(), i16::MAX);
assert_eq!((-1.0f32).to_i16(), i16::MIN);
}
#[test]
fn f32_to_u16() {
assert_eq!((-1.0f32).to_u16(), 0);
assert_eq!(0.0f32.to_u16(), 32768);
assert_eq!(1.0f32.to_u16(), 65535);
}
#[test]
fn f32_to_f32() {
assert_eq!(0.1f32.to_f32(), 0.1);
assert_eq!((-0.7f32).to_f32(), -0.7);
assert_eq!(1.0f32.to_f32(), 1.0);
}
} }

View file

@ -3,7 +3,7 @@
use crate::{ use crate::{
BuildStreamError, Data, DefaultStreamConfigError, DeviceNameError, DevicesError, BuildStreamError, Data, DefaultStreamConfigError, DeviceNameError, DevicesError,
InputCallbackInfo, InputDevices, OutputCallbackInfo, OutputDevices, PauseStreamError, InputCallbackInfo, InputDevices, OutputCallbackInfo, OutputDevices, PauseStreamError,
PlayStreamError, Sample, SampleFormat, StreamConfig, StreamError, SupportedStreamConfig, PlayStreamError, SampleFormat, SizedSample, StreamConfig, StreamError, SupportedStreamConfig,
SupportedStreamConfigRange, SupportedStreamConfigsError, SupportedStreamConfigRange, SupportedStreamConfigsError,
}; };
@ -122,7 +122,7 @@ pub trait DeviceTrait {
error_callback: E, error_callback: E,
) -> Result<Self::Stream, BuildStreamError> ) -> Result<Self::Stream, BuildStreamError>
where where
T: Sample, T: SizedSample,
D: FnMut(&[T], &InputCallbackInfo) + Send + 'static, D: FnMut(&[T], &InputCallbackInfo) + Send + 'static,
E: FnMut(StreamError) + Send + 'static, E: FnMut(StreamError) + Send + 'static,
{ {
@ -148,7 +148,7 @@ pub trait DeviceTrait {
error_callback: E, error_callback: E,
) -> Result<Self::Stream, BuildStreamError> ) -> Result<Self::Stream, BuildStreamError>
where where
T: Sample, T: SizedSample,
D: FnMut(&mut [T], &OutputCallbackInfo) + Send + 'static, D: FnMut(&mut [T], &OutputCallbackInfo) + Send + 'static,
E: FnMut(StreamError) + Send + 'static, E: FnMut(StreamError) + Send + 'static,
{ {