Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

63.2 KB
Raw Blame
// Adapted from Serein (https://github.com/ViceVerse-cz/Serein) at commit a0e72cc,
// files `crates/discord-voice/src/audio.rs` and `crates/platform/src/audio.rs`.
// Copyright (c) 2026 Serein contributors. Licensed under MIT OR Apache-2.0; RustCord's
// modifications are under the same terms. See crates/voice/NOTICE.md.
//
// RustCord changes: the system default devices (followed when they change) or the devices
// chosen in settings (`settings.rs`), microphone/speaker volume and RNNoise "Voice
// Isolation" from those settings, echo cancellation fed with what the speakers played
// (`echo.rs`), a loopback mic test, no preview, a fixed energy gate for sending, and
// automatic gain control (`agc.rs`).
//! Microphone capture and speaker playback on the chosen or system default devices.
//!
//! Devices open only once the call is secured. CPAL callbacks use preallocated
//! lock-free rings; the gate, processing, codecs and channels stay on the worker thread.
use crate::Frame;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use std::sync::{
    Arc,
    atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering},
    mpsc,
};
use std::time::{Duration, Instant};

/// Energy gate for sending: frames quieter than this (dBFS RMS, 3 dB hysteresis and a
/// 200 ms release) are not transmitted. Serein's "Voice Isolation" profile uses -55 dBFS.
/// This is the default; `settings::send_threshold_db` is the level in effect.
pub(crate) const SEND_THRESHOLD_DB: i16 = -55;

/// Frames (20 ms each) every queue between the devices and the media loop holds: 320 ms,
/// so a thread that wakes late under load catches up instead of losing speech.
pub(crate) const QUEUE: usize = 16;
/// Speech starts playing once this many frames wait, so the next late frame (up to 20 ms)
/// does not become a gap.
const CUSHION: usize = 2;
/// Above this many waiting frames, quiet frames are skipped to shed the delay a catch-up
/// left behind; above `TRIM_ALWAYS` any frame is.
const TRIM_QUIET: usize = 4;
const TRIM_ALWAYS: usize = 12;

/// The running call's processed microphone level (dBFS as f32 bits), for the in-call
/// "Input Level" meter. -100 while no call captures (muted, closed or not in a call).
static CALL_INPUT_LEVEL: AtomicU32 = AtomicU32::new(0xC2C8_0000); // -100.0f32

/// The running call's microphone level after processing, in dBFS (-100 when silent).
pub fn call_input_level_db() -> f32 {
    f32::from_bits(CALL_INPUT_LEVEL.load(Ordering::Relaxed))
}

/// Six seconds of reopen attempts before an initial device failure fails the call.
/// Once a call is live, a missing device never ends it: a headset can sleep or switch
/// Bluetooth profiles for minutes, and the person stays in the channel.
const MAX_RECOVERY_ATTEMPTS: u8 = 24;
const RECOVERY_DELAY: Duration = Duration::from_millis(250);
/// How long a live call waits between attempts while its devices stay away.
const RECOVERY_PATIENCE: Duration = Duration::from_secs(5);

pub(crate) struct Gate {
    ready: AtomicBool,
    muted: AtomicBool,
    deafened: AtomicBool,
    stopped: AtomicBool,
    failed_revision: AtomicU64,
    input_failed_revision: AtomicU64,
    input_callbacks: AtomicU64,
    revision: AtomicU64,
    acknowledged_revision: AtomicU64,
    /// Bumped when the microphone gate changes; only capture drops partial PCM.
    capture_generation: AtomicU64,
    /// Bumped when the speaker gate changes; only playback drops queued audio.
    playback_generation: AtomicU64,
    /// Discard queued microphone frames and restart the send gate on the worker.
    flush: AtomicBool,
    /// Mic test: processed microphone level (dBFS as f32 bits), and how often it was read.
    level: AtomicU32,
    level_reads: AtomicU64,
}
impl Default for Gate {
    fn default() -> Self {
        Self {
            ready: AtomicBool::new(false),
            muted: AtomicBool::new(false),
            deafened: AtomicBool::new(false),
            stopped: AtomicBool::new(false),
            failed_revision: AtomicU64::new(0),
            input_failed_revision: AtomicU64::new(0),
            input_callbacks: AtomicU64::new(0),
            revision: AtomicU64::new(1),
            acknowledged_revision: AtomicU64::new(0),
            capture_generation: AtomicU64::new(0),
            playback_generation: AtomicU64::new(0),
            flush: AtomicBool::new(false),
            level: AtomicU32::new((-100.0f32).to_bits()),
            level_reads: AtomicU64::new(0),
        }
    }
}
impl Gate {
    fn is_ready(&self) -> bool {
        let revision = self.revision.load(Ordering::Acquire);
        self.ready.load(Ordering::Acquire)
            && !self.stopped.load(Ordering::Acquire)
            && self.failed_revision.load(Ordering::Acquire) != revision
            && self.acknowledged_revision.load(Ordering::Acquire) == revision
    }
    fn acknowledge(&self, revision: u64) -> bool {
        if self.revision.load(Ordering::Acquire) != revision
            || !self.ready.load(Ordering::Acquire)
            || self.stopped.load(Ordering::Acquire)
        {
            return false;
        }
        self.acknowledged_revision
            .store(revision, Ordering::Release);
        self.is_ready()
    }
    fn capture(&self) -> bool {
        self.is_ready()
            && self.input_failed_revision.load(Ordering::Acquire)
                != self.revision.load(Ordering::Acquire)
            && !self.muted.load(Ordering::Acquire)
            && !self.stopped.load(Ordering::Acquire)
    }
    fn playback(&self) -> bool {
        self.is_ready()
            && !self.deafened.load(Ordering::Acquire)
            && !self.stopped.load(Ordering::Acquire)
    }
}

