Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

34.3 KB
Raw Blame
#![cfg_attr(not(target_os = "macos"), allow(dead_code))]
//! The Web Audio subset the page uses: oscillators and gains with AudioParam automation, mixed into
//! the default output device (AUHAL).
//!
//! Energy: the device runs only while something can sound. It starts on the first `start()`
//! (on a helper thread, so the main thread never waits for CoreAudio) and is torn down after 1 s
//! with no live oscillator, so an idle page has no audio thread. While the device is off, every
//! context's `currentTime` follows the monotonic clock instead, so time keeps moving as in Chromium.
//! While the device is starting the clock holds still: a sound scheduled at `currentTime` plays in
//! full once the first buffer renders instead of being cut by the start-up latency.
//!
//! Threads: the main thread queues commands (`submit`); the render callback applies them at the
//! start of each buffer with `try_lock`, so it never waits on the page. Graph state lives in
//! `MIXER`, which only the render callback touches while the device runs.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::Instant;

// ---------------------------------------------------------------- AudioParam timeline

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Ev {
    Set { t: f64, v: f32 },
    Linear { t: f64, v: f32, t0: f64 },
    Exp { t: f64, v: f32, t0: f64 },
    Target { t: f64, v: f32, tau: f64 },
}

impl Ev {
    fn time(&self) -> f64 {
        match *self {
            Ev::Set { t, .. } | Ev::Linear { t, .. } | Ev::Exp { t, .. } | Ev::Target { t, .. } => t,
        }
    }
    /// Event types as the page encodes them: [type, time, value, tau, scheduledAt] per event.
    pub fn from_flat(f: &[f64]) -> Option<Ev> {
        let (ty, t, v, tau, t0) = (f[0] as u32, f[1], f[2] as f32, f[3], f[4]);
        Some(match ty {
            0 => Ev::Set { t, v },
            1 => Ev::Linear { t, v, t0 },
            2 => Ev::Exp { t, v, t0 },
            3 => Ev::Target { t, v, tau },
            _ => return None,
        })
    }
}

/// Value of an automation timeline at time `t` (Web Audio §1.6.3). `evs` is sorted by time.
pub fn param_value(evs: &[Ev], intrinsic: f32, t: f64) -> f32 {
    // the last event at or before t
    let i = evs.partition_point(|e| e.time() <= t);
    let (prev, next) = (i.checked_sub(1).map(|j| (j, evs[j])), evs.get(i));
    if let Some(&next) = next {
        if let Ev::Linear { t: t1, v: v1, t0: sched } | Ev::Exp { t: t1, v: v1, t0: sched } = next {
            // A ramp runs from the previous event (or, with none, from when it was scheduled).
            let (ta, va) = match prev {
                Some((j, e)) => (e.time(), end_value(&evs[..=j], intrinsic)),
                None => (sched.min(t1), intrinsic),
            };
            if t1 <= ta {
                return v1;
            }
            let x = ((t - ta) / (t1 - ta)).clamp(0.0, 1.0);
            return match next {
                Ev::Linear { .. } => va + (v1 - va) * x as f32,
                _ => {
                    if va == 0.0 || va.signum() != v1.signum() {
                        va
                    } else {
                        va * (v1 / va).powf(x as f32)
                    }
                }
            };
        }
    }
    match prev {
        None => intrinsic,
        Some((j, e)) => match e {
            Ev::Set { v, .. } | Ev::Linear { v, .. } | Ev::Exp { v, .. } => v,
            Ev::Target { t: ts, v: target, tau } => {
                let start = param_value(&evs[..j], intrinsic, ts);
                if tau <= 0.0 {
                    target
                } else {
                    target + (start - target) * (-(t - ts) / tau).exp() as f32
                }
            }
        },
    }
}

/// The value an event leaves behind (for a ramp that follows it).
fn end_value(evs: &[Ev], intrinsic: f32) -> f32 {
    let last = evs[evs.len() - 1];
    match last {
        Ev::Set { v, .. } | Ev::Linear { v, .. } | Ev::Exp { v, .. } => v,
        // A ramp after setTarget starts from where the target curve began.
        Ev::Target { t, .. } => param_value(&evs[..evs.len() - 1], intrinsic, t),
    }
}

#[derive(Clone, Default)]
struct Param {
    events: Vec<Ev>,
    intrinsic: f32,
    /// nodes whose output is added to this param (a-rate modulation)
    inputs: Vec<u32>,
}

// ---------------------------------------------------------------- graph

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Wave {
    Sine,
    Square,
    Sawtooth,
    Triangle,
}

enum Kind {
    Destination,
    Gain,
    Osc { wave: Wave, phase: f64, start: f64, stop: f64, ended: bool },
}

