plughost-core 0.2.2

Shared types and offline render rules for plughost
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
//! Events on event ports: MIDI 1.0 messages, system exclusive data, notes told apart by their IDs,
//! and the expression of single notes. Input for instruments, MIDI effects, and MIDI-controlled
//! effects, and output of plugins that produce events.

use std::ops::RangeInclusive;

mod events;
pub use events::{Events, Iter};

/// Maximum events one processing block takes, counting automation points too: each automation
/// point and each event (a MIDI message, a system exclusive message, a note on or off, or a note
/// expression) is one record. For a chain this is the aggregate across all slots, and overflow
/// rejects the block before DSP. A plugin's event output in one block is bounded by the same
/// count. Render timelines may contain more events provided every submitted block fits.
pub const MAX_BLOCK_EVENTS: usize = 4096;

/// Maximum system exclusive bytes, counting each message's F0 and F7, that one block's events may
/// carry: the chain's input, and each plugin's output. They are kept apart from the fixed-size
/// event records.
pub const MAX_BLOCK_SYSEX_BYTES: usize = 64 << 10;

/// The largest note ID. IDs are the non-negative 32-bit integers CLAP and VST3 use.
pub const MAX_NOTE_ID: u32 = i32::MAX as u32;

/// Checks the combined input count without overflowing while adding untrusted lengths.
pub(crate) fn validate_event_count(
    automation: usize,
    events: usize,
) -> Result<(), crate::InputError> {
    if automation > MAX_BLOCK_EVENTS || events > MAX_BLOCK_EVENTS - automation {
        return Err(crate::InputError::EventCapacity);
    }
    Ok(())
}

/// Checks the combined count of automation and events, and their system exclusive bytes.
pub fn validate_event_budget(automation: usize, events: &Events) -> Result<(), crate::InputError> {
    validate_event_count(automation, events.len())?;
    if events.sysex_bytes() > MAX_BLOCK_SYSEX_BYTES {
        return Err(crate::InputError::EventCapacity);
    }
    Ok(())
}

/// An event on an event port at a sample offset: from the start of the block when processing
/// blocks, and from the start of the input when rendering. Each format receives it in its own
/// form; see [`EventData`]. Events are kept in an [`Events`], which holds the system exclusive
/// bytes an event borrows.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Event<'a> {
    /// Zero-based sample offset in the block or render input.
    pub offset: usize,
    /// For a chain, the index of one of its external event inputs or outputs; for a plugin hosted
    /// directly, the index of its native event port in that direction.
    pub port: usize,
    /// MIDI, SysEx, note, or note-expression payload.
    pub data: EventData<'a>,
}

/// What an event carries.
///
/// Plugins receive notes and expressions in their format's note events where it has them: CLAP
/// note and note expression events on ports that take the CLAP dialect, and VST3 note events,
/// note expression values, and poly pressure. VST3 names a note by its ID, so a note off or an
/// expression without an ID reaches each note on its key by that note's ID, and a note started
/// without an ID takes no expression other than pressure. Ports that take MIDI only receive the
/// MIDI 1.0 form of [`EventData::to_midi`]; the note ID and the precision beyond 7 bits are lost
/// there, and an expression other than pressure has no such form and is not delivered. Output
/// notes and expressions in a format's note events become these variants; MIDI output stays MIDI.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum EventData<'a> {
    /// A MIDI 1.0 channel message. Program change and channel pressure use two bytes; the third
    /// is ignored. MPE is MIDI 1.0 on member channels and is delivered as MIDI.
    Midi([u8; 3]),
    /// A complete system exclusive message, from its F0 to its F7.
    SysEx(&'a [u8]),
    /// Starts a note with normalized velocity and an optional independent note ID.
    NoteOn(Note),
    /// Ends the notes it addresses; `velocity` is the release velocity.
    NoteOff(Note),
    /// Changes an expression of the addressed note or notes.
    Expression(NoteExpression),
}

/// A note, or the notes a note off addresses. A note with an ID is told apart from other notes on
/// the same key by it; without one, it addresses notes by port, channel and key, as MIDI does.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Note {
    /// At most [`MAX_NOTE_ID`].
    pub id: Option<u32>,
    /// 0..=15.
    pub channel: u8,
    /// 0..=127, with 60 the middle C.
    pub key: u8,
    /// 0..=1.
    pub velocity: f64,
}

