420 lines
22 KiB
Swift
420 lines
22 KiB
Swift
// InputGrain.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Accelerate
|
|
import Foundation
|
|
|
|
/// Granular synthesizer that records a live audio input into a circular capture buffer
|
|
/// and reads windowed grains from that history.
|
|
///
|
|
/// `InputGrain` is the live-audio equivalent of `BufferGrain`. It continuously records
|
|
/// its `input` signal into a pre-allocated circular buffer (`lyrebirdInputGrainSize`
|
|
/// frames by default) and triggers grains that read windowed segments from that history.
|
|
///
|
|
/// ## 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.
|
|
///
|
|
/// ## Position semantics
|
|
///
|
|
/// `position = 0.0` → most recently captured audio. `position = 1.0` → oldest audio in
|
|
/// the circular buffer. `positionSpread` adds ± random offset per grain.
|
|
///
|
|
/// ## Per-grain parameters as `ValidGeneratorInput`
|
|
///
|
|
/// Pass any `ValidGeneratorInput` to `position:`, `positionSpread:`, `duration:`, `amp:`,
|
|
/// `pan:`, `pitchRatio:`, and `pitchDispersion:` at init to drive these from generators.
|
|
/// Each is polled block-constantly (once per audio block). `rateSpread` and `panSpread`
|
|
/// remain `@LiveParam` since random spread benefits from main-thread control only.
|
|
///
|
|
/// ## Output
|
|
///
|
|
/// Always stereo [left, right], grains centred (equal-power).
|
|
/// Wire through `output(bus: 0, source: inputGrains)`.
|
|
///
|
|
/// ## CPU layout
|
|
///
|
|
/// - Flat grain pool + active-index list (free-slot O(1) pop, swap-with-last expiry).
|
|
/// - Output rows zeroed with `vDSP_vclrD` per block; inner loop accumulates via hoisted
|
|
/// `UnsafeMutablePointer<Double>` row pointers.
|
|
/// - Window-table read via raw pointer + PoT bitmask wrap (shared Hanning is 2¹⁵).
|
|
/// - Circular capture-buffer read inlined for `.linear` (the default) using a raw pointer
|
|
/// hoisted once per block; `.none` / `.cubic` fall through to `lyrebirdBufferRead`.
|
|
public final class InputGrain: GranularBase, AudioGenerator {
|
|
|
|
public override var outputChannelCount: Int { granularChannelCount }
|
|
|
|
// MARK: - Scheduling parameters
|
|
|
|
@LiveParam public var density: Double = 10.0
|
|
@LiveParam public var rateSpread: Double = 0.0
|
|
|
|
/// Random spread applied to `pan` at each grain trigger. 0 = no spread.
|
|
@LiveParam public var panSpread: Double = 0.0
|
|
|
|
// MARK: - ValidGeneratorInput parameters (polled block-constantly)
|
|
|
|
private let _positionInput: any ValidGeneratorInput
|
|
private let _positionSpreadInput: any ValidGeneratorInput
|
|
private let _durationInput: any ValidGeneratorInput
|
|
private let _ampInput: any ValidGeneratorInput
|
|
private let _panInput: any ValidGeneratorInput
|
|
private let _pitchRatioInput: any ValidGeneratorInput
|
|
private let _pitchDispersionInput: any ValidGeneratorInput
|
|
|
|
// MARK: - Input / density source
|
|
|
|
private let _inputSource: any ValidGeneratorInput
|
|
private let _inputIsGenerator: Bool
|
|
private var _resolvedDensitySource: any ValidGeneratorInput
|
|
private let _interpolation: TableInterpolation
|
|
|
|
// MARK: - Circular capture buffer
|
|
|
|
private let _captureBuf: LyrebirdBuffer
|
|
private let _captureSize: Int
|
|
private let _captureSizeF: Double
|
|
private var _writeHead: Int = 0
|
|
|
|
// 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: - Scratch
|
|
|
|
private var _zeroFallback: [Double]
|
|
|
|
// MARK: - Output
|
|
|
|
// MARK: - Fan-out cache (Generator protocol)
|
|
|
|
private let _mulAdd: MulAddSpec
|
|
|
|
// MARK: - Init
|
|
|
|
/// - Parameters:
|
|
/// - input: Live audio source. Channel 0 is recorded.
|
|
/// - position: Normalised delay position [0, 1] — 0 = newest, 1 = oldest. Default 0.0.
|
|
/// - positionSpread: Random spread applied to position at trigger time. Default 0.0.
|
|
/// - duration: Grain duration in seconds. Polled block-constantly. Default 0.1.
|
|
/// - amp: Grain amplitude. Polled block-constantly. Default 1.0.
|
|
/// - pan: Stereo pan [-1, 1]. Polled block-constantly. Default 0.0.
|
|
/// - pitchRatio: Playback speed multiplier. Polled block-constantly. Default 1.0.
|
|
/// - pitchDispersion: Additive random pitch spread (added to pitchRatio per trigger). 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.
|
|
/// - captureSize: Circular buffer length in frames. Defaults to `lyrebirdInputGrainSize`.
|
|
/// - interpolation: Interpolation mode for grain reads. Defaults to `.linear`.
|
|
/// - 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(
|
|
input: any ValidGeneratorInput,
|
|
position: any ValidGeneratorInput = 0.0,
|
|
positionSpread: any ValidGeneratorInput = 0.0,
|
|
duration: any ValidGeneratorInput = 0.1,
|
|
amp: any ValidGeneratorInput = 1.0,
|
|
pan: any ValidGeneratorInput = 0.0,
|
|
pitchRatio: any ValidGeneratorInput = 1.0,
|
|
pitchDispersion: any ValidGeneratorInput = 0.0,
|
|
density: (any ValidGeneratorInput)? = nil,
|
|
window: LyrebirdBuffer? = nil,
|
|
captureSize: Int = lyrebirdInputGrainSize,
|
|
interpolation: TableInterpolation = .linear,
|
|
seed: UInt64? = nil,
|
|
mul: any ValidGeneratorInput = 1.0,
|
|
add: any ValidGeneratorInput = 0.0
|
|
) {
|
|
precondition(captureSize >= 4,
|
|
"InputGrain: captureSize must be >= 4, got \(captureSize)")
|
|
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
|
let resolvedPosition: any ValidGeneratorInput = position._resolvedInput()
|
|
let resolvedPositionSpread: any ValidGeneratorInput = positionSpread._resolvedInput()
|
|
let resolvedDuration: any ValidGeneratorInput = duration._resolvedInput()
|
|
let resolvedAmp: any ValidGeneratorInput = amp._resolvedInput()
|
|
let resolvedPan: any ValidGeneratorInput = pan._resolvedInput()
|
|
let resolvedPitchRatio: any ValidGeneratorInput = pitchRatio._resolvedInput()
|
|
let resolvedPitchDispersion: any ValidGeneratorInput = pitchDispersion._resolvedInput()
|
|
let resolvedDensity: (any ValidGeneratorInput)? = density?._resolvedInput()
|
|
let poolSize: Int = lyrebirdGrainPoolSize
|
|
_inputSource = resolvedInput
|
|
_inputIsGenerator = resolvedInput is any Generator
|
|
_positionInput = resolvedPosition
|
|
_positionSpreadInput = resolvedPositionSpread
|
|
_durationInput = resolvedDuration
|
|
_ampInput = resolvedAmp
|
|
_panInput = resolvedPan
|
|
_pitchRatioInput = resolvedPitchRatio
|
|
_pitchDispersionInput = resolvedPitchDispersion
|
|
_windowSlot = RTBufferSlot(initial: window)
|
|
_captureSize = captureSize
|
|
_captureSizeF = Double(captureSize)
|
|
_captureBuf = LyrebirdBuffer(count: captureSize)
|
|
_interpolation = interpolation
|
|
_grains = Array(repeating: GrainState(), count: poolSize)
|
|
var indices: [Int] = []
|
|
indices.reserveCapacity(poolSize)
|
|
for s: Int in 0..<poolSize { indices.append(s) }
|
|
_activeIndices = indices
|
|
_zeroFallback = makeSampleBuffer()
|
|
_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 positionVal: Double = max(0.0, min(1.0, _positionInput.floatValue(graph: graph)))
|
|
let posSpreadVal: Double = _positionSpreadInput.floatValue(graph: graph)
|
|
let durationVal: Double = max(0.001, _durationInput.floatValue(graph: graph))
|
|
let pitchRatioVal: Double = _pitchRatioInput.floatValue(graph: graph)
|
|
let pitchDispersionVal: Double = _pitchDispersionInput.floatValue(graph: graph)
|
|
let rateSpreadVal: Double = $rateSpread.floatValue(graph: graph)
|
|
let ampVal: Double = _ampInput.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 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
|
|
|
|
// Evaluate input block once — never re-evaluate inside the grain loop.
|
|
// Generator inputs use calculatedSamples; scalar inputs use floatValue to avoid RT alloc.
|
|
let inputBlock: [Double]
|
|
if _inputIsGenerator {
|
|
let inputSamples: [[Double]] = _inputSource.calculatedSamples(graph: graph, count: count)
|
|
inputBlock = inputSamples.first ?? _zeroFallback
|
|
} else {
|
|
let scalar: Double = _inputSource.floatValue(graph: graph)
|
|
for i: Int in 0..<count { _zeroFallback[i] = scalar }
|
|
inputBlock = _zeroFallback
|
|
}
|
|
|
|
// Hoist circular buffer raw pointers (mono storage — channelCount=1, stride=1).
|
|
// The capture buffer is owned + non-swappable, so the base pointer is stable.
|
|
let captureStorage: UnsafeMutablePointer<Double> = _captureBuf._rawStorageMutable
|
|
let captureSize: Int = _captureSize
|
|
let captureSizeF: Double = _captureSizeF
|
|
let interpolation: TableInterpolation = _interpolation
|
|
|
|
// Hoist scheduling state.
|
|
var hopCounter: Double = _hopCounter
|
|
var nextHopSize: Double = _nextHopSize
|
|
var hasTriggered: Bool = _hasTriggeredFirstGrain
|
|
var activeCount: Int = _activeCount
|
|
var writeHead: Int = _writeHead
|
|
|
|
// Single outer access on `_result` (the [[Double]] container) avoids the
|
|
// exclusivity violation that would fire on nested `_result[0]`/`_result[1]`.
|
|
_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))
|
|
|
|
inputBlock.withUnsafeBufferPointer { inPtr in
|
|
guard let inBase: UnsafePointer<Double> = inPtr.baseAddress else { return }
|
|
|
|
_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 {
|
|
|
|
// Record input into circular buffer before triggering or reading.
|
|
captureStorage[writeHead] = inBase[i]
|
|
writeHead = (writeHead + 1) % captureSize
|
|
|
|
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
|
|
|
|
// Grain start: delay into capture history.
|
|
// positionVal=0 → minimum delay (most recent audio).
|
|
// positionVal=1 → maximum delay (oldest audio in buffer).
|
|
let spread: Double = posSpreadVal * nextRandomBipolar()
|
|
let delayFrac: Double = max(0.0, min(1.0, positionVal + spread))
|
|
let delayFrames: Double = max(1.0, delayFrac * (captureSizeF - 1))
|
|
let rawPhase: Double = Double(writeHead) - delayFrames
|
|
let startPhase: Double = rawPhase < 0 ? rawPhase + captureSizeF : rawPhase
|
|
|
|
// Effective pitch ratio combines base + dispersion + rate spread.
|
|
let effectivePitchRatio: Double = pitchRatioVal
|
|
+ pitchDispersionVal * nextRandomBipolar()
|
|
+ rateSpreadVal * nextRandomBipolar()
|
|
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.phase = startPhase
|
|
gp.pointee.phaseInc = effectivePitchRatio
|
|
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
|
|
}
|
|
}
|
|
|
|
// --- Accumulate active grains via active-index list ---
|
|
var k: Int = 0
|
|
while k < activeCount {
|
|
let s: Int = aBase[k]
|
|
let gp: UnsafeMutablePointer<GrainState> = gBase + s
|
|
var grain: GrainState = gp.pointee
|
|
|
|
// 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)
|
|
|
|
// Inlined circular-buffer read for `.linear`.
|
|
// Capture buffer is mono → stride = 1.
|
|
let sample: Double
|
|
if interpolation == .linear {
|
|
let bPhase: Double = grain.phase
|
|
let intPhase: Int = Int(bPhase.rounded(.down))
|
|
let frac: Double = bPhase - Double(intPhase)
|
|
var r0: Int = intPhase % captureSize
|
|
if r0 < 0 { r0 += captureSize }
|
|
var r1: Int = (intPhase + 1) % captureSize
|
|
if r1 < 0 { r1 += captureSize }
|
|
let s0: Double = captureStorage[r0]
|
|
let s1: Double = captureStorage[r1]
|
|
sample = s0 + frac * (s1 - s0)
|
|
} else {
|
|
sample = lyrebirdBufferRead(
|
|
_captureBuf,
|
|
channel: 0,
|
|
phase: grain.phase,
|
|
interpolation: interpolation,
|
|
loop: true
|
|
)
|
|
}
|
|
|
|
let windowed: Double = sample * windowVal * grain.amp
|
|
row0[i] += windowed * grain.panGainL
|
|
row1[i] += windowed * grain.panGainR
|
|
|
|
grain.phase += grain.phaseInc
|
|
if grain.phase >= captureSizeF { grain.phase -= captureSizeF }
|
|
if grain.phase < 0 { grain.phase += captureSizeF }
|
|
|
|
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
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Writeback scheduling state.
|
|
_hopCounter = hopCounter
|
|
_nextHopSize = nextHopSize
|
|
_hasTriggeredFirstGrain = hasTriggered
|
|
_activeCount = activeCount
|
|
_writeHead = writeHead
|
|
|
|
_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.
|