use std::collections::VecDeque;
use std::f32::consts::TAU;
use std::io;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, mpsc};
use std::thread::JoinHandle;
use std::time::Duration;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{FromSample, SizedSample};
use crate::lock::{Guard, Lock};
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Source {
Silence,
Tone {
hertz: f32,
level: f32,
},
Device {
name: Option<String>,
first_channel: u16,
},
Shared(SharedBuffer),
Blocks(Blocks<dyn BlockSource>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Block {
pub presented: i64,
pub samples: usize,
pub channels: usize,
pub media_reset: bool,
}
pub trait BlockSource: Send + Sync {
fn fill(&self, block: &Block, words: &mut [i32]);
fn sent(&self, block: &Block, sent: bool);
fn left_out(&self, samples: u64);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Arrived {
pub presented: Option<i64>,
pub margin: Option<i64>,
pub samples: usize,
pub channels: usize,
pub missed: u8,
pub media_reset: bool,
}
pub trait BlockSink: Send + Sync {
fn take(&self, arrived: &Arrived, words: &[i32]);
}
pub struct Blocks<T: ?Sized>(pub Arc<T>);
impl<T: ?Sized> Clone for Blocks<T> {
fn clone(&self) -> Self {
Blocks(self.0.clone())
}
}
impl<T: ?Sized> PartialEq for Blocks<T> {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl<T: ?Sized> std::fmt::Debug for Blocks<T> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Blocks")
}
}
#[derive(Clone)]
pub struct SharedBuffer {
pub buffer: Arc<FrameBuffer>,
pub channels: u16,
pub rate: u32,
}
impl PartialEq for SharedBuffer {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.buffer, &other.buffer)
}
}
impl std::fmt::Debug for SharedBuffer {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
formatter,
"SharedBuffer({} channels at {} Hz)",
self.channels, self.rate
)
}
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Sink {
Discard,
Device {
name: Option<String>,
first_channel: u16,
},
Shared(SharedBuffer),
Blocks(Blocks<dyn BlockSink>),
}
pub struct FrameBuffer {
held: Lock<Held>,
channels: usize,
margin: usize,
pub underruns: AtomicU64,
pub adjustments: AtomicU64,
}
struct Held {
samples: VecDeque<f32>,
pushed: u64,
more: usize,
sample: Option<DeviceSample>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeviceSample {
pub chunks: u64,
pub level: usize,
pub chunk: usize,
pub pushed: u64,
pub plays_at: Option<i64>,
}
impl FrameBuffer {
pub fn new(channels: u16, margin: usize) -> Self {
let channels = usize::from(channels).max(1);
FrameBuffer {
held: Lock::new(Held {
samples: VecDeque::with_capacity(4 * margin * channels),
pushed: 0,
more: 0,
sample: None,
}),
channels,
margin: margin.max(1),
underruns: AtomicU64::new(0),
adjustments: AtomicU64::new(0),
}
}
fn lock(&self) -> Guard<'_, Held> {
self.held.lock()
}
pub fn push(&self, samples: &[f32]) {
let mut held = self.lock();
self.push_into(&mut held, samples);
}
fn push_into(&self, held: &mut Held, samples: &[f32]) {
held.samples.extend(samples);
held.pushed += (samples.len() / self.channels) as u64;
let chunk = held.sample.map_or(0, |sample| sample.chunk);
let most = (4 * (self.margin + chunk) + held.more) * self.channels;
if held.samples.len() > most {
let extra = held.samples.len() - most;
held.samples.drain(..extra - extra % self.channels);
self.adjustments.fetch_add(1, Ordering::Relaxed);
}
}
pub fn pull(&self, out: &mut [f32]) {
let mut held = self.lock();
self.pull_from(&mut held, out);
}
fn pull_from(&self, held: &mut Held, out: &mut [f32]) {
let mut short = false;
for slot in out.iter_mut() {
*slot = held.samples.pop_front().unwrap_or_else(|| {
short = true;
0.0
});
}
if short {
self.underruns.fetch_add(1, Ordering::Relaxed);
}
}
pub fn pushed(&self) -> u64 {
self.lock().pushed
}
pub fn hold_more(&self, frames: usize) {
let mut held = self.lock();
held.more = held.more.max(frames);
}
pub fn drop_oldest(&self, frames: usize) {
let mut held = self.lock();
let samples = (frames * self.channels).min(held.samples.len());
held.samples.drain(..samples);
}
pub fn device_push(&self, samples: &[f32]) {
let mut held = self.lock();
self.push_into(&mut held, samples);
self.note(&mut held, samples.len(), None);
}
pub fn device_pull(&self, out: &mut [f32], plays_at: Option<i64>) {
let mut held = self.lock();
self.pull_from(&mut held, out);
self.note(&mut held, out.len(), plays_at);
}
fn note(&self, held: &mut Held, samples: usize, plays_at: Option<i64>) {
let chunks = held.sample.map_or(1, |sample| sample.chunks + 1);
held.sample = Some(DeviceSample {
chunks,
level: held.samples.len() / self.channels,
chunk: samples / self.channels,
pushed: held.pushed,
plays_at,
});
}
pub fn device_sample(&self) -> Option<DeviceSample> {
self.lock().sample
}
pub fn level(&self) -> usize {
self.lock().samples.len() / self.channels
}
}
const SMOOTHING: f64 = 0.02;
const PROPORTIONAL: f64 = 0.0051;
const INTEGRAL: f64 = 1e-5;
const MOST_DRIFT: f64 = 0.002;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeviceSide {
Pushes,
Pulls,
}
pub struct Drift {
channels: usize,
side: DeviceSide,
nominal: f64,
held: VecDeque<f32>,
position: f64,
ratio: f64,
chunks: u64,
error: Option<f64>,
integral: f64,
}
impl Drift {
pub fn new(channels: u16, side: DeviceSide, nominal: f64) -> Self {
Drift {
channels: usize::from(channels).max(1),
side,
nominal,
held: VecDeque::new(),
position: 0.0,
ratio: nominal,
chunks: 0,
error: None,
integral: 0.0,
}
}
pub fn ratio(&self) -> f64 {
self.ratio
}
pub fn device_ppm(&self) -> i32 {
let relative = self.ratio / self.nominal;
let ppm = match self.side {
DeviceSide::Pushes => relative - 1.0,
DeviceSide::Pulls => 1.0 / relative - 1.0,
};
(ppm * 1e6).round() as i32
}
pub fn steer(&mut self, buffer: &FrameBuffer) {
if let Some(sample) = self.new_sample(buffer) {
let excess = sample.level as f64 - self.kept(buffer, &sample) as f64;
self.follow(excess, sample.chunk);
}
}
fn new_sample(&mut self, buffer: &FrameBuffer) -> Option<DeviceSample> {
let sample = buffer.device_sample()?;
if sample.chunks == self.chunks {
return None;
}
self.chunks = sample.chunks;
Some(sample)
}
fn kept(&self, buffer: &FrameBuffer, sample: &DeviceSample) -> usize {
match self.side {
DeviceSide::Pushes => buffer.margin + sample.chunk,
DeviceSide::Pulls => buffer.margin,
}
}
fn follow(&mut self, excess: f64, chunk: usize) {
let error = excess / chunk.max(1) as f64;
let smoothed = self.error.get_or_insert(error);
*smoothed += SMOOTHING * (error - *smoothed);
self.integral = (self.integral + INTEGRAL * *smoothed).clamp(-MOST_DRIFT, MOST_DRIFT);
self.ratio = self.nominal
* (1.0 + PROPORTIONAL * *smoothed + self.integral)
.clamp(1.0 - MOST_DRIFT, 1.0 + MOST_DRIFT);
}
fn held_frames(&self) -> usize {
self.held.len() / self.channels
}
fn pending(&self) -> f64 {
(self.held_frames() as f64 - 1.0 - self.position).max(0.0)
}
pub fn wanted(&self, frames: usize) -> usize {
if frames == 0 {
return 0;
}
let last = self.position + (frames - 1) as f64 * self.ratio;
(last as usize + 4).saturating_sub(self.held_frames())
}
pub fn push(&mut self, input: &[f32]) {
self.held.extend(input);
}
pub fn make(&mut self, out: &mut Vec<f32>, most: usize) {
let channels = self.channels;
let mut made = 0;
while made < most && self.position as usize + 4 <= self.held_frames() {
let base = self.position as usize;
let t = (self.position - base as f64) as f32;
for channel in 0..channels {
let at = |frame: usize| self.held[(base + frame) * channels + channel];
let (before, from, to, after) = (at(0), at(1), at(2), at(3));
let a = -0.5 * before + 1.5 * from - 1.5 * to + 0.5 * after;
let b = before - 2.5 * from + 2.0 * to - 0.5 * after;
let c = -0.5 * before + 0.5 * to;
out.push(((a * t + b) * t + c) * t + from);
}
made += 1;
self.position += self.ratio;
let passed = (self.position as usize).min(self.held_frames());
if passed > 0 {
self.held.drain(..passed * channels);
self.position -= passed as f64;
}
}
}
}
struct DeviceThread {
stop: Arc<AtomicBool>,
handle: Option<JoinHandle<()>>,
}
impl Drop for DeviceThread {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(handle) = self.handle.take() {
handle.thread().unpark();
let _ = handle.join();
}
}
}
fn device_error(error: impl std::fmt::Display) -> io::Error {
io::Error::other(error.to_string())
}
fn find_device(name: Option<&str>, input: bool) -> io::Result<cpal::Device> {
let host = cpal::default_host();
let found = match name {
Some(name) => {
let devices = if input {
host.input_devices()
} else {
host.output_devices()
}
.map_err(device_error)?;
devices
.into_iter()
.find(|device| device.description().is_ok_and(|about| about.name() == name))
}
None if input => host.default_input_device(),
None => host.default_output_device(),
};
found.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
match name {
Some(name) => format!("no audio device named {name}"),
None => "no default audio device".to_owned(),
},
)
})
}
fn device_rate(device: &cpal::Device, input: bool, wanted: u32) -> io::Result<u32> {
let default = if input {
device.default_input_config()
} else {
device.default_output_config()
}
.map_err(device_error)?;
if default.sample_rate() == wanted {
return Ok(wanted);
}
let ranges: Vec<cpal::SupportedStreamConfigRange> = if input {
device.supported_input_configs().map(Iterator::collect)
} else {
device.supported_output_configs().map(Iterator::collect)
}
.unwrap_or_default();
let supported = ranges.iter().any(|range| {
range.channels() == default.channels()
&& (range.min_sample_rate()..=range.max_sample_rate()).contains(&wanted)
});
Ok(if supported {
wanted
} else {
default.sample_rate()
})
}
pub fn device_names() -> (Vec<String>, Vec<String>) {
let host = cpal::default_host();
let named = |device: cpal::Device| Some(device.description().ok()?.name().to_owned());
let inputs = host
.input_devices()
.map(|devices| devices.filter_map(named).collect())
.unwrap_or_default();
let outputs = host
.output_devices()
.map(|devices| devices.filter_map(named).collect())
.unwrap_or_default();
(inputs, outputs)
}
fn device_thread(
name: String,
build: impl FnOnce() -> io::Result<cpal::Stream> + Send + 'static,
) -> io::Result<DeviceThread> {
let stop = Arc::new(AtomicBool::new(false));
let stopping = stop.clone();
let (opened, started) = mpsc::channel();
let handle = std::thread::Builder::new().name(name).spawn(move || {
let stream = match build().and_then(|stream| {
stream.play().map_err(device_error)?;
Ok(stream)
}) {
Ok(stream) => {
let _ = opened.send(Ok(()));
stream
}
Err(error) => {
let _ = opened.send(Err(error));
return;
}
};
while !stopping.load(Ordering::Relaxed) {
std::thread::park_timeout(Duration::from_millis(200));
}
drop(stream);
})?;
started
.recv()
.unwrap_or_else(|_| Err(io::Error::other("the audio thread stopped")))?;
Ok(DeviceThread {
stop,
handle: Some(handle),
})
}
fn input_stream<T>(
device: &cpal::Device,
config: cpal::StreamConfig,
channels: usize,
first: usize,
buffer: Arc<FrameBuffer>,
) -> io::Result<cpal::Stream>
where
T: SizedSample,
f32: FromSample<T>,
{
let device_channels = usize::from(config.channels).max(1);
let mut frames = Vec::new();
device
.build_input_stream(
config,
move |data: &[T], _: &cpal::InputCallbackInfo| {
frames.clear();
for frame in data.chunks_exact(device_channels) {
for channel in 0..channels {
frames.push(
frame
.get(first + channel)
.map_or(0.0, |sample| sample.to_sample::<f32>()),
);
}
}
buffer.device_push(&frames);
},
|_| {},
None,
)
.map_err(device_error)
}
fn output_stream<T>(
device: &cpal::Device,
config: cpal::StreamConfig,
channels: usize,
first: usize,
buffer: Arc<FrameBuffer>,
) -> io::Result<cpal::Stream>
where
T: SizedSample + FromSample<f32>,
{
let device_channels = usize::from(config.channels).max(1);
let rate = i64::from(config.sample_rate.max(1));
let mut frames = Vec::new();
device
.build_output_stream(
config,
move |data: &mut [T], info: &cpal::OutputCallbackInfo| {
let count = data.len() / device_channels;
frames.resize(count * channels, 0.0);
let stamp = info.timestamp();
let latency = stamp.playback.duration_since(stamp.callback);
let plays_at = avb_net::clock::monotonic_now() + latency;
let after = plays_at.as_nanos() as i64 + count as i64 * 1_000_000_000 / rate;
buffer.device_pull(&mut frames, Some(after));
for (frame, samples) in data
.chunks_exact_mut(device_channels)
.zip(frames.chunks_exact(channels.max(1)))
{
for (channel, slot) in frame.iter_mut().enumerate() {
let sample = channel
.checked_sub(first)
.and_then(|stream| samples.get(stream))
.copied()
.unwrap_or(0.0);
*slot = T::from_sample(sample);
}
}
},
|_| {},
None,
)
.map_err(device_error)
}
pub struct Input {
kind: InputKind,
channels: usize,
spread: Vec<f32>,
}
enum InputKind {
Silence,
Tone {
phase: f32,
step: f32,
level: f32,
},
Device {
buffer: Arc<FrameBuffer>,
width: usize,
drift: Drift,
taken: Vec<f32>,
made: Vec<f32>,
_thread: Option<DeviceThread>,
},
}
impl Input {
pub fn open(source: &Source, channels: u16, rate: u32) -> io::Result<Self> {
let kind = match source {
Source::Silence | Source::Blocks(_) => InputKind::Silence,
Source::Tone { hertz, level } => InputKind::Tone {
phase: 0.0,
step: TAU * hertz / rate as f32,
level: level.clamp(0.0, 1.0),
},
Source::Device {
name,
first_channel,
} => {
let device = find_device(name.as_deref(), true)?;
let device_rate = device_rate(&device, true, rate)?;
let margin = device_rate as usize / 100;
let buffer = Arc::new(FrameBuffer::new(channels, margin));
let filling = buffer.clone();
let first = usize::from(*first_channel);
let wanted = usize::from(channels);
let thread = device_thread("audio input".into(), move || {
let supported = device.default_input_config().map_err(device_error)?;
let mut config = supported.config();
config.sample_rate = device_rate;
match supported.sample_format() {
cpal::SampleFormat::F32 => {
input_stream::<f32>(&device, config, wanted, first, filling)
}
cpal::SampleFormat::I16 => {
input_stream::<i16>(&device, config, wanted, first, filling)
}
cpal::SampleFormat::I32 => {
input_stream::<i32>(&device, config, wanted, first, filling)
}
other => Err(io::Error::new(
io::ErrorKind::Unsupported,
format!("samples in {other}"),
)),
}
})?;
InputKind::Device {
buffer,
width: usize::from(channels),
drift: Drift::new(
channels,
DeviceSide::Pushes,
f64::from(device_rate) / f64::from(rate),
),
taken: Vec::new(),
made: Vec::new(),
_thread: Some(thread),
}
}
Source::Shared(shared) => {
shared.buffer.drop_oldest(shared.buffer.level());
InputKind::Device {
buffer: shared.buffer.clone(),
width: usize::from(shared.channels).max(1),
drift: Drift::new(
shared.channels,
DeviceSide::Pushes,
f64::from(shared.rate) / f64::from(rate),
),
taken: Vec::new(),
made: Vec::new(),
_thread: None,
}
}
};
Ok(Input {
kind,
channels: usize::from(channels),
spread: Vec::new(),
})
}
pub fn drift_ppm(&self) -> i32 {
match &self.kind {
InputKind::Device { drift, .. } => drift.device_ppm(),
_ => 0,
}
}
pub fn counts(&self) -> (u64, u64) {
match &self.kind {
InputKind::Device { buffer, .. } => (
buffer.adjustments.load(Ordering::Relaxed),
buffer.underruns.load(Ordering::Relaxed),
),
_ => (0, 0),
}
}
pub fn read(&mut self, out: &mut [f32]) {
match &mut self.kind {
InputKind::Silence => out.fill(0.0),
InputKind::Tone { phase, step, level } => {
for frame in out.chunks_exact_mut(self.channels.max(1)) {
frame.fill(phase.sin() * *level);
*phase = (*phase + *step) % TAU;
}
}
InputKind::Device {
buffer,
width,
drift,
taken,
made,
..
} => {
let frames = out.len() / self.channels.max(1);
drift.steer(buffer);
taken.resize(drift.wanted(frames) * *width, 0.0);
buffer.pull(taken);
drift.push(taken);
made.clear();
drift.make(made, frames);
out.fill(0.0);
if *width == self.channels.max(1) {
out[..made.len()].copy_from_slice(made);
} else {
respread(made, *width, out, self.channels);
}
}
}
}
pub fn read_as(&mut self, out: &mut [f32], channels: usize) {
let channels = channels.max(1);
if channels == self.channels.max(1) {
self.read(out);
return;
}
let mut spread = std::mem::take(&mut self.spread);
spread.resize(out.len() / channels * self.channels.max(1), 0.0);
self.read(&mut spread);
respread(&spread, self.channels, out, channels);
self.spread = spread;
}
pub fn skip(&mut self, frames: usize) {
match &mut self.kind {
InputKind::Silence => {}
InputKind::Tone { phase, step, .. } => {
let turned = f64::from(*phase) + f64::from(*step) * frames as f64;
*phase = (turned % std::f64::consts::TAU) as f32;
}
InputKind::Device { buffer, drift, .. } => {
buffer.drop_oldest((frames as f64 * drift.ratio()).round() as usize);
}
}
}
}
fn respread(samples: &[f32], channels: usize, out: &mut [f32], out_channels: usize) {
let (channels, out_channels) = (channels.max(1), out_channels.max(1));
let kept = channels.min(out_channels);
for (to, from) in out
.chunks_exact_mut(out_channels)
.zip(samples.chunks_exact(channels))
{
to[..kept].copy_from_slice(&from[..kept]);
to[kept..].fill(0.0);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Presented {
pub first: i64,
pub offset: i64,
}
const CHOOSING: i64 = 2_000_000_000;
const DELAY_STEP: i64 = 1_000_000;
const MOST_DELAY: i64 = 500_000_000;
const MOST_AHEAD: i64 = 500_000_000;
struct Playing {
drift: Drift,
made: Vec<f32>,
spread: Vec<f32>,
next_in: Option<i64>,
offset: Option<i64>,
anchor: Option<(u64, i64)>,
delay: Option<i64>,
error: i64,
choosing: Option<(i64, f64, u32)>,
underruns: u64,
}
pub struct Output {
buffer: Option<Arc<FrameBuffer>>,
width: usize,
_thread: Option<DeviceThread>,
playing: Lock<Playing>,
rate: u32,
peak: AtomicU32,
}
impl Output {
pub fn open(sink: &Sink, channels: u16, rate: u32) -> io::Result<Self> {
match sink {
Sink::Discard | Sink::Blocks(_) => {
Ok(Output::new(None, None, channels, channels, rate, rate))
}
Sink::Shared(shared) => Ok(Output::new(
Some(shared.buffer.clone()),
None,
channels,
shared.channels,
rate,
shared.rate,
)),
Sink::Device {
name,
first_channel,
} => {
let device = find_device(name.as_deref(), false)?;
let device_rate = device_rate(&device, false, rate)?;
let margin = device_rate as usize / 100;
let buffer = Arc::new(FrameBuffer::new(channels, margin));
let draining = buffer.clone();
let first = usize::from(*first_channel);
let wanted = usize::from(channels);
let thread = device_thread("audio output".into(), move || {
let supported = device.default_output_config().map_err(device_error)?;
let mut config = supported.config();
config.sample_rate = device_rate;
match supported.sample_format() {
cpal::SampleFormat::F32 => {
output_stream::<f32>(&device, config, wanted, first, draining)
}
cpal::SampleFormat::I16 => {
output_stream::<i16>(&device, config, wanted, first, draining)
}
cpal::SampleFormat::I32 => {
output_stream::<i32>(&device, config, wanted, first, draining)
}
other => Err(io::Error::new(
io::ErrorKind::Unsupported,
format!("samples in {other}"),
)),
}
})?;
Ok(Output::new(
Some(buffer),
Some(thread),
channels,
channels,
rate,
device_rate,
))
}
}
}
fn new(
buffer: Option<Arc<FrameBuffer>>,
thread: Option<DeviceThread>,
channels: u16,
width: u16,
rate: u32,
device_rate: u32,
) -> Self {
let nominal = f64::from(rate) / f64::from(device_rate.max(1));
Output {
buffer,
width: usize::from(width).max(1),
_thread: thread,
playing: Lock::new(Playing {
drift: Drift::new(channels, DeviceSide::Pulls, nominal),
made: Vec::new(),
spread: Vec::new(),
next_in: None,
offset: None,
anchor: None,
delay: None,
error: 0,
choosing: None,
underruns: 0,
}),
rate: rate.max(1),
peak: AtomicU32::new(0),
}
}
fn lock(&self) -> Guard<'_, Playing> {
self.playing.lock()
}
pub fn write(&self, samples: &[f32], presented: Option<Presented>) {
let loudest = samples
.iter()
.fold(0.0f32, |most, sample| most.max(sample.abs()));
self.peak.fetch_max(loudest.to_bits(), Ordering::Relaxed);
let Some(buffer) = &self.buffer else {
return;
};
let mut playing = self.lock();
let playing = &mut *playing;
if let Some(presented) = presented {
playing.next_in = Some(presented.first);
playing.offset = Some(presented.offset);
}
if let Some(sample) = playing.drift.new_sample(buffer) {
self.steer(playing, buffer, &sample);
}
playing.drift.push(samples);
playing.made.clear();
playing.drift.make(&mut playing.made, usize::MAX);
let channels = playing.drift.channels;
if self.width == channels {
buffer.push(&playing.made);
} else {
let frames = playing.made.len() / channels;
playing.spread.resize(frames * self.width, 0.0);
respread(&playing.made, channels, &mut playing.spread, self.width);
buffer.push(&playing.spread);
}
let frames = samples.len() / playing.drift.channels;
let frame = 1e9 / f64::from(self.rate);
if let Some(next) = &mut playing.next_in {
*next += (frames as f64 * frame).round() as i64;
let made = *next - (playing.drift.pending() * frame).round() as i64;
playing.anchor = Some((buffer.pushed(), made));
}
}
fn steer(&self, playing: &mut Playing, buffer: &FrameBuffer, sample: &DeviceSample) {
let excess = sample.level as f64 - playing.drift.kept(buffer, sample) as f64;
let (Some(plays_at), Some((anchor, presented)), Some(offset)) =
(sample.plays_at, playing.anchor, playing.offset)
else {
playing.drift.follow(excess, sample.chunk);
return;
};
let frame = playing.drift.ratio() * 1e9 / f64::from(self.rate);
let oldest = sample.pushed - sample.level as u64;
let presents = presented as f64 - (anchor as f64 - oldest as f64) * frame;
let late = (plays_at + offset) as f64 - presents;
if !(-MOST_AHEAD as f64..=2.0 * MOST_DELAY as f64).contains(&late) {
playing.drift.follow(excess, sample.chunk);
return;
}
let Some(delay) = playing.delay else {
playing.drift.follow(excess, sample.chunk);
let (since, sum, seen) = playing.choosing.get_or_insert((plays_at, 0.0, 0));
*sum += late - excess * frame;
*seen += 1;
if plays_at - *since >= CHOOSING {
let earliest = (*sum / f64::from(*seen)).max(0.0) as i64;
let steps = (earliest + DELAY_STEP - 1) / DELAY_STEP;
let delay = (steps * DELAY_STEP).min(MOST_DELAY);
self.set_delay(playing, buffer, delay, (late - delay as f64) / frame);
}
return;
};
let underruns = buffer.underruns.load(Ordering::Relaxed);
if underruns > playing.underruns && delay < MOST_DELAY {
let later = delay + DELAY_STEP;
self.set_delay(playing, buffer, later, (late - later as f64) / frame);
return;
}
playing.error = (late - delay as f64) as i64;
playing
.drift
.follow((late - delay as f64) / frame, sample.chunk);
}
fn set_delay(&self, playing: &mut Playing, buffer: &FrameBuffer, delay: i64, excess: f64) {
playing.delay = Some(delay);
playing.error = 0;
playing.underruns = buffer.underruns.load(Ordering::Relaxed);
let excess = excess.round() as i64;
buffer.hold_more(excess.unsigned_abs() as usize);
if excess > 0 {
buffer.drop_oldest(excess as usize);
} else if excess < 0 {
let frames = excess.unsigned_abs() as usize;
buffer.push(&vec![0.0; frames * playing.drift.channels]);
if let Some((anchor, _)) = &mut playing.anchor {
*anchor += frames as u64;
}
}
}
pub fn playout(&self) -> Option<(i64, i64)> {
let playing = self.lock();
playing.delay.map(|delay| (delay, playing.error))
}
pub fn drift_ppm(&self) -> i32 {
if self.buffer.is_none() {
return 0;
}
self.lock().drift.device_ppm()
}
pub fn underruns(&self) -> u64 {
self.buffer
.as_ref()
.map_or(0, |buffer| buffer.underruns.load(Ordering::Relaxed))
}
pub fn take_peak(&self) -> f32 {
f32::from_bits(self.peak.swap(0, Ordering::Relaxed))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_buffer_notes_its_fill_after_each_device_chunk() {
let buffer = FrameBuffer::new(2, 10);
assert_eq!(buffer.device_sample(), None);
buffer.device_push(&[1.0; 8]);
buffer.push(&[2.0; 4]);
assert_eq!(
buffer.device_sample(),
Some(DeviceSample {
chunks: 1,
level: 4,
chunk: 4,
pushed: 4,
plays_at: None,
})
);
let mut out = [9.0; 6];
buffer.device_pull(&mut out, None);
assert_eq!(out, [1.0; 6]);
assert_eq!(buffer.device_sample().map(|sample| sample.chunks), Some(2));
buffer.push(&[3.0; 200]);
assert_eq!(buffer.level(), 4 * (10 + 3));
assert!(buffer.adjustments.load(Ordering::Relaxed) > 0);
let mut out = [9.0; 120];
buffer.pull(&mut out);
assert_eq!(out[104..], [0.0; 16]);
assert_eq!(buffer.underruns.load(Ordering::Relaxed), 1);
}
fn numbered(frames: usize) -> Vec<f32> {
(0..frames)
.flat_map(|_| (1..=8).map(|channel| channel as f32 / 10.0))
.collect()
}
#[test]
fn a_stream_takes_the_first_channels_of_a_wider_shared_buffer() {
let shared = SharedBuffer {
buffer: Arc::new(FrameBuffer::new(8, 480)),
channels: 8,
rate: 48_000,
};
let mut input = Input::open(&Source::Shared(shared.clone()), 2, 48_000).expect("opened");
shared.buffer.device_push(&numbered(4800));
let mut out = vec![9.0; 480 * 2];
for _ in 0..4 {
input.read(&mut out);
}
for frame in out.as_chunks::<2>().0 {
assert!((frame[0] - 0.1).abs() < 1e-3, "{frame:?}");
assert!((frame[1] - 0.2).abs() < 1e-3, "{frame:?}");
}
}
#[test]
fn a_stream_fills_the_first_channels_of_a_wider_shared_buffer() {
let shared = SharedBuffer {
buffer: Arc::new(FrameBuffer::new(8, 480)),
channels: 8,
rate: 48_000,
};
let output = Output::open(&Sink::Shared(shared.clone()), 2, 48_000).expect("opened");
let stereo: Vec<f32> = (0..4800).flat_map(|_| [0.5, -0.5]).collect();
output.write(&stereo, None);
let mut out = vec![9.0; 480 * 8];
shared.buffer.device_pull(&mut out, None);
for frame in out.as_chunks::<8>().0 {
assert!((frame[0] - 0.5).abs() < 1e-3, "{frame:?}");
assert!((frame[1] + 0.5).abs() < 1e-3, "{frame:?}");
assert_eq!(frame[2..], [0.0; 6]);
}
}
fn sine(hertz: f64, rate: f64, start: u64, frames: usize) -> Vec<f32> {
(0..frames as u64)
.map(|index| (TAU as f64 * hertz * (start + index) as f64 / rate).sin() as f32 * 0.5)
.collect()
}
fn chunk_time(index: u64, chunk: usize, rate: f64) -> f64 {
let nominal = index as f64 * chunk as f64 / rate;
let wobble = ((index * 7919) % 41) as f64 / 40.0 - 0.5;
nominal + 0.04 * wobble * chunk as f64 / rate
}
#[test]
fn a_fast_device_is_followed_without_a_gap() {
let rate = 48_000.0;
let device_rate = rate * (1.0 + 120e-6);
let buffer = FrameBuffer::new(1, 480);
let mut drift = Drift::new(1, DeviceSide::Pushes, 1.0);
let mut chunks = 0;
let mut out = Vec::new();
let mut steps = Vec::new();
let mut ratios = Vec::new();
for packet in 0..8000 * 120u64 {
let now = packet as f64 / 8000.0;
while chunk_time(chunks, 1024, device_rate) <= now {
buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
chunks += 1;
}
drift.steer(&buffer);
let mut taken = vec![0.0; drift.wanted(6)];
buffer.pull(&mut taken);
drift.push(&taken);
out.clear();
drift.make(&mut out, 6);
assert_eq!(out.len(), 6);
if packet == 8000 {
buffer.underruns.store(0, Ordering::Relaxed);
}
if packet > 8000 * 40 {
steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
ratios.push(drift.ratio());
}
}
for ratio in &ratios {
assert!((ratio - (1.0 + 120e-6)).abs() < 30e-6, "{ratio}");
}
assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
assert!(most < 0.07, "{most}");
}
#[test]
fn a_slow_device_is_fed_without_a_gap() {
let rate = 48_000.0;
let device_rate = rate * (1.0 - 80e-6);
let buffer = FrameBuffer::new(1, 480);
let mut drift = Drift::new(1, DeviceSide::Pulls, 1.0);
let mut chunks = 0;
let mut made = Vec::new();
let mut played = vec![0.0; 1024];
let mut ratios = Vec::new();
for packet in 0..8000 * 120u64 {
drift.steer(&buffer);
drift.push(&sine(1000.0, rate, packet * 6, 6));
made.clear();
drift.make(&mut made, usize::MAX);
buffer.push(&made);
let now = packet as f64 / 8000.0;
while chunk_time(chunks + 1, 1024, device_rate) <= now {
buffer.device_pull(&mut played, None);
chunks += 1;
}
if packet == 8000 {
buffer.underruns.store(0, Ordering::Relaxed);
}
if packet > 8000 * 40 {
ratios.push(drift.ratio());
}
}
for ratio in &ratios {
assert!((ratio - 1.0 / (1.0 - 80e-6)).abs() < 30e-6, "{ratio}");
}
assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
}
#[test]
fn a_device_at_half_the_rate_is_followed() {
let device_rate = 48_000.0 * (1.0 + 50e-6);
let buffer = FrameBuffer::new(1, 480);
let mut drift = Drift::new(1, DeviceSide::Pushes, 0.5);
let mut chunks = 0;
let mut out = Vec::new();
let mut steps = Vec::new();
let mut ppms = Vec::new();
for packet in 0..8000 * 120u64 {
let now = packet as f64 / 8000.0;
while chunk_time(chunks, 1024, device_rate) <= now {
buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
chunks += 1;
}
drift.steer(&buffer);
let mut taken = vec![0.0; drift.wanted(12)];
buffer.pull(&mut taken);
drift.push(&taken);
out.clear();
drift.make(&mut out, 12);
assert_eq!(out.len(), 12);
if packet == 8000 {
buffer.underruns.store(0, Ordering::Relaxed);
}
if packet > 8000 * 40 {
steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
ppms.push(drift.device_ppm());
}
}
for ppm in &ppms {
assert!((ppm - 50).abs() < 30, "{ppm}");
}
assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
assert!(most < 0.04, "{most}");
}
#[test]
fn a_stream_at_four_times_the_devices_rate_is_made_whole() {
let mut drift = Drift::new(2, DeviceSide::Pulls, 4.0);
drift.ratio = 4.0 + 300e-6;
let mut out = Vec::new();
let mut made = 0;
let mut last: Option<f32> = None;
let mut most = 0.0f32;
for frame in 0..8000 * 10 {
let first = frame * 24;
let input: Vec<f32> = (first..first + 24)
.flat_map(|at| {
let sample = (TAU as f64 * 1000.0 * at as f64 / 192_000.0).sin() as f32 * 0.5;
[sample, -sample]
})
.collect();
drift.push(&input);
out.clear();
drift.make(&mut out, usize::MAX);
for pair in out.as_chunks::<2>().0 {
if let Some(previous) = last {
most = most.max((pair[0] - previous).abs());
}
last = Some(pair[0]);
made += 1;
}
}
let expected = 8000.0 * 10.0 * 24.0 / drift.ratio;
assert!((made as f64 - expected).abs() < 4.0, "{made}");
assert!(most < 0.07, "{most}");
}
fn play_out(chunk: usize, latency: f64, ahead: f64) -> (i64, f64, u64) {
let rate = 48_000.0;
let device_rate = rate * (1.0 - 50e-6);
let buffer = Arc::new(FrameBuffer::new(1, 480));
let output = Output::new(Some(buffer.clone()), None, 1, 1, 48_000, 48_000);
let tone = |seconds: f64| (TAU as f64 * 100.0 * seconds).sin() as f32 * 0.5;
let mut played = vec![0.0; chunk];
let mut chunks = 0;
let mut most = 0.0f64;
let mut underruns = 0;
for packet in 0..8000 * 60u64 {
let arrives = packet as f64 / 8000.0;
while chunk_time(chunks, chunk, device_rate) <= arrives {
let plays = chunks as f64 * chunk as f64 / device_rate + latency;
let after = plays + chunk as f64 / device_rate;
buffer.device_pull(&mut played, Some((after * 1e9) as i64));
if arrives > 40.0 {
let (delay, _) = output.playout().unwrap();
for (index, sample) in played.iter().enumerate() {
let at = plays + index as f64 / device_rate - delay as f64 * 1e-9;
let off = f64::from(sample - tone(at)) / (TAU as f64 * 100.0 * 0.5);
most = most.max(off.abs());
}
}
chunks += 1;
}
if packet == 8000 * 10 {
underruns = buffer.underruns.load(Ordering::Relaxed);
}
let first = arrives + ahead;
let samples: Vec<f32> = (0..6)
.map(|index| tone(first + index as f64 / rate))
.collect();
let presented = Presented {
first: (first * 1e9) as i64,
offset: 0,
};
output.write(&samples, Some(presented));
}
let (delay, _) = output.playout().unwrap();
let more = buffer.underruns.load(Ordering::Relaxed) - underruns;
(delay, most, more)
}
#[test]
fn a_slow_device_plays_a_fixed_delay_after_presentation() {
let (delay, most, underruns) = play_out(1024, 0.025, 0.0017);
assert_eq!(delay, 55_000_000);
assert!(most < 0.000_2, "{most}");
assert_eq!(underruns, 0);
}
#[test]
fn early_frames_play_at_presentation_time() {
let (delay, most, underruns) = play_out(256, 0.005, 0.1);
assert_eq!(delay, 0);
assert!(most < 0.000_2, "{most}");
assert_eq!(underruns, 0);
}
#[test]
fn a_tone_fills_every_channel() {
let mut input = Input::open(
&Source::Tone {
hertz: 1000.0,
level: 0.5,
},
2,
48_000,
)
.unwrap();
let mut out = [0.0; 96];
input.read(&mut out);
assert!(out.iter().all(|sample| sample.abs() <= 0.5));
assert!(
out.as_chunks::<2>()
.0
.iter()
.all(|frame| frame[0] == frame[1])
);
assert!(out.iter().any(|sample| sample.abs() > 0.4));
}
#[test]
fn a_stream_of_other_channels_takes_the_first() {
let stereo = [0.1, 0.2, 0.3, 0.4];
let mut eight = [9.0; 16];
respread(&stereo, 2, &mut eight, 8);
assert_eq!(
eight,
[
0.1, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
]
);
let mut two = [9.0; 4];
respread(&eight, 8, &mut two, 2);
assert_eq!(two, stereo);
}
}