Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/PresetTests.swift
T
josh 3fe6b8a50a fix(cab): rebuild board on lightweight recall of a topology selector
Review follow-up to the single-convolver cab change. Now that only the selected
cabinet voice's convolver is built, any path that changes the selector value
without rebuilding leaves audio on the stale convolver. The UI drag already
rebuilds; the gap was ShoeGaze.applyState (lightweight scene recall), which
applies param snapshots to live pedals without a rebuild.

- Pedal.rebuildSelectorValues: values of effectSelectors flagged rebuildsOnChange.
- applyState/applySegmentParams/applyBranchParams: detect when a rebuildsOnChange
  selector value actually changes during recall and rebuild only those boards;
  boards without such a selector keep the cheap live-apply path.
- CabinetVoice.voice(atSelectorValue:): guard non-finite and clamp in Double
  space so Int() can never trap on a corrupt preset value.
- Doc fixes: CabinetPedal.cabinet and AmpVoicePedal chain diagram no longer claim
  a live Select.

MIDI CC is unaffected: selectors are not in ccMappableControls (knobs + sliders
only). Tests: recall changing the cab voice rebuilds and applies; recall with an
unchanged voice does not rebuild.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 20:27:39 -07:00

723 lines
31 KiB
Swift

// PresetTests.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("Preset save/load")
struct PresetTests {
// MARK: - Helpers
/// Builds a two-board test rig and returns the `ShoeGaze` manager plus its engine.
///
/// Board 1: Overdrive → Delay
/// Board 2: Reverb
///
/// - Returns: `(ShoeGaze, SynthesisEngine, URL)` where `URL` is the NRT output file
/// that must be deleted by the caller (via `defer`).
private func makeTwoBoardRig() throws -> (ShoeGaze, SynthesisEngine, URL) {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try sg.addBoard()
try board1.add(OverdrivePedal())
try board1.add(DelayPedal())
try sg.finalizeBoard(board1)
let board2: PedalBoard = try sg.addBoard()
try board2.add(ReverbPedal())
try sg.finalizeBoard(board2)
return (sg, engine, url)
}
// MARK: - Stereo pedal round-trip
@Test func wideningPedalRigRoundTripsThroughFile() throws {
// A linear rig containing a widener + a downstream mono pedal must round-trip:
// the registered widener replays the mono → stereo transition on load, and the
// downstream pedal auto-stereoizes.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let octave: OctaveUpSplitterPedal = OctaveUpSplitterPedal()
octave.drive = 22.0
try board.add(octave)
try board.add(DelayPedal())
try sg.finalizeBoard(board)
#expect(board.width == 2, "Rig should be stereo before saving")
try sg.saveRig(to: presetURL)
try sg.loadRig(from: presetURL)
// After reload: same topology + restored parameter.
guard let loadedBoard: PedalBoard = sg.boards.first else {
Issue.record("No board after loadRig")
return
}
#expect(loadedBoard.width == 2, "Widener should re-widen the board on load")
#expect(loadedBoard.pedals.count == 2, "Both pedals should be reconstructed")
guard let loadedOctave: OctaveUpSplitterPedal =
loadedBoard.pedals.first as? OctaveUpSplitterPedal else {
Issue.record("Octave Splitter not reconstructed (registry miss?)")
return
}
#expect(loadedOctave.$drive.value == 22.0, "Widener drive should be restored")
}
@Test func pingPongPedalIsRegistered() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Ping-Pong")
#expect(pedal is PingPongDelayPedal, "Ping-Pong should be registered")
}
// MARK: - Split-region topology round-trip
@Test func parallelTopologyRoundTripsThroughFile() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
let section: ParallelSection = try board.split()
try section.branchA.add(DelayPedal())
try section.branchB.add(FuzzPedal())
try board.merge(section)
try board.add(ReverbPedal())
try sg.finalizeBoard(board)
// Non-default routing + branch param so the round-trip proves real capture.
section.splitter.mode = .a
if let delay: DelayPedal = section.branchA.pedals.first as? DelayPedal {
delay.time = 0.6
}
let before: ShoeGazeState = sg.captureState()
try sg.saveRig(to: preset)
try sg.loadRig(from: preset)
let after: ShoeGazeState = sg.captureState()
#expect(before == after, "Parallel topology should round-trip through a file")
let hasParallel: Bool = after.boards[0].segments.contains {
if case .parallel = $0 { return true } else { return false }
}
#expect(hasParallel, "Reconstructed board should contain a parallel segment")
}
@Test func stereoSplitTopologyRoundTripsThroughFile() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
let section: StereoSplitSection = try board.splitStereo()
try section.left.add(DelayPedal())
try section.right.add(PingPongDelayPedal())
try board.collectStereo(section)
try sg.finalizeBoard(board)
section.route = .rightOnly
if let delay: DelayPedal = section.left.pedals.first as? DelayPedal {
delay.time = 0.45
}
let before: ShoeGazeState = sg.captureState()
try sg.saveRig(to: preset)
try sg.loadRig(from: preset)
let after: ShoeGazeState = sg.captureState()
#expect(before == after, "Stereo split topology should round-trip through a file")
#expect(sg.boards[0].width == 2, "Reconstructed board should be stereo")
let hasStereo: Bool = after.boards[0].segments.contains {
if case .stereoSplit = $0 { return true } else { return false }
}
#expect(hasStereo, "Reconstructed board should contain a stereo split segment")
// Route survived.
guard case .stereoSplit(let stereoState)? =
after.boards[0].segments.first(where: {
if case .stereoSplit = $0 { return true } else { return false }
}) else {
Issue.record("No stereo split segment after reload")
return
}
#expect(stereoState.route == .rightOnly, "Route should be restored")
}
@Test func mergeToMonoTopologyRoundTripsThroughFile() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(OctaveUpSplitterPedal()) // widen → stereo
try board.mergeToMono() // collapse → mono
try board.add(ReverbPedal()) // mono pedal after merge
try sg.finalizeBoard(board)
#expect(board.width == 1, "Board should be mono after merge")
let before: ShoeGazeState = sg.captureState()
try sg.saveRig(to: preset)
try sg.loadRig(from: preset)
let after: ShoeGazeState = sg.captureState()
#expect(before == after, "Widen→merge→mono topology should round-trip")
#expect(sg.boards[0].width == 1, "Rebuilt board should be mono (merge replayed)")
let hasMerge: Bool = after.boards[0].segments.contains {
if case .mergeToMono = $0 { return true } else { return false }
}
#expect(hasMerge, "Reconstructed board should contain a mergeToMono segment")
}
@Test func legacyFlatPedalsPresetStillDecodes() throws {
// A board snapshot written before topology capture stored a flat `pedals` array and
// no `segments` key. It must still decode, wrapping each pedal as a `.pedal` segment.
let legacyJSON: String = """
{"label":"Legacy","pedals":[\
{"type":"Overdrive","knobValues":[0.5,1.0,1.0],"switchValues":[],"bypass":0.0},\
{"type":"Delay","knobValues":[0.25,1.0,0.35,1.0],"switchValues":[],"bypass":0.0}]}
"""
let decoded: BoardState = try JSONDecoder().decode(
BoardState.self,
from: Data(legacyJSON.utf8)
)
#expect(decoded.label == "Legacy")
#expect(decoded.segments.count == 2, "Legacy pedals should become two segments")
#expect(decoded.pedals.count == 2, "Linear pedal view should expose both")
#expect(decoded.pedals[0].type == "Overdrive")
#expect(decoded.pedals[1].type == "Delay")
}
@Test func unknownPedalInBranchIsSkippedOnLoad() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
// Parallel segment with an unknown pedal in branch A and a known one in branch B.
let parallel: ParallelSectionState = ParallelSectionState(
branchA: [PedalState(type: "GhostPedal", knobValues: [], bypass: 0.0)],
branchB: [PedalState(type: "Fuzz", knobValues: [20.0, 1.0, 1.0], bypass: 0.0)],
mode: .both
)
let boardState: BoardState = BoardState(label: "B", segments: [.parallel(parallel)])
let state: ShoeGazeState = ShoeGazeState(boards: [boardState])
try JSONEncoder().encode(state).write(to: preset)
let sg: ShoeGaze = ShoeGaze(engine: engine)
try sg.loadRig(from: preset)
let after: ShoeGazeState = sg.captureState()
guard case .parallel(let rebuilt)? = after.boards.first?.segments.first(where: {
if case .parallel = $0 { return true } else { return false }
}) else {
Issue.record("No parallel segment after load")
return
}
#expect(rebuilt.branchA.isEmpty, "Unknown branch-A pedal should be skipped")
#expect(rebuilt.branchB.count == 1, "Known branch-B pedal should rebuild")
#expect(rebuilt.branchB.first?.type == "Fuzz")
}
@Test func applyStateRecallsBranchParamsAndRoute() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let section: StereoSplitSection = try board.splitStereo()
try section.left.add(DelayPedal())
try section.right.add(FuzzPedal())
try board.collectStereo(section)
try sg.finalizeBoard(board)
let defaultTime: Double = 0.25 // DelayPedal default
let baseline: ShoeGazeState = sg.captureState()
// Mutate a branch pedal param and the route, then recall the baseline.
guard let delay: DelayPedal = section.left.pedals.first as? DelayPedal else {
Issue.record("No DelayPedal in left branch")
return
}
delay.time = 0.9
section.route = .bypass
sg.applyState(baseline)
#expect(abs(delay.$time.value - defaultTime) < 1e-9, "Branch pedal param should be recalled")
#expect(section.route == .stereo, "Route should be recalled")
}
@Test func applyStateRebuildsBoardWhenCabinetVoiceChanges() throws {
// A cabinet voice is a `rebuildsOnChange` selector: only the selected voice's convolver is
// built, so a lightweight recall that changes it must rebuild the board (a plain node write
// would leave audio on the previously-built convolver).
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(CabinetPedal())
try sg.finalizeBoard(board)
guard let original: CabinetPedal = board.pedals.first as? CabinetPedal else {
Issue.record("No CabinetPedal in board")
return
}
// Snapshot at voice 3, then move the live pedal to voice 0 and recall the snapshot.
original.cabinet = 3.0
let snapshot: ShoeGazeState = sg.captureState()
original.cabinet = 0.0
sg.applyState(snapshot)
// The rebuild replaces the instance — the recalled voice must be reflected on the new one.
guard let rebuilt: CabinetPedal = sg.boards[0].pedals.first as? CabinetPedal else {
Issue.record("No CabinetPedal after recall")
return
}
#expect(rebuilt !== original, "board should rebuild when the cabinet voice changes")
#expect(rebuilt.cabinet == 3.0, "recalled cabinet voice should be applied")
}
@Test func applyStateDoesNotRebuildWhenCabinetVoiceUnchanged() throws {
// Recall with the same cabinet voice must NOT rebuild — the lightweight path stays cheap.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(CabinetPedal())
try sg.finalizeBoard(board)
guard let original: CabinetPedal = board.pedals.first as? CabinetPedal else {
Issue.record("No CabinetPedal in board")
return
}
original.cabinet = 2.0
let snapshot: ShoeGazeState = sg.captureState()
sg.applyState(snapshot)
#expect(sg.boards[0].pedals.first === original, "unchanged cabinet voice should not rebuild")
}
// MARK: - In-memory round-trip
@Test func captureStateRoundTripEquality() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
// Tweak some parameters on board 1 pedals.
guard let overdrive: OverdrivePedal = sg.boards[0].pedals[0] as? OverdrivePedal else {
Issue.record("Expected OverdrivePedal at board 0 pedal 0")
return
}
overdrive.drive = 12.0
overdrive.bypass = 1.0
guard let delay: DelayPedal = sg.boards[0].pedals[1] as? DelayPedal else {
Issue.record("Expected DelayPedal at board 0 pedal 1")
return
}
delay.time = 0.75
delay.feedback = 3.0
// Capture once, JSON encode → decode, compare to a second capture.
let captured: ShoeGazeState = sg.captureState()
let encoder: JSONEncoder = JSONEncoder()
let data: Data = try encoder.encode(captured)
let decoder: JSONDecoder = JSONDecoder()
let decoded: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
#expect(decoded == captured, "Decoded ShoeGazeState must equal original")
#expect(decoded.version == presetFormatVersion)
#expect(decoded.boards.count == 2)
#expect(decoded.boards[0].pedals.count == 2)
#expect(decoded.boards[0].pedals[0].type == "Overdrive")
#expect(decoded.boards[0].pedals[0].bypass == 1.0)
// Verify the overdrive drive value made it through.
// drive is the first effectKnob (index 0 in knobValues).
let driveValue: Double = decoded.boards[0].pedals[0].knobValues[0]
#expect(abs(driveValue - 12.0) < 1e-9, "drive knob value should be 12.0, got \(driveValue)")
}
// MARK: - Tempo & input persistence
@Test func tempoAndInputSettingsRoundTripThroughFile() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
// Save a distinctive tempo + disabled tempo features (input stays on the test loop).
let savedBpm: Double = 132.0
sg.clock.bpm = savedBpm
sg.setTempoEnabled(false)
try sg.saveRig(to: presetURL)
// Drift the live values away from what was saved, then confirm the reload restores them.
sg.clock.bpm = 90.0
sg.setTempoEnabled(true)
try sg.loadRig(from: presetURL)
#expect(abs(sg.clock.bpm - savedBpm) < 1e-9, "bpm should restore to \(savedBpm)")
#expect(sg.tempoEnabled == false, "tempoEnabled should restore to false")
#expect(sg.inputSource == .testLoop, "input source should restore to test loop")
}
@Test func liveInputSourcePersistsAndFallsBackWhenChannelMissing() throws {
// Engine WITH an input channel: a live-input rig round-trips its source.
let (engineIn, urlIn): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numInputChannels: 1,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlIn) }
let sgIn: ShoeGaze = ShoeGaze(engine: engineIn, inputSource: .liveInput(channel: 0))
let board: PedalBoard = try sgIn.addBoard()
try board.add(OverdrivePedal())
try sgIn.finalizeBoard(board)
let state: ShoeGazeState = sgIn.captureState()
#expect(state.inputSource == .liveInput(channel: 0), "capture should record the live input")
// Reload into the same input-capable engine: source preserved.
try sgIn.loadRig(from: state)
#expect(sgIn.inputSource == .liveInput(channel: 0), "live input should round-trip")
// loadRig does NOT auto-apply the saved channel layout, so loading into an engine with no
// input channels falls back to the test loop rather than clobbering the engine's config.
let (engineNoIn, urlNoIn): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numInputChannels: 0,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlNoIn) }
let sgNoIn: ShoeGaze = ShoeGaze(engine: engineNoIn)
try sgNoIn.loadRig(from: state)
#expect(engineNoIn.numInputChannels == 0, "loadRig must not reconfigure the engine's I/O")
#expect(sgNoIn.inputSource == .testLoop, "missing channel should fall back to test loop")
}
@Test func channelCountsPersistButLoadDoesNotReconfigure() throws {
// Capture a rig on an engine with 1 input / 2 output channels: the counts are recorded and
// survive a JSON round-trip.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: 2,
numInputChannels: 1,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlA) }
let sgA: ShoeGaze = ShoeGaze(engine: engineA)
let boardA: PedalBoard = try sgA.addBoard()
try boardA.add(OverdrivePedal())
try sgA.finalizeBoard(boardA)
let state: ShoeGazeState = sgA.captureState()
#expect(state.numInputChannels == 1)
#expect(state.numOutputChannels == 2)
let decoded: ShoeGazeState = try JSONDecoder().decode(
ShoeGazeState.self, from: JSONEncoder().encode(state)
)
#expect(decoded.numInputChannels == 1)
#expect(decoded.numOutputChannels == 2)
// Loading the rig must NOT reconfigure the destination engine's channel layout.
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlB) }
let sgB: ShoeGaze = ShoeGaze(engine: engineB)
try sgB.loadRig(from: state)
#expect(engineB.numInputChannels == 0, "loadRig must leave engine I/O untouched")
}
@Test func applyChannelLayoutReconfiguresEngineToSavedCounts() throws {
// The deliberate opt-in DOES reconfigure the engine to a rig's saved channel layout.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: 2,
numInputChannels: 1,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlA) }
let sgA: ShoeGaze = ShoeGaze(engine: engineA)
let boardA: PedalBoard = try sgA.addBoard()
try boardA.add(OverdrivePedal())
try sgA.finalizeBoard(boardA)
let state: ShoeGazeState = sgA.captureState()
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlB) }
let sgB: ShoeGaze = ShoeGaze(engine: engineB)
try sgB.loadRig(from: state)
#expect(engineB.numInputChannels == 0, "load alone leaves I/O untouched")
let changed: Bool = try sgB.applyChannelLayout(from: state)
#expect(changed, "applyChannelLayout should report a change")
#expect(engineB.numInputChannels == 1, "opt-in apply reconfigures to the saved input count")
#expect(engineB.numOutputChannels == 2)
// Idempotent: applying again with matching counts is a no-op.
let changedAgain: Bool = try sgB.applyChannelLayout(from: state)
#expect(!changedAgain, "no reconfigure when counts already match")
}
// MARK: - Save / Load via temp file
@Test func saveRigAndLoadRigRestoresKnobValues() throws {
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let overdrive: OverdrivePedal = OverdrivePedal()
try board.add(overdrive)
try sg.finalizeBoard(board)
// Set a known knob value.
let knownDriveValue: Double = 17.5
overdrive.drive = knownDriveValue
// Save to a temp file.
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
try sg.saveRig(to: presetURL)
// Mutate the live knob.
overdrive.drive = 1.0
#expect(abs(overdrive.drive - 1.0) < 1e-9)
// Load the preset — this rebuilds the entire graph.
try sg.loadRig(from: presetURL)
// After load there should be one board with one overdrive pedal.
#expect(sg.boards.count == 1, "Expected 1 board after loadRig")
#expect(sg.boards[0].pedals.count == 1, "Expected 1 pedal after loadRig")
guard let restoredPedal: OverdrivePedal = sg.boards[0].pedals[0] as? OverdrivePedal else {
Issue.record("Expected OverdrivePedal after loadRig")
return
}
// drive is the first effectKnob → knobValues[0] was applied via applyState.
#expect(
abs(restoredPedal.drive - knownDriveValue) < 1e-9,
"drive should be \(knownDriveValue) after loadRig, got \(restoredPedal.drive)"
)
}
@Test func savedFileContainsValidJSON() throws {
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(FuzzPedal())
try sg.finalizeBoard(board)
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
try sg.saveRig(to: presetURL)
// Verify the file is non-empty and parses as JSON.
let data: Data = try Data(contentsOf: presetURL)
#expect(!data.isEmpty, "Preset file should not be empty")
let json: Any = try JSONSerialization.jsonObject(with: data)
#expect(json is [String: Any], "Root JSON object should be a dictionary")
}
// MARK: - applyState lightweight recall
@Test func applyStateRecallsKnobValuesWithoutRebuild() throws {
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let compressor: CompressorPedal = CompressorPedal()
try board.add(compressor)
try sg.finalizeBoard(board)
// Set a known threshold.
let knownThreshold: Double = -20.0
compressor.threshold = knownThreshold
// Capture the state at this point.
let captured: ShoeGazeState = sg.captureState()
// Mutate the threshold.
compressor.threshold = -5.0
#expect(abs(compressor.threshold - (-5.0)) < 1e-9)
// Apply the captured state (lightweight recall — no graph rebuild).
sg.applyState(captured)
// applyState calls knob.node.update(value) on each knob; the Threshold knob's
// UIParamNode.value should now reflect the restored value. Look up by label rather
// than position so the test is robust to knob additions.
let thresholdKnobValue: Double = try #require(
compressor.knobs.first(where: { $0.label == "Threshold" })?.node.value
)
#expect(
abs(thresholdKnobValue - knownThreshold) < 1e-9,
"threshold knob should be \(knownThreshold) after applyState, got \(thresholdKnobValue)"
)
}
// MARK: - PedalRegistry
@Test func registryReturnsCorrectPedalTypes() {
let overdrive: Pedal? = PedalRegistry.makePedal(type: "Overdrive")
let delay: Pedal? = PedalRegistry.makePedal(type: "Delay")
let reverb: Pedal? = PedalRegistry.makePedal(type: "Reverb")
let modulation: Pedal? = PedalRegistry.makePedal(type: "Modulation")
let fuzz: Pedal? = PedalRegistry.makePedal(type: "Fuzz")
let tremolo: Pedal? = PedalRegistry.makePedal(type: "Tremolo")
let phaser: Pedal? = PedalRegistry.makePedal(type: "Phaser")
let compressor: Pedal? = PedalRegistry.makePedal(type: "Compressor")
let unknown: Pedal? = PedalRegistry.makePedal(type: "UnknownPedal")
#expect(overdrive is OverdrivePedal, "Overdrive should produce OverdrivePedal")
#expect(delay is DelayPedal, "Delay should produce DelayPedal")
#expect(reverb is ReverbPedal, "Reverb should produce ReverbPedal")
#expect(modulation is ModulationPedal, "Modulation should produce ModulationPedal")
#expect(fuzz is FuzzPedal, "Fuzz should produce FuzzPedal")
#expect(tremolo is TremoloPedal, "Tremolo should produce TremoloPedal")
#expect(phaser is PhaserPedal, "Phaser should produce PhaserPedal")
#expect(compressor is CompressorPedal, "Compressor should produce CompressorPedal")
#expect(unknown == nil, "Unknown type should return nil")
}
// MARK: - Version guard
@Test func loadRigThrowsOnUnsupportedVersion() throws {
// Craft a state whose version is one ahead of the current format.
let futureVersion: Int = presetFormatVersion + 1
let state: ShoeGazeState = ShoeGazeState(version: futureVersion, boards: [])
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
let encoder: JSONEncoder = JSONEncoder()
let data: Data = try encoder.encode(state)
try data.write(to: presetURL, options: .atomic)
do {
try sg.loadRig(from: presetURL)
Issue.record("Expected PresetError.unsupportedVersion to be thrown")
} catch let error as PresetError {
#expect(
error == .unsupportedVersion(futureVersion),
"Expected .unsupportedVersion(\(futureVersion)), got \(error)"
)
}
}
@Test func loadRigSkipsUnknownPedalTypes() throws {
// Craft a ShoeGazeState that contains an unknown pedal type between two known ones.
let state: ShoeGazeState = ShoeGazeState(boards: [
BoardState(
label: "Test Board",
pedals: [
PedalState(type: "Overdrive", knobValues: [4.0, 4000.0, 1.0, 1.0], bypass: 0.0),
PedalState(type: "GhostPedal", knobValues: [], bypass: 0.0),
PedalState(type: "Fuzz", knobValues: [0.05, 3500.0, 1.0, 1.0], bypass: 0.0),
]
)
])
let renderDuration: Double = 0.1
let (engine, audioURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: audioURL) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let presetURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: presetURL) }
// Encode the crafted state to disk and load it.
let encoder: JSONEncoder = JSONEncoder()
let data: Data = try encoder.encode(state)
try data.write(to: presetURL, options: .atomic)
try sg.loadRig(from: presetURL)
// The unknown "GhostPedal" should be skipped; only Overdrive and Fuzz load.
#expect(sg.boards.count == 1, "Expected 1 board after loadRig")
#expect(sg.boards[0].pedals.count == 2, "Expected 2 pedals (unknown type skipped)")
#expect(sg.boards[0].pedals[0].displayName == "Overdrive")
#expect(sg.boards[0].pedals[1].displayName == "Fuzz")
}
}