/// The audio worker of one call. Dropping it closes the devices.
pub(crate) struct Audio {
    gate: Arc<Gate>,
    thread: std::thread::Thread,
}
impl Audio {
    /// Start the device worker. Devices stay closed until `set_ready(true)`.
    /// `fail` is called once if audio cannot be opened at all for this call.
    pub fn start(
        capture: mpsc::SyncSender<Frame>,
        playback: mpsc::Receiver<Frame>,
        fail: impl Fn(&'static str) + Send + 'static,
    ) -> Result<Self, &'static str> {
        Self::spawn(capture, playback, false, fail)
    }
    /// The settings page's mic test: microphone, processing and send gate straight to the
    /// speakers, devices open at once. Stops itself when `test_level` goes unread for 2 s.
    pub fn start_test(fail: impl Fn(&'static str) + Send + 'static) -> Self {
        let (capture, _) = mpsc::sync_channel(1);
        let (_, playback) = mpsc::sync_channel(1);
        match Self::spawn(capture, playback, true, fail) {
            Ok(audio) => {
                audio.set_ready(true);
                audio
            }
            Err(_) => {
                let gate = Gate::default();
                gate.stopped.store(true, Ordering::Release);
                Self {
                    gate: Arc::new(gate),
                    thread: std::thread::current(),
                }
            }
        }
    }
    fn spawn(
        capture: mpsc::SyncSender<Frame>,
        playback: mpsc::Receiver<Frame>,
        loopback: bool,
        fail: impl Fn(&'static str) + Send + 'static,
    ) -> Result<Self, &'static str> {
        let gate = Arc::new(Gate::default());
        let worker_gate = gate.clone();
        let name = if loopback { "rustcord-mic-test" } else { "rustcord-voice-audio" };
        let thread = std::thread::Builder::new()
            .name(name.into())
            .spawn(move || worker(&worker_gate, &capture, &playback, loopback, fail))
            .map_err(|_| "Could not start audio device worker")?;
        Ok(Self {
            gate,
            thread: thread.thread().clone(),
        })
    }
    /// Mic test level in dBFS; reading it keeps the test running.
    pub fn test_level(&self) -> f32 {
        self.gate.level_reads.fetch_add(1, Ordering::AcqRel);
        f32::from_bits(self.gate.level.load(Ordering::Acquire))
    }
    pub fn running(&self) -> bool {
        !self.gate.stopped.load(Ordering::Acquire)
    }
    /// The devices are open but no microphone could be.
    pub fn microphone_missing(&self) -> bool {
        let revision = self.gate.revision.load(Ordering::Acquire);
        self.gate.acknowledged_revision.load(Ordering::Acquire) == revision
            && self.gate.input_failed_revision.load(Ordering::Acquire) == revision
    }
    /// Open (or keep) devices while the call is secured; silence and flush them otherwise.
    pub fn set_ready(&self, ready: bool) {
        let established = self.gate.is_ready();
        if self.gate.ready.swap(ready, Ordering::AcqRel) && !ready {
            self.gate.capture_generation.fetch_add(1, Ordering::AcqRel);
            self.gate.playback_generation.fetch_add(1, Ordering::AcqRel);
            self.gate.flush.store(true, Ordering::Release);
            if !established {
                // An in-flight open must not acknowledge a later security epoch.
                self.gate.revision.fetch_add(1, Ordering::AcqRel);
            }
        }
        self.thread.unpark();
    }
    /// Idempotent. Each gate invalidates only its own direction, so a burst of mute clicks
    /// never drops what you hear. Deafening implies muting.
    pub fn set_controls(&self, muted: bool, deafened: bool) {
        let muted = muted || deafened;
        if self.gate.muted.swap(muted, Ordering::AcqRel) != muted {
            // A quick mute/unmute may happen between callbacks: invalidate partial PCM too.
            self.gate.capture_generation.fetch_add(1, Ordering::AcqRel);
            if !muted {
                self.gate.flush.store(true, Ordering::Release);
            }
        }
        if self.gate.deafened.swap(deafened, Ordering::AcqRel) != deafened {
            self.gate.playback_generation.fetch_add(1, Ordering::AcqRel);
        }
    }
}
impl Drop for Audio {
    fn drop(&mut self) {
        self.gate.stopped.store(true, Ordering::Release);
        self.gate.ready.store(false, Ordering::Release);
        self.thread.unpark();
    }
}

fn worker(
    gate: &Arc<Gate>,
    capture: &mpsc::SyncSender<Frame>,
    playback: &mpsc::Receiver<Frame>,
    loopback: bool,
    fail: impl Fn(&'static str),
) {
    // Relays every frame between the devices and the media loop: late here is heard.
    let _realtime = (!loopback).then(|| crate::timer::Realtime::acquire("audio worker"));
    let mut streams: Option<(u64, Streams)> = None;
    let mut processing = crate::settings::Processing::default();
    let mut devices = crate::settings::device_revision();
    // Mic test only: stop once nobody reads the level any more.
    let (mut reads, mut read_at) = (0u64, Instant::now());
    let mut opened_at: Option<Instant> = None;
    let mut opened_once = false;
    // Unplugged headphones or a changed system default reopen devices instead of
    // ending the call; only a persistent initial failure is reported.
    let mut recovery_attempts = 0u8;
    let mut next_default_check = Instant::now();
    let mut next_input_retry = Instant::now() + Duration::from_secs(2);
    // Logged once per distinct failure, not once per retry.
    let mut open_error: Option<&'static str> = None;
    while !gate.stopped.load(Ordering::Acquire) {
        if loopback {
            let now = gate.level_reads.load(Ordering::Acquire);
            if now != reads {
                (reads, read_at) = (now, Instant::now());
            } else if read_at.elapsed() >= Duration::from_secs(2) {
                break;
            }
        }
        let revision = gate.revision.load(Ordering::Acquire);
        // Devices chosen in settings: a new speaker reopens everything, a new microphone
        // only the microphone (what you hear keeps playing).
        let chosen = crate::settings::device_revision();
        if chosen != devices {
            devices = chosen;
            let (input, output) = crate::settings::wanted_devices();
            if let Some((_, active)) = &mut streams {
                if active.output_wanted != output {
                    gate.revision.fetch_add(1, Ordering::AcqRel);
                    streams = None;
                    continue;
                }
                if active.input_wanted != input {
                    active.input_wanted = input;
                    active.input_stream = None;
                    active.input_id = None;
                    next_input_retry = Instant::now();
                }
            }
        }
        if streams.is_some() && opened_at.is_some_and(|at| at.elapsed() >= Duration::from_secs(5)) {
            recovery_attempts = 0;
        }
        if streams
            .as_ref()
            .is_some_and(|(opened, _)| *opened != revision)
        {
            streams = None;
        }
        if let Some((_, active)) = &streams
            && Instant::now() >= next_default_check
        {
            next_default_check = Instant::now() + Duration::from_secs(1);
            if active.device_changed() {
                log::info!("voice audio: the device to use changed; reopening audio devices");
                gate.revision.fetch_add(1, Ordering::AcqRel);
                streams = None;
                continue;
            }
        }
        if !gate.ready.load(Ordering::Acquire) {
            // An established stream can stay open across a brief MLS rekey.
            // The callback gate silences it, and the generation flushes old PCM.
            for _ in 0..QUEUE {
                if playback.try_recv().is_err() {
                    break;
                }
            }
            std::thread::park_timeout(Duration::from_millis(10));
            continue;
        }
        if gate.failed_revision.load(Ordering::Acquire) == revision
            && gate.revision.load(Ordering::Acquire) == revision
        {
            // A live call keeps its place in the channel: the device is reopened as soon
            // as the system offers it again.
            recovery_attempts += 1;
            log::warn!("voice audio: speaker stream failed; reopening (attempt {recovery_attempts})");
            gate.revision.fetch_add(1, Ordering::AcqRel);
            streams = None;
            if recovery_attempts >= MAX_RECOVERY_ATTEMPTS {
                recovery_attempts = 0;
                std::thread::park_timeout(RECOVERY_PATIENCE);
            } else {
                std::thread::park_timeout(RECOVERY_DELAY);
            }
            continue;
        }
        if streams.is_none() {
            match Streams::open(gate, revision) {
                Ok(value) => {
                    if !gate.acknowledge(revision) {
                        continue;
                    }
                    streams = Some((revision, value));
                    processing.reset_echo();
                    if open_error.take().is_some() {
                        log::info!("voice audio: audio devices recovered");
                    }
                    gate.flush.store(true, Ordering::Release);
                    opened_at = Some(Instant::now());
                    opened_once = true;
                }
                Err(error) => {
                    if gate.revision.load(Ordering::Acquire) != revision
                        || !gate.ready.load(Ordering::Acquire)
                    {
                        continue;
                    }
                    if open_error != Some(error) {
                        open_error = Some(error);
                        log::warn!("voice audio: could not open audio devices: {error}; retrying");
                    }
                    // A call that never opened audio reports the failure. A live call
                    // waits for the device instead of losing the channel.
                    if opened_once {
                        recovery_attempts = 0;
                        std::thread::park_timeout(RECOVERY_PATIENCE);
                        continue;
                    }
                    if recovery_attempts < MAX_RECOVERY_ATTEMPTS {
                        recovery_attempts += 1;
                        std::thread::park_timeout(RECOVERY_DELAY);
                        continue;
                    }
                    fail(error);
                    break;
                }
            }
        }
        let Some((_, active)) = &mut streams else {
            continue;
        };
        // Five seconds without microphone callbacks: reopen the microphone only.
        let callbacks = gate.input_callbacks.load(Ordering::Acquire);
        if callbacks != active.input_callbacks {
            active.input_callbacks = callbacks;
            active.input_activity = Instant::now();
        }
        if active.input_stream.is_some()
            && active.input_activity.elapsed() >= Duration::from_secs(5)
        {
            log::warn!("voice audio: microphone delivered no audio for 5 s");
            gate.input_failed_revision
                .fetch_max(revision, Ordering::AcqRel);
        }
        if gate.input_failed_revision.load(Ordering::Acquire) == revision
            && active.input_stream.is_some()
        {
            log::warn!("voice audio: microphone stream lost; reopening it every 2 s");
            active.input_stream = None;
            active.input_id = None;
            next_input_retry = Instant::now() + Duration::from_secs(2);
        }
        if active.input_stream.is_none() && Instant::now() >= next_input_retry {
            next_input_retry = Instant::now() + Duration::from_secs(2);
            if active.try_reopen_input(gate, revision) {
                processing.reset_echo();
            }
        }
        if gate.flush.swap(false, Ordering::AcqRel) {
            active.send_gate = crate::activity::InputGate::default();
            // What played meanwhile goes too, so the echo canceller's two streams stay in step.
            for _ in 0..QUEUE {
                let _ = active.input.pop();
                let _ = active.played.pop();
            }
        }
        if active.input_stream.is_none() || (!loopback && !gate.capture()) {
            gate.level.store((-100.0f32).to_bits(), Ordering::Release);
            if !loopback {
                CALL_INPUT_LEVEL.store((-100.0f32).to_bits(), Ordering::Relaxed);
            }
        }
        // What the speakers played since the last turn, before this turn's microphone frames
        // (the order the devices produced them in): the echo canceller's reference. While
        // the microphone is muted or missing it is dropped, as are its frames, so both
        // streams pick up in step.
        let capturing = active.input_stream.is_some() && gate.capture();
        for _ in 0..QUEUE {
            let Ok(played) = active.played.pop() else {
                break;
            };
            if capturing {
                processing.played(&played);
            }
        }
        let speaker = crate::settings::output_gain();
        for _ in 0..QUEUE {
            let Ok(mut frame) = active.input.pop() else {
                break;
            };
            if !gate.capture() {
                active.send_gate.forget();
                continue;
            }
            // The sensitivity and meters judge the microphone's own level, not the gain
            // control's: raised room noise must not open the gate.
            let raised = processing.apply(&mut frame);
            // "Listen to Microphone": your own voice, mixed in by the speaker callback.
            // A full ring drops the frame, which bounds the delay.
            if !loopback && crate::settings::listen_to_mic() {
                let mut own = frame;
                crate::settings::scale(&mut own, speaker);
                let _ = active.monitor.push(own);
            }
            let level = (crate::activity::level_db(&frame) - raised).max(-100.0);
            gate.level.store(level.to_bits(), Ordering::Release);
            if !loopback {
                CALL_INPUT_LEVEL.store(level.to_bits(), Ordering::Relaxed);
            }
            // (The mic test ignores Push to Talk: it shows what your microphone picks up.)
            let threshold = if loopback { crate::settings::send_threshold_db() } else { crate::settings::call_threshold_db() };
            let threshold = threshold.saturating_add(raised.round() as i16);
            if active.send_gate.apply(&mut frame, Some(threshold)) {
                let lead = active.send_gate.take_lead();
                for mut frame in lead.into_iter().chain([frame]) {
                    if loopback {
                        crate::settings::scale(&mut frame, speaker);
                        let _ = active.output.push(frame);
                    } else if capture.try_send(frame).is_err() {
                        // A full queue means the media loop is 320 ms behind; drop rather than block.
                        crate::health::count(&crate::health::CAPTURE_DROPPED);
                    }
                }
            }
        }
        for _ in 0..QUEUE {
            let Ok(mut frame) = playback.try_recv() else {
                break;
            };
            if gate.playback() {
                crate::settings::scale(&mut frame, speaker);
                if active.output.push(frame).is_err() {
                    crate::health::count(&crate::health::PLAYBACK_DROPPED);
                }
            }
        }
        std::thread::park_timeout(Duration::from_millis(5));
    }
    gate.stopped.store(true, Ordering::Release);
    drop(streams);
}

struct Streams {
    // Reuse the host that owns these streams for polling and microphone retries.
    host: cpal::Host,
    send_gate: crate::activity::InputGate,
    input_callbacks: u64,
    input_activity: Instant,
    input_stream: Option<cpal::Stream>,
    _output_stream: cpal::Stream,
    input: rtrb::Consumer<Frame>,
    output: rtrb::Producer<Frame>,
    /// Your own microphone for "Listen to Microphone", mixed into the speakers.
    monitor: rtrb::Producer<Frame>,
    /// What the speakers played, for the echo canceller.
    played: rtrb::Consumer<Frame>,
    /// Devices actually opened, so a changed system default can be followed.
    output_id: Option<String>,
    input_id: Option<String>,
    /// Devices chosen in settings when these were opened (`None`: system default).
    output_wanted: Option<String>,
    input_wanted: Option<String>,
    /// Why the microphone last failed to open, so retries log each reason once.
    input_error: Option<&'static str>,
}
impl Streams {
    fn open(gate: &Arc<Gate>, revision: u64) -> Result<Self, &'static str> {
        if gate.stopped.load(Ordering::Acquire)
            || !gate.ready.load(Ordering::Acquire)
            || gate.revision.load(Ordering::Acquire) != revision
        {
            return Err("Call changed before audio devices could open");
        }
        let host = cpal::default_host();
        let (mut input_wanted, output_wanted) = crate::settings::wanted_devices();
        // A chosen speaker that is unplugged, or will not open, falls back to the system
        // default. Only an unplugged one is watched for (`device_changed`); one that fails
        // is retried when the settings or the default change.
        let default = || {
            host.default_output_device()
                .ok_or("No default audio output device is available")
        };
        let chosen = output_wanted
            .as_deref()
            .and_then(|id| chosen_device(&host, id, false));
        let (speakers, output_wanted) =
            match chosen.map(|device| build_output(&device, gate, revision)) {
                Some(Ok(output)) => (output, output_wanted),
                Some(Err(_)) => (build_output(&default()?, gate, revision)?, None),
                None => (build_output(&default()?, gate, revision)?, output_wanted),
            };
        // A missing or failing microphone keeps the call listen-only and is retried.
        let (input_stream, input_read, input_id, input_error) =
            match open_input_stream(&host, &mut input_wanted, gate, revision) {
                Ok((stream, read, id)) => (Some(stream), read, id, None),
                Err(error) => {
                    log::warn!("voice audio: microphone unavailable ({error}); listen-only, retrying every 2 s");
                    gate.input_failed_revision
                        .fetch_max(revision, Ordering::AcqRel);
                    (None, rtrb::RingBuffer::new(QUEUE).1, None, Some(error))
                }
            };
        if !gate.ready.load(Ordering::Acquire)
            || gate.stopped.load(Ordering::Acquire)
            || gate.revision.load(Ordering::Acquire) != revision
        {
            return Err("Call ended before audio devices were ready");
        }
        speakers
            .stream
            .play()
            .map_err(|_| "Could not start speaker playback")?;
        Ok(Self {
            host,
            send_gate: crate::activity::InputGate::default(),
            input_callbacks: gate.input_callbacks.load(Ordering::Acquire),
            input_activity: Instant::now(),
            input_stream,
            _output_stream: speakers.stream,
            input: input_read,
            output: speakers.output,
            monitor: speakers.monitor,
            played: speakers.played,
            output_id: speakers.id,
            input_id,
            output_wanted,
            input_wanted,
            input_error,
        })
    }
    /// True once a microphone is open again.
    fn try_reopen_input(&mut self, gate: &Arc<Gate>, revision: u64) -> bool {
        // Clear the previous failure before callbacks from the replacement can run.
        gate.input_failed_revision.store(0, Ordering::Release);
        match open_input_stream(&self.host, &mut self.input_wanted, gate, revision) {
            Ok((stream, input_read, id)) => {
                self.input_stream = Some(stream);
                self.input = input_read;
                self.input_id = id;
                self.input_callbacks = gate.input_callbacks.load(Ordering::Acquire);
                self.input_activity = Instant::now();
                self.input_error = None;
                gate.flush.store(true, Ordering::Release);
                true
            }
            Err(error) => {
                if self.input_error != Some(error) {
                    self.input_error = Some(error);
                    log::warn!("voice audio: microphone still unavailable: {error}");
                }
                gate.input_failed_revision
                    .fetch_max(revision, Ordering::AcqRel);
                false
            }
        }
    }
    /// True when the device to use (the chosen one, or the system default) is now a
    /// different device than the one opened.
    fn device_changed(&self) -> bool {
        let id = |device: Option<cpal::Device>| {
            device.and_then(|d| d.id().ok()).map(|id| id.to_string())
        };
        chosen_device_changed(
            self.output_id.as_deref(),
            self.output_wanted.as_deref(),
            || id(self.host.default_output_device()),
            |wanted| chosen_device(&self.host, wanted, false).is_some(),
        ) || chosen_device_changed(
            self.input_id.as_deref(),
            self.input_wanted.as_deref(),
            || id(self.host.default_input_device()),
            |wanted| chosen_device(&self.host, wanted, true).is_some(),
        )
    }
}
/// A device chosen in settings, if it is plugged in (and of the right direction).
fn chosen_device(host: &cpal::Host, id: &str, input: bool) -> Option<cpal::Device> {
    let id: cpal::DeviceId = id.parse().ok()?;
    host.device_by_id(&id).filter(|device| {
        if input {
            device.supports_input()
        } else {
            device.supports_output()
        }
    })
}
/// A chosen device in use needs no polling (its failures trigger recovery). One that was
/// missing is switched to as soon as it returns; meanwhile, and without a choice, the
/// system default is followed.
fn chosen_device_changed(
    opened: Option<&str>,
    wanted: Option<&str>,
    default: impl FnOnce() -> Option<String>,
    available: impl FnOnce(&str) -> bool,
) -> bool {
    match wanted {
        Some(wanted) if opened == Some(wanted) => false,
        Some(wanted) if opened.is_some() && available(wanted) => true,
        _ => default_device_changed(opened, default),
    }
}
// A failed lookup is not evidence that a healthy stream's default changed. Device
// callback failures still trigger recovery and replace the host along with the streams.
fn default_device_changed(opened: Option<&str>, lookup: impl FnOnce() -> Option<String>) -> bool {
    opened.is_some_and(|opened| lookup().is_some_and(|current| current != opened))
}
/// A built (not started) speaker stream and the worker's ends of its rings.
struct Speakers {
    stream: cpal::Stream,
    /// The call's mix to play.
    output: rtrb::Producer<Frame>,
    /// "Listen to Microphone": your own voice to play.
    monitor: rtrb::Producer<Frame>,
    /// What was played, for the echo canceller.
    played: rtrb::Consumer<Frame>,
    id: Option<String>,
}
/// Build (not start) a speaker stream fed from fresh rings.
fn build_output(
    output: &cpal::Device,
    gate: &Arc<Gate>,
    revision: u64,
) -> Result<Speakers, &'static str> {
    let output_id = output.id().ok().map(|id| id.to_string());
    let output_config = output_config(output)?;
    let stream_config = output_config.config();
    let (output_write, output_read) = rtrb::RingBuffer::new(QUEUE);
    // Three frames: at most 60 ms of your own voice waits to be played.
    let (monitor_write, monitor_read) = rtrb::RingBuffer::new(3);
    let (played_write, played_read) = rtrb::RingBuffer::new(QUEUE);
    let mut render = Playback::new(output_config.sample_rate(), output_read);
    render.monitor = monitor_read;
    render.played = played_write;
    let output_stream = match output_config.sample_format() {
        cpal::SampleFormat::F32 => {
            output_stream::<f32>(output, stream_config, render, gate.clone(), revision)
        }
        cpal::SampleFormat::I16 => {
            output_stream::<i16>(output, stream_config, render, gate.clone(), revision)
        }
        cpal::SampleFormat::I32 => {
            output_stream::<i32>(output, stream_config, render, gate.clone(), revision)
        }
        cpal::SampleFormat::U16 => {
            output_stream::<u16>(output, stream_config, render, gate.clone(), revision)
        }
        _ => Err("Speaker sample format is not supported"),
    }?;
    log::info!(
        "voice audio: speaker opened: {} ({} Hz, {} ch)",
        label(output),
        output_config.sample_rate(),
        output_config.channels()
    );
    Ok(Speakers {
        stream: output_stream,
        output: output_write,
        monitor: monitor_write,
        played: played_read,
        id: output_id,
    })
}
/// A device's name for the log.
fn label(device: &cpal::Device) -> String {
    device
        .description()
        .ok()
        .map_or_else(|| "unnamed device".to_string(), |d| d.name().to_string())
}
/// Open the chosen microphone, falling back to the system default when it is unplugged
/// or fails; a failing choice is forgotten (`wanted` cleared) so it is not polled for.
fn open_input_stream(
    host: &cpal::Host,
    wanted: &mut Option<String>,
    gate: &Arc<Gate>,
    revision: u64,
) -> Result<(cpal::Stream, rtrb::Consumer<Frame>, Option<String>), &'static str> {
    if let Some(device) = wanted.as_deref().and_then(|id| chosen_device(host, id, true)) {
        match open_input_on(&device, gate, revision) {
            Ok(opened) => return Ok(opened),
            Err(_) => *wanted = None,
        }
    }
    let input = host
        .default_input_device()
        .ok_or("No default microphone is available")?;
    open_input_on(&input, gate, revision)
}
fn open_input_on(
    input: &cpal::Device,
    gate: &Arc<Gate>,
    revision: u64,
) -> Result<(cpal::Stream, rtrb::Consumer<Frame>, Option<String>), &'static str> {
    let input_id = input.id().ok().map(|id| id.to_string());
    let input_config = input_config(&input)?;
    let stream_config = input_config.config();
    let (input_write, input_read) = rtrb::RingBuffer::new(QUEUE);
    let capture = Capture::with_channels(
        input_config.sample_rate(),
        usize::from(input_config.channels()),
        input_write,
    );
    let stream = match input_config.sample_format() {
        cpal::SampleFormat::F32 => {
            input_stream::<f32>(&input, stream_config, capture, gate.clone(), revision)
        }
        cpal::SampleFormat::I16 => {
            input_stream::<i16>(&input, stream_config, capture, gate.clone(), revision)
        }
        cpal::SampleFormat::I32 => {
            input_stream::<i32>(&input, stream_config, capture, gate.clone(), revision)
        }
        cpal::SampleFormat::U16 => {
            input_stream::<u16>(&input, stream_config, capture, gate.clone(), revision)
        }
        _ => Err("Microphone sample format is not supported"),
    }?;
    stream
        .play()
        .map_err(|_| "Could not start microphone; check system microphone permission")?;
    log::info!(
        "voice audio: microphone opened: {} ({} Hz, {} ch)",
        label(input),
        input_config.sample_rate(),
        input_config.channels()
    );
    Ok((stream, input_read, input_id))
}
fn input_config(device: &cpal::Device) -> Result<cpal::SupportedStreamConfig, &'static str> {
    let supported: Vec<_> = device
        .supported_input_configs()
        .map_err(|_| "Microphone formats are unavailable")?
        .take(64)
        .collect();
    if let Some(config) = supported
        .into_iter()
        .filter(|c| c.channels() > 0 && c.channels() <= 8)
        .filter(|c| supported_format(c.sample_format()))
        .filter_map(|c| c.try_with_sample_rate(48_000))
        .min_by_key(|c| c.channels())
    {
        return Ok(config);
    }
    let config = device
        .default_input_config()
        .map_err(|_| "Default audio format is unavailable")?;
    checked(config)
}
/// Windows keeps the native shared-mode mix format, avoiding converted WASAPI formats that
/// some drivers advertise but reject when opening a stream. Elsewhere prefer 48 kHz with
/// the fewest channels and fall back to the default.
fn output_config(device: &cpal::Device) -> Result<cpal::SupportedStreamConfig, &'static str> {
    select_output_config(
        cfg!(target_os = "windows"),
        || {
            device
                .default_output_config()
                .map_err(|_| "Default audio format is unavailable")
        },
        || {
            device
                .supported_output_configs()
                .map_err(|_| "Speaker formats are unavailable")
        },
    )
}
fn select_output_config<I: Iterator<Item = cpal::SupportedStreamConfigRange>>(
    native_mix: bool,
    default: impl FnOnce() -> Result<cpal::SupportedStreamConfig, &'static str>,
    supported: impl FnOnce() -> Result<I, &'static str>,
) -> Result<cpal::SupportedStreamConfig, &'static str> {
    if native_mix {
        return checked(default()?);
    }
    supported()?
        .take(64)
        .filter(|config| {
            (1..=8).contains(&config.channels()) && supported_format(config.sample_format())
        })
        .filter_map(|config| config.try_with_sample_rate(48_000))
        .min_by_key(|config| config.channels())
        .map(Ok)
        .unwrap_or_else(|| checked(default()?))
}
fn checked(
    config: cpal::SupportedStreamConfig,
) -> Result<cpal::SupportedStreamConfig, &'static str> {
    if (1..=8).contains(&config.channels())
        && (8_000..=192_000).contains(&config.sample_rate())
        && supported_format(config.sample_format())
    {
        Ok(config)
    } else {
        Err("Audio device format is unsupported; choose another device")
    }
}
fn supported_format(format: cpal::SampleFormat) -> bool {
    matches!(
        format,
        cpal::SampleFormat::F32
            | cpal::SampleFormat::I16
            | cpal::SampleFormat::I32
            | cpal::SampleFormat::U16
    )
}
fn is_fatal_error(error: &cpal::Error) -> bool {
    !matches!(
        error.kind(),
        cpal::ErrorKind::Xrun | cpal::ErrorKind::RealtimeDenied | cpal::ErrorKind::DeviceChanged
    )
}
fn input_stream<T>(
    device: &cpal::Device,
    config: cpal::StreamConfig,
    mut capture: Capture,
    gate: Arc<Gate>,
    revision: u64,
) -> Result<cpal::Stream, &'static str>
where
    T: cpal::SizedSample,
    f32: cpal::FromSample<T>,
{
    let channels = usize::from(config.channels);
    let failure = gate.clone();
    device
        .build_input_stream(
            config,
            move |data: &[T], _| {
                crate::timer::Realtime::for_this_thread("microphone");
                if !data.is_empty() {
                    gate.input_callbacks.fetch_add(1, Ordering::Release);
                }
                capture.process(data, channels, &gate);
            },
            move |error| {
                if is_fatal_error(&error) {
                    // Only the first failure of a stream is logged; it runs on CPAL's thread.
                    let previous = failure
                        .input_failed_revision
                        .fetch_max(revision, Ordering::AcqRel);
                    if previous < revision {
                        log::warn!("voice audio: microphone error: {error}");
                    }
                }
            },
            None,
        )
        .map_err(|_| "Could not open microphone; check device and microphone permission")
}
fn output_stream<T>(
    device: &cpal::Device,
    config: cpal::StreamConfig,
    mut output: Playback,
    gate: Arc<Gate>,
    revision: u64,
) -> Result<cpal::Stream, &'static str>
where
    T: cpal::SizedSample + cpal::FromSample<f32>,
{
    let channels = usize::from(config.channels);
    let failure = gate.clone();
    device
        .build_output_stream(
            config,
            move |data: &mut [T], _| {
                crate::timer::Realtime::for_this_thread("speaker");
                output.render(data, channels, &gate);
            },
            move |error| {
                if is_fatal_error(&error) {
                    let previous = failure
                        .failed_revision
                        .fetch_max(revision, Ordering::AcqRel);
                    if previous < revision {
                        log::warn!("voice audio: speaker error: {error}");
                    }
                }
            },
            None,
        )
        .map_err(|error| match error.kind() {
            cpal::ErrorKind::DeviceBusy => {
                "Could not open speaker device: device is busy; close other audio apps and retry"
            }
            cpal::ErrorKind::DeviceNotAvailable | cpal::ErrorKind::StreamInvalidated => {
                "Could not open speaker device: device disconnected or changed"
            }
            cpal::ErrorKind::UnsupportedConfig => {
                "Could not open speaker device: audio format is unsupported; check system sound settings"
            }
            cpal::ErrorKind::PermissionDenied => {
                "Could not open speaker device: system denied audio access"
            }
            _ => "Could not open speaker device: audio driver failed; check system sound settings",
        })
}
/// Finite samples clipped to [-1, 1]; invalid PCM becomes silence.
fn sanitize(sample: f32) -> f32 {
    if sample.is_finite() {
        sample.clamp(-1.0, 1.0)
    } else {
        0.0
    }
}
/// Device input to 20 ms mono 48 kHz frames: the channels that carry the voice averaged
/// (`mic::Downmix`), then band-limited resampling for devices not at 48 kHz.
struct Capture {
    media_generation: u64,
    downmix: crate::mic::Downmix,
    resampler: Option<crate::mic::Resampler>,
    framer: Framer,
}
impl Capture {
    fn process<T: cpal::SizedSample>(&mut self, data: &[T], channels: usize, gate: &Gate)
    where
        f32: cpal::FromSample<T>,
    {
        let generation = gate.capture_generation.load(Ordering::Acquire);
        if generation != self.media_generation {
            self.media_generation = generation;
            self.reset();
        }
        if !gate.capture() {
            self.reset();
            return;
        }
        let mut values = [0.0f32; 8];
        for frame in data.chunks_exact(channels) {
            for (value, sample) in values.iter_mut().zip(frame) {
                *value = sanitize(sample.to_sample::<f32>());
            }
            let sample = self.downmix.mix(&values[..channels.min(8)]);
            self.sample(sample);
        }
        if std::mem::take(&mut self.framer.overrun) {
            // The worker fell 320 ms behind: start over from fresh audio.
            crate::health::count(&crate::health::CAPTURE_OVERRUNS);
            gate.flush.store(true, Ordering::Release);
        }
    }
    #[cfg(test)]
    fn new(rate: u32, output: rtrb::Producer<Frame>) -> Self {
        Self::with_channels(rate, 1, output)
    }
    fn with_channels(rate: u32, channels: usize, output: rtrb::Producer<Frame>) -> Self {
        Self {
            media_generation: 0,
            downmix: crate::mic::Downmix::new(channels, rate),
            resampler: crate::mic::Resampler::new(rate),
            framer: Framer { frame: [0.0; 960], index: 0, output, overrun: false },
        }
    }
    fn reset(&mut self) {
        if let Some(resampler) = &mut self.resampler {
            resampler.reset();
        }
        self.framer.index = 0;
        self.framer.frame.fill(0.0);
    }
    fn sample(&mut self, sample: f32) {
        match &mut self.resampler {
            Some(resampler) => resampler.process(sample, |sample| self.framer.push(sample)),
            None => self.framer.push(sample),
        }
    }
}
/// 48 kHz samples into 20 ms frames on the ring to the worker.
struct Framer {
    frame: Frame,
    index: usize,
    output: rtrb::Producer<Frame>,
    overrun: bool,
}
impl Framer {
    fn push(&mut self, sample: f32) {
        self.frame[self.index] = sample;
        self.index += 1;
        if self.index == 960 {
            self.overrun |= self.output.push(self.frame).is_err();
            self.index = 0;
        }
    }
}
/// Mixed 20 ms mono 48 kHz frames to the device rate, copied to every output channel.
struct Playback {
    media_generation: u64,
    input: rtrb::Consumer<Frame>,
    frame: Frame,
    index: usize,
    /// "Listen to Microphone": your own voice, added to the mix sample by sample.
    monitor: rtrb::Consumer<Frame>,
    monitor_frame: Frame,
    monitor_index: usize,
    /// What was played (at 48 kHz, before the device's rate), handed to the worker's echo
    /// canceller 20 ms at a time.
    played: rtrb::Producer<Frame>,
    played_frame: Frame,
    played_index: usize,
    previous: f32,
    next: f32,
    phase: f64,
    step: f64,
    /// Speech is playing (the queue has not run dry since it started).
    playing: bool,
    /// One frame time was already spent waiting for the cushion.
    waited: bool,
    /// Silent frames since speech last played, to tell a gap from the end of speech.
    silent: u8,
}
impl Playback {
    fn render<T: cpal::SizedSample + cpal::FromSample<f32>>(
        &mut self,
        data: &mut [T],
        channels: usize,
        gate: &Gate,
    ) {
        let generation = gate.playback_generation.load(Ordering::Acquire);
        if generation != self.media_generation {
            self.media_generation = generation;
            self.reset();
        }
        if !gate.playback() {
            self.reset();
            data.fill(T::from_sample(0.0));
        } else {
            for frame in data.chunks_mut(channels) {
                let sample = sanitize(self.sample());
                frame.fill(T::from_sample(sample));
            }
        }
    }
    fn new(rate: u32, input: rtrb::Consumer<Frame>) -> Self {
        Self {
            media_generation: 0,
            input,
            frame: [0.0; 960],
            index: 960,
            // Nothing to listen to, and nobody told what played, until `build_output`
            // connects the worker's rings.
            monitor: rtrb::RingBuffer::new(1).1,
            monitor_frame: [0.0; 960],
            monitor_index: 960,
            played: rtrb::RingBuffer::new(1).0,
            played_frame: [0.0; 960],
            played_index: 0,
            previous: 0.0,
            next: 0.0,
            phase: 1.0,
            step: 48_000.0 / f64::from(rate),
            playing: false,
            waited: false,
            silent: u8::MAX,
        }
    }
    fn reset(&mut self) {
        for _ in 0..QUEUE {
            if self.input.pop().is_err() {
                break;
            }
        }
        self.playing = false;
        self.waited = false;
        self.silent = u8::MAX;
        while self.monitor.pop().is_ok() {}
        self.monitor_frame.fill(0.0);
        self.monitor_index = 960;
        self.played_index = 0;
        self.frame.fill(0.0);
        self.index = 960;
        self.previous = 0.0;
        self.next = 0.0;
        self.phase = 1.0;
    }
    /// The next 20 ms to play. An empty queue plays silence; speech then (re)starts with
    /// a two-frame cushion, and a queue left long by a catch-up is shortened in the pauses
    /// between words rather than by cutting speech.
    fn next_frame(&mut self) -> Frame {
        let queued = self.input.slots();
        if queued == 0 {
            self.playing = false;
            self.waited = false;
            self.silent = self.silent.saturating_add(1);
            return [0.0; 960];
        }
        if !self.playing {
            if queued < CUSHION && !self.waited {
                self.waited = true;
                self.silent = self.silent.saturating_add(1);
                return [0.0; 960];
            }
            // Speech that stopped for at most 100 ms and came back was interrupted.
            if self.silent <= 5 {
                crate::health::count(&crate::health::PLAYBACK_GAPS);
            }
            self.playing = true;
        }
        self.silent = 0;
        let mut frame = self.input.pop().unwrap_or([0.0; 960]);
        loop {
            let waiting = self.input.slots();
            let quiet = frame.iter().all(|sample| sample.abs() < 0.004);
            if waiting < TRIM_QUIET || (waiting < TRIM_ALWAYS && !quiet) {
                break;
            }
            let Ok(next) = self.input.pop() else { break };
            crate::health::count(&crate::health::PLAYBACK_TRIMMED);
            frame = next;
        }
        frame
    }
    fn pull(&mut self) -> f32 {
        if self.index == 960 {
            self.frame = self.next_frame();
            self.index = 0;
        }
        if self.monitor_index == 960 {
            self.monitor_frame = self.monitor.pop().unwrap_or([0.0; 960]);
            self.monitor_index = 0;
        }
        let value = sanitize(self.frame[self.index] + self.monitor_frame[self.monitor_index]);
        self.index += 1;
        self.monitor_index += 1;
        self.played_frame[self.played_index] = value;
        self.played_index += 1;
        if self.played_index == 960 {
            self.played_index = 0;
            // A full ring (the worker is 320 ms behind) drops the frame.
            let _ = self.played.push(self.played_frame);
        }
        value
    }
    fn sample(&mut self) -> f32 {
        while self.phase >= 1.0 {
            self.previous = self.next;
            self.next = self.pull();
            self.phase -= 1.0;
        }
        let value = self.previous + (self.next - self.previous) * self.phase as f32;
        self.phase += self.step;
        value
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    fn ready_gate() -> Gate {
        let gate = Gate::default();
        gate.ready.store(true, Ordering::Release);
        assert!(gate.acknowledge(gate.revision.load(Ordering::Acquire)));
        gate
    }
    fn audio_without_devices() -> Audio {
        Audio {
            gate: Arc::new(Gate::default()),
            thread: std::thread::current(),
        }
    }

    #[test]
    fn listened_microphone_is_mixed_into_playback_and_silenced_when_deafened() {
        let gate = ready_gate();
        let (mut send, receive) = rtrb::RingBuffer::new(8);
        let (mut own, monitor) = rtrb::RingBuffer::new(3);
        let mut playback = Playback::new(48_000, receive);
        playback.monitor = monitor;
        send.push([0.25; 960]).unwrap();
        send.push([0.0; 960]).unwrap();
        own.push([0.5; 960]).unwrap();
        let mut rendered = [0.0_f32; 960];
        playback.render(&mut rendered, 1, &gate);
        // The first sample interpolates from silence; the rest is the sum.
        assert!(rendered[8..].iter().all(|s| (*s - 0.75).abs() < 1e-6));
        // Only your own voice, nobody else talking.
        own.push([0.5; 960]).unwrap();
        playback.render(&mut rendered, 1, &gate);
        assert!(rendered[8..].iter().all(|s| (*s - 0.5).abs() < 1e-6));
        own.push([0.5; 960]).unwrap();
        gate.deafened.store(true, Ordering::Release);
        playback.render(&mut rendered, 1, &gate);
        assert_eq!(rendered, [0.0; 960]);
        assert!(own.push([0.5; 960]).is_ok(), "deafening drains the listen queue");
    }

    #[test]
    fn playback_tells_the_echo_canceller_what_it_played() {
        let gate = ready_gate();
        let (mut send, receive) = rtrb::RingBuffer::new(8);
        let (mut own, monitor) = rtrb::RingBuffer::new(3);
        let (played, mut reference) = rtrb::RingBuffer::new(QUEUE);
        // A 44.1 kHz device: the reference stays at 48 kHz, in whole 20 ms frames.
        let mut playback = Playback::new(44_100, receive);
        playback.monitor = monitor;
        playback.played = played;
        send.push([0.25; 960]).unwrap();
        send.push([0.125; 960]).unwrap();
        own.push([0.5; 960]).unwrap();
        let mut rendered = [0.0_f32; 1_000];
        playback.render(&mut rendered, 1, &gate);
        assert_eq!(reference.pop().unwrap(), [0.75; 960], "the call and your own voice");
        assert!(reference.pop().is_err(), "the second frame is not finished yet");
        // Deafening plays nothing, and the unfinished frame is forgotten.
        gate.deafened.store(true, Ordering::Release);
        playback.render(&mut rendered, 1, &gate);
        gate.deafened.store(false, Ordering::Release);
        send.push([0.25; 960]).unwrap();
        send.push([0.25; 960]).unwrap();
        playback.render(&mut rendered, 1, &gate);
        assert_eq!(reference.pop().unwrap(), [0.25; 960]);
    }

    #[test]
    fn rapid_mute_toggles_never_flush_playback_and_end_in_the_latest_state() {
        let audio = audio_without_devices();
        let gate = &audio.gate;
        let generations = || {
            (
                gate.capture_generation.load(Ordering::Acquire),
                gate.playback_generation.load(Ordering::Acquire),
            )
        };
        for _ in 0..10 {
            audio.set_controls(true, false);
            audio.set_controls(false, false);
        }
        assert_eq!(generations(), (20, 0));
        assert!(!gate.muted.load(Ordering::Acquire) && !gate.deafened.load(Ordering::Acquire));
        // Repeating the current state is a no-op.
        audio.set_controls(false, false);
        assert_eq!(generations(), (20, 0));
        // Deafening implies muted; a deafen burst from muted leaves capture untouched.
        audio.set_controls(true, false);
        for _ in 0..3 {
            audio.set_controls(true, true);
            audio.set_controls(true, false);
        }
        assert_eq!(generations(), (21, 6));
        audio.set_controls(false, true);
        assert!(gate.muted.load(Ordering::Acquire) && gate.deafened.load(Ordering::Acquire));
        audio.set_controls(false, false);
        assert!(!gate.muted.load(Ordering::Acquire) && !gate.deafened.load(Ordering::Acquire));
    }

    #[test]
    fn device_readiness_rejects_stale_open_and_fast_security_transitions() {
        let audio = audio_without_devices();
        audio.set_ready(true);
        let first = audio.gate.revision.load(Ordering::Acquire);
        assert!(!audio.gate.is_ready());
        assert!(audio.gate.acknowledge(first));
        assert!(audio.gate.is_ready() && audio.gate.capture() && audio.gate.playback());
        audio.set_ready(false);
        assert!(!audio.gate.is_ready() && !audio.gate.capture() && !audio.gate.playback());
        audio.set_ready(true); // Worker has not observed the intervening pause.
        let second = audio.gate.revision.load(Ordering::Acquire);
        assert_eq!(first, second); // Established devices survive a security pause.
        assert!(audio.gate.is_ready());
        assert_eq!(audio.gate.capture_generation.load(Ordering::Acquire), 1);
        assert_eq!(audio.gate.playback_generation.load(Ordering::Acquire), 1);
        // A pause while devices are still opening must invalidate their late result.
        audio.gate.acknowledged_revision.store(0, Ordering::Release);
        audio.set_ready(false);
        audio.set_ready(true);
        let pending = audio.gate.revision.load(Ordering::Acquire);
        assert_ne!(second, pending);
        assert!(!audio.gate.acknowledge(second));
        assert!(audio.gate.acknowledge(pending));
        // A failing device pauses media until the worker reopens it.
        audio.gate.failed_revision.store(pending, Ordering::Release);
        assert!(!audio.gate.is_ready());
        // Dropping stops everything.
        let gate = audio.gate.clone();
        drop(audio);
        assert!(gate.stopped.load(Ordering::Acquire) && !gate.capture() && !gate.playback());
    }

    #[test]
    fn default_device_polling_follows_only_a_confirmed_change() {
        assert!(!default_device_changed(None, || {
            panic!("Unopened devices have no default to follow")
        }));
        assert!(!default_device_changed(Some("a"), || None));
        assert!(!default_device_changed(Some("a"), || Some("a".into())));
        assert!(default_device_changed(Some("a"), || Some("b".into())));
        // A chosen device in use is never polled; a missing one is switched back to.
        let never = || -> Option<String> { panic!("A chosen device in use needs no polling") };
        assert!(!chosen_device_changed(Some("mic"), Some("mic"), never, |_| panic!()));
        assert!(chosen_device_changed(Some("default"), Some("mic"), || None, |id| id == "mic"));
        assert!(!chosen_device_changed(Some("default"), Some("mic"), || Some("default".into()), |_| false));
        assert!(chosen_device_changed(Some("a"), Some("mic"), || Some("b".into()), |_| false));
        assert!(!chosen_device_changed(None, Some("mic"), || None, |_| true));
    }

    #[test]
    fn mute_and_deafen_gate_each_direction_without_devices() {
        let audio = audio_without_devices();
        let (capture_send, mut captured) = rtrb::RingBuffer::new(8);
        let mut capture = Capture::new(48_000, capture_send);
        let (mut playback_send, playback_receive) = rtrb::RingBuffer::new(8);
        let mut playback = Playback::new(48_000, playback_receive);
        let mut rendered = [1.0_f32; 2];
        // Not secured yet: nothing is captured, playback is silent.
        playback_send.push([0.25; 960]).unwrap();
        capture.process(&[0.25_f32; 961], 1, &audio.gate);
        playback.render(&mut rendered, 1, &audio.gate);
        assert!(captured.pop().is_err());
        assert_eq!(rendered, [0.0; 2]);
        audio.set_ready(true);
        assert!(
            audio
                .gate
                .acknowledge(audio.gate.revision.load(Ordering::Acquire))
        );
        playback.reset();
        playback_send.push([0.25; 960]).unwrap();
        playback_send.push([0.25; 960]).unwrap();
        playback.render(&mut rendered, 1, &audio.gate);
        assert_eq!(rendered, [0.0, 0.25]);
        capture.process(&[0.25_f32; 961], 1, &audio.gate);
        assert_eq!(captured.pop().unwrap(), [0.25; 960]);

        audio.set_controls(true, false);
        capture.process(&[0.75_f32; 961], 1, &audio.gate);
        assert!(captured.pop().is_err());
        playback.render(&mut rendered, 1, &audio.gate);
        // Muting the microphone never drops what you are hearing.
        assert_eq!(rendered, [0.25; 2]);
        audio.set_controls(false, true);
        playback_send.push([0.75; 960]).unwrap();
        capture.process(&[0.75_f32; 961], 1, &audio.gate);
        playback.render(&mut rendered, 1, &audio.gate);
        assert!(captured.pop().is_err(), "deafen implies mute");
        assert_eq!(rendered, [0.0; 2]);
        audio.set_controls(false, false);
        capture.process(&[0.25_f32; 961], 1, &audio.gate);
        assert_eq!(captured.pop().unwrap(), [0.25; 960]);
        audio.gate.stopped.store(true, Ordering::Release);
        capture.process(&[0.75_f32; 961], 1, &audio.gate);
        playback_send.push([0.75; 960]).unwrap();
        playback.render(&mut rendered, 1, &audio.gate);
        assert!(captured.pop().is_err());
        assert_eq!(rendered, [0.0; 2]);
    }

    #[test]
    fn invalid_pcm_is_silenced_and_multichannel_input_is_averaged() {
        let gate = ready_gate();
        for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
            let (send, mut receive) = rtrb::RingBuffer::new(8);
            let mut capture = Capture::new(48_000, send);
            capture.process(&[invalid; 961], 1, &gate);
            assert_eq!(receive.pop().unwrap(), [0.0; 960]);
            let (mut send, receive) = rtrb::RingBuffer::new(8);
            send.push([invalid; 960]).unwrap();
            send.push([invalid; 960]).unwrap();
            let mut playback = Playback::new(48_000, receive);
            let mut rendered = [1.0_f32; 960];
            playback.render(&mut rendered, 1, &gate);
            assert_eq!(rendered, [0.0; 960]);
        }
        // (Until `mic::Downmix` has heard 100 ms, every channel is averaged.)
        let (send, mut receive) = rtrb::RingBuffer::new(8);
        let mut capture = Capture::with_channels(48_000, 2, send);
        let stereo: Vec<i16> = (0..962)
            .map(|i| if i % 2 == 0 { i16::MAX } else { 0 })
            .collect();
        capture.process(&stereo, 2, &gate);
        capture.process(&stereo, 2, &gate);
        assert!(
            receive
                .pop()
                .unwrap()
                .iter()
                .all(|s| (*s - 0.5).abs() < 0.001)
        );
        // Playback fills every output channel with the same sample.
        let (mut send, receive) = rtrb::RingBuffer::new(8);
        send.push([0.5; 960]).unwrap();
        send.push([0.5; 960]).unwrap();
        let mut playback = Playback::new(48_000, receive);
        let mut rendered = [0i16; 12];
        playback.render(&mut rendered, 6, &gate);
        assert_eq!(&rendered[..6], &[0; 6]);
        assert!(rendered[6..].iter().all(|s| (*s - i16::MAX / 2).abs() <= 1));
    }

