weirdnet-audio-engine 0.3.0

Audio engine pieces for Weirdnet: the AudioSink trait, a manual sink for tests, a cpal device sink (feature `cpal`) and a waveform player.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! The live engine: a transport, a voice mixer and lock-free queues between a control thread and the audio callback.
//!
//! [`engine`] returns two halves. [`Engine`] stays with the control thread (a UI, a hot key handler): it sends [`Command`]s and reads
//! [`Event`]s and the [`Timing`] of the clock. [`EngineAudio`] goes to the device ([`EngineAudio::into_render`] makes the callback for an
//! [`crate::AudioSink`]). The callback never locks, blocks or allocates: commands come through a bounded lock-free queue, a new
//! [`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.
//!
//! The mixer is the one in [`crate::SceneRenderer`], so a loop played here matches [`crate::render_offline`] sample for sample, whatever
//! the device's block size.
//!
//! 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
//! 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.
//!
//! ```
//! use std::sync::Arc;
//! use weirdnet_audio_engine::{AudioSink, Command, EngineOptions, ManualSink, Scene, SinkConfig, engine};
//! use weirdnet_media::waveform::Waveform;
//!
//! let config = SinkConfig::new(48_000, 1);
//! let (control, audio) = engine(config, EngineOptions::default())?;
//! let scene = Scene::new(48_000, 1, vec![Waveform::tone(48_000, 440.0, 480, 0.5)?], vec![], 0)?;
//! control.send(Command::SetScene(Arc::new(scene))).unwrap();
//! control.send(Command::Press { sound: 0, gain: 1.0, gated: false, tag: 7 }).unwrap();
//! let mut sink = ManualSink::new();
//! let _running = sink.start(config, audio.into_render())?;
//! let block = sink.render_block(256).expect("the sink is running");
//! assert!(block.iter().any(|s| s.abs() > 0.1));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::scene::{NO_TAG, Scene, SceneRenderer};
use crate::sink::{RenderFn, SinkConfig};
use crossbeam_queue::ArrayQueue;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering, fence};
use std::time::Instant;

/// 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.
const CHUNK_FRAMES: usize = 1024;
const COMMAND_CAPACITY: usize = 512;
const EVENT_CAPACITY: usize = 512;

/// What the control thread asks of the audio thread. Applied at the start of the next device block.
#[derive(Debug, Clone)]
pub enum Command {
    /// Starts sound `sound` of the current scene now. A `gated` voice plays until a [`Command::Release`] with its `tag` and then fades
    /// out; one that is not gated plays to its end. Plays whether or not the transport runs.
    Press { sound: u32, gain: f32, gated: bool, tag: u32 },
    /// Fades out every held voice with this tag.
    Release { tag: u32 },
    /// Starts the transport: scene events play from the cursor.
    Play,
    /// Stops the transport where it is. Voices that are sounding finish, and live presses still sound.
    Pause,
    /// Moves the transport cursor, in frames. In a looping scene it wraps into the loop. Sounding voices carry on.
    Locate(u64),
    /// Replaces the scene at a block boundary, keeping the cursor. Voices of the old scene finish on the old scene's sounds. While the
    /// engine still holds a previous retired scene the swap waits for the next block.
    SetScene(Arc<Scene>),
    /// Master gain on the dry bus, linear.
    SetGain(f32),
    /// Stops every voice at once.
    Panic,
}

/// What the audio thread tells the control thread.
#[derive(Debug, Clone)]
pub enum Event {
    /// A scene the engine no longer uses. Drop it here, off the audio thread.
    SceneRetired(Arc<Scene>),
    /// A [`Command::Press`] started a voice with this tag.
    VoiceStarted { tag: u32 },
    /// A voice with this tag ended (it ran out, was released and faded, was stopped, or was stolen).
    VoiceEnded { tag: u32 },
    /// A command named a sound the scene does not have, or a gain that is not finite.
    Rejected { tag: u32 },
}

/// Options for [`engine`].
#[derive(Debug, Clone, Copy, Default)]
pub struct EngineOptions {
    /// Room, in frames, for the dry tap. Zero means no tap.
    pub dry_tap_frames: usize,
}

/// Why an engine could not be made.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EngineError {
    /// The sample rate or channel count is zero.
    InvalidConfig,
}

impl std::fmt::Display for EngineError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EngineError::InvalidConfig => write!(f, "the engine needs a sample rate and a channel count above zero"),
        }
    }
}

