Add MIDI foot-controller control; board/rig bypass; iOS fixes

Headline: MIDI control for a Behringer FCB1010 (four phases).
- MIDIController (Lyrebird MIDI client): connection indicator via source
  polling, background-queue->main-actor hop, MIDI Learn.
- Volume and Wah pedals (Wah reuses the SVF bandpass sweep, driven by
  pedal position instead of an envelope follower).
- CC -> any pedal knob (0-127 mapped across the knob range).
- Program Change -> pedal/board/rig toggles: software latch for booleans,
  exclusive radio for board solo. Positional addressing with display-name
  hints; stale/out-of-range bindings are skipped, not fired.
- Per-rig MIDIMap embedded in ShoeGazeState as an optional field (old rigs
  decode to nil; no preset version bump). Central MIDI Mapping sheet with
  Learn/Clear per control.

Also included (same working branch):
- Full board bypass and rig bypass (dry passthrough via cascaded
  crossfades in BoardOutputMaster), with UI toggles.
- Horizontal pedal picker grouped by category in filter order.
- Drag a palette pedal onto a chain card to insert before it
  (ShoeGaze.insertPedal); tap still appends.
- iOS: guard macOS-only .menuStyle(.borderlessButton) to silence the
  _UIReparentingView warning; iCloud-unavailable alert; keep the device
  awake while audio runs.

