garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /kernel/src/drivers/sound.rs

raw

//! Sound: a virtio-sound device, its one playback and one capture stream,
//! or else an Intel HDA controller's one output stream (`hda`, a real
//! laptop's), and what programs play and record through them. A program opens a
//! stream as a channel (`AUDIO_PLAY`, `AUDIO_RECORD`): a player sends
//! messages of samples, which the kernel mixes with every other player's
//! into the device's 10 ms periods, telling each player how much it still
//! holds when that runs low and when it ran dry; a recorder gets a message
//! of samples per period. Everything runs on the device's interrupt: no
//! timer, and the device is stopped once nothing plays or records, so an
//! idle system takes no sound interrupts at all.
//!
//! The device runs at [`RATE`] Hz, stereo, 16-bit. A stream's own rate
//! (16 000 for calls, 48 000 for media) and channels (1 or 2) are converted
//! here by repeating or averaging samples, which the integer ratios allow.

use super::virtio::{self, Buffer, Queue, Transport};
use crate::mm::pages;
use crate::object::{Endpoint, Message};
use crate::sync::SpinLock;
use alloc::collections::VecDeque;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicU64, Ordering};

pub const RATE: u32 = 48_000;
pub const CHANNELS: usize = 2;
/// Frames in a period: 10 ms.
pub const PERIOD_FRAMES: usize = RATE as usize / 100;
pub(super) const PERIOD_BYTES: usize = PERIOD_FRAMES * CHANNELS * 2;
/// Periods the device holds at once: 80 ms of latency at most.
pub(super) const PERIODS: usize = 8;
/// Frames a player may have waiting here at most: a second.
const MAX_QUEUED: usize = RATE as usize;
/// Below this many frames waiting, a player is told how much is left.
const LOW_FRAMES: usize = PERIOD_FRAMES * 10;
/// Event buffers offered to the device.
const EVENTS: usize = 8;
const EVENT_BYTES: usize = 64;
/// The core that takes the sound interrupts when it runs.
const IRQ_CORE: usize = 2;
const _: () = assert!(
    4 + PERIOD_BYTES <= 2048,
    "a period and its header fit the first half of a page"
);

const Q_CONTROL: u32 = 0;
const Q_EVENT: u32 = 1;
const Q_TX: u32 = 2;
const Q_RX: u32 = 3;
const R_PCM_INFO: u32 = 0x0100;
const R_PCM_SET_PARAMS: u32 = 0x0101;
const R_PCM_PREPARE: u32 = 0x0102;
const R_PCM_RELEASE: u32 = 0x0103;
const R_PCM_START: u32 = 0x0104;
const R_PCM_STOP: u32 = 0x0105;
const S_OK: u32 = 0x8000;
const D_OUTPUT: u8 = 0;
const D_INPUT: u8 = 1;
const FMT_S16: u8 = 5;
const RATE_48000: u8 = 7;
/// `virtio_snd_pcm_info`: 32 bytes a stream.
const PCM_INFO_SIZE: usize = 32;
/// Where a control response lands in the control page.
const RESPONSE: usize = 2048;

/// A program's stream, as the kernel's end of its channel names it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Stream {
    Play(u32),
    Record(u32),
}

struct Device {
    transport: Transport,
    control: Queue,
    event: Queue,
    tx: Queue,
    rx: Queue,
    control_page: usize,
    event_page: usize,
    event_heads: [Option<u16>; EVENTS],
    /// A page a period: the transfer header at 0, the samples from 4, the
    /// status at [`RESPONSE`].
    tx_pages: [usize; PERIODS],
    rx_pages: [usize; PERIODS],
    tx_heads: [Option<u16>; PERIODS],
    rx_heads: [Option<u16>; PERIODS],
    tx_running: bool,
    /// The last player left: the device stops once it has returned every
    /// period it holds, so what was queued plays to the end.
    tx_stopping: bool,
    rx_running: bool,
    playback: u32,
    capture: Option<u32>,
}

