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;
404 if passed > 0 {
405 self.held.drain(..passed * channels);
406 self.position -= passed as f64;
407 }
408 }
409 }
410}
411
412struct DeviceThread {
414 stop: Arc<AtomicBool>,
415 handle: Option<JoinHandle<()>>,
416}
417
418impl Drop for DeviceThread {
419 fn drop(&mut self) {
420 self.stop.store(true, Ordering::Relaxed);
421 if let Some(handle) = self.handle.take() {
422 handle.thread().unpark();
423 let _ = handle.join();
424 }
425 }
426}
427
428fn device_error(error: impl std::fmt::Display) -> io::Error {
429 io::Error::other(error.to_string())
430}
431
432fn find_device(name: Option<&str>, input: bool) -> io::Result<cpal::Device> {
434 let host = cpal::default_host();
435 let found = match name {
436 Some(name) => {
437 let devices = if input {
438 host.input_devices()
439 } else {
440 host.output_devices()
441 }
442 .map_err(device_error)?;
443 devices
444 .into_iter()
445 .find(|device| device.description().is_ok_and(|about| about.name() == name))
446 }
447 None if input => host.default_input_device(),
448 None => host.default_output_device(),
449 };
450 found.ok_or_else(|| {
451 io::Error::new(
452 io::ErrorKind::NotFound,
453 match name {
454 Some(name) => format!("no audio device named {name}"),
455 None => "no default audio device".to_owned(),
456 },
457 )
458 })
459}
460
461fn device_rate(device: &cpal::Device, input: bool, wanted: u32) -> io::Result<u32> {
464 let default = if input {
465 device.default_input_config()
466 } else {
467 device.default_output_config()
468 }
469 .map_err(device_error)?;
470 if default.sample_rate() == wanted {
471 return Ok(wanted);
472 }
473 let ranges: Vec<cpal::SupportedStreamConfigRange> = if input {
474 device.supported_input_configs().map(Iterator::collect)
475 } else {
476 device.supported_output_configs().map(Iterator::collect)
477 }
478 .unwrap_or_default();
479 let supported = ranges.iter().any(|range| {
480 range.channels() == default.channels()
481 && (range.min_sample_rate()..=range.max_sample_rate()).contains(&wanted)
482 });
483 Ok(if supported {
484 wanted
485 } else {
486 default.sample_rate()
487 })
488}
489
490pub fn device_names() -> (Vec<String>, Vec<String>) {
492 let host = cpal::default_host();
493 let named = |device: cpal::Device| Some(device.description().ok()?.name().to_owned());
494 let inputs = host
495 .input_devices()
496 .map(|devices| devices.filter_map(named).collect())
497 .unwrap_or_default();
498 let outputs = host
499 .output_devices()
500 .map(|devices| devices.filter_map(named).collect())
501 .unwrap_or_default();
502 (inputs, outputs)
503}
504
505fn device_thread(
508 name: String,
509 build: impl FnOnce() -> io::Result<cpal::Stream> + Send + 'static,
510) -> io::Result<DeviceThread> {
511 let stop = Arc::new(AtomicBool::new(false));
512 let stopping = stop.clone();
513 let (opened, started) = mpsc::channel();
514 let handle = std::thread::Builder::new().name(name).spawn(move || {
515 let stream = match build().and_then(|stream| {
516 stream.play().map_err(device_error)?;
517 Ok(stream)
518 }) {
519 Ok(stream) => {
520 let _ = opened.send(Ok(()));
521 stream
522 }
523 Err(error) => {
524 let _ = opened.send(Err(error));
525 return;
526 }
527 };
528 while !stopping.load(Ordering::Relaxed) {
529 std::thread::park_timeout(Duration::from_millis(200));
530 }
531 drop(stream);
532 })?;
533 started
534 .recv()
535 .unwrap_or_else(|_| Err(io::Error::other("the audio thread stopped")))?;
536 Ok(DeviceThread {
537 stop,
538 handle: Some(handle),
539 })
540}
541
542fn input_stream<T>(
543 device: &cpal::Device,
544 config: cpal::StreamConfig,
545 channels: usize,
546 first: usize,
547 buffer: Arc<FrameBuffer>,
548) -> io::Result<cpal::Stream>
549where
550 T: SizedSample,
551 f32: FromSample<T>,
552{
553 let device_channels = usize::from(config.channels).max(1);
554 let mut frames = Vec::new();
555 device
556 .build_input_stream(
557 config,
558 move |data: &[T], _: &cpal::InputCallbackInfo| {
559 frames.clear();
560 for frame in data.chunks_exact(device_channels) {
561 for channel in 0..channels {
562 frames.push(
563 frame
564 .get(first + channel)
565 .map_or(0.0, |sample| sample.to_sample::<f32>()),
566 );
567 }
568 }
569 buffer.device_push(&frames);
570 },
571 |_| {},
572 None,
573 )
574 .map_err(device_error)
575}
576
577fn output_stream<T>(
578 device: &cpal::Device,
579 config: cpal::StreamConfig,
580 channels: usize,
581 first: usize,
582 buffer: Arc<FrameBuffer>,
583) -> io::Result<cpal::Stream>
584where
585 T: SizedSample + FromSample<f32>,
586{
587 let device_channels = usize::from(config.channels).max(1);
588 let rate = i64::from(config.sample_rate.max(1));
589 let mut frames = Vec::new();
590 device
591 .build_output_stream(
592 config,
593 move |data: &mut [T], info: &cpal::OutputCallbackInfo| {
594 let count = data.len() / device_channels;
595 frames.resize(count * channels, 0.0);
596 let stamp = info.timestamp();
599 let latency = stamp.playback.duration_since(stamp.callback);
600 let plays_at = avb_net::clock::monotonic_now() + latency;
601 let after = plays_at.as_nanos() as i64 + count as i64 * 1_000_000_000 / rate;
602 buffer.device_pull(&mut frames, Some(after));
603 for (frame, samples) in data
604 .chunks_exact_mut(device_channels)
605 .zip(frames.chunks_exact(channels.max(1)))
606 {
607 for (channel, slot) in frame.iter_mut().enumerate() {
608 let sample = channel
609 .checked_sub(first)
610 .and_then(|stream| samples.get(stream))
611 .copied()
612 .unwrap_or(0.0);
613 *slot = T::from_sample(sample);
614 }
615 }
616 },
617 |_| {},
618 None,
619 )
620 .map_err(device_error)
621}
622
623pub struct Input {
625 kind: InputKind,
626 channels: usize,
627 spread: Vec<f32>,
629}
630
631enum InputKind {
632 Silence,
633 Tone {
634 phase: f32,
635 step: f32,
636 level: f32,
637 },
638 Device {
639 buffer: Arc<FrameBuffer>,
640 drift: Drift,
641 taken: Vec<f32>,
643 made: Vec<f32>,
644 _thread: Option<DeviceThread>,
645 },
646}
647
648impl Input {
649 pub fn open(source: &Source, channels: u16, rate: u32) -> io::Result<Self> {
651 let kind = match source {
652 Source::Silence => InputKind::Silence,
653 Source::Tone { hertz, level } => InputKind::Tone {
654 phase: 0.0,
655 step: TAU * hertz / rate as f32,
656 level: level.clamp(0.0, 1.0),
657 },
658 Source::Device {
659 name,
660 first_channel,
661 } => {
662 let device = find_device(name.as_deref(), true)?;
663 let device_rate = device_rate(&device, true, rate)?;
664 let margin = device_rate as usize / 100;
666 let buffer = Arc::new(FrameBuffer::new(channels, margin));
667 let filling = buffer.clone();
668 let first = usize::from(*first_channel);
669 let wanted = usize::from(channels);
670 let thread = device_thread("audio input".into(), move || {
671 let supported = device.default_input_config().map_err(device_error)?;
672 let mut config = supported.config();
673 config.sample_rate = device_rate;
674 match supported.sample_format() {
675 cpal::SampleFormat::F32 => {
676 input_stream::<f32>(&device, config, wanted, first, filling)
677 }
678 cpal::SampleFormat::I16 => {
679 input_stream::<i16>(&device, config, wanted, first, filling)
680 }
681 cpal::SampleFormat::I32 => {
682 input_stream::<i32>(&device, config, wanted, first, filling)
683 }
684 other => Err(io::Error::new(
685 io::ErrorKind::Unsupported,
686 format!("samples in {other}"),
687 )),
688 }
689 })?;
690 InputKind::Device {
691 buffer,
692 drift: Drift::new(
693 channels,
694 DeviceSide::Pushes,
695 f64::from(device_rate) / f64::from(rate),
696 ),
697 taken: Vec::new(),
698 made: Vec::new(),
699 _thread: Some(thread),
700 }
701 }
702 Source::Shared(shared) => {
703 if shared.channels != channels {
704 return Err(io::Error::new(
705 io::ErrorKind::InvalidInput,
706 "a shared buffer of other channels than the stream's",
707 ));
708 }
709 shared.buffer.drop_oldest(shared.buffer.level());
712 InputKind::Device {
713 buffer: shared.buffer.clone(),
714 drift: Drift::new(
715 channels,
716 DeviceSide::Pushes,
717 f64::from(shared.rate) / f64::from(rate),
718 ),
719 taken: Vec::new(),
720 made: Vec::new(),
721 _thread: None,
722 }
723 }
724 };
725 Ok(Input {
726 kind,
727 channels: usize::from(channels),
728 spread: Vec::new(),
729 })
730 }
731
732 pub fn drift_ppm(&self) -> i32 {
735 match &self.kind {
736 InputKind::Device { drift, .. } => drift.device_ppm(),
737 _ => 0,
738 }
739 }
740
741 pub fn counts(&self) -> (u64, u64) {
744 match &self.kind {
745 InputKind::Device { buffer, .. } => (
746 buffer.adjustments.load(Ordering::Relaxed),
747 buffer.underruns.load(Ordering::Relaxed),
748 ),
749 _ => (0, 0),
750 }
751 }
752
753 pub fn read(&mut self, out: &mut [f32]) {
755 match &mut self.kind {
756 InputKind::Silence => out.fill(0.0),
757 InputKind::Tone { phase, step, level } => {
758 for frame in out.chunks_exact_mut(self.channels.max(1)) {
759 frame.fill(phase.sin() * *level);
760 *phase = (*phase + *step) % TAU;
761 }
762 }
763 InputKind::Device {
764 buffer,
765 drift,
766 taken,
767 made,
768 ..
769 } => {
770 let frames = out.len() / self.channels.max(1);
771 drift.steer(buffer);
772 taken.resize(drift.wanted(frames) * self.channels, 0.0);
773 buffer.pull(taken);
774 drift.push(taken);
775 made.clear();
776 drift.make(made, frames);
777 out.fill(0.0);
778 out[..made.len()].copy_from_slice(made);
779 }
780 }
781 }
782
783 pub fn read_as(&mut self, out: &mut [f32], channels: usize) {
787 let channels = channels.max(1);
788 if channels == self.channels.max(1) {
789 self.read(out);
790 return;
791 }
792 let mut spread = std::mem::take(&mut self.spread);
793 spread.resize(out.len() / channels * self.channels.max(1), 0.0);
794 self.read(&mut spread);
795 respread(&spread, self.channels, out, channels);
796 self.spread = spread;
797 }
798}
799
800fn respread(samples: &[f32], channels: usize, out: &mut [f32], out_channels: usize) {
804 let (channels, out_channels) = (channels.max(1), out_channels.max(1));
805 let kept = channels.min(out_channels);
806 for (to, from) in out
807 .chunks_exact_mut(out_channels)
808 .zip(samples.chunks_exact(channels))
809 {
810 to[..kept].copy_from_slice(&from[..kept]);
811 to[kept..].fill(0.0);
812 }
813}
814
815#[derive(Debug, Clone, Copy, PartialEq, Eq)]
817pub struct Presented {
818 pub first: i64,
820 pub offset: i64,
822}
823
824const CHOOSING: i64 = 2_000_000_000;
826const DELAY_STEP: i64 = 1_000_000;
829const MOST_DELAY: i64 = 500_000_000;
830const MOST_AHEAD: i64 = 500_000_000;
833
834struct Playing {
836 drift: Drift,
837 made: Vec<f32>,
838 next_in: Option<i64>,
841 offset: Option<i64>,
842 anchor: Option<(u64, i64)>,
844 delay: Option<i64>,
847 error: i64,
848 choosing: Option<(i64, f64, u32)>,
851 underruns: u64,
853}
854
855pub struct Output {
857 buffer: Option<Arc<FrameBuffer>>,
858 _thread: Option<DeviceThread>,
859 playing: Mutex<Playing>,
860 rate: u32,
862 peak: AtomicU32,
864}
865
866impl Output {
867 pub fn open(sink: &Sink, channels: u16, rate: u32) -> io::Result<Self> {
869 match sink {
870 Sink::Discard => Ok(Output::new(None, None, channels, rate, rate)),
871 Sink::Shared(shared) if shared.channels != channels => Err(io::Error::new(
872 io::ErrorKind::InvalidInput,
873 "a shared buffer of other channels than the stream's",
874 )),
875 Sink::Shared(shared) => Ok(Output::new(
876 Some(shared.buffer.clone()),
877 None,
878 channels,
879 rate,
880 shared.rate,
881 )),
882 Sink::Device {
883 name,
884 first_channel,
885 } => {
886 let device = find_device(name.as_deref(), false)?;
887 let device_rate = device_rate(&device, false, rate)?;
888 let margin = device_rate as usize / 100;
889 let buffer = Arc::new(FrameBuffer::new(channels, margin));
890 let draining = buffer.clone();
891 let first = usize::from(*first_channel);
892 let wanted = usize::from(channels);
893 let thread = device_thread("audio output".into(), move || {
894 let supported = device.default_output_config().map_err(device_error)?;
895 let mut config = supported.config();
896 config.sample_rate = device_rate;
897 match supported.sample_format() {
898 cpal::SampleFormat::F32 => {
899 output_stream::<f32>(&device, config, wanted, first, draining)
900 }
901 cpal::SampleFormat::I16 => {
902 output_stream::<i16>(&device, config, wanted, first, draining)
903 }
904 cpal::SampleFormat::I32 => {
905 output_stream::<i32>(&device, config, wanted, first, draining)
906 }
907 other => Err(io::Error::new(
908 io::ErrorKind::Unsupported,
909 format!("samples in {other}"),
910 )),
911 }
912 })?;
913 Ok(Output::new(
914 Some(buffer),
915 Some(thread),
916 channels,
917 rate,
918 device_rate,
919 ))
920 }
921 }
922 }
923
924 fn new(
925 buffer: Option<Arc<FrameBuffer>>,
926 thread: Option<DeviceThread>,
927 channels: u16,
928 rate: u32,
929 device_rate: u32,
930 ) -> Self {
931 let nominal = f64::from(rate) / f64::from(device_rate.max(1));
932 Output {
933 buffer,
934 _thread: thread,
935 playing: Mutex::new(Playing {
936 drift: Drift::new(channels, DeviceSide::Pulls, nominal),
937 made: Vec::new(),
938 next_in: None,
939 offset: None,
940 anchor: None,
941 delay: None,
942 error: 0,
943 choosing: None,
944 underruns: 0,
945 }),
946 rate: rate.max(1),
947 peak: AtomicU32::new(0),
948 }
949 }
950
951 fn lock(&self) -> std::sync::MutexGuard<'_, Playing> {
952 self.playing.lock().unwrap_or_else(PoisonError::into_inner)
953 }
954
955 pub fn write(&self, samples: &[f32], presented: Option<Presented>) {
958 let loudest = samples
959 .iter()
960 .fold(0.0f32, |most, sample| most.max(sample.abs()));
961 self.peak.fetch_max(loudest.to_bits(), Ordering::Relaxed);
962 let Some(buffer) = &self.buffer else {
963 return;
964 };
965 let mut playing = self.lock();
966 let playing = &mut *playing;
967 if let Some(presented) = presented {
968 playing.next_in = Some(presented.first);
969 playing.offset = Some(presented.offset);
970 }
971 if let Some(sample) = playing.drift.new_sample(buffer) {
972 self.steer(playing, buffer, &sample);
973 }
974 playing.drift.push(samples);
975 playing.made.clear();
976 playing.drift.make(&mut playing.made, usize::MAX);
977 buffer.push(&playing.made);
978 let frames = samples.len() / playing.drift.channels;
979 let frame = 1e9 / f64::from(self.rate);
980 if let Some(next) = &mut playing.next_in {
981 *next += (frames as f64 * frame).round() as i64;
982 let made = *next - (playing.drift.pending() * frame).round() as i64;
985 playing.anchor = Some((buffer.pushed(), made));
986 }
987 }
988
989 fn steer(&self, playing: &mut Playing, buffer: &FrameBuffer, sample: &DeviceSample) {
992 let excess = sample.level as f64 - playing.drift.kept(buffer, sample) as f64;
993 let (Some(plays_at), Some((anchor, presented)), Some(offset)) =
994 (sample.plays_at, playing.anchor, playing.offset)
995 else {
996 playing.drift.follow(excess, sample.chunk);
997 return;
998 };
999 let frame = playing.drift.ratio() * 1e9 / f64::from(self.rate);
1001 let oldest = sample.pushed - sample.level as u64;
1002 let presents = presented as f64 - (anchor as f64 - oldest as f64) * frame;
1003 let late = (plays_at + offset) as f64 - presents;
1004 if !(-MOST_AHEAD as f64..=2.0 * MOST_DELAY as f64).contains(&late) {
1005 playing.drift.follow(excess, sample.chunk);
1006 return;
1007 }
1008 let Some(delay) = playing.delay else {
1009 playing.drift.follow(excess, sample.chunk);
1012 let (since, sum, seen) = playing.choosing.get_or_insert((plays_at, 0.0, 0));
1013 *sum += late - excess * frame;
1014 *seen += 1;
1015 if plays_at - *since >= CHOOSING {
1016 let earliest = (*sum / f64::from(*seen)).max(0.0) as i64;
1017 let steps = (earliest + DELAY_STEP - 1) / DELAY_STEP;
1018 let delay = (steps * DELAY_STEP).min(MOST_DELAY);
1019 self.set_delay(playing, buffer, delay, (late - delay as f64) / frame);
1020 }
1021 return;
1022 };
1023 let underruns = buffer.underruns.load(Ordering::Relaxed);
1024 if underruns > playing.underruns && delay < MOST_DELAY {
1025 let later = delay + DELAY_STEP;
1026 self.set_delay(playing, buffer, later, (late - later as f64) / frame);
1027 return;
1028 }
1029 playing.error = (late - delay as f64) as i64;
1030 playing
1031 .drift
1032 .follow((late - delay as f64) / frame, sample.chunk);
1033 }
1034
1035 fn set_delay(&self, playing: &mut Playing, buffer: &FrameBuffer, delay: i64, excess: f64) {
1038 playing.delay = Some(delay);
1039 playing.error = 0;
1040 playing.underruns = buffer.underruns.load(Ordering::Relaxed);
1041 let excess = excess.round() as i64;
1042 buffer.hold_more(excess.unsigned_abs() as usize);
1043 if excess > 0 {
1044 buffer.drop_oldest(excess as usize);
1045 } else if excess < 0 {
1046 let frames = excess.unsigned_abs() as usize;
1049 buffer.push(&vec![0.0; frames * playing.drift.channels]);
1050 if let Some((anchor, _)) = &mut playing.anchor {
1051 *anchor += frames as u64;
1052 }
1053 }
1054 }
1055
1056 pub fn playout(&self) -> Option<(i64, i64)> {
1060 let playing = self.lock();
1061 playing.delay.map(|delay| (delay, playing.error))
1062 }
1063
1064 pub fn drift_ppm(&self) -> i32 {
1067 if self.buffer.is_none() {
1068 return 0;
1069 }
1070 self.lock().drift.device_ppm()
1071 }
1072
1073 pub fn underruns(&self) -> u64 {
1075 self.buffer
1076 .as_ref()
1077 .map_or(0, |buffer| buffer.underruns.load(Ordering::Relaxed))
1078 }
1079
1080 pub fn take_peak(&self) -> f32 {
1082 f32::from_bits(self.peak.swap(0, Ordering::Relaxed))
1083 }
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088 use super::*;
1089
1090 #[test]
1091 fn the_buffer_notes_its_fill_after_each_device_chunk() {
1092 let buffer = FrameBuffer::new(2, 10);
1093 assert_eq!(buffer.device_sample(), None);
1094 buffer.device_push(&[1.0; 8]);
1095 buffer.push(&[2.0; 4]);
1096 assert_eq!(
1097 buffer.device_sample(),
1098 Some(DeviceSample {
1099 chunks: 1,
1100 level: 4,
1101 chunk: 4,
1102 pushed: 4,
1103 plays_at: None,
1104 })
1105 );
1106 let mut out = [9.0; 6];
1107 buffer.device_pull(&mut out, None);
1108 assert_eq!(out, [1.0; 6]);
1109 assert_eq!(buffer.device_sample().map(|sample| sample.chunks), Some(2));
1110 buffer.push(&[3.0; 200]);
1112 assert_eq!(buffer.level(), 4 * (10 + 3));
1113 assert!(buffer.adjustments.load(Ordering::Relaxed) > 0);
1114 let mut out = [9.0; 120];
1116 buffer.pull(&mut out);
1117 assert_eq!(out[104..], [0.0; 16]);
1118 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 1);
1119 }
1120
1121 fn sine(hertz: f64, rate: f64, start: u64, frames: usize) -> Vec<f32> {
1123 (0..frames as u64)
1124 .map(|index| (TAU as f64 * hertz * (start + index) as f64 / rate).sin() as f32 * 0.5)
1125 .collect()
1126 }
1127
1128 fn chunk_time(index: u64, chunk: usize, rate: f64) -> f64 {
1131 let nominal = index as f64 * chunk as f64 / rate;
1132 let wobble = ((index * 7919) % 41) as f64 / 40.0 - 0.5;
1133 nominal + 0.04 * wobble * chunk as f64 / rate
1134 }
1135
1136 #[test]
1141 fn a_fast_device_is_followed_without_a_gap() {
1142 let rate = 48_000.0;
1143 let device_rate = rate * (1.0 + 120e-6);
1144 let buffer = FrameBuffer::new(1, 480);
1145 let mut drift = Drift::new(1, DeviceSide::Pushes, 1.0);
1146 let mut chunks = 0;
1147 let mut out = Vec::new();
1148 let mut steps = Vec::new();
1149 let mut ratios = Vec::new();
1150 for packet in 0..8000 * 120u64 {
1151 let now = packet as f64 / 8000.0;
1152 while chunk_time(chunks, 1024, device_rate) <= now {
1153 buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1154 chunks += 1;
1155 }
1156 drift.steer(&buffer);
1157 let mut taken = vec![0.0; drift.wanted(6)];
1158 buffer.pull(&mut taken);
1159 drift.push(&taken);
1160 out.clear();
1161 drift.make(&mut out, 6);
1162 assert_eq!(out.len(), 6);
1163 if packet == 8000 {
1164 buffer.underruns.store(0, Ordering::Relaxed);
1165 }
1166 if packet > 8000 * 40 {
1167 steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1168 ratios.push(drift.ratio());
1169 }
1170 }
1171 for ratio in &ratios {
1172 assert!((ratio - (1.0 + 120e-6)).abs() < 30e-6, "{ratio}");
1173 }
1174 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1175 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1176 let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1179 assert!(most < 0.07, "{most}");
1180 }
1181
1182 #[test]
1186 fn a_slow_device_is_fed_without_a_gap() {
1187 let rate = 48_000.0;
1188 let device_rate = rate * (1.0 - 80e-6);
1189 let buffer = FrameBuffer::new(1, 480);
1190 let mut drift = Drift::new(1, DeviceSide::Pulls, 1.0);
1191 let mut chunks = 0;
1192 let mut made = Vec::new();
1193 let mut played = vec![0.0; 1024];
1194 let mut ratios = Vec::new();
1195 for packet in 0..8000 * 120u64 {
1196 drift.steer(&buffer);
1197 drift.push(&sine(1000.0, rate, packet * 6, 6));
1198 made.clear();
1199 drift.make(&mut made, usize::MAX);
1200 buffer.push(&made);
1201 let now = packet as f64 / 8000.0;
1202 while chunk_time(chunks + 1, 1024, device_rate) <= now {
1203 buffer.device_pull(&mut played, None);
1204 chunks += 1;
1205 }
1206 if packet == 8000 {
1207 buffer.underruns.store(0, Ordering::Relaxed);
1208 }
1209 if packet > 8000 * 40 {
1210 ratios.push(drift.ratio());
1211 }
1212 }
1213 for ratio in &ratios {
1214 assert!((ratio - 1.0 / (1.0 - 80e-6)).abs() < 30e-6, "{ratio}");
1215 }
1216 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1217 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1218 }
1219
1220 #[test]
1225 fn a_device_at_half_the_rate_is_followed() {
1226 let device_rate = 48_000.0 * (1.0 + 50e-6);
1227 let buffer = FrameBuffer::new(1, 480);
1228 let mut drift = Drift::new(1, DeviceSide::Pushes, 0.5);
1229 let mut chunks = 0;
1230 let mut out = Vec::new();
1231 let mut steps = Vec::new();
1232 let mut ppms = Vec::new();
1233 for packet in 0..8000 * 120u64 {
1234 let now = packet as f64 / 8000.0;
1235 while chunk_time(chunks, 1024, device_rate) <= now {
1236 buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1237 chunks += 1;
1238 }
1239 drift.steer(&buffer);
1240 let mut taken = vec![0.0; drift.wanted(12)];
1241 buffer.pull(&mut taken);
1242 drift.push(&taken);
1243 out.clear();
1244 drift.make(&mut out, 12);
1245 assert_eq!(out.len(), 12);
1246 if packet == 8000 {
1247 buffer.underruns.store(0, Ordering::Relaxed);
1248 }
1249 if packet > 8000 * 40 {
1250 steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1251 ppms.push(drift.device_ppm());
1252 }
1253 }
1254 for ppm in &ppms {
1255 assert!((ppm - 50).abs() < 30, "{ppm}");
1256 }
1257 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1258 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1259 let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1261 assert!(most < 0.04, "{most}");
1262 }
1263
1264 fn play_out(chunk: usize, latency: f64, ahead: f64) -> (i64, f64, u64) {
1270 let rate = 48_000.0;
1271 let device_rate = rate * (1.0 - 50e-6);
1272 let buffer = Arc::new(FrameBuffer::new(1, 480));
1273 let output = Output::new(Some(buffer.clone()), None, 1, 48_000, 48_000);
1274 let tone = |seconds: f64| (TAU as f64 * 100.0 * seconds).sin() as f32 * 0.5;
1275 let mut played = vec![0.0; chunk];
1276 let mut chunks = 0;
1277 let mut most = 0.0f64;
1278 let mut underruns = 0;
1279 for packet in 0..8000 * 60u64 {
1280 let arrives = packet as f64 / 8000.0;
1281 while chunk_time(chunks, chunk, device_rate) <= arrives {
1282 let plays = chunks as f64 * chunk as f64 / device_rate + latency;
1283 let after = plays + chunk as f64 / device_rate;
1284 buffer.device_pull(&mut played, Some((after * 1e9) as i64));
1285 if arrives > 40.0 {
1286 let (delay, _) = output.playout().unwrap();
1287 for (index, sample) in played.iter().enumerate() {
1288 let at = plays + index as f64 / device_rate - delay as f64 * 1e-9;
1289 let off = f64::from(sample - tone(at)) / (TAU as f64 * 100.0 * 0.5);
1291 most = most.max(off.abs());
1292 }
1293 }
1294 chunks += 1;
1295 }
1296 if packet == 8000 * 10 {
1297 underruns = buffer.underruns.load(Ordering::Relaxed);
1298 }
1299 let first = arrives + ahead;
1300 let samples: Vec<f32> = (0..6)
1301 .map(|index| tone(first + index as f64 / rate))
1302 .collect();
1303 let presented = Presented {
1304 first: (first * 1e9) as i64,
1305 offset: 0,
1306 };
1307 output.write(&samples, Some(presented));
1308 }
1309 let (delay, _) = output.playout().unwrap();
1310 let more = buffer.underruns.load(Ordering::Relaxed) - underruns;
1311 (delay, most, more)
1312 }
1313
1314 #[test]
1319 fn a_slow_device_plays_a_fixed_delay_after_presentation() {
1320 let (delay, most, underruns) = play_out(1024, 0.025, 0.0017);
1321 assert_eq!(delay, 55_000_000);
1322 assert!(most < 0.000_2, "{most}");
1323 assert_eq!(underruns, 0);
1324 }
1325
1326 #[test]
1329 fn early_frames_play_at_presentation_time() {
1330 let (delay, most, underruns) = play_out(256, 0.005, 0.1);
1331 assert_eq!(delay, 0);
1332 assert!(most < 0.000_2, "{most}");
1333 assert_eq!(underruns, 0);
1334 }
1335
1336 #[test]
1337 fn a_tone_fills_every_channel() {
1338 let mut input = Input::open(
1339 &Source::Tone {
1340 hertz: 1000.0,
1341 level: 0.5,
1342 },
1343 2,
1344 48_000,
1345 )
1346 .unwrap();
1347 let mut out = [0.0; 96];
1348 input.read(&mut out);
1349 assert!(out.iter().all(|sample| sample.abs() <= 0.5));
1350 assert!(
1351 out.as_chunks::<2>()
1352 .0
1353 .iter()
1354 .all(|frame| frame[0] == frame[1])
1355 );
1356 assert!(out.iter().any(|sample| sample.abs() > 0.4));
1357 }
1358
1359 #[test]
1363 fn a_stream_of_other_channels_takes_the_first() {
1364 let stereo = [0.1, 0.2, 0.3, 0.4];
1365 let mut eight = [9.0; 16];
1366 respread(&stereo, 2, &mut eight, 8);
1367 assert_eq!(
1368 eight,
1369 [
1370 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
1371 ]
1372 );
1373 let mut two = [9.0; 4];
1374 respread(&eight, 8, &mut two, 2);
1375 assert_eq!(two, stereo);
1376 }
1377}