Files
ShoeGaze/Tests/LyrebirdShoeGazeTests/PresetTests.swift
T
josh 5a07a6d4b4 Add input gain stage to Compressor pedal
A pre-compression input gain knob (Input, dB, range [-12, +24], default 0)
boosts/cuts the signal before it hits the compressor, so driving the input
harder pushes more of the signal past the threshold. The dB value is converted
to a linear multiplier via Exp(dB * ln(10)/20) and applied to the dry signal.

Tests: knob list is [Input, Threshold, Ratio]; input gain changes the output.
The preset recall test now finds the Threshold knob by label, not position.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 12:32:32 -07:00

537 lines
23 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")
}
// 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: - 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")
}
}