Skip to main content

avb_stream/
audio.rs

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