struct Node {
    ctx: u32,
    kind: Kind,
    inputs: Vec<u32>,
    params: [Param; 2],
    released: bool,
    want_ended: bool,
    out: Vec<f32>,
    stamp: u64,
}

impl Node {
    fn source_alive(&self) -> bool {
        matches!(self.kind, Kind::Osc { start, ended, .. } if !start.is_nan() && !ended)
    }
}

#[derive(Clone, Copy)]
struct CtxClock {
    /// device time at which this context's time is 0 (suspensions add to it)
    offset: f64,
    /// device time of a suspension in progress
    suspended_at: Option<f64>,
    closed: bool,
}

impl CtxClock {
    fn time(&self, dev: f64) -> f64 {
        (self.suspended_at.unwrap_or(dev) - self.offset).max(0.0)
    }
    fn running(&self) -> bool {
        self.suspended_at.is_none() && !self.closed
    }
}

enum Cmd {
    Ctx(u32, CtxClock),
    CloseCtx(u32),
    Node(u32, u32, u8),
    Connect(u32, u32, i32),
    Disconnect(u32, u32, i32),
    Param(u32, usize, f32, Vec<Ev>),
    Wave(u32, Wave),
    Start(u32, f64),
    Stop(u32, f64),
    WantEnded(u32),
    Release(u32),
    Reset,
}

struct Mixer {
    nodes: HashMap<u32, Node>,
    ctxs: HashMap<u32, CtxClock>,
    rate: f64,
    stamp: u64,
    order: Vec<u32>,
    mix: Vec<f32>,
    silent_frames: u64,
    ended: Vec<u32>,
    dests: Vec<u32>,
    stack: Vec<u32>,
}

impl Mixer {
    fn new(rate: f64) -> Self {
        Mixer {
            nodes: HashMap::new(),
            ctxs: HashMap::new(),
            rate,
            stamp: 0,
            order: Vec::new(),
            mix: Vec::new(),
            silent_frames: 0,
            ended: Vec::new(),
            dests: Vec::new(),
            stack: Vec::new(),
        }
    }

    fn apply(&mut self, cmd: Cmd) {
        match cmd {
            Cmd::Ctx(id, c) => {
                self.ctxs.insert(id, c);
            }
            Cmd::CloseCtx(id) => {
                if let Some(c) = self.ctxs.get_mut(&id) {
                    c.closed = true;
                }
                self.nodes.retain(|_, n| n.ctx != id);
                self.ctxs.remove(&id);
            }
            Cmd::Node(id, ctx, kind) => {
                let (kind, defaults) = match kind {
                    0 => (Kind::Destination, [0.0, 0.0]),
                    1 => (Kind::Gain, [1.0, 0.0]),
                    _ => (Kind::Osc { wave: Wave::Sine, phase: 0.0, start: f64::NAN, stop: f64::INFINITY, ended: false }, [440.0, 0.0]),
                };
                let params = defaults.map(|d| Param { intrinsic: d, ..Default::default() });
                self.nodes.insert(id, Node { ctx, kind, inputs: Vec::new(), params, released: false, want_ended: false, out: Vec::new(), stamp: 0 });
            }
            Cmd::Connect(from, to, param) => {
                if let Some(n) = self.nodes.get_mut(&to) {
                    let list = if param < 0 { &mut n.inputs } else { &mut n.params[param as usize & 1].inputs };
                    if !list.contains(&from) {
                        list.push(from);
                    }
                }
            }
            Cmd::Disconnect(from, to, param) => {
                for (id, n) in self.nodes.iter_mut() {
                    if to != 0 && *id != to {
                        continue;
                    }
                    if param < 0 || to == 0 {
                        n.inputs.retain(|&x| x != from);
                    }
                    for (i, p) in n.params.iter_mut().enumerate() {
                        if to == 0 || param == i as i32 {
                            p.inputs.retain(|&x| x != from);
                        }
                    }
                }
            }
            Cmd::Param(id, i, intrinsic, events) => {
                if let Some(n) = self.nodes.get_mut(&id) {
                    let p = &mut n.params[i & 1];
                    p.intrinsic = intrinsic;
                    p.events = events;
                }
            }
            Cmd::Wave(id, w) => {
                if let Some(Node { kind: Kind::Osc { wave, .. }, .. }) = self.nodes.get_mut(&id) {
                    *wave = w;
                }
            }
            Cmd::Start(id, when) => {
                if let Some(Node { kind: Kind::Osc { start, .. }, .. }) = self.nodes.get_mut(&id) {
                    *start = when;
                }
            }
            Cmd::Stop(id, when) => {
                if let Some(Node { kind: Kind::Osc { stop, .. }, .. }) = self.nodes.get_mut(&id) {
                    *stop = when;
                }
            }
            Cmd::WantEnded(id) => {
                if let Some(n) = self.nodes.get_mut(&id) {
                    n.want_ended = true;
                }
            }
            Cmd::Release(id) => {
                if let Some(n) = self.nodes.get_mut(&id) {
                    n.released = true;
                }
            }
            Cmd::Reset => {
                self.nodes.clear();
                self.ctxs.clear();
            }
        }
    }

