Skip to main content

weirdnet_audio_engine/
engine.rs

1//! The live engine: a transport, a voice mixer and lock-free queues between a control thread and the audio callback.
2//!
3//! [`engine`] returns two halves. [`Engine`] stays with the control thread (a UI, a hot key handler): it sends [`Command`]s and reads
4//! [`Event`]s and the [`Timing`] of the clock. [`EngineAudio`] goes to the device ([`EngineAudio::into_render`] makes the callback for an
5//! [`crate::AudioSink`]). The callback never locks, blocks or allocates: commands come through a bounded lock-free queue, a new
6//! [`Scene`] is swapped in at a block boundary, and the old one goes back to the control thread in an event to be dropped there.
7//!
8//! The mixer is the one in [`crate::SceneRenderer`], so a loop played here matches [`crate::render_offline`] sample for sample, whatever
9//! the device's block size.
10//!
11//! Buses: the voices (the scene's events and live presses) make the **dry** bus, before any gain. The **monitor** bus is what the device plays: the dry
12//! bus with the master gain, and later the inputs of other sources. An optional dry tap hands a copy of the dry bus to another thread.
13//!
14//! ```
15//! use std::sync::Arc;
16//! use weirdnet_audio_engine::{AudioSink, Command, EngineOptions, ManualSink, Scene, SinkConfig, engine};
17//! use weirdnet_media::waveform::Waveform;
18//!
19//! let config = SinkConfig::new(48_000, 1);
20//! let (control, audio) = engine(config, EngineOptions::default())?;
21//! let scene = Scene::new(48_000, 1, vec![Waveform::tone(48_000, 440.0, 480, 0.5)?], vec![], 0)?;
22//! control.send(Command::SetScene(Arc::new(scene))).unwrap();
23//! control.send(Command::Press { sound: 0, gain: 1.0, gated: false, tag: 7 }).unwrap();
24//! let mut sink = ManualSink::new();
25//! let _running = sink.start(config, audio.into_render())?;
26//! let block = sink.render_block(256).expect("the sink is running");
27//! assert!(block.iter().any(|s| s.abs() > 0.1));
28//! # Ok::<(), Box<dyn std::error::Error>>(())
29//! ```
30
31use crate::scene::{NO_TAG, Scene, SceneRenderer};
32use crate::sink::{RenderFn, SinkConfig};
33use crossbeam_queue::ArrayQueue;
34use std::sync::Arc;
35use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering, fence};
36use std::time::Instant;
37
38/// The most frames the audio thread mixes in one piece. A bigger device block is processed in pieces of this size, which changes no sample.
39const CHUNK_FRAMES: usize = 1024;
40const COMMAND_CAPACITY: usize = 512;
41const EVENT_CAPACITY: usize = 512;
42
43/// What the control thread asks of the audio thread. Applied at the start of the next device block.
44#[derive(Debug, Clone)]
45pub enum Command {
46    /// Starts sound `sound` of the current scene now. A `gated` voice plays until a [`Command::Release`] with its `tag` and then fades
47    /// out; one that is not gated plays to its end. Plays whether or not the transport runs.
48    Press { sound: u32, gain: f32, gated: bool, tag: u32 },
49    /// Fades out every held voice with this tag.
50    Release { tag: u32 },
51    /// Starts the transport: scene events play from the cursor.
52    Play,
53    /// Stops the transport where it is. Voices that are sounding finish, and live presses still sound.
54    Pause,
55    /// Moves the transport cursor, in frames. In a looping scene it wraps into the loop. Sounding voices carry on.
56    Locate(u64),
57    /// Replaces the scene at a block boundary, keeping the cursor. Voices of the old scene finish on the old scene's sounds. While the
58    /// engine still holds a previous retired scene the swap waits for the next block.
59    SetScene(Arc<Scene>),
60    /// Master gain on the dry bus, linear.
61    SetGain(f32),
62    /// Stops every voice at once.
63    Panic,
64}
65
66/// What the audio thread tells the control thread.
67#[derive(Debug, Clone)]
68pub enum Event {
69    /// A scene the engine no longer uses. Drop it here, off the audio thread.
70    SceneRetired(Arc<Scene>),
71    /// A [`Command::Press`] started a voice with this tag.
72    VoiceStarted { tag: u32 },
73    /// A voice with this tag ended (it ran out, was released and faded, was stopped, or was stolen).
74    VoiceEnded { tag: u32 },
75    /// A command named a sound the scene does not have, or a gain that is not finite.
76    Rejected { tag: u32 },
77}
78
79/// Options for [`engine`].
80#[derive(Debug, Clone, Copy, Default)]
81pub struct EngineOptions {
82    /// Room, in frames, for the dry tap. Zero means no tap.
83    pub dry_tap_frames: usize,
84}
85
86/// Why an engine could not be made.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum EngineError {
89    /// The sample rate or channel count is zero.
90    InvalidConfig,
91}
92
93impl std::fmt::Display for EngineError {
94    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95        match self {
96            EngineError::InvalidConfig => write!(f, "the engine needs a sample rate and a channel count above zero"),
97        }
98    }
99}
100
101impl std::error::Error for EngineError {}
102
103/// A reading of the engine's clock, taken at the start of an audio callback.
104///
105/// `output_frame` counts every frame the engine has produced since it started, whatever the transport did. `transport_frame` is the scene
106/// cursor. `callback_ns` is when that callback began, on the monotonic clock of the engine ([`Engine::now_ns`]). A device adds its own
107/// output latency after this point; the engine does not know it.
108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
109pub struct Timing {
110    pub sample_rate: u32,
111    pub output_frame: u64,
112    pub transport_frame: u64,
113    pub playing: bool,
114    pub callback_ns: u64,
115    /// How many frames that callback produced.
116    pub block_frames: u32,
117    /// How many callbacks have run.
118    pub callbacks: u64,
119}
120
121impl Timing {
122    /// The output frame that is being produced at monotonic time `ns` (an estimate; it can be before `output_frame` for an earlier time).
123    pub fn output_frame_at(&self, ns: u64) -> i64 {
124        let dt = i128::from(ns) - i128::from(self.callback_ns);
125        self.output_frame as i64 + (dt * i128::from(self.sample_rate) / 1_000_000_000) as i64
126    }
127
128    /// The monotonic time, in nanoseconds, at which output frame `frame` is produced (an estimate).
129    pub fn ns_of_output_frame(&self, frame: u64) -> i64 {
130        let df = i128::from(frame) - i128::from(self.output_frame);
131        self.callback_ns as i64 + (df * 1_000_000_000 / i128::from(self.sample_rate)) as i64
132    }
133}
134
135/// The clock the audio thread writes and any thread reads, with a sequence number so a reader never sees half of an update.
136struct SharedClock {
137    seq: AtomicU64,
138    output_frame: AtomicU64,
139    transport_frame: AtomicU64,
140    playing: AtomicBool,
141    callback_ns: AtomicU64,
142    block_frames: AtomicU32,
143    callbacks: AtomicU64,
144}
145
146impl SharedClock {
147    fn new() -> SharedClock {
148        SharedClock {
149            seq: AtomicU64::new(0),
150            output_frame: AtomicU64::new(0),
151            transport_frame: AtomicU64::new(0),
152            playing: AtomicBool::new(false),
153            callback_ns: AtomicU64::new(0),
154            block_frames: AtomicU32::new(0),
155            callbacks: AtomicU64::new(0),
156        }
157    }
158
159    fn write(&self, t: &Timing) {
160        let s = self.seq.load(Ordering::Relaxed);
161        self.seq.store(s + 1, Ordering::Relaxed);
162        fence(Ordering::Release);
163        self.output_frame.store(t.output_frame, Ordering::Relaxed);
164        self.transport_frame.store(t.transport_frame, Ordering::Relaxed);
165        self.playing.store(t.playing, Ordering::Relaxed);
166        self.callback_ns.store(t.callback_ns, Ordering::Relaxed);
167        self.block_frames.store(t.block_frames, Ordering::Relaxed);
168        self.callbacks.store(t.callbacks, Ordering::Relaxed);
169        self.seq.store(s + 2, Ordering::Release);
170    }
171
172    fn read(&self, sample_rate: u32) -> Timing {
173        loop {
174            let a = self.seq.load(Ordering::Acquire);
175            if a & 1 == 1 {
176                std::hint::spin_loop();
177                continue;
178            }
179            let t = Timing {
180                sample_rate,
181                output_frame: self.output_frame.load(Ordering::Relaxed),
182                transport_frame: self.transport_frame.load(Ordering::Relaxed),
183                playing: self.playing.load(Ordering::Relaxed),
184                callback_ns: self.callback_ns.load(Ordering::Relaxed),
185                block_frames: self.block_frames.load(Ordering::Relaxed),
186                callbacks: self.callbacks.load(Ordering::Relaxed),
187            };
188            fence(Ordering::Acquire);
189            if self.seq.load(Ordering::Relaxed) == a {
190                return t;
191            }
192        }
193    }
194}
195
196struct Shared {
197    commands: ArrayQueue<Command>,
198    events: ArrayQueue<Event>,
199    dry: Option<ArrayQueue<f32>>,
200    clock: SharedClock,
201    dropped_events: AtomicU64,
202    dropped_dry_samples: AtomicU64,
203}
204
205/// The control half: send commands, read events and the clock. Cheap to share by reference between threads.
206pub struct Engine {
207    shared: Arc<Shared>,
208    config: SinkConfig,
209    origin: Instant,
210}
211
212impl Engine {
213    /// Queues a command for the next device block. `Err` gives the command back when the queue is full (512 deep).
214    pub fn send(&self, command: Command) -> Result<(), Command> {
215        self.shared.commands.push(command)
216    }
217
218    /// The next event from the audio thread, if there is one.
219    pub fn poll_event(&self) -> Option<Event> {
220        self.shared.events.pop()
221    }
222
223    /// The latest clock reading.
224    pub fn timing(&self) -> Timing {
225        self.shared.clock.read(self.config.sample_rate)
226    }
227
228    /// Monotonic nanoseconds since the engine was made: the time base of [`Timing::callback_ns`].
229    pub fn now_ns(&self) -> u64 {
230        self.origin.elapsed().as_nanos() as u64
231    }
232
233    pub fn config(&self) -> SinkConfig {
234        self.config
235    }
236
237    /// Events the audio thread had to drop because the event queue was full. Scene retirements are never dropped.
238    pub fn dropped_events(&self) -> u64 {
239        self.shared.dropped_events.load(Ordering::Relaxed)
240    }
241
242    /// Samples of the dry tap that were lost because nobody read them in time.
243    pub fn dropped_dry_samples(&self) -> u64 {
244        self.shared.dropped_dry_samples.load(Ordering::Relaxed)
245    }
246
247    /// Reads up to `out.len()` interleaved samples of the dry bus. Returns how many it wrote. Zero if there is no tap.
248    pub fn read_dry(&self, out: &mut [f32]) -> usize {
249        let Some(q) = &self.shared.dry else { return 0 };
250        let mut n = 0;
251        while n < out.len() {
252            match q.pop() {
253                Some(s) => {
254                    out[n] = s;
255                    n += 1;
256                }
257                None => break,
258            }
259        }
260        n
261    }
262}
263
264/// The audio half: owned by the device callback.
265pub struct EngineAudio {
266    shared: Arc<Shared>,
267    channels: usize,
268    active: SceneRenderer,
269    tail: SceneRenderer,
270    silent: Arc<Scene>,
271    playing: bool,
272    gain: f32,
273    pending_retire: Option<Arc<Scene>>,
274    deferred: Option<Command>,
275    dry: Vec<f32>,
276    scratch: Vec<f32>,
277    output_frame: u64,
278    callbacks: u64,
279    origin: Instant,
280    sample_rate: u32,
281}
282
283/// Makes an engine for `config`. It starts stopped, with an empty scene: presses sound once a scene with sounds is set.
284pub fn engine(config: SinkConfig, options: EngineOptions) -> Result<(Engine, EngineAudio), EngineError> {
285    if config.sample_rate == 0 || config.channels == 0 {
286        return Err(EngineError::InvalidConfig);
287    }
288    let silent = Arc::new(Scene::new(config.sample_rate, config.channels, Vec::new(), Vec::new(), 0).map_err(|_| EngineError::InvalidConfig)?);
289    let shared = Arc::new(Shared {
290        commands: ArrayQueue::new(COMMAND_CAPACITY),
291        events: ArrayQueue::new(EVENT_CAPACITY),
292        dry: (options.dry_tap_frames > 0).then(|| ArrayQueue::new(options.dry_tap_frames * usize::from(config.channels))),
293        clock: SharedClock::new(),
294        dropped_events: AtomicU64::new(0),
295        dropped_dry_samples: AtomicU64::new(0),
296    });
297    let origin = Instant::now();
298    let ch = usize::from(config.channels);
299    let audio = EngineAudio {
300        shared: shared.clone(),
301        channels: ch,
302        active: SceneRenderer::new(silent.clone()),
303        tail: SceneRenderer::new(silent.clone()),
304        silent,
305        playing: false,
306        gain: 1.0,
307        pending_retire: None,
308        deferred: None,
309        dry: vec![0.0; CHUNK_FRAMES * ch],
310        scratch: vec![0.0; CHUNK_FRAMES * ch],
311        output_frame: 0,
312        callbacks: 0,
313        origin,
314        sample_rate: config.sample_rate,
315    };
316    Ok((Engine { shared, config, origin }, audio))
317}
318
319impl EngineAudio {
320    /// The device callback for this engine.
321    pub fn into_render(mut self) -> RenderFn {
322        Box::new(move |out| self.render(out))
323    }
324
325    /// Fills one device block. Allocation-free and lock-free.
326    pub fn render(&mut self, out: &mut [f32]) {
327        let started = self.origin.elapsed().as_nanos() as u64;
328        self.flush_retire();
329        self.apply_commands();
330        let ch = self.channels;
331        let frames = out.len() / ch;
332        let transport_frame = self.active.cursor();
333        let (done_out, rest) = out.split_at_mut(frames * ch);
334        rest.fill(0.0);
335        let mut off = 0;
336        while off < done_out.len() {
337            let end = (off + CHUNK_FRAMES * ch).min(done_out.len());
338            self.render_chunk(&mut done_out[off..end]);
339            off = end;
340        }
341        self.finish_block();
342        self.callbacks += 1;
343        self.output_frame += frames as u64;
344        self.shared.clock.write(&Timing {
345            sample_rate: self.sample_rate,
346            output_frame: self.output_frame - frames as u64,
347            transport_frame,
348            playing: self.playing,
349            callback_ns: started,
350            block_frames: frames as u32,
351            callbacks: self.callbacks,
352        });
353    }
354
355    fn render_chunk(&mut self, out: &mut [f32]) {
356        let n = out.len();
357        let dry = &mut self.dry[..n];
358        if self.playing {
359            self.active.render(dry);
360        } else {
361            self.active.render_voices(dry);
362        }
363        self.tail.render_voices(&mut self.scratch[..n]);
364        for (d, s) in dry.iter_mut().zip(&self.scratch[..n]) {
365            *d += s;
366        }
367        if let Some(q) = &self.shared.dry {
368            let mut lost = 0u64;
369            for s in dry.iter() {
370                if q.push(*s).is_err() {
371                    lost += 1;
372                }
373            }
374            if lost > 0 {
375                self.shared.dropped_dry_samples.fetch_add(lost, Ordering::Relaxed);
376            }
377        }
378        // The monitor bus: the dry bus now, and the inputs of other sources when there are any.
379        for (o, d) in out.iter_mut().zip(dry.iter()) {
380            *o = *d * self.gain;
381        }
382    }
383
384    fn push_event(&self, e: Event) {
385        if self.shared.events.push(e).is_err() {
386            self.shared.dropped_events.fetch_add(1, Ordering::Relaxed);
387        }
388    }
389
390    fn flush_retire(&mut self) {
391        if let Some(s) = self.pending_retire.take()
392            && let Err(e) = self.shared.events.push(Event::SceneRetired(s))
393            && let Event::SceneRetired(s) = e
394        {
395            self.pending_retire = Some(s);
396        }
397    }
398
399    fn apply_commands(&mut self) {
400        if let Some(c) = self.deferred.take()
401            && !self.apply(c)
402        {
403            return;
404        }
405        while let Some(c) = self.shared.commands.pop() {
406            if !self.apply(c) {
407                return;
408            }
409        }
410    }
411
412    /// `false` when the command must wait (it is stored in `deferred`).
413    fn apply(&mut self, c: Command) -> bool {
414        match c {
415            Command::Press { sound, gain, gated, tag } => {
416                if self.active.press(sound, gain, gated, tag) {
417                    self.push_event(Event::VoiceStarted { tag });
418                } else {
419                    self.push_event(Event::Rejected { tag });
420                }
421            }
422            Command::Release { tag } => {
423                self.active.release(tag);
424                self.tail.release(tag);
425            }
426            Command::Play => self.playing = true,
427            Command::Pause => self.playing = false,
428            Command::Locate(frame) => self.active.locate(frame),
429            Command::SetScene(scene) => {
430                if self.pending_retire.is_some() || scene.sample_rate() != self.sample_rate || usize::from(scene.channels()) != self.channels {
431                    if self.pending_retire.is_some() {
432                        self.deferred = Some(Command::SetScene(scene));
433                        return false;
434                    }
435                    // A scene for another format cannot play: send it straight back.
436                    self.pending_retire = Some(scene);
437                    self.push_event(Event::Rejected { tag: NO_TAG });
438                    self.flush_retire();
439                    return true;
440                }
441                let cursor = self.active.cursor();
442                std::mem::swap(&mut self.active, &mut self.tail);
443                // `active` now holds what the tail had: its scene is done with, and its voices stop.
444                let old_tail = self.active.replace_scene(scene, cursor);
445                if !Arc::ptr_eq(&old_tail, &self.silent) {
446                    self.pending_retire = Some(old_tail);
447                }
448                self.flush_retire();
449            }
450            Command::SetGain(g) => {
451                if g.is_finite() {
452                    self.gain = g;
453                }
454            }
455            Command::Panic => {
456                self.active.stop_all();
457                self.tail.stop_all();
458            }
459        }
460        true
461    }
462
463    fn finish_block(&mut self) {
464        let mut ended = [NO_TAG; 64];
465        let mut n = 0;
466        self.active.drain_ended(|t| {
467            if n < ended.len() {
468                ended[n] = t;
469                n += 1;
470            }
471        });
472        self.tail.drain_ended(|t| {
473            if n < ended.len() {
474                ended[n] = t;
475                n += 1;
476            }
477        });
478        for tag in &ended[..n] {
479            self.push_event(Event::VoiceEnded { tag: *tag });
480        }
481        if self.pending_retire.is_none() && self.tail.active_voices() == 0 && !Arc::ptr_eq(self.tail.scene(), &self.silent) {
482            let old = self.tail.replace_scene(self.silent.clone(), 0);
483            self.pending_retire = Some(old);
484            self.flush_retire();
485        }
486    }
487}