Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXAnalysis/BeatGrid.swift3// Description: Constant-tempo beat grid model (BPM, phase anchor, downbeat) with beat/time conversions.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public struct BeatGrid: Codable, Sendable, Equatable {10 public var bpm: Double11 /// Time of a beat (phase anchor), 0 <= value < one beat.12 public var firstBeatSeconds: Double13 /// Which beat (0...3) after `firstBeatSeconds` is a bar start.14 public var downbeatIndex: Int1516 public init(bpm: Double, firstBeatSeconds: Double, downbeatIndex: Int = 0) {17 self.bpm = bpm18 self.firstBeatSeconds = firstBeatSeconds19 self.downbeatIndex = downbeatIndex20 }2122 /// Length of one beat in seconds (0 when the tempo is not positive).23 public var beatDuration: Double { bpm > 0 ? 60 / bpm : 0 }2425 /// Fractional beat index at `seconds` (beat 0 is `firstBeatSeconds`).26 public func beat(at seconds: Double) -> Double {27 guard bpm > 0 else { return 0 }28 return (seconds - firstBeatSeconds) * bpm / 6029 }3031 public func seconds(atBeat beat: Double) -> Double {32 guard bpm > 0 else { return firstBeatSeconds }33 return firstBeatSeconds + beat * 60 / bpm34 }3536 public func nearestBeatSeconds(to seconds: Double) -> Double {37 self.seconds(atBeat: beat(at: seconds).rounded())38 }3940 /// Time of the bar start at or before `seconds`.41 public func barStartSeconds(atOrBefore seconds: Double) -> Double {42 let b = beat(at: seconds) - Double(downbeatIndex)43 return self.seconds(atBeat: (b / 4).rounded(.down) * 4 + Double(downbeatIndex))44 }45}46