    /// Any oscillator that is playing or scheduled in a running context?
    fn active(&self) -> bool {
        self.nodes.values().any(|n| n.source_alive() && self.ctxs.get(&n.ctx).is_some_and(|c| c.running()))
    }

    /// Drop nodes the page released that can no longer sound.
    fn collect(&mut self) {
        loop {
            let dead: Vec<u32> = self
                .nodes
                .iter()
                .filter(|(_, n)| {
                    n.released
                        && match n.kind {
                            Kind::Osc { start, ended, .. } => ended || start.is_nan(),
                            Kind::Gain => n.inputs.is_empty() && n.params.iter().all(|p| p.inputs.is_empty()),
                            Kind::Destination => false,
                        }
                })
                .map(|(id, _)| *id)
                .collect();
            if dead.is_empty() {
                return;
            }
            for id in &dead {
                self.nodes.remove(id);
            }
            for n in self.nodes.values_mut() {
                n.inputs.retain(|x| !dead.contains(x));
                for p in n.params.iter_mut() {
                    p.inputs.retain(|x| !dead.contains(x));
                }
            }
        }
    }

    fn visit(&mut self, id: u32, stack: &mut Vec<u32>) {
        let Some(n) = self.nodes.get_mut(&id) else { return };
        if n.stamp == self.stamp || stack.contains(&id) {
            return; // done, or a cycle (no DelayNode, so cycles are silent)
        }
        stack.push(id);
        let deps: Vec<u32> = n.inputs.iter().chain(n.params.iter().flat_map(|p| p.inputs.iter())).copied().collect();
        for d in deps {
            self.visit(d, stack);
        }
        stack.pop();
        if let Some(n) = self.nodes.get_mut(&id) {
            n.stamp = self.stamp;
        }
        self.order.push(id);
    }

    /// Render `frames` samples starting at device time `dev` into `self.mix` (mono).
    fn render(&mut self, dev: f64, frames: usize) {
        self.stamp += 1;
        self.order.clear();
        self.mix.clear();
        self.mix.resize(frames, 0.0);
        let mut dests = std::mem::take(&mut self.dests);
        dests.clear();
        dests.extend(
            self.nodes
                .iter()
                .filter(|(_, n)| matches!(n.kind, Kind::Destination) && self.ctxs.get(&n.ctx).is_some_and(|c| c.running()))
                .map(|(id, _)| *id),
        );
        let mut stack = std::mem::take(&mut self.stack);
        for d in &dests {
            self.visit(*d, &mut stack);
        }
        self.stack = stack;
        let dt = 1.0 / self.rate;
        let order = std::mem::take(&mut self.order);
        let mut ended_ids = std::mem::take(&mut self.ended);
        for &id in &order {
            let Some(node) = self.nodes.get(&id) else { continue };
            let Some(clock) = self.ctxs.get(&node.ctx).copied() else { continue };
            let t0 = clock.time(dev);
            let mut out = std::mem::take(&mut self.nodes.get_mut(&id).unwrap().out);
            out.clear();
            out.resize(frames, 0.0);
            let node = &self.nodes[&id];
            for inp in &node.inputs {
                if let Some(src) = self.nodes.get(inp) {
                    if src.out.len() == frames {
                        for (o, s) in out.iter_mut().zip(&src.out) {
                            *o += s;
                        }
                    }
                }
            }
            let param_at = |p: &Param, k: usize, t: f64| -> f32 {
                let mut v = if p.events.is_empty() { p.intrinsic } else { param_value(&p.events, p.intrinsic, t) };
                for inp in &p.inputs {
                    if let Some(src) = self.nodes.get(inp) {
                        v += src.out.get(k).copied().unwrap_or(0.0);
                    }
                }
                v
            };
            let mut new_kind = None;
            match &node.kind {
                Kind::Destination => {}
                Kind::Gain => {
                    for (k, o) in out.iter_mut().enumerate() {
                        *o *= param_at(&node.params[0], k, t0 + k as f64 * dt);
                    }
                }
                &Kind::Osc { wave, mut phase, start, stop, ended } => {
                    let mut ended_now = ended;
                    if !start.is_nan() && !ended {
                        for (k, o) in out.iter_mut().enumerate() {
                            let t = t0 + k as f64 * dt;
                            if t < start {
                                continue;
                            }
                            if t >= stop {
                                ended_now = true;
                                break;
                            }
                            let f = param_at(&node.params[0], k, t) as f64 * (param_at(&node.params[1], k, t) as f64 / 1200.0).exp2();
                            let inc = (f * dt).clamp(-0.5, 0.5);
                            *o = osc_sample(wave, phase, inc.abs());
                            phase += inc;
                            phase -= phase.floor();
                        }
                        // a stop scheduled exactly at the end of this buffer
                        if t0 + frames as f64 * dt >= stop {
                            ended_now = true;
                        }
                    }
                    new_kind = Some(Kind::Osc { wave, phase, start, stop, ended: ended_now });
                    if ended_now && !ended && node.want_ended {
                        ended_ids.push(id);
                    }
                }
            }
            let n = self.nodes.get_mut(&id).unwrap();
            if let Some(k) = new_kind {
                n.kind = k;
            }
            n.out = out;
        }
        // Oscillators not reachable from a destination still advance and end on time.
        let unreached: Vec<u32> = self.nodes.iter().filter(|(_, n)| n.stamp != self.stamp && n.source_alive()).map(|(id, _)| *id).collect();
        for id in unreached {
            let n = self.nodes.get_mut(&id).unwrap();
            let Some(clock) = self.ctxs.get(&n.ctx) else { continue };
            if !clock.running() {
                continue;
            }
            let end = clock.time(dev) + frames as f64 * dt;
            if let Kind::Osc { stop, ended, .. } = &mut n.kind {
                if end >= *stop {
                    *ended = true;
                    if n.want_ended {
                        ended_ids.push(id);
                    }
                }
            }
        }
        for d in &dests {
            if let Some(n) = self.nodes.get(d) {
                for (m, s) in self.mix.iter_mut().zip(&n.out) {
                    *m += s;
                }
            }
        }
        self.dests = dests;
        self.order = order;
        self.ended = ended_ids;
        self.collect();
    }
}

