1use std::ops::RangeInclusive;
6
7mod events;
8pub use events::{Events, Iter};
9
10pub const MAX_BLOCK_EVENTS: usize = 4096;
16
17pub const MAX_BLOCK_SYSEX_BYTES: usize = 64 << 10;
21
22pub const MAX_NOTE_ID: u32 = i32::MAX as u32;
24
25pub(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
36pub 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#[derive(Clone, Copy, Debug, PartialEq)]
50#[non_exhaustive]
51pub struct Event<'a> {
52 pub offset: usize,
54 pub port: usize,
57 pub data: EventData<'a>,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq)]
72#[non_exhaustive]
73pub enum EventData<'a> {
74 Midi([u8; 3]),
77 SysEx(&'a [u8]),
79 NoteOn(Note),
81 NoteOff(Note),
83 Expression(NoteExpression),
85}
86
87#[derive(Clone, Copy, Debug, PartialEq)]
90#[non_exhaustive]
91pub struct Note {
92 pub id: Option<u32>,
94 pub channel: u8,
96 pub key: u8,
98 pub velocity: f64,
100}
101
102#[derive(Clone, Copy, Debug, PartialEq)]
106#[non_exhaustive]
107pub struct NoteExpression {
108 pub id: Option<u32>,
110 pub channel: u8,
112 pub key: u8,
114 pub kind: ExpressionKind,
116 pub value: f64,
118}
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123#[non_exhaustive]
124pub enum ExpressionKind {
125 Volume,
127 Pan,
129 Tuning,
131 Vibrato,
133 Expression,
135 Brightness,
137 Pressure,
139}
140
141impl ExpressionKind {
142 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 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 #[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 #[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 #[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 #[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
228fn two_bytes(status: u8) -> bool {
230 matches!(status & 0xF0, 0xC0 | 0xD0)
231}
232
233fn seven_bits(value: f64) -> u8 {
235 (value * 127.0).round().clamp(0.0, 127.0) as u8
236}
237
238impl EventData<'_> {
239 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269#[non_exhaustive]
270pub enum Message {
271 NoteOff {
273 channel: u8,
275 key: u8,
277 velocity: u8,
279 },
280 NoteOn {
282 channel: u8,
284 key: u8,
286 velocity: u8,
288 },
289 PolyPressure {
291 channel: u8,
293 key: u8,
295 pressure: u8,
297 },
298 ControlChange {
300 channel: u8,
302 controller: u8,
304 value: u8,
306 },
307 ProgramChange {
309 channel: u8,
311 program: u8,
313 },
314 ChannelPressure {
316 channel: u8,
318 pressure: u8,
320 },
321 PitchBend {
323 channel: u8,
325 value: u16,
327 },
328}
329
330impl<'a> Event<'a> {
331 #[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 #[must_use]
343 pub fn midi(offset: usize, data: [u8; 3]) -> Event<'a> {
344 Self::new(offset, EventData::Midi(data))
345 }
346
347 #[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 #[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 #[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 #[must_use]
376 pub fn sysex(offset: usize, bytes: &'a [u8]) -> Event<'a> {
377 Self::new(offset, EventData::SysEx(bytes))
378 }
379
380 #[must_use]
382 pub fn on_port(self, port: usize) -> Event<'a> {
383 Event { port, ..self }
384 }
385
386 #[must_use]
388 pub fn at(self, offset: usize) -> Event<'a> {
389 Event { offset, ..self }
390 }
391
392 pub fn message(&self) -> Option<Message> {
395 let EventData::Midi([status, first, second]) = self.data else {
396 return None;
397 };
398 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 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
462pub 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}