/// A change of one expression of the notes it addresses, which applies from its offset until the
/// next change of the same expression. With an ID it addresses that note; without one, every note
/// on its port, channel and key.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct NoteExpression {
    /// At most [`MAX_NOTE_ID`].
    pub id: Option<u32>,
    /// 0..=15.
    pub channel: u8,
    /// 0..=127.
    pub key: u8,
    /// Expression dimension and its allowed value range.
    pub kind: ExpressionKind,
    /// In the range of `kind`, see [`ExpressionKind::range`].
    pub value: f64,
}

/// The expressions a single note has, with the value ranges CLAP defines for them. VST3 receives
/// the first six as note expression values and pressure as poly pressure.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ExpressionKind {
    /// Linear gain, 0..=4; 1 leaves the note's level as it is.
    Volume,
    /// 0..=1: 0 is left, 0.5 center, and 1 right.
    Pan,
    /// Semitones in equal temperament, -120..=120, relative to the note's key.
    Tuning,
    /// 0..=1.
    Vibrato,
    /// 0..=1.
    Expression,
    /// 0..=1.
    Brightness,
    /// 0..=1. In MIDI 1.0, poly pressure.
    Pressure,
}

impl ExpressionKind {
    /// Every expression, in declaration order.
    pub const ALL: [ExpressionKind; 7] = [
        ExpressionKind::Volume,
        ExpressionKind::Pan,
        ExpressionKind::Tuning,
        ExpressionKind::Vibrato,
        ExpressionKind::Expression,
        ExpressionKind::Brightness,
        ExpressionKind::Pressure,
    ];

    /// The values the expression takes.
    pub fn range(self) -> RangeInclusive<f64> {
        match self {
            ExpressionKind::Volume => 0.0..=4.0,
            ExpressionKind::Tuning => -120.0..=120.0,
            ExpressionKind::Pan
            | ExpressionKind::Vibrato
            | ExpressionKind::Expression
            | ExpressionKind::Brightness
            | ExpressionKind::Pressure => 0.0..=1.0,
        }
    }
}

impl Note {
    /// Constructs a note without an independent ID; input validation occurs at processing.
    #[must_use]
    pub fn new(channel: u8, key: u8, velocity: f64) -> Note {
        Note {
            id: None,
            channel,
            key,
            velocity,
        }
    }

    /// The same note with an ID.
    #[must_use]
    pub fn with_id(self, id: u32) -> Note {
        Note {
            id: Some(id),
            ..self
        }
    }

    fn is_valid(&self) -> bool {
        valid_address(self.id, self.channel, self.key)
            && self.velocity.is_finite()
            && (0.0..=1.0).contains(&self.velocity)
    }
}

impl NoteExpression {
    /// Constructs an expression addressing notes by channel and key, without an ID.
    #[must_use]
    pub fn new(channel: u8, key: u8, kind: ExpressionKind, value: f64) -> NoteExpression {
        NoteExpression {
            id: None,
            channel,
            key,
            kind,
            value,
        }
    }

    /// The same expression for the note with this ID.
    #[must_use]
    pub fn with_id(self, id: u32) -> NoteExpression {
        NoteExpression {
            id: Some(id),
            ..self
        }
    }

    fn is_valid(&self) -> bool {
        valid_address(self.id, self.channel, self.key)
            && self.value.is_finite()
            && self.kind.range().contains(&self.value)
    }
}

fn valid_address(id: Option<u32>, channel: u8, key: u8) -> bool {
    id.is_none_or(|id| id <= MAX_NOTE_ID) && channel < 16 && key < 0x80
}

/// Whether a channel message's status takes one data byte: program change and channel pressure.
fn two_bytes(status: u8) -> bool {
    matches!(status & 0xF0, 0xC0 | 0xD0)
}

/// A 7-bit MIDI value from a value in 0..=1.
fn seven_bits(value: f64) -> u8 {
    (value * 127.0).round().clamp(0.0, 127.0) as u8
}