struct Player {
    id: u32,
    rate: u32,
    channels: u32,
    /// Samples at the device's rate, interleaved stereo.
    queue: VecDeque<i16>,
    /// The kernel's end of the program's channel: for what is left.
    endpoint: Arc<Endpoint>,
    told_low: bool,
    told_empty: bool,
}

struct Recorder {
    id: u32,
    rate: u32,
    channels: u32,
    endpoint: Arc<Endpoint>,
}

/// The players and recorders, whichever device they go through.
struct Mixer {
    players: Vec<Player>,
    recorders: Vec<Recorder>,
    next_id: u32,
    /// Percent.
    volume: u32,
}

enum Backend {
    Virtio(alloc::boxed::Box<Device>),
    Hda(super::hda::Hda),
}

impl Backend {
    fn intid(&self) -> u32 {
        match self {
            Backend::Virtio(d) => d.transport.intid,
            Backend::Hda(h) => h.intid,
        }
    }

    /// Whether it plays and will go on doing so.
    fn playing(&self) -> bool {
        match self {
            Backend::Virtio(d) => d.tx_running && !d.tx_stopping,
            Backend::Hda(h) => h.running && !h.stopping,
        }
    }
}

struct Sound {
    device: Backend,
    mixer: Mixer,
}

static SOUND: SpinLock<Option<Sound>> = SpinLock::new(None);

static PLAYED: AtomicU64 = AtomicU64::new(0);
static RECORDED: AtomicU64 = AtomicU64::new(0);
static UNDERRUNS: AtomicU64 = AtomicU64::new(0);
static DROPPED: AtomicU64 = AtomicU64::new(0);

/// How the sound device has been used since boot.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stats {
    /// Periods played and recorded.
    pub played: u64,
    pub recorded: u64,
    /// Periods a player had nothing for, and frames players sent beyond
    /// what the kernel keeps.
    pub underruns: u64,
    pub dropped: u64,
}

pub fn stats() -> Stats {
    Stats {
        played: PLAYED.load(Ordering::Relaxed),
        recorded: RECORDED.load(Ordering::Relaxed),
        underruns: UNDERRUNS.load(Ordering::Relaxed),
        dropped: DROPPED.load(Ordering::Relaxed),
    }
}

/// What the device offers, as `init` found it.
#[derive(Clone, Copy, Debug)]
pub struct Info {
    /// Which: "virtio-sound", "Intel HDA".
    pub device: &'static str,
    pub streams: u32,
    pub capture: bool,
}

fn write_u32(page: usize, at: usize, value: u32) {
    // SAFETY: inside a page of ours.
    unsafe { ((page + at) as *mut u8).copy_from(value.to_le_bytes().as_ptr(), 4) };
}

fn read_u32(page: usize, at: usize) -> u32 {
    // SAFETY: inside a page of ours, which the device may have written.
    unsafe {
        let mut b = [0u8; 4];
        ((page + at) as *const u8).copy_to(b.as_mut_ptr(), 4);
        u32::from_le_bytes(b)
    }
}

impl Device {
    /// Sends a control request (`words`, little-endian) and waits for its
    /// response: its status, and `response_len` bytes after the status in
    /// the control page. Interrupts may take other queues' completions
    /// meanwhile; this one's is waited for here.
    fn control(&mut self, words: &[u32], response_len: usize) -> u32 {
        for (i, w) in words.iter().enumerate() {
            write_u32(self.control_page, i * 4, *w);
        }
        write_u32(self.control_page, RESPONSE, 0);
        let request = Buffer {
            address: self.control_page,
            len: words.len() * 4,
            device_writes: false,
        };
        let response = Buffer {
            address: self.control_page + RESPONSE,
            len: 4 + response_len,
            device_writes: true,
        };
        let Some(mine) = self.control.offer(&[request, response]) else {
            return 0;
        };
        loop {
            if let Some((head, _)) = self.control.take_used()
                && head == mine
            {
                return read_u32(self.control_page, RESPONSE);
            }
            core::hint::spin_loop();
        }
    }

