1use std::collections::VecDeque;
16use std::f32::consts::TAU;
17use std::io;
18use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
19use std::sync::{Arc, Mutex, PoisonError, mpsc};
20use std::thread::JoinHandle;
21use std::time::Duration;
22
23use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
24use cpal::{FromSample, SizedSample};
25
26#[derive(Debug, Clone, PartialEq)]
28pub enum Source {
29 Silence,
30 Tone {
32 hertz: f32,
33 level: f32,
34 },
35 Device {
38 name: Option<String>,
39 first_channel: u16,
40 },
41 Shared(SharedBuffer),
44}
45
46#[derive(Clone)]
49pub struct SharedBuffer {
50 pub buffer: Arc<FrameBuffer>,
51 pub channels: u16,
52 pub rate: u32,
53}
54
55impl PartialEq for SharedBuffer {
56 fn eq(&self, other: &Self) -> bool {
57 Arc::ptr_eq(&self.buffer, &other.buffer)
58 }
59}
60
61impl std::fmt::Debug for SharedBuffer {
62 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63 write!(
64 formatter,
65 "SharedBuffer({} channels at {} Hz)",
66 self.channels, self.rate
67 )
68 }
69}
70
71#[derive(Debug, Clone, PartialEq)]
73pub enum Sink {
74 Discard,
76 Device {
79 name: Option<String>,
80 first_channel: u16,
81 },
82 Shared(SharedBuffer),
85}
86
87pub struct FrameBuffer {
90 held: Mutex<Held>,
91 channels: usize,
92 margin: usize,
94 pub underruns: AtomicU64,
97 pub adjustments: AtomicU64,
98}
99
100struct Held {
101 samples: VecDeque<f32>,
102 pushed: u64,
105 more: usize,
107 sample: Option<DeviceSample>,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct DeviceSample {
115 pub chunks: u64,
117 pub level: usize,
118 pub chunk: usize,
119 pub pushed: u64,
122 pub plays_at: Option<i64>,
125}
126
127impl FrameBuffer {
128 pub fn new(channels: u16, margin: usize) -> Self {
129 let channels = usize::from(channels).max(1);
130 FrameBuffer {
131 held: Mutex::new(Held {
132 samples: VecDeque::with_capacity(4 * margin * channels),
133 pushed: 0,
134 more: 0,
135 sample: None,
136 }),
137 channels,
138 margin: margin.max(1),
139 underruns: AtomicU64::new(0),
140 adjustments: AtomicU64::new(0),
141 }
142 }
143
144 fn lock(&self) -> std::sync::MutexGuard<'_, Held> {
145 self.held.lock().unwrap_or_else(PoisonError::into_inner)
146 }
147
148 pub fn push(&self, samples: &[f32]) {
151 let mut held = self.lock();
152 self.push_into(&mut held, samples);
153 }
154
155 fn push_into(&self, held: &mut Held, samples: &[f32]) {
156 held.samples.extend(samples);
157 held.pushed += (samples.len() / self.channels) as u64;
158 let chunk = held.sample.map_or(0, |sample| sample.chunk);
159 let most = (4 * (self.margin + chunk) + held.more) * self.channels;
160 if held.samples.len() > most {
161 let extra = held.samples.len() - most;
162 held.samples.drain(..extra - extra % self.channels);
163 self.adjustments.fetch_add(1, Ordering::Relaxed);
164 }
165 }
166
167 pub fn pull(&self, out: &mut [f32]) {
169 let mut held = self.lock();
170 self.pull_from(&mut held, out);
171 }
172
173 fn pull_from(&self, held: &mut Held, out: &mut [f32]) {
174 let mut short = false;
175 for slot in out.iter_mut() {
176 *slot = held.samples.pop_front().unwrap_or_else(|| {
177 short = true;
178 0.0
179 });
180 }
181 if short {
182 self.underruns.fetch_add(1, Ordering::Relaxed);
183 }
184 }
185
186 pub fn pushed(&self) -> u64 {
188 self.lock().pushed
189 }
190
191 pub fn hold_more(&self, frames: usize) {
193 let mut held = self.lock();
194 held.more = held.more.max(frames);
195 }
196
197 pub fn drop_oldest(&self, frames: usize) {
199 let mut held = self.lock();
200 let samples = (frames * self.channels).min(held.samples.len());
201 held.samples.drain(..samples);
202 }
203
204 pub fn device_push(&self, samples: &[f32]) {
206 let mut held = self.lock();
207 self.push_into(&mut held, samples);
208 self.note(&mut held, samples.len(), None);
209 }
210
211 pub fn device_pull(&self, out: &mut [f32], plays_at: Option<i64>) {
214 let mut held = self.lock();
215 self.pull_from(&mut held, out);
216 self.note(&mut held, out.len(), plays_at);
217 }
218
219 fn note(&self, held: &mut Held, samples: usize, plays_at: Option<i64>) {
220 let chunks = held.sample.map_or(1, |sample| sample.chunks + 1);
221 held.sample = Some(DeviceSample {
222 chunks,
223 level: held.samples.len() / self.channels,
224 chunk: samples / self.channels,
225 pushed: held.pushed,
226 plays_at,
227 });
228 }
229
230 pub fn device_sample(&self) -> Option<DeviceSample> {
232 self.lock().sample
233 }
234
235 pub fn level(&self) -> usize {
237 self.lock().samples.len() / self.channels
238 }
239}
240
241const SMOOTHING: f64 = 0.02;
247const PROPORTIONAL: f64 = 0.0051;
248const INTEGRAL: f64 = 1e-5;
249const MOST_DRIFT: f64 = 0.002;
251
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub enum DeviceSide {
255 Pushes,
257 Pulls,
259}
260
261pub struct Drift {
265 channels: usize,
266 side: DeviceSide,
267 nominal: f64,
271 held: VecDeque<f32>,
274 position: f64,
277 ratio: f64,
279 chunks: u64,
282 error: Option<f64>,
283 integral: f64,
284}
285
286impl Drift {
287 pub fn new(channels: u16, side: DeviceSide, nominal: f64) -> Self {
288 Drift {
289 channels: usize::from(channels).max(1),
290 side,
291 nominal,
292 held: VecDeque::new(),
293 position: 0.0,
294 ratio: nominal,
295 chunks: 0,
296 error: None,
297 integral: 0.0,
298 }
299 }
300
301 pub fn ratio(&self) -> f64 {
303 self.ratio
304 }
305
306 pub fn device_ppm(&self) -> i32 {
309 let relative = self.ratio / self.nominal;
310 let ppm = match self.side {
311 DeviceSide::Pushes => relative - 1.0,
313 DeviceSide::Pulls => 1.0 / relative - 1.0,
315 };
316 (ppm * 1e6).round() as i32
317 }
318
319 pub fn steer(&mut self, buffer: &FrameBuffer) {
323 if let Some(sample) = self.new_sample(buffer) {
324 let excess = sample.level as f64 - self.kept(buffer, &sample) as f64;
325 self.follow(excess, sample.chunk);
326 }
327 }
328
329 fn new_sample(&mut self, buffer: &FrameBuffer) -> Option<DeviceSample> {
331 let sample = buffer.device_sample()?;
332 if sample.chunks == self.chunks {
333 return None;
334 }
335 self.chunks = sample.chunks;
336 Some(sample)
337 }
338
339 fn kept(&self, buffer: &FrameBuffer, sample: &DeviceSample) -> usize {
343 match self.side {
344 DeviceSide::Pushes => buffer.margin + sample.chunk,
345 DeviceSide::Pulls => buffer.margin,
346 }
347 }
348
349 fn follow(&mut self, excess: f64, chunk: usize) {
352 let error = excess / chunk.max(1) as f64;
353 let smoothed = self.error.get_or_insert(error);
354 *smoothed += SMOOTHING * (error - *smoothed);
355 self.integral = (self.integral + INTEGRAL * *smoothed).clamp(-MOST_DRIFT, MOST_DRIFT);
356 self.ratio = self.nominal
357 * (1.0 + PROPORTIONAL * *smoothed + self.integral)
358 .clamp(1.0 - MOST_DRIFT, 1.0 + MOST_DRIFT);
359 }
360
361 fn held_frames(&self) -> usize {
362 self.held.len() / self.channels
363 }
364
365 fn pending(&self) -> f64 {
368 (self.held_frames() as f64 - 1.0 - self.position).max(0.0)
369 }
370
371 pub fn wanted(&self, frames: usize) -> usize {
373 if frames == 0 {
374 return 0;
375 }
376 let last = self.position + (frames - 1) as f64 * self.ratio;
377 (last as usize + 4).saturating_sub(self.held_frames())
378 }
379
380 pub fn push(&mut self, input: &[f32]) {
381 self.held.extend(input);
382 }
383
384 pub fn make(&mut self, out: &mut Vec<f32>, most: usize) {
387 let channels = self.channels;
388 let mut made = 0;
389 while made < most && self.position as usize + 4 <= self.held_frames() {
390 let base = self.position as usize;
391 let t = (self.position - base as f64) as f32;
392 for channel in 0..channels {
393 let at = |frame: usize| self.held[(base + frame) * channels + channel];
394 let (before, from, to, after) = (at(0), at(1), at(2), at(3));
395 let a = -0.5 * before + 1.5 * from - 1.5 * to + 0.5 * after;
397 let b = before - 2.5 * from + 2.0 * to - 0.5 * after;
398 let c = -0.5 * before + 0.5 * to;
399 out.push(((a * t + b) * t + c) * t + from);
400 }
401 made += 1;
402 self.position += self.ratio;
403 let passed = (self.position as usize).min(self.held_frames());
406 if passed > 0 {
407 self.held.drain(..passed * channels);
408 self.position -= passed as f64;
409 }
410 }
411 }
412}
413
414struct DeviceThread {
416 stop: Arc<AtomicBool>,
417 handle: Option<JoinHandle<()>>,
418}
419
420impl Drop for DeviceThread {
421 fn drop(&mut self) {
422 self.stop.store(true, Ordering::Relaxed);
423 if let Some(handle) = self.handle.take() {
424 handle.thread().unpark();
425 let _ = handle.join();
426 }
427 }
428}
429
430fn device_error(error: impl std::fmt::Display) -> io::Error {
431 io::Error::other(error.to_string())
432}
433
434fn find_device(name: Option<&str>, input: bool) -> io::Result<cpal::Device> {
436 let host = cpal::default_host();
437 let found = match name {
438 Some(name) => {
439 let devices = if input {
440 host.input_devices()
441 } else {
442 host.output_devices()
443 }
444 .map_err(device_error)?;
445 devices
446 .into_iter()
447 .find(|device| device.description().is_ok_and(|about| about.name() == name))
448 }
449 None if input => host.default_input_device(),
450 None => host.default_output_device(),
451 };
452 found.ok_or_else(|| {
453 io::Error::new(
454 io::ErrorKind::NotFound,
455 match name {
456 Some(name) => format!("no audio device named {name}"),
457 None => "no default audio device".to_owned(),
458 },
459 )
460 })
461}
462
463fn device_rate(device: &cpal::Device, input: bool, wanted: u32) -> io::Result<u32> {
466 let default = if input {
467 device.default_input_config()
468 } else {
469 device.default_output_config()
470 }
471 .map_err(device_error)?;
472 if default.sample_rate() == wanted {
473 return Ok(wanted);
474 }
475 let ranges: Vec<cpal::SupportedStreamConfigRange> = if input {
476 device.supported_input_configs().map(Iterator::collect)
477 } else {
478 device.supported_output_configs().map(Iterator::collect)
479 }
480 .unwrap_or_default();
481 let supported = ranges.iter().any(|range| {
482 range.channels() == default.channels()
483 && (range.min_sample_rate()..=range.max_sample_rate()).contains(&wanted)
484 });
485 Ok(if supported {
486 wanted
487 } else {
488 default.sample_rate()
489 })
490}
491
492pub fn device_names() -> (Vec<String>, Vec<String>) {
494 let host = cpal::default_host();
495 let named = |device: cpal::Device| Some(device.description().ok()?.name().to_owned());
496 let inputs = host
497 .input_devices()
498 .map(|devices| devices.filter_map(named).collect())
499 .unwrap_or_default();
500 let outputs = host
501 .output_devices()
502 .map(|devices| devices.filter_map(named).collect())
503 .unwrap_or_default();
504 (inputs, outputs)
505}
506
507fn device_thread(
510 name: String,
511 build: impl FnOnce() -> io::Result<cpal::Stream> + Send + 'static,
512) -> io::Result<DeviceThread> {
513 let stop = Arc::new(AtomicBool::new(false));
514 let stopping = stop.clone();
515 let (opened, started) = mpsc::channel();
516 let handle = std::thread::Builder::new().name(name).spawn(move || {
517 let stream = match build().and_then(|stream| {
518 stream.play().map_err(device_error)?;
519 Ok(stream)
520 }) {
521 Ok(stream) => {
522 let _ = opened.send(Ok(()));
523 stream
524 }
525 Err(error) => {
526 let _ = opened.send(Err(error));
527 return;
528 }
529 };
530 while !stopping.load(Ordering::Relaxed) {
531 std::thread::park_timeout(Duration::from_millis(200));
532 }
533 drop(stream);
534 })?;
535 started
536 .recv()
537 .unwrap_or_else(|_| Err(io::Error::other("the audio thread stopped")))?;
538 Ok(DeviceThread {
539 stop,
540 handle: Some(handle),
541 })
542}
543
544fn input_stream<T>(
545 device: &cpal::Device,
546 config: cpal::StreamConfig,
547 channels: usize,
548 first: usize,
549 buffer: Arc<FrameBuffer>,
550) -> io::Result<cpal::Stream>
551where
552 T: SizedSample,
553 f32: FromSample<T>,
554{
555 let device_channels = usize::from(config.channels).max(1);
556 let mut frames = Vec::new();
557 device
558 .build_input_stream(
559 config,
560 move |data: &[T], _: &cpal::InputCallbackInfo| {
561 frames.clear();
562 for frame in data.chunks_exact(device_channels) {
563 for channel in 0..channels {
564 frames.push(
565 frame
566 .get(first + channel)
567 .map_or(0.0, |sample| sample.to_sample::<f32>()),
568 );
569 }
570 }
571 buffer.device_push(&frames);
572 },
573 |_| {},
574 None,
575 )
576 .map_err(device_error)
577}
578
579fn output_stream<T>(
580 device: &cpal::Device,
581 config: cpal::StreamConfig,
582 channels: usize,
583 first: usize,
584 buffer: Arc<FrameBuffer>,
585) -> io::Result<cpal::Stream>
586where
587 T: SizedSample + FromSample<f32>,
588{
589 let device_channels = usize::from(config.channels).max(1);
590 let rate = i64::from(config.sample_rate.max(1));
591 let mut frames = Vec::new();
592 device
593 .build_output_stream(
594 config,
595 move |data: &mut [T], info: &cpal::OutputCallbackInfo| {
596 let count = data.len() / device_channels;
597 frames.resize(count * channels, 0.0);
598 let stamp = info.timestamp();
601 let latency = stamp.playback.duration_since(stamp.callback);
602 let plays_at = avb_net::clock::monotonic_now() + latency;
603 let after = plays_at.as_nanos() as i64 + count as i64 * 1_000_000_000 / rate;
604 buffer.device_pull(&mut frames, Some(after));
605 for (frame, samples) in data
606 .chunks_exact_mut(device_channels)
607 .zip(frames.chunks_exact(channels.max(1)))
608 {
609 for (channel, slot) in frame.iter_mut().enumerate() {
610 let sample = channel
611 .checked_sub(first)
612 .and_then(|stream| samples.get(stream))
613 .copied()
614 .unwrap_or(0.0);
615 *slot = T::from_sample(sample);
616 }
617 }
618 },
619 |_| {},
620 None,
621 )
622 .map_err(device_error)
623}
624
625pub struct Input {
627 kind: InputKind,
628 channels: usize,
629 spread: Vec<f32>,
631}
632
633enum InputKind {
634 Silence,
635 Tone {
636 phase: f32,
637 step: f32,
638 level: f32,
639 },
640 Device {
641 buffer: Arc<FrameBuffer>,
642 drift: Drift,
643 taken: Vec<f32>,
645 made: Vec<f32>,
646 _thread: Option<DeviceThread>,
647 },
648}
649
650impl Input {
651 pub fn open(source: &Source, channels: u16, rate: u32) -> io::Result<Self> {
653 let kind = match source {
654 Source::Silence => InputKind::Silence,
655 Source::Tone { hertz, level } => InputKind::Tone {
656 phase: 0.0,
657 step: TAU * hertz / rate as f32,
658 level: level.clamp(0.0, 1.0),
659 },
660 Source::Device {
661 name,
662 first_channel,
663 } => {
664 let device = find_device(name.as_deref(), true)?;
665 let device_rate = device_rate(&device, true, rate)?;
666 let margin = device_rate as usize / 100;
668 let buffer = Arc::new(FrameBuffer::new(channels, margin));
669 let filling = buffer.clone();
670 let first = usize::from(*first_channel);
671 let wanted = usize::from(channels);
672 let thread = device_thread("audio input".into(), move || {
673 let supported = device.default_input_config().map_err(device_error)?;
674 let mut config = supported.config();
675 config.sample_rate = device_rate;
676 match supported.sample_format() {
677 cpal::SampleFormat::F32 => {
678 input_stream::<f32>(&device, config, wanted, first, filling)
679 }
680 cpal::SampleFormat::I16 => {
681 input_stream::<i16>(&device, config, wanted, first, filling)
682 }
683 cpal::SampleFormat::I32 => {
684 input_stream::<i32>(&device, config, wanted, first, filling)
685 }
686 other => Err(io::Error::new(
687 io::ErrorKind::Unsupported,
688 format!("samples in {other}"),
689 )),
690 }
691 })?;
692 InputKind::Device {
693 buffer,
694 drift: Drift::new(
695 channels,
696 DeviceSide::Pushes,
697 f64::from(device_rate) / f64::from(rate),
698 ),
699 taken: Vec::new(),
700 made: Vec::new(),
701 _thread: Some(thread),
702 }
703 }
704 Source::Shared(shared) => {
705 if shared.channels != channels {
706 return Err(io::Error::new(
707 io::ErrorKind::InvalidInput,
708 "a shared buffer of other channels than the stream's",
709 ));
710 }
711 shared.buffer.drop_oldest(shared.buffer.level());
714 InputKind::Device {
715 buffer: shared.buffer.clone(),
716 drift: Drift::new(
717 channels,
718 DeviceSide::Pushes,
719 f64::from(shared.rate) / f64::from(rate),
720 ),
721 taken: Vec::new(),
722 made: Vec::new(),
723 _thread: None,
724 }
725 }
726 };
727 Ok(Input {
728 kind,
729 channels: usize::from(channels),
730 spread: Vec::new(),
731 })
732 }
733
734 pub fn drift_ppm(&self) -> i32 {
737 match &self.kind {
738 InputKind::Device { drift, .. } => drift.device_ppm(),
739 _ => 0,
740 }
741 }
742
743 pub fn counts(&self) -> (u64, u64) {
746 match &self.kind {
747 InputKind::Device { buffer, .. } => (
748 buffer.adjustments.load(Ordering::Relaxed),
749 buffer.underruns.load(Ordering::Relaxed),
750 ),
751 _ => (0, 0),
752 }
753 }
754
755 pub fn read(&mut self, out: &mut [f32]) {
757 match &mut self.kind {
758 InputKind::Silence => out.fill(0.0),
759 InputKind::Tone { phase, step, level } => {
760 for frame in out.chunks_exact_mut(self.channels.max(1)) {
761 frame.fill(phase.sin() * *level);
762 *phase = (*phase + *step) % TAU;
763 }
764 }
765 InputKind::Device {
766 buffer,
767 drift,
768 taken,
769 made,
770 ..
771 } => {
772 let frames = out.len() / self.channels.max(1);
773 drift.steer(buffer);
774 taken.resize(drift.wanted(frames) * self.channels, 0.0);
775 buffer.pull(taken);
776 drift.push(taken);
777 made.clear();
778 drift.make(made, frames);
779 out.fill(0.0);
780 out[..made.len()].copy_from_slice(made);
781 }
782 }
783 }
784
785 pub fn read_as(&mut self, out: &mut [f32], channels: usize) {
789 let channels = channels.max(1);
790 if channels == self.channels.max(1) {
791 self.read(out);
792 return;
793 }
794 let mut spread = std::mem::take(&mut self.spread);
795 spread.resize(out.len() / channels * self.channels.max(1), 0.0);
796 self.read(&mut spread);
797 respread(&spread, self.channels, out, channels);
798 self.spread = spread;
799 }
800}
801
802fn respread(samples: &[f32], channels: usize, out: &mut [f32], out_channels: usize) {
806 let (channels, out_channels) = (channels.max(1), out_channels.max(1));
807 let kept = channels.min(out_channels);
808 for (to, from) in out
809 .chunks_exact_mut(out_channels)
810 .zip(samples.chunks_exact(channels))
811 {
812 to[..kept].copy_from_slice(&from[..kept]);
813 to[kept..].fill(0.0);
814 }
815}
816
817#[derive(Debug, Clone, Copy, PartialEq, Eq)]
819pub struct Presented {
820 pub first: i64,
822 pub offset: i64,
824}
825
826const CHOOSING: i64 = 2_000_000_000;
828const DELAY_STEP: i64 = 1_000_000;
831const MOST_DELAY: i64 = 500_000_000;
832const MOST_AHEAD: i64 = 500_000_000;
835
836struct Playing {
838 drift: Drift,
839 made: Vec<f32>,
840 next_in: Option<i64>,
843 offset: Option<i64>,
844 anchor: Option<(u64, i64)>,
846 delay: Option<i64>,
849 error: i64,
850 choosing: Option<(i64, f64, u32)>,
853 underruns: u64,
855}
856
857pub struct Output {
859 buffer: Option<Arc<FrameBuffer>>,
860 _thread: Option<DeviceThread>,
861 playing: Mutex<Playing>,
862 rate: u32,
864 peak: AtomicU32,
866}
867
868impl Output {
869 pub fn open(sink: &Sink, channels: u16, rate: u32) -> io::Result<Self> {
871 match sink {
872 Sink::Discard => Ok(Output::new(None, None, channels, rate, rate)),
873 Sink::Shared(shared) if shared.channels != channels => Err(io::Error::new(
874 io::ErrorKind::InvalidInput,
875 "a shared buffer of other channels than the stream's",
876 )),
877 Sink::Shared(shared) => Ok(Output::new(
878 Some(shared.buffer.clone()),
879 None,
880 channels,
881 rate,
882 shared.rate,
883 )),
884 Sink::Device {
885 name,
886 first_channel,
887 } => {
888 let device = find_device(name.as_deref(), false)?;
889 let device_rate = device_rate(&device, false, rate)?;
890 let margin = device_rate as usize / 100;
891 let buffer = Arc::new(FrameBuffer::new(channels, margin));
892 let draining = buffer.clone();
893 let first = usize::from(*first_channel);
894 let wanted = usize::from(channels);
895 let thread = device_thread("audio output".into(), move || {
896 let supported = device.default_output_config().map_err(device_error)?;
897 let mut config = supported.config();
898 config.sample_rate = device_rate;
899 match supported.sample_format() {
900 cpal::SampleFormat::F32 => {
901 output_stream::<f32>(&device, config, wanted, first, draining)
902 }
903 cpal::SampleFormat::I16 => {
904 output_stream::<i16>(&device, config, wanted, first, draining)
905 }
906 cpal::SampleFormat::I32 => {
907 output_stream::<i32>(&device, config, wanted, first, draining)
908 }
909 other => Err(io::Error::new(
910 io::ErrorKind::Unsupported,
911 format!("samples in {other}"),
912 )),
913 }
914 })?;
915 Ok(Output::new(
916 Some(buffer),
917 Some(thread),
918 channels,
919 rate,
920 device_rate,
921 ))
922 }
923 }
924 }
925
926 fn new(
927 buffer: Option<Arc<FrameBuffer>>,
928 thread: Option<DeviceThread>,
929 channels: u16,
930 rate: u32,
931 device_rate: u32,
932 ) -> Self {
933 let nominal = f64::from(rate) / f64::from(device_rate.max(1));
934 Output {
935 buffer,
936 _thread: thread,
937 playing: Mutex::new(Playing {
938 drift: Drift::new(channels, DeviceSide::Pulls, nominal),
939 made: Vec::new(),
940 next_in: None,
941 offset: None,
942 anchor: None,
943 delay: None,
944 error: 0,
945 choosing: None,
946 underruns: 0,
947 }),
948 rate: rate.max(1),
949 peak: AtomicU32::new(0),
950 }
951 }
952
953 fn lock(&self) -> std::sync::MutexGuard<'_, Playing> {
954 self.playing.lock().unwrap_or_else(PoisonError::into_inner)
955 }
956
957 pub fn write(&self, samples: &[f32], presented: Option<Presented>) {
960 let loudest = samples
961 .iter()
962 .fold(0.0f32, |most, sample| most.max(sample.abs()));
963 self.peak.fetch_max(loudest.to_bits(), Ordering::Relaxed);
964 let Some(buffer) = &self.buffer else {
965 return;
966 };
967 let mut playing = self.lock();
968 let playing = &mut *playing;
969 if let Some(presented) = presented {
970 playing.next_in = Some(presented.first);
971 playing.offset = Some(presented.offset);
972 }
973 if let Some(sample) = playing.drift.new_sample(buffer) {
974 self.steer(playing, buffer, &sample);
975 }
976 playing.drift.push(samples);
977 playing.made.clear();
978 playing.drift.make(&mut playing.made, usize::MAX);
979 buffer.push(&playing.made);
980 let frames = samples.len() / playing.drift.channels;
981 let frame = 1e9 / f64::from(self.rate);
982 if let Some(next) = &mut playing.next_in {
983 *next += (frames as f64 * frame).round() as i64;
984 let made = *next - (playing.drift.pending() * frame).round() as i64;
987 playing.anchor = Some((buffer.pushed(), made));
988 }
989 }
990
991 fn steer(&self, playing: &mut Playing, buffer: &FrameBuffer, sample: &DeviceSample) {
994 let excess = sample.level as f64 - playing.drift.kept(buffer, sample) as f64;
995 let (Some(plays_at), Some((anchor, presented)), Some(offset)) =
996 (sample.plays_at, playing.anchor, playing.offset)
997 else {
998 playing.drift.follow(excess, sample.chunk);
999 return;
1000 };
1001 let frame = playing.drift.ratio() * 1e9 / f64::from(self.rate);
1003 let oldest = sample.pushed - sample.level as u64;
1004 let presents = presented as f64 - (anchor as f64 - oldest as f64) * frame;
1005 let late = (plays_at + offset) as f64 - presents;
1006 if !(-MOST_AHEAD as f64..=2.0 * MOST_DELAY as f64).contains(&late) {
1007 playing.drift.follow(excess, sample.chunk);
1008 return;
1009 }
1010 let Some(delay) = playing.delay else {
1011 playing.drift.follow(excess, sample.chunk);
1014 let (since, sum, seen) = playing.choosing.get_or_insert((plays_at, 0.0, 0));
1015 *sum += late - excess * frame;
1016 *seen += 1;
1017 if plays_at - *since >= CHOOSING {
1018 let earliest = (*sum / f64::from(*seen)).max(0.0) as i64;
1019 let steps = (earliest + DELAY_STEP - 1) / DELAY_STEP;
1020 let delay = (steps * DELAY_STEP).min(MOST_DELAY);
1021 self.set_delay(playing, buffer, delay, (late - delay as f64) / frame);
1022 }
1023 return;
1024 };
1025 let underruns = buffer.underruns.load(Ordering::Relaxed);
1026 if underruns > playing.underruns && delay < MOST_DELAY {
1027 let later = delay + DELAY_STEP;
1028 self.set_delay(playing, buffer, later, (late - later as f64) / frame);
1029 return;
1030 }
1031 playing.error = (late - delay as f64) as i64;
1032 playing
1033 .drift
1034 .follow((late - delay as f64) / frame, sample.chunk);
1035 }
1036
1037 fn set_delay(&self, playing: &mut Playing, buffer: &FrameBuffer, delay: i64, excess: f64) {
1040 playing.delay = Some(delay);
1041 playing.error = 0;
1042 playing.underruns = buffer.underruns.load(Ordering::Relaxed);
1043 let excess = excess.round() as i64;
1044 buffer.hold_more(excess.unsigned_abs() as usize);
1045 if excess > 0 {
1046 buffer.drop_oldest(excess as usize);
1047 } else if excess < 0 {
1048 let frames = excess.unsigned_abs() as usize;
1051 buffer.push(&vec![0.0; frames * playing.drift.channels]);
1052 if let Some((anchor, _)) = &mut playing.anchor {
1053 *anchor += frames as u64;
1054 }
1055 }
1056 }
1057
1058 pub fn playout(&self) -> Option<(i64, i64)> {
1062 let playing = self.lock();
1063 playing.delay.map(|delay| (delay, playing.error))
1064 }
1065
1066 pub fn drift_ppm(&self) -> i32 {
1069 if self.buffer.is_none() {
1070 return 0;
1071 }
1072 self.lock().drift.device_ppm()
1073 }
1074
1075 pub fn underruns(&self) -> u64 {
1077 self.buffer
1078 .as_ref()
1079 .map_or(0, |buffer| buffer.underruns.load(Ordering::Relaxed))
1080 }
1081
1082 pub fn take_peak(&self) -> f32 {
1084 f32::from_bits(self.peak.swap(0, Ordering::Relaxed))
1085 }
1086}
1087
1088#[cfg(test)]
1089mod tests {
1090 use super::*;
1091
1092 #[test]
1093 fn the_buffer_notes_its_fill_after_each_device_chunk() {
1094 let buffer = FrameBuffer::new(2, 10);
1095 assert_eq!(buffer.device_sample(), None);
1096 buffer.device_push(&[1.0; 8]);
1097 buffer.push(&[2.0; 4]);
1098 assert_eq!(
1099 buffer.device_sample(),
1100 Some(DeviceSample {
1101 chunks: 1,
1102 level: 4,
1103 chunk: 4,
1104 pushed: 4,
1105 plays_at: None,
1106 })
1107 );
1108 let mut out = [9.0; 6];
1109 buffer.device_pull(&mut out, None);
1110 assert_eq!(out, [1.0; 6]);
1111 assert_eq!(buffer.device_sample().map(|sample| sample.chunks), Some(2));
1112 buffer.push(&[3.0; 200]);
1114 assert_eq!(buffer.level(), 4 * (10 + 3));
1115 assert!(buffer.adjustments.load(Ordering::Relaxed) > 0);
1116 let mut out = [9.0; 120];
1118 buffer.pull(&mut out);
1119 assert_eq!(out[104..], [0.0; 16]);
1120 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 1);
1121 }
1122
1123 fn sine(hertz: f64, rate: f64, start: u64, frames: usize) -> Vec<f32> {
1125 (0..frames as u64)
1126 .map(|index| (TAU as f64 * hertz * (start + index) as f64 / rate).sin() as f32 * 0.5)
1127 .collect()
1128 }
1129
1130 fn chunk_time(index: u64, chunk: usize, rate: f64) -> f64 {
1133 let nominal = index as f64 * chunk as f64 / rate;
1134 let wobble = ((index * 7919) % 41) as f64 / 40.0 - 0.5;
1135 nominal + 0.04 * wobble * chunk as f64 / rate
1136 }
1137
1138 #[test]
1143 fn a_fast_device_is_followed_without_a_gap() {
1144 let rate = 48_000.0;
1145 let device_rate = rate * (1.0 + 120e-6);
1146 let buffer = FrameBuffer::new(1, 480);
1147 let mut drift = Drift::new(1, DeviceSide::Pushes, 1.0);
1148 let mut chunks = 0;
1149 let mut out = Vec::new();
1150 let mut steps = Vec::new();
1151 let mut ratios = Vec::new();
1152 for packet in 0..8000 * 120u64 {
1153 let now = packet as f64 / 8000.0;
1154 while chunk_time(chunks, 1024, device_rate) <= now {
1155 buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1156 chunks += 1;
1157 }
1158 drift.steer(&buffer);
1159 let mut taken = vec![0.0; drift.wanted(6)];
1160 buffer.pull(&mut taken);
1161 drift.push(&taken);
1162 out.clear();
1163 drift.make(&mut out, 6);
1164 assert_eq!(out.len(), 6);
1165 if packet == 8000 {
1166 buffer.underruns.store(0, Ordering::Relaxed);
1167 }
1168 if packet > 8000 * 40 {
1169 steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1170 ratios.push(drift.ratio());
1171 }
1172 }
1173 for ratio in &ratios {
1174 assert!((ratio - (1.0 + 120e-6)).abs() < 30e-6, "{ratio}");
1175 }
1176 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1177 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1178 let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1181 assert!(most < 0.07, "{most}");
1182 }
1183
1184 #[test]
1188 fn a_slow_device_is_fed_without_a_gap() {
1189 let rate = 48_000.0;
1190 let device_rate = rate * (1.0 - 80e-6);
1191 let buffer = FrameBuffer::new(1, 480);
1192 let mut drift = Drift::new(1, DeviceSide::Pulls, 1.0);
1193 let mut chunks = 0;
1194 let mut made = Vec::new();
1195 let mut played = vec![0.0; 1024];
1196 let mut ratios = Vec::new();
1197 for packet in 0..8000 * 120u64 {
1198 drift.steer(&buffer);
1199 drift.push(&sine(1000.0, rate, packet * 6, 6));
1200 made.clear();
1201 drift.make(&mut made, usize::MAX);
1202 buffer.push(&made);
1203 let now = packet as f64 / 8000.0;
1204 while chunk_time(chunks + 1, 1024, device_rate) <= now {
1205 buffer.device_pull(&mut played, None);
1206 chunks += 1;
1207 }
1208 if packet == 8000 {
1209 buffer.underruns.store(0, Ordering::Relaxed);
1210 }
1211 if packet > 8000 * 40 {
1212 ratios.push(drift.ratio());
1213 }
1214 }
1215 for ratio in &ratios {
1216 assert!((ratio - 1.0 / (1.0 - 80e-6)).abs() < 30e-6, "{ratio}");
1217 }
1218 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1219 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1220 }
1221
1222 #[test]
1227 fn a_device_at_half_the_rate_is_followed() {
1228 let device_rate = 48_000.0 * (1.0 + 50e-6);
1229 let buffer = FrameBuffer::new(1, 480);
1230 let mut drift = Drift::new(1, DeviceSide::Pushes, 0.5);
1231 let mut chunks = 0;
1232 let mut out = Vec::new();
1233 let mut steps = Vec::new();
1234 let mut ppms = Vec::new();
1235 for packet in 0..8000 * 120u64 {
1236 let now = packet as f64 / 8000.0;
1237 while chunk_time(chunks, 1024, device_rate) <= now {
1238 buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1239 chunks += 1;
1240 }
1241 drift.steer(&buffer);
1242 let mut taken = vec![0.0; drift.wanted(12)];
1243 buffer.pull(&mut taken);
1244 drift.push(&taken);
1245 out.clear();
1246 drift.make(&mut out, 12);
1247 assert_eq!(out.len(), 12);
1248 if packet == 8000 {
1249 buffer.underruns.store(0, Ordering::Relaxed);
1250 }
1251 if packet > 8000 * 40 {
1252 steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1253 ppms.push(drift.device_ppm());
1254 }
1255 }
1256 for ppm in &ppms {
1257 assert!((ppm - 50).abs() < 30, "{ppm}");
1258 }
1259 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1260 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1261 let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1263 assert!(most < 0.04, "{most}");
1264 }
1265
1266 #[test]
1270 fn a_stream_at_four_times_the_devices_rate_is_made_whole() {
1271 let mut drift = Drift::new(2, DeviceSide::Pulls, 4.0);
1272 drift.ratio = 4.0 + 300e-6;
1273 let mut out = Vec::new();
1274 let mut made = 0;
1275 let mut last: Option<f32> = None;
1276 let mut most = 0.0f32;
1277 for frame in 0..8000 * 10 {
1278 let first = frame * 24;
1279 let input: Vec<f32> = (first..first + 24)
1280 .flat_map(|at| {
1281 let sample = (TAU as f64 * 1000.0 * at as f64 / 192_000.0).sin() as f32 * 0.5;
1282 [sample, -sample]
1283 })
1284 .collect();
1285 drift.push(&input);
1286 out.clear();
1287 drift.make(&mut out, usize::MAX);
1288 for pair in out.as_chunks::<2>().0 {
1289 if let Some(previous) = last {
1290 most = most.max((pair[0] - previous).abs());
1291 }
1292 last = Some(pair[0]);
1293 made += 1;
1294 }
1295 }
1296 let expected = 8000.0 * 10.0 * 24.0 / drift.ratio;
1298 assert!((made as f64 - expected).abs() < 4.0, "{made}");
1299 assert!(most < 0.07, "{most}");
1301 }
1302
1303 fn play_out(chunk: usize, latency: f64, ahead: f64) -> (i64, f64, u64) {
1309 let rate = 48_000.0;
1310 let device_rate = rate * (1.0 - 50e-6);
1311 let buffer = Arc::new(FrameBuffer::new(1, 480));
1312 let output = Output::new(Some(buffer.clone()), None, 1, 48_000, 48_000);
1313 let tone = |seconds: f64| (TAU as f64 * 100.0 * seconds).sin() as f32 * 0.5;
1314 let mut played = vec![0.0; chunk];
1315 let mut chunks = 0;
1316 let mut most = 0.0f64;
1317 let mut underruns = 0;
1318 for packet in 0..8000 * 60u64 {
1319 let arrives = packet as f64 / 8000.0;
1320 while chunk_time(chunks, chunk, device_rate) <= arrives {
1321 let plays = chunks as f64 * chunk as f64 / device_rate + latency;
1322 let after = plays + chunk as f64 / device_rate;
1323 buffer.device_pull(&mut played, Some((after * 1e9) as i64));
1324 if arrives > 40.0 {
1325 let (delay, _) = output.playout().unwrap();
1326 for (index, sample) in played.iter().enumerate() {
1327 let at = plays + index as f64 / device_rate - delay as f64 * 1e-9;
1328 let off = f64::from(sample - tone(at)) / (TAU as f64 * 100.0 * 0.5);
1330 most = most.max(off.abs());
1331 }
1332 }
1333 chunks += 1;
1334 }
1335 if packet == 8000 * 10 {
1336 underruns = buffer.underruns.load(Ordering::Relaxed);
1337 }
1338 let first = arrives + ahead;
1339 let samples: Vec<f32> = (0..6)
1340 .map(|index| tone(first + index as f64 / rate))
1341 .collect();
1342 let presented = Presented {
1343 first: (first * 1e9) as i64,
1344 offset: 0,
1345 };
1346 output.write(&samples, Some(presented));
1347 }
1348 let (delay, _) = output.playout().unwrap();
1349 let more = buffer.underruns.load(Ordering::Relaxed) - underruns;
1350 (delay, most, more)
1351 }
1352
1353 #[test]
1358 fn a_slow_device_plays_a_fixed_delay_after_presentation() {
1359 let (delay, most, underruns) = play_out(1024, 0.025, 0.0017);
1360 assert_eq!(delay, 55_000_000);
1361 assert!(most < 0.000_2, "{most}");
1362 assert_eq!(underruns, 0);
1363 }
1364
1365 #[test]
1368 fn early_frames_play_at_presentation_time() {
1369 let (delay, most, underruns) = play_out(256, 0.005, 0.1);
1370 assert_eq!(delay, 0);
1371 assert!(most < 0.000_2, "{most}");
1372 assert_eq!(underruns, 0);
1373 }
1374
1375 #[test]
1376 fn a_tone_fills_every_channel() {
1377 let mut input = Input::open(
1378 &Source::Tone {
1379 hertz: 1000.0,
1380 level: 0.5,
1381 },
1382 2,
1383 48_000,
1384 )
1385 .unwrap();
1386 let mut out = [0.0; 96];
1387 input.read(&mut out);
1388 assert!(out.iter().all(|sample| sample.abs() <= 0.5));
1389 assert!(
1390 out.as_chunks::<2>()
1391 .0
1392 .iter()
1393 .all(|frame| frame[0] == frame[1])
1394 );
1395 assert!(out.iter().any(|sample| sample.abs() > 0.4));
1396 }
1397
1398 #[test]
1402 fn a_stream_of_other_channels_takes_the_first() {
1403 let stereo = [0.1, 0.2, 0.3, 0.4];
1404 let mut eight = [9.0; 16];
1405 respread(&stereo, 2, &mut eight, 8);
1406 assert_eq!(
1407 eight,
1408 [
1409 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
1410 ]
1411 );
1412 let mut two = [9.0; 4];
1413 respread(&eight, 8, &mut two, 2);
1414 assert_eq!(two, stereo);
1415 }
1416}