SPB Git

Repository Public License

WindowFunction.swift 2.3 KB 64 lines swift

1//2//  ORIX Audio3//  File: Core/Sources/ORIXAudioCore/DSP/WindowFunction.swift4//  Description: Analysis windows with the gains needed for correct spectrum scaling.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//9import Foundation1011/// Window functions used before the FFT to control spectral leakage.12/// All windows are generated in their *periodic* (DFT-even) form, which is the correct form for spectral analysis.13public enum WindowFunction: String, CaseIterable, Codable, Sendable, Identifiable {14    case rectangular, hann, hamming, blackman, blackmanHarris, flatTop1516    public var id: String { rawValue }1718    public var displayName: String {19        switch self {20        case .rectangular: "Rectangular"21        case .hann: "Hann"22        case .hamming: "Hamming"23        case .blackman: "Blackman"24        case .blackmanHarris: "Blackman–Harris"25        case .flatTop: "Flat Top"26        }27    }2829    /// Cosine-sum coefficients a0, a1, … with w[n] = Σ (−1)^k a_k cos(2πkn/N).30    var cosineTerms: [Double] {31        switch self {32        case .rectangular: [1]33        case .hann: [0.5, 0.5]34        case .hamming: [0.54, 0.46]35        case .blackman: [0.42, 0.5, 0.08]36        case .blackmanHarris: [0.35875, 0.48829, 0.14128, 0.01168]37        case .flatTop: [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368]38        }39    }4041    public func coefficients(count n: Int) -> [Float] {42        let terms = cosineTerms43        return (0..<n).map { i in44            var w = 0.045            for (k, a) in terms.enumerated() {46                w += (k % 2 == 0 ? 1 : -1) * a * cos(2 * Double.pi * Double(k) * Double(i) / Double(n))47            }48            return Float(w)49        }50    }5152    /// Coherent gain: mean of the window. Divides amplitude readings so that a sinusoid reads its true amplitude.53    public var coherentGain: Double { cosineTerms[0] }5455    /// Mean of the squared window (noise power gain). Used for power-spectral-density normalisation.56    public var noisePowerGain: Double {57        let t = cosineTerms58        return t[0] * t[0] + t.dropFirst().reduce(0) { $0 + $1 * $1 / 2 }59    }6061    /// Equivalent noise bandwidth, in FFT bins.62    public var equivalentNoiseBandwidthBins: Double { noisePowerGain / (coherentGain * coherentGain) }63}64
Files main
Menu

Theme