Skip to main content

plughost_core/
event.rs

1//! Events on event ports: MIDI 1.0 messages, system exclusive data, notes told apart by their IDs,
2//! and the expression of single notes. Input for instruments, MIDI effects, and MIDI-controlled
3//! effects, and output of plugins that produce events.
4
5use std::ops::RangeInclusive;
6
7mod events;
8pub use events::{Events, Iter};
9
10/// Maximum events one processing block takes, counting automation points too: each automation
11/// point and each event (a MIDI message, a system exclusive message, a note on or off, or a note
12/// expression) is one record. For a chain this is the aggregate across all slots, and overflow
13/// rejects the block before DSP. A plugin's event output in one block is bounded by the same
14/// count. Render timelines may contain more events provided every submitted block fits.
15pub const MAX_BLOCK_EVENTS: usize = 4096;
16
17/// Maximum system exclusive bytes, counting each message's F0 and F7, that one block's events may
18/// carry: the chain's input, and each plugin's output. They are kept apart from the fixed-size
19/// event records.
20pub const MAX_BLOCK_SYSEX_BYTES: usize = 64 << 10;
21
22/// The largest note ID. IDs are the non-negative 32-bit integers CLAP and VST3 use.
23pub const MAX_NOTE_ID: u32 = i32::MAX as u32;
24
25/// Checks the combined input count without overflowing while adding untrusted lengths.
26pub(crate) fn validate_event_count(
27    automation: usize,
28    events: usize,
29) -> Result<(), crate::InputError> {
30    if automation > MAX_BLOCK_EVENTS || events > MAX_BLOCK_EVENTS - automation {
31        return Err(crate::InputError::EventCapacity);
32    }
33    Ok(())
34}
35
36/// Checks the combined count of automation and events, and their system exclusive bytes.
37pub fn validate_event_budget(automation: usize, events: &Events) -> Result<(), crate::InputError> {
38    validate_event_count(automation, events.len())?;
39    if events.sysex_bytes() > MAX_BLOCK_SYSEX_BYTES {
40        return Err(crate::InputError::EventCapacity);
41    }
42    Ok(())
43}
44
45/// An event on an event port at a sample offset: from the start of the block when processing
46/// blocks, and from the start of the input when rendering. Each format receives it in its own
47/// form; see [`EventData`]. Events are kept in an [`Events`], which holds the system exclusive
48/// bytes an event borrows.
49#[derive(Clone, Copy, Debug, PartialEq)]
50#[non_exhaustive]
51pub struct Event<'a> {
52    /// Zero-based sample offset in the block or render input.
53    pub offset: usize,
54    /// For a chain, the index of one of its external event inputs or outputs; for a plugin hosted
55    /// directly, the index of its native event port in that direction.
56    pub port: usize,
57    /// MIDI, SysEx, note, or note-expression payload.
58    pub data: EventData<'a>,
59}
60
61/// What an event carries.
62///
63/// Plugins receive notes and expressions in their format's note events where it has them: CLAP
64/// note and note expression events on ports that take the CLAP dialect, and VST3 note events,
65/// note expression values, and poly pressure. VST3 names a note by its ID, so a note off or an
66/// expression without an ID reaches each note on its key by that note's ID, and a note started
67/// without an ID takes no expression other than pressure. Ports that take MIDI only receive the
68/// MIDI 1.0 form of [`EventData::to_midi`]; the note ID and the precision beyond 7 bits are lost
69/// there, and an expression other than pressure has no such form and is not delivered. Output
70/// notes and expressions in a format's note events become these variants; MIDI output stays MIDI.
71#[derive(Clone, Copy, Debug, PartialEq)]
72#[non_exhaustive]
73pub enum EventData<'a> {
74    /// A MIDI 1.0 channel message. Program change and channel pressure use two bytes; the third
75    /// is ignored. MPE is MIDI 1.0 on member channels and is delivered as MIDI.
76    Midi([u8; 3]),
77    /// A complete system exclusive message, from its F0 to its F7.
78    SysEx(&'a [u8]),
79    /// Starts a note with normalized velocity and an optional independent note ID.
80    NoteOn(Note),
81    /// Ends the notes it addresses; `velocity` is the release velocity.
82    NoteOff(Note),
83    /// Changes an expression of the addressed note or notes.
84    Expression(NoteExpression),
85}
86
87/// A note, or the notes a note off addresses. A note with an ID is told apart from other notes on
88/// the same key by it; without one, it addresses notes by port, channel and key, as MIDI does.
89#[derive(Clone, Copy, Debug, PartialEq)]
90#[non_exhaustive]
91pub struct Note {
92    /// At most [`MAX_NOTE_ID`].
93    pub id: Option<u32>,
94    /// 0..=15.
95    pub channel: u8,
96    /// 0..=127, with 60 the middle C.
97    pub key: u8,
98    /// 0..=1.
99    pub velocity: f64,
100}
101
102/// A change of one expression of the notes it addresses, which applies from its offset until the
103/// next change of the same expression. With an ID it addresses that note; without one, every note
104/// on its port, channel and key.
105#[derive(Clone, Copy, Debug, PartialEq)]
106#[non_exhaustive]
107pub struct NoteExpression {
108    /// At most [`MAX_NOTE_ID`].
109    pub id: Option<u32>,
110    /// 0..=15.
111    pub channel: u8,
112    /// 0..=127.
113    pub key: u8,
114    /// Expression dimension and its allowed value range.
115    pub kind: ExpressionKind,
116    /// In the range of `kind`, see [`ExpressionKind::range`].
117    pub value: f64,
118}
119
120/// The expressions a single note has, with the value ranges CLAP defines for them. VST3 receives
121/// the first six as note expression values and pressure as poly pressure.
122#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123#[non_exhaustive]
124pub enum ExpressionKind {
125    /// Linear gain, 0..=4; 1 leaves the note's level as it is.
126    Volume,
127    /// 0..=1: 0 is left, 0.5 center, and 1 right.
128    Pan,
129    /// Semitones in equal temperament, -120..=120, relative to the note's key.
130    Tuning,
131    /// 0..=1.
132    Vibrato,
133    /// 0..=1.
134    Expression,
135    /// 0..=1.
136    Brightness,
137    /// 0..=1. In MIDI 1.0, poly pressure.
138    Pressure,
139}
140
141impl ExpressionKind {
142    /// Every expression, in declaration order.
143    pub const ALL: [ExpressionKind; 7] = [
144        ExpressionKind::Volume,
145        ExpressionKind::Pan,
146        ExpressionKind::Tuning,
147        ExpressionKind::Vibrato,
148        ExpressionKind::Expression,
149        ExpressionKind::Brightness,
150        ExpressionKind::Pressure,
151    ];
152
153    /// The values the expression takes.
154    pub fn range(self) -> RangeInclusive<f64> {
155        match self {
156            ExpressionKind::Volume => 0.0..=4.0,
157            ExpressionKind::Tuning => -120.0..=120.0,
158            ExpressionKind::Pan
159            | ExpressionKind::Vibrato
160            | ExpressionKind::Expression
161            | ExpressionKind::Brightness
162            | ExpressionKind::Pressure => 0.0..=1.0,
163        }
164    }
165}
166
167impl Note {
168    /// Constructs a note without an independent ID; input validation occurs at processing.
169    #[must_use]
170    pub fn new(channel: u8, key: u8, velocity: f64) -> Note {
171        Note {
172            id: None,
173            channel,
174            key,
175            velocity,
176        }
177    }
178
179    /// The same note with an ID.
180    #[must_use]
181    pub fn with_id(self, id: u32) -> Note {
182        Note {
183            id: Some(id),
184            ..self
185        }
186    }
187
188    fn is_valid(&self) -> bool {
189        valid_address(self.id, self.channel, self.key)
190            && self.velocity.is_finite()
191            && (0.0..=1.0).contains(&self.velocity)
192    }
193}
194
195impl NoteExpression {
196    /// Constructs an expression addressing notes by channel and key, without an ID.
197    #[must_use]
198    pub fn new(channel: u8, key: u8, kind: ExpressionKind, value: f64) -> NoteExpression {
199        NoteExpression {
200            id: None,
201            channel,
202            key,
203            kind,
204            value,
205        }
206    }
207
208    /// The same expression for the note with this ID.
209    #[must_use]
210    pub fn with_id(self, id: u32) -> NoteExpression {
211        NoteExpression {
212            id: Some(id),
213            ..self
214        }
215    }
216
217    fn is_valid(&self) -> bool {
218        valid_address(self.id, self.channel, self.key)
219            && self.value.is_finite()
220            && self.kind.range().contains(&self.value)
221    }
222}
223
224fn valid_address(id: Option<u32>, channel: u8, key: u8) -> bool {
225    id.is_none_or(|id| id <= MAX_NOTE_ID) && channel < 16 && key < 0x80
226}
227
228/// Whether a channel message's status takes one data byte: program change and channel pressure.
229fn two_bytes(status: u8) -> bool {
230    matches!(status & 0xF0, 0xC0 | 0xD0)
231}
232
233/// A 7-bit MIDI value from a value in 0..=1.
234fn seven_bits(value: f64) -> u8 {
235    (value * 127.0).round().clamp(0.0, 127.0) as u8
236}
237
238impl EventData<'_> {
239    /// The MIDI 1.0 channel message form: the message itself, a note on (with a velocity of at
240    /// least 1, since 0 would end the note) or note off, or poly pressure for a pressure
241    /// expression. `None` for system exclusive data and the other expressions.
242    pub fn to_midi(&self) -> Option<[u8; 3]> {
243        Some(match self {
244            EventData::Midi([status, first, _]) if two_bytes(*status) => [*status, *first, 0],
245            EventData::Midi(bytes) => *bytes,
246            EventData::NoteOn(note) => [
247                0x90 | (note.channel & 0x0F),
248                note.key & 0x7F,
249                seven_bits(note.velocity).max(1),
250            ],
251            EventData::NoteOff(note) => [
252                0x80 | (note.channel & 0x0F),
253                note.key & 0x7F,
254                seven_bits(note.velocity),
255            ],
256            EventData::Expression(expression) if expression.kind == ExpressionKind::Pressure => [
257                0xA0 | (expression.channel & 0x0F),
258                expression.key & 0x7F,
259                seven_bits(expression.value),
260            ],
261            EventData::Expression(_) | EventData::SysEx(_) => return None,
262        })
263    }
264}
265
266/// A decoded channel message. Channels are 0..=15; data values are 7-bit except the 14-bit pitch
267/// bend (8192 is the center).
268#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269#[non_exhaustive]
270pub enum Message {
271    /// Ends a MIDI note; velocity is release velocity.
272    NoteOff {
273        /// MIDI channel in `0..=15`.
274        channel: u8,
275        /// MIDI key in `0..=127`; 60 is middle C.
276        key: u8,
277        /// Seven-bit attack or release velocity.
278        velocity: u8,
279    },
280    /// Starts a MIDI note.
281    NoteOn {
282        /// MIDI channel in `0..=15`.
283        channel: u8,
284        /// MIDI key in `0..=127`; 60 is middle C.
285        key: u8,
286        /// Seven-bit attack or release velocity.
287        velocity: u8,
288    },
289    /// Changes pressure for a channel/key pair.
290    PolyPressure {
291        /// MIDI channel in `0..=15`.
292        channel: u8,
293        /// MIDI key in `0..=127`; 60 is middle C.
294        key: u8,
295        /// Seven-bit pressure value.
296        pressure: u8,
297    },
298    /// Changes a MIDI controller value.
299    ControlChange {
300        /// MIDI channel in `0..=15`.
301        channel: u8,
302        /// MIDI controller number in `0..=127`.
303        controller: u8,
304        /// Seven-bit controller value.
305        value: u8,
306    },
307    /// Selects a MIDI program.
308    ProgramChange {
309        /// MIDI channel in `0..=15`.
310        channel: u8,
311        /// Zero-based MIDI program number in `0..=127`.
312        program: u8,
313    },
314    /// Changes pressure for every note on the channel.
315    ChannelPressure {
316        /// MIDI channel in `0..=15`.
317        channel: u8,
318        /// Seven-bit pressure value.
319        pressure: u8,
320    },
321    /// Changes the channel’s 14-bit pitch-bend value.
322    PitchBend {
323        /// MIDI channel in `0..=15`.
324        channel: u8,
325        /// Pitch bend in `0..=16383`; 8192 is center.
326        value: u16,
327    },
328}
329
330impl<'a> Event<'a> {
331    /// An event on port 0.
332    #[must_use]
333    pub fn new(offset: usize, data: EventData<'a>) -> Event<'a> {
334        Event {
335            offset,
336            port: 0,
337            data,
338        }
339    }
340
341    /// A MIDI 1.0 channel message on port 0.
342    #[must_use]
343    pub fn midi(offset: usize, data: [u8; 3]) -> Event<'a> {
344        Self::new(offset, EventData::Midi(data))
345    }
346
347    /// A MIDI 1.0 note on.
348    #[must_use]
349    pub fn note_on(offset: usize, channel: u8, key: u8, velocity: u8) -> Event<'a> {
350        Self::midi(
351            offset,
352            [0x90 | (channel & 0x0F), key & 0x7F, velocity & 0x7F],
353        )
354    }
355
356    /// A MIDI 1.0 note off.
357    #[must_use]
358    pub fn note_off(offset: usize, channel: u8, key: u8, velocity: u8) -> Event<'a> {
359        Self::midi(
360            offset,
361            [0x80 | (channel & 0x0F), key & 0x7F, velocity & 0x7F],
362        )
363    }
364
365    /// Constructs a MIDI controller event on port 0, masking channel and data to MIDI widths.
366    #[must_use]
367    pub fn control_change(offset: usize, channel: u8, controller: u8, value: u8) -> Event<'a> {
368        Self::midi(
369            offset,
370            [0xB0 | (channel & 0x0F), controller & 0x7F, value & 0x7F],
371        )
372    }
373
374    /// A system exclusive message on port 0; `bytes` include the F0 and the F7.
375    #[must_use]
376    pub fn sysex(offset: usize, bytes: &'a [u8]) -> Event<'a> {
377        Self::new(offset, EventData::SysEx(bytes))
378    }
379
380    /// The same event on `port`.
381    #[must_use]
382    pub fn on_port(self, port: usize) -> Event<'a> {
383        Event { port, ..self }
384    }
385
386    /// The same event at `offset`.
387    #[must_use]
388    pub fn at(self, offset: usize) -> Event<'a> {
389        Event { offset, ..self }
390    }
391
392    /// The MIDI 1.0 channel message, or `None` for other data or bytes that are not a channel
393    /// message. A note on with velocity 0 is a note off, as in MIDI.
394    pub fn message(&self) -> Option<Message> {
395        let EventData::Midi([status, first, second]) = self.data else {
396            return None;
397        };
398        // Program change and channel pressure have no second data byte.
399        if !(0x80..0xF0).contains(&status) || first > 0x7F || (second > 0x7F && !two_bytes(status))
400        {
401            return None;
402        }
403        let channel = status & 0x0F;
404        Some(match status & 0xF0 {
405            0x80 => Message::NoteOff {
406                channel,
407                key: first,
408                velocity: second,
409            },
410            0x90 if second == 0 => Message::NoteOff {
411                channel,
412                key: first,
413                velocity: 64,
414            },
415            0x90 => Message::NoteOn {
416                channel,
417                key: first,
418                velocity: second,
419            },
420            0xA0 => Message::PolyPressure {
421                channel,
422                key: first,
423                pressure: second,
424            },
425            0xB0 => Message::ControlChange {
426                channel,
427                controller: first,
428                value: second,
429            },
430            0xC0 => Message::ProgramChange {
431                channel,
432                program: first,
433            },
434            0xD0 => Message::ChannelPressure {
435                channel,
436                pressure: first,
437            },
438            _ => Message::PitchBend {
439                channel,
440                value: u16::from(first) | (u16::from(second) << 7),
441            },
442        })
443    }
444
445    /// Whether the data is a MIDI 1.0 channel message, a complete system exclusive message, or a
446    /// note or expression with values in their ranges.
447    pub fn is_valid(&self) -> bool {
448        match self.data {
449            EventData::Midi(_) => self.message().is_some(),
450            EventData::SysEx(bytes) => {
451                bytes.len() >= 2
452                    && bytes[0] == 0xF0
453                    && bytes[bytes.len() - 1] == 0xF7
454                    && bytes[1..bytes.len() - 1].iter().all(|&byte| byte < 0x80)
455            }
456            EventData::NoteOn(note) | EventData::NoteOff(note) => note.is_valid(),
457            EventData::Expression(expression) => expression.is_valid(),
458        }
459    }
460}
461
462/// Whether `events` can go with a block of `frames` samples: valid events in offset order, every
463/// offset inside the block. Budgets and ports are checked separately.
464pub fn events_fit(events: &Events, frames: usize) -> bool {
465    let mut previous = 0;
466    events.iter().all(|event| {
467        let ordered = event.offset >= previous;
468        previous = event.offset;
469        ordered && event.offset < frames && event.is_valid()
470    })
471}
472
473#[cfg(test)]
474mod tests {
475    use super::*;
476
477    #[test]
478    fn block_event_budget_counts_both_inputs_without_integer_overflow() {
479        assert_eq!(validate_event_count(0, 0), Ok(()));
480        assert_eq!(validate_event_count(MAX_BLOCK_EVENTS, 0), Ok(()));
481        assert_eq!(validate_event_count(1, MAX_BLOCK_EVENTS - 1), Ok(()));
482        for (automation, events) in [
483            (MAX_BLOCK_EVENTS, 1),
484            (0, MAX_BLOCK_EVENTS + 1),
485            (usize::MAX, usize::MAX),
486            (1, usize::MAX),
487        ] {
488            assert_eq!(
489                validate_event_count(automation, events),
490                Err(crate::InputError::EventCapacity)
491            );
492        }
493    }
494
495    #[test]
496    fn channel_messages_decode() {
497        assert_eq!(
498            Event::note_on(0, 1, 60, 100).message(),
499            Some(Message::NoteOn {
500                channel: 1,
501                key: 60,
502                velocity: 100
503            })
504        );
505        assert!(matches!(
506            Event::note_on(0, 0, 60, 0).message(),
507            Some(Message::NoteOff { key: 60, .. })
508        ));
509        assert_eq!(
510            Event::midi(0, [0xE3, 0x00, 0x40]).message(),
511            Some(Message::PitchBend {
512                channel: 3,
513                value: 8192
514            })
515        );
516        let clock = Event::midi(0, [0xF8, 0, 0]);
517        assert_eq!(clock.message(), None);
518        assert!(!clock.is_valid());
519    }
520
521    #[test]
522    fn system_exclusive_messages_are_complete_and_budgeted() {
523        let sysex = Event::sysex(0, &[0xF0, 0x7D, 0x01, 0xF7]).on_port(1);
524        assert!(sysex.is_valid());
525        assert_eq!(sysex.message(), None);
526        assert_eq!(sysex.data.to_midi(), None);
527        assert_eq!(sysex.port, 1);
528        for bytes in [vec![0xF0], vec![0xF0, 0x80, 0xF7], vec![0x7D, 0xF7]] {
529            assert!(!Event::sysex(0, &bytes).is_valid());
530        }
531        let mut large = vec![0; MAX_BLOCK_SYSEX_BYTES + 1];
532        large[0] = 0xF0;
533        large[MAX_BLOCK_SYSEX_BYTES] = 0xF7;
534        assert_eq!(
535            validate_event_budget(0, &Events::from_iter([Event::sysex(0, &large)])),
536            Err(crate::InputError::EventCapacity)
537        );
538    }
539
540    #[test]
541    fn notes_and_expressions_are_checked_against_their_ranges() {
542        let note = Note::new(15, 127, 1.0).with_id(MAX_NOTE_ID);
543        assert!(Event::new(0, EventData::NoteOn(note)).is_valid());
544        for invalid in [
545            Note::new(16, 60, 0.5),
546            Note::new(0, 128, 0.5),
547            Note::new(0, 60, 1.5),
548            Note::new(0, 60, f64::NAN),
549            Note::new(0, 60, 0.5).with_id(MAX_NOTE_ID + 1),
550        ] {
551            assert!(!Event::new(0, EventData::NoteOff(invalid)).is_valid());
552        }
553        for (kind, min, max) in [
554            (ExpressionKind::Volume, 0.0, 4.0),
555            (ExpressionKind::Pan, 0.0, 1.0),
556            (ExpressionKind::Tuning, -120.0, 120.0),
557            (ExpressionKind::Vibrato, 0.0, 1.0),
558            (ExpressionKind::Expression, 0.0, 1.0),
559            (ExpressionKind::Brightness, 0.0, 1.0),
560            (ExpressionKind::Pressure, 0.0, 1.0),
561        ] {
562            for (value, valid) in [
563                (min, true),
564                (max, true),
565                (min - 0.001, false),
566                (max + 0.001, false),
567                (f64::NAN, false),
568                (f64::NEG_INFINITY, false),
569                (f64::INFINITY, false),
570            ] {
571                let expression = NoteExpression::new(0, 60, kind, value).with_id(3);
572                assert_eq!(
573                    Event::new(0, EventData::Expression(expression)).is_valid(),
574                    valid,
575                    "{kind:?} {value}"
576                );
577            }
578        }
579    }
580
581    #[test]
582    fn notes_and_pressure_have_a_midi_form() {
583        let note = Note::new(2, 64, 0.0).with_id(9);
584        assert_eq!(EventData::NoteOn(note).to_midi(), Some([0x92, 64, 1]));
585        let note = Note::new(2, 64, 0.5);
586        assert_eq!(EventData::NoteOff(note).to_midi(), Some([0x82, 64, 64]));
587        let pressure = NoteExpression::new(1, 60, ExpressionKind::Pressure, 1.0);
588        assert_eq!(
589            EventData::Expression(pressure).to_midi(),
590            Some([0xA1, 60, 127])
591        );
592        let tuning = NoteExpression::new(1, 60, ExpressionKind::Tuning, 1.0);
593        assert_eq!(EventData::Expression(tuning).to_midi(), None);
594    }
595
596    #[test]
597    fn two_byte_messages_ignore_their_third_byte() {
598        for status in [0xC3, 0xD3] {
599            let event = Event::midi(0, [status, 5, 0x80]);
600            assert!(event.is_valid());
601            assert_eq!(event.data.to_midi(), Some([status, 5, 0]));
602        }
603        assert!(!Event::midi(0, [0xB3, 5, 0x80]).is_valid());
604    }
605
606    #[test]
607    fn events_must_be_ordered_and_inside_the_block() {
608        let on = Event::note_on(10, 0, 60, 100);
609        let off = Event::note_off(20, 0, 60, 0);
610        assert!(events_fit(&Events::from_iter([on, off]), 64));
611        assert!(!events_fit(&Events::from_iter([off, on]), 64));
612        assert!(!events_fit(&Events::from_iter([on, off]), 20));
613    }
614}