impl EventData<'_> {
    /// The MIDI 1.0 channel message form: the message itself, a note on (with a velocity of at
    /// least 1, since 0 would end the note) or note off, or poly pressure for a pressure
    /// expression. `None` for system exclusive data and the other expressions.
    pub fn to_midi(&self) -> Option<[u8; 3]> {
        Some(match self {
            EventData::Midi([status, first, _]) if two_bytes(*status) => [*status, *first, 0],
            EventData::Midi(bytes) => *bytes,
            EventData::NoteOn(note) => [
                0x90 | (note.channel & 0x0F),
                note.key & 0x7F,
                seven_bits(note.velocity).max(1),
            ],
            EventData::NoteOff(note) => [
                0x80 | (note.channel & 0x0F),
                note.key & 0x7F,
                seven_bits(note.velocity),
            ],
            EventData::Expression(expression) if expression.kind == ExpressionKind::Pressure => [
                0xA0 | (expression.channel & 0x0F),
                expression.key & 0x7F,
                seven_bits(expression.value),
            ],
            EventData::Expression(_) | EventData::SysEx(_) => return None,
        })
    }
}

/// A decoded channel message. Channels are 0..=15; data values are 7-bit except the 14-bit pitch
/// bend (8192 is the center).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Message {
    /// Ends a MIDI note; velocity is release velocity.
    NoteOff {
        /// MIDI channel in `0..=15`.
        channel: u8,
        /// MIDI key in `0..=127`; 60 is middle C.
        key: u8,
        /// Seven-bit attack or release velocity.
        velocity: u8,
    },
    /// Starts a MIDI note.
    NoteOn {
        /// MIDI channel in `0..=15`.
        channel: u8,
        /// MIDI key in `0..=127`; 60 is middle C.
        key: u8,
        /// Seven-bit attack or release velocity.
        velocity: u8,
    },
    /// Changes pressure for a channel/key pair.
    PolyPressure {
        /// MIDI channel in `0..=15`.
        channel: u8,
        /// MIDI key in `0..=127`; 60 is middle C.
        key: u8,
        /// Seven-bit pressure value.
        pressure: u8,
    },
    /// Changes a MIDI controller value.
    ControlChange {
        /// MIDI channel in `0..=15`.
        channel: u8,
        /// MIDI controller number in `0..=127`.
        controller: u8,
        /// Seven-bit controller value.
        value: u8,
    },
    /// Selects a MIDI program.
    ProgramChange {
        /// MIDI channel in `0..=15`.
        channel: u8,
        /// Zero-based MIDI program number in `0..=127`.
        program: u8,
    },
    /// Changes pressure for every note on the channel.
    ChannelPressure {
        /// MIDI channel in `0..=15`.
        channel: u8,
        /// Seven-bit pressure value.
        pressure: u8,
    },
    /// Changes the channel’s 14-bit pitch-bend value.
    PitchBend {
        /// MIDI channel in `0..=15`.
        channel: u8,
        /// Pitch bend in `0..=16383`; 8192 is center.
        value: u16,
    },
}

impl<'a> Event<'a> {
    /// An event on port 0.
    #[must_use]
    pub fn new(offset: usize, data: EventData<'a>) -> Event<'a> {
        Event {
            offset,
            port: 0,
            data,
        }
    }

    /// A MIDI 1.0 channel message on port 0.
    #[must_use]
    pub fn midi(offset: usize, data: [u8; 3]) -> Event<'a> {
        Self::new(offset, EventData::Midi(data))
    }

