Skip to main content

qualia_audio/midi/bridge/
from_pitch_midi.rs

1//! Convert transcribed pitch→MIDI [`NoteEvent`] proposals into sequencer
2//! [`TimedEvent`] note-on / note-off pairs.
3//!
4//! Lane AU-MIDI-BRIDGE. This reconciles two already-built pieces without
5//! reimplementing either: [`crate::features::pitch_midi::NoteEvent`] (the output
6//! of `segment_notes` / `audio_to_midi`) and [`crate::midi::sequencer::TimedEvent`]
7//! (the sequencer's timeline event currency).
8//!
9//! # Epistemic contract — these events are PROPOSALS
10//!
11//! Every [`TimedEvent`] this function emits derives from a *transcribed*
12//! [`NoteEvent`], which carries a per-note voicing `confidence` and is a
13//! **proposal**, never an authoritative transcription. `TimedEvent` is a bare
14//! `(tick, status, data1, data2)` POD with no room for confidence, so the
15//! proposal status **cannot travel inside the event** — it is a property of the
16//! path: anything produced by [`note_events_to_timed`] is proposal-grade and
17//! must be treated as such downstream (weighted, reviewed, or rejected on the
18//! originating note's confidence). This is the opposite of events flattened from
19//! an authored/imported SMF via [`super::to_note_events`], which are
20//! AUTHORITATIVE. See [`PROPOSAL_NOTE`].
21//!
22//! Zero-heap: note-on/off events are written into the caller-supplied `out`
23//! slice; the function allocates nothing.
24
25use crate::features::pitch_midi::NoteEvent;
26use crate::midi::message::note::{STATUS_NOTE_OFF, STATUS_NOTE_ON};
27use crate::midi::sequencer::TimedEvent;
28use crate::types::AudioError;
29
30/// The MIDI channel transcribed proposals are placed on. Transcription has no
31/// channel concept, so a single default channel is used.
32pub const PROPOSAL_CHANNEL: u8 = 0;
33
34/// Release velocity written into the generated note-off events.
35pub const NOTE_OFF_VELOCITY: u8 = 0;
36
37/// Human-readable statement of the epistemic status of every event this module
38/// emits, for surfacing in provenance / UI. Transcribed MIDI is a proposal.
39pub const PROPOSAL_NOTE: &str =
40    "transcribed (audio→MIDI) — epistemic PROPOSAL carrying source confidence, not authoritative";
41
42/// Map an audio frame index to a sequencer tick given `frames_per_tick`.
43///
44/// `tick = round(frame / frames_per_tick)`. `frames_per_tick` is the width of
45/// one PPQ tick measured in analysis frames — e.g. with a hop that yields 10
46/// frames per tick, frame 100 maps to tick 10.
47#[inline]
48fn frame_to_tick(frame: u32, frames_per_tick: f32) -> u64 {
49    let t = (frame as f32 / frames_per_tick).round();
50    if t <= 0.0 {
51        0
52    } else {
53        t as u64
54    }
55}
56
57/// Convert transcribed [`NoteEvent`] proposals into paired note-on / note-off
58/// [`TimedEvent`]s on the sequencer timeline.
59///
60/// For each input note two events are written to `out`, in order: a note-on at
61/// the tick its `start_frame` maps to (status `0x90`, velocity from the note),
62/// then a note-off at the tick its `end_frame` maps to (status `0x80`, release
63/// velocity [`NOTE_OFF_VELOCITY`]). Both carry [`PROPOSAL_CHANNEL`].
64///
65/// The output is **not** re-sorted: it is emitted in input order as on/off
66/// pairs. Because `segment_notes` yields notes in start-frame order, callers who
67/// need a tick-sorted [`crate::midi::sequencer::Track`] should `insert` each
68/// event (which keeps the track sorted) rather than assume global tick order.
69///
70/// - `events`: transcribed note proposals (see [`crate::features::pitch_midi`]).
71/// - `frames_per_tick`: analysis frames per PPQ tick; must be finite and `> 0`.
72/// - `out`: caller-owned destination; must hold `2 * events.len()` events.
73///
74/// Returns the number of [`TimedEvent`]s written (always `2 * events.len()`).
75///
76/// Every emitted event is a **proposal** (see the module docs / [`PROPOSAL_NOTE`]).
77///
78/// # Errors
79/// - [`AudioError::InvalidParameter`] if `frames_per_tick` is not finite/`> 0`,
80///   or a note's `note`/`velocity` is out of MIDI range (`> 127`).
81/// - [`AudioError::OutputBufferTooSmall`] if `out` cannot hold every event.
82pub fn note_events_to_timed(
83    events: &[NoteEvent],
84    frames_per_tick: f32,
85    out: &mut [TimedEvent],
86) -> Result<usize, AudioError> {
87    if !frames_per_tick.is_finite() || frames_per_tick <= 0.0 {
88        return Err(AudioError::InvalidParameter);
89    }
90    let needed = events
91        .len()
92        .checked_mul(2)
93        .ok_or(AudioError::InvalidParameter)?;
94    if out.len() < needed {
95        return Err(AudioError::OutputBufferTooSmall);
96    }
97
98    let mut n = 0usize;
99    for ev in events {
100        if ev.note > 127 || ev.velocity > 127 {
101            return Err(AudioError::InvalidParameter);
102        }
103        let on_tick = frame_to_tick(ev.start_frame, frames_per_tick);
104        let off_tick = frame_to_tick(ev.end_frame, frames_per_tick);
105
106        out[n] = TimedEvent::new(
107            on_tick,
108            STATUS_NOTE_ON | (PROPOSAL_CHANNEL & 0x0F),
109            ev.note,
110            ev.velocity,
111        );
112        out[n + 1] = TimedEvent::new(
113            off_tick,
114            STATUS_NOTE_OFF | (PROPOSAL_CHANNEL & 0x0F),
115            ev.note,
116            NOTE_OFF_VELOCITY,
117        );
118        n += 2;
119    }
120    Ok(n)
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    fn note_event(note: u8, start: u32, end: u32, vel: u8) -> NoteEvent {
128        NoteEvent {
129            note,
130            velocity: vel,
131            start_frame: start,
132            end_frame: end,
133            confidence: 0.9,
134        }
135    }
136
137    #[test]
138    fn golden_a4_maps_to_on_at_0_off_at_10() {
139        // NoteEvent(note 69, start 0, end 100); frames_per_tick 10 → off tick 10.
140        let events = [note_event(69, 0, 100, 100)];
141        let mut out = [TimedEvent::ZERO; 2];
142        let n = note_events_to_timed(&events, 10.0, &mut out).expect("convert");
143        assert_eq!(n, 2);
144
145        // Note-on at tick 0.
146        assert_eq!(out[0].tick, 0);
147        assert_eq!(out[0].status, 0x90);
148        assert_eq!(out[0].data1, 69);
149        assert_eq!(out[0].data2, 100);
150
151        // Note-off at tick 10.
152        assert_eq!(out[1].tick, 10);
153        assert_eq!(out[1].status, 0x80);
154        assert_eq!(out[1].data1, 69);
155        assert_eq!(out[1].data2, NOTE_OFF_VELOCITY);
156    }
157
158    #[test]
159    fn two_notes_produce_four_events_in_order() {
160        let events = [note_event(60, 0, 48, 80), note_event(62, 48, 96, 90)];
161        let mut out = [TimedEvent::ZERO; 4];
162        let n = note_events_to_timed(&events, 48.0, &mut out).expect("convert");
163        assert_eq!(n, 4);
164        assert_eq!((out[0].tick, out[0].status, out[0].data1), (0, 0x90, 60));
165        assert_eq!((out[1].tick, out[1].status, out[1].data1), (1, 0x80, 60));
166        assert_eq!((out[2].tick, out[2].status, out[2].data1), (1, 0x90, 62));
167        assert_eq!((out[3].tick, out[3].status, out[3].data1), (2, 0x80, 62));
168    }
169
170    #[test]
171    fn bad_frames_per_tick_rejected() {
172        let events = [note_event(69, 0, 100, 100)];
173        let mut out = [TimedEvent::ZERO; 2];
174        assert_eq!(
175            note_events_to_timed(&events, 0.0, &mut out),
176            Err(AudioError::InvalidParameter)
177        );
178        assert_eq!(
179            note_events_to_timed(&events, f32::NAN, &mut out),
180            Err(AudioError::InvalidParameter)
181        );
182    }
183
184    #[test]
185    fn output_too_small_reported() {
186        let events = [note_event(69, 0, 100, 100)];
187        let mut out = [TimedEvent::ZERO; 1];
188        assert_eq!(
189            note_events_to_timed(&events, 10.0, &mut out),
190            Err(AudioError::OutputBufferTooSmall)
191        );
192    }
193
194    #[test]
195    fn out_of_range_note_rejected() {
196        let events = [note_event(200, 0, 100, 100)];
197        let mut out = [TimedEvent::ZERO; 2];
198        assert_eq!(
199            note_events_to_timed(&events, 10.0, &mut out),
200            Err(AudioError::InvalidParameter)
201        );
202    }
203}