fn poly_blep(t: f64, dt: f64) -> f64 {
    if dt <= 0.0 {
        0.0
    } else if t < dt {
        let x = t / dt;
        x + x - x * x - 1.0
    } else if t > 1.0 - dt {
        let x = (t - 1.0) / dt;
        x * x + x + x + 1.0
    } else {
        0.0
    }
}

/// One sample of a unit waveform at `phase` (0..1). Phases match Chromium's tables: every shape
/// starts at 0 (square at +1) and rises. Square and sawtooth are band-limited with PolyBLEP.
fn osc_sample(wave: Wave, phase: f64, inc: f64) -> f32 {
    let v = match wave {
        Wave::Sine => (phase * std::f64::consts::TAU).sin(),
        Wave::Square => {
            let mut v = if phase < 0.5 { 1.0 } else { -1.0 };
            v += poly_blep(phase, inc);
            v -= poly_blep((phase + 0.5).fract(), inc);
            v
        }
        Wave::Sawtooth => {
            let p = (phase + 0.5).fract();
            2.0 * p - 1.0 - poly_blep(p, inc)
        }
        Wave::Triangle => 1.0 - 4.0 * (((phase + 0.25).fract()) - 0.5).abs(),
    };
    v as f32
}

// ---------------------------------------------------------------- device clock

const STOPPED: u8 = 0;
const STARTING: u8 = 1;
const RUNNING: u8 = 2;
const STOPPING: u8 = 3;

static STATE: AtomicU8 = AtomicU8::new(STOPPED);
static FRAMES: AtomicU64 = AtomicU64::new(0);
/// `Clock::dev_base` as f64 bits, so the render callback reads it without a lock.
static DEV_BASE: AtomicU64 = AtomicU64::new(0);
static STOP_REQUESTED: AtomicBool = AtomicBool::new(false);
static RESTART: AtomicBool = AtomicBool::new(false);

struct Clock {
    idle_base: f64,
    idle_since: Instant,
    dev_base: f64,
}

static CLOCK: Mutex<Option<Clock>> = Mutex::new(None);
static CMDS: Mutex<Vec<Cmd>> = Mutex::new(Vec::new());
static MIXER: Mutex<Option<Mixer>> = Mutex::new(None);

/// Device time in seconds: rendered frames while the device runs, the monotonic clock otherwise.
fn device_time() -> f64 {
    let mut g = CLOCK.lock().unwrap();
    let c = g.get_or_insert_with(|| Clock { idle_base: 0.0, idle_since: Instant::now(), dev_base: 0.0 });
    match STATE.load(Ordering::SeqCst) {
        RUNNING | STOPPING => f64::from_bits(DEV_BASE.load(Ordering::SeqCst)) + FRAMES.load(Ordering::SeqCst) as f64 / sample_rate(),
        STARTING => c.idle_base,
        _ => c.idle_base + c.idle_since.elapsed().as_secs_f64(),
    }
}

