Add segmented pedal switch control; Mu-Tron sweep + mode switches

Introduces a discrete multi-position switch control alongside the rotary
knobs, and uses it to expose the Mu-Tron's sweep direction and filter mode.

- PedalSwitch: UI-agnostic descriptor (label, node, ordered options of
  caption + value), parallel to PedalKnob. Two options make a two-state
  switch, three a three-state switch.
- PedalSwitchView: segmented SwiftUI control bound to a UIParamNode. Lit
  segment is the option nearest the node's value; tapping writes that
  option's value. Serves both two- and three-state switches.
- Pedal gains an effectSwitches hook; PedalView renders a switch row
  between the knob grid and the footswitch.
- MuTronPedal: sweep direction is now a two-state switch (Down/Up) and
  filter mode a three-state switch (LP/BP/HP). The effect builds six
  MuTronIII instances (three modes x two directions) selected by a nested
  Select so every filter state stays warmed for click-free switching.
- Presets: PedalState gains a backward-compatible switchValues array
  (decodes to empty for older presets); captureState/applyState persist
  and restore switch positions.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-21 15:40:26 -07:00
parent c28e7cac90
commit cb28ea8c7d
8 changed files with 403 additions and 29 deletions
+9
View File
@@ -118,6 +118,15 @@ open class Pedal: SynthesizerBase {
[]
}
/// Effect-specific discrete switches for this pedal, rendered as a row of segmented
/// controls beneath the knob grid.
///
/// Override in subclasses to publish each discrete `@UIParam` parameter as a two- or
/// three-state ``PedalSwitch`` (sweep direction, filter mode, …). Defaults to empty.
open var effectSwitches: [PedalSwitch] {
[]
}
/// 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,69 @@
// PedalSwitch.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// A UI-agnostic description of one multi-position pedal switch.
///
/// Where ``PedalKnob`` describes a continuous rotary control, `PedalSwitch` describes a
/// discrete segmented switch with a fixed set of labelled positions — a two-state toggle
/// (e.g. sweep Up / Down) or a three-state selector (e.g. filter LP / BP / HP). A `Pedal`
/// publishes an array of these via ``Pedal/effectSwitches`` so a generic pedalboard UI can
/// render a segmented control per discrete parameter without knowing the concrete type.
///
/// Each option pairs a short caption with the exact `Double` written to the live
/// ``UIParamNode`` when that position is selected; the currently-lit segment is the option
/// whose `value` is nearest the node's current value.
public struct PedalSwitch {
/// One labelled position of a ``PedalSwitch``.
public struct Option {
/// Short caption shown inside the segment (e.g. "Up", "BP").
public let title: String
/// Value written to the switch's node when this position is selected.
public let value: Double
/// Creates a switch position.
///
/// - Parameters:
/// - title: Short caption shown inside the segment.
/// - value: Value written to the node when this position is selected.
public init(title: String, value: Double) {
self.title = title
self.value = value
}
}
/// Short label shown beneath the segmented control (e.g. "Mode", "Sweep").
public let label: String
/// The live parameter node the switch reads and writes. Pass `pedal.$paramName`.
public let node: UIParamNode
/// Ordered positions, left to right. Two entries make a two-state switch, three a
/// three-state switch. Must contain at least two options.
public let options: [Option]
/// Creates a switch descriptor.
///
/// - Parameters:
/// - label: Short label shown beneath the segmented control.
/// - node: The `UIParamNode` projected value of an `@UIParam` property
/// (`pedal.$mode`, `pedal.$direction`, …).
/// - options: Ordered switch positions, left to right. At least two.
public init(
label: String,
node: UIParamNode,
options: [Option]
) {
precondition(options.count >= 2, "PedalSwitch requires at least two options")
self.label = label
self.node = node
self.options = options
}
}
@@ -11,22 +11,29 @@ import LyrebirdUI
///
/// Wraps the Lyrebird `MuTronIII` generator. The input amplitude drives an exponential
/// cutoff sweep through a resonant Chamberlin state-variable filter. Because `MuTronIII`
/// fixes its filter `mode` at `init`, three instances (lowpass, bandpass, highpass) run
/// in parallel on the shared dry signal and a `Select` switch picks the active one from
/// the `mode` knob — this keeps all three filter states warmed so mode changes are
/// click-free (SuperCollider `Select` semantics: every input advances each block).
/// fixes both its filter `mode` and sweep `direction` at `init`, six instances (three
/// filter modes × two sweep directions) run in parallel on the shared dry signal and a
/// nested `Select` picks the active one from the `mode` and `direction` switches — this
/// keeps every filter state warmed so switch changes are click-free (SuperCollider
/// `Select` semantics: every input advances each block).
///
/// ## Knobs
/// - `mode`: Filter response. `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass.
/// - `sensitivity`: Drive into the envelope follower; higher values open the filter on quieter notes.
/// - `resonance`: Filter peak emphasis at the swept cutoff.
///
/// ## Switches
/// - `direction` (two-state): `0` = Down (louder closes the filter), `1` = Up (louder opens it).
/// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass.
public final class MuTronPedal: Pedal {
// MARK: - Parameters
/// Filter response selector. `0` = lowpass, `1` = bandpass, `2` = highpass.
/// Filter response selector. `0` = lowpass, `1` = bandpass, `2` = highpass. Driven by a three-state switch.
@UIParam public var mode: Double = 1.0
/// Sweep direction selector. `0` = down (louder closes), `1` = up (louder opens). Driven by a two-state switch.
@UIParam public var direction: Double = 1.0
/// Envelope-follower drive. Higher values make the filter respond to quieter input.
@UIParam public var sensitivity: Double = 1.5
@@ -37,9 +44,6 @@ public final class MuTronPedal: Pedal {
private static let defaultMix: Double = 1.0
/// Sweep direction is fixed to the classic "louder opens the filter" response.
private let sweepDirection: MuTronIIISweep = .up
/// Cutoff at zero envelope, in Hz.
private let freqLo: Double = 80.0
@@ -50,13 +54,19 @@ public final class MuTronPedal: Pedal {
private let attackTime: Double = 0.005
private let releaseTime: Double = 0.15
/// Half-step bias added before `Select`'s truncate-toward-zero index, turning the
/// `mode` knob into a round-to-nearest 3-position switch over `[0, 2]`.
private let modeRoundingBias: Double = 0.5
/// Half-step bias added before each `Select`'s truncate-toward-zero index, turning a
/// switch parameter into a round-to-nearest position selector.
private let selectRoundingBias: Double = 0.5
/// Switch position values.
private let modeLowpassValue: Double = 0.0
private let modeBandpassValue: Double = 1.0
private let modeHighpassValue: Double = 2.0
private let directionDownValue: Double = 0.0
private let directionUpValue: Double = 1.0
// MARK: - Ranges
private let modeRange: ClosedRange<Double> = 0.0 ... 2.0
private let sensitivityRange: ClosedRange<Double> = 0.0 ... 4.0
private let resonanceRange: ClosedRange<Double> = 1.0 ... 12.0
@@ -64,12 +74,35 @@ public final class MuTronPedal: Pedal {
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Mode", node: $mode, range: modeRange),
PedalKnob(label: "Sensitivity", node: $sensitivity, range: sensitivityRange),
PedalKnob(label: "Resonance", node: $resonance, range: resonanceRange),
]
}
// MARK: - Switches
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Sweep",
node: $direction,
options: [
PedalSwitch.Option(title: "Down", value: directionDownValue),
PedalSwitch.Option(title: "Up", value: directionUpValue),
]
),
PedalSwitch(
label: "Mode",
node: $mode,
options: [
PedalSwitch.Option(title: "LP", value: modeLowpassValue),
PedalSwitch.Option(title: "BP", value: modeBandpassValue),
PedalSwitch.Option(title: "HP", value: modeHighpassValue),
]
),
]
}
// MARK: - Init
public init(inputBus: Int = 0, outputBus: Int = 0) {
@@ -84,26 +117,43 @@ public final class MuTronPedal: Pedal {
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let lowpass: MuTronIII.Audio = makeFilter(dry, mode: .lowpass)
let bandpass: MuTronIII.Audio = makeFilter(dry, mode: .bandpass)
let highpass: MuTronIII.Audio = makeFilter(dry, mode: .highpass)
// Inner mode selectors per sweep direction. `Select` rounds the [0, 2] mode switch
// to the nearest position and advances all three filters each block (warmed state).
let modeWhich: any ValidGeneratorInput = $mode + selectRoundingBias
let downModes: Select.Audio = Select.Audio(
which: modeWhich,
inputs: [
makeFilter(dry, mode: .lowpass, direction: .down),
makeFilter(dry, mode: .bandpass, direction: .down),
makeFilter(dry, mode: .highpass, direction: .down),
]
)
let upModes: Select.Audio = Select.Audio(
which: modeWhich,
inputs: [
makeFilter(dry, mode: .lowpass, direction: .up),
makeFilter(dry, mode: .bandpass, direction: .up),
makeFilter(dry, mode: .highpass, direction: .up),
]
)
// Round the [0, 2] knob to the nearest integer index, then switch.
let which: any ValidGeneratorInput = $mode + modeRoundingBias
// Outer selector picks the sweep direction (Down = 0, Up = 1).
let directionWhich: any ValidGeneratorInput = $direction + selectRoundingBias
return Select.Audio(
which: which,
inputs: [lowpass, bandpass, highpass]
which: directionWhich,
inputs: [downModes, upModes]
)
}
private func makeFilter(
_ dry: any ValidGeneratorInput,
mode: MuTronIIIMode
mode: MuTronIIIMode,
direction: MuTronIIISweep
) -> MuTronIII.Audio {
MuTronIII.Audio(
input: dry,
mode: mode,
direction: sweepDirection,
direction: direction,
sensitivity: $sensitivity,
peak: $resonance,
freqLo: freqLo,
@@ -17,9 +17,11 @@ extension Pedal {
/// - Returns: A `PedalState` reflecting the pedal's current parameter values.
public func captureState() -> PedalState {
let values: [Double] = knobs.map { $0.node.value }
let switchValues: [Double] = effectSwitches.map { $0.node.value }
return PedalState(
type: displayName,
knobValues: values,
switchValues: switchValues,
bypass: bypass
)
}
@@ -27,10 +29,12 @@ extension Pedal {
/// Applies a previously captured `PedalState` to this pedal's parameters.
///
/// For each (knob, value) pair in `zip(knobs, state.knobValues)`, the knob's
/// `UIParamNode` is updated via `node.update(_:)`. If `state.knobValues` has
/// fewer entries than `knobs`, the trailing knobs retain their current values.
/// Extra values beyond `knobs.count` are ignored. The `bypass` parameter is
/// always applied regardless of knob-count mismatches.
/// `UIParamNode` is updated via `node.update(_:)`; switch positions are restored the
/// same way from `zip(effectSwitches, state.switchValues)`. If either array has fewer
/// entries than its controls, the trailing controls retain their current values; extra
/// values are ignored. The `bypass` parameter is always applied regardless of any
/// count mismatch. Presets saved before switches existed carry an empty
/// `switchValues`, leaving switch positions at their defaults.
///
/// - Parameter state: The state to restore. The `state.type` is not validated
/// against `displayName` — the caller is responsible for matching types before
@@ -39,6 +43,9 @@ extension Pedal {
for (knob, value) in zip(knobs, state.knobValues) {
knob.node.update(value)
}
for (pedalSwitch, value) in zip(effectSwitches, state.switchValues) {
pedalSwitch.node.update(value)
}
bypass = state.bypass
}
}
@@ -22,6 +22,10 @@ public struct PedalState: Codable, Equatable {
/// Knob values in the same order as `Pedal.knobs` (effect knobs then Mix, Level).
public let knobValues: [Double]
/// Switch values in the same order as `Pedal.effectSwitches`. Empty for pedals with
/// no switches. Absent in presets saved before switches existed — decodes to `[]`.
public let switchValues: [Double]
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
public let bypass: Double
@@ -30,14 +34,34 @@ public struct PedalState: Codable, Equatable {
/// - Parameters:
/// - 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.
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
public init(
type: String,
knobValues: [Double],
switchValues: [Double] = [],
bypass: Double
) {
self.type = type
self.knobValues = knobValues
self.switchValues = switchValues
self.bypass = bypass
}
private enum CodingKeys: String, CodingKey {
case type
case knobValues
case switchValues
case bypass
}
/// Decodes a snapshot, tolerating presets saved before `switchValues` existed by
/// defaulting the missing key 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.bypass = try container.decode(Double.self, forKey: .bypass)
}
}
@@ -0,0 +1,125 @@
// PedalSwitchView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdUI
import LyrebirdShoeGaze
// MARK: - PedalSwitchView
/// A segmented multi-position switch bound to a live ``UIParamNode``.
///
/// Renders one button per ``PedalSwitch/Option`` in a horizontal pill, with a caption
/// label beneath — mirroring the look of ``ParameterKnob``. The same view serves both a
/// two-state toggle (two options, e.g. sweep Up / Down) and a three-state selector (three
/// options, e.g. filter LP / BP / HP); the segment count follows `pedalSwitch.options`.
///
/// The lit segment is the option whose `value` is nearest the node's current value.
/// Tapping a segment writes that option's exact `value` via `node.update(_:)`. Reading
/// `node.value` in `body` registers the view for automatic re-render (UIParamNode is
/// `@Observable`).
///
/// ## Usage
/// ```swift
/// PedalSwitchView(pedalSwitch)
/// ```
public struct PedalSwitchView: View {
// MARK: - Layout constants
private static let cornerRadius: CGFloat = 6
private static let segmentSpacing: CGFloat = 3
private static let labelSpacing: CGFloat = 4
private static let segmentPaddingV: CGFloat = 5
private static let segmentPaddingH: CGFloat = 6
private static let fontSize: CGFloat = 11
private static let captionFontSize: CGFloat = 11
private static let activeFillOpacity: Double = 0.88
private static let inactiveFillOpacity: Double = 0.16
private static let borderOpacity: Double = 0.35
private static let borderLineWidth: CGFloat = 1
private static let activeTextBrightness: Double = 0.12
// MARK: - Properties
private let pedalSwitch: PedalSwitch
// MARK: - Init
/// Creates a segmented switch view.
///
/// - Parameter pedalSwitch: The discrete switch descriptor to render.
public init(_ pedalSwitch: PedalSwitch) {
self.pedalSwitch = pedalSwitch
}
// MARK: - Body
public var body: some View {
// Reading `node.value` registers this view for @Observable re-render on change.
let current: Double = pedalSwitch.node.value
let selectedIndex: Int = nearestIndex(to: current)
VStack(spacing: PedalSwitchView.labelSpacing) {
HStack(spacing: PedalSwitchView.segmentSpacing) {
ForEach(Array(pedalSwitch.options.enumerated()), id: \.offset) { pair in
let option: PedalSwitch.Option = pair.element
let isActive: Bool = pair.offset == selectedIndex
segment(option: option, isActive: isActive)
}
}
.overlay(
RoundedRectangle(cornerRadius: PedalSwitchView.cornerRadius)
.stroke(Color.black.opacity(PedalSwitchView.borderOpacity),
lineWidth: PedalSwitchView.borderLineWidth)
)
Text(pedalSwitch.label)
.font(.system(size: PedalSwitchView.captionFontSize))
.foregroundStyle(Color.white)
}
}
// MARK: - Subviews
private func segment(option: PedalSwitch.Option, isActive: Bool) -> some View {
Button(action: {
pedalSwitch.node.update(option.value)
}) {
Text(option.title)
.font(.system(size: PedalSwitchView.fontSize, weight: .semibold))
.foregroundStyle(isActive
? Color(white: PedalSwitchView.activeTextBrightness)
: Color.white)
.padding(.vertical, PedalSwitchView.segmentPaddingV)
.padding(.horizontal, PedalSwitchView.segmentPaddingH)
.frame(maxWidth: .infinity)
.background(
RoundedRectangle(cornerRadius: PedalSwitchView.cornerRadius)
.fill(Color.white.opacity(isActive
? PedalSwitchView.activeFillOpacity
: PedalSwitchView.inactiveFillOpacity))
)
}
.buttonStyle(.plain)
}
// MARK: - Helpers
/// Index of the option whose `value` is nearest `value` — the lit segment.
private func nearestIndex(to value: Double) -> Int {
var bestIndex: Int = 0
var bestDistance: Double = .greatestFiniteMagnitude
for index: Int in pedalSwitch.options.indices {
let distance: Double = abs(pedalSwitch.options[index].value - value)
if distance < bestDistance {
bestDistance = distance
bestIndex = index
}
}
return bestIndex
}
}
@@ -247,6 +247,7 @@ public struct PedalView: View {
VStack(spacing: PedalView.sectionSpacing) {
namePlate
knobGrid
switchRow
Spacer(minLength: 0)
bottomControls
}
@@ -312,6 +313,20 @@ public struct PedalView: View {
}
}
/// Row of segmented switches drawn from `pedal.effectSwitches`, one per row, beneath
/// the knob grid. Renders nothing when the pedal publishes no switches.
@ViewBuilder
private var switchRow: some View {
let switches: [PedalSwitch] = pedal.effectSwitches
if !switches.isEmpty {
VStack(spacing: PedalView.knobSpacing) {
ForEach(Array(switches.enumerated()), id: \.offset) { pair in
PedalSwitchView(pair.element)
}
}
}
}
/// Bottom control row: the `Level` knob and the bypass switch side-by-side, centred
/// with equal padding below.
private var bottomControls: some View {
@@ -95,9 +95,84 @@ struct MuTronPedalTests {
#expect(ssd > 0, "lowpass and highpass modes produced identical output")
}
@Test func exposesModeSensitivityAndResonanceKnobs() throws {
@Test func presetRoundTripPreservesSwitchPositions() throws {
let pedal: MuTronPedal = MuTronPedal()
pedal.mode = 2.0 // highpass
pedal.direction = 0.0 // down
let state: PedalState = pedal.captureState()
#expect(state.switchValues == [0.0, 2.0]) // [direction, mode]
let restored: MuTronPedal = MuTronPedal()
restored.applyState(state)
#expect(restored.mode == 2.0)
#expect(restored.direction == 0.0)
}
@Test func exposesSensitivityAndResonanceKnobs() throws {
let pedal: MuTronPedal = MuTronPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Mode", "Sensitivity", "Resonance"])
#expect(labels == ["Sensitivity", "Resonance"])
}
@Test func exposesTwoStateSweepAndThreeStateModeSwitches() throws {
let pedal: MuTronPedal = MuTronPedal()
let switches: [PedalSwitch] = pedal.effectSwitches
#expect(switches.map { $0.label } == ["Sweep", "Mode"])
// Two-state sweep (Down/Up), three-state mode (LP/BP/HP).
#expect(switches.first?.options.map { $0.title } == ["Down", "Up"])
#expect(switches.last?.options.map { $0.title } == ["LP", "BP", "HP"])
}
@Test func sweepDirectionChangesOutput() throws {
let renderDuration: Double = 0.1
let numAudioBuses: Int = 64
func renderWithDirection(_ directionValue: Double) throws -> [Float] {
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: MuTronPedal = MuTronPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
pedal.direction = directionValue
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)
}
let downSamples: [Float] = try renderWithDirection(0.0)
let upSamples: [Float] = try renderWithDirection(1.0)
#expect(hasNonSilentOutput(downSamples), "down-sweep render was silent")
#expect(hasNonSilentOutput(upSamples), "up-sweep render was silent")
let skipSamples: Int = 1024
let windowSize: Int = 2048
guard downSamples.count >= skipSamples + windowSize,
upSamples.count >= skipSamples + windowSize else { return }
let downWindow: [Float] = Array(downSamples[skipSamples..<(skipSamples + windowSize)])
let upWindow: [Float] = Array(upSamples[skipSamples..<(skipSamples + windowSize)])
let ssd: Double = zip(downWindow, upWindow).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
#expect(ssd > 0, "down and up sweep produced identical output")
}
}