Repository Public License
1//2// ORIX Audio3// File: Core/Sources/ORIXAudioCore/DSP/SpectrumAnalyzer.swift4// Description: Streaming magnitude spectrum with smoothing, peak hold, band energy and dominant-frequency estimation.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Accelerate10import Foundation1112public struct SpectrumConfiguration: Codable, Sendable, Hashable {13 public var fftSize: Int = 409614 public var window: WindowFunction = .hann15 public var scaling: SpectrumScaling = .amplitude16 /// Exponential time-averaging factor in [0, 1): 0 = no smoothing, 0.9 = heavy smoothing. Averaging is done on power.17 public var smoothing: Float = 0.618 /// Peak-hold decay in dB per second (0 = infinite hold).19 public var peakDecayDBPerSecond: Float = 1220 public init() {}21}2223/// One analysed frame. Values are in decibels of the quantity named by `scaling`.24public struct SpectrumFrame: Sendable {25 public var sampleRate: Double26 public var fftSize: Int27 public var scaling: SpectrumScaling28 public var decibels: [Float]29 public var peakHold: [Float]30 /// Interpolated frequency of the strongest bin above 20 Hz, or nil when the frame is effectively silent.31 public var dominantFrequency: Double?32 public var dominantLevel: Float33 /// Mean-square power per ORIX band (linear, FS²).34 public var bandPower: [Float]3536 public var binCount: Int { decibels.count }37 public func frequency(ofBin k: Int) -> Double { Double(k) * sampleRate / Double(fftSize) }38 public func bin(forFrequency f: Double) -> Int { min(binCount - 1, max(0, Int((f * Double(fftSize) / sampleRate).rounded()))) }39}4041public struct SpectralPeak: Codable, Sendable, Hashable {42 public var frequency: Double43 public var decibels: Float44}4546/// Streaming analyser. Feed it mono frames of exactly `fftSize` samples (the caller owns overlap). One thread only.47public final class SpectrumAnalyzer {48 public private(set) var configuration: SpectrumConfiguration49 public let sampleRate: Double50 public let bands: FrequencyBandLayout51 private var fft: RealFFT52 private var bandRanges: [Range<Int>]53 private var averagedPower: [Float]54 private var peak: [Float]55 private var scratch: [Float]56 private var hasHistory = false5758 public init(sampleRate: Double, configuration: SpectrumConfiguration = .init(), bands: FrequencyBandLayout = .orix) {59 self.sampleRate = sampleRate60 self.configuration = configuration61 self.bands = bands62 self.fft = RealFFT(size: configuration.fftSize, window: configuration.window)63 self.bandRanges = bands.binRanges(fftSize: configuration.fftSize, sampleRate: sampleRate)64 self.averagedPower = [Float](repeating: 0, count: fft.binCount)65 self.peak = [Float](repeating: Decibels.floor, count: fft.binCount)66 self.scratch = [Float](repeating: 0, count: fft.binCount)67 }6869 public func update(_ new: SpectrumConfiguration) {70 let rebuild = new.fftSize != configuration.fftSize || new.window != configuration.window71 let rescale = new.scaling != configuration.scaling72 configuration = new73 if rebuild {74 fft = RealFFT(size: new.fftSize, window: new.window)75 bandRanges = bands.binRanges(fftSize: new.fftSize, sampleRate: sampleRate)76 averagedPower = [Float](repeating: 0, count: fft.binCount)77 scratch = [Float](repeating: 0, count: fft.binCount)78 }79 if rebuild || rescale { resetPeakHold(); hasHistory = false }80 }8182 public func resetPeakHold() { peak = [Float](repeating: Decibels.floor, count: fft.binCount) }8384 /// Analyses one frame. `elapsed` is the time since the previous frame, used for peak-hold decay.85 public func process(_ frame: UnsafePointer<Float>, elapsed: Double) -> SpectrumFrame {86 let n = fft.binCount87 scratch.withUnsafeMutableBufferPointer { fft.squaredMagnitudes(frame, into: $0.baseAddress!) }8889 // Time-average on |X|² (power domain), which is the statistically meaningful average.90 let a = hasHistory ? min(0.98, max(0, configuration.smoothing)) : 091 var keep = a, take = 1 - a92 vDSP_vsmsma(averagedPower, 1, &keep, scratch, 1, &take, &averagedPower, 1, vDSP_Length(n))93 hasHistory = true9495 // Band power always comes from the mean-square ("power") scaling, independent of the display scaling.96 var power = averagedPower97 power.withUnsafeMutableBufferPointer { fft.scale($0.baseAddress!, to: .power, sampleRate: sampleRate) }98 var bandPower = [Float](repeating: 0, count: bandRanges.count)99 // Summing coherent-gain-corrected bins over-counts by the window's ENBW; divide to get true band power.100 let enbw = Float(fft.window.equivalentNoiseBandwidthBins)101 power.withUnsafeBufferPointer { p in102 bandPower.withUnsafeMutableBufferPointer { bands.energies(powerSpectrum: p.baseAddress!, ranges: bandRanges, into: $0.baseAddress!) }103 }104 for i in bandPower.indices { bandPower[i] /= enbw }105106 var display = averagedPower107 display.withUnsafeMutableBufferPointer { fft.scale($0.baseAddress!, to: configuration.scaling, sampleRate: sampleRate) }108 Decibels.convert(&display, isPower: configuration.scaling != .amplitude)109110 let decay = configuration.peakDecayDBPerSecond * Float(elapsed)111 for k in 0..<n { peak[k] = max(display[k], configuration.peakDecayDBPerSecond > 0 ? peak[k] - decay : peak[k]) }112113 let dominant = Self.dominant(inPowerDB: power, fftSize: fft.size, sampleRate: sampleRate)114 return SpectrumFrame(sampleRate: sampleRate, fftSize: fft.size, scaling: configuration.scaling, decibels: display,115 peakHold: peak, dominantFrequency: dominant?.frequency, dominantLevel: dominant?.decibels ?? Decibels.floor,116 bandPower: bandPower)117 }118119 /// Strongest bin above 20 Hz with parabolic interpolation on the log magnitude (accurate to a small fraction of a bin for120 /// stationary tones with Hann-family windows). Returns nil below −90 dBFS.121 static func dominant(inPowerDB linearPower: [Float], fftSize: Int, sampleRate: Double) -> SpectralPeak? {122 let lo = max(1, Int((20 * Double(fftSize) / sampleRate).rounded(.up)))123 guard linearPower.count > lo + 2 else { return nil }124 var best = lo, bestValue: Float = 0125 for k in lo..<(linearPower.count - 1) where linearPower[k] > bestValue { bestValue = linearPower[k]; best = k }126 let dB = Decibels.fromPower(bestValue)127 guard dB > -90 else { return nil }128 let a = Decibels.fromPower(linearPower[best - 1]), b = dB, c = Decibels.fromPower(linearPower[best + 1])129 let denom = a - 2 * b + c130 let offset = denom == 0 ? 0 : 0.5 * (a - c) / denom131 let freq = (Double(best) + Double(max(-0.5, min(0.5, offset)))) * sampleRate / Double(fftSize)132 // +3.01 dB: mean-square power → peak amplitude dBFS of the sinusoid.133 return SpectralPeak(frequency: freq, decibels: b - 0.25 * (a - c) * offset + 3.0103)134 }135136 /// Local maxima of a dB spectrum, strongest first, at least `minimumSeparationBins` apart and above `thresholdDB`.137 public static func peaks(in decibels: [Float], fftSize: Int, sampleRate: Double, count: Int = 8,138 thresholdDB: Float = -80, minimumSeparationBins: Int = 3) -> [SpectralPeak] {139 guard decibels.count > 3 else { return [] }140 var candidates: [(Int, Float)] = []141 for k in 1..<(decibels.count - 1) where decibels[k] > thresholdDB && decibels[k] >= decibels[k - 1] && decibels[k] > decibels[k + 1] {142 candidates.append((k, decibels[k]))143 }144 candidates.sort { $0.1 > $1.1 }145 var chosen: [(Int, Float)] = []146 for c in candidates {147 if chosen.count >= count { break }148 if chosen.allSatisfy({ abs($0.0 - c.0) >= minimumSeparationBins }) { chosen.append(c) }149 }150 return chosen.map { k, v in151 let a = decibels[k - 1], c = decibels[k + 1]152 let denom = a - 2 * v + c153 let off = denom == 0 ? 0 : max(-0.5, min(0.5, 0.5 * (a - c) / denom))154 return SpectralPeak(frequency: (Double(k) + Double(off)) * sampleRate / Double(fftSize), decibels: v - 0.25 * (a - c) * off)155 }156 }157}158159/// Maps a linear-frequency dB spectrum onto display columns, linear or logarithmic in frequency.160public enum FrequencyAxis: String, CaseIterable, Codable, Sendable, Identifiable {161 case linear, logarithmic162 public var id: String { rawValue }163164 /// Normalised position in [0, 1] of frequency `f` between `fMin` and `fMax`.165 public func position(of f: Double, min fMin: Double, max fMax: Double) -> Double {166 switch self {167 case .linear: return (f - fMin) / (fMax - fMin)168 case .logarithmic:169 let lo = Swift.max(fMin, 1)170 return log(Swift.max(f, lo) / lo) / log(fMax / lo)171 }172 }173174 public func frequency(at position: Double, min fMin: Double, max fMax: Double) -> Double {175 switch self {176 case .linear: return fMin + position * (fMax - fMin)177 case .logarithmic:178 let lo = Swift.max(fMin, 1)179 return lo * pow(fMax / lo, position)180 }181 }182183 /// Resamples `decibels` (bins 0…N/2) to `columns` display points. Each column takes the maximum of the bins it covers184 /// (so narrow peaks are never lost), or interpolates linearly when a column is narrower than one bin.185 public func resample(_ decibels: [Float], fftSize: Int, sampleRate: Double, columns: Int, min fMin: Double, max fMax: Double) -> [Float] {186 guard columns > 0, decibels.count > 1 else { return [] }187 var out = [Float](repeating: Decibels.floor, count: columns)188 let binHz = sampleRate / Double(fftSize)189 let last = Double(decibels.count - 1)190 for c in 0..<columns {191 let f0 = frequency(at: Double(c) / Double(columns), min: fMin, max: fMax)192 let f1 = frequency(at: Double(c + 1) / Double(columns), min: fMin, max: fMax)193 let b0 = Swift.min(last, Swift.max(0, f0 / binHz)), b1 = Swift.min(last, Swift.max(0, f1 / binHz))194 if b1 - b0 < 1 {195 let mid = (b0 + b1) / 2196 let i = Int(mid), frac = Float(mid - Double(i))197 let j = Swift.min(decibels.count - 1, i + 1)198 out[c] = decibels[i] * (1 - frac) + decibels[j] * frac199 } else {200 var m = Decibels.floor201 for k in Int(b0.rounded(.up))...Int(b1) { m = Swift.max(m, decibels[k]) }202 out[c] = m203 }204 }205 return out206 }207}208