Files
Lyrebird/Sources/Lyrebird/Generators/Granular/FormantGrain.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
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>
2026-09-10 21:09:11 -07:00

331 lines
16 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// FormantGrain.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdDSP
import Foundation
// MARK: - File-scope constants
/// Exponential decay gain below which a FOF grain is considered silent and deactivated.
let fofGrainDeathThreshold: Double = 1e-4
/// Window phase value at which the sine² rise reaches its peak (sin²(π/2) = 1.0).
let fofGrainRisePeakPhase: Double = .pi / 2.0
/// Full sine cycle in radians — used for sinePhase wrap.
let fofSineFullCycle: Double = 2.0 * .pi
/// Minimum glottal pulse rate (Hz). Prevents division-by-zero in `hopSize = sr / glottalFreq`.
let fofGlottalFreqMin: Double = 0.1
/// Minimum formant frequency (Hz). Prevents zero / negative phase increments.
let fofFormantFreqMin: Double = 1.0
/// Minimum bandwidth (Hz). Prevents `decayFactor == 1.0` (grain never decays).
let fofBandwidthMin: Double = 1.0
// MARK: - FOFGrainState
/// State for one slot in the FormantGrain pool.
///
/// All fields are value types. The pool array is pre-allocated at generator init time;
/// `_computeSamples` modifies slots in-place — no allocation on the RT thread.
private struct FOFGrainState {
var isActive: Bool = false
var sinePhase: Double = 0 // radians, continuous carrier oscillator
var sinePhaseInc: Double = 0 // radians per sample
var windowPhase: Double = 0 // [0, π/2] during rise phase
var windowPhaseInc: Double = 0 // radians per sample during rise
var inRise: Bool = true // true = sine² attack; false = exponential decay
var decayGain: Double = 1.0 // envelope amplitude during decay
var decayFactor: Double = 1.0 // per-sample multiplier: exp(-π * bw / sr)
var amplitude: Double = 1.0 // signed per-grain amplitude (for octaviation)
var spawnTick: UInt64 = 0 // monotonic spawn order; lowest = oldest grain
}
// MARK: - FormantGrain
/// FOF (Fonction d'Onde Formantique) formant-grain synthesizer.
///
/// Generates a continuous stream of exponentially-decaying sine grains triggered at
/// the glottal pulse rate. Each instance models one vocal-tract formant; stacking
/// 3–5 instances at different `formantFreq` values synthesises vowel sounds.
///
/// The grain shape follows the IRCAM CHANT algorithm:
/// - **Attack** (sine² ramp): half a period of `formantFreq`, from 0 → 1
/// - **Decay** (exponential): `exp(-π · bandwidth · t)` from the peak
///
/// `octaviation ≥ 1` alternates successive grain sign, adding a suboctave at
/// half the glottal rate.
///
/// All inputs are sampled **once per audio block** (block-rate). Generator-driven
/// inputs collapse to a single value per block — useful for control-rate modulation
/// but does not perform per-sample modulation of the formant carrier.
///
/// When the grain pool (`lyrebirdGrainPoolSize`, currently 64) is exhausted, new
/// triggers steal the **oldest** active grain rather than being silently dropped.
///
/// ## CPU layout
///
/// - Flat grain pool + active-index list. The inner per-sample accumulator iterates
/// only currently-active slots, not the full 64-slot pool. Free-slot pop is O(1);
/// expired grains swap-with-last to keep the partition invariant.
/// - Steal-oldest fallback when the pool is full scans the active region only
/// (size = activeCount), not the entire pool.
/// - Output row zeroed with `vDSP_vclrD`; inner writes go through a hoisted
/// `UnsafeMutablePointer<Double>` row pointer.
///
/// - Parameters:
/// - glottalFreq: Glottal pulse rate in Hz (fundamental pitch). Clamped to
/// `[fofGlottalFreqMin, sampleRate]` so `hopSize ≥ 1`.
/// - formantFreq: Formant resonance frequency in Hz. Clamped to ≥ `fofFormantFreqMin`.
/// - bandwidth: Formant bandwidth in Hz; controls exponential decay speed.
/// Clamped to ≥ `fofBandwidthMin`. Larger values = faster decay = broader formant.
/// - octaviation: 0 = unmodified. ≥ 1 = alternating grain sign (adds suboctave).
/// - amp: Per-grain peak amplitude. Defaults to `0.5`.
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Output offset added after multiplier. Defaults to `0.0`.
public enum FormantGrain {
public final class Audio: GeneratorBase, AudioGenerator {
// MARK: Inputs
private let _glottalFreqInput: any ValidGeneratorInput
private let _formantFreqInput: any ValidGeneratorInput
private let _bandwidthInput: any ValidGeneratorInput
private let _octaviationInput: any ValidGeneratorInput
private let _amplitudeInput: any ValidGeneratorInput
// MARK: MulAdd
private let _mulAdd: MulAddSpec
// MARK: Grain pool (flat)
private var _grains: [FOFGrainState]
/// Permutation of slot indices `[0, lyrebirdGrainPoolSize)`. Indices
/// `[0, _activeCount)` are active; `[_activeCount, poolSize)` are free.
private var _activeIndices: [Int]
private var _activeCount: Int = 0
// MARK: Scheduling state
private var _hopCounter: Double = 0
private var _hasTriggeredFirst: Bool = false
private var _glottalCount: UInt64 = 0
private var _grainSpawnTick: UInt64 = 0
// MARK: Output buffer
// MARK: Init
/// FOF (Fonction d'Onde Formantique) formant-grain synthesizer.
///
/// Generates a continuous stream of exponentially-decaying sine grains triggered at
/// the glottal pulse rate. Each instance models one vocal-tract formant; stacking
/// 3–5 instances at different `formantFreq` values synthesises vowel sounds.
///
/// - Parameters:
/// - glottalFreq: Glottal pulse rate in Hz (fundamental pitch). Clamped to
/// `[fofGlottalFreqMin, sampleRate]` so `hopSize ≥ 1`.
/// - formantFreq: Formant resonance frequency in Hz. Clamped to ≥ `fofFormantFreqMin`.
/// - bandwidth: Formant bandwidth in Hz; controls exponential decay speed.
/// Clamped to ≥ `fofBandwidthMin`. Larger values = faster decay = broader formant.
/// - octaviation: 0 = unmodified. ≥ 1 = alternating grain sign (adds suboctave).
/// - amp: Per-grain peak amplitude. Defaults to `0.5`.
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
/// - add: Output offset added after multiplier. Defaults to `0.0`.
public init(
glottalFreq: any ValidGeneratorInput = 100.0,
formantFreq: any ValidGeneratorInput = 700.0,
bandwidth: any ValidGeneratorInput = 200.0,
octaviation: any ValidGeneratorInput = 0.0,
amp: any ValidGeneratorInput = 0.5,
mul: any ValidGeneratorInput = 1.0,
add: any ValidGeneratorInput = 0.0
) {
// Resolve every `any ValidGeneratorInput` slot before storing.
// `mul` / `add` resolved inside MulAddSpec.
let resolvedGlottal: any ValidGeneratorInput = glottalFreq._resolvedInput()
let resolvedFormant: any ValidGeneratorInput = formantFreq._resolvedInput()
let resolvedBand: any ValidGeneratorInput = bandwidth._resolvedInput()
let resolvedOctav: any ValidGeneratorInput = octaviation._resolvedInput()
let resolvedAmp: any ValidGeneratorInput = amp._resolvedInput()
let poolSize: Int = lyrebirdGrainPoolSize
_glottalFreqInput = resolvedGlottal
_formantFreqInput = resolvedFormant
_bandwidthInput = resolvedBand
_octaviationInput = resolvedOctav
_amplitudeInput = resolvedAmp
_mulAdd = MulAddSpec(mul: mul, add: add)
_grains = Array(repeating: FOFGrainState(), count: poolSize)
var indices: [Int] = []
indices.reserveCapacity(poolSize)
for s: Int in 0..<poolSize { indices.append(s) }
_activeIndices = indices
super.init()
}
// MARK: AudioGenerator
// MARK: _computeSamples
public func _computeSamples(graph: SynthGraph, count: Int) -> [[Double]] {
_checkCount(count)
let poolSize: Int = lyrebirdGrainPoolSize
let sr: Double = Double(graph.engine.sampleRate)
// Clamp glottalFreq ≤ sr so `hopSize = sr / glottalFreq ≥ 1.0` —
// prevents same-sample re-trigger that would drain the pool every sample.
let glottalFreq: Double = min(sr, max(fofGlottalFreqMin, _glottalFreqInput.floatValue(graph: graph)))
let formantFreq: Double = max(fofFormantFreqMin, _formantFreqInput.floatValue(graph: graph))
let bw: Double = max(fofBandwidthMin, _bandwidthInput.floatValue(graph: graph))
let ampVal: Double = _amplitudeInput.floatValue(graph: graph)
let octaviationRaw: Double = _octaviationInput.floatValue(graph: graph)
let sinePhaseInc: Double = fofSineFullCycle * formantFreq / sr
// windowPhaseInc reaches π/2 after half a formant period (rise duration).
let windowPhaseInc: Double = Double.pi * formantFreq / sr
let decayFactor: Double = exp(-Double.pi * bw / sr)
let hopSize: Double = sr / glottalFreq
var hopCounter: Double = _hopCounter
var hasTriggered: Bool = _hasTriggeredFirst
var glottalCount: UInt64 = _glottalCount
var spawnTick: UInt64 = _grainSpawnTick
var activeCount: Int = _activeCount
_result[0].withUnsafeMutableBufferPointer { rowPtr in
guard let row0: UnsafeMutablePointer<Double> = rowPtr.baseAddress else { return }
vDSP_vclrD(row0, 1, vDSP_Length(count))
_grains.withUnsafeMutableBufferPointer { gPtr in
guard let gBase: UnsafeMutablePointer<FOFGrainState> = gPtr.baseAddress else { return }
_activeIndices.withUnsafeMutableBufferPointer { aPtr in
guard let aBase: UnsafeMutablePointer<Int> = aPtr.baseAddress else { return }
for i: Int in 0..<count {
hopCounter += 1
let shouldTrigger: Bool = !hasTriggered || hopCounter >= hopSize
if shouldTrigger {
if hasTriggered {
hopCounter -= hopSize
} else {
hopCounter = 0
hasTriggered = true
}
// Octaviation: alternate grain sign when octaviation >= 1.
let octaviationInt: Int = Int(octaviationRaw.rounded())
let sign: Double = (octaviationInt >= 1 && glottalCount % 2 == 1) ? -1.0 : 1.0
glottalCount &+= 1
spawnTick &+= 1
let newTick: UInt64 = spawnTick
// Find a free slot (O(1) pop) or steal the oldest active grain.
let spawnIndex: Int
if activeCount < poolSize {
spawnIndex = aBase[activeCount]
activeCount += 1
} else {
// Scan active region for oldest spawnTick. Active slots live in
// `aBase[0 ..< activeCount]` so we don't touch inactive slots.
var oldestTick: UInt64 = UInt64.max
var oldestIdx: Int = aBase[0]
for k: Int in 0..<activeCount {
let s: Int = aBase[k]
let tick: UInt64 = gBase[s].spawnTick
if tick < oldestTick {
oldestTick = tick
oldestIdx = s
}
}
spawnIndex = oldestIdx
// Slot is already in the active region; no count change.
}
gBase[spawnIndex] = FOFGrainState(
isActive: true,
sinePhase: 0,
sinePhaseInc: sinePhaseInc,
windowPhase: 0,
windowPhaseInc: windowPhaseInc,
inRise: true,
decayGain: 1.0,
decayFactor: decayFactor,
amplitude: ampVal * sign,
spawnTick: newTick
)
}
// Accumulate all active grains into this sample.
var k: Int = 0
while k < activeCount {
let s: Int = aBase[k]
let gp: UnsafeMutablePointer<FOFGrainState> = gBase + s
var grain: FOFGrainState = gp.pointee
let envVal: Double
if grain.inRise {
let wp: Double = grain.windowPhase
let sw: Double = sin(wp)
envVal = sw * sw // sin² rise: 0 at wp=0, 1 at wp=π/2
grain.windowPhase += grain.windowPhaseInc
if grain.windowPhase >= fofGrainRisePeakPhase {
grain.inRise = false
grain.decayGain = 1.0 // peak = 1
}
} else {
envVal = grain.decayGain
grain.decayGain *= grain.decayFactor
if grain.decayGain < fofGrainDeathThreshold {
grain.isActive = false
}
}
row0[i] += sin(grain.sinePhase) * envVal * grain.amplitude
grain.sinePhase += grain.sinePhaseInc
// Unconditional remainder handles arbitrary sinePhaseInc magnitudes
// (e.g. when formantFreq exceeds sampleRate so sinePhaseInc > 2π).
if grain.sinePhase >= fofSineFullCycle {
grain.sinePhase = grain.sinePhase.truncatingRemainder(dividingBy: fofSineFullCycle)
}
if !grain.isActive {
gp.pointee = grain
let lastK: Int = activeCount - 1
if k != lastK {
let tmp: Int = aBase[k]
aBase[k] = aBase[lastK]
aBase[lastK] = tmp
}
activeCount -= 1
} else {
gp.pointee = grain
k += 1
}
}
}
}
}
}
_hopCounter = hopCounter
_hasTriggeredFirst = hasTriggered
_glottalCount = glottalCount
_grainSpawnTick = spawnTick
_activeCount = activeCount
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
return _result
}
}
} // enum FormantGrain
// GeneratorEnum conformance intentionally omitted — Audio-only.