1use std::{collections::BTreeMap, fmt, path::Path};
2
3use serde::{Deserialize, Serialize};
4use thiserror::Error;
5
6use crate::contract::{
7 ClockAuthority, ClockCapability, ClockField, ClockState, ClockTimeSignature,
8 MidiClockDiagnostic, MidiClockDiagnosticSeverity, MidiClockMessage, MidiClockMessageKind,
9 MidiClockSnapshot, apply_midi_clock_message, midi_clock_snapshot_to_clock_state,
10 parse_midi_clock_message,
11};
12
13pub const RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA: &str = "skenion.clock.midi.fixture";
14pub const RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION: &str = "0.1.0";
15
16#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
17#[serde(transparent)]
18pub struct RuntimeMidiClockSourceId(pub String);
19
20impl RuntimeMidiClockSourceId {
21 pub fn new(value: impl Into<String>) -> Self {
22 Self(value.into())
23 }
24
25 pub fn as_str(&self) -> &str {
26 &self.0
27 }
28}
29
30impl fmt::Display for RuntimeMidiClockSourceId {
31 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
32 formatter.write_str(self.as_str())
33 }
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
37#[serde(rename_all = "kebab-case")]
38pub enum RuntimeMidiClockSourceKind {
39 MidiClock,
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
43#[serde(rename_all = "kebab-case")]
44pub enum MidiSongPositionSource {
45 Spp,
46 StartReset,
47 TickAccumulated,
48 Unknown,
49}
50
51impl MidiSongPositionSource {
52 fn label(self) -> &'static str {
53 match self {
54 Self::Spp => "runtime.midi-clock.spp",
55 Self::StartReset => "runtime.midi-clock.start-reset",
56 Self::TickAccumulated => "runtime.midi-clock.tick-accumulated",
57 Self::Unknown => "runtime.midi-clock.unknown",
58 }
59 }
60
61 fn song_position_authority(self) -> ClockAuthority {
62 match self {
63 Self::Spp => ClockAuthority::Authoritative,
64 Self::StartReset | Self::TickAccumulated => ClockAuthority::Derived,
65 Self::Unknown => ClockAuthority::Unavailable,
66 }
67 }
68}
69
70#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
71#[serde(rename_all = "lowercase")]
72pub enum RuntimeClockDiagnosticSeverity {
73 Warning,
74 Error,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
78#[serde(rename_all = "camelCase")]
79pub struct RuntimeClockDiagnostic {
80 pub severity: RuntimeClockDiagnosticSeverity,
81 pub code: String,
82 pub message: String,
83}
84
85#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
86#[serde(rename_all = "camelCase")]
87pub struct RuntimeMidiClockStateSnapshot {
88 pub source_id: RuntimeMidiClockSourceId,
89 pub source_kind: RuntimeMidiClockSourceKind,
90 pub clock_state: ClockState,
91 #[serde(skip_serializing_if = "Option::is_none")]
92 pub received_host_time_ns: Option<u64>,
93 pub song_position_source: MidiSongPositionSource,
94 pub diagnostics: Vec<RuntimeClockDiagnostic>,
95}
96
97#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
98#[serde(rename_all = "camelCase")]
99pub struct RuntimeMidiClockTimeline {
100 snapshots: BTreeMap<RuntimeMidiClockSourceId, RuntimeMidiClockStateSnapshot>,
101}
102
103impl RuntimeMidiClockTimeline {
104 pub fn new() -> Self {
105 Self::default()
106 }
107
108 pub fn record(&mut self, snapshot: RuntimeMidiClockStateSnapshot) {
109 self.snapshots.insert(snapshot.source_id.clone(), snapshot);
110 }
111
112 pub fn get(
113 &self,
114 source_id: &RuntimeMidiClockSourceId,
115 ) -> Option<&RuntimeMidiClockStateSnapshot> {
116 self.snapshots.get(source_id)
117 }
118
119 pub fn list(&self) -> Vec<&RuntimeMidiClockStateSnapshot> {
120 self.snapshots.values().collect()
121 }
122
123 pub fn is_empty(&self) -> bool {
124 self.snapshots.is_empty()
125 }
126
127 pub fn len(&self) -> usize {
128 self.snapshots.len()
129 }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
133#[serde(rename_all = "camelCase")]
134pub struct TimestampedMidiMessage {
135 pub bytes: Vec<u8>,
136 pub received_host_time_ns: u64,
137}
138
139#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
140#[serde(rename_all = "camelCase")]
141pub struct RuntimeMidiClockFixture {
142 pub schema: String,
143 pub schema_version: String,
144 pub source_id: String,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub time_signature: Option<ClockTimeSignature>,
147 pub events: Vec<RuntimeMidiClockFixtureEvent>,
148}
149
150#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
151#[serde(rename_all = "camelCase")]
152pub struct RuntimeMidiClockFixtureEvent {
153 pub at_ns: u64,
154 pub bytes: Vec<u8>,
155}
156
157#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
158#[serde(rename_all = "camelCase")]
159pub struct RuntimeMidiClockFixtureReport {
160 pub schema: String,
161 pub schema_version: String,
162 pub source_id: RuntimeMidiClockSourceId,
163 pub event_count: usize,
164 pub timeline: RuntimeMidiClockTimeline,
165 pub latest_snapshot: RuntimeMidiClockStateSnapshot,
166 pub diagnostics: Vec<RuntimeClockDiagnostic>,
167}
168
169#[derive(Debug, Error)]
170pub enum MidiClockFixtureError {
171 #[error("failed to read MIDI Clock fixture {path}: {source}")]
172 Read {
173 path: String,
174 #[source]
175 source: std::io::Error,
176 },
177 #[error("failed to parse MIDI Clock fixture {path}: {source}")]
178 Parse {
179 path: String,
180 #[source]
181 source: serde_json::Error,
182 },
183 #[error("invalid MIDI Clock fixture {path}: {message}")]
184 Invalid { path: String, message: String },
185}
186
187pub struct MidiClockAdapter {
188 source_id: RuntimeMidiClockSourceId,
189 snapshot: MidiClockSnapshot,
190 song_position_source: MidiSongPositionSource,
191 last_received_host_time_ns: Option<u64>,
192}
193
194impl MidiClockAdapter {
195 pub fn new(source_id: impl Into<String>, time_signature: Option<ClockTimeSignature>) -> Self {
196 let source_id = RuntimeMidiClockSourceId::new(source_id);
197 let mut snapshot = MidiClockSnapshot::new(source_id.as_str());
198 snapshot.time_signature = time_signature;
199 Self {
200 source_id,
201 snapshot,
202 song_position_source: MidiSongPositionSource::Unknown,
203 last_received_host_time_ns: None,
204 }
205 }
206
207 pub fn current_snapshot(&self) -> RuntimeMidiClockStateSnapshot {
208 self.runtime_snapshot(Vec::new(), self.last_received_host_time_ns)
209 }
210
211 pub fn apply_timestamped_message(
212 &mut self,
213 timestamped: TimestampedMidiMessage,
214 ) -> RuntimeMidiClockStateSnapshot {
215 let received_host_time_ns = timestamped.received_host_time_ns;
216 self.last_received_host_time_ns = Some(received_host_time_ns);
217
218 let Some(mut message) = parse_runtime_midi_clock_message(×tamped.bytes) else {
219 let diagnostic = invalid_or_unsupported_message_diagnostic(×tamped.bytes);
220 return self.runtime_snapshot(vec![diagnostic], Some(received_host_time_ns));
221 };
222 message.received_host_time_ns = Some(received_host_time_ns);
223
224 let message_kind = message.kind;
225 let result = apply_midi_clock_message(&self.snapshot, &message);
226 self.snapshot = result.snapshot;
227 let diagnostics: Vec<RuntimeClockDiagnostic> = result
228 .diagnostics
229 .into_iter()
230 .map(runtime_clock_diagnostic_from_midi)
231 .collect();
232
233 if !diagnostics
234 .iter()
235 .any(|diagnostic| diagnostic.severity == RuntimeClockDiagnosticSeverity::Error)
236 {
237 self.update_song_position_source(message_kind);
238 }
239
240 self.runtime_snapshot(diagnostics, Some(received_host_time_ns))
241 }
242
243 fn update_song_position_source(&mut self, message_kind: MidiClockMessageKind) {
244 self.song_position_source = match message_kind {
245 MidiClockMessageKind::Start => MidiSongPositionSource::StartReset,
246 MidiClockMessageKind::SongPositionPointer => MidiSongPositionSource::Spp,
247 MidiClockMessageKind::Tick => match self.song_position_source {
248 MidiSongPositionSource::Unknown => MidiSongPositionSource::Unknown,
249 MidiSongPositionSource::Spp
250 | MidiSongPositionSource::StartReset
251 | MidiSongPositionSource::TickAccumulated => {
252 MidiSongPositionSource::TickAccumulated
253 }
254 },
255 MidiClockMessageKind::Continue | MidiClockMessageKind::Stop => {
256 self.song_position_source
257 }
258 };
259 }
260
261 fn runtime_snapshot(
262 &self,
263 diagnostics: Vec<RuntimeClockDiagnostic>,
264 received_host_time_ns: Option<u64>,
265 ) -> RuntimeMidiClockStateSnapshot {
266 RuntimeMidiClockStateSnapshot {
267 source_id: self.source_id.clone(),
268 source_kind: RuntimeMidiClockSourceKind::MidiClock,
269 clock_state: self.corrected_clock_state(),
270 received_host_time_ns,
271 song_position_source: self.song_position_source,
272 diagnostics,
273 }
274 }
275
276 fn corrected_clock_state(&self) -> ClockState {
277 let mut state = midi_clock_snapshot_to_clock_state(&self.snapshot);
278 let source = self.song_position_source.label();
279 let authority = self.song_position_source.song_position_authority();
280 let song_position_value = match authority {
281 ClockAuthority::Unavailable => None,
282 _ => Some(self.snapshot.song_position_sixteenth),
283 };
284
285 if authority == ClockAuthority::Unavailable {
286 state.song_position_sixteenth =
287 Some(clock_field(song_position_value, authority, source));
288 state
289 .capabilities
290 .retain(|capability| capability != &ClockCapability::SongPosition);
291 set_bar_beat_unavailable(&mut state, source);
292 } else {
293 state.song_position_sixteenth =
294 Some(clock_field(song_position_value, authority.clone(), source));
295 set_bar_beat_authority(&mut state, ClockAuthority::Derived, source);
296 }
297 state
298 }
299}
300
301pub fn run_midi_clock_fixture_file(
302 path: impl AsRef<Path>,
303) -> Result<RuntimeMidiClockFixtureReport, MidiClockFixtureError> {
304 let path = path.as_ref();
305 let path_label = path.display().to_string();
306 let bytes = std::fs::read(path).map_err(|source| MidiClockFixtureError::Read {
307 path: path_label.clone(),
308 source,
309 })?;
310 let fixture: RuntimeMidiClockFixture =
311 serde_json::from_slice(&bytes).map_err(|source| MidiClockFixtureError::Parse {
312 path: path_label.clone(),
313 source,
314 })?;
315 run_midi_clock_fixture(fixture, path_label)
316}
317
318pub fn run_midi_clock_fixture(
319 fixture: RuntimeMidiClockFixture,
320 path_label: impl Into<String>,
321) -> Result<RuntimeMidiClockFixtureReport, MidiClockFixtureError> {
322 let path = path_label.into();
323 validate_midi_clock_fixture(&fixture, &path)?;
324
325 let mut adapter = MidiClockAdapter::new(fixture.source_id.clone(), fixture.time_signature);
326 let mut timeline = RuntimeMidiClockTimeline::new();
327 let mut diagnostics = Vec::new();
328 let mut latest_snapshot = adapter.current_snapshot();
329
330 for event in &fixture.events {
331 latest_snapshot = adapter.apply_timestamped_message(TimestampedMidiMessage {
332 bytes: event.bytes.clone(),
333 received_host_time_ns: event.at_ns,
334 });
335 diagnostics.extend(latest_snapshot.diagnostics.clone());
336 timeline.record(latest_snapshot.clone());
337 }
338
339 if timeline.is_empty() {
340 timeline.record(latest_snapshot.clone());
341 }
342
343 Ok(RuntimeMidiClockFixtureReport {
344 schema: "skenion.runtime.clock-midi.report".to_owned(),
345 schema_version: "0.1.0".to_owned(),
346 source_id: RuntimeMidiClockSourceId::new(fixture.source_id),
347 event_count: fixture.events.len(),
348 timeline,
349 latest_snapshot,
350 diagnostics,
351 })
352}
353
354pub fn format_midi_clock_fixture_report_text(report: &RuntimeMidiClockFixtureReport) -> String {
355 let snapshot = &report.latest_snapshot;
356 let state = &snapshot.clock_state;
357 let mut lines = vec![
358 format!("runtime midi clock: {}", snapshot.source_id),
359 format!("events: {}", report.event_count),
360 format!("sourceKind: {:?}", snapshot.source_kind),
361 format!("songPositionSource: {:?}", snapshot.song_position_source),
362 ];
363 push_field(&mut lines, "running", state.running.as_ref());
364 push_field(
365 &mut lines,
366 "songPositionSixteenth",
367 state.song_position_sixteenth.as_ref(),
368 );
369 push_field(&mut lines, "bar", state.bar.as_ref());
370 push_field(&mut lines, "beat", state.beat.as_ref());
371 push_field(&mut lines, "tempoBpm", state.tempo_bpm.as_ref());
372 lines.push(format!("diagnostics: {}", report.diagnostics.len()));
373 for diagnostic in &report.diagnostics {
374 lines.push(format!(
375 "diagnostic: {:?} {} {}",
376 diagnostic.severity, diagnostic.code, diagnostic.message
377 ));
378 }
379 lines.join("\n") + "\n"
380}
381
382fn validate_midi_clock_fixture(
383 fixture: &RuntimeMidiClockFixture,
384 path: &str,
385) -> Result<(), MidiClockFixtureError> {
386 if fixture.schema != RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA {
387 return Err(MidiClockFixtureError::Invalid {
388 path: path.to_owned(),
389 message: format!(
390 "expected schema {RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA}, got {}",
391 fixture.schema
392 ),
393 });
394 }
395 if fixture.schema_version != RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION {
396 return Err(MidiClockFixtureError::Invalid {
397 path: path.to_owned(),
398 message: format!(
399 "expected schemaVersion {RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION}, got {}",
400 fixture.schema_version
401 ),
402 });
403 }
404 if fixture.source_id.trim().is_empty() {
405 return Err(MidiClockFixtureError::Invalid {
406 path: path.to_owned(),
407 message: "sourceId must be a non-empty string".to_owned(),
408 });
409 }
410 for (index, event) in fixture.events.iter().enumerate() {
411 if event.bytes.is_empty() {
412 return Err(MidiClockFixtureError::Invalid {
413 path: path.to_owned(),
414 message: format!("events[{index}].bytes must be non-empty"),
415 });
416 }
417 }
418 Ok(())
419}
420
421fn parse_runtime_midi_clock_message(bytes: &[u8]) -> Option<MidiClockMessage> {
422 parse_midi_clock_message(bytes).or_else(|| {
423 (bytes.first() == Some(&0xf2)).then_some(MidiClockMessage {
424 kind: MidiClockMessageKind::SongPositionPointer,
425 song_position_sixteenth: None,
426 received_host_time_ns: None,
427 })
428 })
429}
430
431fn invalid_or_unsupported_message_diagnostic(_bytes: &[u8]) -> RuntimeClockDiagnostic {
432 RuntimeClockDiagnostic {
433 severity: RuntimeClockDiagnosticSeverity::Error,
434 code: "unsupported-midi-clock-message".to_owned(),
435 message: "MIDI Clock adapter supports tick/start/continue/stop/SPP messages only"
436 .to_owned(),
437 }
438}
439
440fn clock_field<T>(value: Option<T>, authority: ClockAuthority, source: &str) -> ClockField<T> {
441 ClockField {
442 value,
443 authority,
444 source: source.to_owned(),
445 confidence: None,
446 }
447}
448
449fn unavailable_field<T>(source: &str) -> ClockField<T> {
450 clock_field(None, ClockAuthority::Unavailable, source)
451}
452
453fn set_bar_beat_unavailable(state: &mut ClockState, source: &str) {
454 state.bar = Some(unavailable_field(source));
455 state.beat = Some(unavailable_field(source));
456 state.division = Some(unavailable_field(source));
457 state.tick_in_division = Some(unavailable_field(source));
458 state
459 .capabilities
460 .retain(|capability| capability != &ClockCapability::BarBeat);
461}
462
463fn set_bar_beat_authority(state: &mut ClockState, authority: ClockAuthority, source: &str) {
464 set_field_authority(&mut state.bar, authority.clone(), source);
465 set_field_authority(&mut state.beat, authority.clone(), source);
466 set_field_authority(&mut state.division, authority.clone(), source);
467 set_field_authority(&mut state.tick_in_division, authority, source);
468}
469
470fn set_field_authority<T>(
471 field: &mut Option<ClockField<T>>,
472 authority: ClockAuthority,
473 source: &str,
474) {
475 if let Some(field) = field.as_mut()
476 && field.value.is_some()
477 {
478 field.authority = authority;
479 field.source = source.to_owned();
480 }
481}
482
483fn push_field<T: fmt::Display>(
484 lines: &mut Vec<String>,
485 label: &str,
486 field: Option<&ClockField<T>>,
487) {
488 let Some(field) = field else {
489 lines.push(format!("{label}: <missing>"));
490 return;
491 };
492 let value = field
493 .value
494 .as_ref()
495 .map(ToString::to_string)
496 .unwrap_or_else(|| "unavailable".to_owned());
497 lines.push(format!(
498 "{label}: {value} authority={:?} source={}",
499 field.authority, field.source
500 ));
501}
502
503fn runtime_clock_diagnostic_from_midi(diagnostic: MidiClockDiagnostic) -> RuntimeClockDiagnostic {
504 RuntimeClockDiagnostic {
505 severity: match diagnostic.severity {
506 MidiClockDiagnosticSeverity::Warning => RuntimeClockDiagnosticSeverity::Warning,
507 MidiClockDiagnosticSeverity::Error => RuntimeClockDiagnosticSeverity::Error,
508 },
509 code: diagnostic.code,
510 message: diagnostic.message,
511 }
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517
518 #[test]
519 fn simulated_start_ticks_and_stop_update_timeline_snapshot() {
520 let fixture = RuntimeMidiClockFixture {
521 schema: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA.to_owned(),
522 schema_version: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION.to_owned(),
523 source_id: "midi-clock-start-stop".to_owned(),
524 time_signature: Some(ClockTimeSignature {
525 numerator: 4,
526 denominator: 4,
527 }),
528 events: vec![
529 event(0, &[0xfa]),
530 event(1_000_000, &[0xf8]),
531 event(2_000_000, &[0xfc]),
532 ],
533 };
534
535 let report = run_midi_clock_fixture(fixture, "inline").unwrap();
536 let snapshot = &report.latest_snapshot;
537
538 assert_eq!(report.event_count, 3);
539 assert_eq!(report.timeline.len(), 1);
540 assert!(snapshot.clock_state.running.as_ref().unwrap().value == Some(false));
541 assert_eq!(
542 snapshot.song_position_source,
543 MidiSongPositionSource::TickAccumulated
544 );
545 assert_eq!(
546 snapshot
547 .clock_state
548 .song_position_sixteenth
549 .as_ref()
550 .unwrap()
551 .authority,
552 ClockAuthority::Derived
553 );
554 assert!(report.diagnostics.is_empty());
555 }
556
557 #[test]
558 fn spp_position_is_authoritative_and_meter_derives_bar_beat() {
559 let mut adapter = MidiClockAdapter::new(
560 "midi-clock-spp",
561 Some(ClockTimeSignature {
562 numerator: 4,
563 denominator: 4,
564 }),
565 );
566
567 let snapshot = adapter.apply_timestamped_message(TimestampedMidiMessage {
568 bytes: vec![0xf2, 16, 0],
569 received_host_time_ns: 10,
570 });
571
572 assert_eq!(snapshot.song_position_source, MidiSongPositionSource::Spp);
573 assert_eq!(
574 snapshot
575 .clock_state
576 .song_position_sixteenth
577 .as_ref()
578 .unwrap()
579 .authority,
580 ClockAuthority::Authoritative
581 );
582 assert_eq!(snapshot.clock_state.bar.as_ref().unwrap().value, Some(2));
583 assert_eq!(
584 snapshot.clock_state.bar.as_ref().unwrap().authority,
585 ClockAuthority::Derived
586 );
587 assert_eq!(snapshot.clock_state.beat.as_ref().unwrap().value, Some(1));
588 }
589
590 #[test]
591 fn continue_without_position_anchor_leaves_song_position_unavailable() {
592 let mut adapter = MidiClockAdapter::new("midi-clock-continue", None);
593
594 adapter.apply_timestamped_message(TimestampedMidiMessage {
595 bytes: vec![0xfb],
596 received_host_time_ns: 10,
597 });
598 let snapshot = adapter.apply_timestamped_message(TimestampedMidiMessage {
599 bytes: vec![0xf8],
600 received_host_time_ns: 20,
601 });
602
603 let field = snapshot
604 .clock_state
605 .song_position_sixteenth
606 .as_ref()
607 .unwrap();
608 assert_eq!(
609 snapshot.song_position_source,
610 MidiSongPositionSource::Unknown
611 );
612 assert_eq!(field.value, None);
613 assert_eq!(field.authority, ClockAuthority::Unavailable);
614 assert!(
615 !snapshot
616 .clock_state
617 .capabilities
618 .contains(&ClockCapability::SongPosition)
619 );
620 }
621
622 #[test]
623 fn meterless_spp_leaves_bar_and_beat_unavailable() {
624 let mut adapter = MidiClockAdapter::new("midi-clock-meterless", None);
625
626 let snapshot = adapter.apply_timestamped_message(TimestampedMidiMessage {
627 bytes: vec![0xf2, 16, 0],
628 received_host_time_ns: 10,
629 });
630
631 assert_eq!(
632 snapshot.clock_state.bar.as_ref().unwrap().authority,
633 ClockAuthority::Unavailable
634 );
635 assert_eq!(snapshot.clock_state.bar.as_ref().unwrap().value, None);
636 assert_eq!(
637 snapshot.clock_state.beat.as_ref().unwrap().authority,
638 ClockAuthority::Unavailable
639 );
640 }
641
642 #[test]
643 fn invalid_spp_bytes_produce_diagnostic_without_state_change() {
644 let mut adapter = MidiClockAdapter::new("midi-clock-invalid", None);
645
646 let snapshot = adapter.apply_timestamped_message(TimestampedMidiMessage {
647 bytes: vec![0xf2, 0x80, 0],
648 received_host_time_ns: 10,
649 });
650
651 assert_eq!(snapshot.diagnostics.len(), 1);
652 assert_eq!(
653 snapshot.diagnostics[0].code,
654 "invalid-midi-song-position-pointer"
655 );
656 assert_eq!(
657 snapshot.song_position_source,
658 MidiSongPositionSource::Unknown
659 );
660 }
661
662 #[test]
663 fn start_reset_position_is_derived_until_ticks_accumulate() {
664 let mut adapter = MidiClockAdapter::new("midi-clock-start", None);
665
666 let snapshot = adapter.apply_timestamped_message(TimestampedMidiMessage {
667 bytes: vec![0xfa],
668 received_host_time_ns: 5,
669 });
670
671 assert_eq!(
672 snapshot.song_position_source,
673 MidiSongPositionSource::StartReset
674 );
675 let field = snapshot
676 .clock_state
677 .song_position_sixteenth
678 .as_ref()
679 .unwrap();
680 assert_eq!(field.value, Some(0));
681 assert_eq!(field.authority, ClockAuthority::Derived);
682 assert_eq!(field.source, "runtime.midi-clock.start-reset");
683 }
684
685 #[test]
686 fn midi_clock_timeline_gets_and_lists_snapshots() {
687 let adapter = MidiClockAdapter::new("midi-clock-timeline", None);
688 let snapshot = adapter.current_snapshot();
689 let source_id = snapshot.source_id.clone();
690 let mut timeline = RuntimeMidiClockTimeline::new();
691
692 assert!(timeline.is_empty());
693 timeline.record(snapshot);
694
695 assert_eq!(source_id.as_str(), "midi-clock-timeline");
696 assert_eq!(source_id.to_string(), "midi-clock-timeline");
697 assert_eq!(timeline.len(), 1);
698 assert_eq!(timeline.get(&source_id).unwrap().source_id, source_id);
699 assert_eq!(timeline.list().len(), 1);
700 }
701
702 #[test]
703 fn fixture_file_runs_and_text_report_formats_fields() {
704 let path = temp_fixture_path("valid-empty");
705 std::fs::write(
706 &path,
707 r#"{
708 "schema": "skenion.clock.midi.fixture",
709 "schemaVersion": "0.1.0",
710 "sourceId": "midi-clock-empty",
711 "events": []
712 }"#,
713 )
714 .unwrap();
715
716 let report = run_midi_clock_fixture_file(&path).unwrap();
717 let text = format_midi_clock_fixture_report_text(&report);
718 std::fs::remove_file(path).unwrap();
719
720 assert_eq!(report.event_count, 0);
721 assert_eq!(report.timeline.len(), 1);
722 assert!(text.contains("runtime midi clock: midi-clock-empty"));
723 assert!(text.contains("songPositionSource: Unknown"));
724 assert!(text.contains("tempoBpm: unavailable authority=Unavailable"));
725
726 let inline_empty = run_midi_clock_fixture(
727 RuntimeMidiClockFixture {
728 schema: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA.to_owned(),
729 schema_version: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION.to_owned(),
730 source_id: "midi-clock-inline-empty".to_owned(),
731 time_signature: None,
732 events: vec![],
733 },
734 "inline-empty",
735 )
736 .unwrap();
737 assert_eq!(inline_empty.timeline.len(), 1);
738
739 let string_label_report = run_midi_clock_fixture(
740 RuntimeMidiClockFixture {
741 schema: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA.to_owned(),
742 schema_version: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION.to_owned(),
743 source_id: "midi-clock-string-label".to_owned(),
744 time_signature: None,
745 events: vec![event(0, &[0xfa])],
746 },
747 "inline-string-label".to_owned(),
748 )
749 .unwrap();
750 assert_eq!(string_label_report.event_count, 1);
751 }
752
753 #[test]
754 fn fixture_file_reports_read_parse_and_validation_errors() {
755 let missing = temp_fixture_path("missing");
756 let read_error = run_midi_clock_fixture_file(&missing).unwrap_err();
757 assert!(read_error.to_string().contains("failed to read"));
758
759 let parse_path = temp_fixture_path("parse");
760 std::fs::write(&parse_path, "{").unwrap();
761 let parse_error = run_midi_clock_fixture_file(&parse_path).unwrap_err();
762 std::fs::remove_file(parse_path).unwrap();
763 assert!(parse_error.to_string().contains("failed to parse"));
764
765 let invalid_cases = [
766 (
767 RuntimeMidiClockFixture {
768 schema: "wrong".to_owned(),
769 schema_version: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION.to_owned(),
770 source_id: "source".to_owned(),
771 time_signature: None,
772 events: vec![],
773 },
774 "expected schema",
775 ),
776 (
777 RuntimeMidiClockFixture {
778 schema: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA.to_owned(),
779 schema_version: "9.9.9".to_owned(),
780 source_id: "source".to_owned(),
781 time_signature: None,
782 events: vec![],
783 },
784 "expected schemaVersion",
785 ),
786 (
787 RuntimeMidiClockFixture {
788 schema: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA.to_owned(),
789 schema_version: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION.to_owned(),
790 source_id: " ".to_owned(),
791 time_signature: None,
792 events: vec![],
793 },
794 "sourceId must be",
795 ),
796 (
797 RuntimeMidiClockFixture {
798 schema: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA.to_owned(),
799 schema_version: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION.to_owned(),
800 source_id: "source".to_owned(),
801 time_signature: None,
802 events: vec![event(0, &[])],
803 },
804 "bytes must be",
805 ),
806 ];
807
808 for (fixture, expected) in invalid_cases {
809 let error = run_midi_clock_fixture(fixture, "inline").unwrap_err();
810 assert!(error.to_string().contains(expected));
811 }
812 }
813
814 #[test]
815 fn unsupported_messages_and_tick_overflow_report_diagnostics() {
816 let mut adapter = MidiClockAdapter::new("midi-clock-diagnostics", None);
817
818 let unsupported = adapter.apply_timestamped_message(TimestampedMidiMessage {
819 bytes: vec![0x90, 60, 127],
820 received_host_time_ns: 1,
821 });
822 assert_eq!(unsupported.diagnostics.len(), 1);
823 assert_eq!(
824 unsupported.diagnostics[0].code,
825 "unsupported-midi-clock-message"
826 );
827
828 let invalid_spp = adapter.apply_timestamped_message(TimestampedMidiMessage {
829 bytes: vec![0xf2],
830 received_host_time_ns: 2,
831 });
832 assert_eq!(
833 invalid_spp.diagnostics[0].code,
834 "invalid-midi-song-position-pointer"
835 );
836
837 adapter.snapshot.tick_index = u64::MAX;
838 adapter.song_position_source = MidiSongPositionSource::StartReset;
839 let overflow = adapter.apply_timestamped_message(TimestampedMidiMessage {
840 bytes: vec![0xf8],
841 received_host_time_ns: 3,
842 });
843 assert!(
844 overflow
845 .diagnostics
846 .iter()
847 .any(|diagnostic| diagnostic.code == "midi-clock-tick-overflow"
848 && diagnostic.severity == RuntimeClockDiagnosticSeverity::Warning)
849 );
850 assert_eq!(
851 overflow.song_position_source,
852 MidiSongPositionSource::TickAccumulated
853 );
854 }
855
856 #[test]
857 fn invalid_fixture_text_report_formats_diagnostics_and_error_severity() {
858 let report = run_midi_clock_fixture(
859 RuntimeMidiClockFixture {
860 schema: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA.to_owned(),
861 schema_version: RUNTIME_MIDI_CLOCK_FIXTURE_SCHEMA_VERSION.to_owned(),
862 source_id: "midi-clock-invalid-spp".to_owned(),
863 time_signature: None,
864 events: vec![event(0, &[0xf2])],
865 },
866 "inline",
867 )
868 .unwrap();
869 let text = format_midi_clock_fixture_report_text(&report);
870
871 assert!(text.contains("diagnostics: 1"));
872 assert!(text.contains("diagnostic:"));
873 assert!(text.contains("invalid-midi-song-position-pointer"));
874
875 let diagnostic = runtime_clock_diagnostic_from_midi(MidiClockDiagnostic {
876 severity: MidiClockDiagnosticSeverity::Error,
877 code: "runtime-midi-clock-error".to_owned(),
878 message: "runtime MIDI Clock error".to_owned(),
879 });
880 assert_eq!(diagnostic.severity, RuntimeClockDiagnosticSeverity::Error);
881 }
882
883 #[test]
884 fn private_format_helpers_cover_missing_and_none_fields() {
885 let mut lines = Vec::new();
886 push_field::<bool>(&mut lines, "missingBool", None);
887 push_field::<f64>(&mut lines, "missingFloat", None);
888 push_field::<u64>(&mut lines, "missing", None);
889 assert_eq!(lines[0], "missingBool: <missing>");
890 assert_eq!(lines[1], "missingFloat: <missing>");
891 assert_eq!(lines[2], "missing: <missing>");
892
893 let bool_field = clock_field::<bool>(None, ClockAuthority::Unavailable, "bool-source");
894 push_field(&mut lines, "unavailableBool", Some(&bool_field));
895 assert_eq!(
896 lines[3],
897 "unavailableBool: unavailable authority=Unavailable source=bool-source"
898 );
899
900 let mut field = Some(clock_field(
901 Some(1_u64),
902 ClockAuthority::Authoritative,
903 "before",
904 ));
905 set_field_authority(&mut field, ClockAuthority::Derived, "after");
906 let field = field.unwrap();
907 assert_eq!(field.authority, ClockAuthority::Derived);
908 assert_eq!(field.source, "after");
909
910 let mut unavailable: Option<ClockField<u64>> = None;
911 set_field_authority(&mut unavailable, ClockAuthority::Derived, "after");
912 assert!(unavailable.is_none());
913 }
914
915 fn event(at_ns: u64, bytes: &[u8]) -> RuntimeMidiClockFixtureEvent {
916 RuntimeMidiClockFixtureEvent {
917 at_ns,
918 bytes: bytes.to_vec(),
919 }
920 }
921
922 fn temp_fixture_path(label: &str) -> std::path::PathBuf {
923 let nonce = std::time::SystemTime::now()
924 .duration_since(std::time::UNIX_EPOCH)
925 .unwrap()
926 .as_nanos();
927 std::env::temp_dir().join(format!("skenion-runtime-midi-clock-{label}-{nonce}.json"))
928 }
929}