Skip to main content

avb_stream/
audio.rs

1//! Where a talker's samples come from and where a listener's go: the
2//! computer's audio devices through cpal, a test tone, or nothing.
3//!
4//! A device runs on its own clock, not gPTP's, so the samples pass
5//! through a buffer and are resampled on the stream's side of it, by a
6//! ratio a slow controller steers to keep the buffer near its fill
7//! level: the device's drift, a few hundred parts per million at most,
8//! is taken up without a sample frame dropped or played twice.
9//!
10//! A listener's output steers by time instead, once it knows when the
11//! device plays: each sample then plays at its presentation time, or a
12//! fixed delay after it where the device's own latency is longer than
13//! the stream allows.
14
15use 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/// Where a talker's samples come from.
29#[derive(Debug, Clone, PartialEq)]
30pub enum Source {
31    Silence,
32    /// A sine on every channel, its level from 0 to 1.
33    Tone {
34        hertz: f32,
35        level: f32,
36    },
37    /// An audio input, by name or the default one, the stream's channels
38    /// taken from its channel `first_channel` on.
39    Device {
40        name: Option<String>,
41        first_channel: u16,
42    },
43    /// A buffer another part of the program fills as a device would, such
44    /// as a virtual audio device apps play into.
45    Shared(SharedBuffer),
46}
47
48/// A buffer another part of the program fills or drains as an audio
49/// device would, on its own clock: `channels` channels at `rate` hertz.
50#[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/// Where a listener's samples go.
74#[derive(Debug, Clone, PartialEq)]
75pub enum Sink {
76    /// Nowhere, though their level is still measured.
77    Discard,
78    /// An audio output, by name or the default one, the stream's channels
79    /// played on its channel `first_channel` on.
80    Device {
81        name: Option<String>,
82        first_channel: u16,
83    },
84    /// A buffer another part of the program drains as a device would, such
85    /// as a virtual audio device apps record from.
86    Shared(SharedBuffer),
87}
88
89/// Interleaved sample frames passed between an audio device's callback
90/// and a stream's thread.
91pub struct FrameBuffer {
92    held: Lock<Held>,
93    channels: usize,
94    /// The fill kept beyond the device's own chunks, in frames.
95    margin: usize,
96    /// Frames read while it was empty, and times frames were dropped as
97    /// it held four times what it keeps.
98    pub underruns: AtomicU64,
99    pub adjustments: AtomicU64,
100}
101
102struct Held {
103    samples: VecDeque<f32>,
104    /// Frames ever pushed on the stream's side: the oldest held is frame
105    /// `pushed` less those held.
106    pushed: u64,
107    /// Frames held beyond the usual most, for a listener's delay.
108    more: usize,
109    /// The fill right after the device's last chunk, which the controller
110    /// steers by.
111    sample: Option<DeviceSample>,
112}
113
114/// The buffer's fill right after one of the device's chunks.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct DeviceSample {
117    /// Counts the device's chunks, telling a new sample from the last.
118    pub chunks: u64,
119    pub level: usize,
120    pub chunk: usize,
121    /// Frames pushed by then, so the oldest held is frame `pushed -
122    /// level`.
123    pub pushed: u64,
124    /// When the oldest frame held plays, in monotonic nanoseconds, where
125    /// the device says.
126    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    /// Adds interleaved frames, keeping no more than four times the
151    /// margin and the device's chunk.
152    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    /// Fills `out` with the oldest frames, silence where there are none.
170    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    /// Frames ever pushed on the stream's side.
189    pub fn pushed(&self) -> u64 {
190        self.lock().pushed
191    }
192
193    /// Holds as many as `frames` more before dropping the oldest.
194    pub fn hold_more(&self, frames: usize) {
195        let mut held = self.lock();
196        held.more = held.more.max(frames);
197    }
198
199    /// Drops the oldest `frames`, as many as are held at most.
200    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    /// The device's side: adds one chunk, and notes the fill after it.
207    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    /// The device's side: takes one chunk, and notes the fill after it
214    /// and, where the device says, when the oldest frame left plays.
215    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    /// The fill right after the device's last chunk.
233    pub fn device_sample(&self) -> Option<DeviceSample> {
234        self.lock().sample
235    }
236
237    /// The frames held.
238    pub fn level(&self) -> usize {
239        self.lock().samples.len() / self.channels
240    }
241}
242
243/// The controller's gains, for each of the device's chunks: how much of
244/// each new fill its smoothed error takes, the ratio's change for an
245/// error of a whole chunk, and the integral's growth for it. Near
246/// critically damped, settling within 40 ppm in about 30 s of 1024-frame
247/// chunks, faster with smaller ones.
248const SMOOTHING: f64 = 0.02;
249const PROPORTIONAL: f64 = 0.0051;
250const INTEGRAL: f64 = 1e-5;
251/// The most the ratio strays from 1.
252const MOST_DRIFT: f64 = 0.002;
253
254/// Which side of the buffer the device is on.
255#[derive(Debug, Clone, Copy, PartialEq, Eq)]
256pub enum DeviceSide {
257    /// An input: the device pushes, the stream pulls.
258    Pushes,
259    /// An output: the stream pushes, the device pulls.
260    Pulls,
261}
262
263/// Resamples interleaved frames from one clock to another close to it, by
264/// cubic interpolation between the input frames, at a ratio steered from
265/// the buffer's fill after each of the device's chunks.
266pub struct Drift {
267    channels: usize,
268    side: DeviceSide,
269    /// Input frames for each output frame were both clocks exact: 1
270    /// when the device runs at the stream's rate, 2 for a 96 kHz stream
271    /// to a 48 kHz device.
272    nominal: f64,
273    /// Input frames: the one before the current position, then those
274    /// after.
275    held: VecDeque<f32>,
276    /// Where the next output frame lies past the second held frame, from
277    /// 0 to 1.
278    position: f64,
279    /// Input frames for each output frame.
280    ratio: f64,
281    /// The last device chunk steered by, the smoothed error and the
282    /// integral.
283    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    /// Input frames for each output frame now.
304    pub fn ratio(&self) -> f64 {
305        self.ratio
306    }
307
308    /// How far the device's clock runs from the stream's, in parts per
309    /// million, as the ratio follows it.
310    pub fn device_ppm(&self) -> i32 {
311        let relative = self.ratio / self.nominal;
312        let ppm = match self.side {
313            // A fast input device gives more frames than the stream takes.
314            DeviceSide::Pushes => relative - 1.0,
315            // A slow output device takes fewer than the stream gives.
316            DeviceSide::Pulls => 1.0 / relative - 1.0,
317        };
318        (ppm * 1e6).round() as i32
319    }
320
321    /// Steers the ratio from the fill after the device's last chunk, once
322    /// for each chunk: a fuller buffer than kept takes more input frames
323    /// for each output frame, whichever side the device is on.
324    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    /// The device's last chunk, when not yet steered by.
332    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    /// The fill kept right after a chunk: after an input's the buffer
342    /// holds it on top of what is kept; after an output's, just what is
343    /// kept.
344    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    /// Steers by `excess` frames held beyond what is wanted, after a
352    /// device chunk of `chunk` frames.
353    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    /// Input frames taken but not yet made into output, counted from
368    /// where the next output frame lies.
369    fn pending(&self) -> f64 {
370        (self.held_frames() as f64 - 1.0 - self.position).max(0.0)
371    }
372
373    /// The input frames to add before `frames` output frames can be made.
374    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    /// Makes output frames while there are input frames enough, into
387    /// `out`, up to `most` of them.
388    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                // Catmull-Rom between `from` and `to`.
398                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            // At four times the device's rate or more, a step can pass
406            // frames yet to come: the rest is passed as they do.
407            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
416/// A thread holding an open cpal stream until dropped.
417struct 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
436/// The input or output device with `name`, or the default one.
437fn 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
465/// The rate to open a device at: the stream's when the device takes it,
466/// else the device's own, which the resampler then converts from or to.
467fn 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
494/// The names of the audio devices: inputs, then outputs.
495pub 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
509/// Opens a device on a thread of its own, which `build` gives a stream to
510/// play until the thread is told to stop.
511fn 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                // The chunk's first frame plays the device's latency from
601                // now, the frame after its last a chunk later.
602                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
627/// The stream's samples from its source.
628pub struct Input {
629    kind: InputKind,
630    channels: usize,
631    /// Its frames on their way to a stream of other channels.
632    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        /// Input frames on their way to the resampler, and its output.
646        taken: Vec<f32>,
647        made: Vec<f32>,
648        _thread: Option<DeviceThread>,
649    },
650}
651
652impl Input {
653    /// Opens `source` for `channels` channels at `rate` hertz.
654    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                // 10 ms kept beyond the device's chunks.
669                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                // What it held from before goes, so the stream starts from
714                // now rather than behind.
715                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    /// How far the device's clock runs from the stream's, in parts per
737    /// million, as the resampler follows it.
738    pub fn drift_ppm(&self) -> i32 {
739        match &self.kind {
740            InputKind::Device { drift, .. } => drift.device_ppm(),
741            _ => 0,
742        }
743    }
744
745    /// Times frames were dropped as the device ran too far ahead, and
746    /// reads while it had none.
747    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    /// Fills `out` with interleaved frames.
758    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    /// Fills `out` with interleaved frames of `channels`, as a stream of
788    /// other channels than its source takes them: the source's from the
789    /// first, silence past them, and those past `channels` left out.
790    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    /// Leaves out the next `frames` frames, as for frames too late to
804    /// send, so those after come when they would have.
805    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            // The device's frames those would have been made from.
813            InputKind::Device { buffer, drift, .. } => {
814                buffer.drop_oldest((frames as f64 * drift.ratio()).round() as usize);
815            }
816        }
817    }
818}
819
820/// `samples`, frames of `channels` interleaved, into `out`'s frames of
821/// `out_channels`: each channel where it was, silence in those past
822/// `channels`, and those past `out_channels` left out.
823fn 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/// When the samples a listener writes are due.
836#[derive(Debug, Clone, Copy, PartialEq, Eq)]
837pub struct Presented {
838    /// The first sample's presentation time, in gPTP nanoseconds.
839    pub first: i64,
840    /// gPTP time less monotonic time, in nanoseconds.
841    pub offset: i64,
842}
843
844/// How long an output watches its device before choosing the delay.
845const CHOOSING: i64 = 2_000_000_000;
846/// The delay comes in steps of this, and grows by one each time the
847/// device then finds nothing to play.
848const DELAY_STEP: i64 = 1_000_000;
849const MOST_DELAY: i64 = 500_000_000;
850/// Frames further ahead of the device than this say the clocks disagree,
851/// and the output steers by the fill alone.
852const MOST_AHEAD: i64 = 500_000_000;
853
854/// The resampler toward the device, and when its frames play.
855struct Playing {
856    drift: Drift,
857    made: Vec<f32>,
858    /// The presentation time of the next input frame, and gPTP time less
859    /// monotonic time, in nanoseconds.
860    next_in: Option<i64>,
861    offset: Option<i64>,
862    /// Device frame `.0` presents at gPTP nanoseconds `.1`.
863    anchor: Option<(u64, i64)>,
864    /// How long after its presentation time each frame plays, once
865    /// chosen, and how far from that the last chunk played.
866    delay: Option<i64>,
867    error: i64,
868    /// While choosing: when it started, in monotonic nanoseconds, and the
869    /// lateness at the kept fill, summed, with the times it was seen.
870    choosing: Option<(i64, f64, u32)>,
871    /// The device's underruns when the delay was last set.
872    underruns: u64,
873}
874
875/// The stream's samples to their sink.
876pub struct Output {
877    buffer: Option<Arc<FrameBuffer>>,
878    _thread: Option<DeviceThread>,
879    playing: Lock<Playing>,
880    /// Input frames a second.
881    rate: u32,
882    /// The loudest sample since the last look, as f32 bits.
883    peak: AtomicU32,
884}
885
886impl Output {
887    /// Opens `sink` for `channels` channels at `rate` hertz.
888    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    /// Takes interleaved frames, and when they are due where the stream
976    /// says.
977    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            // The next frame the resampler makes lies the frames it holds
1003            // back before the next to come.
1004            let made = *next - (playing.drift.pending() * frame).round() as i64;
1005            playing.anchor = Some((buffer.pushed(), made));
1006        }
1007    }
1008
1009    /// Steers by when the frames play, once the device and the stream say
1010    /// when, else by the buffer's fill.
1011    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        // How late the oldest frame held plays.
1020        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            // Steered by the fill while choosing, noting how late frames
1030            // play at the fill kept: the earliest that is safe.
1031            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    /// Plays each frame `delay` after its presentation time from now on,
1056    /// moving at once by the `excess` frames held beyond that.
1057    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            // Silence in front of what comes next, which then presents
1067            // that much later than the frames before it.
1068            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    /// How long after its presentation time each sample plays, once the
1077    /// output knows, and how far from that the last chunk played, in
1078    /// nanoseconds.
1079    pub fn playout(&self) -> Option<(i64, i64)> {
1080        let playing = self.lock();
1081        playing.delay.map(|delay| (delay, playing.error))
1082    }
1083
1084    /// How far the device's clock runs from the stream's, in parts per
1085    /// million, as the resampler follows it.
1086    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    /// Times the device found nothing to play.
1094    pub fn underruns(&self) -> u64 {
1095        self.buffer
1096            .as_ref()
1097            .map_or(0, |buffer| buffer.underruns.load(Ordering::Relaxed))
1098    }
1099
1100    /// The loudest sample since the last call, from 0 to 1.
1101    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        // Past four times the margin and the chunk, the oldest go.
1131        buffer.push(&[3.0; 200]);
1132        assert_eq!(buffer.level(), 4 * (10 + 3));
1133        assert!(buffer.adjustments.load(Ordering::Relaxed) > 0);
1134        // Empty: silence, counted.
1135        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    /// A sine at `hertz` sampled at `rate`, from sample `start` on.
1142    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    /// When the device's `index`th chunk comes, at `rate`: on time give
1149    /// or take up to 2% of a chunk.
1150    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    /// A device 120 ppm fast feeding a talker's stream, in chunks of 1024
1157    /// frames that come a little early or late, for a simulated two
1158    /// minutes: the ratio settles on the drift, nothing runs short or
1159    /// over once started, and the sine comes out whole.
1160    #[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        // No frame is missing: no step is bigger than a 1 kHz sine at
1197        // half scale ever takes between two samples.
1198        let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1199        assert!(most < 0.07, "{most}");
1200    }
1201
1202    /// A slow device playing a listener's stream in chunks of 1024
1203    /// frames, the other side of the buffer: it settles too, and never
1204    /// finds the buffer empty once playing.
1205    #[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    /// A 48 kHz device 50 ppm fast feeding a 96 kHz stream: the ratio
1241    /// settles on half the device's frames for each of the stream's,
1242    /// the drift reads as the device's own, and the sine comes out whole
1243    /// at twice the rate.
1244    #[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        // A 1 kHz sine at half scale steps at most 0.033 at 96 kHz.
1280        let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1281        assert!(most < 0.04, "{most}");
1282    }
1283
1284    /// A 192 kHz stream to a 48 kHz device, steered a little above four of
1285    /// its frames for each of the device's, as a listener plays it: each
1286    /// step passes as many as five input frames, never more than it holds.
1287    #[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        // 1.92 million input frames make about 480 thousand.
1315        let expected = 8000.0 * 10.0 * 24.0 / drift.ratio;
1316        assert!((made as f64 - expected).abs() < 4.0, "{made}");
1317        // A 1 kHz sine at half scale steps at most 0.066 at 48 kHz.
1318        assert!(most < 0.07, "{most}");
1319    }
1320
1321    /// A listener's output to a device 50 ppm slow that plays each chunk
1322    /// of `chunk` frames `latency` after its callback, for frames arriving
1323    /// `ahead` before their presentation time, for a simulated minute: the
1324    /// delay it chooses, and the most any sample in the last 20 s played
1325    /// away from that delay after its presentation time, in seconds.
1326    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                        // How far in time the sample is from the one due.
1347                        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    /// Frames 1.7 ms ahead to a device 25 ms behind its callbacks of 1024
1372    /// frames: too late for presentation time, so each plays the same
1373    /// whole milliseconds after it, the device's latency, a chunk and
1374    /// the margin less the 1.7 ms.
1375    #[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    /// Frames 100 ms ahead to a device 5 ms behind its callbacks of 256
1384    /// frames: each plays at its presentation time.
1385    #[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    /// Two channels go into an eight-channel stream as its first two,
1417    /// with silence in the rest, and eight into a stereo one as their
1418    /// first two.
1419    #[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}