diff --git a/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj b/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..0e6a0f9 --- /dev/null +++ b/Demo/ShoeGazeDemo.xcodeproj/project.pbxproj @@ -0,0 +1,387 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + C3B0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000007 /* main.swift */; }; + C3B0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000008 /* AppDelegate.swift */; }; + C3B0000000000000000000E /* DemoRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000009 /* DemoRootView.swift */; }; + C3B0000000000000000000F /* ShoeGazeDemoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B00000000000000000000A /* ShoeGazeDemoController.swift */; }; + C3B000000000000000000020 /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3B00000000000000000001E /* LyrebirdShoeGaze */; }; + C3B000000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B00000000000000000001F /* LyrebirdShoeGazeUI */; }; + C3B000000000000000000022 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3B000000000000000000023 /* Lyrebird */; }; + C3B000000000000000000024 /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B000000000000000000025 /* LyrebirdUI */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + C3B000000000000000000004 /* ShoeGazeDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + C3B000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C3B000000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = ""; }; + C3B000000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + C3B000000000000000000009 /* DemoRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoRootView.swift; sourceTree = ""; }; + C3B00000000000000000000A /* ShoeGazeDemoController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeDemoController.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + C3B000000000000000000012 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C3B000000000000000000020 /* LyrebirdShoeGaze in Frameworks */, + C3B000000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */, + C3B000000000000000000022 /* Lyrebird in Frameworks */, + C3B000000000000000000024 /* LyrebirdUI in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + C3B000000000000000000002 = { + isa = PBXGroup; + children = ( + C3B000000000000000000005 /* ShoeGazeDemo */, + C3B000000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + C3B000000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + C3B000000000000000000004 /* ShoeGazeDemo.app */, + ); + name = Products; + sourceTree = ""; + }; + C3B000000000000000000005 /* ShoeGazeDemo */ = { + isa = PBXGroup; + children = ( + C3B000000000000000000007 /* main.swift */, + C3B000000000000000000008 /* AppDelegate.swift */, + C3B000000000000000000009 /* DemoRootView.swift */, + C3B00000000000000000000A /* ShoeGazeDemoController.swift */, + C3B000000000000000000006 /* Info.plist */, + ); + path = ShoeGazeDemo; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + C3B000000000000000000014 /* ShoeGazeDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = C3B000000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeDemo" */; + buildPhases = ( + C3B000000000000000000011 /* Sources */, + C3B000000000000000000012 /* Frameworks */, + C3B000000000000000000013 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ShoeGazeDemo; + packageProductDependencies = ( + C3B00000000000000000001E /* LyrebirdShoeGaze */, + C3B00000000000000000001F /* LyrebirdShoeGazeUI */, + C3B000000000000000000023 /* Lyrebird */, + C3B000000000000000000025 /* LyrebirdUI */, + ); + productName = ShoeGazeDemo; + productReference = C3B000000000000000000004 /* ShoeGazeDemo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + C3B000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + C3B000000000000000000014 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = C3B000000000000000000018 /* Build configuration list for PBXProject "ShoeGazeDemo" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = C3B000000000000000000002; + packageReferences = ( + C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */, + C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */, + ); + productRefGroup = C3B000000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + C3B000000000000000000014 /* ShoeGazeDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + C3B000000000000000000013 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + C3B000000000000000000011 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C3B0000000000000000000C /* main.swift in Sources */, + C3B0000000000000000000D /* AppDelegate.swift in Sources */, + C3B0000000000000000000E /* DemoRootView.swift in Sources */, + C3B0000000000000000000F /* ShoeGazeDemoController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + C3B000000000000000000016 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CODE_SIGNING_REQUIRED = NO; + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = ShoeGazeDemo/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + C3B000000000000000000017 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CODE_SIGNING_REQUIRED = NO; + COMBINE_HIDPI_IMAGES = YES; + DEAD_CODE_STRIPPING = YES; + DEVELOPMENT_TEAM = ""; + ENABLE_HARDENED_RUNTIME = YES; + INFOPLIST_FILE = ShoeGazeDemo/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 15.0; + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + C3B000000000000000000019 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + C3B00000000000000000001A /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + C3B000000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C3B000000000000000000016 /* Debug */, + C3B000000000000000000017 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C3B000000000000000000018 /* Build configuration list for PBXProject "ShoeGazeDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C3B000000000000000000019 /* Debug */, + C3B00000000000000000001A /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCRemoteSwiftPackageReference section */ + C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.2.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + C3B00000000000000000001E /* LyrebirdShoeGaze */ = { + isa = XCSwiftPackageProductDependency; + package = C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */; + productName = LyrebirdShoeGaze; + }; + C3B00000000000000000001F /* LyrebirdShoeGazeUI */ = { + isa = XCSwiftPackageProductDependency; + package = C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */; + productName = LyrebirdShoeGazeUI; + }; + C3B000000000000000000023 /* Lyrebird */ = { + isa = XCSwiftPackageProductDependency; + package = C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */; + productName = Lyrebird; + }; + C3B000000000000000000025 /* LyrebirdUI */ = { + isa = XCSwiftPackageProductDependency; + package = C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */; + productName = LyrebirdUI; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = C3B000000000000000000001 /* Project object */; +} diff --git a/Demo/ShoeGazeDemo.xcodeproj/xcshareddata/xcschemes/ShoeGazeDemo.xcscheme b/Demo/ShoeGazeDemo.xcodeproj/xcshareddata/xcschemes/ShoeGazeDemo.xcscheme new file mode 100644 index 0000000..b787f7a --- /dev/null +++ b/Demo/ShoeGazeDemo.xcodeproj/xcshareddata/xcschemes/ShoeGazeDemo.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demo/ShoeGazeDemo/AppDelegate.swift b/Demo/ShoeGazeDemo/AppDelegate.swift new file mode 100644 index 0000000..a74af91 --- /dev/null +++ b/Demo/ShoeGazeDemo/AppDelegate.swift @@ -0,0 +1,147 @@ +// AppDelegate.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import AppKit +import LyrebirdSynth +import LyrebirdUI +import LyrebirdShoeGaze +import LyrebirdShoeGazeUI + +/// Application delegate for the ShoeGaze demo. +/// +/// Creates a `SynthesisEngine`, a `ShoeGazeDemoController` (which builds the default +/// `.boards` showcase automatically), and opens a `LyrebirdWindow` hosting `DemoRootView`. +/// +/// The engine is **not** started automatically. The user clicks Start in `DemoRootView`'s +/// toolbar (or presses Stop to halt audio). On application termination, `stop()` is called +/// to release Core Audio resources cleanly. +@MainActor +final class AppDelegate: NSObject, NSApplicationDelegate { + + // MARK: - Engine configuration constants + + private static let blockSize: Int = 512 + private static let sampleRate: Double = 48_000.0 + private static let outputChannels: Int = 2 + private static let inputChannels: Int = 6 + private static let numAudioBuses: Int = 256 + + // MARK: - Window geometry constants + + private static let windowWidth: CGFloat = 1_100 + private static let windowHeight: CGFloat = 640 + + // MARK: - Owned objects + + private let controller: ShoeGazeDemoController + private let window: LyrebirdWindow + + /// The Mute menu item, retained so `validateMenuItem(_:)` can update its checkmark. + private var muteMenuItem: NSMenuItem? + + // MARK: - Init + + override init() { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: AppDelegate.blockSize, + sampleRate: AppDelegate.sampleRate, + numOutputChannels: AppDelegate.outputChannels, + numInputChannels: AppDelegate.inputChannels, + numAudioBuses: AppDelegate.numAudioBuses, + driver: CoreAudioDriver() + ) + + self.controller = ShoeGazeDemoController(engine: engine) + self.window = LyrebirdWindow( + title: "ShoeGaze — Lyrebird Guitar Pedalboard", + width: AppDelegate.windowWidth, + height: AppDelegate.windowHeight + ) + super.init() + } + + // MARK: - NSApplicationDelegate + + func applicationDidFinishLaunching(_ notification: Notification) { + installMainMenu() + let demoController: ShoeGazeDemoController = controller + window.open { + DemoRootView(controller: demoController) + } + } + + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + true + } + + func applicationWillTerminate(_ notification: Notification) { + controller.stop() + } + + // MARK: - Main menu + + /// Builds the app's menu bar: an application menu (About / Hide / Quit ⌘Q) and an + /// Audio menu (Mute ⌘M). Standard items route through the responder chain to + /// `NSApplication`; Mute targets this delegate. + private func installMainMenu() { + let appName: String = ProcessInfo.processInfo.processName + let mainMenu: NSMenu = NSMenu() + + // Application menu. + let appMenuItem: NSMenuItem = NSMenuItem() + mainMenu.addItem(appMenuItem) + let appMenu: NSMenu = NSMenu() + appMenuItem.submenu = appMenu + appMenu.addItem( + withTitle: "About \(appName)", + action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)), + keyEquivalent: "" + ) + appMenu.addItem(NSMenuItem.separator()) + appMenu.addItem( + withTitle: "Hide \(appName)", + action: #selector(NSApplication.hide(_:)), + keyEquivalent: "h" + ) + appMenu.addItem(NSMenuItem.separator()) + appMenu.addItem( + withTitle: "Quit \(appName)", + action: #selector(NSApplication.terminate(_:)), + keyEquivalent: "q" + ) + + // Audio menu. + let audioMenuItem: NSMenuItem = NSMenuItem() + mainMenu.addItem(audioMenuItem) + let audioMenu: NSMenu = NSMenu(title: "Audio") + audioMenuItem.submenu = audioMenu + let mute: NSMenuItem = NSMenuItem( + title: "Mute", + action: #selector(toggleMute(_:)), + keyEquivalent: "m" + ) + mute.target = self + audioMenu.addItem(mute) + muteMenuItem = mute + + NSApplication.shared.mainMenu = mainMenu + } + + /// Toggles audio output (mute). Bound to the Audio ▸ Mute menu item (⌘M). + @objc private func toggleMute(_ sender: Any?) { + controller.toggleMute() + } + + /// Shows a checkmark on the Mute item while audio is silenced (engine not running). + func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { + if menuItem == muteMenuItem { + menuItem.state = controller.isRunning ? .off : .on + } + return true + } +} +#endif diff --git a/Demo/ShoeGazeDemo/DemoRootView.swift b/Demo/ShoeGazeDemo/DemoRootView.swift new file mode 100644 index 0000000..4a40d78 --- /dev/null +++ b/Demo/ShoeGazeDemo/DemoRootView.swift @@ -0,0 +1,263 @@ +// DemoRootView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import SwiftUI +import LyrebirdSynth +import LyrebirdUI +import LyrebirdShoeGaze +import LyrebirdShoeGazeUI + +/// Root view for the ShoeGaze demo window. +/// +/// Presents a top toolbar with a mode picker, an input-source toggle, and a Start/Stop +/// transport button, followed by a content area that switches between four showcase +/// modes as the user selects them. +/// +/// Because `ShoeGazeDemoController` is `@Observable`, SwiftUI re-renders this view and +/// all its children whenever `controller.mode`, `controller.shoeGaze.boards`, +/// `controller.router`, `controller.parallelSection`, or `controller.isRunning` change — +/// including after a ``ShoeGazeDemoController/rebuild()`` that replaces `shoeGaze`. +/// +/// ## Mode showcases +/// +/// - `.boards` → `ShoeGazeView` — two boards, eight pedals, master gain per board. +/// - `.editor` → `BoardEditorView` — board + FlowLayout pedal area + version snapshots. +/// - `.parallel` → `ParallelSectionView` — splitter, two branch rows, merger (via board). +/// - `.router` → `ChainRouterView` — dual-board chain router with splitter + master. +struct DemoRootView: View { + + // MARK: - Layout constants + + private static let toolbarSpacing: CGFloat = 10 + private static let toolbarPadding: CGFloat = 12 + private static let contentPadding: CGFloat = 16 + private static let windowMinWidth: CGFloat = 1_100 + private static let windowMinHeight: CGFloat = 640 + /// Dark stage-floor background (warm almost-black). + private static let backgroundRed: Double = 0.08 + private static let backgroundGreen: Double = 0.07 + private static let backgroundBlue: Double = 0.06 + private static let dividerOpacity: Double = 0.15 + + // MARK: - Properties + + private let controller: ShoeGazeDemoController + + /// Bumped on each transport press so the buttons re-read `controller.isRunning` + /// (which derives from the non-observable engine). + @State private var transportTick: Bool = false + + // MARK: - Init + + /// Creates the root demo view bound to the given controller. + /// + /// - Parameter controller: The `ShoeGazeDemoController` that owns the engine, active + /// `ShoeGaze` session, and current mode. All toolbar actions dispatch through this. + init(controller: ShoeGazeDemoController) { + self.controller = controller + } + + // MARK: - Body + + var body: some View { + VStack(spacing: 0) { + toolbar + Divider() + .overlay(Color.white.opacity(DemoRootView.dividerOpacity)) + contentArea + .padding(DemoRootView.contentPadding) + } + .frame( + minWidth: DemoRootView.windowMinWidth, + minHeight: DemoRootView.windowMinHeight + ) + .background( + Color( + red: DemoRootView.backgroundRed, + green: DemoRootView.backgroundGreen, + blue: DemoRootView.backgroundBlue + ) + ) + } + + // MARK: - Toolbar + + /// Top toolbar: mode picker, input-source picker, transport, and CPU meter. + private var toolbar: some View { + HStack(spacing: DemoRootView.toolbarSpacing) { + modePicker + Spacer() + inputSourcePicker + // In Boards mode the pedalboard view (`ShoeGazeView`) supplies its own + // Start/Stop, so the board starts only when its own button is pressed. The + // other modes have no in-content transport, so show it here for them. + if controller.mode != .boards { + transportButtons + } + } + .padding(DemoRootView.toolbarPadding) + } + + /// Segmented picker for `DemoMode`. + /// + /// The selection binding's setter delegates to `controller.select(_:)` rather than + /// writing a `@State` directly, so the controller handles the mode switch and rebuild. + private var modePicker: some View { + let modeBinding: Binding = Binding( + get: { controller.mode }, + set: { controller.select($0) } + ) + return Picker("Mode", selection: modeBinding) { + ForEach(DemoMode.allCases) { demoMode in + Text(demoMode.title).tag(demoMode) + } + } + .pickerStyle(.segmented) + .frame(maxWidth: 380) + .foregroundStyle(Color.white) + } + + /// A `Binding` mapping the input Picker tag to `InputSource`. + /// + /// Tag `-1` = `.testLoop`; tags `0 ..< numInputChannels` = `.liveInput(channel:)`. + /// Setting the binding calls `controller.setInputSource(_:)`. + private var inputSourceBinding: Binding { + Binding( + get: { + switch controller.inputSource { + case .testLoop: + return -1 + case .liveInput(let channel): + return channel + } + }, + set: { newValue in + if newValue == -1 { + controller.setInputSource(.testLoop) + } else { + controller.setInputSource(.liveInput(channel: newValue)) + } + } + ) + } + + /// Picker listing "Test Loop" and one option per available hardware input channel. + /// + /// When `engine.numInputChannels == 0` only "Test Loop" is shown; the live options + /// are omitted so the picker never offers channels that do not exist. + private var inputSourcePicker: some View { + HStack(spacing: DemoRootView.toolbarSpacing) { + Text("Input:") + .font(.subheadline) + .foregroundStyle(Color.white.opacity(0.65)) + Picker("Input", selection: inputSourceBinding) { + Text("Test Loop").tag(-1) + ForEach(0.. + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSApplicationCategoryType + public.app-category.music + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHighResolutionCapable + + NSHumanReadableCopyright + Copyright © 2026 Realized Sound. All rights reserved. + NSMicrophoneUsageDescription + ShoeGazeDemo can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode. + NSPrincipalClass + NSApplication + + diff --git a/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift new file mode 100644 index 0000000..9d9682f --- /dev/null +++ b/Demo/ShoeGazeDemo/ShoeGazeDemoController.swift @@ -0,0 +1,274 @@ +// ShoeGazeDemoController.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import Observation +import LyrebirdSynth +import LyrebirdUI +import LyrebirdShoeGaze + +// MARK: - DemoMode + +/// The active showcase mode displayed in the demo window. +/// +/// Each case corresponds to one full-window showcase of a distinct ShoeGaze feature. +/// Switching modes tears down the current audio graph and rebuilds it fresh. +enum DemoMode: String, CaseIterable, Identifiable { + + /// Two full boards, each with four pedals (Board 1: Overdrive → Delay → Reverb → Modulation; + /// Board 2: Fuzz → Tremolo → Phaser → Compressor). + case boards = "Boards" + + /// A single board inside `BoardEditorView` with preset version snapshots pre-populated. + case editor = "Editor" + + /// A single board with a ``ParallelSection`` (Overdrive → split → Delay|Fuzz → merge → Reverb). + case parallel = "Parallel" + + /// A ``ChainRouter`` that splits one input across two independent boards (A: Overdrive + Delay; + /// B: Fuzz + Reverb) and recombines them through a shared master stage. + case router = "Router" + + var id: String { rawValue } + + /// Short human-readable title used in the mode picker. + var title: String { + switch self { + case .boards: return "Boards" + case .editor: return "Editor" + case .parallel: return "Parallel" + case .router: return "Router" + } + } +} + +// MARK: - ShoeGazeDemoController + +/// Main-actor observable controller that owns the engine and active ShoeGaze session. +/// +/// A single `ShoeGaze` instance plus optional `router` / `parallelSection` hold the +/// current showcase. Switching modes via ``select(_:)`` or changing the input source via +/// ``setInputSource(_:)`` calls ``rebuild()`` which: +/// +/// 1. Stops the engine if it is running. +/// 2. Calls `shoeGaze.teardown()` to remove all nodes and release all buses. +/// 3. Replaces `shoeGaze` with a fresh instance. +/// 4. Builds the new mode-specific graph. +/// 5. Restarts the engine if it was running before the rebuild. +/// +/// This guarantees the engine never holds stale references across mode switches. +@MainActor +@Observable +final class ShoeGazeDemoController { + + // MARK: - Public state + + /// The synthesis engine. Callers must not call `engine.start()` or `engine.stop()` + /// directly — use ``start()`` and ``stop()`` so `isRunning` stays consistent. + let engine: SynthesisEngine + + /// The active ShoeGaze session. Replaced on every ``rebuild()`` call. + private(set) var shoeGaze: ShoeGaze + + /// Non-nil only in `.router` mode, after ``buildRouter()`` succeeds. + private(set) var router: ChainRouter? + + /// Non-nil only in `.parallel` mode, after ``buildParallel()`` succeeds. + private(set) var parallelSection: ParallelSection? + + /// Stores named board snapshots for the `.editor` showcase. + let versionStore: BoardVersionStore = BoardVersionStore() + + /// Currently selected showcase mode. + private(set) var mode: DemoMode = .boards + + /// Current input source policy. + private(set) var inputSource: InputSource = .testLoop + + /// `true` while the engine is running. Derived from the engine (the single source + /// of truth) so it stays correct regardless of which control starts/stops it. + var isRunning: Bool { engine.isRunning } + + // MARK: - Init + + /// Creates a controller, builds the default `.boards` showcase, and does NOT start the engine. + /// + /// - Parameter engine: A pre-configured `SynthesisEngine` owned by the caller. The + /// engine must not be running when this initialiser is called. + init(engine: SynthesisEngine) { + self.engine = engine + self.shoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop) + buildBoards() + } + + // MARK: - Mode selection + + /// Switches to the given mode if different from the current one, triggering a full rebuild. + /// + /// - Parameter newMode: The showcase to activate. + func select(_ newMode: DemoMode) { + guard newMode != mode else { return } + mode = newMode + rebuild() + } + + // MARK: - Input source + + /// Changes the input source policy and triggers a full rebuild. + /// + /// - Parameter source: `.testLoop` for the built-in test signal or `.liveInput(channel:)` + /// for hardware microphone/instrument input on the given channel. + func setInputSource(_ source: InputSource) { + inputSource = source + rebuild() + } + + // MARK: - Transport + + /// Starts the engine. Updates ``isRunning`` on success; prints on failure. + func start() { + do { + try engine.start() + } catch { + print("[ShoeGazeDemoController] engine.start() failed: \(error)") + } + } + + /// Stops the engine and updates ``isRunning``. + func stop() { + engine.stop() + } + + /// Toggles audio output on/off (mute). Muting silences output by stopping the engine; + /// unmuting restarts it. `isRunning == false` is the "muted" (silent) state. + func toggleMute() { + if isRunning { + stop() + } else { + start() + } + } + + // MARK: - Rebuild + + /// Tears down the current session and rebuilds the active mode. + /// + /// The engine is stopped before teardown and restarted afterward if it was running, + /// satisfying the remove-before-release invariant documented on `ShoeGaze.teardown()`. + private func rebuild() { + let wasRunning: Bool = isRunning + if wasRunning { stop() } + + shoeGaze.teardown() + router = nil + parallelSection = nil + + shoeGaze = ShoeGaze(engine: engine, inputSource: inputSource) + + switch mode { + case .boards: buildBoards() + case .editor: buildEditor() + case .parallel: buildParallel() + case .router: buildRouter() + } + + if wasRunning { start() } + } + + // MARK: - Mode builders + + /// `.boards` — two full boards covering all eight pedal types. + /// + /// Board 1: Overdrive → Delay → Reverb → Modulation + /// Board 2: Fuzz → Tremolo → Phaser → Compressor + private func buildBoards() { + do { + let board1: PedalBoard = try shoeGaze.addBoard() + board1.label = "Board 1" + try board1.add(OverdrivePedal()) + try board1.add(DelayPedal()) + try board1.add(ReverbPedal()) + try board1.add(ModulationPedal()) + try shoeGaze.finalizeBoard(board1) + + let board2: PedalBoard = try shoeGaze.addBoard() + board2.label = "Board 2" + try board2.add(FuzzPedal()) + try board2.add(TremoloPedal()) + try board2.add(PhaserPedal()) + try board2.add(CompressorPedal()) + try shoeGaze.finalizeBoard(board2) + } catch { + print("[ShoeGazeDemoController] buildBoards failed: \(error)") + } + } + + /// `.editor` — one board inside `BoardEditorView` with two pre-captured versions. + /// + /// The pre-populated version entries ("Crunch" and "Clean Shimmer") ensure the + /// Versions menu is not empty when the showcase first appears. + private func buildEditor() { + do { + let board: PedalBoard = try shoeGaze.addBoard() + board.label = "Editor Board" + try board.add(OverdrivePedal()) + try board.add(FuzzPedal()) + try board.add(DelayPedal()) + try board.add(ReverbPedal()) + try shoeGaze.finalizeBoard(board) + + // Pre-populate two named snapshots so the Versions menu is immediately useful. + versionStore.capture(board, name: "Crunch") + versionStore.capture(board, name: "Clean Shimmer") + } catch { + print("[ShoeGazeDemoController] buildEditor failed: \(error)") + } + } + + /// `.parallel` — Overdrive → split(Delay | Fuzz) → merge → Reverb. + /// + /// Stores the `ParallelSection` in `parallelSection` so `DemoRootView` can display + /// `ParallelSectionView`. + private func buildParallel() { + do { + let board: PedalBoard = try shoeGaze.addBoard() + board.label = "Parallel Board" + try board.add(OverdrivePedal()) + + let section: ParallelSection = try board.split() + try section.branchA.add(DelayPedal()) + try section.branchB.add(FuzzPedal()) + try board.merge(section) + + try board.add(ReverbPedal()) + try shoeGaze.finalizeBoard(board) + + parallelSection = section + } catch { + print("[ShoeGazeDemoController] buildParallel failed: \(error)") + } + } + + /// `.router` — ChainRouter with two independent chains: A (Overdrive + Delay), + /// B (Fuzz + Reverb), merged through a shared master stage. + /// + /// Stores the `ChainRouter` in `router` so `DemoRootView` can display + /// `ChainRouterView`. + private func buildRouter() { + do { + let r: ChainRouter = try shoeGaze.makeChainRouter() + try r.addToA(OverdrivePedal()) + try r.addToA(DelayPedal()) + try r.addToB(FuzzPedal()) + try r.addToB(ReverbPedal()) + try r.finalize() + router = r + } catch { + print("[ShoeGazeDemoController] buildRouter failed: \(error)") + } + } +} +#endif diff --git a/Demo/ShoeGazeDemo/main.swift b/Demo/ShoeGazeDemo/main.swift new file mode 100644 index 0000000..e7205d2 --- /dev/null +++ b/Demo/ShoeGazeDemo/main.swift @@ -0,0 +1,24 @@ +// main.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import AppKit + +// Program entry runs on the main thread; assert main-actor isolation for the +// AppKit bootstrap rather than hopping asynchronously. `AppDelegate.init` builds +// `@MainActor` synthesizers and UI. +MainActor.assumeIsolated { + let app: NSApplication = NSApplication.shared + let delegate: AppDelegate = AppDelegate() + app.setActivationPolicy(.regular) + app.delegate = delegate + app.activate(ignoringOtherApps: true) + app.run() +} +#else +// The ShoeGaze demo is a macOS AppKit application and has no iOS entry point. +print("ShoeGazeDemo runs on macOS only.") +#endif diff --git a/Demo/ShoeGazeiOSDemo.xcodeproj/project.pbxproj b/Demo/ShoeGazeiOSDemo.xcodeproj/project.pbxproj new file mode 100644 index 0000000..471d9e7 --- /dev/null +++ b/Demo/ShoeGazeiOSDemo.xcodeproj/project.pbxproj @@ -0,0 +1,379 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + C3C000000000000000000009 /* ShoeGazeiOSDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */; }; + C3C00000000000000000000A /* ShoeGazeiOSDemoAppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */; }; + C3C00000000000000000000B /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001A /* LyrebirdShoeGaze */; }; + C3C00000000000000000000C /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001B /* LyrebirdShoeGazeUI */; }; + C3C00000000000000000000D /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001C /* LyrebirdUI */; }; + C3C00000000000000000001D /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001E /* Lyrebird */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + C3C000000000000000000004 /* ShoeGazeiOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeiOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + C3C000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeiOSDemoApp.swift; sourceTree = ""; }; + C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeiOSDemoAppModel.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + C3C00000000000000000000F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C3C00000000000000000000B /* LyrebirdShoeGaze in Frameworks */, + C3C00000000000000000000C /* LyrebirdShoeGazeUI in Frameworks */, + C3C00000000000000000000D /* LyrebirdUI in Frameworks */, + C3C00000000000000000001D /* Lyrebird in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + C3C000000000000000000002 = { + isa = PBXGroup; + children = ( + C3C000000000000000000005 /* ShoeGazeiOSDemo */, + C3C000000000000000000003 /* Products */, + ); + sourceTree = ""; + }; + C3C000000000000000000003 /* Products */ = { + isa = PBXGroup; + children = ( + C3C000000000000000000004 /* ShoeGazeiOSDemo.app */, + ); + name = Products; + sourceTree = ""; + }; + C3C000000000000000000005 /* ShoeGazeiOSDemo */ = { + isa = PBXGroup; + children = ( + C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */, + C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */, + C3C000000000000000000006 /* Info.plist */, + ); + path = ShoeGazeiOSDemo; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + C3C000000000000000000011 /* ShoeGazeiOSDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = C3C000000000000000000012 /* Build configuration list for PBXNativeTarget "ShoeGazeiOSDemo" */; + buildPhases = ( + C3C00000000000000000000E /* Sources */, + C3C00000000000000000000F /* Frameworks */, + C3C000000000000000000010 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = ShoeGazeiOSDemo; + packageProductDependencies = ( + C3C00000000000000000001A /* LyrebirdShoeGaze */, + C3C00000000000000000001B /* LyrebirdShoeGazeUI */, + C3C00000000000000000001C /* LyrebirdUI */, + C3C00000000000000000001E /* Lyrebird */, + ); + productName = ShoeGazeiOSDemo; + productReference = C3C000000000000000000004 /* ShoeGazeiOSDemo.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + C3C000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 2620; + TargetAttributes = { + C3C000000000000000000011 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = C3C000000000000000000015 /* Build configuration list for PBXProject "ShoeGazeiOSDemo" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = C3C000000000000000000002; + packageReferences = ( + C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */, + C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */, + ); + productRefGroup = C3C000000000000000000003 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + C3C000000000000000000011 /* ShoeGazeiOSDemo */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + C3C000000000000000000010 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + C3C00000000000000000000E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + C3C000000000000000000009 /* ShoeGazeiOSDemoApp.swift in Sources */, + C3C00000000000000000000A /* ShoeGazeiOSDemoAppModel.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + C3C000000000000000000013 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CODE_SIGNING_REQUIRED = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = ""; + INFOPLIST_FILE = ShoeGazeiOSDemo/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeiOSDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + C3C000000000000000000014 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CODE_SIGNING_REQUIRED = NO; + DEVELOPMENT_TEAM = ""; + INFOPLIST_FILE = ShoeGazeiOSDemo/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeiOSDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + C3C000000000000000000016 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + C3C000000000000000000017 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + C3C000000000000000000012 /* Build configuration list for PBXNativeTarget "ShoeGazeiOSDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C3C000000000000000000013 /* Debug */, + C3C000000000000000000014 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + C3C000000000000000000015 /* Build configuration list for PBXProject "ShoeGazeiOSDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + C3C000000000000000000016 /* Debug */, + C3C000000000000000000017 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCRemoteSwiftPackageReference section */ + C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 1.2.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + C3C00000000000000000001A /* LyrebirdShoeGaze */ = { + isa = XCSwiftPackageProductDependency; + package = C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */; + productName = LyrebirdShoeGaze; + }; + C3C00000000000000000001B /* LyrebirdShoeGazeUI */ = { + isa = XCSwiftPackageProductDependency; + package = C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */; + productName = LyrebirdShoeGazeUI; + }; + C3C00000000000000000001C /* LyrebirdUI */ = { + isa = XCSwiftPackageProductDependency; + package = C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */; + productName = LyrebirdUI; + }; + C3C00000000000000000001E /* Lyrebird */ = { + isa = XCSwiftPackageProductDependency; + package = C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */; + productName = Lyrebird; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = C3C000000000000000000001 /* Project object */; +} diff --git a/Demo/ShoeGazeiOSDemo.xcodeproj/xcshareddata/xcschemes/ShoeGazeiOSDemo.xcscheme b/Demo/ShoeGazeiOSDemo.xcodeproj/xcshareddata/xcschemes/ShoeGazeiOSDemo.xcscheme new file mode 100644 index 0000000..8d5b689 --- /dev/null +++ b/Demo/ShoeGazeiOSDemo.xcodeproj/xcshareddata/xcschemes/ShoeGazeiOSDemo.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Demo/ShoeGazeiOSDemo/Info.plist b/Demo/ShoeGazeiOSDemo/Info.plist new file mode 100644 index 0000000..dfec45c --- /dev/null +++ b/Demo/ShoeGazeiOSDemo/Info.plist @@ -0,0 +1,46 @@ + + + + + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + NSHumanReadableCopyright + Copyright © 2026 Realized Sound. All rights reserved. + NSMicrophoneUsageDescription + ShoeGazeiOSDemo can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode. + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + + UILaunchScreen + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoApp.swift b/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoApp.swift new file mode 100644 index 0000000..a254966 --- /dev/null +++ b/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoApp.swift @@ -0,0 +1,33 @@ +// ShoeGazeiOSDemoApp.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGazeUI + +/// iOS entry point for the ShoeGaze in-repo demo. +/// +/// Holds the `ShoeGazeiOSDemoAppModel` as `@State` so it is created once and +/// owned for the lifetime of the app. The audio engine is **not** started +/// automatically — the user presses Start in the pedalboard (`ShoeGazeView`) to +/// begin audio. The engine is stopped when the view disappears. +@main +struct ShoeGazeiOSDemoApp: App { + + @State private var model: ShoeGazeiOSDemoAppModel = ShoeGazeiOSDemoAppModel() + + var body: some Scene { + WindowGroup { + NavigationStack { + ScrollView { + ShoeGazeView(shoeGaze: model.shoeGaze) + .padding(.horizontal, 12) + } + .navigationTitle("ShoeGaze") + } + .onDisappear { model.stop() } + } + } +} diff --git a/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoAppModel.swift b/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoAppModel.swift new file mode 100644 index 0000000..d7ceba5 --- /dev/null +++ b/Demo/ShoeGazeiOSDemo/ShoeGazeiOSDemoAppModel.swift @@ -0,0 +1,97 @@ +// ShoeGazeiOSDemoAppModel.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AVFoundation +import Observation +import LyrebirdSynth +import LyrebirdShoeGaze + +/// Observable model that owns the `SynthesisEngine` and `ShoeGaze` session for +/// the ShoeGaze iOS demo. +/// +/// The engine is not started automatically — the pedalboard's Start button +/// (`ShoeGazeView`) drives `engine.start()`. `stop()` is called from `.onDisappear` +/// to release audio resources when the view goes away. +/// +/// `AVAudioSession` is activated at init so the hardware sample rate is known +/// before the engine is constructed — iOS devices typically lock to 48 000 Hz +/// regardless of the preferred rate, and querying the session after activation +/// avoids pitch and timing errors. +/// +/// The default board (Overdrive → Delay → Reverb → Modulation) uses `.testLoop` +/// as the input source, so no microphone permission is required to run the demo. +/// Switch to `.liveInput(channel: 0)` and set `numInputChannels: 1` in the +/// engine init to route hardware microphone or instrument input through the board. +@Observable +@MainActor +final class ShoeGazeiOSDemoAppModel { + + // MARK: - Engine configuration constants + + private static let blockSize: Int = 512 + private static let outputChannels: Int = 2 + private static let numAudioBuses: Int = 256 + + // MARK: - Owned objects + + /// The active ShoeGaze pedalboard session. + private(set) var shoeGaze: ShoeGaze + + private let engine: SynthesisEngine + + // MARK: - Init + + init() { + // Activate the session before querying `sampleRate` so the hardware rate + // is reported correctly (iOS locks to 48 000 Hz on most devices). + let session: AVAudioSession = AVAudioSession.sharedInstance() + try? session.setCategory(.playAndRecord, + mode: .default, + options: [.defaultToSpeaker, .allowBluetoothHFP]) + try? session.setActive(true) + let sampleRate: Double = session.sampleRate + + let eng: SynthesisEngine = SynthesisEngine( + blockSize: ShoeGazeiOSDemoAppModel.blockSize, + sampleRate: sampleRate, + numOutputChannels: ShoeGazeiOSDemoAppModel.outputChannels, + numInputChannels: 0, + numAudioBuses: ShoeGazeiOSDemoAppModel.numAudioBuses, + driver: iOSAudioDriver() + ) + self.engine = eng + self.shoeGaze = ShoeGaze(engine: eng) + + do { + let board: PedalBoard = try shoeGaze.addBoard() + board.label = "Demo Board" + try board.add(OverdrivePedal()) + try board.add(DelayPedal()) + try board.add(ReverbPedal()) + try board.add(ModulationPedal()) + try shoeGaze.finalizeBoard(board) + } catch { + print("[ShoeGazeiOSDemo] board build failed: \(error)") + } + } + + // MARK: - Transport + + /// Starts the audio engine. Not called automatically — the pedalboard's Start + /// button drives `engine.start()`; this is here for callers that want to start it. + func start() { + do { + try engine.start() + } catch { + print("[ShoeGazeiOSDemo] engine.start() failed: \(error)") + } + } + + /// Stops the audio engine. Call from `.onDisappear`. + func stop() { + engine.stop() + } +} diff --git a/Package.resolved b/Package.resolved new file mode 100644 index 0000000..36b4d97 --- /dev/null +++ b/Package.resolved @@ -0,0 +1,33 @@ +{ + "originHash" : "34b5d439cb0aa8023e4d055198b63d5bcb210c30e370037d88c4bb2b45c9e486", + "pins" : [ + { + "identity" : "linenoise-swift", + "kind" : "remoteSourceControl", + "location" : "https://github.com/andybest/linenoise-swift", + "state" : { + "revision" : "afc897c02b030af7333105c4fedcd843a8339238", + "version" : "0.0.3" + } + }, + { + "identity" : "lyrebird", + "kind" : "remoteSourceControl", + "location" : "https://realizedsound.mooo.com/josh/Lyrebird", + "state" : { + "revision" : "73191c958f0d6e355897717b34317e40fdf158f9", + "version" : "1.1.1" + } + }, + { + "identity" : "nimble", + "kind" : "remoteSourceControl", + "location" : "https://github.com/Quick/Nimble.git", + "state" : { + "revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0", + "version" : "7.3.4" + } + } + ], + "version" : 3 +} diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..0f743b5 --- /dev/null +++ b/Package.swift @@ -0,0 +1,60 @@ +// swift-tools-version: 6.0 +// ShoeGaze — a standalone guitar-pedalboard sample project for Lyrebird. +// +// Depends on the published Lyrebird package by URL. Two products: +// • LyrebirdShoeGaze — core pedal/board framework (no SwiftUI). +// • LyrebirdShoeGazeUI — SwiftUI pedalboard views (knobs + bypass toggle). +// +// Linkage note: both targets link the *static* Lyrebird products (`Lyrebird`, +// `LyrebirdUI`). SwiftPM resolves the shared `LyrebirdSynth` target once, so +// there is a single copy of the module in any consumer — no ObjC class +// double-registration. The dynamic-product dance used by `LiveCompile/` is only +// required for runtime dylib hot-swap, which ShoeGaze does not do. +// +// The demo app lives at Demo/ShoeGazeDemo.xcodeproj — open ShoeGaze.xcworkspace +// in Xcode and run the ShoeGazeDemo scheme to build it. +import PackageDescription + +let package = Package( + name: "LyrebirdShoeGaze", + platforms: [.macOS(.v15), .iOS(.v18)], + products: [ + .library(name: "LyrebirdShoeGaze", targets: ["LyrebirdShoeGaze"]), + .library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]), + ], + dependencies: [ + .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.0"), + ], + targets: [ + // The core target depends on LyrebirdUI as well as the synthesis core: + // pedals expose their knobs as `@UIParam`, whose projected `UIParamNode` + // (the type `ParameterKnob` binds to) lives in LyrebirdUI. Importing + // LyrebirdUI here does not pull SwiftUI into ShoeGaze's own sources — + // it only makes the `@UIParam` wrapper and `UIParamNode` visible. + .target( + name: "LyrebirdShoeGaze", + dependencies: [ + .product(name: "Lyrebird", package: "Lyrebird"), + .product(name: "LyrebirdUI", package: "Lyrebird"), + ], + path: "Sources/LyrebirdShoeGaze" + ), + .target( + name: "LyrebirdShoeGazeUI", + dependencies: [ + "LyrebirdShoeGaze", + .product(name: "LyrebirdUI", package: "Lyrebird"), + ], + path: "Sources/LyrebirdShoeGazeUI" + ), + .testTarget( + name: "LyrebirdShoeGazeTests", + dependencies: [ + "LyrebirdShoeGaze", + .product(name: "Lyrebird", package: "Lyrebird"), + .product(name: "LyrebirdUI", package: "Lyrebird"), + ], + path: "Tests/LyrebirdShoeGazeTests" + ), + ] +) diff --git a/ShoeGaze.xcworkspace/contents.xcworkspacedata b/ShoeGaze.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..c7c9596 --- /dev/null +++ b/ShoeGaze.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift b/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift new file mode 100644 index 0000000..c3ebccc --- /dev/null +++ b/Sources/LyrebirdShoeGaze/BoardOutputMaster.swift @@ -0,0 +1,68 @@ +// BoardOutputMaster.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Internal synthesizer that reads a pedalboard's output bus, applies a master +/// gain, pans it to stereo, and writes to hardware output buses 0 (left) and 1 (right). +/// +/// Ordered `.after` the last pedal in the board's chain so it evaluates after the +/// full signal chain is complete. +final class BoardOutputMaster: SynthesizerBase { + + // MARK: - Parameters + + /// Master output gain in [0, 1]. The user-facing volume knob; applied directly. + @UIParam var masterGain: Double = 0.8 + + /// Board-select gain in [0, 1]. `1` = this board is audible, `0` = silenced. + /// Driven by `ShoeGaze.selectBoard(_:crossfadeSeconds:)`; lagged by `crossfadeTime` + /// so switching boards crossfades instead of clicking. Defaults to `1` (audible). + @UIParam var selectGain: Double = 1.0 + + /// Lag time in seconds for `selectGain` transitions — the board crossfade duration. + /// Defaults to a short 20 ms so normal use is click-free; raise it for a slow crossfade. + @UIParam var crossfadeTime: Double = 0.02 + + /// The live `UIParamNode` backing `masterGain`, exposed so the board (and its UI) + /// can bind a master-volume knob to this stage. + var gainNode: UIParamNode { $masterGain } + + /// The live `UIParamNode` backing `selectGain` (board-select crossfade gain). + var selectGainNode: UIParamNode { $selectGain } + + /// The live `UIParamNode` backing `crossfadeTime` (board crossfade seconds). + var crossfadeTimeNode: UIParamNode { $crossfadeTime } + + // MARK: - Routing + + private let boardOutputBusIndex: Int + + // MARK: - Constants + + /// Pan position for the board in the stereo field. Centre = 0.0. + private let stereoPan: Double = 0.0 + + // MARK: - Init + + init(boardOutputBusIndex: Int) { + self.boardOutputBusIndex = boardOutputBusIndex + super.init() + } + + // MARK: - Build + + override func build() { + let boardOut: In.Audio = input(bus: boardOutputBusIndex) + // Lag the board-select gain so switching boards crossfades over `crossfadeTime` + // seconds rather than clicking. The user master-gain knob is applied directly. + let smoothedSelect: Lag.Control = Lag.Control(input: $selectGain, time: $crossfadeTime) + let gained: any ValidGeneratorInput = (boardOut * smoothedSelect) * $masterGain + // Pan2 spreads the mono pedalboard output to stereo hardware buses 0 + 1. + output(bus: 0, source: Pan2(input: gained, pan: stereoPan)) + } +} diff --git a/Sources/LyrebirdShoeGaze/Input/HardwareInputPassThrough.swift b/Sources/LyrebirdShoeGaze/Input/HardwareInputPassThrough.swift new file mode 100644 index 0000000..9c66bd2 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Input/HardwareInputPassThrough.swift @@ -0,0 +1,48 @@ +// HardwareInputPassThrough.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Internal synthesizer that copies one hardware input bus to a board head bus. +/// +/// When `ShoeGaze` is configured with `.liveInput`, a `HardwareInputPassThrough` is +/// added to the engine before the first pedal. It reads the hardware input bus at +/// `inputBusIndex` and writes its samples to the board's head bus at `outputBusIndex`. +/// This ensures the first pedal reads from a user-space bus that the board controls, +/// rather than from the raw hardware input bus directly. +/// +/// - Note: The synthesizer must be removed from the engine before the board's +/// `teardown()` releases the head bus back to the allocator. +final class HardwareInputPassThrough: SynthesizerBase { + + // MARK: - Routing + + /// Index of the hardware input bus to read from (typically `engine.numOutputChannels`). + private let inputBusIndex: Int + + /// Index of the board head bus to write to. + private let outputBusIndex: Int + + // MARK: - Init + + /// Creates a pass-through that copies `inputBusIndex` to `outputBusIndex`. + /// + /// - Parameters: + /// - inputBusIndex: Hardware input bus index to read from. + /// Typically `engine.numOutputChannels` for the first input channel. + /// - outputBusIndex: Board head bus index to write to. + init(inputBusIndex: Int, outputBusIndex: Int) { + self.inputBusIndex = inputBusIndex + self.outputBusIndex = outputBusIndex + super.init() + } + + // MARK: - Build + + override func build() { + output(bus: outputBusIndex, source: input(bus: inputBusIndex)) + } +} diff --git a/Sources/LyrebirdShoeGaze/Input/InputSource.swift b/Sources/LyrebirdShoeGaze/Input/InputSource.swift new file mode 100644 index 0000000..4bedcb9 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Input/InputSource.swift @@ -0,0 +1,52 @@ +// InputSource.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth + +/// Selects how the pedalboard's head bus is fed with audio. +/// +/// - `.testLoop`: A synthesized test tone (`TestLoopSource`) writes to the head bus. +/// Suitable for testing the pedalboard with no hardware connected. +/// - `.liveInput(channel:)`: A hardware input channel feeds the head bus. `channel` is +/// the zero-based hardware input channel index (`0` = first input). It maps to engine +/// audio-bus index `numOutputChannels + channel` (hardware input buses follow the +/// output buses). Requires the engine to be created with `numInputChannels > channel`. +public enum InputSource { + /// Synthesized test signal — no hardware required. + case testLoop + /// Live hardware input from the given zero-based input channel. The engine must be + /// created with `numInputChannels > channel`. + case liveInput(channel: Int) +} + +/// Validates a `.liveInput` channel against the engine and returns the engine audio-bus +/// index of that hardware input channel. +/// +/// Hardware input buses occupy indices `numOutputChannels ..< (numOutputChannels + +/// numInputChannels)`, so input channel `channel` lives at `numOutputChannels + channel`. +/// +/// - Parameters: +/// - channel: Zero-based hardware input channel index. +/// - engine: The engine whose bus layout is queried. +/// - Returns: The audio-bus index to read the requested input channel from. +/// - Throws: +/// - `ShoeGazeError.liveInputRequiresInputChannels` if the engine has no input channels. +/// - `ShoeGazeError.inputChannelOutOfRange` if `channel` is negative or `>= numInputChannels`. +internal func liveInputBusIndex( + channel: Int, + engine: SynthesisEngine +) throws -> Int { + guard engine.numInputChannels > 0 else { + throw ShoeGazeError.liveInputRequiresInputChannels + } + guard channel >= 0, channel < engine.numInputChannels else { + throw ShoeGazeError.inputChannelOutOfRange( + requested: channel, + available: engine.numInputChannels + ) + } + return engine.numOutputChannels + channel +} diff --git a/Sources/LyrebirdShoeGaze/Input/TestLoopSource.swift b/Sources/LyrebirdShoeGaze/Input/TestLoopSource.swift new file mode 100644 index 0000000..2395653 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Input/TestLoopSource.swift @@ -0,0 +1,76 @@ +// TestLoopSource.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A synthesized test signal source that writes to a target audio bus. +/// +/// Produces two detuned sine oscillators at 110 Hz and 165 Hz — an approximation +/// of a guitar's A2 and E3 strings — with a slow amplitude envelope driven by a +/// low-frequency sine LFO. This makes the board audible immediately without any +/// hardware connection. +/// +/// The output is written to `targetBus` so downstream pedals read it from that bus. +/// `TestLoopSource` should be added to the engine **before** the first pedal in the +/// chain to ensure signal-order correctness (source evaluates first). +/// +/// ## Parameters +/// +/// - Parameters: +/// - targetBus: Audio bus index to write the test signal to. Typically the +/// pedalboard's head bus index. +/// - amplitude: Output amplitude in [0, 1]. Defaults to `0.25`. +public final class TestLoopSource: SynthesizerBase { + + // MARK: - Parameters + + /// Output amplitude in [0, 1]. + @UIParam public var amplitude: Double = 0.25 + + // MARK: - Constants + + /// Frequency of the first oscillator in Hz (approximates guitar A2 string). + private let freqA: Double = 110.0 + + /// Frequency of the second oscillator in Hz (approximates guitar E3 string, slightly detuned). + private let freqB: Double = 165.75 + + /// LFO frequency in Hz for amplitude modulation (slow tremolo). + private let lfoFreq: Double = 0.5 + + /// LFO depth as a fraction of base amplitude [0, 1]. + private let lfoDepth: Double = 0.3 + + /// Gain for each individual oscillator before summing. Two oscillators × 0.5 = unity. + private let oscGain: Double = 0.5 + + // MARK: - Routing + + /// The bus this source writes its output to. + private let targetBus: Int + + // MARK: - Init + + /// Creates a test loop source that writes to `targetBus`. + /// + /// - Parameters: + /// - targetBus: Audio bus index to write the synthesized test signal to. + public init(targetBus: Int) { + self.targetBus = targetBus + super.init() + } + + // MARK: - Build + + public override func build() { + let oscA: OscSin.Audio = OscSin.Audio(freq: freqA, mul: oscGain) + let oscB: OscSin.Audio = OscSin.Audio(freq: freqB, phase: 0.25, mul: oscGain) + let lfo: OscSin.Audio = OscSin.Audio(freq: lfoFreq, mul: lfoDepth, add: 1.0 - lfoDepth) + let signal: any ValidGeneratorInput = (oscA + oscB) * lfo * $amplitude + output(bus: targetBus, source: signal) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedal.swift b/Sources/LyrebirdShoeGaze/Pedal.swift new file mode 100644 index 0000000..7fccc19 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedal.swift @@ -0,0 +1,179 @@ +// Pedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Abstract base class for a single-signal-chain guitar pedal effect. +/// +/// Each pedal reads from `inputBus`, applies `effect(_:)` (implemented by subclasses), +/// then crossfades wet/dry and bypass before writing to `outputBus`. +/// +/// ## Signal chain +/// +/// ``` +/// inputBus → dry → effect(_:) → wet +/// ↕ mix (equal-power crossfade) +/// blended +/// ↕ bypass (lagged equal-power crossfade with dry) +/// switched → × level → outputBus +/// ``` +/// +/// ## Subclassing +/// +/// Override `effect(_:)` to return a mono processed signal. The base `build()` handles +/// wet/dry mixing, smooth bypass switching, and output gain automatically. +/// +/// ## Parameters +/// +/// - `mix`: Wet/dry blend in `[0, 1]`. `0` = fully dry, `1` = fully wet. +/// - `bypass`: Bypass state. `0` = engaged (effect active), `1` = bypassed (pure dry). +/// Transitions are smoothed with a 20 ms lag to avoid clicks. +/// - `level`: Output gain as a linear multiplier. `1.0` = unity gain. +/// +/// - Parameters: +/// - mix: Wet/dry ratio in [0, 1]. `0` = dry only, `1` = wet only. Defaults to `1.0`. +/// - bypass: Bypass flag. `0` = engaged, `1` = bypassed. Defaults to `0.0`. +/// - level: Output gain multiplier in [0, ∞). Defaults to `1.0`. +open class Pedal: SynthesizerBase { + + // MARK: - Parameters + + /// Wet/dry blend ratio in [0, 1]. `0` = dry only, `1` = wet only. + @UIParam public var mix: Double = 1.0 + + /// Bypass state. `0` = engaged (effect active), `1` = bypassed (dry signal only). + /// Transitions are smoothed by `bypassLagTime` seconds to prevent clicks. + @UIParam public var bypass: Double = 0.0 + + /// Output gain as a linear multiplier. `1.0` = unity gain. + @UIParam public var level: Double = 1.0 + + // MARK: - Sample rate + + /// Engine sample rate, injected by `PedalBoard.add(_:)` before the pedal is added + /// to the engine; effect stages that need the sample rate read this. Defaults to a + /// safe 48 kHz fallback. + public var sampleRate: Double = 48000.0 + + // MARK: - Identity / routing + + /// Human-readable name for the pedal (e.g. "Overdrive", "Delay"). + public let displayName: String + + /// Index of the audio bus from which this pedal reads its dry input. + public internal(set) var inputBus: Int + + /// Index of the audio bus to which this pedal writes its output. + public internal(set) var outputBus: Int + + // MARK: - Constants + + /// Lag time constant in seconds (60 dB convergence) for the bypass crossfade. + /// Smooths engaged ↔ bypassed transitions to prevent audible clicks. + private let bypassLagTime: Double = 0.02 + + // Bipolar-span constant used to remap a [0, 1] value to [-1, +1] + // for CrossFade's equal-power pan parameter. + private let bipolarSpan: Double = 2.0 + private let bipolarOffset: Double = 1.0 + + // MARK: - Init + + /// Creates a pedal with a display name and initial bus assignments. + /// + /// Bus assignments are updated by `PedalBoard.add(_:)` before `engine.add`; the + /// defaults here are only placeholders. Always configure via the board. + /// + /// - Parameters: + /// - name: Human-readable pedal name shown in UI and debug output. + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + /// - initialMix: Initial wet/dry blend in `[0, 1]`. Time-based pedals (delay, + /// reverb, modulation) pass a partial blend so the dry signal stays present; + /// gain-shaping pedals (overdrive) leave the default fully-wet `1.0`. + public init( + name: String, + inputBus: Int = 0, + outputBus: Int = 0, + initialMix: Double = 1.0 + ) { + self.displayName = name + self.inputBus = inputBus + self.outputBus = outputBus + super.init() + self.mix = initialMix + } + + // MARK: - UI knob descriptors + + /// Effect-specific knobs for this pedal, listed before the common knobs in the UI. + /// + /// Override in subclasses to publish each `@UIParam` effect parameter with its + /// display label and value range. Defaults to an empty list. + open var effectKnobs: [PedalKnob] { + [] + } + + /// All knobs a generic UI should render for this pedal: effect-specific knobs + /// first, then the common `mix` and `level` knobs. The `bypass` parameter is + /// surfaced separately as a header toggle, not as a knob. + public var knobs: [PedalKnob] { + effectKnobs + [ + PedalKnob(label: "Mix", node: $mix, range: 0.0 ... 1.0), + PedalKnob(label: "Level", node: $level, range: 0.0 ... 1.0), + ] + } + + // MARK: - Subclass hook + + /// Returns the processed (wet) mono signal for this pedal. + /// + /// The default implementation is a pass-through — override in subclasses to apply + /// the desired effect. The return value must be mono. + /// + /// - Parameter dry: The dry signal read from `inputBus`. + /// - Returns: The wet processed signal (mono). + open func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + dry + } + + // MARK: - Build + + /// Builds the signal graph: dry → effect → wet/dry blend → bypass switch → output. + public override func build() { + let dry: In.Audio = input(bus: inputBus) + let wet: any ValidGeneratorInput = effect(dry) + + // Map mix [0, 1] → pan [-1, +1] for CrossFade (−1 = full inA/dry, +1 = full inB/wet). + let mixPan: any ValidGeneratorInput = ($mix * bipolarSpan) - bipolarOffset + + // Equal-power crossfade between dry and wet signal. + let blended: CrossFade.Audio = CrossFade.Audio( + inA: dry, + inB: wet, + pan: mixPan + ) + + // Smooth bypass transitions with a 20 ms lag to prevent clicks. + let bypassLagged: Lag.Control = Lag.Control( + input: $bypass, + time: bypassLagTime + ) + + // Map bypass [0, 1] → pan [-1, +1]: −1 = blended (engaged), +1 = dry (bypassed). + let bypassPan: any ValidGeneratorInput = (bypassLagged * bipolarSpan) - bipolarOffset + + // Equal-power crossfade: engaged → blended; bypassed → dry. + let switched: CrossFade.Audio = CrossFade.Audio( + inA: blended, + inB: dry, + pan: bypassPan + ) + + output(bus: outputBus, source: switched * $level) + } +} diff --git a/Sources/LyrebirdShoeGaze/PedalBoard.swift b/Sources/LyrebirdShoeGaze/PedalBoard.swift new file mode 100644 index 0000000..964f5cc --- /dev/null +++ b/Sources/LyrebirdShoeGaze/PedalBoard.swift @@ -0,0 +1,352 @@ +// PedalBoard.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A linear signal chain of `Pedal` instances sharing a dedicated mono bus path, with +/// optional parallel sections created via `split()` and `merge()`. +/// +/// `PedalBoard` manages bus allocation and the engine node-tree insertion order +/// so that signal flows: +/// +/// ``` +/// headBus → pedal[0] → pedal[1] → … → pedal[N-1] → outputBus (tail) +/// ``` +/// +/// Parallel branches can be inserted at any point in the chain: +/// +/// ``` +/// headBus → pre-pedals → Splitter → branchA pedals ─┐ +/// → branchB pedals ─┤ +/// Merger → post-pedals → outputBus +/// ``` +/// +/// ## Evaluation order +/// +/// Lyrebird evaluates the node tree top-to-bottom. Every node is inserted `.after` its +/// predecessor so signal flows correctly: +/// +/// ``` +/// headInputNode → pedal[0] → … → Splitter → branchA[0] → … → branchB[0] → … → Merger → … +/// ``` +/// +/// Both branch chains share a single tail tracking pointer so all branch pedals appear in +/// a flat linear sequence in the tree, regardless of which branch the caller adds pedals +/// to first. The merger is always inserted after the shared tail — i.e. after the last pedal +/// added across either branch — ensuring all branch pedals have evaluated before the merge. +/// +/// ## Bus allocation +/// +/// - One mono bus is allocated for the board head (`headBus`). +/// - Each `add(_:)` call allocates a new mono bus for the pedal's output. +/// - `split()` allocates two branch-input buses (one per branch) and one bus per pedal +/// added to each branch. +/// - `merge()` allocates one post-merge output bus. +/// - Hardware output buses (indices 0.. ParallelSection { + let preBus: AudioBus = outputBus + + let branchAInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let branchBInBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + // Branch input buses are tracked (and released) by each BranchChain, not here. + // Do not append to allocatedBuses to avoid a double-release on teardown. + + let splitter: Splitter = Splitter( + inputBus: preBus.index, + outputBusA: branchAInBus.index, + outputBusB: branchBInBus.index + ) + + if let previous: any Synthesizer = lastNode { + try engine.add(splitter, position: .after(previous)) + } else if let head: any Synthesizer = headInputNode { + try engine.add(splitter, position: .after(head)) + } else { + try engine.add(splitter) + } + + routingNodes.append(splitter) + lastNode = splitter + + // Both branch chains share a single tail pointer so their pedals form a flat linear + // sequence in the node tree rather than two sibling sub-trees both rooted at the + // splitter. This guarantees all branch pedals evaluate before the merger regardless + // of whether the caller adds pedals to branchA first, branchB first, or interleaved. + let tail: SharedTail = SharedTail(node: splitter) + + let chainA: BranchChain = BranchChain( + engine: engine, + inputBus: branchAInBus, + sampleRate: engine.sampleRate, + sharedTail: tail + ) + let chainB: BranchChain = BranchChain( + engine: engine, + inputBus: branchBInBus, + sampleRate: engine.sampleRate, + sharedTail: tail + ) + branchChains.append(chainA) + branchChains.append(chainB) + + return ParallelSection(splitter: splitter, branchA: chainA, branchB: chainB, sharedTail: tail) + } + + /// Combines the two branches of a ``ParallelSection`` back into the main board chain. + /// + /// Creates a ``Merger`` that sums the tail buses of both branches into a new output bus. + /// The merger is inserted after the section's shared tail node — the last node inserted + /// across either branch. Because both branch chains share a single ``SharedTail`` pointer, + /// this is always the most recently added pedal from either branch, guaranteeing all branch + /// pedals have evaluated before the merger reads their output buses. + /// + /// After `merge(_:)` returns, subsequent `board.add(_:)` calls chain after the merger. + /// + /// - Parameter section: A ``ParallelSection`` returned by ``split()`` with pedals added to + /// each branch. Passing the same section twice or a section from a different board is + /// undefined behaviour. + /// - Throws: + /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for the post-merge bus. + /// - `EngineAddError` if the engine rejects the merger add. + public func merge(_ section: ParallelSection) throws { + let branchAOut: Int = section.branchA.tailBusIndex + let branchBOut: Int = section.branchB.tailBusIndex + + let postBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + allocatedBuses.append(postBus) + + let merger: Merger = Merger( + inputBusA: branchAOut, + inputBusB: branchBOut, + outputBus: postBus.index + ) + + // Insert merger after the shared tail — the last node inserted across either branch. + // Because both branch chains share a single `SharedTail` pointer, `sharedTail.node` + // is always the node that was most recently added to the tree (from either branch). + // This guarantees all branch pedals have written their output buses before the merger + // reads them, regardless of which branch the caller added pedals to last. + let mergerPredecessor: any Synthesizer = section.sharedTail.node + try engine.add(merger, position: .after(mergerPredecessor)) + + routingNodes.append(merger) + lastNode = merger + outputBus = postBus + } + + // MARK: - Teardown + + /// Removes all pedals, routing nodes, and branch chains from the engine and releases + /// all allocated buses. + /// + /// Removal order follows the remove-before-release invariant: + /// + /// 1. Remove main-chain pedals from the engine. + /// 2. Remove all routing nodes (splitters, mergers) — these write branch buses that + /// the next step releases, so they must be dequeued first. + /// 3. `BranchChain.teardown()` for each branch — removes branch pedals and releases + /// branch buses (safe because the splitter/merger writers are already dequeued). + /// 4. Release board-owned buses. + /// + /// - Important: Call only after the engine has been stopped, or accept one block + /// of glitch on a still-running engine. `engine.remove(_:)` only enqueues removal; + /// the actual dequeue happens on the next render block. Releasing buses immediately + /// after enqueue means a still-running engine could write to a reallocated bus for + /// one block. The buses are pooled (not freed), so worst case is a transient glitch, + /// not a crash. Stop the engine first to avoid this. + /// + /// After calling this method the `PedalBoard` should not be reused. + public func teardown() { + // Step 1: Remove main-chain pedals. + for pedal: Pedal in pedals { + engine.remove(pedal) + } + pedals.removeAll() + + // Step 2: Remove routing nodes (splitters and mergers) BEFORE releasing the branch + // buses they write/read. BranchChain.teardown() releases those buses in step 3, + // so the writers must be dequeued first. + for node: any Synthesizer in routingNodes { + engine.remove(node) + } + routingNodes.removeAll() + + // Step 3: Remove branch pedals and release branch buses. + for chain: BranchChain in branchChains { + chain.teardown() + } + branchChains.removeAll() + + lastNode = nil + + // Step 4: Release board-owned buses (head bus and main-chain inter-node buses). + for bus: AudioBus in allocatedBuses { + engine.busAllocator.releaseAudioBus(bus) + } + allocatedBuses.removeAll() + } +} diff --git a/Sources/LyrebirdShoeGaze/PedalKnob.swift b/Sources/LyrebirdShoeGaze/PedalKnob.swift new file mode 100644 index 0000000..f17971a --- /dev/null +++ b/Sources/LyrebirdShoeGaze/PedalKnob.swift @@ -0,0 +1,43 @@ +// PedalKnob.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdUI + +/// A UI-agnostic description of one controllable pedal knob. +/// +/// A `Pedal` publishes an array of these (via ``Pedal/knobs``) so a generic +/// pedalboard UI can render a rotary control per parameter without knowing the +/// concrete pedal type. Each descriptor pairs a display label with the live +/// ``UIParamNode`` (the projected value of an `@UIParam` property) and the +/// value range the control should span. +public struct PedalKnob { + + /// Short label shown beneath the knob (e.g. "Drive", "Mix"). + public let label: String + + /// The live parameter node the knob reads and writes. Pass `pedal.$paramName`. + public let node: UIParamNode + + /// Inclusive value range the knob spans, in the parameter's own units. + public let range: ClosedRange + + /// Creates a knob descriptor. + /// + /// - Parameters: + /// - label: Short label shown beneath the knob. + /// - node: The `UIParamNode` projected value of an `@UIParam` property + /// (`pedal.$drive`, `pedal.$mix`, …). + /// - range: Inclusive value range the knob spans, in the parameter's units. + public init( + label: String, + node: UIParamNode, + range: ClosedRange + ) { + self.label = label + self.node = node + self.range = range + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/CompressorPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/CompressorPedal.swift new file mode 100644 index 0000000..ee6d48d --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/CompressorPedal.swift @@ -0,0 +1,111 @@ +// CompressorPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Compressor pedal: feed-forward dynamic range compressor. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → Compressor.Audio(threshold:, ratio:, attack:, release:, makeupGain:) → mono out +/// ``` +/// +/// Attack, release, knee, and makeup gain are fixed at musically sensible defaults. +/// Knobs expose the two most-musical parameters: threshold and ratio. +/// +/// The wet/dry mix and bypass switching are handled by the `Pedal` base class. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - threshold: Gain-reduction threshold in dB. Signals above this level are +/// compressed. Range `[-40, 0]` dB. Defaults to `-12.0`. +/// - ratio: Compression ratio `≥ 1.0`. `1.0` = bypass, `4.0` = 4:1 compression. +/// Range `[1, 20]`. Defaults to `4.0`. +public final class CompressorPedal: Pedal { + + // MARK: - Parameters + + /// Compression threshold in dB. Range [-40, 0]. + @UIParam public var threshold: Double = -12.0 + + /// Compression ratio. Range [1, 20]. + @UIParam public var ratio: Double = 4.0 + + // MARK: - Constants + + /// Default wet/dry blend — fully wet; the compressor is inserted in-line. + private static let defaultMix: Double = 1.0 + + /// Attack time constant in seconds — time to reach full gain reduction on a transient. + private let attackTime: Double = 0.01 + + /// Release time constant in seconds — time for gain to recover after level drops below threshold. + private let releaseTime: Double = 0.1 + + /// Soft-knee width in dB. Zero = hard knee for maximum punch. + private let kneeWidth: Double = 0.0 + + /// Makeup gain in dB applied after compression to restore perceived loudness. + private let makeupGainDB: Double = 4.0 + + // MARK: - UI knobs + + /// Threshold knob range in dB. + private let thresholdRange: ClosedRange = -40.0 ... 0.0 + + /// Ratio knob range. + private let ratioRange: ClosedRange = 1.0 ... 20.0 + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Threshold", node: $threshold, range: thresholdRange), + PedalKnob(label: "Ratio", node: $ratio, range: ratioRange), + ] + } + + // MARK: - Init + + /// Creates a compressor pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Compressor", + inputBus: inputBus, + outputBus: outputBus, + initialMix: CompressorPedal.defaultMix + ) + } + + // MARK: - Effect + + /// Applies feed-forward dynamic range compression. + /// + /// Output is mono. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Compressed mono output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + Compressor.Audio( + in: dry, + threshold: $threshold, + ratio: $ratio, + attack: attackTime, + release: releaseTime, + kneeWidth: kneeWidth, + makeupGain: makeupGainDB + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/DelayPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/DelayPedal.swift new file mode 100644 index 0000000..0265e30 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/DelayPedal.swift @@ -0,0 +1,103 @@ +// DelayPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Delay pedal: feedback delay line. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → DelayLineFeedback(delay: time, decayTime: feedback) → mono wet out +/// ``` +/// +/// `effect` returns the pure wet delay signal. The base `Pedal` class handles +/// wet/dry blending via `mix`, so do not pre-blend inside `effect`. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - time: Delay time in seconds. Range `[0.01, 1.5]`. Defaults to `0.25`. +/// - feedback: Feedback amount expressed as decay time in seconds — the time +/// for echoes to fall to `targetAmp` (−60 dB). Longer values produce more +/// repeats. Range `[0.05, 6.0]` seconds. Defaults to `1.0`. +public final class DelayPedal: Pedal { + + // MARK: - Parameters + + /// Delay time in seconds. Range [0.01, 1.5]. + @UIParam public var time: Double = 0.25 + + /// Feedback decay time in seconds (time to reach −60 dB amplitude). + @UIParam public var feedback: Double = 1.0 + + // MARK: - Constants + + /// Maximum supported delay time in seconds. Sizes the delay line buffer at init. + private let maxDelayTime: Double = 1.5 + + /// Amplitude target for the `decayTime` calculation (−60 dB). + private let targetAmp: Double = 0.001 + + /// Default wet/dry blend — a partial mix so dry signal and echoes coexist. + private static let defaultMix: Double = 0.35 + + // MARK: - UI knobs + + /// Delay-time knob range in seconds. + private let timeRange: ClosedRange = 0.01 ... 1.5 + + /// Feedback (decay-time) knob range in seconds. + private let feedbackRange: ClosedRange = 0.05 ... 6.0 + + // MARK: - Init + + /// Creates a delay pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Delay", + inputBus: inputBus, + outputBus: outputBus, + initialMix: DelayPedal.defaultMix + ) + } + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Time", node: $time, range: timeRange), + PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange), + ] + } + + // MARK: - Effect + + /// Applies a feedback delay line. Returns the pure wet (delayed) signal. + /// + /// The base class `Pedal` mixes this with the dry signal via the `mix` parameter. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Pure wet mono delayed output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + DelayLineFeedback( + input: dry, + maxDelay: maxDelayTime, + delay: $time, + decayTime: $feedback, + targetAmp: targetAmp, + sampleRate: sampleRate, + interpolation: .linear + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/FuzzPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/FuzzPedal.swift new file mode 100644 index 0000000..e46841c --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/FuzzPedal.swift @@ -0,0 +1,112 @@ +// FuzzPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Fuzz pedal: high-gain `tanh` saturation followed by a tonal low-pass filter. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → (× fuzz drive) → Tanh → RBJLowPass(freq: tone, q: 0.707) → mono out +/// ``` +/// +/// The `fuzz` knob is a pre-gain (drive): it multiplies the input hard before the +/// `tanh` saturator, which squares the waveform off into the thick, sustaining fuzz +/// texture. Because `tanh` saturates toward ±1, the output level stays roughly constant +/// as `fuzz` rises — more drive means more grit and sustain, never less signal. A tone +/// filter then rolls off high-frequency harshness. +/// +/// > Note: This deliberately differs from the earlier crossover-distortion model, where +/// > the knob set a silent dead-zone width and large values muted quiet signals. +/// +/// The wet/dry mix and bypass switching are handled by the `Pedal` base class. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - fuzz: Pre-gain drive into the `tanh` saturator. Higher = more saturation and +/// sustain. Range `[1, 60]`. Defaults to `20.0`. +/// - tone: Low-pass tone cutoff in Hz. Roll off high-frequency fuzz harshness. +/// Range `[200, 8000]` Hz. Defaults to `3500.0`. +public final class FuzzPedal: Pedal { + + // MARK: - Parameters + + /// Pre-gain drive into the saturator. Range [1, 60]; higher = more fuzz. + @UIParam public var fuzz: Double = 20.0 + + /// Tone filter cutoff frequency in Hz. Range [200, 8000]. + @UIParam public var tone: Double = 3500.0 + + // MARK: - Constants + + /// Default wet/dry blend — fully wet so fuzz completely replaces dry signal. + private static let defaultMix: Double = 1.0 + + /// Q factor for the tone low-pass filter. Butterworth response (no resonant peak). + private let toneQ: Double = 0.707 + + /// Output trim applied after the `tanh` saturator so the fuzz sits at a sane level + /// relative to the other pedals (`tanh` output is roughly ±1). + private let outputTrim: Double = 0.6 + + // MARK: - UI knobs + + /// Fuzz knob range (saturator pre-gain / drive). + private let fuzzRange: ClosedRange = 1.0 ... 60.0 + + /// Tone knob range in Hz (low-pass cutoff). + private let toneRange: ClosedRange = 200.0 ... 8000.0 + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Fuzz", node: $fuzz, range: fuzzRange), + PedalKnob(label: "Tone", node: $tone, range: toneRange), + ] + } + + // MARK: - Init + + /// Creates a fuzz pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Fuzz", + inputBus: inputBus, + outputBus: outputBus, + initialMix: FuzzPedal.defaultMix + ) + } + + // MARK: - Effect + + /// Drives the input hard into a `tanh` saturator, then applies a tonal low-pass. + /// + /// Output is mono. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Fuzzed and tone-shaped mono output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // Pre-gain the signal hard, then saturate. `tanh` squares the waveform off as the + // drive rises while keeping the level bounded — the hallmark of a fuzz. + let driven: any ValidGeneratorInput = dry * $fuzz + let saturated: Tanh.Audio = Tanh.Audio(driven, mul: outputTrim) + return RBJLowPass.Audio( + input: saturated, + freq: $tone, + q: toneQ + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/ModulationPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/ModulationPedal.swift new file mode 100644 index 0000000..042ec9f --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/ModulationPedal.swift @@ -0,0 +1,121 @@ +// ModulationPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Modulation pedal: stereo chorus folded to mono. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → Chorus.Audio(mix: 1.0, rate:, depth:) → stereo (2 ch) +/// → SumChannels.Audio(mul: 0.5) → mono +/// ``` +/// +/// `Chorus.Audio` has a built-in `mix` parameter that blends dry+wet internally. +/// Here it is set to `1.0` (fully wet) so the base `Pedal` class handles dry/wet +/// blending uniformly via its own `mix` parameter. +/// +/// The stereo output from `Chorus` is summed to mono with a ×0.5 gain to compensate +/// for channel doubling. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - rate: Chorus LFO frequency in Hz. Range `[0.1, 10]`. Defaults to `1.5`. +/// - depth: Chorus modulation depth as a fraction of the delay time in [0, 1]. +/// Smaller values (0.001–0.01) produce classic chorus width. Defaults to `0.002`. +public final class ModulationPedal: Pedal { + + // MARK: - Parameters + + /// Chorus LFO rate in Hz. Range [0.1, 10]. + @UIParam public var rate: Double = 1.5 + + /// Chorus modulation depth as a fraction of delay time in [0, 1]. + @UIParam public var depth: Double = 0.002 + + // MARK: - Constants + + /// Chorus `mix` value. Set to 1.0 (fully wet) so the base `Pedal` handles + /// the dry/wet blend via its own `mix` parameter. + private let chorusWetMix: Double = 1.0 + + /// Base delay time for the chorus in seconds. + private let chorusDelayTime: Double = 0.025 + + /// Maximum delay time that the chorus delay line is allocated for. + private let chorusMaxDelayTime: Double = 0.1 + + /// Gain applied to the summed stereo→mono output to compensate for channel doubling. + private let stereoSumGain: Double = 0.5 + + /// Default wet/dry blend — an even mix for classic chorus width. + private static let defaultMix: Double = 0.5 + + // MARK: - UI knobs + + /// Rate knob range in Hz (chorus LFO frequency). + private let rateRange: ClosedRange = 0.1 ... 8.0 + + /// Depth knob range (fraction of delay time). + private let depthRange: ClosedRange = 0.0005 ... 0.01 + + // MARK: - Init + + /// Creates a modulation (chorus) pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Modulation", + inputBus: inputBus, + outputBus: outputBus, + initialMix: ModulationPedal.defaultMix + ) + } + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Rate", node: $rate, range: rateRange), + PedalKnob(label: "Depth", node: $depth, range: depthRange), + ] + } + + // MARK: - Effect + + /// Applies stereo chorus and folds the result to mono. + /// + /// Returns a mono wet signal. The base `Pedal` class mixes this with the + /// dry signal according to the `mix` parameter. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Wet mono chorus output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // Chorus.Audio produces a 2-channel stereo output. + let stereoChorus: Chorus.Audio = Chorus.Audio( + input: dry, + delayTime: chorusDelayTime, + depth: $depth, + rate: $rate, + mix: chorusWetMix, + sampleRate: sampleRate, + maxDelayTime: chorusMaxDelayTime + ) + // Sum stereo → mono with ×0.5 to avoid level doubling. + return SumChannels.Audio( + input: stereoChorus, + mul: stereoSumGain + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/OverdrivePedal.swift b/Sources/LyrebirdShoeGaze/Pedals/OverdrivePedal.swift new file mode 100644 index 0000000..576b040 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/OverdrivePedal.swift @@ -0,0 +1,88 @@ +// OverdrivePedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Overdrive pedal: soft-clipping saturation followed by a tonal low-pass filter. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → SoftClip(drive:) → RBJLowPass(freq: tone, q: 0.707) → mono out +/// ``` +/// +/// The wet/dry mix and bypass switching are handled by the `Pedal` base class. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - drive: Saturation amount. Higher values push more of the signal into soft-clip +/// territory. Range `[1, 20]`. Defaults to `4.0`. +/// - tone: Low-pass tone cutoff in Hz. Roll off high-frequency harshness. +/// Range `(0, 20000]`. Defaults to `4000.0`. +public final class OverdrivePedal: Pedal { + + // MARK: - Parameters + + /// Saturation drive amount. Range [1, 20]; higher = more clipping. + @UIParam public var drive: Double = 4.0 + + /// Tone filter cutoff frequency in Hz. Range (0, 20000]. + @UIParam public var tone: Double = 4000.0 + + // MARK: - Constants + + /// Q factor for the tone low-pass filter. Butterworth response (no resonant peak). + private let toneQ: Double = 0.707 + + // MARK: - Init + + /// Creates an overdrive pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init(name: "Overdrive", inputBus: inputBus, outputBus: outputBus) + } + + // MARK: - UI knobs + + /// Drive knob range (waveshaper input gain). + private let driveRange: ClosedRange = 1.0 ... 20.0 + + /// Tone knob range in Hz (low-pass cutoff). + private let toneRange: ClosedRange = 200.0 ... 8000.0 + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Drive", node: $drive, range: driveRange), + PedalKnob(label: "Tone", node: $tone, range: toneRange), + ] + } + + // MARK: - Effect + + /// Applies soft-clip saturation followed by a tonal low-pass filter. + /// + /// Output is mono. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Saturated and tone-shaped mono output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let saturated: SoftClip.Audio = SoftClip.Audio(dry, drive: $drive) + return RBJLowPass.Audio( + input: saturated, + freq: $tone, + q: toneQ + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/PhaserPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/PhaserPedal.swift new file mode 100644 index 0000000..17ebea1 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/PhaserPedal.swift @@ -0,0 +1,113 @@ +// PhaserPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Phaser pedal: cascaded all-pass filter swept by a sine LFO. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → Phaser.Audio(rate:, feedback:, mix: 1.0) → mono out +/// ``` +/// +/// `Phaser.Audio` is mono-in / mono-out. Its internal `mix` is set to `1.0` (fully +/// wet) so the base `Pedal` class handles the dry/wet blend uniformly via its own +/// `mix` parameter. +/// +/// The wet/dry mix and bypass switching are handled by the `Pedal` base class. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - rate: LFO sweep rate in Hz. Range `[0.05, 5.0]`. Defaults to `0.5`. +/// - feedback: Feedback gain in `[0, 0.9]`. Higher values deepen the notches. +/// Range `[0.0, 0.9]`. Defaults to `0.5`. +public final class PhaserPedal: Pedal { + + // MARK: - Parameters + + /// LFO sweep rate in Hz. Range [0.05, 5.0]. + @UIParam public var rate: Double = 0.5 + + /// Feedback gain in [0, 0.9]. Deepens the all-pass notches. + @UIParam public var feedback: Double = 0.5 + + // MARK: - Constants + + /// Default wet/dry blend — even mix for classic phaser comb-filter sweep. + private static let defaultMix: Double = 0.5 + + /// Internal `Phaser.Audio` mix — set to 1.0 so the base `Pedal` handles dry/wet. + private let phaserInternalMix: Double = 1.0 + + /// LFO depth fraction — sweeps the all-pass coefficient across its full range. + private let phaserDepth: Double = 0.9 + + /// Center frequency in Hz for the all-pass coefficient sweep. + private let phaserCenterFreq: Double = 800.0 + + /// Number of cascaded all-pass stages. Must be 4, 6, or 8. + private let phaserStages: Int = 6 + + // MARK: - UI knobs + + /// Rate knob range in Hz (LFO sweep frequency). + private let rateRange: ClosedRange = 0.05 ... 5.0 + + /// Feedback knob range (all-pass feedback gain). + private let feedbackRange: ClosedRange = 0.0 ... 0.9 + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Rate", node: $rate, range: rateRange), + PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange), + ] + } + + // MARK: - Init + + /// Creates a phaser pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Phaser", + inputBus: inputBus, + outputBus: outputBus, + initialMix: PhaserPedal.defaultMix + ) + } + + // MARK: - Effect + + /// Applies cascaded all-pass phasing and returns the fully-wet signal. + /// + /// `Phaser.Audio` is mono-in / mono-out. The base `Pedal` class mixes this with + /// the dry signal according to the `mix` parameter. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Wet mono phaser output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + Phaser.Audio( + input: dry, + rate: $rate, + depth: phaserDepth, + centerFreq: phaserCenterFreq, + feedback: $feedback, + stages: phaserStages, + mix: phaserInternalMix, + sampleRate: sampleRate + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/ReverbPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/ReverbPedal.swift new file mode 100644 index 0000000..c4c9dd3 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/ReverbPedal.swift @@ -0,0 +1,110 @@ +// ReverbPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Reverb pedal: Freeverb stereo reverb folded to mono. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry → FreeVerb.Audio(mix: 1.0, roomSize:, damping:) → stereo (2 ch) +/// → SumChannels.Audio(mul: 0.5) → mono (fold + compensate) +/// ``` +/// +/// `FreeVerb` is driven at `mix: 1.0` so it produces a pure wet signal; the base +/// `Pedal` class handles the wet/dry blend via its `mix` parameter. The stereo +/// output from `FreeVerb` is summed to mono with a ×0.5 gain to compensate for +/// the channel doubling. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - roomSize: Room size in [0, 1]. Larger values produce longer, denser tails. +/// Defaults to `0.6`. +/// - damping: High-frequency damping in [0, 1]. Higher values produce darker, +/// shorter tails. Defaults to `0.5`. +public final class ReverbPedal: Pedal { + + // MARK: - Parameters + + /// Room size in [0, 1]. Larger = longer reverb tail. + @UIParam public var roomSize: Double = 0.6 + + /// High-frequency damping in [0, 1]. Higher = darker tail. + @UIParam public var damping: Double = 0.5 + + // MARK: - Constants + + /// FreeVerb mix value. Set to 1.0 so FreeVerb produces pure wet output; + /// the base Pedal handles dry/wet blending via its own `mix` parameter. + private let freeVerbWetMix: Double = 1.0 + + /// Gain applied to the summed stereo→mono fold to compensate for the doubling + /// of energy when two channels are added together. + private let stereoSumGain: Double = 0.5 + + /// Default wet/dry blend — a partial mix so the dry signal stays up front. + private static let defaultMix: Double = 0.3 + + // MARK: - UI knobs + + /// Room-size and damping knob range (both normalised [0, 1]). + private let normalizedRange: ClosedRange = 0.0 ... 1.0 + + // MARK: - Init + + /// Creates a reverb pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Reverb", + inputBus: inputBus, + outputBus: outputBus, + initialMix: ReverbPedal.defaultMix + ) + } + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Room", node: $roomSize, range: normalizedRange), + PedalKnob(label: "Damp", node: $damping, range: normalizedRange), + ] + } + + // MARK: - Effect + + /// Applies Freeverb stereo reverb and folds the result to mono. + /// + /// Returns a mono wet signal. The base `Pedal` class mixes this with the + /// dry signal according to the `mix` parameter. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Wet mono reverberated output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // FreeVerb produces a 2-channel stereo output. + let stereoVerb: FreeVerb.Audio = FreeVerb.Audio( + source: dry, + roomSize: $roomSize, + damping: $damping, + mix: freeVerbWetMix, + sampleRate: sampleRate + ) + // Sum stereo → mono with ×0.5 to avoid level doubling. + return SumChannels.Audio( + input: stereoVerb, + mul: stereoSumGain + ) + } +} diff --git a/Sources/LyrebirdShoeGaze/Pedals/TremoloPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/TremoloPedal.swift new file mode 100644 index 0000000..9ea3628 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/TremoloPedal.swift @@ -0,0 +1,110 @@ +// TremoloPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Tremolo pedal: amplitude modulation via a unipolar sine LFO. +/// +/// Signal chain (inside `effect(_:)`): +/// ``` +/// dry × OscSin(freq: rate, mul: depth×0.5, add: 1−depth×0.5) → mono out +/// ``` +/// +/// The LFO oscillates between `[1 − depth, 1]` so full depth produces silence-to-unity +/// swells while zero depth leaves the signal unmodified. The result is a gain effect — +/// `defaultMix` is `1.0` (fully wet) so the base `Pedal` passes the tremolo signal through +/// unchanged; the `mix` knob can soften the wobble effect. +/// +/// The wet/dry mix and bypass switching are handled by the `Pedal` base class. +/// +/// ## Parameters +/// +/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: +/// +/// - Parameters: +/// - rate: LFO modulation rate in Hz. Range `[0.5, 12]`. Defaults to `4.0`. +/// - depth: Modulation depth in `[0, 1]`. `0` = no modulation, `1` = full tremolo. +/// Defaults to `0.7`. +public final class TremoloPedal: Pedal { + + // MARK: - Parameters + + /// LFO rate in Hz. Range [0.5, 12]. + @UIParam public var rate: Double = 4.0 + + /// Modulation depth in [0, 1]. + @UIParam public var depth: Double = 0.7 + + // MARK: - Constants + + /// Default wet/dry blend — fully wet; tremolo is a gain effect so dry/wet + /// blending does not apply in the same way as a parallel effect. + private static let defaultMix: Double = 1.0 + + /// Scale factor applied to `depth` to compute the LFO half-amplitude swing. + /// At full depth the LFO oscillates over half the normalised range, so the + /// peak gain is 1.0 and the trough is `1 − depth`. + private let lfoDepthScale: Double = 0.5 + + // MARK: - UI knobs + + /// Rate knob range in Hz (LFO frequency). + private let rateRange: ClosedRange = 0.5 ... 12.0 + + /// Depth knob range (modulation fraction). + private let depthRange: ClosedRange = 0.0 ... 1.0 + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Rate", node: $rate, range: rateRange), + PedalKnob(label: "Depth", node: $depth, range: depthRange), + ] + } + + // MARK: - Init + + /// Creates a tremolo pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Tremolo", + inputBus: inputBus, + outputBus: outputBus, + initialMix: TremoloPedal.defaultMix + ) + } + + // MARK: - Effect + + /// Multiplies the dry signal by a unipolar sine LFO. + /// + /// The LFO range is `[1 − depth, 1]`. At `depth = 0` the multiplier is constant 1.0; + /// at `depth = 1` it swings between `0.0` and `1.0`. + /// + /// Output is mono. + /// + /// - Parameter dry: Dry mono input signal. + /// - Returns: Amplitude-modulated mono output. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // lfoScale = depth × lfoDepthScale → LFO swing half-amplitude + // lfoOffset = 1 − depth × lfoDepthScale → LFO centre, so peak = 1.0, trough = 1 − depth + let lfoScale: any ValidGeneratorInput = $depth * lfoDepthScale + let lfoOffset: any ValidGeneratorInput = 1.0 - ($depth * lfoDepthScale) + let lfo: OscSin.Audio = OscSin.Audio( + freq: $rate, + mul: lfoScale, + add: lfoOffset + ) + return dry * lfo + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/BoardState.swift b/Sources/LyrebirdShoeGaze/Presets/BoardState.swift new file mode 100644 index 0000000..f3f7448 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/BoardState.swift @@ -0,0 +1,32 @@ +// BoardState.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Serialisable snapshot of one `PedalBoard`'s label and pedal chain. +/// +/// `label` is the board's display name. `pedals` contains one `PedalState` per +/// pedal in signal-flow order. Unknown pedal types in the array are skipped +/// silently during `ShoeGaze.loadRig(from:)`. +public struct BoardState: Codable, Equatable { + + /// The board's display label (e.g. `"Board 1"`). + public let label: String + + /// Ordered list of pedal snapshots in signal-flow order. + public let pedals: [PedalState] + + /// Creates a board state snapshot. + /// + /// - Parameters: + /// - label: The board's display label. + /// - pedals: Ordered list of pedal state snapshots. + public init( + label: String, + pedals: [PedalState] + ) { + self.label = label + self.pedals = pedals + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/BoardVersion.swift b/Sources/LyrebirdShoeGaze/Presets/BoardVersion.swift new file mode 100644 index 0000000..a2b69b0 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/BoardVersion.swift @@ -0,0 +1,73 @@ +// BoardVersion.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// A named, timestamped snapshot of a single `PedalBoard`'s label and pedal chain. +/// +/// `BoardVersion` is the unit stored and retrieved by `BoardVersionStore`. Each version +/// captures a complete `BoardState` (pedal types, knob values, bypass flags) alongside +/// a human-readable `name` (e.g. `"Lead Crunch"`) and a `savedAt` timestamp. +/// +/// `BoardVersion` is `Codable` so it can be written to and read from JSON files by +/// `BoardVersionStore`. It is `Identifiable` (via `UUID`) so SwiftUI `List` and +/// `ForEach` views can use it directly, and `Equatable` for round-trip testing. +/// +/// ## Typical usage +/// +/// ```swift +/// let store = BoardVersionStore() +/// store.capture(myBoard, name: "Lead Crunch") +/// try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory()) +/// ``` +/// +/// - Parameters: +/// - id: Stable unique identifier for this version. +/// - name: Human-readable label (e.g. `"Lead Crunch"`). +/// - savedAt: The `Date` when this version was captured. +/// - state: The full `BoardState` snapshot. +public struct BoardVersion: Codable, Identifiable, Equatable { + + /// Stable unique identifier for this version entry. + public let id: UUID + + /// Human-readable name for this version (e.g. `"Lead Crunch"`, `"Clean Wash"`). + public let name: String + + /// Date and time at which this version was captured, at **whole-second precision**. + /// + /// The timestamp is rounded to the nearest second at init so it survives a JSON + /// round-trip exactly (a `Date` serialised as a fractional `secondsSince1970` Double + /// otherwise loses precision through the decimal text form, which would break + /// `Equatable` after `writeToDisk` / `loadAllFromDisk`). + public let savedAt: Date + + /// The full `BoardState` snapshot — label, pedal types, knob values, and bypass flags. + public let state: BoardState + + /// Creates a board version snapshot. + /// + /// - Parameters: + /// - id: Stable unique identifier. Defaults to a newly generated `UUID()`. + /// - name: Human-readable name for this version. + /// - savedAt: Capture timestamp. Defaults to `Date()` (now). Rounded to the + /// nearest whole second so persistence round-trips are lossless. + /// - state: The `BoardState` to store. + public init( + id: UUID = UUID(), + name: String, + savedAt: Date = Date(), + state: BoardState + ) { + self.id = id + self.name = name + // Round to whole seconds: a fractional Date loses precision through the JSON + // `secondsSince1970` Double text form, which would break `Equatable` after a + // disk round-trip. + self.savedAt = Date(timeIntervalSince1970: savedAt.timeIntervalSince1970.rounded()) + self.state = state + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/BoardVersionStore.swift b/Sources/LyrebirdShoeGaze/Presets/BoardVersionStore.swift new file mode 100644 index 0000000..9db2220 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/BoardVersionStore.swift @@ -0,0 +1,288 @@ +// BoardVersionStore.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Observation + +/// In-memory list of `BoardVersion` snapshots with optional disk persistence. +/// +/// `BoardVersionStore` is `@Observable` so SwiftUI views automatically update when the +/// `versions` list changes. All mutations run on the main actor. +/// +/// ## Typical usage +/// +/// ```swift +/// let store = BoardVersionStore() +/// store.capture(myBoard, name: "Lead Crunch") // add a version +/// try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory()) +/// +/// // Restore on next launch: +/// let freshStore = BoardVersionStore() +/// try freshStore.loadAllFromDisk(in: BoardVersionStore.defaultDirectory()) +/// if let v = freshStore.versions.first { +/// try shoeGaze.rebuildBoard(myBoard, from: v.state) +/// } +/// ``` +/// +/// ## Disk format +/// +/// Each `BoardVersion` is written as a separate pretty-printed JSON file named +/// `-.json` inside the chosen directory. File names are +/// sanitised by replacing `/`, `\`, `:`, NUL, leading `.`, and whitespace with +/// underscores; the sanitised prefix is capped at 200 UTF-8 bytes; all-whitespace +/// or all-separator names fall back to `"unnamed"`. `Date` values are encoded as +/// seconds since the Unix epoch (`TimeInterval`) for lossless round-trip equality. +@MainActor +@Observable +public final class BoardVersionStore { + + // MARK: - State + + /// All in-memory `BoardVersion` entries, sorted by `savedAt` after any disk load. + public private(set) var versions: [BoardVersion] = [] + + // MARK: - Init + + /// Creates an empty store. Call `loadAllFromDisk(in:)` to populate from disk. + public init() {} + + // MARK: - Capture + + /// Captures the current state of `board` and appends a new `BoardVersion` to `versions`. + /// + /// - Parameters: + /// - board: The `PedalBoard` to snapshot. + /// - name: Human-readable label for this version (e.g. `"Lead Crunch"`). + public func capture( + _ board: PedalBoard, + name: String + ) { + let version: BoardVersion = BoardVersion( + id: UUID(), + name: name, + savedAt: Date(), + state: board.captureState() + ) + versions.append(version) + } + + // MARK: - Remove + + /// Removes a version from the in-memory list. Matching is by `id`. + /// + /// This is **memory-only**. Any JSON file previously written by `writeToDisk(_:in:)` is + /// not touched; call `deleteFromDisk(_:in:)` first if you also need to remove the file + /// so that the deletion survives `loadAllFromDisk`. + /// + /// - Parameter version: The `BoardVersion` to remove. + public func remove(_ version: BoardVersion) { + versions.removeAll { $0.id == version.id } + } + + // MARK: - Disk delete + + /// Deletes the JSON file for `version` from `directory`. + /// + /// The filename is derived using the same `-.json` scheme as + /// `writeToDisk(_:in:)`. No-op if the file does not exist. Use this alongside + /// `remove(_:)` to make a deletion persist across `loadAllFromDisk`. + /// + /// - Parameters: + /// - version: The `BoardVersion` whose file should be removed. + /// - directory: The directory that was passed to `writeToDisk(_:in:)`. + /// - Throws: `FileManager` errors other than "file not found". + public func deleteFromDisk( + _ version: BoardVersion, + in directory: URL + ) throws { + let sanitized: String = sanitizeFilename(version.name) + let filename: String = "\(sanitized)-\(version.id.uuidString).json" + let fileURL: URL = directory.appendingPathComponent(filename) + do { + try FileManager.default.removeItem(at: fileURL) + } catch let error as NSError + where error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError { + // File does not exist — treat as a no-op. + } + } + + // MARK: - Disk write + + /// Writes a single `BoardVersion` to `directory` as pretty-printed JSON. + /// + /// The filename is `-.json`. The sanitised name replaces `/`, + /// `:`, newlines, and other whitespace with underscores so the filename is safe on + /// HFS+ and APFS. The directory is created if it does not already exist. + /// + /// - Parameters: + /// - version: The `BoardVersion` to write. + /// - directory: Destination directory URL. Created recursively if absent. + /// - Throws: + /// - `FileManager` errors if directory creation fails. + /// - `JSONEncoder` errors on encode failure. + /// - `Data.write(to:options:)` errors on write failure. + public func writeToDisk( + _ version: BoardVersion, + in directory: URL + ) throws { + try FileManager.default.createDirectory( + at: directory, + withIntermediateDirectories: true, + attributes: nil + ) + + let sanitized: String = sanitizeFilename(version.name) + let filename: String = "\(sanitized)-\(version.id.uuidString).json" + let fileURL: URL = directory.appendingPathComponent(filename) + + let encoder: JSONEncoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + encoder.dateEncodingStrategy = .secondsSince1970 + let data: Data = try encoder.encode(version) + try data.write(to: fileURL, options: .atomic) + } + + /// Writes every in-memory `BoardVersion` to `directory`. + /// + /// Each version is written as a separate file (see `writeToDisk(_:in:)`). + /// The directory is created if it does not already exist. A failure on one file + /// propagates immediately and stops the remaining writes. + /// + /// - Parameter directory: Destination directory URL. Created recursively if absent. + /// - Throws: The first error encountered during write. + public func writeAllToDisk(in directory: URL) throws { + for version: BoardVersion in versions { + try writeToDisk(version, in: directory) + } + } + + // MARK: - Disk load + + /// Loads all `*.json` files in `directory` as `BoardVersion` entries, replacing the + /// current in-memory `versions` list. + /// + /// Files that cannot be **read** (e.g. permission errors) and files that cannot be + /// **decoded** (corrupt or unrecognised JSON) are both silently skipped — a single + /// bad file does not prevent the rest from loading. After loading, the list is sorted + /// ascending by `savedAt`. + /// + /// - Parameter directory: The directory to scan. If the directory does not exist or + /// is empty, `versions` is set to `[]` without throwing. + /// - Throws: `FileManager` errors for directory enumeration failures (not for + /// individual file read/decode failures — those are silently skipped). + public func loadAllFromDisk(in directory: URL) throws { + var loaded: [BoardVersion] = [] + + // Early exit if the directory doesn't exist yet. + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory), + isDirectory.boolValue else { + versions = [] + return + } + + let contents: [URL] = try FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: nil, + options: .skipsHiddenFiles + ) + + let decoder: JSONDecoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + + for fileURL: URL in contents { + guard fileURL.pathExtension == "json" else { continue } + guard let data: Data = try? Data(contentsOf: fileURL) else { continue } + guard let version: BoardVersion = try? decoder.decode(BoardVersion.self, from: data) else { + continue + } + loaded.append(version) + } + + loaded.sort { $0.savedAt < $1.savedAt } + versions = loaded + } + + // MARK: - Default directory + + /// Returns the recommended directory for storing board version files. + /// + /// Resolves to `/LyrebirdShoeGaze/ShoeGazeVersions/` for the + /// current user. Falls back to a `ShoeGazeVersions/` subdirectory inside the + /// system temporary directory if Application Support is unavailable. + /// + /// The directory is **not** created by this method — call `writeToDisk(_:in:)` or + /// `writeAllToDisk(in:)` (which create the directory automatically) before writing. + /// + /// - Returns: A `URL` for the ShoeGaze versions directory. + public static func defaultDirectory() -> URL { + let appSupportDir: URL? = try? FileManager.default.url( + for: .applicationSupportDirectory, + in: .userDomainMask, + appropriateFor: nil, + create: false + ) + let base: URL = appSupportDir ?? FileManager.default.temporaryDirectory + return base + .appendingPathComponent("LyrebirdShoeGaze", isDirectory: true) + .appendingPathComponent("ShoeGazeVersions", isDirectory: true) + } + + // MARK: - Private helpers + + /// Maximum UTF-8 byte length for the sanitised name prefix before the `-.json` + /// suffix is appended, so the full filename stays well under the 255-byte component limit. + private let maxNameLength: Int = 200 + + /// Sanitises a string so it is safe as a file-system component on HFS+ and APFS. + /// + /// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace characters with underscores. + /// - Replaces a leading `.` (which would produce hidden-file or `.`/`..` names) with an + /// underscore. + /// - Trims leading and trailing underscores that resulted from whitespace or separator + /// substitution (cosmetic only — the result is always safe even before trimming). + /// - Caps the UTF-8 byte length of the result at `maxNameLength` so the full filename + /// (`-.json`, 54 extra bytes) cannot exceed the 255-byte component limit. + /// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely + /// to separator characters after substitution. + private func sanitizeFilename(_ name: String) -> String { + let replacementCharacter: Character = "_" + let forbiddenCharacters: Set = ["/", "\\", ":", "\0"] + + var sanitized: String = name.map { character -> Character in + if character.isWhitespace || forbiddenCharacters.contains(character) { + return replacementCharacter + } + return character + }.reduce(into: "") { $0.append($1) } + + // Replace a leading dot so the filename is never `.`, `..`, or a hidden file. + if sanitized.first == "." { + sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_") + } + + // Trim whitespace-replacement underscores at both ends (cosmetic). + sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_")) + + // Treat all-empty or all-separator results as unnamed. + guard !sanitized.isEmpty else { return "unnamed" } + + // Cap to maxNameLength UTF-8 bytes so the full filename stays within 255 bytes. + if sanitized.utf8.count > maxNameLength { + var truncated: String = "" + var byteCount: Int = 0 + for scalar: Unicode.Scalar in sanitized.unicodeScalars { + let encodedLength: Int = UTF8.width(scalar) + guard byteCount + encodedLength <= maxNameLength else { break } + truncated.unicodeScalars.append(scalar) + byteCount += encodedLength + } + sanitized = truncated + } + + return sanitized.isEmpty ? "unnamed" : sanitized + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift new file mode 100644 index 0000000..a986da5 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift @@ -0,0 +1,44 @@ +// Pedal+Preset.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +extension Pedal { + + /// Captures the current parameter values of this pedal as a `PedalState`. + /// + /// The returned snapshot includes: + /// - `type`: the pedal's `displayName` (used as a factory key on load). + /// - `knobValues`: one `Double` per entry in `knobs`, in order + /// (effect-specific knobs first, then Mix, then Level). + /// - `bypass`: the current bypass parameter value. + /// + /// - Returns: A `PedalState` reflecting the pedal's current parameter values. + public func captureState() -> PedalState { + let values: [Double] = knobs.map { $0.node.value } + return PedalState( + type: displayName, + knobValues: values, + bypass: bypass + ) + } + + /// Applies a previously captured `PedalState` to this pedal's parameters. + /// + /// For each (knob, value) pair in `zip(knobs, state.knobValues)`, the knob's + /// `UIParamNode` is updated via `node.update(_:)`. If `state.knobValues` has + /// fewer entries than `knobs`, the trailing knobs retain their current values. + /// Extra values beyond `knobs.count` are ignored. The `bypass` parameter is + /// always applied regardless of knob-count mismatches. + /// + /// - Parameter state: The state to restore. The `state.type` is not validated + /// against `displayName` — the caller is responsible for matching types before + /// calling this method. + public func applyState(_ state: PedalState) { + for (knob, value) in zip(knobs, state.knobValues) { + knob.node.update(value) + } + bypass = state.bypass + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift new file mode 100644 index 0000000..d7e6ad7 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/PedalBoard+Preset.swift @@ -0,0 +1,19 @@ +// PedalBoard+Preset.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +extension PedalBoard { + + /// Captures the current state of this board's label and pedal chain as a `BoardState`. + /// + /// Each pedal's `displayName`, knob values, and bypass flag are snapshotted in + /// signal-flow order. The engine graph is not modified; this is a read-only operation. + /// + /// - Returns: A `BoardState` reflecting the board's current label and pedal parameters. + public func captureState() -> BoardState { + let pedalStates: [PedalState] = pedals.map { $0.captureState() } + return BoardState(label: label, pedals: pedalStates) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift new file mode 100644 index 0000000..b8c8692 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -0,0 +1,51 @@ +// PedalRegistry.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// A factory registry mapping built-in pedal display names to their constructors. +/// +/// `PedalRegistry` is the authoritative lookup used by `ShoeGaze.loadRig(from:)` to +/// instantiate the correct `Pedal` subclass for each `PedalState.type` string found +/// in a saved preset. Unknown type strings return `nil` from `makePedal(type:)` and +/// are silently skipped by the loader. +/// +/// To register custom pedal types, extend `builtIn` by building your own dictionary +/// and merging it before calling `loadRig`. The built-in registry covers the eight +/// factory pedals: Overdrive, Delay, Reverb, Modulation, Fuzz, Tremolo, Phaser, and +/// Compressor. +public enum PedalRegistry { + + /// Maps each built-in pedal display name to a `@MainActor` no-argument constructor. + /// + /// Keys are the `displayName` values returned by the corresponding `Pedal` subclass. + /// Values are closures that allocate a fresh instance with default bus indices — + /// `ShoeGaze.loadRig(from:)` updates `inputBus`/`outputBus` when adding the pedal + /// to a board via `board.add(_:)`. + public static let builtIn: [String: @MainActor () -> Pedal] = [ + "Overdrive": { OverdrivePedal() }, + "Delay": { DelayPedal() }, + "Reverb": { ReverbPedal() }, + "Modulation": { ModulationPedal() }, + "Fuzz": { FuzzPedal() }, + "Tremolo": { TremoloPedal() }, + "Phaser": { PhaserPedal() }, + "Compressor": { CompressorPedal() }, + ] + + /// Returns a new `Pedal` instance for the given type string, or `nil` if the type + /// is not in the built-in registry. + /// + /// The returned pedal has default bus indices (`inputBus: 0`, `outputBus: 0`); + /// the caller is responsible for routing it via `board.add(_:)` before the engine + /// processes any audio. + /// + /// - Parameter type: The `displayName` of the pedal (e.g. `"Overdrive"`, `"Delay"`). + /// - Returns: A freshly allocated `Pedal` subclass instance, or `nil` for unknown types. + @MainActor + public static func makePedal(type: String) -> Pedal? { + guard let constructor: @MainActor () -> Pedal = builtIn[type] else { return nil } + return constructor() + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift new file mode 100644 index 0000000..725be94 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift @@ -0,0 +1,43 @@ +// PedalState.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Serialisable snapshot of one pedal's parameter values. +/// +/// `type` stores the pedal's `displayName` and is used by `PedalRegistry` to +/// reconstruct the correct subclass on load. `knobValues` mirrors `Pedal.knobs` +/// in order — effect-specific knobs first, then `mix`, then `level`. `bypass` +/// stores the bypass parameter value (`0.0` = engaged, `1.0` = bypassed). +/// +/// - Note: Extra knob values beyond the pedal's current knob count are silently +/// ignored on apply; missing values (fewer entries than knobs) leave trailing +/// knobs at their current value. +public struct PedalState: Codable, Equatable { + + /// The pedal's `displayName` — used as a factory key by `PedalRegistry`. + public let type: String + + /// Knob values in the same order as `Pedal.knobs` (effect knobs then Mix, Level). + public let knobValues: [Double] + + /// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed. + public let bypass: Double + + /// Creates a pedal state snapshot. + /// + /// - Parameters: + /// - type: The pedal's `displayName`, used to identify the pedal type on load. + /// - knobValues: Current knob values in `Pedal.knobs` order. + /// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed). + public init( + type: String, + knobValues: [Double], + bypass: Double + ) { + self.type = type + self.knobValues = knobValues + self.bypass = bypass + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PresetError.swift b/Sources/LyrebirdShoeGaze/Presets/PresetError.swift new file mode 100644 index 0000000..73c1164 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/PresetError.swift @@ -0,0 +1,17 @@ +// PresetError.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Errors thrown by preset load and version-check operations. +/// +/// - `unsupportedVersion`: The serialised preset's `version` field exceeds +/// `presetFormatVersion`. The associated value carries the version number that +/// was found in the file so callers can surface a meaningful error message. +public enum PresetError: Error, Equatable { + + /// The preset file was written by a newer version of the format than this + /// build understands. The associated `Int` is the version found in the file. + case unsupportedVersion(Int) +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift new file mode 100644 index 0000000..030fbad --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -0,0 +1,187 @@ +// ShoeGaze+Preset.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +extension ShoeGaze { + + // MARK: - Capture + + /// Captures the current rig topology and parameter values as a `ShoeGazeState`. + /// + /// Each board's label and pedal parameters are snapshotted in order. The engine + /// graph is not modified; this is a read-only operation. + /// + /// - Returns: A `ShoeGazeState` reflecting the current rig. + public func captureState() -> ShoeGazeState { + let boardStates: [BoardState] = boards.map { board in + let pedalStates: [PedalState] = board.pedals.map { $0.captureState() } + return BoardState(label: board.label, pedals: pedalStates) + } + return ShoeGazeState(boards: boardStates) + } + + // MARK: - Save / Load + + /// Saves the current rig to a JSON file at `url`. + /// + /// The file is pretty-printed for readability and human-editability. Existing + /// files at `url` are overwritten. + /// + /// - Parameter url: Destination file URL. The directory must already exist. + /// - Throws: Any error from `JSONEncoder` or `Data.write(to:options:)`. + public func saveRig(to url: URL) throws { + let encoder: JSONEncoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let data: Data = try encoder.encode(captureState()) + try data.write(to: url, options: .atomic) + } + + /// Loads a rig from a JSON preset file and rebuilds the engine graph. + /// + /// This method: + /// 1. Calls `teardown()` to remove all current nodes and release all buses. + /// 2. For each `BoardState`, calls `addBoard()`, sets `board.label`, adds each + /// pedal (skipping unknown types without throwing), applies the saved parameter + /// values via `pedal.applyState(_:)`, and calls `finalizeBoard(_:)`. + /// + /// - Important: Call this method with the engine **stopped** (before `engine.start()` + /// or after `engine.stop()`). The same async-removal caveat as `teardown()` applies: + /// the engine processes one more block after `remove` is enqueued. Unknown pedal + /// types in the preset are silently skipped — the board is still created and finalized + /// with however many pedals were successfully reconstructed. + /// + /// - Parameter url: Source file URL pointing to a JSON preset written by `saveRig(to:)`. + /// - Throws: Any error from `Data(contentsOf:)`, `JSONDecoder`, `PedalBoard.init`, + /// `board.add(_:)`, or `finalizeBoard(_:)`. Also throws + /// `PresetError.unsupportedVersion` when the file's version exceeds + /// `presetFormatVersion`. + public func loadRig(from url: URL) throws { + let data: Data = try Data(contentsOf: url) + let decoder: JSONDecoder = JSONDecoder() + let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data) + guard state.version <= presetFormatVersion else { + throw PresetError.unsupportedVersion(state.version) + } + + teardown() + + for boardState: BoardState in state.boards { + let board: PedalBoard = try addBoard() + board.label = boardState.label + + for pedalState: PedalState in boardState.pedals { + guard let pedal: Pedal = PedalRegistry.makePedal(type: pedalState.type) else { + // Unknown pedal type — skip without crashing. + continue + } + pedal.applyState(pedalState) + try board.add(pedal) + } + + try finalizeBoard(board) + } + } + + // MARK: - Per-board rebuild + + /// Tears down a single board and recreates it from a saved `BoardState`, preserving + /// its position in `boards` so UI ordering remains stable. + /// + /// ## Behaviour + /// + /// 1. Finds `board` in `boards` by identity (`===`). If absent, the board is treated as + /// unmanaged: a fresh board is built, finalised, and returned without reordering. + /// 2. Calls `addBoard()` to allocate a new board and sets `newBoard.label = state.label`. + /// 3. For each `PedalState` in `state.pedals`, calls `PedalRegistry.makePedal(type:)`; + /// unknown types are logged and skipped so presets with missing custom pedals degrade + /// gracefully. Known pedals have `applyState(_:)` called before `board.add(_:)`. + /// 4. Calls `finalizeBoard(_:)` to connect the output master. + /// 5. Only after the new board is fully wired does `removeBoard(_:)` tear down the old + /// board — so a failure during steps 2–4 leaves the original board intact. + /// 6. Moves the new board to `oldIndex` in `boards` so it occupies the same slot as the + /// removed board. + /// + /// - Important: Call with the engine **stopped** (or accept one block of glitch on a + /// running engine). Both boards exist briefly while the new one is being built; + /// this requires two additional buses but is safe because the bus pool has headroom + /// and the documented precondition is engine-stopped. `removeBoard(_:)` enqueues + /// removal; the engine processes one more block before the node is dequeued. + /// Unknown pedal types are silently skipped. + /// + /// - Parameters: + /// - board: The board to replace. Must have been returned by `addBoard()` on this instance. + /// - state: The `BoardState` snapshot to restore. + /// - Returns: The newly created `PedalBoard` at the same index as the replaced board. + /// - Throws: + /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available during rebuild. + /// - `EngineAddError` if the engine rejects any node insertion. + @discardableResult + public func rebuildBoard( + _ board: PedalBoard, + from state: BoardState + ) throws -> PedalBoard { + // Record the existing position before allocating the new board so the slot + // can be restored. May be nil when `board` is unmanaged (not in `boards`). + let oldIndex: Int? = boards.firstIndex(where: { $0 === board }) + + // Build the new board FIRST so that any failure leaves the old board intact. + let newBoard: PedalBoard = try addBoard() + do { + newBoard.label = state.label + + for pedalState: PedalState in state.pedals { + guard let pedal: Pedal = PedalRegistry.makePedal(type: pedalState.type) else { + // Unknown pedal type — log for diagnosability, then skip. + print("[ShoeGaze] rebuildBoard: skipping unknown pedal type \(pedalState.type)") + continue + } + pedal.applyState(pedalState) + try newBoard.add(pedal) + } + + try finalizeBoard(newBoard) + } catch { + // New board is partial — clean it up while the old board is still intact. + removeBoard(newBoard) + throw error + } + + // New board fully wired — now remove the old one and restore its position. + if let targetIndex: Int = oldIndex { + removeBoard(board) + // `addBoard()` always appends; move the new board back to the original slot. + // `moveBoard(_:to:)` locates by identity so the correct element is repositioned + // even if `removeBoard` shifted indices. + moveBoard(newBoard, to: targetIndex) + } + + return newBoard + } + + // MARK: - Lightweight recall + + /// Applies parameter values from `state` to the current rig topology without + /// rebuilding the engine graph. + /// + /// This is a lightweight "recall settings" path intended for topologically identical + /// rigs (same board count, same pedal count and types in the same order). Boards + /// and pedals are matched positionally; any count or type mismatch at the board or + /// pedal level is silently ignored for that entry — no error is thrown and remaining + /// entries continue to be processed. + /// + /// Use `loadRig(from:)` when you need a full topology rebuild. + /// + /// - Parameter state: The `ShoeGazeState` whose parameter values should be applied. + public func applyState(_ state: ShoeGazeState) { + for (board, boardState) in zip(boards, state.boards) { + for (pedal, pedalState) in zip(board.pedals, boardState.pedals) { + guard pedal.displayName == pedalState.type else { continue } + pedal.applyState(pedalState) + } + } + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift new file mode 100644 index 0000000..1deafe0 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGazeState.swift @@ -0,0 +1,42 @@ +// ShoeGazeState.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Format version written into every saved preset file. +/// +/// Increment this constant when the `ShoeGazeState` schema changes in a way that +/// requires migration logic on load. +public let presetFormatVersion: Int = 1 + +/// Serialisable snapshot of an entire `ShoeGaze` rig — all boards and their pedals. +/// +/// Use `ShoeGaze.saveRig(to:)` to write and `ShoeGaze.loadRig(from:)` to restore. +/// The `version` field allows future migrations: loaders that read a file with a +/// higher `version` than `presetFormatVersion` should reject or warn, while loaders +/// reading older versions may apply forward-compatibility mappings. +/// +/// Unknown pedal types encountered during load are silently skipped so presets made +/// with custom third-party pedals degrade gracefully on systems without those pedals. +public struct ShoeGazeState: Codable, Equatable { + + /// Preset format version. Written as `presetFormatVersion` at save time. + public let version: Int + + /// All board snapshots in the order they were created. + public let boards: [BoardState] + + /// Creates a rig state snapshot. + /// + /// - Parameters: + /// - version: Preset format version. Defaults to `presetFormatVersion`. + /// - boards: Ordered list of board state snapshots. + public init( + version: Int = presetFormatVersion, + boards: [BoardState] + ) { + self.version = version + self.boards = boards + } +} diff --git a/Sources/LyrebirdShoeGaze/Recording/RecordTap.swift b/Sources/LyrebirdShoeGaze/Recording/RecordTap.swift new file mode 100644 index 0000000..a08f8db --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Recording/RecordTap.swift @@ -0,0 +1,84 @@ +// RecordTap.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth + +/// An internal synthesizer that taps one or more audio buses and records them to a +/// WAV file via `DiskOut.Audio`. +/// +/// `RecordTap` reads `channelCount` consecutive audio buses starting at `firstBusIndex` +/// and passes them to a `DiskOut.Audio` instance that writes to `fileURL`. It is added +/// `.after(engine.mainGroup)` so it evaluates after every board and master synth has +/// written their final bus values for the block. +/// +/// Call `diskOut?.close()` after removing the tap from the engine to flush any +/// buffered frames and close the file handle. +final class RecordTap: SynthesizerBase { + + // MARK: - Configuration + + /// Index of the first audio bus to record. + private let firstBusIndex: Int + + /// Number of consecutive buses to record (and interleave into the output file). + private let channelCount: Int + + /// Destination file URL. Created or overwritten when the `DiskOut.Audio` is initialised. + private let fileURL: URL + + /// Sample rate written into the WAV file header. + private let recordSampleRate: Double + + // MARK: - DiskOut handle + + /// The `DiskOut.Audio` generator created during `build()`. `nil` if `build()` has not + /// run yet, or if `DiskOut.Audio.init` threw (error is printed to stdout). + private(set) var diskOut: DiskOut.Audio? + + // MARK: - Init + + /// Creates a record tap that reads `channelCount` buses from `firstBusIndex`. + /// + /// - Parameters: + /// - firstBusIndex: Index of the first audio bus to record. + /// - channelCount: Number of consecutive audio buses to record. + /// - fileURL: Output WAV file URL. Created or overwritten at build time. + /// - sampleRate: Sample rate to embed in the WAV file header. + init( + firstBusIndex: Int, + channelCount: Int, + fileURL: URL, + sampleRate: Double + ) { + self.firstBusIndex = firstBusIndex + self.channelCount = channelCount + self.fileURL = fileURL + self.recordSampleRate = sampleRate + super.init() + } + + // MARK: - Build + + override func build() { + let source: any ValidGeneratorInput = channelCount > 1 + ? input(bus: firstBusIndex, channels: channelCount) + : input(bus: firstBusIndex) + do { + diskOut = try DiskOut.Audio( + source: source, + channelCount: channelCount, + url: fileURL, + sampleRate: recordSampleRate, + format: .wav + ) + // DiskOut.Audio conforms to RootRegistering and auto-registers as a synth root + // when constructed inside build(). No explicit addOutputGenerator call is needed. + } catch { + print("[ShoeGaze] RecordTap could not open \(fileURL.lastPathComponent): \(error)") + } + } +} diff --git a/Sources/LyrebirdShoeGaze/Recording/ShoeGaze+Recording.swift b/Sources/LyrebirdShoeGaze/Recording/ShoeGaze+Recording.swift new file mode 100644 index 0000000..8609e7b --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Recording/ShoeGaze+Recording.swift @@ -0,0 +1,193 @@ +// ShoeGaze+Recording.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth + +// MARK: - Recording constants + +/// Preferred number of interleaved output channels captured by the output record tap. +/// Clamped to `engine.numOutputChannels` at recording time so a mono engine never reads +/// an input bus as if it were a second output channel. +private let recordingOutputChannelCount: Int = 2 + +/// Number of channels captured by the input record tap (always mono — hardware input is mono). +private let recordingInputChannelCount: Int = 1 + +/// `DateFormatter` format string used to build timestamped file names. +private let recordingTimestampFormat: String = "yyyyMMdd-HHmmss" + +/// POSIX locale used for the timestamp `DateFormatter` so the filename always uses the +/// Gregorian calendar regardless of the user's system locale. +private let posixLocaleIdentifier: String = "en_US_POSIX" + +// MARK: - ShoeGaze + Recording + +extension ShoeGaze { + + // MARK: - Start + + /// Starts recording the overall output and (when possible) the raw input to timestamped + /// WAV files in ``recordingFolder``. + /// + /// Two files are written: + /// - `output-.wav` — the final mix read from hardware output buses starting at 0. + /// The channel count is `min(2, engine.numOutputChannels)` so a mono-output engine records + /// only one channel (bus 0) instead of accidentally reading bus 1 (which is the first input + /// bus on a mono-output configuration). + /// - `input-.wav` — the raw mono input signal. For `.liveInput(channel:)` this is + /// the hardware input bus; for `.testLoop` this is the head bus of the first board. If no + /// board exists when using `.testLoop`, only the output file is created and a note is printed. + /// If `.liveInput(channel:)` specifies an out-of-range channel, only the output file is + /// created and a note is printed. + /// + /// Both taps are inserted `.after(engine.mainGroup)` so they evaluate after every board and + /// master synth, guaranteeing they read final bus values for each block. + /// + /// If a tap's output file cannot be opened (e.g. disk full or permissions error), any taps + /// that were already added to the engine are removed, and + /// `ShoeGazeError.recordTapFailedToOpen` is thrown. `isRecording` remains `false`. + /// + /// - Throws: + /// - `ShoeGazeError.recordingFolderNotSet` if ``recordingFolder`` is `nil`. + /// - Any error thrown by `FileManager.createDirectory` if the folder cannot be created. + /// - `EngineAddError` if the engine rejects a tap insertion. + /// - `ShoeGazeError.recordTapFailedToOpen` if a `DiskOut.Audio` could not open its file. + public func startRecording() throws { + guard let folder: URL = recordingFolder else { + throw ShoeGazeError.recordingFolderNotSet + } + guard !isRecording else { return } + + // Ensure the destination folder exists. + try FileManager.default.createDirectory( + at: folder, + withIntermediateDirectories: true, + attributes: nil + ) + + // Build a timestamp string using POSIX locale so the Gregorian calendar is always + // used, regardless of the user's system locale or calendar setting. + let formatter: DateFormatter = DateFormatter() + formatter.dateFormat = recordingTimestampFormat + formatter.locale = Locale(identifier: posixLocaleIdentifier) + let timestamp: String = formatter.string(from: Date()) + + // Clamp the output channel count to the engine's actual output channel count so we + // never read bus index 1 on a mono-output engine (bus 1 would be the first input bus). + let outChannels: Int = min(recordingOutputChannelCount, engine.numOutputChannels) + guard outChannels >= 1 else { + // Engine has no output channels — nothing to record. + print("[ShoeGaze] startRecording: engine has no output channels — skipping output tap.") + return + } + + // --- Output tap --- + let outputFileURL: URL = folder + .appendingPathComponent("output-\(timestamp).wav") + let outputTap: RecordTap = RecordTap( + firstBusIndex: 0, + channelCount: outChannels, + fileURL: outputFileURL, + sampleRate: engine.sampleRate + ) + try engine.add(outputTap, position: .after(engine.mainGroup)) + // Guard that DiskOut actually opened — build() prints the error; we surface it here. + guard outputTap.diskOut != nil else { + engine.remove(outputTap) + throw ShoeGazeError.recordTapFailedToOpen(outputFileURL) + } + recordTaps.append(outputTap) + + // --- Input tap (mono) --- + let inputBusIndex: Int? = resolvedInputBusIndex() + if let busIndex: Int = inputBusIndex { + let inputFileURL: URL = folder + .appendingPathComponent("input-\(timestamp).wav") + let inputTap: RecordTap = RecordTap( + firstBusIndex: busIndex, + channelCount: recordingInputChannelCount, + fileURL: inputFileURL, + sampleRate: engine.sampleRate + ) + do { + try engine.add(inputTap, position: .after(engine.mainGroup)) + } catch { + // The output tap was already added — remove it before propagating. + engine.remove(outputTap) + outputTap.diskOut?.close() + recordTaps.removeAll() + throw error + } + guard inputTap.diskOut != nil else { + // Input file could not be opened — roll back both taps cleanly. + engine.remove(inputTap) + engine.remove(outputTap) + outputTap.diskOut?.close() + recordTaps.removeAll() + throw ShoeGazeError.recordTapFailedToOpen(inputFileURL) + } + recordTaps.append(inputTap) + } + + isRecording = true + } + + // MARK: - Stop + + /// Stops an active recording, flushes all buffered frames to disk, and closes the output files. + /// + /// Each tap is removed from the engine then `DiskOut.close()` is called synchronously to + /// flush any remaining buffered frames and dispose the file handle. + /// + /// > Important: `engine.remove(_:)` is asynchronous — it enqueues the removal for the next + /// > render block. When the engine is still running, the RT thread may render one or two + /// > additional blocks after `stopRecording()` returns; those frames are written to the + /// > `DiskOut` ring buffer but the ring buffer drainer may not flush them before `close()` + /// > is called, resulting in a bounded tail truncation of those final blocks. This is not + /// > file corruption — the WAV header length is written on `close()`. For a sample-accurate + /// > tail with no truncation, stop the engine (`engine.stop()`) before calling + /// > `stopRecording()`, then close. + /// + /// No-op if `isRecording` is `false`. + public func stopRecording() { + guard isRecording else { return } + for tap: RecordTap in recordTaps { + engine.remove(tap) + tap.diskOut?.close() + } + recordTaps.removeAll() + isRecording = false + } + + // MARK: - Private helpers + + /// Resolves the audio bus index of the raw input signal based on the current `inputSource`. + /// + /// - `.liveInput(channel:)` → validated via `liveInputBusIndex(channel:engine:)`. Returns + /// `nil` (with a printed note) if the channel is out of range rather than recording an + /// incorrect bus; the output track is still written. + /// - `.testLoop` → `boards.first?.headBus.index` (the first board's head bus). Returns `nil` + /// if there are no boards; the input track is skipped and a note is printed. + private func resolvedInputBusIndex() -> Int? { + switch inputSource { + case .liveInput(let channel): + do { + return try liveInputBusIndex(channel: channel, engine: engine) + } catch { + print("[ShoeGaze] startRecording: invalid .liveInput channel — skipping input tap. (\(error))") + return nil + } + + case .testLoop: + guard let firstBoard: PedalBoard = boards.first else { + print("[ShoeGaze] startRecording: no boards available for .testLoop input tap — recording output only.") + return nil + } + return firstBoard.headBus.index + } + } +} diff --git a/Sources/LyrebirdShoeGaze/Routing/BranchChain.swift b/Sources/LyrebirdShoeGaze/Routing/BranchChain.swift new file mode 100644 index 0000000..49b1b9e --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/BranchChain.swift @@ -0,0 +1,154 @@ +// BranchChain.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A linear sub-chain of pedals within one branch of a parallel section. +/// +/// `BranchChain` mirrors ``PedalBoard/add(_:)`` logic but writes into branch-local buses +/// rather than the board's main bus path. Each call to ``add(_:)`` allocates a new output +/// bus, configures the pedal's sample rate and bus indices, and inserts the pedal into the +/// engine immediately after the current shared tail node. +/// +/// ## Evaluation order +/// +/// Both branches in a ``ParallelSection`` share a single `sharedTail` pointer so that all +/// branch pedals appear in a flat linear sequence in the engine's node tree. The tree layout is: +/// +/// ``` +/// Splitter → [branchA pedals in order] → [branchB pedals in order] → Merger +/// ``` +/// +/// Despite being "parallel" in signal-flow terms (each branch reads from an independent +/// splitter output bus), correctness requires that all pedals that write their respective +/// output buses evaluate before the ``Merger`` reads those buses. The flat linear layout +/// guarantees this regardless of which branch pedals are added first. +/// +/// A `BranchChain` is created by ``PedalBoard/split()`` and is accessed via +/// ``ParallelSection/branchA`` and ``ParallelSection/branchB``. Call ``PedalBoard/merge(_:)`` +/// to combine the two branches back into the main chain after adding pedals. +@MainActor +public final class BranchChain { + + // MARK: - State + + private let engine: SynthesisEngine + + /// All pedals in this branch in insertion (signal-flow) order. + public private(set) var pedals: [Pedal] = [] + + /// Index of the bus that the last pedal in this branch writes to. Before any pedal is + /// added this is the branch's input bus (the output of the splitter for this branch). + public private(set) var tailBusIndex: Int + + /// Shared tail node pointer. Both branches in a ``ParallelSection`` share the same + /// `SharedTail` wrapper so all pedals are inserted in a flat linear order. + private let sharedTail: SharedTail + + /// All buses allocated by this branch (for release on teardown). + private var allocatedBuses: [AudioBus] = [] + + /// Sample rate injected from the board, used to configure each added pedal. + private let sampleRate: Double + + // MARK: - Init + + /// Creates a branch chain seeded to a particular starting bus and shared tail reference. + /// + /// This initialiser is called internally by ``PedalBoard/split()``. Callers never + /// construct a `BranchChain` directly. + /// + /// - Parameters: + /// - engine: The `SynthesisEngine` that will own the branch's pedal nodes. + /// - inputBus: The bus index from which the first pedal in the branch reads its input. + /// - sampleRate: The engine sample rate; injected into each added pedal. + /// - sharedTail: Shared mutable reference to the current tree tail node. Both branches + /// of the same `ParallelSection` share this wrapper so insertions from either branch + /// form a flat linear chain rather than sibling trees both rooted at the splitter. + init( + engine: SynthesisEngine, + inputBus: AudioBus, + sampleRate: Double, + sharedTail: SharedTail + ) { + self.engine = engine + self.tailBusIndex = inputBus.index + self.sampleRate = sampleRate + self.sharedTail = sharedTail + self.allocatedBuses.append(inputBus) + } + + // MARK: - Adding pedals + + /// Appends a pedal to the end of this branch and adds it to the engine. + /// + /// The pedal's `inputBus` is set to the current branch tail bus; a new mono bus is + /// allocated for its `outputBus`. After this call, ``tailBusIndex`` advances to the + /// new output bus. + /// + /// The pedal is inserted after the shared tail node (which may be the splitter, or a + /// pedal from either branch), so all branch pedals appear in the tree in the order they + /// were added across both branches combined. + /// + /// - Parameter pedal: The pedal to append to this branch. + /// - Throws: + /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. + /// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add). + public func add(_ pedal: Pedal) throws { + let pedalOutputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + allocatedBuses.append(pedalOutputBus) + + pedal.inputBus = tailBusIndex + pedal.outputBus = pedalOutputBus.index + pedal.sampleRate = sampleRate + + try engine.add(pedal, position: .after(sharedTail.node)) + + pedals.append(pedal) + sharedTail.node = pedal + tailBusIndex = pedalOutputBus.index + } + + // MARK: - Teardown + + /// Removes all pedals from the engine and releases all allocated buses. + /// + /// Called internally by ``PedalBoard/teardown()`` when the board is torn down. + /// After calling this method the `BranchChain` should not be reused. + func teardown() { + for pedal: Pedal in pedals { + engine.remove(pedal) + } + pedals.removeAll() + for bus: AudioBus in allocatedBuses { + engine.busAllocator.releaseAudioBus(bus) + } + allocatedBuses.removeAll() + } +} + +// MARK: - SharedTail + +/// A mutable reference wrapper for the current tree-tail node shared between branch chains. +/// +/// Both ``BranchChain`` instances in a ``ParallelSection`` hold the same `SharedTail` so +/// that insertions from either branch always go after the most recently inserted node — forming +/// a flat linear chain in the node tree. Isolation is provided by `@MainActor`. +@MainActor +final class SharedTail { + + /// The current tree-tail node. Updated by each `BranchChain.add(_:)` call. + var node: any Synthesizer + + /// Creates a `SharedTail` seeded to the given node (typically the ``Splitter``). + /// + /// - Parameter node: The initial tail — the node after which the first branch pedal will + /// be inserted. + init(node: any Synthesizer) { + self.node = node + } +} diff --git a/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift b/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift new file mode 100644 index 0000000..cf40190 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/ChainRouter.swift @@ -0,0 +1,328 @@ +// ChainRouter.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Routes one shared input to two independent `PedalBoard` chains, then merges their +/// outputs through a single `BoardOutputMaster` to stereo hardware output. +/// +/// ## Topology +/// +/// ``` +/// inputSource → routerInputBus → Splitter → boardA.headBus → boardA chain ─┐ +/// → boardB.headBus → boardB chain ─┤ +/// Merger → routerMixBus → BoardOutputMaster → hw 0/1 +/// ``` +/// +/// The ``mode`` property (delegating to ``splitter``) selects which chain is audible: +/// - `.a` — only board A passes through; board B is muted. +/// - `.b` — only board B passes through; board A is muted. +/// - `.both` — both boards are summed at the merger (full parallel operation). +/// +/// ## Typical usage +/// +/// ```swift +/// let router: ChainRouter = try shoeGaze.makeChainRouter() +/// try router.addToA(OverdrivePedal()) +/// try router.addToB(DelayPedal()) +/// try router.finalize() +/// router.mode = .both +/// try engine.start() +/// ``` +/// +/// Add pedals via ``addToA(_:)`` and ``addToB(_:)`` rather than calling `boardA.add` or +/// `boardB.add` directly. These methods update an internal `lastInsertedNode` pointer so +/// ``finalize()`` can always place the merger after the true last node in the evaluation +/// tree, regardless of the order in which boards are populated. +/// +/// Do **not** add the router's boards to `ShoeGaze.boards` via `addBoard()` — +/// this router owns their lifecycle. Call ``teardown()`` (or `ShoeGaze.teardown()`) +/// to clean up. +/// +/// ## Evaluation order +/// +/// 1. `source` evaluates first and writes `routerInputBus`. +/// 2. `splitter` evaluates immediately after `source`, reads `routerInputBus`, +/// and writes `boardA.headBus` and `boardB.headBus`. +/// 3. Each board's pedals evaluate in the order they were added via ``addToA(_:)`` / +/// ``addToB(_:)``. Because `lastInsertedNode` is updated after every add, +/// pedals from either board are always chained after the previously inserted node. +/// 4. After ``finalize()``, the `merger` is inserted after `lastInsertedNode` +/// (the overall last node across both boards, or the splitter when both are empty). +/// 5. The `BoardOutputMaster` is inserted immediately after the merger. +@MainActor +public final class ChainRouter { + + // MARK: - Public boards + + /// The first pedalboard chain. + /// + /// Add pedals via ``addToA(_:)`` (preferred) to keep ``finalize()`` ordering correct. + /// This property is public for read-only inspection and UI binding only. + public let boardA: PedalBoard + + /// The second pedalboard chain. + /// + /// Add pedals via ``addToB(_:)`` (preferred) to keep ``finalize()`` ordering correct. + /// This property is public for read-only inspection and UI binding only. + public let boardB: PedalBoard + + // MARK: - Routing nodes + + /// The splitter that distributes the shared input to both board head buses. + public let splitter: Splitter + + /// The merger that combines both board output buses. + /// `nil` until ``finalize()`` is called. + public private(set) var merger: Merger? + + // MARK: - Mode convenience + + /// Routing mode. Delegates to ``splitter``. + /// + /// - `.a` → board A audible, board B muted. + /// - `.b` → board B audible, board A muted. + /// - `.both` → both boards summed at the merger. + /// + /// Transitions are click-free (the splitter lags branch enables over 20 ms). + public var mode: SplitMode { + get { splitter.mode } + set { splitter.mode = newValue } + } + + // MARK: - Master stage + + /// The live master-gain `UIParamNode` for the router's output stage. `nil` until + /// ``finalize()`` is called. Bind a master-volume knob here. + public internal(set) var masterGainNode: UIParamNode? + + // MARK: - Private + + private let engine: SynthesisEngine + + /// The shared input source (either a `TestLoopSource` or `HardwareInputPassThrough`). + private let source: any Synthesizer + + /// The bus that the input source writes to, shared by both board head buses via the splitter. + private let routerInputBus: AudioBus + + /// The bus that the merger writes to, read by the `BoardOutputMaster`. + /// Allocated during ``finalize()``. + private var routerMixBus: AudioBus? + + /// The output master synth. `nil` until ``finalize()`` is called. + private var outputMaster: BoardOutputMaster? + + /// The board whose first pedal was added earliest (i.e. the board that received its first + /// `addToA` / `addToB` call first). Because each board's first pedal inserts + /// `.after(splitter)` and subsequent boards push the earlier board further down the + /// evaluation list, the first-populated board's tail node is always the last node + /// evaluated across both boards — regardless of populate order. ``finalize()`` uses + /// `firstPopulatedBoard.tailNode` to place the merger after the full tree. + /// + /// `nil` until the first `addToA` or `addToB` call. + private var firstPopulatedBoard: PedalBoard? + + /// Guard that prevents pedals being added after the merger has been inserted. + private var finalized: Bool = false + + // MARK: - Init + + /// Creates a chain router backed by `engine` with the given input source policy. + /// + /// Allocates `routerInputBus`, adds the input source to the engine, creates `boardA` + /// and `boardB` (each with their own `headBus`), creates the `Splitter` and adds it + /// after the source, then sets both boards' `headInputNode` to the splitter so the + /// first pedal on each board chains after the splitter automatically. + /// + /// Call ``finalize()`` after all pedals have been added to both boards via + /// ``addToA(_:)`` and ``addToB(_:)``. + /// + /// - Parameters: + /// - engine: The `SynthesisEngine` that will own all nodes. + /// - inputSource: How the shared input bus is fed. Defaults to `.testLoop`. + /// - Throws: + /// - `ShoeGazeError.liveInputRequiresInputChannels` when `.liveInput` is used + /// but `engine.numInputChannels == 0`. + /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. + /// - `EngineAddError` if the engine rejects any node insertion. + public init( + engine: SynthesisEngine, + inputSource: InputSource = .testLoop + ) throws { + self.engine = engine + + // Step 1 — allocate the shared input bus. + let inputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + self.routerInputBus = inputBus + + // Step 2 — add the input source that writes the shared input bus. + let addedSource: any Synthesizer + switch inputSource { + case .testLoop: + let loop: TestLoopSource = TestLoopSource(targetBus: inputBus.index) + try engine.add(loop) + addedSource = loop + + case .liveInput(let channel): + let hardwareInputBusIndex: Int + do { + hardwareInputBusIndex = try liveInputBusIndex(channel: channel, engine: engine) + } catch { + engine.busAllocator.releaseAudioBus(inputBus) + throw error + } + let passThrough: HardwareInputPassThrough = HardwareInputPassThrough( + inputBusIndex: hardwareInputBusIndex, + outputBusIndex: inputBus.index + ) + try engine.add(passThrough) + addedSource = passThrough + } + self.source = addedSource + + // Step 3 — create both boards (each allocates its own head bus). + let createdBoardA: PedalBoard = try PedalBoard(engine: engine) + let createdBoardB: PedalBoard = try PedalBoard(engine: engine) + self.boardA = createdBoardA + self.boardB = createdBoardB + + // Step 4 — create the splitter and insert it after the source. + let builtSplitter: Splitter = Splitter( + inputBus: inputBus.index, + outputBusA: createdBoardA.headBus.index, + outputBusB: createdBoardB.headBus.index + ) + try engine.add(builtSplitter, position: .after(addedSource)) + self.splitter = builtSplitter + + // Step 5 — point each board's headInputNode at the splitter so the first + // pedal on each board is inserted `.after(splitter)` automatically. + createdBoardA.headInputNode = builtSplitter + createdBoardB.headInputNode = builtSplitter + } + + // MARK: - Pedal add helpers + + /// Appends a pedal to board A and, on the first call across either board, records + /// board A as the first-populated board so ``finalize()`` can correctly place the + /// merger after the full evaluation tree. + /// + /// - Parameter pedal: The pedal to append to board A's signal chain. + /// - Throws: + /// - `ShoeGazeError.routerAlreadyFinalized` if ``finalize()`` has already been called. + /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. + /// - `EngineAddError` if the engine rejects the add. + public func addToA(_ pedal: Pedal) throws { + guard !finalized else { throw ShoeGazeError.routerAlreadyFinalized } + try boardA.add(pedal) + // Record the first board to receive a pedal. The first-populated board's first + // pedal inserts `.after(splitter)`; subsequent boards push it further down the + // tree, making the first-populated board's tail always the last evaluated node. + if firstPopulatedBoard == nil { firstPopulatedBoard = boardA } + } + + /// Appends a pedal to board B and, on the first call across either board, records + /// board B as the first-populated board so ``finalize()`` can correctly place the + /// merger after the full evaluation tree. + /// + /// - Parameter pedal: The pedal to append to board B's signal chain. + /// - Throws: + /// - `ShoeGazeError.routerAlreadyFinalized` if ``finalize()`` has already been called. + /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available. + /// - `EngineAddError` if the engine rejects the add. + public func addToB(_ pedal: Pedal) throws { + guard !finalized else { throw ShoeGazeError.routerAlreadyFinalized } + try boardB.add(pedal) + // See addToA — only the first call across either board sets firstPopulatedBoard. + if firstPopulatedBoard == nil { firstPopulatedBoard = boardB } + } + + // MARK: - Finalize + + /// Completes the router by inserting the merger and output master into the engine. + /// + /// The merger is inserted after ``lastInsertedNode`` — the most recently added pedal + /// across either board (via ``addToA(_:)`` / ``addToB(_:)``), or the splitter when + /// neither board has any pedals. This placement is correct regardless of whether + /// board A or board B was populated first. The `BoardOutputMaster` is inserted + /// immediately after the merger and writes stereo hardware output buses 0 and 1. + /// + /// After `finalize()` returns, calls to ``addToA(_:)`` / ``addToB(_:)`` throw + /// `ShoeGazeError.routerAlreadyFinalized`. + /// + /// - Throws: + /// - `BusAllocatorError.noFreeBus` if no mono audio bus is available for the mix bus. + /// - `EngineAddError` if the engine rejects the merger or master node. + public func finalize() throws { + // Finalize step 1 — allocate the mix bus and create the merger. + let mixBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + self.routerMixBus = mixBus + + let builtMerger: Merger = Merger( + inputBusA: boardA.outputBus.index, + inputBusB: boardB.outputBus.index, + outputBus: mixBus.index + ) + + // Insert the merger after the true last node in the evaluation tree. + // + // Both boards set headInputNode = splitter, so each board's first pedal inserts + // `.after(splitter)`. The second board to add its first pedal pushes the first + // board's chain further down the list. Therefore the board whose first pedal was + // added FIRST always has its tail node last in the tree — `firstPopulatedBoard` + // captures this. Fall back to the splitter when neither board has any pedals. + let mergerPredecessor: any Synthesizer = firstPopulatedBoard?.tailNode ?? splitter + try engine.add(builtMerger, position: .after(mergerPredecessor)) + self.merger = builtMerger + + // Finalize step 2 — create the output master and insert it after the merger. + let master: BoardOutputMaster = BoardOutputMaster(boardOutputBusIndex: mixBus.index) + try engine.add(master, position: .after(builtMerger)) + self.outputMaster = master + self.masterGainNode = master.gainNode + + finalized = true + } + + // MARK: - Teardown + + /// Removes all router-owned nodes from the engine and releases the router buses. + /// + /// Calls `boardA.teardown()` and `boardB.teardown()` to remove pedals and release + /// board buses. The router's own nodes (master, merger, splitter, source) are + /// removed first so no node writes to a bus after it has been released. + /// + /// - Important: Call only after the engine has been stopped, or accept one block + /// of glitch on a still-running engine. `engine.remove(_:)` only enqueues removal; + /// the actual dequeue happens on the next render block. Releasing buses immediately + /// after enqueue means a still-running engine could write to a reallocated bus for + /// one block. The buses are pooled (not freed), so worst case is a transient glitch, + /// not a crash. Stop the engine first to avoid this. + public func teardown() { + // Remove master and merger (writers of routerMixBus) before releasing it. + if let master: BoardOutputMaster = outputMaster { + engine.remove(master) + } + if let builtMerger: Merger = merger { + engine.remove(builtMerger) + } + // Remove splitter and source before boards release their head buses. + engine.remove(splitter) + engine.remove(source) + + // Remove all pedals from both boards and release board buses. + boardA.teardown() + boardB.teardown() + + // Release the router-owned buses. + if let mixBus: AudioBus = routerMixBus { + engine.busAllocator.releaseAudioBus(mixBus) + } + engine.busAllocator.releaseAudioBus(routerInputBus) + } +} diff --git a/Sources/LyrebirdShoeGaze/Routing/Merger.swift b/Sources/LyrebirdShoeGaze/Routing/Merger.swift new file mode 100644 index 0000000..7c3c306 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/Merger.swift @@ -0,0 +1,87 @@ +// Merger.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Sums two branch buses to a single output bus with independent per-branch levels. +/// +/// Intended as the downstream companion to ``Splitter`` when combining two parallel +/// signal paths back into a single chain. Each branch contributes its signal scaled +/// by its level parameter; the two scaled signals are summed into `outputBus`. +/// +/// ## Signal graph +/// +/// ``` +/// inputBusA → In.Audio × levelA ──┐ +/// + → outputBus +/// inputBusB → In.Audio × levelB ──┘ +/// ``` +/// +/// ## Parameters +/// +/// - `levelA`: Gain applied to branch A before summing. `1.0` = unity gain, `0.0` = muted. +/// - `levelB`: Gain applied to branch B before summing. `1.0` = unity gain, `0.0` = muted. +/// +/// > Note: With both defaults at `1.0`, two branches carrying the same signal sum to +/// > approximately 2× amplitude. In normal use the ``Splitter`` routes independent bus +/// > paths to each branch, so they carry different signals and this doubling does not +/// > occur. For an empty (pass-through) branch with `levelA = levelB = 1.0`, lower +/// > one of the levels or attenuate in the signal chain to avoid the additive boost. +/// +/// - Parameters: +/// - inputBusA: Audio bus index from which branch A's signal is read. +/// - inputBusB: Audio bus index from which branch B's signal is read. +/// - outputBus: Audio bus index to which the summed output is written. +public final class Merger: SynthesizerBase { + + // MARK: - Parameters + + /// Level for branch A. `1.0` = unity gain, `0.0` = muted. + @UIParam public var levelA: Double = 1.0 + + /// Level for branch B. `1.0` = unity gain, `0.0` = muted. + @UIParam public var levelB: Double = 1.0 + + // MARK: - Routing + + /// Audio bus index from which branch A's signal is read. + public internal(set) var inputBusA: Int + + /// Audio bus index from which branch B's signal is read. + public internal(set) var inputBusB: Int + + /// Audio bus index to which the summed output is written. + public internal(set) var outputBus: Int + + // MARK: - Init + + /// Creates a merger that sums two branch buses into one output bus. + /// + /// - Parameters: + /// - inputBusA: Audio bus index from which branch A's signal is read. + /// - inputBusB: Audio bus index from which branch B's signal is read. + /// - outputBus: Audio bus index to which the summed output is written. + public init( + inputBusA: Int, + inputBusB: Int, + outputBus: Int + ) { + self.inputBusA = inputBusA + self.inputBusB = inputBusB + self.outputBus = outputBus + super.init() + } + + // MARK: - Build + + /// Builds the signal graph: (inputBusA × levelA) + (inputBusB × levelB) → outputBus. + public override func build() { + let sigA: In.Audio = input(bus: inputBusA) + let sigB: In.Audio = input(bus: inputBusB) + output(bus: outputBus, source: (sigA * $levelA) + (sigB * $levelB)) + } +} diff --git a/Sources/LyrebirdShoeGaze/Routing/ParallelSection.swift b/Sources/LyrebirdShoeGaze/Routing/ParallelSection.swift new file mode 100644 index 0000000..14f70a1 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/ParallelSection.swift @@ -0,0 +1,79 @@ +// ParallelSection.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A parallel signal-routing section inside a ``PedalBoard``. +/// +/// A `ParallelSection` is created by ``PedalBoard/split()`` and holds the two independent +/// branch sub-chains plus the ``Splitter`` node that feeds them. After adding pedals to each +/// branch, pass the section to ``PedalBoard/merge(_:)`` to combine the branches back into +/// the main board chain. +/// +/// ## Typical usage +/// +/// ```swift +/// let section = try board.split() +/// try section.branchA.add(DelayPedal()) +/// try section.branchB.add(FuzzPedal()) +/// try board.merge(section) +/// // Further board.add(_:) calls chain after the merger. +/// ``` +/// +/// ## Evaluation order +/// +/// Both branches share a single `SharedTail` tracking pointer so all pedals from both +/// branches are inserted in a flat linear sequence in the node tree. Signal-flow parallelism +/// is expressed via independent buses, not via tree structure: +/// +/// ``` +/// … → Splitter → [branchA pedals] → [branchB pedals] → Merger → … +/// ``` +/// +/// The merger is inserted after the `SharedTail` — i.e. after the last pedal added across +/// either branch — so all branch pedals have written their output buses before the merger reads +/// them. This guarantees correctness regardless of the order in which the caller adds pedals to +/// the two branches. +@MainActor +public final class ParallelSection { + + // MARK: - Nodes and chains + + /// The splitter that routes the pre-section signal into the two branches. + public let splitter: Splitter + + /// Sub-chain A of this parallel section. + public let branchA: BranchChain + + /// Sub-chain B of this parallel section. + public let branchB: BranchChain + + /// Shared tail pointer updated by both branch chains. Used by ``PedalBoard/merge(_:)`` + /// to determine the node after which the merger should be inserted. + internal let sharedTail: SharedTail + + // MARK: - Init + + /// Creates a parallel section. Called internally by ``PedalBoard/split()``. + /// + /// - Parameters: + /// - splitter: The ``Splitter`` node that fans out into the two branches. + /// - branchA: The first branch sub-chain, fed by the splitter's A output bus. + /// - branchB: The second branch sub-chain, fed by the splitter's B output bus. + /// - sharedTail: The shared tail tracking pointer used by both branch chains. + init( + splitter: Splitter, + branchA: BranchChain, + branchB: BranchChain, + sharedTail: SharedTail + ) { + self.splitter = splitter + self.branchA = branchA + self.branchB = branchB + self.sharedTail = sharedTail + } +} diff --git a/Sources/LyrebirdShoeGaze/Routing/SplitMode.swift b/Sources/LyrebirdShoeGaze/Routing/SplitMode.swift new file mode 100644 index 0000000..1c4648c --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/SplitMode.swift @@ -0,0 +1,27 @@ +// SplitMode.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Routing mode for a ``Splitter``. +/// +/// Controls which of the two output branches carries signal: +/// +/// - `.a`: Only branch A passes; branch B is muted. +/// - `.b`: Only branch B passes; branch A is muted. +/// - `.both`: Both branches carry the full input signal (parallel operation). +/// +/// Transitions between modes are click-free because the ``Splitter`` applies +/// a lag to each branch enable value. +public enum SplitMode: String, Codable, CaseIterable { + + /// Branch A active, branch B muted. + case a + + /// Branch B active, branch A muted. + case b + + /// Both branches active (parallel routing). + case both +} diff --git a/Sources/LyrebirdShoeGaze/Routing/Splitter.swift b/Sources/LyrebirdShoeGaze/Routing/Splitter.swift new file mode 100644 index 0000000..896dcba --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Routing/Splitter.swift @@ -0,0 +1,129 @@ +// Splitter.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Routes one input bus to two independent output buses with click-free per-branch enables. +/// +/// Both branches read the same input signal. Each branch level is lagged through a +/// ``Lag.Control`` so enable/disable transitions are artefact-free (no abrupt cuts). +/// +/// Use ``mode`` as a convenience setter to configure common routing patterns: +/// - `.a` → branch A on, branch B muted +/// - `.b` → branch B on, branch A muted +/// - `.both` → both branches active (full parallel routing) +/// +/// ## Signal graph +/// +/// ``` +/// inputBus → In.Audio +/// ├── × Lag(branchAEnabled) → outputBusA +/// └── × Lag(branchBEnabled) → outputBusB +/// ``` +/// +/// ## Parameters +/// +/// - `branchAEnabled`: Branch A level. `1.0` = passing, `0.0` = muted. +/// - `branchBEnabled`: Branch B level. `1.0` = passing, `0.0` = muted. +/// +/// - Parameters: +/// - inputBus: Audio bus index to read the input signal from. +/// - outputBusA: Audio bus index to write branch A's output to. +/// - outputBusB: Audio bus index to write branch B's output to. +public final class Splitter: SynthesizerBase { + + // MARK: - Parameters + + /// Branch A level. `1.0` = passing, `0.0` = muted. Transitions are click-free. + @UIParam public var branchAEnabled: Double = 1.0 + + /// Branch B level. `1.0` = passing, `0.0` = muted. Transitions are click-free. + @UIParam public var branchBEnabled: Double = 1.0 + + // MARK: - Routing + + /// Audio bus index from which the input signal is read. + public internal(set) var inputBus: Int + + /// Audio bus index to which branch A's output is written. + public internal(set) var outputBusA: Int + + /// Audio bus index to which branch B's output is written. + public internal(set) var outputBusB: Int + + // MARK: - Constants + + /// Lag time in seconds for branch enable transitions. + /// Prevents audible clicks when toggling a branch on or off. + private let switchLagTime: Double = 0.02 + + /// Threshold above which an enable value is treated as "on" for ``mode`` getter. + private let enableThreshold: Double = 0.5 + + // MARK: - Init + + /// Creates a splitter that routes one input bus to two branch buses. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the input signal from. + /// - outputBusA: Audio bus index to write branch A's output to. + /// - outputBusB: Audio bus index to write branch B's output to. + public init( + inputBus: Int, + outputBusA: Int, + outputBusB: Int + ) { + self.inputBus = inputBus + self.outputBusA = outputBusA + self.outputBusB = outputBusB + super.init() + } + + // MARK: - Mode convenience + + /// Routing mode derived from the current branch enable values. + /// + /// - Getting: Returns `.both` if both enables are ≥ 0.5; `.a` if only branch A + /// is ≥ 0.5; `.b` if only branch B is ≥ 0.5. Returns `.a` if both are below 0.5 + /// (neither branch active — `.a` is the least-surprising fallback). + /// - Setting: Updates `branchAEnabled` and `branchBEnabled` to match the chosen mode. + /// `.a` → (1, 0); `.b` → (0, 1); `.both` → (1, 1). Transitions are click-free. + public var mode: SplitMode { + get { + let aOn: Bool = branchAEnabled >= enableThreshold + let bOn: Bool = branchBEnabled >= enableThreshold + if aOn && bOn { return .both } + if aOn { return .a } + if bOn { return .b } + return .a + } + set { + switch newValue { + case .a: + branchAEnabled = 1.0 + branchBEnabled = 0.0 + case .b: + branchAEnabled = 0.0 + branchBEnabled = 1.0 + case .both: + branchAEnabled = 1.0 + branchBEnabled = 1.0 + } + } + } + + // MARK: - Build + + /// Builds the signal graph: input → lagged per-branch gain → two output buses. + public override func build() { + let inSig: In.Audio = input(bus: inputBus) + let gainA: Lag.Control = Lag.Control(input: $branchAEnabled, time: switchLagTime) + let gainB: Lag.Control = Lag.Control(input: $branchBEnabled, time: switchLagTime) + output(bus: outputBusA, source: inSig * gainA) + output(bus: outputBusB, source: inSig * gainB) + } +} diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift new file mode 100644 index 0000000..4a14f0a --- /dev/null +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -0,0 +1,395 @@ +// ShoeGaze.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import Observation +import LyrebirdSynth +import LyrebirdUI + +// MARK: - ShoeGaze + +/// Top-level manager for a collection of `PedalBoard`s connected to a `SynthesisEngine`. +/// +/// `ShoeGaze` allocates and connects input sources, board chains, and a master output +/// stage. The caller owns the `SynthesisEngine` lifecycle (`engine.start()` / +/// `engine.stop()`). +/// +/// ## Typical usage +/// +/// ```swift +/// let driver = CoreAudioDriver() +/// let engine = SynthesisEngine( +/// blockSize: 512, sampleRate: 44100, +/// numOutputChannels: 2, numInputChannels: 0, driver: driver +/// ) +/// let sg = try ShoeGaze(engine: engine) +/// let board = try sg.addBoard() +/// try board.add(OverdrivePedal()) +/// try board.add(ReverbPedal()) +/// try engine.start() +/// ``` +/// +/// ## Input routing +/// +/// When `inputSource == .testLoop`, a `TestLoopSource` is added to the engine +/// **before** the first pedal on each board (plain `engine.add` places it at the +/// head of `mainGroup`, so it evaluates first). +/// +/// When `inputSource == .liveInput(channel:)`, a `HardwareInputPassThrough` synthesizer +/// copies hardware input `channel` (engine bus `numOutputChannels + channel`) to the +/// board's head bus. This ensures the first pedal reads from a board-owned bus, not the +/// raw hardware input bus. The engine must be created with `numInputChannels > channel`; +/// otherwise `addBoard()` throws `ShoeGazeError.liveInputRequiresInputChannels` (no input +/// channels) or `.inputChannelOutOfRange` (channel too high). +/// +/// ## Master stage +/// +/// Each board's output bus is read by a `BoardOutputMaster` synth added **after** +/// the board's last pedal via `.after(_:)`. The master pans the mono board signal +/// to stereo and writes to hardware buses 0 (left) and 1 (right). +@MainActor +@Observable +public final class ShoeGaze { + + // MARK: - Public state + + /// The engine that owns all nodes. + public let engine: SynthesisEngine + + /// All boards managed by this instance. + public private(set) var boards: [PedalBoard] = [] + + /// Input source policy. Affects how `addBoard()` routes signal to the head bus. + public var inputSource: InputSource + + // MARK: - Recording state + + /// The folder into which `startRecording()` writes timestamped WAV files. + /// + /// Set this before calling `startRecording()`. If `nil`, `startRecording()` throws + /// `ShoeGazeError.recordingFolderNotSet`. The folder is created if it does not exist. + public var recordingFolder: URL? + + /// `true` while recording is in progress (between `startRecording()` and `stopRecording()`). + /// + /// The setter is `internal` so that `ShoeGaze+Recording.swift` (same module, different file) + /// can toggle this flag; external callers only observe the value through this `public` getter. + public internal(set) var isRecording: Bool = false + + /// Active `RecordTap` instances (output + optional input). Populated by `startRecording()`, + /// cleared by `stopRecording()`. `internal` so the extension in `ShoeGaze+Recording.swift` + /// (same module, different file) can mutate it. + internal var recordTaps: [RecordTap] = [] + + // MARK: - Private + + private var testLoopSources: [TestLoopSource] = [] + private var inputPassThroughs: [HardwareInputPassThrough] = [] + private var outputMasters: [BoardOutputMaster] = [] + + /// All chain routers created via ``makeChainRouter()``. + /// Routers are torn down (in reverse-creation order) by ``teardown()``. + private var routers: [ChainRouter] = [] + + // MARK: - Init + + /// Creates a `ShoeGaze` manager backed by the given engine. + /// + /// The caller retains ownership of `engine` and is responsible for calling + /// `engine.start()` and `engine.stop()`. + /// + /// - Parameters: + /// - engine: The `SynthesisEngine` to add synthesizers and boards to. + /// - inputSource: How the board head bus is fed. Defaults to `.testLoop`. + public init( + engine: SynthesisEngine, + inputSource: InputSource = .testLoop + ) { + self.engine = engine + self.inputSource = inputSource + } + + // MARK: - Board management + + /// Allocates a new `PedalBoard` connected to the engine, wires the input source, + /// and returns the board ready for pedals to be added via `board.add(_:)`. + /// + /// Call this before adding pedals. After all pedals have been added to the returned + /// board, call `finalizeBoard(_:)` to connect the output master. + /// + /// When `inputSource == .liveInput(channel:)`, a `HardwareInputPassThrough` is added + /// that copies hardware input bus `numOutputChannels + channel` to the board head bus. + /// The engine must have been created with `numInputChannels > channel`. + /// + /// - Returns: A configured `PedalBoard` with its head bus allocated and input source wired. + /// - Throws: + /// - `ShoeGazeError.liveInputRequiresInputChannels` if `.liveInput` is selected but + /// the engine has `numInputChannels == 0`. + /// - `BusAllocatorError.noFreeBus` if no mono bus is available. + /// - `EngineAddError` if the engine rejects a node insertion. + @discardableResult + public func addBoard() throws -> PedalBoard { + let board: PedalBoard = try PedalBoard(engine: engine) + board.label = "Board \(boards.count + 1)" + + // Route the input source to the board head bus. + switch inputSource { + case .testLoop: + let source: TestLoopSource = TestLoopSource(targetBus: board.headBus.index) + // Plain add → head of mainGroup (evaluates before any pedal). + try engine.add(source) + testLoopSources.append(source) + // Record the source as the head input node so PedalBoard.add(_:) can chain + // the first pedal after it automatically (without needing an explicit `after:`). + board.headInputNode = source + + case .liveInput(let channel): + // Hardware input channel `channel` lives at bus numOutputChannels + channel. + // A HardwareInputPassThrough copies it to the board's head bus so all pedals + // read from a board-owned bus (not the raw hardware input bus). + let hardwareInputBusIndex: Int = try liveInputBusIndex(channel: channel, engine: engine) + let passThrough: HardwareInputPassThrough = HardwareInputPassThrough( + inputBusIndex: hardwareInputBusIndex, + outputBusIndex: board.headBus.index + ) + try engine.add(passThrough) + inputPassThroughs.append(passThrough) + board.headInputNode = passThrough + } + + // Only record the board after all wiring has succeeded. This prevents + // orphaning a board (with an allocated head bus) in `boards` if the + // input-source add or the guard above throws. + boards.append(board) + return board + } + + /// Connects the output master for a previously prepared board and adds it to the engine. + /// + /// Call this after all pedals have been added to the board via `board.add(_:)`. + /// The master reads the board's current `outputBus` and routes it to hardware + /// outputs 0 and 1 in stereo. + /// + /// If the board has no pedals, the master is added `.after(headInputNode)` so it + /// evaluates after the input source has written the head bus. If no head input node + /// is present either, a plain add is used as a last resort. + /// + /// - Parameter board: A `PedalBoard` returned by `addBoard()` with pedals added. + /// - Throws: `EngineAddError` if the engine rejects the master node. + public func finalizeBoard(_ board: PedalBoard) throws { + let master: BoardOutputMaster = BoardOutputMaster( + boardOutputBusIndex: board.outputBus.index + ) + // The master evaluates after the entire chain (pedals, splitters, mergers). + // `board.tailNode` returns the last inserted node (any Synthesizer), which covers + // plain-pedal chains and parallel sections containing routing nodes alike. + if let tail: any Synthesizer = board.tailNode { + // Normal case: chain after the last node in the board. + try engine.add(master, position: .after(tail)) + } else { + // No nodes and no head input node (unusual): plain add. + try engine.add(master) + } + outputMasters.append(master) + // Expose the master to the board so the UI can bind a master-volume knob + // and `removeBoard(_:)` can tear down just this board's master. + board.outputMaster = master + board.masterGainNode = master.gainNode + board.selectGainNode = master.selectGainNode + board.crossfadeTimeNode = master.crossfadeTimeNode + + // If a board is currently soloed, a newly-finalized board must come up silent + // (select-gain 0) so it doesn't leak audio past the active solo. + if let soloIndex: Int = activeBoardIndex, + let newIndex: Int = boards.firstIndex(where: { $0 === board }), + newIndex != soloIndex { + master.selectGainNode.update(0.0) + } + } + + // MARK: - Board selection / crossfade + + /// The index of the currently soloed board in ``boards``, or `nil` when all boards + /// are audible (the default — every board's output sums to the hardware output). + public private(set) var activeBoardIndex: Int? + + /// Crossfades so only `board` is audible, fading the others out. + /// + /// Sets every board's crossfade time to `crossfadeSeconds`, then ramps the selected + /// board's select-gain to `1` and all others to `0`. Each board's `BoardOutputMaster` + /// lags the select-gain, so the transition is a click-free crossfade of that duration. + /// The per-board master-volume knob is unaffected. + /// + /// - Parameters: + /// - board: The board to make audible. No-op if not managed by this instance. + /// - crossfadeSeconds: Crossfade duration in seconds (`0` = instant). + public func selectBoard(_ board: PedalBoard, crossfadeSeconds: Double) { + guard let index: Int = boards.firstIndex(where: { $0 === board }) else { return } + for (offset, managed): (Int, PedalBoard) in boards.enumerated() { + managed.crossfadeTimeNode?.update(crossfadeSeconds) + managed.selectGainNode?.update(offset == index ? 1.0 : 0.0) + } + activeBoardIndex = index + } + + /// Crossfades all boards back to audible (the default summed state). + /// + /// - Parameter crossfadeSeconds: Crossfade duration in seconds (`0` = instant). + public func selectAllBoards(crossfadeSeconds: Double) { + for managed: PedalBoard in boards { + managed.crossfadeTimeNode?.update(crossfadeSeconds) + managed.selectGainNode?.update(1.0) + } + activeBoardIndex = nil + } + + /// Removes a single board and its associated input source and output master from + /// the engine, then releases the board's buses. The other boards are unaffected. + /// + /// - Important: Same async-removal caveat as ``teardown()`` — call with the engine + /// stopped, or accept up to one block of glitch on a still-running engine. + /// + /// - Parameter board: A board previously returned by ``addBoard()``. No-op if the + /// board is not managed by this instance. + public func removeBoard(_ board: PedalBoard) { + guard let index: Int = boards.firstIndex(where: { $0 === board }) else { return } + + // Stop any active recording before removing the board. The record taps in .testLoop + // mode read the first board's headBus; in .liveInput mode they read a hardware input + // bus that is valid until the board's input pass-through is removed. Either way, + // removing a board while recording could leave the input tap reading a released or + // reused bus. Stopping first ensures all taps are removed before any bus is freed. + if isRecording { + stopRecording() + } + + // Remove the board's output master (writer of the hardware output bus). + if let master: BoardOutputMaster = board.outputMaster { + engine.remove(master) + outputMasters.removeAll { $0 === master } + } + + // Remove the board's input source (writer of the head bus). + if let testLoop: TestLoopSource = board.headInputNode as? TestLoopSource { + engine.remove(testLoop) + testLoopSources.removeAll { $0 === testLoop } + } else if let passThrough: HardwareInputPassThrough = board.headInputNode as? HardwareInputPassThrough { + engine.remove(passThrough) + inputPassThroughs.removeAll { $0 === passThrough } + } + + // Remove the pedals and release the board's buses. + board.teardown() + boards.remove(at: index) + } + + // MARK: - Chain router + + /// Creates a ``ChainRouter`` that routes one shared input to two independent + /// ``PedalBoard`` chains and merges their outputs through a single master stage. + /// + /// The router is tracked internally and torn down automatically by ``teardown()``. + /// Do **not** also add the router's boards via ``addBoard()`` — the router owns + /// their lifecycle. + /// + /// Typical usage: + /// + /// ```swift + /// let router = try shoeGaze.makeChainRouter() + /// try router.boardA.add(OverdrivePedal()) + /// try router.boardB.add(DelayPedal()) + /// try router.finalize() + /// router.mode = .both + /// try engine.start() + /// ``` + /// + /// - Returns: A ``ChainRouter`` with both boards ready to receive pedals. + /// - Throws: + /// - `ShoeGazeError.liveInputRequiresInputChannels` when `inputSource == .liveInput` + /// but `engine.numInputChannels == 0`. + /// - `BusAllocatorError.noFreeBus` if no mono bus is available. + /// - `EngineAddError` if the engine rejects any node insertion. + @discardableResult + public func makeChainRouter() throws -> ChainRouter { + let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource) + routers.append(router) + return router + } + + // MARK: - Internal board reordering + + /// Moves `board` to `targetIndex` within `boards`, locating it by identity. + /// + /// This is an internal helper that mutates `boards` directly — valid only because + /// `ShoeGaze` is `@MainActor` (no concurrent access). The method is `internal` rather than + /// `public` so callers outside the ShoeGaze module cannot disrupt board ordering. + /// + /// - Parameters: + /// - board: The `PedalBoard` to reposition. No-op if not found in `boards`. + /// - index: The desired destination index. Clamped to `boards.count` after removal + /// so it is always a valid insertion point. + internal func moveBoard(_ board: PedalBoard, to index: Int) { + guard let sourceIndex: Int = boards.firstIndex(where: { $0 === board }) else { return } + let removed: PedalBoard = boards.remove(at: sourceIndex) + let destination: Int = min(index, boards.count) + boards.insert(removed, at: destination) + } + + // MARK: - Teardown + + /// Removes all nodes (test sources, input pass-throughs, pedals, masters) from + /// the engine and releases all allocated buses. + /// + /// - Important: Call only after the engine has been stopped, or accept one block + /// of glitch on a still-running engine. `engine.remove(_:)` only enqueues removal; + /// the actual dequeue happens on the next render block. Releasing buses immediately + /// after enqueue means a still-running engine could write to a reallocated bus for + /// one block. The buses are pooled (not freed), so worst case is a transient glitch, + /// not a crash. Stop the engine first to avoid this. + /// + /// All engine nodes that write board buses are removed **before** any + /// `board.teardown()` releases buses back to the allocator, preserving the + /// remove-before-release ordering. + public func teardown() { + // Step 0: Stop any active recording before removing board nodes. This ensures + // the record taps are removed and their DiskOut handles are closed before the + // board buses they reference are released. + stopRecording() + + // Step 1: Remove all engine nodes that write to board buses. + // Order within this step does not matter; all must finish before bus release. + for source: TestLoopSource in testLoopSources { + engine.remove(source) + } + testLoopSources.removeAll() + + for passThrough: HardwareInputPassThrough in inputPassThroughs { + engine.remove(passThrough) + } + inputPassThroughs.removeAll() + + for master: BoardOutputMaster in outputMasters { + engine.remove(master) + } + outputMasters.removeAll() + + // Step 2: Remove pedals from the engine and release all board-owned buses. + // board.teardown() removes pedals from the engine and then releases buses, + // so bus release only happens after all writers have been dequeued. + for board: PedalBoard in boards { + board.teardown() + } + boards.removeAll() + + // Step 3: Tear down all chain routers. Each router removes its own nodes and + // releases its buses (master → merger → splitter → source → board buses → + // router buses), maintaining the remove-before-release ordering. + for router: ChainRouter in routers { + router.teardown() + } + routers.removeAll() + } +} diff --git a/Sources/LyrebirdShoeGaze/ShoeGazeError.swift b/Sources/LyrebirdShoeGaze/ShoeGazeError.swift new file mode 100644 index 0000000..3a82605 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/ShoeGazeError.swift @@ -0,0 +1,61 @@ +// ShoeGazeError.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Errors thrown by `ShoeGaze` during board and session management. +public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable { + + /// Thrown by `ShoeGaze.addBoard()` when `inputSource == .liveInput` but the engine + /// was created with `numInputChannels == 0`. + /// + /// Re-create the `SynthesisEngine` with `numInputChannels > 0` before using `.liveInput`. + case liveInputRequiresInputChannels + + /// Thrown when `.liveInput(channel:)` requests a hardware input channel that is + /// negative or `>= numInputChannels`. `requested` is the channel asked for; + /// `available` is the engine's `numInputChannels`. + case inputChannelOutOfRange(requested: Int, available: Int) + + /// Thrown by `ChainRouter.addToA(_:)` or `addToB(_:)` when called after + /// ``ChainRouter/finalize()`` has already been invoked. + /// + /// Pedals must be added to the router's boards before `finalize()` so the merger + /// is placed after the full evaluation tree. Adding pedals after finalization would + /// leave them ordered before the merger in the node tree, causing stale-bus reads. + case routerAlreadyFinalized + + /// Thrown by `ShoeGaze.startRecording()` when `recordingFolder` is `nil`. + /// + /// Set `ShoeGaze.recordingFolder` to a `URL` pointing to the desired output + /// directory before calling `startRecording()`. + case recordingFolderNotSet + + /// Thrown by `ShoeGaze.startRecording()` when a `RecordTap`'s `DiskOut.Audio` + /// could not open the destination file (e.g. permissions, disk full). + /// + /// The `URL` identifies the file that could not be created. Any taps that + /// were successfully added before the failure are removed and the recording + /// session is not started. + case recordTapFailedToOpen(URL) + + // MARK: - LocalizedError + + public var errorDescription: String? { + switch self { + case .liveInputRequiresInputChannels: + return "ShoeGaze: .liveInput requires the engine to be created with numInputChannels > 0." + case .inputChannelOutOfRange(let requested, let available): + return "ShoeGaze: .liveInput channel \(requested) is out of range; engine has \(available) input channel(s)." + case .routerAlreadyFinalized: + return "ChainRouter: cannot add pedals after finalize() has been called." + case .recordingFolderNotSet: + return "ShoeGaze: set recordingFolder before calling startRecording()." + case .recordTapFailedToOpen(let url): + return "ShoeGaze: could not open recording file '\(url.lastPathComponent)'." + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/BoardEditorView.swift b/Sources/LyrebirdShoeGazeUI/BoardEditorView.swift new file mode 100644 index 0000000..660dbf0 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/BoardEditorView.swift @@ -0,0 +1,298 @@ +// BoardEditorView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// An interactive editor for a single `PedalBoard`. +/// +/// `BoardEditorView` binds to `ShoeGaze` (an `@Observable` class) and reads the live +/// board via `shoeGaze.boards[boardIndex]`. Because `ShoeGaze.boards` is an `@Observable` +/// tracked property, loading a version — which calls `shoeGaze.rebuildBoard(_:from:)` and +/// mutates `boards` in-place at the same index — triggers an automatic SwiftUI re-render +/// with the new board and its new pedal list without any manual refresh. +/// +/// ## Board-load re-binding +/// +/// `rebuildBoard(_:from:)` tears down the old board, calls `addBoard()`, and moves the +/// result back to `oldIndex`. The `boards` array is mutated on the main actor, so +/// `shoeGaze.boards[boardIndex]` — read fresh in `body` — always resolves to the current +/// board after a load. `BoardEditorView` never caches the `PedalBoard` reference itself; +/// the index is the stable anchor. +/// +/// ## Usage +/// +/// ```swift +/// BoardEditorView( +/// shoeGaze: shoeGaze, +/// boardIndex: 0, +/// versionStore: versionStore +/// ) +/// ``` +/// +/// - Parameters: +/// - shoeGaze: The `ShoeGaze` manager that owns the board. +/// - boardIndex: Index into `shoeGaze.boards`. If out of range, a small placeholder +/// is shown instead. +/// - versionStore: The `BoardVersionStore` that manages named snapshots. +public struct BoardEditorView: View { + + // MARK: - Layout constants + + private static let outerPadding: CGFloat = 16 + private static let headerSpacing: CGFloat = 10 + private static let sectionSpacing: CGFloat = 14 + private static let boardBackgroundRed: Double = 0.12 + private static let boardBackgroundGreen: Double = 0.10 + private static let boardBackgroundBlue: Double = 0.08 + private static let boardCornerRadius: CGFloat = 10 + private static let boardBorderBrightness: Double = 0.30 + private static let boardBorderOpacity: Double = 0.50 + private static let boardBorderLineWidth: CGFloat = 1 + private static let boardPedalAreaPadding: CGFloat = 16 + private static let labelFontSize: CGFloat = 17 + private static let placeholderOpacity: Double = 0.55 + private static let versionMenuMaxWidth: CGFloat = 280 + private static let versionRowSpacing: CGFloat = 6 + private static let versionDateOpacity: Double = 0.55 + private static let versionDateFontSize: CGFloat = 11 + private static let toolbarButtonSpacing: CGFloat = 8 + private static let textFieldMinWidth: CGFloat = 160 + private static let dividerOpacity: Double = 0.20 + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + private let boardIndex: Int + private let versionStore: BoardVersionStore + + /// The text typed into the version-name field before saving. + @State private var newVersionName: String = "" + + // MARK: - Date formatting + + /// Short date + time formatter used on version menu rows. + private static let savedAtStyle: Date.FormatStyle = Date.FormatStyle() + .month(.abbreviated) + .day(.defaultDigits) + .year(.defaultDigits) + .hour(.defaultDigits(amPM: .abbreviated)) + .minute(.twoDigits) + + // MARK: - Init + + /// Creates a board editor view. + /// + /// - Parameters: + /// - shoeGaze: The `ShoeGaze` manager that owns the board at `boardIndex`. + /// - boardIndex: Index into `shoeGaze.boards`. Renders a placeholder when out of range. + /// - versionStore: The `BoardVersionStore` that manages named snapshots for this board. + public init( + shoeGaze: ShoeGaze, + boardIndex: Int, + versionStore: BoardVersionStore + ) { + self.shoeGaze = shoeGaze + self.boardIndex = boardIndex + self.versionStore = versionStore + } + + // MARK: - Body + + public var body: some View { + if boardIndex < 0 || boardIndex >= shoeGaze.boards.count { + outOfRangePlaceholder + } else { + let board: PedalBoard = shoeGaze.boards[boardIndex] + editorContent(board: board) + } + } + + // MARK: - Main editor layout + + /// The primary editor layout when `boardIndex` is in range. + private func editorContent(board: PedalBoard) -> some View { + VStack(alignment: .leading, spacing: BoardEditorView.sectionSpacing) { + header(board: board) + Divider() + .overlay(Color.white.opacity(BoardEditorView.dividerOpacity)) + pedalArea(board: board) + } + .padding(BoardEditorView.outerPadding) + } + + // MARK: - Header + + /// Toolbar row: board label on the left, version controls on the right. + private func header(board: PedalBoard) -> some View { + VStack(alignment: .leading, spacing: BoardEditorView.headerSpacing) { + HStack(spacing: BoardEditorView.headerSpacing) { + Text(board.label) + .font(.system(size: BoardEditorView.labelFontSize, weight: .semibold)) + .foregroundStyle(Color.white) + Spacer() + diskButtons + } + HStack(spacing: BoardEditorView.toolbarButtonSpacing) { + versionNameField(board: board) + versionsMenu + } + } + } + + /// "Save to Disk" and "Load from Disk" buttons. Cross-platform; no file picker used. + private var diskButtons: some View { + HStack(spacing: BoardEditorView.toolbarButtonSpacing) { + Button("Save to Disk") { + try? versionStore.writeAllToDisk( + in: BoardVersionStore.defaultDirectory() + ) + } + .buttonStyle(.bordered) + + Button("Load from Disk") { + try? versionStore.loadAllFromDisk( + in: BoardVersionStore.defaultDirectory() + ) + } + .buttonStyle(.bordered) + } + } + + /// Version-name `TextField` + "Save Version" button. + private func versionNameField(board: PedalBoard) -> some View { + HStack(spacing: BoardEditorView.toolbarButtonSpacing) { + TextField("Version name…", text: $newVersionName) + .textFieldStyle(.roundedBorder) + .frame(minWidth: BoardEditorView.textFieldMinWidth) + + Button("Save Version") { + let effectiveName: String = newVersionName.isEmpty + ? "Version \(versionStore.versions.count + 1)" + : newVersionName + versionStore.capture(board, name: effectiveName) + newVersionName = "" + } + .buttonStyle(.borderedProminent) + .tint(.orange) + } + } + + /// A `Menu` listing all saved versions. + /// + /// Each version is represented by a nested `Menu` whose title is the version name. + /// Opening a version's sub-menu exposes two reliably-reachable actions: + /// - **Load** — calls `shoeGaze.rebuildBoard(_:from:)`, which tears down the old board, + /// builds a fresh one from the saved `BoardState`, and moves it back to `boardIndex`. + /// Because `ShoeGaze.boards` is `@Observable`, every view reading `shoeGaze.boards` + /// re-renders automatically with the replacement board. + /// - **Delete** — removes the version from memory AND from disk so that the deletion + /// survives the next `loadAllFromDisk` call. + private var versionsMenu: some View { + Menu { + if versionStore.versions.isEmpty { + Text("No saved versions") + } else { + ForEach(versionStore.versions) { version in + versionSubmenu(version: version) + } + } + } label: { + Label("Versions", systemImage: "clock.arrow.circlepath") + } + .menuStyle(.automatic) + .frame(maxWidth: BoardEditorView.versionMenuMaxWidth, alignment: .leading) + } + + /// A nested `Menu` for a single version with Load and Delete actions. + /// + /// Using a sub-menu rather than an `HStack` inside a single menu row ensures that + /// both buttons are independently hittable on every platform. + private func versionSubmenu(version: BoardVersion) -> some View { + let dateString: String = version.savedAt.formatted(BoardEditorView.savedAtStyle) + return Menu { + Button("Load") { + loadVersion(version) + } + Button("Delete", role: .destructive) { + versionStore.remove(version) + try? versionStore.deleteFromDisk(version, in: BoardVersionStore.defaultDirectory()) + } + } label: { + VStack(alignment: .leading, spacing: BoardEditorView.versionRowSpacing) { + Text(version.name) + Text(dateString) + .font(.system(size: BoardEditorView.versionDateFontSize)) + .foregroundStyle(Color.secondary.opacity(BoardEditorView.versionDateOpacity)) + } + } + } + + // MARK: - Pedal area + + /// Scrollable wrap-to-fit pedal area backed by `FlowLayout`. + private func pedalArea(board: PedalBoard) -> some View { + ScrollView(.vertical, showsIndicators: true) { + FlowLayout( + horizontalSpacing: FlowLayout.defaultHorizontalSpacing, + verticalSpacing: FlowLayout.defaultVerticalSpacing + ) { + ForEach(Array(board.pedals.enumerated()), id: \.offset) { pair in + let pedal: Pedal = pair.element + PedalView(pedal: pedal) + } + } + .padding(BoardEditorView.boardPedalAreaPadding) + } + .background( + RoundedRectangle(cornerRadius: BoardEditorView.boardCornerRadius) + .fill( + Color( + red: BoardEditorView.boardBackgroundRed, + green: BoardEditorView.boardBackgroundGreen, + blue: BoardEditorView.boardBackgroundBlue + ) + ) + .overlay( + RoundedRectangle(cornerRadius: BoardEditorView.boardCornerRadius) + .stroke( + Color(white: BoardEditorView.boardBorderBrightness) + .opacity(BoardEditorView.boardBorderOpacity), + lineWidth: BoardEditorView.boardBorderLineWidth + ) + ) + ) + } + + // MARK: - Out-of-range placeholder + + /// Shown when `boardIndex` is outside `shoeGaze.boards`. + private var outOfRangePlaceholder: some View { + Text("No board at index \(boardIndex).") + .foregroundStyle(Color.secondary.opacity(BoardEditorView.placeholderOpacity)) + .padding(BoardEditorView.outerPadding) + } + + // MARK: - Version loading + + /// Loads `version` back into the board at `boardIndex`. + /// + /// `rebuildBoard(_:from:)` tears down the old board, allocates a new one populated + /// from `version.state`, finalises it, and moves it back to `boardIndex`. Because + /// `ShoeGaze` is `@Observable` and `boards` is a tracked property, the mutation + /// causes this view to re-render immediately with the replacement board — no manual + /// state refresh needed. + private func loadVersion(_ version: BoardVersion) { + guard boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return } + let board: PedalBoard = shoeGaze.boards[boardIndex] + do { + _ = try shoeGaze.rebuildBoard(board, from: version.state) + } catch { + print("[BoardEditorView] rebuildBoard failed: \(error)") + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ChainRouterView.swift b/Sources/LyrebirdShoeGazeUI/ChainRouterView.swift new file mode 100644 index 0000000..ae33236 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/ChainRouterView.swift @@ -0,0 +1,164 @@ +// ChainRouterView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// Renders a ``ChainRouter`` as a vertical stack with transport controls, two labelled +/// board rows, and a merger + optional master-gain output stage. +/// +/// Layout (top → bottom): +/// 1. **Header row** — ``SplitterView`` on the left; if `router.masterGainNode` is +/// non-nil, a "Master" ``ParameterKnob`` on the right. +/// 2. **Board A row** — label "A" followed by ``PedalBoardView`` for `router.boardA`. +/// 3. **Board B row** — label "B" followed by ``PedalBoardView`` for `router.boardB`. +/// 4. **Footer row** — ``MergerView`` for `router.merger` (shown only once finalize +/// has been called and `router.merger` is non-nil). +/// +/// `merger` is optional on `ChainRouter` (nil before `finalize()`) — the footer is +/// conditionally shown so the view is usable at any lifecycle stage. +/// +/// ## Usage +/// +/// ```swift +/// ChainRouterView(router: chainRouter) +/// ``` +public struct ChainRouterView: View { + + // MARK: - Layout constants + + private static let outerSpacing: CGFloat = 16 + private static let headerSpacing: CGFloat = 14 + private static let boardRowSpacing: CGFloat = 8 + private static let boardLabelFontSize: CGFloat = 11 + private static let boardLabelOpacity: Double = 0.55 + private static let masterLabelFontSize: CGFloat = 11 + private static let masterLabelOpacity: Double = 0.45 + private static let masterKnobSpacing: CGFloat = 6 + private static let footerSpacing: CGFloat = 14 + private static let outerPaddingH: CGFloat = 12 + private static let outerPaddingV: CGFloat = 12 + private static let sectionDividerOpacity: Double = 0.12 + private static let sectionDividerHeight: CGFloat = 1 + /// Master gain range: 0 = silence, 1 = unity output. + private static let masterGainRange: ClosedRange = 0.0...1.0 + /// Background colour for the router enclosure (darker than stage floor). + private static let backgroundRed: Double = 0.11 + private static let backgroundGreen: Double = 0.10 + private static let backgroundBlue: Double = 0.13 + private static let backgroundCornerRadius: CGFloat = 10 + private static let backgroundBorderOpacity: Double = 0.30 + private static let backgroundBorderLineWidth: CGFloat = 1.0 + + // MARK: - Properties + + private let router: ChainRouter + + // MARK: - Init + + /// Creates a chain router view for the given ``ChainRouter``. + /// + /// - Parameter router: The `ChainRouter` to display. Board A/B pedal views, the + /// splitter mode picker, the merger mix knobs, and the optional master gain knob + /// are all derived from this instance. The view correctly handles the pre-`finalize()` + /// state where `router.merger` and `router.masterGainNode` are `nil`. + public init(router: ChainRouter) { + self.router = router + } + + // MARK: - Body + + public var body: some View { + VStack(alignment: .leading, spacing: ChainRouterView.outerSpacing) { + headerRow + sectionDivider + boardRow(label: "A", board: router.boardA) + sectionDivider + boardRow(label: "B", board: router.boardB) + if let builtMerger: Merger = router.merger { + sectionDivider + footerRow(merger: builtMerger) + } + } + .padding(.horizontal, ChainRouterView.outerPaddingH) + .padding(.vertical, ChainRouterView.outerPaddingV) + .background( + RoundedRectangle(cornerRadius: ChainRouterView.backgroundCornerRadius) + .fill(Color( + red: ChainRouterView.backgroundRed, + green: ChainRouterView.backgroundGreen, + blue: ChainRouterView.backgroundBlue + )) + .overlay( + RoundedRectangle(cornerRadius: ChainRouterView.backgroundCornerRadius) + .stroke( + Color.white.opacity(ChainRouterView.backgroundBorderOpacity), + lineWidth: ChainRouterView.backgroundBorderLineWidth + ) + ) + ) + } + + // MARK: - Subviews + + /// Top row: splitter mode selector + optional master gain knob. + private var headerRow: some View { + HStack(alignment: .top, spacing: ChainRouterView.headerSpacing) { + SplitterView(splitter: router.splitter) + Spacer() + if let masterNode: UIParamNode = router.masterGainNode { + masterKnob(node: masterNode) + } + } + } + + /// Master gain knob with a small label above. + private func masterKnob(node: UIParamNode) -> some View { + VStack(spacing: ChainRouterView.masterKnobSpacing) { + Text("MASTER") + .font(.system( + size: ChainRouterView.masterLabelFontSize, + weight: .medium, + design: .monospaced + )) + .foregroundStyle(Color.white.opacity(ChainRouterView.masterLabelOpacity)) + ParameterKnob("Gain", node: node, range: ChainRouterView.masterGainRange) + .foregroundStyle(Color.white) + } + } + + /// A labelled board row. + private func boardRow(label: String, board: PedalBoard) -> some View { + HStack(alignment: .top, spacing: ChainRouterView.boardRowSpacing) { + Text(label) + .font(.system( + size: ChainRouterView.boardLabelFontSize, + weight: .semibold, + design: .monospaced + )) + .foregroundStyle(Color.white.opacity(ChainRouterView.boardLabelOpacity)) + .frame(width: 14, alignment: .leading) + .padding(.top, 4) // optically align with board content + PedalBoardView(board: board) + } + } + + /// Footer row with merger mix knobs. + private func footerRow(merger: Merger) -> some View { + HStack(spacing: ChainRouterView.footerSpacing) { + MergerView(merger: merger) + Spacer() + } + } + + /// A thin horizontal rule between sections. + private var sectionDivider: some View { + Rectangle() + .fill(Color.white.opacity(ChainRouterView.sectionDividerOpacity)) + .frame(height: ChainRouterView.sectionDividerHeight) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/FlowLayout.swift b/Sources/LyrebirdShoeGazeUI/FlowLayout.swift new file mode 100644 index 0000000..3bc8b43 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/FlowLayout.swift @@ -0,0 +1,209 @@ +// FlowLayout.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI + +/// A SwiftUI `Layout` that arranges subviews left-to-right and wraps to the next +/// row whenever the remaining horizontal space in the current row is exhausted. +/// +/// Each row is filled greedily: subviews are placed in insertion order until +/// the next subview would exceed the proposed width, at which point a new row +/// begins. The final layout height is the sum of all row heights plus the +/// inter-row spacing. +/// +/// ## Infinite / nil proposed width +/// +/// When the container proposes an infinite or `nil` width (e.g. inside a +/// horizontal `ScrollView`), `FlowLayout` falls back to `FlowLayout.fallbackMaxWidth` +/// and lays out subviews on a single logical strip up to that cap. This avoids +/// an unbounded single-row layout that would make `sizeThatFits` report infinite +/// height. +/// +/// ## Usage +/// +/// ```swift +/// FlowLayout(horizontalSpacing: 12, verticalSpacing: 16) { +/// ForEach(pedals, id: \.id) { pedal in +/// PedalView(pedal: pedal) +/// } +/// } +/// ``` +/// +/// - Parameters: +/// - horizontalSpacing: Gap between adjacent subviews in the same row. +/// Defaults to `FlowLayout.defaultHorizontalSpacing`. +/// - verticalSpacing: Gap between rows. +/// Defaults to `FlowLayout.defaultVerticalSpacing`. +public struct FlowLayout: Layout { + + // MARK: - Named constants + + /// Default gap between subviews within the same row (points). + public static let defaultHorizontalSpacing: CGFloat = 16 + + /// Default gap between rows (points). + public static let defaultVerticalSpacing: CGFloat = 16 + + /// Maximum width used when the container proposes infinite or zero width, + /// preventing an unbounded single-row layout. + public static let fallbackMaxWidth: CGFloat = 1200 + + // MARK: - Properties + + /// Gap between adjacent subviews in the same row. + public let horizontalSpacing: CGFloat + + /// Gap between rows. + public let verticalSpacing: CGFloat + + // MARK: - Init + + /// Creates a flow layout with the given spacings. + /// + /// - Parameters: + /// - horizontalSpacing: Gap between subviews within a row (points). + /// Defaults to `FlowLayout.defaultHorizontalSpacing`. + /// - verticalSpacing: Gap between rows (points). + /// Defaults to `FlowLayout.defaultVerticalSpacing`. + public init( + horizontalSpacing: CGFloat = FlowLayout.defaultHorizontalSpacing, + verticalSpacing: CGFloat = FlowLayout.defaultVerticalSpacing + ) { + self.horizontalSpacing = horizontalSpacing + self.verticalSpacing = verticalSpacing + } + + // MARK: - Layout protocol + + public func sizeThatFits( + proposal: ProposedViewSize, + subviews: Subviews, + cache: inout () + ) -> CGSize { + let rows: [[RowItem]] = computeRows( + subviews: subviews, + availableWidth: resolvedWidth(from: proposal) + ) + return totalSize(rows: rows) + } + + public func placeSubviews( + in bounds: CGRect, + proposal: ProposedViewSize, + subviews: Subviews, + cache: inout () + ) { + let rows: [[RowItem]] = computeRows( + subviews: subviews, + availableWidth: resolvedWidth(from: proposal) + ) + + var y: CGFloat = bounds.minY + for (rowIndex, row): (Int, [RowItem]) in rows.enumerated() { + var x: CGFloat = bounds.minX + let rowHeight: CGFloat = row.max(by: { $0.size.height < $1.size.height })?.size.height ?? 0 + + for item: RowItem in row { + subviews[item.index].place( + at: CGPoint(x: x, y: y), + anchor: .topLeading, + proposal: ProposedViewSize(item.size) + ) + x += item.size.width + horizontalSpacing + } + y += rowHeight + if rowIndex < rows.count - 1 { + y += verticalSpacing + } + } + } + + // MARK: - Private helpers + + /// A single subview's natural (ideal) size and its index into `subviews`. + private struct RowItem { + let index: Int + let size: CGSize + } + + /// Resolves the available width from the container proposal. + /// + /// Falls back to `FlowLayout.fallbackMaxWidth` when the proposed width is + /// `nil`, zero, or infinite so the layout algorithm always has a finite bound + /// to wrap against. + private func resolvedWidth(from proposal: ProposedViewSize) -> CGFloat { + guard let width: CGFloat = proposal.width, + width > 0, + width.isFinite else { + return FlowLayout.fallbackMaxWidth + } + return width + } + + /// Partitions all subviews into rows given the available width. + /// + /// Each subview is measured at its ideal size (`unspecified` proposal). + /// Subviews are appended to the current row while they fit; when adding the + /// next subview would overflow `availableWidth`, a new row is started. + /// + /// A subview wider than `availableWidth` is placed alone on its own row so + /// it is always visible rather than silently clipped. + private func computeRows(subviews: Subviews, availableWidth: CGFloat) -> [[RowItem]] { + var rows: [[RowItem]] = [] + var currentRow: [RowItem] = [] + var currentRowWidth: CGFloat = 0 + + for index: Int in subviews.indices { + let size: CGSize = subviews[index].sizeThatFits(.unspecified) + let neededWidth: CGFloat = currentRow.isEmpty + ? size.width + : currentRowWidth + horizontalSpacing + size.width + + if !currentRow.isEmpty, neededWidth > availableWidth { + // The subview doesn't fit — commit the current row and start fresh. + rows.append(currentRow) + currentRow = [RowItem(index: index, size: size)] + currentRowWidth = size.width + } else { + // Fits in the current row (or is the first item on a new row). + currentRow.append(RowItem(index: index, size: size)) + currentRowWidth = neededWidth + } + } + + if !currentRow.isEmpty { + rows.append(currentRow) + } + + return rows + } + + /// Computes the bounding size of the finished row layout. + /// + /// Width is the widest row; height is the sum of all row heights plus + /// inter-row spacing. Returns `.zero` for an empty subview list. + private func totalSize(rows: [[RowItem]]) -> CGSize { + guard !rows.isEmpty else { return .zero } + + var totalHeight: CGFloat = 0 + var maxWidth: CGFloat = 0 + + for (rowIndex, row): (Int, [RowItem]) in rows.enumerated() { + let rowHeight: CGFloat = row.max(by: { $0.size.height < $1.size.height })?.size.height ?? 0 + let rowWidth: CGFloat = row.reduce(0) { acc, item in + acc + item.size.width + } + CGFloat(max(row.count - 1, 0)) * horizontalSpacing + + totalHeight += rowHeight + if rowIndex < rows.count - 1 { + totalHeight += verticalSpacing + } + maxWidth = max(maxWidth, rowWidth) + } + + return CGSize(width: maxWidth, height: totalHeight) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/MergerView.swift b/Sources/LyrebirdShoeGazeUI/MergerView.swift new file mode 100644 index 0000000..85af12a --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/MergerView.swift @@ -0,0 +1,92 @@ +// MergerView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// A compact routing-box view for a ``Merger`` showing two `ParameterKnob` controls +/// that adjust the per-branch mix levels. +/// +/// Branch A and B knobs are each bound to their respective `UIParamNode` (obtained via +/// `merger.$levelA` / `merger.$levelB`) and accept values in ``MergerView/levelRange``. +/// +/// The enclosure uses a slate/steel tint to visually distinguish routing boxes from +/// effect pedals. +/// +/// ## Usage +/// +/// ```swift +/// MergerView(merger: router.merger) +/// ``` +public struct MergerView: View { + + // MARK: - Layout constants + + private static let containerCornerRadius: CGFloat = 10 + private static let containerPaddingH: CGFloat = 14 + private static let containerPaddingV: CGFloat = 10 + private static let containerBorderOpacity: Double = 0.55 + private static let containerBorderLineWidth: CGFloat = 1.0 + private static let sectionSpacing: CGFloat = 8 + private static let knobRowSpacing: CGFloat = 12 + private static let titleFontSize: CGFloat = 11 + private static let titleOpacity: Double = 0.55 + /// Background colour components for the routing-box enclosure (steel). + private static let backgroundRed: Double = 0.22 + private static let backgroundGreen: Double = 0.22 + private static let backgroundBlue: Double = 0.26 + /// Level knob range: 0 = muted, 1 = unity gain, 2 = double gain. + private static let levelRange: ClosedRange = 0.0...2.0 + + // MARK: - Properties + + private let merger: Merger + + // MARK: - Init + + /// Creates a merger view for the given ``Merger``. + /// + /// - Parameter merger: The `Merger` whose branch level parameters will be bound to + /// the two knobs. + public init(merger: Merger) { + self.merger = merger + } + + // MARK: - Body + + public var body: some View { + VStack(spacing: MergerView.sectionSpacing) { + Text("MIX") + .font(.system(size: MergerView.titleFontSize, weight: .semibold, design: .monospaced)) + .foregroundStyle(Color.white.opacity(MergerView.titleOpacity)) + + HStack(spacing: MergerView.knobRowSpacing) { + ParameterKnob("A", node: merger.$levelA, range: MergerView.levelRange) + .foregroundStyle(Color.white) + ParameterKnob("B", node: merger.$levelB, range: MergerView.levelRange) + .foregroundStyle(Color.white) + } + } + .padding(.horizontal, MergerView.containerPaddingH) + .padding(.vertical, MergerView.containerPaddingV) + .background( + RoundedRectangle(cornerRadius: MergerView.containerCornerRadius) + .fill(Color( + red: MergerView.backgroundRed, + green: MergerView.backgroundGreen, + blue: MergerView.backgroundBlue + )) + .overlay( + RoundedRectangle(cornerRadius: MergerView.containerCornerRadius) + .stroke( + Color.white.opacity(MergerView.containerBorderOpacity), + lineWidth: MergerView.containerBorderLineWidth + ) + ) + ) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ParallelSectionView.swift b/Sources/LyrebirdShoeGazeUI/ParallelSectionView.swift new file mode 100644 index 0000000..30f23d6 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/ParallelSectionView.swift @@ -0,0 +1,108 @@ +// ParallelSectionView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// Renders a ``ParallelSection`` as a horizontal parallel rack. +/// +/// Layout (left → right): +/// 1. ``SplitterView`` — mode selector and branch LED indicators. +/// 2. A central `VStack` with two labelled branch rows: +/// - **A** row: one ``PedalView`` per pedal in `section.branchA`. +/// - **B** row: one ``PedalView`` per pedal in `section.branchB`. +/// Empty branches show a placeholder label. +/// +/// `ParallelSection` does not expose a `Merger`; the merger is owned by `PedalBoard` +/// and is not part of the section object. Only the splitter and branch pedal rows are +/// rendered here. The view wraps its central panel in a horizontal `ScrollView` so +/// wide branch chains do not overflow the window. +/// +/// ## Usage +/// +/// ```swift +/// ParallelSectionView(section: parallelSection) +/// ``` +public struct ParallelSectionView: View { + + // MARK: - Layout constants + + private static let outerSpacing: CGFloat = 16 + private static let branchStackSpacing: CGFloat = 12 + private static let pedalSpacing: CGFloat = 16 + private static let branchLabelFontSize: CGFloat = 11 + private static let branchLabelOpacity: Double = 0.55 + private static let emptyBranchOpacity: Double = 0.30 + private static let emptyBranchFontSize: CGFloat = 11 + private static let scrollPaddingH: CGFloat = 12 + private static let scrollPaddingV: CGFloat = 8 + private static let branchSeparatorOpacity: Double = 0.15 + private static let branchSeparatorHeight: CGFloat = 1 + + // MARK: - Properties + + private let section: ParallelSection + + // MARK: - Init + + /// Creates a parallel section view for the given ``ParallelSection``. + /// + /// - Parameter section: The `ParallelSection` to render. Both branch pedal arrays + /// and the splitter's enable nodes are read from this instance. + public init(section: ParallelSection) { + self.section = section + } + + // MARK: - Body + + public var body: some View { + HStack(alignment: .top, spacing: ParallelSectionView.outerSpacing) { + SplitterView(splitter: section.splitter) + + ScrollView(.horizontal, showsIndicators: false) { + VStack(alignment: .leading, spacing: ParallelSectionView.branchStackSpacing) { + branchRow(label: "A", pedals: section.branchA.pedals) + + Rectangle() + .fill(Color.white.opacity(ParallelSectionView.branchSeparatorOpacity)) + .frame(height: ParallelSectionView.branchSeparatorHeight) + + branchRow(label: "B", pedals: section.branchB.pedals) + } + .padding(.horizontal, ParallelSectionView.scrollPaddingH) + .padding(.vertical, ParallelSectionView.scrollPaddingV) + } + } + } + + // MARK: - Subviews + + /// A labelled row of pedal cards for one branch. + private func branchRow(label: String, pedals: [Pedal]) -> some View { + HStack(alignment: .bottom, spacing: ParallelSectionView.pedalSpacing) { + Text(label) + .font(.system( + size: ParallelSectionView.branchLabelFontSize, + weight: .semibold, + design: .monospaced + )) + .foregroundStyle(Color.white.opacity(ParallelSectionView.branchLabelOpacity)) + .frame(width: 14, alignment: .leading) + + if pedals.isEmpty { + Text("(empty)") + .font(.system(size: ParallelSectionView.emptyBranchFontSize)) + .foregroundStyle(Color.white.opacity(ParallelSectionView.emptyBranchOpacity)) + } else { + ForEach(Array(pedals.enumerated()), id: \.offset) { pair in + let pedal: Pedal = pair.element + PedalView(pedal: pedal) + } + } + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalBoardView.swift b/Sources/LyrebirdShoeGazeUI/PedalBoardView.swift new file mode 100644 index 0000000..fd99c8b --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/PedalBoardView.swift @@ -0,0 +1,166 @@ +// PedalBoardView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// A horizontal scrolling strip of ``PedalView`` cards, one per pedal in a `PedalBoard`. +/// +/// Pedals appear left-to-right in signal-flow order (the same order as +/// `PedalBoard.pedals`). The board's `label` property is shown above the strip on a +/// dark "pedalboard" backdrop that evokes a wooden/metal board surface. +/// +/// When `board.masterGainNode` is non-nil (i.e. after `ShoeGaze.finalizeBoard(_:)` has +/// been called), a small "Master" section appears at the right end of the scrollable +/// strip, containing a single output-level `ParameterKnob` bound to the board's gain node. +/// +/// An optional `onRemove` callback, if provided, is invoked by a small remove button +/// rendered in the header row so `PedalBoardView` remains decoupled from `ShoeGaze`. +/// +/// ## Usage +/// +/// ```swift +/// PedalBoardView(board: pedalBoard, onRemove: { shoeGaze.removeBoard(pedalBoard) }) +/// ``` +public struct PedalBoardView: View { + + // MARK: - Layout constants + + private static let pedalSpacing: CGFloat = 20 + private static let horizontalPadding: CGFloat = 16 + private static let verticalPadding: CGFloat = 20 + private static let sectionSpacing: CGFloat = 10 + private static let boardCornerRadius: CGFloat = 8 + private static let boardBorderOpacity: Double = 0.50 + private static let boardBorderBrightness: Double = 0.30 + private static let labelOpacity: Double = 0.60 + private static let outerHorizontalPadding: CGFloat = 4 + private static let boardBorderLineWidth: CGFloat = 1 + /// Dark walnut board surface colour components. + private static let boardBackgroundRed: Double = 0.12 + private static let boardBackgroundGreen: Double = 0.10 + private static let boardBackgroundBlue: Double = 0.08 + /// Separator between the pedal strip and the master section. + private static let masterSeparatorOpacity: Double = 0.25 + private static let masterSeparatorWidth: CGFloat = 1 + private static let masterSectionPaddingH: CGFloat = 12 + private static let masterSectionPaddingV: CGFloat = 8 + private static let masterLabelOpacity: Double = 0.45 + private static let masterGainRange: ClosedRange = 0.0...1.0 + /// Size of the header-area remove button. + private static let removeButtonFontSize: CGFloat = 11 + private static let removeButtonOpacity: Double = 0.55 + private static let headerSpacing: CGFloat = 6 + + // MARK: - Properties + + private let board: PedalBoard + + /// Called when the user taps the remove button in the board header. + /// If `nil`, no remove button is rendered. + private let onRemove: (() -> Void)? + + // MARK: - Init + + /// Creates a horizontal board view for the given `PedalBoard`. + /// + /// - Parameters: + /// - board: The `PedalBoard` whose pedals will be rendered as stompbox cards. + /// The board's `label` property is used as the header text. + /// - onRemove: Optional closure invoked when the user taps the remove button. + /// Pass `nil` to suppress the button entirely. Defaults to `nil`. + public init( + board: PedalBoard, + onRemove: (() -> Void)? = nil + ) { + self.board = board + self.onRemove = onRemove + } + + // MARK: - Body + + public var body: some View { + VStack(alignment: .leading, spacing: PedalBoardView.sectionSpacing) { + boardHeader + ScrollView(.horizontal, showsIndicators: false) { + HStack(alignment: .bottom, spacing: PedalBoardView.pedalSpacing) { + ForEach(Array(board.pedals.enumerated()), id: \.offset) { pair in + let pedal: Pedal = pair.element + PedalView(pedal: pedal) + } + if let masterNode: UIParamNode = board.masterGainNode { + masterSection(node: masterNode) + } + } + .padding(.horizontal, PedalBoardView.horizontalPadding) + .padding(.vertical, PedalBoardView.verticalPadding) + } + } + .background( + RoundedRectangle(cornerRadius: PedalBoardView.boardCornerRadius) + .fill(Color( + red: PedalBoardView.boardBackgroundRed, + green: PedalBoardView.boardBackgroundGreen, + blue: PedalBoardView.boardBackgroundBlue + )) // dark walnut board surface + .overlay( + RoundedRectangle(cornerRadius: PedalBoardView.boardCornerRadius) + .stroke( + Color(white: PedalBoardView.boardBorderBrightness) + .opacity(PedalBoardView.boardBorderOpacity), + lineWidth: PedalBoardView.boardBorderLineWidth + ) + ) + ) + .padding(.horizontal, PedalBoardView.outerHorizontalPadding) + } + + // MARK: - Subviews + + /// Label row with optional remove button, shown above the pedal strip. + private var boardHeader: some View { + HStack(spacing: PedalBoardView.headerSpacing) { + Text(board.label) + .font(.subheadline) + .foregroundStyle(Color.white.opacity(PedalBoardView.labelOpacity)) + Spacer() + if let remove: () -> Void = onRemove { + Button(action: remove) { + Text("Remove") + .font(.system(size: PedalBoardView.removeButtonFontSize)) + .foregroundStyle(Color.white.opacity(PedalBoardView.removeButtonOpacity)) + } + .buttonStyle(.plain) + } + } + // Indent to align with the board interior, matching horizontalPadding. + .padding(.horizontal, PedalBoardView.horizontalPadding) + .padding(.top, PedalBoardView.masterSectionPaddingV) + } + + /// Master-gain section rendered at the right end of the pedal strip. + /// + /// A thin vertical separator visually divides the pedal chain from the + /// master output stage, matching the pattern used by hardware pedalboards. + private func masterSection(node: UIParamNode) -> some View { + HStack(alignment: .bottom, spacing: PedalBoardView.pedalSpacing) { + Rectangle() + .fill(Color.white.opacity(PedalBoardView.masterSeparatorOpacity)) + .frame(width: PedalBoardView.masterSeparatorWidth) + .padding(.vertical, PedalBoardView.masterSectionPaddingV) + + VStack(spacing: PedalBoardView.masterSectionPaddingV) { + Text("MASTER") + .font(.system(size: PedalBoardView.removeButtonFontSize, weight: .medium, design: .monospaced)) + .foregroundStyle(Color.white.opacity(PedalBoardView.masterLabelOpacity)) + ParameterKnob("Gain", node: node, range: PedalBoardView.masterGainRange) + .foregroundStyle(Color.white) + } + .padding(.horizontal, PedalBoardView.masterSectionPaddingH) + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift new file mode 100644 index 0000000..a5c0451 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -0,0 +1,372 @@ +// PedalView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +// MARK: - Accent-color mapping (UI-only, never in the core target) + +/// Returns a stompbox enclosure tint colour keyed on the pedal's display name. +/// +/// The core `Pedal` type cannot carry a SwiftUI `Color`, so the mapping lives +/// here in the UI target. Unrecognised names fall through to `.gray`. +private func enclosureColor(for displayName: String) -> Color { + switch displayName { + case "Overdrive": return Color(red: 0.85, green: 0.42, blue: 0.08) // warm orange + case "Delay": return Color(red: 0.10, green: 0.55, blue: 0.55) // teal + case "Reverb": return Color(red: 0.30, green: 0.18, blue: 0.65) // indigo + case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green + case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson + case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue + case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet + case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green + default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray + } +} + +// MARK: - Screw decoration + +/// A small circular "screw head" decoration placed in each corner of the enclosure. +private struct ScrewDot: View { + + private static let size: CGFloat = 8 + private static let strokeWidth: CGFloat = 1 + private static let slotWidth: CGFloat = 1 + private static let slotHeight: CGFloat = 4 + private static let fillOpacity: Double = 0.25 + private static let rimOpacity: Double = 0.18 + private static let slotOpacity: Double = 0.50 + + var body: some View { + ZStack { + Circle() + .fill(Color.black.opacity(ScrewDot.fillOpacity)) + .frame(width: ScrewDot.size, height: ScrewDot.size) + Circle() + .stroke(Color.white.opacity(ScrewDot.rimOpacity), lineWidth: ScrewDot.strokeWidth) + .frame(width: ScrewDot.size, height: ScrewDot.size) + // Slot line — Phillips-style cross + Rectangle() + .fill(Color.black.opacity(ScrewDot.slotOpacity)) + .frame(width: ScrewDot.slotWidth, height: ScrewDot.slotHeight) + Rectangle() + .fill(Color.black.opacity(ScrewDot.slotOpacity)) + .frame(width: ScrewDot.slotHeight, height: ScrewDot.slotWidth) + } + } +} + +// MARK: - LED + +/// A small circular LED that glows green when the effect is engaged. +/// +/// Bypass polarity: `0` = engaged (effect ON), `1` = bypassed. +/// The LED is lit when `bypassValue < 0.5`. +private struct LEDIndicator: View { + + private static let diameter: CGFloat = 10 + private static let glowRadius: CGFloat = 6 + private static let glowOpacity: Double = 0.75 + private static let rimLineWidth: CGFloat = 0.5 + private static let dimBrightness: Double = 0.15 + private static let rimStrokeOpacity: Double = 0.30 + + let bypassValue: Double + + private var isEngaged: Bool { bypassValue < 0.5 } + + var body: some View { + ZStack { + if isEngaged { + Circle() + .fill(Color.green.opacity(LEDIndicator.glowOpacity)) + .frame( + width: LEDIndicator.diameter + LEDIndicator.glowRadius, + height: LEDIndicator.diameter + LEDIndicator.glowRadius + ) + .blur(radius: LEDIndicator.glowRadius / 2) + } + Circle() + .fill(isEngaged ? Color.green : Color(white: LEDIndicator.dimBrightness)) + .frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter) + .overlay( + Circle() + .stroke(Color.white.opacity(LEDIndicator.rimStrokeOpacity), lineWidth: LEDIndicator.rimLineWidth) + .frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter) + ) + } + .frame(width: LEDIndicator.diameter + LEDIndicator.glowRadius, + height: LEDIndicator.diameter + LEDIndicator.glowRadius) + } +} + +// MARK: - Footswitch + +/// A round footswitch-style button that toggles bypass on/off. +private struct FootswitchButton: View { + + private static let diameter: CGFloat = 44 + private static let strokeWidth: CGFloat = 2.5 + private static let innerDiameter: CGFloat = 36 + private static let outerFillBrightness: Double = 0.18 + private static let ringBrightness: Double = 0.50 + private static let innerFillBrightness: Double = 0.25 + + let node: UIParamNode + + var body: some View { + Button(action: { + let engaged: Bool = node.value < 0.5 + // Toggle: engaged (0) → bypassed (1) and vice-versa. + node.update(engaged ? 1.0 : 0.0) + }) { + ZStack { + Circle() + .fill(Color(white: FootswitchButton.outerFillBrightness)) + .frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter) + Circle() + .stroke(Color(white: FootswitchButton.ringBrightness), + lineWidth: FootswitchButton.strokeWidth) + .frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter) + Circle() + .fill(Color(white: FootswitchButton.innerFillBrightness)) + .frame(width: FootswitchButton.innerDiameter, height: FootswitchButton.innerDiameter) + } + } + .buttonStyle(.plain) + .frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter) + } +} + +// MARK: - PedalView + +/// A stompbox-style enclosure view that renders all controls for a single `Pedal`. +/// +/// The enclosure shows: +/// - Corner screw decorations. +/// - A contrasting name-plate capsule near the top with `displayName`. +/// - A grid of ``ParameterKnob`` controls (up to ``knobColumnCount`` per row) drawn from +/// the effect + `Mix` knobs of ``Pedal/knobs``. +/// - A centred bottom row pairing the `Level` knob with the bypass switch (LED + footswitch). +/// +/// ## Bypass LED polarity +/// +/// `Pedal.bypass` is `0` = engaged (effect active), `1` = bypassed. +/// The LED is **green/lit** when `bypass < 0.5` (effect is on) and dark when bypassed. +/// +/// ## Accent color +/// +/// The enclosure tint is assigned by `enclosureColor(for:)` — a private helper in +/// this file keyed on `displayName`. Core `Pedal` never imports SwiftUI. +/// +/// ## Usage +/// +/// ```swift +/// PedalView(pedal: overdrivePedal) +/// ``` +public struct PedalView: View { + + // MARK: - Layout constants + + /// Wide enough for three ~55 pt knobs (dial + label + value) plus padding in a + /// single row, so the effect controls never overlap. + private static let enclosureWidth: CGFloat = 220 + private static let enclosureCornerRadius: CGFloat = 12 + private static let enclosurePadding: CGFloat = 14 + private static let screwInset: CGFloat = 6 + private static let knobColumnCount: Int = 3 + private static let knobSpacing: CGFloat = 10 + /// Horizontal gap between the Level knob and the bypass control in the bottom row. + private static let bottomControlsSpacing: CGFloat = 18 + private static let sectionSpacing: CGFloat = 14 + private static let namePlateCornerRadius: CGFloat = 8 + private static let namePlatePaddingH: CGFloat = 10 + private static let namePlatePaddingV: CGFloat = 4 + private static let outerBorderOpacity: Double = 0.60 + private static let innerHighlightOpacity: Double = 0.22 + private static let shadowRadius: CGFloat = 8 + private static let shadowYOffset: CGFloat = 4 + private static let shadowOpacity: Double = 0.60 + private static let enclosureGradientDarkFraction: Double = 0.30 + private static let bypassSectionSpacing: CGFloat = 6 + /// Half the screw-dot size — used to centre screws on the corner position. + private static let screwHalfSize: CGFloat = 4 + private static let namePlateBackgroundOpacity: Double = 0.35 + private static let fontSizeNamePlate: CGFloat = 13 + private static let outerBorderLineWidth: CGFloat = 1.5 + private static let innerHighlightLineWidth: CGFloat = 1 + private static let innerHighlightPadding: CGFloat = 1 + private static let shadowXOffset: CGFloat = 0 + + // MARK: - Properties + + private let pedal: Pedal + + // MARK: - Init + + /// Creates a stompbox pedal view for the given pedal. + /// + /// - Parameter pedal: The `Pedal` whose parameters will be displayed. + public init(pedal: Pedal) { + self.pedal = pedal + } + + // MARK: - Body + + public var body: some View { + let accent: Color = enclosureColor(for: pedal.displayName) + let darkAccent: Color = accent.opacity(PedalView.enclosureGradientDarkFraction) + + ZStack(alignment: .topLeading) { + // Enclosure fill with top-to-bottom gradient + RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius) + .fill( + LinearGradient( + gradient: Gradient(colors: [accent, darkAccent]), + startPoint: .top, + endPoint: .bottom + ) + ) + + // Outer border + RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius) + .stroke(Color.black.opacity(PedalView.outerBorderOpacity), + lineWidth: PedalView.outerBorderLineWidth) + + // Inner highlight rim (subtle bevel) + RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius - PedalView.innerHighlightPadding) + .stroke(Color.white.opacity(PedalView.innerHighlightOpacity), + lineWidth: PedalView.innerHighlightLineWidth) + .padding(PedalView.innerHighlightPadding) + + // Content stack + VStack(spacing: PedalView.sectionSpacing) { + namePlate + knobGrid + Spacer(minLength: 0) + bottomControls + } + .padding(PedalView.enclosurePadding) + + // Corner screws — overlaid at the four corners + screwCorners + } + .frame(width: PedalView.enclosureWidth) + .shadow( + color: Color.black.opacity(PedalView.shadowOpacity), + radius: PedalView.shadowRadius, + x: PedalView.shadowXOffset, + y: PedalView.shadowYOffset + ) + } + + // MARK: - Subviews + + /// Capsule name plate near the top of the enclosure. + private var namePlate: some View { + Text(pedal.displayName) + .font(.system(size: PedalView.fontSizeNamePlate, weight: .bold, design: .rounded)) + .foregroundStyle(Color.white) + .padding(.horizontal, PedalView.namePlatePaddingH) + .padding(.vertical, PedalView.namePlatePaddingV) + .background(Color.black.opacity(PedalView.namePlateBackgroundOpacity)) + .clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius)) + } + + /// Grid of the effect + `Mix` knobs, in rows of up to `knobColumnCount`. + /// + /// The `Level` knob (the last entry of `pedal.knobs`) is dropped here and rendered in + /// the bottom control row next to the bypass switch, leaving more room for the effect + /// controls at the top. + private var knobGrid: some View { + let knobs: [PedalKnob] = Array(pedal.knobs.dropLast()) + let rows: [[PedalKnob]] = stride( + from: 0, + to: knobs.count, + by: PedalView.knobColumnCount + ).map { startIndex in + Array(knobs[startIndex ..< min(startIndex + PedalView.knobColumnCount, knobs.count)]) + } + + return VStack(spacing: PedalView.knobSpacing) { + ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in + let row: [PedalKnob] = rowPair.element + HStack(spacing: PedalView.knobSpacing) { + ForEach(Array(row.enumerated()), id: \.offset) { knobPair in + let knob: PedalKnob = knobPair.element + ParameterKnob(knob.label, node: knob.node, range: knob.range) + .foregroundStyle(Color.white) + } + // Pad short rows so knobs stay aligned in their columns. + if row.count < PedalView.knobColumnCount { + ForEach(0 ..< (PedalView.knobColumnCount - row.count), id: \.self) { _ in + Spacer() + } + } + } + } + } + } + + /// Bottom control row: the `Level` knob and the bypass switch side-by-side, centred + /// with equal padding below. + private var bottomControls: some View { + HStack(alignment: .center, spacing: PedalView.bottomControlsSpacing) { + levelControl + bypassControl + } + .frame(maxWidth: .infinity) + } + + /// The `Level` knob — the last entry of `pedal.knobs`. + @ViewBuilder + private var levelControl: some View { + if let level: PedalKnob = pedal.knobs.last { + ParameterKnob(level.label, node: level.node, range: level.range) + .foregroundStyle(Color.white) + } + } + + /// LED + footswitch bypass control, paired beside the Level knob. + private var bypassControl: some View { + // Reading `pedal.$bypass.value` here registers this view for automatic + // re-renders whenever the bypass parameter changes on the main thread + // (UIParamNode is @Observable). + let bypassValue: Double = pedal.$bypass.value + + return VStack(spacing: PedalView.bypassSectionSpacing) { + LEDIndicator(bypassValue: bypassValue) + FootswitchButton(node: pedal.$bypass) + } + } + + /// Four screw dots overlaid at the enclosure corners. + private var screwCorners: some View { + GeometryReader { geometry in + let w: CGFloat = geometry.size.width + let h: CGFloat = geometry.size.height + let inset: CGFloat = PedalView.screwInset + + let half: CGFloat = PedalView.screwHalfSize + + ZStack(alignment: .topLeading) { + // Top-left + ScrewDot() + .position(x: inset + half, y: inset + half) + // Top-right + ScrewDot() + .position(x: w - inset - half, y: inset + half) + // Bottom-left + ScrewDot() + .position(x: inset + half, y: h - inset - half) + // Bottom-right + ScrewDot() + .position(x: w - inset - half, y: h - inset - half) + } + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift new file mode 100644 index 0000000..6d1ecbe --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift @@ -0,0 +1,12 @@ +// ShoeGazeUI.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +// LyrebirdShoeGazeUI views are implemented in: +// PedalView.swift — single pedal card +// PedalBoardView.swift — horizontal board strip +// ShoeGazeView.swift — top-level session view with transport +// FlowLayout.swift — wrap-to-fit Layout (left-to-right, row-wrapping) +// BoardEditorView.swift — per-board editor with FlowLayout pedal area + version store diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift new file mode 100644 index 0000000..419d34d --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift @@ -0,0 +1,381 @@ +// ShoeGazeView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if canImport(AppKit) +import AppKit +#endif +import SwiftUI +import LyrebirdSynth +import LyrebirdUI +import LyrebirdShoeGaze + +/// The top-level view for a `ShoeGaze` session. +/// +/// Displays a transport header (Start / Stop engine buttons and an Add Board button), +/// a vertically scrollable list of ``PedalBoardView`` strips (one per board), and a +/// ``LyrebirdStatusView`` CPU meter at the bottom, all on a dark backdrop that matches +/// the stompbox enclosure aesthetic. +/// +/// ## Board identity keying +/// +/// The boards `ForEach` uses `id: \.offset` on an enumerated copy of `shoeGaze.boards`. +/// `PedalBoard` is a `@MainActor` class and is neither `Identifiable` nor `Hashable` +/// (adding conformance to the core type would violate the module-layering constraint). +/// Index keying is stable for the simple append/remove-by-position pattern this demo +/// uses and avoids any protocol requirements on the core `PedalBoard` type. +/// +/// ## Usage +/// +/// ```swift +/// ShoeGazeView(shoeGaze: shoeGaze) +/// ``` +public struct ShoeGazeView: View { + + // MARK: - Layout constants + + private static let outerPadding: CGFloat = 20 + private static let sectionSpacing: CGFloat = 16 + private static let transportSpacing: CGFloat = 12 + private static let boardSpacing: CGFloat = 20 + private static let minWidth: CGFloat = 400 + private static let dividerOpacity: Double = 0.12 + /// Stage-floor dark background colour components (very dark warm black). + private static let backgroundRed: Double = 0.08 + private static let backgroundGreen: Double = 0.07 + private static let backgroundBlue: Double = 0.06 + /// Default crossfade duration in seconds for board-select transitions. + private static let defaultCrossfadeSeconds: Double = 0.3 + /// Maximum crossfade duration accepted by the crossfade seconds stepper. + private static let maxCrossfadeSeconds: Double = 10.0 + /// Stepper increment for the crossfade seconds control. + private static let crossfadeStepIncrement: Double = 0.1 + /// Width of the crossfade-seconds text field. + private static let crossfadeFieldWidth: CGFloat = 60 + /// Spacing inside the board-select row. + private static let boardSelectSpacing: CGFloat = 8 + /// Opacity for the board-select row labels. + private static let labelOpacity: Double = 0.65 + /// Diameter of the recording-in-progress indicator dot. + private static let recordDotSize: CGFloat = 10 + /// Opacity of the secondary folder-name label shown next to the folder picker button. + private static let folderLabelOpacity: Double = 0.55 + /// Spacing inside the recording controls sub-row. + private static let recordingRowSpacing: CGFloat = 10 + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + + /// Bumped on each transport button press to force a re-read of the engine's + /// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning` + /// directly (the single source of truth) rather than a private mirror that could + /// drift out of sync if the engine is started/stopped elsewhere. + @State private var transportTick: Bool = false + + /// Crossfade duration used for the next board-select transition. + @State private var crossfadeSeconds: Double = ShoeGazeView.defaultCrossfadeSeconds + + /// Controls presentation of the iOS `.fileImporter` directory picker. + /// On macOS the picker is opened imperatively via `NSOpenPanel`; this flag is + /// only meaningful on iOS / non-macOS targets. + @State private var showFolderImporter: Bool = false + + // MARK: - Init + + /// Creates a top-level ShoeGaze view. + /// + /// - Parameter shoeGaze: The `ShoeGaze` manager whose boards and engine will + /// be displayed. The caller is responsible for engine lifecycle; this view + /// provides Start and Stop transport buttons as a convenience. + public init(shoeGaze: ShoeGaze) { + self.shoeGaze = shoeGaze + } + + // MARK: - Body + + public var body: some View { + VStack(alignment: .leading, spacing: ShoeGazeView.sectionSpacing) { + transportHeader + recordingRow + Divider() + .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) + boardSelectRow + Divider() + .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) + boardList + Divider() + .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) + LyrebirdStatusView(engine: shoeGaze.engine) + } + .padding(ShoeGazeView.outerPadding) + .frame(minWidth: ShoeGazeView.minWidth) + .background( + Color( + red: ShoeGazeView.backgroundRed, + green: ShoeGazeView.backgroundGreen, + blue: ShoeGazeView.backgroundBlue + ) + ) + #if !os(macOS) + .fileImporter( + isPresented: $showFolderImporter, + allowedContentTypes: [.folder] + ) { result in + switch result { + case .success(let url): + // A `.fileImporter` directory URL is security-scoped on iOS; access must + // be started before `FileManager` can write into it. Kept open for the + // session (released when the app exits). + if url.startAccessingSecurityScopedResource() { + shoeGaze.recordingFolder = url + } else { + print("[ShoeGazeView] could not access selected folder") + } + case .failure(let error): + print("[ShoeGazeView] folder picker failed: \(error)") + } + } + #endif + } + + // MARK: - Subviews + + /// Transport bar: title, Start/Stop engine buttons, and Add Board button. + /// + /// The button state reads `shoeGaze.engine.isRunning` (the single source of truth) + /// so it stays correct even when the engine is started/stopped by another control. + /// Audio only flows once the user presses Start — adding boards does not auto-start + /// the engine. + private var transportHeader: some View { + // Referencing `transportTick` makes a press (which toggles it) re-evaluate this + // view so `engine.isRunning` is re-read; toggling any @State invalidates the view. + _ = transportTick + let isRunning: Bool = shoeGaze.engine.isRunning + return HStack(spacing: ShoeGazeView.transportSpacing) { + Text("ShoeGaze") + .font(.title2) + .bold() + .foregroundStyle(Color.white) + Spacer() + Button("Add Board") { + addBoard() + } + .buttonStyle(.bordered) + .tint(.orange) + + Button("Start") { + do { + try shoeGaze.engine.start() + } catch { + // Surface start errors to the console; the UI remains in the + // non-running state so the user can retry. + print("[ShoeGazeView] engine.start() failed: \(error)") + } + transportTick.toggle() + } + .buttonStyle(.borderedProminent) + .tint(.green) + .disabled(isRunning) + + Button("Stop") { + shoeGaze.engine.stop() + transportTick.toggle() + } + .buttonStyle(.bordered) + .tint(.red) + .disabled(!isRunning) + } + } + + /// Recording controls: folder picker, chosen-folder label, and record/stop button. + /// + /// The folder picker opens an `NSOpenPanel` on macOS or a `.fileImporter` sheet on iOS. + /// The Record button is disabled until a folder has been chosen; it turns into a Stop + /// button (red) while recording is in progress. + private var recordingRow: some View { + HStack(spacing: ShoeGazeView.recordingRowSpacing) { + // --- Folder picker button --- + Button("Choose Folder…") { + chooseFolderAction() + } + .buttonStyle(.bordered) + .tint(.blue) + + // --- Chosen folder label --- + let folderName: String = shoeGaze.recordingFolder?.lastPathComponent ?? "No folder" + Text(folderName) + .font(.caption) + .foregroundStyle(Color.white.opacity(ShoeGazeView.folderLabelOpacity)) + .lineLimit(1) + .truncationMode(.middle) + + Spacer() + + // --- Recording-in-progress indicator dot --- + if shoeGaze.isRecording { + Circle() + .fill(Color.red) + .frame( + width: ShoeGazeView.recordDotSize, + height: ShoeGazeView.recordDotSize + ) + } + + // --- Record / Stop button --- + Button(shoeGaze.isRecording ? "Stop" : "Record") { + if shoeGaze.isRecording { + shoeGaze.stopRecording() + } else { + do { + try shoeGaze.startRecording() + } catch { + print("[ShoeGazeView] startRecording() failed: \(error)") + } + } + } + .buttonStyle(.borderedProminent) + .tint(shoeGaze.isRecording ? .red : .accentColor) + .disabled(shoeGaze.recordingFolder == nil) + } + } + + /// A `Binding` that maps between the Picker's integer tag and `ShoeGaze` select API. + /// + /// Tag `-1` represents "All boards audible" (`activeBoardIndex == nil`). + /// Tags `0 ..< boards.count` represent the soloed board at that index. + /// Setting the binding calls `selectBoard(_:crossfadeSeconds:)` or + /// `selectAllBoards(crossfadeSeconds:)` with the current `crossfadeSeconds` value. + private var boardSelectBinding: Binding { + Binding( + get: { shoeGaze.activeBoardIndex ?? -1 }, + set: { newValue in + // Clamp here so a value typed into the crossfade text field (which has no + // built-in bounds) can never pass a negative or oversized lag time. + let seconds: Double = min(max(crossfadeSeconds, 0.0), ShoeGazeView.maxCrossfadeSeconds) + if newValue == -1 { + shoeGaze.selectAllBoards(crossfadeSeconds: seconds) + } else if newValue >= 0, newValue < shoeGaze.boards.count { + shoeGaze.selectBoard(shoeGaze.boards[newValue], crossfadeSeconds: seconds) + } + } + ) + } + + /// Board-select row: an "Active" Picker to solo a board (or hear all), a crossfade- + /// seconds text field, and a companion Stepper for convenient adjustment. + /// + /// The row is always visible. When `boards.count <= 1` the Picker has only one or two + /// options, which is still useful for the "All" / single-board toggle. + private var boardSelectRow: some View { + HStack(spacing: ShoeGazeView.boardSelectSpacing) { + Text("Active:") + .font(.subheadline) + .foregroundStyle(Color.white.opacity(ShoeGazeView.labelOpacity)) + + Picker("Active", selection: boardSelectBinding) { + Text("All").tag(-1) + ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in + let label: String = pair.element.label.isEmpty + ? "Board \(pair.offset + 1)" + : pair.element.label + Text(label).tag(pair.offset) + } + } + .pickerStyle(.menu) + .foregroundStyle(Color.white) + + Spacer() + + Text("Crossfade (s):") + .font(.subheadline) + .foregroundStyle(Color.white.opacity(ShoeGazeView.labelOpacity)) + + TextField( + "s", + value: $crossfadeSeconds, + format: .number.precision(.fractionLength(1)) + ) + .frame(width: ShoeGazeView.crossfadeFieldWidth) + #if os(macOS) + .textFieldStyle(.squareBorder) + #endif + + Stepper( + "", + value: $crossfadeSeconds, + in: 0...ShoeGazeView.maxCrossfadeSeconds, + step: ShoeGazeView.crossfadeStepIncrement + ) + .labelsHidden() + } + } + + /// Vertically scrollable list of board strips. + /// + /// Keyed by `\.offset` on an enumerated snapshot; see the doc-comment on + /// `ShoeGazeView` for the rationale. + private var boardList: some View { + ScrollView(.vertical, showsIndicators: true) { + VStack(alignment: .leading, spacing: ShoeGazeView.boardSpacing) { + ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in + let board: PedalBoard = pair.element + PedalBoardView(board: board) { + shoeGaze.removeBoard(board) + } + } + } + } + } + + // MARK: - Recording + + /// Opens a directory picker so the user can choose the recording destination folder. + /// + /// On macOS an `NSOpenPanel` is presented imperatively (directories only, no file + /// selection, no multiple selection). On iOS/non-macOS the `.fileImporter` modifier + /// attached to the view hierarchy is toggled via `showFolderImporter`. + private func chooseFolderAction() { + #if os(macOS) + let panel: NSOpenPanel = NSOpenPanel() + panel.canChooseDirectories = true + panel.canChooseFiles = false + panel.allowsMultipleSelection = false + panel.canCreateDirectories = true // show the "New Folder" button + panel.prompt = "Choose" + panel.message = "Select a folder for recording output" + // `begin` is non-blocking (unlike `runModal`, which would freeze the SwiftUI + // main-thread update loop while the panel is open). + panel.begin { response in + if response == .OK, let url: URL = panel.url { + shoeGaze.recordingFolder = url + } + } + #else + showFolderImporter = true + #endif + } + + // MARK: - Board management + + /// Adds a new board with one `OverdrivePedal` as a default pedal so the board + /// produces audible output immediately after being finalized. If any step after + /// `shoeGaze.addBoard()` throws, the partially-built board is removed via + /// `shoeGaze.removeBoard(_:)` before logging, leaving the rig in a consistent state. + private func addBoard() { + var createdBoard: PedalBoard? + do { + let board: PedalBoard = try shoeGaze.addBoard() + createdBoard = board + try board.add(OverdrivePedal()) + try shoeGaze.finalizeBoard(board) + } catch { + if let board: PedalBoard = createdBoard { + shoeGaze.removeBoard(board) + } + print("[ShoeGazeView] addBoard() failed: \(error)") + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/SplitterView.swift b/Sources/LyrebirdShoeGazeUI/SplitterView.swift new file mode 100644 index 0000000..2078fe7 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/SplitterView.swift @@ -0,0 +1,168 @@ +// SplitterView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// A compact routing-box view for a ``Splitter`` that exposes a 3-way mode selector +/// and two live LED indicators reflecting each branch's current enable value. +/// +/// The segmented `Picker` is driven by a computed `Binding` whose `get` reads +/// `splitter.mode` directly and whose `set` writes back to `splitter.mode`, so the picker +/// stays in sync whether the mode is changed via the UI or programmatically. +/// +/// Because `body` already reads `splitter.$branchAEnabled.value` and +/// `splitter.$branchBEnabled.value` (both `@Observable`), SwiftUI re-renders the view on +/// any external mode change and the binding getter returns the correct value. +/// +/// LED polarity: a branch LED is **lit** (blue/teal) when its `UIParamNode` value is +/// ≥ 0.5, and dark when the branch is muted. +/// +/// ## Usage +/// +/// ```swift +/// SplitterView(splitter: section.splitter) +/// ``` +public struct SplitterView: View { + + // MARK: - Layout constants + + private static let containerCornerRadius: CGFloat = 10 + private static let containerPaddingH: CGFloat = 14 + private static let containerPaddingV: CGFloat = 10 + private static let containerBorderOpacity: Double = 0.55 + private static let containerBorderLineWidth: CGFloat = 1.0 + private static let sectionSpacing: CGFloat = 8 + private static let ledRowSpacing: CGFloat = 16 + private static let titleFontSize: CGFloat = 11 + private static let titleOpacity: Double = 0.55 + private static let ledLabelFontSize: CGFloat = 10 + private static let ledLabelOpacity: Double = 0.60 + private static let ledDiameter: CGFloat = 8 + private static let ledGlowRadius: CGFloat = 5 + private static let ledGlowOpacity: Double = 0.80 + private static let ledDimBrightness: Double = 0.12 + private static let ledRimOpacity: Double = 0.30 + private static let ledRimLineWidth: CGFloat = 0.5 + private static let ledPairSpacing: CGFloat = 6 + /// Threshold above which a UIParamNode enable value is considered "on". + private static let enableOnThreshold: Double = 0.5 + /// Background colour components for the routing-box enclosure (slate). + private static let backgroundRed: Double = 0.20 + private static let backgroundGreen: Double = 0.23 + private static let backgroundBlue: Double = 0.28 + + // MARK: - Properties + + private let splitter: Splitter + + // MARK: - Init + + /// Creates a splitter view for the given ``Splitter``. + /// + /// - Parameter splitter: The `Splitter` whose mode and branch enable values will be + /// displayed and edited. The picker reads and writes `splitter.mode` directly via + /// a computed binding, so external mode changes are always reflected correctly. + public init(splitter: Splitter) { + self.splitter = splitter + } + + // MARK: - Body + + public var body: some View { + // Read branch enable values — because UIParamNode is @Observable, SwiftUI + // automatically re-renders this view whenever either value changes on the main thread. + // The mode binding getter also reads splitter.mode directly, so the picker stays in + // sync with any programmatic mode change. + let aValue: Double = splitter.$branchAEnabled.value + let bValue: Double = splitter.$branchBEnabled.value + let modeBinding: Binding = Binding( + get: { splitter.mode }, + set: { splitter.mode = $0 } + ) + + VStack(spacing: SplitterView.sectionSpacing) { + Text("SPLIT") + .font(.system(size: SplitterView.titleFontSize, weight: .semibold, design: .monospaced)) + .foregroundStyle(Color.white.opacity(SplitterView.titleOpacity)) + + Picker("Mode", selection: modeBinding) { + ForEach(SplitMode.allCases, id: \.self) { splitMode in + Text(splitMode.rawValue.uppercased()) + .tag(splitMode) + } + } + .pickerStyle(.segmented) + + branchLEDs(aValue: aValue, bValue: bValue) + } + .padding(.horizontal, SplitterView.containerPaddingH) + .padding(.vertical, SplitterView.containerPaddingV) + .background( + RoundedRectangle(cornerRadius: SplitterView.containerCornerRadius) + .fill(Color( + red: SplitterView.backgroundRed, + green: SplitterView.backgroundGreen, + blue: SplitterView.backgroundBlue + )) + .overlay( + RoundedRectangle(cornerRadius: SplitterView.containerCornerRadius) + .stroke( + Color.white.opacity(SplitterView.containerBorderOpacity), + lineWidth: SplitterView.containerBorderLineWidth + ) + ) + ) + } + + // MARK: - Subviews + + /// Pair of LED indicators showing live branch enable state. + private func branchLEDs(aValue: Double, bValue: Double) -> some View { + HStack(spacing: SplitterView.ledRowSpacing) { + branchLED(label: "A", value: aValue) + branchLED(label: "B", value: bValue) + } + } + + /// A single labelled LED dot for one branch. + private func branchLED(label: String, value: Double) -> some View { + let isOn: Bool = value >= SplitterView.enableOnThreshold + + return VStack(spacing: SplitterView.ledPairSpacing) { + Text(label) + .font(.system(size: SplitterView.ledLabelFontSize, weight: .medium, design: .monospaced)) + .foregroundStyle(Color.white.opacity(SplitterView.ledLabelOpacity)) + ZStack { + if isOn { + Circle() + .fill(Color.cyan.opacity(SplitterView.ledGlowOpacity)) + .frame( + width: SplitterView.ledDiameter + SplitterView.ledGlowRadius, + height: SplitterView.ledDiameter + SplitterView.ledGlowRadius + ) + .blur(radius: SplitterView.ledGlowRadius / 2) + } + Circle() + .fill(isOn ? Color.cyan : Color(white: SplitterView.ledDimBrightness)) + .frame(width: SplitterView.ledDiameter, height: SplitterView.ledDiameter) + .overlay( + Circle() + .stroke( + Color.white.opacity(SplitterView.ledRimOpacity), + lineWidth: SplitterView.ledRimLineWidth + ) + .frame(width: SplitterView.ledDiameter, height: SplitterView.ledDiameter) + ) + } + .frame( + width: SplitterView.ledDiameter + SplitterView.ledGlowRadius, + height: SplitterView.ledDiameter + SplitterView.ledGlowRadius + ) + } + } +} diff --git a/Tests/LyrebirdShoeGazeTests/BoardSelectionTests.swift b/Tests/LyrebirdShoeGazeTests/BoardSelectionTests.swift new file mode 100644 index 0000000..f3e8f69 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/BoardSelectionTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/BoardVersionTests.swift b/Tests/LyrebirdShoeGazeTests/BoardVersionTests.swift new file mode 100644 index 0000000..cf2f9d0 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/BoardVersionTests.swift @@ -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 = Set(store.versions.map { $0.id }) + let loadedIDs: Set = 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'") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/ChainRouterTests.swift b/Tests/LyrebirdShoeGazeTests/ChainRouterTests.swift new file mode 100644 index 0000000..20b898c --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ChainRouterTests.swift @@ -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" + ) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/CompressorPedalTests.swift b/Tests/LyrebirdShoeGazeTests/CompressorPedalTests.swift new file mode 100644 index 0000000..2c6b61d --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/CompressorPedalTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/DelayPedalTests.swift b/Tests/LyrebirdShoeGazeTests/DelayPedalTests.swift new file mode 100644 index 0000000..8919271 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/DelayPedalTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/FuzzPedalTests.swift b/Tests/LyrebirdShoeGazeTests/FuzzPedalTests.swift new file mode 100644 index 0000000..263909b --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/FuzzPedalTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/LiveInputBoardTests.swift b/Tests/LyrebirdShoeGazeTests/LiveInputBoardTests.swift new file mode 100644 index 0000000..b5ce774 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/LiveInputBoardTests.swift @@ -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() + } + } +} diff --git a/Tests/LyrebirdShoeGazeTests/MergerTests.swift b/Tests/LyrebirdShoeGazeTests/MergerTests.swift new file mode 100644 index 0000000..e79935c --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/MergerTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/ModulationPedalTests.swift b/Tests/LyrebirdShoeGazeTests/ModulationPedalTests.swift new file mode 100644 index 0000000..ff88c4c --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ModulationPedalTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/OverdrivePedalTests.swift b/Tests/LyrebirdShoeGazeTests/OverdrivePedalTests.swift new file mode 100644 index 0000000..1f86c6e --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/OverdrivePedalTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/ParallelSectionTests.swift b/Tests/LyrebirdShoeGazeTests/ParallelSectionTests.swift new file mode 100644 index 0000000..1cf8f83 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ParallelSectionTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/PedalBoardTests.swift b/Tests/LyrebirdShoeGazeTests/PedalBoardTests.swift new file mode 100644 index 0000000..2ae25ad --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/PedalBoardTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/PhaserPedalTests.swift b/Tests/LyrebirdShoeGazeTests/PhaserPedalTests.swift new file mode 100644 index 0000000..b933e53 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/PhaserPedalTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/PresetTests.swift b/Tests/LyrebirdShoeGazeTests/PresetTests.swift new file mode 100644 index 0000000..ed37c09 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/PresetTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/RecordingTests.swift b/Tests/LyrebirdShoeGazeTests/RecordingTests.swift new file mode 100644 index 0000000..c514766 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/RecordingTests.swift @@ -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") + } + } +} diff --git a/Tests/LyrebirdShoeGazeTests/ReverbPedalTests.swift b/Tests/LyrebirdShoeGazeTests/ReverbPedalTests.swift new file mode 100644 index 0000000..0d9fcbb --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ReverbPedalTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/ShoeGazeMultiBoardTests.swift b/Tests/LyrebirdShoeGazeTests/ShoeGazeMultiBoardTests.swift new file mode 100644 index 0000000..6ba4072 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/ShoeGazeMultiBoardTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/SplitterTests.swift b/Tests/LyrebirdShoeGazeTests/SplitterTests.swift new file mode 100644 index 0000000..5c6c163 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/SplitterTests.swift @@ -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) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/Support/OfflineRender.swift b/Tests/LyrebirdShoeGazeTests/Support/OfflineRender.swift new file mode 100644 index 0000000..d82374f --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/Support/OfflineRender.swift @@ -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.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.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)) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/TestLoopSourceTests.swift b/Tests/LyrebirdShoeGazeTests/TestLoopSourceTests.swift new file mode 100644 index 0000000..0c51bbe --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/TestLoopSourceTests.swift @@ -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") + } +} diff --git a/Tests/LyrebirdShoeGazeTests/TremoloPedalTests.swift b/Tests/LyrebirdShoeGazeTests/TremoloPedalTests.swift new file mode 100644 index 0000000..8e66a4d --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/TremoloPedalTests.swift @@ -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") + } +}