57 lines
2.1 KiB
Swift
57 lines
2.1 KiB
Swift
// SwapQuantize.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// LyrebirdLiveCompile
|
|
//
|
|
// `SwapQuantize` chooses when a named-slot swap becomes audible: immediately, or
|
|
// aligned to the next beat / bar of a `LyrebirdClock`. Quantizing the swap to a
|
|
// musical boundary is what masks compile latency — the `swiftc` build finishes a
|
|
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
|
|
// than whenever the compile happened to finish.
|
|
|
|
#if os(macOS)
|
|
import Foundation
|
|
import LyrebirdSynth
|
|
|
|
/// When a ``LiveSession`` named-slot swap becomes audible.
|
|
///
|
|
/// Set on ``LiveSession/swapQuantize`` together with a ``LiveSession/swapClock``.
|
|
/// With no clock, or `.immediate`, a swap takes effect right away. `.nextBeat` /
|
|
/// `.nextBar` schedule the new voice's add and the old voice's removal at the
|
|
/// same upcoming boundary sample time, so the swap is glitch-free and on-grid.
|
|
public enum SwapQuantize: Sendable, Equatable {
|
|
|
|
/// Swap immediately, as soon as the snippet runs.
|
|
case immediate
|
|
|
|
/// Swap on the next whole beat boundary.
|
|
case nextBeat
|
|
|
|
/// Swap on the next bar boundary, where a bar is `beatsPerBar` beats.
|
|
case nextBar(beatsPerBar: Int)
|
|
|
|
/// The absolute clock beat this quantization targets from *now*, or `nil`
|
|
/// for `.immediate`. `.nextBeat` returns the next whole beat; `.nextBar`
|
|
/// returns the next multiple of `beatsPerBar` beats.
|
|
///
|
|
/// Reads `clock.currentBeat` once; the returned beat is strictly in the
|
|
/// future for a running clock (a whole-numbered current beat rounds up to
|
|
/// the following boundary, matching `LyrebirdClock.nextBeat`).
|
|
public func targetBeat(clock: LyrebirdClock) -> Double? {
|
|
switch self {
|
|
case .immediate:
|
|
return nil
|
|
case .nextBeat:
|
|
return floor(clock.currentBeat) + 1.0
|
|
case .nextBar(let beatsPerBar):
|
|
let bar: Double = Double(max(1, beatsPerBar))
|
|
return (floor(clock.currentBeat / bar) + 1.0) * bar
|
|
}
|
|
}
|
|
}
|
|
|
|
#endif
|