Skip to main content

weirdnet_audio_engine/
scene.rs

1//! A [`Scene`] (sounds plus a sorted list of events in frames) and the [`SceneRenderer`] that mixes it.
2//!
3//! The renderer is the one mixer: a device callback calls [`SceneRenderer::render`] block by block, and [`render_offline`] calls the same
4//! function without a device, so an export matches live playback sample for sample whatever the block size. Each block is split at event
5//! boundaries, so an event starts on its exact frame. Voices live in a fixed pool; nothing in [`SceneRenderer::render`] allocates.
6
7use std::sync::Arc;
8use weirdnet_media::waveform::Waveform;
9
10/// The size of the voice pool. When it is full, the oldest voice is stolen.
11pub const MAX_VOICES: usize = 64;
12
13/// One sound starting at a frame.
14#[derive(Debug, Clone, Copy, PartialEq)]
15pub struct SceneEvent {
16    /// The frame it starts on, counted from the start of the scene.
17    pub at: u64,
18    /// An index into [`Scene::sounds`].
19    pub sound: u32,
20    /// Linear gain.
21    pub gain: f32,
22    /// A gate: after this many frames the voice fades out over the scene's release. `None` plays the sound to its end.
23    pub gate_frames: Option<u64>,
24}
25
26impl SceneEvent {
27    /// A one-shot at `at` with unity gain.
28    pub fn new(at: u64, sound: u32) -> Self {
29        SceneEvent { at, sound, gain: 1.0, gate_frames: None }
30    }
31
32    pub fn with_gain(mut self, gain: f32) -> Self {
33        self.gain = gain;
34        self
35    }
36
37    pub fn with_gate(mut self, frames: u64) -> Self {
38        self.gate_frames = Some(frames);
39        self
40    }
41}
42
43/// Why a scene could not be built.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum SceneError {
46    ZeroSampleRate,
47    ZeroChannels,
48    /// A sound runs at another sample rate than the scene.
49    RateMismatch {
50        sound: u32,
51    },
52    /// A sound has a channel count other than the scene's or one.
53    ChannelMismatch {
54        sound: u32,
55    },
56    /// An event names a sound that does not exist.
57    UnknownSound {
58        event: usize,
59    },
60    /// An event's gain is not a finite number.
61    NotFinite {
62        event: usize,
63    },
64    /// A loop of zero frames.
65    ZeroLoop,
66}
67
68impl std::fmt::Display for SceneError {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        match self {
71            SceneError::ZeroSampleRate => write!(f, "the scene's sample rate is zero"),
72            SceneError::ZeroChannels => write!(f, "the scene's channel count is zero"),
73            SceneError::RateMismatch { sound } => write!(f, "sound {sound} has a different sample rate than the scene"),
74            SceneError::ChannelMismatch { sound } => write!(f, "sound {sound} is neither mono nor the scene's channel count"),
75            SceneError::UnknownSound { event } => write!(f, "event {event} names a sound that does not exist"),
76            SceneError::NotFinite { event } => write!(f, "event {event} has a gain that is not a finite number"),
77            SceneError::ZeroLoop => write!(f, "the loop is zero frames long"),
78        }
79    }
80}
81
82impl std::error::Error for SceneError {}
83
84/// Sounds and the events that play them. Immutable; share it with `Arc` and hand it to the audio thread whole.
85#[derive(Debug, Clone, PartialEq)]
86pub struct Scene {
87    sample_rate: u32,
88    channels: u16,
89    sounds: Vec<Waveform>,
90    events: Vec<SceneEvent>,
91    release_frames: u32,
92    loop_frames: Option<u64>,
93}
94
95impl Scene {
96    /// A scene. Every sound must run at `sample_rate` and have `channels` channels or be mono (a mono sound plays on every channel at
97    /// the same level). Events are sorted by frame (events on the same frame keep their order). `release_frames` is the fade-out of a
98    /// gated voice; zero cuts it.
99    pub fn new(
100        sample_rate: u32,
101        channels: u16,
102        sounds: Vec<Waveform>,
103        mut events: Vec<SceneEvent>,
104        release_frames: u32,
105    ) -> Result<Scene, SceneError> {
106        if sample_rate == 0 {
107            return Err(SceneError::ZeroSampleRate);
108        }
109        if channels == 0 {
110            return Err(SceneError::ZeroChannels);
111        }
112        for (i, s) in sounds.iter().enumerate() {
113            let sound = i as u32;
114            if s.sample_rate() != sample_rate {
115                return Err(SceneError::RateMismatch { sound });
116            }
117            if s.channels() != channels && s.channels() != 1 {
118                return Err(SceneError::ChannelMismatch { sound });
119            }
120        }
121        for (i, e) in events.iter().enumerate() {
122            if e.sound as usize >= sounds.len() {
123                return Err(SceneError::UnknownSound { event: i });
124            }
125            if !e.gain.is_finite() {
126                return Err(SceneError::NotFinite { event: i });
127            }
128        }
129        events.sort_by_key(|e| e.at);
130        Ok(Scene { sample_rate, channels, sounds, events, release_frames, loop_frames: None })
131    }
132
133    /// Makes the scene repeat every `frames` frames: when the cursor reaches the end it returns to frame 0, and voices that are sounding
134    /// carry on across the wrap. Events at or past `frames` never play.
135    pub fn with_loop(mut self, frames: u64) -> Result<Scene, SceneError> {
136        if frames == 0 {
137            return Err(SceneError::ZeroLoop);
138        }
139        self.loop_frames = Some(frames);
140        Ok(self)
141    }
142
143    /// The loop length in frames, if the scene repeats.
144    pub fn loop_frames(&self) -> Option<u64> {
145        self.loop_frames
146    }
147
148    pub fn sample_rate(&self) -> u32 {
149        self.sample_rate
150    }
151
152    pub fn channels(&self) -> u16 {
153        self.channels
154    }
155
156    pub fn sounds(&self) -> &[Waveform] {
157        &self.sounds
158    }
159
160    /// The events, sorted by frame.
161    pub fn events(&self) -> &[SceneEvent] {
162        &self.events
163    }
164
165    pub fn release_frames(&self) -> u32 {
166        self.release_frames
167    }
168
169    /// The frame after the last sample any event can make: the length that holds everything, tails included.
170    pub fn end_frame(&self) -> u64 {
171        let release = u64::from(self.release_frames);
172        self.events
173            .iter()
174            .map(|e| {
175                let len = self.sounds[e.sound as usize].frames() as u64;
176                e.at + match e.gate_frames {
177                    Some(g) => len.min(g.max(1) + release),
178                    None => len,
179                }
180            })
181            .max()
182            .unwrap_or(0)
183    }
184}
185
186/// A voice's tag when it was started by a scene event rather than a live press.
187pub const NO_TAG: u32 = u32::MAX;
188
189#[derive(Debug, Clone, Copy)]
190struct Voice {
191    active: bool,
192    sound: u32,
193    /// The next frame of the sound to play.
194    pos: u64,
195    gain: f32,
196    /// How many frames of the sound play before the fade-out begins (`u64::MAX`: never).
197    release_after: u64,
198    /// A live voice that plays until [`SceneRenderer::release`].
199    held: bool,
200    tag: u32,
201    /// Start order, to find the oldest voice.
202    serial: u64,
203}
204
205const IDLE: Voice = Voice { active: false, sound: 0, pos: 0, gain: 0.0, release_after: u64::MAX, held: false, tag: NO_TAG, serial: 0 };
206
207/// How many ended tagged voices a renderer remembers between calls to [`SceneRenderer::drain_ended`].
208const ENDED_CAPACITY: usize = 64;
209
210/// Mixes a [`Scene`] block by block.
211pub struct SceneRenderer {
212    scene: Arc<Scene>,
213    cursor: u64,
214    next_event: usize,
215    voices: Vec<Voice>,
216    serial: u64,
217    ended: [u32; ENDED_CAPACITY],
218    ended_len: usize,
219}
220
221impl SceneRenderer {
222    pub fn new(scene: Arc<Scene>) -> SceneRenderer {
223        SceneRenderer { scene, cursor: 0, next_event: 0, voices: vec![IDLE; MAX_VOICES], serial: 0, ended: [NO_TAG; ENDED_CAPACITY], ended_len: 0 }
224    }
225
226    pub fn scene(&self) -> &Arc<Scene> {
227        &self.scene
228    }
229
230    /// The frame the next block starts on (inside the loop, for a looping scene).
231    pub fn cursor(&self) -> u64 {
232        self.cursor
233    }
234
235    /// How many voices are sounding.
236    pub fn active_voices(&self) -> usize {
237        self.voices.iter().filter(|v| v.active).count()
238    }
239
240    /// Nothing is sounding and no event is left. A looping scene is never finished.
241    pub fn is_finished(&self) -> bool {
242        self.scene.loop_frames.is_none() && self.next_event >= self.scene.events.len() && self.active_voices() == 0
243    }
244
245    /// Moves to `frame`: every voice stops, and events from `frame` on are still to come.
246    pub fn seek(&mut self, frame: u64) {
247        self.voices.fill(IDLE);
248        self.locate(frame);
249    }
250
251    /// Moves to `frame` and lets the voices that are sounding finish. In a looping scene `frame` wraps into the loop.
252    pub fn locate(&mut self, frame: u64) {
253        let frame = match self.scene.loop_frames {
254            Some(l) => frame % l,
255            None => frame,
256        };
257        self.cursor = frame;
258        self.next_event = self.scene.events.partition_point(|e| e.at < frame);
259    }
260
261    /// Swaps the scene for `scene` and starts at `cursor`. Every voice stops. Returns the old scene, so the caller can drop it where
262    /// dropping is allowed.
263    pub fn replace_scene(&mut self, scene: Arc<Scene>, cursor: u64) -> Arc<Scene> {
264        self.voices.fill(IDLE);
265        self.ended_len = 0;
266        let old = std::mem::replace(&mut self.scene, scene);
267        self.locate(cursor);
268        old
269    }
270
271    /// Starts `sound` of the scene now, with `tag` to find it again. A `gated` voice plays until [`release`](Self::release) and then
272    /// fades out over the scene's release; one that is not gated plays to its end. `false` if the scene has no such sound.
273    pub fn press(&mut self, sound: u32, gain: f32, gated: bool, tag: u32) -> bool {
274        if sound as usize >= self.scene.sounds.len() || !gain.is_finite() {
275            return false;
276        }
277        let slot = self.free_slot();
278        self.serial += 1;
279        self.voices[slot] = Voice { active: true, sound, pos: 0, gain, release_after: u64::MAX, held: gated, tag, serial: self.serial };
280        true
281    }
282
283    /// Begins the fade-out of every held voice with `tag`. Returns how many it released.
284    pub fn release(&mut self, tag: u32) -> usize {
285        let mut n = 0;
286        for v in self.voices.iter_mut().filter(|v| v.active && v.held && v.tag == tag) {
287            v.held = false;
288            v.release_after = v.pos;
289            n += 1;
290        }
291        n
292    }
293
294    /// Stops every voice at once.
295    pub fn stop_all(&mut self) {
296        for i in 0..self.voices.len() {
297            let v = self.voices[i];
298            if v.active {
299                self.note_ended(v.tag);
300            }
301        }
302        self.voices.fill(IDLE);
303    }
304
305    /// Calls `f` with the tag of each tagged voice that ended since the last call, oldest first. Allocation-free.
306    pub fn drain_ended(&mut self, mut f: impl FnMut(u32)) {
307        for tag in &self.ended[..self.ended_len] {
308            f(*tag);
309        }
310        self.ended_len = 0;
311    }
312
313    fn note_ended(&mut self, tag: u32) {
314        if tag != NO_TAG && self.ended_len < ENDED_CAPACITY {
315            self.ended[self.ended_len] = tag;
316            self.ended_len += 1;
317        }
318    }
319
320    fn free_slot(&mut self) -> usize {
321        match self.voices.iter().position(|v| !v.active) {
322            Some(i) => i,
323            None => {
324                let i = self.voices.iter().enumerate().min_by_key(|(_, v)| v.serial).map(|(i, _)| i).unwrap_or(0);
325                let tag = self.voices[i].tag;
326                self.note_ended(tag);
327                i
328            }
329        }
330    }
331
332    fn start(&mut self, ev: SceneEvent) {
333        let slot = self.free_slot();
334        self.serial += 1;
335        let release_after = match ev.gate_frames {
336            Some(g) => g.max(1),
337            None => u64::MAX,
338        };
339        self.voices[slot] =
340            Voice { active: true, sound: ev.sound, pos: 0, gain: ev.gain, release_after, held: false, tag: NO_TAG, serial: self.serial };
341    }
342
343    /// Fills `out` (interleaved, `scene.channels()` per frame; a trailing partial frame is silenced) and advances. Scene events start on
344    /// their frames and a looping scene wraps. Allocation-free and lock-free.
345    pub fn render(&mut self, out: &mut [f32]) {
346        out.fill(0.0);
347        let ch = usize::from(self.scene.channels);
348        let total = out.len() / ch;
349        let mut done = 0usize;
350        while done < total {
351            let loop_end = self.scene.loop_frames;
352            while self.next_event < self.scene.events.len() && self.scene.events[self.next_event].at <= self.cursor {
353                let ev = self.scene.events[self.next_event];
354                self.start(ev);
355                self.next_event += 1;
356            }
357            let mut seg = total - done;
358            if let Some(next) = self.scene.events.get(self.next_event) {
359                seg = seg.min((next.at - self.cursor) as usize);
360            }
361            if let Some(l) = loop_end {
362                seg = seg.min((l - self.cursor) as usize);
363            }
364            self.mix_segment(&mut out[done * ch..(done + seg) * ch], seg);
365            self.cursor += seg as u64;
366            done += seg;
367            if let Some(l) = loop_end
368                && self.cursor >= l
369            {
370                self.cursor = 0;
371                self.next_event = 0;
372            }
373        }
374    }
375
376    /// Fills `out` with the voices that are sounding and nothing else: the cursor stays and no scene event starts. This is a stopped
377    /// transport, where live presses still sound, and the tail of a scene that was swapped out.
378    pub fn render_voices(&mut self, out: &mut [f32]) {
379        out.fill(0.0);
380        let ch = usize::from(self.scene.channels);
381        let total = out.len() / ch;
382        self.mix_segment(&mut out[..total * ch], total);
383    }
384
385    fn mix_segment(&mut self, out: &mut [f32], seg: usize) {
386        let ch = usize::from(self.scene.channels);
387        let release = u64::from(self.scene.release_frames);
388        for vi in 0..self.voices.len() {
389            let mut v = self.voices[vi];
390            if !v.active {
391                continue;
392            }
393            let sound = &self.scene.sounds[v.sound as usize];
394            let src = sound.samples();
395            let src_ch = usize::from(sound.channels());
396            let remaining = (sound.frames() as u64).saturating_sub(v.pos);
397            let mut n = (seg as u64).min(remaining) as usize;
398            let mut ended = (n as u64) == remaining;
399            let limit = n;
400            for i in 0..limit {
401                let p = v.pos + i as u64;
402                let mut g = v.gain;
403                if p >= v.release_after {
404                    let k = p - v.release_after;
405                    if k >= release {
406                        n = i;
407                        ended = true;
408                        break;
409                    }
410                    g *= (release - k) as f32 / release as f32;
411                }
412                let at = p as usize * src_ch;
413                let dst = &mut out[i * ch..(i + 1) * ch];
414                if src_ch == ch {
415                    for (d, s) in dst.iter_mut().zip(&src[at..at + ch]) {
416                        *d += s * g;
417                    }
418                } else {
419                    let s = src[at] * g;
420                    for d in dst.iter_mut() {
421                        *d += s;
422                    }
423                }
424            }
425            v.pos += n as u64;
426            if ended {
427                v.active = false;
428                self.note_ended(v.tag);
429            }
430            self.voices[vi] = v;
431        }
432    }
433}
434
435/// Renders `frames` frames of `scene` from its start, with the same mixer a device callback uses.
436pub fn render_offline(scene: &Arc<Scene>, frames: usize) -> Waveform {
437    let ch = usize::from(scene.channels());
438    let mut renderer = SceneRenderer::new(scene.clone());
439    let mut samples = vec![0.0f32; frames * ch];
440    for block in samples.chunks_mut(4096 * ch) {
441        renderer.render(block);
442    }
443    Waveform::new(scene.sample_rate(), scene.channels(), samples).expect("a valid rate, channel count and whole frames")
444}
445
446/// Renders the whole scene, ending on the frame the last voice ends on ([`Scene::end_frame`]).
447pub fn render_to_end(scene: &Arc<Scene>) -> Waveform {
448    render_offline(scene, scene.end_frame() as usize)
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454
455    fn ramp(frames: usize, ch: u16, start: f32) -> Waveform {
456        let n = frames * usize::from(ch);
457        Waveform::new(48_000, ch, (0..n).map(|i| start + i as f32).collect::<Vec<f32>>()).unwrap()
458    }
459
460    fn scene(events: Vec<SceneEvent>, release: u32) -> Arc<Scene> {
461        Arc::new(Scene::new(48_000, 1, vec![ramp(4, 1, 1.0), ramp(3, 1, 100.0)], events, release).unwrap())
462    }
463
464    #[test]
465    fn events_start_on_their_exact_frame_and_sum() {
466        let s = scene(vec![SceneEvent::new(2, 0), SceneEvent::new(4, 1)], 0);
467        let w = render_offline(&s, 9);
468        // sound 0 = 1,2,3,4 from frame 2; sound 1 = 100,101,102 from frame 4.
469        assert_eq!(w.samples(), &[0.0, 0.0, 1.0, 2.0, 3.0 + 100.0, 4.0 + 101.0, 102.0, 0.0, 0.0]);
470    }
471
472    #[test]
473    fn the_block_size_never_changes_a_sample() {
474        let events: Vec<SceneEvent> = (0..40).map(|i| SceneEvent::new(i * 3, (i % 2) as u32).with_gain(0.5 + i as f32 * 0.01)).collect();
475        let s = scene(events, 0);
476        let whole = render_offline(&s, 150);
477        for block in [1usize, 2, 3, 7, 64, 149] {
478            let mut r = SceneRenderer::new(s.clone());
479            let mut got = Vec::new();
480            let mut left = 150;
481            while left > 0 {
482                let n = block.min(left);
483                let mut b = vec![0.0; n];
484                r.render(&mut b);
485                got.extend(b);
486                left -= n;
487            }
488            assert_eq!(got, whole.samples(), "block size {block}");
489        }
490    }
491
492    #[test]
493    fn gain_scales_and_mono_plays_on_every_channel() {
494        let s = Arc::new(Scene::new(48_000, 2, vec![ramp(2, 1, 1.0)], vec![SceneEvent::new(0, 0).with_gain(0.5)], 0).unwrap());
495        assert_eq!(render_offline(&s, 3).samples(), &[0.5, 0.5, 1.0, 1.0, 0.0, 0.0]);
496    }
497
498    #[test]
499    fn a_stereo_sound_keeps_its_channels() {
500        let s = Arc::new(Scene::new(48_000, 2, vec![ramp(2, 2, 1.0)], vec![SceneEvent::new(1, 0)], 0).unwrap());
501        assert_eq!(render_offline(&s, 3).samples(), &[0.0, 0.0, 1.0, 2.0, 3.0, 4.0]);
502    }
503
504    #[test]
505    fn a_gate_fades_out_over_the_release() {
506        let long = Waveform::new(48_000, 1, vec![1.0; 100]).unwrap();
507        let s = Arc::new(Scene::new(48_000, 1, vec![long], vec![SceneEvent::new(0, 0).with_gate(10)], 4).unwrap());
508        let w = render_offline(&s, 20);
509        let want: Vec<f32> = (0..20)
510            .map(|i| {
511                if i < 10 {
512                    1.0
513                } else if i < 14 {
514                    (4 - (i - 10)) as f32 / 4.0
515                } else {
516                    0.0
517                }
518            })
519            .collect();
520        assert_eq!(w.samples(), &want[..]);
521        assert_eq!(s.end_frame(), 14);
522    }
523
524    #[test]
525    fn a_zero_release_cuts_the_gate() {
526        let long = Waveform::new(48_000, 1, vec![1.0; 100]).unwrap();
527        let s = Arc::new(Scene::new(48_000, 1, vec![long], vec![SceneEvent::new(0, 0).with_gate(3)], 0).unwrap());
528        assert_eq!(render_offline(&s, 6).samples(), &[1.0, 1.0, 1.0, 0.0, 0.0, 0.0]);
529    }
530
531    #[test]
532    fn a_gate_longer_than_the_sound_just_plays_it() {
533        let s = scene(vec![SceneEvent::new(0, 0).with_gate(1000)], 8);
534        assert_eq!(render_offline(&s, 5).samples(), &[1.0, 2.0, 3.0, 4.0, 0.0]);
535        assert_eq!(s.end_frame(), 4);
536    }
537
538    #[test]
539    fn end_frame_holds_the_last_tail_and_render_to_end_uses_it() {
540        let s = scene(vec![SceneEvent::new(10, 0), SceneEvent::new(2, 1)], 0);
541        assert_eq!(s.end_frame(), 14);
542        assert_eq!(render_to_end(&s).frames(), 14);
543        assert_eq!(scene(vec![], 0).end_frame(), 0);
544    }
545
546    #[test]
547    fn the_oldest_voice_is_stolen_when_the_pool_is_full() {
548        let long = Waveform::new(48_000, 1, vec![1.0; 1000]).unwrap();
549        let events: Vec<SceneEvent> = (0..=MAX_VOICES as u64).map(|i| SceneEvent::new(i, 0)).collect();
550        let s = Arc::new(Scene::new(48_000, 1, vec![long], events, 0).unwrap());
551        let mut r = SceneRenderer::new(s);
552        let mut b = vec![0.0; MAX_VOICES + 1];
553        r.render(&mut b);
554        assert_eq!(r.active_voices(), MAX_VOICES);
555        // frame 64 sums 64 voices (the 65th started and stole the first).
556        assert_eq!(b[MAX_VOICES], MAX_VOICES as f32);
557    }
558
559    #[test]
560    fn seek_drops_voices_and_replays_later_events() {
561        let s = scene(vec![SceneEvent::new(0, 0), SceneEvent::new(10, 1)], 0);
562        let mut r = SceneRenderer::new(s);
563        let mut b = vec![0.0; 2];
564        r.render(&mut b);
565        assert_eq!(r.active_voices(), 1);
566        r.seek(10);
567        assert_eq!(r.active_voices(), 0);
568        let mut b = vec![0.0; 4];
569        r.render(&mut b);
570        assert_eq!(b, vec![100.0, 101.0, 102.0, 0.0]);
571        assert!(r.is_finished());
572        assert_eq!(r.cursor(), 14);
573    }
574
575    #[test]
576    fn bad_scenes_are_errors() {
577        let w = ramp(2, 1, 0.0);
578        assert_eq!(Scene::new(0, 1, vec![], vec![], 0), Err(SceneError::ZeroSampleRate));
579        assert_eq!(Scene::new(48_000, 0, vec![], vec![], 0), Err(SceneError::ZeroChannels));
580        assert_eq!(Scene::new(44_100, 1, vec![w.clone()], vec![], 0), Err(SceneError::RateMismatch { sound: 0 }));
581        assert_eq!(Scene::new(48_000, 2, vec![ramp(2, 3, 0.0)], vec![], 0), Err(SceneError::ChannelMismatch { sound: 0 }));
582        assert_eq!(Scene::new(48_000, 1, vec![w.clone()], vec![SceneEvent::new(0, 1)], 0), Err(SceneError::UnknownSound { event: 0 }));
583        assert_eq!(Scene::new(48_000, 1, vec![w], vec![SceneEvent::new(0, 0).with_gain(f32::NAN)], 0), Err(SceneError::NotFinite { event: 0 }));
584    }
585
586    #[test]
587    fn events_are_sorted_and_keep_their_order_on_a_tie() {
588        let s = scene(vec![SceneEvent::new(5, 0), SceneEvent::new(1, 1), SceneEvent::new(5, 1)], 0);
589        let order: Vec<(u64, u32)> = s.events().iter().map(|e| (e.at, e.sound)).collect();
590        assert_eq!(order, vec![(1, 1), (5, 0), (5, 1)]);
591    }
592}