    /// A MIDI 1.0 note on.
    #[must_use]
    pub fn note_on(offset: usize, channel: u8, key: u8, velocity: u8) -> Event<'a> {
        Self::midi(
            offset,
            [0x90 | (channel & 0x0F), key & 0x7F, velocity & 0x7F],
        )
    }

    /// A MIDI 1.0 note off.
    #[must_use]
    pub fn note_off(offset: usize, channel: u8, key: u8, velocity: u8) -> Event<'a> {
        Self::midi(
            offset,
            [0x80 | (channel & 0x0F), key & 0x7F, velocity & 0x7F],
        )
    }

    /// Constructs a MIDI controller event on port 0, masking channel and data to MIDI widths.
    #[must_use]
    pub fn control_change(offset: usize, channel: u8, controller: u8, value: u8) -> Event<'a> {
        Self::midi(
            offset,
            [0xB0 | (channel & 0x0F), controller & 0x7F, value & 0x7F],
        )
    }

    /// A system exclusive message on port 0; `bytes` include the F0 and the F7.
    #[must_use]
    pub fn sysex(offset: usize, bytes: &'a [u8]) -> Event<'a> {
        Self::new(offset, EventData::SysEx(bytes))
    }

    /// The same event on `port`.
    #[must_use]
    pub fn on_port(self, port: usize) -> Event<'a> {
        Event { port, ..self }
    }

    /// The same event at `offset`.
    #[must_use]
    pub fn at(self, offset: usize) -> Event<'a> {
        Event { offset, ..self }
    }

    /// The MIDI 1.0 channel message, or `None` for other data or bytes that are not a channel
    /// message. A note on with velocity 0 is a note off, as in MIDI.
    pub fn message(&self) -> Option<Message> {
        let EventData::Midi([status, first, second]) = self.data else {
            return None;
        };
        // Program change and channel pressure have no second data byte.
        if !(0x80..0xF0).contains(&status) || first > 0x7F || (second > 0x7F && !two_bytes(status))
        {
            return None;
        }
        let channel = status & 0x0F;
        Some(match status & 0xF0 {
            0x80 => Message::NoteOff {
                channel,
                key: first,
                velocity: second,
            },
            0x90 if second == 0 => Message::NoteOff {
                channel,
                key: first,
                velocity: 64,
            },
            0x90 => Message::NoteOn {
                channel,
                key: first,
                velocity: second,
            },
            0xA0 => Message::PolyPressure {
                channel,
                key: first,
                pressure: second,
            },
            0xB0 => Message::ControlChange {
                channel,
                controller: first,
                value: second,
            },
            0xC0 => Message::ProgramChange {
                channel,
                program: first,
            },
            0xD0 => Message::ChannelPressure {
                channel,
                pressure: first,
            },
            _ => Message::PitchBend {
                channel,
                value: u16::from(first) | (u16::from(second) << 7),
            },
        })
    }

    /// Whether the data is a MIDI 1.0 channel message, a complete system exclusive message, or a
    /// note or expression with values in their ranges.
    pub fn is_valid(&self) -> bool {
        match self.data {
            EventData::Midi(_) => self.message().is_some(),
            EventData::SysEx(bytes) => {
                bytes.len() >= 2
                    && bytes[0] == 0xF0
                    && bytes[bytes.len() - 1] == 0xF7
                    && bytes[1..bytes.len() - 1].iter().all(|&byte| byte < 0x80)
            }
            EventData::NoteOn(note) | EventData::NoteOff(note) => note.is_valid(),
            EventData::Expression(expression) => expression.is_valid(),
        }
    }
}