    /// Sends a control request without waiting (from an interrupt).
    fn control_nowait(&mut self, words: &[u32]) {
        for (i, w) in words.iter().enumerate() {
            write_u32(self.control_page, i * 4, *w);
        }
        let request = Buffer {
            address: self.control_page,
            len: words.len() * 4,
            device_writes: false,
        };
        let response = Buffer {
            address: self.control_page + RESPONSE,
            len: 4,
            device_writes: true,
        };
        self.control.offer(&[request, response]);
    }

    fn set_params(&mut self, stream: u32) -> bool {
        let buffer = (PERIODS * PERIOD_BYTES) as u32;
        let tail = u32::from(CHANNELS as u8) | u32::from(FMT_S16) << 8 | u32::from(RATE_48000) << 16;
        self.control(
            &[R_PCM_SET_PARAMS, stream, buffer, PERIOD_BYTES as u32, 0, tail],
            0,
        ) == S_OK
            && self.control(&[R_PCM_PREPARE, stream], 0) == S_OK
    }

    fn offer_tx(&mut self, slot: usize) {
        let page = self.tx_pages[slot];
        write_u32(page, 0, self.playback);
        let data = Buffer {
            address: page,
            len: 4 + PERIOD_BYTES,
            device_writes: false,
        };
        let status = Buffer {
            address: page + RESPONSE,
            len: 8,
            device_writes: true,
        };
        self.tx_heads[slot] = self.tx.offer(&[data, status]);
    }

    fn offer_rx(&mut self, slot: usize) {
        let page = self.rx_pages[slot];
        let Some(capture) = self.capture else { return };
        write_u32(page, 0, capture);
        let header = Buffer {
            address: page,
            len: 4,
            device_writes: false,
        };
        let data = Buffer {
            address: page + 4,
            len: PERIOD_BYTES,
            device_writes: true,
        };
        let status = Buffer {
            address: page + RESPONSE,
            len: 8,
            device_writes: true,
        };
        self.rx_heads[slot] = self.rx.offer(&[header, data, status]);
    }

    fn offer_event(&mut self, slot: usize) {
        self.event_heads[slot] = self.event.offer(&[Buffer {
            address: self.event_page + slot * EVENT_BYTES,
            len: EVENT_BYTES,
            device_writes: true,
        }]);
    }
}

/// The messages to send once the lock is let go: each a player's or
/// recorder's endpoint and its bytes.
type Outgoing = Vec<(Arc<Endpoint>, Vec<u8>)>;

/// Mixes the next period of every player into the period's samples at
/// `into` ([`PERIOD_BYTES`] of them), at the volume, and notes who should
/// hear how much they have left.
fn fill_period(sound: &mut Mixer, into: usize, out: &mut Outgoing) {
    let mut mix = [0i32; PERIOD_FRAMES * CHANNELS];
    for player in &mut sound.players {
        let mut taken = 0;
        for sample in mix.iter_mut() {
            match player.queue.pop_front() {
                Some(v) => *sample += i32::from(v),
                None => break,
            }
            taken += 1;
        }
        // Part of a period: the program fell behind mid-stream. (None at
        // all is a player that finished, or has not started.)
        if taken > 0 && taken < mix.len() {
            UNDERRUNS.fetch_add(1, Ordering::Relaxed);
        }
        let frames = player.queue.len() / CHANNELS;
        let tell = if frames == 0 {
            !player.told_empty
        } else {
            frames < LOW_FRAMES && !player.told_low
        };
        if tell {
            player.told_low = true;
            player.told_empty = frames == 0;
            let own = (frames as u64 * u64::from(player.rate) / u64::from(RATE)) as u32;
            out.push((player.endpoint.clone(), own.to_le_bytes().to_vec()));
        }
    }
    let volume = sound.volume as i32;
    for (i, sample) in mix.iter().enumerate() {
        let v = (*sample * volume / 100).clamp(-32768, 32767) as i16;
        // SAFETY: the period's sample area, ours while it is not in flight.
        unsafe { ((into + i * 2) as *mut u8).copy_from(v.to_le_bytes().as_ptr(), 2) };
    }
}