    #[test]
    fn resampling_buffers_and_capture_gate_are_bounded_without_devices() {
        let gate = Gate::default();
        assert!(!gate.capture());
        gate.ready.store(true, Ordering::Release);
        assert!(gate.acknowledge(gate.revision.load(Ordering::Acquire)));
        assert!(gate.capture());
        gate.muted.store(true, Ordering::Release);
        assert!(!gate.capture());
        assert!(gate.playback());
        gate.deafened.store(true, Ordering::Release);
        assert!(!gate.playback());
        for rate in [44_100, 48_000, 96_000] {
            let (send, mut receive) = rtrb::RingBuffer::new(8);
            let mut capture = Capture::new(rate, send);
            let mut count = 0;
            for _ in 0..rate {
                capture.sample(0.25);
                while let Ok(frame) = receive.pop() {
                    assert!(frame.iter().all(|s| (*s - 0.25).abs() < 0.0001));
                    count += 960;
                }
            }
            assert!((47_040..=48_000).contains(&count));
        }
        let (mut send, receive) = rtrb::RingBuffer::new(8);
        for _ in 0..8 {
            send.push([0.5; 960]).unwrap();
        }
        assert!(send.push([0.5; 960]).is_err());
        let mut playback = Playback::new(44_100, receive);
        for _ in 0..7000 {
            assert!(playback.sample().is_finite());
        }
        playback.reset();
        assert_eq!(playback.sample(), 0.0);
    }

