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    gain_now: f32,
274    rendered: bool,
275    pending_retire: Option<Arc<Scene>>,
276    deferred: Option<Command>,
277    dry: Vec<f32>,
278    scratch: Vec<f32>,
279    output_frame: u64,
280    callbacks: u64,
281    origin: Instant,
282    sample_rate: u32,
283}
284
285/// Makes an engine for `config`. It starts stopped, with an empty scene: presses sound once a scene with sounds is set.
286pub fn engine(config: SinkConfig, options: EngineOptions) -> Result<(Engine, EngineAudio), EngineError> {
287    if config.sample_rate == 0 || config.channels == 0 {
288        return Err(EngineError::InvalidConfig);
289    }
290    let silent = Arc::new(Scene::new(config.sample_rate, config.channels, Vec::new(), Vec::new(), 0).map_err(|_| EngineError::InvalidConfig)?);
291    let shared = Arc::new(Shared {
292        commands: ArrayQueue::new(COMMAND_CAPACITY),
293        events: ArrayQueue::new(EVENT_CAPACITY),
294        dry: (options.dry_tap_frames > 0).then(|| ArrayQueue::new(options.dry_tap_frames * usize::from(config.channels))),
295        clock: SharedClock::new(),
296        dropped_events: AtomicU64::new(0),
297        dropped_dry_samples: AtomicU64::new(0),
298    });
299    let origin = Instant::now();
300    let ch = usize::from(config.channels);
301    let audio = EngineAudio {
302        shared: shared.clone(),
303        channels: ch,
304        active: SceneRenderer::new(silent.clone()),
305        tail: SceneRenderer::new(silent.clone()),
306        silent,
307        playing: false,
308        gain: 1.0,
309        gain_now: 1.0,
310        rendered: false,
311        pending_retire: None,
312        deferred: None,
313        dry: vec![0.0; CHUNK_FRAMES * ch],
314        scratch: vec![0.0; CHUNK_FRAMES * ch],
315        output_frame: 0,
316        callbacks: 0,
317        origin,
318        sample_rate: config.sample_rate,
319    };
320    Ok((Engine { shared, config, origin }, audio))
321}
322
323impl EngineAudio {
324    /// The device callback for this engine.
325    pub fn into_render(mut self) -> RenderFn {
326        Box::new(move |out| self.render(out))
327    }
328
329    /// Fills one device block. Allocation-free and lock-free.
330    pub fn render(&mut self, out: &mut [f32]) {
331        let started = self.origin.elapsed().as_nanos() as u64;
332        self.flush_retire();
333        self.apply_commands();
334        let ch = self.channels;
335        let frames = out.len() / ch;
336        let transport_frame = self.active.cursor();
337        let (done_out, rest) = out.split_at_mut(frames * ch);
338        rest.fill(0.0);
339        let mut off = 0;
340        while off < done_out.len() {
341            let end = (off + CHUNK_FRAMES * ch).min(done_out.len());
342            self.render_chunk(&mut done_out[off..end]);
343            off = end;
344        }
345        self.finish_block();
346        self.callbacks += 1;
347        self.output_frame += frames as u64;
348        self.shared.clock.write(&Timing {
349            sample_rate: self.sample_rate,
350            output_frame: self.output_frame - frames as u64,
351            transport_frame,
352            playing: self.playing,
353            callback_ns: started,
354            block_frames: frames as u32,
355            callbacks: self.callbacks,
356        });
357    }
358
359    fn render_chunk(&mut self, out: &mut [f32]) {
360        let n = out.len();
361        let dry = &mut self.dry[..n];
362        if self.playing {
363            self.active.render(dry);
364        } else {
365            self.active.render_voices(dry);
366        }
367        self.tail.render_voices(&mut self.scratch[..n]);
368        for (d, s) in dry.iter_mut().zip(&self.scratch[..n]) {
369            *d += s;
370        }
371        if let Some(q) = &self.shared.dry {
372            let mut lost = 0u64;
373            for s in dry.iter() {
374                if q.push(*s).is_err() {
375                    lost += 1;
376                }
377            }
378            if lost > 0 {
379                self.shared.dropped_dry_samples.fetch_add(lost, Ordering::Relaxed);
380            }
381        }
382        // The monitor bus: the dry bus now, and the inputs of other sources when there are any.
383        self.rendered = true;
384        // A gain change ramps across one block, so a fader or a ducker does not click.
385        if self.gain_now == self.gain || out.is_empty() {
386            for (o, d) in out.iter_mut().zip(dry.iter()) {
387                *o = *d * self.gain;
388            }
389        } else {
390            let step = (self.gain - self.gain_now) / out.len() as f32;
391            for (i, (o, d)) in out.iter_mut().zip(dry.iter()).enumerate() {
392                *o = *d * (self.gain_now + step * (i + 1) as f32);
393            }
394            self.gain_now = self.gain;
395        }
396    }
397
398    fn push_event(&self, e: Event) {
399        if self.shared.events.push(e).is_err() {
400            self.shared.dropped_events.fetch_add(1, Ordering::Relaxed);
401        }
402    }
403
404    fn flush_retire(&mut self) {
405        if let Some(s) = self.pending_retire.take()
406            && let Err(e) = self.shared.events.push(Event::SceneRetired(s))
407            && let Event::SceneRetired(s) = e
408        {
409            self.pending_retire = Some(s);
410        }
411    }
412
413    fn apply_commands(&mut self) {
414        if let Some(c) = self.deferred.take()
415            && !self.apply(c)
416        {
417            return;
418        }
419        while let Some(c) = self.shared.commands.pop() {
420            if !self.apply(c) {
421                return;
422            }
423        }
424    }
425
426    /// `false` when the command must wait (it is stored in `deferred`).
427    fn apply(&mut self, c: Command) -> bool {
428        match c {
429            Command::Press { sound, gain, gated, tag } => {
430                if self.active.press(sound, gain, gated, tag) {
431                    self.push_event(Event::VoiceStarted { tag });
432                } else {
433                    self.push_event(Event::Rejected { tag });
434                }
435            }
436            Command::Release { tag } => {
437                self.active.release(tag);
438                self.tail.release(tag);
439            }
440            Command::Play => self.playing = true,
441            Command::Pause => self.playing = false,
442            Command::Locate(frame) => self.active.locate(frame),
443            Command::SetScene(scene) => {
444                if self.pending_retire.is_some() || scene.sample_rate() != self.sample_rate || usize::from(scene.channels()) != self.channels {
445                    if self.pending_retire.is_some() {
446                        self.deferred = Some(Command::SetScene(scene));
447                        return false;
448                    }
449                    // A scene for another format cannot play: send it straight back.
450                    self.pending_retire = Some(scene);
451                    self.push_event(Event::Rejected { tag: NO_TAG });
452                    self.flush_retire();
453                    return true;
454                }
455                let cursor = self.active.cursor();
456                std::mem::swap(&mut self.active, &mut self.tail);
457                // `active` now holds what the tail had: its scene is done with, and its voices stop.
458                let old_tail = self.active.replace_scene(scene, cursor);
459                if !Arc::ptr_eq(&old_tail, &self.silent) {
460                    self.pending_retire = Some(old_tail);
461                }
462                self.flush_retire();
463            }
464            Command::SetGain(g) => {
465                if g.is_finite() {
466                    self.gain = g;
467                    // before the first block there is nothing to ramp from
468                    if !self.rendered {
469                        self.gain_now = g;
470                    }
471                }
472            }
473            Command::Panic => {
474                self.active.stop_all();
475                self.tail.stop_all();
476            }
477        }
478        true
479    }
480
481    fn finish_block(&mut self) {
482        let mut ended = [NO_TAG; 64];
483        let mut n = 0;
484        self.active.drain_ended(|t| {
485            if n < ended.len() {
486                ended[n] = t;
487                n += 1;
488            }
489        });
490        self.tail.drain_ended(|t| {
491            if n < ended.len() {
492                ended[n] = t;
493                n += 1;
494            }
495        });
496        for tag in &ended[..n] {
497            self.push_event(Event::VoiceEnded { tag: *tag });
498        }
499        if self.pending_retire.is_none() && self.tail.active_voices() == 0 && !Arc::ptr_eq(self.tail.scene(), &self.silent) {
500            let old = self.tail.replace_scene(self.silent.clone(), 0);
501            self.pending_retire = Some(old);
502            self.flush_retire();
503        }
504    }
505}