/// A recorded period (rx page `slot`), as each recorder wants it: its rate
/// by averaging groups of frames, mono by averaging the channels.
fn recorded_period(device: &Device, recorders: &[Recorder], slot: usize, out: &mut Outgoing) {
    let page = device.rx_pages[slot];
    let mut frames = [[0i32; CHANNELS]; PERIOD_FRAMES];
    for (i, frame) in frames.iter_mut().enumerate() {
        for (c, sample) in frame.iter_mut().enumerate() {
            // SAFETY: the page's sample area, which the device filled.
            let b = unsafe {
                let mut b = [0u8; 2];
                ((page + 4 + (i * CHANNELS + c) * 2) as *const u8).copy_to(b.as_mut_ptr(), 2);
                b
            };
            *sample = i32::from(i16::from_le_bytes(b));
        }
    }
    for recorder in recorders {
        let group = (RATE / recorder.rate) as usize;
        let mut bytes = Vec::with_capacity(PERIOD_FRAMES / group * recorder.channels as usize * 2);
        for chunk in frames.chunks(group) {
            let mut sum = [0i32; CHANNELS];
            for frame in chunk {
                for c in 0..CHANNELS {
                    sum[c] += frame[c];
                }
            }
            let n = chunk.len() as i32;
            if recorder.channels == 1 {
                let mono = (sum[0] + sum[1]) / (2 * n);
                bytes.extend_from_slice(&(mono as i16).to_le_bytes());
            } else {
                for s in sum {
                    bytes.extend_from_slice(&((s / n) as i16).to_le_bytes());
                }
            }
        }
        out.push((recorder.endpoint.clone(), bytes));
    }
}

fn deliver(out: Outgoing) {
    for (end, bytes) in out {
        end.send(Message {
            bytes,
            handles: Vec::new(),
        });
    }
}

/// Starts the playback stream: every period filled and offered, then START.
fn start_tx(sound: &mut Sound, out: &mut Outgoing) {
    let Sound { device, mixer } = sound;
    match device {
        Backend::Virtio(d) => {
            for slot in 0..PERIODS {
                if d.tx_heads[slot].is_none() {
                    fill_period(mixer, d.tx_pages[slot] + 4, out);
                    d.offer_tx(slot);
                }
            }
            d.tx_stopping = false;
            if !d.tx_running {
                let playback = d.playback;
                d.tx_running = d.control(&[R_PCM_START, playback], 0) == S_OK;
            }
        }
        Backend::Hda(h) => {
            if !h.running {
                for slot in 0..PERIODS {
                    fill_period(mixer, h.period(slot), out);
                }
                h.start();
            }
            h.stopping = false;
            h.silent = 0;
        }
    }
}

/// Starts the capture stream, from the beginning: parameters, every period
/// offered, START.
fn start_rx(device: &mut Device) -> bool {
    let Some(capture) = device.capture else {
        return false;
    };
    if !device.set_params(capture) {
        return false;
    }
    for slot in 0..PERIODS {
        device.offer_rx(slot);
    }
    device.rx_running = device.control(&[R_PCM_START, capture], 0) == S_OK;
    device.rx_running
}

/// Stops the capture stream and takes back every period the device held
/// (RELEASE completes them all).
fn stop_rx(device: &mut Device) {
    let Some(capture) = device.capture else {
        return;
    };
    device.control(&[R_PCM_STOP, capture], 0);
    device.control(&[R_PCM_RELEASE, capture], 0);
    let until = crate::timer::now_ms() + 100;
    while device.rx_heads.iter().any(Option::is_some) && crate::timer::now_ms() < until {
        while let Some((head, _)) = device.rx.take_used() {
            if let Some(slot) = device.rx_heads.iter().position(|h| *h == Some(head)) {
                device.rx_heads[slot] = None;
            }
        }
        core::hint::spin_loop();
    }
    device.rx_heads = [None; PERIODS];
    device.rx_running = false;
}

