# MIDI Clock Sync `MIDIClockFollower` estimates BPM from incoming MIDI Clock (0xF8) messages and drives a `LyrebirdClock` to follow an external transport. Ableton Link sync is not planned; MIDI Clock follow is the supported external-transport path. --- ## Overview MIDI System Real-Time sends 0xF8 bytes 24 times per quarter note. `MIDIClockFollower` maintains a rolling window of the most recent N tick arrival times (default: 24 ticks = one quarter-note), computes the average inter-tick interval, and derives a BPM estimate. When the estimate changes by more than 0.01 BPM it writes `clock.bpm` — which correctly accumulates beat-offset history inside `LyrebirdClock` so routines and tasks remain phase-continuous across tempo changes. Transport messages are handled as follows: | Message | Effect | |---------|--------| | `.start` (0xFA) | `isRunning = true`, clears tick history | | `.continue` (0xFB) | `isRunning = true`, clears tick history (beat alignment preserved) | | `.stop` (0xFC) | `isRunning = false`, clears tick history. `clock.bpm` is **not** modified. | | `.clock` (0xF8) | Updates rolling estimate, pushes to `clock.bpm` if change > epsilon | All other messages are silently ignored. --- ## Wiring `MIDIClockFollower` to `MIDI` ```swift import LyrebirdSynth let engine = SynthesisEngine( blockSize: 512, sampleRate: 44100, numOutputChannels: 2, numInputChannels: 0, driver: CoreAudioDriver() ) try engine.start() // Create a clock. Initial BPM is a placeholder; the follower will override it quickly. let clock = LyrebirdClock(engine: engine, bpm: 120.0) // Create the follower. let follower = MIDIClockFollower( engine: engine, clock: clock, smoothingWindowTicks: 24, // one quarter-note window minBPM: 40.0, maxBPM: 250.0 ) // Create the MIDI integration. let midi = MIDI(engine: engine) try midi.start() // Register a handler that passes every message to the follower. midi.addHandler(name: "clockFollow") { message, _ in follower.handle(message) } ``` After this, any sequence clock running through MIDI will continuously update `clock.bpm`. Routines and tasks that use `ctx.wait(beats:)` or `clock.nextBeat()` will automatically track the external tempo. --- ## Parameters | Parameter | Default | Meaning | |-----------|---------|---------| | `smoothingWindowTicks` | `24` | Rolling window size in ticks. 24 = one quarter-note. Smaller windows react faster but are more sensitive to jitter. | | `minBPM` | `20.0` | Minimum accepted BPM. Estimates below this are clamped. | | `maxBPM` | `999.0` | Maximum accepted BPM. Estimates above this are clamped. | --- ## Reading the estimate ```swift print(follower.estimatedBPM) // current rolling BPM estimate print(follower.isRunning) // true between .start/.continue and .stop ``` `estimatedBPM` returns `0.0` until at least 2 ticks have arrived since the last `.start`, `.continue`, `reset()`, or initialisation. --- ## Manually resetting ```swift follower.reset() // clears tick history; clock.bpm and isRunning are unchanged ``` --- ## Beat alignment limitation `LyrebirdClock` does not expose a public beat re-alignment API. When a `.start` message arrives, `MIDIClockFollower` clears its tick history but cannot reset the clock's beat phase to match the sender's Song Position Pointer. If beat-phase alignment is required, snapshot `clock.currentBeat` at the moment `.start` arrives and offset all beat calculations accordingly. --- ## Thread safety `MIDIClockFollower` is `@unchecked Sendable`. All internal state is serialised under an `NSLock`. `handle(_:)` is safe to call from any thread — in normal use it runs on the `lyrebird.midi` background queue that `MIDI` uses for handler dispatch. The write to `clock.bpm` is performed outside the follower's lock to prevent lock-ordering issues with `LyrebirdClock`'s internal lock.