pub fn sample_rate() -> f64 {
    static RATE: OnceLock<f64> = OnceLock::new();
    *RATE.get_or_init(|| device::default_rate().filter(|r| (8000.0..=384000.0).contains(r)).unwrap_or(48000.0))
}

// ---------------------------------------------------------------- page-facing API (main thread)

thread_local! {
    static CTXS: std::cell::RefCell<HashMap<u32, CtxClock>> = std::cell::RefCell::new(HashMap::new());
}

fn submit(cmd: Cmd) {
    CMDS.lock().unwrap().push(cmd);
    if STATE.load(Ordering::SeqCst) == STOPPED {
        // Nothing renders: apply now so the queue cannot grow while the device is off.
        if let Ok(mut m) = MIXER.try_lock() {
            let m = m.get_or_insert_with(|| Mixer::new(sample_rate()));
            for c in std::mem::take(&mut *CMDS.lock().unwrap()) {
                m.apply(c);
            }
            m.collect();
        }
    }
}

static NEXT_ID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);

/// Node and context ids are process-wide, so a late `ended` from a previous page never matches a
/// node of the next one.
fn next_id() -> u32 {
    NEXT_ID.fetch_add(1, Ordering::Relaxed)
}

/// A new context; its id is also the id of its destination node.
pub fn create_context() -> u32 {
    let id = next_id();
    let c = CtxClock { offset: device_time(), suspended_at: None, closed: false };
    CTXS.with(|m| m.borrow_mut().insert(id, c));
    submit(Cmd::Ctx(id, c));
    submit(Cmd::Node(id, id, 0)); // the destination shares the context's id
    id
}

pub fn context_time(id: u32) -> f64 {
    CTXS.with(|m| m.borrow().get(&id).map(|c| c.time(device_time()))).unwrap_or(0.0)
}

pub fn suspend(id: u32) {
    let dev = device_time();
    let c = CTXS.with(|m| {
        let mut m = m.borrow_mut();
        let c = m.get_mut(&id)?;
        if c.suspended_at.is_none() {
            c.suspended_at = Some(dev);
        }
        Some(*c)
    });
    if let Some(c) = c {
        submit(Cmd::Ctx(id, c));
    }
}

pub fn resume(id: u32) {
    let dev = device_time();
    let c = CTXS.with(|m| {
        let mut m = m.borrow_mut();
        let c = m.get_mut(&id)?;
        if let Some(at) = c.suspended_at.take() {
            c.offset += dev - at;
        }
        Some(*c)
    });
    if let Some(c) = c {
        submit(Cmd::Ctx(id, c));
        ensure_device();
    }
}

pub fn close_context(id: u32) {
    CTXS.with(|m| m.borrow_mut().remove(&id));
    submit(Cmd::CloseCtx(id));
}

/// `kind`: 1 gain, 2 oscillator.
pub fn create_node(ctx: u32, kind: u8) -> u32 {
    let id = next_id();
    submit(Cmd::Node(id, ctx, kind));
    id
}
pub fn connect(from: u32, to: u32, param: i32) {
    submit(Cmd::Connect(from, to, param));
}
pub fn disconnect(from: u32, to: u32, param: i32) {
    submit(Cmd::Disconnect(from, to, param));
}
pub fn set_param(node: u32, index: usize, intrinsic: f32, events: Vec<Ev>) {
    submit(Cmd::Param(node, index, intrinsic, events));
}
pub fn set_wave(node: u32, wave: Wave) {
    submit(Cmd::Wave(node, wave));
}
pub fn start(node: u32, when: f64) {
    submit(Cmd::Start(node, when));
    ensure_device();
}
pub fn stop(node: u32, when: f64) {
    submit(Cmd::Stop(node, when));
}
pub fn want_ended(node: u32) {
    submit(Cmd::WantEnded(node));
}
pub fn release(node: u32) {
    submit(Cmd::Release(node));
}

/// Page teardown: silence everything and drop the graph.
pub fn reset() {
    CTXS.with(|m| m.borrow_mut().clear());
    submit(Cmd::Reset);
    ENDED.lock().unwrap().clear();
}

/// Oscillators that ended (for `onended`), collected by the render thread.
static ENDED: Mutex<Vec<u32>> = Mutex::new(Vec::new());

pub fn take_ended() -> Vec<u32> {
    std::mem::take(&mut *ENDED.lock().unwrap())
}