    #[test]
    fn output_format_selection_keeps_windows_native_mix() {
        use cpal::{
            SampleFormat, SupportedBufferSize, SupportedStreamConfig, SupportedStreamConfigRange,
        };
        let range = |channels, min, max, format| {
            SupportedStreamConfigRange::new(
                channels,
                min,
                max,
                SupportedBufferSize::Unknown,
                format,
            )
        };
        let default = |channels, rate, format| {
            SupportedStreamConfig::new(channels, rate, SupportedBufferSize::Unknown, format)
        };
        let native = select_output_config(
            true,
            || Ok(default(6, 44_100, SampleFormat::F32)),
            || -> Result<std::iter::Empty<SupportedStreamConfigRange>, &'static str> {
                panic!("WASAPI enumeration must not run")
            },
        )
        .unwrap();
        assert_eq!((native.channels(), native.sample_rate()), (6, 44_100));
        assert!(
            select_output_config(
                true,
                || Ok(default(2, 48_000, SampleFormat::I24)),
                || Ok(std::iter::empty())
            )
            .is_err()
        );
        let voice = select_output_config(
            false,
            || Ok(default(2, 44_100, SampleFormat::I24)),
            || {
                Ok([
                    range(2, 8_000, 192_000, SampleFormat::I24),
                    range(1, 48_000, 48_000, SampleFormat::F32),
                    range(6, 48_000, 48_000, SampleFormat::I16),
                ]
                .into_iter())
            },
        )
        .unwrap();
        assert_eq!((voice.channels(), voice.sample_rate()), (1, 48_000));
        for kind in [
            cpal::ErrorKind::Xrun,
            cpal::ErrorKind::RealtimeDenied,
            cpal::ErrorKind::DeviceChanged,
        ] {
            assert!(!is_fatal_error(&cpal::Error::from(kind)));
        }
        for kind in [
            cpal::ErrorKind::DeviceNotAvailable,
            cpal::ErrorKind::StreamInvalidated,
            cpal::ErrorKind::PermissionDenied,
            cpal::ErrorKind::DeviceBusy,
        ] {
            assert!(is_fatal_error(&cpal::Error::from(kind)));
        }
    }
}

