1.0 release

This commit is contained in:
2026-06-21 12:25:18 -07:00
parent b7973cba9a
commit 6f55615d7b
81 changed files with 10968 additions and 0 deletions
@@ -0,0 +1,100 @@
// BoardSelectionTests.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("Board selection / crossfade")
struct BoardSelectionTests {
@Test func selectBoardSetsSelectGainsAndCrossfadeTime() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
// Default: both boards audible (select gain 1), no solo.
#expect(board1.selectGainNode?.value == 1.0)
#expect(board2.selectGainNode?.value == 1.0)
#expect(shoeGaze.activeBoardIndex == nil)
// Solo board 2 with a half-second crossfade.
let crossfadeSeconds: Double = 0.5
shoeGaze.selectBoard(board2, crossfadeSeconds: crossfadeSeconds)
#expect(board1.selectGainNode?.value == 0.0, "non-selected board fades out")
#expect(board2.selectGainNode?.value == 1.0, "selected board fades in")
#expect(board1.crossfadeTimeNode?.value == crossfadeSeconds)
#expect(board2.crossfadeTimeNode?.value == crossfadeSeconds)
#expect(shoeGaze.activeBoardIndex == 1)
// Back to all audible.
shoeGaze.selectAllBoards(crossfadeSeconds: crossfadeSeconds)
#expect(board1.selectGainNode?.value == 1.0)
#expect(board2.selectGainNode?.value == 1.0)
#expect(shoeGaze.activeBoardIndex == nil)
}
@Test func boardAddedWhileSoloedComesUpSilent() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
// Solo board 1.
shoeGaze.selectBoard(board1, crossfadeSeconds: 0.0)
// A board finalized while a solo is active must come up silent.
let board2: PedalBoard = try shoeGaze.addBoard()
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
#expect(board2.selectGainNode?.value == 0.0, "board added mid-solo must be muted")
#expect(board1.selectGainNode?.value == 1.0, "soloed board stays audible")
}
@Test func soloedBoardRendersNonSilent() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.2,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
// Instant crossfade so the soloed board is full level immediately.
shoeGaze.selectBoard(board1, crossfadeSeconds: 0.0)
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "soloed board should still produce audio")
}
}
@@ -0,0 +1,444 @@
// BoardVersionTests.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("BoardVersion — save/load and rebuild")
struct BoardVersionTests {
// MARK: - Helpers
/// Creates a two-board test rig.
///
/// Board 0 (index 0): Overdrive → Delay
/// Board 1 (index 1): Reverb
///
/// - Returns: `(ShoeGaze, SynthesisEngine, URL)` where `URL` is the NRT audio 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 board0: PedalBoard = try sg.addBoard()
try board0.add(OverdrivePedal())
try board0.add(DelayPedal())
try sg.finalizeBoard(board0)
let board1: PedalBoard = try sg.addBoard()
try board1.add(ReverbPedal())
try sg.finalizeBoard(board1)
return (sg, engine, url)
}
// MARK: - PedalBoard.captureState
@Test func captureStateReflectsCurrentPedalTypesAndLabel() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
let state: BoardState = sg.boards[0].captureState()
#expect(state.label == "Board 1", "Label should be 'Board 1'")
#expect(state.pedals.count == 2, "Board 0 should have 2 pedals")
#expect(state.pedals[0].type == "Overdrive")
#expect(state.pedals[1].type == "Delay")
}
@Test func captureStateReflectsCurrentKnobValues() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
guard let overdrive: OverdrivePedal = sg.boards[0].pedals[0] as? OverdrivePedal else {
Issue.record("Expected OverdrivePedal at index 0")
return
}
let knownDrive: Double = 18.5
overdrive.drive = knownDrive
let state: BoardState = sg.boards[0].captureState()
// drive is effectKnobs[0] → knobValues[0]
let capturedDrive: Double = state.pedals[0].knobValues[0]
#expect(abs(capturedDrive - knownDrive) < 1e-9,
"Captured drive should be \(knownDrive), got \(capturedDrive)")
}
// MARK: - rebuildBoard(_:from:)
@Test func rebuildBoardReplacesPedalsFromState() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
let board0: PedalBoard = sg.boards[0]
// Build a state that has only a Reverb pedal.
let newState: BoardState = BoardState(
label: "Rebuilt Board",
pedals: [
PedalState(type: "Reverb", knobValues: [2.5, 0.3, 1.0, 0.9], bypass: 0.0),
]
)
let rebuilt: PedalBoard = try sg.rebuildBoard(board0, from: newState)
#expect(rebuilt.pedals.count == 1, "Rebuilt board should have 1 pedal")
#expect(rebuilt.pedals[0].displayName == "Reverb",
"Rebuilt board's only pedal should be Reverb")
#expect(rebuilt.label == "Rebuilt Board")
}
@Test func rebuildBoardPreservesIndexInBoards() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
// board0 is at index 0; board1 is at index 1.
let board0: PedalBoard = sg.boards[0]
let newState: BoardState = BoardState(
label: "Replaced Board 1",
pedals: [
PedalState(type: "Fuzz", knobValues: [0.05, 3500.0, 1.0, 1.0], bypass: 0.0),
]
)
let rebuilt: PedalBoard = try sg.rebuildBoard(board0, from: newState)
// After rebuild, boards should still have 2 entries.
#expect(sg.boards.count == 2, "boards count should remain 2")
// The rebuilt board must occupy index 0.
#expect(sg.boards[0] === rebuilt, "Rebuilt board should be at index 0")
}
@Test func rebuildBoardSkipsUnknownPedalTypes() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
let board0: PedalBoard = sg.boards[0]
let newState: BoardState = BoardState(
label: "Mixed 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 rebuilt: PedalBoard = try sg.rebuildBoard(board0, from: newState)
// "GhostPedal" is unknown and must be skipped; only Overdrive and Fuzz should load.
#expect(rebuilt.pedals.count == 2, "Unknown pedal type should be skipped")
#expect(rebuilt.pedals[0].displayName == "Overdrive")
#expect(rebuilt.pedals[1].displayName == "Fuzz")
}
@Test func rebuildBoardRendersNonSilentAfterEngineStart() throws {
let renderDuration: Double = 0.2
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(OverdrivePedal())
try sg.finalizeBoard(board)
let newState: BoardState = BoardState(
label: "After Rebuild",
pedals: [
PedalState(type: "Reverb", knobValues: [2.5, 0.3, 1.0, 0.9], bypass: 0.0),
]
)
// Rebuild before engine.start() — the canonical "engine stopped" path.
let rebuilt: PedalBoard = try sg.rebuildBoard(board, from: newState)
#expect(sg.boards.count == 1)
#expect(sg.boards[0] === rebuilt)
try engine.start()
defer { engine.stop() }
// The test loop source feeds signal; the reverb+master chain should produce output.
let samples: [Float] = readStereoCAF(url: audioURL, sampleRate: engine.sampleRate)
#expect(hasNonSilentOutput(samples), "Rebuilt board should produce non-silent output")
}
// MARK: - BoardVersionStore.capture / disk round-trip
@Test func versionStoreRoundTrip() throws {
let (sg, _, audioURL): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: audioURL) }
let store: BoardVersionStore = BoardVersionStore()
store.capture(sg.boards[0], name: "Test Capture")
#expect(store.versions.count == 1)
let tempDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString, isDirectory: true)
defer { try? FileManager.default.removeItem(atPath: tempDir.path) }
try store.writeAllToDisk(in: tempDir)
// Load into a fresh store.
let freshStore: BoardVersionStore = BoardVersionStore()
try freshStore.loadAllFromDisk(in: tempDir)
#expect(freshStore.versions.count == 1, "Fresh store should contain one version")
let original: BoardVersion = store.versions[0]
let loaded: BoardVersion = try #require(freshStore.versions.first)
#expect(loaded == original, "Loaded version should equal the saved version")
}
@Test func versionStoreRoundTripPreservesMultipleVersions() throws {
let (sg, _, audioURL): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: audioURL) }
let store: BoardVersionStore = BoardVersionStore()
store.capture(sg.boards[0], name: "Version A")
store.capture(sg.boards[1], name: "Version B")
#expect(store.versions.count == 2)
let tempDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString, isDirectory: true)
defer { try? FileManager.default.removeItem(atPath: tempDir.path) }
try store.writeAllToDisk(in: tempDir)
let freshStore: BoardVersionStore = BoardVersionStore()
try freshStore.loadAllFromDisk(in: tempDir)
#expect(freshStore.versions.count == 2, "Should load both versions")
// Loaded versions are sorted by savedAt; original store insertion order may differ.
// Compare by id membership rather than order.
let originalIDs: Set<UUID> = Set(store.versions.map { $0.id })
let loadedIDs: Set<UUID> = Set(freshStore.versions.map { $0.id })
#expect(originalIDs == loadedIDs, "All version IDs should survive round-trip")
}
// MARK: - Knob value restoration via rebuildBoard
@Test func rebuildBoardRestoresKnobValues() 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 drive value.
let knownDrive: Double = 15.0
overdrive.drive = knownDrive
// Capture the state at this point via BoardVersionStore.
let store: BoardVersionStore = BoardVersionStore()
store.capture(board, name: "Known Drive State")
let version: BoardVersion = try #require(store.versions.first)
// Mutate the knob value.
overdrive.drive = 1.0
#expect(abs(overdrive.drive - 1.0) < 1e-9)
// Rebuild from the saved version state.
let rebuilt: PedalBoard = try sg.rebuildBoard(sg.boards[0], from: version.state)
guard let restoredOverdrive: OverdrivePedal = rebuilt.pedals[0] as? OverdrivePedal else {
Issue.record("Expected OverdrivePedal after rebuildBoard")
return
}
// drive is effectKnobs[0] → knobValues[0]; applyState restores it via UIParamNode.update.
#expect(
abs(restoredOverdrive.drive - knownDrive) < 1e-9,
"drive should be \(knownDrive) after rebuild, got \(restoredOverdrive.drive)"
)
}
// MARK: - BoardVersionStore.remove
@Test func versionStoreRemoveDropsEntryByID() throws {
let (sg, _, audioURL): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: audioURL) }
let store: BoardVersionStore = BoardVersionStore()
store.capture(sg.boards[0], name: "A")
store.capture(sg.boards[1], name: "B")
#expect(store.versions.count == 2)
let toRemove: BoardVersion = try #require(store.versions.first)
store.remove(toRemove)
#expect(store.versions.count == 1, "Store should have 1 version after remove")
#expect(store.versions.first?.id != toRemove.id, "Removed version should not be present")
}
// MARK: - BoardVersionStore.loadAllFromDisk skips bad files
@Test func loadAllFromDiskSkipsCorruptFiles() throws {
let (sg, _, audioURL): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: audioURL) }
let tempDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString, isDirectory: true)
defer { try? FileManager.default.removeItem(atPath: tempDir.path) }
// Capture one real version using the store's public API (captures sg.boards[0]).
// `writeToDisk` uses secondsSince1970 encoding, which `loadAllFromDisk` expects.
let writeStore: BoardVersionStore = BoardVersionStore()
writeStore.capture(sg.boards[0], name: "Valid")
let validID: UUID = try #require(writeStore.versions.first?.id)
try writeStore.writeAllToDisk(in: tempDir)
// Write one corrupt JSON file into the same directory.
let corruptURL: URL = tempDir.appendingPathComponent("corrupt.json")
let corruptData: Data = Data("not valid json at all {{{".utf8)
try corruptData.write(to: corruptURL, options: .atomic)
// Write a non-JSON file that should be ignored by extension filter.
let ignoredURL: URL = tempDir.appendingPathComponent("readme.txt")
let ignoredData: Data = Data("this is not JSON".utf8)
try ignoredData.write(to: ignoredURL, options: .atomic)
let store: BoardVersionStore = BoardVersionStore()
try store.loadAllFromDisk(in: tempDir)
#expect(store.versions.count == 1, "Only the valid JSON should be loaded")
#expect(store.versions.first?.id == validID)
}
// MARK: - rebuildBoard — non-destructive on failure
/// Verifies that a successful `rebuildBoard` keeps `boards.count` stable and places
/// the rebuilt board at the correct index. Also verifies that rebuilding an unmanaged
/// board (not in `boards`) appends the new board without disturbing the managed list.
@Test func rebuildBoardPreservesCountAndIndexOnSuccess() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
// Precondition: 2 boards at indices 0 and 1.
#expect(sg.boards.count == 2)
let originalBoard1: PedalBoard = sg.boards[1]
// Rebuild board at index 0 with a single Compressor.
let board0: PedalBoard = sg.boards[0]
let state: BoardState = BoardState(
label: "Compressor Only",
pedals: [PedalState(type: "Compressor", knobValues: [0.5, 0.7, 2.0, 1.0], bypass: 0.0)]
)
let rebuilt: PedalBoard = try sg.rebuildBoard(board0, from: state)
// Count must be unchanged.
#expect(sg.boards.count == 2, "boards.count should remain 2 after successful rebuild")
// Rebuilt board occupies the original slot.
#expect(sg.boards[0] === rebuilt, "Rebuilt board should be at index 0")
// The other board is undisturbed.
#expect(sg.boards[1] === originalBoard1, "Board at index 1 should be unchanged")
// Content is correct.
#expect(rebuilt.pedals.count == 1)
#expect(rebuilt.pedals[0].displayName == "Compressor")
}
/// Verifies that when `rebuildBoard` is called with a board that is NOT in `boards`
/// (an unmanaged board), the managed list grows by one and the existing boards are
/// undisturbed.
@Test func rebuildBoardUnmanagedBoardAppendsWithoutCorruption() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: url) }
// Create a board that we do NOT pass through addBoard on this sg instance.
// We simulate an unmanaged board by capturing a reference to the second board
// and then removing it manually, leaving us with only board 0 managed.
let unmanagedBoard: PedalBoard = sg.boards[1]
sg.removeBoard(unmanagedBoard)
#expect(sg.boards.count == 1, "Should have 1 managed board after manual remove")
let state: BoardState = BoardState(
label: "Unmanaged Rebuild",
pedals: [PedalState(type: "Tremolo", knobValues: [0.4, 1.0, 0.5, 1.0], bypass: 0.0)]
)
// Pass the removed (now unmanaged) board to rebuildBoard.
let rebuilt: PedalBoard = try sg.rebuildBoard(unmanagedBoard, from: state)
// An unmanaged board has no oldIndex, so the new board is simply appended.
#expect(sg.boards.count == 2, "Unmanaged rebuild should append (count goes to 2)")
#expect(sg.boards.last === rebuilt, "Rebuilt board should be the last element")
#expect(rebuilt.pedals.count == 1)
#expect(rebuilt.pedals[0].displayName == "Tremolo")
// The original managed board is undisturbed.
#expect(sg.boards[0] !== rebuilt, "The original board at index 0 should be unchanged")
}
// MARK: - BoardVersionStore.deleteFromDisk
@Test func deleteFromDiskRemovesFile() throws {
let (sg, _, audioURL): (ShoeGaze, SynthesisEngine, URL) = try makeTwoBoardRig()
defer { try? FileManager.default.removeItem(at: audioURL) }
let tempDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString, isDirectory: true)
defer { try? FileManager.default.removeItem(atPath: tempDir.path) }
// Capture a version and write it to disk.
let store: BoardVersionStore = BoardVersionStore()
store.capture(sg.boards[0], name: "To Delete")
let capturedVersion: BoardVersion = try #require(store.versions.first)
try store.writeAllToDisk(in: tempDir)
// Confirm the file is present on disk.
let freshStore1: BoardVersionStore = BoardVersionStore()
try freshStore1.loadAllFromDisk(in: tempDir)
#expect(freshStore1.versions.count == 1, "File should be present before delete")
// Delete from disk and remove from memory.
try store.deleteFromDisk(capturedVersion, in: tempDir)
store.remove(capturedVersion)
#expect(store.versions.isEmpty, "In-memory store should be empty after remove")
// Reload — the deleted file must not appear.
let freshStore2: BoardVersionStore = BoardVersionStore()
try freshStore2.loadAllFromDisk(in: tempDir)
#expect(freshStore2.versions.isEmpty, "Deleted version should not appear after reload")
}
/// `deleteFromDisk` is a no-op when the file is already absent — must not throw.
@Test func deleteFromDiskIsNoOpForMissingFile() throws {
let tempDir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString, isDirectory: true)
defer { try? FileManager.default.removeItem(atPath: tempDir.path) }
// Create a version but do NOT write it to disk.
let store: BoardVersionStore = BoardVersionStore()
let phantom: BoardVersion = BoardVersion(
id: UUID(),
name: "Never Written",
savedAt: Date(),
state: BoardState(label: "Empty", pedals: [])
)
// Should not throw even though the file was never written.
#expect(throws: Never.self) {
try store.deleteFromDisk(phantom, in: tempDir)
}
}
// MARK: - BoardVersionStore.defaultDirectory
@Test func defaultDirectoryIsNonEmpty() {
let dir: URL = BoardVersionStore.defaultDirectory()
#expect(!dir.path.isEmpty, "Default directory path should be non-empty")
#expect(dir.lastPathComponent == "ShoeGazeVersions",
"Default directory last component should be 'ShoeGazeVersions'")
}
}
@@ -0,0 +1,270 @@
// ChainRouterTests.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("ChainRouter")
struct ChainRouterTests {
// MARK: - Helpers
/// Audio bus pool size for test engines.
private let numAudioBuses: Int = 128
/// Render duration in seconds.
private let renderDuration: Double = 0.2
// MARK: - Non-silent output (full chain)
@Test func routerWithOnePedalPerBoardRendersNonSilent() throws {
// Build a router with .testLoop, add one pedal to each board via addToA/addToB,
// finalize, start the engine, and confirm the hardware output is non-silent.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
try router.addToA(OverdrivePedal())
try router.addToB(DelayPedal())
try router.finalize()
// The BoardOutputMaster writes hardware buses 0/1 directly; no extra master needed.
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "ChainRouter produced no samples")
#expect(hasNonSilentOutput(samples), "ChainRouter output was silent")
}
// MARK: - Mode: branch A only
@Test func modeARendersNonSilent() throws {
// Set mode = .a before finalize so only board A contributes.
// Output must still be non-silent (board A passes through the master).
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
try router.addToA(OverdrivePedal())
try router.addToB(DelayPedal())
router.mode = .a
try router.finalize()
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "mode .a produced no samples")
#expect(hasNonSilentOutput(samples), "mode .a: board A chain should produce non-silent output")
}
// MARK: - Mode: branch B only
@Test func modeBRendersNonSilent() throws {
// Set mode = .b before finalize so only board B contributes.
// Output must still be non-silent (board B passes through the master).
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
try router.addToA(OverdrivePedal())
try router.addToB(DelayPedal())
router.mode = .b
try router.finalize()
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "mode .b produced no samples")
#expect(hasNonSilentOutput(samples), "mode .b: board B chain should produce non-silent output")
}
// MARK: - Both branches muted → silence
@Test func bothBranchesMutedProducesSilence() throws {
// Disable both splitter branches before finalize.
// After the 20 ms lag settles the output should be silent.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
try router.addToA(OverdrivePedal())
try router.addToB(DelayPedal())
// Mute both branches before the engine starts.
router.splitter.branchAEnabled = 0.0
router.splitter.branchBEnabled = 0.0
try router.finalize()
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
// Skip the initial lag-settle period (approx 20 ms = ~882 stereo frames at 44.1 kHz).
let lagSettleFrames: Int = 2048
guard samples.count > lagSettleFrames else { return }
let settled: [Float] = Array(samples[lagSettleFrames...])
#expect(
!hasNonSilentOutput(settled, threshold: 1e-4),
"Both branches muted: output should be silent after lag settles"
)
}
// MARK: - Empty boards
@Test func routerWithEmptyBoardsRendersNonSilent() throws {
// No pedals added — signal passes straight through head→output buses,
// which are both the board head buses (pass-through). The merger sums them.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
// No pedals added to either board.
try router.finalize()
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Empty-board router produced no samples")
#expect(hasNonSilentOutput(samples), "Empty-board router produced silence")
}
// MARK: - makeChainRouter registers and teardown does not crash
@Test func makeChainRouterRegistersAndTeardownDoesNotCrash() throws {
// Confirm ShoeGaze.makeChainRouter() tracks the router and teardown cleans up.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let router: ChainRouter = try shoeGaze.makeChainRouter()
try router.addToA(OverdrivePedal())
try router.addToB(ReverbPedal())
try router.finalize()
// teardown must not crash and must remove all router nodes cleanly.
shoeGaze.teardown()
// Boards owned by ShoeGaze are unrelated to the router boards.
#expect(shoeGaze.boards.isEmpty, "ShoeGaze.boards should be empty after teardown")
}
// MARK: - makeChainRouter renders non-silent via ShoeGaze
@Test func makeChainRouterRendersNonSilentViaShoeGaze() throws {
// End-to-end: ShoeGaze.makeChainRouter → add pedals → finalize → start → sound.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let router: ChainRouter = try shoeGaze.makeChainRouter()
try router.addToA(FuzzPedal())
try router.addToB(ReverbPedal())
router.mode = .both
try router.finalize()
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "makeChainRouter produced no samples")
#expect(hasNonSilentOutput(samples), "makeChainRouter output was silent")
}
// MARK: - masterGainNode exposed after finalize
@Test func masterGainNodeIsNilBeforeFinalizeAndExposedAfter() throws {
// masterGainNode must be nil until finalize() is called.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.01,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
#expect(router.masterGainNode == nil, "masterGainNode should be nil before finalize()")
try router.finalize()
#expect(router.masterGainNode != nil, "masterGainNode should be non-nil after finalize()")
}
// MARK: - routerAlreadyFinalized guard
@Test func addToAAfterFinalizeThrows() throws {
// addToA called after finalize() must throw routerAlreadyFinalized.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.01,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
try router.finalize()
#expect(throws: ShoeGazeError.routerAlreadyFinalized) {
try router.addToA(OverdrivePedal())
}
}
@Test func addToBAfterFinalizeThrows() throws {
// addToB called after finalize() must throw routerAlreadyFinalized.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.01,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
try router.finalize()
#expect(throws: ShoeGazeError.routerAlreadyFinalized) {
try router.addToB(DelayPedal())
}
}
// MARK: - Populate order independence (B then A)
@Test func populateBThenARendersNonSilentInModeBoth() throws {
// Populate board B first, then board A. With mode .both the output must be
// non-silent, demonstrating that lastInsertedNode tracking makes the merger
// placement independent of populate order.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: .testLoop)
// B populated before A — the ordering bug would place the merger before A's pedal.
try router.addToB(ReverbPedal())
try router.addToA(OverdrivePedal())
router.mode = .both
try router.finalize()
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "B-then-A populate produced no samples")
#expect(
hasNonSilentOutput(samples),
"B-then-A populate with mode .both produced silence; merger ordering may be wrong"
)
}
}
@@ -0,0 +1,101 @@
// CompressorPedalTests.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("CompressorPedal")
struct CompressorPedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
let renderDuration: Double = 0.1
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: CompressorPedal = CompressorPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "CompressorPedal produced silence")
}
@Test func ratioChangesOutput() throws {
// A high-ratio render should differ from a low-ratio render (bypass-equivalent).
let renderDuration: Double = 0.1
let numAudioBuses: Int = 64
func renderWithRatio(_ ratioValue: 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: CompressorPedal = CompressorPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
// Use a low threshold so the test signal (peak ~0.25 linear ≈ -12 dB) is
// well above it, ensuring ratio differences produce measurable gain changes.
pedal.threshold = -24.0
pedal.ratio = ratioValue
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 lowRatioSamples: [Float] = try renderWithRatio(1.0)
let highRatioSamples: [Float] = try renderWithRatio(20.0)
#expect(hasNonSilentOutput(lowRatioSamples), "ratio=1 render was silent")
#expect(hasNonSilentOutput(highRatioSamples), "ratio=20 render was silent")
let skipSamples: Int = 1024
let windowSize: Int = 2048
guard lowRatioSamples.count >= skipSamples + windowSize,
highRatioSamples.count >= skipSamples + windowSize else { return }
let lowWindow: [Float] = Array(lowRatioSamples[skipSamples..<(skipSamples + windowSize)])
let highWindow: [Float] = Array(highRatioSamples[skipSamples..<(skipSamples + windowSize)])
let ssd: Double = zip(lowWindow, highWindow).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
#expect(ssd > 0, "ratio=1 and ratio=20 produced identical output — ratio knob has no effect")
}
}
@@ -0,0 +1,48 @@
// DelayPedalTests.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("DelayPedal")
struct DelayPedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
// Render for longer than the default delay time (0.25 s) so echoes appear in the output.
// The base Pedal blends wet (delay output) with dry via `mix`. With the default mix = 1.0
// the output is fully wet, meaning the first 0.25 s of output from `effect()` is silence
// (the delay line hasn't filled yet). Use mix = 0.5 so the dry signal bleeds through.
let renderDuration: Double = 0.5
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: DelayPedal = DelayPedal(inputBus: srcBus.index, outputBus: dstBus.index)
// Use mix = 0.5 so the dry signal is present from frame 0, making the
// non-silence check reliable without needing to wait for the full delay.
pedal.mix = 0.5
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "DelayPedal produced silence")
}
}
@@ -0,0 +1,99 @@
// FuzzPedalTests.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("FuzzPedal")
struct FuzzPedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
let renderDuration: Double = 0.1
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: FuzzPedal = FuzzPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "FuzzPedal produced silence")
}
@Test func fuzzKnobChangesOutput() throws {
// A high-fuzz render should differ from a low-fuzz render.
let renderDuration: Double = 0.1
let numAudioBuses: Int = 64
func renderWithFuzz(_ fuzzValue: 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: FuzzPedal = FuzzPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
pedal.fuzz = fuzzValue
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 lowFuzzSamples: [Float] = try renderWithFuzz(2.0)
let highFuzzSamples: [Float] = try renderWithFuzz(50.0)
#expect(hasNonSilentOutput(lowFuzzSamples), "low-fuzz render was silent")
#expect(hasNonSilentOutput(highFuzzSamples), "high-fuzz render was silent")
// The two renders should differ — different drive amounts saturate differently.
let skipSamples: Int = 1024
let windowSize: Int = 2048
guard lowFuzzSamples.count >= skipSamples + windowSize,
highFuzzSamples.count >= skipSamples + windowSize else { return }
let lowWindow: [Float] = Array(lowFuzzSamples[skipSamples..<(skipSamples + windowSize)])
let highWindow: [Float] = Array(highFuzzSamples[skipSamples..<(skipSamples + windowSize)])
let ssd: Double = zip(lowWindow, highWindow).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
#expect(ssd > 0, "low-fuzz and high-fuzz produced identical output")
}
}
@@ -0,0 +1,131 @@
// LiveInputBoardTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// Tests for the `.liveInput` path in `ShoeGaze.addBoard()`.
///
/// The NRT driver does not supply real hardware input samples, so the pedal chain
/// reads silence. These tests assert correct setup: no thrown error, the expected
/// number of nodes added to the engine, and the pass-through board structure.
@MainActor
@Suite("LiveInputBoard")
struct LiveInputBoardTests {
/// `addBoard()` with `.liveInput` and `numInputChannels > 0` must not throw and
/// must add a `HardwareInputPassThrough` that is tracked and torn down correctly.
@Test func liveInputBoardBuildsWithoutThrowing() throws {
let numOutputChannels: Int = 2
let numInputChannels: Int = 1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numOutputChannels: numOutputChannels,
numInputChannels: numInputChannels,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: 0))
// addBoard() must succeed — no throw even though the NRT driver produces
// silence on the input bus.
let board: PedalBoard = try sg.addBoard()
// The board's head bus index must be distinct from the hardware input bus
// (the pass-through copies from numOutputChannels to board.headBus.index).
let hardwareInputBusIndex: Int = numOutputChannels
#expect(board.headBus.index != hardwareInputBusIndex,
"board head bus should be a user-space bus, not the raw hardware input bus")
// headInputNode must be set so PedalBoard.add(_:) can chain the first pedal
// after the pass-through automatically.
#expect(board.headInputNode != nil,
"headInputNode should be set to the HardwareInputPassThrough")
// Add a pedal and finalize to verify the full signal chain builds without error.
let pedal: OverdrivePedal = OverdrivePedal()
try board.add(pedal)
try sg.finalizeBoard(board)
try engine.start()
// Teardown must not crash or assert.
sg.teardown()
}
/// `addBoard()` with `.liveInput` and `numInputChannels == 0` must throw
/// `ShoeGazeError.liveInputRequiresInputChannels` rather than trapping.
@Test func liveInputBoardThrowsWhenNoInputChannels() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numInputChannels: 0
)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: 0))
#expect(throws: ShoeGazeError.liveInputRequiresInputChannels) {
try sg.addBoard()
}
}
/// `liveInputBusIndex` maps a hardware input channel to bus `numOutputChannels + channel`.
@Test func liveInputBusIndexMapsChannelToBus() throws {
let numOutputChannels: Int = 2
let numInputChannels: Int = 4
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05,
numOutputChannels: numOutputChannels,
numInputChannels: numInputChannels,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let channel: Int = 2
let busIndex: Int = try liveInputBusIndex(channel: channel, engine: engine)
#expect(busIndex == numOutputChannels + channel,
"input channel \(channel) should map to bus \(numOutputChannels + channel)")
}
/// `addBoard()` with `.liveInput(channel:)` on a valid non-zero channel builds without throwing.
@Test func liveInputNonZeroChannelBuildsWithoutThrowing() throws {
let numInputChannels: Int = 4
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numInputChannels: numInputChannels,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: 2))
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
try sg.finalizeBoard(board)
try engine.start()
sg.teardown()
}
/// `addBoard()` with a `.liveInput` channel `>= numInputChannels` throws
/// `ShoeGazeError.inputChannelOutOfRange`.
@Test func liveInputChannelOutOfRangeThrows() throws {
let numInputChannels: Int = 1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05,
numInputChannels: numInputChannels
)
defer { try? FileManager.default.removeItem(at: url) }
let outOfRangeChannel: Int = 3
let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: outOfRangeChannel))
#expect(throws: ShoeGazeError.inputChannelOutOfRange(requested: outOfRangeChannel, available: numInputChannels)) {
try sg.addBoard()
}
}
}
@@ -0,0 +1,136 @@
// MergerTests.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("Merger")
struct MergerTests {
// MARK: - Helpers
/// Number of audio buses allocated in the test engine.
private let numAudioBuses: Int = 64
/// Render duration in seconds.
private let renderDuration: Double = 0.2
// MARK: - Non-silent output
@Test func mergerSumsTwoBusesToOutput() throws {
// Feed a test loop to bus A only; bus B is silent. Merger output should be non-silent.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let busA: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let busB: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let outBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(busA)
engine.busAllocator.releaseAudioBus(busB)
engine.busAllocator.releaseAudioBus(outBus)
}
// Write a test signal to bus A only; bus B remains zero.
let sourceA: TestLoopSource = TestLoopSource(targetBus: busA.index)
let merger: Merger = Merger(
inputBusA: busA.index,
inputBusB: busB.index,
outputBus: outBus.index
)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: outBus.index)
try engine.add(sourceA)
try engine.add(merger, position: NodePosition.after(sourceA))
try engine.add(master, position: NodePosition.after(merger))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Merger produced no samples")
#expect(hasNonSilentOutput(samples), "Merger output was silent when bus A had signal")
}
@Test func mergerWithBothBranches() throws {
// Feed two independent test loop sources into bus A and bus B; both should sum.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let busA: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let busB: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let outBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(busA)
engine.busAllocator.releaseAudioBus(busB)
engine.busAllocator.releaseAudioBus(outBus)
}
let sourceA: TestLoopSource = TestLoopSource(targetBus: busA.index)
let sourceB: TestLoopSource = TestLoopSource(targetBus: busB.index)
let merger: Merger = Merger(
inputBusA: busA.index,
inputBusB: busB.index,
outputBus: outBus.index
)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: outBus.index)
try engine.add(sourceA)
try engine.add(sourceB, position: NodePosition.after(sourceA))
try engine.add(merger, position: NodePosition.after(sourceB))
try engine.add(master, position: NodePosition.after(merger))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Merger produced no samples")
#expect(hasNonSilentOutput(samples), "Merger output was silent with two active buses")
}
@Test func mergerWithLevelAZeroPassesBranchBOnly() throws {
// Set levelA=0 and only wire bus B to carry signal. Output should still be non-silent.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let busA: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let busB: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let outBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(busA)
engine.busAllocator.releaseAudioBus(busB)
engine.busAllocator.releaseAudioBus(outBus)
}
// Only bus B carries signal.
let sourceB: TestLoopSource = TestLoopSource(targetBus: busB.index)
let merger: Merger = Merger(
inputBusA: busA.index,
inputBusB: busB.index,
outputBus: outBus.index
)
merger.levelA = 0.0
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: outBus.index)
try engine.add(sourceB)
try engine.add(merger, position: NodePosition.after(sourceB))
try engine.add(master, position: NodePosition.after(merger))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Merger produced no samples")
#expect(hasNonSilentOutput(samples), "Merger was silent even though branch B has signal")
}
}
@@ -0,0 +1,40 @@
// ModulationPedalTests.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("ModulationPedal")
struct ModulationPedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.2)
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: ModulationPedal = ModulationPedal(inputBus: srcBus.index, outputBus: dstBus.index)
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "ModulationPedal produced silence")
}
}
@@ -0,0 +1,182 @@
// OverdrivePedalTests.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("OverdrivePedal")
struct OverdrivePedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
let renderDuration: Double = 0.1
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: OverdrivePedal = OverdrivePedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "OverdrivePedal produced silence")
}
@Test func bypassYieldsDrySignal() throws {
// Render with bypass = 0 (engaged) and bypass = 1 (bypassed) and compare.
// The bypassed render should closely match a render of the dry signal alone.
let renderDuration: Double = 0.1
let numAudioBuses: Int = 64
// --- Dry reference render ---
let (dryEngine, dryURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: dryURL) }
let drySrcBus: AudioBus = try dryEngine.busAllocator.allocateAudioBus(channelCount: 1)
defer { dryEngine.busAllocator.releaseAudioBus(drySrcBus) }
let drySource: TestLoopSource = TestLoopSource(targetBus: drySrcBus.index)
let dryMaster: TestRouteMaster = TestRouteMaster(inputBusIndex: drySrcBus.index)
try dryEngine.add(drySource)
try dryEngine.add(dryMaster, position: NodePosition.after(drySource))
try dryEngine.start()
let drySamples: [Float] = readStereoCAF(url: dryURL, sampleRate: 44100.0)
// --- Bypass render ---
let (bypassEngine, bypassURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: bypassURL) }
let bpSrcBus: AudioBus = try bypassEngine.busAllocator.allocateAudioBus(channelCount: 1)
let bpDstBus: AudioBus = try bypassEngine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
bypassEngine.busAllocator.releaseAudioBus(bpSrcBus)
bypassEngine.busAllocator.releaseAudioBus(bpDstBus)
}
let bpSource: TestLoopSource = TestLoopSource(targetBus: bpSrcBus.index)
let bpPedal: OverdrivePedal = OverdrivePedal(
inputBus: bpSrcBus.index,
outputBus: bpDstBus.index
)
bpPedal.bypass = 1.0 // fully bypassed
let bpMaster: TestRouteMaster = TestRouteMaster(inputBusIndex: bpDstBus.index)
try bypassEngine.add(bpSource)
try bypassEngine.add(bpPedal, position: NodePosition.after(bpSource))
try bypassEngine.add(bpMaster, position: NodePosition.after(bpPedal))
try bypassEngine.start()
let bypassSamples: [Float] = readStereoCAF(url: bypassURL, sampleRate: 44100.0)
// Both renders should be non-silent.
#expect(hasNonSilentOutput(drySamples), "dry reference was silent")
#expect(hasNonSilentOutput(bypassSamples), "bypass render was silent")
// The bypass has a 20 ms lag — skip the first 2048 samples (1024 frames × 2 ch)
// for the transition to settle, then compare a window of 2048 interleaved samples.
let skipSamples: Int = 2048
let windowSize: Int = 2048
guard drySamples.count >= skipSamples + windowSize,
bypassSamples.count >= skipSamples + windowSize else { return }
let dryWindow: [Float] = Array(drySamples[skipSamples..<(skipSamples + windowSize)])
let bypassWindow: [Float] = Array(bypassSamples[skipSamples..<(skipSamples + windowSize)])
// Sum of squared differences should be small (within 1% power of the dry window).
let ssd: Double = zip(dryWindow, bypassWindow).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
let dryPower: Double = dryWindow.reduce(0.0) { acc, s in
let v: Double = Double(s)
return acc + v * v
}
let relativeError: Double = dryPower > 0 ? ssd / dryPower : ssd
#expect(relativeError < 0.01, "Bypass output differed too much from dry: relErr=\(relativeError)")
}
@Test func mixChangesOutput() throws {
// A render with mix = 0.0 (fully dry) should differ from mix = 1.0 (fully wet).
let renderDuration: Double = 0.1
let blockSize: Int = 512
let sampleRate: Double = 44100.0
let numAudioBuses: Int = 64
func renderWithMix(_ mix: Double) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
blockSize: blockSize,
sampleRate: sampleRate,
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: OverdrivePedal = OverdrivePedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
pedal.mix = mix
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
let drySamples: [Float] = try renderWithMix(0.0)
let wetSamples: [Float] = try renderWithMix(1.0)
// Both should be non-silent.
#expect(hasNonSilentOutput(drySamples))
#expect(hasNonSilentOutput(wetSamples))
// Wet and dry should not be identical — the overdrive changes the signal.
// Compare a window after the first block to skip any transients.
let skipSamples: Int = blockSize * 2
let windowSize: Int = blockSize * 2
guard drySamples.count >= skipSamples + windowSize,
wetSamples.count >= skipSamples + windowSize else { return }
let dryWindow: [Float] = Array(drySamples[skipSamples..<(skipSamples + windowSize)])
let wetWindow: [Float] = Array(wetSamples[skipSamples..<(skipSamples + windowSize)])
let ssd: Double = zip(dryWindow, wetWindow).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
#expect(ssd > 0, "mix=0 and mix=1 produced identical output — mix parameter has no effect")
}
}
@@ -0,0 +1,275 @@
// ParallelSectionTests.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("ParallelSection")
struct ParallelSectionTests {
// MARK: - Helpers
/// Audio bus pool size for test engines.
private let numAudioBuses: Int = 128
/// Render duration in seconds.
private let renderDuration: Double = 0.2
// MARK: - Full parallel chain render
@Test func parallelChainRendersNonSilent() throws {
// Full board: OverdrivePedal → split → branchA(DelayPedal), branchB(FuzzPedal)
// → merge → ReverbPedal → output.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try shoeGaze.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())
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: board.outputBus.index)
guard let tailNode: any Synthesizer = board.tailNode else {
Issue.record("Board tail node was nil after adding pedals")
return
}
try engine.add(master, position: NodePosition.after(tailNode))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Parallel chain produced no samples")
#expect(hasNonSilentOutput(samples), "Parallel chain produced silence")
}
@Test func parallelChainWithoutPreOrPostPedals() throws {
// Board with only a parallel section — no pre-split or post-merge pedals.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try shoeGaze.addBoard()
let section: ParallelSection = try board.split()
try section.branchA.add(OverdrivePedal())
try section.branchB.add(ReverbPedal())
try board.merge(section)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: board.outputBus.index)
guard let tailNode: any Synthesizer = board.tailNode else {
Issue.record("Board tail node was nil")
return
}
try engine.add(master, position: NodePosition.after(tailNode))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Board with only a parallel section produced no samples")
#expect(hasNonSilentOutput(samples), "Board with only a parallel section produced silence")
}
// MARK: - Empty branches
@Test func parallelSectionWithEmptyBranches() throws {
// split → merge with no pedals in either branch — signal passes through unchanged.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try shoeGaze.addBoard()
let section: ParallelSection = try board.split()
// No pedals added to either branch — both branch input buses are identical to their
// tail buses. The merger sums two copies of the splitter outputs at unity gain.
try board.merge(section)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: board.outputBus.index)
guard let tailNode: any Synthesizer = board.tailNode else {
Issue.record("Board tail node was nil")
return
}
try engine.add(master, position: NodePosition.after(tailNode))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Empty-branch parallel section produced no samples")
#expect(hasNonSilentOutput(samples), "Empty-branch parallel section produced silence")
}
// MARK: - Mode: branch A only
@Test func splitterModeAMutesB() throws {
// Set splitter.mode = .a — branch A passes, branch B is muted.
// The merger still produces non-silent output from branch A alone.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try shoeGaze.addBoard()
let section: ParallelSection = try board.split()
try section.branchA.add(OverdrivePedal())
try section.branchB.add(FuzzPedal())
try board.merge(section)
// Set mode .a (mute B) before starting.
section.splitter.mode = .a
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: board.outputBus.index)
guard let tailNode: any Synthesizer = board.tailNode else {
Issue.record("Board tail node was nil")
return
}
try engine.add(master, position: NodePosition.after(tailNode))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "mode .a produced no samples")
#expect(hasNonSilentOutput(samples), "mode .a: branch A should produce non-silent output")
}
// MARK: - Mode: branch B only
@Test func splitterModeBMutesA() throws {
// Set splitter.mode = .b — branch B passes, branch A is muted.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try shoeGaze.addBoard()
let section: ParallelSection = try board.split()
try section.branchA.add(OverdrivePedal())
try section.branchB.add(FuzzPedal())
try board.merge(section)
// Set mode .b (mute A) before starting.
section.splitter.mode = .b
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: board.outputBus.index)
guard let tailNode: any Synthesizer = board.tailNode else {
Issue.record("Board tail node was nil")
return
}
try engine.add(master, position: NodePosition.after(tailNode))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "mode .b produced no samples")
#expect(hasNonSilentOutput(samples), "mode .b: branch B should produce non-silent output")
}
// MARK: - ShoeGaze finalizeBoard with parallel section
@Test func shoegazeFinalizeBoardAfterParallelSection() throws {
// Confirm ShoeGaze.finalizeBoard positions the master after the merger correctly.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try shoeGaze.addBoard()
let section: ParallelSection = try board.split()
try section.branchA.add(DelayPedal())
try section.branchB.add(FuzzPedal())
try board.merge(section)
// finalizeBoard uses board.tailNode — should chain after the merger.
try shoeGaze.finalizeBoard(board)
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Finalized board with parallel section produced no samples")
#expect(hasNonSilentOutput(samples), "Finalized board with parallel section produced silence")
}
// MARK: - Teardown
@Test func boardTeardownRemovesAllParallelNodes() throws {
// Confirm teardown succeeds and does not throw when routing nodes are present.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try shoeGaze.addBoard()
let section: ParallelSection = try board.split()
try section.branchA.add(OverdrivePedal())
try section.branchB.add(ReverbPedal())
try board.merge(section)
try shoeGaze.finalizeBoard(board)
// Teardown should complete without error (remove-before-bus-release ordering).
shoeGaze.teardown()
#expect(shoeGaze.boards.isEmpty, "boards should be empty after teardown")
}
// MARK: - post-merge add chains correctly
@Test func addAfterMergeChainsFurtherPedals() throws {
// After merge, board.add(_:) should chain after the merger and still produce sound.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try shoeGaze.addBoard()
let section: ParallelSection = try board.split()
try section.branchA.add(DelayPedal())
try section.branchB.add(FuzzPedal())
try board.merge(section)
// Add a post-merge pedal that chains after the merger.
try board.add(ReverbPedal())
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: board.outputBus.index)
guard let tailNode: any Synthesizer = board.tailNode else {
Issue.record("Board tail node was nil after post-merge add")
return
}
try engine.add(master, position: NodePosition.after(tailNode))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Post-merge chain produced no samples")
#expect(hasNonSilentOutput(samples), "Post-merge chain produced silence")
}
}
@@ -0,0 +1,54 @@
// PedalBoardTests.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("PedalBoard")
struct PedalBoardTests {
@Test func twoPedalBoardRendersNonSilent() throws {
// Verify that a two-pedal chain produces non-silent output and that the second
// pedal receives the first pedal's output (the chain is wired correctly).
let renderDuration: Double = 0.2
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let board: PedalBoard = try PedalBoard(engine: engine)
// Add the test loop source writing to the board head bus.
let source: TestLoopSource = TestLoopSource(targetBus: board.headBus.index)
try engine.add(source)
// Add two pedals to the chain.
// Pass `after: source` for the first pedal so it evaluates after the source in the
// node tree (source writes headBus → overdrive reads it → reverb reads overdrive out).
let overdrive: OverdrivePedal = OverdrivePedal()
let reverb: ReverbPedal = ReverbPedal()
try board.add(overdrive, after: source)
try board.add(reverb)
// Verify that the board tracks both pedals.
#expect(board.pedals.count == 2)
// A master to route the board output to hardware output.
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: board.outputBus.index)
try engine.add(master, position: NodePosition.after(reverb))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Two-pedal board produced no samples")
#expect(hasNonSilentOutput(samples), "Two-pedal board produced silence")
}
}
@@ -0,0 +1,98 @@
// PhaserPedalTests.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("PhaserPedal")
struct PhaserPedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
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: PhaserPedal = PhaserPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "PhaserPedal produced silence")
}
@Test func feedbackKnobChangesOutput() throws {
// Low-feedback and high-feedback renders should differ.
let renderDuration: Double = 0.2
let numAudioBuses: Int = 64
func renderWithFeedback(_ feedbackValue: 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: PhaserPedal = PhaserPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
pedal.feedback = feedbackValue
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 lowFeedbackSamples: [Float] = try renderWithFeedback(0.0)
let highFeedbackSamples: [Float] = try renderWithFeedback(0.8)
#expect(hasNonSilentOutput(lowFeedbackSamples), "low-feedback phaser render was silent")
#expect(hasNonSilentOutput(highFeedbackSamples), "high-feedback phaser render was silent")
let skipSamples: Int = 1024
let windowSize: Int = 2048
guard lowFeedbackSamples.count >= skipSamples + windowSize,
highFeedbackSamples.count >= skipSamples + windowSize else { return }
let lowWindow: [Float] = Array(lowFeedbackSamples[skipSamples..<(skipSamples + windowSize)])
let highWindow: [Float] = Array(highFeedbackSamples[skipSamples..<(skipSamples + windowSize)])
let ssd: Double = zip(lowWindow, highWindow).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
#expect(ssd > 0, "low-feedback and high-feedback phaser produced identical output")
}
}
@@ -0,0 +1,301 @@
// 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: - 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)
// threshold is the first effectKnob; applyState calls knob.node.update(value)
// which sets the UIParamNode. The UIParamNode.value should now reflect the restored value.
let thresholdKnobValue: Double = compressor.knobs[0].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")
}
}
@@ -0,0 +1,186 @@
// RecordingTests.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("Recording")
struct RecordingTests {
// MARK: - Helpers
/// Creates a temporary directory and returns its URL. The caller is responsible for cleanup.
private func makeTempFolder() throws -> URL {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
return url
}
// MARK: - Tests
@Test func recordingWritesInputAndOutputFiles() throws {
let renderDuration: Double = 0.2
let (engine, cafURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
// The NRT driver output CAF is not checked here — clean it up when done.
defer { try? FileManager.default.removeItem(at: cafURL) }
let tempFolder: URL = try makeTempFolder()
defer { try? FileManager.default.removeItem(atPath: tempFolder.path) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
let board: PedalBoard = try shoeGaze.addBoard()
try board.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board)
shoeGaze.recordingFolder = tempFolder
try shoeGaze.startRecording()
// NRT render: engine.start() renders the full duration synchronously.
try engine.start()
// Stop recording: flushes DiskOut ring buffers and closes file handles.
shoeGaze.stopRecording()
// Assert both output and input WAV files were created and are non-empty.
let contents: [URL] = try FileManager.default.contentsOfDirectory(
at: tempFolder,
includingPropertiesForKeys: [.fileSizeKey],
options: []
)
let outputFiles: [URL] = contents.filter { $0.lastPathComponent.hasPrefix("output-") && $0.pathExtension == "wav" }
let inputFiles: [URL] = contents.filter { $0.lastPathComponent.hasPrefix("input-") && $0.pathExtension == "wav" }
#expect(outputFiles.count == 1, "Expected one output WAV file")
#expect(inputFiles.count == 1, "Expected one input WAV file")
if let outputFile: URL = outputFiles.first {
let attrs: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: outputFile.path)
let size: Int = (attrs[.size] as? Int) ?? 0
#expect(size > 0, "output WAV file is empty")
}
if let inputFile: URL = inputFiles.first {
let attrs: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: inputFile.path)
let size: Int = (attrs[.size] as? Int) ?? 0
#expect(size > 0, "input WAV file is empty")
}
}
@Test func startRecordingThrowsWhenNoFolder() throws {
let (engine, cafURL): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
defer { try? FileManager.default.removeItem(at: cafURL) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
// recordingFolder is nil by default — startRecording() must throw.
#expect(throws: ShoeGazeError.recordingFolderNotSet) {
try shoeGaze.startRecording()
}
}
@Test func isRecordingTogglesAroundStartStop() throws {
let renderDuration: Double = 0.1
let (engine, cafURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: cafURL) }
let tempFolder: URL = try makeTempFolder()
defer { try? FileManager.default.removeItem(atPath: tempFolder.path) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
#expect(!shoeGaze.isRecording, "isRecording should be false before startRecording()")
shoeGaze.recordingFolder = tempFolder
try shoeGaze.startRecording()
#expect(shoeGaze.isRecording, "isRecording should be true after startRecording()")
// Render so DiskOut has data to flush.
try engine.start()
shoeGaze.stopRecording()
#expect(!shoeGaze.isRecording, "isRecording should be false after stopRecording()")
}
@Test func removeBoardWhileRecordingStopsRecording() throws {
let renderDuration: Double = 0.1
let (engine, cafURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: cafURL) }
let tempFolder: URL = try makeTempFolder()
defer { try? FileManager.default.removeItem(atPath: tempFolder.path) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.recordingFolder = tempFolder
try shoeGaze.startRecording()
#expect(shoeGaze.isRecording, "isRecording should be true after startRecording()")
// Removing a board mid-recording must stop the recording to prevent the input
// record tap from reading a released or reused head bus.
shoeGaze.removeBoard(board)
#expect(!shoeGaze.isRecording, "isRecording must be false after removeBoard(_:)")
}
@Test func monoOutputEngineWritesOutputFileOnly() throws {
let renderDuration: Double = 0.1
// Build a mono-output engine (numOutputChannels: 1) so the output tap channel count
// is clamped to 1 and bus 1 (which is the first input bus) is never read.
let (engine, cafURL): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numOutputChannels: 1,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: cafURL) }
let tempFolder: URL = try makeTempFolder()
defer { try? FileManager.default.removeItem(atPath: tempFolder.path) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.recordingFolder = tempFolder
try shoeGaze.startRecording()
try engine.start()
shoeGaze.stopRecording()
let contents: [URL] = try FileManager.default.contentsOfDirectory(
at: tempFolder,
includingPropertiesForKeys: [.fileSizeKey],
options: []
)
let outputFiles: [URL] = contents.filter {
$0.lastPathComponent.hasPrefix("output-") && $0.pathExtension == "wav"
}
// Exactly one output file must be written and must be non-empty.
#expect(outputFiles.count == 1, "Expected exactly one output WAV file for mono engine")
if let outputFile: URL = outputFiles.first {
let attrs: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(
atPath: outputFile.path
)
let fileSize: Int = (attrs[.size] as? Int) ?? 0
#expect(fileSize > 0, "Output WAV file from mono engine must be non-empty")
}
}
}
@@ -0,0 +1,40 @@
// ReverbPedalTests.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("ReverbPedal")
struct ReverbPedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.2)
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: ReverbPedal = ReverbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "ReverbPedal produced silence")
}
}
@@ -0,0 +1,91 @@
// ShoeGazeMultiBoardTests.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("ShoeGaze multi-board")
struct ShoeGazeMultiBoardTests {
@Test func addBoardAssignsLabelAndFinalizeWiresMasterNode() throws {
let renderDuration: Double = 0.05
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
#expect(board1.label == "Board 1")
#expect(board1.masterGainNode == nil, "Master node is nil until finalizeBoard")
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
#expect(board1.masterGainNode != nil, "finalizeBoard must expose the master gain node")
let board2: PedalBoard = try shoeGaze.addBoard()
#expect(board2.label == "Board 2")
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
#expect(shoeGaze.boards.count == 2)
}
@Test func removeBoardLeavesOtherBoards() throws {
let renderDuration: Double = 0.05
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
#expect(shoeGaze.boards.count == 2)
shoeGaze.removeBoard(board1)
#expect(shoeGaze.boards.count == 1)
#expect(shoeGaze.boards.first === board2, "Remaining board must be the one not removed")
}
@Test func twoBoardsRenderNonSilent() throws {
let renderDuration: Double = 0.2
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
let board1: PedalBoard = try shoeGaze.addBoard()
try board1.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
try board2.add(DelayPedal())
try shoeGaze.finalizeBoard(board2)
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Two-board ShoeGaze produced no samples")
#expect(hasNonSilentOutput(samples), "Two-board ShoeGaze produced silence")
}
}
@@ -0,0 +1,188 @@
// SplitterTests.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("Splitter")
struct SplitterTests {
// MARK: - Helpers
/// Number of audio buses allocated in the test engine.
private let numAudioBuses: Int = 64
/// Render duration in seconds.
private let renderDuration: Double = 0.2
// MARK: - Non-silent output
@Test func splitterPassesThroughBothBranchesByDefault() throws {
// Both branches enabled at 1.0 — both output buses should carry signal.
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 busA: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let busB: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(busA)
engine.busAllocator.releaseAudioBus(busB)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let splitter: Splitter = Splitter(
inputBus: srcBus.index,
outputBusA: busA.index,
outputBusB: busB.index
)
// Route bus A to the hardware output.
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: busA.index)
try engine.add(source)
try engine.add(splitter, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(splitter))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "Splitter produced no samples")
#expect(hasNonSilentOutput(samples), "Splitter branch A produced silence with enable=1")
}
// MARK: - Branch muting
@Test func branchBDisabledMutesBranchBBus() throws {
// Wire only bus B to the output. Set branchBEnabled = 0. Expect silence.
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 busA: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let busB: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(busA)
engine.busAllocator.releaseAudioBus(busB)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let splitter: Splitter = Splitter(
inputBus: srcBus.index,
outputBusA: busA.index,
outputBusB: busB.index
)
// Route only bus B to the hardware output — branch A is ignored here.
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: busB.index)
// Mute branch B before adding.
splitter.branchBEnabled = 0.0
try engine.add(source)
try engine.add(splitter, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(splitter))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
// Allow for the 20 ms lag: silence expectation applies once the lag settles.
// Because branchBEnabled is set to 0 before the splitter is added, the very
// first block already ramps toward 0 — the overall render should be silent or
// very nearly so. Use a tight threshold to allow for the lag ramp.
let lagSettleSamples: Int = 2048
guard samples.count > lagSettleSamples else { return }
let settled: [Float] = Array(samples[lagSettleSamples...])
#expect(!hasNonSilentOutput(settled, threshold: 1e-4), "Branch B should be muted")
}
@Test func branchADisabledMutesBranchABus() throws {
// Wire only bus A to the output. Set branchAEnabled = 0. Expect silence.
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 busA: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let busB: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(busA)
engine.busAllocator.releaseAudioBus(busB)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let splitter: Splitter = Splitter(
inputBus: srcBus.index,
outputBusA: busA.index,
outputBusB: busB.index
)
// Route only bus A to the hardware output.
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: busA.index)
// Mute branch A before adding.
splitter.branchAEnabled = 0.0
try engine.add(source)
try engine.add(splitter, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(splitter))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
let lagSettleSamples: Int = 2048
guard samples.count > lagSettleSamples else { return }
let settled: [Float] = Array(samples[lagSettleSamples...])
#expect(!hasNonSilentOutput(settled, threshold: 1e-4), "Branch A should be muted")
}
// MARK: - Mode convenience
@Test func modeSetterConfiguresBranchEnables() throws {
// Test the mode convenience setter in isolation (no engine needed).
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.01)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let busA: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let busB: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(busA)
engine.busAllocator.releaseAudioBus(busB)
}
let splitter: Splitter = Splitter(
inputBus: srcBus.index,
outputBusA: busA.index,
outputBusB: busB.index
)
splitter.mode = .a
#expect(splitter.branchAEnabled == 1.0, "mode .a should set branchAEnabled=1")
#expect(splitter.branchBEnabled == 0.0, "mode .a should set branchBEnabled=0")
#expect(splitter.mode == .a)
splitter.mode = .b
#expect(splitter.branchAEnabled == 0.0, "mode .b should set branchAEnabled=0")
#expect(splitter.branchBEnabled == 1.0, "mode .b should set branchBEnabled=1")
#expect(splitter.mode == .b)
splitter.mode = .both
#expect(splitter.branchAEnabled == 1.0, "mode .both should set branchAEnabled=1")
#expect(splitter.branchBEnabled == 1.0, "mode .both should set branchBEnabled=1")
#expect(splitter.mode == .both)
}
}
@@ -0,0 +1,134 @@
// OfflineRender.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import AudioToolbox
import LyrebirdSynth
import LyrebirdUI
// MARK: - NRT engine factory
/// Creates an `NRTDriver`-backed `SynthesisEngine` and renders to a temporary CAF file.
///
/// - Parameters:
/// - duration: Render duration in seconds.
/// - blockSize: Audio block size. Defaults to 512.
/// - sampleRate: Engine sample rate. Defaults to 44100.
/// - numOutputChannels: Hardware output channel count. Defaults to 2.
/// - numInputChannels: Hardware input channel count. Defaults to 0.
/// - numAudioBuses: Total audio bus pool size. Defaults to 64.
/// - Returns: `(engine, outputURL)` — caller must delete `outputURL` when done.
@MainActor
func makeNRTEngine(
duration: Double,
blockSize: Int = 512,
sampleRate: Double = 44100.0,
numOutputChannels: Int = 2,
numInputChannels: Int = 0,
numAudioBuses: Int = 64
) -> (SynthesisEngine, URL) {
/// Number of control buses to allocate in the test engine.
let numControlBuses: Int = 512
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".caf")
let driver: NRTDriver = NRTDriver(outputURL: url, duration: duration)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: numOutputChannels,
numInputChannels: numInputChannels,
numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses,
driver: driver
)
return (engine, url)
}
// MARK: - CAF reader
/// Reads all interleaved Float32 samples from a stereo CAF file written by NRTDriver.
///
/// - Parameters:
/// - url: Path of the CAF file.
/// - sampleRate: Sample rate of the file.
/// - Returns: Interleaved stereo samples, or an empty array on error.
func readStereoCAF(url: URL, sampleRate: Double = 44100.0) -> [Float] {
let stereoChannelCount: UInt32 = 2
let bytesPerSample: UInt32 = 4
let bitsPerSample: UInt32 = 32
let bytesPerFrame: UInt32 = stereoChannelCount * bytesPerSample
var fileRef: ExtAudioFileRef?
guard ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr,
let fileRef: ExtAudioFileRef else { return [] }
defer { ExtAudioFileDispose(fileRef) }
var clientFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
mSampleRate: sampleRate,
mFormatID: kAudioFormatLinearPCM,
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
mBytesPerPacket: bytesPerFrame,
mFramesPerPacket: 1,
mBytesPerFrame: bytesPerFrame,
mChannelsPerFrame: stereoChannelCount,
mBitsPerChannel: bitsPerSample,
mReserved: 0
)
guard ExtAudioFileSetProperty(
fileRef,
kExtAudioFileProperty_ClientDataFormat,
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
&clientFormat
) == noErr else { return [] }
let readFrames: UInt32 = 4096
var samples: [Float] = [Float](repeating: 0, count: Int(readFrames) * 2)
var framesRead: UInt32 = readFrames
samples.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: 2,
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
mData: ptr.baseAddress
)
)
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
}
return Array(samples.prefix(Int(framesRead) * 2))
}
// MARK: - Signal analysis
/// Returns `true` if any sample in `samples` has absolute value greater than `threshold`.
func hasNonSilentOutput(_ samples: [Float], threshold: Float = 1e-6) -> Bool {
samples.contains { abs($0) > threshold }
}
// MARK: - TestRouteMaster
/// A minimal `SynthesizerBase` that reads a mono bus and routes it to hardware stereo output.
/// Used only in tests — not part of the public ShoeGaze API.
final class TestRouteMaster: SynthesizerBase {
private let inputBusIndex: Int
/// Gain applied before panning to hardware output.
private let outputGain: Double = 0.8
/// Stereo pan position (0 = centre).
private let pan: Double = 0.0
init(inputBusIndex: Int) {
self.inputBusIndex = inputBusIndex
super.init()
}
override func build() {
let sig: In.Audio = input(bus: inputBusIndex)
output(bus: 0, source: Pan2(input: sig * outputGain, pan: pan))
}
}
@@ -0,0 +1,39 @@
// TestLoopSourceTests.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("TestLoopSource")
struct TestLoopSourceTests {
@Test func buildsAndProducesNonSilentOutput() throws {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
defer { try? FileManager.default.removeItem(at: url) }
// Allocate a scratch bus for the source to write to, then read back via Pan2→output.
let scratchBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(scratchBus) }
let source: TestLoopSource = TestLoopSource(targetBus: scratchBus.index)
try engine.add(source)
// A simple master synth to route the scratch bus to hardware output.
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: scratchBus.index)
try engine.add(master, position: NodePosition.after(source))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty, "NRT render produced no samples")
#expect(hasNonSilentOutput(samples), "TestLoopSource produced silence")
}
}
@@ -0,0 +1,78 @@
// TremoloPedalTests.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("TremoloPedal")
struct TremoloPedalTests {
@Test func buildsAndProducesNonSilentOutput() throws {
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: TremoloPedal = TremoloPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "TremoloPedal produced silence")
}
@Test func depthZeroPassesSignalUnmodified() throws {
// With depth = 0 the LFO multiplier is 1.0 — output should match a pedal
// whose mix is also 1.0 but with no tremolo (depth = 0 means no modulation).
// We verify the render is non-silent (signal passes through) without
// checking exact sample equality across different engine instances.
let renderDuration: Double = 0.1
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: TremoloPedal = TremoloPedal(
inputBus: srcBus.index,
outputBus: dstBus.index
)
pedal.depth = 0.0
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()
let samples: [Float] = readStereoCAF(url: url)
#expect(hasNonSilentOutput(samples), "TremoloPedal depth=0 produced silence — signal was muted")
}
}