static ENDED_NOTIFY: OnceLock<Box<dyn Fn() + Send + Sync>> = OnceLock::new();

/// Set how the render thread tells the main thread about ended oscillators.
pub fn set_ended_notify(f: impl Fn() + Send + Sync + 'static) {
    let _ = ENDED_NOTIFY.set(Box::new(f));
}

// ---------------------------------------------------------------- device lifecycle

fn ensure_device() {
    match STATE.load(Ordering::SeqCst) {
        STOPPED => {}
        STOPPING => {
            RESTART.store(true, Ordering::SeqCst);
            return;
        }
        _ => return,
    }
    {
        // Freeze the clock until the first buffer renders.
        let mut g = CLOCK.lock().unwrap();
        let c = g.get_or_insert_with(|| Clock { idle_base: 0.0, idle_since: Instant::now(), dev_base: 0.0 });
        if STATE.compare_exchange(STOPPED, STARTING, Ordering::SeqCst, Ordering::SeqCst).is_err() {
            return;
        }
        c.idle_base += c.idle_since.elapsed().as_secs_f64();
        c.idle_since = Instant::now();
    }
    let _ = std::thread::Builder::new().name("net-audio-start".into()).spawn(|| {
        if !device::start() {
            eprintln!("[audio] could not start the output device");
            let mut g = CLOCK.lock().unwrap();
            if let Some(c) = g.as_mut() {
                c.idle_since = Instant::now();
            }
            STATE.store(STOPPED, Ordering::SeqCst);
        }
    });
}

/// Main thread, posted by the render callback after a second of silence.
fn stop_device() {
    if STATE.compare_exchange(RUNNING, STOPPING, Ordering::SeqCst, Ordering::SeqCst).is_err() {
        STOP_REQUESTED.store(false, Ordering::SeqCst);
        return;
    }
    let _ = std::thread::Builder::new().name("net-audio-stop".into()).spawn(|| {
        device::stop();
        {
            let mut g = CLOCK.lock().unwrap();
            let c = g.as_mut().unwrap();
            c.idle_base = f64::from_bits(DEV_BASE.load(Ordering::SeqCst)) + FRAMES.load(Ordering::SeqCst) as f64 / sample_rate();
            c.idle_since = Instant::now();
            STATE.store(STOPPED, Ordering::SeqCst);
        }
        STOP_REQUESTED.store(false, Ordering::SeqCst);
        // Sounds requested while we were stopping must still play.
        let pending = {
            let mut m = MIXER.lock().unwrap();
            let m = m.get_or_insert_with(|| Mixer::new(sample_rate()));
            for c in std::mem::take(&mut *CMDS.lock().unwrap()) {
                m.apply(c);
            }
            m.active()
        };
        if RESTART.swap(false, Ordering::SeqCst) || pending {
            ensure_device();
        }
    });
}

/// The render callback body: render `frames` samples and hand the mono mix to `out`.
fn render_into(frames: usize, mut out: impl FnMut(&[f32])) {
    let rate = sample_rate();
    if STATE.load(Ordering::SeqCst) == STARTING {
        // First buffer: device time continues from where the idle clock was frozen.
        let mut g = CLOCK.lock().unwrap();
        let c = g.as_mut().unwrap();
        c.dev_base = c.idle_base;
        DEV_BASE.store(c.dev_base.to_bits(), Ordering::SeqCst);
        FRAMES.store(0, Ordering::SeqCst);
        STATE.store(RUNNING, Ordering::SeqCst);
    }
    let dev = f64::from_bits(DEV_BASE.load(Ordering::SeqCst)) + FRAMES.load(Ordering::SeqCst) as f64 / rate;
    let mut guard = MIXER.lock().unwrap();
    let m = guard.get_or_insert_with(|| Mixer::new(rate));
    if let Ok(mut q) = CMDS.try_lock() {
        for c in q.drain(..) {
            m.apply(c);
        }
    }
    m.render(dev, frames);
    for s in m.mix.iter_mut() {
        *s = s.clamp(-1.0, 1.0);
    }
    out(&m.mix);
    FRAMES.fetch_add(frames as u64, Ordering::SeqCst);
    if !m.ended.is_empty() {
        ENDED.lock().unwrap().append(&mut m.ended);
        if let Some(f) = ENDED_NOTIFY.get() {
            f();
        }
    }
    if m.active() {
        m.silent_frames = 0;
    } else {
        m.silent_frames += frames as u64;
        if m.silent_frames as f64 >= rate && !STOP_REQUESTED.swap(true, Ordering::SeqCst) {
            m.silent_frames = 0;
            rt::post(stop_device);
        }
    }
}

#[cfg(target_os = "macos")]
mod device {
    use std::ffi::c_void;
    use super::*;

