b6fdee8bfc
Consolidated release: the cross-platform Linux port (engine, generators, CLI, REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive. See RELEASES.md and LINUX_README.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
743 lines
35 KiB
Swift
743 lines
35 KiB
Swift
// SpectralChain.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
import LyrebirdDSP
|
||
|
||
/// Consolidated short-time Fourier transform pipeline. A single audio-rate
|
||
/// Generator that owns the entire chain: input accumulation, windowed forward
|
||
/// FFT, an ordered ``SpectralStage`` pipeline (mono + cross-synthesis
|
||
/// processors interleaved in any order), an optional terminal mono→N
|
||
/// fan-out processor, and N inverse FFTs with windowed overlap-add
|
||
/// resynthesis.
|
||
///
|
||
/// **Four operating modes:**
|
||
///
|
||
/// 1. **Mono resynthesis** (default — `fanOut == nil`, `analyzeOnly == false`):
|
||
/// one output channel. `output(bus: 0, source: chain)`.
|
||
/// 2. **Mono → N fan-out** (`fanOut != nil`): the host runs the standard
|
||
/// processor chain on the source buffer, then calls
|
||
/// `fanOut.process(source:into:channel:)` once per output channel into
|
||
/// a per-channel destination buffer, then runs N IFFTs to produce N
|
||
/// audio rows. Wire each channel to its own output bus.
|
||
/// 3. **Analyze-only** (`analyzeOnly == true`): no IFFT runs and the audio
|
||
/// output is silence. Used by spectral feature extractors
|
||
/// (`SpectralCentroid.Control`, `SpectralFlatness.Control`, etc.) and
|
||
/// by sidechain analyses that only need the spectral buffer.
|
||
/// 4. **Synth-only** (`spectralSource` init): no forward FFT runs. The
|
||
/// chain reads from an external ``SpectralBufferGenerator`` (e.g.
|
||
/// ``SpectralBufferRead``, ``SpectralPlayBuffer``) which populates its
|
||
/// own `spectralBuffer` each hop. The chain runs the processor chain
|
||
/// and IFFT bank as usual. Use for frame-buffer playback and offline
|
||
/// pre-analysed material.
|
||
///
|
||
/// ## RT safety
|
||
///
|
||
/// All buffers + FFT setups are allocated in `init`. `_computeSamples`
|
||
/// performs no Swift allocation. Per-channel IFFT state lives in separately-
|
||
/// allocated `UnsafeMutablePointer<Float>` regions; the analysis FFT
|
||
/// scratch is shared across hops. The `vDSP_create_fftsetup` is created
|
||
/// once and reused by all IFFTs (same `fftSize` and `log2n`).
|
||
///
|
||
/// ## Common shapes
|
||
///
|
||
/// ```swift
|
||
/// // Process: audio in → stages → audio out
|
||
/// let chain = SpectralChain.Audio(input: src, stages: [.mono(diffuser)])
|
||
/// output(bus: 0, source: chain)
|
||
///
|
||
/// // Analyze for feature extraction
|
||
/// let analysis = SpectralChain.Audio(input: src, analyzeOnly: true)
|
||
/// let centroid = SpectralCentroid.Control(analysis: analysis, sampleRate: sr)
|
||
///
|
||
/// // Synthesise from a pre-analysed frame buffer
|
||
/// let player = SpectralPlayBuffer(frameBuffer: frames, fftSize: 2048, hopSize: 512)
|
||
/// let chain = SpectralChain.Audio(spectralSource: player)
|
||
/// output(bus: 0, source: chain)
|
||
/// ```
|
||
public enum SpectralChain {
|
||
|
||
/// Audio-rate consolidated STFT pipeline. Two public init shapes:
|
||
/// audio-input (forward FFT → stages → fanOut → IFFT) and synthOnly
|
||
/// (`spectralSource:` Generator → stages → fanOut → IFFT, no forward FFT).
|
||
///
|
||
/// - Parameters:
|
||
/// - input: Audio-rate input signal. Any ``ValidGeneratorInput``.
|
||
/// Audio-input init only — mutually exclusive with `spectralSource`.
|
||
/// - spectralSource: An ``SpectralBufferGenerator`` that owns and
|
||
/// populates a `SpectralBuffer` each hop. SynthOnly init
|
||
/// only — mutually exclusive with `input`. Engine `blockSize`
|
||
/// must be `<= hopSize` (runtime precondition); a single source
|
||
/// hop fires per chain call.
|
||
/// - fftSize: FFT frame size. Power of two ≥ 4. Default 2048.
|
||
/// - hopSize: Samples between FFT hops. In `[1, fftSize]`. Default 512.
|
||
/// - analysisWindow: Optional window of length `fftSize`. Pass `nil`
|
||
/// to use `LyrebirdBuffer.sineWindow(size:)` (default). Audio-input
|
||
/// init only — synthOnly uses no analysis window.
|
||
/// - synthesisWindow: Optional synthesis window of length `fftSize`.
|
||
/// Audio-input init: defaults to the analysis window. SynthOnly init:
|
||
/// defaults to `LyrebirdBuffer.sineWindow(size:)`. Pre-scaled
|
||
/// internally by the WOLA normalisation factor.
|
||
/// - stages: Ordered ``SpectralStage`` pipeline applied to the chain's
|
||
/// `spectralBuffer` after each FFT hop. `.mono(_)` runs a
|
||
/// single-input transform; `.dual(_, sideChain:)` runs a
|
||
/// cross-synthesis transform reading from the named sidechain
|
||
/// (sidechains must share `fftSize` and `hopSize`). Default empty.
|
||
/// - fanOut: Optional ``SpectralFanOutProcessor`` — terminal stage
|
||
/// that runs after all `stages` and populates N destination
|
||
/// spectral buffers, producing N audio output channels. `nil` =
|
||
/// single mono output. Cannot be followed by further spectral
|
||
/// processing in this chain. Default `nil`.
|
||
/// - analyzeOnly: When `true`, skip all IFFT resynthesis; audio
|
||
/// output is silent (mono); the source `spectralBuffer` is still
|
||
/// populated each hop. Audio-input init only — synthOnly + analyzeOnly
|
||
/// would be silent. Default `false`.
|
||
/// - mul: Output multiplier applied after synthesis. Default 1.
|
||
/// - add: Output offset added after multiplier. Default 0.
|
||
public final class Audio: GeneratorBase, AudioGenerator {
|
||
|
||
// MARK: - Public
|
||
|
||
/// Source spectral buffer — the polar spectrum written by the
|
||
/// forward FFT and mutated in place by the registered
|
||
/// `SpectralProcessor` chain. Feature extractors and sidechain
|
||
/// processors read this buffer.
|
||
public let spectralBuffer: SpectralBuffer
|
||
|
||
/// FFT frame size, set at init.
|
||
public let fftSize: Int
|
||
|
||
/// Number of new samples between FFT hops, set at init.
|
||
public let hopSize: Int
|
||
|
||
/// Output channel count. Equals `fanOut?.outputChannelCount ?? 1`.
|
||
/// Always `1` when `analyzeOnly == true` (silent output).
|
||
public final override var outputChannelCount: Int { _outputChannelCount }
|
||
private let _outputChannelCount: Int
|
||
|
||
/// `true` when this chain skips IFFT resynthesis and only populates
|
||
/// `spectralBuffer` for downstream feature extractors / sidechain.
|
||
public let analyzeOnly: Bool
|
||
|
||
/// Analysis window applied before each FFT hop.
|
||
public let analysisWindow: [Float]
|
||
|
||
/// `true` when this chain reads its source spectral buffer from an
|
||
/// external ``SpectralBufferGenerator`` instead of running its own
|
||
/// forward FFT on an audio input.
|
||
public var synthOnly: Bool { _spectralSource != nil }
|
||
|
||
// MARK: - Configuration
|
||
|
||
private let inputSource: any ValidGeneratorInput
|
||
private let inputIsGenerator: Bool
|
||
private let _spectralSource: (any SpectralBufferGenerator)?
|
||
private let halfSize: Int
|
||
private let fftMask: Int // fftSize − 1, for power-of-2 ring modulo
|
||
private let log2n: vDSP_Length
|
||
internal let stages: [SpectralStage]
|
||
private let fanOut: (any SpectralFanOutProcessor)?
|
||
|
||
// MARK: - Analysis-side state
|
||
|
||
private var _inputRing: [Float]
|
||
private var _ringWritePos: Int = 0
|
||
private var _analysisHopCounter: Int = 0
|
||
private var _windowedBuf: [Float]
|
||
/// Forward-FFT split-complex scratch. `nil` in synthOnly mode (no
|
||
/// forward FFT runs). Allocated `halfSize` Floats in the audio-input
|
||
/// path; freed in `deinit`.
|
||
private let _fftAnalysisRealp: UnsafeMutablePointer<Float>?
|
||
private let _fftAnalysisImagp: UnsafeMutablePointer<Float>?
|
||
|
||
// MARK: - Destination buffers (per output channel)
|
||
|
||
/// `destinations[0..<outputChannelCount]`. When `fanOut == nil` and
|
||
/// `outputChannelCount == 1`, the single entry aliases
|
||
/// `spectralBuffer` (no per-channel copy needed). When `fanOut !=
|
||
/// nil`, each entry is an independent `SpectralBuffer`
|
||
/// written by `fanOut.process(source:into:channel:)`.
|
||
private let _destinations: [SpectralBuffer]
|
||
|
||
// MARK: - Synthesis-side state (one set per output channel)
|
||
|
||
private let _fftSetup: FFTSetup
|
||
private let _synthesisWindow: [Float]
|
||
private let _ringSize: Int
|
||
private let _ringMask: Int
|
||
|
||
/// Per-channel synthesis scratch + overlap-add. Allocated only
|
||
/// when `!analyzeOnly`. Each pointer addresses `halfSize` floats
|
||
/// (work realp / imagp) or `fftSize` floats (timeDomainBuf /
|
||
/// overlapBuf), one set per output channel.
|
||
private let _workRealps: [UnsafeMutablePointer<Float>]
|
||
private let _workImagps: [UnsafeMutablePointer<Float>]
|
||
private let _timeDomainBufs: [UnsafeMutablePointer<Float>]
|
||
private let _overlapBufs: [UnsafeMutablePointer<Float>]
|
||
private var _outputRings: [[Float]]
|
||
private var _outputRingWritePos: [Int]
|
||
private var _outputRingReadPos: [Int]
|
||
private var _synthesisHopCounter: Int = 0
|
||
private let _mulAdd: MulAddSpec
|
||
|
||
// MARK: - Init
|
||
|
||
/// - Parameters:
|
||
/// - input: Audio-rate input signal. Any `ValidGeneratorInput`.
|
||
/// - fftSize: FFT frame size. Power of two ≥ 4. Default 2048.
|
||
/// - hopSize: Samples between FFT hops. In `[1, fftSize]`.
|
||
/// Default 512.
|
||
/// - analysisWindow: Optional window of length `fftSize` applied
|
||
/// before each forward FFT. Pass `nil` to use
|
||
/// `LyrebirdBuffer.sineWindow(size:)` which satisfies WOLA
|
||
/// COLA at both 50% and 75% overlap when paired with the
|
||
/// default synthesis window.
|
||
/// - synthesisWindow: Optional window of length `fftSize`
|
||
/// applied to each IFFT frame before overlap-add. Pass `nil`
|
||
/// to reuse the analysis window. Pre-scaled by the WOLA
|
||
/// normalisation factor internally.
|
||
/// - stages: Ordered ``SpectralStage`` pipeline applied to the
|
||
/// chain's `spectralBuffer` after each FFT hop. `.mono(_)`
|
||
/// runs a single-input transform; `.dual(_, sideChain:)`
|
||
/// runs a cross-synthesis transform reading from the named
|
||
/// sidechain (sidechains must share `fftSize` and `hopSize`).
|
||
/// Default empty.
|
||
/// - fanOut: Optional mono→N processor that allocates and
|
||
/// populates N destination spectral buffers from the
|
||
/// post-stages `spectralBuffer`. Terminal — runs after all
|
||
/// `stages`, before the IFFT bank. When `nil`, the chain has
|
||
/// one output channel; when non-nil, the chain has
|
||
/// `fanOut.outputChannelCount` output channels. Default `nil`.
|
||
/// - analyzeOnly: When `true`, skip all IFFT resynthesis. The
|
||
/// audio output is silent (mono); the source spectral buffer
|
||
/// is still populated each hop. Used by feature extractors
|
||
/// and sidechain analyses. Default `false`.
|
||
/// - mul: Output multiplier applied after synthesis. Default 1.
|
||
/// - add: Output offset added after multiplier. Default 0.
|
||
public convenience init(
|
||
input: any ValidGeneratorInput,
|
||
fftSize: Int = 2048,
|
||
hopSize: Int = 512,
|
||
analysisWindow: [Float]? = nil,
|
||
synthesisWindow: [Float]? = nil,
|
||
stages: [SpectralStage] = [],
|
||
fanOut: (any SpectralFanOutProcessor)? = nil,
|
||
analyzeOnly: Bool = false,
|
||
mul: any ValidGeneratorInput = 1.0,
|
||
add: any ValidGeneratorInput = 0.0
|
||
) {
|
||
self.init(
|
||
input: input,
|
||
spectralSource: nil,
|
||
fftSize: fftSize,
|
||
hopSize: hopSize,
|
||
analysisWindow: analysisWindow,
|
||
synthesisWindow: synthesisWindow,
|
||
stages: stages,
|
||
fanOut: fanOut,
|
||
analyzeOnly: analyzeOnly,
|
||
mul: mul,
|
||
add: add
|
||
)
|
||
}
|
||
|
||
/// SynthOnly init — reads spectral frames from an external
|
||
/// ``SpectralBufferGenerator`` (e.g. ``SpectralBufferRead`` or
|
||
/// ``SpectralPlayBuffer``) instead of running a forward FFT on an
|
||
/// audio input. The chain dispatches the registered `stages` on
|
||
/// the source's `spectralBuffer` each hop, then runs the IFFT bank.
|
||
///
|
||
/// > **Hop-alignment constraint:** engine `blockSize` must be
|
||
/// > `<= hopSize`. The chain pulls the source once per
|
||
/// > `_computeSamples` call; if `count > hopSize`, multiple source
|
||
/// > hops would fire and overwrite each other in the aliased
|
||
/// > `spectralBuffer`, dropping frames. A runtime precondition in
|
||
/// > `_computeSamples` enforces this. For typical configurations
|
||
/// > (`fftSize=2048, hopSize=512`, engine `blockSize=64..512`) this
|
||
/// > holds automatically.
|
||
///
|
||
/// - Parameters:
|
||
/// - spectralSource: Generator that owns and populates a
|
||
/// `SpectralBuffer` each hop. `spectralSource.hopSize`
|
||
/// must equal `hopSize`; `spectralSource.spectralBuffer.fftSize`
|
||
/// must equal `fftSize`.
|
||
/// - fftSize: FFT frame size. Power of two ≥ 4. Default 2048.
|
||
/// - hopSize: Samples between hops. In `[1, fftSize]`. Default 512.
|
||
/// - synthesisWindow: Optional window of length `fftSize`. Pass
|
||
/// `nil` to use `LyrebirdBuffer.sineWindow(size:)`.
|
||
/// - stages: Ordered ``SpectralStage`` pipeline applied after each
|
||
/// hop. See the audio-input init for details. Default empty.
|
||
/// - fanOut: Optional terminal mono→N processor. Default `nil`.
|
||
/// - mul: Output multiplier. Default 1.
|
||
/// - add: Output offset. Default 0.
|
||
public convenience init(
|
||
spectralSource: any SpectralBufferGenerator,
|
||
fftSize: Int = 2048,
|
||
hopSize: Int = 512,
|
||
synthesisWindow: [Float]? = nil,
|
||
stages: [SpectralStage] = [],
|
||
fanOut: (any SpectralFanOutProcessor)? = nil,
|
||
mul: any ValidGeneratorInput = 1.0,
|
||
add: any ValidGeneratorInput = 0.0
|
||
) {
|
||
self.init(
|
||
input: 0.0 as Double,
|
||
spectralSource: spectralSource,
|
||
fftSize: fftSize,
|
||
hopSize: hopSize,
|
||
analysisWindow: nil,
|
||
synthesisWindow: synthesisWindow,
|
||
stages: stages,
|
||
fanOut: fanOut,
|
||
analyzeOnly: false,
|
||
mul: mul,
|
||
add: add
|
||
)
|
||
}
|
||
|
||
// MARK: - Designated init
|
||
|
||
private init(
|
||
input: any ValidGeneratorInput,
|
||
spectralSource: (any SpectralBufferGenerator)?,
|
||
fftSize: Int,
|
||
hopSize: Int,
|
||
analysisWindow: [Float]?,
|
||
synthesisWindow: [Float]?,
|
||
stages: [SpectralStage],
|
||
fanOut: (any SpectralFanOutProcessor)?,
|
||
analyzeOnly: Bool,
|
||
mul: any ValidGeneratorInput,
|
||
add: any ValidGeneratorInput
|
||
) {
|
||
precondition(fftSize >= 4 && (fftSize & (fftSize - 1)) == 0,
|
||
"SpectralChain.Audio: fftSize must be a power of two >= 4")
|
||
precondition(hopSize > 0 && hopSize <= fftSize,
|
||
"SpectralChain.Audio: hopSize must be in 1...fftSize")
|
||
for case .dual(_, let sideChain) in stages {
|
||
precondition(sideChain.fftSize == fftSize,
|
||
"SpectralChain.Audio: sidechain fftSize must match")
|
||
precondition(sideChain.hopSize == hopSize,
|
||
"SpectralChain.Audio: sidechain hopSize must match")
|
||
}
|
||
if let source: any SpectralBufferGenerator = spectralSource {
|
||
precondition(!analyzeOnly,
|
||
"SpectralChain.Audio: spectralSource is incompatible with analyzeOnly")
|
||
precondition(source.hopSize == hopSize,
|
||
"SpectralChain.Audio: spectralSource.hopSize must match host hopSize")
|
||
precondition(source.spectralBuffer.fftSize == fftSize,
|
||
"SpectralChain.Audio: spectralSource buffer fftSize must match host fftSize")
|
||
}
|
||
|
||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||
self.inputSource = resolvedInput
|
||
self.inputIsGenerator = resolvedInput is any Generator
|
||
self._spectralSource = spectralSource
|
||
self.fftSize = fftSize
|
||
self.hopSize = hopSize
|
||
self.halfSize = fftSize / 2
|
||
self.fftMask = fftSize - 1
|
||
self.log2n = vDSP_Length(fftSize.trailingZeroBitCount)
|
||
self.stages = stages
|
||
self.fanOut = fanOut
|
||
self.analyzeOnly = analyzeOnly
|
||
|
||
// Output channel count: 1 in analyze-only or no-fanOut path,
|
||
// fanOut's declared count otherwise.
|
||
let channelCount: Int
|
||
if analyzeOnly {
|
||
channelCount = 1
|
||
} else if let fanOut: any SpectralFanOutProcessor {
|
||
channelCount = fanOut.outputChannelCount
|
||
precondition(channelCount >= 1,
|
||
"SpectralChain.Audio: fanOut.outputChannelCount must be >= 1")
|
||
} else {
|
||
channelCount = 1
|
||
}
|
||
self._outputChannelCount = channelCount
|
||
|
||
// Analysis-side allocations. SynthOnly mode aliases the source's
|
||
// spectralBuffer and skips the forward FFT scratch.
|
||
if let source: any SpectralBufferGenerator = spectralSource {
|
||
self.spectralBuffer = source.spectralBuffer
|
||
self._inputRing = []
|
||
self._windowedBuf = []
|
||
self._fftAnalysisRealp = nil
|
||
self._fftAnalysisImagp = nil
|
||
self.analysisWindow = []
|
||
} else {
|
||
self.spectralBuffer = SpectralBuffer(fftSize: fftSize)
|
||
self._inputRing = [Float](repeating: 0, count: fftSize)
|
||
self._windowedBuf = [Float](repeating: 0, count: fftSize)
|
||
|
||
let anaRealp: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||
let anaImagp: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||
anaRealp.initialize(repeating: 0, count: halfSize)
|
||
anaImagp.initialize(repeating: 0, count: halfSize)
|
||
self._fftAnalysisRealp = anaRealp
|
||
self._fftAnalysisImagp = anaImagp
|
||
|
||
let analysisWin: [Float]
|
||
if let w: [Float] = analysisWindow {
|
||
precondition(w.count == fftSize,
|
||
"SpectralChain.Audio: analysisWindow length must equal fftSize")
|
||
analysisWin = w
|
||
} else {
|
||
analysisWin = LyrebirdBuffer.sineWindow(size: fftSize)
|
||
}
|
||
self.analysisWindow = analysisWin
|
||
}
|
||
|
||
// Destination buffers. Source aliasing for the no-fanOut +
|
||
// non-analyzeOnly case avoids an unnecessary per-hop copy.
|
||
if fanOut == nil || analyzeOnly {
|
||
self._destinations = [spectralBuffer]
|
||
} else {
|
||
var dests: [SpectralBuffer] = []
|
||
dests.reserveCapacity(channelCount)
|
||
for _ in 0..<channelCount {
|
||
dests.append(SpectralBuffer(fftSize: fftSize))
|
||
}
|
||
self._destinations = dests
|
||
}
|
||
|
||
// Shared FFT setup (same fftSize for all channels).
|
||
guard let setup: FFTSetup = vDSP_create_fftsetup(log2n, FFTRadix(kFFTRadix2)) else {
|
||
fatalError("SpectralChain.Audio: failed to create FFT setup")
|
||
}
|
||
self._fftSetup = setup
|
||
|
||
// Synthesis window: pre-scaled by WOLA normalisation
|
||
// (1 / (2N × Σ w²[n] / hopSize)) so a single vDSP_vmul in the
|
||
// IFFT path handles windowing + gain correction. When
|
||
// analyzeOnly we never use this; allocate as empty.
|
||
let ringFactor: Int = 2
|
||
let ringSize: Int = ringFactor * fftSize
|
||
precondition((ringSize & (ringSize - 1)) == 0,
|
||
"SpectralChain.Audio: ringSize must be a power of two")
|
||
self._ringSize = ringSize
|
||
self._ringMask = ringSize - 1
|
||
|
||
if analyzeOnly {
|
||
self._synthesisWindow = []
|
||
self._workRealps = []
|
||
self._workImagps = []
|
||
self._timeDomainBufs = []
|
||
self._overlapBufs = []
|
||
self._outputRings = []
|
||
self._outputRingWritePos = []
|
||
self._outputRingReadPos = []
|
||
} else {
|
||
var synth: [Float]
|
||
if let w: [Float] = synthesisWindow {
|
||
precondition(w.count == fftSize,
|
||
"SpectralChain.Audio: synthesisWindow length must equal fftSize")
|
||
synth = w
|
||
} else if spectralSource != nil {
|
||
synth = LyrebirdBuffer.sineWindow(size: fftSize)
|
||
} else {
|
||
synth = self.analysisWindow
|
||
}
|
||
var sqSum: Float = 0
|
||
synth.withUnsafeBufferPointer { ptr in
|
||
guard let base: UnsafePointer<Float> = ptr.baseAddress else { return }
|
||
vDSP_dotpr(base, 1, base, 1, &sqSum, vDSP_Length(fftSize))
|
||
}
|
||
let olaSqSum: Float = sqSum / Float(hopSize)
|
||
var wScale: Float = 1.0 / (Float(2 * fftSize) * olaSqSum)
|
||
synth.withUnsafeMutableBufferPointer { ptr in
|
||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||
vDSP_vsmul(base, 1, &wScale, base, 1, vDSP_Length(fftSize))
|
||
}
|
||
self._synthesisWindow = synth
|
||
|
||
var workRealps: [UnsafeMutablePointer<Float>] = []
|
||
var workImagps: [UnsafeMutablePointer<Float>] = []
|
||
var timeDomainBufs: [UnsafeMutablePointer<Float>] = []
|
||
var overlapBufs: [UnsafeMutablePointer<Float>] = []
|
||
workRealps.reserveCapacity(channelCount)
|
||
workImagps.reserveCapacity(channelCount)
|
||
timeDomainBufs.reserveCapacity(channelCount)
|
||
overlapBufs.reserveCapacity(channelCount)
|
||
for _ in 0..<channelCount {
|
||
let r: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||
let i: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: halfSize)
|
||
let t: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fftSize)
|
||
let o: UnsafeMutablePointer<Float> = UnsafeMutablePointer<Float>.allocate(capacity: fftSize)
|
||
r.initialize(repeating: 0, count: halfSize)
|
||
i.initialize(repeating: 0, count: halfSize)
|
||
t.initialize(repeating: 0, count: fftSize)
|
||
o.initialize(repeating: 0, count: fftSize)
|
||
workRealps.append(r)
|
||
workImagps.append(i)
|
||
timeDomainBufs.append(t)
|
||
overlapBufs.append(o)
|
||
}
|
||
self._workRealps = workRealps
|
||
self._workImagps = workImagps
|
||
self._timeDomainBufs = timeDomainBufs
|
||
self._overlapBufs = overlapBufs
|
||
|
||
self._outputRings = [[Float]](
|
||
repeating: [Float](repeating: 0, count: ringSize),
|
||
count: channelCount
|
||
)
|
||
self._outputRingWritePos = [Int](repeating: 0, count: channelCount)
|
||
// Read pointer starts hopSize behind write so block 0 emits
|
||
// silence and block 1 reads the first IFFT output written
|
||
// at the end of block 0 — one-hop inherent latency.
|
||
self._outputRingReadPos = [Int](
|
||
repeating: ringSize - hopSize,
|
||
count: channelCount
|
||
)
|
||
}
|
||
|
||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||
super.init(channels: channelCount)
|
||
}
|
||
|
||
deinit {
|
||
if let realp: UnsafeMutablePointer<Float> = _fftAnalysisRealp {
|
||
realp.deinitialize(count: halfSize)
|
||
realp.deallocate()
|
||
}
|
||
if let imagp: UnsafeMutablePointer<Float> = _fftAnalysisImagp {
|
||
imagp.deinitialize(count: halfSize)
|
||
imagp.deallocate()
|
||
}
|
||
for c: Int in 0..<_workRealps.count {
|
||
_workRealps[c].deinitialize(count: halfSize)
|
||
_workRealps[c].deallocate()
|
||
_workImagps[c].deinitialize(count: halfSize)
|
||
_workImagps[c].deallocate()
|
||
_timeDomainBufs[c].deinitialize(count: fftSize)
|
||
_timeDomainBufs[c].deallocate()
|
||
_overlapBufs[c].deinitialize(count: fftSize)
|
||
_overlapBufs[c].deallocate()
|
||
}
|
||
vDSP_destroy_fftsetup(_fftSetup)
|
||
}
|
||
|
||
// MARK: - Generator protocol
|
||
|
||
public func floatValue(graph: SynthGraph) -> Double {
|
||
calculatedSamples(graph: graph, count: graph.engine.blockSize)
|
||
.first?.first ?? 0
|
||
}
|
||
|
||
public func _computeSamples(
|
||
graph: SynthGraph,
|
||
count: Int
|
||
) -> [[Double]] {
|
||
_checkCount(count)
|
||
|
||
// Drive sidechain analyses so their spectralBuffers are current
|
||
// before our hop dispatches the `.dual` stages. Their fan-out
|
||
// cache makes the call cheap when another consumer already
|
||
// pulled them this block.
|
||
for case .dual(_, let sideChain) in stages {
|
||
_ = sideChain.calculatedSamples(graph: graph, count: count)
|
||
}
|
||
|
||
// Resolve input or spectralSource once outside the per-sample loop.
|
||
let inputSamples: [Double]?
|
||
let scalarInput: Double
|
||
let isSynthOnly: Bool = _spectralSource != nil
|
||
if let source: any SpectralBufferGenerator = _spectralSource {
|
||
// SynthOnly invariant: at most one hop fires per chain call.
|
||
// If `count > hopSize`, the source's _runHop overwrites
|
||
// spectralBuffer multiple times within the block and the chain
|
||
// only reads the final frame — earlier frames silently drop.
|
||
// Enforce `count <= hopSize` so the chain + source hop counters
|
||
// never advance past one boundary per call. The init also
|
||
// requires `hopSize >= lyrebirdDefaultResultBufferSize` for the
|
||
// spectralSource path so engine block sizes up to the
|
||
// pre-allocated maximum are safe.
|
||
precondition(count <= hopSize,
|
||
"SpectralChain.Audio (synthOnly): count must be <= hopSize")
|
||
// Drive the source so its spectralBuffer is current for this
|
||
// block. The chain reads from it at hop boundaries below.
|
||
_ = source.calculatedSamples(graph: graph, count: count)
|
||
inputSamples = nil
|
||
scalarInput = 0
|
||
} else if inputIsGenerator {
|
||
inputSamples = inputSource.calculatedSamples(graph: graph, count: count).first
|
||
scalarInput = 0
|
||
} else {
|
||
inputSamples = nil
|
||
scalarInput = inputSource.floatValue(graph: graph)
|
||
}
|
||
|
||
let runSynthesis: Bool = !analyzeOnly
|
||
let nch: Int = _outputChannelCount
|
||
|
||
for i: Int in 0..<count {
|
||
if !isSynthOnly {
|
||
// Push the new input sample into the analysis ring.
|
||
let sample: Float = Float(inputSamples?[i] ?? scalarInput)
|
||
_inputRing[_ringWritePos] = sample
|
||
_ringWritePos = (_ringWritePos + 1) & fftMask
|
||
}
|
||
|
||
// Advance analysis-side hopCounter; trigger FFT hop (when
|
||
// not synthOnly) + processor dispatch + fan-out at the
|
||
// boundary.
|
||
_analysisHopCounter += 1
|
||
if _analysisHopCounter >= hopSize {
|
||
_runAnalysisHop(engine: graph.engine)
|
||
_analysisHopCounter = 0
|
||
}
|
||
|
||
if runSynthesis {
|
||
// Advance synthesis-side hopCounter; trigger IFFT bank
|
||
// at the same hop boundary.
|
||
_synthesisHopCounter += 1
|
||
if _synthesisHopCounter >= hopSize {
|
||
_runIFFTBank()
|
||
_synthesisHopCounter = 0
|
||
}
|
||
// Per-channel output read.
|
||
for c: Int in 0..<nch {
|
||
_result[c][i] = Double(_outputRings[c][_outputRingReadPos[c]])
|
||
_outputRingReadPos[c] = (_outputRingReadPos[c] + 1) & _ringMask
|
||
}
|
||
} else {
|
||
_result[0][i] = 0
|
||
}
|
||
}
|
||
|
||
if runSynthesis {
|
||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||
}
|
||
return _result
|
||
}
|
||
|
||
// MARK: - Analysis hop
|
||
|
||
private func _runAnalysisHop(engine: SynthesisEngine) {
|
||
// SynthOnly mode: the source generator has already populated
|
||
// `spectralBuffer` (aliased to source.spectralBuffer) during
|
||
// its own _computeSamples earlier this block. Skip the forward
|
||
// FFT and run the processor / fan-out dispatch directly on it.
|
||
if _spectralSource == nil,
|
||
let realp: UnsafeMutablePointer<Float> = _fftAnalysisRealp,
|
||
let imagp: UnsafeMutablePointer<Float> = _fftAnalysisImagp {
|
||
// Window the oldest fftSize samples from the input ring into
|
||
// the windowed scratch buffer.
|
||
let readStart: Int = _ringWritePos
|
||
for k: Int in 0..<fftSize {
|
||
_windowedBuf[k] = _inputRing[(readStart + k) & fftMask] * analysisWindow[k]
|
||
}
|
||
|
||
// Forward real FFT into private split-complex work arrays.
|
||
_windowedBuf.withUnsafeBufferPointer { wPtr in
|
||
guard let wBase: UnsafePointer<Float> = wPtr.baseAddress else { return }
|
||
wBase.withMemoryRebound(to: DSPComplex.self, capacity: halfSize) { complexPtr in
|
||
var split: DSPSplitComplex = DSPSplitComplex(realp: realp, imagp: imagp)
|
||
vDSP_ctoz(complexPtr, 2, &split, 1, vDSP_Length(halfSize))
|
||
vDSP_fft_zrip(_fftSetup, &split, 1, log2n,
|
||
FFTDirection(kFFTDirection_Forward))
|
||
}
|
||
}
|
||
|
||
// Convert split-complex rectangular → polar in the source
|
||
// spectral buffer (one conversion per hop, amortised across
|
||
// all processors in the chain).
|
||
spectralBuffer._writeFromRectangular(realp, imagp: imagp)
|
||
}
|
||
|
||
// Run the ordered stage pipeline. The enum dispatch avoids a second
|
||
// array walk (vs. the prior two-array layout) and is RT-safe: tag
|
||
// check + payload deref only, no `as?` / `is` on the audio thread.
|
||
// The witness-table call into the wrapped processor is unchanged
|
||
// from the prior shape.
|
||
for stage: SpectralStage in stages {
|
||
switch stage {
|
||
case .mono(let processor):
|
||
processor.process(spectral: spectralBuffer, engine: engine)
|
||
case .dual(let processor, let sideChain):
|
||
processor.process(
|
||
spectral: spectralBuffer,
|
||
sideChain: sideChain.spectralBuffer,
|
||
engine: engine
|
||
)
|
||
}
|
||
}
|
||
|
||
// Fan-out: populate per-channel destinations. When fanOut == nil
|
||
// or analyzeOnly, _destinations[0] aliases spectralBuffer at init
|
||
// and nothing more is needed. When fanOut != nil, destinations
|
||
// are independent buffers — even a single-channel fan-out
|
||
// conformer must run process() to populate the destination.
|
||
if let fanOut: any SpectralFanOutProcessor, !analyzeOnly {
|
||
for c: Int in 0..<_destinations.count {
|
||
fanOut.process(
|
||
source: spectralBuffer,
|
||
into: _destinations[c],
|
||
channel: c
|
||
)
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - IFFT bank
|
||
|
||
private func _runIFFTBank() {
|
||
for c: Int in 0..<_outputChannelCount {
|
||
_runIFFT(channel: c)
|
||
}
|
||
}
|
||
|
||
private func _runIFFT(channel c: Int) {
|
||
let realp: UnsafeMutablePointer<Float> = _workRealps[c]
|
||
let imagp: UnsafeMutablePointer<Float> = _workImagps[c]
|
||
let timeDomainBuf: UnsafeMutablePointer<Float> = _timeDomainBufs[c]
|
||
let overlapBuf: UnsafeMutablePointer<Float> = _overlapBufs[c]
|
||
let source: SpectralBuffer = _destinations[c]
|
||
|
||
// Polar → split-complex rectangular into the per-channel
|
||
// work arrays. Bypassed magnitudes from earlier processors
|
||
// and any fanOut-written destination spectrum are honoured.
|
||
source._readToRectangular(realp: realp, imagp: imagp)
|
||
|
||
var split: DSPSplitComplex = DSPSplitComplex(realp: realp, imagp: imagp)
|
||
vDSP_fft_zrip(_fftSetup, &split, 1, log2n,
|
||
FFTDirection(kFFTDirection_Inverse))
|
||
|
||
// Unpack split-complex back to interleaved real (fftSize floats).
|
||
let n: Int = halfSize
|
||
timeDomainBuf.withMemoryRebound(to: DSPComplex.self, capacity: n) { complexPtr in
|
||
vDSP_ztoc(&split, 1, complexPtr, 2, vDSP_Length(n))
|
||
}
|
||
|
||
// Window + WOLA-normalise in one vDSP_vmul.
|
||
_synthesisWindow.withUnsafeBufferPointer { wPtr in
|
||
guard let wBase: UnsafePointer<Float> = wPtr.baseAddress else { return }
|
||
vDSP_vmul(timeDomainBuf, 1, wBase, 1, timeDomainBuf, 1, vDSP_Length(fftSize))
|
||
}
|
||
|
||
// Overlap-add: accumulate into overlapBuf.
|
||
vDSP_vadd(overlapBuf, 1, timeDomainBuf, 1, overlapBuf, 1, vDSP_Length(fftSize))
|
||
|
||
// Write the oldest hopSize samples into the output ring.
|
||
let writePos: Int = _outputRingWritePos[c]
|
||
for k: Int in 0..<hopSize {
|
||
_outputRings[c][(writePos + k) & _ringMask] = overlapBuf[k]
|
||
}
|
||
_outputRingWritePos[c] = (writePos + hopSize) & _ringMask
|
||
|
||
// Shift overlapBuf left by hopSize (memmove — non-allocating).
|
||
let tail: Int = fftSize - hopSize
|
||
memmove(overlapBuf, overlapBuf.advanced(by: hopSize),
|
||
tail * MemoryLayout<Float>.stride)
|
||
for k: Int in tail..<fftSize {
|
||
overlapBuf[k] = 0
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// GeneratorEnum conformance intentionally omitted — Audio-only.
|