26 KiB
Spectral Processing
FFT / IFFT infrastructure using Accelerate/vDSP with a polar-primary buffer. The analysis + processor + IFFT pipeline is consolidated into one SpectralChain.Audio Generator. The legacy FFTAnalysis + IFFTSynthesis generators have been removed entirely; a synthOnly mode drives the IFFT bank from an external SpectralBufferGenerator (e.g. SpectralBufferRead, SpectralPlayBuffer).
Overview
| Layer | Type | Role |
|---|---|---|
SpectralBuffer |
Data container | Polar (magnitude + phase) FFT frame |
SpectralChain.Audio |
AudioGenerator |
Consolidated STFT pipeline: forward FFT → processor chain → optional sidechain → optional fan-out → N × IFFT. Four modes. |
SpectralProcessor |
Protocol | In-place polar transform called after each FFT hop |
SpectralProcessor2 |
Protocol | Two-input processor (cross-synthesis / sidechain) |
SpectralFanOutProcessor |
Protocol | Mono → N decorrelation processor (writes per-channel destination buffers) |
SpectralBufferGenerator |
Protocol | A Generator that owns + populates its own spectralBuffer each hop; drives synthOnly mode of SpectralChain.Audio |
SpectralBufferRead |
SpectralBufferGenerator |
Random-access frame playback via normalized position |
SpectralPlayBuffer |
SpectralBufferGenerator |
Phase-vocoder playback with time-stretch |
SpectralChain.Audio — four operating modes
// 1. Mono resynthesis — audio in, audio out:
let chain = SpectralChain.Audio(
input: signal,
fftSize: 2048,
hopSize: 512,
stages: [.mono(SpectralDiffuse(fftSize: 2048, amount: 0.5))]
)
output(bus: 0, source: chain)
// 2. Mono → N fan-out (stereo decorrelation example):
let diffuser = SpectralStereoDiffuse(amount: 0.8)
let stereoChain = SpectralChain.Audio(
input: monoIn,
fftSize: 2048,
fanOut: diffuser
)
output(bus: 0, source: stereoChain[0])
output(bus: 1, source: stereoChain[1])
// 3. Analyze-only for feature extraction or sidechain:
let analysisOnly = SpectralChain.Audio(
input: signal,
fftSize: 2048,
analyzeOnly: true
)
let centroid = SpectralCentroid.Control(analysis: analysisOnly,
sampleRate: engine.sampleRate)
// 4. SynthOnly — IFFT bank driven by a pre-analysed frame buffer:
let player = SpectralPlayBuffer(frameBuffer: frames, fftSize: 2048, hopSize: 512)
let synth = SpectralChain.Audio(spectralSource: player,
fftSize: 2048, hopSize: 512)
output(bus: 0, source: synth)
Mono → N decorrelation
SpectralFanOutProcessor is a processor shape that reads the source spectral buffer (post-SpectralProcessor chain) and writes a full polar spectrum into each of N destination buffers. The host SpectralChain.Audio then runs N IFFTs to produce N audio output channels.
SpectralStereoDiffuse is the first conformer. Mono → stereo. Magnitudes pass through unchanged. Phases blend toward independent per-channel uniform random targets via shortest-angular-distance interpolation. Channels 0 and 1 draw from anti-correlated xorshift64 streams (seeded from seed and seed ^ spectralStereoDiffuseAntiSeedMask).
let diff = SpectralStereoDiffuse(amount: 0.8, seed: 0xDEADBEEF)
let chain = SpectralChain.Audio(input: monoIn, fftSize: 2048, fanOut: diff)
amount == 0is exact bypass; both output channels equal the input.amount == 1is full per-channel randomisation, producing a wide decorrelated stereo image with magnitude conserved per bin.- Magnitude conservation guarantees per-channel energy is preserved; summing L + R does not reconstruct the input (the random phase realisations interfere).
Conversion flow per hop (non-synthOnly modes)
SpectralChain.Audio._runAnalysisHop()
vDSP_fft_zrip (forward) → private _fftAnalysisRealp/Imagp
_writeFromRectangular → spectralBuffer (polar: mag + phase)
[Processor chain — all in polar]
[Optional fan-out: SpectralFanOutProcessor → per-channel destinations]
SpectralChain.Audio._runIFFTBank() (one IFFT per output channel)
_readToRectangular → per-channel work arrays
vDSP_fft_zrip (inverse) + WOLA overlap-add → per-channel audio output
In synthOnly mode, _runAnalysisHop skips windowing + forward FFT + polar conversion; the source SpectralBufferGenerator has already populated spectralBuffer during its own _computeSamples. Registered processors and fan-out run as usual on the source's buffer, then the IFFT bank resynthesises.
vDSP normalization
vDSP forward real FFT multiplies output by 2 (Apple convention). After rect→polar conversion, dcValue reflects this:
buf.dcValue ≈ 2 × Σ window[n] × input[n]
The synthesis-side WOLA normalisation factor 1 / (2N × Σ w²[n] / hopSize) is pre-multiplied into the synthesis window at init, so a single vDSP_vmul in the IFFT path handles windowing + gain correction. Round-trip unity gain holds at any integer overlap ratio with the default sine window.
Latency
Output is delayed by exactly hopSize samples (one hop). Block 0 outputs silence; block 1 outputs the first IFFT result.
Precision note
Polar conversion uses vDSP_zvmags + vvsqrtf + vvatan2f; the inverse path uses vvcosf + vvsinf + vDSP_vmul. The round-trip introduces ~1e-7 float error per hop — inaudible in practice. Pass-through with no processors is not bit-exact with raw rectangular processing.
SpectralBuffer
Holds one FFT frame in polar form: magnitudes and phases stored as UnsafeMutablePointer<Float> — addresses are stable for the object's lifetime, no Swift Array CoW.
DC and Nyquist are purely real (no meaningful phase); they are stored as signed scalars and accessed via properties, not subscripts.
let buf = SpectralBuffer(fftSize: 2048)
// DC and Nyquist — signed scalars
buf.dcValue // signed DC (may be negative)
buf.dcValue = -3.0 // set directly
buf.nyquistValue // signed Nyquist
buf.nyquistValue = 2.5
// Complex bins k = 1 ..< fftSize/2
buf[magnitude: k] // magnitude of bin k (≥ 0)
buf[magnitude: k] = 5.0 // set magnitude
buf[phase: k] // phase of bin k (radians, in (−π, π])
buf[phase: k] = Float.pi / 4
// Convenience — works for all bins including DC (0) and Nyquist (fftSize/2)
buf.magnitude(at: 0) // abs(dcValue)
buf.magnitude(at: 1024) // abs(nyquistValue) — Nyquist bin for fftSize=2048
buf.magnitude(at: k) // _mag[k] for complex bins
buf.phase(at: k)
buf.setMagnitude(1.0, at: k)
buf.invalidate() // non-RT — signals the chain to output silence
Buffer layout
For fftSize = N:
| Accessor | Content |
|---|---|
dcValue |
Signed DC component |
[magnitude: k], [phase: k] for k=1..N/2-1 |
Complex bin k |
nyquistValue |
Signed Nyquist component |
SpectralProcessor protocol
public protocol SpectralProcessor: AnyObject {
func process(spectral: SpectralBuffer, engine: SynthesisEngine)
}
process is called on the RT thread from inside SpectralChain.Audio._runAnalysisHop. Implementations must not allocate memory or acquire locks. The buffer is in polar form — read magnitudes and phases directly, modify in-place.
engine is the host engine. Processors that hold RTBufferSlot-backed parameter buffers (e.g. SpectralBinDelay, SpectralMagnitudeMap) use it to push displaced retains to engine.bufferSwapKillQueue from the RT thread. Processors with no swappable state can ignore the parameter.
For vDSP batch operations on complex bins, use the package-internal helpers:
// Inside a SpectralProcessor implementation:
spectral.withUnsafeMutableMagnitudePointer { mp in
// mp points to _mag[1] — valid for fftSize/2-1 elements (bins 1..halfSize-1)
vDSP_vsmul(mp, 1, &scale, mp, 1, vDSP_Length(spectral.fftSize / 2 - 1))
}
spectral.withUnsafeMutablePhasePointer { pp in
// pp points to _phase[1] — same element count
}
SpectralFanOutProcessor protocol
public protocol SpectralFanOutProcessor: AnyObject {
var outputChannelCount: Int { get }
func process(source: SpectralBuffer,
into: SpectralBuffer,
channel: Int)
}
Called once per output channel by the host SpectralChain.Audio after the SpectralProcessor chain has run. The source buffer is read-only from the fan-out's perspective (any single-input processor that needed to mutate it has already done so); the destination buffer is per-channel scratch that the host's IFFT bank then reads.
SpectralBufferGenerator protocol
public protocol SpectralBufferGenerator: Generator {
var spectralBuffer: SpectralBuffer { get }
var hopSize: Int { get }
}
A Generator that owns + populates its own spectralBuffer each hop. Built-in conformers: SpectralBufferRead (random-access frame playback by normalized position), SpectralPlayBuffer (phase-vocoder frame playback with time-stretch). Use as spectralSource: arg of SpectralChain.Audio to drive synthOnly mode.
Both source and host chain advance internal sample-by-sample hop counters from 0 at construction. Matching hopSize keeps them aligned within an audio block. A precondition in SpectralChain.Audio.init catches hopSize / fftSize mismatches at construction time.
Built-in processors
SpectralMagnitudeScale
Multiplies all bin magnitudes (including DC and Nyquist) by a constant factor.
let chain = SpectralChain.Audio(input: sig,
stages: [.mono(SpectralMagnitudeScale(scale: 0.5))])
output(bus: 0, source: chain)
SpectralFreeze
Phase-vocoder freeze: captures magnitudes and phases, then advances each bin's phase by its locked instantaneous delta on every frozen hop.
let freeze = SpectralFreeze(fftSize: 2048)
let chain = SpectralChain.Audio(input: sig, stages: [.mono(freeze)])
output(bus: 0, source: chain)
// To freeze (call from non-RT thread):
freeze.freeze()
// To unfreeze:
freeze.unfreeze()
freeze() sets an Atomic<Bool> flag; the RT thread captures the polar frame (magnitude + phase) on the next hop — no rect→polar conversion needed since the buffer already stores polar data.
OnsetDetector
Per-hop onset detector. Computes an onset-detection function (ODF) — either half-wave-rectified spectral flux or complex-domain prediction error — on every FFT hop, smooths the ODF with a rolling median to derive an adaptive threshold, and increments an atomic onset counter when the latest ODF exceeds max(rollingMedian, floor) * threshold. A configurable refractory window (minHopsBetweenOnsets) suppresses double-triggering on the tail of an attack.
OnsetDetector itself is a SpectralProcessor; pair it with an OnsetDetector.Control generator to surface the detected onsets as a trigger signal. OnsetDetector.Control emits a single-sample pulse at sample 0 of any audio block during which one or more onsets fired (zero otherwise) — guaranteeing a clean ≤0 → >0 edge for downstream SendTrigger.Control even on back-to-back onset blocks.
let detector = OnsetDetector(
fftSize: 2048,
hopSize: 512,
method: .spectralFlux, // .complexDomain for soft / pitched onsets
threshold: 1.5,
medianWindowFrames: 7,
minHopsBetweenOnsets: 3
)
let chain = SpectralChain.Audio(
input: micIn, fftSize: 2048, hopSize: 512,
stages: [.mono(detector)], analyzeOnly: true
)
let trig = OnsetDetector.Control(detector: detector, analysis: chain)
addOutputGenerator(SendTrigger.Control(trig: trig, id: 1))
threshold and minHopsBetweenOnsets are backed by Atomic storage and may be tuned from a non-RT thread at any time. lastODF and lastMedian expose the most recent RT-side telemetry for visualisation. Reference: Bello et al., "A Tutorial on Onset Detection in Music Signals", IEEE TSAP 2005.
Spectral Filtering & Phase
A family of bin-domain processors for filtering, EQ, phase manipulation, and magnitude smearing. All operate directly on SpectralBuffer polar storage — no rectangular conversion — and are RT-safe. All scalar parameters that may be retuned at runtime are backed by Atomic<…>; updates take effect on the next FFT hop.
SpectralBrickwall
Hard brick-wall filter with .lp / .hp / .bp / .br modes. Cutoffs in Hz are converted to nearest bin indices and magnitudes outside the pass band are zeroed via vDSP_vclr. Phase is untouched.
let lp = SpectralBrickwall(
fftSize: 2048, sampleRate: 48000, mode: .lp, highHz: 4000)
let bp = SpectralBrickwall(
fftSize: 2048, sampleRate: 48000, mode: .bp, lowHz: 200, highHz: 2000)
lp.lowHz = 100 // live retune
SpectralPhaseShift
Adds a constant offset to every complex bin's phase, leaving magnitude untouched. .deg90 is equivalent to a Hilbert transform (analytic-signal imaginary part); .deg180 flips DC + Nyquist sign; .radians(_:) allows arbitrary fixed shifts. The radians property accepts live updates of the complex-bin offset; the DC/Nyquist sign-flip behaviour is fixed at init by the chosen PhaseShiftAmount.
let hilbert = SpectralPhaseShift(fftSize: 2048, shift: .deg90)
let custom = SpectralPhaseShift(fftSize: 2048, shift: .radians(0.3))
custom.radians = 1.0
SpectralGate
Per-bin spectral gate. Bins whose magnitude is below threshold are scaled by floor (∈ [0, 1]); bins above pass through. floor = 0 is a hard gate; floor = 1 is bypass. DC and Nyquist gate on abs(value) and preserve sign. A thresholdDB: convenience initialiser converts dB to linear magnitude.
let gate = SpectralGate(fftSize: 2048, thresholdDB: -40, floor: 0.1)
gate.threshold = 0.05 // live retune (linear)
SpectralTilt
Tilt EQ in the spectral domain: applies a constant dB/octave slope around a pivot frequency. The per-bin gain table is pre-computed at init from slopeDBPerOctave and pivotHz, so process is pure vDSP_vmul. slope = 0 produces unity gain everywhere. slope and pivot are init-only.
let darken = SpectralTilt(
fftSize: 2048, sampleRate: 48000, slopeDBPerOctave: -3, pivotHz: 1000)
let sparkle = SpectralTilt(
fftSize: 2048, sampleRate: 48000, slopeDBPerOctave: +6, pivotHz: 1000)
SpectralBlur
Magnitude moving-average ("box blur") across complex bins. Smears spectral peaks into plateaus of width 2 · radius + 1. Edge bins shrink the window rather than wrap. Computation uses a running sum, so cost is O(halfSize) per hop regardless of radius. Phase is untouched.
let blur = SpectralBlur(fftSize: 2048, radius: 4)
blur.radius = 12 // wider smear
SpectralDiffuse
Continuous phase-randomisation. Each hop, every complex bin's phase is blended by amount ∈ [0, 1] toward a freshly drawn uniform random target. 0 is bypass; 1 is full randomisation; intermediate values produce continuous spectral smearing — useful for transient softening, reverb-like washes, and "frozen cloud" effects when combined with SpectralFreeze.
let diffuse = SpectralDiffuse(fftSize: 2048, amount: 0.5)
diffuse.amount = 1.0 // full smear
SpectralConvolve
Frequency-domain convolution: per-bin complex multiply between the live spectrum and a second SpectralBuffer (other). Equivalent to time-domain circular convolution of the two underlying signals. other is typically populated by either a parallel SpectralChain.Audio chain (cross-synthesis or matched filtering) or a static impulse response prepared once at startup. Either buffer being invalid causes the live buffer to be cleared.
let irBuf = SpectralBuffer(fftSize: 2048)
// ... populate irBuf from a precomputed impulse-response FFT frame ...
let conv = SpectralConvolve(spectralBuffer: liveBuf, other: irBuf)
let chain = SpectralChain.Audio(input: dryIn, fftSize: 2048, hopSize: 512,
stages: [.mono(conv)])
output(bus: 0, source: chain)
SpectralFormantShift
Magnitude-envelope-preserving formant shifter. Estimates the smooth spectral envelope of the current frame, whitens the spectrum by dividing it out, resamples the envelope along the bin axis by shiftRatio, and reapplies the shifted envelope to the whitened residual. Phase is untouched. Pairs with SpectralPitchShift to decouple pitch from formant motion.
Two envelope-estimation methods:
.cepstral(default) — real cepstrum with a low-quefrency lifter. Accurate; uses a secondFFTSetupallocated at init..magnitudeSmoothing(radiusBins:)— box moving-average of magnitudes. Cheaper; coarser envelope.
shiftRatio is Atomic<Float> and clamped to [0.25, 4.0]. 1.0 is bypass; < 1.0 lowers formants; > 1.0 raises them and fades bins whose source position falls above Nyquist to 0. DC and Nyquist participate in envelope estimation as unsigned magnitudes; their signs are preserved when the reshaped magnitude is written back.
// Pitch down an octave, keep formants in place:
let pitch = SpectralPitchShift(fftSize: 2048, hopSize: 512, pitchRatio: 0.5)
let formant = SpectralFormantShift(fftSize: 2048, shiftRatio: 2.0)
let chain = SpectralChain.Audio(input: voice, fftSize: 2048, hopSize: 512,
stages: [.mono(pitch), .mono(formant)])
output(bus: 0, source: chain)
formant.shiftRatio = 1.5 // live retune
Complete example
final class SpectralPatch: SynthesizerBase {
let mic = In.Audio(bus: 0)
let freeze = SpectralFreeze(fftSize: 2048)
lazy var chain = SpectralChain.Audio(
input: mic, fftSize: 2048, hopSize: 512, stages: [.mono(freeze)]
)
override func build() {
output(bus: 0, source: chain)
}
}
// Freeze on button press (main thread):
freeze.freeze()
Closure-driven spectral processors
SpectralPolarClosure and SpectralComplexClosure are SpectralProcessor conformers that
wrap an arbitrary user function. They provide the same role for spectral DSP that
Closure plays for time-domain DSP — rapid prototyping of spectral transforms
inline inside a Synthesizer.build() body, without writing a separate class.
SpectralPolarClosure
Provides direct zero-copy access to the SpectralBuffer's polar storage
(magnitudes and phases) on each FFT hop. No coordinate conversion — the buffer already
stores polar data. This is the cheapest spectral closure variant.
// 6 dB magnitude attenuation across all complex bins + DC + Nyquist:
let halver = SpectralPolarClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
for i in 0..<ctx.binCount {
ctx.magnitudes[i] *= 0.5
}
ctx.dcValue.pointee *= 0.5
ctx.nyquistValue.pointee *= 0.5
}
let chain = SpectralChain.Audio(input: sig, fftSize: 2048, stages: [.mono(halver)])
output(bus: 0, source: chain)
Context layout (SpectralPolarContext):
| Property | Type | Content |
|---|---|---|
magnitudes |
UnsafeMutableBufferPointer<Float> |
Complex bin magnitudes, length fftSize/2 - 1 (bins 1 ..< fftSize/2) |
phases |
UnsafeMutableBufferPointer<Float> |
Complex bin phases (radians), same length |
dcValue |
UnsafeMutablePointer<Float> |
Signed DC component (bin 0) |
nyquistValue |
UnsafeMutablePointer<Float> |
Signed Nyquist component (bin fftSize/2) |
binCount |
Int |
Number of complex bins = fftSize/2 - 1 |
sampleRate |
Double |
Engine sample rate in Hz |
fftSize |
Int |
FFT frame size |
hopSize |
Int |
Samples between hops |
frameIndex |
Int |
Zero-based hop counter since processor creation |
Addressing spectral bin k (where k ≥ 1): ctx.magnitudes[k - 1], ctx.phases[k - 1].
SpectralComplexClosure
Provides Cartesian (split-complex real + imaginary) access to the spectral frame. The framework performs a polar→Cartesian conversion before the closure and a Cartesian→polar conversion after it, so the buffer is always up to date for downstream processors. Use this when your transform is naturally expressed in rectangular form (complex multiplication, comb filtering, phase rotation).
Round-trip cost: one vectorised vvcosf + vvsinf + vDSP_vmul pass (polar→Cartesian)
and one vDSP_zvmags + vvsqrtf + vvatan2f pass (Cartesian→polar) per hop. Negligible
at typical FFT sizes but non-zero. Prefer SpectralPolarClosure for magnitude-only
or phase-only transforms.
// Simple 6 dB magnitude scale in Cartesian space (less efficient than polar but illustrative):
let halver = SpectralComplexClosure(fftSize: 2048, hopSize: 512, sampleRate: sr) { ctx in
for i in 0..<ctx.binCount {
ctx.real[i] *= 0.5
ctx.imag[i] *= 0.5
}
}
Context layout (SpectralComplexContext):
| Property | Type | Content |
|---|---|---|
real |
UnsafeMutableBufferPointer<Float> |
Split-complex real parts, length fftSize/2 |
imag |
UnsafeMutableBufferPointer<Float> |
Split-complex imaginary parts, length fftSize/2 |
binCount |
Int |
= fftSize/2 (includes packed DC/Nyquist at index 0) |
sampleRate |
Double |
Engine sample rate in Hz |
fftSize |
Int |
FFT frame size |
hopSize |
Int |
Samples between hops |
frameIndex |
Int |
Zero-based hop counter since processor creation |
Split-complex packing convention (matches vDSP):
real[0]= DC value;imag[0]= Nyquist value.real[k]= real part of complex bink;imag[k]= imaginary part (fork = 1..<binCount).
RT-safety contract
Both closure variants execute on the RT audio thread. The closure body must:
- Not allocate heap memory (no
Array(...), noclassinstantiation). - Not acquire locks.
- Not call
print,NSLog, or anyString-constructing API. - Not
throw.
These constraints are identical to Closure and are architecturally
unenforceable. Violations cause audio dropouts. Pre-allocate any scratch storage
before audio starts (e.g. via UnsafeMutablePointer.allocate at build() time)
and capture the pointer in the closure's capture list.
RT safety summary
| Component | RT-safe | How |
|---|---|---|
SpectralChain.Audio._runAnalysisHop |
✓ | FFT into private work arrays; vectorized rect→polar into spectralBuffer raw pointers |
SpectralChain.Audio._runIFFTBank |
✓ | Vectorized polar→rect into per-channel work arrays; raw pointer IFFT; OLA via vDSP_vadd |
SpectralMagnitudeScale.process |
✓ | vDSP_vsmul in-place on _mag pointer; scalar DC/Nyquist multiply |
SpectralFreeze.process |
✓ | Reads polar directly from buffer (no atan2f); writes polar back; no allocation |
SpectralFreeze.freeze() |
non-RT only | Sets Atomic<Bool> flag; RT thread captures polar on next hop |
OnsetDetector.process |
✓ | Pre-allocated per-bin and ring buffers; Atomic<Float> params; manual selection-sort median (no Swift sort) |
SpectralBufferRead._runHop |
✓ | Pre-allocated interpolation scratch; vDSP interpolation; floatValue for position read |
SpectralPlayBuffer._runHop |
✓ | Pre-allocated phase-vocoder scratch; Atomic<Double> rate; no allocation |
SpectralPolarClosure.process |
✓ (body is user's responsibility) | Zero-copy direct pointer into _mag[1]/_phase[1]; DC/Nyquist via pre-allocated single-element pointers |
SpectralComplexClosure.process |
✓ (body is user's responsibility) | Polar→rect via _readToRectangular; user closure on pre-allocated scratch; rect→polar via _writeFromRectangular |
Live parameter-buffer swap
Two built-in processors hold per-bin parameter buffers that can be replaced on a
running engine without rebuilding the synth graph. Both use RTBufferSlot
internally — see BufferGuide § "Live Buffer Swap" for the full pattern.
SpectralBinDelay
let delays = LyrebirdBuffer(count: halfSize)
let feedbacks = LyrebirdBuffer(count: halfSize)
delays.fill { i, n in Double(i) / Double(n) * 0.5 }
feedbacks.fill(with: 0.6)
let bd = SpectralBinDelay(fftSize: 2048, hopSize: 512,
maxDelaySeconds: 1.0, sampleRate: 44_100,
delayTimes: delays, feedbacks: feedbacks)
// Later, mid-piece:
let newDelays = LyrebirdBuffer(count: halfSize)
newDelays.fill { i, n in Double(i) / Double(n) * 0.25 } // halve the spread
bd.setDelayTimes(newDelays, engine: engine)
// Or silence the processor:
bd.setFeedbacks(nil, engine: engine)
Preconditions: both buffers must be mono and have count >= fftSize/2. When
either slot is empty or its loaded buffer is invalid, the hop is skipped
(no spectral mutation — output passes through unchanged).
SpectralMagnitudeMap
let curve = LyrebirdBuffer(count: 256)
curve.fill { i, n in pow(Double(i) / Double(n - 1), 2.0) } // squared compression
let map = SpectralMagnitudeMap(buffer: curve)
// Swap to a steeper curve:
let steep = LyrebirdBuffer(count: 256)
steep.fill { i, n in pow(Double(i) / Double(n - 1), 4.0) }
map.setBuffer(steep, engine: engine)
// Or bypass (input magnitudes pass through unchanged):
map.setBuffer(nil, engine: engine)
Precondition: buffer must be mono with count >= 2.
Authoring a swap-aware SpectralProcessor
The protocol's engine: SynthesisEngine argument is the host engine for the
chain — pass it to RTBufferSlot.load(engine:) inside your process body.
If your processor has no swappable state, ignore it.
public final class MyEnvelopeMask: SpectralProcessor {
private let _slot: RTBufferSlot
private let _halfSize: Int
public init(fftSize: Int, mask: LyrebirdBuffer) {
precondition(mask.count >= fftSize / 2 && mask.channelCount == 1)
self._slot = RTBufferSlot(initial: mask)
self._halfSize = fftSize / 2
}
public func setMask(_ buffer: LyrebirdBuffer?, engine: SynthesisEngine) {
if let buffer {
precondition(buffer.count >= _halfSize && buffer.channelCount == 1)
}
_slot.swap(buffer, engine: engine)
}
public func process(spectral: SpectralBuffer, engine: SynthesisEngine) {
guard let mask = _slot.load(engine: engine), mask.isValid else { return }
spectral.withUnsafeMutableMagnitudePointer { mp in
for i in 0..<(_halfSize - 1) {
mp[i] *= Float(mask[i + 1])
}
}
}
}