180 lines
7.3 KiB
Swift
180 lines
7.3 KiB
Swift
// CepstralEnvelopeEstimator.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import Accelerate
|
||
|
||
/// Real cepstrum-based spectral envelope estimator.
|
||
///
|
||
/// Given a magnitude spectrum of length `halfSize + 1` (DC, complex bins
|
||
/// `1 ..< halfSize`, Nyquist), produces a smooth envelope of the same length
|
||
/// by lifting in the quefrency domain. Used by `SpectralFormantShift.cepstral`
|
||
/// to separate a smooth formant-tracking envelope from the harmonic fine
|
||
/// structure.
|
||
///
|
||
/// ## Algorithm
|
||
///
|
||
/// 1. `_logMag[k] = log(max(mag[k], ε))` for `k = 0 … halfSize`.
|
||
/// 2. Pack `_logMag` into half-complex form (DC at `realp[0]`, Nyquist at
|
||
/// `imagp[0]`, all other `imagp[k] = 0`) and run an inverse real FFT to
|
||
/// obtain the real cepstrum of length `fftSize`.
|
||
/// 3. Lifter: zero cepstrum samples whose index `n` lies in
|
||
/// `[cutoffQuefrency, fftSize − cutoffQuefrency]`. The low-quefrency
|
||
/// region either side of `n = 0` is the smooth log-envelope.
|
||
/// 4. Forward real FFT of the liftered cepstrum yields the smoothed
|
||
/// log-envelope in `realp`. `vvexpf` returns it to linear magnitudes.
|
||
///
|
||
/// vDSP's real FFT scales the forward by 2 and the inverse by `fftSize`; the
|
||
/// 2·N round-trip is divided out before exponentiation.
|
||
///
|
||
/// ## RT safety
|
||
///
|
||
/// All scratch buffers and the `FFTSetup` are allocated once in `init`.
|
||
/// `estimate(magnitudes:into:)` performs no allocation and no locking; it is
|
||
/// safe to call from the RT thread.
|
||
internal final class CepstralEnvelopeEstimator {
|
||
|
||
private let fftSize: Int
|
||
private let halfSize: Int
|
||
private let cutoffQuefrency: Int
|
||
private let log2n: vDSP_Length
|
||
private let fftSetup: FFTSetup
|
||
|
||
/// log(magnitudes) — length `halfSize + 1`.
|
||
private let _logMag: UnsafeMutablePointer<Float>
|
||
|
||
/// Split-complex scratch (DC at `_realp[0]`, Nyquist at `_imagp[0]`,
|
||
/// complex bins `1 ..< halfSize` in `_realp[k]` / `_imagp[k]`).
|
||
/// Length `halfSize` each.
|
||
private let _realp: UnsafeMutablePointer<Float>
|
||
private let _imagp: UnsafeMutablePointer<Float>
|
||
|
||
/// Real cepstrum scratch — length `fftSize`.
|
||
private let _cepstrum: UnsafeMutablePointer<Float>
|
||
|
||
/// Smallest magnitude allowed before taking the log. Picked an order of
|
||
/// magnitude below typical float underflow so `log(ε)` stays finite but
|
||
/// far below any meaningful spectrum amplitude.
|
||
private static let magnitudeFloor: Float = 1e-12
|
||
|
||
/// Create an estimator for an FFT of size `fftSize` that keeps the lowest
|
||
/// `cutoffQuefrency` quefrencies (and their mirror counterparts) of the
|
||
/// real cepstrum.
|
||
///
|
||
/// - Parameters:
|
||
/// - fftSize: Spectrum size used to compute magnitudes. Must be a power
|
||
/// of two ≥ 4.
|
||
/// - cutoffQuefrency: Number of low-quefrency bins kept. Clamped to
|
||
/// `[1, halfSize]`. Smaller = smoother envelope (fewer formant peaks
|
||
/// resolved); larger = closer to the original magnitude spectrum.
|
||
init(
|
||
fftSize: Int,
|
||
cutoffQuefrency: Int
|
||
) {
|
||
precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0,
|
||
"CepstralEnvelopeEstimator: fftSize must be a power of two >= 4, got \(fftSize)")
|
||
self.fftSize = fftSize
|
||
self.halfSize = fftSize / 2
|
||
self.cutoffQuefrency = Swift.max(1, Swift.min(self.halfSize, cutoffQuefrency))
|
||
self.log2n = vDSP_Length(fftSize.trailingZeroBitCount)
|
||
|
||
guard let setup: FFTSetup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2)) else {
|
||
fatalError("CepstralEnvelopeEstimator: failed to create FFT setup for fftSize \(fftSize)")
|
||
}
|
||
self.fftSetup = setup
|
||
|
||
_logMag = UnsafeMutablePointer<Float>.allocate(capacity: halfSize + 1)
|
||
_realp = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||
_imagp = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||
_cepstrum = UnsafeMutablePointer<Float>.allocate(capacity: fftSize)
|
||
|
||
_logMag.initialize(repeating: 0, count: halfSize + 1)
|
||
_realp.initialize(repeating: 0, count: halfSize)
|
||
_imagp.initialize(repeating: 0, count: halfSize)
|
||
_cepstrum.initialize(repeating: 0, count: fftSize)
|
||
}
|
||
|
||
deinit {
|
||
_logMag.deinitialize(count: halfSize + 1)
|
||
_logMag.deallocate()
|
||
_realp.deinitialize(count: halfSize)
|
||
_realp.deallocate()
|
||
_imagp.deinitialize(count: halfSize)
|
||
_imagp.deallocate()
|
||
_cepstrum.deinitialize(count: fftSize)
|
||
_cepstrum.deallocate()
|
||
vDSP_destroy_fftsetup(fftSetup)
|
||
}
|
||
|
||
/// Compute the smoothed envelope of `magnitudes` and write it to
|
||
/// `envelope`. Both buffers have length `halfSize + 1` (index 0 = DC,
|
||
/// index `halfSize` = Nyquist). Magnitudes must be non-negative.
|
||
///
|
||
/// Safe to call on the RT thread.
|
||
func estimate(
|
||
magnitudes: UnsafePointer<Float>,
|
||
into envelope: UnsafeMutablePointer<Float>
|
||
) {
|
||
let n: Int = halfSize + 1
|
||
var floor: Float = CepstralEnvelopeEstimator.magnitudeFloor
|
||
|
||
// _logMag = log(max(magnitudes, floor))
|
||
vDSP_vthr(magnitudes, 1, &floor, _logMag, 1, vDSP_Length(n))
|
||
var nLog: Int32 = Int32(n)
|
||
vvlogf(_logMag, _logMag, &nLog)
|
||
|
||
// Pack log-magnitudes into half-complex form for inverse real FFT.
|
||
// realp[0] = log|X[0]| (DC)
|
||
// imagp[0] = log|X[N/2]| (Nyquist, packed into imagp[0] in vDSP layout)
|
||
// realp[k] = log|X[k]| (1..halfSize-1)
|
||
// imagp[k] = 0
|
||
_realp[0] = _logMag[0]
|
||
_imagp[0] = _logMag[halfSize]
|
||
for k: Int in 1..<halfSize {
|
||
_realp[k] = _logMag[k]
|
||
_imagp[k] = 0
|
||
}
|
||
|
||
var split: DSPSplitComplex = DSPSplitComplex(realp: _realp, imagp: _imagp)
|
||
|
||
// Inverse real FFT → split-complex packed time-domain of length fftSize.
|
||
vDSP_fft_zrip(fftSetup, &split, 1, log2n, FFTDirection(kFFTDirection_Inverse))
|
||
|
||
// Unpack to contiguous real cepstrum.
|
||
_cepstrum.withMemoryRebound(to: DSPComplex.self, capacity: halfSize) { complexPtr in
|
||
vDSP_ztoc(&split, 1, complexPtr, 2, vDSP_Length(halfSize))
|
||
}
|
||
|
||
// Lifter: keep low quefrencies on both ends of the cyclic cepstrum.
|
||
// Zero indices [cutoffQuefrency, fftSize − cutoffQuefrency].
|
||
let cutoff: Int = cutoffQuefrency
|
||
if cutoff < fftSize - cutoff {
|
||
for i: Int in cutoff...(fftSize - cutoff) {
|
||
_cepstrum[i] = 0
|
||
}
|
||
}
|
||
|
||
// Repack liftered cepstrum into split-complex for forward FFT.
|
||
_cepstrum.withMemoryRebound(to: DSPComplex.self, capacity: halfSize) { complexPtr in
|
||
vDSP_ctoz(complexPtr, 2, &split, 1, vDSP_Length(halfSize))
|
||
}
|
||
|
||
// Forward real FFT → half-complex log-envelope.
|
||
vDSP_fft_zrip(fftSetup, &split, 1, log2n, FFTDirection(kFFTDirection_Forward))
|
||
|
||
// Read log-envelope, divide out the 2·N vDSP round-trip scaling.
|
||
let invScale: Float = Float(1.0 / Double(2 * fftSize))
|
||
envelope[0] = _realp[0] * invScale
|
||
envelope[halfSize] = _imagp[0] * invScale
|
||
for k: Int in 1..<halfSize {
|
||
envelope[k] = _realp[k] * invScale
|
||
}
|
||
|
||
// Exp back to linear magnitude domain.
|
||
var nExp: Int32 = Int32(n)
|
||
vvexpf(envelope, envelope, &nExp)
|
||
}
|
||
}
|