/// Whether `events` can go with a block of `frames` samples: valid events in offset order, every
/// offset inside the block. Budgets and ports are checked separately.
pub fn events_fit(events: &Events, frames: usize) -> bool {
    let mut previous = 0;
    events.iter().all(|event| {
        let ordered = event.offset >= previous;
        previous = event.offset;
        ordered && event.offset < frames && event.is_valid()
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn block_event_budget_counts_both_inputs_without_integer_overflow() {
        assert_eq!(validate_event_count(0, 0), Ok(()));
        assert_eq!(validate_event_count(MAX_BLOCK_EVENTS, 0), Ok(()));
        assert_eq!(validate_event_count(1, MAX_BLOCK_EVENTS - 1), Ok(()));
        for (automation, events) in [
            (MAX_BLOCK_EVENTS, 1),
            (0, MAX_BLOCK_EVENTS + 1),
            (usize::MAX, usize::MAX),
            (1, usize::MAX),
        ] {
            assert_eq!(
                validate_event_count(automation, events),
                Err(crate::InputError::EventCapacity)
            );
        }
    }

    #[test]
    fn channel_messages_decode() {
        assert_eq!(
            Event::note_on(0, 1, 60, 100).message(),
            Some(Message::NoteOn {
                channel: 1,
                key: 60,
                velocity: 100
            })
        );
        assert!(matches!(
            Event::note_on(0, 0, 60, 0).message(),
            Some(Message::NoteOff { key: 60, .. })
        ));
        assert_eq!(
            Event::midi(0, [0xE3, 0x00, 0x40]).message(),
            Some(Message::PitchBend {
                channel: 3,
                value: 8192
            })
        );
        let clock = Event::midi(0, [0xF8, 0, 0]);
        assert_eq!(clock.message(), None);
        assert!(!clock.is_valid());
    }

    #[test]
    fn system_exclusive_messages_are_complete_and_budgeted() {
        let sysex = Event::sysex(0, &[0xF0, 0x7D, 0x01, 0xF7]).on_port(1);
        assert!(sysex.is_valid());
        assert_eq!(sysex.message(), None);
        assert_eq!(sysex.data.to_midi(), None);
        assert_eq!(sysex.port, 1);
        for bytes in [vec![0xF0], vec![0xF0, 0x80, 0xF7], vec![0x7D, 0xF7]] {
            assert!(!Event::sysex(0, &bytes).is_valid());
        }
        let mut large = vec![0; MAX_BLOCK_SYSEX_BYTES + 1];
        large[0] = 0xF0;
        large[MAX_BLOCK_SYSEX_BYTES] = 0xF7;
        assert_eq!(
            validate_event_budget(0, &Events::from_iter([Event::sysex(0, &large)])),
            Err(crate::InputError::EventCapacity)
        );
    }

    #[test]
    fn notes_and_expressions_are_checked_against_their_ranges() {
        let note = Note::new(15, 127, 1.0).with_id(MAX_NOTE_ID);
        assert!(Event::new(0, EventData::NoteOn(note)).is_valid());
        for invalid in [
            Note::new(16, 60, 0.5),
            Note::new(0, 128, 0.5),
            Note::new(0, 60, 1.5),
            Note::new(0, 60, f64::NAN),
            Note::new(0, 60, 0.5).with_id(MAX_NOTE_ID + 1),
        ] {
            assert!(!Event::new(0, EventData::NoteOff(invalid)).is_valid());
        }
        for (kind, min, max) in [
            (ExpressionKind::Volume, 0.0, 4.0),
            (ExpressionKind::Pan, 0.0, 1.0),
            (ExpressionKind::Tuning, -120.0, 120.0),
            (ExpressionKind::Vibrato, 0.0, 1.0),
            (ExpressionKind::Expression, 0.0, 1.0),
            (ExpressionKind::Brightness, 0.0, 1.0),
            (ExpressionKind::Pressure, 0.0, 1.0),
        ] {
            for (value, valid) in [
                (min, true),
                (max, true),
                (min - 0.001, false),
                (max + 0.001, false),
                (f64::NAN, false),
                (f64::NEG_INFINITY, false),
                (f64::INFINITY, false),
            ] {
                let expression = NoteExpression::new(0, 60, kind, value).with_id(3);
                assert_eq!(
                    Event::new(0, EventData::Expression(expression)).is_valid(),
                    valid,
                    "{kind:?} {value}"
                );
            }
        }
    }

    #[test]
    fn notes_and_pressure_have_a_midi_form() {
        let note = Note::new(2, 64, 0.0).with_id(9);
        assert_eq!(EventData::NoteOn(note).to_midi(), Some([0x92, 64, 1]));
        let note = Note::new(2, 64, 0.5);
        assert_eq!(EventData::NoteOff(note).to_midi(), Some([0x82, 64, 64]));
        let pressure = NoteExpression::new(1, 60, ExpressionKind::Pressure, 1.0);
        assert_eq!(
            EventData::Expression(pressure).to_midi(),
            Some([0xA1, 60, 127])
        );
        let tuning = NoteExpression::new(1, 60, ExpressionKind::Tuning, 1.0);
        assert_eq!(EventData::Expression(tuning).to_midi(), None);
    }

    #[test]
    fn two_byte_messages_ignore_their_third_byte() {
        for status in [0xC3, 0xD3] {
            let event = Event::midi(0, [status, 5, 0x80]);
            assert!(event.is_valid());
            assert_eq!(event.data.to_midi(), Some([status, 5, 0]));
        }
        assert!(!Event::midi(0, [0xB3, 5, 0x80]).is_valid());
    }

    #[test]
    fn events_must_be_ordered_and_inside_the_block() {
        let on = Event::note_on(10, 0, 60, 100);
        let off = Event::note_off(20, 0, 60, 0);
        assert!(events_fit(&Events::from_iter([on, off]), 64));
        assert!(!events_fit(&Events::from_iter([off, on]), 64));
        assert!(!events_fit(&Events::from_iter([on, off]), 20));
    }
}