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)]
30#[non_exhaustive]
31pub enum Source {
32 Silence,
33 Tone {
35 hertz: f32,
36 level: f32,
37 },
38 Device {
41 name: Option<String>,
42 first_channel: u16,
43 },
44 Shared(SharedBuffer),
47 Blocks(Blocks<dyn BlockSource>),
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct Block {
57 pub presented: i64,
59 pub samples: usize,
61 pub channels: usize,
63 pub media_reset: bool,
66}
67
68pub trait BlockSource: Send + Sync {
73 fn fill(&self, block: &Block, words: &mut [i32]);
76 fn sent(&self, block: &Block, sent: bool);
79 fn left_out(&self, samples: u64);
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
87pub struct Arrived {
88 pub presented: Option<i64>,
91 pub margin: Option<i64>,
94 pub samples: usize,
96 pub channels: usize,
98 pub missed: u8,
100 pub media_reset: bool,
102}
103
104pub trait BlockSink: Send + Sync {
109 fn take(&self, arrived: &Arrived, words: &[i32]);
112}
113
114pub struct Blocks<T: ?Sized>(pub Arc<T>);
117
118impl<T: ?Sized> Clone for Blocks<T> {
119 fn clone(&self) -> Self {
120 Blocks(self.0.clone())
121 }
122}
123
124impl<T: ?Sized> PartialEq for Blocks<T> {
125 fn eq(&self, other: &Self) -> bool {
126 Arc::ptr_eq(&self.0, &other.0)
127 }
128}
129
130impl<T: ?Sized> std::fmt::Debug for Blocks<T> {
131 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132 formatter.write_str("Blocks")
133 }
134}
135
136#[derive(Clone)]
141pub struct SharedBuffer {
142 pub buffer: Arc<FrameBuffer>,
143 pub channels: u16,
144 pub rate: u32,
145}
146
147impl PartialEq for SharedBuffer {
148 fn eq(&self, other: &Self) -> bool {
149 Arc::ptr_eq(&self.buffer, &other.buffer)
150 }
151}
152
153impl std::fmt::Debug for SharedBuffer {
154 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 write!(
156 formatter,
157 "SharedBuffer({} channels at {} Hz)",
158 self.channels, self.rate
159 )
160 }
161}
162
163#[derive(Debug, Clone, PartialEq)]
165#[non_exhaustive]
166pub enum Sink {
167 Discard,
169 Device {
172 name: Option<String>,
173 first_channel: u16,
174 },
175 Shared(SharedBuffer),
178 Blocks(Blocks<dyn BlockSink>),
183}
184
185pub struct FrameBuffer {
188 held: Lock<Held>,
189 channels: usize,
190 margin: usize,
192 pub underruns: AtomicU64,
195 pub adjustments: AtomicU64,
196}
197
198struct Held {
199 samples: VecDeque<f32>,
200 pushed: u64,
203 more: usize,
205 sample: Option<DeviceSample>,
208}
209
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub struct DeviceSample {
213 pub chunks: u64,
215 pub level: usize,
216 pub chunk: usize,
217 pub pushed: u64,
220 pub plays_at: Option<i64>,
223}
224
225impl FrameBuffer {
226 pub fn new(channels: u16, margin: usize) -> Self {
227 let channels = usize::from(channels).max(1);
228 FrameBuffer {
229 held: Lock::new(Held {
230 samples: VecDeque::with_capacity(4 * margin * channels),
231 pushed: 0,
232 more: 0,
233 sample: None,
234 }),
235 channels,
236 margin: margin.max(1),
237 underruns: AtomicU64::new(0),
238 adjustments: AtomicU64::new(0),
239 }
240 }
241
242 fn lock(&self) -> Guard<'_, Held> {
243 self.held.lock()
244 }
245
246 pub fn push(&self, samples: &[f32]) {
249 let mut held = self.lock();
250 self.push_into(&mut held, samples);
251 }
252
253 fn push_into(&self, held: &mut Held, samples: &[f32]) {
254 held.samples.extend(samples);
255 held.pushed += (samples.len() / self.channels) as u64;
256 let chunk = held.sample.map_or(0, |sample| sample.chunk);
257 let most = (4 * (self.margin + chunk) + held.more) * self.channels;
258 if held.samples.len() > most {
259 let extra = held.samples.len() - most;
260 held.samples.drain(..extra - extra % self.channels);
261 self.adjustments.fetch_add(1, Ordering::Relaxed);
262 }
263 }
264
265 pub fn pull(&self, out: &mut [f32]) {
267 let mut held = self.lock();
268 self.pull_from(&mut held, out);
269 }
270
271 fn pull_from(&self, held: &mut Held, out: &mut [f32]) {
272 let mut short = false;
273 for slot in out.iter_mut() {
274 *slot = held.samples.pop_front().unwrap_or_else(|| {
275 short = true;
276 0.0
277 });
278 }
279 if short {
280 self.underruns.fetch_add(1, Ordering::Relaxed);
281 }
282 }
283
284 pub fn pushed(&self) -> u64 {
286 self.lock().pushed
287 }
288
289 pub fn hold_more(&self, frames: usize) {
291 let mut held = self.lock();
292 held.more = held.more.max(frames);
293 }
294
295 pub fn drop_oldest(&self, frames: usize) {
297 let mut held = self.lock();
298 let samples = (frames * self.channels).min(held.samples.len());
299 held.samples.drain(..samples);
300 }
301
302 pub fn device_push(&self, samples: &[f32]) {
304 let mut held = self.lock();
305 self.push_into(&mut held, samples);
306 self.note(&mut held, samples.len(), None);
307 }
308
309 pub fn device_pull(&self, out: &mut [f32], plays_at: Option<i64>) {
312 let mut held = self.lock();
313 self.pull_from(&mut held, out);
314 self.note(&mut held, out.len(), plays_at);
315 }
316
317 fn note(&self, held: &mut Held, samples: usize, plays_at: Option<i64>) {
318 let chunks = held.sample.map_or(1, |sample| sample.chunks + 1);
319 held.sample = Some(DeviceSample {
320 chunks,
321 level: held.samples.len() / self.channels,
322 chunk: samples / self.channels,
323 pushed: held.pushed,
324 plays_at,
325 });
326 }
327
328 pub fn device_sample(&self) -> Option<DeviceSample> {
330 self.lock().sample
331 }
332
333 pub fn level(&self) -> usize {
335 self.lock().samples.len() / self.channels
336 }
337}
338
339const SMOOTHING: f64 = 0.02;
345const PROPORTIONAL: f64 = 0.0051;
346const INTEGRAL: f64 = 1e-5;
347const MOST_DRIFT: f64 = 0.002;
349
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352pub enum DeviceSide {
353 Pushes,
355 Pulls,
357}
358
359pub struct Drift {
363 channels: usize,
364 side: DeviceSide,
365 nominal: f64,
369 held: VecDeque<f32>,
372 position: f64,
375 ratio: f64,
377 chunks: u64,
380 error: Option<f64>,
381 integral: f64,
382}
383
384impl Drift {
385 pub fn new(channels: u16, side: DeviceSide, nominal: f64) -> Self {
386 Drift {
387 channels: usize::from(channels).max(1),
388 side,
389 nominal,
390 held: VecDeque::new(),
391 position: 0.0,
392 ratio: nominal,
393 chunks: 0,
394 error: None,
395 integral: 0.0,
396 }
397 }
398
399 pub fn ratio(&self) -> f64 {
401 self.ratio
402 }
403
404 pub fn device_ppm(&self) -> i32 {
407 let relative = self.ratio / self.nominal;
408 let ppm = match self.side {
409 DeviceSide::Pushes => relative - 1.0,
411 DeviceSide::Pulls => 1.0 / relative - 1.0,
413 };
414 (ppm * 1e6).round() as i32
415 }
416
417 pub fn steer(&mut self, buffer: &FrameBuffer) {
421 if let Some(sample) = self.new_sample(buffer) {
422 let excess = sample.level as f64 - self.kept(buffer, &sample) as f64;
423 self.follow(excess, sample.chunk);
424 }
425 }
426
427 fn new_sample(&mut self, buffer: &FrameBuffer) -> Option<DeviceSample> {
429 let sample = buffer.device_sample()?;
430 if sample.chunks == self.chunks {
431 return None;
432 }
433 self.chunks = sample.chunks;
434 Some(sample)
435 }
436
437 fn kept(&self, buffer: &FrameBuffer, sample: &DeviceSample) -> usize {
441 match self.side {
442 DeviceSide::Pushes => buffer.margin + sample.chunk,
443 DeviceSide::Pulls => buffer.margin,
444 }
445 }
446
447 fn follow(&mut self, excess: f64, chunk: usize) {
450 let error = excess / chunk.max(1) as f64;
451 let smoothed = self.error.get_or_insert(error);
452 *smoothed += SMOOTHING * (error - *smoothed);
453 self.integral = (self.integral + INTEGRAL * *smoothed).clamp(-MOST_DRIFT, MOST_DRIFT);
454 self.ratio = self.nominal
455 * (1.0 + PROPORTIONAL * *smoothed + self.integral)
456 .clamp(1.0 - MOST_DRIFT, 1.0 + MOST_DRIFT);
457 }
458
459 fn held_frames(&self) -> usize {
460 self.held.len() / self.channels
461 }
462
463 fn pending(&self) -> f64 {
466 (self.held_frames() as f64 - 1.0 - self.position).max(0.0)
467 }
468
469 pub fn wanted(&self, frames: usize) -> usize {
471 if frames == 0 {
472 return 0;
473 }
474 let last = self.position + (frames - 1) as f64 * self.ratio;
475 (last as usize + 4).saturating_sub(self.held_frames())
476 }
477
478 pub fn push(&mut self, input: &[f32]) {
479 self.held.extend(input);
480 }
481
482 pub fn make(&mut self, out: &mut Vec<f32>, most: usize) {
485 let channels = self.channels;
486 let mut made = 0;
487 while made < most && self.position as usize + 4 <= self.held_frames() {
488 let base = self.position as usize;
489 let t = (self.position - base as f64) as f32;
490 for channel in 0..channels {
491 let at = |frame: usize| self.held[(base + frame) * channels + channel];
492 let (before, from, to, after) = (at(0), at(1), at(2), at(3));
493 let a = -0.5 * before + 1.5 * from - 1.5 * to + 0.5 * after;
495 let b = before - 2.5 * from + 2.0 * to - 0.5 * after;
496 let c = -0.5 * before + 0.5 * to;
497 out.push(((a * t + b) * t + c) * t + from);
498 }
499 made += 1;
500 self.position += self.ratio;
501 let passed = (self.position as usize).min(self.held_frames());
504 if passed > 0 {
505 self.held.drain(..passed * channels);
506 self.position -= passed as f64;
507 }
508 }
509 }
510}
511
512struct DeviceThread {
514 stop: Arc<AtomicBool>,
515 handle: Option<JoinHandle<()>>,
516}
517
518impl Drop for DeviceThread {
519 fn drop(&mut self) {
520 self.stop.store(true, Ordering::Relaxed);
521 if let Some(handle) = self.handle.take() {
522 handle.thread().unpark();
523 let _ = handle.join();
524 }
525 }
526}
527
528fn device_error(error: impl std::fmt::Display) -> io::Error {
529 io::Error::other(error.to_string())
530}
531
532fn find_device(name: Option<&str>, input: bool) -> io::Result<cpal::Device> {
534 let host = cpal::default_host();
535 let found = match name {
536 Some(name) => {
537 let devices = if input {
538 host.input_devices()
539 } else {
540 host.output_devices()
541 }
542 .map_err(device_error)?;
543 devices
544 .into_iter()
545 .find(|device| device.description().is_ok_and(|about| about.name() == name))
546 }
547 None if input => host.default_input_device(),
548 None => host.default_output_device(),
549 };
550 found.ok_or_else(|| {
551 io::Error::new(
552 io::ErrorKind::NotFound,
553 match name {
554 Some(name) => format!("no audio device named {name}"),
555 None => "no default audio device".to_owned(),
556 },
557 )
558 })
559}
560
561fn device_rate(device: &cpal::Device, input: bool, wanted: u32) -> io::Result<u32> {
564 let default = if input {
565 device.default_input_config()
566 } else {
567 device.default_output_config()
568 }
569 .map_err(device_error)?;
570 if default.sample_rate() == wanted {
571 return Ok(wanted);
572 }
573 let ranges: Vec<cpal::SupportedStreamConfigRange> = if input {
574 device.supported_input_configs().map(Iterator::collect)
575 } else {
576 device.supported_output_configs().map(Iterator::collect)
577 }
578 .unwrap_or_default();
579 let supported = ranges.iter().any(|range| {
580 range.channels() == default.channels()
581 && (range.min_sample_rate()..=range.max_sample_rate()).contains(&wanted)
582 });
583 Ok(if supported {
584 wanted
585 } else {
586 default.sample_rate()
587 })
588}
589
590pub fn device_names() -> (Vec<String>, Vec<String>) {
592 let host = cpal::default_host();
593 let named = |device: cpal::Device| Some(device.description().ok()?.name().to_owned());
594 let inputs = host
595 .input_devices()
596 .map(|devices| devices.filter_map(named).collect())
597 .unwrap_or_default();
598 let outputs = host
599 .output_devices()
600 .map(|devices| devices.filter_map(named).collect())
601 .unwrap_or_default();
602 (inputs, outputs)
603}
604
605fn device_thread(
608 name: String,
609 build: impl FnOnce() -> io::Result<cpal::Stream> + Send + 'static,
610) -> io::Result<DeviceThread> {
611 let stop = Arc::new(AtomicBool::new(false));
612 let stopping = stop.clone();
613 let (opened, started) = mpsc::channel();
614 let handle = std::thread::Builder::new().name(name).spawn(move || {
615 let stream = match build().and_then(|stream| {
616 stream.play().map_err(device_error)?;
617 Ok(stream)
618 }) {
619 Ok(stream) => {
620 let _ = opened.send(Ok(()));
621 stream
622 }
623 Err(error) => {
624 let _ = opened.send(Err(error));
625 return;
626 }
627 };
628 while !stopping.load(Ordering::Relaxed) {
629 std::thread::park_timeout(Duration::from_millis(200));
630 }
631 drop(stream);
632 })?;
633 started
634 .recv()
635 .unwrap_or_else(|_| Err(io::Error::other("the audio thread stopped")))?;
636 Ok(DeviceThread {
637 stop,
638 handle: Some(handle),
639 })
640}
641
642fn input_stream<T>(
643 device: &cpal::Device,
644 config: cpal::StreamConfig,
645 channels: usize,
646 first: usize,
647 buffer: Arc<FrameBuffer>,
648) -> io::Result<cpal::Stream>
649where
650 T: SizedSample,
651 f32: FromSample<T>,
652{
653 let device_channels = usize::from(config.channels).max(1);
654 let mut frames = Vec::new();
655 device
656 .build_input_stream(
657 config,
658 move |data: &[T], _: &cpal::InputCallbackInfo| {
659 frames.clear();
660 for frame in data.chunks_exact(device_channels) {
661 for channel in 0..channels {
662 frames.push(
663 frame
664 .get(first + channel)
665 .map_or(0.0, |sample| sample.to_sample::<f32>()),
666 );
667 }
668 }
669 buffer.device_push(&frames);
670 },
671 |_| {},
672 None,
673 )
674 .map_err(device_error)
675}
676
677fn output_stream<T>(
678 device: &cpal::Device,
679 config: cpal::StreamConfig,
680 channels: usize,
681 first: usize,
682 buffer: Arc<FrameBuffer>,
683) -> io::Result<cpal::Stream>
684where
685 T: SizedSample + FromSample<f32>,
686{
687 let device_channels = usize::from(config.channels).max(1);
688 let rate = i64::from(config.sample_rate.max(1));
689 let mut frames = Vec::new();
690 device
691 .build_output_stream(
692 config,
693 move |data: &mut [T], info: &cpal::OutputCallbackInfo| {
694 let count = data.len() / device_channels;
695 frames.resize(count * channels, 0.0);
696 let stamp = info.timestamp();
699 let latency = stamp.playback.duration_since(stamp.callback);
700 let plays_at = avb_net::clock::monotonic_now() + latency;
701 let after = plays_at.as_nanos() as i64 + count as i64 * 1_000_000_000 / rate;
702 buffer.device_pull(&mut frames, Some(after));
703 for (frame, samples) in data
704 .chunks_exact_mut(device_channels)
705 .zip(frames.chunks_exact(channels.max(1)))
706 {
707 for (channel, slot) in frame.iter_mut().enumerate() {
708 let sample = channel
709 .checked_sub(first)
710 .and_then(|stream| samples.get(stream))
711 .copied()
712 .unwrap_or(0.0);
713 *slot = T::from_sample(sample);
714 }
715 }
716 },
717 |_| {},
718 None,
719 )
720 .map_err(device_error)
721}
722
723pub struct Input {
725 kind: InputKind,
726 channels: usize,
727 spread: Vec<f32>,
729}
730
731enum InputKind {
732 Silence,
733 Tone {
734 phase: f32,
735 step: f32,
736 level: f32,
737 },
738 Device {
739 buffer: Arc<FrameBuffer>,
740 width: usize,
742 drift: Drift,
743 taken: Vec<f32>,
745 made: Vec<f32>,
746 _thread: Option<DeviceThread>,
747 },
748}
749
750impl Input {
751 pub fn open(source: &Source, channels: u16, rate: u32) -> io::Result<Self> {
753 let kind = match source {
754 Source::Silence | Source::Blocks(_) => InputKind::Silence,
756 Source::Tone { hertz, level } => InputKind::Tone {
757 phase: 0.0,
758 step: TAU * hertz / rate as f32,
759 level: level.clamp(0.0, 1.0),
760 },
761 Source::Device {
762 name,
763 first_channel,
764 } => {
765 let device = find_device(name.as_deref(), true)?;
766 let device_rate = device_rate(&device, true, rate)?;
767 let margin = device_rate as usize / 100;
769 let buffer = Arc::new(FrameBuffer::new(channels, margin));
770 let filling = buffer.clone();
771 let first = usize::from(*first_channel);
772 let wanted = usize::from(channels);
773 let thread = device_thread("audio input".into(), move || {
774 let supported = device.default_input_config().map_err(device_error)?;
775 let mut config = supported.config();
776 config.sample_rate = device_rate;
777 match supported.sample_format() {
778 cpal::SampleFormat::F32 => {
779 input_stream::<f32>(&device, config, wanted, first, filling)
780 }
781 cpal::SampleFormat::I16 => {
782 input_stream::<i16>(&device, config, wanted, first, filling)
783 }
784 cpal::SampleFormat::I32 => {
785 input_stream::<i32>(&device, config, wanted, first, filling)
786 }
787 other => Err(io::Error::new(
788 io::ErrorKind::Unsupported,
789 format!("samples in {other}"),
790 )),
791 }
792 })?;
793 InputKind::Device {
794 buffer,
795 width: usize::from(channels),
796 drift: Drift::new(
797 channels,
798 DeviceSide::Pushes,
799 f64::from(device_rate) / f64::from(rate),
800 ),
801 taken: Vec::new(),
802 made: Vec::new(),
803 _thread: Some(thread),
804 }
805 }
806 Source::Shared(shared) => {
807 shared.buffer.drop_oldest(shared.buffer.level());
810 InputKind::Device {
811 buffer: shared.buffer.clone(),
812 width: usize::from(shared.channels).max(1),
813 drift: Drift::new(
814 shared.channels,
815 DeviceSide::Pushes,
816 f64::from(shared.rate) / f64::from(rate),
817 ),
818 taken: Vec::new(),
819 made: Vec::new(),
820 _thread: None,
821 }
822 }
823 };
824 Ok(Input {
825 kind,
826 channels: usize::from(channels),
827 spread: Vec::new(),
828 })
829 }
830
831 pub fn drift_ppm(&self) -> i32 {
834 match &self.kind {
835 InputKind::Device { drift, .. } => drift.device_ppm(),
836 _ => 0,
837 }
838 }
839
840 pub fn counts(&self) -> (u64, u64) {
843 match &self.kind {
844 InputKind::Device { buffer, .. } => (
845 buffer.adjustments.load(Ordering::Relaxed),
846 buffer.underruns.load(Ordering::Relaxed),
847 ),
848 _ => (0, 0),
849 }
850 }
851
852 pub fn read(&mut self, out: &mut [f32]) {
854 match &mut self.kind {
855 InputKind::Silence => out.fill(0.0),
856 InputKind::Tone { phase, step, level } => {
857 for frame in out.chunks_exact_mut(self.channels.max(1)) {
858 frame.fill(phase.sin() * *level);
859 *phase = (*phase + *step) % TAU;
860 }
861 }
862 InputKind::Device {
863 buffer,
864 width,
865 drift,
866 taken,
867 made,
868 ..
869 } => {
870 let frames = out.len() / self.channels.max(1);
871 drift.steer(buffer);
872 taken.resize(drift.wanted(frames) * *width, 0.0);
873 buffer.pull(taken);
874 drift.push(taken);
875 made.clear();
876 drift.make(made, frames);
877 out.fill(0.0);
878 if *width == self.channels.max(1) {
879 out[..made.len()].copy_from_slice(made);
880 } else {
881 respread(made, *width, out, self.channels);
883 }
884 }
885 }
886 }
887
888 pub fn read_as(&mut self, out: &mut [f32], channels: usize) {
892 let channels = channels.max(1);
893 if channels == self.channels.max(1) {
894 self.read(out);
895 return;
896 }
897 let mut spread = std::mem::take(&mut self.spread);
898 spread.resize(out.len() / channels * self.channels.max(1), 0.0);
899 self.read(&mut spread);
900 respread(&spread, self.channels, out, channels);
901 self.spread = spread;
902 }
903
904 pub fn skip(&mut self, frames: usize) {
907 match &mut self.kind {
908 InputKind::Silence => {}
909 InputKind::Tone { phase, step, .. } => {
910 let turned = f64::from(*phase) + f64::from(*step) * frames as f64;
911 *phase = (turned % std::f64::consts::TAU) as f32;
912 }
913 InputKind::Device { buffer, drift, .. } => {
915 buffer.drop_oldest((frames as f64 * drift.ratio()).round() as usize);
916 }
917 }
918 }
919}
920
921fn respread(samples: &[f32], channels: usize, out: &mut [f32], out_channels: usize) {
925 let (channels, out_channels) = (channels.max(1), out_channels.max(1));
926 let kept = channels.min(out_channels);
927 for (to, from) in out
928 .chunks_exact_mut(out_channels)
929 .zip(samples.chunks_exact(channels))
930 {
931 to[..kept].copy_from_slice(&from[..kept]);
932 to[kept..].fill(0.0);
933 }
934}
935
936#[derive(Debug, Clone, Copy, PartialEq, Eq)]
938pub struct Presented {
939 pub first: i64,
941 pub offset: i64,
943}
944
945const CHOOSING: i64 = 2_000_000_000;
947const DELAY_STEP: i64 = 1_000_000;
950const MOST_DELAY: i64 = 500_000_000;
951const MOST_AHEAD: i64 = 500_000_000;
954
955struct Playing {
957 drift: Drift,
958 made: Vec<f32>,
959 spread: Vec<f32>,
961 next_in: Option<i64>,
964 offset: Option<i64>,
965 anchor: Option<(u64, i64)>,
967 delay: Option<i64>,
970 error: i64,
971 choosing: Option<(i64, f64, u32)>,
974 underruns: u64,
976}
977
978pub struct Output {
980 buffer: Option<Arc<FrameBuffer>>,
981 width: usize,
983 _thread: Option<DeviceThread>,
984 playing: Lock<Playing>,
985 rate: u32,
987 peak: AtomicU32,
989}
990
991impl Output {
992 pub fn open(sink: &Sink, channels: u16, rate: u32) -> io::Result<Self> {
994 match sink {
995 Sink::Discard | Sink::Blocks(_) => {
997 Ok(Output::new(None, None, channels, channels, rate, rate))
998 }
999 Sink::Shared(shared) => Ok(Output::new(
1000 Some(shared.buffer.clone()),
1001 None,
1002 channels,
1003 shared.channels,
1004 rate,
1005 shared.rate,
1006 )),
1007 Sink::Device {
1008 name,
1009 first_channel,
1010 } => {
1011 let device = find_device(name.as_deref(), false)?;
1012 let device_rate = device_rate(&device, false, rate)?;
1013 let margin = device_rate as usize / 100;
1014 let buffer = Arc::new(FrameBuffer::new(channels, margin));
1015 let draining = buffer.clone();
1016 let first = usize::from(*first_channel);
1017 let wanted = usize::from(channels);
1018 let thread = device_thread("audio output".into(), move || {
1019 let supported = device.default_output_config().map_err(device_error)?;
1020 let mut config = supported.config();
1021 config.sample_rate = device_rate;
1022 match supported.sample_format() {
1023 cpal::SampleFormat::F32 => {
1024 output_stream::<f32>(&device, config, wanted, first, draining)
1025 }
1026 cpal::SampleFormat::I16 => {
1027 output_stream::<i16>(&device, config, wanted, first, draining)
1028 }
1029 cpal::SampleFormat::I32 => {
1030 output_stream::<i32>(&device, config, wanted, first, draining)
1031 }
1032 other => Err(io::Error::new(
1033 io::ErrorKind::Unsupported,
1034 format!("samples in {other}"),
1035 )),
1036 }
1037 })?;
1038 Ok(Output::new(
1039 Some(buffer),
1040 Some(thread),
1041 channels,
1042 channels,
1043 rate,
1044 device_rate,
1045 ))
1046 }
1047 }
1048 }
1049
1050 fn new(
1053 buffer: Option<Arc<FrameBuffer>>,
1054 thread: Option<DeviceThread>,
1055 channels: u16,
1056 width: u16,
1057 rate: u32,
1058 device_rate: u32,
1059 ) -> Self {
1060 let nominal = f64::from(rate) / f64::from(device_rate.max(1));
1061 Output {
1062 buffer,
1063 width: usize::from(width).max(1),
1064 _thread: thread,
1065 playing: Lock::new(Playing {
1066 drift: Drift::new(channels, DeviceSide::Pulls, nominal),
1067 made: Vec::new(),
1068 spread: Vec::new(),
1069 next_in: None,
1070 offset: None,
1071 anchor: None,
1072 delay: None,
1073 error: 0,
1074 choosing: None,
1075 underruns: 0,
1076 }),
1077 rate: rate.max(1),
1078 peak: AtomicU32::new(0),
1079 }
1080 }
1081
1082 fn lock(&self) -> Guard<'_, Playing> {
1083 self.playing.lock()
1084 }
1085
1086 pub fn write(&self, samples: &[f32], presented: Option<Presented>) {
1089 let loudest = samples
1090 .iter()
1091 .fold(0.0f32, |most, sample| most.max(sample.abs()));
1092 self.peak.fetch_max(loudest.to_bits(), Ordering::Relaxed);
1093 let Some(buffer) = &self.buffer else {
1094 return;
1095 };
1096 let mut playing = self.lock();
1097 let playing = &mut *playing;
1098 if let Some(presented) = presented {
1099 playing.next_in = Some(presented.first);
1100 playing.offset = Some(presented.offset);
1101 }
1102 if let Some(sample) = playing.drift.new_sample(buffer) {
1103 self.steer(playing, buffer, &sample);
1104 }
1105 playing.drift.push(samples);
1106 playing.made.clear();
1107 playing.drift.make(&mut playing.made, usize::MAX);
1108 let channels = playing.drift.channels;
1109 if self.width == channels {
1110 buffer.push(&playing.made);
1111 } else {
1112 let frames = playing.made.len() / channels;
1114 playing.spread.resize(frames * self.width, 0.0);
1115 respread(&playing.made, channels, &mut playing.spread, self.width);
1116 buffer.push(&playing.spread);
1117 }
1118 let frames = samples.len() / playing.drift.channels;
1119 let frame = 1e9 / f64::from(self.rate);
1120 if let Some(next) = &mut playing.next_in {
1121 *next += (frames as f64 * frame).round() as i64;
1122 let made = *next - (playing.drift.pending() * frame).round() as i64;
1125 playing.anchor = Some((buffer.pushed(), made));
1126 }
1127 }
1128
1129 fn steer(&self, playing: &mut Playing, buffer: &FrameBuffer, sample: &DeviceSample) {
1132 let excess = sample.level as f64 - playing.drift.kept(buffer, sample) as f64;
1133 let (Some(plays_at), Some((anchor, presented)), Some(offset)) =
1134 (sample.plays_at, playing.anchor, playing.offset)
1135 else {
1136 playing.drift.follow(excess, sample.chunk);
1137 return;
1138 };
1139 let frame = playing.drift.ratio() * 1e9 / f64::from(self.rate);
1141 let oldest = sample.pushed - sample.level as u64;
1142 let presents = presented as f64 - (anchor as f64 - oldest as f64) * frame;
1143 let late = (plays_at + offset) as f64 - presents;
1144 if !(-MOST_AHEAD as f64..=2.0 * MOST_DELAY as f64).contains(&late) {
1145 playing.drift.follow(excess, sample.chunk);
1146 return;
1147 }
1148 let Some(delay) = playing.delay else {
1149 playing.drift.follow(excess, sample.chunk);
1152 let (since, sum, seen) = playing.choosing.get_or_insert((plays_at, 0.0, 0));
1153 *sum += late - excess * frame;
1154 *seen += 1;
1155 if plays_at - *since >= CHOOSING {
1156 let earliest = (*sum / f64::from(*seen)).max(0.0) as i64;
1157 let steps = (earliest + DELAY_STEP - 1) / DELAY_STEP;
1158 let delay = (steps * DELAY_STEP).min(MOST_DELAY);
1159 self.set_delay(playing, buffer, delay, (late - delay as f64) / frame);
1160 }
1161 return;
1162 };
1163 let underruns = buffer.underruns.load(Ordering::Relaxed);
1164 if underruns > playing.underruns && delay < MOST_DELAY {
1165 let later = delay + DELAY_STEP;
1166 self.set_delay(playing, buffer, later, (late - later as f64) / frame);
1167 return;
1168 }
1169 playing.error = (late - delay as f64) as i64;
1170 playing
1171 .drift
1172 .follow((late - delay as f64) / frame, sample.chunk);
1173 }
1174
1175 fn set_delay(&self, playing: &mut Playing, buffer: &FrameBuffer, delay: i64, excess: f64) {
1178 playing.delay = Some(delay);
1179 playing.error = 0;
1180 playing.underruns = buffer.underruns.load(Ordering::Relaxed);
1181 let excess = excess.round() as i64;
1182 buffer.hold_more(excess.unsigned_abs() as usize);
1183 if excess > 0 {
1184 buffer.drop_oldest(excess as usize);
1185 } else if excess < 0 {
1186 let frames = excess.unsigned_abs() as usize;
1189 buffer.push(&vec![0.0; frames * playing.drift.channels]);
1190 if let Some((anchor, _)) = &mut playing.anchor {
1191 *anchor += frames as u64;
1192 }
1193 }
1194 }
1195
1196 pub fn playout(&self) -> Option<(i64, i64)> {
1200 let playing = self.lock();
1201 playing.delay.map(|delay| (delay, playing.error))
1202 }
1203
1204 pub fn drift_ppm(&self) -> i32 {
1207 if self.buffer.is_none() {
1208 return 0;
1209 }
1210 self.lock().drift.device_ppm()
1211 }
1212
1213 pub fn underruns(&self) -> u64 {
1215 self.buffer
1216 .as_ref()
1217 .map_or(0, |buffer| buffer.underruns.load(Ordering::Relaxed))
1218 }
1219
1220 pub fn take_peak(&self) -> f32 {
1222 f32::from_bits(self.peak.swap(0, Ordering::Relaxed))
1223 }
1224}
1225
1226#[cfg(test)]
1227mod tests {
1228 use super::*;
1229
1230 #[test]
1231 fn the_buffer_notes_its_fill_after_each_device_chunk() {
1232 let buffer = FrameBuffer::new(2, 10);
1233 assert_eq!(buffer.device_sample(), None);
1234 buffer.device_push(&[1.0; 8]);
1235 buffer.push(&[2.0; 4]);
1236 assert_eq!(
1237 buffer.device_sample(),
1238 Some(DeviceSample {
1239 chunks: 1,
1240 level: 4,
1241 chunk: 4,
1242 pushed: 4,
1243 plays_at: None,
1244 })
1245 );
1246 let mut out = [9.0; 6];
1247 buffer.device_pull(&mut out, None);
1248 assert_eq!(out, [1.0; 6]);
1249 assert_eq!(buffer.device_sample().map(|sample| sample.chunks), Some(2));
1250 buffer.push(&[3.0; 200]);
1252 assert_eq!(buffer.level(), 4 * (10 + 3));
1253 assert!(buffer.adjustments.load(Ordering::Relaxed) > 0);
1254 let mut out = [9.0; 120];
1256 buffer.pull(&mut out);
1257 assert_eq!(out[104..], [0.0; 16]);
1258 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 1);
1259 }
1260
1261 fn numbered(frames: usize) -> Vec<f32> {
1263 (0..frames)
1264 .flat_map(|_| (1..=8).map(|channel| channel as f32 / 10.0))
1265 .collect()
1266 }
1267
1268 #[test]
1272 fn a_stream_takes_the_first_channels_of_a_wider_shared_buffer() {
1273 let shared = SharedBuffer {
1274 buffer: Arc::new(FrameBuffer::new(8, 480)),
1275 channels: 8,
1276 rate: 48_000,
1277 };
1278 let mut input = Input::open(&Source::Shared(shared.clone()), 2, 48_000).expect("opened");
1279 shared.buffer.device_push(&numbered(4800));
1280 let mut out = vec![9.0; 480 * 2];
1281 for _ in 0..4 {
1282 input.read(&mut out);
1283 }
1284 for frame in out.as_chunks::<2>().0 {
1285 assert!((frame[0] - 0.1).abs() < 1e-3, "{frame:?}");
1286 assert!((frame[1] - 0.2).abs() < 1e-3, "{frame:?}");
1287 }
1288 }
1289
1290 #[test]
1293 fn a_stream_fills_the_first_channels_of_a_wider_shared_buffer() {
1294 let shared = SharedBuffer {
1295 buffer: Arc::new(FrameBuffer::new(8, 480)),
1296 channels: 8,
1297 rate: 48_000,
1298 };
1299 let output = Output::open(&Sink::Shared(shared.clone()), 2, 48_000).expect("opened");
1300 let stereo: Vec<f32> = (0..4800).flat_map(|_| [0.5, -0.5]).collect();
1301 output.write(&stereo, None);
1302 let mut out = vec![9.0; 480 * 8];
1303 shared.buffer.device_pull(&mut out, None);
1304 for frame in out.as_chunks::<8>().0 {
1305 assert!((frame[0] - 0.5).abs() < 1e-3, "{frame:?}");
1306 assert!((frame[1] + 0.5).abs() < 1e-3, "{frame:?}");
1307 assert_eq!(frame[2..], [0.0; 6]);
1308 }
1309 }
1310
1311 fn sine(hertz: f64, rate: f64, start: u64, frames: usize) -> Vec<f32> {
1313 (0..frames as u64)
1314 .map(|index| (TAU as f64 * hertz * (start + index) as f64 / rate).sin() as f32 * 0.5)
1315 .collect()
1316 }
1317
1318 fn chunk_time(index: u64, chunk: usize, rate: f64) -> f64 {
1321 let nominal = index as f64 * chunk as f64 / rate;
1322 let wobble = ((index * 7919) % 41) as f64 / 40.0 - 0.5;
1323 nominal + 0.04 * wobble * chunk as f64 / rate
1324 }
1325
1326 #[test]
1331 fn a_fast_device_is_followed_without_a_gap() {
1332 let rate = 48_000.0;
1333 let device_rate = rate * (1.0 + 120e-6);
1334 let buffer = FrameBuffer::new(1, 480);
1335 let mut drift = Drift::new(1, DeviceSide::Pushes, 1.0);
1336 let mut chunks = 0;
1337 let mut out = Vec::new();
1338 let mut steps = Vec::new();
1339 let mut ratios = Vec::new();
1340 for packet in 0..8000 * 120u64 {
1341 let now = packet as f64 / 8000.0;
1342 while chunk_time(chunks, 1024, device_rate) <= now {
1343 buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1344 chunks += 1;
1345 }
1346 drift.steer(&buffer);
1347 let mut taken = vec![0.0; drift.wanted(6)];
1348 buffer.pull(&mut taken);
1349 drift.push(&taken);
1350 out.clear();
1351 drift.make(&mut out, 6);
1352 assert_eq!(out.len(), 6);
1353 if packet == 8000 {
1354 buffer.underruns.store(0, Ordering::Relaxed);
1355 }
1356 if packet > 8000 * 40 {
1357 steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1358 ratios.push(drift.ratio());
1359 }
1360 }
1361 for ratio in &ratios {
1362 assert!((ratio - (1.0 + 120e-6)).abs() < 30e-6, "{ratio}");
1363 }
1364 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1365 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1366 let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1369 assert!(most < 0.07, "{most}");
1370 }
1371
1372 #[test]
1376 fn a_slow_device_is_fed_without_a_gap() {
1377 let rate = 48_000.0;
1378 let device_rate = rate * (1.0 - 80e-6);
1379 let buffer = FrameBuffer::new(1, 480);
1380 let mut drift = Drift::new(1, DeviceSide::Pulls, 1.0);
1381 let mut chunks = 0;
1382 let mut made = Vec::new();
1383 let mut played = vec![0.0; 1024];
1384 let mut ratios = Vec::new();
1385 for packet in 0..8000 * 120u64 {
1386 drift.steer(&buffer);
1387 drift.push(&sine(1000.0, rate, packet * 6, 6));
1388 made.clear();
1389 drift.make(&mut made, usize::MAX);
1390 buffer.push(&made);
1391 let now = packet as f64 / 8000.0;
1392 while chunk_time(chunks + 1, 1024, device_rate) <= now {
1393 buffer.device_pull(&mut played, None);
1394 chunks += 1;
1395 }
1396 if packet == 8000 {
1397 buffer.underruns.store(0, Ordering::Relaxed);
1398 }
1399 if packet > 8000 * 40 {
1400 ratios.push(drift.ratio());
1401 }
1402 }
1403 for ratio in &ratios {
1404 assert!((ratio - 1.0 / (1.0 - 80e-6)).abs() < 30e-6, "{ratio}");
1405 }
1406 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1407 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1408 }
1409
1410 #[test]
1415 fn a_device_at_half_the_rate_is_followed() {
1416 let device_rate = 48_000.0 * (1.0 + 50e-6);
1417 let buffer = FrameBuffer::new(1, 480);
1418 let mut drift = Drift::new(1, DeviceSide::Pushes, 0.5);
1419 let mut chunks = 0;
1420 let mut out = Vec::new();
1421 let mut steps = Vec::new();
1422 let mut ppms = Vec::new();
1423 for packet in 0..8000 * 120u64 {
1424 let now = packet as f64 / 8000.0;
1425 while chunk_time(chunks, 1024, device_rate) <= now {
1426 buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1427 chunks += 1;
1428 }
1429 drift.steer(&buffer);
1430 let mut taken = vec![0.0; drift.wanted(12)];
1431 buffer.pull(&mut taken);
1432 drift.push(&taken);
1433 out.clear();
1434 drift.make(&mut out, 12);
1435 assert_eq!(out.len(), 12);
1436 if packet == 8000 {
1437 buffer.underruns.store(0, Ordering::Relaxed);
1438 }
1439 if packet > 8000 * 40 {
1440 steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1441 ppms.push(drift.device_ppm());
1442 }
1443 }
1444 for ppm in &ppms {
1445 assert!((ppm - 50).abs() < 30, "{ppm}");
1446 }
1447 assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1448 assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1449 let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1451 assert!(most < 0.04, "{most}");
1452 }
1453
1454 #[test]
1458 fn a_stream_at_four_times_the_devices_rate_is_made_whole() {
1459 let mut drift = Drift::new(2, DeviceSide::Pulls, 4.0);
1460 drift.ratio = 4.0 + 300e-6;
1461 let mut out = Vec::new();
1462 let mut made = 0;
1463 let mut last: Option<f32> = None;
1464 let mut most = 0.0f32;
1465 for frame in 0..8000 * 10 {
1466 let first = frame * 24;
1467 let input: Vec<f32> = (first..first + 24)
1468 .flat_map(|at| {
1469 let sample = (TAU as f64 * 1000.0 * at as f64 / 192_000.0).sin() as f32 * 0.5;
1470 [sample, -sample]
1471 })
1472 .collect();
1473 drift.push(&input);
1474 out.clear();
1475 drift.make(&mut out, usize::MAX);
1476 for pair in out.as_chunks::<2>().0 {
1477 if let Some(previous) = last {
1478 most = most.max((pair[0] - previous).abs());
1479 }
1480 last = Some(pair[0]);
1481 made += 1;
1482 }
1483 }
1484 let expected = 8000.0 * 10.0 * 24.0 / drift.ratio;
1486 assert!((made as f64 - expected).abs() < 4.0, "{made}");
1487 assert!(most < 0.07, "{most}");
1489 }
1490
1491 fn play_out(chunk: usize, latency: f64, ahead: f64) -> (i64, f64, u64) {
1497 let rate = 48_000.0;
1498 let device_rate = rate * (1.0 - 50e-6);
1499 let buffer = Arc::new(FrameBuffer::new(1, 480));
1500 let output = Output::new(Some(buffer.clone()), None, 1, 1, 48_000, 48_000);
1501 let tone = |seconds: f64| (TAU as f64 * 100.0 * seconds).sin() as f32 * 0.5;
1502 let mut played = vec![0.0; chunk];
1503 let mut chunks = 0;
1504 let mut most = 0.0f64;
1505 let mut underruns = 0;
1506 for packet in 0..8000 * 60u64 {
1507 let arrives = packet as f64 / 8000.0;
1508 while chunk_time(chunks, chunk, device_rate) <= arrives {
1509 let plays = chunks as f64 * chunk as f64 / device_rate + latency;
1510 let after = plays + chunk as f64 / device_rate;
1511 buffer.device_pull(&mut played, Some((after * 1e9) as i64));
1512 if arrives > 40.0 {
1513 let (delay, _) = output.playout().unwrap();
1514 for (index, sample) in played.iter().enumerate() {
1515 let at = plays + index as f64 / device_rate - delay as f64 * 1e-9;
1516 let off = f64::from(sample - tone(at)) / (TAU as f64 * 100.0 * 0.5);
1518 most = most.max(off.abs());
1519 }
1520 }
1521 chunks += 1;
1522 }
1523 if packet == 8000 * 10 {
1524 underruns = buffer.underruns.load(Ordering::Relaxed);
1525 }
1526 let first = arrives + ahead;
1527 let samples: Vec<f32> = (0..6)
1528 .map(|index| tone(first + index as f64 / rate))
1529 .collect();
1530 let presented = Presented {
1531 first: (first * 1e9) as i64,
1532 offset: 0,
1533 };
1534 output.write(&samples, Some(presented));
1535 }
1536 let (delay, _) = output.playout().unwrap();
1537 let more = buffer.underruns.load(Ordering::Relaxed) - underruns;
1538 (delay, most, more)
1539 }
1540
1541 #[test]
1546 fn a_slow_device_plays_a_fixed_delay_after_presentation() {
1547 let (delay, most, underruns) = play_out(1024, 0.025, 0.0017);
1548 assert_eq!(delay, 55_000_000);
1549 assert!(most < 0.000_2, "{most}");
1550 assert_eq!(underruns, 0);
1551 }
1552
1553 #[test]
1556 fn early_frames_play_at_presentation_time() {
1557 let (delay, most, underruns) = play_out(256, 0.005, 0.1);
1558 assert_eq!(delay, 0);
1559 assert!(most < 0.000_2, "{most}");
1560 assert_eq!(underruns, 0);
1561 }
1562
1563 #[test]
1564 fn a_tone_fills_every_channel() {
1565 let mut input = Input::open(
1566 &Source::Tone {
1567 hertz: 1000.0,
1568 level: 0.5,
1569 },
1570 2,
1571 48_000,
1572 )
1573 .unwrap();
1574 let mut out = [0.0; 96];
1575 input.read(&mut out);
1576 assert!(out.iter().all(|sample| sample.abs() <= 0.5));
1577 assert!(
1578 out.as_chunks::<2>()
1579 .0
1580 .iter()
1581 .all(|frame| frame[0] == frame[1])
1582 );
1583 assert!(out.iter().any(|sample| sample.abs() > 0.4));
1584 }
1585
1586 #[test]
1590 fn a_stream_of_other_channels_takes_the_first() {
1591 let stereo = [0.1, 0.2, 0.3, 0.4];
1592 let mut eight = [9.0; 16];
1593 respread(&stereo, 2, &mut eight, 8);
1594 assert_eq!(
1595 eight,
1596 [
1597 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
1598 ]
1599 );
1600 let mut two = [9.0; 4];
1601 respread(&eight, 8, &mut two, 2);
1602 assert_eq!(two, stereo);
1603 }
1604}