Add Limiter, Noise Gate, and Graphic EQ pedals + vertical-fader UI control
Three new pedals: - LimiterPedal: linear boost gain stage into a LookAheadLimiter brick-wall ceiling. Reads engine sampleRate injected by PedalBoard.add at build time. - NoiseGatePedal: AmplitudeFollower -> hysteretic Schmidt gate -> LinLin floor map -> Lag smoothing. Tuneable residual floor when the gate is closed. - GraphicEQPedal: five cascaded RBJ filters (low/high shelf + three peaking mids) with per-band dB gains and a linear master output gain. New UI control: - PedalSlider descriptor and Pedal.effectSliders hook, alongside effectKnobs and effectSwitches. - VerticalParameterSlider: a vertical fader bound to a UIParamNode. - PedalView renders the fader bank and widens the enclosure to fit it. Persistence/registry: - PedalState.sliderValues (decodeIfPresent for backward compatibility); capture and apply in Pedal+Preset. - Registry entries and palette ordering for all three pedals. Tests: non-silent builds, limiter ceiling enforcement, gate open/closed/unity floor power ratios, EQ flat output, global-gain scaling, and 6-slider preset round-trip. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -147,6 +147,16 @@ open class Pedal: SynthesizerBase {
|
||||
[]
|
||||
}
|
||||
|
||||
/// Effect-specific continuous sliders for this pedal, rendered as a row of vertical
|
||||
/// faders beneath the knob grid and switches.
|
||||
///
|
||||
/// Override in subclasses to publish each `@UIParam` parameter that reads best as a
|
||||
/// vertical fader rather than a rotary knob — graphic-EQ band gains, a master output
|
||||
/// fader, and similar bank-style controls. Defaults to empty.
|
||||
open var effectSliders: [PedalSlider] {
|
||||
[]
|
||||
}
|
||||
|
||||
/// All knobs a generic UI should render for this pedal: effect-specific knobs
|
||||
/// first, then the common `mix` and `level` knobs. The `bypass` parameter is
|
||||
/// surfaced separately as a header toggle, not as a knob.
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// PedalSlider.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdUI
|
||||
|
||||
/// A UI-agnostic description of one continuous vertical pedal fader.
|
||||
///
|
||||
/// Where ``PedalKnob`` describes a rotary control and ``PedalSwitch`` a discrete
|
||||
/// segmented control, `PedalSlider` describes a continuous vertical fader — the control
|
||||
/// a graphic EQ uses for its per-band gains and master output level. A `Pedal` publishes
|
||||
/// an array of these via ``Pedal/effectSliders`` so a generic pedalboard UI can render a
|
||||
/// bank of vertical faders without knowing the concrete pedal type.
|
||||
///
|
||||
/// Each descriptor pairs a display label with the live ``UIParamNode`` (the projected
|
||||
/// value of an `@UIParam` property) and the value range the fader should span.
|
||||
public struct PedalSlider {
|
||||
|
||||
/// Short label shown beneath the fader (e.g. "Low", "Gain").
|
||||
public let label: String
|
||||
|
||||
/// The live parameter node the fader reads and writes. Pass `pedal.$paramName`.
|
||||
public let node: UIParamNode
|
||||
|
||||
/// Inclusive value range the fader spans, in the parameter's own units.
|
||||
public let range: ClosedRange<Double>
|
||||
|
||||
/// Creates a slider descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Short label shown beneath the fader.
|
||||
/// - node: The `UIParamNode` projected value of an `@UIParam` property
|
||||
/// (`pedal.$lowGain`, `pedal.$globalGain`, …).
|
||||
/// - range: Inclusive value range the fader spans, in the parameter's units.
|
||||
public init(
|
||||
label: String,
|
||||
node: UIParamNode,
|
||||
range: ClosedRange<Double>
|
||||
) {
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.range = range
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// GraphicEQPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Five-band graphic EQ pedal built from cascaded RBJ filters, with a master output gain.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → RBJLowShelf(80 Hz) → RBJPeakingEQ(240 Hz) → RBJPeakingEQ(750 Hz)
|
||||
/// → RBJPeakingEQ(2.2 kHz) → RBJHighShelf(6.5 kHz) → × globalGain → mono out
|
||||
/// ```
|
||||
///
|
||||
/// Each band's gain is an `@UIParam` in decibels and is published as a vertical fader via
|
||||
/// ``effectSliders`` — the pedalboard UI renders the bank as a row of graphic-EQ sliders.
|
||||
/// The trailing master fader (`globalGain`, a linear multiplier) trims the overall level
|
||||
/// after the EQ curve so boosting several bands need not clip the output.
|
||||
///
|
||||
/// Band centre frequencies and filter Q/slope are fixed; only the per-band gains and the
|
||||
/// master output level are adjustable.
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lowGain: Low-shelf gain at 80 Hz, in dB. Range `[-12, 12]`. Defaults to `0.0`.
|
||||
/// - lowMidGain: Peaking gain at 240 Hz, in dB. Range `[-12, 12]`. Defaults to `0.0`.
|
||||
/// - midGain: Peaking gain at 750 Hz, in dB. Range `[-12, 12]`. Defaults to `0.0`.
|
||||
/// - highMidGain: Peaking gain at 2.2 kHz, in dB. Range `[-12, 12]`. Defaults to `0.0`.
|
||||
/// - highGain: High-shelf gain at 6.5 kHz, in dB. Range `[-12, 12]`. Defaults to `0.0`.
|
||||
/// - globalGain: Master output gain in dB. `0` = unity. Range `[-12, 12]`.
|
||||
/// Defaults to `0.0`.
|
||||
public final class GraphicEQPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Low-shelf gain in dB. Range [-12, 12].
|
||||
@UIParam public var lowGain: Double = 0.0
|
||||
|
||||
/// Low-mid peaking gain in dB. Range [-12, 12].
|
||||
@UIParam public var lowMidGain: Double = 0.0
|
||||
|
||||
/// Mid peaking gain in dB. Range [-12, 12].
|
||||
@UIParam public var midGain: Double = 0.0
|
||||
|
||||
/// High-mid peaking gain in dB. Range [-12, 12].
|
||||
@UIParam public var highMidGain: Double = 0.0
|
||||
|
||||
/// High-shelf gain in dB. Range [-12, 12].
|
||||
@UIParam public var highGain: Double = 0.0
|
||||
|
||||
/// Master output gain in dB. Range [-12, 12]. `0` = unity.
|
||||
@UIParam public var globalGain: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the EQ sits in-line.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Band centre frequencies in Hz (low shelf, three peaks, high shelf).
|
||||
private let lowFreq: Double = 80.0
|
||||
private let lowMidFreq: Double = 240.0
|
||||
private let midFreq: Double = 750.0
|
||||
private let highMidFreq: Double = 2200.0
|
||||
private let highFreq: Double = 6500.0
|
||||
|
||||
/// Shelf slope. `1.0` = maximum (steepest) shelf with no overshoot.
|
||||
private let shelfSlope: Double = 1.0
|
||||
|
||||
/// Peaking-band quality factor — moderate bandwidth so adjacent bands overlap smoothly.
|
||||
private let peakQ: Double = 0.9
|
||||
|
||||
/// dB → natural-exponent scale, `ln(10) / 20`. `exp(dB · scale) == 10^(dB/20)`, the
|
||||
/// linear amplitude multiplier for a dB gain. Applied to the master output gain.
|
||||
private let dbToLinExpScale: Double = 0.115_129_254_649_702_28
|
||||
|
||||
// MARK: - UI sliders
|
||||
|
||||
/// Per-band gain fader range, in dB.
|
||||
private let bandGainRange: ClosedRange<Double> = -12.0 ... 12.0
|
||||
|
||||
/// Master output fader range, in dB.
|
||||
private let globalGainRange: ClosedRange<Double> = -12.0 ... 12.0
|
||||
|
||||
public override var effectSliders: [PedalSlider] {
|
||||
[
|
||||
PedalSlider(label: "80", node: $lowGain, range: bandGainRange),
|
||||
PedalSlider(label: "240", node: $lowMidGain, range: bandGainRange),
|
||||
PedalSlider(label: "750", node: $midGain, range: bandGainRange),
|
||||
PedalSlider(label: "2.2k", node: $highMidGain, range: bandGainRange),
|
||||
PedalSlider(label: "6.5k", node: $highGain, range: bandGainRange),
|
||||
PedalSlider(label: "Gain", node: $globalGain, range: globalGainRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a five-band graphic EQ 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: "Graphic EQ",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: GraphicEQPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Applies the cascaded five-band RBJ EQ curve, then the master output gain.
|
||||
///
|
||||
/// Output is mono.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Equalised, level-trimmed mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let lowShelf: RBJLowShelf.Audio = RBJLowShelf.Audio(
|
||||
input: dry,
|
||||
freq: lowFreq,
|
||||
gain: $lowGain,
|
||||
slope: shelfSlope
|
||||
)
|
||||
let lowMid: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
|
||||
input: lowShelf,
|
||||
freq: lowMidFreq,
|
||||
gain: $lowMidGain,
|
||||
q: peakQ
|
||||
)
|
||||
let mid: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
|
||||
input: lowMid,
|
||||
freq: midFreq,
|
||||
gain: $midGain,
|
||||
q: peakQ
|
||||
)
|
||||
let highMid: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
|
||||
input: mid,
|
||||
freq: highMidFreq,
|
||||
gain: $highMidGain,
|
||||
q: peakQ
|
||||
)
|
||||
let highShelf: RBJHighShelf.Audio = RBJHighShelf.Audio(
|
||||
input: highMid,
|
||||
freq: highFreq,
|
||||
gain: $highGain,
|
||||
slope: shelfSlope
|
||||
)
|
||||
// Convert the master dB gain to a linear amplitude multiplier: 10^(dB/20).
|
||||
let masterGain: Exp.Audio = Exp.Audio($globalGain * dbToLinExpScale)
|
||||
return highShelf * masterGain
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
// LimiterPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Limiter pedal: a clean gain-boost stage feeding a brick-wall look-ahead limiter.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → × boost → LookAheadLimiter(maxAmplitude: ceiling) → mono out
|
||||
/// ```
|
||||
///
|
||||
/// The boost stage drives the signal up *before* the limiter, so cranking `boost`
|
||||
/// pushes more of the signal into limiting and raises sustain/perceived loudness while
|
||||
/// the look-ahead limiter guarantees the output peak never exceeds `ceiling`.
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - boost: Pre-limit input gain as a linear multiplier. `1.0` = unity. Higher values
|
||||
/// drive harder into the limiter. Range `[1, 12]`. Defaults to `1.0`.
|
||||
/// - ceiling: Output peak ceiling as a linear amplitude in `[0, 1]`. The limited output
|
||||
/// never exceeds this absolute value. Range `[0.1, 1.0]`. Defaults to `0.95`.
|
||||
public final class LimiterPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Pre-limit input gain (linear multiplier). Range [1, 12].
|
||||
@UIParam public var boost: Double = 1.0
|
||||
|
||||
/// Output peak ceiling (linear amplitude). Range [0.1, 1.0].
|
||||
@UIParam public var ceiling: Double = 0.95
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the limiter sits in-line.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Look-ahead / output delay in seconds. Fixed at a short window that catches
|
||||
/// transients without smearing attack.
|
||||
private let lookAheadTime: Double = 0.005
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Boost knob range (linear pre-limit gain).
|
||||
private let boostRange: ClosedRange<Double> = 1.0 ... 12.0
|
||||
|
||||
/// Ceiling knob range (linear output peak).
|
||||
private let ceilingRange: ClosedRange<Double> = 0.1 ... 1.0
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Boost", node: $boost, range: boostRange),
|
||||
PedalKnob(label: "Ceiling", node: $ceiling, range: ceilingRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a limiter 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: "Limiter",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: LimiterPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Boosts the dry signal then constrains its peak with a look-ahead limiter.
|
||||
///
|
||||
/// Output is mono.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Boosted, peak-limited mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let boosted: any ValidGeneratorInput = dry * $boost
|
||||
return LookAheadLimiter(
|
||||
in: boosted,
|
||||
maxAmplitude: $ceiling,
|
||||
lookAheadTime: lookAheadTime,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// NoiseGatePedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Noise-gate pedal: an amplitude-tracked gate with a tuneable residual floor.
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry ─┬─────────────────────────────────────────────────────────┐
|
||||
/// └→ AmplitudeFollower → Schmidt(lo: thr, hi: thr×ratio) │
|
||||
/// → LinLin(0…1 → floor…1) │
|
||||
/// → Lag(smooth) ───────────── × ──┴→ mono out
|
||||
/// ```
|
||||
///
|
||||
/// An `AmplitudeFollower` tracks the dry signal level. A Schmitt trigger turns that
|
||||
/// envelope into an open/closed gate with hysteresis (opens above `threshold × openRatio`,
|
||||
/// closes below `threshold`) so the gate does not chatter around the threshold. The 0/1
|
||||
/// gate is mapped to a gain in `[floor, 1]` and smoothed before multiplying the dry signal:
|
||||
/// when the gate is closed the signal is attenuated to `floor` rather than hard-muted, so
|
||||
/// `floor` sets how much of the quiet signal/noise tail bleeds through.
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
///
|
||||
/// ## Parameters
|
||||
///
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - threshold: Gate close threshold as a linear amplitude. Envelope below this closes
|
||||
/// the gate. Range `[0, 0.2]`. Defaults to `0.02`.
|
||||
/// - floor: Residual gain applied while the gate is closed, in `[0, 1]`. `0` = full
|
||||
/// mute, `1` = no gating. Range `[0, 1]`. Defaults to `0.0`.
|
||||
public final class NoiseGatePedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Gate close threshold (linear amplitude). Range [0, 0.2].
|
||||
@UIParam public var threshold: Double = 0.02
|
||||
|
||||
/// Residual gain while closed, [0, 1]. Range [0, 1].
|
||||
@UIParam public var floor: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the gate sits in-line.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Envelope-follower attack time, in seconds — fast so the gate opens promptly on a note.
|
||||
private let detectAttack: Double = 0.002
|
||||
|
||||
/// Envelope-follower release time, in seconds — slower so the gate holds through decay.
|
||||
private let detectRelease: Double = 0.05
|
||||
|
||||
/// Open-threshold multiplier. The gate opens above `threshold × openRatio` and closes
|
||||
/// below `threshold`, giving hysteresis that prevents chatter near the threshold.
|
||||
private let openRatio: Double = 2.0
|
||||
|
||||
/// Gain-smoothing lag time, in seconds — removes the click of an instantaneous 0↔1 gate.
|
||||
private let gainSmoothTime: Double = 0.01
|
||||
|
||||
/// Gate signal bounds for the `LinLin` floor map.
|
||||
private let gateLo: Double = 0.0
|
||||
private let gateHi: Double = 1.0
|
||||
|
||||
/// Upper gain the open gate maps to (unity).
|
||||
private let openGain: Double = 1.0
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Threshold knob range (linear amplitude).
|
||||
private let thresholdRange: ClosedRange<Double> = 0.0 ... 0.2
|
||||
|
||||
/// Floor knob range (residual gain).
|
||||
private let floorRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Threshold", node: $threshold, range: thresholdRange),
|
||||
PedalKnob(label: "Floor", node: $floor, range: floorRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a noise-gate 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: "Noise Gate",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: NoiseGatePedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Gates the dry signal below `threshold`, attenuating closed passages to `floor`.
|
||||
///
|
||||
/// Output is mono.
|
||||
///
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Gated mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// Track the dry signal's amplitude envelope.
|
||||
let envelope: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||
in: dry,
|
||||
attackTime: detectAttack,
|
||||
releaseTime: detectRelease
|
||||
)
|
||||
|
||||
// Hysteretic open/closed gate: opens above threshold×openRatio, closes below threshold.
|
||||
let gate: Schmidt.Audio = Schmidt.Audio(
|
||||
input: envelope,
|
||||
lo: $threshold,
|
||||
hi: $threshold * openRatio
|
||||
)
|
||||
|
||||
// Map the 0/1 gate to a gain in [floor, 1] so closed passages bleed `floor`, not silence.
|
||||
let gain: LinLin.Audio = LinLin.Audio(
|
||||
gate,
|
||||
inLo: gateLo,
|
||||
inHi: gateHi,
|
||||
outLo: $floor,
|
||||
outHi: openGain
|
||||
)
|
||||
|
||||
// Smooth the gain to remove the click of an instantaneous gate transition.
|
||||
let smoothed: Lag.Audio = Lag.Audio(
|
||||
input: gain,
|
||||
time: gainSmoothTime
|
||||
)
|
||||
|
||||
return dry * smoothed
|
||||
}
|
||||
}
|
||||
@@ -18,10 +18,12 @@ extension Pedal {
|
||||
public func captureState() -> PedalState {
|
||||
let values: [Double] = knobs.map { $0.node.value }
|
||||
let switchValues: [Double] = effectSwitches.map { $0.node.value }
|
||||
let sliderValues: [Double] = effectSliders.map { $0.node.value }
|
||||
return PedalState(
|
||||
type: displayName,
|
||||
knobValues: values,
|
||||
switchValues: switchValues,
|
||||
sliderValues: sliderValues,
|
||||
bypass: bypass
|
||||
)
|
||||
}
|
||||
@@ -46,6 +48,9 @@ extension Pedal {
|
||||
for (pedalSwitch, value) in zip(effectSwitches, state.switchValues) {
|
||||
pedalSwitch.node.update(value)
|
||||
}
|
||||
for (slider, value) in zip(effectSliders, state.sliderValues) {
|
||||
slider.node.update(value)
|
||||
}
|
||||
bypass = state.bypass
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,9 @@ public enum PedalRegistry {
|
||||
"Octave Splitter": { OctaveUpSplitterPedal() },
|
||||
"Bass Octaver": { BassOctaverPedal() },
|
||||
"Ping-Pong": { PingPongDelayPedal() },
|
||||
"Limiter": { LimiterPedal() },
|
||||
"Noise Gate": { NoiseGatePedal() },
|
||||
"Graphic EQ": { GraphicEQPedal() },
|
||||
]
|
||||
|
||||
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
|
||||
|
||||
@@ -26,6 +26,10 @@ public struct PedalState: Codable, Equatable {
|
||||
/// no switches. Absent in presets saved before switches existed — decodes to `[]`.
|
||||
public let switchValues: [Double]
|
||||
|
||||
/// Slider values in the same order as `Pedal.effectSliders`. Empty for pedals with
|
||||
/// no sliders. Absent in presets saved before sliders existed — decodes to `[]`.
|
||||
public let sliderValues: [Double]
|
||||
|
||||
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
|
||||
public let bypass: Double
|
||||
|
||||
@@ -35,16 +39,19 @@ public struct PedalState: Codable, Equatable {
|
||||
/// - type: The pedal's `displayName`, used to identify the pedal type on load.
|
||||
/// - 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.
|
||||
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
public init(
|
||||
type: String,
|
||||
knobValues: [Double],
|
||||
switchValues: [Double] = [],
|
||||
sliderValues: [Double] = [],
|
||||
bypass: Double
|
||||
) {
|
||||
self.type = type
|
||||
self.knobValues = knobValues
|
||||
self.switchValues = switchValues
|
||||
self.sliderValues = sliderValues
|
||||
self.bypass = bypass
|
||||
}
|
||||
|
||||
@@ -52,16 +59,18 @@ public struct PedalState: Codable, Equatable {
|
||||
case type
|
||||
case knobValues
|
||||
case switchValues
|
||||
case sliderValues
|
||||
case bypass
|
||||
}
|
||||
|
||||
/// Decodes a snapshot, tolerating presets saved before `switchValues` existed by
|
||||
/// defaulting the missing key to an empty array.
|
||||
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues`
|
||||
/// existed by defaulting the missing keys to an empty array.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = 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.bypass = try container.decode(Double.self, forKey: .bypass)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,8 @@ 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", "Fuzz", "Tremolo", "Phaser", "Modulation",
|
||||
"Overdrive", "Compressor", "Limiter", "Noise Gate", "Fuzz",
|
||||
"Graphic EQ", "Tremolo", "Phaser", "Modulation",
|
||||
"Auto-Wah", "Mu-Tron", "Bass Octaver", "Octave Splitter",
|
||||
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb",
|
||||
]
|
||||
|
||||
@@ -28,6 +28,9 @@ 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 "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
|
||||
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
|
||||
}
|
||||
}
|
||||
@@ -184,6 +187,11 @@ public struct PedalView: View {
|
||||
private static let screwInset: CGFloat = 6
|
||||
private static let knobColumnCount: Int = 3
|
||||
private static let knobSpacing: CGFloat = 10
|
||||
/// Horizontal gap between adjacent vertical faders in the slider bank.
|
||||
private static let sliderBankSpacing: CGFloat = 4
|
||||
/// Approximate per-fader footprint (matches `VerticalParameterSlider.controlWidth`),
|
||||
/// used to widen the enclosure so a wide bank (e.g. a 6-band EQ) is never clipped.
|
||||
private static let sliderBankItemWidth: CGFloat = 28
|
||||
/// Horizontal gap between the Level knob and the bypass control in the bottom row.
|
||||
private static let bottomControlsSpacing: CGFloat = 18
|
||||
private static let sectionSpacing: CGFloat = 14
|
||||
@@ -224,6 +232,9 @@ public struct PedalView: View {
|
||||
public var body: some View {
|
||||
let accent: Color = enclosureColor(for: pedal.displayName)
|
||||
let darkAccent: Color = accent.opacity(PedalView.enclosureGradientDarkFraction)
|
||||
// Evaluate the (computed) slider descriptors once per render — both the bank and
|
||||
// the enclosure-width calculation consume the same array.
|
||||
let sliders: [PedalSlider] = pedal.effectSliders
|
||||
|
||||
ZStack(alignment: .topLeading) {
|
||||
// Enclosure fill with top-to-bottom gradient
|
||||
@@ -252,6 +263,7 @@ public struct PedalView: View {
|
||||
namePlate
|
||||
knobGrid
|
||||
switchRow
|
||||
sliderBank(sliders)
|
||||
Spacer(minLength: 0)
|
||||
bottomControls
|
||||
}
|
||||
@@ -260,7 +272,7 @@ public struct PedalView: View {
|
||||
// Corner screws — overlaid at the four corners
|
||||
screwCorners
|
||||
}
|
||||
.frame(width: PedalView.enclosureWidth)
|
||||
.frame(width: enclosureWidth(for: sliders))
|
||||
.shadow(
|
||||
color: Color.black.opacity(PedalView.shadowOpacity),
|
||||
radius: PedalView.shadowRadius,
|
||||
@@ -332,6 +344,32 @@ public struct PedalView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row of vertical faders drawn from `pedal.effectSliders`, beneath the switch row.
|
||||
/// Renders nothing when the pedal publishes no sliders.
|
||||
@ViewBuilder
|
||||
private func sliderBank(_ sliders: [PedalSlider]) -> some View {
|
||||
if !sliders.isEmpty {
|
||||
HStack(alignment: .top, spacing: PedalView.sliderBankSpacing) {
|
||||
ForEach(Array(sliders.enumerated()), id: \.offset) { pair in
|
||||
let slider: PedalSlider = pair.element
|
||||
VerticalParameterSlider(slider.label, node: slider.node, range: slider.range)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enclosure width — the base stompbox width, widened to fit a wide vertical-fader bank
|
||||
/// (e.g. a multi-band graphic EQ) so its faders are never clipped.
|
||||
private func enclosureWidth(for sliders: [PedalSlider]) -> CGFloat {
|
||||
let sliderCount: Int = sliders.count
|
||||
guard sliderCount > 0 else { return PedalView.enclosureWidth }
|
||||
let bankContentWidth: CGFloat =
|
||||
CGFloat(sliderCount) * PedalView.sliderBankItemWidth
|
||||
+ CGFloat(max(0, sliderCount - 1)) * PedalView.sliderBankSpacing
|
||||
let needed: CGFloat = bankContentWidth + 2 * PedalView.enclosurePadding
|
||||
return max(PedalView.enclosureWidth, needed)
|
||||
}
|
||||
|
||||
/// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob,
|
||||
/// side-by-side and centred — a symmetric knob-switch-knob footer shared by all pedals.
|
||||
private var bottomControls: some View {
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
// VerticalParameterSlider.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
|
||||
/// A vertical fader bound to a single ``UIParamNode``.
|
||||
///
|
||||
/// Drag anywhere on the track to set the value: dragging to the top maps to
|
||||
/// `range.upperBound`, dragging to the bottom maps to `range.lowerBound`. A filled bar
|
||||
/// grows up from the bottom to show the current position and a thin thumb marks the value.
|
||||
/// The control reads `node.value` (so it re-renders when the parameter changes elsewhere)
|
||||
/// and writes back via `node.update(_:)`.
|
||||
///
|
||||
/// `PedalView` renders a row of these for the graphic-EQ-style fader bank a pedal
|
||||
/// publishes through `Pedal.effectSliders`.
|
||||
struct VerticalParameterSlider: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
private static let trackWidth: CGFloat = 10
|
||||
private static let trackCornerRadius: CGFloat = 5
|
||||
private static let thumbHeight: CGFloat = 4
|
||||
private static let thumbWidth: CGFloat = 20
|
||||
private static let thumbCornerRadius: CGFloat = 2
|
||||
private static let controlWidth: CGFloat = 28
|
||||
private static let trackHeight: CGFloat = 110
|
||||
private static let labelSpacing: CGFloat = 4
|
||||
private static let valueSpacing: CGFloat = 4
|
||||
private static let fontSizeLabel: CGFloat = 9
|
||||
private static let fontSizeValue: CGFloat = 9
|
||||
private static let trackBackgroundOpacity: Double = 0.30
|
||||
private static let fillTopOpacity: Double = 0.95
|
||||
private static let fillBottomOpacity: Double = 0.55
|
||||
private static let thumbOpacity: Double = 0.95
|
||||
private static let labelOpacity: Double = 0.85
|
||||
private static let valueOpacity: Double = 0.70
|
||||
/// Range span at or above which the value is shown as a whole number (dB bands) rather
|
||||
/// than with two decimals (narrow linear ranges like the master gain).
|
||||
private static let wideSpanThreshold: Double = 5.0
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let label: String
|
||||
private let node: UIParamNode
|
||||
private let range: ClosedRange<Double>
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a vertical fader.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Short caption shown beneath the fader.
|
||||
/// - node: The `UIParamNode` the fader reads and writes.
|
||||
/// - range: Inclusive value range the fader spans, in the parameter's units.
|
||||
init(
|
||||
_ label: String,
|
||||
node: UIParamNode,
|
||||
range: ClosedRange<Double>
|
||||
) {
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.range = range
|
||||
}
|
||||
|
||||
// MARK: - Value mapping
|
||||
|
||||
/// Current value clamped into `range`.
|
||||
private var clampedValue: Double {
|
||||
min(max(node.value, range.lowerBound), range.upperBound)
|
||||
}
|
||||
|
||||
/// Current value as a `[0, 1]` fraction of the range (0 = bottom, 1 = top).
|
||||
private var fraction: CGFloat {
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
guard span > 0 else { return 0 }
|
||||
return CGFloat((clampedValue - range.lowerBound) / span)
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: VerticalParameterSlider.labelSpacing) {
|
||||
track
|
||||
Text(label)
|
||||
.font(.system(size: VerticalParameterSlider.fontSizeLabel, weight: .semibold))
|
||||
.foregroundStyle(Color.white.opacity(VerticalParameterSlider.labelOpacity))
|
||||
.lineLimit(1)
|
||||
Text(valueText)
|
||||
.font(.system(size: VerticalParameterSlider.fontSizeValue, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(VerticalParameterSlider.valueOpacity))
|
||||
.lineLimit(1)
|
||||
}
|
||||
.frame(width: VerticalParameterSlider.controlWidth)
|
||||
}
|
||||
|
||||
/// The draggable track with background, value fill, and thumb.
|
||||
private var track: some View {
|
||||
GeometryReader { geometry in
|
||||
let height: CGFloat = geometry.size.height
|
||||
let fillHeight: CGFloat = height * fraction
|
||||
|
||||
ZStack(alignment: .bottom) {
|
||||
// Background track
|
||||
RoundedRectangle(cornerRadius: VerticalParameterSlider.trackCornerRadius)
|
||||
.fill(Color.black.opacity(VerticalParameterSlider.trackBackgroundOpacity))
|
||||
.frame(width: VerticalParameterSlider.trackWidth)
|
||||
|
||||
// Value fill growing up from the bottom
|
||||
RoundedRectangle(cornerRadius: VerticalParameterSlider.trackCornerRadius)
|
||||
.fill(
|
||||
LinearGradient(
|
||||
colors: [
|
||||
Color.white.opacity(VerticalParameterSlider.fillTopOpacity),
|
||||
Color.white.opacity(VerticalParameterSlider.fillBottomOpacity),
|
||||
],
|
||||
startPoint: .top,
|
||||
endPoint: .bottom
|
||||
)
|
||||
)
|
||||
.frame(width: VerticalParameterSlider.trackWidth, height: fillHeight)
|
||||
|
||||
// Thumb marking the current value. Clamp its centre into the track so it
|
||||
// never overhangs the ends at the value extremes.
|
||||
let halfThumb: CGFloat = VerticalParameterSlider.thumbHeight / 2
|
||||
let thumbCentre: CGFloat = min(max(fillHeight, halfThumb), height - halfThumb)
|
||||
RoundedRectangle(cornerRadius: VerticalParameterSlider.thumbCornerRadius)
|
||||
.fill(Color.white.opacity(VerticalParameterSlider.thumbOpacity))
|
||||
.frame(
|
||||
width: VerticalParameterSlider.thumbWidth,
|
||||
height: VerticalParameterSlider.thumbHeight
|
||||
)
|
||||
.offset(y: -(thumbCentre - halfThumb))
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.contentShape(Rectangle())
|
||||
.gesture(
|
||||
DragGesture(minimumDistance: 0)
|
||||
.onChanged { drag in
|
||||
updateValue(forY: drag.location.y, height: height)
|
||||
}
|
||||
)
|
||||
}
|
||||
.frame(width: VerticalParameterSlider.controlWidth, height: VerticalParameterSlider.trackHeight)
|
||||
}
|
||||
|
||||
/// Formats the current value: integers when the span is wide (dB bands), two decimals otherwise.
|
||||
private var valueText: String {
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
if span >= VerticalParameterSlider.wideSpanThreshold {
|
||||
return String(format: "%.0f", clampedValue)
|
||||
}
|
||||
return String(format: "%.2f", clampedValue)
|
||||
}
|
||||
|
||||
// MARK: - Drag handling
|
||||
|
||||
/// Converts a vertical drag position into a parameter value and writes it to the node.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - y: Drag Y position in the track's coordinate space (0 = top).
|
||||
/// - height: Track height in points.
|
||||
private func updateValue(forY y: CGFloat, height: CGFloat) {
|
||||
guard height > 0 else { return }
|
||||
// Invert: top of the track (y = 0) is the maximum, bottom is the minimum.
|
||||
let clampedY: CGFloat = min(max(y, 0), height)
|
||||
let frac: Double = Double(1 - clampedY / height)
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
node.update(range.lowerBound + frac * span)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// GraphicEQPedalTests.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("GraphicEQPedal")
|
||||
struct GraphicEQPedalTests {
|
||||
|
||||
/// Renders a `GraphicEQPedal` after applying `configure`, returning the interleaved output.
|
||||
private func render(configure: (GraphicEQPedal) -> Void) throws -> [Float] {
|
||||
let renderDuration: Double = 0.1
|
||||
let sampleRate: Double = 44100.0
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
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: GraphicEQPedal = GraphicEQPedal(
|
||||
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, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
@Test func flatEQProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in } // all gains 0 dB, unity output
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "Flat EQ produced silence")
|
||||
}
|
||||
|
||||
@Test func publishesSixSliders() throws {
|
||||
let pedal: GraphicEQPedal = GraphicEQPedal()
|
||||
#expect(pedal.effectSliders.count == 6)
|
||||
#expect(pedal.effectSliders.last?.label == "Gain")
|
||||
}
|
||||
|
||||
@Test func globalGainScalesOutput() throws {
|
||||
// The master gain is in dB. +12 dB should be far louder than -12 dB
|
||||
// (24 dB apart ≈ 15.8× amplitude ≈ 250× power).
|
||||
let quiet: [Float] = try render { $0.globalGain = -12.0 }
|
||||
let loud: [Float] = try render { $0.globalGain = 12.0 }
|
||||
|
||||
func power(_ samples: [Float]) -> Double {
|
||||
samples.reduce(0.0) { acc, s in
|
||||
let v: Double = Double(s)
|
||||
return acc + v * v
|
||||
}
|
||||
}
|
||||
let quietPower: Double = power(quiet)
|
||||
let loudPower: Double = power(loud)
|
||||
|
||||
#expect(quietPower > 0, "-12 dB EQ was silent")
|
||||
// Expect well over an order of magnitude more power at +12 dB vs -12 dB.
|
||||
let minPowerRatio: Double = 50.0
|
||||
#expect(
|
||||
loudPower > quietPower * minPowerRatio,
|
||||
"Master dB gain did not scale output: loud=\(loudPower) quiet=\(quietPower)"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func sliderValuesRoundTripThroughPresetState() throws {
|
||||
// Band/global gains live in effectSliders; they must survive captureState/applyState.
|
||||
let source: GraphicEQPedal = GraphicEQPedal()
|
||||
source.lowGain = 6.0
|
||||
source.lowMidGain = -3.0
|
||||
source.midGain = 4.5
|
||||
source.highMidGain = -7.0
|
||||
source.highGain = 2.0
|
||||
source.globalGain = 1.5
|
||||
|
||||
let state: PedalState = source.captureState()
|
||||
#expect(state.sliderValues.count == 6)
|
||||
|
||||
let restored: GraphicEQPedal = GraphicEQPedal()
|
||||
restored.applyState(state)
|
||||
|
||||
let tolerance: Double = 1e-6
|
||||
#expect(abs(restored.lowGain - 6.0) < tolerance)
|
||||
#expect(abs(restored.lowMidGain - (-3.0)) < tolerance)
|
||||
#expect(abs(restored.midGain - 4.5) < tolerance)
|
||||
#expect(abs(restored.highMidGain - (-7.0)) < tolerance)
|
||||
#expect(abs(restored.highGain - 2.0) < tolerance)
|
||||
#expect(abs(restored.globalGain - 1.5) < tolerance)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// LimiterPedalTests.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("LimiterPedal")
|
||||
struct LimiterPedalTests {
|
||||
|
||||
/// Renders a `LimiterPedal` through an offline engine and returns the interleaved output.
|
||||
private func render(
|
||||
boost: Double,
|
||||
ceiling: Double,
|
||||
sampleRate: Double = 44100.0
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.1
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
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: LimiterPedal = LimiterPedal(
|
||||
inputBus: srcBus.index,
|
||||
outputBus: dstBus.index
|
||||
)
|
||||
// Match the engine rate so the look-ahead limiter sizes its ring correctly.
|
||||
pedal.sampleRate = sampleRate
|
||||
pedal.boost = boost
|
||||
pedal.ceiling = ceiling
|
||||
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, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render(boost: 2.0, ceiling: 0.95)
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "LimiterPedal produced silence")
|
||||
}
|
||||
|
||||
@Test func outputNeverExceedsCeiling() throws {
|
||||
// Drive hard into the limiter with a low ceiling; the peak must stay at the ceiling.
|
||||
// Downstream Pan2/gain in the master only attenuates, so the recorded peak is a
|
||||
// conservative upper bound on the limiter output peak.
|
||||
let ceiling: Double = 0.5
|
||||
let samples: [Float] = try render(boost: 12.0, ceiling: ceiling)
|
||||
#expect(hasNonSilentOutput(samples), "Driven limiter produced silence")
|
||||
|
||||
// Skip the look-ahead fill window before measuring the peak. The limiter's 5 ms
|
||||
// look-ahead at 44.1 kHz is ~220 frames; 2048 interleaved samples is a comfortable
|
||||
// margin past the window-fill transient.
|
||||
let lookAheadFillSamples: Int = 2048
|
||||
guard samples.count > lookAheadFillSamples else { return }
|
||||
let window: ArraySlice<Float> = samples[lookAheadFillSamples...]
|
||||
let peak: Float = window.reduce(0) { Swift.max($0, abs($1)) }
|
||||
|
||||
let tolerance: Float = 0.05
|
||||
#expect(peak <= Float(ceiling) + tolerance, "Limiter overshot ceiling: peak=\(peak)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// NoiseGatePedalTests.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("NoiseGatePedal")
|
||||
struct NoiseGatePedalTests {
|
||||
|
||||
/// Renders a `NoiseGatePedal` through an offline engine and returns the interleaved output.
|
||||
private func render(
|
||||
threshold: Double,
|
||||
floor: Double
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.1
|
||||
let sampleRate: Double = 44100.0
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
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: NoiseGatePedal = NoiseGatePedal(
|
||||
inputBus: srcBus.index,
|
||||
outputBus: dstBus.index
|
||||
)
|
||||
pedal.threshold = threshold
|
||||
pedal.floor = floor
|
||||
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, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
/// Sum of squared samples — a proxy for output power.
|
||||
private func power(_ samples: [Float]) -> Double {
|
||||
samples.reduce(0.0) { acc, s in
|
||||
let v: Double = Double(s)
|
||||
return acc + v * v
|
||||
}
|
||||
}
|
||||
|
||||
@Test func openGatePassesSignal() throws {
|
||||
// A threshold of 0 keeps the gate open — the loop signal should pass through.
|
||||
let samples: [Float] = try render(threshold: 0.0, floor: 0.0)
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "Open gate produced silence")
|
||||
}
|
||||
|
||||
@Test func closedGateWithZeroFloorStronglyAttenuates() throws {
|
||||
// An impossibly high threshold keeps the gate closed; with floor 0 the output
|
||||
// should be far quieter than the open-gate render.
|
||||
let openSamples: [Float] = try render(threshold: 0.0, floor: 0.0)
|
||||
let closedSamples: [Float] = try render(threshold: 0.95, floor: 0.0)
|
||||
|
||||
let openPower: Double = power(openSamples)
|
||||
let closedPower: Double = power(closedSamples)
|
||||
|
||||
#expect(openPower > 0, "Open gate render was silent")
|
||||
// Closed gate should suppress nearly all energy.
|
||||
let suppressionFactor: Double = 0.05
|
||||
#expect(
|
||||
closedPower < openPower * suppressionFactor,
|
||||
"Closed gate did not attenuate: open=\(openPower) closed=\(closedPower)"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func unityFloorLeavesSignalUntouched() throws {
|
||||
// floor = 1 means no gating regardless of threshold — output stays present.
|
||||
let samples: [Float] = try render(threshold: 0.95, floor: 1.0)
|
||||
#expect(hasNonSilentOutput(samples), "Unity-floor gate muted the signal")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user