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, Mutex, PoisonError, mpsc};
20use std::thread::JoinHandle;
21use std::time::Duration;
22
23use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
24use cpal::{FromSample, SizedSample};
25
26/// Where a talker's samples come from.
27#[derive(Debug, Clone, PartialEq)]
28pub enum Source {
29    Silence,
30    /// A sine on every channel, its level from 0 to 1.
31    Tone {
32        hertz: f32,
33        level: f32,
34    },
35    /// An audio input, by name or the default one, the stream's channels
36    /// taken from its channel `first_channel` on.
37    Device {
38        name: Option<String>,
39        first_channel: u16,
40    },
41    /// A buffer another part of the program fills as a device would, such
42    /// as a virtual audio device apps play into.
43    Shared(SharedBuffer),
44}
45
46/// A buffer another part of the program fills or drains as an audio
47/// device would, on its own clock: `channels` channels at `rate` hertz.
48#[derive(Clone)]
49pub struct SharedBuffer {
50    pub buffer: Arc<FrameBuffer>,
51    pub channels: u16,
52    pub rate: u32,
53}
54
55impl PartialEq for SharedBuffer {
56    fn eq(&self, other: &Self) -> bool {
57        Arc::ptr_eq(&self.buffer, &other.buffer)
58    }
59}
60
61impl std::fmt::Debug for SharedBuffer {
62    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        write!(
64            formatter,
65            "SharedBuffer({} channels at {} Hz)",
66            self.channels, self.rate
67        )
68    }
69}
70
71/// Where a listener's samples go.
72#[derive(Debug, Clone, PartialEq)]
73pub enum Sink {
74    /// Nowhere, though their level is still measured.
75    Discard,
76    /// An audio output, by name or the default one, the stream's channels
77    /// played on its channel `first_channel` on.
78    Device {
79        name: Option<String>,
80        first_channel: u16,
81    },
82    /// A buffer another part of the program drains as a device would, such
83    /// as a virtual audio device apps record from.
84    Shared(SharedBuffer),
85}
86
87/// Interleaved sample frames passed between an audio device's callback
88/// and a stream's thread.
89pub struct FrameBuffer {
90    held: Mutex<Held>,
91    channels: usize,
92    /// The fill kept beyond the device's own chunks, in frames.
93    margin: usize,
94    /// Frames read while it was empty, and times frames were dropped as
95    /// it held four times what it keeps.
96    pub underruns: AtomicU64,
97    pub adjustments: AtomicU64,
98}
99
100struct Held {
101    samples: VecDeque<f32>,
102    /// Frames ever pushed on the stream's side: the oldest held is frame
103    /// `pushed` less those held.
104    pushed: u64,
105    /// Frames held beyond the usual most, for a listener's delay.
106    more: usize,
107    /// The fill right after the device's last chunk, which the controller
108    /// steers by.
109    sample: Option<DeviceSample>,
110}
111
112/// The buffer's fill right after one of the device's chunks.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct DeviceSample {
115    /// Counts the device's chunks, telling a new sample from the last.
116    pub chunks: u64,
117    pub level: usize,
118    pub chunk: usize,
119    /// Frames pushed by then, so the oldest held is frame `pushed -
120    /// level`.
121    pub pushed: u64,
122    /// When the oldest frame held plays, in monotonic nanoseconds, where
123    /// the device says.
124    pub plays_at: Option<i64>,
125}
126
127impl FrameBuffer {
128    pub fn new(channels: u16, margin: usize) -> Self {
129        let channels = usize::from(channels).max(1);
130        FrameBuffer {
131            held: Mutex::new(Held {
132                samples: VecDeque::with_capacity(4 * margin * channels),
133                pushed: 0,
134                more: 0,
135                sample: None,
136            }),
137            channels,
138            margin: margin.max(1),
139            underruns: AtomicU64::new(0),
140            adjustments: AtomicU64::new(0),
141        }
142    }
143
144    fn lock(&self) -> std::sync::MutexGuard<'_, Held> {
145        self.held.lock().unwrap_or_else(PoisonError::into_inner)
146    }
147
148    /// Adds interleaved frames, keeping no more than four times the
149    /// margin and the device's chunk.
150    pub fn push(&self, samples: &[f32]) {
151        let mut held = self.lock();
152        self.push_into(&mut held, samples);
153    }
154
155    fn push_into(&self, held: &mut Held, samples: &[f32]) {
156        held.samples.extend(samples);
157        held.pushed += (samples.len() / self.channels) as u64;
158        let chunk = held.sample.map_or(0, |sample| sample.chunk);
159        let most = (4 * (self.margin + chunk) + held.more) * self.channels;
160        if held.samples.len() > most {
161            let extra = held.samples.len() - most;
162            held.samples.drain(..extra - extra % self.channels);
163            self.adjustments.fetch_add(1, Ordering::Relaxed);
164        }
165    }
166
167    /// Fills `out` with the oldest frames, silence where there are none.
168    pub fn pull(&self, out: &mut [f32]) {
169        let mut held = self.lock();
170        self.pull_from(&mut held, out);
171    }
172
173    fn pull_from(&self, held: &mut Held, out: &mut [f32]) {
174        let mut short = false;
175        for slot in out.iter_mut() {
176            *slot = held.samples.pop_front().unwrap_or_else(|| {
177                short = true;
178                0.0
179            });
180        }
181        if short {
182            self.underruns.fetch_add(1, Ordering::Relaxed);
183        }
184    }
185
186    /// Frames ever pushed on the stream's side.
187    pub fn pushed(&self) -> u64 {
188        self.lock().pushed
189    }
190
191    /// Holds as many as `frames` more before dropping the oldest.
192    pub fn hold_more(&self, frames: usize) {
193        let mut held = self.lock();
194        held.more = held.more.max(frames);
195    }
196
197    /// Drops the oldest `frames`, as many as are held at most.
198    pub fn drop_oldest(&self, frames: usize) {
199        let mut held = self.lock();
200        let samples = (frames * self.channels).min(held.samples.len());
201        held.samples.drain(..samples);
202    }
203
204    /// The device's side: adds one chunk, and notes the fill after it.
205    pub fn device_push(&self, samples: &[f32]) {
206        let mut held = self.lock();
207        self.push_into(&mut held, samples);
208        self.note(&mut held, samples.len(), None);
209    }
210
211    /// The device's side: takes one chunk, and notes the fill after it
212    /// and, where the device says, when the oldest frame left plays.
213    pub fn device_pull(&self, out: &mut [f32], plays_at: Option<i64>) {
214        let mut held = self.lock();
215        self.pull_from(&mut held, out);
216        self.note(&mut held, out.len(), plays_at);
217    }
218
219    fn note(&self, held: &mut Held, samples: usize, plays_at: Option<i64>) {
220        let chunks = held.sample.map_or(1, |sample| sample.chunks + 1);
221        held.sample = Some(DeviceSample {
222            chunks,
223            level: held.samples.len() / self.channels,
224            chunk: samples / self.channels,
225            pushed: held.pushed,
226            plays_at,
227        });
228    }
229
230    /// The fill right after the device's last chunk.
231    pub fn device_sample(&self) -> Option<DeviceSample> {
232        self.lock().sample
233    }
234
235    /// The frames held.
236    pub fn level(&self) -> usize {
237        self.lock().samples.len() / self.channels
238    }
239}
240
241/// The controller's gains, for each of the device's chunks: how much of
242/// each new fill its smoothed error takes, the ratio's change for an
243/// error of a whole chunk, and the integral's growth for it. Near
244/// critically damped, settling within 40 ppm in about 30 s of 1024-frame
245/// chunks, faster with smaller ones.
246const SMOOTHING: f64 = 0.02;
247const PROPORTIONAL: f64 = 0.0051;
248const INTEGRAL: f64 = 1e-5;
249/// The most the ratio strays from 1.
250const MOST_DRIFT: f64 = 0.002;
251
252/// Which side of the buffer the device is on.
253#[derive(Debug, Clone, Copy, PartialEq, Eq)]
254pub enum DeviceSide {
255    /// An input: the device pushes, the stream pulls.
256    Pushes,
257    /// An output: the stream pushes, the device pulls.
258    Pulls,
259}
260
261/// Resamples interleaved frames from one clock to another close to it, by
262/// cubic interpolation between the input frames, at a ratio steered from
263/// the buffer's fill after each of the device's chunks.
264pub struct Drift {
265    channels: usize,
266    side: DeviceSide,
267    /// Input frames for each output frame were both clocks exact: 1
268    /// when the device runs at the stream's rate, 2 for a 96 kHz stream
269    /// to a 48 kHz device.
270    nominal: f64,
271    /// Input frames: the one before the current position, then those
272    /// after.
273    held: VecDeque<f32>,
274    /// Where the next output frame lies past the second held frame, from
275    /// 0 to 1.
276    position: f64,
277    /// Input frames for each output frame.
278    ratio: f64,
279    /// The last device chunk steered by, the smoothed error and the
280    /// integral.
281    chunks: u64,
282    error: Option<f64>,
283    integral: f64,
284}
285
286impl Drift {
287    pub fn new(channels: u16, side: DeviceSide, nominal: f64) -> Self {
288        Drift {
289            channels: usize::from(channels).max(1),
290            side,
291            nominal,
292            held: VecDeque::new(),
293            position: 0.0,
294            ratio: nominal,
295            chunks: 0,
296            error: None,
297            integral: 0.0,
298        }
299    }
300
301    /// Input frames for each output frame now.
302    pub fn ratio(&self) -> f64 {
303        self.ratio
304    }
305
306    /// How far the device's clock runs from the stream's, in parts per
307    /// million, as the ratio follows it.
308    pub fn device_ppm(&self) -> i32 {
309        let relative = self.ratio / self.nominal;
310        let ppm = match self.side {
311            // A fast input device gives more frames than the stream takes.
312            DeviceSide::Pushes => relative - 1.0,
313            // A slow output device takes fewer than the stream gives.
314            DeviceSide::Pulls => 1.0 / relative - 1.0,
315        };
316        (ppm * 1e6).round() as i32
317    }
318
319    /// Steers the ratio from the fill after the device's last chunk, once
320    /// for each chunk: a fuller buffer than kept takes more input frames
321    /// for each output frame, whichever side the device is on.
322    pub fn steer(&mut self, buffer: &FrameBuffer) {
323        if let Some(sample) = self.new_sample(buffer) {
324            let excess = sample.level as f64 - self.kept(buffer, &sample) as f64;
325            self.follow(excess, sample.chunk);
326        }
327    }
328
329    /// The device's last chunk, when not yet steered by.
330    fn new_sample(&mut self, buffer: &FrameBuffer) -> Option<DeviceSample> {
331        let sample = buffer.device_sample()?;
332        if sample.chunks == self.chunks {
333            return None;
334        }
335        self.chunks = sample.chunks;
336        Some(sample)
337    }
338
339    /// The fill kept right after a chunk: after an input's the buffer
340    /// holds it on top of what is kept; after an output's, just what is
341    /// kept.
342    fn kept(&self, buffer: &FrameBuffer, sample: &DeviceSample) -> usize {
343        match self.side {
344            DeviceSide::Pushes => buffer.margin + sample.chunk,
345            DeviceSide::Pulls => buffer.margin,
346        }
347    }
348
349    /// Steers by `excess` frames held beyond what is wanted, after a
350    /// device chunk of `chunk` frames.
351    fn follow(&mut self, excess: f64, chunk: usize) {
352        let error = excess / chunk.max(1) as f64;
353        let smoothed = self.error.get_or_insert(error);
354        *smoothed += SMOOTHING * (error - *smoothed);
355        self.integral = (self.integral + INTEGRAL * *smoothed).clamp(-MOST_DRIFT, MOST_DRIFT);
356        self.ratio = self.nominal
357            * (1.0 + PROPORTIONAL * *smoothed + self.integral)
358                .clamp(1.0 - MOST_DRIFT, 1.0 + MOST_DRIFT);
359    }
360
361    fn held_frames(&self) -> usize {
362        self.held.len() / self.channels
363    }
364
365    /// Input frames taken but not yet made into output, counted from
366    /// where the next output frame lies.
367    fn pending(&self) -> f64 {
368        (self.held_frames() as f64 - 1.0 - self.position).max(0.0)
369    }
370
371    /// The input frames to add before `frames` output frames can be made.
372    pub fn wanted(&self, frames: usize) -> usize {
373        if frames == 0 {
374            return 0;
375        }
376        let last = self.position + (frames - 1) as f64 * self.ratio;
377        (last as usize + 4).saturating_sub(self.held_frames())
378    }
379
380    pub fn push(&mut self, input: &[f32]) {
381        self.held.extend(input);
382    }
383
384    /// Makes output frames while there are input frames enough, into
385    /// `out`, up to `most` of them.
386    pub fn make(&mut self, out: &mut Vec<f32>, most: usize) {
387        let channels = self.channels;
388        let mut made = 0;
389        while made < most && self.position as usize + 4 <= self.held_frames() {
390            let base = self.position as usize;
391            let t = (self.position - base as f64) as f32;
392            for channel in 0..channels {
393                let at = |frame: usize| self.held[(base + frame) * channels + channel];
394                let (before, from, to, after) = (at(0), at(1), at(2), at(3));
395                // Catmull-Rom between `from` and `to`.
396                let a = -0.5 * before + 1.5 * from - 1.5 * to + 0.5 * after;
397                let b = before - 2.5 * from + 2.0 * to - 0.5 * after;
398                let c = -0.5 * before + 0.5 * to;
399                out.push(((a * t + b) * t + c) * t + from);
400            }
401            made += 1;
402            self.position += self.ratio;
403            let passed = self.position as usize;
404            if passed > 0 {
405                self.held.drain(..passed * channels);
406                self.position -= passed as f64;
407            }
408        }
409    }
410}
411
412/// A thread holding an open cpal stream until dropped.
413struct DeviceThread {
414    stop: Arc<AtomicBool>,
415    handle: Option<JoinHandle<()>>,
416}
417
418impl Drop for DeviceThread {
419    fn drop(&mut self) {
420        self.stop.store(true, Ordering::Relaxed);
421        if let Some(handle) = self.handle.take() {
422            handle.thread().unpark();
423            let _ = handle.join();
424        }
425    }
426}
427
428fn device_error(error: impl std::fmt::Display) -> io::Error {
429    io::Error::other(error.to_string())
430}
431
432/// The input or output device with `name`, or the default one.
433fn find_device(name: Option<&str>, input: bool) -> io::Result<cpal::Device> {
434    let host = cpal::default_host();
435    let found = match name {
436        Some(name) => {
437            let devices = if input {
438                host.input_devices()
439            } else {
440                host.output_devices()
441            }
442            .map_err(device_error)?;
443            devices
444                .into_iter()
445                .find(|device| device.description().is_ok_and(|about| about.name() == name))
446        }
447        None if input => host.default_input_device(),
448        None => host.default_output_device(),
449    };
450    found.ok_or_else(|| {
451        io::Error::new(
452            io::ErrorKind::NotFound,
453            match name {
454                Some(name) => format!("no audio device named {name}"),
455                None => "no default audio device".to_owned(),
456            },
457        )
458    })
459}
460
461/// The rate to open a device at: the stream's when the device takes it,
462/// else the device's own, which the resampler then converts from or to.
463fn device_rate(device: &cpal::Device, input: bool, wanted: u32) -> io::Result<u32> {
464    let default = if input {
465        device.default_input_config()
466    } else {
467        device.default_output_config()
468    }
469    .map_err(device_error)?;
470    if default.sample_rate() == wanted {
471        return Ok(wanted);
472    }
473    let ranges: Vec<cpal::SupportedStreamConfigRange> = if input {
474        device.supported_input_configs().map(Iterator::collect)
475    } else {
476        device.supported_output_configs().map(Iterator::collect)
477    }
478    .unwrap_or_default();
479    let supported = ranges.iter().any(|range| {
480        range.channels() == default.channels()
481            && (range.min_sample_rate()..=range.max_sample_rate()).contains(&wanted)
482    });
483    Ok(if supported {
484        wanted
485    } else {
486        default.sample_rate()
487    })
488}
489
490/// The names of the audio devices: inputs, then outputs.
491pub fn device_names() -> (Vec<String>, Vec<String>) {
492    let host = cpal::default_host();
493    let named = |device: cpal::Device| Some(device.description().ok()?.name().to_owned());
494    let inputs = host
495        .input_devices()
496        .map(|devices| devices.filter_map(named).collect())
497        .unwrap_or_default();
498    let outputs = host
499        .output_devices()
500        .map(|devices| devices.filter_map(named).collect())
501        .unwrap_or_default();
502    (inputs, outputs)
503}
504
505/// Opens a device on a thread of its own, which `build` gives a stream to
506/// play until the thread is told to stop.
507fn device_thread(
508    name: String,
509    build: impl FnOnce() -> io::Result<cpal::Stream> + Send + 'static,
510) -> io::Result<DeviceThread> {
511    let stop = Arc::new(AtomicBool::new(false));
512    let stopping = stop.clone();
513    let (opened, started) = mpsc::channel();
514    let handle = std::thread::Builder::new().name(name).spawn(move || {
515        let stream = match build().and_then(|stream| {
516            stream.play().map_err(device_error)?;
517            Ok(stream)
518        }) {
519            Ok(stream) => {
520                let _ = opened.send(Ok(()));
521                stream
522            }
523            Err(error) => {
524                let _ = opened.send(Err(error));
525                return;
526            }
527        };
528        while !stopping.load(Ordering::Relaxed) {
529            std::thread::park_timeout(Duration::from_millis(200));
530        }
531        drop(stream);
532    })?;
533    started
534        .recv()
535        .unwrap_or_else(|_| Err(io::Error::other("the audio thread stopped")))?;
536    Ok(DeviceThread {
537        stop,
538        handle: Some(handle),
539    })
540}
541
542fn input_stream<T>(
543    device: &cpal::Device,
544    config: cpal::StreamConfig,
545    channels: usize,
546    first: usize,
547    buffer: Arc<FrameBuffer>,
548) -> io::Result<cpal::Stream>
549where
550    T: SizedSample,
551    f32: FromSample<T>,
552{
553    let device_channels = usize::from(config.channels).max(1);
554    let mut frames = Vec::new();
555    device
556        .build_input_stream(
557            config,
558            move |data: &[T], _: &cpal::InputCallbackInfo| {
559                frames.clear();
560                for frame in data.chunks_exact(device_channels) {
561                    for channel in 0..channels {
562                        frames.push(
563                            frame
564                                .get(first + channel)
565                                .map_or(0.0, |sample| sample.to_sample::<f32>()),
566                        );
567                    }
568                }
569                buffer.device_push(&frames);
570            },
571            |_| {},
572            None,
573        )
574        .map_err(device_error)
575}
576
577fn output_stream<T>(
578    device: &cpal::Device,
579    config: cpal::StreamConfig,
580    channels: usize,
581    first: usize,
582    buffer: Arc<FrameBuffer>,
583) -> io::Result<cpal::Stream>
584where
585    T: SizedSample + FromSample<f32>,
586{
587    let device_channels = usize::from(config.channels).max(1);
588    let rate = i64::from(config.sample_rate.max(1));
589    let mut frames = Vec::new();
590    device
591        .build_output_stream(
592            config,
593            move |data: &mut [T], info: &cpal::OutputCallbackInfo| {
594                let count = data.len() / device_channels;
595                frames.resize(count * channels, 0.0);
596                // The chunk's first frame plays the device's latency from
597                // now, the frame after its last a chunk later.
598                let stamp = info.timestamp();
599                let latency = stamp.playback.duration_since(stamp.callback);
600                let plays_at = avb_net::clock::monotonic_now() + latency;
601                let after = plays_at.as_nanos() as i64 + count as i64 * 1_000_000_000 / rate;
602                buffer.device_pull(&mut frames, Some(after));
603                for (frame, samples) in data
604                    .chunks_exact_mut(device_channels)
605                    .zip(frames.chunks_exact(channels.max(1)))
606                {
607                    for (channel, slot) in frame.iter_mut().enumerate() {
608                        let sample = channel
609                            .checked_sub(first)
610                            .and_then(|stream| samples.get(stream))
611                            .copied()
612                            .unwrap_or(0.0);
613                        *slot = T::from_sample(sample);
614                    }
615                }
616            },
617            |_| {},
618            None,
619        )
620        .map_err(device_error)
621}
622
623/// The stream's samples from its source.
624pub struct Input {
625    kind: InputKind,
626    channels: usize,
627    /// Its frames on their way to a stream of other channels.
628    spread: Vec<f32>,
629}
630
631enum InputKind {
632    Silence,
633    Tone {
634        phase: f32,
635        step: f32,
636        level: f32,
637    },
638    Device {
639        buffer: Arc<FrameBuffer>,
640        drift: Drift,
641        /// Input frames on their way to the resampler, and its output.
642        taken: Vec<f32>,
643        made: Vec<f32>,
644        _thread: Option<DeviceThread>,
645    },
646}
647
648impl Input {
649    /// Opens `source` for `channels` channels at `rate` hertz.
650    pub fn open(source: &Source, channels: u16, rate: u32) -> io::Result<Self> {
651        let kind = match source {
652            Source::Silence => InputKind::Silence,
653            Source::Tone { hertz, level } => InputKind::Tone {
654                phase: 0.0,
655                step: TAU * hertz / rate as f32,
656                level: level.clamp(0.0, 1.0),
657            },
658            Source::Device {
659                name,
660                first_channel,
661            } => {
662                let device = find_device(name.as_deref(), true)?;
663                let device_rate = device_rate(&device, true, rate)?;
664                // 10 ms kept beyond the device's chunks.
665                let margin = device_rate as usize / 100;
666                let buffer = Arc::new(FrameBuffer::new(channels, margin));
667                let filling = buffer.clone();
668                let first = usize::from(*first_channel);
669                let wanted = usize::from(channels);
670                let thread = device_thread("audio input".into(), move || {
671                    let supported = device.default_input_config().map_err(device_error)?;
672                    let mut config = supported.config();
673                    config.sample_rate = device_rate;
674                    match supported.sample_format() {
675                        cpal::SampleFormat::F32 => {
676                            input_stream::<f32>(&device, config, wanted, first, filling)
677                        }
678                        cpal::SampleFormat::I16 => {
679                            input_stream::<i16>(&device, config, wanted, first, filling)
680                        }
681                        cpal::SampleFormat::I32 => {
682                            input_stream::<i32>(&device, config, wanted, first, filling)
683                        }
684                        other => Err(io::Error::new(
685                            io::ErrorKind::Unsupported,
686                            format!("samples in {other}"),
687                        )),
688                    }
689                })?;
690                InputKind::Device {
691                    buffer,
692                    drift: Drift::new(
693                        channels,
694                        DeviceSide::Pushes,
695                        f64::from(device_rate) / f64::from(rate),
696                    ),
697                    taken: Vec::new(),
698                    made: Vec::new(),
699                    _thread: Some(thread),
700                }
701            }
702            Source::Shared(shared) => {
703                if shared.channels != channels {
704                    return Err(io::Error::new(
705                        io::ErrorKind::InvalidInput,
706                        "a shared buffer of other channels than the stream's",
707                    ));
708                }
709                // What it held from before goes, so the stream starts from
710                // now rather than behind.
711                shared.buffer.drop_oldest(shared.buffer.level());
712                InputKind::Device {
713                    buffer: shared.buffer.clone(),
714                    drift: Drift::new(
715                        channels,
716                        DeviceSide::Pushes,
717                        f64::from(shared.rate) / f64::from(rate),
718                    ),
719                    taken: Vec::new(),
720                    made: Vec::new(),
721                    _thread: None,
722                }
723            }
724        };
725        Ok(Input {
726            kind,
727            channels: usize::from(channels),
728            spread: Vec::new(),
729        })
730    }
731
732    /// How far the device's clock runs from the stream's, in parts per
733    /// million, as the resampler follows it.
734    pub fn drift_ppm(&self) -> i32 {
735        match &self.kind {
736            InputKind::Device { drift, .. } => drift.device_ppm(),
737            _ => 0,
738        }
739    }
740
741    /// Times frames were dropped as the device ran too far ahead, and
742    /// reads while it had none.
743    pub fn counts(&self) -> (u64, u64) {
744        match &self.kind {
745            InputKind::Device { buffer, .. } => (
746                buffer.adjustments.load(Ordering::Relaxed),
747                buffer.underruns.load(Ordering::Relaxed),
748            ),
749            _ => (0, 0),
750        }
751    }
752
753    /// Fills `out` with interleaved frames.
754    pub fn read(&mut self, out: &mut [f32]) {
755        match &mut self.kind {
756            InputKind::Silence => out.fill(0.0),
757            InputKind::Tone { phase, step, level } => {
758                for frame in out.chunks_exact_mut(self.channels.max(1)) {
759                    frame.fill(phase.sin() * *level);
760                    *phase = (*phase + *step) % TAU;
761                }
762            }
763            InputKind::Device {
764                buffer,
765                drift,
766                taken,
767                made,
768                ..
769            } => {
770                let frames = out.len() / self.channels.max(1);
771                drift.steer(buffer);
772                taken.resize(drift.wanted(frames) * self.channels, 0.0);
773                buffer.pull(taken);
774                drift.push(taken);
775                made.clear();
776                drift.make(made, frames);
777                out.fill(0.0);
778                out[..made.len()].copy_from_slice(made);
779            }
780        }
781    }
782
783    /// Fills `out` with interleaved frames of `channels`, as a stream of
784    /// other channels than its source takes them: the source's from the
785    /// first, silence past them, and those past `channels` left out.
786    pub fn read_as(&mut self, out: &mut [f32], channels: usize) {
787        let channels = channels.max(1);
788        if channels == self.channels.max(1) {
789            self.read(out);
790            return;
791        }
792        let mut spread = std::mem::take(&mut self.spread);
793        spread.resize(out.len() / channels * self.channels.max(1), 0.0);
794        self.read(&mut spread);
795        respread(&spread, self.channels, out, channels);
796        self.spread = spread;
797    }
798}
799
800/// `samples`, frames of `channels` interleaved, into `out`'s frames of
801/// `out_channels`: each channel where it was, silence in those past
802/// `channels`, and those past `out_channels` left out.
803fn respread(samples: &[f32], channels: usize, out: &mut [f32], out_channels: usize) {
804    let (channels, out_channels) = (channels.max(1), out_channels.max(1));
805    let kept = channels.min(out_channels);
806    for (to, from) in out
807        .chunks_exact_mut(out_channels)
808        .zip(samples.chunks_exact(channels))
809    {
810        to[..kept].copy_from_slice(&from[..kept]);
811        to[kept..].fill(0.0);
812    }
813}
814
815/// When the samples a listener writes are due.
816#[derive(Debug, Clone, Copy, PartialEq, Eq)]
817pub struct Presented {
818    /// The first sample's presentation time, in gPTP nanoseconds.
819    pub first: i64,
820    /// gPTP time less monotonic time, in nanoseconds.
821    pub offset: i64,
822}
823
824/// How long an output watches its device before choosing the delay.
825const CHOOSING: i64 = 2_000_000_000;
826/// The delay comes in steps of this, and grows by one each time the
827/// device then finds nothing to play.
828const DELAY_STEP: i64 = 1_000_000;
829const MOST_DELAY: i64 = 500_000_000;
830/// Frames further ahead of the device than this say the clocks disagree,
831/// and the output steers by the fill alone.
832const MOST_AHEAD: i64 = 500_000_000;
833
834/// The resampler toward the device, and when its frames play.
835struct Playing {
836    drift: Drift,
837    made: Vec<f32>,
838    /// The presentation time of the next input frame, and gPTP time less
839    /// monotonic time, in nanoseconds.
840    next_in: Option<i64>,
841    offset: Option<i64>,
842    /// Device frame `.0` presents at gPTP nanoseconds `.1`.
843    anchor: Option<(u64, i64)>,
844    /// How long after its presentation time each frame plays, once
845    /// chosen, and how far from that the last chunk played.
846    delay: Option<i64>,
847    error: i64,
848    /// While choosing: when it started, in monotonic nanoseconds, and the
849    /// lateness at the kept fill, summed, with the times it was seen.
850    choosing: Option<(i64, f64, u32)>,
851    /// The device's underruns when the delay was last set.
852    underruns: u64,
853}
854
855/// The stream's samples to their sink.
856pub struct Output {
857    buffer: Option<Arc<FrameBuffer>>,
858    _thread: Option<DeviceThread>,
859    playing: Mutex<Playing>,
860    /// Input frames a second.
861    rate: u32,
862    /// The loudest sample since the last look, as f32 bits.
863    peak: AtomicU32,
864}
865
866impl Output {
867    /// Opens `sink` for `channels` channels at `rate` hertz.
868    pub fn open(sink: &Sink, channels: u16, rate: u32) -> io::Result<Self> {
869        match sink {
870            Sink::Discard => Ok(Output::new(None, None, channels, rate, rate)),
871            Sink::Shared(shared) if shared.channels != channels => Err(io::Error::new(
872                io::ErrorKind::InvalidInput,
873                "a shared buffer of other channels than the stream's",
874            )),
875            Sink::Shared(shared) => Ok(Output::new(
876                Some(shared.buffer.clone()),
877                None,
878                channels,
879                rate,
880                shared.rate,
881            )),
882            Sink::Device {
883                name,
884                first_channel,
885            } => {
886                let device = find_device(name.as_deref(), false)?;
887                let device_rate = device_rate(&device, false, rate)?;
888                let margin = device_rate as usize / 100;
889                let buffer = Arc::new(FrameBuffer::new(channels, margin));
890                let draining = buffer.clone();
891                let first = usize::from(*first_channel);
892                let wanted = usize::from(channels);
893                let thread = device_thread("audio output".into(), move || {
894                    let supported = device.default_output_config().map_err(device_error)?;
895                    let mut config = supported.config();
896                    config.sample_rate = device_rate;
897                    match supported.sample_format() {
898                        cpal::SampleFormat::F32 => {
899                            output_stream::<f32>(&device, config, wanted, first, draining)
900                        }
901                        cpal::SampleFormat::I16 => {
902                            output_stream::<i16>(&device, config, wanted, first, draining)
903                        }
904                        cpal::SampleFormat::I32 => {
905                            output_stream::<i32>(&device, config, wanted, first, draining)
906                        }
907                        other => Err(io::Error::new(
908                            io::ErrorKind::Unsupported,
909                            format!("samples in {other}"),
910                        )),
911                    }
912                })?;
913                Ok(Output::new(
914                    Some(buffer),
915                    Some(thread),
916                    channels,
917                    rate,
918                    device_rate,
919                ))
920            }
921        }
922    }
923
924    fn new(
925        buffer: Option<Arc<FrameBuffer>>,
926        thread: Option<DeviceThread>,
927        channels: u16,
928        rate: u32,
929        device_rate: u32,
930    ) -> Self {
931        let nominal = f64::from(rate) / f64::from(device_rate.max(1));
932        Output {
933            buffer,
934            _thread: thread,
935            playing: Mutex::new(Playing {
936                drift: Drift::new(channels, DeviceSide::Pulls, nominal),
937                made: Vec::new(),
938                next_in: None,
939                offset: None,
940                anchor: None,
941                delay: None,
942                error: 0,
943                choosing: None,
944                underruns: 0,
945            }),
946            rate: rate.max(1),
947            peak: AtomicU32::new(0),
948        }
949    }
950
951    fn lock(&self) -> std::sync::MutexGuard<'_, Playing> {
952        self.playing.lock().unwrap_or_else(PoisonError::into_inner)
953    }
954
955    /// Takes interleaved frames, and when they are due where the stream
956    /// says.
957    pub fn write(&self, samples: &[f32], presented: Option<Presented>) {
958        let loudest = samples
959            .iter()
960            .fold(0.0f32, |most, sample| most.max(sample.abs()));
961        self.peak.fetch_max(loudest.to_bits(), Ordering::Relaxed);
962        let Some(buffer) = &self.buffer else {
963            return;
964        };
965        let mut playing = self.lock();
966        let playing = &mut *playing;
967        if let Some(presented) = presented {
968            playing.next_in = Some(presented.first);
969            playing.offset = Some(presented.offset);
970        }
971        if let Some(sample) = playing.drift.new_sample(buffer) {
972            self.steer(playing, buffer, &sample);
973        }
974        playing.drift.push(samples);
975        playing.made.clear();
976        playing.drift.make(&mut playing.made, usize::MAX);
977        buffer.push(&playing.made);
978        let frames = samples.len() / playing.drift.channels;
979        let frame = 1e9 / f64::from(self.rate);
980        if let Some(next) = &mut playing.next_in {
981            *next += (frames as f64 * frame).round() as i64;
982            // The next frame the resampler makes lies the frames it holds
983            // back before the next to come.
984            let made = *next - (playing.drift.pending() * frame).round() as i64;
985            playing.anchor = Some((buffer.pushed(), made));
986        }
987    }
988
989    /// Steers by when the frames play, once the device and the stream say
990    /// when, else by the buffer's fill.
991    fn steer(&self, playing: &mut Playing, buffer: &FrameBuffer, sample: &DeviceSample) {
992        let excess = sample.level as f64 - playing.drift.kept(buffer, sample) as f64;
993        let (Some(plays_at), Some((anchor, presented)), Some(offset)) =
994            (sample.plays_at, playing.anchor, playing.offset)
995        else {
996            playing.drift.follow(excess, sample.chunk);
997            return;
998        };
999        // How late the oldest frame held plays.
1000        let frame = playing.drift.ratio() * 1e9 / f64::from(self.rate);
1001        let oldest = sample.pushed - sample.level as u64;
1002        let presents = presented as f64 - (anchor as f64 - oldest as f64) * frame;
1003        let late = (plays_at + offset) as f64 - presents;
1004        if !(-MOST_AHEAD as f64..=2.0 * MOST_DELAY as f64).contains(&late) {
1005            playing.drift.follow(excess, sample.chunk);
1006            return;
1007        }
1008        let Some(delay) = playing.delay else {
1009            // Steered by the fill while choosing, noting how late frames
1010            // play at the fill kept: the earliest that is safe.
1011            playing.drift.follow(excess, sample.chunk);
1012            let (since, sum, seen) = playing.choosing.get_or_insert((plays_at, 0.0, 0));
1013            *sum += late - excess * frame;
1014            *seen += 1;
1015            if plays_at - *since >= CHOOSING {
1016                let earliest = (*sum / f64::from(*seen)).max(0.0) as i64;
1017                let steps = (earliest + DELAY_STEP - 1) / DELAY_STEP;
1018                let delay = (steps * DELAY_STEP).min(MOST_DELAY);
1019                self.set_delay(playing, buffer, delay, (late - delay as f64) / frame);
1020            }
1021            return;
1022        };
1023        let underruns = buffer.underruns.load(Ordering::Relaxed);
1024        if underruns > playing.underruns && delay < MOST_DELAY {
1025            let later = delay + DELAY_STEP;
1026            self.set_delay(playing, buffer, later, (late - later as f64) / frame);
1027            return;
1028        }
1029        playing.error = (late - delay as f64) as i64;
1030        playing
1031            .drift
1032            .follow((late - delay as f64) / frame, sample.chunk);
1033    }
1034
1035    /// Plays each frame `delay` after its presentation time from now on,
1036    /// moving at once by the `excess` frames held beyond that.
1037    fn set_delay(&self, playing: &mut Playing, buffer: &FrameBuffer, delay: i64, excess: f64) {
1038        playing.delay = Some(delay);
1039        playing.error = 0;
1040        playing.underruns = buffer.underruns.load(Ordering::Relaxed);
1041        let excess = excess.round() as i64;
1042        buffer.hold_more(excess.unsigned_abs() as usize);
1043        if excess > 0 {
1044            buffer.drop_oldest(excess as usize);
1045        } else if excess < 0 {
1046            // Silence in front of what comes next, which then presents
1047            // that much later than the frames before it.
1048            let frames = excess.unsigned_abs() as usize;
1049            buffer.push(&vec![0.0; frames * playing.drift.channels]);
1050            if let Some((anchor, _)) = &mut playing.anchor {
1051                *anchor += frames as u64;
1052            }
1053        }
1054    }
1055
1056    /// How long after its presentation time each sample plays, once the
1057    /// output knows, and how far from that the last chunk played, in
1058    /// nanoseconds.
1059    pub fn playout(&self) -> Option<(i64, i64)> {
1060        let playing = self.lock();
1061        playing.delay.map(|delay| (delay, playing.error))
1062    }
1063
1064    /// How far the device's clock runs from the stream's, in parts per
1065    /// million, as the resampler follows it.
1066    pub fn drift_ppm(&self) -> i32 {
1067        if self.buffer.is_none() {
1068            return 0;
1069        }
1070        self.lock().drift.device_ppm()
1071    }
1072
1073    /// Times the device found nothing to play.
1074    pub fn underruns(&self) -> u64 {
1075        self.buffer
1076            .as_ref()
1077            .map_or(0, |buffer| buffer.underruns.load(Ordering::Relaxed))
1078    }
1079
1080    /// The loudest sample since the last call, from 0 to 1.
1081    pub fn take_peak(&self) -> f32 {
1082        f32::from_bits(self.peak.swap(0, Ordering::Relaxed))
1083    }
1084}
1085
1086#[cfg(test)]
1087mod tests {
1088    use super::*;
1089
1090    #[test]
1091    fn the_buffer_notes_its_fill_after_each_device_chunk() {
1092        let buffer = FrameBuffer::new(2, 10);
1093        assert_eq!(buffer.device_sample(), None);
1094        buffer.device_push(&[1.0; 8]);
1095        buffer.push(&[2.0; 4]);
1096        assert_eq!(
1097            buffer.device_sample(),
1098            Some(DeviceSample {
1099                chunks: 1,
1100                level: 4,
1101                chunk: 4,
1102                pushed: 4,
1103                plays_at: None,
1104            })
1105        );
1106        let mut out = [9.0; 6];
1107        buffer.device_pull(&mut out, None);
1108        assert_eq!(out, [1.0; 6]);
1109        assert_eq!(buffer.device_sample().map(|sample| sample.chunks), Some(2));
1110        // Past four times the margin and the chunk, the oldest go.
1111        buffer.push(&[3.0; 200]);
1112        assert_eq!(buffer.level(), 4 * (10 + 3));
1113        assert!(buffer.adjustments.load(Ordering::Relaxed) > 0);
1114        // Empty: silence, counted.
1115        let mut out = [9.0; 120];
1116        buffer.pull(&mut out);
1117        assert_eq!(out[104..], [0.0; 16]);
1118        assert_eq!(buffer.underruns.load(Ordering::Relaxed), 1);
1119    }
1120
1121    /// A sine at `hertz` sampled at `rate`, from sample `start` on.
1122    fn sine(hertz: f64, rate: f64, start: u64, frames: usize) -> Vec<f32> {
1123        (0..frames as u64)
1124            .map(|index| (TAU as f64 * hertz * (start + index) as f64 / rate).sin() as f32 * 0.5)
1125            .collect()
1126    }
1127
1128    /// When the device's `index`th chunk comes, at `rate`: on time give
1129    /// or take up to 2% of a chunk.
1130    fn chunk_time(index: u64, chunk: usize, rate: f64) -> f64 {
1131        let nominal = index as f64 * chunk as f64 / rate;
1132        let wobble = ((index * 7919) % 41) as f64 / 40.0 - 0.5;
1133        nominal + 0.04 * wobble * chunk as f64 / rate
1134    }
1135
1136    /// A device 120 ppm fast feeding a talker's stream, in chunks of 1024
1137    /// frames that come a little early or late, for a simulated two
1138    /// minutes: the ratio settles on the drift, nothing runs short or
1139    /// over once started, and the sine comes out whole.
1140    #[test]
1141    fn a_fast_device_is_followed_without_a_gap() {
1142        let rate = 48_000.0;
1143        let device_rate = rate * (1.0 + 120e-6);
1144        let buffer = FrameBuffer::new(1, 480);
1145        let mut drift = Drift::new(1, DeviceSide::Pushes, 1.0);
1146        let mut chunks = 0;
1147        let mut out = Vec::new();
1148        let mut steps = Vec::new();
1149        let mut ratios = Vec::new();
1150        for packet in 0..8000 * 120u64 {
1151            let now = packet as f64 / 8000.0;
1152            while chunk_time(chunks, 1024, device_rate) <= now {
1153                buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1154                chunks += 1;
1155            }
1156            drift.steer(&buffer);
1157            let mut taken = vec![0.0; drift.wanted(6)];
1158            buffer.pull(&mut taken);
1159            drift.push(&taken);
1160            out.clear();
1161            drift.make(&mut out, 6);
1162            assert_eq!(out.len(), 6);
1163            if packet == 8000 {
1164                buffer.underruns.store(0, Ordering::Relaxed);
1165            }
1166            if packet > 8000 * 40 {
1167                steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1168                ratios.push(drift.ratio());
1169            }
1170        }
1171        for ratio in &ratios {
1172            assert!((ratio - (1.0 + 120e-6)).abs() < 30e-6, "{ratio}");
1173        }
1174        assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1175        assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1176        // No frame is missing: no step is bigger than a 1 kHz sine at
1177        // half scale ever takes between two samples.
1178        let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1179        assert!(most < 0.07, "{most}");
1180    }
1181
1182    /// A slow device playing a listener's stream in chunks of 1024
1183    /// frames, the other side of the buffer: it settles too, and never
1184    /// finds the buffer empty once playing.
1185    #[test]
1186    fn a_slow_device_is_fed_without_a_gap() {
1187        let rate = 48_000.0;
1188        let device_rate = rate * (1.0 - 80e-6);
1189        let buffer = FrameBuffer::new(1, 480);
1190        let mut drift = Drift::new(1, DeviceSide::Pulls, 1.0);
1191        let mut chunks = 0;
1192        let mut made = Vec::new();
1193        let mut played = vec![0.0; 1024];
1194        let mut ratios = Vec::new();
1195        for packet in 0..8000 * 120u64 {
1196            drift.steer(&buffer);
1197            drift.push(&sine(1000.0, rate, packet * 6, 6));
1198            made.clear();
1199            drift.make(&mut made, usize::MAX);
1200            buffer.push(&made);
1201            let now = packet as f64 / 8000.0;
1202            while chunk_time(chunks + 1, 1024, device_rate) <= now {
1203                buffer.device_pull(&mut played, None);
1204                chunks += 1;
1205            }
1206            if packet == 8000 {
1207                buffer.underruns.store(0, Ordering::Relaxed);
1208            }
1209            if packet > 8000 * 40 {
1210                ratios.push(drift.ratio());
1211            }
1212        }
1213        for ratio in &ratios {
1214            assert!((ratio - 1.0 / (1.0 - 80e-6)).abs() < 30e-6, "{ratio}");
1215        }
1216        assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1217        assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1218    }
1219
1220    /// A 48 kHz device 50 ppm fast feeding a 96 kHz stream: the ratio
1221    /// settles on half the device's frames for each of the stream's,
1222    /// the drift reads as the device's own, and the sine comes out whole
1223    /// at twice the rate.
1224    #[test]
1225    fn a_device_at_half_the_rate_is_followed() {
1226        let device_rate = 48_000.0 * (1.0 + 50e-6);
1227        let buffer = FrameBuffer::new(1, 480);
1228        let mut drift = Drift::new(1, DeviceSide::Pushes, 0.5);
1229        let mut chunks = 0;
1230        let mut out = Vec::new();
1231        let mut steps = Vec::new();
1232        let mut ppms = Vec::new();
1233        for packet in 0..8000 * 120u64 {
1234            let now = packet as f64 / 8000.0;
1235            while chunk_time(chunks, 1024, device_rate) <= now {
1236                buffer.device_push(&sine(1000.0, device_rate, chunks * 1024, 1024));
1237                chunks += 1;
1238            }
1239            drift.steer(&buffer);
1240            let mut taken = vec![0.0; drift.wanted(12)];
1241            buffer.pull(&mut taken);
1242            drift.push(&taken);
1243            out.clear();
1244            drift.make(&mut out, 12);
1245            assert_eq!(out.len(), 12);
1246            if packet == 8000 {
1247                buffer.underruns.store(0, Ordering::Relaxed);
1248            }
1249            if packet > 8000 * 40 {
1250                steps.extend(out.windows(2).map(|pair| (pair[1] - pair[0]).abs()));
1251                ppms.push(drift.device_ppm());
1252            }
1253        }
1254        for ppm in &ppms {
1255            assert!((ppm - 50).abs() < 30, "{ppm}");
1256        }
1257        assert_eq!(buffer.adjustments.load(Ordering::Relaxed), 0);
1258        assert_eq!(buffer.underruns.load(Ordering::Relaxed), 0);
1259        // A 1 kHz sine at half scale steps at most 0.033 at 96 kHz.
1260        let most = steps.iter().fold(0.0f32, |most, step| most.max(*step));
1261        assert!(most < 0.04, "{most}");
1262    }
1263
1264    /// A listener's output to a device 50 ppm slow that plays each chunk
1265    /// of `chunk` frames `latency` after its callback, for frames arriving
1266    /// `ahead` before their presentation time, for a simulated minute: the
1267    /// delay it chooses, and the most any sample in the last 20 s played
1268    /// away from that delay after its presentation time, in seconds.
1269    fn play_out(chunk: usize, latency: f64, ahead: f64) -> (i64, f64, u64) {
1270        let rate = 48_000.0;
1271        let device_rate = rate * (1.0 - 50e-6);
1272        let buffer = Arc::new(FrameBuffer::new(1, 480));
1273        let output = Output::new(Some(buffer.clone()), None, 1, 48_000, 48_000);
1274        let tone = |seconds: f64| (TAU as f64 * 100.0 * seconds).sin() as f32 * 0.5;
1275        let mut played = vec![0.0; chunk];
1276        let mut chunks = 0;
1277        let mut most = 0.0f64;
1278        let mut underruns = 0;
1279        for packet in 0..8000 * 60u64 {
1280            let arrives = packet as f64 / 8000.0;
1281            while chunk_time(chunks, chunk, device_rate) <= arrives {
1282                let plays = chunks as f64 * chunk as f64 / device_rate + latency;
1283                let after = plays + chunk as f64 / device_rate;
1284                buffer.device_pull(&mut played, Some((after * 1e9) as i64));
1285                if arrives > 40.0 {
1286                    let (delay, _) = output.playout().unwrap();
1287                    for (index, sample) in played.iter().enumerate() {
1288                        let at = plays + index as f64 / device_rate - delay as f64 * 1e-9;
1289                        // How far in time the sample is from the one due.
1290                        let off = f64::from(sample - tone(at)) / (TAU as f64 * 100.0 * 0.5);
1291                        most = most.max(off.abs());
1292                    }
1293                }
1294                chunks += 1;
1295            }
1296            if packet == 8000 * 10 {
1297                underruns = buffer.underruns.load(Ordering::Relaxed);
1298            }
1299            let first = arrives + ahead;
1300            let samples: Vec<f32> = (0..6)
1301                .map(|index| tone(first + index as f64 / rate))
1302                .collect();
1303            let presented = Presented {
1304                first: (first * 1e9) as i64,
1305                offset: 0,
1306            };
1307            output.write(&samples, Some(presented));
1308        }
1309        let (delay, _) = output.playout().unwrap();
1310        let more = buffer.underruns.load(Ordering::Relaxed) - underruns;
1311        (delay, most, more)
1312    }
1313
1314    /// Frames 1.7 ms ahead to a device 25 ms behind its callbacks of 1024
1315    /// frames: too late for presentation time, so each plays the same
1316    /// whole milliseconds after it, the device's latency, a chunk and
1317    /// the margin less the 1.7 ms.
1318    #[test]
1319    fn a_slow_device_plays_a_fixed_delay_after_presentation() {
1320        let (delay, most, underruns) = play_out(1024, 0.025, 0.0017);
1321        assert_eq!(delay, 55_000_000);
1322        assert!(most < 0.000_2, "{most}");
1323        assert_eq!(underruns, 0);
1324    }
1325
1326    /// Frames 100 ms ahead to a device 5 ms behind its callbacks of 256
1327    /// frames: each plays at its presentation time.
1328    #[test]
1329    fn early_frames_play_at_presentation_time() {
1330        let (delay, most, underruns) = play_out(256, 0.005, 0.1);
1331        assert_eq!(delay, 0);
1332        assert!(most < 0.000_2, "{most}");
1333        assert_eq!(underruns, 0);
1334    }
1335
1336    #[test]
1337    fn a_tone_fills_every_channel() {
1338        let mut input = Input::open(
1339            &Source::Tone {
1340                hertz: 1000.0,
1341                level: 0.5,
1342            },
1343            2,
1344            48_000,
1345        )
1346        .unwrap();
1347        let mut out = [0.0; 96];
1348        input.read(&mut out);
1349        assert!(out.iter().all(|sample| sample.abs() <= 0.5));
1350        assert!(
1351            out.as_chunks::<2>()
1352                .0
1353                .iter()
1354                .all(|frame| frame[0] == frame[1])
1355        );
1356        assert!(out.iter().any(|sample| sample.abs() > 0.4));
1357    }
1358
1359    /// Two channels go into an eight-channel stream as its first two,
1360    /// with silence in the rest, and eight into a stereo one as their
1361    /// first two.
1362    #[test]
1363    fn a_stream_of_other_channels_takes_the_first() {
1364        let stereo = [0.1, 0.2, 0.3, 0.4];
1365        let mut eight = [9.0; 16];
1366        respread(&stereo, 2, &mut eight, 8);
1367        assert_eq!(
1368            eight,
1369            [
1370                0.1, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3, 0.4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0
1371            ]
1372        );
1373        let mut two = [9.0; 4];
1374        respread(&eight, 8, &mut two, 2);
1375        assert_eq!(two, stereo);
1376    }
1377}