/// The first virtio-sound device: its playback stream ready to start, its
/// capture stream found; and how many streams it has.
fn init_virtio() -> Option<(Device, u32)> {
    let transport = virtio::find(virtio::device::SOUND).next()?;
    transport.begin(0)?;
    let streams = transport.config_u32(4);
    let control = Queue::new(transport, Q_CONTROL);
    let event = Queue::new(transport, Q_EVENT);
    let tx = Queue::new(transport, Q_TX);
    let rx = Queue::new(transport, Q_RX);
    transport.ready();
    let control_page = pages::alloc(0)?;
    let event_page = pages::alloc(0)?;
    let mut tx_pages = [0; PERIODS];
    let mut rx_pages = [0; PERIODS];
    for page in tx_pages.iter_mut().chain(rx_pages.iter_mut()) {
        *page = pages::alloc(0)?;
    }
    let mut device = Device {
        transport,
        control,
        event,
        tx,
        rx,
        control_page,
        event_page,
        event_heads: [None; EVENTS],
        tx_pages,
        rx_pages,
        tx_heads: [None; PERIODS],
        rx_heads: [None; PERIODS],
        tx_running: false,
        tx_stopping: false,
        rx_running: false,
        playback: 0,
        capture: None,
    };
    // Which stream plays and which records, and that both do S16 at 48 kHz.
    let count = streams.min(((2048 - 4) / PCM_INFO_SIZE) as u32);
    if device.control(
        &[R_PCM_INFO, 0, count, PCM_INFO_SIZE as u32],
        count as usize * PCM_INFO_SIZE,
    ) != S_OK
    {
        return None;
    }
    let mut playback = None;
    let mut capture = None;
    for i in 0..count as usize {
        let at = RESPONSE + 4 + i * PCM_INFO_SIZE;
        let formats =
            u64::from(read_u32(control_page, at + 8)) | u64::from(read_u32(control_page, at + 12)) << 32;
        let rates =
            u64::from(read_u32(control_page, at + 16)) | u64::from(read_u32(control_page, at + 20)) << 32;
        let tail = read_u32(control_page, at + 24);
        let (direction, channels_min, channels_max) = (tail as u8, (tail >> 8) as u8, (tail >> 16) as u8);
        let fits = formats & 1 << FMT_S16 != 0
            && rates & 1 << RATE_48000 != 0
            && (channels_min..=channels_max).contains(&(CHANNELS as u8));
        match direction {
            D_OUTPUT if fits && playback.is_none() => playback = Some(i as u32),
            D_INPUT if fits && capture.is_none() => capture = Some(i as u32),
            _ => {}
        }
    }
    device.playback = playback?;
    device.capture = capture;
    if !device.set_params(device.playback) {
        return None;
    }
    for slot in 0..EVENTS {
        device.offer_event(slot);
    }
    Some((device, streams))
}

/// Sets up the sound device: the first virtio-sound device, else the first
/// Intel HDA controller with a codec that plays. Its playback stream ready
/// to start; the streams run only while something plays or records.
pub fn init() -> Option<Info> {
    let (device, info) = match init_virtio() {
        Some((device, streams)) => {
            let capture = device.capture.is_some();
            (
                Backend::Virtio(alloc::boxed::Box::new(device)),
                Info {
                    device: "virtio-sound",
                    streams,
                    capture,
                },
            )
        }
        None => (
            Backend::Hda(super::hda::init()?),
            Info {
                device: "Intel HDA",
                streams: 1,
                capture: false,
            },
        ),
    };
    let intid = device.intid();
    {
        let mut guard = SOUND.lock();
        let sound = guard.insert(Sound {
            device,
            mixer: Mixer {
                players: Vec::new(),
                recorders: Vec::new(),
                next_id: 1,
                volume: 80,
            },
        });
        if let Backend::Hda(h) = &mut sound.device {
            h.enable_interrupts();
        }
    }
    let irq_core = if crate::smp::online() & (1 << IRQ_CORE) != 0 {
        IRQ_CORE
    } else {
        0
    };
    // Only now: an interrupt before the device is in place would find no one.
    crate::gic::enable_shared_on(intid, irq_core);
    Some(info)
}

