qualia_audio/midi/bridge/to_note_events.rs
1//! Pair a stream of timed MIDI events into whole notes (`note-on` matched to its
2//! `note-off`).
3//!
4//! Lane AU-MIDI-BRIDGE. The input is a tick-ordered slice of
5//! [`crate::midi::sequencer::TimedEvent`] — the sequencer's event currency, and
6//! the natural flattened form of an authored [`crate::midi::smf`] track (each
7//! delta-timed [`crate::midi::smf::TrackEvent::Midi`] carries a status + data
8//! bytes at an absolute tick). This function walks that stream, matches each
9//! note-on to the next note-off (or velocity-0 note-on, the running-status note
10//! off) on the same channel + note, and emits one [`PairedNote`] per completed
11//! note with its `start_tick`, `end_tick`, and attack `velocity`.
12//!
13//! # Epistemic contract — authored MIDI is AUTHORITATIVE
14//!
15//! Notes paired here come from *authored / imported* MIDI (a sequencer track or
16//! a parsed SMF), which is **authoritative** ground truth — unlike transcribed
17//! proposals produced by [`super::from_pitch_midi`]. This function adds no
18//! confidence field because none is warranted: an authored note is asserted, not
19//! proposed. Callers must not blend a [`PairedNote`] with a transcription
20//! proposal without tracking which stream it came from.
21//!
22//! Zero-heap: pairing state lives in a fixed on-stack table; completed notes are
23//! written into the caller-supplied `out` slice.
24
25use crate::midi::sequencer::TimedEvent;
26use crate::types::AudioError;
27
28/// Maximum number of notes that may be sounding simultaneously while pairing.
29/// A stream with more than this many concurrently-open note-ons is rejected.
30pub const MAX_OPEN_NOTES: usize = 128;
31
32/// A whole note recovered by pairing a note-on with its note-off.
33#[repr(C)]
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct PairedNote {
36 /// MIDI channel, 0..=15.
37 pub channel: u8,
38 /// Note number, 0..=127.
39 pub note: u8,
40 /// Attack velocity from the note-on, 0..=127.
41 pub velocity: u8,
42 /// Tick of the note-on.
43 pub start_tick: u64,
44 /// Tick of the matched note-off.
45 pub end_tick: u64,
46}
47
48impl PairedNote {
49 /// An all-zero placeholder for initialising a caller-owned `out` array.
50 pub const ZERO: PairedNote = PairedNote {
51 channel: 0,
52 note: 0,
53 velocity: 0,
54 start_tick: 0,
55 end_tick: 0,
56 };
57}
58
59/// One currently-sounding note-on awaiting its note-off.
60#[derive(Clone, Copy)]
61struct OpenNote {
62 channel: u8,
63 note: u8,
64 velocity: u8,
65 start_tick: u64,
66}
67
68/// True if `status` is a note-on (`0x9n`).
69#[inline]
70fn is_note_on(status: u8) -> bool {
71 status & 0xF0 == 0x90
72}
73
74/// True if `status` is a note-off (`0x8n`).
75#[inline]
76fn is_note_off(status: u8) -> bool {
77 status & 0xF0 == 0x80
78}
79
80/// Pair a tick-ordered timed-MIDI stream into whole notes.
81///
82/// A note opens on a note-on with `velocity > 0`. It closes on the first
83/// subsequent note-off (`0x8n`) **or** velocity-0 note-on (`0x9n` vel 0) with the
84/// same channel and note; the newest matching open note is closed first (LIFO),
85/// which is the standard resolution for a repeated note re-struck before its
86/// first release. Unmatched note-ons still open at the end of the stream are
87/// dropped (no synthetic note-off is invented). Non-note events are ignored.
88///
89/// - `events`: the timed MIDI stream (sequencer track / flattened SMF track).
90/// - `out`: caller-owned destination for completed [`PairedNote`]s.
91///
92/// Returns the number of notes written to `out`.
93///
94/// # Errors
95/// - [`AudioError::OutputBufferTooSmall`] if `out` cannot hold every completed
96/// note.
97/// - [`AudioError::InvalidParameter`] if more than [`MAX_OPEN_NOTES`] notes are
98/// sounding at once (pairing table exhausted).
99pub fn pair_note_events(
100 events: &[TimedEvent],
101 out: &mut [PairedNote],
102) -> Result<usize, AudioError> {
103 let mut open: [Option<OpenNote>; MAX_OPEN_NOTES] = [None; MAX_OPEN_NOTES];
104 let mut open_len = 0usize;
105 let mut count = 0usize;
106
107 for ev in events {
108 let channel = ev.status & 0x0F;
109 let note = ev.data1;
110 let velocity = ev.data2;
111
112 let closes = is_note_off(ev.status) || (is_note_on(ev.status) && velocity == 0);
113 let opens = is_note_on(ev.status) && velocity > 0;
114
115 if closes {
116 // Close the newest matching open note (LIFO), if any.
117 if let Some(slot) = find_newest_match(&open, open_len, channel, note) {
118 let on = open[slot].take().expect("matched slot is occupied");
119 // Compact: pull the last live entry into the freed slot.
120 open_len = compact(&mut open, open_len, slot);
121 if count >= out.len() {
122 return Err(AudioError::OutputBufferTooSmall);
123 }
124 out[count] = PairedNote {
125 channel: on.channel,
126 note: on.note,
127 velocity: on.velocity,
128 start_tick: on.start_tick,
129 end_tick: ev.tick,
130 };
131 count += 1;
132 }
133 // An unmatched note-off is a stray release; ignore it.
134 } else if opens {
135 if open_len >= MAX_OPEN_NOTES {
136 return Err(AudioError::InvalidParameter);
137 }
138 open[open_len] = Some(OpenNote {
139 channel,
140 note,
141 velocity,
142 start_tick: ev.tick,
143 });
144 open_len += 1;
145 }
146 // All other events (CC, pitch-bend, meta-as-status, …) are ignored.
147 }
148
149 Ok(count)
150}
151
152/// Index of the newest (highest) occupied slot in `open[..len]` matching
153/// `channel` + `note`, or `None`.
154#[inline]
155fn find_newest_match(
156 open: &[Option<OpenNote>],
157 len: usize,
158 channel: u8,
159 note: u8,
160) -> Option<usize> {
161 for i in (0..len).rev() {
162 if let Some(o) = open[i] {
163 if o.channel == channel && o.note == note {
164 return Some(i);
165 }
166 }
167 }
168 None
169}
170
171/// After clearing `open[slot]`, move the last live entry (`open[len-1]`) into it
172/// so the live entries stay packed in `open[..len-1]`. Returns the new length.
173#[inline]
174fn compact(open: &mut [Option<OpenNote>], len: usize, slot: usize) -> usize {
175 debug_assert!(open[slot].is_none());
176 let last = len - 1;
177 if slot != last {
178 open[slot] = open[last].take();
179 } else {
180 open[last] = None;
181 }
182 last
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188
189 #[test]
190 fn golden_pairs_one_note() {
191 // Note-on at tick 0, note-off at tick 480, same channel + note.
192 let events = [
193 TimedEvent::new(0, 0x90, 60, 100),
194 TimedEvent::new(480, 0x80, 60, 0),
195 ];
196 let mut out = [PairedNote::ZERO; 4];
197 let n = pair_note_events(&events, &mut out).expect("pair");
198 assert_eq!(n, 1);
199 assert_eq!(
200 out[0],
201 PairedNote {
202 channel: 0,
203 note: 60,
204 velocity: 100,
205 start_tick: 0,
206 end_tick: 480
207 }
208 );
209 }
210
211 #[test]
212 fn velocity_zero_note_on_closes_the_note() {
213 // Running-status note off: 0x90 note 62 vel 0.
214 let events = [
215 TimedEvent::new(10, 0x90, 62, 90),
216 TimedEvent::new(100, 0x90, 62, 0),
217 ];
218 let mut out = [PairedNote::ZERO; 2];
219 let n = pair_note_events(&events, &mut out).expect("pair");
220 assert_eq!(n, 1);
221 assert_eq!(out[0].start_tick, 10);
222 assert_eq!(out[0].end_tick, 100);
223 assert_eq!(out[0].velocity, 90);
224 }
225
226 #[test]
227 fn two_overlapping_notes_on_different_channels() {
228 let events = [
229 TimedEvent::new(0, 0x90, 60, 100), // ch0 on
230 TimedEvent::new(5, 0x91, 64, 80), // ch1 on
231 TimedEvent::new(50, 0x81, 64, 0), // ch1 off
232 TimedEvent::new(60, 0x80, 60, 0), // ch0 off
233 ];
234 let mut out = [PairedNote::ZERO; 4];
235 let n = pair_note_events(&events, &mut out).expect("pair");
236 assert_eq!(n, 2);
237 // ch1 note closes first.
238 assert_eq!(
239 (
240 out[0].channel,
241 out[0].note,
242 out[0].start_tick,
243 out[0].end_tick
244 ),
245 (1, 64, 5, 50)
246 );
247 assert_eq!(
248 (
249 out[1].channel,
250 out[1].note,
251 out[1].start_tick,
252 out[1].end_tick
253 ),
254 (0, 60, 0, 60)
255 );
256 }
257
258 #[test]
259 fn restruck_note_pairs_lifo() {
260 // Same note struck twice before any release, then two releases.
261 let events = [
262 TimedEvent::new(0, 0x90, 60, 100),
263 TimedEvent::new(10, 0x90, 60, 110),
264 TimedEvent::new(20, 0x80, 60, 0), // closes the newest (start 10)
265 TimedEvent::new(30, 0x80, 60, 0), // closes the older (start 0)
266 ];
267 let mut out = [PairedNote::ZERO; 4];
268 let n = pair_note_events(&events, &mut out).expect("pair");
269 assert_eq!(n, 2);
270 assert_eq!(
271 (out[0].start_tick, out[0].end_tick, out[0].velocity),
272 (10, 20, 110)
273 );
274 assert_eq!(
275 (out[1].start_tick, out[1].end_tick, out[1].velocity),
276 (0, 30, 100)
277 );
278 }
279
280 #[test]
281 fn unmatched_note_on_is_dropped() {
282 let events = [TimedEvent::new(0, 0x90, 60, 100)];
283 let mut out = [PairedNote::ZERO; 2];
284 let n = pair_note_events(&events, &mut out).expect("pair");
285 assert_eq!(n, 0);
286 }
287
288 #[test]
289 fn non_note_events_ignored() {
290 let events = [
291 TimedEvent::new(0, 0xB0, 7, 100), // control change
292 TimedEvent::new(0, 0x90, 60, 100), // note on
293 TimedEvent::new(0, 0xE0, 0, 64), // pitch bend
294 TimedEvent::new(20, 0x80, 60, 0), // note off
295 ];
296 let mut out = [PairedNote::ZERO; 2];
297 let n = pair_note_events(&events, &mut out).expect("pair");
298 assert_eq!(n, 1);
299 assert_eq!(out[0].note, 60);
300 }
301
302 #[test]
303 fn output_too_small_reported() {
304 let events = [
305 TimedEvent::new(0, 0x90, 60, 100),
306 TimedEvent::new(10, 0x80, 60, 0),
307 TimedEvent::new(20, 0x90, 62, 100),
308 TimedEvent::new(30, 0x80, 62, 0),
309 ];
310 let mut out = [PairedNote::ZERO; 1];
311 assert_eq!(
312 pair_note_events(&events, &mut out),
313 Err(AudioError::OutputBufferTooSmall)
314 );
315 }
316}