Skip to main content

aura_core/
note_events.rs

1//! CLAP-shaped note / expression / per-note-mod events for `process`.
2//!
3//! Additive to 7-bit [`crate::MidiBuffer`]. Wrappers keep filling MIDI;
4//! plugins that need `note_id` or expressions read this list.
5
6use crate::chunked_process::TimedParamEvent;
7
8/// Wildcard used by CLAP when a field is unspecified (`-1`).
9pub const NOTE_UNSPECIFIED: i32 = -1;
10
11/// Note-scope fields shared by CLAP note / expression / per-note-mod events.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct NoteTarget {
14    pub note_id: i32,
15    pub port_index: i16,
16    pub channel: i16,
17    pub key: i16,
18}
19
20impl NoteTarget {
21    pub const UNSPECIFIED: Self = Self {
22        note_id: NOTE_UNSPECIFIED,
23        port_index: -1,
24        channel: -1,
25        key: -1,
26    };
27
28    /// Host scoped this event to a voice (`note_id`, key, or channel set).
29    /// Unspecified (`-1`) everywhere is mono (knob / `Params`).
30    #[must_use]
31    pub const fn is_voice_scoped(self) -> bool {
32        self.note_id >= 0 || self.key >= 0 || self.channel >= 0
33    }
34}
35
36/// CLAP note-expression id (`clap_note_expression`). Unknown values stay raw.
37#[derive(Clone, Copy, Debug, PartialEq)]
38pub enum NoteExpression {
39    Volume,
40    Pan,
41    Tuning,
42    Vibrato,
43    Expression,
44    Brightness,
45    Pressure,
46    /// Spec id we do not name yet — still delivered.
47    Other(i32),
48}
49
50impl NoteExpression {
51    #[must_use]
52    pub fn from_clap(id: i32) -> Self {
53        match id {
54            0 => Self::Volume,
55            1 => Self::Pan,
56            2 => Self::Tuning,
57            3 => Self::Vibrato,
58            4 => Self::Expression,
59            5 => Self::Brightness,
60            6 => Self::Pressure,
61            other => Self::Other(other),
62        }
63    }
64
65    #[must_use]
66    pub fn to_clap(self) -> i32 {
67        match self {
68            Self::Volume => 0,
69            Self::Pan => 1,
70            Self::Tuning => 2,
71            Self::Vibrato => 3,
72            Self::Expression => 4,
73            Self::Brightness => 5,
74            Self::Pressure => 6,
75            Self::Other(id) => id,
76        }
77    }
78}
79
80/// What happened to a (possibly scoped) note.
81#[derive(Clone, Copy, Debug, PartialEq)]
82pub enum NoteEventKind {
83    On {
84        velocity: f64,
85    },
86    Off {
87        velocity: f64,
88    },
89    Choke,
90    /// Voice finished sounding (`CLAP_EVENT_NOTE_END`). Host drops poly mods.
91    End,
92    Expression {
93        id: NoteExpression,
94        value: f64,
95    },
96    /// Per-note `PARAM_MOD` (`note_id >= 0`). Does not touch [`crate::Params`].
97    ParamMod {
98        param_id: u32,
99        amount: f64,
100    },
101    /// Per-note `PARAM_VALUE` (`note_id >= 0`). Absolute plain; not the knob.
102    ParamValue {
103        param_id: u32,
104        plain: f64,
105    },
106}
107
108/// One timed note-scoped event inside a process block.
109#[derive(Clone, Copy, Debug, PartialEq)]
110pub struct NoteEvent {
111    pub sample_offset: u32,
112    /// Host note id, or [`NOTE_UNSPECIFIED`].
113    pub note_id: i32,
114    pub port_index: i16,
115    pub channel: i16,
116    pub key: i16,
117    pub kind: NoteEventKind,
118}
119
120impl NoteEvent {
121    #[must_use]
122    pub fn on(sample_offset: u32, note_id: i32, key: i16, velocity: f64) -> Self {
123        Self {
124            sample_offset,
125            note_id,
126            port_index: 0,
127            channel: 0,
128            key,
129            kind: NoteEventKind::On { velocity },
130        }
131    }
132
133    #[must_use]
134    pub fn off(sample_offset: u32, note_id: i32, key: i16, velocity: f64) -> Self {
135        Self {
136            sample_offset,
137            note_id,
138            port_index: 0,
139            channel: 0,
140            key,
141            kind: NoteEventKind::Off { velocity },
142        }
143    }
144
145    /// `CLAP_EVENT_NOTE_END` — voice silent; host can drop per-note modulators.
146    #[must_use]
147    pub fn end(sample_offset: u32, note_id: i32, key: i16) -> Self {
148        Self {
149            sample_offset,
150            note_id,
151            port_index: 0,
152            channel: 0,
153            key,
154            kind: NoteEventKind::End,
155        }
156    }
157
158    /// 7-bit MIDI for VST3/LV2 (On/Off/Choke only). `End` / expressions stay CLAP-native.
159    #[must_use]
160    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
161    pub fn to_midi1(self) -> Option<crate::MidiMessage> {
162        use crate::MidiMessage;
163        let key = u8::try_from(self.key.clamp(0, 127)).ok()?;
164        let channel = if self.channel < 0 {
165            0
166        } else {
167            (self.channel as u8) & 0x0F
168        };
169        match self.kind {
170            NoteEventKind::On { velocity } => {
171                let vel = (velocity * 127.0).round().clamp(0.0, 127.0) as u8;
172                Some(MidiMessage::note_on(channel, key, vel.max(1)))
173            }
174            NoteEventKind::Off { velocity } => {
175                let vel = (velocity * 127.0).round().clamp(0.0, 127.0) as u8;
176                Some(MidiMessage::note_off(channel, key, vel))
177            }
178            NoteEventKind::Choke => Some(MidiMessage::note_off(channel, key, 0)),
179            NoteEventKind::End
180            | NoteEventKind::Expression { .. }
181            | NoteEventKind::ParamMod { .. }
182            | NoteEventKind::ParamValue { .. } => None,
183        }
184    }
185
186    /// True when this event applies to the sounding voice (`-1` = wildcard).
187    #[must_use]
188    pub fn matches_voice(self, note_id: i32, key: i16) -> bool {
189        let id_ok = self.note_id < 0 || note_id < 0 || self.note_id == note_id;
190        let key_ok = self.key < 0 || key < 0 || self.key == key;
191        id_ok && key_ok
192    }
193}
194
195/// Ordered note events for one audio block (same insert rules as MIDI).
196#[derive(Clone, Debug, Default)]
197pub struct NoteBuffer {
198    events: Vec<NoteEvent>,
199}
200
201impl NoteBuffer {
202    #[must_use]
203    pub const fn new() -> Self {
204        Self { events: Vec::new() }
205    }
206
207    #[must_use]
208    pub fn with_capacity(cap: usize) -> Self {
209        Self {
210            events: Vec::with_capacity(cap),
211        }
212    }
213
214    pub fn clear(&mut self) {
215        self.events.clear();
216    }
217
218    pub fn reserve(&mut self, additional: usize) {
219        self.events.reserve(additional);
220    }
221
222    #[must_use]
223    pub fn len(&self) -> usize {
224        self.events.len()
225    }
226
227    #[must_use]
228    pub fn is_empty(&self) -> bool {
229        self.events.is_empty()
230    }
231
232    pub fn push(&mut self, ev: NoteEvent) {
233        let off = ev.sample_offset;
234        match self.events.binary_search_by_key(&off, |e| e.sample_offset) {
235            Ok(mut i) => {
236                while i < self.events.len() && self.events[i].sample_offset == off {
237                    i += 1;
238                }
239                self.events.insert(i, ev);
240            }
241            Err(i) => self.events.insert(i, ev),
242        }
243    }
244
245    pub fn iter(&self) -> impl Iterator<Item = NoteEvent> + '_ {
246        self.events.iter().copied()
247    }
248
249    pub fn iter_range(&self, start: u32, end: u32) -> impl Iterator<Item = NoteEvent> + '_ {
250        self.events
251            .iter()
252            .copied()
253            .filter(move |e| e.sample_offset >= start && e.sample_offset < end)
254    }
255
256    #[must_use]
257    pub fn slice_rebased(&self, start: u32, end: u32) -> Self {
258        let mut out = Self::with_capacity(self.events.len());
259        out.copy_range_rebased(self, start, end);
260        out
261    }
262
263    /// Like [`slice_rebased`](Self::slice_rebased) into an existing buffer (no new `Vec`).
264    pub fn copy_range_rebased(&mut self, src: &Self, start: u32, end: u32) {
265        self.clear();
266        for mut ev in src.iter_range(start, end) {
267            ev.sample_offset = ev.sample_offset.saturating_sub(start);
268            self.events.push(ev);
269        }
270    }
271
272    #[must_use]
273    pub fn as_slice(&self) -> &[NoteEvent] {
274        &self.events
275    }
276}
277
278/// Append On/Off/Choke from `notes` as 7-bit MIDI (VST3/LV2 out).
279pub fn append_notes_as_midi(midi: &mut crate::MidiBuffer, notes: &NoteBuffer) {
280    for ev in notes.iter() {
281        if let Some(msg) = ev.to_midi1() {
282            midi.push(ev.sample_offset, msg);
283        }
284    }
285}
286
287/// Append Note-On/Off and All-Sound/Notes-Off (CC 120/123) from `midi` as CLAP notes.
288///
289/// Does not clear `notes`. Other MIDI messages are skipped. Note-On with
290/// velocity 0 follows [`crate::MidiMessage::is_note_off`].
291pub fn append_midi_as_notes(notes: &mut NoteBuffer, midi: &crate::MidiBuffer) {
292    for ev in midi.iter() {
293        let msg = ev.message;
294        if matches!(msg.status, crate::MidiStatus::ControlChange) && matches!(msg.data1, 120 | 123)
295        {
296            notes.push(NoteEvent {
297                sample_offset: ev.sample_offset,
298                note_id: NOTE_UNSPECIFIED,
299                port_index: -1,
300                channel: -1,
301                key: -1,
302                kind: NoteEventKind::Choke,
303            });
304            continue;
305        }
306        let Some(note) = msg.note_number() else {
307            continue;
308        };
309        let key = i16::from(note);
310        let note_id = i32::from(note);
311        let channel = i16::from(msg.channel);
312        if msg.is_note_on() {
313            notes.push(NoteEvent {
314                sample_offset: ev.sample_offset,
315                note_id,
316                port_index: 0,
317                channel,
318                key,
319                kind: NoteEventKind::On {
320                    velocity: f64::from(msg.data2) / 127.0,
321                },
322            });
323        } else if msg.is_note_off() {
324            notes.push(NoteEvent {
325                sample_offset: ev.sample_offset,
326                note_id,
327                port_index: 0,
328                channel,
329                key,
330                kind: NoteEventKind::Off { velocity: 0.0 },
331            });
332        }
333    }
334}
335
336/// Prefer CLAP notes when the host sent any; otherwise fill `scratch` from MIDI.
337///
338/// When `notes` is non-empty, `scratch` is left untouched.
339pub fn notes_or_midi<'a>(
340    notes: &'a NoteBuffer,
341    midi: &crate::MidiBuffer,
342    scratch: &'a mut NoteBuffer,
343) -> &'a NoteBuffer {
344    if !notes.is_empty() {
345        return notes;
346    }
347    scratch.clear();
348    append_midi_as_notes(scratch, midi);
349    scratch
350}
351
352/// Sorted unique split points in `0..=frames` (always includes `0` and `frames`).
353///
354/// Interior points are note `sample_offset`s with `0 < t < frames`. An event at
355/// `frames` belongs to the next block and is not a split.
356pub fn note_split_points_into(out: &mut Vec<u32>, frames: u32, notes: &NoteBuffer) {
357    out.clear();
358    out.push(0);
359    out.push(frames);
360    for ev in notes.iter() {
361        let t = ev.sample_offset;
362        if t > 0 && t < frames {
363            out.push(t);
364        }
365    }
366    out.sort_unstable();
367    out.dedup();
368}
369
370/// Allocating wrapper around [`note_split_points_into`].
371#[must_use]
372pub fn note_split_points(frames: u32, notes: &NoteBuffer) -> Vec<u32> {
373    let mut out = Vec::new();
374    note_split_points_into(&mut out, frames, notes);
375    out
376}
377
378/// Mono `PARAM_MOD` (`note_id < 0`) → timed params. Per-note → [`NoteBuffer`].
379pub fn route_param_mod(
380    timed: &mut Vec<TimedParamEvent>,
381    notes: &mut NoteBuffer,
382    sample_offset: u32,
383    param_id: u32,
384    amount: f64,
385    target: NoteTarget,
386) {
387    if target.is_voice_scoped() {
388        notes.push(NoteEvent {
389            sample_offset,
390            note_id: target.note_id,
391            port_index: target.port_index,
392            channel: target.channel,
393            key: target.key,
394            kind: NoteEventKind::ParamMod { param_id, amount },
395        });
396    } else {
397        timed.push(TimedParamEvent::Mod {
398            sample_offset,
399            id: param_id,
400            amount,
401        });
402    }
403}
404
405/// Mono `PARAM_VALUE` (`note_id < 0`) → timed params. Per-note → [`NoteBuffer`].
406pub fn route_param_value(
407    timed: &mut Vec<TimedParamEvent>,
408    notes: &mut NoteBuffer,
409    sample_offset: u32,
410    param_id: u32,
411    plain: f64,
412    target: NoteTarget,
413) {
414    if target.is_voice_scoped() {
415        notes.push(NoteEvent {
416            sample_offset,
417            note_id: target.note_id,
418            port_index: target.port_index,
419            channel: target.channel,
420            key: target.key,
421            kind: NoteEventKind::ParamValue { param_id, plain },
422        });
423    } else {
424        timed.push(TimedParamEvent::Value {
425            sample_offset,
426            id: param_id,
427            plain,
428        });
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn poly_mod_does_not_enter_timed_params() {
438        let mut timed = Vec::new();
439        let mut notes = NoteBuffer::new();
440        route_param_mod(
441            &mut timed,
442            &mut notes,
443            8,
444            1,
445            0.25,
446            NoteTarget {
447                note_id: 7,
448                port_index: 0,
449                channel: 0,
450                key: 60,
451            },
452        );
453        route_param_mod(&mut timed, &mut notes, 0, 1, 0.1, NoteTarget::UNSPECIFIED);
454        route_param_mod(
455            &mut timed,
456            &mut notes,
457            4,
458            1,
459            0.5,
460            NoteTarget {
461                note_id: -1,
462                port_index: -1,
463                channel: -1,
464                key: 60,
465            },
466        );
467        assert_eq!(timed.len(), 1);
468        assert_eq!(notes.len(), 2);
469        assert!(matches!(
470            timed[0],
471            TimedParamEvent::Mod {
472                sample_offset: 0,
473                id: 1,
474                amount: a
475            } if (a - 0.1).abs() < 1e-12
476        ));
477        let by_id = notes.iter().find(|e| e.note_id == 7).expect("note_id");
478        assert_eq!(by_id.sample_offset, 8);
479        assert!(matches!(
480            by_id.kind,
481            NoteEventKind::ParamMod {
482                param_id: 1,
483                amount: a
484            } if (a - 0.25).abs() < 1e-12
485        ));
486        let by_key = notes
487            .iter()
488            .find(|e| e.note_id < 0 && e.key == 60)
489            .expect("key");
490        assert!(matches!(
491            by_key.kind,
492            NoteEventKind::ParamMod {
493                amount: a,
494                ..
495            } if (a - 0.5).abs() < 1e-12
496        ));
497    }
498
499    #[test]
500    fn slice_rebases_and_matches_voice() {
501        let mut notes = NoteBuffer::new();
502        notes.push(NoteEvent::on(10, 1, 60, 0.8));
503        notes.push(NoteEvent {
504            sample_offset: 20,
505            note_id: 1,
506            port_index: 0,
507            channel: 0,
508            key: 60,
509            kind: NoteEventKind::Expression {
510                id: NoteExpression::Tuning,
511                value: 0.5,
512            },
513        });
514        notes.push(NoteEvent::on(40, 2, 64, 0.5));
515        let chunk = notes.slice_rebased(10, 30);
516        assert_eq!(chunk.len(), 2);
517        assert_eq!(chunk.as_slice()[0].sample_offset, 0);
518        assert_eq!(chunk.as_slice()[1].sample_offset, 10);
519        assert!(chunk.as_slice()[1].matches_voice(1, 60));
520        assert!(!chunk.as_slice()[1].matches_voice(2, 64));
521    }
522
523    #[test]
524    fn copy_range_rebased_reuses_buffer() {
525        let mut notes = NoteBuffer::new();
526        notes.push(NoteEvent::on(10, 1, 60, 0.8));
527        notes.push(NoteEvent::on(40, 2, 64, 0.5));
528        let mut dest = NoteBuffer::with_capacity(8);
529        dest.copy_range_rebased(&notes, 10, 30);
530        assert_eq!(dest.len(), 1);
531        assert_eq!(dest.as_slice()[0].sample_offset, 0);
532        dest.copy_range_rebased(&notes, 0, 50);
533        assert_eq!(dest.len(), 2);
534    }
535
536    #[test]
537    fn end_and_to_midi1() {
538        let end = NoteEvent::end(8, 3, 60);
539        assert!(matches!(end.kind, NoteEventKind::End));
540        assert!(end.to_midi1().is_none());
541        let on = NoteEvent::on(0, 1, 64, 0.5);
542        let msg = on.to_midi1().expect("on");
543        assert!(msg.is_note_on());
544        assert_eq!(msg.note_number(), Some(64));
545        let off = NoteEvent::off(4, 1, 64, 0.0);
546        assert!(
547            off.to_midi1()
548                .is_some_and(aura_midi::MidiMessage::is_note_off)
549        );
550        let mut midi = crate::MidiBuffer::new();
551        let mut notes = NoteBuffer::new();
552        notes.push(on);
553        notes.push(end);
554        append_notes_as_midi(&mut midi, &notes);
555        assert_eq!(midi.len(), 1);
556    }
557
558    #[test]
559    fn append_midi_as_notes_maps_on_off_and_all_notes_off() {
560        let mut midi = crate::MidiBuffer::new();
561        midi.push(3, crate::MidiMessage::note_on(0, 69, 100));
562        midi.push(9, crate::MidiMessage::note_off(0, 69, 0));
563        midi.push(11, crate::MidiMessage::raw(0xB0, 123, 0));
564        midi.push(12, crate::MidiMessage::raw(0xB0, 1, 64));
565        let mut notes = NoteBuffer::new();
566        append_midi_as_notes(&mut notes, &midi);
567        assert_eq!(notes.len(), 3);
568        assert_eq!(
569            notes.iter().next().unwrap(),
570            NoteEvent::on(3, 69, 69, 100.0 / 127.0)
571        );
572        let off = notes.iter().nth(1).unwrap();
573        assert!(matches!(off.kind, NoteEventKind::Off { .. }));
574        assert_eq!(off.sample_offset, 9);
575        let choke = notes.iter().nth(2).unwrap();
576        assert_eq!(choke.kind, NoteEventKind::Choke);
577        assert_eq!(choke.note_id, NOTE_UNSPECIFIED);
578        assert_eq!(choke.key, -1);
579    }
580
581    #[test]
582    fn notes_or_midi_prefers_clap_notes() {
583        let mut clap = NoteBuffer::new();
584        clap.push(NoteEvent::on(0, 1, 60, 1.0));
585        let mut midi = crate::MidiBuffer::new();
586        midi.push(0, crate::MidiMessage::note_on(0, 69, 100));
587        let mut scratch = NoteBuffer::new();
588        let got = notes_or_midi(&clap, &midi, &mut scratch);
589        assert_eq!(got.len(), 1);
590        assert_eq!(got.iter().next().unwrap().key, 60);
591        assert!(scratch.is_empty());
592    }
593
594    #[test]
595    fn notes_or_midi_falls_back_to_midi() {
596        let clap = NoteBuffer::new();
597        let mut midi = crate::MidiBuffer::new();
598        midi.push(4, crate::MidiMessage::note_on(2, 64, 90));
599        let mut scratch = NoteBuffer::new();
600        scratch.push(NoteEvent::on(99, 1, 1, 1.0));
601        let got = notes_or_midi(&clap, &midi, &mut scratch);
602        assert_eq!(got.len(), 1);
603        let ev = got.iter().next().unwrap();
604        assert_eq!(ev.key, 64);
605        assert_eq!(ev.sample_offset, 4);
606        assert_eq!(ev.channel, 2);
607    }
608
609    #[test]
610    fn note_split_points_empty_is_block_bounds() {
611        let notes = NoteBuffer::new();
612        assert_eq!(note_split_points(32, &notes), vec![0, 32]);
613    }
614
615    #[test]
616    fn note_split_points_inserts_interior_offsets() {
617        let mut notes = NoteBuffer::new();
618        notes.push(NoteEvent::on(7, 1, 69, 1.0));
619        notes.push(NoteEvent::off(7, 1, 69, 0.0));
620        notes.push(NoteEvent::off(32, 1, 69, 0.0));
621        notes.push(NoteEvent::on(40, 2, 60, 1.0));
622        notes.push(NoteEvent::on(0, 3, 61, 1.0));
623        assert_eq!(note_split_points(32, &notes), vec![0, 7, 32]);
624    }
625}