Add Granulator and Auto Granulator pedals; color-code + filter pedal picker
- StereoGranulator generator: records mono input into a circular buffer and replays overlapping Hann-windowed grains, each randomly panned by `spread` (0 = centred, 1 = full field). Voice pool + control-rate grain size / overlap / spread, all pre-allocated; inlined xorshift64 for grain pans. - GranulatorPedal (.widener): Grain / Overlap / Spread. - AutoGranulatorPedal (.widener): grain size tracks input level via AmplitudeFollower → LinLin, with a Response switch (Loud→Short / Loud→Long) selected by a CrossFade. Min/Max Grain / Overlap / Spread. - Pedal picker (PedalPaletteView): cards colour-coded by a new PedalCategory (Gain/Dynamics/EQ&Filter/Modulation/Pitch/Delay/Reverb/Texture) plus a "filter by type" menu defaulting to All. Tests: generator (seeded determinism + stereo-spread L/R separation) and both pedals (build/non-silent, param/response changes, knobs, registry, preset round-trip). Suite 271. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,253 @@
|
|||||||
|
// StereoGranulator.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation // `cos`/`sin` for the init-time Hann table and per-grain pan gains
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
|
||||||
|
private let stereoGranulatorZeroBlock: [Double] = makeSampleBuffer()
|
||||||
|
|
||||||
|
/// Stereo input granulator: records the mono input into a circular buffer and replays it as a
|
||||||
|
/// cloud of overlapping Hann-windowed grains, each randomly panned across the stereo field by
|
||||||
|
/// `spread`.
|
||||||
|
///
|
||||||
|
/// Each grain is a unity-speed windowed copy of the most recent `grainSize` of audio (so the cloud
|
||||||
|
/// thickens and smears the input without changing pitch). Grains are spawned every
|
||||||
|
/// `grainSize / overlap` samples from a fixed voice pool; each grain's pan is a fresh random value
|
||||||
|
/// in `[-1, 1] × spread` turned into equal-power L/R gains. `spread = 0` collapses every grain to
|
||||||
|
/// centre (mono); `spread = 1` scatters grains across the full field.
|
||||||
|
///
|
||||||
|
/// `grainSize`, `overlap`, and `spread` are read at control rate (once per block). Output is two
|
||||||
|
/// channels (`[0]` = left, `[1]` = right) — use the ``left`` / ``right`` accessors.
|
||||||
|
///
|
||||||
|
/// - Important: All buffers and the grain voice pool are pre-allocated at `init` for `maxGrainSize`
|
||||||
|
/// seconds — the RT path never allocates or resizes.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - input: Audio-rate mono signal to granulate.
|
||||||
|
/// - maxGrainSize: Largest grain length in seconds; sizes the pre-allocated buffer.
|
||||||
|
/// - grainSize: Grain length in seconds. Control rate; clamped to `[~0.003, maxGrainSize]`.
|
||||||
|
/// - overlap: Number of overlapping grains (spawn density). Control rate; clamped to `[1, 24]`.
|
||||||
|
/// - spread: Stereo spread `[0, 1]` — scales each grain's random pan. Control rate.
|
||||||
|
/// - sampleRate: Sample rate used to size the buffer and convert seconds → frames.
|
||||||
|
/// - seed: Optional PRNG seed for deterministic grain panning (tests). Defaults to time-based.
|
||||||
|
public final class StereoGranulator: GeneratorBase, AudioGenerator {
|
||||||
|
|
||||||
|
// MARK: - Inputs
|
||||||
|
|
||||||
|
let _input: any ValidGeneratorInput
|
||||||
|
let _inputIsGenerator: Bool
|
||||||
|
let _grainSize: any ValidGeneratorInput
|
||||||
|
let _overlap: any ValidGeneratorInput
|
||||||
|
let _spread: any ValidGeneratorInput
|
||||||
|
|
||||||
|
// MARK: - Buffers + state
|
||||||
|
|
||||||
|
private var _buffer: [Double]
|
||||||
|
private let _mask: Int
|
||||||
|
private var _writeHead: Int = 0
|
||||||
|
|
||||||
|
private let _maxGrainFrames: Int
|
||||||
|
private let _minGrainFrames: Int
|
||||||
|
|
||||||
|
/// Precomputed unit Hann window, indexed by `phase · hannSize / grainLen`.
|
||||||
|
private var _hann: [Double]
|
||||||
|
private let _hannSize: Int = 2048
|
||||||
|
|
||||||
|
// Grain voice pool (fixed size; a grain that can't find a free voice is skipped).
|
||||||
|
private static let maxVoices: Int = 24
|
||||||
|
private var _vActive: [Bool]
|
||||||
|
private var _vReadHead: [Int]
|
||||||
|
private var _vPhase: [Int]
|
||||||
|
private var _vLen: [Int]
|
||||||
|
private var _vGainL: [Double]
|
||||||
|
private var _vGainR: [Double]
|
||||||
|
|
||||||
|
private var _spawnCountdown: Int = 0
|
||||||
|
private var _rng: UInt64
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
private let minGrainSeconds: Double = 0.003
|
||||||
|
/// Equal-power pan: `angle = (pan + 1) · π/4`, `gainL = cos`, `gainR = sin`.
|
||||||
|
private let panAngleScale: Double = Double.pi / 4.0
|
||||||
|
/// Non-zero fallback PRNG seed (golden-ratio constant).
|
||||||
|
private static let defaultSeed: UInt64 = 0x9E37_79B9_7F4A_7C15
|
||||||
|
|
||||||
|
public override var outputChannelCount: Int { 2 }
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
public init(
|
||||||
|
input: any ValidGeneratorInput,
|
||||||
|
maxGrainSize: Double,
|
||||||
|
grainSize: any ValidGeneratorInput,
|
||||||
|
overlap: any ValidGeneratorInput,
|
||||||
|
spread: any ValidGeneratorInput,
|
||||||
|
sampleRate: Double,
|
||||||
|
seed: UInt64? = nil
|
||||||
|
) {
|
||||||
|
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||||
|
_input = resolvedInput
|
||||||
|
_inputIsGenerator = resolvedInput is any Generator
|
||||||
|
_grainSize = grainSize._resolvedInput()
|
||||||
|
_overlap = overlap._resolvedInput()
|
||||||
|
_spread = spread._resolvedInput()
|
||||||
|
|
||||||
|
let maxFrames: Int = max(1, Int((maxGrainSize * sampleRate).rounded()))
|
||||||
|
_maxGrainFrames = maxFrames
|
||||||
|
_minGrainFrames = max(1, Int((minGrainSeconds * sampleRate).rounded()))
|
||||||
|
|
||||||
|
// A grain reads the `grainLen` samples behind the write head while the head writes
|
||||||
|
// `grainLen` ahead during the grain's life — disjoint spans needing ≥ 2·maxGrainFrames.
|
||||||
|
// Round up to a power of two for branchless `& _mask` wrapping.
|
||||||
|
let needed: Int = 2 * maxFrames + 2
|
||||||
|
var size: Int = 1
|
||||||
|
while size < needed { size <<= 1 }
|
||||||
|
_buffer = [Double](repeating: 0.0, count: size)
|
||||||
|
_mask = size - 1
|
||||||
|
|
||||||
|
_vActive = [Bool](repeating: false, count: StereoGranulator.maxVoices)
|
||||||
|
_vReadHead = [Int](repeating: 0, count: StereoGranulator.maxVoices)
|
||||||
|
_vPhase = [Int](repeating: 0, count: StereoGranulator.maxVoices)
|
||||||
|
_vLen = [Int](repeating: 1, count: StereoGranulator.maxVoices)
|
||||||
|
_vGainL = [Double](repeating: 0.0, count: StereoGranulator.maxVoices)
|
||||||
|
_vGainR = [Double](repeating: 0.0, count: StereoGranulator.maxVoices)
|
||||||
|
|
||||||
|
var hann: [Double] = [Double](repeating: 0.0, count: _hannSize)
|
||||||
|
let twoPi: Double = 2.0 * Double.pi
|
||||||
|
for i: Int in 0..<_hannSize {
|
||||||
|
hann[i] = 0.5 - 0.5 * cos(twoPi * Double(i) / Double(_hannSize))
|
||||||
|
}
|
||||||
|
_hann = hann
|
||||||
|
|
||||||
|
let requestedSeed: UInt64 = seed ?? StereoGranulator.defaultSeed
|
||||||
|
_rng = requestedSeed == 0 ? StereoGranulator.defaultSeed : requestedSeed
|
||||||
|
|
||||||
|
super.init(channels: 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Render
|
||||||
|
|
||||||
|
public func _computeSamples(
|
||||||
|
graph: SynthGraph,
|
||||||
|
count: Int
|
||||||
|
) -> [[Double]] {
|
||||||
|
_checkCount(count)
|
||||||
|
guard count > 0 else { return _result }
|
||||||
|
|
||||||
|
let sampleRate: Double = graph.engine.sampleRate
|
||||||
|
|
||||||
|
let rawGrain: Double = _grainSize.floatValue(graph: graph)
|
||||||
|
let grainSeconds: Double = rawGrain.isFinite
|
||||||
|
? min(max(rawGrain, minGrainSeconds), Double(_maxGrainFrames) / sampleRate)
|
||||||
|
: minGrainSeconds
|
||||||
|
let grainLen: Int = min(max(Int((grainSeconds * sampleRate).rounded()), _minGrainFrames), _maxGrainFrames)
|
||||||
|
|
||||||
|
let rawOverlap: Double = _overlap.floatValue(graph: graph)
|
||||||
|
let overlap: Int = rawOverlap.isFinite
|
||||||
|
? min(max(Int(rawOverlap.rounded()), 1), StereoGranulator.maxVoices)
|
||||||
|
: 1
|
||||||
|
|
||||||
|
let rawSpread: Double = _spread.floatValue(graph: graph)
|
||||||
|
let spread: Double = rawSpread.isFinite ? min(max(rawSpread, 0.0), 1.0) : 0.0
|
||||||
|
|
||||||
|
let spawnPeriod: Int = max(1, grainLen / overlap)
|
||||||
|
|
||||||
|
let inputSamples: [Double] = _inputIsGenerator
|
||||||
|
? (_input.calculatedSamples(graph: graph, count: count).first ?? stereoGranulatorZeroBlock)
|
||||||
|
: stereoGranulatorZeroBlock
|
||||||
|
let inputCount: Int = inputSamples.count
|
||||||
|
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||||
|
|
||||||
|
var writeHead: Int = _writeHead
|
||||||
|
var spawnCountdown: Int = _spawnCountdown
|
||||||
|
var rng: UInt64 = _rng
|
||||||
|
|
||||||
|
for i: Int in 0..<count {
|
||||||
|
let x: Double = _inputIsGenerator
|
||||||
|
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||||
|
: inputScalar
|
||||||
|
_buffer[writeHead & _mask] = x
|
||||||
|
|
||||||
|
var left: Double = 0.0
|
||||||
|
var right: Double = 0.0
|
||||||
|
for v: Int in 0..<StereoGranulator.maxVoices where _vActive[v] {
|
||||||
|
let phase: Int = _vPhase[v]
|
||||||
|
let len: Int = _vLen[v]
|
||||||
|
let windowIndex: Int = phase * _hannSize / len
|
||||||
|
let windowed: Double = _buffer[_vReadHead[v] & _mask] * _hann[windowIndex]
|
||||||
|
left += windowed * _vGainL[v]
|
||||||
|
right += windowed * _vGainR[v]
|
||||||
|
_vReadHead[v] = _vReadHead[v] + 1
|
||||||
|
let nextPhase: Int = phase + 1
|
||||||
|
if nextPhase >= len {
|
||||||
|
_vActive[v] = false
|
||||||
|
} else {
|
||||||
|
_vPhase[v] = nextPhase
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
spawnCountdown -= 1
|
||||||
|
if spawnCountdown <= 0 {
|
||||||
|
spawnCountdown = spawnPeriod
|
||||||
|
spawnGrain(grainLen: grainLen, spread: spread, writeHead: writeHead, rng: &rng)
|
||||||
|
}
|
||||||
|
|
||||||
|
writeHead = writeHead + 1
|
||||||
|
_result[0][i] = left
|
||||||
|
_result[1][i] = right
|
||||||
|
}
|
||||||
|
|
||||||
|
_writeHead = writeHead
|
||||||
|
_spawnCountdown = spawnCountdown
|
||||||
|
_rng = rng
|
||||||
|
return _result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Activates the first free grain voice (no-op if all are busy — overlap saturates gracefully).
|
||||||
|
private func spawnGrain(
|
||||||
|
grainLen: Int,
|
||||||
|
spread: Double,
|
||||||
|
writeHead: Int,
|
||||||
|
rng: inout UInt64
|
||||||
|
) {
|
||||||
|
var voice: Int = -1
|
||||||
|
for v: Int in 0..<StereoGranulator.maxVoices where !_vActive[v] {
|
||||||
|
voice = v
|
||||||
|
break
|
||||||
|
}
|
||||||
|
guard voice >= 0 else { return }
|
||||||
|
|
||||||
|
_vActive[voice] = true
|
||||||
|
_vPhase[voice] = 0
|
||||||
|
_vLen[voice] = grainLen
|
||||||
|
// Read the grainLen samples just before the write head.
|
||||||
|
_vReadHead[voice] = writeHead - grainLen
|
||||||
|
let pan: Double = StereoGranulator.nextBipolar(&rng) * spread
|
||||||
|
let angle: Double = (pan + 1.0) * panAngleScale
|
||||||
|
_vGainL[voice] = cos(angle)
|
||||||
|
_vGainR[voice] = sin(angle)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// xorshift64 step → uniform Double in `[-1, 1)`. RT-safe (no allocation, no locks).
|
||||||
|
@inline(__always)
|
||||||
|
private static func nextBipolar(_ state: inout UInt64) -> Double {
|
||||||
|
state ^= state << 13
|
||||||
|
state ^= state >> 7
|
||||||
|
state ^= state << 17
|
||||||
|
return Double(state) / Double(UInt64.max) * 2.0 - 1.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Channel accessors
|
||||||
|
|
||||||
|
public extension StereoGranulator {
|
||||||
|
/// Left output channel.
|
||||||
|
var left: ChannelSelect.Audio { self[0] }
|
||||||
|
/// Right output channel.
|
||||||
|
var right: ChannelSelect.Audio { self[1] }
|
||||||
|
}
|
||||||
@@ -67,6 +67,8 @@ public extension PedalType {
|
|||||||
static let ringModulator = PedalType("Ring Modulator")
|
static let ringModulator = PedalType("Ring Modulator")
|
||||||
static let diffuser = PedalType("Diffuser")
|
static let diffuser = PedalType("Diffuser")
|
||||||
static let bitcrusher = PedalType("Bitcrusher")
|
static let bitcrusher = PedalType("Bitcrusher")
|
||||||
|
static let granulator = PedalType("Granulator")
|
||||||
|
static let autoGranulator = PedalType("Auto Granulator")
|
||||||
|
|
||||||
// Dynamics (additional)
|
// Dynamics (additional)
|
||||||
static let sustainer = PedalType("Sustainer")
|
static let sustainer = PedalType("Sustainer")
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
// AutoGranulatorPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Amplitude-tracking stereo granulator.
|
||||||
|
///
|
||||||
|
/// Like ``GranulatorPedal``, but the grain size follows the input level: by default louder playing
|
||||||
|
/// uses the **minimum** grain size and softer playing the **maximum** (so dynamics shrink and grow
|
||||||
|
/// the grains). The `Response` switch flips that relationship. Grains are randomly scattered across
|
||||||
|
/// the stereo field by `Spread`. Wraps ``StereoGranulator`` as a `.widener`.
|
||||||
|
///
|
||||||
|
/// The level → grain-size map is `AmplitudeFollower` → `LinLin`, with a `CrossFade` selecting the
|
||||||
|
/// normal vs flipped mapping from the `Response` switch.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `minGrain`: Minimum grain size in seconds. Range `[0.005, 0.1]`.
|
||||||
|
/// - `maxGrain`: Maximum grain size in seconds. Range `[0.05, 0.4]`.
|
||||||
|
/// - `overlap`: Overlapping grain count (density). Range `[1, 16]`.
|
||||||
|
/// - `spread`: Stereo spread `[0, 1]`.
|
||||||
|
///
|
||||||
|
/// ## Switches
|
||||||
|
/// - `response` (two-state): `0` = Loud → Short grains, `1` = Loud → Long grains.
|
||||||
|
public final class AutoGranulatorPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"Granular wash whose grain size tracks your dynamics — loud shrinks grains, soft grows them."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// Minimum grain size in seconds. Range [0.005, 0.1].
|
||||||
|
@UIParam public var minGrain: Double = 0.02
|
||||||
|
|
||||||
|
/// Maximum grain size in seconds. Range [0.05, 0.4].
|
||||||
|
@UIParam public var maxGrain: Double = 0.25
|
||||||
|
|
||||||
|
/// Overlapping grain count (density). Range [1, 16].
|
||||||
|
@UIParam public var overlap: Double = 4.0
|
||||||
|
|
||||||
|
/// Stereo spread [0, 1].
|
||||||
|
@UIParam public var spread: Double = 0.7
|
||||||
|
|
||||||
|
/// Level → grain-size response. `0` = Loud → Short, `1` = Loud → Long. Two-state switch.
|
||||||
|
@UIParam public var response: Double = 0.0
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
private static let defaultMix: Double = 0.5
|
||||||
|
/// Largest grain the buffer is allocated for, in seconds (≥ the `maxGrain` knob maximum).
|
||||||
|
private let maxGrainSize: Double = 0.4
|
||||||
|
/// Amplitude at which the grain size reaches its loud-end value (follower output is unbounded;
|
||||||
|
/// this sets the sensitivity). Values above it are clamped by the generator's grain-size clamp.
|
||||||
|
private let ampSensitivity: Double = 0.5
|
||||||
|
private let amplitudeAttack: Double = 0.01
|
||||||
|
private let amplitudeRelease: Double = 0.2
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
private let minGrainRange: ClosedRange<Double> = 0.005 ... 0.1
|
||||||
|
private let maxGrainRange: ClosedRange<Double> = 0.05 ... 0.4
|
||||||
|
private let overlapRange: ClosedRange<Double> = 1.0 ... 16.0
|
||||||
|
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Min Grain", node: $minGrain, range: minGrainRange),
|
||||||
|
PedalKnob(label: "Max Grain", node: $maxGrain, range: maxGrainRange),
|
||||||
|
PedalKnob(label: "Overlap", node: $overlap, range: overlapRange),
|
||||||
|
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Switches
|
||||||
|
|
||||||
|
private let responseLoudShortValue: Double = 0.0
|
||||||
|
private let responseLoudLongValue: Double = 1.0
|
||||||
|
|
||||||
|
public override var effectSwitches: [PedalSwitch] {
|
||||||
|
[
|
||||||
|
PedalSwitch(
|
||||||
|
label: "Response",
|
||||||
|
node: $response,
|
||||||
|
options: [
|
||||||
|
PedalSwitch.Option(title: "Loud→Short", value: responseLoudShortValue),
|
||||||
|
PedalSwitch.Option(title: "Loud→Long", value: responseLoudLongValue),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Channel topology
|
||||||
|
|
||||||
|
public override var channelKind: PedalChannelKind { .widener }
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates an amplitude-tracking granulator pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Auto Granulator",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: AutoGranulatorPedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func wideEffect(
|
||||||
|
_ dry: any ValidGeneratorInput
|
||||||
|
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||||
|
let amplitude: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||||
|
in: dry,
|
||||||
|
attackTime: amplitudeAttack,
|
||||||
|
releaseTime: amplitudeRelease
|
||||||
|
)
|
||||||
|
// Loud → short: amp 0 → maxGrain, amp ampSensitivity → minGrain.
|
||||||
|
let loudShort: LinLin.Audio = LinLin.Audio(
|
||||||
|
amplitude, inLo: 0.0, inHi: ampSensitivity, outLo: $maxGrain, outHi: $minGrain
|
||||||
|
)
|
||||||
|
// Loud → long: amp 0 → minGrain, amp ampSensitivity → maxGrain.
|
||||||
|
let loudLong: LinLin.Audio = LinLin.Audio(
|
||||||
|
amplitude, inLo: 0.0, inHi: ampSensitivity, outLo: $minGrain, outHi: $maxGrain
|
||||||
|
)
|
||||||
|
// `response` 0 → pan −1 → loudShort; 1 → pan +1 → loudLong (endpoints are full A / full B).
|
||||||
|
let grainSize: CrossFade.Audio = CrossFade.Audio(
|
||||||
|
inA: loudShort, inB: loudLong, pan: $response * 2.0 - 1.0
|
||||||
|
)
|
||||||
|
|
||||||
|
let granulator: StereoGranulator = StereoGranulator(
|
||||||
|
input: dry,
|
||||||
|
maxGrainSize: maxGrainSize,
|
||||||
|
grainSize: grainSize,
|
||||||
|
overlap: $overlap,
|
||||||
|
spread: $spread,
|
||||||
|
sampleRate: sampleRate
|
||||||
|
)
|
||||||
|
return (granulator.left, granulator.right)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
// GranulatorPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Stereo input granulator.
|
||||||
|
///
|
||||||
|
/// Chops the input into a cloud of overlapping windowed grains, each randomly scattered across the
|
||||||
|
/// stereo field by `Spread`, for a lush, smeared, widened texture. Wraps the ``StereoGranulator``
|
||||||
|
/// generator (mono in → stereo out) as a `.widener`.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `grain`: Grain size in seconds. Range `[0.01, 0.5]`.
|
||||||
|
/// - `overlap`: Overlapping grain count (density). Range `[1, 16]`.
|
||||||
|
/// - `spread`: Stereo spread `[0, 1]` — 0 = centred (mono), 1 = full field.
|
||||||
|
public final class GranulatorPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"Scatters overlapping grains of your sound across the stereo field — a lush, smeared wash."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// Grain size in seconds. Range [0.01, 0.5].
|
||||||
|
@UIParam public var grain: Double = 0.08
|
||||||
|
|
||||||
|
/// Overlapping grain count (density). Range [1, 16].
|
||||||
|
@UIParam public var overlap: Double = 4.0
|
||||||
|
|
||||||
|
/// Stereo spread [0, 1].
|
||||||
|
@UIParam public var spread: Double = 0.7
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
private static let defaultMix: Double = 0.5
|
||||||
|
/// Largest grain the buffer is allocated for, in seconds (≥ the `grain` knob maximum).
|
||||||
|
private let maxGrainSize: Double = 0.5
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
private let grainRange: ClosedRange<Double> = 0.01 ... 0.5
|
||||||
|
private let overlapRange: ClosedRange<Double> = 1.0 ... 16.0
|
||||||
|
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Grain", node: $grain, range: grainRange),
|
||||||
|
PedalKnob(label: "Overlap", node: $overlap, range: overlapRange),
|
||||||
|
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Channel topology
|
||||||
|
|
||||||
|
public override var channelKind: PedalChannelKind { .widener }
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a granulator pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Granulator",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: GranulatorPedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func wideEffect(
|
||||||
|
_ dry: any ValidGeneratorInput
|
||||||
|
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||||
|
let granulator: StereoGranulator = StereoGranulator(
|
||||||
|
input: dry,
|
||||||
|
maxGrainSize: maxGrainSize,
|
||||||
|
grainSize: $grain,
|
||||||
|
overlap: $overlap,
|
||||||
|
spread: $spread,
|
||||||
|
sampleRate: sampleRate
|
||||||
|
)
|
||||||
|
return (granulator.left, granulator.right)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -61,6 +61,8 @@ public enum PedalRegistry {
|
|||||||
"Ring Modulator": { RingModulatorPedal() },
|
"Ring Modulator": { RingModulatorPedal() },
|
||||||
"Diffuser": { DiffuserPedal() },
|
"Diffuser": { DiffuserPedal() },
|
||||||
"Bitcrusher": { BitcrusherPedal() },
|
"Bitcrusher": { BitcrusherPedal() },
|
||||||
|
"Granulator": { GranulatorPedal() },
|
||||||
|
"Auto Granulator": { AutoGranulatorPedal() },
|
||||||
]
|
]
|
||||||
|
|
||||||
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
|
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
// PedalCategory.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import SwiftUI
|
||||||
|
|
||||||
|
/// A presentation grouping for pedals in the palette — used to colour-code the picker cards and to
|
||||||
|
/// drive the "filter by type" menu. Purely a UI concern: the mapping from a pedal's `displayName`
|
||||||
|
/// to its category lives here, keyed by name like ``PedalPaletteView``'s preferred order.
|
||||||
|
enum PedalCategory: String, CaseIterable, Identifiable {
|
||||||
|
case gain = "Gain"
|
||||||
|
case dynamics = "Dynamics"
|
||||||
|
case filter = "EQ & Filter"
|
||||||
|
case modulation = "Modulation"
|
||||||
|
case pitch = "Pitch"
|
||||||
|
case delay = "Delay"
|
||||||
|
case reverb = "Reverb"
|
||||||
|
case texture = "Texture"
|
||||||
|
|
||||||
|
var id: String { rawValue }
|
||||||
|
|
||||||
|
/// Accent colour used to tint the palette card and the filter chip.
|
||||||
|
var color: Color {
|
||||||
|
switch self {
|
||||||
|
case .gain: return Color(red: 0.82, green: 0.38, blue: 0.12)
|
||||||
|
case .dynamics: return Color(red: 0.20, green: 0.50, blue: 0.32)
|
||||||
|
case .filter: return Color(red: 0.14, green: 0.46, blue: 0.55)
|
||||||
|
case .modulation: return Color(red: 0.40, green: 0.34, blue: 0.74)
|
||||||
|
case .pitch: return Color(red: 0.60, green: 0.26, blue: 0.50)
|
||||||
|
case .delay: return Color(red: 0.10, green: 0.52, blue: 0.62)
|
||||||
|
case .reverb: return Color(red: 0.34, green: 0.22, blue: 0.66)
|
||||||
|
case .texture: return Color(red: 0.48, green: 0.42, blue: 0.30)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The category for a pedal `displayName`. Unknown (e.g. third-party) names fall back to
|
||||||
|
/// ``texture`` so they remain visible and tinted.
|
||||||
|
static func category(for displayName: String) -> PedalCategory {
|
||||||
|
mapping[displayName] ?? .texture
|
||||||
|
}
|
||||||
|
|
||||||
|
private static let mapping: [String: PedalCategory] = [
|
||||||
|
"Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain,
|
||||||
|
"Compressor": .dynamics, "Sustainer": .dynamics, "Limiter": .dynamics, "Noise Gate": .dynamics,
|
||||||
|
"Graphic EQ": .filter, "Auto-Wah": .filter, "Mutant": .filter,
|
||||||
|
"Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation,
|
||||||
|
"Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation,
|
||||||
|
"Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch,
|
||||||
|
"Delay": .delay, "Feedback Delay": .delay, "Multi-Tap Delay": .delay, "Ping-Pong": .delay,
|
||||||
|
"Reverse Delay": .delay,
|
||||||
|
"Reverb": .reverb, "Shimmer Reverb": .reverb,
|
||||||
|
"Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture,
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -38,6 +38,9 @@ public struct PedalPaletteView: View {
|
|||||||
private static let cardBorderWidth: CGFloat = 1
|
private static let cardBorderWidth: CGFloat = 1
|
||||||
private static let pedalCardBrightness: Double = 0.18
|
private static let pedalCardBrightness: Double = 0.18
|
||||||
private static let routingCardBrightness: Double = 0.1
|
private static let routingCardBrightness: Double = 0.1
|
||||||
|
/// Category-colour fill / border opacity for the colour-coded pedal cards.
|
||||||
|
private static let categoryFillOpacity: Double = 0.22
|
||||||
|
private static let categoryBorderOpacity: Double = 0.65
|
||||||
private static let routingCaptionOpacity: Double = 0.5
|
private static let routingCaptionOpacity: Double = 0.5
|
||||||
private static let routingCaptionFontSize: CGFloat = 10
|
private static let routingCaptionFontSize: CGFloat = 10
|
||||||
private static let addGlyphOpacity: Double = 0.4
|
private static let addGlyphOpacity: Double = 0.4
|
||||||
@@ -53,8 +56,8 @@ public struct PedalPaletteView: View {
|
|||||||
private static let preferredOrder: [String] = [
|
private static let preferredOrder: [String] = [
|
||||||
"Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
|
"Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
|
||||||
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
|
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
|
||||||
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Bass Octaver",
|
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator",
|
||||||
"Octave Splitter", "Harmonizer",
|
"Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer",
|
||||||
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
|
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
|
||||||
"Shimmer Reverb",
|
"Shimmer Reverb",
|
||||||
]
|
]
|
||||||
@@ -80,6 +83,9 @@ public struct PedalPaletteView: View {
|
|||||||
private let onRouting: (RoutingAction) -> Void
|
private let onRouting: (RoutingAction) -> Void
|
||||||
private let axis: Axis
|
private let axis: Axis
|
||||||
|
|
||||||
|
/// Active type filter; `nil` shows all pedals.
|
||||||
|
@State private var filter: PedalCategory?
|
||||||
|
|
||||||
// MARK: - Init
|
// MARK: - Init
|
||||||
|
|
||||||
/// Creates a pedal palette.
|
/// Creates a pedal palette.
|
||||||
@@ -111,6 +117,12 @@ public struct PedalPaletteView: View {
|
|||||||
return ordered + extras
|
return ordered + extras
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Pedal names after applying the active type filter.
|
||||||
|
private var visiblePedalNames: [String] {
|
||||||
|
guard let filter: PedalCategory = filter else { return orderedPedalNames }
|
||||||
|
return orderedPedalNames.filter { PedalCategory.category(for: $0) == filter }
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Body
|
// MARK: - Body
|
||||||
|
|
||||||
public var body: some View {
|
public var body: some View {
|
||||||
@@ -124,8 +136,12 @@ public struct PedalPaletteView: View {
|
|||||||
private var verticalBody: some View {
|
private var verticalBody: some View {
|
||||||
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
|
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
|
||||||
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
|
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
|
||||||
sectionTitle("PEDALS")
|
HStack {
|
||||||
ForEach(orderedPedalNames, id: \.self) { name in
|
sectionTitle("PEDALS")
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
filterMenu
|
||||||
|
}
|
||||||
|
ForEach(visiblePedalNames, id: \.self) { name in
|
||||||
pedalRow(name)
|
pedalRow(name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,12 +155,15 @@ public struct PedalPaletteView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fixed-width-card row for a horizontal scroller: leading PEDALS group, a divider, then the
|
/// Fixed-width-card row for a horizontal scroller: leading filter + PEDALS group, a divider,
|
||||||
/// ROUTING group.
|
/// then the ROUTING group.
|
||||||
private var horizontalBody: some View {
|
private var horizontalBody: some View {
|
||||||
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
|
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
|
||||||
sectionTitle("PEDALS")
|
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
|
||||||
ForEach(orderedPedalNames, id: \.self) { name in
|
sectionTitle("PEDALS")
|
||||||
|
filterMenu
|
||||||
|
}
|
||||||
|
ForEach(visiblePedalNames, id: \.self) { name in
|
||||||
pedalRow(name)
|
pedalRow(name)
|
||||||
}
|
}
|
||||||
Divider().overlay(Color.white.opacity(PedalPaletteView.cardBorderOpacity))
|
Divider().overlay(Color.white.opacity(PedalPaletteView.cardBorderOpacity))
|
||||||
@@ -163,6 +182,26 @@ public struct PedalPaletteView: View {
|
|||||||
.foregroundStyle(Color.white.opacity(PedalPaletteView.titleOpacity))
|
.foregroundStyle(Color.white.opacity(PedalPaletteView.titleOpacity))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// "Filter by type" menu — defaults to **All** (no filtering).
|
||||||
|
private var filterMenu: some View {
|
||||||
|
Menu {
|
||||||
|
Button("All Types") { filter = nil }
|
||||||
|
Divider()
|
||||||
|
ForEach(PedalCategory.allCases) { category in
|
||||||
|
Button(category.rawValue) { filter = category }
|
||||||
|
}
|
||||||
|
} label: {
|
||||||
|
HStack(spacing: 3) {
|
||||||
|
Image(systemName: "line.3.horizontal.decrease.circle")
|
||||||
|
Text(filter?.rawValue ?? "All").lineLimit(1)
|
||||||
|
}
|
||||||
|
.font(.system(size: PedalPaletteView.titleFontSize))
|
||||||
|
.foregroundStyle((filter?.color ?? Color.white).opacity(0.9))
|
||||||
|
}
|
||||||
|
.menuStyle(.borderlessButton)
|
||||||
|
.fixedSize()
|
||||||
|
}
|
||||||
|
|
||||||
/// A full-width pedal row: tap appends to the main chain; drag carries `"add:<name>"` so it can
|
/// A full-width pedal row: tap appends to the main chain; drag carries `"add:<name>"` so it can
|
||||||
/// be dropped onto a stereo/parallel lane.
|
/// be dropped onto a stereo/parallel lane.
|
||||||
private func pedalRow(_ name: String) -> some View {
|
private func pedalRow(_ name: String) -> some View {
|
||||||
@@ -193,12 +232,24 @@ public struct PedalPaletteView: View {
|
|||||||
.padding(.horizontal, PedalPaletteView.cardPaddingH)
|
.padding(.horizontal, PedalPaletteView.cardPaddingH)
|
||||||
.padding(.vertical, PedalPaletteView.cardPaddingV)
|
.padding(.vertical, PedalPaletteView.cardPaddingV)
|
||||||
.modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth))
|
.modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth))
|
||||||
.background(cardBackground(brightness: PedalPaletteView.pedalCardBrightness))
|
.background(categoryCardBackground(PedalCategory.category(for: name).color))
|
||||||
}
|
}
|
||||||
.buttonStyle(.plain)
|
.buttonStyle(.plain)
|
||||||
.draggable("add:\(name)")
|
.draggable("add:\(name)")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Category-tinted card background — a low-opacity fill plus a stronger border in the category
|
||||||
|
/// colour, so palette blocks are colour-coded by type.
|
||||||
|
private func categoryCardBackground(_ color: Color) -> some View {
|
||||||
|
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
|
||||||
|
.fill(color.opacity(PedalPaletteView.categoryFillOpacity))
|
||||||
|
.overlay(
|
||||||
|
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
|
||||||
|
.stroke(color.opacity(PedalPaletteView.categoryBorderOpacity),
|
||||||
|
lineWidth: PedalPaletteView.cardBorderWidth)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// A tappable routing row that inserts a region/node into the board.
|
/// A tappable routing row that inserts a region/node into the board.
|
||||||
private func routingCard(title: String, caption: String, action: RoutingAction) -> some View {
|
private func routingCard(title: String, caption: String, action: RoutingAction) -> some View {
|
||||||
Button {
|
Button {
|
||||||
|
|||||||
@@ -43,6 +43,8 @@ private func enclosureColor(for displayName: String) -> Color {
|
|||||||
case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle
|
case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle
|
||||||
case "Harmonizer": return Color(red: 0.52, green: 0.20, blue: 0.40) // wine / mauve
|
case "Harmonizer": return Color(red: 0.52, green: 0.20, blue: 0.40) // wine / mauve
|
||||||
case "Bitcrusher": return Color(red: 0.30, green: 0.34, blue: 0.40) // slate / digital gray
|
case "Bitcrusher": return Color(red: 0.30, green: 0.34, blue: 0.40) // slate / digital gray
|
||||||
|
case "Granulator": return Color(red: 0.20, green: 0.55, blue: 0.50) // sea green
|
||||||
|
case "Auto Granulator": return Color(red: 0.24, green: 0.50, blue: 0.56) // teal-aqua
|
||||||
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
|
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
// AutoGranulatorPedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("AutoGranulatorPedal")
|
||||||
|
struct AutoGranulatorPedalTests {
|
||||||
|
|
||||||
|
private func render(
|
||||||
|
configure: (AutoGranulatorPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let renderDuration: Double = 0.2
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: renderDuration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
|
||||||
|
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||||
|
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
|
||||||
|
defer {
|
||||||
|
engine.busAllocator.releaseAudioBus(srcBus)
|
||||||
|
engine.busAllocator.releaseAudioBus(dstBus)
|
||||||
|
}
|
||||||
|
|
||||||
|
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||||
|
let pedal: AutoGranulatorPedal = AutoGranulatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||||
|
|
||||||
|
try engine.add(source)
|
||||||
|
try engine.add(pedal, position: NodePosition.after(source))
|
||||||
|
try engine.add(master, position: NodePosition.after(pedal))
|
||||||
|
try engine.start()
|
||||||
|
|
||||||
|
return readStereoCAF(url: url)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
zip(a, b).reduce(0.0) { acc, pair in
|
||||||
|
let diff: Double = Double(pair.0 - pair.1)
|
||||||
|
return acc + diff * diff
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Small min/max grains so audible output (which trails the write head by one grain) fills the
|
||||||
|
// reader's 4096-frame window.
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let samples: [Float] = try render { pedal in pedal.minGrain = 0.01; pedal.maxGrain = 0.03 }
|
||||||
|
#expect(!samples.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(samples), "auto granulator output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func responseSwitchChangesOutput() throws {
|
||||||
|
let loudShort: [Float] = try render { pedal in pedal.minGrain = 0.008; pedal.maxGrain = 0.02; pedal.response = 0.0; pedal.mix = 1.0 }
|
||||||
|
let loudLong: [Float] = try render { pedal in pedal.minGrain = 0.008; pedal.maxGrain = 0.02; pedal.response = 1.0; pedal.mix = 1.0 }
|
||||||
|
#expect(hasNonSilentOutput(loudLong), "flipped-response granulator was silent")
|
||||||
|
#expect(totalSSD(loudShort, loudLong) > 0, "flipping the response did not change the output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func exposesKnobsAndResponseSwitch() throws {
|
||||||
|
let pedal: AutoGranulatorPedal = AutoGranulatorPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Min Grain", "Max Grain", "Overlap", "Spread"])
|
||||||
|
#expect(pedal.effectSwitches.map { $0.label } == ["Response"])
|
||||||
|
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Loud→Short", "Loud→Long"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesResponse() throws {
|
||||||
|
let pedal: AutoGranulatorPedal = AutoGranulatorPedal()
|
||||||
|
pedal.response = 1.0
|
||||||
|
pedal.minGrain = 0.03
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
|
||||||
|
let restored: AutoGranulatorPedal = AutoGranulatorPedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
#expect(restored.response == 1.0)
|
||||||
|
#expect(restored.minGrain == 0.03)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Auto Granulator")
|
||||||
|
#expect(pedal is AutoGranulatorPedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
// GranulatorPedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("GranulatorPedal")
|
||||||
|
struct GranulatorPedalTests {
|
||||||
|
|
||||||
|
private func render(
|
||||||
|
configure: (GranulatorPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let renderDuration: Double = 0.2
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: renderDuration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
|
||||||
|
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||||
|
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
|
||||||
|
defer {
|
||||||
|
engine.busAllocator.releaseAudioBus(srcBus)
|
||||||
|
engine.busAllocator.releaseAudioBus(dstBus)
|
||||||
|
}
|
||||||
|
|
||||||
|
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||||
|
let pedal: GranulatorPedal = GranulatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||||
|
|
||||||
|
try engine.add(source)
|
||||||
|
try engine.add(pedal, position: NodePosition.after(source))
|
||||||
|
try engine.add(master, position: NodePosition.after(pedal))
|
||||||
|
try engine.start()
|
||||||
|
|
||||||
|
return readStereoCAF(url: url)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
zip(a, b).reduce(0.0) { acc, pair in
|
||||||
|
let diff: Double = Double(pair.0 - pair.1)
|
||||||
|
return acc + diff * diff
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Small grains so audible output (which trails the write head by one grain) fills the reader's
|
||||||
|
// 4096-frame window rather than starting after a long grain's worth of silence.
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let samples: [Float] = try render { pedal in pedal.grain = 0.02 }
|
||||||
|
#expect(!samples.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(samples), "granulator output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func spreadChangesOutput() throws {
|
||||||
|
let mono: [Float] = try render { pedal in pedal.grain = 0.01; pedal.spread = 0.0; pedal.mix = 1.0 }
|
||||||
|
let wide: [Float] = try render { pedal in pedal.grain = 0.01; pedal.spread = 1.0; pedal.mix = 1.0 }
|
||||||
|
#expect(hasNonSilentOutput(wide), "spread granulator was silent")
|
||||||
|
#expect(totalSSD(mono, wide) > 0, "changing spread did not change the channel output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func grainSizeChangesOutput() throws {
|
||||||
|
let small: [Float] = try render { pedal in pedal.grain = 0.01; pedal.mix = 1.0 }
|
||||||
|
let large: [Float] = try render { pedal in pedal.grain = 0.04; pedal.mix = 1.0 }
|
||||||
|
#expect(totalSSD(small, large) > 0, "changing grain size did not change the output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func exposesGrainOverlapSpreadKnobs() throws {
|
||||||
|
let pedal: GranulatorPedal = GranulatorPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Grain", "Overlap", "Spread"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Granulator")
|
||||||
|
#expect(pedal is GranulatorPedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
// StereoGranulatorTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("StereoGranulator")
|
||||||
|
struct StereoGranulatorTests {
|
||||||
|
|
||||||
|
/// Minimal synth: a sine through a seeded `StereoGranulator`, routing one of its two channels
|
||||||
|
/// to a mono bus so the offline render captures that channel's content.
|
||||||
|
private final class GranSynth: SynthesizerBase {
|
||||||
|
private let channel: Int
|
||||||
|
private let spread: Double
|
||||||
|
private let seed: UInt64
|
||||||
|
private let outBus: Int
|
||||||
|
|
||||||
|
init(channel: Int, spread: Double, seed: UInt64, outBus: Int) {
|
||||||
|
self.channel = channel
|
||||||
|
self.spread = spread
|
||||||
|
self.seed = seed
|
||||||
|
self.outBus = outBus
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
let osc: OscSin.Audio = OscSin.Audio(freq: 220.0)
|
||||||
|
let gran: StereoGranulator = StereoGranulator(
|
||||||
|
input: osc,
|
||||||
|
maxGrainSize: 0.2,
|
||||||
|
grainSize: 0.05,
|
||||||
|
overlap: 4.0,
|
||||||
|
spread: spread,
|
||||||
|
sampleRate: 44100.0,
|
||||||
|
seed: seed
|
||||||
|
)
|
||||||
|
output(bus: outBus, source: channel == 0 ? gran.left : gran.right)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func renderChannel(_ channel: Int, spread: Double, seed: UInt64) throws -> [Float] {
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||||
|
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||||
|
let synth: GranSynth = GranSynth(channel: channel, spread: spread, seed: seed, outBus: dstBus.index)
|
||||||
|
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||||
|
try engine.add(synth)
|
||||||
|
try engine.add(master, position: NodePosition.after(synth))
|
||||||
|
try engine.start()
|
||||||
|
return readStereoCAF(url: url, sampleRate: 44100.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
zip(a, b).reduce(0.0) { acc, pair in
|
||||||
|
let diff: Double = Double(pair.0 - pair.1)
|
||||||
|
return acc + diff * diff
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func producesNonSilentOutput() throws {
|
||||||
|
let samples: [Float] = try renderChannel(0, spread: 0.7, seed: 7)
|
||||||
|
#expect(hasNonSilentOutput(samples), "granulator output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func deterministicForAFixedSeed() throws {
|
||||||
|
let a: [Float] = try renderChannel(0, spread: 1.0, seed: 7)
|
||||||
|
let b: [Float] = try renderChannel(0, spread: 1.0, seed: 7)
|
||||||
|
#expect(totalSSD(a, b) == 0.0, "same seed must produce identical output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func zeroSpreadCentersBothChannels() throws {
|
||||||
|
// spread 0 → every grain pans to centre → left and right channels are identical.
|
||||||
|
let left: [Float] = try renderChannel(0, spread: 0.0, seed: 7)
|
||||||
|
let right: [Float] = try renderChannel(1, spread: 0.0, seed: 7)
|
||||||
|
#expect(totalSSD(left, right) == 0.0, "zero spread should center grains (L == R)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func fullSpreadSeparatesChannels() throws {
|
||||||
|
// spread 1 → grains scatter → left and right differ.
|
||||||
|
let left: [Float] = try renderChannel(0, spread: 1.0, seed: 7)
|
||||||
|
let right: [Float] = try renderChannel(1, spread: 1.0, seed: 7)
|
||||||
|
#expect(hasNonSilentOutput(left) && hasNonSilentOutput(right), "spread channels were silent")
|
||||||
|
#expect(totalSSD(left, right) > 0.0, "full spread should separate L and R")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user