Skip to main content

qualia_audio/midi/bridge/
sonic_token.rs

1//! A packed `u64` **SonicToken** for MIDI — the qualia-audio-side bridge type.
2//!
3//! Lane AU-MIDI-BRIDGE. This mirrors the bit layout of core-db's
4//! `net/sonic_token.rs` so a later cross-crate reconciliation can map this token
5//! to that one field-for-field, but it is defined here independently (this crate
6//! takes no dependency on qualia-core-db). It exists so a canonical
7//! [`crate::midi::message::MidiMessage`] can be squeezed into a single 8-byte
8//! `Copy` word for the AcousticPlane hot path and recovered losslessly.
9//!
10//! # Bit layout (mirrors core-db `SonicToken::pack`)
11//! ```text
12//! bits  0.. 8  delta_time      (u8)   — inter-event tick delta (0 here)
13//! bits  8..12  event_type      (4b)   — 0 NoteOn, 1 NoteOff, 2 ControlChange, 3 Parametric
14//! bits 12..16  channel         (4b)   — MIDI channel 0..=15
15//! bits 16..24  note / data     (u8)   — note number, or CC controller number
16//! bits 24..32  velocity/value  (u8)   — velocity, or CC value
17//! bits 32..48  tensor_index    (u16)  — graph node hint (0 here)
18//! bits 48..64  flags           (u16)  — provenance flags (0 here)
19//! ```
20//!
21//! Only the three MIDI-mappable event types round-trip: `NoteOn`, `NoteOff`, and
22//! `ControlChange`. `Parametric` has no MIDI-1.0 equivalent, so
23//! [`sonic_token_to_midi`] returns `None` for it, and non-note/CC messages (pitch
24//! bend, pressure, system) return `None` from [`midi_to_sonic_token`].
25//!
26//! Epistemic note: a `SonicToken` is a *transport encoding*, not a truth claim.
27//! Whether the note it carries is a transcription proposal or an authoritative
28//! authored event is a property of its source stream (see [`super::from_pitch_midi`]
29//! vs [`super::to_note_events`]); the token itself carries no confidence.
30
31use crate::midi::message::control_change::ControlChange;
32use crate::midi::message::note::{NoteOff, NoteOn};
33use crate::midi::message::MidiMessage;
34
35/// Provenance magic byte mirrored from core-db (`'S'`), packed into `flags`.
36pub const SONIC_MAGIC: u8 = 0x53;
37
38/// The MIDI-relevant sonic event types (values match core-db `SonicEventType`).
39#[repr(u8)]
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum SonicEventType {
42    /// Note On (`0x9n`, velocity > 0).
43    NoteOn = 0,
44    /// Note Off (`0x8n`, or `0x9n` velocity 0).
45    NoteOff = 1,
46    /// Control Change (`0xBn`).
47    ControlChange = 2,
48    /// Non-MIDI parametric pulse (no MIDI-1.0 equivalent).
49    Parametric = 3,
50}
51
52impl SonicEventType {
53    /// Decode the 4-bit event-type field.
54    #[inline]
55    fn from_bits(bits: u64) -> Self {
56        match bits & 0x0F {
57            1 => SonicEventType::NoteOff,
58            2 => SonicEventType::ControlChange,
59            3 => SonicEventType::Parametric,
60            _ => SonicEventType::NoteOn,
61        }
62    }
63}
64
65/// Pack the fields into the mirrored `u64` layout.
66///
67/// `note` doubles as the CC controller number; `velocity` doubles as the CC
68/// value. `tensor_index` and `flags` are 16-bit graph/provenance hints (0 for a
69/// pure MIDI bridge token).
70#[inline]
71pub fn pack(
72    delta_time: u8,
73    event_type: SonicEventType,
74    channel: u8,
75    note: u8,
76    velocity: u8,
77    tensor_index: u16,
78    flags: u16,
79) -> u64 {
80    let et = event_type as u64;
81    (delta_time as u64)
82        | ((et & 0x0F) << 8)
83        | (((channel as u64) & 0x0F) << 12)
84        | ((note as u64) << 16)
85        | ((velocity as u64) << 24)
86        | (((tensor_index as u64) & 0xFFFF) << 32)
87        | (((flags as u64) & 0xFFFF) << 48)
88}
89
90/// The 4-bit event type carried by `token`.
91#[inline]
92pub fn event_type(token: u64) -> SonicEventType {
93    SonicEventType::from_bits(token >> 8)
94}
95
96/// The 8-bit delta-time field.
97#[inline]
98pub fn delta_time(token: u64) -> u8 {
99    token as u8
100}
101
102/// The 4-bit channel field (0..=15).
103#[inline]
104pub fn channel(token: u64) -> u8 {
105    ((token >> 12) & 0x0F) as u8
106}
107
108/// The 8-bit note / CC-controller field.
109#[inline]
110pub fn note(token: u64) -> u8 {
111    ((token >> 16) & 0xFF) as u8
112}
113
114/// The 8-bit velocity / CC-value field.
115#[inline]
116pub fn velocity(token: u64) -> u8 {
117    ((token >> 24) & 0xFF) as u8
118}
119
120/// The 16-bit tensor-index (graph node) field.
121#[inline]
122pub fn tensor_index(token: u64) -> u16 {
123    ((token >> 32) & 0xFFFF) as u16
124}
125
126/// The 16-bit flags field.
127#[inline]
128pub fn flags(token: u64) -> u16 {
129    (token >> 48) as u16
130}
131
132/// Encode a [`MidiMessage`] into a packed sonic-token `u64`.
133///
134/// Returns `None` for messages with no sonic-token event type (everything except
135/// note-on, note-off, and control change). A velocity-0 note-on is preserved as
136/// a `NoteOn` (not rewritten to `NoteOff`) so the round-trip is byte-faithful to
137/// the input message; interpret it as a note-off downstream as usual.
138pub fn midi_to_sonic_token(msg: &MidiMessage) -> Option<u64> {
139    match *msg {
140        MidiMessage::NoteOn(NoteOn {
141            channel: ch,
142            note: n,
143            velocity: v,
144        }) => Some(pack(0, SonicEventType::NoteOn, ch, n, v, 0, 0)),
145        MidiMessage::NoteOff(NoteOff {
146            channel: ch,
147            note: n,
148            velocity: v,
149        }) => Some(pack(0, SonicEventType::NoteOff, ch, n, v, 0, 0)),
150        MidiMessage::ControlChange(ControlChange {
151            channel: ch,
152            controller,
153            value,
154        }) => Some(pack(
155            0,
156            SonicEventType::ControlChange,
157            ch,
158            controller,
159            value,
160            0,
161            0,
162        )),
163        _ => None,
164    }
165}
166
167/// Decode a packed sonic-token `u64` back into a [`MidiMessage`].
168///
169/// Returns `None` if the token's event type is [`SonicEventType::Parametric`]
170/// (no MIDI equivalent) or if a decoded field is out of MIDI range (note or
171/// value `> 127`). Channel is always in range (4-bit field).
172pub fn sonic_token_to_midi(token: u64) -> Option<MidiMessage> {
173    let ch = channel(token);
174    let d0 = note(token);
175    let d1 = velocity(token);
176    match event_type(token) {
177        SonicEventType::NoteOn => NoteOn::new(ch, d0, d1).ok().map(MidiMessage::NoteOn),
178        SonicEventType::NoteOff => NoteOff::new(ch, d0, d1).ok().map(MidiMessage::NoteOff),
179        SonicEventType::ControlChange => ControlChange::new(ch, d0, d1)
180            .ok()
181            .map(MidiMessage::ControlChange),
182        SonicEventType::Parametric => None,
183    }
184}
185
186#[cfg(test)]
187mod tests {
188    use super::*;
189
190    #[test]
191    fn golden_note_on_round_trip() {
192        // midi_to_sonic_token(NoteOn ch0 note60 vel100) → u64 → same NoteOn.
193        let msg = MidiMessage::NoteOn(NoteOn {
194            channel: 0,
195            note: 60,
196            velocity: 100,
197        });
198        let token = midi_to_sonic_token(&msg).expect("encodable");
199        // Fields land in the mirrored positions.
200        assert_eq!(event_type(token), SonicEventType::NoteOn);
201        assert_eq!(channel(token), 0);
202        assert_eq!(note(token), 60);
203        assert_eq!(velocity(token), 100);
204        // Full round-trip.
205        assert_eq!(sonic_token_to_midi(token), Some(msg));
206    }
207
208    #[test]
209    fn note_off_round_trip() {
210        let msg = MidiMessage::NoteOff(NoteOff {
211            channel: 9,
212            note: 64,
213            velocity: 40,
214        });
215        let token = midi_to_sonic_token(&msg).expect("encodable");
216        assert_eq!(event_type(token), SonicEventType::NoteOff);
217        assert_eq!(channel(token), 9);
218        assert_eq!(sonic_token_to_midi(token), Some(msg));
219    }
220
221    #[test]
222    fn control_change_round_trip() {
223        // CC controller in the note field, value in the velocity field.
224        let msg = MidiMessage::ControlChange(ControlChange {
225            channel: 3,
226            controller: 7,
227            value: 127,
228        });
229        let token = midi_to_sonic_token(&msg).expect("encodable");
230        assert_eq!(event_type(token), SonicEventType::ControlChange);
231        assert_eq!(channel(token), 3);
232        assert_eq!(note(token), 7); // controller
233        assert_eq!(velocity(token), 127); // value
234        assert_eq!(sonic_token_to_midi(token), Some(msg));
235    }
236
237    #[test]
238    fn pack_layout_matches_core_db_positions() {
239        // Same arguments as core-db's pack_roundtrip, checking the shared layout.
240        let t = pack(3, SonicEventType::NoteOn, 2, 60, 100, 42, 0x0053);
241        assert_eq!(delta_time(t), 3);
242        assert_eq!(event_type(t), SonicEventType::NoteOn);
243        assert_eq!(channel(t), 2);
244        assert_eq!(note(t), 60);
245        assert_eq!(velocity(t), 100);
246        assert_eq!(tensor_index(t), 42);
247        assert_eq!(flags(t), 0x0053);
248    }
249
250    #[test]
251    fn non_mappable_message_returns_none() {
252        assert_eq!(midi_to_sonic_token(&MidiMessage::TimingClock), None);
253        assert_eq!(midi_to_sonic_token(&MidiMessage::TuneRequest), None);
254        assert_eq!(midi_to_sonic_token(&MidiMessage::SongSelect(3)), None);
255    }
256
257    #[test]
258    fn parametric_token_has_no_midi() {
259        let t = pack(0, SonicEventType::Parametric, 0, 0, 100, 0, 0);
260        assert_eq!(sonic_token_to_midi(t), None);
261    }
262}