extern crate alloc;
use self::alloc::{sync::Arc, vec, vec::Vec};
use crate::{Block, FRAMES, Submission};
use ::cpal::{
BufferSize, Device, ErrorKind, FromSample, Sample, SampleFormat, SizedSample, Stream,
StreamConfig, SupportedBufferSize, SupportedStreamConfig,
traits::{DeviceTrait as _, StreamTrait as _},
};
use core::{
num::NonZeroU32,
sync::atomic::{AtomicBool, Ordering},
};
use rtrb::{Consumer, Producer, RingBuffer};
use rubato::{Async, FixedAsync, Resampler, audioadapter_buffers::direct::InterleavedSlice};
use std::io;
type Frame = [i32; 2];
const MIN_Q23: i32 = -(1 << 23);
const MAX_Q23: i32 = (1 << 23) - 1;
const MAX_PERIOD: u32 = 65_536;
fn alsa_period(size: SupportedBufferSize) -> io::Result<u32> {
match size {
SupportedBufferSize::Unknown => Ok(256),
SupportedBufferSize::Range { min, max } => {
let min = min.max(1);
let max = max.min(MAX_PERIOD);
if min > max {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"no supported ALSA period within 1..=65536 frames",
));
}
Ok(256_u32.clamp(min, max))
}
}
}
struct Handoff<Q> {
initial: Consumer<Q>,
active: Option<Q>,
}
impl<Q> Handoff<Q> {
fn new() -> (impl FnOnce(Q), Self) {
let (mut send, initial) = RingBuffer::new(1);
(
move |queue| assert!(send.push(queue).is_ok(), "one writer, one unused slot"),
Self {
initial,
active: None,
},
)
}
fn get(&mut self) -> Option<&mut Q> {
if self.active.is_none() {
self.active = self.initial.pop().ok();
}
self.active.as_mut()
}
}
enum Callback {
Output(Handoff<Consumer<Frame>>),
Input(Handoff<Producer<Frame>>),
}
impl Callback {
fn build(
self,
device: &Device,
config: &SupportedStreamConfig,
channels: (usize, usize),
failed: Arc<AtomicBool>,
) -> io::Result<Stream> {
let mut stream_config = config.config();
if cfg!(target_os = "linux") {
stream_config.buffer_size = BufferSize::Fixed(alsa_period(*config.buffer_size())?);
}
macro_rules! build {
($sample:ty) => {
self.build_typed::<$sample>(device, stream_config, channels, failed)
};
}
match config.sample_format() {
SampleFormat::I8 => build!(i8),
SampleFormat::I16 => build!(i16),
SampleFormat::I24 => build!(::cpal::I24),
SampleFormat::I32 => build!(i32),
SampleFormat::I64 => build!(i64),
SampleFormat::U8 => build!(u8),
SampleFormat::U16 => build!(u16),
SampleFormat::U24 => build!(::cpal::U24),
SampleFormat::U32 => build!(u32),
SampleFormat::U64 => build!(u64),
SampleFormat::F32 => build!(f32),
SampleFormat::F64 => build!(f64),
_ => Err(io::Error::new(
io::ErrorKind::Unsupported,
"unsupported device sample format",
)),
}
}
fn build_typed<T>(
self,
device: &Device,
config: StreamConfig,
channels: (usize, usize),
failed: Arc<AtomicBool>,
) -> io::Result<Stream>
where
T: SizedSample + FromSample<i32>,
i32: FromSample<T>,
{
let width = usize::from(config.channels);
let on_error = move |error: ::cpal::Error| {
if !matches!(
error.kind(),
ErrorKind::Xrun | ErrorKind::DeviceChanged | ErrorKind::RealtimeDenied
) {
failed.store(true, Ordering::Relaxed);
}
};
match self {
Self::Output(mut handoff) => device.build_output_stream(
config,
move |data: &mut [T], _| {
write_output(handoff.get(), data, width, channels);
},
on_error,
None,
),
Self::Input(mut handoff) => device.build_input_stream(
config,
move |data: &[T], _| {
if let Some(sink) = handoff.get() {
read_input(sink, data, width, channels);
}
},
on_error,
None,
),
}
.map_err(io::Error::other)
}
}
fn write_output<T: Sample + FromSample<i32>>(
source: Option<&mut Consumer<Frame>>,
data: &mut [T],
width: usize,
(left, right): (usize, usize),
) {
data.fill(T::EQUILIBRIUM);
let Some(source) = source else { return };
let frames = data.chunks_exact_mut(width);
let available = frames.len().min(source.slots());
let chunk = source
.read_chunk(available)
.expect("single consumer owns the available frames");
let encode = |sample: i32| T::from_sample(sample.clamp(MIN_Q23, MAX_Q23) << 8);
for (out, [l, r]) in frames.zip(chunk) {
if left == right {
out[left] = encode(l.midpoint(r));
} else {
out[left] = encode(l);
out[right] = encode(r);
}
}
}
fn read_input<T: Sample>(
sink: &mut Producer<Frame>,
data: &[T],
width: usize,
(left, right): (usize, usize),
) where
i32: FromSample<T>,
{
let frames = data.chunks_exact(width);
let available = frames.len().min(sink.slots());
let chunk = sink
.write_chunk_uninit(available)
.expect("single producer owns the free slots");
chunk.fill_from_iter(
frames.map(|frame| [frame[left], frame[right]].map(|sample| i32::from_sample(sample) >> 8)),
);
}
struct Converter {
sinc: Async<f32>,
input: Vec<[f32; 2]>,
output: Vec<[f32; 2]>,
}
impl Converter {
fn new(input_rate: u32, output_rate: u32, fixed: FixedAsync) -> io::Result<Option<Self>> {
if input_rate == output_rate {
return Ok(None);
}
let ratio = f64::from(output_rate) / f64::from(input_rate);
if !(1.0 / 256.0..=256.0).contains(&ratio) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"sample-rate conversion ratio exceeds 256:1",
));
}
let sinc = Async::new_sinc(ratio, 1.0, &Default::default(), FRAMES, 2, fixed)
.map_err(io::Error::other)?;
let input = vec![[0.; 2]; sinc.input_frames_max()];
let output = vec![[0.; 2]; sinc.output_frames_max()];
Ok(Some(Self {
sinc,
input,
output,
}))
}
#[allow(
clippy::cast_precision_loss,
clippy::cast_possible_truncation,
reason = "f32 represents Q23 exactly. Filtered samples round back to signed PCM."
)]
fn process(
&mut self,
frames: impl IntoIterator<Item = Frame>,
) -> io::Result<impl Iterator<Item = Frame> + '_> {
for (dest, frame) in self.input.iter_mut().zip(frames) {
*dest = frame.map(|s| s as f32);
}
let input = InterleavedSlice::new(self.input.as_flattened(), 2, self.input.len())
.map_err(io::Error::other)?;
let capacity = self.output.len();
let mut output = InterleavedSlice::new_mut(self.output.as_flattened_mut(), 2, capacity)
.map_err(io::Error::other)?;
let (_, written) = self
.sinc
.process_into_buffer(&input, &mut output, None)
.map_err(io::Error::other)?;
Ok(self.output[..written]
.iter()
.map(|frame| frame.map(|s| s.round() as i32)))
}
}
pub(super) struct OutputQueue {
queue: Producer<Frame>,
converter: Option<Converter>,
}
impl OutputQueue {
pub(super) fn render(&mut self, render: impl FnOnce(&mut Block, ())) -> io::Result<Submission> {
let frames = self
.converter
.as_ref()
.map_or(FRAMES, |c| c.sinc.output_frames_next());
let Ok(chunk) = self.queue.write_chunk_uninit(frames) else {
return Ok(Submission::WouldBlock);
};
let mut block = [[0; 2]; FRAMES];
render(&mut block, ());
if let Some(converter) = &mut self.converter {
chunk.fill_from_iter(converter.process(block)?);
} else {
chunk.fill_from_iter(block);
}
Ok(Submission::Written)
}
}
pub(super) struct InputQueue {
queue: Consumer<Frame>,
converter: Option<Converter>,
}
impl InputQueue {
pub(super) fn read(&mut self, block: &mut Block) -> io::Result<bool> {
let Some(converter) = &mut self.converter else {
return Ok(self.queue.pop_entire_slice(block).is_ok());
};
let Ok(chunk) = self.queue.read_chunk(converter.sinc.input_frames_next()) else {
return Ok(false);
};
for (dest, frame) in block.iter_mut().zip(converter.process(chunk)?) {
*dest = frame.map(|s| s.clamp(MIN_Q23, MAX_Q23));
}
Ok(true)
}
}
fn queue_capacity(period: u32, block: usize) -> io::Result<usize> {
if !(1..=MAX_PERIOD).contains(&period) {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"device period outside 1..=65536 frames",
));
}
let period = usize::try_from(period).map_err(io::Error::other)?;
Ok(period.saturating_mul(2).max(block.saturating_mul(4)))
}
pub(super) fn open_output(
device: &Device,
config: SupportedStreamConfig,
channels: (usize, usize),
rate: NonZeroU32,
failed: Arc<AtomicBool>,
) -> io::Result<(Stream, OutputQueue)> {
let converter = Converter::new(rate.get(), config.sample_rate(), FixedAsync::Input)?;
let (init, handoff) = Handoff::new();
let stream = Callback::Output(handoff).build(device, &config, channels, failed)?;
let block = converter
.as_ref()
.map_or(FRAMES, |c| c.sinc.output_frames_max());
let (queue, consumer) =
RingBuffer::new(queue_capacity(stream.buffer_size().unwrap_or(512), block)?);
init(consumer);
stream.play().map_err(io::Error::other)?;
Ok((stream, OutputQueue { queue, converter }))
}
pub(super) fn open_input(
device: &Device,
config: SupportedStreamConfig,
channels: (usize, usize),
rate: NonZeroU32,
failed: Arc<AtomicBool>,
) -> io::Result<(Stream, InputQueue)> {
let converter = Converter::new(config.sample_rate(), rate.get(), FixedAsync::Output)?;
let (init, handoff) = Handoff::new();
let stream = Callback::Input(handoff).build(device, &config, channels, failed)?;
let block = converter
.as_ref()
.map_or(FRAMES, |c| c.sinc.input_frames_max());
let (producer, queue) =
RingBuffer::new(queue_capacity(stream.buffer_size().unwrap_or(512), block)?);
init(producer);
stream.play().map_err(io::Error::other)?;
Ok((stream, InputQueue { queue, converter }))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bound_alsa_requests_and_negotiated_periods() -> io::Result<()> {
use SupportedBufferSize::{Range, Unknown};
assert_eq!(alsa_period(Unknown)?, 256);
assert_eq!(
alsa_period(Range {
min: 0,
max: u32::MAX
})?,
256
);
assert_eq!(alsa_period(Range { min: 8, max: 64 })?, 64);
assert_eq!(
alsa_period(Range {
min: 1024,
max: u32::MAX
})?,
1024
);
assert!(
alsa_period(Range {
min: u32::MAX,
max: u32::MAX
})
.is_err()
);
assert!(alsa_period(Range { min: 32, max: 16 }).is_err());
assert!(queue_capacity(0, FRAMES).is_err());
assert!(queue_capacity(u32::MAX, FRAMES).is_err());
assert_eq!(queue_capacity(8192, FRAMES)?, 16_384);
Ok(())
}
#[test]
fn reject_extreme_resampling_ratios_before_constructing_the_filter() -> io::Result<()> {
assert!(Converter::new(1, 192_000, FixedAsync::Input).is_err());
assert!(Converter::new(44_100, u32::MAX, FixedAsync::Output).is_err());
assert!(Converter::new(1_536_000, 8000, FixedAsync::Output)?.is_some());
Ok(())
}
#[test]
fn map_and_clip_only_the_selected_channels() {
let (mut send, mut recv) = RingBuffer::new(5);
send.push_entire_slice(&[[i32::MIN, i32::MAX], [-1, 1]])
.expect("space");
let mut device = [42_i32; 12];
write_output(Some(&mut recv), &mut device, 4, (2, 3));
assert_eq!(
device,
[0, 0, i32::MIN, MAX_Q23 << 8, 0, 0, -256, 256, 0, 0, 0, 0]
);
read_input(&mut send, &device, 4, (2, 3));
assert_eq!(recv.pop(), Ok([MIN_Q23, MAX_Q23]));
assert_eq!(recv.pop(), Ok([-1, 1]));
assert_eq!(recv.pop(), Ok([0, 0]));
send.push([12_000_000, -4_000_000]).expect("space");
let mut mono = [0_u32; 4];
write_output(Some(&mut recv), &mut mono, 2, (1, 1));
assert_eq!(
mono,
[
u32::EQUILIBRIUM,
u32::from_sample(4_000_000 << 8),
u32::EQUILIBRIUM,
u32::EQUILIBRIUM
]
);
read_input(&mut send, &mono, 2, (1, 1));
assert_eq!(recv.pop(), Ok([4_000_000; 2]));
assert_eq!(recv.pop(), Ok([0; 2]));
}
#[test]
fn callbacks_of_different_lengths_preserve_whole_graph_blocks() -> io::Result<()> {
let (send, mut recv) = RingBuffer::new(FRAMES);
let mut out = OutputQueue {
queue: send,
converter: None,
};
assert_eq!(
out.render(|block, ()| {
assert_eq!(*block, [[0; 2]; FRAMES]);
for (index, frame) in (1..).zip(block) {
*frame = [index, -index];
}
})?,
Submission::Written
);
let mut part = [1_f32; 6];
write_output(Some(&mut recv), &mut part, 2, (0, 1));
assert_eq!(part[0], f32::from_sample(1 << 8));
assert_eq!(out.render(|_, ()| unreachable!())?, Submission::WouldBlock);
let mut tail = [1_f32; 256];
write_output(Some(&mut recv), &mut tail, 2, (0, 1));
assert_eq!(tail[0], f32::from_sample(4 << 8));
assert_eq!(tail[249], f32::from_sample(-128 << 8));
assert_eq!(tail[250..], [0.; 6]);
let (mut send, recv) = RingBuffer::new(FRAMES);
let mut input = InputQueue {
queue: recv,
converter: None,
};
let mut block = [[42; 2]; FRAMES];
read_input(&mut send, &[0.5_f32; 3], 1, (0, 0));
assert!(!input.read(&mut block)?);
assert_eq!(block, [[42; 2]; FRAMES]);
read_input(&mut send, &[-0.25_f32; 220], 1, (0, 0));
assert!(input.read(&mut block)?);
assert_eq!(block[..3], [[1 << 22; 2]; 3]);
assert_eq!(block[3..], [[-(1 << 21); 2]; 125]);
assert!(!input.read(&mut block)?);
Ok(())
}
#[test]
fn sinc_conversion_preserves_stereo_and_the_graph_clock() -> io::Result<()> {
let (send, recv) = RingBuffer::new(12 * FRAMES);
let mut output = OutputQueue {
queue: send,
converter: Converter::new(44_100, 48_000, FixedAsync::Input)?,
};
let mut input = InputQueue {
queue: recv,
converter: Converter::new(48_000, 44_100, FixedAsync::Output)?,
};
let mut captured = [[0; 2]; FRAMES];
let mut read = 0;
let mut device_frames = 0;
for block in 0..151 {
let before = input.queue.slots();
assert_eq!(
output.render(|b, ()| b.fill([1 << 20, -(1 << 21)]))?,
Submission::Written
);
if block >= 4 {
device_frames += input.queue.slots() - before;
}
while input.read(&mut captured)? {
read += 1;
}
}
assert!(device_frames.abs_diff(160 * FRAMES) <= 1);
assert!((148..=151).contains(&read));
for [left, right] in captured {
assert!(left.abs_diff(1 << 20) < 32);
assert!(right.abs_diff(-(1 << 21)) < 64);
}
Ok(())
}
}