#[cfg(test)]
mod cushion_tests {
    use super::*;

    #[test]
    fn speech_waits_for_a_cushion_and_a_long_queue_is_trimmed_in_pauses() {
        let (mut send, receive) = rtrb::RingBuffer::new(QUEUE);
        let mut playback = Playback::new(48_000, receive);
        // One frame alone waits one frame time, then plays (the tail of speech is kept).
        send.push([0.5; 960]).unwrap();
        assert_eq!(playback.next_frame(), [0.0; 960]);
        assert_eq!(playback.next_frame(), [0.5; 960]);
        assert_eq!(playback.next_frame(), [0.0; 960]);
        // Two frames start at once.
        send.push([0.25; 960]).unwrap();
        send.push([0.25; 960]).unwrap();
        assert_eq!(playback.next_frame(), [0.25; 960]);
        assert_eq!(playback.next_frame(), [0.25; 960]);
        // A catch-up burst: loud frames all play; quiet ones are skipped while the queue
        // is long, so the delay goes away between words.
        for value in [0.5, 0.5, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 0.5, 0.5] {
            send.push([value; 960]).unwrap();
        }
        let mut played = Vec::new();
        while playback.input.slots() > 0 {
            played.push(playback.next_frame()[0]);
        }
        assert_eq!(played, [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]);
        // Far too long a queue is shortened even without a pause.
        for _ in 0..QUEUE {
            send.push([0.5; 960]).unwrap();
        }
        playback.next_frame();
        assert!(playback.input.slots() < TRIM_ALWAYS);
    }
}