    #[repr(C)]
    struct AudioComponentDescription {
        ty: u32,
        sub: u32,
        manufacturer: u32,
        flags: u32,
        mask: u32,
    }
    #[repr(C)]
    struct StreamDescription {
        rate: f64,
        format: u32,
        flags: u32,
        bytes_per_packet: u32,
        frames_per_packet: u32,
        bytes_per_frame: u32,
        channels: u32,
        bits: u32,
        reserved: u32,
    }
    type RenderProc = unsafe extern "C" fn(*mut c_void, *mut u32, *const c_void, u32, u32, *mut BufferList) -> i32;
    #[repr(C)]
    struct RenderCallback {
        proc_: RenderProc,
        refcon: *mut c_void,
    }
    #[repr(C)]
    struct Buffer {
        channels: u32,
        size: u32,
        data: *mut c_void,
    }
    #[repr(C)]
    struct BufferList {
        count: u32,
        buffers: [Buffer; 1],
    }
    #[repr(C)]
    struct PropertyAddress {
        selector: u32,
        scope: u32,
        element: u32,
    }

    const fn fourcc(s: &[u8; 4]) -> u32 {
        (s[0] as u32) << 24 | (s[1] as u32) << 16 | (s[2] as u32) << 8 | s[3] as u32
    }

    #[link(name = "AudioToolbox", kind = "framework")]
    unsafe extern "C" {
        fn AudioComponentFindNext(c: *mut c_void, d: *const AudioComponentDescription) -> *mut c_void;
        fn AudioComponentInstanceNew(c: *mut c_void, out: *mut *mut c_void) -> i32;
        fn AudioComponentInstanceDispose(u: *mut c_void) -> i32;
        fn AudioUnitSetProperty(u: *mut c_void, id: u32, scope: u32, elem: u32, data: *const c_void, size: u32) -> i32;
        fn AudioUnitInitialize(u: *mut c_void) -> i32;
        fn AudioUnitUninitialize(u: *mut c_void) -> i32;
        fn AudioOutputUnitStart(u: *mut c_void) -> i32;
        fn AudioOutputUnitStop(u: *mut c_void) -> i32;
    }
    #[link(name = "CoreAudio", kind = "framework")]
    unsafe extern "C" {
        fn AudioObjectGetPropertyData(obj: u32, addr: *const PropertyAddress, qsize: u32, q: *const c_void, size: *mut u32, data: *mut c_void) -> i32;
    }

    struct Unit(*mut c_void);
    unsafe impl Send for Unit {}
    static UNIT: Mutex<Option<Unit>> = Mutex::new(None);

    pub fn default_rate() -> Option<f64> {
        unsafe {
            let mut dev: u32 = 0;
            let mut size = 4u32;
            let addr = PropertyAddress { selector: fourcc(b"dOut"), scope: fourcc(b"glob"), element: 0 };
            if AudioObjectGetPropertyData(1, &addr, 0, std::ptr::null(), &mut size, (&mut dev as *mut u32).cast()) != 0 || dev == 0 {
                return None;
            }
            let mut rate: f64 = 0.0;
            let mut size = 8u32;
            let addr = PropertyAddress { selector: fourcc(b"nsrt"), scope: fourcc(b"glob"), element: 0 };
            if AudioObjectGetPropertyData(dev, &addr, 0, std::ptr::null(), &mut size, (&mut rate as *mut f64).cast()) != 0 {
                return None;
            }
            Some(rate)
        }
    }

    unsafe extern "C" fn render(_refcon: *mut c_void, _flags: *mut u32, _ts: *const c_void, _bus: u32, frames: u32, data: *mut BufferList) -> i32 {
        unsafe {
            let list = &mut *data;
            let bufs = std::slice::from_raw_parts_mut(list.buffers.as_mut_ptr(), list.count as usize);
            render_into(frames as usize, |mix| {
                for b in bufs.iter_mut() {
                    // mono mix to every channel (Web Audio's speaker up-mix of a mono source)
                    let n = (b.size as usize / 4).min(mix.len());
                    std::slice::from_raw_parts_mut(b.data.cast::<f32>(), n).copy_from_slice(&mix[..n]);
                }
            });
        }
        0
    }

