diff --git a/Sources/LyrebirdShoeGaze/Generators/BitReduce.swift b/Sources/LyrebirdShoeGaze/Generators/BitReduce.swift new file mode 100644 index 0000000..611108a --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Generators/BitReduce.swift @@ -0,0 +1,79 @@ +// BitReduce.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates. +private let bitReduceZeroBlock: [Double] = makeSampleBuffer() + +/// Bit-depth reducer: quantises the signal to `2^bits` amplitude levels, producing the gritty +/// quantisation noise of the "bit" half of a lo-fi / bitcrusher effect. +/// +/// `bits` is read at control rate (once per block) and clamped to `[1, 16]`. Each sample is +/// rounded to the nearest step of size `2^(1-bits)` over the `[-1, 1]` range. Output is mono. +public final class BitReduce: GeneratorBase, AudioGenerator { + + /// Resolved input signal. + let _input: any ValidGeneratorInput + + /// `true` when `_input` resolved to a generator; classified once so the RT path runs no + /// `is`/`as?` check. + let _inputIsGenerator: Bool + + /// Quantisation bit depth, read at block rate. Pass a control-rate node or scalar. + let _bits: any ValidGeneratorInput + + /// Quantisation bounds. + private let minimumBits: Double = 1.0 + private let maximumBits: Double = 16.0 + + /// Creates a bit-depth reducer. + /// + /// - Parameters: + /// - input: Signal to quantise. + /// - bits: Bit depth (control rate). Clamped to `[1, 16]`. + public init( + input: any ValidGeneratorInput, + bits: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + _inputIsGenerator = resolvedInput is any Generator + _bits = bits._resolvedInput() + super.init() + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let bits: Double = min(max(_bits.floatValue(graph: graph), minimumBits), maximumBits) + // Number of quantisation levels = 2^bits, via an integer shift (avoids importing `pow`). + let bitsInt: Int = Int(bits.rounded()) + let levels: Double = Double(1 << bitsInt) + // Step between adjacent levels over [-1, 1], and its reciprocal for the round. + let step: Double = 2.0 / levels + let inverseStep: Double = levels / 2.0 + + let inputSamples: [Double] = _inputIsGenerator + ? (_input.calculatedSamples(graph: graph, count: count).first ?? bitReduceZeroBlock) + : bitReduceZeroBlock + let inputCount: Int = inputSamples.count + let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph) + + for i: Int in 0.. [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let sampleRate: Double = graph.engine.sampleRate + let delaySeconds: Double = _delay.floatValue(graph: graph) + let rawFeedback: Double = _feedback.floatValue(graph: graph) + let feedback: Double = min(max(rawFeedback, 0.0), maxFeedback) + + // Target segment length, applied at the next boundary so a read never changes length mid-segment. + let targetLen: Int = min(max(Int((delaySeconds * sampleRate).rounded()), 1), _maxFrames) + + let inputSamples: [Double] = _inputIsGenerator + ? (_input.calculatedSamples(graph: graph, count: count).first ?? reverseDelayZeroBlock) + : reverseDelayZeroBlock + let inputCount: Int = inputSamples.count + let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph) + + var phase: Int = _phase + var segLen: Int = _segLen + var recordIsA: Bool = _recordIsA + let fadeFrames: Int = _fadeFrames + + // Adopt the live delay length on the first block — at `init` the node value isn't known, so + // the segment must not start at the full buffer length (that would delay the first reversed + // segment by `maxDelay`). + if !_segLenInitialized { + segLen = targetLen + phase = 0 + _segLenInitialized = true + } + + _bufferA.withUnsafeMutableBufferPointer { aBuffer in + _bufferB.withUnsafeMutableBufferPointer { bBuffer in + guard let aPointer: UnsafeMutablePointer = aBuffer.baseAddress, + let bPointer: UnsafeMutablePointer = bBuffer.baseAddress else { return } + _result[0].withUnsafeMutableBufferPointer { outBuffer in + guard let outPointer: UnsafeMutablePointer = outBuffer.baseAddress else { return } + + for i: Int in 0.. = recordIsA ? aPointer : bPointer + let playPointer: UnsafeMutablePointer = recordIsA ? bPointer : aPointer + + // Reversed read: end of the play segment first. + let readIndex: Int = segLen - 1 - phase + let raw: Double = playPointer[readIndex] + let envelope: Double = ReverseDelay.edgeFade( + phase: phase, segLen: segLen, fadeFrames: fadeFrames + ) + let out: Double = raw * envelope + + recordPointer[phase] = x + feedback * out + outPointer[i] = out + + phase += 1 + if phase >= segLen { + phase = 0 + recordIsA.toggle() + segLen = targetLen + } + } + } + } + } + + _phase = phase + _segLen = segLen + _recordIsA = recordIsA + return _result + } + + /// Linear raised-edge fade in `[0, 1]`: ramps up over the first `fadeFrames` of a segment and + /// down over the last `fadeFrames`, flat `1` in the middle. De-clicks the reverse wrap. + private static func edgeFade( + phase: Int, + segLen: Int, + fadeFrames: Int + ) -> Double { + let fade: Int = min(fadeFrames, segLen / 2) + guard fade > 0 else { return 1.0 } + let fromStart: Int = phase + let fromEnd: Int = segLen - 1 - phase + let nearestEdge: Int = min(fromStart, fromEnd) + guard nearestEdge < fade else { return 1.0 } + return Double(nearestEdge) / Double(fade) + } +} diff --git a/Sources/LyrebirdShoeGaze/Generators/SampleRateDecimate.swift b/Sources/LyrebirdShoeGaze/Generators/SampleRateDecimate.swift new file mode 100644 index 0000000..ad6681f --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Generators/SampleRateDecimate.swift @@ -0,0 +1,89 @@ +// SampleRateDecimate.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates. +private let sampleRateDecimateZeroBlock: [Double] = makeSampleBuffer() + +/// Sample-rate reducer (decimator): a sample-and-hold that latches a new input value only once +/// every `downsample` samples, holding it in between. The aliased, stair-stepped result is the +/// "crushed sample rate" half of a lo-fi / bitcrusher effect. +/// +/// `downsample` is read at control rate (once per block). `1` passes the signal through; `N` holds +/// each sample for `N` output samples (effective rate `sampleRate / N`). Output is mono (channel 0). +public final class SampleRateDecimate: GeneratorBase, AudioGenerator { + + /// Resolved input signal. + let _input: any ValidGeneratorInput + + /// `true` when `_input` resolved to a generator; classified once so the RT path runs no + /// `is`/`as?` check. + let _inputIsGenerator: Bool + + /// Downsample factor, read at block rate. Pass a control-rate node or scalar. + let _downsample: any ValidGeneratorInput + + /// Samples remaining before the next latch. `0` latches a fresh input on the current sample. + var _countdown: Int = 0 + + /// Currently held output value. + var _held: Double = 0.0 + + /// Smallest decimation factor (pass-through). + private let minimumFactor: Int = 1 + + /// Creates a sample-rate decimator. + /// + /// - Parameters: + /// - input: Signal to decimate. + /// - downsample: Hold length in samples (control rate). Clamped to `>= 1`; `1` is transparent. + public init( + input: any ValidGeneratorInput, + downsample: any ValidGeneratorInput + ) { + let resolvedInput: any ValidGeneratorInput = input._resolvedInput() + _input = resolvedInput + _inputIsGenerator = resolvedInput is any Generator + _downsample = downsample._resolvedInput() + super.init() + } + + public func _computeSamples( + graph: SynthGraph, + count: Int + ) -> [[Double]] { + _checkCount(count) + guard count > 0 else { return _result } + + let factor: Int = max(minimumFactor, Int(_downsample.floatValue(graph: graph).rounded())) + + let inputSamples: [Double] = _inputIsGenerator + ? (_input.calculatedSamples(graph: graph, count: count).first ?? sampleRateDecimateZeroBlock) + : sampleRateDecimateZeroBlock + let inputCount: Int = inputSamples.count + let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph) + + var countdown: Int = _countdown + var held: Double = _held + + for i: Int in 0..= 2, "PedalSelectorKnob requires at least two stops") + self.label = label + self.node = node + self.stops = stops + } +} diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index 559fac0..9bea8d3 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -45,6 +45,7 @@ public extension PedalType { // Drive & dynamics static let overdrive = PedalType("Overdrive") + static let distortion = PedalType("Distortion") static let fuzz = PedalType("Fuzz") static let compressor = PedalType("Compressor") static let limiter = PedalType("Limiter") @@ -60,8 +61,12 @@ public extension PedalType { static let tremolo = PedalType("Tremolo") static let modulation = PedalType("Modulation") static let chorus = PedalType("Chorus") + static let flanger = PedalType("Flanger") + static let vibrato = PedalType("Vibrato") + static let rotary = PedalType("Rotary") static let ringModulator = PedalType("Ring Modulator") static let diffuser = PedalType("Diffuser") + static let bitcrusher = PedalType("Bitcrusher") // Dynamics (additional) static let sustainer = PedalType("Sustainer") @@ -71,9 +76,11 @@ public extension PedalType { static let feedbackDelay = PedalType("Feedback Delay") static let multiTapDelay = PedalType("Multi-Tap Delay") static let pingPong = PedalType("Ping-Pong") + static let reverseDelay = PedalType("Reverse Delay") static let reverb = PedalType("Reverb") // Pitch & octave static let octaveSplitter = PedalType("Octave Splitter") static let bassOctaver = PedalType("Bass Octaver") + static let harmonizer = PedalType("Harmonizer") } diff --git a/Sources/LyrebirdShoeGaze/Pedals/BitcrusherPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/BitcrusherPedal.swift new file mode 100644 index 0000000..eaeb713 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/BitcrusherPedal.swift @@ -0,0 +1,89 @@ +// BitcrusherPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Lo-fi bitcrusher: sample-rate decimation followed by bit-depth reduction. +/// +/// A sample-and-hold drops the effective sample rate (aliasing, stair-stepping); a quantiser then +/// reduces the bit depth (gritty quantisation noise). A post `Tone` low-pass tames the harsh +/// aliasing for a more usable lo-fi voice. Wraps the ``SampleRateDecimate`` and ``BitReduce`` +/// generators, run fully wet so the pedal's `Mix` knob sets the blend. +/// +/// ## Knobs +/// - `crush`: Sample-rate decimation factor (hold length in samples). Range `[1, 50]`. +/// - `bits`: Bit depth. Range `[1, 16]`. +/// - `tone`: Post low-pass cutoff in Hz. Range `[800, 8000]`. +public final class BitcrusherPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Lo-fi crusher: drops the sample rate and bit depth for gritty digital grunge." + } + + // MARK: - Parameters + + /// Sample-rate decimation factor (hold length in samples). Range [1, 50]. + @UIParam public var crush: Double = 8.0 + + /// Bit depth. Range [1, 16]. + @UIParam public var bits: Double = 8.0 + + /// Post low-pass cutoff in Hz. Range [800, 8000]. + @UIParam public var tone: Double = 4000.0 + + // MARK: - Constants + + /// Bitcrusher is heard fully wet; the `Mix` knob can dial it back. + private static let defaultMix: Double = 1.0 + + /// Butterworth Q (no resonant peak) for the tone low-pass. + private let filterQ: Double = 0.707 + + // MARK: - Ranges + + private let crushRange: ClosedRange = 1.0 ... 50.0 + private let bitsRange: ClosedRange = 1.0 ... 16.0 + private let toneRange: ClosedRange = 800.0 ... 8000.0 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Crush", node: $crush, range: crushRange), + PedalKnob(label: "Bits", node: $bits, range: bitsRange), + PedalKnob(label: "Tone", node: $tone, range: toneRange), + ] + } + + // MARK: - Init + + /// Creates a bitcrusher 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: "Bitcrusher", + inputBus: inputBus, + outputBus: outputBus, + initialMix: BitcrusherPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let decimated: SampleRateDecimate = SampleRateDecimate(input: dry, downsample: $crush) + let crushed: BitReduce = BitReduce(input: decimated, bits: $bits) + return RBJLowPass.Audio(input: crushed, freq: $tone, q: filterQ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/DistortionPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/DistortionPedal.swift new file mode 100644 index 0000000..b59a515 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/DistortionPedal.swift @@ -0,0 +1,98 @@ +// DistortionPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Mid-gain distortion — more saturated than `OverdrivePedal`, more controlled than `FuzzPedal`. +/// +/// A DC-blocking high-pass feeds a `tanh` soft-clipper driven hard by the `Drive` knob; a +/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip guarantees the +/// output stays bounded. +/// +/// ## Knobs +/// - `drive`: Pre-clip gain into the `tanh` stage. Range `[1, 50]`. +/// - `tone`: Post-clip low-pass cutoff in Hz. Range `[500, 6000]`. +public final class DistortionPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Mid-gain saturated distortion sitting between overdrive and fuzz." + } + + // MARK: - Parameters + + /// Pre-clip gain into the `tanh` stage. Range [1, 50]. + @UIParam public var drive: Double = 12.0 + + /// Post-clip low-pass cutoff in Hz. Range [500, 6000]. + @UIParam public var tone: Double = 3000.0 + + // MARK: - Constants + + /// Distortion is heard fully wet; the `Level` knob sets output gain. + private static let defaultMix: Double = 1.0 + + /// DC-blocking high-pass cutoff in Hz, applied before the clipper. + private let dcBlockFreq: Double = 80.0 + + /// Butterworth Q (no resonant peak) for the conditioning filters. + private let filterQ: Double = 0.707 + + /// Output hard-clip bounds — guarantees a bounded signal after tone shaping. + private let clipLow: Double = -1.0 + private let clipHigh: Double = 1.0 + + // MARK: - Ranges + + private let driveRange: ClosedRange = 1.0 ... 50.0 + private let toneRange: ClosedRange = 500.0 ... 6000.0 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Drive", node: $drive, range: driveRange), + PedalKnob(label: "Tone", node: $tone, range: toneRange), + ] + } + + // MARK: - Init + + /// Creates a distortion 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: "Distortion", + inputBus: inputBus, + outputBus: outputBus, + initialMix: DistortionPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let dcBlocked: RBJHighPass.Audio = RBJHighPass.Audio( + input: dry, + freq: dcBlockFreq, + q: filterQ + ) + let driven: Tanh.Audio = Tanh.Audio(dcBlocked, mul: $drive) + let toned: RBJLowPass.Audio = RBJLowPass.Audio( + input: driven, + freq: $tone, + q: filterQ + ) + return Clip.Audio(toned, lo: clipLow, hi: clipHigh) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/FlangerPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/FlangerPedal.swift new file mode 100644 index 0000000..e028c06 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/FlangerPedal.swift @@ -0,0 +1,101 @@ +// FlangerPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Classic jet-flanger. +/// +/// A short LFO-swept delay summed with the dry signal produces the sweeping comb-filter notches; +/// feedback sharpens them into the metallic "jet" whoosh. Wraps Lyrebird's `Flanger` generator, +/// run fully wet so the pedal's own `Mix` knob sets the wet/dry blend. +/// +/// ## Knobs +/// - `rate`: LFO sweep rate in Hz. Range `[0.05, 8]`. +/// - `depth`: Sweep depth as a fraction of the center delay. Range `[0, 1]`. +/// - `feedback`: Comb feedback (resonance). Range `[0, 0.95]`. +public final class FlangerPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Sweeping comb-filter jet flanger, with feedback for that metallic whoosh." + } + + // MARK: - Parameters + + /// LFO sweep rate in Hz. Range [0.05, 8]. + @UIParam public var rate: Double = 0.4 + + /// Sweep depth as a fraction of the center delay. Range [0, 1]. + @UIParam public var depth: Double = 0.6 + + /// Comb feedback (resonance). Range [0, 0.95]. + @UIParam public var feedback: Double = 0.3 + + // MARK: - Constants + + /// Default wet/dry blend — flanger sits under the dry signal. + private static let defaultMix: Double = 0.5 + + /// Center delay the LFO sweeps around, in seconds. + private let centerDelayTime: Double = 0.005 + + /// Maximum delay the line is allocated for, in seconds. Covers `centerDelayTime · (1 + maxDepth)`. + private let maxDelayTime: Double = 0.05 + + /// The wrapped generator runs fully wet; the `Pedal` base `Mix` knob does the blend. + private let fullyWetMix: Double = 1.0 + + // MARK: - Ranges + + private let rateRange: ClosedRange = 0.05 ... 8.0 + private let depthRange: ClosedRange = 0.0 ... 1.0 + private let feedbackRange: ClosedRange = 0.0 ... 0.95 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Rate", node: $rate, range: rateRange), + PedalKnob(label: "Depth", node: $depth, range: depthRange), + PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange), + ] + } + + // MARK: - Init + + /// Creates a flanger 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: "Flanger", + inputBus: inputBus, + outputBus: outputBus, + initialMix: FlangerPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + Flanger.Audio( + input: dry, + delayTime: centerDelayTime, + depth: $depth, + rate: $rate, + feedback: $feedback, + mix: fullyWetMix, + sampleRate: sampleRate, + maxDelayTime: maxDelayTime + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/HarmonizerPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/HarmonizerPedal.swift new file mode 100644 index 0000000..8f04026 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/HarmonizerPedal.swift @@ -0,0 +1,146 @@ +// HarmonizerPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Two-voice diatonic-interval harmonizer. +/// +/// Adds two pitch-shifted harmony voices at fixed musical intervals above or below the input, +/// mixed against the dry signal — an OC-2-style level layout (Voice 1 / Voice 2 / Direct) with a +/// knob picker selecting each voice's interval. +/// +/// Each voice is a granular `PitchShift` whose ratio is `2^(semitones/12)`, driven live from the +/// voice's interval selector. Intervals include minor and major thirds above and below, plus +/// fourths, fifths, and octaves. +/// +/// ## Knobs +/// - `voice1Level`: Voice 1 level in `[0, 1]`. +/// - `voice2Level`: Voice 2 level in `[0, 1]`. +/// - `direct`: Dry signal level in `[0, 1]`. +/// +/// ## Selectors (knob pickers) +/// - `voice1`: Voice 1 interval in semitones (snaps to musical intervals). +/// - `voice2`: Voice 2 interval in semitones. +public final class HarmonizerPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Two pitch-shifted harmony voices at intervals you pick, stacked under your note." + } + + // MARK: - Parameters + + /// Voice 1 interval in semitones. Snaps to musical-interval stops. + @UIParam public var voice1: Double = 4.0 + + /// Voice 2 interval in semitones. Snaps to musical-interval stops. + @UIParam public var voice2: Double = 7.0 + + /// Voice 1 level in `[0, 1]`. + @UIParam public var voice1Level: Double = 0.6 + + /// Voice 2 level in `[0, 1]`. + @UIParam public var voice2Level: Double = 0.45 + + /// Dry (direct) signal level in `[0, 1]`. + @UIParam public var direct: Double = 1.0 + + // MARK: - Constants + + /// Pedal blends internally via the level knobs, so the base wet/dry stays fully wet. + private static let defaultMix: Double = 1.0 + + /// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio`. + private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12 + + /// Granular pitch-shift window in seconds. Larger = smoother but more latency. + private let windowSize: Double = 0.1 + + // MARK: - Ranges + + private let levelRange: ClosedRange = 0.0 ... 1.0 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "V1 Level", node: $voice1Level, range: levelRange), + PedalKnob(label: "V2 Level", node: $voice2Level, range: levelRange), + PedalKnob(label: "Direct", node: $direct, range: levelRange), + ] + } + + // MARK: - Selectors + + /// Musical-interval stops for the voice pickers, low to high. Values are semitones; captions are + /// short interval names (`m3`/`M3` = minor/major third, `4`/`5` = perfect fourth/fifth, + /// `8ve` = octave, `Uni` = unison). Minus = below the input. + private static let intervalStops: [PedalSelectorKnob.Stop] = [ + PedalSelectorKnob.Stop(title: "-8ve", value: -12.0), + PedalSelectorKnob.Stop(title: "-M6", value: -9.0), + PedalSelectorKnob.Stop(title: "-m6", value: -8.0), + PedalSelectorKnob.Stop(title: "-5", value: -7.0), + PedalSelectorKnob.Stop(title: "-4", value: -5.0), + PedalSelectorKnob.Stop(title: "-M3", value: -4.0), + PedalSelectorKnob.Stop(title: "-m3", value: -3.0), + PedalSelectorKnob.Stop(title: "Uni", value: 0.0), + PedalSelectorKnob.Stop(title: "m3", value: 3.0), + PedalSelectorKnob.Stop(title: "M3", value: 4.0), + PedalSelectorKnob.Stop(title: "4", value: 5.0), + PedalSelectorKnob.Stop(title: "5", value: 7.0), + PedalSelectorKnob.Stop(title: "m6", value: 8.0), + PedalSelectorKnob.Stop(title: "M6", value: 9.0), + PedalSelectorKnob.Stop(title: "8ve", value: 12.0), + ] + + public override var effectSelectors: [PedalSelectorKnob] { + [ + PedalSelectorKnob(label: "Voice 1", node: $voice1, stops: HarmonizerPedal.intervalStops), + PedalSelectorKnob(label: "Voice 2", node: $voice2, stops: HarmonizerPedal.intervalStops), + ] + } + + // MARK: - Init + + /// Creates a harmonizer pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Harmonizer", + inputBus: inputBus, + outputBus: outputBus, + initialMix: HarmonizerPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let voice1Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice1) + let voice2Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice2) + + let directVoice: any ValidGeneratorInput = dry * $direct + let harmony1: any ValidGeneratorInput = voice1Signal * $voice1Level + let harmony2: any ValidGeneratorInput = voice2Signal * $voice2Level + return directVoice + harmony1 + harmony2 + } + + /// One pitch-shifted voice: ratio `2^(semitones/12)` via `Exp`, fed to a granular `PitchShift`. + private func harmonyVoice( + _ dry: any ValidGeneratorInput, + semitones: any ValidGeneratorInput + ) -> any ValidGeneratorInput { + let ratio: Exp.Audio = Exp.Audio(semitones * semitoneToRatioScale) + return PitchShift.Audio(input: dry, pitchRatio: ratio, windowSize: windowSize) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/ReverseDelayPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/ReverseDelayPedal.swift new file mode 100644 index 0000000..976f65c --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/ReverseDelayPedal.swift @@ -0,0 +1,87 @@ +// ReverseDelayPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Reverse delay. +/// +/// Records the input in fixed-length segments and plays each one back reversed, so notes and +/// phrases swell in backwards — the classic backwards-tape effect. `Feedback` recirculates the +/// reversed output for layered backward trails. Wraps the ``ReverseDelay`` generator, run fully wet +/// so the pedal's `Mix` knob sets the wet/dry blend. +/// +/// ## Knobs +/// - `time`: Reverse segment length in seconds. Range `[0.05, 2.0]`. +/// - `feedback`: Reverse-trail feedback. Range `[0, 0.95]`. +public final class ReverseDelayPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Plays your phrases back in reverse — the backwards-tape swell, with feedback trails." + } + + // MARK: - Parameters + + /// Reverse segment length in seconds. Range [0.05, 2.0]. + @UIParam public var time: Double = 0.5 + + /// Reverse-trail feedback. Range [0, 0.95]. + @UIParam public var feedback: Double = 0.3 + + // MARK: - Constants + + /// Default wet/dry blend — reverse delay sits under the dry signal. + private static let defaultMix: Double = 0.5 + + /// Maximum segment length the buffers are allocated for, in seconds. + private let maxDelayTime: Double = 2.0 + + // MARK: - Ranges + + private let timeRange: ClosedRange = 0.05 ... 2.0 + private let feedbackRange: ClosedRange = 0.0 ... 0.95 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Time", node: $time, range: timeRange), + PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange), + ] + } + + // MARK: - Init + + /// Creates a reverse-delay 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: "Reverse Delay", + inputBus: inputBus, + outputBus: outputBus, + initialMix: ReverseDelayPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + ReverseDelay( + input: dry, + maxDelay: maxDelayTime, + delay: $time, + feedback: $feedback, + sampleRate: sampleRate + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/RotaryPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/RotaryPedal.swift new file mode 100644 index 0000000..3d32d55 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/RotaryPedal.swift @@ -0,0 +1,173 @@ +// RotaryPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Rotary-speaker (Leslie) emulation. +/// +/// A spinning speaker produces correlated amplitude modulation (volume throb) and frequency +/// modulation (Doppler pitch wobble). This pedal builds both from one rotor LFO per channel, with +/// the left and right rotors in anti-phase so the image rotates across the stereo field. A two-speed +/// switch (Chorale / Tremolo) selects the rotor speed, and the **Accel** knob sets how quickly the +/// rotor ramps between speeds — the authentic spin-up / spin-down glide — via a `Lag` on the rate. +/// +/// Signal path (per channel, inside `wideEffect(_:)`): +/// ``` +/// dry → DelayLine(delay: base ± fm·sin(rate)) → × (1 ± am·sin(rate)) → wet +/// ``` +/// +/// ## Knobs +/// - `depth`: Rotor intensity — scales both the AM throb and the FM Doppler. Range `[0, 1]`. +/// - `accel`: Spin-up / spin-down ramp time in seconds. Range `[0.05, 3]`. +/// +/// ## Switches +/// - `speed` (two-state): `0` = Chorale (slow), `1` = Tremolo (fast). +public final class RotaryPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Spinning Leslie rotor: Doppler pitch wobble plus volume throb, two-speed with ramp." + } + + // MARK: - Parameters + + /// Rotor intensity — scales both AM and FM. Range [0, 1]. + @UIParam public var depth: Double = 0.7 + + /// Spin-up / spin-down ramp time in seconds. Range [0.05, 3]. + @UIParam public var accel: Double = 0.5 + + /// Rotor speed selector. `0` = Chorale (slow), `1` = Tremolo (fast). Driven by a two-state switch. + @UIParam public var speed: Double = 0.0 + + // MARK: - Constants + + /// Rotary is heard fully wet; the `Mix` knob can dial it back if desired. + private static let defaultMix: Double = 1.0 + + /// Chorale (slow) rotor rate in Hz. + private let slowRateHz: Double = 0.8 + + /// Tremolo (fast) rotor rate in Hz. + private let fastRateHz: Double = 6.5 + + /// Maximum FM (Doppler) sweep half-swing in seconds, at full depth. + private let fmDepthScale: Double = 0.0008 + + /// Maximum AM (throb) depth, at full depth. + private let amDepthScale: Double = 0.4 + + /// Center delay the FM sweeps around, in seconds. + private let baseDelayTime: Double = 0.004 + + /// Maximum delay the lines are allocated for, in seconds. + private let maxDelayTime: Double = 0.02 + + /// LFO phase (cycles) for the left rotor. + private let leftPhase: Double = 0.0 + + /// LFO phase (cycles) for the right rotor — a half cycle opposite the left. + private let rightPhase: Double = 0.5 + + // MARK: - Ranges + + private let depthRange: ClosedRange = 0.0 ... 1.0 + private let accelRange: ClosedRange = 0.05 ... 3.0 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Depth", node: $depth, range: depthRange), + PedalKnob(label: "Accel", node: $accel, range: accelRange), + ] + } + + // MARK: - Switches + + private let speedChoraleValue: Double = 0.0 + private let speedTremoloValue: Double = 1.0 + + public override var effectSwitches: [PedalSwitch] { + [ + PedalSwitch( + label: "Speed", + node: $speed, + options: [ + PedalSwitch.Option(title: "Chorale", value: speedChoraleValue), + PedalSwitch.Option(title: "Tremolo", value: speedTremoloValue), + ] + ) + ] + } + + // MARK: - Channel topology + + public override var channelKind: PedalChannelKind { .widener } + + // MARK: - Init + + /// Creates a rotary-speaker 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: "Rotary", + inputBus: inputBus, + outputBus: outputBus, + initialMix: RotaryPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func wideEffect( + _ dry: any ValidGeneratorInput + ) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) { + // Rotor rate glides between the two speeds — the spin-up / spin-down ramp. Shared by both + // rotors (fan-out is cached per block). + let rateTarget: any ValidGeneratorInput = $speed * (fastRateHz - slowRateHz) + slowRateHz + let rate: Lag.Audio = Lag.Audio(input: rateTarget, time: $accel) + return (voice(dry, rate: rate, phase: leftPhase), + voice(dry, rate: rate, phase: rightPhase)) + } + + /// One rotor voice: a Doppler-swept delay line whose output is amplitude-modulated by the same + /// rotor LFO, both at `rate` and the given `phase`. + private func voice( + _ dry: any ValidGeneratorInput, + rate: any ValidGeneratorInput, + phase: Double + ) -> any ValidGeneratorInput { + let fmSweep: OscSin.Audio = OscSin.Audio( + freq: rate, + phase: phase, + mul: $depth * fmDepthScale, + add: baseDelayTime + ) + let delayed: DelayLine = DelayLine( + input: dry, + maxDelay: maxDelayTime, + delay: fmSweep, + sampleRate: sampleRate, + interpolation: .linear + ) + // Throb gain in [1 - 2·depth·amScale, 1]. + let amGain: OscSin.Audio = OscSin.Audio( + freq: rate, + phase: phase, + mul: $depth * amDepthScale, + add: 1.0 - $depth * amDepthScale + ) + return delayed * amGain + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/VibratoPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/VibratoPedal.swift new file mode 100644 index 0000000..78b59d3 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/VibratoPedal.swift @@ -0,0 +1,96 @@ +// VibratoPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Pitch vibrato. +/// +/// A single delay line whose time is swept by a sine LFO produces a periodic pitch wobble. Unlike +/// `TremoloPedal` (which modulates *volume*), vibrato modulates *pitch*, and unlike `ChorusPedal` +/// it is heard fully wet — there is no dry voice underneath, so the result is pure pitch movement. +/// +/// ## Knobs +/// - `rate`: LFO rate in Hz. Range `[0.1, 8]`. +/// - `depth`: Delay-sweep depth in seconds (half-swing around the base delay). Range +/// `[0.0005, 0.006]`. +public final class VibratoPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Periodic pitch wobble — a sine-swept delay heard fully wet." + } + + // MARK: - Parameters + + /// LFO rate in Hz. Range [0.1, 8]. + @UIParam public var rate: Double = 5.0 + + /// Delay-sweep depth in seconds. Range [0.0005, 0.006]. + @UIParam public var depth: Double = 0.002 + + // MARK: - Constants + + /// Vibrato is pure pitch movement — fully wet, no dry voice underneath. + private static let defaultMix: Double = 1.0 + + /// Base delay around which the LFO sweeps, in seconds. + private let baseDelayTime: Double = 0.006 + + /// Maximum delay the line is allocated for, in seconds. Covers `baseDelayTime + max depth`. + private let maxDelayTime: Double = 0.02 + + // MARK: - Ranges + + private let rateRange: ClosedRange = 0.1 ... 8.0 + private let depthRange: ClosedRange = 0.0005 ... 0.006 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Rate", node: $rate, range: rateRange), + PedalKnob(label: "Depth", node: $depth, range: depthRange), + ] + } + + // MARK: - Init + + /// Creates a vibrato 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: "Vibrato", + inputBus: inputBus, + outputBus: outputBus, + initialMix: VibratoPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let sweep: OscSin.Audio = OscSin.Audio( + freq: $rate, + phase: 0.0, + mul: $depth, + add: baseDelayTime + ) + return DelayLine( + input: dry, + maxDelay: maxDelayTime, + delay: sweep, + sampleRate: sampleRate, + interpolation: .linear + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift index 76d4df2..54af6b7 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift @@ -19,11 +19,13 @@ extension Pedal { let values: [Double] = knobs.map { $0.node.value } let switchValues: [Double] = effectSwitches.map { $0.node.value } let sliderValues: [Double] = effectSliders.map { $0.node.value } + let selectorValues: [Double] = effectSelectors.map { $0.node.value } return PedalState( type: displayName, knobValues: values, switchValues: switchValues, sliderValues: sliderValues, + selectorValues: selectorValues, bypass: bypass ) } @@ -51,6 +53,9 @@ extension Pedal { for (slider, value) in zip(effectSliders, state.sliderValues) { slider.node.update(value) } + for (selector, value) in zip(effectSelectors, state.selectorValues) { + selector.node.update(value) + } bypass = state.bypass } } diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index 2b36334..1c2b4a3 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -32,6 +32,7 @@ public enum PedalRegistry { /// to a board via `board.add(_:)`. public static let builtIn: [String: @MainActor () -> Pedal] = [ "Overdrive": { OverdrivePedal() }, + "Distortion": { DistortionPedal() }, "Delay": { DelayPedal() }, "Reverb": { ReverbPedal() }, "Modulation": { ModulationPedal() }, @@ -45,14 +46,20 @@ public enum PedalRegistry { "Multi-Tap Delay": { MultiTapDelayPedal() }, "Octave Splitter": { OctaveUpSplitterPedal() }, "Bass Octaver": { BassOctaverPedal() }, + "Harmonizer": { HarmonizerPedal() }, "Ping-Pong": { PingPongDelayPedal() }, + "Reverse Delay": { ReverseDelayPedal() }, "Limiter": { LimiterPedal() }, "Noise Gate": { NoiseGatePedal() }, "Graphic EQ": { GraphicEQPedal() }, "Chorus": { ChorusPedal() }, + "Flanger": { FlangerPedal() }, + "Vibrato": { VibratoPedal() }, + "Rotary": { RotaryPedal() }, "Sustainer": { SustainerPedal() }, "Ring Modulator": { RingModulatorPedal() }, "Diffuser": { DiffuserPedal() }, + "Bitcrusher": { BitcrusherPedal() }, ] /// Returns a new `Pedal` instance for the given type string, or `nil` if the type diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift index ea418f4..daa2293 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift @@ -30,6 +30,10 @@ public struct PedalState: Codable, Equatable { /// no sliders. Absent in presets saved before sliders existed — decodes to `[]`. public let sliderValues: [Double] + /// Selector-knob values in the same order as `Pedal.effectSelectors`. Empty for pedals with + /// no selectors. Absent in presets saved before selectors existed — decodes to `[]`. + public let selectorValues: [Double] + /// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed. public let bypass: Double @@ -40,18 +44,21 @@ public struct PedalState: Codable, Equatable { /// - knobValues: Current knob values in `Pedal.knobs` order. /// - switchValues: Current switch values in `Pedal.effectSwitches` order. Defaults to empty. /// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty. + /// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty. /// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed). public init( type: String, knobValues: [Double], switchValues: [Double] = [], sliderValues: [Double] = [], + selectorValues: [Double] = [], bypass: Double ) { self.type = type self.knobValues = knobValues self.switchValues = switchValues self.sliderValues = sliderValues + self.selectorValues = selectorValues self.bypass = bypass } @@ -60,17 +67,19 @@ public struct PedalState: Codable, Equatable { case knobValues case switchValues case sliderValues + case selectorValues case bypass } - /// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` - /// existed by defaulting the missing keys to an empty array. + /// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` / + /// `selectorValues` existed by defaulting the missing keys to an empty array. public init(from decoder: any Decoder) throws { let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) self.type = try container.decode(String.self, forKey: .type) self.knobValues = try container.decode([Double].self, forKey: .knobValues) self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? [] self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? [] + self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? [] self.bypass = try container.decode(Double.self, forKey: .bypass) } } diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift index 04aead2..e3b50eb 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -51,10 +51,11 @@ public struct PedalPaletteView: View { /// Preferred display order for the built-in pedals. Any registered pedal not listed here is /// appended afterwards (sorted) so the palette never silently drops a newly added pedal. private static let preferredOrder: [String] = [ - "Overdrive", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", - "Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", - "Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter", - "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb", + "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", + "Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary", + "Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Bass Octaver", + "Octave Splitter", "Harmonizer", + "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb", ] /// Routing/branching topologies the user can insert into the board. diff --git a/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift b/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift new file mode 100644 index 0000000..d9bfbba --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift @@ -0,0 +1,126 @@ +// PedalSelectorKnobView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGaze + +/// Renders a ``PedalSelectorKnob`` — a rotary knob that snaps to a fixed set of labelled stops. +/// +/// Visually matches `ParameterKnob` (same dial + indicator), but drag quantises to discrete +/// positions and the caption shows the current stop's title rather than a numeric value. Drag up to +/// advance clockwise through the stops, down to go back. +struct PedalSelectorKnobView: View { + + // MARK: - Layout constants + + private static let dialSize: CGFloat = 50 + private static let indicatorWidth: CGFloat = 2 + private static let indicatorHeight: CGFloat = 14 + private static let indicatorInset: CGFloat = 3 + private static let startAngle: Double = -135.0 + private static let totalArc: Double = 270.0 + /// Pixels of vertical drag per stop step. + private static let pixelsPerStep: CGFloat = 22 + private static let labelSpacing: CGFloat = 4 + + // MARK: - Input + + private let selector: PedalSelectorKnob + + // MARK: - Drag state + + @State private var dragStartIndex: Int = 0 + @State private var dragInProgress: Bool = false + + // MARK: - Init + + init(_ selector: PedalSelectorKnob) { + self.selector = selector + } + + // MARK: - Body + + var body: some View { + VStack(spacing: PedalSelectorKnobView.labelSpacing) { + dial + .frame(width: PedalSelectorKnobView.dialSize, height: PedalSelectorKnobView.dialSize) + .gesture(dragGesture) + Text(selector.label) + .font(.caption) + .foregroundStyle(Color.white) + Text(currentStop.title) + .font(.caption) + .foregroundStyle(Color.white) + } + } + + // MARK: - Dial + + private var dial: some View { + let count: Int = selector.stops.count + let normalised: Double = count > 1 ? Double(currentIndex) / Double(count - 1) : 0 + let rotation: Double = PedalSelectorKnobView.startAngle + normalised * PedalSelectorKnobView.totalArc + let offset: CGFloat = -(PedalSelectorKnobView.dialSize / 2 + - PedalSelectorKnobView.indicatorHeight / 2 + - PedalSelectorKnobView.indicatorInset) + + return ZStack { + Circle() + .fill(Color.lyrebirdControlBackground) + .overlay(Circle().stroke(Color.lyrebirdSeparator, lineWidth: 1)) + Rectangle() + .fill(Color.accentColor) + .frame( + width: PedalSelectorKnobView.indicatorWidth, + height: PedalSelectorKnobView.indicatorHeight + ) + .offset(y: offset) + .rotationEffect(.degrees(rotation)) + } + } + + // MARK: - Drag + + private var dragGesture: some Gesture { + DragGesture(minimumDistance: 1) + .onChanged { gesture in + if !dragInProgress { + dragInProgress = true + dragStartIndex = currentIndex + } + let delta: CGFloat = gesture.translation.height // down = positive + // Up should advance (increase index), so subtract the downward delta. + let steps: Int = Int((-delta / PedalSelectorKnobView.pixelsPerStep).rounded()) + let target: Int = min(max(dragStartIndex + steps, 0), selector.stops.count - 1) + let value: Double = selector.stops[target].value + if value != selector.node.value { + selector.node.update(value) + } + } + .onEnded { _ in dragInProgress = false } + } + + // MARK: - Helpers + + /// Index of the stop whose value is nearest the node's current value. + private var currentIndex: Int { + let value: Double = selector.node.value + var bestIndex: Int = 0 + var bestDistance: Double = .greatestFiniteMagnitude + for (index, stop) in selector.stops.enumerated() { + let distance: Double = abs(stop.value - value) + if distance < bestDistance { + bestDistance = distance + bestIndex = index + } + } + return bestIndex + } + + private var currentStop: PedalSelectorKnob.Stop { + selector.stops[currentIndex] + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index eda0df1..02cda08 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -17,6 +17,7 @@ import LyrebirdShoeGaze private func enclosureColor(for displayName: String) -> Color { switch displayName { case "Overdrive": return Color(red: 0.85, green: 0.42, blue: 0.08) // warm orange + case "Distortion": return Color(red: 0.80, green: 0.26, blue: 0.12) // hot rust case "Delay": return Color(red: 0.10, green: 0.55, blue: 0.55) // teal case "Reverb": return Color(red: 0.30, green: 0.18, blue: 0.65) // indigo case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green @@ -28,13 +29,19 @@ private func enclosureColor(for displayName: String) -> Color { case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold case "Feedback Delay": return Color(red: 0.48, green: 0.30, blue: 0.14) // tape sepia case "Multi-Tap Delay": return Color(red: 0.08, green: 0.48, blue: 0.68) // cyan + case "Reverse Delay": return Color(red: 0.10, green: 0.44, blue: 0.60) // deep cyan-teal case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal case "Chorus": return Color(red: 0.16, green: 0.50, blue: 0.64) // aqua + case "Flanger": return Color(red: 0.28, green: 0.52, blue: 0.78) // steel blue + case "Vibrato": return Color(red: 0.42, green: 0.30, blue: 0.70) // violet-blue + case "Rotary": return Color(red: 0.45, green: 0.34, blue: 0.20) // Leslie cabinet walnut case "Sustainer": return Color(red: 0.22, green: 0.46, blue: 0.30) // pine green case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber 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 "Bitcrusher": return Color(red: 0.30, green: 0.34, blue: 0.40) // slate / digital gray default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray } } @@ -277,6 +284,7 @@ public struct PedalView: View { VStack(spacing: PedalView.sectionSpacing) { namePlate knobGrid + selectorRow switchRow sliderBank(sliders) Spacer(minLength: 0) @@ -371,6 +379,22 @@ public struct PedalView: View { } } + /// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid. + /// Renders nothing when the pedal publishes no selectors. + @ViewBuilder + private var selectorRow: some View { + let selectors: [PedalSelectorKnob] = pedal.effectSelectors + if !selectors.isEmpty { + HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) { + Spacer(minLength: 0) + ForEach(Array(selectors.enumerated()), id: \.offset) { pair in + PedalSelectorKnobView(pair.element) + } + Spacer(minLength: 0) + } + } + } + /// Row of segmented switches drawn from `pedal.effectSwitches`, one per row, beneath /// the knob grid. Renders nothing when the pedal publishes no switches. @ViewBuilder diff --git a/Tests/LyrebirdShoeGazeTests/BitcrusherPedalTests.swift b/Tests/LyrebirdShoeGazeTests/BitcrusherPedalTests.swift new file mode 100644 index 0000000..e9cd2ba --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/BitcrusherPedalTests.swift @@ -0,0 +1,85 @@ +// BitcrusherPedalTests.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("BitcrusherPedal") +struct BitcrusherPedalTests { + + private func render( + configure: (BitcrusherPedal) -> 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: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: BitcrusherPedal = BitcrusherPedal(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 + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { _ in } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "bitcrusher output was silent") + } + + @Test func crushChangesOutput() throws { + let light: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 } + let heavy: [Float] = try render { pedal in pedal.crush = 32.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 } + #expect(hasNonSilentOutput(heavy), "decimated bitcrusher was silent") + #expect(totalSSD(light, heavy) > 0, "changing crush did not change the output") + } + + @Test func bitsChangeOutput() throws { + let clean: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 } + let crushed: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 3.0; pedal.tone = 8000.0; pedal.mix = 1.0 } + #expect(hasNonSilentOutput(crushed), "bit-reduced output was silent") + #expect(totalSSD(clean, crushed) > 0, "changing bit depth did not change the output") + } + + @Test func exposesCrushBitsToneKnobs() throws { + let pedal: BitcrusherPedal = BitcrusherPedal() + let labels: [String] = pedal.effectKnobs.map { $0.label } + #expect(labels == ["Crush", "Bits", "Tone"]) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Bitcrusher") + #expect(pedal is BitcrusherPedal) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/DistortionPedalTests.swift b/Tests/LyrebirdShoeGazeTests/DistortionPedalTests.swift new file mode 100644 index 0000000..4af5ab8 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/DistortionPedalTests.swift @@ -0,0 +1,91 @@ +// DistortionPedalTests.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("DistortionPedal") +struct DistortionPedalTests { + + private func render( + configure: (DistortionPedal) -> 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: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: DistortionPedal = DistortionPedal(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 windowedSSD(_ a: [Float], _ b: [Float]) -> Double { + let skipSamples: Int = 2048 + let windowSize: Int = 2048 + guard a.count >= skipSamples + windowSize, + b.count >= skipSamples + windowSize else { return 0.0 } + let aWindow: ArraySlice = a[skipSamples..<(skipSamples + windowSize)] + let bWindow: ArraySlice = b[skipSamples..<(skipSamples + windowSize)] + return zip(aWindow, bWindow).reduce(0.0) { acc, pair in + let diff: Double = Double(pair.0 - pair.1) + return acc + diff * diff + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { _ in } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "distortion output was silent") + } + + @Test func driveChangesOutput() throws { + let low: [Float] = try render { pedal in pedal.drive = 2.0 } + let high: [Float] = try render { pedal in pedal.drive = 45.0 } + #expect(hasNonSilentOutput(high), "high-drive distortion was silent") + #expect(windowedSSD(low, high) > 0, "changing drive did not change the output") + } + + @Test func toneChangesOutput() throws { + let dark: [Float] = try render { pedal in pedal.drive = 30.0; pedal.tone = 700.0 } + let bright: [Float] = try render { pedal in pedal.drive = 30.0; pedal.tone = 5500.0 } + #expect(hasNonSilentOutput(bright), "bright distortion was silent") + #expect(windowedSSD(dark, bright) > 0, "changing tone did not change the output") + } + + @Test func exposesDriveToneKnobs() throws { + let pedal: DistortionPedal = DistortionPedal() + let labels: [String] = pedal.effectKnobs.map { $0.label } + #expect(labels == ["Drive", "Tone"]) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Distortion") + #expect(pedal is DistortionPedal) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/FlangerPedalTests.swift b/Tests/LyrebirdShoeGazeTests/FlangerPedalTests.swift new file mode 100644 index 0000000..61a5a19 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/FlangerPedalTests.swift @@ -0,0 +1,91 @@ +// FlangerPedalTests.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("FlangerPedal") +struct FlangerPedalTests { + + private func render( + configure: (FlangerPedal) -> 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: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: FlangerPedal = FlangerPedal(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 windowedSSD(_ a: [Float], _ b: [Float]) -> Double { + let skipSamples: Int = 2048 + let windowSize: Int = 2048 + guard a.count >= skipSamples + windowSize, + b.count >= skipSamples + windowSize else { return 0.0 } + let aWindow: ArraySlice = a[skipSamples..<(skipSamples + windowSize)] + let bWindow: ArraySlice = b[skipSamples..<(skipSamples + windowSize)] + return zip(aWindow, bWindow).reduce(0.0) { acc, pair in + let diff: Double = Double(pair.0 - pair.1) + return acc + diff * diff + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { _ in } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "flanger output was silent") + } + + @Test func depthChangesOutput() throws { + let shallow: [Float] = try render { pedal in pedal.depth = 0.1; pedal.mix = 1.0 } + let deep: [Float] = try render { pedal in pedal.depth = 0.95; pedal.mix = 1.0 } + #expect(hasNonSilentOutput(deep), "deep flanger was silent") + #expect(windowedSSD(shallow, deep) > 0, "changing depth did not change the output") + } + + @Test func feedbackChangesOutput() throws { + let dry: [Float] = try render { pedal in pedal.feedback = 0.0; pedal.mix = 1.0 } + let resonant: [Float] = try render { pedal in pedal.feedback = 0.85; pedal.mix = 1.0 } + #expect(hasNonSilentOutput(resonant), "resonant flanger was silent") + #expect(windowedSSD(dry, resonant) > 0, "changing feedback did not change the output") + } + + @Test func exposesRateDepthFeedbackKnobs() throws { + let pedal: FlangerPedal = FlangerPedal() + let labels: [String] = pedal.effectKnobs.map { $0.label } + #expect(labels == ["Rate", "Depth", "Feedback"]) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Flanger") + #expect(pedal is FlangerPedal) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/HarmonizerPedalTests.swift b/Tests/LyrebirdShoeGazeTests/HarmonizerPedalTests.swift new file mode 100644 index 0000000..41d111e --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/HarmonizerPedalTests.swift @@ -0,0 +1,147 @@ +// HarmonizerPedalTests.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("HarmonizerPedal") +struct HarmonizerPedalTests { + + /// Renders the pedal through an NRT engine with the given configuration and returns the output. + private func render( + configure: (HarmonizerPedal) -> Void + ) throws -> [Float] { + let renderDuration: Double = 0.3 + 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: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: HarmonizerPedal = HarmonizerPedal( + 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) + } + + /// Sum of squared differences over a stable window of two renders. + private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double { + let skipSamples: Int = 4096 + let windowSize: Int = 2048 + guard a.count >= skipSamples + windowSize, + b.count >= skipSamples + windowSize else { return 0.0 } + let aWindow: ArraySlice = a[skipSamples..<(skipSamples + windowSize)] + let bWindow: ArraySlice = b[skipSamples..<(skipSamples + windowSize)] + return zip(aWindow, bWindow).reduce(0.0) { acc, pair in + let diff: Double = Double(pair.0 - pair.1) + return acc + diff * diff + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { pedal in + pedal.direct = 1.0 + pedal.voice1Level = 0.6 + pedal.voice2Level = 0.5 + } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "harmonizer output was silent") + } + + @Test func changingVoiceIntervalChangesOutput() throws { + let third: [Float] = try render { pedal in + pedal.direct = 0.0 + pedal.voice1Level = 1.0 + pedal.voice2Level = 0.0 + pedal.voice1 = 3.0 // minor third up + } + let fifth: [Float] = try render { pedal in + pedal.direct = 0.0 + pedal.voice1Level = 1.0 + pedal.voice2Level = 0.0 + pedal.voice1 = 7.0 // perfect fifth up + } + #expect(hasNonSilentOutput(third), "minor-third voice was silent") + #expect(hasNonSilentOutput(fifth), "fifth voice was silent") + #expect(windowedSSD(third, fifth) > 0, "changing the interval did not change the output") + } + + @Test func harmonyVoicesDifferFromDirectOnly() throws { + let directOnly: [Float] = try render { pedal in + pedal.direct = 1.0 + pedal.voice1Level = 0.0 + pedal.voice2Level = 0.0 + } + let withVoices: [Float] = try render { pedal in + pedal.direct = 1.0 + pedal.voice1Level = 1.0 + pedal.voice2Level = 1.0 + } + #expect(hasNonSilentOutput(directOnly), "direct-only render was silent") + #expect(windowedSSD(directOnly, withVoices) > 0, "adding harmony voices did not change the output") + } + + @Test func exposesLevelKnobs() throws { + let pedal: HarmonizerPedal = HarmonizerPedal() + let labels: [String] = pedal.effectKnobs.map { $0.label } + #expect(labels == ["V1 Level", "V2 Level", "Direct"]) + } + + @Test func exposesTwoIntervalSelectors() throws { + let pedal: HarmonizerPedal = HarmonizerPedal() + let selectors: [PedalSelectorKnob] = pedal.effectSelectors + #expect(selectors.map { $0.label } == ["Voice 1", "Voice 2"]) + // Both minor- and major-thirds above and below must be available. + let titles: [String] = selectors.first?.stops.map { $0.title } ?? [] + #expect(titles.contains("m3")) + #expect(titles.contains("M3")) + #expect(titles.contains("-m3")) + #expect(titles.contains("-M3")) + } + + @Test func presetRoundTripPreservesIntervalsAndLevels() throws { + let pedal: HarmonizerPedal = HarmonizerPedal() + pedal.voice1 = -3.0 + pedal.voice2 = 12.0 + pedal.voice1Level = 0.3 + + let state: PedalState = pedal.captureState() + #expect(state.selectorValues == [-3.0, 12.0]) + + let restored: HarmonizerPedal = HarmonizerPedal() + restored.applyState(state) + #expect(restored.voice1 == -3.0) + #expect(restored.voice2 == 12.0) + #expect(restored.voice1Level == 0.3) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Harmonizer") + #expect(pedal is HarmonizerPedal) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/ReverseDelayPedalTests.swift b/Tests/LyrebirdShoeGazeTests/ReverseDelayPedalTests.swift new file mode 100644 index 0000000..44156ec --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ReverseDelayPedalTests.swift @@ -0,0 +1,94 @@ +// ReverseDelayPedalTests.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("ReverseDelayPedal") +struct ReverseDelayPedalTests { + + private func render( + configure: (ReverseDelayPedal) -> Void + ) throws -> [Float] { + let renderDuration: Double = 0.6 + 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: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: ReverseDelayPedal = ReverseDelayPedal(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) + } + + /// Sum of squared differences over the full overlapping length. Feedback only diverges once a + /// fed-back segment is replayed (the third segment), so a narrow window can miss it; comparing + /// the whole readable buffer (the reader returns the first 4096 frames) is robust. + 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 buildsAndProducesNonSilentOutput() throws { + // Short segment so reversed playback begins within the reader's 4096-frame window. + let samples: [Float] = try render { pedal in pedal.time = 0.03; pedal.mix = 1.0 } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "reverse delay output was silent") + } + + @Test func feedbackChangesOutput() throws { + let dry: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.0; pedal.mix = 1.0 } + let trails: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.6; pedal.mix = 1.0 } + #expect(hasNonSilentOutput(trails), "feedback reverse delay was silent") + #expect(totalSSD(dry, trails) > 0, "changing feedback did not change the output") + } + + @Test func exposesTimeFeedbackKnobs() throws { + let pedal: ReverseDelayPedal = ReverseDelayPedal() + let labels: [String] = pedal.effectKnobs.map { $0.label } + #expect(labels == ["Time", "Feedback"]) + } + + @Test func presetRoundTripPreservesKnobs() throws { + let pedal: ReverseDelayPedal = ReverseDelayPedal() + pedal.time = 1.2 + pedal.feedback = 0.7 + let state: PedalState = pedal.captureState() + + let restored: ReverseDelayPedal = ReverseDelayPedal() + restored.applyState(state) + #expect(restored.time == 1.2) + #expect(restored.feedback == 0.7) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Reverse Delay") + #expect(pedal is ReverseDelayPedal) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/RotaryPedalTests.swift b/Tests/LyrebirdShoeGazeTests/RotaryPedalTests.swift new file mode 100644 index 0000000..397596b --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/RotaryPedalTests.swift @@ -0,0 +1,97 @@ +// RotaryPedalTests.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("RotaryPedal") +struct RotaryPedalTests { + + private func render( + configure: (RotaryPedal) -> Void + ) throws -> [Float] { + let renderDuration: Double = 0.3 + 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: RotaryPedal = RotaryPedal(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 windowedSSD(_ a: [Float], _ b: [Float]) -> Double { + let skipSamples: Int = 4096 + let windowSize: Int = 4096 + guard a.count >= skipSamples + windowSize, + b.count >= skipSamples + windowSize else { return 0.0 } + let aWindow: ArraySlice = a[skipSamples..<(skipSamples + windowSize)] + let bWindow: ArraySlice = b[skipSamples..<(skipSamples + windowSize)] + return zip(aWindow, bWindow).reduce(0.0) { acc, pair in + let diff: Double = Double(pair.0 - pair.1) + return acc + diff * diff + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { _ in } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "rotary output was silent") + } + + @Test func speedChangesOutput() throws { + let chorale: [Float] = try render { pedal in pedal.speed = 0.0; pedal.accel = 0.05 } + let tremolo: [Float] = try render { pedal in pedal.speed = 1.0; pedal.accel = 0.05 } + #expect(hasNonSilentOutput(tremolo), "fast rotary was silent") + #expect(windowedSSD(chorale, tremolo) > 0, "changing speed did not change the output") + } + + @Test func exposesDepthAccelKnobsAndSpeedSwitch() throws { + let pedal: RotaryPedal = RotaryPedal() + #expect(pedal.effectKnobs.map { $0.label } == ["Depth", "Accel"]) + #expect(pedal.effectSwitches.map { $0.label } == ["Speed"]) + #expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Chorale", "Tremolo"]) + } + + @Test func presetRoundTripPreservesSpeed() throws { + let pedal: RotaryPedal = RotaryPedal() + pedal.speed = 1.0 + pedal.depth = 0.4 + let state: PedalState = pedal.captureState() + + let restored: RotaryPedal = RotaryPedal() + restored.applyState(state) + #expect(restored.speed == 1.0) + #expect(restored.depth == 0.4) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Rotary") + #expect(pedal is RotaryPedal) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/VibratoPedalTests.swift b/Tests/LyrebirdShoeGazeTests/VibratoPedalTests.swift new file mode 100644 index 0000000..8bb3bcd --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/VibratoPedalTests.swift @@ -0,0 +1,84 @@ +// VibratoPedalTests.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("VibratoPedal") +struct VibratoPedalTests { + + private func render( + configure: (VibratoPedal) -> 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: 1) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index) + let pedal: VibratoPedal = VibratoPedal(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 windowedSSD(_ a: [Float], _ b: [Float]) -> Double { + let skipSamples: Int = 2048 + let windowSize: Int = 2048 + guard a.count >= skipSamples + windowSize, + b.count >= skipSamples + windowSize else { return 0.0 } + let aWindow: ArraySlice = a[skipSamples..<(skipSamples + windowSize)] + let bWindow: ArraySlice = b[skipSamples..<(skipSamples + windowSize)] + return zip(aWindow, bWindow).reduce(0.0) { acc, pair in + let diff: Double = Double(pair.0 - pair.1) + return acc + diff * diff + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { _ in } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "vibrato output was silent") + } + + @Test func depthChangesOutput() throws { + let shallow: [Float] = try render { pedal in pedal.depth = 0.0006 } + let deep: [Float] = try render { pedal in pedal.depth = 0.006 } + #expect(hasNonSilentOutput(deep), "deep vibrato was silent") + #expect(windowedSSD(shallow, deep) > 0, "changing depth did not change the output") + } + + @Test func exposesRateDepthKnobs() throws { + let pedal: VibratoPedal = VibratoPedal() + let labels: [String] = pedal.effectKnobs.map { $0.label } + #expect(labels == ["Rate", "Depth"]) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Vibrato") + #expect(pedal is VibratoPedal) + } +} diff --git a/docs/plans/1.2-new-pedals.md b/docs/plans/1.2-new-pedals.md new file mode 100644 index 0000000..a9efbc7 --- /dev/null +++ b/docs/plans/1.2-new-pedals.md @@ -0,0 +1,190 @@ +# 1.2 New Pedals — Plan + +Eight pedals targeted for 1.2 (Wah deferred — pending MIDI-control hardware). Grounded against the +Lyrebird generators actually available. Each entry lists the signal path, the generators used, +controls, channel kind, the per-pedal checklist (registry / `PedalType` / enclosure color / palette +order / tests), and effort. + +Effort legend: **S** = thin wrapper over existing generators; **M** = composite graph; **L** = +needs a new RT-safe generator first. + +Build order recommendation: Flanger → Vibrato → Distortion → Harmonizer → Rotary → Shimmer Reverb → +Reverse Delay → Bitcrusher. (Cheap/whole-cloth-available first; new-generator pedals last.) + +--- + +## 1. Flanger — **S** + +Lyrebird already ships `Flanger.Audio(input:delayTime:depth:rate:feedback:mix:sampleRate:maxDelayTime:)`. +Thin wrapper like `ModulationPedal`. + +- **Path:** `dry → Flanger.Audio → wet` (base `mix`/`level`/bypass handle blend). +- **Controls (knobs):** Rate (0.05–8 Hz), Depth (0–1), Feedback (0–0.95), Manual/center delay + (0.001–0.01 s, optional). Mix inherited. +- **Channel:** `.processor` (mono). A stereo `.widener` variant (two LFOs anti-phase, like + `ChorusPedal`) is a nice follow-up but not required. +- **Effort:** S. + +## 2. Vibrato — **S** + +Pitch wobble = a single swept delay line, fully wet (no dry blend). Mirrors `ChorusPedal.voice` but +`initialMix = 1.0` and one voice. + +- **Path:** `dry → DelayLine(delay: OscSin(rate, mul: depth, add: base)) → wet`, `mix = 1.0`. +- **Controls:** Rate (0.1–8 Hz), Depth (0.0005–0.006 s). (Expose Depth as "Depth"; keep mix locked + fully wet — vibrato is not a blend effect.) +- **Channel:** `.processor`. +- **Effort:** S. Distinct from Tremolo (amplitude) — document the difference in `summary`. + +## 3. Distortion — **S** + +Mid-gain clipper between Overdrive (soft) and Fuzz (extreme). Reuse the `Tanh.Audio` drive trick +from `BassOctaverPedal`, plus a tone tilt and output clamp. + +- **Path:** `dry → HPF(~80) → Tanh(mul: drive) → tone (RBJLowPass, freq from Tone knob) → Clip(-1,1) + → wet`. (Optionally `Waveshaper` with a fixed asymmetric table for more character.) +- **Controls:** Drive (1–50), Tone (500–6000 Hz), Level (inherited). Mix default 1.0. +- **Channel:** `.processor`. +- **Effort:** S. Pick clipping flavor at impl: `Tanh` (smooth), `Clip` (hard), or `Fold` (octave-y). + Recommend `Tanh` → `Clip` cascade. + +## 4. Harmonizer — **M** (user priority) + +Two pitch-shifted harmony voices at **fixed, user-picked interval ratios**, mixed under the dry +signal. Uses `PitchShift.Audio` (granular, real-time, mono, `pitchRatio` clamped 0.25–4.0). + +- **Path:** + ``` + dry ─┬───────────────────────────────── direct·directLevel + ├─ PitchShift(pitchRatio: r1) ····· × voice1Level + └─ PitchShift(pitchRatio: r2) ····· × voice2Level → sum + ``` +- **Interval ratios:** semitone → ratio `2^(n/12)`. Offer a musical set, e.g. + `-12, -7, -5, -3, 0, +3, +4, +5, +7, +12` semitones (octave/5th/4th/3rds). Map each option's + `value` to the ratio at build time. +- **Controls:** + - **Voice 1 Interval** + **Voice 2 Interval** — the "knob pickers" for fixed ratios. + - **Voice 1 Level**, **Voice 2 Level**, **Direct** (dry) level knobs (OC-2-style, like + `BassOctaverPedal`). +- **Picker control (decided):** add a new **`PedalSelectorKnob`** — a knob that snaps to labeled + stops. Reusable for future discrete-knob pedals. Interval stops must include minor- and major-3rd + **above and below**: `-12, -7, -5, -4, -3, 0, +3, +4, +5, +7, +12` semitones (m3 = ±3, M3 = ±4, + P4 = ±5, P5 = ±7, octave = ±12, 0 = unison/off). Each stop's value maps to ratio `2^(n/12)`. + Default voices: Voice 1 = +4 (M3 up), Voice 2 = +7 (P5 up). +- **Channel:** `.processor` (sum to mono). Optional `.widener` (pan the two voices L/R) as a follow-up. +- **Effort:** M. Watch granular latency/CPU with two `PitchShift` instances; verify under the + 512-block engine. Consider `windowSize` tuning per voice for smoothness. + +## 5. Rotary / Leslie — **M** + +Leslie = amplitude modulation (volume throb) + frequency modulation (Doppler pitch wobble) + +stereo spread, with a two-speed (Chorale/Tremolo) ramp. + +- **Path (per channel, `.widener`):** + `dry → DelayLine(delay: OscSin(rate, mul: depth, add: base)) → ×(0.5 + 0.5·OscSin(rate, phase))`, + left/right LFOs offset (≈180°) for rotating stereo image. AM and FM share the rotor `rate`. +- **Controls:** Speed switch (Chorale ≈0.8 Hz / Tremolo ≈6.5 Hz) via `PedalSwitch`; **Accel** knob + (ramp time between speeds); **Depth**/**Mix**. Acceleration ramp = a `Lag`/`Decay` on the rate + target so speed changes glide (authentic spin-up/down). +- **Alternative:** `PanAzDistance.Audio` gives real Doppler but outputs 4 channels — would need a + 4→2 downmix; the LFO-AM+FM approach above stays stereo and is simpler. Recommend the simple path + for 1.2. +- **Channel:** `.widener`. +- **Effort:** M. + +## 6. Shimmer Reverb — **M** (with caveat) + +Octave-up sparkle over a reverb tail. Built on an existing reverb (`PlateReverb` or `GVerb`) plus +`PitchShift(pitchRatio: 2.0)`. + +- **Caveat — no true regeneration:** Lyrebird's per-synth graph is an acyclic DAG, so a real + *regenerating* shimmer feedback loop (tail → pitch-up → back into tail) isn't expressible inside + one pedal. For 1.2 ship the **parallel** approximation: + ``` + dry ─┬─ Reverb ───────────────── tail + └─ PitchShift(×2) → Reverb → shimmer → blend + ``` + This gives the shimmer character without infinite regeneration. True regenerative shimmer needs a + bus-feedback structure (cross-block) or a new feedback-capable generator — note as a future item. +- **Controls:** Room/Decay, Shimmer amount (pitch-voice level), Damp, Mix. +- **Channel:** `.widener` (reverbs output stereo — keep L/R). +- **Effort:** M. Confirm which reverb `ReverbPedal` already uses to avoid duplication; pick the other + (or add an algorithm switch). + +## 7. Reverse Delay — **L** (needs new generator) + +No reverse-capable delay exists in Lyrebird. Add a new RT-safe generator (in ShoeGaze, or upstream +in Lyrebird Delays). + +- **New generator `ReverseDelay`:** pre-allocated segment buffer (max length fixed at init, no RT + alloc); record forward into a segment, play it back reversed; segment length = delay time; + optional feedback. Crossfade at segment boundaries to avoid clicks. Follow Lyrebird generator + rules (`GeneratorBase`, `_checkCount`, pre-allocated buffers, no RT alloc/locks). +- **Pedal path:** `dry → ReverseDelay(time, feedback) → wet`. +- **Controls:** Time (0.05–2 s), Feedback (0–0.9), Mix. +- **Channel:** `.processor`. +- **Effort:** L (generator + tests first, then the thin pedal). Run `lyrebird_external_review` on the + new generator for RT safety. + +## 8. Bitcrusher / Lo-Fi — **L** (needs new generators) + +No decimation/bit-reduction generators exist. Add two small RT-safe generators. + +- **New generators:** + - `SampleRateDecimate` — sample-and-hold at a reduced rate (hold last sample for N input samples; + rate or downsample-factor parameter). + - `BitReduce` — quantize amplitude to `2^bits` levels. + (Both trivial per-sample math, pre-allocated state only.) +- **Pedal path:** `dry → SampleRateDecimate(rate) → BitReduce(bits) → (optional RBJLowPass tone) → + wet`. +- **Controls:** Sample Rate / Downsample (knob), Bits (1–16, stepped), Tone, Mix. +- **Channel:** `.processor`. +- **Effort:** L (two generators + tests, then pedal). Consider contributing the generators upstream + to Lyrebird since they're broadly useful. + +--- + +## Cross-cutting checklist (every pedal) + +Per `CLAUDE.md` "Adding a new pedal": +1. `Sources/LyrebirdShoeGaze/Pedals/Pedal.swift` — subclass `Pedal`, override `effect`/ + `wideEffect`, `effectKnobs`/`effectSwitches`/`effectSliders`. +2. **`summary`** (mandatory, one line). +3. Register in `PedalRegistry.builtIn[""]`. +4. Add `PedalType.`. +5. Enclosure color in `PedalView.enclosureColor(for:)`. +6. Add to `PedalPaletteView.preferredOrder` (group with family: gain near Overdrive/Fuzz; modulation + near Chorus/Phaser; pitch near the octavers; delay/reverb near their families). +7. Tests in `Tests/LyrebirdShoeGazeTests/PedalTests.swift` — builds + non-silent, each param + measurably changes output, knob/switch list assertions, preset round-trip if it has + switches/sliders. +8. Use `PedalType` static members at call sites. + +## Shimmer scope (true regenerative) — findings + +Investigated the regenerative path. The per-pedal graph is acyclic; the only feedback mechanisms in +Lyrebird are (a) generators that close their own loop internally (`DelayLineFeedback`, the reverbs) +and (b) cross-block bus read/write. Pedals use inherited `input(bus:)` / `output(bus:)` In/Out +nodes, but **no pedal allocates an internal scratch/feedback bus** — there's no precedent or +lifecycle hook for that. A bus-feedback shimmer would mean new pedal infrastructure (allocate + +release an internal feedback bus, ordered Out→In with a one-block delay) — fragile and off-pattern. + +**Conclusion:** true regenerative shimmer is best built as a **new closed-loop generator** +(`ShimmerReverb`) that holds a reverb + an in-loop pitch-shift + damped feedback internally, the same +way `DelayLineFeedback` contains its own feedback. That's a substantial RT-safe DSP generator +(pre-allocated buffers, denormal guards, feedback clamp for stability, granular/FFT pitch latency in +the loop) — larger than Reverse Delay or Bitcrush, and needing its own stability tuning + RT review. + +**Recommendation:** build Reverse Delay and Bitcrusher first (self-contained), then take +`ShimmerReverb` as its own focused task. If it proves too large for the 1.2 window, ship the +parallel-pitch-into-reverb approximation for 1.2 and schedule the regenerative generator for 1.3. +**Decision pending:** regenerative `ShimmerReverb` now, or parallel approximation for 1.2 + defer. + +## Decisions (resolved) + +- **Harmonizer picker:** new `PedalSelectorKnob` (stepped knob) with the ±3rd interval set above. + Build the Harmonizer first to evaluate the control. +- **New generators (Reverse Delay, Bitcrush):** land in the **ShoeGaze package** (self-contained; + no Lyrebird-release dependency for 1.2). +- **Shimmer:** scope a **true regenerative** version (cross-block bus feedback) rather than the + parallel approximation — larger, may slip 1.2.