325 lines
15 KiB
Swift
325 lines
15 KiB
Swift
// SineGrain.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Accelerate
|
|
import Foundation
|
|
|
|
/// Granular synthesizer that generates a windowed sine tone inside each grain.
|
|
///
|
|
/// Unlike `BufferGrain` (which reads from a pre-recorded buffer), `SineGrain` synthesises
|
|
/// each grain internally using the shared sine table. Tone parameters (`freq`, `amp`) are
|
|
/// **polled once per grain trigger** — connect generators for per-grain pitch/amplitude variation.
|
|
///
|
|
/// ## Density
|
|
///
|
|
/// Pass any `ValidGeneratorInput` to `density:` at init to drive grain rate from a generator.
|
|
/// The value is polled at each trigger to set the next hop interval. Omit `density:` to use
|
|
/// the `@LiveParam density` property for live main-thread control.
|
|
///
|
|
/// ## Per-grain parameters as `ValidGeneratorInput`
|
|
///
|
|
/// Pass any `ValidGeneratorInput` to `duration:` and `pan:` at init to drive these from
|
|
/// generators. Each is polled block-constantly. `panSpread` remains `@LiveParam`.
|
|
///
|
|
/// ## Output
|
|
///
|
|
/// Always stereo [left, right], all grains centred.
|
|
/// Wire through `output(bus: 0, source: sineGrains)`.
|
|
///
|
|
/// ## CPU layout
|
|
///
|
|
/// - Flat grain pool + active-index list (O(1) free-slot pop, swap-with-last expiry).
|
|
/// - Sine + window tables accessed via hoisted raw pointers; window uses PoT bitmask
|
|
/// wrap when applicable. Sine table is always PoT (`lyrebirdDefaultTableSize` = 2¹⁵).
|
|
/// - Output rows zeroed with `vDSP_vclrD` per block; inner loop accumulates via hoisted
|
|
/// `UnsafeMutablePointer<Double>` row pointers.
|
|
///
|
|
/// ## Usage
|
|
///
|
|
/// ```swift
|
|
/// let sineGrains = SineGrain(freq: 440.0, amp: 0.3, duration: 0.05)
|
|
/// sineGrains.density = 20.0
|
|
///
|
|
/// // Stochastic density + pitch spread:
|
|
/// let noiseDensity = WhiteNoise.Control() * 15.0 + 20.0
|
|
/// let grains2 = SineGrain(freq: someFreqGen, amp: 0.3, density: noiseDensity)
|
|
/// ```
|
|
public final class SineGrain: GranularBase, AudioGenerator {
|
|
|
|
public override var outputChannelCount: Int { granularChannelCount }
|
|
|
|
// MARK: - Scheduling parameters
|
|
|
|
/// Grain rate when no external density generator is provided.
|
|
@LiveParam public var density: Double = 10.0
|
|
|
|
/// Random spread applied to `pan` at each grain trigger. 0 = no spread.
|
|
@LiveParam public var panSpread: Double = 0.0
|
|
|
|
// MARK: - Per-grain tone inputs (polled at trigger time)
|
|
|
|
private let _freqInput: any ValidGeneratorInput
|
|
private let _ampInput: any ValidGeneratorInput
|
|
|
|
// MARK: - Block-constantly polled inputs
|
|
|
|
private let _durationInput: any ValidGeneratorInput
|
|
private let _panInput: any ValidGeneratorInput
|
|
|
|
// MARK: - Density source
|
|
|
|
private var _resolvedDensitySource: any ValidGeneratorInput
|
|
|
|
// MARK: - Configuration
|
|
|
|
/// Atomic slot holding an optional custom window. `nil` falls back to the engine's
|
|
/// shared Hanning table. Loaded once per audio block; supports live swap via
|
|
/// ``setWindow(_:engine:)``.
|
|
private let _windowSlot: RTBufferSlot
|
|
|
|
// MARK: - State (flat grain pool)
|
|
|
|
private var _grains: [GrainState]
|
|
private var _activeIndices: [Int]
|
|
private var _activeCount: Int = 0
|
|
private var _hopCounter: Double = 0
|
|
private var _nextHopSize: Double = 0
|
|
private var _hasTriggeredFirstGrain: Bool = false
|
|
|
|
// MARK: - Output
|
|
|
|
// MARK: - Fan-out cache (Generator protocol)
|
|
|
|
private let _mulAdd: MulAddSpec
|
|
|
|
// MARK: - Init
|
|
|
|
/// - Parameters:
|
|
/// - freq: Sine frequency in Hz. Polled once per grain trigger.
|
|
/// - amp: Grain amplitude. Polled once per grain trigger.
|
|
/// - duration: Grain duration in seconds. Polled block-constantly. Default 0.1.
|
|
/// - pan: Stereo pan [-1, 1]. Polled block-constantly. Default 0.0.
|
|
/// - density: Optional density generator, polled at each trigger for the next hop interval.
|
|
/// `nil` uses `@LiveParam density`.
|
|
/// - window: Custom window shape. `nil` uses the shared Hanning table.
|
|
/// - seed: PRNG seed. `nil` = time-derived.
|
|
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
|
|
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
|
public init(
|
|
freq: any ValidGeneratorInput = 440.0,
|
|
amp: any ValidGeneratorInput = 0.5,
|
|
duration: any ValidGeneratorInput = 0.1,
|
|
pan: any ValidGeneratorInput = 0.0,
|
|
density: (any ValidGeneratorInput)? = nil,
|
|
window: LyrebirdBuffer? = nil,
|
|
seed: UInt64? = nil,
|
|
mul: any ValidGeneratorInput = 1.0,
|
|
add: any ValidGeneratorInput = 0.0
|
|
) {
|
|
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
|
let resolvedAmp: any ValidGeneratorInput = amp._resolvedInput()
|
|
let resolvedDuration: any ValidGeneratorInput = duration._resolvedInput()
|
|
let resolvedPan: any ValidGeneratorInput = pan._resolvedInput()
|
|
let resolvedDensity: (any ValidGeneratorInput)? = density?._resolvedInput()
|
|
let poolSize: Int = lyrebirdGrainPoolSize
|
|
_freqInput = resolvedFreq
|
|
_ampInput = resolvedAmp
|
|
_durationInput = resolvedDuration
|
|
_panInput = resolvedPan
|
|
_windowSlot = RTBufferSlot(initial: window)
|
|
_grains = Array(repeating: GrainState(), count: poolSize)
|
|
var indices: [Int] = []
|
|
indices.reserveCapacity(poolSize)
|
|
for s: Int in 0..<poolSize { indices.append(s) }
|
|
_activeIndices = indices
|
|
_resolvedDensitySource = resolvedDensity ?? (10.0 as Double)
|
|
_mulAdd = MulAddSpec(mul: mul, add: add)
|
|
super.init(seed: seed, channels: 2)
|
|
if resolvedDensity == nil { _resolvedDensitySource = $density }
|
|
}
|
|
|
|
/// Replace the custom window buffer. Pass `nil` to fall back to the engine's
|
|
/// shared Hanning table. See `BufferGrain.setWindow(_:engine:)` for the in-flight
|
|
/// grain envelope caveat.
|
|
public func setWindow(_ window: LyrebirdBuffer?, engine: SynthesisEngine) {
|
|
_windowSlot.swap(window, engine: engine)
|
|
}
|
|
|
|
// MARK: - Generator protocol
|
|
// MARK: - Compute
|
|
|
|
public func _computeSamples(
|
|
graph: SynthGraph,
|
|
count: Int
|
|
) -> [[Double]] {
|
|
_checkCount(count)
|
|
|
|
let poolSize: Int = lyrebirdGrainPoolSize
|
|
|
|
let durationVal: Double = max(0.001, _durationInput.floatValue(graph: graph))
|
|
let panBase: Double = max(-1.0, min(1.0, _panInput.floatValue(graph: graph)))
|
|
let panSpreadVal: Double = $panSpread.floatValue(graph: graph)
|
|
let sampleRate: Double = Double(graph.engine.sampleRate)
|
|
let durationSamples: Int = max(1, Int((durationVal * sampleRate).rounded()))
|
|
|
|
let sineTable: LyrebirdBuffer = graph.engine.sharedTables.sineTable
|
|
let tableSize: Int = sineTable.count
|
|
let tableSizeF: Double = Double(tableSize)
|
|
let tableMask: Int = tableSize - 1
|
|
// Sine table is always PoT (lyrebirdDefaultTableSize). Bitmask wrap unconditional.
|
|
let sineStorage: UnsafePointer<Double> = sineTable._rawStorage
|
|
|
|
let windowTable: LyrebirdBuffer = _windowSlot.load(engine: graph.engine) ?? graph.engine.sharedTables.hanningTable
|
|
let windowTableSize: Int = windowTable.count
|
|
let windowTableSizeF: Double = Double(windowTableSize)
|
|
let windowTableMask: Int = windowTableSize - 1
|
|
let windowIsPoT: Bool = (windowTableSize > 0) && ((windowTableSize & windowTableMask) == 0)
|
|
let windowStorage: UnsafePointer<Double> = windowTable._rawStorage
|
|
|
|
let densitySource: any ValidGeneratorInput = _resolvedDensitySource
|
|
|
|
var hopCounter: Double = _hopCounter
|
|
var nextHopSize: Double = _nextHopSize
|
|
var hasTriggered: Bool = _hasTriggeredFirstGrain
|
|
var activeCount: Int = _activeCount
|
|
|
|
// Single outer access on `_result` avoids the exclusivity violation that
|
|
// would fire on nested `_result[0]`/`_result[1]` accesses.
|
|
_result.withUnsafeMutableBufferPointer { rowsPtr in
|
|
rowsPtr[0].withUnsafeMutableBufferPointer { row0Ptr in
|
|
guard let row0: UnsafeMutablePointer<Double> = row0Ptr.baseAddress else { return }
|
|
rowsPtr[1].withUnsafeMutableBufferPointer { row1Ptr in
|
|
guard let row1: UnsafeMutablePointer<Double> = row1Ptr.baseAddress else { return }
|
|
vDSP_vclrD(row0, 1, vDSP_Length(count))
|
|
vDSP_vclrD(row1, 1, vDSP_Length(count))
|
|
|
|
_grains.withUnsafeMutableBufferPointer { gPtr in
|
|
guard let gBase: UnsafeMutablePointer<GrainState> = 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 >= nextHopSize
|
|
if shouldTrigger {
|
|
if hasTriggered {
|
|
hopCounter -= nextHopSize
|
|
} else {
|
|
hopCounter = 0
|
|
hasTriggered = true
|
|
}
|
|
|
|
let densityVal: Double = max(0.001, densitySource.floatValue(graph: graph))
|
|
nextHopSize = sampleRate / densityVal
|
|
|
|
let freqVal: Double = _freqInput.floatValue(graph: graph)
|
|
let ampVal: Double = _ampInput.floatValue(graph: graph)
|
|
let winInc: Double = windowTableSizeF / Double(durationSamples)
|
|
|
|
if activeCount < poolSize {
|
|
let s: Int = aBase[activeCount]
|
|
let grainPan: Double = max(-1.0, min(1.0, panBase + panSpreadVal * nextRandomBipolar()))
|
|
let panAngle: Double = (grainPan + 1.0) * granularPanAngleScale
|
|
|
|
let gp: UnsafeMutablePointer<GrainState> = gBase + s
|
|
gp.pointee.isActive = true
|
|
gp.pointee.synthPhase = 0
|
|
gp.pointee.synthPhaseInc = max(0, freqVal) * tableSizeF / sampleRate
|
|
gp.pointee.remaining = durationSamples
|
|
gp.pointee.amp = ampVal
|
|
gp.pointee.panGainL = cos(panAngle)
|
|
gp.pointee.panGainR = sin(panAngle)
|
|
gp.pointee.windowPhase = 0
|
|
gp.pointee.windowInc = winInc
|
|
|
|
activeCount += 1
|
|
}
|
|
}
|
|
|
|
var k: Int = 0
|
|
while k < activeCount {
|
|
let s: Int = aBase[k]
|
|
let gp: UnsafeMutablePointer<GrainState> = gBase + s
|
|
var grain: GrainState = gp.pointee
|
|
|
|
// Sine-table lookup — PoT bitmask wrap (table size always PoT).
|
|
let sp: Double = grain.synthPhase
|
|
let si: Int = Int(sp)
|
|
let sf: Double = sp - Double(si)
|
|
let s0: Double = sineStorage[si & tableMask]
|
|
let s1: Double = sineStorage[(si + 1) & tableMask]
|
|
let sample: Double = s0 + sf * (s1 - s0)
|
|
|
|
// Window-table lookup (PoT bitmask or modulo).
|
|
let wp: Double = grain.windowPhase
|
|
let wi: Int = Int(wp)
|
|
let wf: Double = wp - Double(wi)
|
|
let w0: Double
|
|
let w1: Double
|
|
if windowIsPoT {
|
|
w0 = windowStorage[wi & windowTableMask]
|
|
w1 = windowStorage[(wi + 1) & windowTableMask]
|
|
} else {
|
|
var widx: Int = wi % windowTableSize
|
|
if widx < 0 { widx += windowTableSize }
|
|
w0 = windowStorage[widx]
|
|
w1 = windowStorage[min(wi + 1, windowTableSize - 1)]
|
|
}
|
|
let windowVal: Double = w0 + wf * (w1 - w0)
|
|
|
|
let windowed: Double = sample * windowVal * grain.amp
|
|
row0[i] += windowed * grain.panGainL
|
|
row1[i] += windowed * grain.panGainR
|
|
|
|
grain.synthPhase += grain.synthPhaseInc
|
|
if grain.synthPhase >= tableSizeF { grain.synthPhase -= tableSizeF }
|
|
// Fallback for very high frequencies where one subtract isn't enough.
|
|
if grain.synthPhase >= tableSizeF {
|
|
grain.synthPhase = grain.synthPhase
|
|
.truncatingRemainder(dividingBy: tableSizeF)
|
|
}
|
|
|
|
grain.windowPhase += grain.windowInc
|
|
grain.remaining -= 1
|
|
|
|
if grain.remaining <= 0 {
|
|
grain.isActive = false
|
|
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
|
|
_nextHopSize = nextHopSize
|
|
_hasTriggeredFirstGrain = hasTriggered
|
|
_activeCount = activeCount
|
|
|
|
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
|
return _result
|
|
}
|
|
}
|
|
|
|
// MARK: - GeneratorEnum
|
|
|
|
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
|
|
// generator with no paired `Control` variant.
|