Repository Public License
1//2// ORIX Audio3// File: Core/Sources/ORIXAudioCore/DSP/RealFFT.swift4// Description: Real-input FFT on vDSP with explicit, documented amplitude / power / PSD scaling.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Accelerate10import Foundation1112/// What a spectrum value means. These are three different quantities and are never mixed in the UI.13public enum SpectrumScaling: String, CaseIterable, Codable, Sendable, Identifiable {14 /// Peak amplitude of the sinusoid in each bin, corrected for the window's coherent gain.15 /// A sine of amplitude A reads A (20·log10 → dBFS, where a full-scale sine reads 0 dBFS).16 case amplitude17 /// Mean-square power of each bin (A²/2 for a sinusoid), coherent-gain corrected. 10·log10 → dBFS (RMS reference).18 case power19 /// Power spectral density in FS²/Hz, normalised by the window's noise power gain; integrates to the signal's mean-square power.20 case powerSpectralDensity2122 public var id: String { rawValue }23 public var displayName: String {24 switch self {25 case .amplitude: "Amplitude"26 case .power: "Power"27 case .powerSpectralDensity: "PSD"28 }29 }30 public var unit: String {31 switch self {32 case .amplitude: "dBFS"33 case .power: "dBFS (RMS)"34 case .powerSpectralDensity: "dBFS/Hz"35 }36 }37}3839/// Real FFT of a fixed power-of-two size. Not thread-safe: use one instance per thread.40public final class RealFFT {41 public let size: Int42 public let binCount: Int // size/2 + 1 (DC … Nyquist)43 public let window: WindowFunction44 private let log2n: vDSP_Length45 private let setup: FFTSetup46 private let windowCoefficients: [Float]47 private var windowed: [Float]48 private var real: [Float]49 private var imag: [Float]5051 public static let supportedSizes = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768]5253 public init(size: Int, window: WindowFunction = .hann) {54 precondition(size >= 16 && size & (size - 1) == 0, "FFT size must be a power of two")55 self.size = size56 self.binCount = size / 2 + 157 self.window = window58 self.log2n = vDSP_Length(size.trailingZeroBitCount)59 self.setup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2))!60 self.windowCoefficients = window.coefficients(count: size)61 self.windowed = [Float](repeating: 0, count: size)62 self.real = [Float](repeating: 0, count: size / 2)63 self.imag = [Float](repeating: 0, count: size / 2)64 }6566 deinit { vDSP_destroy_fftsetup(setup) }6768 /// Centre frequency of bin `k` in hertz.69 public static func frequency(ofBin k: Int, size: Int, sampleRate: Double) -> Double { Double(k) * sampleRate / Double(size) }70 public func frequency(ofBin k: Int, sampleRate: Double) -> Double { Self.frequency(ofBin: k, size: size, sampleRate: sampleRate) }71 public func binResolution(sampleRate: Double) -> Double { sampleRate / Double(size) }7273 /// Squared magnitude |X[k]|² of the mathematically-scaled DFT of the windowed frame (X[k] = Σ w[n]x[n]e^{-j2πkn/N}).74 /// `frame` must hold `size` samples; `output` must hold `binCount` values.75 public func squaredMagnitudes(_ frame: UnsafePointer<Float>, into output: UnsafeMutablePointer<Float>) {76 vDSP_vmul(frame, 1, windowCoefficients, 1, &windowed, 1, vDSP_Length(size))77 let half = size / 278 var nyquistReal: Float = 079 real.withUnsafeMutableBufferPointer { rp in80 imag.withUnsafeMutableBufferPointer { ip in81 var split = DSPSplitComplex(realp: rp.baseAddress!, imagp: ip.baseAddress!)82 windowed.withUnsafeBufferPointer { wp in83 wp.baseAddress!.withMemoryRebound(to: DSPComplex.self, capacity: half) {84 vDSP_ctoz($0, 2, &split, 1, vDSP_Length(half))85 }86 }87 vDSP_fft_zrip(setup, &split, 1, log2n, FFTDirection(FFT_FORWARD))88 // Packed format: imag[0] holds the Nyquist real part; DC and Nyquist have no imaginary part.89 nyquistReal = ip[0]90 ip[0] = 091 vDSP_zvmags(&split, 1, output, 1, vDSP_Length(half))92 }93 }94 output[half] = nyquistReal * nyquistReal95 // vDSP's real forward transform returns twice the mathematical DFT → squared magnitudes are 4× too large.96 var quarter: Float = 0.2597 vDSP_vsmul(output, 1, &quarter, output, 1, vDSP_Length(binCount))98 }99100 /// Converts |X[k]|² to the requested linear quantity, in place.101 public func scale(_ squared: UnsafeMutablePointer<Float>, to scaling: SpectrumScaling, sampleRate: Double) {102 let n = Double(size)103 let half = size / 2104 switch scaling {105 case .amplitude:106 // one-sided peak amplitude = 2|X| / (N·CG); DC and Nyquist are not doubled.107 var count = Int32(binCount)108 vvsqrtf(squared, squared, &count)109 var g = Float(2 / (n * window.coherentGain))110 vDSP_vsmul(squared, 1, &g, squared, 1, vDSP_Length(binCount))111 squared[0] *= 0.5112 squared[half] *= 0.5113 case .power:114 // mean-square power of the bin's sinusoid = (2|X|/(N·CG))² / 2115 let cg = window.coherentGain116 var g = Float(2 / (n * n * cg * cg))117 vDSP_vsmul(squared, 1, &g, squared, 1, vDSP_Length(binCount))118 squared[0] *= 0.5119 squared[half] *= 0.5120 case .powerSpectralDensity:121 // one-sided PSD = 2|X|² / (fs · Σw²), Σw² = N · noisePowerGain122 var g = Float(2 / (sampleRate * n * window.noisePowerGain))123 vDSP_vsmul(squared, 1, &g, squared, 1, vDSP_Length(binCount))124 squared[0] *= 0.5125 squared[half] *= 0.5126 }127 }128129 /// Convenience: scaled spectrum of one frame.130 public func spectrum(of frame: [Float], scaling: SpectrumScaling, sampleRate: Double) -> [Float] {131 precondition(frame.count >= size)132 var out = [Float](repeating: 0, count: binCount)133 frame.withUnsafeBufferPointer { f in134 out.withUnsafeMutableBufferPointer { o in135 squaredMagnitudes(f.baseAddress!, into: o.baseAddress!)136 scale(o.baseAddress!, to: scaling, sampleRate: sampleRate)137 }138 }139 return out140 }141}142143public enum Decibels {144 /// Floor used everywhere a logarithm of a possibly-zero value is taken.145 public static let floor: Float = -160146147 @inlinable public static func fromAmplitude(_ a: Float) -> Float { a > 1e-8 ? 20 * log10(a) : floor }148 @inlinable public static func fromPower(_ p: Float) -> Float { p > 1e-16 ? 10 * log10(p) : floor }149 @inlinable public static func toAmplitude(_ dB: Float) -> Float { pow(10, dB / 20) }150151 /// In-place conversion of a linear vector to decibels. `isPower` selects 10·log10 instead of 20·log10.152 public static func convert(_ values: inout [Float], isPower: Bool) {153 var lo: Float = isPower ? 1e-16 : 1e-8154 var hi = Float.greatestFiniteMagnitude155 vDSP_vclip(values, 1, &lo, &hi, &values, 1, vDSP_Length(values.count))156 var one: Float = 1157 vDSP_vdbcon(values, 1, &one, &values, 1, vDSP_Length(values.count), isPower ? 0 : 1)158 }159}160