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 pub fn skip(&mut self, frames: usize) {
804 match &mut self.kind {
805 InputKind::Silence => {}
806 InputKind::Tone { phase, step, .. } => {
807 let turned = f64::from(*phase) + f64::from(*step) * frames as f64;
808 *phase = (turned % std::f64::consts::TAU) as f32;
809 }
810 InputKind::Device { buffer, drift, .. } => {
812 buffer.drop_oldest((frames as f64 * drift.ratio()).round() as usize);
813 }
814 }
815 }
816}
817
818fn respread(samples: &[f32], channels: usize, out: &mut [f32], out_channels: usize) {
822 let (channels, out_channels) = (channels.max(1), out_channels.max(1));
823 let kept = channels.min(out_channels);
824 for (to, from) in out
825 .chunks_exact_mut(out_channels)
826 .zip(samples.chunks_exact(channels))
827 {
828 to[..kept].copy_from_slice(&from[..kept]);
829 to[kept..].fill(0.0);
830 }
831}
832
833#[derive(Debug, Clone, Copy, PartialEq, Eq)]
835pub struct Presented {
836 pub first: i64,
838 pub offset: i64,
840}
841
842const CHOOSING: i64 = 2_000_000_000;
844const DELAY_STEP: i64 = 1_000_000;
847const MOST_DELAY: i64 = 500_000_000;
848const MOST_AHEAD: i64 = 500_000_000;
851
852struct Playing {
854 drift: Drift,
855 made: Vec<f32>,
856 next_in: Option<i64>,
859 offset: Option<i64>,
860 anchor: Option<(u64, i64)>,
862 delay: Option<i64>,
865 error: i64,
866 choosing: Option<(i64, f64, u32)>,
869 underruns: u64,
871}
872
873pub struct Output {
875 buffer: Option<Arc<FrameBuffer>>,
876 _thread: Option<DeviceThread>,
877 playing: Mutex<Playing>,
878 rate: u32,
880 peak: AtomicU32,
882}
883
884impl Output {
885 pub fn open(sink: &Sink, channels: u16, rate: u32) -> io::Result<Self> {
887 match sink {
888 Sink::Discard => Ok(Output::new(None, None, channels, rate, rate)),
889 Sink::Shared(shared) if shared.channels != channels => Err(io::Error::new(
890 io::ErrorKind::InvalidInput,
891 "a shared buffer of other channels than the stream's",
892 )),
893 Sink::Shared(shared) => Ok(Output::new(
894 Some(shared.buffer.clone()),
895 None,
896 channels,
897 rate,
898 shared.rate,
899 )),
900 Sink::Device {
901 name,
902 first_channel,
903 } => {
904 let device = find_device(name.as_deref(), false)?;
905 let device_rate = device_rate(&device, false, rate)?;
906 let margin = device_rate as usize / 100;
907 let buffer = Arc::new(FrameBuffer::new(channels, margin));
908 let draining = buffer.clone();
909 let first = usize::from(*first_channel);
910 let wanted = usize::from(channels);
911 let thread = device_thread("audio output".into(), move || {
912 let supported = device.default_output_config().map_err(device_error)?;
913 let mut config = supported.config();
914 config.sample_rate = device_rate;
915 match supported.sample_format() {
916 cpal::SampleFormat::F32 => {
917 output_stream::<f32>(&device, config, wanted, first, draining)
918 }
919 cpal::SampleFormat::I16 => {
920 output_stream::<i16>(&device, config, wanted, first, draining)
921 }
922 cpal::SampleFormat::I32 => {
923 output_stream::<i32>(&device, config, wanted, first, draining)
924 }
925 other => Err(io::Error::new(
926 io::ErrorKind::Unsupported,
927 format!("samples in {other}"),
928 )),
929 }
930 })?;
931 Ok(Output::new(
932 Some(buffer),
933 Some(thread),
934 channels,
935 rate,
936 device_rate,
937 ))
938 }
939 }
940 }
941
942 fn new(
943 buffer: Option<Arc<FrameBuffer>>,
944 thread: Option<DeviceThread>,
945 channels: u16,
946 rate: u32,
947 device_rate: u32,
948 ) -> Self {
949 let nominal = f64::from(rate) / f64::from(device_rate.max(1));
950 Output {
951 buffer,
952 _thread: thread,
953 playing: Mutex::new(Playing {
954 drift: Drift::new(channels, DeviceSide::Pulls, nominal),
955 made: Vec::new(),
956 next_in: None,
957 offset: None,
958 anchor: None,
959 delay: None,
960 error: 0,
961 choosing: None,
962 underruns: 0,
963 }),
964 rate: rate.max(1),
965 peak: AtomicU32::new(0),
966 }
967 }
968
969 fn lock(&self) -> std::sync::MutexGuard<'_, Playing> {
970 self.playing.lock().unwrap_or_else(PoisonError::into_inner)
971 }
972
973 pub fn write(&self, samples: &[f32], presented: Option<Presented>) {
976 let loudest = samples
977 .iter()
978 .fold(0.0f32, |most, sample| most.max(sample.abs()));
979 self.peak.fetch_max(loudest.to_bits(), Ordering::Relaxed);
980 let Some(buffer) = &self.buffer else {
981 return;
982 };
983 let mut playing = self.lock();
984 let playing = &mut *playing;
985 if let Some(presented) = presented {
986 playing.next_in = Some(presented.first);
987 playing.offset = Some(presented.offset);
988 }
989 if let Some(sample) = playing.drift.new_sample(buffer) {
990 self.steer(playing, buffer, &sample);
991 }
992 playing.drift.push(samples);
993 playing.made.clear();
994 playing.drift.make(&mut playing.made, usize::MAX);
995 buffer.push(&playing.made);
996 let frames = samples.len() / playing.drift.channels;
997 let frame = 1e9 / f64::from(self.rate);
998 if let Some(next) = &mut playing.next_in {
999 *next += (frames as f64 * frame).round() as i64;
1000 let made = *next - (playing.drift.pending() * frame).round() as i64;
1003 playing.anchor = Some((buffer.pushed(), made));
1004 }
1005 }
1006
1007 fn steer(&self, playing: &mut Playing, buffer: &FrameBuffer, sample: &DeviceSample) {
1010 let excess = sample.level as f64 - playing.drift.kept(buffer, sample) as f64;
1011 let (Some(plays_at), Some((anchor, presented)), Some(offset)) =
1012 (sample.plays_at, playing.anchor, playing.offset)
1013 else {
1014 playing.drift.follow(excess, sample.chunk);
1015 return;
1016 };
1017 let frame = playing.drift.ratio() * 1e9 / f64::from(self.rate);
1019 let oldest = sample.pushed - sample.level as u64;
1020 let presents = presented as f64 - (anchor as f64 - oldest as f64) * frame;
1021 let late = (plays_at + offset) as f64 - presents;
1022 if !(-MOST_AHEAD as f64..=2.0 * MOST_DELAY as f64).contains(&late) {
1023 playing.drift.follow(excess, sample.chunk);
1024 return;
1025 }
1026 let Some(delay) = playing.delay else {
1027 playing.drift.follow(excess, sample.chunk);
1030 let (since, sum, seen) = playing.choosing.get_or_insert((plays_at, 0.0, 0));
1031 *sum += late - excess * frame;
1032 *seen += 1;
1033 if plays_at - *since >= CHOOSING {
1034 let earliest = (*sum / f64::from(*seen)).max(0.0) as i64;
1035 let steps = (earliest + DELAY_STEP - 1) / DELAY_STEP;
1036 let delay = (steps * DELAY_STEP).min(MOST_DELAY);
1037 self.set_delay(playing, buffer, delay, (late - delay as f64) / frame);
1038 }
1039 return;
1040 };
1041 let underruns = buffer.underruns.load(Ordering::Relaxed);
1042 if underruns > playing.underruns && delay < MOST_DELAY {
1043 let later = delay + DELAY_STEP;
1044 self.set_delay(playing, buffer, later, (late - later as f64) / frame);
1045 return;
1046 }
1047 playing.error = (late - delay as f64) as i64;
1048 playing
1049 .drift
1050 .follow((late - delay as f64) / frame, sample.chunk);
1051 }
1052
1053 fn set_delay(&self, playing: &mut Playing, buffer: &FrameBuffer, delay: i64, excess: f64) {
1056 playing.delay = Some(delay);
1057 playing.error = 0;
1058 playing.underruns = buffer.underruns.load(Ordering::Relaxed);
1059 let excess = excess.round() as i64;
1060 buffer.hold_more(excess.unsigned_abs() as usize);
1061 if excess > 0 {
1062 buffer.drop_oldest(excess as usize);
1063 } else if excess < 0 {
1064 let frames = excess.unsigned_abs() as usize;
1067 buffer.push(&vec![0.0; frames * playing.drift.channels]);
1068 if let Some((anchor, _)) = &mut playing.anchor {
1069 *anchor += frames as u64;
1070 }
1071 }
1072 }
1073
1074 pub fn playout(&self) -> Option<(i64, i64)> {
1078 let playing = self.lock();
1079 playing.delay.map(|delay| (delay, playing.error))
1080 }
1081
1082 pub fn drift_ppm(&self) -> i32 {
1085 if self.buffer.is_none() {
1086 return 0;
1087 }
1088 self.lock().drift.device_ppm()
1089 }
1090
1091 pub fn underruns(&self) -> u64 {
1093 self.buffer
1094 .as_ref()
1095 .map_or(0, |buffer| buffer.underruns.load(Ordering::Relaxed))
1096 }
1097
1098 pub fn take_peak(&self) -> f32 {
1100 f32::from_bits(self.peak.swap(0, Ordering::Relaxed))
1101 }
1102}
1103
1104#[cfg(test)]
1105mod tests {
1106 use super::*;
1107
1108 #[test]
1109 fn the_buffer_notes_its_fill_after_each_device_chunk() {
1110 let buffer = FrameBuffer::new(2, 10);
1111 assert_eq!(buffer.device_sample(), None);
1112 buffer.device_push(&[1.0; 8]);
1113 buffer.push(&[2.0; 4]);
1114 assert_eq!(
1115 buffer.device_sample(),
1116 Some(DeviceSample {
1117 chunks: 1,
1118 level: 4,
1119 chunk: 4,
1120 pushed: 4,
1121 plays_at: None,
1122 })
1123 );
1124 let mut out = [9.0; 6];
1125 buffer.device_pull(&mut out, None);
1126 assert_eq!(out, [1.0; 6]);
1127 assert_eq!(buffer.device_sample().map(|sample| sample.chunks), Some(2));
1128 buffer.push(&[3.0; 200]);
1130 assert_eq!(buffer.level(), 4 * (10 + 3));
1131 assert!(buffer.adjustments.load(Ordering::Relaxed) > 0);
1132 let mut out = [9.0; 120];
1134 buffer.pull(&mut out);
1135 assert_eq!(out[104..], [0.0; 16]);
1136 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 1);
1137 }
1138
1139 fn sine(hertz: f64, rate: f64, start: u64, frames: usize) -> Vec<f32> {
1141 (0..frames as u64)
1142 .map(|index| (TAU as f64 * hertz * (start + index) as f64 / rate).sin() as f32 * 0.5)
1143 .collect()
1144 }
1145
1146 fn chunk_time(index: u64, chunk: usize, rate: f64) -> f64 {
1149 let nominal = index as f64 * chunk as f64 / rate;
1150 let wobble = ((index * 7919) % 41) as f64 / 40.0 - 0.5;
1151 nominal + 0.04 * wobble * chunk as f64 / rate
1152 }
1153
1154 #[test]
1159 fn a_fast_device_is_followed_without_a_gap() {
1160 let rate = 48_000.0;
1161 let device_rate = rate * (1.0 + 120e-6);
1162 let buffer = FrameBuffer::new(1, 480);
1163 let mut drift = Drift::new(1, DeviceSide::Pushes, 1.0);
1164 let mut chunks = 0;
1165 let mut out = Vec::new();
1166 let mut steps = Vec::new();
1167 let mut ratios = Vec::new();
1168 for packet in 0..8000 * 120u64 {
1169 let now = packet as f64 / 8000.0;
1170 while chunk_time(chunks, 1024, device_rate) <= now {
1171 buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1172 chunks += 1;
1173 }
1174 drift.steer(&buffer);
1175 let mut taken = vec![0.0; drift.wanted(6)];
1176 buffer.pull(&mut taken);
1177 drift.push(&taken);
1178 out.clear();
1179 drift.make(&mut out, 6);
1180 assert_eq!(out.len(), 6);
1181 if packet == 8000 {
1182 buffer.underruns.store(0, Ordering::Relaxed);
1183 }
1184 if packet > 8000 * 40 {
1185 steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1186 ratios.push(drift.ratio());
1187 }
1188 }
1189 for ratio in &ratios {
1190 assert!((ratio - (1.0 + 120e-6)).abs() < 30e-6, "{ratio}");
1191 }
1192 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1193 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1194 let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1197 assert!(most < 0.07, "{most}");
1198 }
1199
1200 #[test]
1204 fn a_slow_device_is_fed_without_a_gap() {
1205 let rate = 48_000.0;
1206 let device_rate = rate * (1.0 - 80e-6);
1207 let buffer = FrameBuffer::new(1, 480);
1208 let mut drift = Drift::new(1, DeviceSide::Pulls, 1.0);
1209 let mut chunks = 0;
1210 let mut made = Vec::new();
1211 let mut played = vec![0.0; 1024];
1212 let mut ratios = Vec::new();
1213 for packet in 0..8000 * 120u64 {
1214 drift.steer(&buffer);
1215 drift.push(&sine(1000.0, rate, packet * 6, 6));
1216 made.clear();
1217 drift.make(&mut made, usize::MAX);
1218 buffer.push(&made);
1219 let now = packet as f64 / 8000.0;
1220 while chunk_time(chunks + 1, 1024, device_rate) <= now {
1221 buffer.device_pull(&mut played, None);
1222 chunks += 1;
1223 }
1224 if packet == 8000 {
1225 buffer.underruns.store(0, Ordering::Relaxed);
1226 }
1227 if packet > 8000 * 40 {
1228 ratios.push(drift.ratio());
1229 }
1230 }
1231 for ratio in &ratios {
1232 assert!((ratio - 1.0 / (1.0 - 80e-6)).abs() < 30e-6, "{ratio}");
1233 }
1234 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1235 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1236 }
1237
1238 #[test]
1243 fn a_device_at_half_the_rate_is_followed() {
1244 let device_rate = 48_000.0 * (1.0 + 50e-6);
1245 let buffer = FrameBuffer::new(1, 480);
1246 let mut drift = Drift::new(1, DeviceSide::Pushes, 0.5);
1247 let mut chunks = 0;
1248 let mut out = Vec::new();
1249 let mut steps = Vec::new();
1250 let mut ppms = Vec::new();
1251 for packet in 0..8000 * 120u64 {
1252 let now = packet as f64 / 8000.0;
1253 while chunk_time(chunks, 1024, device_rate) <= now {
1254 buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1255 chunks += 1;
1256 }
1257 drift.steer(&buffer);
1258 let mut taken = vec![0.0; drift.wanted(12)];
1259 buffer.pull(&mut taken);
1260 drift.push(&taken);
1261 out.clear();
1262 drift.make(&mut out, 12);
1263 assert_eq!(out.len(), 12);
1264 if packet == 8000 {
1265 buffer.underruns.store(0, Ordering::Relaxed);
1266 }
1267 if packet > 8000 * 40 {
1268 steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1269 ppms.push(drift.device_ppm());
1270 }
1271 }
1272 for ppm in &ppms {
1273 assert!((ppm - 50).abs() < 30, "{ppm}");
1274 }
1275 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1276 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1277 let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1279 assert!(most < 0.04, "{most}");
1280 }
1281
1282 #[test]
1286 fn a_stream_at_four_times_the_devices_rate_is_made_whole() {
1287 let mut drift = Drift::new(2, DeviceSide::Pulls, 4.0);
1288 drift.ratio = 4.0 + 300e-6;
1289 let mut out = Vec::new();
1290 let mut made = 0;
1291 let mut last: Option<f32> = None;
1292 let mut most = 0.0f32;
1293 for frame in 0..8000 * 10 {
1294 let first = frame * 24;
1295 let input: Vec<f32> = (first..first + 24)
1296 .flat_map(|at| {
1297 let sample = (TAU as f64 * 1000.0 * at as f64 / 192_000.0).sin() as f32 * 0.5;
1298 [sample, -sample]
1299 })
1300 .collect();
1301 drift.push(&input);
1302 out.clear();
1303 drift.make(&mut out, usize::MAX);
1304 for pair in out.as_chunks::<2>().0 {
1305 if let Some(previous) = last {
1306 most = most.max((pair[0] - previous).abs());
1307 }
1308 last = Some(pair[0]);
1309 made += 1;
1310 }
1311 }
1312 let expected = 8000.0 * 10.0 * 24.0 / drift.ratio;
1314 assert!((made as f64 - expected).abs() < 4.0, "{made}");
1315 assert!(most < 0.07, "{most}");
1317 }
1318
1319 fn play_out(chunk: usize, latency: f64, ahead: f64) -> (i64, f64, u64) {
1325 let rate = 48_000.0;
1326 let device_rate = rate * (1.0 - 50e-6);
1327 let buffer = Arc::new(FrameBuffer::new(1, 480));
1328 let output = Output::new(Some(buffer.clone()), None, 1, 48_000, 48_000);
1329 let tone = |seconds: f64| (TAU as f64 * 100.0 * seconds).sin() as f32 * 0.5;
1330 let mut played = vec![0.0; chunk];
1331 let mut chunks = 0;
1332 let mut most = 0.0f64;
1333 let mut underruns = 0;
1334 for packet in 0..8000 * 60u64 {
1335 let arrives = packet as f64 / 8000.0;
1336 while chunk_time(chunks, chunk, device_rate) <= arrives {
1337 let plays = chunks as f64 * chunk as f64 / device_rate + latency;
1338 let after = plays + chunk as f64 / device_rate;
1339 buffer.device_pull(&mut played, Some((after * 1e9) as i64));
1340 if arrives > 40.0 {
1341 let (delay, _) = output.playout().unwrap();
1342 for (index, sample) in played.iter().enumerate() {
1343 let at = plays + index as f64 / device_rate - delay as f64 * 1e-9;
1344 let off = f64::from(sample - tone(at)) / (TAU as f64 * 100.0 * 0.5);
1346 most = most.max(off.abs());
1347 }
1348 }
1349 chunks += 1;
1350 }
1351 if packet == 8000 * 10 {
1352 underruns = buffer.underruns.load(Ordering::Relaxed);
1353 }
1354 let first = arrives + ahead;
1355 let samples: Vec<f32> = (0..6)
1356 .map(|index| tone(first + index as f64 / rate))
1357 .collect();
1358 let presented = Presented {
1359 first: (first * 1e9) as i64,
1360 offset: 0,
1361 };
1362 output.write(&samples, Some(presented));
1363 }
1364 let (delay, _) = output.playout().unwrap();
1365 let more = buffer.underruns.load(Ordering::Relaxed) - underruns;
1366 (delay, most, more)
1367 }
1368
1369 #[test]
1374 fn a_slow_device_plays_a_fixed_delay_after_presentation() {
1375 let (delay, most, underruns) = play_out(1024, 0.025, 0.0017);
1376 assert_eq!(delay, 55_000_000);
1377 assert!(most < 0.000_2, "{most}");
1378 assert_eq!(underruns, 0);
1379 }
1380
1381 #[test]
1384 fn early_frames_play_at_presentation_time() {
1385 let (delay, most, underruns) = play_out(256, 0.005, 0.1);
1386 assert_eq!(delay, 0);
1387 assert!(most < 0.000_2, "{most}");
1388 assert_eq!(underruns, 0);
1389 }
1390
1391 #[test]
1392 fn a_tone_fills_every_channel() {
1393 let mut input = Input::open(
1394 &Source::Tone {
1395 hertz: 1000.0,
1396 level: 0.5,
1397 },
1398 2,
1399 48_000,
1400 )
1401 .unwrap();
1402 let mut out = [0.0; 96];
1403 input.read(&mut out);
1404 assert!(out.iter().all(|sample| sample.abs() <= 0.5));
1405 assert!(
1406 out.as_chunks::<2>()
1407 .0
1408 .iter()
1409 .all(|frame| frame[0] == frame[1])
1410 );
1411 assert!(out.iter().any(|sample| sample.abs() > 0.4));
1412 }
1413
1414 #[test]
1418 fn a_stream_of_other_channels_takes_the_first() {
1419 let stereo = [0.1, 0.2, 0.3, 0.4];
1420 let mut eight = [9.0; 16];
1421 respread(&stereo, 2, &mut eight, 8);
1422 assert_eq!(
1423 eight,
1424 [
1425 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
1426 ]
1427 );
1428 let mut two = [9.0; 4];
1429 respread(&eight, 8, &mut two, 2);
1430 assert_eq!(two, stereo);
1431 }
1432}