Repository Public
1// ORIX DJ2// File: Packages/ORIXDJCore/Sources/ORIXAnalysis/Key.swift3// Description: Musical key model (names, Camelot wheel, compatibility) and chromagram-based key estimation.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Accelerate89public enum KeyMode: String, Codable, Sendable { case major, minor }1011public struct KeyEstimate: Codable, Sendable, Equatable {12 /// 0 = C ... 11 = B13 public var tonic: Int14 public var mode: KeyMode15 /// 0...116 public var confidence: Double1718 public init(tonic: Int, mode: KeyMode, confidence: Double = 1) {19 self.tonic = ((tonic % 12) + 12) % 1220 self.mode = mode21 self.confidence = confidence22 }2324 private static let majorNames = ["C", "D♭", "D", "E♭", "E", "F", "F♯", "G", "A♭", "A", "B♭", "B"]25 private static let minorNames = ["C", "C♯", "D", "E♭", "E", "F", "F♯", "G", "G♯", "A", "B♭", "B"]2627 private var tonicName: String {28 let t = ((tonic % 12) + 12) % 1229 return mode == .major ? Self.majorNames[t] : Self.minorNames[t]30 }3132 /// "A minor", "F♯ major"33 public var name: String { "\(tonicName) \(mode.rawValue)" }34 /// "Am", "F♯"35 public var shortName: String { mode == .major ? tonicName : tonicName + "m" }3637 /// Position 1...12 on the Camelot wheel.38 public var camelotNumber: Int {39 let t = ((tonic % 12) + 12) % 1240 let majorTonic = mode == .major ? t : (t + 3) % 1241 return (majorTonic * 7 + 7) % 12 + 142 }4344 /// "8A" (wheel notation: A = minor, B = major)45 public var camelot: String { "\(camelotNumber)\(mode == .minor ? "A" : "B")" }4647 /// Same key, ±1 on the wheel (same letter), or relative major/minor.48 public func isCompatible(with other: KeyEstimate) -> Bool {49 let a = camelotNumber, b = other.camelotNumber50 if a == b { return true }51 guard mode == other.mode else { return false }52 let d = ((a - b) % 12 + 12) % 1253 return d == 1 || d == 1154 }5556 public func transposed(semitones: Int) -> KeyEstimate {57 KeyEstimate(tonic: ((tonic + semitones) % 12 + 12) % 12, mode: mode, confidence: confidence)58 }59}6061enum KeyEstimator {62 // Krumhansl & Kessler (1982) probe-tone profiles.63 static let majorProfile: [Double] = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88]64 static let minorProfile: [Double] = [6.33, 2.68, 3.52, 5.38, 2.60, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17]65 /// Relative strength of successive overtones folded into the templates (a spectrum-derived chroma contains them).66 static let harmonicDecay = 0.456768 /// Probe-tone profile with the contribution of the first six partials of every note folded in.69 static func harmonicTemplate(_ profile: [Double]) -> [Double] {70 let s = harmonicDecay71 var out = [Double](repeating: 0, count: 12)72 // partial h (1...6) lands on pitch class +0, +0, +7, +0, +4, +773 let partials: [(Int, Double)] = [(0, 1), (0, s), (7, s * s), (0, s * s * s), (4, pow(s, 4)), (7, pow(s, 5))]74 for note in 0..<12 {75 for (interval, weight) in partials { out[(note + interval) % 12] += profile[note] * weight }76 }77 return out78 }7980 struct Chroma {81 var bins: [Double] // 12 pitch classes, C first82 var tuningCents: Double83 }8485 /// Global chromagram from spectral peaks between ~55 Hz and 2 kHz, with tuning estimation at 10-cent resolution.86 static func chroma(mono: UnsafeBufferPointer<Float>, sampleRate: Double, check: () throws -> Void) throws -> Chroma? {87 let n = mono.count88 guard n > 0, let base = mono.baseAddress else { return nil }8990 // 1. Decimate to roughly 5.5 kHz (the analysis band stops at 2 kHz).91 let factor = max(1, Int(sampleRate / 5000))92 let fs = sampleRate / Double(factor)93 var decimated: [Float]94 if factor > 1 {95 let taps = 12 * factor + 196 guard n >= taps + factor else { return nil }97 var filter = [Float](repeating: 0, count: taps)98 let cutoff = 0.45 / Double(factor) // cycles per input sample99 let mid = Double(taps - 1) / 2100 var sum = 0.0101 for i in 0..<taps {102 let x = Double(i) - mid103 let sinc = x == 0 ? 2 * cutoff : sin(2 * Double.pi * cutoff * x) / (Double.pi * x)104 let w = 0.54 - 0.46 * cos(2 * Double.pi * Double(i) / Double(taps - 1))105 filter[i] = Float(sinc * w)106 sum += sinc * w107 }108 for i in 0..<taps { filter[i] /= Float(sum) }109 let outCount = (n - taps) / factor + 1110 decimated = [Float](repeating: 0, count: outCount)111 vDSP_desamp(base, vDSP_Stride(factor), filter, &decimated, vDSP_Length(outCount), vDSP_Length(taps))112 } else {113 decimated = Array(mono)114 }115 try check()116117 // 2. STFT with ~0.74 s windows, peak picking, accumulation in a 120-bin (10 cents) pitch-class histogram.118 let size = max(256, 1 << Int(log2(0.74 * fs).rounded()))119 let half = size / 2120 let hop = size / 4121 guard decimated.count >= size / 4 else { return nil }122 let frames = max(1, (decimated.count - size) / hop + 1)123 let binHz = fs / Double(size)124 let kLow = max(2, Int((55 / binHz).rounded(.up)))125 let kHigh = min(half - 2, Int(2000 / binHz))126 guard kHigh > kLow + 2 else { return nil }127128 let fft = RealFFT(size: size)129 var window = [Float](repeating: 0, count: size)130 vDSP_hann_window(&window, vDSP_Length(size), Int32(vDSP_HANN_DENORM))131 var buffer = [Float](repeating: 0, count: size)132 var mags = [Float](repeating: 0, count: half)133 var logMags = [Float](repeating: 0, count: half)134 var histogram = [Double](repeating: 0, count: 120)135136 for frame in 0..<frames {137 if frame & 63 == 0 { try check() }138 let start = frame * hop139 let available = min(size, decimated.count - start)140 decimated.withUnsafeBufferPointer { d in141 buffer.withUnsafeMutableBufferPointer { b in142 if available < size { vDSP_vclr(b.baseAddress!, 1, vDSP_Length(size)) }143 vDSP_vmul(d.baseAddress! + start, 1, window, 1, b.baseAddress!, 1, vDSP_Length(available))144 }145 }146 fft.magnitudes(buffer, into: &mags)147 var frameMax: Float = 0148 mags.withUnsafeBufferPointer { m in149 vDSP_maxv(m.baseAddress! + kLow, 1, &frameMax, vDSP_Length(kHigh - kLow + 1))150 }151 guard frameMax > 1e-6 else { continue }152 let threshold = frameMax * 0.03153 var count = Int32(half)154 var floorValue: Float = 1e-12155 vDSP_vthr(mags, 1, &floorValue, &logMags, 1, vDSP_Length(half))156 vvlogf(&logMags, logMags, &count)157 for k in kLow...kHigh {158 let m = mags[k]159 if m > threshold && m > mags[k - 1] && m >= mags[k + 1] {160 let p = parabolicOffset(Double(logMags[k - 1]), Double(logMags[k]), Double(logMags[k + 1]))161 let frequency = (Double(k) + p) * binHz162 let pitch = 69 + 12 * log2(frequency / 440)163 let bin = ((Int((pitch * 10).rounded()) % 120) + 120) % 120164 histogram[bin] += Double(m).squareRoot()165 }166 }167 }168 let total = histogram.reduce(0, +)169 guard total > 0 else { return nil }170171 // 3. Tuning: offset (in 10-cent steps) of the 12-tooth comb that captures the most energy.172 var bestOffset = 0173 var bestScore = -1.0174 for offset in 0..<10 {175 var s = 0.0176 for pc in 0..<12 {177 let c = pc * 10 + offset178 s += histogram[c % 120] + 0.5 * (histogram[(c + 1) % 120] + histogram[(c + 119) % 120])179 }180 if s > bestScore { bestScore = s; bestOffset = offset }181 }182 let offset = bestOffset < 5 ? bestOffset : bestOffset - 10183 var bins = [Double](repeating: 0, count: 12)184 for pc in 0..<12 {185 for d in -4...4 {186 let w = cos(Double.pi * Double(d) / 10)187 bins[pc] += histogram[((pc * 10 + offset + d) % 120 + 120) % 120] * w * w188 }189 }190 return Chroma(bins: bins, tuningCents: Double(offset) * 10)191 }192193 static func correlation(_ a: [Double], _ b: [Double], shift: Int) -> Double {194 let ma = a.reduce(0, +) / 12, mb = b.reduce(0, +) / 12195 var num = 0.0, da = 0.0, db = 0.0196 for i in 0..<12 {197 let x = a[(i + shift) % 12] - ma198 let y = b[i] - mb199 num += x * y; da += x * x; db += y * y200 }201 let den = (da * db).squareRoot()202 return den > 0 ? num / den : 0203 }204205 static func estimate(mono: UnsafeBufferPointer<Float>, sampleRate: Double, check: () throws -> Void) throws -> KeyEstimate? {206 guard let chroma = try chroma(mono: mono, sampleRate: sampleRate, check: check) else { return nil }207 return estimate(chroma: chroma.bins)208 }209210 static func estimate(chroma: [Double]) -> KeyEstimate? {211 let major = harmonicTemplate(majorProfile), minor = harmonicTemplate(minorProfile)212 var scores: [(Double, Int, KeyMode)] = []213 for tonic in 0..<12 {214 scores.append((correlation(chroma, major, shift: tonic), tonic, .major))215 scores.append((correlation(chroma, minor, shift: tonic), tonic, .minor))216 }217 scores.sort { $0.0 > $1.0 }218 let best = scores[0], second = scores[1]219 guard best.0 > 0 else { return nil }220 let margin = max(0, best.0 - second.0)221 let confidence = min(1, margin / 0.15) * min(1, max(0, best.0)).squareRoot()222 return KeyEstimate(tonic: best.1, mode: best.2, confidence: confidence)223 }224}225