impl std::error::Error for EngineError {}

/// A reading of the engine's clock, taken at the start of an audio callback.
///
/// `output_frame` counts every frame the engine has produced since it started, whatever the transport did. `transport_frame` is the scene
/// cursor. `callback_ns` is when that callback began, on the monotonic clock of the engine ([`Engine::now_ns`]). A device adds its own
/// output latency after this point; the engine does not know it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timing {
    pub sample_rate: u32,
    pub output_frame: u64,
    pub transport_frame: u64,
    pub playing: bool,
    pub callback_ns: u64,
    /// How many frames that callback produced.
    pub block_frames: u32,
    /// How many callbacks have run.
    pub callbacks: u64,
}

impl Timing {
    /// The output frame that is being produced at monotonic time `ns` (an estimate; it can be before `output_frame` for an earlier time).
    pub fn output_frame_at(&self, ns: u64) -> i64 {
        let dt = i128::from(ns) - i128::from(self.callback_ns);
        self.output_frame as i64 + (dt * i128::from(self.sample_rate) / 1_000_000_000) as i64
    }

    /// The monotonic time, in nanoseconds, at which output frame `frame` is produced (an estimate).
    pub fn ns_of_output_frame(&self, frame: u64) -> i64 {
        let df = i128::from(frame) - i128::from(self.output_frame);
        self.callback_ns as i64 + (df * 1_000_000_000 / i128::from(self.sample_rate)) as i64
    }
}

/// The clock the audio thread writes and any thread reads, with a sequence number so a reader never sees half of an update.
struct SharedClock {
    seq: AtomicU64,
    output_frame: AtomicU64,
    transport_frame: AtomicU64,
    playing: AtomicBool,
    callback_ns: AtomicU64,
    block_frames: AtomicU32,
    callbacks: AtomicU64,
}

impl SharedClock {
    fn new() -> SharedClock {
        SharedClock {
            seq: AtomicU64::new(0),
            output_frame: AtomicU64::new(0),
            transport_frame: AtomicU64::new(0),
            playing: AtomicBool::new(false),
            callback_ns: AtomicU64::new(0),
            block_frames: AtomicU32::new(0),
            callbacks: AtomicU64::new(0),
        }
    }

    fn write(&self, t: &Timing) {
        let s = self.seq.load(Ordering::Relaxed);
        self.seq.store(s + 1, Ordering::Relaxed);
        fence(Ordering::Release);
        self.output_frame.store(t.output_frame, Ordering::Relaxed);
        self.transport_frame.store(t.transport_frame, Ordering::Relaxed);
        self.playing.store(t.playing, Ordering::Relaxed);
        self.callback_ns.store(t.callback_ns, Ordering::Relaxed);
        self.block_frames.store(t.block_frames, Ordering::Relaxed);
        self.callbacks.store(t.callbacks, Ordering::Relaxed);
        self.seq.store(s + 2, Ordering::Release);
    }

    fn read(&self, sample_rate: u32) -> Timing {
        loop {
            let a = self.seq.load(Ordering::Acquire);
            if a & 1 == 1 {
                std::hint::spin_loop();
                continue;
            }
            let t = Timing {
                sample_rate,
                output_frame: self.output_frame.load(Ordering::Relaxed),
                transport_frame: self.transport_frame.load(Ordering::Relaxed),
                playing: self.playing.load(Ordering::Relaxed),
                callback_ns: self.callback_ns.load(Ordering::Relaxed),
                block_frames: self.block_frames.load(Ordering::Relaxed),
                callbacks: self.callbacks.load(Ordering::Relaxed),
            };
            fence(Ordering::Acquire);
            if self.seq.load(Ordering::Relaxed) == a {
                return t;
            }
        }
    }
}

struct Shared {
    commands: ArrayQueue<Command>,
    events: ArrayQueue<Event>,
    dry: Option<ArrayQueue<f32>>,
    clock: SharedClock,
    dropped_events: AtomicU64,
    dropped_dry_samples: AtomicU64,
}

/// The control half: send commands, read events and the clock. Cheap to share by reference between threads.
pub struct Engine {
    shared: Arc<Shared>,
    config: SinkConfig,
    origin: Instant,
}

impl Engine {
    /// Queues a command for the next device block. `Err` gives the command back when the queue is full (512 deep).
    pub fn send(&self, command: Command) -> Result<(), Command> {
        self.shared.commands.push(command)
    }

