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