// ShoeGaze+Tempo.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation // MARK: - ShoeGaze + Tempo extension ShoeGaze { /// Default tempo, in BPM, for a newly-created ``ShoeGaze/clock``. public static let defaultTempoBpm: Double = 120.0 // MARK: - Tap tempo /// Minimum plausible interval between taps, in seconds — guards against a double-tap /// or debounce glitch registering as an implausibly fast tempo (`60 / minTapInterval` /// ≈ 300 BPM cap). private static let minTapInterval: TimeInterval = 0.2 /// Maximum interval since the last tap before the tap history resets — a pause this /// long means the user is starting a new tap-tempo sequence, not continuing one. private static let tapTimeoutInterval: TimeInterval = 2.0 /// Number of most-recent inter-tap intervals averaged into the computed tempo. private static let tapHistoryCount: Int = 4 /// Registers one tap-tempo press. Call this each time the user taps (mouse click, /// screen tap, or MIDI trigger). Averages the last few inter-tap intervals and sets /// ``ShoeGaze/clock``'s `bpm` once at least two taps have landed within /// `tapTimeoutInterval` of each other. A pause longer than `tapTimeoutInterval` /// discards prior taps and starts a fresh sequence. public func tapTempo() { let now: Date = Date() if let last: Date = tapTimestamps.last, now.timeIntervalSince(last) > ShoeGaze.tapTimeoutInterval { tapTimestamps.removeAll() } tapTimestamps.append(now) if tapTimestamps.count > ShoeGaze.tapHistoryCount + 1 { tapTimestamps.removeFirst(tapTimestamps.count - (ShoeGaze.tapHistoryCount + 1)) } guard tapTimestamps.count >= 2 else { return } let intervals: [TimeInterval] = zip(tapTimestamps, tapTimestamps.dropFirst()) .map { $1.timeIntervalSince($0) } .filter { $0 >= ShoeGaze.minTapInterval } guard !intervals.isEmpty else { return } let averageInterval: TimeInterval = intervals.reduce(0, +) / Double(intervals.count) let secondsPerMinute: Double = 60.0 setBpm(secondsPerMinute / averageInterval) } }