/// The device's interrupt: periods played, periods recorded, events.
/// False if `intid` is not the sound device's.
pub fn interrupt(intid: u32) -> bool {
    let mut guard = SOUND.lock();
    let Some(sound) = guard.as_mut() else { return false };
    if sound.device.intid() != intid {
        return false;
    }
    let mut out = Vec::new();
    let Sound { device, mixer } = sound;
    match device {
        Backend::Virtio(d) => virtio_interrupt(d, mixer, &mut out),
        Backend::Hda(h) => {
            let (first, played) = h.interrupt();
            for k in 0..played {
                let slot = (first + k) % PERIODS;
                PLAYED.fetch_add(1, Ordering::Relaxed);
                if h.stopping && mixer.players.is_empty() {
                    h.silent += 1;
                }
                fill_period(mixer, h.period(slot), &mut out);
            }
            // Every period in the ring silence: all that was played is heard.
            if h.stopping && h.silent >= PERIODS {
                h.stop();
            }
        }
    }
    drop(guard);
    deliver(out);
    true
}

fn virtio_interrupt(device: &mut Device, mixer: &mut Mixer, out: &mut Outgoing) {
    device.transport.acknowledge();
    // A STOP sent from here, answered.
    while device.control.take_used().is_some() {}
    while let Some((head, _)) = device.event.take_used() {
        if let Some(slot) = device.event_heads.iter().position(|h| *h == Some(head)) {
            device.offer_event(slot);
        }
    }
    while let Some((head, _)) = device.tx.take_used() {
        let Some(slot) = device.tx_heads.iter().position(|h| *h == Some(head)) else {
            continue;
        };
        device.tx_heads[slot] = None;
        PLAYED.fetch_add(1, Ordering::Relaxed);
        if !(device.tx_stopping && mixer.players.is_empty()) {
            fill_period(mixer, device.tx_pages[slot] + 4, out);
            device.offer_tx(slot);
        }
    }
    if device.tx_stopping && device.tx_heads.iter().all(Option::is_none) {
        let playback = device.playback;
        device.control_nowait(&[R_PCM_STOP, playback]);
        device.tx_running = false;
        device.tx_stopping = false;
    }
    while let Some((head, _)) = device.rx.take_used() {
        let Some(slot) = device.rx_heads.iter().position(|h| *h == Some(head)) else {
            continue;
        };
        device.rx_heads[slot] = None;
        RECORDED.fetch_add(1, Ordering::Relaxed);
        if device.rx_running {
            recorded_period(device, &mixer.recorders, slot, out);
            device.offer_rx(slot);
        }
    }
}

/// Whether a stream of `rate` Hz and `channels` channels can be had: the
/// device's rate must be a whole multiple of it.
fn fits(rate: u32, channels: u32) -> bool {
    rate > 0 && RATE.is_multiple_of(rate) && (1..=CHANNELS as u32).contains(&channels)
}

/// A playback stream, as the program's end of a channel: it sends messages
/// of interleaved 16-bit samples at `rate` Hz, and gets back, as four
/// bytes, how many of its frames are still waiting when that runs low (and
/// 0 when none is). None without a device, or for a rate the device's is
/// not a multiple of.
pub fn open_player(rate: u32, channels: u32) -> Option<Arc<Endpoint>> {
    if !fits(rate, channels) {
        return None;
    }
    let mut guard = SOUND.lock();
    let sound = &mut guard.as_mut()?.mixer;
    let id = sound.next_id;
    sound.next_id += 1;
    let (program, kernel) = Endpoint::pair_with_sink(crate::object::Sink::Audio(Stream::Play(id)));
    sound.players.push(Player {
        id,
        rate,
        channels,
        queue: VecDeque::new(),
        endpoint: kernel,
        told_low: false,
        told_empty: false,
    });
    Some(program)
}