    /// The next event from the audio thread, if there is one.
    pub fn poll_event(&self) -> Option<Event> {
        self.shared.events.pop()
    }

    /// The latest clock reading.
    pub fn timing(&self) -> Timing {
        self.shared.clock.read(self.config.sample_rate)
    }

    /// Monotonic nanoseconds since the engine was made: the time base of [`Timing::callback_ns`].
    pub fn now_ns(&self) -> u64 {
        self.origin.elapsed().as_nanos() as u64
    }

    pub fn config(&self) -> SinkConfig {
        self.config
    }

    /// Events the audio thread had to drop because the event queue was full. Scene retirements are never dropped.
    pub fn dropped_events(&self) -> u64 {
        self.shared.dropped_events.load(Ordering::Relaxed)
    }

    /// Samples of the dry tap that were lost because nobody read them in time.
    pub fn dropped_dry_samples(&self) -> u64 {
        self.shared.dropped_dry_samples.load(Ordering::Relaxed)
    }

    /// Reads up to `out.len()` interleaved samples of the dry bus. Returns how many it wrote. Zero if there is no tap.
    pub fn read_dry(&self, out: &mut [f32]) -> usize {
        let Some(q) = &self.shared.dry else { return 0 };
        let mut n = 0;
        while n < out.len() {
            match q.pop() {
                Some(s) => {
                    out[n] = s;
                    n += 1;
                }
                None => break,
            }
        }
        n
    }
}

/// The audio half: owned by the device callback.
pub struct EngineAudio {
    shared: Arc<Shared>,
    channels: usize,
    active: SceneRenderer,
    tail: SceneRenderer,
    silent: Arc<Scene>,
    playing: bool,
    gain: f32,
    pending_retire: Option<Arc<Scene>>,
    deferred: Option<Command>,
    dry: Vec<f32>,
    scratch: Vec<f32>,
    output_frame: u64,
    callbacks: u64,
    origin: Instant,
    sample_rate: u32,
}

/// Makes an engine for `config`. It starts stopped, with an empty scene: presses sound once a scene with sounds is set.
pub fn engine(config: SinkConfig, options: EngineOptions) -> Result<(Engine, EngineAudio), EngineError> {
    if config.sample_rate == 0 || config.channels == 0 {
        return Err(EngineError::InvalidConfig);
    }
    let silent = Arc::new(Scene::new(config.sample_rate, config.channels, Vec::new(), Vec::new(), 0).map_err(|_| EngineError::InvalidConfig)?);
    let shared = Arc::new(Shared {
        commands: ArrayQueue::new(COMMAND_CAPACITY),
        events: ArrayQueue::new(EVENT_CAPACITY),
        dry: (options.dry_tap_frames > 0).then(|| ArrayQueue::new(options.dry_tap_frames * usize::from(config.channels))),
        clock: SharedClock::new(),
        dropped_events: AtomicU64::new(0),
        dropped_dry_samples: AtomicU64::new(0),
    });
    let origin = Instant::now();
    let ch = usize::from(config.channels);
    let audio = EngineAudio {
        shared: shared.clone(),
        channels: ch,
        active: SceneRenderer::new(silent.clone()),
        tail: SceneRenderer::new(silent.clone()),
        silent,
        playing: false,
        gain: 1.0,
        pending_retire: None,
        deferred: None,
        dry: vec![0.0; CHUNK_FRAMES * ch],
        scratch: vec![0.0; CHUNK_FRAMES * ch],
        output_frame: 0,
        callbacks: 0,
        origin,
        sample_rate: config.sample_rate,
    };
    Ok((Engine { shared, config, origin }, audio))
}

impl EngineAudio {
    /// The device callback for this engine.
    pub fn into_render(mut self) -> RenderFn {
        Box::new(move |out| self.render(out))
    }

    /// Fills one device block. Allocation-free and lock-free.
    pub fn render(&mut self, out: &mut [f32]) {
        let started = self.origin.elapsed().as_nanos() as u64;
        self.flush_retire();
        self.apply_commands();
        let ch = self.channels;
        let frames = out.len() / ch;
        let transport_frame = self.active.cursor();
        let (done_out, rest) = out.split_at_mut(frames * ch);
        rest.fill(0.0);
        let mut off = 0;
        while off < done_out.len() {
            let end = (off + CHUNK_FRAMES * ch).min(done_out.len());
            self.render_chunk(&mut done_out[off..end]);
            off = end;
        }
        self.finish_block();
        self.callbacks += 1;
        self.output_frame += frames as u64;
        self.shared.clock.write(&Timing {
            sample_rate: self.sample_rate,
            output_frame: self.output_frame - frames as u64,
            transport_frame,
            playing: self.playing,
            callback_ns: started,
            block_frames: frames as u32,
            callbacks: self.callbacks,
        });
    }

