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