Skip to main content

qualia_audio/midi/bridge/
smf_provenance.rs

1//! Extract provenance `(key, value)` pairs from a parsed Standard MIDI File for
2//! NQuin emission.
3//!
4//! Lane AU-MIDI-BRIDGE. Walks a parsed [`SmfFile`]'s meta-events and lifts the
5//! human-meaningful provenance — track names, tempo, time signature, key
6//! signature, sequence number, and the copyright notice — into a bounded,
7//! `Copy`, heap-free [`ProvenancePair`] the graph layer can turn into NQuins.
8//! Reuses the existing [`crate::midi::smf`] model; it parses nothing itself.
9//!
10//! # Epistemic contract — SMF provenance is AUTHORITATIVE
11//!
12//! An SMF is authored / imported content, so its embedded metadata (who named
13//! the track, the declared tempo, the copyright holder) is an **authoritative**
14//! assertion by the file's author — not a transcription proposal. These pairs
15//! are safe to record as stated provenance; they carry no confidence because
16//! none is implied.
17//!
18//! Zero-heap: pairs are written into the caller-supplied `out` slice; each pair
19//! stores its value inline in a fixed [`MAX_PROV_VALUE`]-byte buffer (longer text
20//! is truncated).
21
22use crate::midi::smf::{MetaEvent, SmfFile, TrackEvent};
23use crate::types::AudioError;
24
25/// SMF copyright-notice meta type (`0xFF 0x02`); not structurally decoded by the
26/// `smf` module, so it arrives as [`MetaEvent::Unknown`].
27pub const META_COPYRIGHT: u8 = 0x02;
28
29/// Maximum inline value length. Track-name / copyright text longer than this is
30/// truncated; all structured values (tempo, time/key signature, sequence number)
31/// fit comfortably.
32pub const MAX_PROV_VALUE: usize = 64;
33
34/// The kind of provenance a [`ProvenancePair`] carries.
35#[repr(u8)]
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum ProvenanceKey {
38    /// `0x03` track name. Value = raw name bytes (SMF text, not guaranteed UTF-8).
39    TrackName = 0,
40    /// `0x51` tempo, microseconds per quarter note. Value = 4-byte big-endian `u32`.
41    Tempo = 1,
42    /// `0x58` time signature. Value = `[numerator, denominator_pow2,
43    /// clocks_per_click, thirty_seconds_per_quarter]` (4 bytes).
44    TimeSignature = 2,
45    /// `0x59` key signature. Value = `[sharps_as_i8_bits, minor_flag]` (2 bytes).
46    KeySignature = 3,
47    /// `0x00` sequence number. Value = 2-byte big-endian `u16`.
48    SequenceNumber = 4,
49    /// `0x02` copyright notice. Value = raw text bytes.
50    Copyright = 5,
51}
52
53/// One bounded provenance pair: a typed key + inline value bytes.
54#[repr(C)]
55#[derive(Debug, Clone, Copy)]
56pub struct ProvenancePair {
57    /// Which track (index into [`SmfFile::tracks`]) the pair came from.
58    pub track: u16,
59    /// The provenance kind.
60    pub key: ProvenanceKey,
61    /// Number of valid bytes in `value`.
62    pub value_len: u8,
63    /// Inline value bytes; only `value[..value_len]` is meaningful.
64    pub value: [u8; MAX_PROV_VALUE],
65}
66
67impl ProvenancePair {
68    /// The bytes actually carried by this pair.
69    #[inline]
70    pub fn value(&self) -> &[u8] {
71        &self.value[..self.value_len as usize]
72    }
73
74    /// Construct a pair, copying up to [`MAX_PROV_VALUE`] bytes of `bytes`
75    /// (truncating any excess).
76    #[inline]
77    fn new(track: u16, key: ProvenanceKey, bytes: &[u8]) -> Self {
78        let mut value = [0u8; MAX_PROV_VALUE];
79        let len = bytes.len().min(MAX_PROV_VALUE);
80        value[..len].copy_from_slice(&bytes[..len]);
81        Self {
82            track,
83            key,
84            value_len: len as u8,
85            value,
86        }
87    }
88}
89
90/// Extract provenance pairs from every track of `smf` into `out`, in track then
91/// event order.
92///
93/// One [`ProvenancePair`] is emitted per recognised meta-event:
94/// [`MetaEvent::TrackName`], [`MetaEvent::Tempo`], [`MetaEvent::TimeSignature`],
95/// [`MetaEvent::KeySignature`], [`MetaEvent::SequenceNumber`], and the copyright
96/// notice ([`MetaEvent::Unknown`] with type [`META_COPYRIGHT`]). All other events
97/// (channel messages, SysEx, end-of-track, other Unknown metas) are skipped.
98///
99/// Returns the number of pairs written.
100///
101/// # Errors
102/// - [`AudioError::OutputBufferTooSmall`] if `out` cannot hold every pair.
103pub fn extract_smf_provenance(
104    smf: &SmfFile,
105    out: &mut [ProvenancePair],
106) -> Result<usize, AudioError> {
107    let mut count = 0usize;
108
109    for (ti, track) in smf.tracks.iter().enumerate() {
110        let track_idx = ti as u16;
111        for ev in &track.events {
112            let pair = match &ev.event {
113                TrackEvent::Meta(MetaEvent::TrackName(name)) => {
114                    ProvenancePair::new(track_idx, ProvenanceKey::TrackName, name)
115                }
116                TrackEvent::Meta(MetaEvent::Tempo(us)) => {
117                    ProvenancePair::new(track_idx, ProvenanceKey::Tempo, &us.to_be_bytes())
118                }
119                TrackEvent::Meta(MetaEvent::TimeSignature {
120                    numerator,
121                    denominator_pow2,
122                    clocks_per_click,
123                    thirty_seconds_per_quarter,
124                }) => ProvenancePair::new(
125                    track_idx,
126                    ProvenanceKey::TimeSignature,
127                    &[
128                        *numerator,
129                        *denominator_pow2,
130                        *clocks_per_click,
131                        *thirty_seconds_per_quarter,
132                    ],
133                ),
134                TrackEvent::Meta(MetaEvent::KeySignature { sharps, minor }) => ProvenancePair::new(
135                    track_idx,
136                    ProvenanceKey::KeySignature,
137                    &[*sharps as u8, u8::from(*minor)],
138                ),
139                TrackEvent::Meta(MetaEvent::SequenceNumber(n)) => {
140                    ProvenancePair::new(track_idx, ProvenanceKey::SequenceNumber, &n.to_be_bytes())
141                }
142                TrackEvent::Meta(MetaEvent::Unknown { meta_type, data })
143                    if *meta_type == META_COPYRIGHT =>
144                {
145                    ProvenancePair::new(track_idx, ProvenanceKey::Copyright, data)
146                }
147                _ => continue,
148            };
149
150            if count >= out.len() {
151                return Err(AudioError::OutputBufferTooSmall);
152            }
153            out[count] = pair;
154            count += 1;
155        }
156    }
157
158    Ok(count)
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use crate::midi::smf::read_smf;
165
166    /// Build a minimal format-0 SMF (division 96) carrying a single track whose
167    /// body is `track_body`.
168    fn smf_with_track(track_body: &[u8]) -> Vec<u8> {
169        let mut b = Vec::new();
170        b.extend_from_slice(b"MThd");
171        b.extend_from_slice(&6u32.to_be_bytes());
172        b.extend_from_slice(&0u16.to_be_bytes()); // format 0
173        b.extend_from_slice(&1u16.to_be_bytes()); // 1 track
174        b.extend_from_slice(&96u16.to_be_bytes()); // division
175        b.extend_from_slice(b"MTrk");
176        b.extend_from_slice(&(track_body.len() as u32).to_be_bytes());
177        b.extend_from_slice(track_body);
178        b
179    }
180
181    #[test]
182    fn golden_reads_track_name() {
183        // Track: delta 0, meta track-name (0xFF 0x03 len "Lead"), then end-of-track.
184        let mut body = Vec::new();
185        body.extend_from_slice(&[0x00, 0xFF, 0x03, 0x04]);
186        body.extend_from_slice(b"Lead");
187        body.extend_from_slice(&[0x00, 0xFF, 0x2F, 0x00]);
188        let bytes = smf_with_track(&body);
189        let smf = read_smf(&bytes).expect("parse smf");
190
191        let mut out = [ProvenancePair {
192            track: 0,
193            key: ProvenanceKey::TrackName,
194            value_len: 0,
195            value: [0; MAX_PROV_VALUE],
196        }; 8];
197        let n = extract_smf_provenance(&smf, &mut out).expect("extract");
198        assert_eq!(n, 1);
199        assert_eq!(out[0].key, ProvenanceKey::TrackName);
200        assert_eq!(out[0].track, 0);
201        assert_eq!(out[0].value(), b"Lead");
202    }
203
204    #[test]
205    fn extracts_tempo_time_sig_and_copyright() {
206        let mut body = Vec::new();
207        // Copyright notice (0xFF 0x02) "(c)Q".
208        body.extend_from_slice(&[0x00, 0xFF, 0x02, 0x04]);
209        body.extend_from_slice(b"(c)Q");
210        // Tempo 500000 µs/qtr = 0x07A120.
211        body.extend_from_slice(&[0x00, 0xFF, 0x51, 0x03, 0x07, 0xA1, 0x20]);
212        // Time signature 4/4, 24 clocks/click, 8 32nds/qtr.
213        body.extend_from_slice(&[0x00, 0xFF, 0x58, 0x04, 0x04, 0x02, 0x18, 0x08]);
214        // End of track.
215        body.extend_from_slice(&[0x00, 0xFF, 0x2F, 0x00]);
216        let bytes = smf_with_track(&body);
217        let smf = read_smf(&bytes).expect("parse smf");
218
219        let mut out = [ProvenancePair {
220            track: 0,
221            key: ProvenanceKey::TrackName,
222            value_len: 0,
223            value: [0; MAX_PROV_VALUE],
224        }; 8];
225        let n = extract_smf_provenance(&smf, &mut out).expect("extract");
226        assert_eq!(n, 3);
227
228        assert_eq!(out[0].key, ProvenanceKey::Copyright);
229        assert_eq!(out[0].value(), b"(c)Q");
230
231        assert_eq!(out[1].key, ProvenanceKey::Tempo);
232        assert_eq!(
233            u32::from_be_bytes(out[1].value().try_into().unwrap()),
234            500_000
235        );
236
237        assert_eq!(out[2].key, ProvenanceKey::TimeSignature);
238        assert_eq!(out[2].value(), &[4, 2, 24, 8]);
239    }
240
241    #[test]
242    fn output_too_small_reported() {
243        let mut body = Vec::new();
244        body.extend_from_slice(&[0x00, 0xFF, 0x03, 0x01, b'A']);
245        body.extend_from_slice(&[0x00, 0xFF, 0x03, 0x01, b'B']);
246        body.extend_from_slice(&[0x00, 0xFF, 0x2F, 0x00]);
247        let bytes = smf_with_track(&body);
248        let smf = read_smf(&bytes).expect("parse smf");
249
250        let mut out = [ProvenancePair {
251            track: 0,
252            key: ProvenanceKey::TrackName,
253            value_len: 0,
254            value: [0; MAX_PROV_VALUE],
255        }; 1];
256        assert_eq!(
257            extract_smf_provenance(&smf, &mut out),
258            Err(AudioError::OutputBufferTooSmall)
259        );
260    }
261}