1.0.0 release
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// SpectralBinFromHz.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Convert a frequency in Hz to its nearest FFT bin index, clamped to `[0, halfSize]`.
|
||||
///
|
||||
/// `halfSize = fftSize / 2` (Nyquist bin). Negative or NaN `hz` clamps to `0`;
|
||||
/// values above Nyquist clamp to `halfSize`. Rounds to the nearest integer bin.
|
||||
///
|
||||
/// Allocation-free; safe to call on the RT thread.
|
||||
@inline(__always)
|
||||
internal func binFromHz(
|
||||
_ hz: Float,
|
||||
fftSize: Int,
|
||||
sampleRate: Double
|
||||
) -> Int {
|
||||
let halfSize: Int = fftSize / 2
|
||||
if !hz.isFinite || hz <= 0 { return 0 }
|
||||
let binFloat: Double = Double(hz) * Double(fftSize) / sampleRate
|
||||
if binFloat <= 0 { return 0 }
|
||||
if binFloat >= Double(halfSize) { return halfSize }
|
||||
return Int(binFloat.rounded())
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
// SpectralBuffer.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Synchronization
|
||||
|
||||
/// A pre-allocated buffer for one FFT frame in polar (magnitude + phase) format.
|
||||
///
|
||||
/// `SpectralChain.Audio` writes to this buffer after each forward FFT hop by
|
||||
/// converting the raw split-complex output to polar form once, and reads from it
|
||||
/// in the inverse path by converting back to split-complex immediately before
|
||||
/// each IFFT. Spectral processors registered on `SpectralChain.Audio` receive a
|
||||
/// reference to this buffer after each hop and may read or modify magnitudes and
|
||||
/// phases in-place.
|
||||
///
|
||||
/// ## Layout
|
||||
///
|
||||
/// For a real FFT of size N, `binCount = N/2 + 1` unique frequency bins exist:
|
||||
///
|
||||
/// | Bin | Property | Notes |
|
||||
/// |-----|----------|-------|
|
||||
/// | 0 | `dcValue` | Signed DC — may be negative |
|
||||
/// | 1 … N/2−1 | `[magnitude: k]`, `[phase: k]` | Complex bins |
|
||||
/// | N/2 | `nyquistValue` | Signed Nyquist — may be negative |
|
||||
///
|
||||
/// DC and Nyquist are purely real in vDSP's half-complex layout and have no
|
||||
/// meaningful spectral phase; they are stored as signed scalars.
|
||||
///
|
||||
/// ## Storage
|
||||
///
|
||||
/// All storage uses `UnsafeMutablePointer<Float>` allocations, eliminating Swift
|
||||
/// Array copy-on-write on the RT audio thread. Pointer addresses are stable for
|
||||
/// the lifetime of this object.
|
||||
///
|
||||
/// ## Thread safety
|
||||
///
|
||||
/// `isValid` uses `Atomic<Bool>` with acquiring/releasing semantics. The raw
|
||||
/// storage (`_mag`, `_phase`, `_dcValue`, `_nyquistValue`) is written on the RT
|
||||
/// thread by `SpectralChain.Audio._computeSamples` (forward path) and read on
|
||||
/// the RT thread by `SpectralChain.Audio._computeSamples` (inverse path). Public
|
||||
/// accessors (`magnitude(at:)`,
|
||||
/// `phase(at:)`, `setMagnitude(_:at:)`, subscripts) must be called from the RT
|
||||
/// thread only, or when no RT processing is active.
|
||||
// @unchecked Sendable invariant: structural fields (`fftSize`, `_mag`, `_phase`,
|
||||
// `_dcValue`, `_nyquistValue`, buffer pointers) are immutable post-init. Bin
|
||||
// values are mutated only on the RT thread by `SpectralChain.Audio._computeSamples`
|
||||
// (forward + inverse passes) and read only on the RT thread by the inverse
|
||||
// pass — never cross-thread. Public accessors are RT-thread-only (or quiesced).
|
||||
public final class SpectralBuffer: @unchecked Sendable {
|
||||
|
||||
// MARK: - Immutable properties
|
||||
|
||||
/// Number of samples per FFT frame. Power of two.
|
||||
public let fftSize: Int
|
||||
|
||||
/// Number of unique frequency bins: `fftSize / 2 + 1` (includes DC and Nyquist).
|
||||
public let binCount: Int
|
||||
|
||||
// MARK: - Private storage
|
||||
|
||||
/// Signed DC component (vDSP's realp[0]).
|
||||
private var _dcValue: Float = 0
|
||||
|
||||
/// Signed Nyquist component (vDSP's imagp[0]).
|
||||
private var _nyquistValue: Float = 0
|
||||
|
||||
/// Magnitudes for complex bins 1..halfSize-1. Allocated at halfSize; index 0 unused.
|
||||
private let _mag: UnsafeMutablePointer<Float>
|
||||
|
||||
/// Phases (radians) for complex bins 1..halfSize-1. Allocated at halfSize; index 0 unused.
|
||||
private let _phase: UnsafeMutablePointer<Float>
|
||||
|
||||
private let _halfSize: Int
|
||||
private let _binCount: Int // halfSize - 1 (complex bins 1..halfSize-1)
|
||||
|
||||
// MARK: - Validity flag
|
||||
|
||||
private let _isValid: Atomic<Bool>
|
||||
|
||||
/// Whether this buffer is valid. Set to `false` via `invalidate()` from a non-RT thread
|
||||
/// to stop generator processing.
|
||||
public var isValid: Bool { _isValid.load(ordering: .acquiring) }
|
||||
|
||||
// MARK: - Initialisation
|
||||
|
||||
/// Create a spectral buffer for an FFT of size `fftSize`.
|
||||
///
|
||||
/// - Parameter fftSize: Must be a power of two ≥ 4 (e.g. 1024, 2048, 4096).
|
||||
public init(fftSize: Int) {
|
||||
precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0,
|
||||
"SpectralBuffer: fftSize must be a power of two >= 4, got \(fftSize)")
|
||||
self.fftSize = fftSize
|
||||
self.binCount = fftSize / 2 + 1
|
||||
let halfSize: Int = fftSize / 2
|
||||
_halfSize = halfSize
|
||||
_binCount = halfSize - 1 // complex bins 1..<halfSize
|
||||
|
||||
_mag = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_phase = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||||
_mag.initialize(repeating: 0, count: halfSize)
|
||||
_phase.initialize(repeating: 0, count: halfSize)
|
||||
|
||||
_isValid = Atomic(true)
|
||||
}
|
||||
|
||||
deinit {
|
||||
_mag.deinitialize(count: _halfSize)
|
||||
_mag.deallocate()
|
||||
_phase.deinitialize(count: _halfSize)
|
||||
_phase.deallocate()
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/// Mark this buffer invalid. Call from a non-RT thread.
|
||||
public func invalidate() {
|
||||
_isValid.store(false, ordering: .releasing)
|
||||
}
|
||||
|
||||
// MARK: - DC and Nyquist access
|
||||
|
||||
/// Signed DC component (bin 0). May be negative.
|
||||
///
|
||||
/// - Warning: Call from the RT thread only, or only when no RT processing is active.
|
||||
public var dcValue: Float {
|
||||
get { _dcValue }
|
||||
set { _dcValue = newValue }
|
||||
}
|
||||
|
||||
/// Signed Nyquist component (bin `fftSize / 2`). May be negative.
|
||||
///
|
||||
/// - Warning: Call from the RT thread only, or only when no RT processing is active.
|
||||
public var nyquistValue: Float {
|
||||
get { _nyquistValue }
|
||||
set { _nyquistValue = newValue }
|
||||
}
|
||||
|
||||
// MARK: - Per-bin polar subscripts
|
||||
|
||||
/// Read or write the magnitude of complex bin `bin`.
|
||||
///
|
||||
/// Valid range: `1 ..< fftSize/2`. DC (bin 0) and Nyquist (bin fftSize/2) use
|
||||
/// `dcValue` and `nyquistValue` respectively.
|
||||
///
|
||||
/// - Warning: Call from the RT thread only, or only when no RT processing is active.
|
||||
public subscript(magnitude bin: Int) -> Float {
|
||||
get {
|
||||
precondition(bin >= 1 && bin < _halfSize,
|
||||
"SpectralBuffer[magnitude:] bin \(bin) out of range [1, \(_halfSize))")
|
||||
return _mag[bin]
|
||||
}
|
||||
set {
|
||||
precondition(bin >= 1 && bin < _halfSize,
|
||||
"SpectralBuffer[magnitude:] bin \(bin) out of range [1, \(_halfSize))")
|
||||
_mag[bin] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
/// Read or write the phase (radians) of complex bin `bin`.
|
||||
///
|
||||
/// Valid range: `1 ..< fftSize/2`. DC and Nyquist have no meaningful spectral
|
||||
/// phase; access them via `dcValue` and `nyquistValue`.
|
||||
///
|
||||
/// - Warning: Call from the RT thread only, or only when no RT processing is active.
|
||||
public subscript(phase bin: Int) -> Float {
|
||||
get {
|
||||
precondition(bin >= 1 && bin < _halfSize,
|
||||
"SpectralBuffer[phase:] bin \(bin) out of range [1, \(_halfSize))")
|
||||
return _phase[bin]
|
||||
}
|
||||
set {
|
||||
precondition(bin >= 1 && bin < _halfSize,
|
||||
"SpectralBuffer[phase:] bin \(bin) out of range [1, \(_halfSize))")
|
||||
_phase[bin] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Convenience bin access (all bins including DC and Nyquist)
|
||||
|
||||
/// Magnitude of frequency bin `bin`.
|
||||
///
|
||||
/// - DC (bin 0): `abs(dcValue)`
|
||||
/// - Nyquist (bin `fftSize / 2`): `abs(nyquistValue)`
|
||||
/// - Complex bins 1 ..< fftSize/2: stored magnitude (always ≥ 0)
|
||||
///
|
||||
/// - Warning: Call from the RT thread only, or only when no RT processing is active.
|
||||
public func magnitude(at bin: Int) -> Float {
|
||||
precondition(bin >= 0 && bin < binCount,
|
||||
"SpectralBuffer: bin \(bin) out of range [0, \(binCount))")
|
||||
if bin == 0 { return abs(_dcValue) }
|
||||
if bin == _halfSize { return abs(_nyquistValue) }
|
||||
return _mag[bin]
|
||||
}
|
||||
|
||||
/// Phase (radians) of frequency bin `bin`.
|
||||
///
|
||||
/// DC and Nyquist are purely real — both return `0`.
|
||||
///
|
||||
/// - Warning: Call from the RT thread only, or only when no RT processing is active.
|
||||
public func phase(at bin: Int) -> Float {
|
||||
precondition(bin >= 0 && bin < binCount,
|
||||
"SpectralBuffer: bin \(bin) out of range [0, \(binCount))")
|
||||
if bin == 0 || bin == _halfSize { return 0 }
|
||||
return _phase[bin]
|
||||
}
|
||||
|
||||
/// Set the magnitude of bin `bin`, preserving phase.
|
||||
///
|
||||
/// DC and Nyquist are unsigned after this call (sign is not preserved since
|
||||
/// sign corresponds to a phase of 0 or π, which processors should express
|
||||
/// via `dcValue`/`nyquistValue` directly).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - v: Magnitude to set. Must be non-negative.
|
||||
/// - bin: Bin index in `[0, binCount)`.
|
||||
/// - Warning: Call from the RT thread only, or only when no RT processing is active.
|
||||
public func setMagnitude(
|
||||
_ v: Float,
|
||||
at bin: Int
|
||||
) {
|
||||
precondition(v >= 0, "SpectralBuffer.setMagnitude: magnitude must be non-negative, got \(v)")
|
||||
precondition(bin >= 0 && bin < binCount,
|
||||
"SpectralBuffer: bin \(bin) out of range [0, \(binCount))")
|
||||
if bin == 0 {
|
||||
// Preserve sign: DC sign encodes phase (0 = positive, π = negative).
|
||||
_dcValue = _dcValue < 0 ? -v : v
|
||||
} else if bin == _halfSize {
|
||||
// Preserve sign: same convention for Nyquist.
|
||||
_nyquistValue = _nyquistValue < 0 ? -v : v
|
||||
} else {
|
||||
_mag[bin] = v
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal pointer access (package-internal, RT-safe, no CoW)
|
||||
|
||||
/// Call `body` with a read-only pointer to the magnitude array at index 1.
|
||||
/// Valid for `fftSize/2 − 1` elements (complex bins 1..halfSize-1).
|
||||
@discardableResult
|
||||
func withUnsafeMagnitudePointer<R>(_ body: (UnsafePointer<Float>) -> R) -> R {
|
||||
body(UnsafePointer(_mag.advanced(by: 1)))
|
||||
}
|
||||
|
||||
/// Call `body` with a mutable pointer to the magnitude array at index 1.
|
||||
/// Valid for `fftSize/2 − 1` elements (complex bins 1..halfSize-1).
|
||||
@discardableResult
|
||||
func withUnsafeMutableMagnitudePointer<R>(_ body: (UnsafeMutablePointer<Float>) -> R) -> R {
|
||||
body(_mag.advanced(by: 1))
|
||||
}
|
||||
|
||||
/// Call `body` with a read-only pointer to the phase array at index 1.
|
||||
/// Valid for `fftSize/2 − 1` elements (complex bins 1..halfSize-1).
|
||||
@discardableResult
|
||||
func withUnsafePhasePointer<R>(_ body: (UnsafePointer<Float>) -> R) -> R {
|
||||
body(UnsafePointer(_phase.advanced(by: 1)))
|
||||
}
|
||||
|
||||
/// Call `body` with a mutable pointer to the phase array at index 1.
|
||||
/// Valid for `fftSize/2 − 1` elements (complex bins 1..halfSize-1).
|
||||
@discardableResult
|
||||
func withUnsafeMutablePhasePointer<R>(_ body: (UnsafeMutablePointer<Float>) -> R) -> R {
|
||||
body(_phase.advanced(by: 1))
|
||||
}
|
||||
|
||||
// MARK: - Internal rectangular conversion (package-internal)
|
||||
|
||||
/// Convert split-complex rectangular data to polar and store in this buffer.
|
||||
///
|
||||
/// Called by `SpectralChain.Audio` immediately after each forward FFT hop.
|
||||
/// `realp` and `imagp` must each have at least `fftSize/2` valid elements
|
||||
/// in vDSP split-complex layout (DC at index 0, Nyquist packed at imagp[0]).
|
||||
///
|
||||
/// Uses `vDSP_zvmags + vvsqrtf` for magnitudes and `vvatan2f` for phases.
|
||||
/// All work is vectorized — no scalar loops over complex bins.
|
||||
func _writeFromRectangular(
|
||||
_ realp: UnsafePointer<Float>,
|
||||
imagp: UnsafePointer<Float>
|
||||
) {
|
||||
// DC and Nyquist — preserve signed values directly.
|
||||
_dcValue = realp[0]
|
||||
_nyquistValue = imagp[0]
|
||||
|
||||
guard _binCount > 0 else { return }
|
||||
|
||||
let rp: UnsafePointer<Float> = realp.advanced(by: 1)
|
||||
let ip: UnsafePointer<Float> = imagp.advanced(by: 1)
|
||||
let mp: UnsafeMutablePointer<Float> = _mag.advanced(by: 1)
|
||||
let pp: UnsafeMutablePointer<Float> = _phase.advanced(by: 1)
|
||||
let n: vDSP_Length = vDSP_Length(_binCount)
|
||||
|
||||
// Magnitudes: squared magnitude via vDSP, then vectorized sqrt.
|
||||
var split: DSPSplitComplex = DSPSplitComplex(
|
||||
realp: UnsafeMutablePointer(mutating: rp),
|
||||
imagp: UnsafeMutablePointer(mutating: ip)
|
||||
)
|
||||
vDSP_zvmags(&split, 1, mp, 1, n)
|
||||
var count: Int32 = Int32(_binCount)
|
||||
vvsqrtf(mp, mp, &count)
|
||||
|
||||
// Phases: vvatan2f(output, y, x, n) = atan2f(imagp, realp) per bin.
|
||||
vvatan2f(pp, ip, rp, &count)
|
||||
}
|
||||
|
||||
/// Convert the polar data in this buffer to split-complex rectangular form.
|
||||
///
|
||||
/// Called by `SpectralChain.Audio` immediately before each inverse FFT hop.
|
||||
/// `realp` and `imagp` must each have at least `fftSize/2` elements.
|
||||
///
|
||||
/// Uses `vvcosf + vvsinf` for the unit vector and `vDSP_vmul` for magnitude
|
||||
/// scaling. DC and Nyquist are written as-is (signed scalars).
|
||||
func _readToRectangular(
|
||||
realp: UnsafeMutablePointer<Float>,
|
||||
imagp: UnsafeMutablePointer<Float>
|
||||
) {
|
||||
// DC and Nyquist — signed scalars pass through unchanged.
|
||||
realp[0] = _dcValue
|
||||
imagp[0] = _nyquistValue
|
||||
|
||||
guard _binCount > 0 else { return }
|
||||
|
||||
let rp: UnsafeMutablePointer<Float> = realp.advanced(by: 1)
|
||||
let ip: UnsafeMutablePointer<Float> = imagp.advanced(by: 1)
|
||||
let mp: UnsafeMutablePointer<Float> = _mag.advanced(by: 1)
|
||||
let pp: UnsafeMutablePointer<Float> = _phase.advanced(by: 1)
|
||||
let n: vDSP_Length = vDSP_Length(_binCount)
|
||||
var count: Int32 = Int32(_binCount)
|
||||
|
||||
// rp = cos(phase), ip = sin(phase)
|
||||
vvcosf(rp, pp, &count)
|
||||
vvsinf(ip, pp, &count)
|
||||
|
||||
// rp = mag × cos(phase), ip = mag × sin(phase)
|
||||
vDSP_vmul(mp, 1, rp, 1, rp, 1, n)
|
||||
vDSP_vmul(mp, 1, ip, 1, ip, 1, n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
// SpectralFrameBuffer.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Accelerate
|
||||
import Synchronization
|
||||
|
||||
/// Pre-allocated multi-frame polar spectral buffer for recording and replaying FFT frames.
|
||||
///
|
||||
/// Stores `frameCount` FFT frames in polar (magnitude + phase) format. All storage uses
|
||||
/// `UnsafeMutablePointer<Float>` to eliminate Swift Array copy-on-write overhead.
|
||||
/// Pointer addresses are stable for the object's lifetime.
|
||||
///
|
||||
/// ## Layout
|
||||
///
|
||||
/// For each frame `f`:
|
||||
/// - `_dc[f]` — signed DC component
|
||||
/// - `_nyquist[f]` — signed Nyquist component
|
||||
/// - `_mag[f*halfSize + 1 ..< f*halfSize + halfSize]` — magnitudes for bins 1..halfSize-1
|
||||
/// - `_phase[f*halfSize + 1 ..< f*halfSize + halfSize]` — phases for bins 1..halfSize-1
|
||||
///
|
||||
/// Index 0 of each frame's `_mag`/`_phase` row is unused (matches `SpectralBuffer`
|
||||
/// convention where index 0 is reserved and only bins 1..halfSize-1 hold complex data).
|
||||
///
|
||||
/// ## Thread safety
|
||||
///
|
||||
/// `writeFrame` and `readFrame` are RT-safe (memcpy only). `isValid` uses `Atomic<Bool>`.
|
||||
/// All other per-frame accessors are RT-thread-only.
|
||||
public final class SpectralFrameBuffer: @unchecked Sendable {
|
||||
// Sendable invariant: geometry fields (`fftSize`, `hopSize`, `frameCount`,
|
||||
// `sampleRate`, `halfSize`) and the four storage pointers are immutable lets.
|
||||
// Per-frame magnitude/phase storage is RT-thread-private (writeFrame/readFrame
|
||||
// are memcpy-only and never overlap because `_writeIndex` advances monotonically).
|
||||
// Cross-thread visibility is gated by the `Atomic<Bool>` `_isValid` flag.
|
||||
|
||||
// MARK: - Immutable geometry
|
||||
|
||||
public let fftSize: Int
|
||||
public let hopSize: Int
|
||||
public let frameCount: Int
|
||||
public let sampleRate: Double
|
||||
public let halfSize: Int // fftSize / 2
|
||||
|
||||
// MARK: - Internal storage (module-internal for FileIO and SpectralPlayBuffer access)
|
||||
|
||||
let _dc: UnsafeMutablePointer<Float> // [frameCount]
|
||||
let _nyquist: UnsafeMutablePointer<Float> // [frameCount]
|
||||
let _mag: UnsafeMutablePointer<Float> // [frameCount × halfSize]; index 0 per frame unused
|
||||
let _phase: UnsafeMutablePointer<Float> // [frameCount × halfSize]; same layout
|
||||
let _binCount: Int // halfSize - 1 (complex bins 1..<halfSize)
|
||||
|
||||
// MARK: - Validity
|
||||
|
||||
private let _isValid: Atomic<Bool>
|
||||
|
||||
/// Whether this buffer is valid.
|
||||
public var isValid: Bool { _isValid.load(ordering: .acquiring) }
|
||||
|
||||
/// Mark invalid. Call from a non-RT thread.
|
||||
public func invalidate() { _isValid.store(false, ordering: .releasing) }
|
||||
|
||||
// MARK: - Frames written
|
||||
|
||||
/// Number of frames that contain valid recorded data.
|
||||
///
|
||||
/// Defaults to `frameCount` so manually-filled buffers work without extra setup.
|
||||
/// `SpectralRecordBuffer` overwrites this atomically after each hop so language-side
|
||||
/// code can read progress safely.
|
||||
let _framesWritten: Atomic<Int>
|
||||
|
||||
/// Number of frames that contain valid recorded data. Read from any thread.
|
||||
public var framesWritten: Int { _framesWritten.load(ordering: .acquiring) }
|
||||
|
||||
/// Duration of the recorded spectral data in seconds.
|
||||
/// Uses `framesWritten` (not `frameCount`) so partially-filled buffers report actual captured length.
|
||||
/// Returns `0` when `sampleRate == 0` (unknown).
|
||||
public var duration: Double {
|
||||
guard sampleRate > 0 else { return 0 }
|
||||
return Double(hopSize * framesWritten) / sampleRate
|
||||
}
|
||||
|
||||
/// Frequency to drive a `Phasor` for `SpectralPlayBuffer` / `SpectralBufferRead` to sweep
|
||||
/// position 0→1 over the full recorded duration. Returns `nil` when `sampleRate == 0` or
|
||||
/// `framesWritten == 0`.
|
||||
public var phasorFrequency: Double? {
|
||||
let d: Double = duration
|
||||
guard d > 0 else { return nil }
|
||||
return 1.0 / d
|
||||
}
|
||||
|
||||
// MARK: - Initialisation
|
||||
|
||||
/// Allocate a frame buffer for `frameCount` FFT frames.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - fftSize: Power of two ≥ 4.
|
||||
/// - hopSize: Hop size (samples between frames). Must be > 0.
|
||||
/// - frameCount: Number of frames to store. Must be > 0.
|
||||
/// - sampleRate: Sample rate at which frames were captured; `0` = unknown.
|
||||
public init(
|
||||
fftSize: Int,
|
||||
hopSize: Int,
|
||||
frameCount: Int,
|
||||
sampleRate: Double
|
||||
) {
|
||||
precondition(
|
||||
fftSize >= 4 && (fftSize & (fftSize - 1)) == 0 && frameCount > 0 && hopSize > 0,
|
||||
"SpectralFrameBuffer: fftSize must be a power of two >= 4, frameCount > 0, hopSize > 0"
|
||||
)
|
||||
self.fftSize = fftSize
|
||||
self.hopSize = hopSize
|
||||
self.frameCount = frameCount
|
||||
self.sampleRate = sampleRate
|
||||
let hs: Int = fftSize / 2
|
||||
self.halfSize = hs
|
||||
_binCount = hs - 1
|
||||
|
||||
let magPhaseCount: Int = frameCount * hs
|
||||
_dc = UnsafeMutablePointer<Float>.allocate(capacity: frameCount)
|
||||
_nyquist = UnsafeMutablePointer<Float>.allocate(capacity: frameCount)
|
||||
_mag = UnsafeMutablePointer<Float>.allocate(capacity: magPhaseCount)
|
||||
_phase = UnsafeMutablePointer<Float>.allocate(capacity: magPhaseCount)
|
||||
|
||||
_dc.initialize(repeating: 0, count: frameCount)
|
||||
_nyquist.initialize(repeating: 0, count: frameCount)
|
||||
_mag.initialize(repeating: 0, count: magPhaseCount)
|
||||
_phase.initialize(repeating: 0, count: magPhaseCount)
|
||||
|
||||
_isValid = Atomic(true)
|
||||
_framesWritten = Atomic(frameCount)
|
||||
}
|
||||
|
||||
deinit {
|
||||
let magPhaseCount: Int = frameCount * halfSize
|
||||
_dc.deinitialize(count: frameCount)
|
||||
_dc.deallocate()
|
||||
_nyquist.deinitialize(count: frameCount)
|
||||
_nyquist.deallocate()
|
||||
_mag.deinitialize(count: magPhaseCount)
|
||||
_mag.deallocate()
|
||||
_phase.deinitialize(count: magPhaseCount)
|
||||
_phase.deallocate()
|
||||
}
|
||||
|
||||
// MARK: - Phase interpolation (RT-safe)
|
||||
|
||||
/// Linearly interpolate stored phases between `frameA` and `frameB` using the shortest
|
||||
/// angular path, writing into `dst[1..halfSize-1]`.
|
||||
///
|
||||
/// Shortest-path formula: `dst[k] = phaseA[k] + frac × principalValue(phaseB[k] − phaseA[k])`.
|
||||
///
|
||||
/// Unlike the phase-vocoder accumulator in `SpectralPlayBuffer`, this method reads the
|
||||
/// raw stored analysis phases without accumulation. It is suited to random-access position
|
||||
/// playback (`SpectralBufferRead`) where a synthesis accumulator would drift when the
|
||||
/// position jumps.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dst: Output pointer, size ≥ halfSize. Index 0 is not written; bins 1..halfSize-1 are filled.
|
||||
/// - frameA: Source frame index A.
|
||||
/// - frameB: Source frame index B (typically A + 1, clamped to `framesWritten − 1`).
|
||||
/// - frac: Blend weight [0, 1] for B.
|
||||
public func interpolatePhases(
|
||||
into dst: UnsafeMutablePointer<Float>,
|
||||
frameA: Int,
|
||||
frameB: Int,
|
||||
frac: Float
|
||||
) {
|
||||
let baseA: Int = frameA * halfSize
|
||||
let baseB: Int = frameB * halfSize
|
||||
let twoPi: Float = .pi * 2
|
||||
for k: Int in 1..<halfSize {
|
||||
var d: Float = _phase[baseB + k] - _phase[baseA + k]
|
||||
if d > .pi { d -= twoPi }
|
||||
else if d < -.pi { d += twoPi }
|
||||
dst[k] = _phase[baseA + k] + frac * d
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Trimming
|
||||
|
||||
/// Return a new `SpectralFrameBuffer` containing only the frames that hold
|
||||
/// valid recorded data (`0..<framesWritten`).
|
||||
///
|
||||
/// Useful when a large buffer is pre-allocated but only partially filled by
|
||||
/// `SpectralRecordBuffer`: `trimmed()` produces a smaller buffer whose `frameCount`
|
||||
/// equals the actually-captured duration, so `write(to:)` stores no wasted space.
|
||||
///
|
||||
/// - Returns: New buffer with `frameCount == min(framesWritten, frameCount)`.
|
||||
/// The new buffer's `framesWritten` equals its `frameCount`.
|
||||
public func trimmed() -> SpectralFrameBuffer {
|
||||
let n: Int = min(framesWritten, frameCount)
|
||||
precondition(n > 0, "SpectralFrameBuffer.trimmed(): framesWritten is 0 — no frames to trim to")
|
||||
let newBuf: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fftSize, hopSize: hopSize,
|
||||
frameCount: n, sampleRate: sampleRate
|
||||
)
|
||||
let byteCount: Int = _binCount * MemoryLayout<Float>.stride
|
||||
for f: Int in 0..<n {
|
||||
newBuf._dc[f] = _dc[f]
|
||||
newBuf._nyquist[f] = _nyquist[f]
|
||||
let base: Int = f * halfSize
|
||||
_ = memcpy(newBuf._mag + base + 1, _mag + base + 1, byteCount)
|
||||
_ = memcpy(newBuf._phase + base + 1, _phase + base + 1, byteCount)
|
||||
}
|
||||
return newBuf
|
||||
}
|
||||
|
||||
// MARK: - Scalar accessors
|
||||
|
||||
/// Signed DC component at `frame`.
|
||||
public func dc(at frame: Int) -> Float { _dc[frame] }
|
||||
|
||||
/// Signed Nyquist component at `frame`.
|
||||
public func nyquist(at frame: Int) -> Float { _nyquist[frame] }
|
||||
|
||||
// MARK: - Frame I/O (RT-safe)
|
||||
|
||||
/// Copy polar data from `spectral` into frame `at`. RT-safe (memcpy only).
|
||||
public func writeFrame(
|
||||
from spectral: SpectralBuffer,
|
||||
at frame: Int
|
||||
) {
|
||||
precondition(frame >= 0 && frame < frameCount,
|
||||
"SpectralFrameBuffer.writeFrame: frame \(frame) out of range")
|
||||
_dc[frame] = spectral.dcValue
|
||||
_nyquist[frame] = spectral.nyquistValue
|
||||
let base: Int = frame * halfSize
|
||||
let byteCount: Int = _binCount * MemoryLayout<Float>.stride
|
||||
spectral.withUnsafeMagnitudePointer { src in
|
||||
_ = memcpy(_mag + base + 1, src, byteCount)
|
||||
}
|
||||
spectral.withUnsafePhasePointer { src in
|
||||
_ = memcpy(_phase + base + 1, src, byteCount)
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy polar data from frame `at` into `spectral`. RT-safe (memcpy only).
|
||||
public func readFrame(
|
||||
into spectral: SpectralBuffer,
|
||||
at frame: Int
|
||||
) {
|
||||
precondition(frame >= 0 && frame < frameCount,
|
||||
"SpectralFrameBuffer.readFrame: frame \(frame) out of range")
|
||||
spectral.dcValue = _dc[frame]
|
||||
spectral.nyquistValue = _nyquist[frame]
|
||||
let base: Int = frame * halfSize
|
||||
let byteCount: Int = _binCount * MemoryLayout<Float>.stride
|
||||
spectral.withUnsafeMutableMagnitudePointer { dst in
|
||||
_ = memcpy(dst, _mag + base + 1, byteCount)
|
||||
}
|
||||
spectral.withUnsafeMutablePhasePointer { dst in
|
||||
_ = memcpy(dst, _phase + base + 1, byteCount)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Interpolation (RT-safe)
|
||||
|
||||
/// Linearly interpolate magnitudes between `frameA` and `frameB` into `dst[1..halfSize-1]`.
|
||||
///
|
||||
/// Uses `vDSP_vintb`: `dst[k] = mag[frameA][k] + frac × (mag[frameB][k] − mag[frameA][k])`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - dst: Output pointer, size ≥ halfSize. Index 0 is not written; bins 1..halfSize-1 are filled.
|
||||
/// - frameA: Source frame index A (integer part of playback position).
|
||||
/// - frameB: Source frame index B (A + 1, clamped to frameCount − 1).
|
||||
/// - frac: Fractional blend weight for B. 0 → frameA only, 1 → frameB only.
|
||||
public func interpolateMagnitudes(
|
||||
into dst: UnsafeMutablePointer<Float>,
|
||||
frameA: Int,
|
||||
frameB: Int,
|
||||
frac: Float
|
||||
) {
|
||||
var beta: Float = frac
|
||||
vDSP_vintb(
|
||||
_mag + frameA * halfSize + 1, 1,
|
||||
_mag + frameB * halfSize + 1, 1,
|
||||
&beta,
|
||||
dst + 1, 1,
|
||||
vDSP_Length(_binCount)
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Phase delta (RT-safe)
|
||||
|
||||
/// Compute the principal-value phase difference `(phaseB[k] − phaseA[k])` per bin
|
||||
/// and write into `dst[1..halfSize-1]`.
|
||||
///
|
||||
/// Result is wrapped to `(−π, π]` via a scalar if/else. A single add or subtract
|
||||
/// always suffices because stored phases come from `vvatan2f` output (guaranteed in `(−π, π]`)
|
||||
/// so raw differences lie in `(−2π, 2π)`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - frameA: Frame with earlier (reference) phases.
|
||||
/// - frameB: Frame with later phases.
|
||||
/// - dst: Output pointer, size ≥ halfSize. Index 0 is not written.
|
||||
public func phaseDelta(
|
||||
frameA: Int,
|
||||
frameB: Int,
|
||||
into dst: UnsafeMutablePointer<Float>
|
||||
) {
|
||||
let baseA: Int = frameA * halfSize
|
||||
let baseB: Int = frameB * halfSize
|
||||
let twoPi: Float = .pi * 2
|
||||
for k: Int in 1..<halfSize {
|
||||
var d: Float = _phase[baseB + k] - _phase[baseA + k]
|
||||
if d > .pi { d -= twoPi }
|
||||
else if d < -.pi { d += twoPi }
|
||||
dst[k] = d
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// SpectralFrameBufferFileIO.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - Error type
|
||||
|
||||
/// Errors thrown by `SpectralFrameBuffer` file I/O.
|
||||
public enum SpectralFileError: Error, Equatable {
|
||||
case cannotCreateFile
|
||||
case cannotOpenFile
|
||||
case invalidMagic
|
||||
case invalidHeader
|
||||
case unsupportedVersion(UInt32)
|
||||
}
|
||||
|
||||
// MARK: - .lbsf format constants
|
||||
|
||||
/// Byte length of the `.lbsf` file header.
|
||||
private let lbsfHeaderSize: Int = 40
|
||||
|
||||
/// Supported `.lbsf` format version.
|
||||
private let lbsfVersion: UInt32 = 1
|
||||
|
||||
/// ASCII magic bytes "LBSF".
|
||||
private let lbsfMagic: [UInt8] = [0x4C, 0x42, 0x53, 0x46]
|
||||
|
||||
// Header field byte offsets (all little-endian).
|
||||
private let lbsfOffsetVersion: Int = 4
|
||||
private let lbsfOffsetFftSize: Int = 8
|
||||
private let lbsfOffsetHopSize: Int = 12
|
||||
private let lbsfOffsetFrameCount: Int = 16
|
||||
private let lbsfOffsetSampleRate: Int = 20
|
||||
|
||||
// MARK: - File I/O extension
|
||||
|
||||
/// Binary `.lbsf` file format for `SpectralFrameBuffer`.
|
||||
///
|
||||
/// ## Format
|
||||
///
|
||||
/// ```
|
||||
/// Header (40 bytes, little-endian):
|
||||
/// [0..3] "LBSF" ASCII magic
|
||||
/// [4..7] version: UInt32 = 1
|
||||
/// [8..11] fftSize: UInt32
|
||||
/// [12..15] hopSize: UInt32
|
||||
/// [16..19] frameCount: UInt32
|
||||
/// [20..27] sampleRate: Float64 (0 = unknown)
|
||||
/// [28..39] reserved, zeroed
|
||||
///
|
||||
/// Body — per frame (Float32, little-endian):
|
||||
/// DC: Float32 × 1
|
||||
/// Nyquist: Float32 × 1
|
||||
/// Mags: Float32 × (halfSize − 1)
|
||||
/// Phases: Float32 × (halfSize − 1)
|
||||
/// ```
|
||||
///
|
||||
/// Total = 40 + frameCount × fftSize × 4 bytes.
|
||||
/// (1 + 1 + (halfSize−1) + (halfSize−1) = fftSize floats per frame.)
|
||||
///
|
||||
/// Files written on macOS are little-endian. Since macOS runs on little-endian hardware,
|
||||
/// no byte-swapping is needed for native reads and writes.
|
||||
extension SpectralFrameBuffer {
|
||||
|
||||
// MARK: - Write
|
||||
|
||||
/// Write this buffer to `url` in `.lbsf` format.
|
||||
///
|
||||
/// Only the frames that contain valid recorded data are written: the header stores
|
||||
/// `framesWritten` (not `frameCount`), and the body contains exactly that many frames.
|
||||
/// This ensures that a partially-filled buffer (e.g. a large pre-allocation used with
|
||||
/// `SpectralRecordBuffer`) produces a compact file without trailing garbage frames.
|
||||
public func write(to url: URL) throws {
|
||||
let path: String = url.path
|
||||
guard FileManager.default.createFile(atPath: path, contents: nil, attributes: nil) else {
|
||||
throw SpectralFileError.cannotCreateFile
|
||||
}
|
||||
guard let fh: FileHandle = FileHandle(forWritingAtPath: path) else {
|
||||
throw SpectralFileError.cannotCreateFile
|
||||
}
|
||||
// Close on error bail-out; the success path closes explicitly below so
|
||||
// flush failures surface to the caller rather than being swallowed.
|
||||
var didClose: Bool = false
|
||||
defer { if !didClose { try? fh.close() } }
|
||||
|
||||
let writtenCount: Int = min(framesWritten, frameCount)
|
||||
try fh.write(contentsOf: _makeHeader(frameCount: writtenCount))
|
||||
|
||||
// Write body: one frame at a time to bound peak memory usage.
|
||||
let frameFloats: Int = fftSize // 1 + 1 + (halfSize-1) + (halfSize-1) = fftSize
|
||||
var frameBuf: [Float] = [Float](repeating: 0, count: frameFloats)
|
||||
for f: Int in 0..<writtenCount {
|
||||
let base: Int = f * halfSize
|
||||
frameBuf[0] = _dc[f]
|
||||
frameBuf[1] = _nyquist[f]
|
||||
frameBuf.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let bptr: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
memcpy(bptr + 2, _mag + base + 1, _binCount * MemoryLayout<Float>.stride)
|
||||
memcpy(bptr + 2 + _binCount, _phase + base + 1, _binCount * MemoryLayout<Float>.stride)
|
||||
}
|
||||
let frameData: Data = frameBuf.withUnsafeBufferPointer { Data(buffer: $0) }
|
||||
try fh.write(contentsOf: frameData)
|
||||
}
|
||||
|
||||
try fh.close()
|
||||
didClose = true
|
||||
}
|
||||
|
||||
// MARK: - Load
|
||||
|
||||
/// Load a `.lbsf` file from `url` and return a new `SpectralFrameBuffer`.
|
||||
///
|
||||
/// - Throws: `SpectralFileError` on invalid magic, unsupported version, or I/O failure.
|
||||
public static func load(url: URL) throws -> SpectralFrameBuffer {
|
||||
guard let fh: FileHandle = try? FileHandle(forReadingFrom: url) else {
|
||||
throw SpectralFileError.cannotOpenFile
|
||||
}
|
||||
defer { try? fh.close() }
|
||||
|
||||
// Read and validate header.
|
||||
let headerData: Data = fh.readData(ofLength: lbsfHeaderSize)
|
||||
guard headerData.count == lbsfHeaderSize else {
|
||||
throw SpectralFileError.invalidMagic
|
||||
}
|
||||
guard headerData[0] == lbsfMagic[0], headerData[1] == lbsfMagic[1],
|
||||
headerData[2] == lbsfMagic[2], headerData[3] == lbsfMagic[3] else {
|
||||
throw SpectralFileError.invalidMagic
|
||||
}
|
||||
|
||||
// Use loadUnaligned — Data bytes may not be aligned to UInt32/Float64 boundaries.
|
||||
let version: UInt32 = headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetVersion, as: UInt32.self) }
|
||||
guard version == lbsfVersion else {
|
||||
throw SpectralFileError.unsupportedVersion(version)
|
||||
}
|
||||
|
||||
let fileFftSize: Int = Int(headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetFftSize, as: UInt32.self) })
|
||||
let fileHopSize: Int = Int(headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetHopSize, as: UInt32.self) })
|
||||
let fileFrameCount: Int = Int(headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetFrameCount, as: UInt32.self) })
|
||||
let fileSampleRate: Float64 = headerData.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: lbsfOffsetSampleRate, as: Float64.self) }
|
||||
|
||||
guard fileFftSize >= 4 && (fileFftSize & (fileFftSize - 1)) == 0
|
||||
&& fileHopSize > 0 && fileFrameCount > 0 else {
|
||||
throw SpectralFileError.invalidHeader
|
||||
}
|
||||
|
||||
let buf: SpectralFrameBuffer = SpectralFrameBuffer(
|
||||
fftSize: fileFftSize,
|
||||
hopSize: fileHopSize,
|
||||
frameCount: fileFrameCount,
|
||||
sampleRate: fileSampleRate
|
||||
)
|
||||
|
||||
// Read body frame by frame. Copy into a local Float array to avoid alignment issues.
|
||||
let frameFloats: Int = fileFftSize
|
||||
let frameBytes: Int = frameFloats * MemoryLayout<Float>.stride
|
||||
let binCount: Int = buf._binCount
|
||||
var frameBuf: [Float] = [Float](repeating: 0, count: frameFloats)
|
||||
var framesRead: Int = 0
|
||||
for f: Int in 0..<fileFrameCount {
|
||||
let data: Data = fh.readData(ofLength: frameBytes)
|
||||
guard data.count == frameBytes else { break }
|
||||
frameBuf.withUnsafeMutableBytes { dst in
|
||||
guard let dstPtr: UnsafeMutableRawPointer = dst.baseAddress else { return }
|
||||
data.withUnsafeBytes { src in
|
||||
guard let srcPtr: UnsafeRawPointer = src.baseAddress else { return }
|
||||
_ = memcpy(dstPtr, srcPtr, frameBytes)
|
||||
}
|
||||
}
|
||||
buf._dc[f] = frameBuf[0]
|
||||
buf._nyquist[f] = frameBuf[1]
|
||||
let frameBase: Int = f * buf.halfSize
|
||||
frameBuf.withUnsafeBufferPointer { ptr in
|
||||
guard let bptr: UnsafePointer<Float> = ptr.baseAddress else { return }
|
||||
_ = memcpy(buf._mag + frameBase + 1, bptr + 2, binCount * MemoryLayout<Float>.stride)
|
||||
_ = memcpy(buf._phase + frameBase + 1, bptr + 2 + binCount, binCount * MemoryLayout<Float>.stride)
|
||||
}
|
||||
framesRead += 1
|
||||
}
|
||||
// Reflect actual frames read so callers see the true valid range on truncated files.
|
||||
buf._framesWritten.store(framesRead, ordering: .releasing)
|
||||
return buf
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
private func _makeHeader(frameCount overrideFrameCount: Int) -> Data {
|
||||
var d: Data = Data(capacity: lbsfHeaderSize)
|
||||
d.append(contentsOf: lbsfMagic)
|
||||
// UInt32 fields
|
||||
func appendU32(_ v: UInt32) { withUnsafeBytes(of: v) { d.append(contentsOf: $0) } }
|
||||
func appendF64(_ v: Float64) { withUnsafeBytes(of: v) { d.append(contentsOf: $0) } }
|
||||
appendU32(lbsfVersion)
|
||||
appendU32(UInt32(fftSize))
|
||||
appendU32(UInt32(hopSize))
|
||||
appendU32(UInt32(overrideFrameCount))
|
||||
appendF64(sampleRate)
|
||||
// Reserved (12 bytes zeroed)
|
||||
let reservedByteCount: Int = lbsfHeaderSize - d.count
|
||||
d.append(contentsOf: [UInt8](repeating: 0, count: reservedByteCount))
|
||||
return d
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// SpectralPhaseHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Wrap each element of `p[0..<count]` to the principal value range `(−π, π]`.
|
||||
///
|
||||
/// Assumes inputs are within `(−2π, 2π)` (one wrap suffices). This holds when
|
||||
/// the source is a sum of two principal-value phases or a single increment ≤ 2π.
|
||||
/// For larger excursions, callers should apply this repeatedly or fold modulo
|
||||
/// `2π` first.
|
||||
///
|
||||
/// Branchless `Float.pi` comparisons; no allocation; safe to call on the RT thread.
|
||||
@inline(__always)
|
||||
internal func wrapPhasesInPlace(
|
||||
_ p: UnsafeMutablePointer<Float>,
|
||||
count: Int
|
||||
) {
|
||||
let twoPi: Float = 2 * Float.pi
|
||||
for i: Int in 0..<count {
|
||||
let v: Float = p[i]
|
||||
if v > Float.pi { p[i] = v - twoPi }
|
||||
else if v < -Float.pi { p[i] = v + twoPi }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user