/// A capture stream, as the program's end of a channel: each period's
/// samples arrive as a message, interleaved 16-bit at `rate` Hz. None
/// without a device that records.
pub fn open_recorder(rate: u32, channels: u32) -> Option<Arc<Endpoint>> {
    if !fits(rate, channels) {
        return None;
    }
    let mut guard = SOUND.lock();
    let sound = guard.as_mut()?;
    let Backend::Virtio(device) = &mut sound.device else {
        return None;
    };
    device.capture?;
    if !device.rx_running && !start_rx(device) {
        return None;
    }
    let mixer = &mut sound.mixer;
    let id = mixer.next_id;
    mixer.next_id += 1;
    let (program, kernel) = Endpoint::pair_with_sink(crate::object::Sink::Audio(Stream::Record(id)));
    mixer.recorders.push(Recorder {
        id,
        rate,
        channels,
        endpoint: kernel,
    });
    Some(program)
}

/// Sets the volume (percent, at most 100; more leaves it) and returns the
/// one before. None without a device.
pub fn volume(percent: u64) -> Option<u64> {
    let mut guard = SOUND.lock();
    let sound = &mut guard.as_mut()?.mixer;
    let before = u64::from(sound.volume);
    if percent <= 100 {
        sound.volume = percent as u32;
    }
    Some(before)
}

/// A program sent samples on its playback channel (nothing on a recorder's).
pub fn sink_send(stream: Stream, bytes: &[u8]) {
    let Stream::Play(id) = stream else { return };
    let mut guard = SOUND.lock();
    let Some(sound) = guard.as_mut() else { return };
    let Some(player) = sound.mixer.players.iter_mut().find(|p| p.id == id) else {
        return;
    };
    let repeat = (RATE / player.rate) as usize;
    let channels = player.channels as usize;
    let room = MAX_QUEUED.saturating_sub(player.queue.len() / CHANNELS);
    let frames = bytes.len() / 2 / channels;
    let taken = frames.min(room / repeat);
    DROPPED.fetch_add((frames - taken) as u64, Ordering::Relaxed);
    for frame in bytes.as_chunks::<2>().0.chunks(channels).take(taken) {
        let left = i16::from_le_bytes(frame[0]);
        let right = if channels == 2 {
            i16::from_le_bytes(frame[1])
        } else {
            left
        };
        for _ in 0..repeat {
            player.queue.push_back(left);
            player.queue.push_back(right);
        }
    }
    player.told_low = false;
    player.told_empty = false;
    let mut out = Vec::new();
    if !sound.device.playing() {
        start_tx(sound, &mut out);
    }
    drop(guard);
    deliver(out);
}

/// A program let go of its stream.
pub fn sink_close(stream: Stream) {
    let mut guard = SOUND.lock();
    let Some(sound) = guard.as_mut() else { return };
    let Sound { device, mixer } = sound;
    match stream {
        Stream::Play(id) => {
            mixer.players.retain(|p| p.id != id);
            if mixer.players.is_empty() {
                match device {
                    Backend::Virtio(d) if d.tx_running => d.tx_stopping = true,
                    Backend::Hda(h) if h.running => h.stopping = true,
                    _ => {}
                }
            }
        }
        Stream::Record(id) => {
            mixer.recorders.retain(|r| r.id != id);
            if let Backend::Virtio(d) = device
                && mixer.recorders.is_empty()
                && d.rx_running
            {
                stop_rx(d);
            }
        }
    }
}

/// Whether a sound device was set up.
pub fn present() -> bool {
    SOUND.lock().is_some()
}