Tests: 24 added (Volume/Wah, MIDIMap Codable incl. legacy decode,
CC and PC controller behavior, insert/bypass API). Full suite green;
macOS and iOS app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-01 08:18:09 -07:00
parent ec6c97c065
commit 1893576718
31 changed files with 2117 additions and 28 deletions
@@ -118,6 +118,168 @@ struct BoardEditAPITests {
}
}
// MARK: - Insert
@Test func insertPlacesPedalBeforeTargetAndRenders() throws {
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
// Insert before linear index 1 (the Delay) → lands between Overdrive and Delay.
let edited: PedalBoard = try sg.insertPedal(.fuzz, at: 1, to: board)
#expect(names(edited) == ["Overdrive", "Fuzz", "Delay", "Reverb"])
#expect(sg.boards.count == 1, "insert should not change board count")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "board should still render after insert")
}
@Test func insertAtZeroPrependsToChain() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
let edited: PedalBoard = try sg.insertPedal(.reverb, at: 0, to: board)
#expect(names(edited) == ["Reverb", "Overdrive", "Delay"])
}
@Test func insertAtCountAppendsToChain() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// index == pedal count → append, matching appendPedal placement.
let edited: PedalBoard = try sg.insertPedal(.reverb, at: 2, to: board)
#expect(names(edited) == ["Overdrive", "Delay", "Reverb"])
}
@Test func insertUnknownTypeThrows() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(throws: ShoeGazeError.unknownPedalType("Nope")) {
try sg.insertPedal(PedalType("Nope"), at: 0, to: board)
}
}
@Test func insertOutOfRangeThrows() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// Past the end (count is 2, so valid inserts are 0...2): index 3 is out of range.
#expect(throws: ShoeGazeError.pedalIndexOutOfRange(index: 3, count: 2)) {
try sg.insertPedal(.reverb, at: 3, to: board)
}
}
@Test func insertBeforeTrailingRegionStaysInLinearChain() throws {
// Board: [Overdrive, Delay, <stereo split>]. Inserting at the end of the linear chain must
// land before the split region, not after it.
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendStereoSplit(to: board) // segment index 2
live = try sg.insertPedal(.fuzz, at: 2, to: live, lane: .main) // end of linear chain
#expect(names(live) == ["Overdrive", "Delay", "Fuzz"], "Fuzz appends to the linear chain")
guard case .stereoSplit = live.captureState().segments.last else {
Issue.record("Stereo split should remain the trailing segment; pedal jumped past it")
return
}
}
@Test func insertIntoBranchLaneBeforeTarget() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendStereoSplit(to: board)
live = try sg.appendPedal(.delay, to: live, lane: .left(region: 1))
live = try sg.appendPedal(.reverb, to: live, lane: .left(region: 1))
// Left lane is [Delay, Reverb]; insert Fuzz before index 1 → [Delay, Fuzz, Reverb].
live = try sg.insertPedal(.fuzz, at: 1, to: live, lane: .left(region: 1))
#expect(stereoState(live)?.left.map { $0.type } == ["Delay", "Fuzz", "Reverb"],
"Fuzz should land between Delay and Reverb in the left lane")
}
// MARK: - Full bypass (board / rig)
@Test func boardBypassTogglesStateAndStillRenders() throws {
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(!sg.isBoardBypassed(board), "board starts engaged")
sg.setBoard(board, bypassed: true)
#expect(sg.isBoardBypassed(board), "board reports bypassed after toggle")
// Dry passes straight through — the board still produces audio when bypassed.
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "bypassed board should pass dry audio")
}
@Test func boardBypassReengages() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
sg.setBoard(board, bypassed: true)
sg.setBoard(board, bypassed: false)
#expect(!sg.isBoardBypassed(board), "board should re-engage")
}
@Test func rigBypassTogglesFlagAndRenders() throws {
let (sg, engine, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(!sg.rigBypassed, "rig starts engaged")
sg.toggleRigBypassed()
#expect(sg.rigBypassed, "rig reports bypassed after toggle")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "bypassed rig should pass dry audio")
sg.setRigBypassed(false)
#expect(!sg.rigBypassed, "rig should re-engage")
}
@Test func boardFinalizedWhileRigBypassedComesUpBypassed() throws {
let (sg, _, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
sg.setRigBypassed(true)
// A board added after the rig is bypassed must not leak processed audio: its rig-bypass
// node should come up engaged. We can at least confirm the new board joins cleanly and the
// rig flag stays set.
let board2: PedalBoard = try sg.addBoard()
try board2.add(DelayPedal())
try sg.finalizeBoard(board2)
#expect(sg.rigBypassed, "rig stays bypassed after adding a board")
#expect(board2.rigBypassNode?.value == 1.0, "new board comes up rig-bypassed")
}
@Test func rigRebuildClearsTransientBypass() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"], numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url) }
sg.setBoard(board, bypassed: true)
sg.setRigBypassed(true)
// Reconfiguring the engine tears down and rebuilds every board — transient bypass state
// (which is keyed by board identity) must reset rather than linger stale.
try sg.reconfigureEngine(sampleRate: 48_000, inputChannels: 0, outputChannels: 2)
#expect(!sg.rigBypassed, "rig bypass cleared on rebuild")
#expect(sg.bypassedBoards.isEmpty, "per-board bypass set cleared on rebuild")
}
// MARK: - Branch preservation
@Test func editingLinearPedalPreservesStereoSplitRegion() throws {
@@ -0,0 +1,113 @@
// MIDIControllerCCTests.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("MIDIController CC")
struct MIDIControllerCCTests {
/// Builds an engine + a one-board rig whose first pedal is a Volume pedal, plus a controller.
private func makeRig() throws -> (MIDIController, ShoeGaze, Pedal, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 128)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
// Add the pedal directly (not via appendPedal, which rebuilds and replaces the board and
// would leave this `board` reference stale).
try board.add(VolumePedal())
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
return (controller, sg, board.pedals[0], url)
}
@Test func learnCapturesBindingAndFiresCallback() throws {
let (controller, sg, pedal, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
var mapChanged: Bool = false
controller.onMapChanged = { mapChanged = true }
// Position is knob 0 on a Volume pedal.
controller.armCCLearn(boardIndex: 0, pedalIndex: 0, knobIndex: 0)
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64))
#expect(controller.learnTarget == nil, "learn should clear after capture")
#expect(mapChanged, "onMapChanged should fire on capture")
let binding: MIDIMap.CCBinding? = controller.ccBinding(boardIndex: 0, pedalIndex: 0, knobIndex: 0)
#expect(binding?.controller == 20)
#expect(binding?.target.pedalNameHint == "Volume")
#expect(binding?.target.knobLabelHint == "Position")
#expect(sg.midiMap?.ccs.count == 1)
_ = pedal
}
@Test func boundCCDrivesKnobAcrossItsRange() throws {
// `sg` must be retained: MIDIController holds it weakly, so binding it to `_` would let the
// rig deallocate and every message no-op.
let (controller, sg, pedal, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
controller.armCCLearn(boardIndex: 0, pedalIndex: 0, knobIndex: 0)
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
let node: UIParamNode = pedal.knobs[0].node // Position, range 0...1
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127))
#expect(abs(node.value - 1.0) < 1e-9, "CC 127 should map to the knob max")
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64))
#expect(abs(node.value - 64.0 / 127.0) < 1e-9, "CC 64 should map mid-range")
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
#expect(abs(node.value - 0.0) < 1e-9, "CC 0 should map to the knob min")
}
}
@Test func unboundCCIsIgnored() throws {
let (controller, sg, pedal, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
let node: UIParamNode = pedal.knobs[0].node
let before: Double = node.value
// No binding learned → an incoming CC must not touch anything.
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127))
#expect(node.value == before)
}
}
@Test func channelFilterBlocksOtherChannels() throws {
let (controller, sg, pedal, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
// Learn on channel 0 (the binding captures that channel).
controller.armCCLearn(boardIndex: 0, pedalIndex: 0, knobIndex: 0)
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
let node: UIParamNode = pedal.knobs[0].node
node.update(0.5)
// A CC on a different channel must not drive the channel-0 binding.
controller.ingestForTesting(.controlChange(channel: 5, controller: 20, value: 127))
#expect(abs(node.value - 0.5) < 1e-9, "CC on a non-matching channel should be ignored")
}
}
@Test func clearRemovesBinding() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, Pedal, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
controller.armCCLearn(boardIndex: 0, pedalIndex: 0, knobIndex: 0)
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
#expect(sg.midiMap?.ccs.isEmpty == false)
controller.clearCCBinding(boardIndex: 0, pedalIndex: 0, knobIndex: 0)
#expect(controller.ccBinding(boardIndex: 0, pedalIndex: 0, knobIndex: 0) == nil)
#expect(sg.midiMap?.ccs.isEmpty == true)
}
}
@@ -0,0 +1,151 @@
// MIDIControllerPCTests.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("MIDIController Program Change")
struct MIDIControllerPCTests {
/// Builds an engine + a rig of `boardCount` boards (each with one Volume pedal) + a controller.
private func makeRig(boardCount: Int = 1) throws -> (MIDIController, ShoeGaze, [PedalBoard], URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
var boards: [PedalBoard] = []
for index: Int in 0 ..< boardCount {
let board: PedalBoard = try sg.addBoard()
board.label = "Board \(index + 1)"
try board.add(VolumePedal())
try sg.finalizeBoard(board)
boards.append(board)
}
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
return (controller, sg, boards, url)
}
@Test func learnCapturesSwitchAndFiresCallback() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
var changed: Bool = false
controller.onMapChanged = { changed = true }
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 7))
#expect(controller.learnTarget == nil)
#expect(changed)
#expect(controller.switchBinding(for: .rigBypass)?.program == 7)
#expect(sg.midiMap?.switches.count == 1)
}
}
@Test func rigBypassLatchesOnEachPress() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 1)) // learn only
#expect(sg.rigBypassed == false, "learn must not toggle")
controller.ingestForTesting(.programChange(channel: 0, program: 1))
#expect(sg.rigBypassed == true, "first press engages")
controller.ingestForTesting(.programChange(channel: 0, program: 1))
#expect(sg.rigBypassed == false, "second press releases")
}
}
@Test func pedalBypassLatches() throws {
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
let node: UIParamNode = boards[0].pedals[0].$bypass
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 0))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
#expect(node.value == 0.0)
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(abs(node.value - 1.0) < 1e-9, "first press bypasses")
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(abs(node.value - 0.0) < 1e-9, "second press re-engages")
}
}
@Test func boardBypassLatches() throws {
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
controller.armSwitchLearn(.boardBypass(boardIndex: 0))
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 3))
#expect(sg.isBoardBypassed(boards[0]) == true)
controller.ingestForTesting(.programChange(channel: 0, program: 3))
#expect(sg.isBoardBypassed(boards[0]) == false)
}
}
@Test func boardSoloIsExclusiveRadio() throws {
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) =
try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
controller.armSwitchLearn(.boardSolo(boardIndex: 1))
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // solo board 2
#expect(sg.activeBoardIndex == 1)
#expect(sg.isBoardAudible(boards[1]) == true)
#expect(sg.isBoardAudible(boards[0]) == false)
}
}
@Test func channelFilterBlocksOtherChannels() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 1)) // learn on ch 0
controller.ingestForTesting(.programChange(channel: 4, program: 1)) // other channel
#expect(sg.rigBypassed == false, "PC on a non-matching channel should be ignored")
}
}
@Test func staleOutOfRangeBindingIsIgnored() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
// Bind to a pedal index that doesn't exist; applying it must be a safe no-op.
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 9))
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // apply — no crash
#expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 9)) != nil)
}
}
@Test func reassigningProgramStealsFromPriorAction() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
try withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 8))
controller.armSwitchLearn(.boardBypass(boardIndex: 0))
controller.ingestForTesting(.programChange(channel: 0, program: 8)) // same PC steals it
#expect(controller.switchBinding(for: .rigBypass) == nil, "prior action loses the PC")
#expect(controller.switchBinding(for: .boardBypass(boardIndex: 0))?.program == 8)
#expect(sg.midiMap?.switches.count == 1)
}
}
}
@@ -0,0 +1,55 @@
// MIDIMapCodableTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@MainActor
@Suite("MIDIMap persistence")
struct MIDIMapCodableTests {
private func sampleMap() -> MIDIMap {
MIDIMap(
switches: [
MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"),
MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardIndex: 1), displayNameHint: "Board 2"),
],
ccs: [
MIDIMap.CCBinding(
controller: 7,
channel: 0,
target: MIDIMap.CCTarget(
boardIndex: 0, pedalIndex: 1, knobIndex: 0,
pedalNameHint: "Volume", knobLabelHint: "Position"
)
),
]
)
}
@Test func mapRoundTrips() throws {
let map: MIDIMap = sampleMap()
let data: Data = try JSONEncoder().encode(map)
let decoded: MIDIMap = try JSONDecoder().decode(MIDIMap.self, from: data)
#expect(decoded == map)
}
@Test func rigStateEmbedsAndRestoresMap() throws {
let state: ShoeGazeState = ShoeGazeState(boards: [], midiMap: sampleMap())
let data: Data = try JSONEncoder().encode(state)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.midiMap == sampleMap())
}
@Test func oldRigWithoutMapDecodesToNil() throws {
// A rig saved before MIDI mapping existed has no `midiMap` key at all.
let legacyJSON: String = #"{"version":1,"boards":[]}"#
let data: Data = Data(legacyJSON.utf8)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.midiMap == nil, "legacy rig JSON should decode with a nil midiMap")
}
}
@@ -0,0 +1,73 @@
// VolumePedalTests.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("VolumePedal")
struct VolumePedalTests {
/// Renders a Volume pedal at the given position and returns the stereo output samples.
private func render(position: Double) throws -> [Float] {
let renderDuration: Double = 0.2
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
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: VolumePedal = VolumePedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.position = position
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 rms(_ samples: [Float]) -> Double {
guard !samples.isEmpty else { return 0 }
let sumSquares: Double = samples.reduce(0) { $0 + Double($1) * Double($1) }
return (sumSquares / Double(samples.count)).squareRoot()
}
@Test func buildsAndProducesNonSilentOutputAtUnity() throws {
let samples: [Float] = try render(position: 1.0)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "VolumePedal at unity produced silence")
}
@Test func zeroPositionIsSilent() throws {
let samples: [Float] = try render(position: 0.0)
#expect(!hasNonSilentOutput(samples), "VolumePedal at position 0 should be silent")
}
@Test func positionScalesLevelMonotonically() throws {
let full: Double = rms(try render(position: 1.0))
let half: Double = rms(try render(position: 0.5))
let quarter: Double = rms(try render(position: 0.25))
#expect(full > half, "position 1.0 should be louder than 0.5")
#expect(half > quarter, "position 0.5 should be louder than 0.25")
}
@Test func exposesPositionKnob() throws {
let pedal: VolumePedal = VolumePedal()
// Effect knob (before the common Mix/Level pair) is Position.
#expect(pedal.effectKnobs.map { $0.label } == ["Position"])
}
}
@@ -0,0 +1,80 @@
// WahPedalTests.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("WahPedal")
struct WahPedalTests {
/// Renders a Wah pedal at the given position / resonance and returns the stereo output.
private func render(position: Double, resonance: Double = 3.0) throws -> [Float] {
let renderDuration: Double = 0.2
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
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: WahPedal = WahPedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.position = position
pedal.resonance = resonance
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)
}
/// Mean absolute difference between two equal-length renders.
private func meanAbsDiff(_ a: [Float], _ b: [Float]) -> Double {
let count: Int = min(a.count, b.count)
guard count > 0 else { return 0 }
var sum: Double = 0
for i: Int in 0 ..< count {
sum += abs(Double(a[i]) - Double(b[i]))
}
return sum / Double(count)
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render(position: 0.5)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "WahPedal produced silence")
}
@Test func differentPositionsProduceDifferentOutput() throws {
let heel: [Float] = try render(position: 0.0)
let toe: [Float] = try render(position: 1.0)
// Sweeping the cutoff must audibly change the filtered signal.
let diff: Double = meanAbsDiff(heel, toe)
#expect(diff > 1e-4, "heel and toe positions produced near-identical output (diff \(diff))")
}
@Test func resonanceChangesOutput() throws {
let low: [Float] = try render(position: 0.5, resonance: 0.7)
let high: [Float] = try render(position: 0.5, resonance: 8.0)
let diff: Double = meanAbsDiff(low, high)
#expect(diff > 1e-4, "resonance change produced near-identical output (diff \(diff))")
}
@Test func exposesPositionAndResonanceKnobs() throws {
let pedal: WahPedal = WahPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Position", "Resonance"])
}
}