    pub fn start() -> bool {
        unsafe {
            let desc = AudioComponentDescription { ty: fourcc(b"auou"), sub: fourcc(b"def "), manufacturer: fourcc(b"appl"), flags: 0, mask: 0 };
            let comp = AudioComponentFindNext(std::ptr::null_mut(), &desc);
            if comp.is_null() {
                return false;
            }
            let mut unit: *mut c_void = std::ptr::null_mut();
            if AudioComponentInstanceNew(comp, &mut unit) != 0 || unit.is_null() {
                return false;
            }
            let fmt = StreamDescription {
                rate: sample_rate(),
                format: fourcc(b"lpcm"),
                flags: 1 | 8 | 0x20, // float, packed, non-interleaved
                bytes_per_packet: 4,
                frames_per_packet: 1,
                bytes_per_frame: 4,
                channels: 2,
                bits: 32,
                reserved: 0,
            };
            let cb = RenderCallback { proc_: render, refcon: std::ptr::null_mut() };
            let ok = AudioUnitSetProperty(unit, 8, 1, 0, (&fmt as *const StreamDescription).cast(), size_of::<StreamDescription>() as u32) == 0
                && AudioUnitSetProperty(unit, 23, 1, 0, (&cb as *const RenderCallback).cast(), size_of::<RenderCallback>() as u32) == 0
                && AudioUnitInitialize(unit) == 0;
            if !ok || AudioOutputUnitStart(unit) != 0 {
                AudioComponentInstanceDispose(unit);
                return false;
            }
            *UNIT.lock().unwrap() = Some(Unit(unit));
            true
        }
    }

    /// Stop and release the device: nothing of CoreAudio's I/O machinery stays awake.
    pub fn stop() {
        if let Some(Unit(u)) = UNIT.lock().unwrap().take() {
            unsafe {
                AudioOutputUnitStop(u);
                AudioUnitUninitialize(u);
                AudioComponentInstanceDispose(u);
            }
        }
    }
}

#[cfg(not(target_os = "macos"))]
mod device {
    pub fn default_rate() -> Option<f64> {
        None
    }
    pub fn start() -> bool {
        false
    }
    pub fn stop() {}
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn automation() {
        let evs = [Ev::Set { t: 1.0, v: 0.025 }, Ev::Exp { t: 1.05, v: 0.0001, t0: 1.0 }];
        assert_eq!(param_value(&evs, 1.0, 0.5), 1.0);
        assert!((param_value(&evs, 1.0, 1.0) - 0.025).abs() < 1e-6);
        let mid = param_value(&evs, 1.0, 1.025);
        assert!((mid - (0.025f32 * 0.0001).sqrt()).abs() < 1e-5, "{mid}");
        assert!((param_value(&evs, 1.0, 2.0) - 0.0001).abs() < 1e-7);
        let lin = [Ev::Set { t: 0.0, v: 0.0 }, Ev::Linear { t: 1.0, v: 1.0, t0: 0.0 }];
        assert!((param_value(&lin, 5.0, 0.25) - 0.25).abs() < 1e-6);
        let tgt = [Ev::Set { t: 0.0, v: 1.0 }, Ev::Target { t: 1.0, v: 0.0, tau: 0.5 }];
        assert!((param_value(&tgt, 0.0, 1.5) - (-1.0f32).exp()).abs() < 1e-5);
        // ramp with no previous event starts when it was scheduled
        let r = [Ev::Linear { t: 2.0, v: 1.0, t0: 1.0 }];
        assert!((param_value(&r, 0.0, 1.5) - 0.5).abs() < 1e-6);
    }
    #[test]
    fn renders_blip() {
        let mut m = Mixer::new(48000.0);
        m.apply(Cmd::Ctx(1, CtxClock { offset: 0.0, suspended_at: None, closed: false }));
        m.apply(Cmd::Node(1, 1, 0));
        m.apply(Cmd::Node(2, 1, 2));
        m.apply(Cmd::Node(3, 1, 1));
        m.apply(Cmd::Wave(2, Wave::Triangle));
        m.apply(Cmd::Param(3, 0, 1.0, vec![Ev::Set { t: 0.0, v: 0.025 }, Ev::Exp { t: 0.05, v: 0.0001, t0: 0.0 }]));
        m.apply(Cmd::Connect(2, 3, -1));
        m.apply(Cmd::Connect(3, 1, -1));
        m.apply(Cmd::Start(2, 0.0));
        m.apply(Cmd::Stop(2, 0.06));
        m.apply(Cmd::WantEnded(2));
        m.apply(Cmd::Release(2));
        m.apply(Cmd::Release(3));
        m.render(0.0, 512);
        let peak = m.mix.iter().fold(0f32, |a, s| a.max(s.abs()));
        assert!(peak > 0.01 && peak <= 0.026, "{peak}");
        assert!(m.active());
        for i in 1..8 {
            m.render(i as f64 * 512.0 / 48000.0, 512);
        }
        assert!(!m.active());
        assert_eq!(m.ended, vec![2]);
        // released and finished: the oscillator and its gain are gone, the destination stays
        assert_eq!(m.nodes.len(), 1);
    }
}