    fn render_chunk(&mut self, out: &mut [f32]) {
        let n = out.len();
        let dry = &mut self.dry[..n];
        if self.playing {
            self.active.render(dry);
        } else {
            self.active.render_voices(dry);
        }
        self.tail.render_voices(&mut self.scratch[..n]);
        for (d, s) in dry.iter_mut().zip(&self.scratch[..n]) {
            *d += s;
        }
        if let Some(q) = &self.shared.dry {
            let mut lost = 0u64;
            for s in dry.iter() {
                if q.push(*s).is_err() {
                    lost += 1;
                }
            }
            if lost > 0 {
                self.shared.dropped_dry_samples.fetch_add(lost, Ordering::Relaxed);
            }
        }
        // The monitor bus: the dry bus now, and the inputs of other sources when there are any.
        for (o, d) in out.iter_mut().zip(dry.iter()) {
            *o = *d * self.gain;
        }
    }

    fn push_event(&self, e: Event) {
        if self.shared.events.push(e).is_err() {
            self.shared.dropped_events.fetch_add(1, Ordering::Relaxed);
        }
    }

    fn flush_retire(&mut self) {
        if let Some(s) = self.pending_retire.take()
            && let Err(e) = self.shared.events.push(Event::SceneRetired(s))
            && let Event::SceneRetired(s) = e
        {
            self.pending_retire = Some(s);
        }
    }

    fn apply_commands(&mut self) {
        if let Some(c) = self.deferred.take()
            && !self.apply(c)
        {
            return;
        }
        while let Some(c) = self.shared.commands.pop() {
            if !self.apply(c) {
                return;
            }
        }
    }

    /// `false` when the command must wait (it is stored in `deferred`).
    fn apply(&mut self, c: Command) -> bool {
        match c {
            Command::Press { sound, gain, gated, tag } => {
                if self.active.press(sound, gain, gated, tag) {
                    self.push_event(Event::VoiceStarted { tag });
                } else {
                    self.push_event(Event::Rejected { tag });
                }
            }
            Command::Release { tag } => {
                self.active.release(tag);
                self.tail.release(tag);
            }
            Command::Play => self.playing = true,
            Command::Pause => self.playing = false,
            Command::Locate(frame) => self.active.locate(frame),
            Command::SetScene(scene) => {
                if self.pending_retire.is_some() || scene.sample_rate() != self.sample_rate || usize::from(scene.channels()) != self.channels {
                    if self.pending_retire.is_some() {
                        self.deferred = Some(Command::SetScene(scene));
                        return false;
                    }
                    // A scene for another format cannot play: send it straight back.
                    self.pending_retire = Some(scene);
                    self.push_event(Event::Rejected { tag: NO_TAG });
                    self.flush_retire();
                    return true;
                }
                let cursor = self.active.cursor();
                std::mem::swap(&mut self.active, &mut self.tail);
                // `active` now holds what the tail had: its scene is done with, and its voices stop.
                let old_tail = self.active.replace_scene(scene, cursor);
                if !Arc::ptr_eq(&old_tail, &self.silent) {
                    self.pending_retire = Some(old_tail);
                }
                self.flush_retire();
            }
            Command::SetGain(g) => {
                if g.is_finite() {
                    self.gain = g;
                }
            }
            Command::Panic => {
                self.active.stop_all();
                self.tail.stop_all();
            }
        }
        true
    }

    fn finish_block(&mut self) {
        let mut ended = [NO_TAG; 64];
        let mut n = 0;
        self.active.drain_ended(|t| {
            if n < ended.len() {
                ended[n] = t;
                n += 1;
            }
        });
        self.tail.drain_ended(|t| {
            if n < ended.len() {
                ended[n] = t;
                n += 1;
            }
        });
        for tag in &ended[..n] {
            self.push_event(Event::VoiceEnded { tag: *tag });
        }
        if self.pending_retire.is_none() && self.tail.active_voices() == 0 && !Arc::ptr_eq(self.tail.scene(), &self.silent) {
            let old = self.tail.replace_scene(self.silent.clone(), 0);
            self.pending_retire = Some(old);
            self.flush_retire();
        }
    }
}