Compare commits
37 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b6a9dbbb91 | |||
| ef20a0eb95 | |||
| aeab19236b | |||
| 8c4b2ab1e7 | |||
| 3322400b7c | |||
| 9e09eb284a | |||
| 657ecaf4f4 | |||
| 957a99d802 | |||
| e839447aa8 | |||
| a21121e120 | |||
| bc6e6286df | |||
| bc7157b7ee | |||
| 7d3bafe200 | |||
| 284093c302 | |||
| a5f3aab237 | |||
| f573d1e9a6 | |||
| 8775134d4f | |||
| 7a39a2477e | |||
| a12f58e1d1 | |||
| 16f837ee10 | |||
| 0d75108fb1 | |||
| 17f74a4ede | |||
| 077a8ad9f0 | |||
| 7ceb93e411 | |||
| a334a76f7c | |||
| 5af4230038 | |||
| 0f69c27772 | |||
| eafc68d283 | |||
| f0b30379c7 | |||
| de4d650378 | |||
| 6e299b9d38 | |||
| 9a8e5461c0 | |||
| 849240e6e2 | |||
| e8e134499d | |||
| dc42db0c59 | |||
| b55df174a6 | |||
| f87fc1d4b1 |
@@ -19,3 +19,4 @@ DerivedData/
|
||||
|
||||
# Note: Package.resolved is intentionally tracked to pin the Lyrebird dependency.
|
||||
icon-source.png
|
||||
review.diff
|
||||
|
||||
@@ -163,7 +163,7 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 3;
|
||||
CURRENT_PROJECT_VERSION = 4;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
@@ -176,7 +176,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 1.0;
|
||||
MARKETING_VERSION = 1.2.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -194,7 +194,7 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 3;
|
||||
CURRENT_PROJECT_VERSION = 4;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
@@ -206,7 +206,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 1.0;
|
||||
MARKETING_VERSION = 1.2.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
|
||||
@@ -55,11 +55,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
private let shoeGaze: ShoeGaze
|
||||
private let window: LyrebirdWindow
|
||||
|
||||
/// The rig library; constructed in `init`, resolved + loaded asynchronously after launch.
|
||||
private let library: RigLibraryStore
|
||||
|
||||
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
|
||||
private var recordMenuItem: NSMenuItem?
|
||||
|
||||
/// Default file name offered by the Save panel.
|
||||
private static let defaultRigFileName: String = "ShoeGazeRig"
|
||||
/// Default file name offered by the archive Export panel.
|
||||
private static let defaultArchiveFileName: String = "ShoeGaze Library"
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
@@ -73,24 +76,29 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
numAudioBuses: AppDelegate.numAudioBuses,
|
||||
driver: coreDriver
|
||||
)
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
|
||||
self.coreDriver = coreDriver
|
||||
self.engine = engine
|
||||
self.shoeGaze = ShoeGaze(engine: engine)
|
||||
self.shoeGaze = shoeGaze
|
||||
self.window = LyrebirdWindow(
|
||||
title: "ShoeGaze Builder — Lyrebird Pedalboard",
|
||||
width: AppDelegate.windowWidth,
|
||||
height: AppDelegate.windowHeight
|
||||
)
|
||||
super.init()
|
||||
|
||||
// Restore the autosaved rig if there is one; otherwise seed a default board.
|
||||
// Stored `let`s must be set before `super.init()`. Restore the autosaved working rig (or
|
||||
// seed a board) — operating on `shoeGaze`, not on `self` methods (unavailable pre-super).
|
||||
if !RigStore.restore(into: shoeGaze) {
|
||||
seedInitialBoard()
|
||||
AppDelegate.seedInitialBoard(into: shoeGaze)
|
||||
}
|
||||
// The library constructs instantly; it resolves iCloud + loads asynchronously after launch.
|
||||
self.library = RigLibraryBootstrap.makeStore()
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
|
||||
private func seedInitialBoard() {
|
||||
private static func seedInitialBoard(into shoeGaze: ShoeGaze) {
|
||||
var created: PedalBoard?
|
||||
do {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
@@ -108,10 +116,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
installMainMenu()
|
||||
let session: ShoeGaze = shoeGaze
|
||||
let driver: CoreAudioDriver = coreDriver
|
||||
let rigLibrary: RigLibraryStore = library
|
||||
window.open {
|
||||
ShoeGazeBuilderView(shoeGaze: session, hardwareSampleRate: { driver.deviceSampleRate })
|
||||
ShoeGazeBuilderView(
|
||||
shoeGaze: session,
|
||||
library: rigLibrary,
|
||||
hardwareSampleRate: { driver.deviceSampleRate }
|
||||
)
|
||||
}
|
||||
anchorWindowLeft()
|
||||
|
||||
// Resolve iCloud + load the library off the main thread, then seed from the working rig if
|
||||
// it is still empty (first run).
|
||||
let rigSession: ShoeGaze = shoeGaze
|
||||
Task { await RigLibraryBootstrap.start(rigLibrary, seedFrom: rigSession) }
|
||||
}
|
||||
|
||||
/// Anchors the window `leftMargin` points from the left of the visible screen and sizes it to
|
||||
@@ -136,8 +154,61 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens `.shoegaze` files handed to the app by Finder, AirDrop, "Open With", or a double-click.
|
||||
///
|
||||
/// Rig documents are imported into the library (they appear in the sidebar, ready to load);
|
||||
/// board documents are surfaced with a note that boards are opened from a rig's board editor.
|
||||
func application(_ application: NSApplication, open urls: [URL]) {
|
||||
for url: URL in urls {
|
||||
openShoeGazeDocument(at: url)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads and imports a single `.shoegaze` document, reporting the outcome to the user.
|
||||
private func openShoeGazeDocument(at url: URL) {
|
||||
// A LaunchServices-supplied URL is security-scoped; start access to read it.
|
||||
let scoped: Bool = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
do {
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
let document: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
|
||||
if document.rigEntries?.isEmpty == false {
|
||||
let added: Int = try library.importArchive(from: data)
|
||||
presentOpenInfo(
|
||||
title: added == 1 ? "Rig Imported" : "Rigs Imported",
|
||||
message: added == 1
|
||||
? "Added 1 rig to your library. Select it in the Rigs sidebar to load it."
|
||||
: "Added \(added) rigs to your library. Select one in the Rigs sidebar to load it."
|
||||
)
|
||||
} else if document.boardVersion != nil {
|
||||
presentOpenInfo(
|
||||
title: "Board Document",
|
||||
message: "This file is a single board. Open a rig, then load the board from the "
|
||||
+ "board editor's Versions menu."
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
presentOpenInfo(
|
||||
title: "Couldn’t Open File",
|
||||
message: "“\(url.lastPathComponent)” is not a readable ShoeGaze document."
|
||||
)
|
||||
print("[ShoeGazeBuilder] open document failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows a one-button informational alert for a document-open outcome.
|
||||
private func presentOpenInfo(title: String, message: String) {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = title
|
||||
alert.informativeText = message
|
||||
alert.addButton(withTitle: "OK")
|
||||
alert.runModal()
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
RigStore.save(shoeGaze)
|
||||
// Ensure any in-flight background rig-library writes finish before exit.
|
||||
library.flushPendingWrites()
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
@@ -180,8 +251,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
mainMenu.addItem(fileMenuItem)
|
||||
let fileMenu: NSMenu = NSMenu(title: "File")
|
||||
fileMenuItem.submenu = fileMenu
|
||||
addItem(to: fileMenu, title: "Save Rig…", action: #selector(saveRigAction(_:)), key: "s")
|
||||
addItem(to: fileMenu, title: "Load Rig…", action: #selector(loadRigAction(_:)), key: "o")
|
||||
// Per-rig commands forward to the in-window builder (which owns the current-rig state and
|
||||
// the naming prompts) via notifications.
|
||||
addItem(to: fileMenu, title: "New Rig", action: #selector(newRigAction(_:)), key: "n")
|
||||
addItem(to: fileMenu, title: "Save Rig", action: #selector(saveRigAction(_:)), key: "s")
|
||||
fileMenu.addItem(NSMenuItem.separator())
|
||||
// The whole-library archive: a single file holding every rig, for backup or transfer.
|
||||
addItem(to: fileMenu, title: "Export Archive…", action: #selector(exportArchiveAction(_:)), key: "e")
|
||||
addItem(to: fileMenu, title: "Import Archive…", action: #selector(importArchiveAction(_:)), key: "i")
|
||||
|
||||
// Board menu — add board + transport.
|
||||
let boardMenuItem: NSMenuItem = NSMenuItem()
|
||||
@@ -230,34 +307,44 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
// MARK: - Menu actions
|
||||
|
||||
@objc private func newRigAction(_ sender: Any?) {
|
||||
// Forward to the builder view, which owns the current-rig state and naming prompt.
|
||||
NotificationCenter.default.post(name: .shoeGazeNewRig, object: nil)
|
||||
}
|
||||
|
||||
@objc private func saveRigAction(_ sender: Any?) {
|
||||
NotificationCenter.default.post(name: .shoeGazeSaveRig, object: nil)
|
||||
}
|
||||
|
||||
@objc private func exportArchiveAction(_ sender: Any?) {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.allowedContentTypes = [.json]
|
||||
panel.nameFieldStringValue = "\(AppDelegate.defaultRigFileName).json"
|
||||
panel.allowedContentTypes = [.shoeGaze]
|
||||
panel.nameFieldStringValue =
|
||||
"\(AppDelegate.defaultArchiveFileName).\(ShoeGazeDocument.fileExtension)"
|
||||
panel.canCreateDirectories = true
|
||||
let session: ShoeGaze = shoeGaze
|
||||
let rigLibrary: RigLibraryStore = library
|
||||
panel.begin { response in
|
||||
guard response == .OK, let url: URL = panel.url else { return }
|
||||
do { try session.saveRig(to: url) }
|
||||
catch { print("[ShoeGazeBuilder] saveRig failed: \(error)") }
|
||||
do { try rigLibrary.exportDocumentData().write(to: url, options: .atomic) }
|
||||
catch { print("[ShoeGazeBuilder] export library failed: \(error)") }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func loadRigAction(_ sender: Any?) {
|
||||
@objc private func importArchiveAction(_ sender: Any?) {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.json]
|
||||
// Accept the .shoegaze document plus legacy plain-JSON archives.
|
||||
panel.allowedContentTypes = [.shoeGaze, .json]
|
||||
panel.canChooseDirectories = false
|
||||
panel.allowsMultipleSelection = false
|
||||
let session: ShoeGaze = shoeGaze
|
||||
let activeEngine: SynthesisEngine = engine
|
||||
let rigLibrary: RigLibraryStore = library
|
||||
panel.begin { response in
|
||||
guard response == .OK, let url: URL = panel.url else { return }
|
||||
// loadRig rebuilds the graph; stop the engine around it and restart if it was running.
|
||||
let wasRunning: Bool = activeEngine.isRunning
|
||||
if wasRunning { activeEngine.stop() }
|
||||
do { try session.loadRig(from: url) }
|
||||
catch { print("[ShoeGazeBuilder] loadRig failed: \(error)") }
|
||||
if wasRunning { try? activeEngine.start() }
|
||||
do {
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
_ = try rigLibrary.importArchive(from: data)
|
||||
} catch {
|
||||
print("[ShoeGazeBuilder] import library failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<string>1.3.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSApplicationCategoryType</key>
|
||||
@@ -28,5 +28,56 @@
|
||||
<string>ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSUbiquitousContainers</key>
|
||||
<dict>
|
||||
<key>iCloud.net.realizedsound.ShoeGazeData</key>
|
||||
<dict>
|
||||
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
|
||||
<true/>
|
||||
<key>NSUbiquitousContainerName</key>
|
||||
<string>ShoeGaze</string>
|
||||
<key>NSUbiquitousContainerSupportedFolderLevels</key>
|
||||
<string>Any</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>ShoeGaze Document</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Editor</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Owner</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array>
|
||||
<string>net.realizedsound.shoegaze</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>UTExportedTypeDeclarations</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UTTypeIdentifier</key>
|
||||
<string>net.realizedsound.shoegaze</string>
|
||||
<key>UTTypeDescription</key>
|
||||
<string>ShoeGaze Document</string>
|
||||
<key>UTTypeConformsTo</key>
|
||||
<array>
|
||||
<string>public.json</string>
|
||||
</array>
|
||||
<key>UTTypeTagSpecification</key>
|
||||
<dict>
|
||||
<key>public.filename-extension</key>
|
||||
<array>
|
||||
<string>shoegaze</string>
|
||||
</array>
|
||||
<key>public.mime-type</key>
|
||||
<array>
|
||||
<string>application/json</string>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -4,5 +4,17 @@
|
||||
<dict>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
<key>com.apple.developer.icloud-container-identifiers</key>
|
||||
<array>
|
||||
<string>iCloud.net.realizedsound.ShoeGazeData</string>
|
||||
</array>
|
||||
<key>com.apple.developer.icloud-services</key>
|
||||
<array>
|
||||
<string>CloudDocuments</string>
|
||||
</array>
|
||||
<key>com.apple.developer.ubiquity-container-identifiers</key>
|
||||
<array>
|
||||
<string>iCloud.net.realizedsound.ShoeGazeData</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -169,6 +169,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = iphoneos;
|
||||
@@ -194,6 +195,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = iphoneos;
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<string>1.3.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
@@ -41,5 +41,56 @@
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>NSUbiquitousContainers</key>
|
||||
<dict>
|
||||
<key>iCloud.net.realizedsound.ShoeGazeData</key>
|
||||
<dict>
|
||||
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
|
||||
<true/>
|
||||
<key>NSUbiquitousContainerName</key>
|
||||
<string>ShoeGaze</string>
|
||||
<key>NSUbiquitousContainerSupportedFolderLevels</key>
|
||||
<string>Any</string>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>CFBundleDocumentTypes</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>CFBundleTypeName</key>
|
||||
<string>ShoeGaze Document</string>
|
||||
<key>CFBundleTypeRole</key>
|
||||
<string>Editor</string>
|
||||
<key>LSHandlerRank</key>
|
||||
<string>Owner</string>
|
||||
<key>LSItemContentTypes</key>
|
||||
<array>
|
||||
<string>net.realizedsound.shoegaze</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<key>UTExportedTypeDeclarations</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UTTypeIdentifier</key>
|
||||
<string>net.realizedsound.shoegaze</string>
|
||||
<key>UTTypeDescription</key>
|
||||
<string>ShoeGaze Document</string>
|
||||
<key>UTTypeConformsTo</key>
|
||||
<array>
|
||||
<string>public.json</string>
|
||||
</array>
|
||||
<key>UTTypeTagSpecification</key>
|
||||
<dict>
|
||||
<key>public.filename-extension</key>
|
||||
<array>
|
||||
<string>shoegaze</string>
|
||||
</array>
|
||||
<key>public.mime-type</key>
|
||||
<array>
|
||||
<string>application/json</string>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.developer.icloud-container-identifiers</key>
|
||||
<array>
|
||||
<string>iCloud.net.realizedsound.ShoeGazeData</string>
|
||||
</array>
|
||||
<key>com.apple.developer.icloud-services</key>
|
||||
<array>
|
||||
<string>CloudDocuments</string>
|
||||
</array>
|
||||
<key>com.apple.developer.ubiquity-container-identifiers</key>
|
||||
<array>
|
||||
<string>iCloud.net.realizedsound.ShoeGazeData</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -26,13 +26,16 @@ struct ShoeGazeBuilderiOSApp: App {
|
||||
NavigationStack {
|
||||
ShoeGazeBuilderView(
|
||||
shoeGaze: model.shoeGaze,
|
||||
library: model.library,
|
||||
hardwareSampleRate: { model.hardwareSampleRate },
|
||||
onEnableLiveInput: { model.enableLiveInput() }
|
||||
)
|
||||
.navigationTitle("ShoeGaze Builder")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.task { await model.startLibrary() }
|
||||
}
|
||||
.onDisappear { model.stop() }
|
||||
.onOpenURL { url in model.importDocument(at: url) }
|
||||
}
|
||||
.onChange(of: scenePhase) { _, phase in
|
||||
// Persist the rig whenever the app leaves the foreground.
|
||||
|
||||
@@ -8,6 +8,7 @@ import AVFoundation
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdShoeGaze
|
||||
import LyrebirdShoeGazeUI
|
||||
|
||||
/// Observable model owning the `SynthesisEngine` and `ShoeGaze` session for the iOS builder.
|
||||
///
|
||||
@@ -48,28 +49,67 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
private var engine: SynthesisEngine
|
||||
private var iosDriver: iOSAudioDriver
|
||||
|
||||
/// The shared rig library (iCloud-or-local). Independent of the engine, so it survives the
|
||||
/// live-input engine rebuild.
|
||||
private(set) var library: RigLibraryStore
|
||||
|
||||
/// The sample rate the audio session actually committed to (for the config mismatch warning).
|
||||
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
|
||||
|
||||
/// Resolves iCloud + loads the library off the main thread, then seeds it from the working rig
|
||||
/// on first run. Call once from the app's `.task`. Safe to call again (no-op once non-empty).
|
||||
func startLibrary() async {
|
||||
await RigLibraryBootstrap.start(library, seedFrom: shoeGaze)
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init() {
|
||||
ShoeGazeBuilderiOSAppModel.configureAudioSession()
|
||||
let built: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
|
||||
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: ShoeGazeBuilderiOSAppModel.inputChannels)
|
||||
let shoeGaze: ShoeGaze = built.shoeGaze
|
||||
self.engine = built.engine
|
||||
self.iosDriver = built.driver
|
||||
self.shoeGaze = built.shoeGaze
|
||||
self.shoeGaze = shoeGaze
|
||||
|
||||
// Restore the autosaved rig if there is one; otherwise seed a default board.
|
||||
// Restore the autosaved working rig if there is one; otherwise seed a default board. Operate
|
||||
// on the local `shoeGaze`, not `self.shoeGaze`: self may not be touched until every stored
|
||||
// property (including `library`) is initialized.
|
||||
if !RigStore.restore(into: shoeGaze) {
|
||||
seedFallbackBoard()
|
||||
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
|
||||
}
|
||||
|
||||
// Construct the library instantly; it resolves iCloud + loads asynchronously via
|
||||
// startLibrary() from the app's .task.
|
||||
self.library = RigLibraryBootstrap.makeStore()
|
||||
}
|
||||
|
||||
/// Persists the current rig. Call when the app moves to the background.
|
||||
func save() {
|
||||
RigStore.save(shoeGaze)
|
||||
// Flush any in-flight background rig-library writes while we still have time in the
|
||||
// background.
|
||||
library.flushPendingWrites()
|
||||
}
|
||||
|
||||
// MARK: - Document open
|
||||
|
||||
/// Imports a `.shoegaze` file opened from Files, AirDrop, or another app into the rig library.
|
||||
/// Rig documents add their rigs (they appear in the sidebar, ready to load); board documents are
|
||||
/// ignored here. Returns the number of rigs added.
|
||||
@discardableResult
|
||||
func importDocument(at url: URL) -> Int {
|
||||
// A document opened from outside the sandbox is security-scoped; start access to read it.
|
||||
let scoped: Bool = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
do {
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
return try library.importArchive(from: data)
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderiOS] open document failed: \(error)")
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Audio session / engine construction
|
||||
@@ -158,7 +198,7 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
try shoeGaze.loadRig(from: snapshot)
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderiOS] rig restore after rebuild failed: \(error)")
|
||||
seedFallbackBoard()
|
||||
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
|
||||
}
|
||||
|
||||
selectLiveInputAndPersist()
|
||||
@@ -180,7 +220,7 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
}
|
||||
|
||||
/// Seeds a single default board so the rig is never empty after a failed restore.
|
||||
private func seedFallbackBoard() {
|
||||
private static func seedFallbackBoard(into shoeGaze: ShoeGaze) {
|
||||
do {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
board.label = "Board 1"
|
||||
|
||||
@@ -11,13 +11,16 @@ signal (no hardware needed) or on live guitar through an audio input.
|
||||
|
||||
## Features
|
||||
|
||||
- **22 modeled pedals** across drive, dynamics, EQ/filter, modulation, delay/reverb, and
|
||||
pitch — see the catalog below.
|
||||
- **32 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and
|
||||
texture — see the catalog below.
|
||||
- **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel
|
||||
style) or **Blend** any subset, each with its own level and a click-free crossfade.
|
||||
- **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or
|
||||
stereo lanes, and merge back to mono.
|
||||
- **Save / load rigs** as JSON, on both platforms.
|
||||
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across
|
||||
your devices and both apps via iCloud.
|
||||
- **Sharing** — send a rig or a saved board to anyone as a `.shoegaze` file via the system share
|
||||
sheet (AirDrop, Mail, Messages, Files); export/import the whole library the same way.
|
||||
- **Recording** — capture your output to timestamped files.
|
||||
- **Test signal or live input** — a built-in arpeggiated test loop (shared across all boards so
|
||||
they stay phase-locked) or a hardware input channel.
|
||||
@@ -28,11 +31,14 @@ signal (no hardware needed) or on live guitar through an audio input.
|
||||
|
||||
| Category | Pedals |
|
||||
|---|---|
|
||||
| Drive & dynamics | Overdrive, Fuzz, Compressor, Sustainer, Limiter, Noise Gate |
|
||||
| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Phaser |
|
||||
| Modulation | Tremolo, Modulation, Chorus, Ring Modulator, Diffuser |
|
||||
| Delay & reverb | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverb |
|
||||
| Pitch & octave | Octave Splitter, Bass Octaver |
|
||||
| Gain | Overdrive, Distortion, Fuzz |
|
||||
| Dynamics | Compressor, Sustainer, Limiter, Noise Gate |
|
||||
| EQ & filter | Graphic EQ, Auto-Wah, Mutant |
|
||||
| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Rotary, Ring Modulator |
|
||||
| Pitch | Bass Octaver, Octave Splitter, Harmonizer |
|
||||
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay |
|
||||
| Reverb | Reverb, Shimmer Reverb |
|
||||
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator |
|
||||
|
||||
Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format.
|
||||
|
||||
|
||||
+58
@@ -1,5 +1,63 @@
|
||||
# Releases
|
||||
|
||||
## 1.3.0 — 2026-06-28
|
||||
|
||||
### Sharing — the `.shoegaze` document type
|
||||
- New shareable file type **`.shoegaze`** (`net.realizedsound.shoegaze`, conforming to
|
||||
`public.json`) registered by every app, so the system associates the file with ShoeGaze for
|
||||
Open and Share.
|
||||
- **Share a rig** from the library sidebar (per-rig) and **share a saved board** from the board
|
||||
editor's Versions menu, via the OS share sheet — AirDrop, Mail, Messages, Files. Local only; no
|
||||
account or backend.
|
||||
- Library **export/import migrated** to `.shoegaze`. A document wraps either a whole rig (or many)
|
||||
or a single board; legacy archive and single-rig JSON files still import.
|
||||
- Internal per-rig and board-version files stay app-private JSON — only the share/export surface
|
||||
uses `.shoegaze`.
|
||||
|
||||
## 1.2.0 — 2026-06-28
|
||||
|
||||
### New pedals (catalog now 32)
|
||||
- **Distortion** — mid-gain saturation between Overdrive and Fuzz.
|
||||
- **Flanger** — sweeping comb-filter jet with feedback.
|
||||
- **Vibrato** — pure pitch wobble, fully wet.
|
||||
- **Rotary** — Leslie rotary-speaker: Doppler wobble + volume throb, two-speed with accel ramp.
|
||||
- **Harmonizer** — two pitch-shifted harmony voices at fixed musical intervals (stepped knob).
|
||||
- **Reverse Delay** — backward-tape segments with feedback trails.
|
||||
- **Shimmer Reverb** — regenerative reverb whose tail climbs an octave as it sustains.
|
||||
- **Bitcrusher** — sample-rate decimation + bit-depth reduction + tone.
|
||||
- **Granulator** — stereo grain cloud, scattered across the field by Spread.
|
||||
- **Auto Granulator** — granulator whose grain size tracks your dynamics (Response switch).
|
||||
|
||||
### Rig library (iCloud)
|
||||
- Rigs are a managed **library** in the sidebar (New, Save, Save As, Duplicate, Rename, Delete,
|
||||
Erase All), each holding multiple boards.
|
||||
- **iCloud sync** across devices and both apps via a shared container, with a local fallback.
|
||||
- **Archive** import/export bundles the whole library as one hand-editable JSON file (replaced the
|
||||
old single-rig save/load); legacy single-rig files still import.
|
||||
- macOS File menu: New Rig (⌘N), Save Rig (⌘S), Export / Import Archive (⌘E / ⌘I). Saves/loads run
|
||||
off the main thread.
|
||||
|
||||
### Builder UI
|
||||
- Reworked top layout (scope + CPU beside a stacked board-mixer / pedal-picker); **colour-coded**
|
||||
pedal cards with a **filter-by-type** menu; routing cards in their own row.
|
||||
- Dark color scheme pinned (fixes black-on-dark system controls on iOS); input-source picker
|
||||
reflects the In channel count immediately; failed edits surface as alerts.
|
||||
|
||||
### Fixes / under the hood
|
||||
- Granulators are now latency-free; Shimmer Reverb DC-blocked. New RT-safe generators
|
||||
(`ReverseDelay`, `SampleRateDecimate`, `BitReduce`, `ShimmerReverb`, `StereoGranulator`) and a
|
||||
reusable `PedalSelectorKnob`. 271 tests; RT-safety reviewed.
|
||||
|
||||
## 1.1.1 — 2026-06-26
|
||||
|
||||
### Fixes
|
||||
- Pedal **ⓘ info button** moved to the top-left corner (under the corner screw),
|
||||
out of the way of the name plate.
|
||||
- Fixed **dragging a pedal into a Stereo Unzip / Split / Parallel lane**. Dropping a pedal
|
||||
from the main chain (or another lane) into a region lane now moves it there, preserving its
|
||||
parameters — previously the drop was silently ignored. Empty lanes are also fully
|
||||
hit-testable now.
|
||||
|
||||
## 1.1.0 — 2026-06-24
|
||||
|
||||
### New pedals
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// BitReduce.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
|
||||
private let bitReduceZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Bit-depth reducer: quantises the signal to `2^bits` amplitude levels, producing the gritty
|
||||
/// quantisation noise of the "bit" half of a lo-fi / bitcrusher effect.
|
||||
///
|
||||
/// `bits` is read at control rate (once per block) and clamped to `[1, 16]`. Each sample is
|
||||
/// rounded to the nearest of `2^bits` levels over the `[-1, 1]` range (mid-tread). Output is mono.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to quantise.
|
||||
/// - bits: Bit depth — quantises to `2^bits` levels. Control rate; clamped to `[1, 16]`.
|
||||
public final class BitReduce: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal.
|
||||
let _input: any ValidGeneratorInput
|
||||
|
||||
/// `true` when `_input` resolved to a generator; classified once so the RT path runs no
|
||||
/// `is`/`as?` check.
|
||||
let _inputIsGenerator: Bool
|
||||
|
||||
/// Quantisation bit depth, read at block rate. Pass a control-rate node or scalar.
|
||||
let _bits: any ValidGeneratorInput
|
||||
|
||||
/// Quantisation bounds.
|
||||
private let minimumBits: Double = 1.0
|
||||
private let maximumBits: Double = 16.0
|
||||
|
||||
/// Creates a bit-depth reducer.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to quantise.
|
||||
/// - bits: Bit depth (control rate). Clamped to `[1, 16]`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
bits: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_bits = bits._resolvedInput()
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
// Sanitise the control read (finite + clamped) so `Int(bits.rounded())` can't trap on a
|
||||
// NaN/inf input.
|
||||
let rawBits: Double = _bits.floatValue(graph: graph)
|
||||
let bits: Double = rawBits.isFinite ? min(max(rawBits, minimumBits), maximumBits) : minimumBits
|
||||
// Number of quantisation levels = 2^bits, via an integer shift (avoids importing `pow`).
|
||||
// Clamp the shift amount directly too: `1 << bitsInt` is only safe while bits ∈ [1, 16].
|
||||
let bitsInt: Int = min(max(Int(bits.rounded()), 1), 16)
|
||||
let levels: Double = Double(1 << bitsInt)
|
||||
// Step between adjacent levels over [-1, 1], and its reciprocal for the round.
|
||||
let step: Double = 2.0 / levels
|
||||
let inverseStep: Double = levels / 2.0
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? bitReduceZeroBlock)
|
||||
: bitReduceZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
_result[0][i] = (x * inverseStep).rounded() * step
|
||||
}
|
||||
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
// ReverseDelay.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream input
|
||||
/// yields no channel for a `_computeSamples` call, so the RT path never allocates.
|
||||
private let reverseDelayZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Segmented reverse delay: records the input in fixed-length segments and plays each segment back
|
||||
/// **reversed**, so phrases come out backwards.
|
||||
///
|
||||
/// Two segment buffers ping-pong: one records the incoming signal while the other is read back from
|
||||
/// its end to its start. At each segment boundary the buffers swap. A short raised-edge (linear)
|
||||
/// fade at both ends of every reversed segment hides the wrap discontinuity, and an optional
|
||||
/// feedback term recirculates the reversed output into the record buffer for layered reverse trails.
|
||||
///
|
||||
/// `delay` and `feedback` are read at **control rate** (once per block via `floatValue`); a changed
|
||||
/// `delay` takes effect at the next segment boundary, so the segment length never changes mid-read.
|
||||
/// Output is mono (channel 0 of the input is processed).
|
||||
///
|
||||
/// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds — the RT path never
|
||||
/// allocates or resizes. Keep `delay <= maxDelay`; larger values are clamped.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to reverse.
|
||||
/// - maxDelay: Maximum segment length in seconds; sizes the pre-allocated buffers.
|
||||
/// - delay: Segment length in seconds. Control rate; clamped to `[1 frame, maxDelay]`; a change
|
||||
/// applies at the next segment boundary.
|
||||
/// - feedback: Reverse-trail feedback factor. Control rate; clamped to `[0, 0.95]`.
|
||||
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
|
||||
/// - fadeTime: Edge-fade length in seconds hiding the segment wrap. Defaults to `0.004`.
|
||||
public final class ReverseDelay: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs (classified once at init)
|
||||
|
||||
/// Resolved input signal.
|
||||
let _input: any ValidGeneratorInput
|
||||
|
||||
/// `true` when `_input` resolved to a generator; `false` for a scalar constant. Classified once
|
||||
/// so the RT path never runs an `is`/`as?` check.
|
||||
let _inputIsGenerator: Bool
|
||||
|
||||
/// Resolved control inputs. Read at block rate via `floatValue` — pass control-rate nodes
|
||||
/// (`@UIParam` projections) or scalars, not audio-rate generators.
|
||||
let _delay: any ValidGeneratorInput
|
||||
let _feedback: any ValidGeneratorInput
|
||||
|
||||
// MARK: - Buffers + state
|
||||
|
||||
/// The two ping-pong segment buffers, each `_maxFrames` long. One records while the other plays.
|
||||
private var _bufferA: [Double]
|
||||
private var _bufferB: [Double]
|
||||
|
||||
/// Maximum segment length in frames (`maxDelay · sampleRate`).
|
||||
private let _maxFrames: Int
|
||||
|
||||
/// `true` when buffer A is the record buffer (B plays); toggled at each segment boundary.
|
||||
var _recordIsA: Bool = true
|
||||
|
||||
/// Read/write position within the current segment, `0 ..< _segLen`.
|
||||
var _phase: Int = 0
|
||||
|
||||
/// Current segment length in frames.
|
||||
var _segLen: Int
|
||||
|
||||
/// `false` until the first render block adopts the live `delay` as the segment length (the node
|
||||
/// value isn't available at `init`).
|
||||
var _segLenInitialized: Bool = false
|
||||
|
||||
/// Edge-fade length in frames, clamped to half the segment per call.
|
||||
private let _fadeFrames: Int
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Largest stable feedback factor.
|
||||
private let maxFeedback: Double = 0.95
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a reverse delay.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to reverse.
|
||||
/// - maxDelay: Maximum segment length in seconds. Sizes the pre-allocated buffers.
|
||||
/// - delay: Segment length in seconds (control rate). Clamped to `[1 frame, maxDelay]`; a
|
||||
/// change applies at the next segment boundary.
|
||||
/// - feedback: Reverse-trail feedback factor (control rate). Clamped to `[0, 0.95]`. Defaults
|
||||
/// to `0`.
|
||||
/// - sampleRate: Sample rate used to size the buffers and convert seconds → frames.
|
||||
/// - fadeTime: Edge-fade length in seconds, hiding the segment wrap. Defaults to `0.004`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
maxDelay: Double,
|
||||
delay: any ValidGeneratorInput,
|
||||
feedback: any ValidGeneratorInput = 0.0,
|
||||
sampleRate: Double,
|
||||
fadeTime: Double = 0.004
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_delay = delay._resolvedInput()
|
||||
_feedback = feedback._resolvedInput()
|
||||
|
||||
let frames: Int = max(1, Int((maxDelay * sampleRate).rounded()))
|
||||
_maxFrames = frames
|
||||
_bufferA = [Double](repeating: 0.0, count: frames)
|
||||
_bufferB = [Double](repeating: 0.0, count: frames)
|
||||
_segLen = frames
|
||||
_fadeFrames = max(0, Int((fadeTime * sampleRate).rounded()))
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let sampleRate: Double = graph.engine.sampleRate
|
||||
// Sanitise control reads (finite + clamped): a NaN/inf/huge `delay` would otherwise trap the
|
||||
// seconds→frames `Int` conversion, and a NaN `feedback` would poison the loop.
|
||||
let maxDelaySeconds: Double = Double(_maxFrames) / sampleRate
|
||||
let rawDelay: Double = _delay.floatValue(graph: graph)
|
||||
let delaySeconds: Double = rawDelay.isFinite ? min(max(rawDelay, 0.0), maxDelaySeconds) : 0.0
|
||||
let rawFeedback: Double = _feedback.floatValue(graph: graph)
|
||||
let feedback: Double = rawFeedback.isFinite ? min(max(rawFeedback, 0.0), maxFeedback) : 0.0
|
||||
|
||||
// Target segment length, applied at the next boundary so a read never changes length mid-segment.
|
||||
// `delaySeconds` is bounded to `maxDelaySeconds`, so the `Int` conversion cannot overflow.
|
||||
let targetLen: Int = min(max(Int((delaySeconds * sampleRate).rounded()), 1), _maxFrames)
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? reverseDelayZeroBlock)
|
||||
: reverseDelayZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
var phase: Int = _phase
|
||||
var segLen: Int = _segLen
|
||||
var recordIsA: Bool = _recordIsA
|
||||
let fadeFrames: Int = _fadeFrames
|
||||
|
||||
// Adopt the live delay length on the first block — at `init` the node value isn't known, so
|
||||
// the segment must not start at the full buffer length (that would delay the first reversed
|
||||
// segment by `maxDelay`).
|
||||
if !_segLenInitialized {
|
||||
segLen = targetLen
|
||||
phase = 0
|
||||
_segLenInitialized = true
|
||||
}
|
||||
|
||||
_bufferA.withUnsafeMutableBufferPointer { aBuffer in
|
||||
_bufferB.withUnsafeMutableBufferPointer { bBuffer in
|
||||
// `baseAddress` is non-nil for these always-non-empty buffers (sized `_maxFrames >= 1`
|
||||
// at init), so this guard never fires; it satisfies the optional without an RT trap.
|
||||
guard let aPointer: UnsafeMutablePointer<Double> = aBuffer.baseAddress,
|
||||
let bPointer: UnsafeMutablePointer<Double> = bBuffer.baseAddress else { return }
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuffer in
|
||||
guard let outPointer: UnsafeMutablePointer<Double> = outBuffer.baseAddress else { return }
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
|
||||
let recordPointer: UnsafeMutablePointer<Double> = recordIsA ? aPointer : bPointer
|
||||
let playPointer: UnsafeMutablePointer<Double> = recordIsA ? bPointer : aPointer
|
||||
|
||||
// Reversed read: end of the play segment first.
|
||||
let readIndex: Int = segLen - 1 - phase
|
||||
let raw: Double = playPointer[readIndex]
|
||||
let envelope: Double = ReverseDelay.edgeFade(
|
||||
phase: phase, segLen: segLen, fadeFrames: fadeFrames
|
||||
)
|
||||
let out: Double = raw * envelope
|
||||
|
||||
recordPointer[phase] = x + feedback * out
|
||||
outPointer[i] = out
|
||||
|
||||
phase += 1
|
||||
if phase >= segLen {
|
||||
phase = 0
|
||||
recordIsA.toggle()
|
||||
segLen = targetLen
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_phase = phase
|
||||
_segLen = segLen
|
||||
_recordIsA = recordIsA
|
||||
return _result
|
||||
}
|
||||
|
||||
/// Linear raised-edge fade in `[0, 1]`: ramps up over the first `fadeFrames` of a segment and
|
||||
/// down over the last `fadeFrames`, flat `1` in the middle. De-clicks the reverse wrap.
|
||||
private static func edgeFade(
|
||||
phase: Int,
|
||||
segLen: Int,
|
||||
fadeFrames: Int
|
||||
) -> Double {
|
||||
let fade: Int = min(fadeFrames, segLen / 2)
|
||||
guard fade > 0 else { return 1.0 }
|
||||
let fromStart: Int = phase
|
||||
let fromEnd: Int = segLen - 1 - phase
|
||||
let nearestEdge: Int = min(fromStart, fromEnd)
|
||||
guard nearestEdge < fade else { return 1.0 }
|
||||
return Double(nearestEdge) / Double(fade)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// SampleRateDecimate.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
|
||||
private let sampleRateDecimateZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Sample-rate reducer (decimator): a sample-and-hold that latches a new input value only once
|
||||
/// every `downsample` samples, holding it in between. The aliased, stair-stepped result is the
|
||||
/// "crushed sample rate" half of a lo-fi / bitcrusher effect.
|
||||
///
|
||||
/// `downsample` is read at control rate (once per block). `1` passes the signal through; `N` holds
|
||||
/// each sample for `N` output samples (effective rate `sampleRate / N`). Output is mono (channel 0).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to decimate.
|
||||
/// - downsample: Hold length in samples — effective rate is `sampleRate / downsample`. Control
|
||||
/// rate; clamped to `>= 1` (`1` is transparent).
|
||||
public final class SampleRateDecimate: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal.
|
||||
let _input: any ValidGeneratorInput
|
||||
|
||||
/// `true` when `_input` resolved to a generator; classified once so the RT path runs no
|
||||
/// `is`/`as?` check.
|
||||
let _inputIsGenerator: Bool
|
||||
|
||||
/// Downsample factor, read at block rate. Pass a control-rate node or scalar.
|
||||
let _downsample: any ValidGeneratorInput
|
||||
|
||||
/// Samples remaining before the next latch. `0` latches a fresh input on the current sample.
|
||||
var _countdown: Int = 0
|
||||
|
||||
/// Currently held output value.
|
||||
var _held: Double = 0.0
|
||||
|
||||
/// Smallest decimation factor (pass-through).
|
||||
private let minimumFactor: Int = 1
|
||||
|
||||
/// Largest accepted decimation factor — bounds the control read so the `Int` conversion can
|
||||
/// never overflow on a NaN/inf/huge input.
|
||||
private let maximumFactor: Double = 1_048_576.0
|
||||
|
||||
/// Creates a sample-rate decimator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to decimate.
|
||||
/// - downsample: Hold length in samples (control rate). Clamped to `>= 1`; `1` is transparent.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
downsample: any ValidGeneratorInput
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_downsample = downsample._resolvedInput()
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
// Sanitise the control read (finite + clamped) so the `Int` conversion can't overflow.
|
||||
let raw: Double = _downsample.floatValue(graph: graph)
|
||||
let safeFactor: Double = raw.isFinite
|
||||
? min(max(raw, Double(minimumFactor)), maximumFactor)
|
||||
: Double(minimumFactor)
|
||||
let factor: Int = Int(safeFactor.rounded())
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? sampleRateDecimateZeroBlock)
|
||||
: sampleRateDecimateZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
var countdown: Int = _countdown
|
||||
var held: Double = _held
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
if countdown <= 0 {
|
||||
held = x
|
||||
countdown = factor
|
||||
}
|
||||
countdown -= 1
|
||||
_result[0][i] = held
|
||||
}
|
||||
|
||||
_countdown = countdown
|
||||
_held = held
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
// ShimmerReverb.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation // `cos` for the init-time Hann window (not used on the RT path)
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
|
||||
private let shimmerReverbZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Regenerative shimmer reverb: a damped feedback tank with an octave-up grain reader **inside**
|
||||
/// the feedback path, so the pitched-up tail recirculates and the shimmer builds and sustains
|
||||
/// (rather than the one-shot parallel pitch-into-reverb approximation).
|
||||
///
|
||||
/// Signal path per sample:
|
||||
/// ```
|
||||
/// input → 2 series Schroeder allpasses (diffusion) ─┐
|
||||
/// ▼
|
||||
/// tank delay (size) → damping one-pole → ┬─────────→ output (wet tail)
|
||||
/// │
|
||||
/// octave-up grains read from the tank ───┤ (× shimmer)
|
||||
/// ▼
|
||||
/// feedback = decay·damped + shimmer·pitched → written back into the tank
|
||||
/// ```
|
||||
///
|
||||
/// The octave-up is a two-grain, 50%-overlap, Hann-windowed reader running at 2× over the most
|
||||
/// recent `grain` samples of the tank (the live wet content), a tape-style pitch raise whose
|
||||
/// pitched output recirculates through the feedback. A per-sample safety clamp + denormal flush
|
||||
/// keep the loop bounded even at high `decay` / `shimmer`.
|
||||
///
|
||||
/// `size`, `decay`, `shimmer`, and `damp` are read at control rate (once per block). Output is mono.
|
||||
///
|
||||
/// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds plus the grain
|
||||
/// length — the RT path never allocates or resizes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to reverberate.
|
||||
/// - maxDelay: Maximum tank delay in seconds; sizes the pre-allocated buffer.
|
||||
/// - size: Tank delay in seconds. Control rate; clamped to `[0.005, maxDelay]`.
|
||||
/// - decay: Feedback gain (tail length). Control rate; clamped to `[0, 0.92]`.
|
||||
/// - shimmer: Octave-up feedback amount. Control rate; clamped to `[0, 0.85]`.
|
||||
/// - damp: High-frequency damping in the feedback `[0, 1]` (0 = bright, 1 = dark). Control rate.
|
||||
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
|
||||
public final class ShimmerReverb: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
let _input: any ValidGeneratorInput
|
||||
let _inputIsGenerator: Bool
|
||||
let _size: any ValidGeneratorInput
|
||||
let _decay: any ValidGeneratorInput
|
||||
let _shimmer: any ValidGeneratorInput
|
||||
let _damp: any ValidGeneratorInput
|
||||
|
||||
// MARK: - Buffers + state
|
||||
|
||||
/// Tank delay/grain buffer (circular), length `_bufLen`.
|
||||
private var _tank: [Double]
|
||||
/// Two Schroeder input-diffusion allpass buffers.
|
||||
private var _allpassA: [Double]
|
||||
private var _allpassB: [Double]
|
||||
/// Precomputed Hann window over one grain, length `_grainFrames`.
|
||||
private var _hann: [Double]
|
||||
|
||||
private let _bufLen: Int
|
||||
private let _grainFrames: Int
|
||||
private let _maxDelayFrames: Int
|
||||
private let _allpassALen: Int
|
||||
private let _allpassBLen: Int
|
||||
|
||||
private var _writePos: Int = 0
|
||||
private var _allpassAPos: Int = 0
|
||||
private var _allpassBPos: Int = 0
|
||||
private var _grainCounter: Int = 0
|
||||
private var _dampState: Double = 0.0
|
||||
/// DC-blocker state (previous input/output) on the feedback path.
|
||||
private var _dcX1: Double = 0.0
|
||||
private var _dcY1: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private let minSizeSeconds: Double = 0.005
|
||||
private let maxDecay: Double = 0.92
|
||||
private let maxShimmer: Double = 0.85
|
||||
private let grainSeconds: Double = 0.05
|
||||
/// Schroeder allpass coefficient and (prime-ish) lengths in samples for input diffusion.
|
||||
private let allpassGain: Double = 0.7
|
||||
private let allpassAFrames: Int = 142
|
||||
private let allpassBFrames: Int = 107
|
||||
/// Hard safety bound on the recirculated value — prevents runaway / NaN at extreme settings.
|
||||
private let safetyClamp: Double = 8.0
|
||||
/// Below this magnitude feedback state is flushed to zero (denormal guard).
|
||||
private let denormalFloor: Double = 1.0e-15
|
||||
/// DC-blocker pole — a one-pole high-pass on the feedback path. Without it the octave-up of DC
|
||||
/// (≈ DC) plus the DC-passing damping filter gives the loop a DC gain near `decay + shimmer`,
|
||||
/// which exceeds 1 at higher settings and accumulates into a DC offset. ~7 Hz cutoff @ 44.1 kHz
|
||||
/// — sub-bass only, so the shimmer wash is unaffected.
|
||||
private let dcBlockCoeff: Double = 0.999
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a shimmer reverb.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate signal to reverberate.
|
||||
/// - maxDelay: Maximum tank delay in seconds; sizes the pre-allocated buffer.
|
||||
/// - size: Tank delay in seconds. Control rate; clamped to `[0.005, maxDelay]`.
|
||||
/// - decay: Feedback gain (tail length). Control rate; clamped to `[0, 0.92]`.
|
||||
/// - shimmer: Octave-up feedback amount. Control rate; clamped to `[0, 0.85]`.
|
||||
/// - damp: High-frequency damping in the feedback `[0, 1]` (0 = bright, 1 = dark). Control rate.
|
||||
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
maxDelay: Double,
|
||||
size: any ValidGeneratorInput,
|
||||
decay: any ValidGeneratorInput,
|
||||
shimmer: any ValidGeneratorInput,
|
||||
damp: any ValidGeneratorInput,
|
||||
sampleRate: Double
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_size = size._resolvedInput()
|
||||
_decay = decay._resolvedInput()
|
||||
_shimmer = shimmer._resolvedInput()
|
||||
_damp = damp._resolvedInput()
|
||||
|
||||
let maxFrames: Int = max(1, Int((maxDelay * sampleRate).rounded()))
|
||||
let grain: Int = max(2, Int((grainSeconds * sampleRate).rounded()))
|
||||
_maxDelayFrames = maxFrames
|
||||
_grainFrames = grain
|
||||
// Buffer holds the deepest tank read plus a full grain look-back, with headroom.
|
||||
_bufLen = maxFrames + grain + 2
|
||||
_allpassALen = allpassAFrames
|
||||
_allpassBLen = allpassBFrames
|
||||
|
||||
_tank = [Double](repeating: 0.0, count: _bufLen)
|
||||
_allpassA = [Double](repeating: 0.0, count: allpassAFrames)
|
||||
_allpassB = [Double](repeating: 0.0, count: allpassBFrames)
|
||||
|
||||
// Precompute the Hann window for the grain (off the RT thread).
|
||||
var hann: [Double] = [Double](repeating: 0.0, count: grain)
|
||||
let twoPi: Double = 2.0 * Double.pi
|
||||
for i: Int in 0..<grain {
|
||||
hann[i] = 0.5 - 0.5 * cos(twoPi * Double(i) / Double(grain))
|
||||
}
|
||||
_hann = hann
|
||||
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let sampleRate: Double = graph.engine.sampleRate
|
||||
// Sanitise control reads (finite + clamped) so a NaN/inf/huge value can never reach the
|
||||
// feedback math or trap the seconds→frames `Int` conversion.
|
||||
let maxSizeSeconds: Double = Double(_maxDelayFrames) / sampleRate
|
||||
let sizeSeconds: Double = ShimmerReverb.clamp(_size.floatValue(graph: graph), minSizeSeconds, maxSizeSeconds)
|
||||
let decay: Double = ShimmerReverb.clamp(_decay.floatValue(graph: graph), 0.0, maxDecay)
|
||||
let shimmer: Double = ShimmerReverb.clamp(_shimmer.floatValue(graph: graph), 0.0, maxShimmer)
|
||||
let damp: Double = ShimmerReverb.clamp(_damp.floatValue(graph: graph), 0.0, 1.0)
|
||||
|
||||
let minFrames: Int = max(1, Int((minSizeSeconds * sampleRate).rounded()))
|
||||
// `sizeSeconds` is bounded to `maxSizeSeconds`, so `sizeSeconds · sampleRate <= _maxDelayFrames`
|
||||
// and the `Int` conversion cannot overflow.
|
||||
let sizeFrames: Int = min(max(Int((sizeSeconds * sampleRate).rounded()), minFrames), _maxDelayFrames)
|
||||
let halfGrain: Int = _grainFrames / 2
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? shimmerReverbZeroBlock)
|
||||
: shimmerReverbZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
var writePos: Int = _writePos
|
||||
var grainCounter: Int = _grainCounter
|
||||
var dampState: Double = _dampState
|
||||
var allpassAPos: Int = _allpassAPos
|
||||
var allpassBPos: Int = _allpassBPos
|
||||
var dcX1: Double = _dcX1
|
||||
var dcY1: Double = _dcY1
|
||||
|
||||
_tank.withUnsafeMutableBufferPointer { tankBuffer in
|
||||
_allpassA.withUnsafeMutableBufferPointer { apABuffer in
|
||||
_allpassB.withUnsafeMutableBufferPointer { apBBuffer in
|
||||
_hann.withUnsafeBufferPointer { hannBuffer in
|
||||
_result[0].withUnsafeMutableBufferPointer { outBuffer in
|
||||
guard let tank: UnsafeMutablePointer<Double> = tankBuffer.baseAddress,
|
||||
let apA: UnsafeMutablePointer<Double> = apABuffer.baseAddress,
|
||||
let apB: UnsafeMutablePointer<Double> = apBBuffer.baseAddress,
|
||||
let hann: UnsafePointer<Double> = hannBuffer.baseAddress,
|
||||
let out: UnsafeMutablePointer<Double> = outBuffer.baseAddress
|
||||
else { return }
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
|
||||
// Input diffusion: two series Schroeder allpasses.
|
||||
let diffused: Double = ShimmerReverb.allpass(
|
||||
ShimmerReverb.allpass(x, apA, &allpassAPos, _allpassALen, allpassGain),
|
||||
apB, &allpassBPos, _allpassBLen, allpassGain
|
||||
)
|
||||
|
||||
// Delayed tank read → one-pole damping (HF absorption).
|
||||
let readTail: Double = tank[ShimmerReverb.wrap(writePos - sizeFrames, _bufLen)]
|
||||
dampState = dampState + (1.0 - damp) * (readTail - dampState)
|
||||
let damped: Double = dampState
|
||||
|
||||
// Octave-up: two 50%-overlapped Hann grains read at 2× over the tank.
|
||||
let offsetA: Int = _grainFrames - grainCounter
|
||||
let phaseB: Int = (grainCounter + halfGrain) % _grainFrames
|
||||
let offsetB: Int = _grainFrames - phaseB
|
||||
let pitched: Double =
|
||||
hann[grainCounter] * tank[ShimmerReverb.wrap(writePos - offsetA, _bufLen)]
|
||||
+ hann[phaseB] * tank[ShimmerReverb.wrap(writePos - offsetB, _bufLen)]
|
||||
|
||||
// Feedback: decayed damped tail + pitched shimmer, DC-blocked so the
|
||||
// loop has no DC gain (the octave-up of DC is DC), then add the input.
|
||||
let feedbackRaw: Double = decay * damped + shimmer * pitched
|
||||
let feedback: Double = feedbackRaw - dcX1 + dcBlockCoeff * dcY1
|
||||
dcX1 = feedbackRaw
|
||||
dcY1 = feedback
|
||||
var writeVal: Double = diffused + feedback
|
||||
if writeVal > safetyClamp { writeVal = safetyClamp }
|
||||
else if writeVal < -safetyClamp { writeVal = -safetyClamp }
|
||||
// Flush denormals so they never recirculate in the tank (RT CPU guard).
|
||||
if abs(writeVal) < denormalFloor { writeVal = 0.0 }
|
||||
tank[writePos] = writeVal
|
||||
|
||||
out[i] = damped
|
||||
|
||||
writePos += 1
|
||||
if writePos >= _bufLen { writePos = 0 }
|
||||
grainCounter += 1
|
||||
if grainCounter >= _grainFrames { grainCounter = 0 }
|
||||
}
|
||||
if abs(dampState) < denormalFloor { dampState = 0.0 }
|
||||
if abs(dcY1) < denormalFloor { dcY1 = 0.0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_writePos = writePos
|
||||
_grainCounter = grainCounter
|
||||
_dampState = dampState
|
||||
_allpassAPos = allpassAPos
|
||||
_allpassBPos = allpassBPos
|
||||
_dcX1 = dcX1
|
||||
_dcY1 = dcY1
|
||||
return _result
|
||||
}
|
||||
|
||||
/// One Schroeder allpass step over a circular buffer; advances `pos`. `y = -g·x + d;
|
||||
/// buf = x + g·y` where `d` is the delayed sample.
|
||||
private static func allpass(
|
||||
_ x: Double,
|
||||
_ buffer: UnsafeMutablePointer<Double>,
|
||||
_ pos: inout Int,
|
||||
_ length: Int,
|
||||
_ gain: Double
|
||||
) -> Double {
|
||||
let delayed: Double = buffer[pos]
|
||||
let y: Double = -gain * x + delayed
|
||||
buffer[pos] = x + gain * y
|
||||
pos += 1
|
||||
if pos >= length { pos = 0 }
|
||||
return y
|
||||
}
|
||||
|
||||
/// Returns `v` clamped to `[lo, hi]`, or `lo` when `v` is not finite — sanitising control reads
|
||||
/// before they reach the feedback math or an `Int` frame conversion.
|
||||
private static func clamp(_ v: Double, _ lo: Double, _ hi: Double) -> Double {
|
||||
guard v.isFinite else { return lo }
|
||||
return min(max(v, lo), hi)
|
||||
}
|
||||
|
||||
/// Wraps `index` into `[0, length)` (handles a single negative wrap, as produced by
|
||||
/// `writePos - offset` with `offset <= length`).
|
||||
private static func wrap(_ index: Int, _ length: Int) -> Int {
|
||||
let m: Int = index % length
|
||||
return m < 0 ? m + length : m
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
// StereoGranulator.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation // `cos`/`sin` for the init-time Hann table and per-grain pan gains
|
||||
@_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
|
||||
private let stereoGranulatorZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Stereo input granulator (straight-through): windows and pans the **live** input directly,
|
||||
/// without a delay/look-back buffer, so there is no latency.
|
||||
///
|
||||
/// A pool of overlapping grain voices each apply a Hann envelope to the incoming sample and pan it
|
||||
/// to a fresh random position in `[-1, 1] × spread`; the windowed, panned copies sum to the stereo
|
||||
/// output. Because every active grain reads the current input sample (not buffered history), the
|
||||
/// effect adds stereo width and a shimmering amplitude texture with **no time delay**. `spread = 0`
|
||||
/// collapses every grain to centre (mono); `spread = 1` scatters grains across the full field.
|
||||
/// Output is normalised by `overlap` so density doesn't change the level.
|
||||
///
|
||||
/// `grainSize`, `overlap`, and `spread` are read at control rate (once per block). Output is two
|
||||
/// channels (`[0]` = left, `[1]` = right) — use the ``left`` / ``right`` accessors.
|
||||
///
|
||||
/// - Important: The grain voice pool is pre-allocated at `init` — the RT path never allocates.
|
||||
public final class StereoGranulator: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
let _input: any ValidGeneratorInput
|
||||
let _inputIsGenerator: Bool
|
||||
let _grainSize: any ValidGeneratorInput
|
||||
let _overlap: any ValidGeneratorInput
|
||||
let _spread: any ValidGeneratorInput
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// Precomputed unit Hann window, indexed by `phase · hannSize / grainLen`.
|
||||
private var _hann: [Double]
|
||||
private let _hannSize: Int = 2048
|
||||
|
||||
private let _maxGrainFrames: Int
|
||||
private let _minGrainFrames: Int
|
||||
|
||||
// Grain voice pool (fixed size; a grain that can't find a free voice is skipped).
|
||||
private static let maxVoices: Int = 24
|
||||
private var _vActive: [Bool]
|
||||
private var _vPhase: [Int]
|
||||
private var _vLen: [Int]
|
||||
private var _vGainL: [Double]
|
||||
private var _vGainR: [Double]
|
||||
|
||||
private var _spawnCountdown: Int = 0
|
||||
private var _rng: UInt64
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private let minGrainSeconds: Double = 0.003
|
||||
/// Equal-power pan: `angle = (pan + 1) · π/4`, `gainL = cos`, `gainR = sin`.
|
||||
private let panAngleScale: Double = Double.pi / 4.0
|
||||
/// Non-zero fallback PRNG seed (golden-ratio constant).
|
||||
private static let defaultSeed: UInt64 = 0x9E37_79B9_7F4A_7C15
|
||||
|
||||
public override var outputChannelCount: Int { 2 }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a stereo granulator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Audio-rate mono signal to granulate.
|
||||
/// - maxGrainSize: Largest grain length in seconds; bounds the grain-length clamp.
|
||||
/// - grainSize: Grain (window) length in seconds. Control rate; clamped to `[~0.003, maxGrainSize]`.
|
||||
/// - overlap: Number of overlapping grains (density); also the level normaliser. Control rate;
|
||||
/// clamped to `[1, 24]`.
|
||||
/// - spread: Stereo spread `[0, 1]` — scales each grain's random pan. Control rate.
|
||||
/// - sampleRate: Sample rate used to convert grain seconds → frames.
|
||||
/// - seed: Optional PRNG seed for deterministic grain panning (tests). Defaults to a constant.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
maxGrainSize: Double,
|
||||
grainSize: any ValidGeneratorInput,
|
||||
overlap: any ValidGeneratorInput,
|
||||
spread: any ValidGeneratorInput,
|
||||
sampleRate: Double,
|
||||
seed: UInt64? = nil
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_inputIsGenerator = resolvedInput is any Generator
|
||||
_grainSize = grainSize._resolvedInput()
|
||||
_overlap = overlap._resolvedInput()
|
||||
_spread = spread._resolvedInput()
|
||||
|
||||
_maxGrainFrames = max(1, Int((maxGrainSize * sampleRate).rounded()))
|
||||
_minGrainFrames = max(1, Int((minGrainSeconds * sampleRate).rounded()))
|
||||
|
||||
_vActive = [Bool](repeating: false, count: StereoGranulator.maxVoices)
|
||||
_vPhase = [Int](repeating: 0, count: StereoGranulator.maxVoices)
|
||||
_vLen = [Int](repeating: 1, count: StereoGranulator.maxVoices)
|
||||
_vGainL = [Double](repeating: 0.0, count: StereoGranulator.maxVoices)
|
||||
_vGainR = [Double](repeating: 0.0, count: StereoGranulator.maxVoices)
|
||||
|
||||
var hann: [Double] = [Double](repeating: 0.0, count: _hannSize)
|
||||
let twoPi: Double = 2.0 * Double.pi
|
||||
for i: Int in 0..<_hannSize {
|
||||
hann[i] = 0.5 - 0.5 * cos(twoPi * Double(i) / Double(_hannSize))
|
||||
}
|
||||
_hann = hann
|
||||
|
||||
let requestedSeed: UInt64 = seed ?? StereoGranulator.defaultSeed
|
||||
_rng = requestedSeed == 0 ? StereoGranulator.defaultSeed : requestedSeed
|
||||
|
||||
super.init(channels: 2)
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let sampleRate: Double = graph.engine.sampleRate
|
||||
|
||||
let rawGrain: Double = _grainSize.floatValue(graph: graph)
|
||||
let grainSeconds: Double = rawGrain.isFinite
|
||||
? min(max(rawGrain, minGrainSeconds), Double(_maxGrainFrames) / sampleRate)
|
||||
: minGrainSeconds
|
||||
let grainLen: Int = min(max(Int((grainSeconds * sampleRate).rounded()), _minGrainFrames), _maxGrainFrames)
|
||||
|
||||
let rawOverlap: Double = _overlap.floatValue(graph: graph)
|
||||
let overlap: Int = rawOverlap.isFinite
|
||||
? min(max(Int(rawOverlap.rounded()), 1), StereoGranulator.maxVoices)
|
||||
: 1
|
||||
|
||||
let rawSpread: Double = _spread.floatValue(graph: graph)
|
||||
let spread: Double = rawSpread.isFinite ? min(max(rawSpread, 0.0), 1.0) : 0.0
|
||||
|
||||
let spawnPeriod: Int = max(1, grainLen / overlap)
|
||||
// Normalise so denser overlap doesn't raise the level (≈ sum of overlapping Hann windows).
|
||||
let norm: Double = 1.0 / Double(overlap)
|
||||
|
||||
let inputSamples: [Double] = _inputIsGenerator
|
||||
? (_input.calculatedSamples(graph: graph, count: count).first ?? stereoGranulatorZeroBlock)
|
||||
: stereoGranulatorZeroBlock
|
||||
let inputCount: Int = inputSamples.count
|
||||
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
|
||||
|
||||
var spawnCountdown: Int = _spawnCountdown
|
||||
var rng: UInt64 = _rng
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = _inputIsGenerator
|
||||
? (i < inputCount ? inputSamples[i] : 0.0)
|
||||
: inputScalar
|
||||
|
||||
var left: Double = 0.0
|
||||
var right: Double = 0.0
|
||||
for v: Int in 0..<StereoGranulator.maxVoices where _vActive[v] {
|
||||
let phase: Int = _vPhase[v]
|
||||
let len: Int = _vLen[v]
|
||||
let windowIndex: Int = phase * _hannSize / len
|
||||
// Straight-through: window + pan the LIVE sample (no delay buffer).
|
||||
let windowed: Double = x * _hann[windowIndex]
|
||||
left += windowed * _vGainL[v]
|
||||
right += windowed * _vGainR[v]
|
||||
let nextPhase: Int = phase + 1
|
||||
if nextPhase >= len {
|
||||
_vActive[v] = false
|
||||
} else {
|
||||
_vPhase[v] = nextPhase
|
||||
}
|
||||
}
|
||||
|
||||
spawnCountdown -= 1
|
||||
if spawnCountdown <= 0 {
|
||||
spawnCountdown = spawnPeriod
|
||||
spawnGrain(grainLen: grainLen, spread: spread, rng: &rng)
|
||||
}
|
||||
|
||||
_result[0][i] = left * norm
|
||||
_result[1][i] = right * norm
|
||||
}
|
||||
|
||||
_spawnCountdown = spawnCountdown
|
||||
_rng = rng
|
||||
return _result
|
||||
}
|
||||
|
||||
/// Activates the first free grain voice (no-op if all are busy — overlap saturates gracefully).
|
||||
private func spawnGrain(
|
||||
grainLen: Int,
|
||||
spread: Double,
|
||||
rng: inout UInt64
|
||||
) {
|
||||
var voice: Int = -1
|
||||
for v: Int in 0..<StereoGranulator.maxVoices where !_vActive[v] {
|
||||
voice = v
|
||||
break
|
||||
}
|
||||
guard voice >= 0 else { return }
|
||||
|
||||
_vActive[voice] = true
|
||||
_vPhase[voice] = 0
|
||||
_vLen[voice] = grainLen
|
||||
let pan: Double = xorshift64Next(&rng) * spread // shared RT-safe PRNG, [-1, 1) × spread
|
||||
let angle: Double = (pan + 1.0) * panAngleScale
|
||||
_vGainL[voice] = cos(angle)
|
||||
_vGainR[voice] = sin(angle)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Channel accessors
|
||||
|
||||
public extension StereoGranulator {
|
||||
/// Left output channel.
|
||||
var left: ChannelSelect.Audio { self[0] }
|
||||
/// Right output channel.
|
||||
var right: ChannelSelect.Audio { self[1] }
|
||||
}
|
||||
@@ -168,6 +168,15 @@ open class Pedal: SynthesizerBase {
|
||||
[]
|
||||
}
|
||||
|
||||
/// Effect-specific stepped "knob picker" controls for this pedal, rendered as a row of rotary
|
||||
/// knobs that snap to labelled stops, beneath the knob grid.
|
||||
///
|
||||
/// Override in subclasses to publish each discrete `@UIParam` parameter that reads best as a
|
||||
/// knob that snaps through fixed positions (e.g. a harmony interval selector). Defaults to empty.
|
||||
open var effectSelectors: [PedalSelectorKnob] {
|
||||
[]
|
||||
}
|
||||
|
||||
/// 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.
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
// PedalSelectorKnob.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdUI
|
||||
|
||||
/// A UI-agnostic description of a knob that snaps to a fixed set of labelled stops.
|
||||
///
|
||||
/// Where ``PedalKnob`` is a continuous rotary and ``PedalSwitch`` is a segmented strip, a
|
||||
/// `PedalSelectorKnob` reads like a rotary knob but quantises to discrete positions — a knob picker.
|
||||
/// Dragging rotates through the stops; the knob shows the current stop's caption. A `Pedal`
|
||||
/// publishes an array of these via ``Pedal/effectSelectors`` so a generic pedalboard UI can render
|
||||
/// a stepped knob per discrete parameter without knowing the concrete type.
|
||||
///
|
||||
/// Each stop pairs a short caption with the exact `Double` written to the live ``UIParamNode`` when
|
||||
/// that position is selected; the lit position is the stop whose `value` is nearest the node's
|
||||
/// current value.
|
||||
public struct PedalSelectorKnob {
|
||||
|
||||
/// One labelled position of a ``PedalSelectorKnob``.
|
||||
public struct Stop {
|
||||
|
||||
/// Short caption shown under the knob when this position is selected (e.g. "M3", "Oct").
|
||||
public let title: String
|
||||
|
||||
/// Value written to the node when this position is selected.
|
||||
public let value: Double
|
||||
|
||||
/// Creates a selector stop.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - title: Short caption shown when this position is selected.
|
||||
/// - value: Value written to the node when this position is selected.
|
||||
public init(title: String, value: Double) {
|
||||
self.title = title
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
|
||||
/// Short label shown beneath the knob (e.g. "Voice 1").
|
||||
public let label: String
|
||||
|
||||
/// The live parameter node the knob reads and writes. Pass `pedal.$paramName`.
|
||||
public let node: UIParamNode
|
||||
|
||||
/// Ordered stops the knob snaps through, from fully counter-clockwise to fully clockwise. Must
|
||||
/// contain at least two.
|
||||
public let stops: [Stop]
|
||||
|
||||
/// Creates a selector-knob descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Short label shown beneath the knob.
|
||||
/// - node: The `UIParamNode` projected value of an `@UIParam` property (`pedal.$voice1`, …).
|
||||
/// - stops: Ordered stops, CCW → CW. At least two.
|
||||
public init(
|
||||
label: String,
|
||||
node: UIParamNode,
|
||||
stops: [Stop]
|
||||
) {
|
||||
precondition(stops.count >= 2, "PedalSelectorKnob requires at least two stops")
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.stops = stops
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,7 @@ public extension PedalType {
|
||||
|
||||
// Drive & dynamics
|
||||
static let overdrive = PedalType("Overdrive")
|
||||
static let distortion = PedalType("Distortion")
|
||||
static let fuzz = PedalType("Fuzz")
|
||||
static let compressor = PedalType("Compressor")
|
||||
static let limiter = PedalType("Limiter")
|
||||
@@ -60,8 +61,14 @@ public extension PedalType {
|
||||
static let tremolo = PedalType("Tremolo")
|
||||
static let modulation = PedalType("Modulation")
|
||||
static let chorus = PedalType("Chorus")
|
||||
static let flanger = PedalType("Flanger")
|
||||
static let vibrato = PedalType("Vibrato")
|
||||
static let rotary = PedalType("Rotary")
|
||||
static let ringModulator = PedalType("Ring Modulator")
|
||||
static let diffuser = PedalType("Diffuser")
|
||||
static let bitcrusher = PedalType("Bitcrusher")
|
||||
static let granulator = PedalType("Granulator")
|
||||
static let autoGranulator = PedalType("Auto Granulator")
|
||||
|
||||
// Dynamics (additional)
|
||||
static let sustainer = PedalType("Sustainer")
|
||||
@@ -71,9 +78,12 @@ public extension PedalType {
|
||||
static let feedbackDelay = PedalType("Feedback Delay")
|
||||
static let multiTapDelay = PedalType("Multi-Tap Delay")
|
||||
static let pingPong = PedalType("Ping-Pong")
|
||||
static let reverseDelay = PedalType("Reverse Delay")
|
||||
static let reverb = PedalType("Reverb")
|
||||
static let shimmerReverb = PedalType("Shimmer Reverb")
|
||||
|
||||
// Pitch & octave
|
||||
static let octaveSplitter = PedalType("Octave Splitter")
|
||||
static let bassOctaver = PedalType("Bass Octaver")
|
||||
static let harmonizer = PedalType("Harmonizer")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// AutoGranulatorPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Amplitude-tracking stereo granulator.
|
||||
///
|
||||
/// Like ``GranulatorPedal``, but the grain size follows the input level: by default louder playing
|
||||
/// uses the **minimum** grain size and softer playing the **maximum** (so dynamics shrink and grow
|
||||
/// the grains). The `Response` switch flips that relationship. Grains are randomly scattered across
|
||||
/// the stereo field by `Spread`. Wraps ``StereoGranulator`` as a `.widener`.
|
||||
///
|
||||
/// The level → grain-size map is `AmplitudeFollower` → `LinLin`, with a `CrossFade` selecting the
|
||||
/// normal vs flipped mapping from the `Response` switch.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `minGrain`: Minimum grain size in seconds. Range `[0.005, 0.1]`.
|
||||
/// - `maxGrain`: Maximum grain size in seconds. Range `[0.05, 0.4]`.
|
||||
/// - `overlap`: Overlapping grain count (density). Range `[1, 16]`.
|
||||
/// - `spread`: Stereo spread `[0, 1]`.
|
||||
///
|
||||
/// ## Switches
|
||||
/// - `response` (two-state): `0` = Loud → Short grains, `1` = Loud → Long grains.
|
||||
public final class AutoGranulatorPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Granular wash whose grain size tracks your dynamics — loud shrinks grains, soft grows them."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Minimum grain size in seconds. Range [0.005, 0.1].
|
||||
@UIParam public var minGrain: Double = 0.02
|
||||
|
||||
/// Maximum grain size in seconds. Range [0.05, 0.4].
|
||||
@UIParam public var maxGrain: Double = 0.25
|
||||
|
||||
/// Overlapping grain count (density). Range [1, 16].
|
||||
@UIParam public var overlap: Double = 4.0
|
||||
|
||||
/// Stereo spread [0, 1].
|
||||
@UIParam public var spread: Double = 0.7
|
||||
|
||||
/// Level → grain-size response. `0` = Loud → Short, `1` = Loud → Long. Two-state switch.
|
||||
@UIParam public var response: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let defaultMix: Double = 0.5
|
||||
/// Largest grain the buffer is allocated for, in seconds (≥ the `maxGrain` knob maximum).
|
||||
private let maxGrainSize: Double = 0.4
|
||||
/// Amplitude at which the grain size reaches its loud-end value (follower output is unbounded;
|
||||
/// this sets the sensitivity). Values above it are clamped by the generator's grain-size clamp.
|
||||
private let ampSensitivity: Double = 0.5
|
||||
private let amplitudeAttack: Double = 0.01
|
||||
private let amplitudeRelease: Double = 0.2
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let minGrainRange: ClosedRange<Double> = 0.005 ... 0.1
|
||||
private let maxGrainRange: ClosedRange<Double> = 0.05 ... 0.4
|
||||
private let overlapRange: ClosedRange<Double> = 1.0 ... 16.0
|
||||
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Min Grain", node: $minGrain, range: minGrainRange),
|
||||
PedalKnob(label: "Max Grain", node: $maxGrain, range: maxGrainRange),
|
||||
PedalKnob(label: "Overlap", node: $overlap, range: overlapRange),
|
||||
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Switches
|
||||
|
||||
private let responseLoudShortValue: Double = 0.0
|
||||
private let responseLoudLongValue: Double = 1.0
|
||||
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Response",
|
||||
node: $response,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Loud→Short", value: responseLoudShortValue),
|
||||
PedalSwitch.Option(title: "Loud→Long", value: responseLoudLongValue),
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Channel topology
|
||||
|
||||
public override var channelKind: PedalChannelKind { .widener }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates an amplitude-tracking granulator 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: "Auto Granulator",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: AutoGranulatorPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func wideEffect(
|
||||
_ dry: any ValidGeneratorInput
|
||||
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||
let amplitude: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||
in: dry,
|
||||
attackTime: amplitudeAttack,
|
||||
releaseTime: amplitudeRelease
|
||||
)
|
||||
// Loud → short: amp 0 → maxGrain, amp ampSensitivity → minGrain.
|
||||
let loudShort: LinLin.Audio = LinLin.Audio(
|
||||
amplitude, inLo: 0.0, inHi: ampSensitivity, outLo: $maxGrain, outHi: $minGrain
|
||||
)
|
||||
// Loud → long: amp 0 → minGrain, amp ampSensitivity → maxGrain.
|
||||
let loudLong: LinLin.Audio = LinLin.Audio(
|
||||
amplitude, inLo: 0.0, inHi: ampSensitivity, outLo: $minGrain, outHi: $maxGrain
|
||||
)
|
||||
// `response` 0 → pan −1 → loudShort; 1 → pan +1 → loudLong (endpoints are full A / full B).
|
||||
let grainSize: CrossFade.Audio = CrossFade.Audio(
|
||||
inA: loudShort, inB: loudLong, pan: $response * 2.0 - 1.0
|
||||
)
|
||||
|
||||
let granulator: StereoGranulator = StereoGranulator(
|
||||
input: dry,
|
||||
maxGrainSize: maxGrainSize,
|
||||
grainSize: grainSize,
|
||||
overlap: $overlap,
|
||||
spread: $spread,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
return (granulator.left, granulator.right)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// BitcrusherPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Lo-fi bitcrusher: sample-rate decimation followed by bit-depth reduction.
|
||||
///
|
||||
/// A sample-and-hold drops the effective sample rate (aliasing, stair-stepping); a quantiser then
|
||||
/// reduces the bit depth (gritty quantisation noise). A post `Tone` low-pass tames the harsh
|
||||
/// aliasing for a more usable lo-fi voice. Wraps the ``SampleRateDecimate`` and ``BitReduce``
|
||||
/// generators, run fully wet so the pedal's `Mix` knob sets the blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `crush`: Sample-rate decimation factor (hold length in samples). Range `[1, 50]`.
|
||||
/// - `bits`: Bit depth. Range `[1, 16]`.
|
||||
/// - `tone`: Post low-pass cutoff in Hz. Range `[800, 8000]`.
|
||||
public final class BitcrusherPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Lo-fi crusher: drops the sample rate and bit depth for gritty digital grunge."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Sample-rate decimation factor (hold length in samples). Range [1, 50].
|
||||
@UIParam public var crush: Double = 8.0
|
||||
|
||||
/// Bit depth. Range [1, 16].
|
||||
@UIParam public var bits: Double = 8.0
|
||||
|
||||
/// Post low-pass cutoff in Hz. Range [800, 8000].
|
||||
@UIParam public var tone: Double = 4000.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Bitcrusher is heard fully wet; the `Mix` knob can dial it back.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Butterworth Q (no resonant peak) for the tone low-pass.
|
||||
private let filterQ: Double = 0.707
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let crushRange: ClosedRange<Double> = 1.0 ... 50.0
|
||||
private let bitsRange: ClosedRange<Double> = 1.0 ... 16.0
|
||||
private let toneRange: ClosedRange<Double> = 800.0 ... 8000.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Crush", node: $crush, range: crushRange),
|
||||
PedalKnob(label: "Bits", node: $bits, range: bitsRange),
|
||||
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a bitcrusher 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: "Bitcrusher",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: BitcrusherPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let decimated: SampleRateDecimate = SampleRateDecimate(input: dry, downsample: $crush)
|
||||
let crushed: BitReduce = BitReduce(input: decimated, bits: $bits)
|
||||
return RBJLowPass.Audio(input: crushed, freq: $tone, q: filterQ)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// DistortionPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Mid-gain distortion — more saturated than `OverdrivePedal`, more controlled than `FuzzPedal`.
|
||||
///
|
||||
/// A DC-blocking high-pass feeds a `tanh` soft-clipper driven hard by the `Drive` knob; a
|
||||
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip guarantees the
|
||||
/// output stays bounded.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `drive`: Pre-clip gain into the `tanh` stage. Range `[1, 50]`.
|
||||
/// - `tone`: Post-clip low-pass cutoff in Hz. Range `[500, 6000]`.
|
||||
public final class DistortionPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Mid-gain saturated distortion sitting between overdrive and fuzz."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Pre-clip gain into the `tanh` stage. Range [1, 50].
|
||||
@UIParam public var drive: Double = 12.0
|
||||
|
||||
/// Post-clip low-pass cutoff in Hz. Range [500, 6000].
|
||||
@UIParam public var tone: Double = 3000.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Distortion is heard fully wet; the `Level` knob sets output gain.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// DC-blocking high-pass cutoff in Hz, applied before the clipper.
|
||||
private let dcBlockFreq: Double = 80.0
|
||||
|
||||
/// Butterworth Q (no resonant peak) for the conditioning filters.
|
||||
private let filterQ: Double = 0.707
|
||||
|
||||
/// Output hard-clip bounds — guarantees a bounded signal after tone shaping.
|
||||
private let clipLow: Double = -1.0
|
||||
private let clipHigh: Double = 1.0
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let driveRange: ClosedRange<Double> = 1.0 ... 50.0
|
||||
private let toneRange: ClosedRange<Double> = 500.0 ... 6000.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Drive", node: $drive, range: driveRange),
|
||||
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a distortion 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: "Distortion",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: DistortionPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let dcBlocked: RBJHighPass.Audio = RBJHighPass.Audio(
|
||||
input: dry,
|
||||
freq: dcBlockFreq,
|
||||
q: filterQ
|
||||
)
|
||||
let driven: Tanh.Audio = Tanh.Audio(dcBlocked, mul: $drive)
|
||||
let toned: RBJLowPass.Audio = RBJLowPass.Audio(
|
||||
input: driven,
|
||||
freq: $tone,
|
||||
q: filterQ
|
||||
)
|
||||
return Clip.Audio(toned, lo: clipLow, hi: clipHigh)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// FlangerPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Classic jet-flanger.
|
||||
///
|
||||
/// A short LFO-swept delay summed with the dry signal produces the sweeping comb-filter notches;
|
||||
/// feedback sharpens them into the metallic "jet" whoosh. Wraps Lyrebird's `Flanger` generator,
|
||||
/// run fully wet so the pedal's own `Mix` knob sets the wet/dry blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `rate`: LFO sweep rate in Hz. Range `[0.05, 8]`.
|
||||
/// - `depth`: Sweep depth as a fraction of the center delay. Range `[0, 1]`.
|
||||
/// - `feedback`: Comb feedback (resonance). Range `[0, 0.95]`.
|
||||
public final class FlangerPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Sweeping comb-filter jet flanger, with feedback for that metallic whoosh."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// LFO sweep rate in Hz. Range [0.05, 8].
|
||||
@UIParam public var rate: Double = 0.4
|
||||
|
||||
/// Sweep depth as a fraction of the center delay. Range [0, 1].
|
||||
@UIParam public var depth: Double = 0.6
|
||||
|
||||
/// Comb feedback (resonance). Range [0, 0.95].
|
||||
@UIParam public var feedback: Double = 0.3
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — flanger sits under the dry signal.
|
||||
private static let defaultMix: Double = 0.5
|
||||
|
||||
/// Center delay the LFO sweeps around, in seconds.
|
||||
private let centerDelayTime: Double = 0.005
|
||||
|
||||
/// Maximum delay the line is allocated for, in seconds. Covers `centerDelayTime · (1 + maxDepth)`.
|
||||
private let maxDelayTime: Double = 0.05
|
||||
|
||||
/// The wrapped generator runs fully wet; the `Pedal` base `Mix` knob does the blend.
|
||||
private let fullyWetMix: Double = 1.0
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let rateRange: ClosedRange<Double> = 0.05 ... 8.0
|
||||
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
PedalKnob(label: "Depth", node: $depth, range: depthRange),
|
||||
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a flanger 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: "Flanger",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: FlangerPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
Flanger.Audio(
|
||||
input: dry,
|
||||
delayTime: centerDelayTime,
|
||||
depth: $depth,
|
||||
rate: $rate,
|
||||
feedback: $feedback,
|
||||
mix: fullyWetMix,
|
||||
sampleRate: sampleRate,
|
||||
maxDelayTime: maxDelayTime
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// GranulatorPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Stereo input granulator.
|
||||
///
|
||||
/// Chops the input into a cloud of overlapping windowed grains, each randomly scattered across the
|
||||
/// stereo field by `Spread`, for a lush, smeared, widened texture. Wraps the ``StereoGranulator``
|
||||
/// generator (mono in → stereo out) as a `.widener`.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `grain`: Grain size in seconds. Range `[0.01, 0.5]`.
|
||||
/// - `overlap`: Overlapping grain count (density). Range `[1, 16]`.
|
||||
/// - `spread`: Stereo spread `[0, 1]` — 0 = centred (mono), 1 = full field.
|
||||
public final class GranulatorPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Scatters overlapping grains of your sound across the stereo field — a lush, smeared wash."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Grain size in seconds. Range [0.01, 0.5].
|
||||
@UIParam public var grain: Double = 0.08
|
||||
|
||||
/// Overlapping grain count (density). Range [1, 16].
|
||||
@UIParam public var overlap: Double = 4.0
|
||||
|
||||
/// Stereo spread [0, 1].
|
||||
@UIParam public var spread: Double = 0.7
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let defaultMix: Double = 0.5
|
||||
/// Largest grain the buffer is allocated for, in seconds (≥ the `grain` knob maximum).
|
||||
private let maxGrainSize: Double = 0.5
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let grainRange: ClosedRange<Double> = 0.01 ... 0.5
|
||||
private let overlapRange: ClosedRange<Double> = 1.0 ... 16.0
|
||||
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Grain", node: $grain, range: grainRange),
|
||||
PedalKnob(label: "Overlap", node: $overlap, range: overlapRange),
|
||||
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Channel topology
|
||||
|
||||
public override var channelKind: PedalChannelKind { .widener }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a granulator 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: "Granulator",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: GranulatorPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func wideEffect(
|
||||
_ dry: any ValidGeneratorInput
|
||||
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||
let granulator: StereoGranulator = StereoGranulator(
|
||||
input: dry,
|
||||
maxGrainSize: maxGrainSize,
|
||||
grainSize: $grain,
|
||||
overlap: $overlap,
|
||||
spread: $spread,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
return (granulator.left, granulator.right)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// HarmonizerPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Two-voice diatonic-interval harmonizer.
|
||||
///
|
||||
/// Adds two pitch-shifted harmony voices at fixed musical intervals above or below the input,
|
||||
/// mixed against the dry signal — an OC-2-style level layout (Voice 1 / Voice 2 / Direct) with a
|
||||
/// knob picker selecting each voice's interval.
|
||||
///
|
||||
/// Each voice is a granular `PitchShift` whose ratio is `2^(semitones/12)`, driven live from the
|
||||
/// voice's interval selector. Intervals include minor and major thirds above and below, plus
|
||||
/// fourths, fifths, and octaves.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `voice1Level`: Voice 1 level in `[0, 1]`.
|
||||
/// - `voice2Level`: Voice 2 level in `[0, 1]`.
|
||||
/// - `direct`: Dry signal level in `[0, 1]`.
|
||||
///
|
||||
/// ## Selectors (knob pickers)
|
||||
/// - `voice1`: Voice 1 interval in semitones (snaps to musical intervals).
|
||||
/// - `voice2`: Voice 2 interval in semitones.
|
||||
public final class HarmonizerPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Two pitch-shifted harmony voices at intervals you pick, stacked under your note."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Voice 1 interval in semitones. Snaps to musical-interval stops.
|
||||
@UIParam public var voice1: Double = 4.0
|
||||
|
||||
/// Voice 2 interval in semitones. Snaps to musical-interval stops.
|
||||
@UIParam public var voice2: Double = 7.0
|
||||
|
||||
/// Voice 1 level in `[0, 1]`.
|
||||
@UIParam public var voice1Level: Double = 0.6
|
||||
|
||||
/// Voice 2 level in `[0, 1]`.
|
||||
@UIParam public var voice2Level: Double = 0.45
|
||||
|
||||
/// Dry (direct) signal level in `[0, 1]`.
|
||||
@UIParam public var direct: Double = 1.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Pedal blends internally via the level knobs, so the base wet/dry stays fully wet.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio`.
|
||||
private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12
|
||||
|
||||
/// Granular pitch-shift window in seconds. Larger = smoother but more latency.
|
||||
private let windowSize: Double = 0.1
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let levelRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "V1 Level", node: $voice1Level, range: levelRange),
|
||||
PedalKnob(label: "V2 Level", node: $voice2Level, range: levelRange),
|
||||
PedalKnob(label: "Direct", node: $direct, range: levelRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Selectors
|
||||
|
||||
/// Musical-interval stops for the voice pickers, low to high. Values are semitones; captions are
|
||||
/// short interval names (`m3`/`M3` = minor/major third, `4`/`5` = perfect fourth/fifth,
|
||||
/// `8ve` = octave, `Uni` = unison). Minus = below the input.
|
||||
private static let intervalStops: [PedalSelectorKnob.Stop] = [
|
||||
PedalSelectorKnob.Stop(title: "-8ve", value: -12.0),
|
||||
PedalSelectorKnob.Stop(title: "-M6", value: -9.0),
|
||||
PedalSelectorKnob.Stop(title: "-m6", value: -8.0),
|
||||
PedalSelectorKnob.Stop(title: "-5", value: -7.0),
|
||||
PedalSelectorKnob.Stop(title: "-4", value: -5.0),
|
||||
PedalSelectorKnob.Stop(title: "-M3", value: -4.0),
|
||||
PedalSelectorKnob.Stop(title: "-m3", value: -3.0),
|
||||
PedalSelectorKnob.Stop(title: "Uni", value: 0.0),
|
||||
PedalSelectorKnob.Stop(title: "m3", value: 3.0),
|
||||
PedalSelectorKnob.Stop(title: "M3", value: 4.0),
|
||||
PedalSelectorKnob.Stop(title: "4", value: 5.0),
|
||||
PedalSelectorKnob.Stop(title: "5", value: 7.0),
|
||||
PedalSelectorKnob.Stop(title: "m6", value: 8.0),
|
||||
PedalSelectorKnob.Stop(title: "M6", value: 9.0),
|
||||
PedalSelectorKnob.Stop(title: "8ve", value: 12.0),
|
||||
]
|
||||
|
||||
public override var effectSelectors: [PedalSelectorKnob] {
|
||||
[
|
||||
PedalSelectorKnob(label: "Voice 1", node: $voice1, stops: HarmonizerPedal.intervalStops),
|
||||
PedalSelectorKnob(label: "Voice 2", node: $voice2, stops: HarmonizerPedal.intervalStops),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a harmonizer pedal.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||
/// - outputBus: Audio bus index to write the output to. Defaults to `0`.
|
||||
public init(
|
||||
inputBus: Int = 0,
|
||||
outputBus: Int = 0
|
||||
) {
|
||||
super.init(
|
||||
name: "Harmonizer",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: HarmonizerPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let voice1Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice1)
|
||||
let voice2Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice2)
|
||||
|
||||
let directVoice: any ValidGeneratorInput = dry * $direct
|
||||
let harmony1: any ValidGeneratorInput = voice1Signal * $voice1Level
|
||||
let harmony2: any ValidGeneratorInput = voice2Signal * $voice2Level
|
||||
return directVoice + harmony1 + harmony2
|
||||
}
|
||||
|
||||
/// One pitch-shifted voice: ratio `2^(semitones/12)` via `Exp`, fed to a granular `PitchShift`.
|
||||
private func harmonyVoice(
|
||||
_ dry: any ValidGeneratorInput,
|
||||
semitones: any ValidGeneratorInput
|
||||
) -> any ValidGeneratorInput {
|
||||
let ratio: Exp.Audio = Exp.Audio(semitones * semitoneToRatioScale)
|
||||
return PitchShift.Audio(input: dry, pitchRatio: ratio, windowSize: windowSize)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// ReverseDelayPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Reverse delay.
|
||||
///
|
||||
/// Records the input in fixed-length segments and plays each one back reversed, so notes and
|
||||
/// phrases swell in backwards — the classic backwards-tape effect. `Feedback` recirculates the
|
||||
/// reversed output for layered backward trails. Wraps the ``ReverseDelay`` generator, run fully wet
|
||||
/// so the pedal's `Mix` knob sets the wet/dry blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `time`: Reverse segment length in seconds. Range `[0.05, 2.0]`.
|
||||
/// - `feedback`: Reverse-trail feedback. Range `[0, 0.95]`.
|
||||
public final class ReverseDelayPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Plays your phrases back in reverse — the backwards-tape swell, with feedback trails."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Reverse segment length in seconds. Range [0.05, 2.0].
|
||||
@UIParam public var time: Double = 0.5
|
||||
|
||||
/// Reverse-trail feedback. Range [0, 0.95].
|
||||
@UIParam public var feedback: Double = 0.3
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — reverse delay sits under the dry signal.
|
||||
private static let defaultMix: Double = 0.5
|
||||
|
||||
/// Maximum segment length the buffers are allocated for, in seconds.
|
||||
private let maxDelayTime: Double = 2.0
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let timeRange: ClosedRange<Double> = 0.05 ... 2.0
|
||||
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Time", node: $time, range: timeRange),
|
||||
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a reverse-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: "Reverse Delay",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: ReverseDelayPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
ReverseDelay(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: $time,
|
||||
feedback: $feedback,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// RotaryPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Rotary-speaker (Leslie) emulation.
|
||||
///
|
||||
/// A spinning speaker produces correlated amplitude modulation (volume throb) and frequency
|
||||
/// modulation (Doppler pitch wobble). This pedal builds both from one rotor LFO per channel, with
|
||||
/// the left and right rotors in anti-phase so the image rotates across the stereo field. A two-speed
|
||||
/// switch (Chorale / Tremolo) selects the rotor speed, and the **Accel** knob sets how quickly the
|
||||
/// rotor ramps between speeds — the authentic spin-up / spin-down glide — via a `Lag` on the rate.
|
||||
///
|
||||
/// Signal path (per channel, inside `wideEffect(_:)`):
|
||||
/// ```
|
||||
/// dry → DelayLine(delay: base ± fm·sin(rate)) → × (1 ± am·sin(rate)) → wet
|
||||
/// ```
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `depth`: Rotor intensity — scales both the AM throb and the FM Doppler. Range `[0, 1]`.
|
||||
/// - `accel`: Spin-up / spin-down ramp time in seconds. Range `[0.05, 3]`.
|
||||
///
|
||||
/// ## Switches
|
||||
/// - `speed` (two-state): `0` = Chorale (slow), `1` = Tremolo (fast).
|
||||
public final class RotaryPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Spinning Leslie rotor: Doppler pitch wobble plus volume throb, two-speed with ramp."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Rotor intensity — scales both AM and FM. Range [0, 1].
|
||||
@UIParam public var depth: Double = 0.7
|
||||
|
||||
/// Spin-up / spin-down ramp time in seconds. Range [0.05, 3].
|
||||
@UIParam public var accel: Double = 0.5
|
||||
|
||||
/// Rotor speed selector. `0` = Chorale (slow), `1` = Tremolo (fast). Driven by a two-state switch.
|
||||
@UIParam public var speed: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Rotary is heard fully wet; the `Mix` knob can dial it back if desired.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Chorale (slow) rotor rate in Hz.
|
||||
private let slowRateHz: Double = 0.8
|
||||
|
||||
/// Tremolo (fast) rotor rate in Hz.
|
||||
private let fastRateHz: Double = 6.5
|
||||
|
||||
/// Maximum FM (Doppler) sweep half-swing in seconds, at full depth.
|
||||
private let fmDepthScale: Double = 0.0008
|
||||
|
||||
/// Maximum AM (throb) depth, at full depth.
|
||||
private let amDepthScale: Double = 0.4
|
||||
|
||||
/// Center delay the FM sweeps around, in seconds.
|
||||
private let baseDelayTime: Double = 0.004
|
||||
|
||||
/// Maximum delay the lines are allocated for, in seconds.
|
||||
private let maxDelayTime: Double = 0.02
|
||||
|
||||
/// LFO phase (cycles) for the left rotor.
|
||||
private let leftPhase: Double = 0.0
|
||||
|
||||
/// LFO phase (cycles) for the right rotor — a half cycle opposite the left.
|
||||
private let rightPhase: Double = 0.5
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
private let accelRange: ClosedRange<Double> = 0.05 ... 3.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Depth", node: $depth, range: depthRange),
|
||||
PedalKnob(label: "Accel", node: $accel, range: accelRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Switches
|
||||
|
||||
private let speedChoraleValue: Double = 0.0
|
||||
private let speedTremoloValue: Double = 1.0
|
||||
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Speed",
|
||||
node: $speed,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Chorale", value: speedChoraleValue),
|
||||
PedalSwitch.Option(title: "Tremolo", value: speedTremoloValue),
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Channel topology
|
||||
|
||||
public override var channelKind: PedalChannelKind { .widener }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a rotary-speaker 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: "Rotary",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: RotaryPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func wideEffect(
|
||||
_ dry: any ValidGeneratorInput
|
||||
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
|
||||
// Rotor rate glides between the two speeds — the spin-up / spin-down ramp. Shared by both
|
||||
// rotors (fan-out is cached per block).
|
||||
let rateTarget: any ValidGeneratorInput = $speed * (fastRateHz - slowRateHz) + slowRateHz
|
||||
let rate: Lag.Audio = Lag.Audio(input: rateTarget, time: $accel)
|
||||
return (voice(dry, rate: rate, phase: leftPhase),
|
||||
voice(dry, rate: rate, phase: rightPhase))
|
||||
}
|
||||
|
||||
/// One rotor voice: a Doppler-swept delay line whose output is amplitude-modulated by the same
|
||||
/// rotor LFO, both at `rate` and the given `phase`.
|
||||
private func voice(
|
||||
_ dry: any ValidGeneratorInput,
|
||||
rate: any ValidGeneratorInput,
|
||||
phase: Double
|
||||
) -> any ValidGeneratorInput {
|
||||
let fmSweep: OscSin.Audio = OscSin.Audio(
|
||||
freq: rate,
|
||||
phase: phase,
|
||||
mul: $depth * fmDepthScale,
|
||||
add: baseDelayTime
|
||||
)
|
||||
let delayed: DelayLine = DelayLine(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: fmSweep,
|
||||
sampleRate: sampleRate,
|
||||
interpolation: .linear
|
||||
)
|
||||
// Throb gain in [1 - 2·depth·amScale, 1].
|
||||
let amGain: OscSin.Audio = OscSin.Audio(
|
||||
freq: rate,
|
||||
phase: phase,
|
||||
mul: $depth * amDepthScale,
|
||||
add: 1.0 - $depth * amDepthScale
|
||||
)
|
||||
return delayed * amGain
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// ShimmerReverbPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Shimmer reverb — an ambient reverb whose tail rises an octave as it sustains.
|
||||
///
|
||||
/// Wraps the ``ShimmerReverb`` generator: a damped feedback tank with an octave-up grain reader
|
||||
/// inside the feedback path, so the pitched tail regenerates into a glassy, ever-ascending wash.
|
||||
/// Run fully wet internally; the pedal's `Mix` knob sets the wet/dry blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `size`: Tank size (delay) in seconds. Range `[0.01, 0.12]`.
|
||||
/// - `decay`: Tail length (feedback). Range `[0, 0.92]`.
|
||||
/// - `shimmer`: Octave-up regeneration amount. Range `[0, 0.85]`.
|
||||
/// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark).
|
||||
public final class ShimmerReverbPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Ambient reverb whose tail climbs an octave as it sustains — glassy, ascending wash."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Tank size (delay) in seconds. Range [0.01, 0.12].
|
||||
@UIParam public var size: Double = 0.06
|
||||
|
||||
/// Tail length (feedback). Range [0, 0.92].
|
||||
@UIParam public var decay: Double = 0.8
|
||||
|
||||
/// Octave-up regeneration amount. Range [0, 0.85].
|
||||
@UIParam public var shimmer: Double = 0.5
|
||||
|
||||
/// High-frequency damping. Range [0, 1].
|
||||
@UIParam public var damp: Double = 0.4
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — reverb sits under the dry signal.
|
||||
private static let defaultMix: Double = 0.35
|
||||
|
||||
/// Maximum tank delay the buffers are allocated for, in seconds.
|
||||
private let maxDelayTime: Double = 0.12
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let sizeRange: ClosedRange<Double> = 0.01 ... 0.12
|
||||
private let decayRange: ClosedRange<Double> = 0.0 ... 0.92
|
||||
private let shimmerRange: ClosedRange<Double> = 0.0 ... 0.85
|
||||
private let dampRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Size", node: $size, range: sizeRange),
|
||||
PedalKnob(label: "Decay", node: $decay, range: decayRange),
|
||||
PedalKnob(label: "Shimmer", node: $shimmer, range: shimmerRange),
|
||||
PedalKnob(label: "Damp", node: $damp, range: dampRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a shimmer-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: "Shimmer Reverb",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: ShimmerReverbPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
ShimmerReverb(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
size: $size,
|
||||
decay: $decay,
|
||||
shimmer: $shimmer,
|
||||
damp: $damp,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// VibratoPedal.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Pitch vibrato.
|
||||
///
|
||||
/// A single delay line whose time is swept by a sine LFO produces a periodic pitch wobble. Unlike
|
||||
/// `TremoloPedal` (which modulates *volume*), vibrato modulates *pitch*, and unlike `ChorusPedal`
|
||||
/// it is heard fully wet — there is no dry voice underneath, so the result is pure pitch movement.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `rate`: LFO rate in Hz. Range `[0.1, 8]`.
|
||||
/// - `depth`: Delay-sweep depth in seconds (half-swing around the base delay). Range
|
||||
/// `[0.0005, 0.006]`.
|
||||
public final class VibratoPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
public override var summary: String {
|
||||
"Periodic pitch wobble — a sine-swept delay heard fully wet."
|
||||
}
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// LFO rate in Hz. Range [0.1, 8].
|
||||
@UIParam public var rate: Double = 5.0
|
||||
|
||||
/// Delay-sweep depth in seconds. Range [0.0005, 0.006].
|
||||
@UIParam public var depth: Double = 0.002
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Vibrato is pure pitch movement — fully wet, no dry voice underneath.
|
||||
private static let defaultMix: Double = 1.0
|
||||
|
||||
/// Base delay around which the LFO sweeps, in seconds.
|
||||
private let baseDelayTime: Double = 0.006
|
||||
|
||||
/// Maximum delay the line is allocated for, in seconds. Covers `baseDelayTime + max depth`.
|
||||
private let maxDelayTime: Double = 0.02
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let rateRange: ClosedRange<Double> = 0.1 ... 8.0
|
||||
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.006
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
PedalKnob(label: "Depth", node: $depth, range: depthRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a vibrato 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: "Vibrato",
|
||||
inputBus: inputBus,
|
||||
outputBus: outputBus,
|
||||
initialMix: VibratoPedal.defaultMix
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let sweep: OscSin.Audio = OscSin.Audio(
|
||||
freq: $rate,
|
||||
phase: 0.0,
|
||||
mul: $depth,
|
||||
add: baseDelayTime
|
||||
)
|
||||
return DelayLine(
|
||||
input: dry,
|
||||
maxDelay: maxDelayTime,
|
||||
delay: sweep,
|
||||
sampleRate: sampleRate,
|
||||
interpolation: .linear
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -98,7 +98,7 @@ public final class BoardVersionStore {
|
||||
_ version: BoardVersion,
|
||||
in directory: URL
|
||||
) throws {
|
||||
let sanitized: String = sanitizeFilename(version.name)
|
||||
let sanitized: String = sanitizePresetFilename(version.name, maxLength: maxNameLength)
|
||||
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
|
||||
let fileURL: URL = directory.appendingPathComponent(filename)
|
||||
do {
|
||||
@@ -134,7 +134,7 @@ public final class BoardVersionStore {
|
||||
attributes: nil
|
||||
)
|
||||
|
||||
let sanitized: String = sanitizeFilename(version.name)
|
||||
let sanitized: String = sanitizePresetFilename(version.name, maxLength: maxNameLength)
|
||||
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
|
||||
let fileURL: URL = directory.appendingPathComponent(filename)
|
||||
|
||||
@@ -236,53 +236,4 @@ public final class BoardVersionStore {
|
||||
/// Maximum UTF-8 byte length for the sanitised name prefix before the `-<uuid>.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
|
||||
/// (`<name>-<uuid>.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<Character> = ["/", "\\", ":", "\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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,11 +19,13 @@ extension Pedal {
|
||||
let values: [Double] = knobs.map { $0.node.value }
|
||||
let switchValues: [Double] = effectSwitches.map { $0.node.value }
|
||||
let sliderValues: [Double] = effectSliders.map { $0.node.value }
|
||||
let selectorValues: [Double] = effectSelectors.map { $0.node.value }
|
||||
return PedalState(
|
||||
type: displayName,
|
||||
knobValues: values,
|
||||
switchValues: switchValues,
|
||||
sliderValues: sliderValues,
|
||||
selectorValues: selectorValues,
|
||||
bypass: bypass
|
||||
)
|
||||
}
|
||||
@@ -51,6 +53,9 @@ extension Pedal {
|
||||
for (slider, value) in zip(effectSliders, state.sliderValues) {
|
||||
slider.node.update(value)
|
||||
}
|
||||
for (selector, value) in zip(effectSelectors, state.selectorValues) {
|
||||
selector.node.update(value)
|
||||
}
|
||||
bypass = state.bypass
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ public enum PedalRegistry {
|
||||
/// to a board via `board.add(_:)`.
|
||||
public static let builtIn: [String: @MainActor () -> Pedal] = [
|
||||
"Overdrive": { OverdrivePedal() },
|
||||
"Distortion": { DistortionPedal() },
|
||||
"Delay": { DelayPedal() },
|
||||
"Reverb": { ReverbPedal() },
|
||||
"Modulation": { ModulationPedal() },
|
||||
@@ -45,14 +46,23 @@ public enum PedalRegistry {
|
||||
"Multi-Tap Delay": { MultiTapDelayPedal() },
|
||||
"Octave Splitter": { OctaveUpSplitterPedal() },
|
||||
"Bass Octaver": { BassOctaverPedal() },
|
||||
"Harmonizer": { HarmonizerPedal() },
|
||||
"Ping-Pong": { PingPongDelayPedal() },
|
||||
"Reverse Delay": { ReverseDelayPedal() },
|
||||
"Shimmer Reverb": { ShimmerReverbPedal() },
|
||||
"Limiter": { LimiterPedal() },
|
||||
"Noise Gate": { NoiseGatePedal() },
|
||||
"Graphic EQ": { GraphicEQPedal() },
|
||||
"Chorus": { ChorusPedal() },
|
||||
"Flanger": { FlangerPedal() },
|
||||
"Vibrato": { VibratoPedal() },
|
||||
"Rotary": { RotaryPedal() },
|
||||
"Sustainer": { SustainerPedal() },
|
||||
"Ring Modulator": { RingModulatorPedal() },
|
||||
"Diffuser": { DiffuserPedal() },
|
||||
"Bitcrusher": { BitcrusherPedal() },
|
||||
"Granulator": { GranulatorPedal() },
|
||||
"Auto Granulator": { AutoGranulatorPedal() },
|
||||
]
|
||||
|
||||
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
|
||||
|
||||
@@ -30,6 +30,10 @@ public struct PedalState: Codable, Equatable {
|
||||
/// no sliders. Absent in presets saved before sliders existed — decodes to `[]`.
|
||||
public let sliderValues: [Double]
|
||||
|
||||
/// Selector-knob values in the same order as `Pedal.effectSelectors`. Empty for pedals with
|
||||
/// no selectors. Absent in presets saved before selectors existed — decodes to `[]`.
|
||||
public let selectorValues: [Double]
|
||||
|
||||
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
|
||||
public let bypass: Double
|
||||
|
||||
@@ -40,18 +44,21 @@ public struct PedalState: Codable, Equatable {
|
||||
/// - knobValues: Current knob values in `Pedal.knobs` order.
|
||||
/// - switchValues: Current switch values in `Pedal.effectSwitches` order. Defaults to empty.
|
||||
/// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty.
|
||||
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
|
||||
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
public init(
|
||||
type: String,
|
||||
knobValues: [Double],
|
||||
switchValues: [Double] = [],
|
||||
sliderValues: [Double] = [],
|
||||
selectorValues: [Double] = [],
|
||||
bypass: Double
|
||||
) {
|
||||
self.type = type
|
||||
self.knobValues = knobValues
|
||||
self.switchValues = switchValues
|
||||
self.sliderValues = sliderValues
|
||||
self.selectorValues = selectorValues
|
||||
self.bypass = bypass
|
||||
}
|
||||
|
||||
@@ -60,17 +67,19 @@ public struct PedalState: Codable, Equatable {
|
||||
case knobValues
|
||||
case switchValues
|
||||
case sliderValues
|
||||
case selectorValues
|
||||
case bypass
|
||||
}
|
||||
|
||||
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues`
|
||||
/// existed by defaulting the missing keys to an empty array.
|
||||
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` /
|
||||
/// `selectorValues` existed by defaulting the missing keys to an empty array.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.type = try container.decode(String.self, forKey: .type)
|
||||
self.knobValues = try container.decode([Double].self, forKey: .knobValues)
|
||||
self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? []
|
||||
self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? []
|
||||
self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? []
|
||||
self.bypass = try container.decode(Double.self, forKey: .bypass)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// PresetFilename.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Sanitises a user-supplied name so it is safe as a file-system component on HFS+ and APFS.
|
||||
///
|
||||
/// Shared by the preset stores (`BoardVersionStore`, `RigLibraryStore`) so every on-disk preset
|
||||
/// filename follows one scheme: `<sanitized-name>-<uuid>.json`.
|
||||
///
|
||||
/// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace with underscores.
|
||||
/// - Replaces a leading `.` (which would produce a hidden file or `.`/`..`) with an underscore.
|
||||
/// - Trims leading and trailing underscores that resulted from the substitutions (cosmetic).
|
||||
/// - Caps the UTF-8 byte length of the result at `maxLength` so the full filename
|
||||
/// (`<name>-<uuid>.json`, 54 extra bytes) stays within the 255-byte component limit.
|
||||
/// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely to
|
||||
/// separator characters after substitution.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The raw, user-supplied name.
|
||||
/// - maxLength: Maximum UTF-8 byte length of the sanitised prefix. Defaults to `200`.
|
||||
/// - Returns: A file-system-safe name, never empty.
|
||||
func sanitizePresetFilename(
|
||||
_ name: String,
|
||||
maxLength: Int = 200
|
||||
) -> String {
|
||||
let replacementCharacter: Character = "_"
|
||||
let forbiddenCharacters: Set<Character> = ["/", "\\", ":", "\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 maxLength UTF-8 bytes so the full filename stays within 255 bytes.
|
||||
if sanitized.utf8.count > maxLength {
|
||||
var truncated: String = ""
|
||||
var byteCount: Int = 0
|
||||
for scalar: Unicode.Scalar in sanitized.unicodeScalars {
|
||||
let encodedLength: Int = UTF8.width(scalar)
|
||||
guard byteCount + encodedLength <= maxLength else { break }
|
||||
truncated.unicodeScalars.append(scalar)
|
||||
byteCount += encodedLength
|
||||
}
|
||||
sanitized = truncated
|
||||
}
|
||||
|
||||
return sanitized.isEmpty ? "unnamed" : sanitized
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// RigArchive.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Format version written into every exported ``RigArchive``.
|
||||
///
|
||||
/// Increment when the archive schema changes in a way that requires migration on load.
|
||||
public let rigArchiveFormatVersion: Int = 1
|
||||
|
||||
/// A portable bundle of one or more ``RigEntry`` rigs in a single JSON document.
|
||||
///
|
||||
/// `RigArchive` is the hand-editable, shareable file format used by the library's
|
||||
/// **Export Archive** / **Import Archive** actions — the way to back up or move an entire
|
||||
/// collection of rigs as one file. It is the multi-rig successor to the old single-rig file
|
||||
/// save/load: a legacy single-rig file (a bare ``ShoeGazeState``) is still importable and is
|
||||
/// treated as a one-rig archive (see `RigLibraryStore.importArchive`).
|
||||
///
|
||||
/// The document is written pretty-printed with sorted keys, so it stays readable and editable by
|
||||
/// hand. `Date` values inside each ``RigEntry`` are encoded as `secondsSince1970`.
|
||||
public struct RigArchive: Codable, Equatable {
|
||||
|
||||
/// Archive format version. Written as `rigArchiveFormatVersion` at export time.
|
||||
public let version: Int
|
||||
|
||||
/// The rigs contained in this archive, in listing order.
|
||||
public let rigs: [RigEntry]
|
||||
|
||||
/// Creates a rig archive.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: Archive format version. Defaults to `rigArchiveFormatVersion`.
|
||||
/// - rigs: The rigs to bundle.
|
||||
public init(
|
||||
version: Int = rigArchiveFormatVersion,
|
||||
rigs: [RigEntry]
|
||||
) {
|
||||
self.version = version
|
||||
self.rigs = rigs
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// RigEntry.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A named, timestamped rig in the user's library.
|
||||
///
|
||||
/// `RigEntry` is the unit stored and retrieved by `RigLibraryStore`. Each entry pairs a complete
|
||||
/// ``ShoeGazeState`` snapshot (every board and its pedals) with a human-readable `name`
|
||||
/// (e.g. `"Ambient Wash"`) and a `savedAt` timestamp. It is the rig-level analogue of
|
||||
/// `BoardVersion`, which captures a single board.
|
||||
///
|
||||
/// `RigEntry` is `Codable` so it round-trips through the per-rig JSON files written by
|
||||
/// `RigLibraryStore` and through the bundled ``RigArchive`` export. It is `Identifiable`
|
||||
/// (via `UUID`) for direct use in SwiftUI `List` / `ForEach`, and `Equatable` for round-trip tests.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let entry = shoeGaze.captureEntry(name: "Ambient Wash")
|
||||
/// try store.save(entry)
|
||||
/// // later …
|
||||
/// try shoeGaze.loadRig(from: entry.state)
|
||||
/// ```
|
||||
public struct RigEntry: Codable, Identifiable, Equatable {
|
||||
|
||||
/// Stable unique identifier for this entry. Also seeds the on-disk filename.
|
||||
public let id: UUID
|
||||
|
||||
/// Human-readable name (e.g. `"Ambient Wash"`, `"Live Set A"`).
|
||||
public let name: String
|
||||
|
||||
/// Date and time at which this entry was last saved, at **whole-second precision**.
|
||||
///
|
||||
/// Rounded to the nearest second at init so it survives a JSON `secondsSince1970`
|
||||
/// round-trip exactly — otherwise the fractional `Double` text form loses precision and
|
||||
/// breaks `Equatable` after a `RigLibraryStore` write/load cycle.
|
||||
public let savedAt: Date
|
||||
|
||||
/// The full rig snapshot — every board, segment, and pedal parameter.
|
||||
public let state: ShoeGazeState
|
||||
|
||||
/// Creates a rig library entry.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - id: Stable unique identifier. Defaults to a newly generated `UUID()`.
|
||||
/// - name: Human-readable name for this rig.
|
||||
/// - savedAt: Save timestamp. Defaults to `Date()` (now). Rounded to the nearest
|
||||
/// whole second so persistence round-trips are lossless.
|
||||
/// - state: The ``ShoeGazeState`` rig snapshot to store.
|
||||
public init(
|
||||
id: UUID = UUID(),
|
||||
name: String,
|
||||
savedAt: Date = Date(),
|
||||
state: ShoeGazeState
|
||||
) {
|
||||
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
|
||||
}
|
||||
|
||||
/// Returns a copy of this entry with a new `name`, a fresh `id`, and `savedAt` updated to
|
||||
/// `date`. Used by the library's "duplicate" action so a copied rig becomes an independent
|
||||
/// entry rather than overwriting the original's file.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The new entry's name.
|
||||
/// - date: The new save timestamp. Defaults to `Date()` (now).
|
||||
/// - Returns: A new `RigEntry` carrying the same `state` under a new identity.
|
||||
public func duplicated(
|
||||
name: String,
|
||||
date: Date = Date()
|
||||
) -> RigEntry {
|
||||
RigEntry(id: UUID(), name: name, savedAt: date, state: state)
|
||||
}
|
||||
|
||||
/// Returns a copy of this entry with a new `name` and `savedAt` updated to `date`, keeping
|
||||
/// the same `id`. Used by the library's "rename" action so the entry's identity and file
|
||||
/// association are preserved.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The new name.
|
||||
/// - date: The new save timestamp. Defaults to `Date()` (now).
|
||||
/// - Returns: A new `RigEntry` with the same `id` and `state` under the new name.
|
||||
public func renamed(
|
||||
to name: String,
|
||||
date: Date = Date()
|
||||
) -> RigEntry {
|
||||
RigEntry(id: id, name: name, savedAt: date, state: state)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// RigLibraryLocation.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Resolves where the rig library lives on disk: the shared iCloud container when available,
|
||||
/// otherwise a local Application Support folder.
|
||||
///
|
||||
/// Both the macOS and iOS builder apps declare the **same** iCloud container
|
||||
/// (``containerIdentifier``) in their entitlements — even though their bundle identifiers differ —
|
||||
/// so a single rig library is shared across a user's devices and across both apps. When iCloud is
|
||||
/// unavailable (not signed in, entitlement missing, or running in a context without provisioning)
|
||||
/// the library falls back to a local folder and simply does not sync.
|
||||
public enum RigLibraryLocation {
|
||||
|
||||
/// The shared iCloud container identifier. Both builder targets must list this exact value in
|
||||
/// `com.apple.developer.icloud-container-identifiers` / `ubiquity-container-identifiers`, and
|
||||
/// the container must be enabled on both App IDs in the developer account.
|
||||
public static let containerIdentifier: String = "iCloud.net.realizedsound.ShoeGazeData"
|
||||
|
||||
/// Subfolder (inside the container's `Documents/` or inside Application Support) holding the
|
||||
/// per-rig JSON files.
|
||||
private static let rigsFolderName: String = "Rigs"
|
||||
|
||||
/// Local Application Support namespace, matching `BoardVersionStore.defaultDirectory()`.
|
||||
private static let localFolderName: String = "LyrebirdShoeGaze"
|
||||
|
||||
/// iCloud documents subfolder. Storing rigs under `Documents/` (rather than the container root)
|
||||
/// makes them eligible to appear in the Files app when `NSUbiquitousContainers` is configured.
|
||||
private static let documentsFolderName: String = "Documents"
|
||||
|
||||
/// A resolved library directory and whether it is backed by iCloud.
|
||||
public struct Resolved: Equatable {
|
||||
|
||||
/// The directory holding per-rig JSON files (created if needed).
|
||||
public let directory: URL
|
||||
|
||||
/// `true` when `directory` is inside the iCloud ubiquity container (sync active);
|
||||
/// `false` for the local Application Support fallback.
|
||||
public let isICloud: Bool
|
||||
}
|
||||
|
||||
/// Resolves the rig library directory, preferring iCloud.
|
||||
///
|
||||
/// - Important: When an iCloud account is signed in,
|
||||
/// `FileManager.url(forUbiquityContainerIdentifier:)` performs **blocking** I/O that can be
|
||||
/// slow on its first call. Prefer calling this **once at app startup, off the main thread**.
|
||||
/// When no iCloud account is present, the cheap `ubiquityIdentityToken` check short-circuits
|
||||
/// straight to the local fallback without the blocking call. The created directory is returned
|
||||
/// ready to use.
|
||||
///
|
||||
/// - Parameter containerIdentifier: The ubiquity container to use. Defaults to
|
||||
/// ``containerIdentifier``.
|
||||
/// - Returns: The resolved directory and whether iCloud backing is active.
|
||||
public static func resolve(
|
||||
containerIdentifier identifier: String = containerIdentifier
|
||||
) -> Resolved {
|
||||
let fileManager: FileManager = FileManager.default
|
||||
// No iCloud account signed in → skip the potentially-slow container lookup entirely.
|
||||
guard fileManager.ubiquityIdentityToken != nil else {
|
||||
return Resolved(directory: localDirectory(), isICloud: false)
|
||||
}
|
||||
if let container: URL = fileManager.url(forUbiquityContainerIdentifier: identifier) {
|
||||
let directory: URL = container
|
||||
.appendingPathComponent(documentsFolderName, isDirectory: true)
|
||||
.appendingPathComponent(rigsFolderName, isDirectory: true)
|
||||
try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
return Resolved(directory: directory, isICloud: true)
|
||||
}
|
||||
return Resolved(directory: localDirectory(), isICloud: false)
|
||||
}
|
||||
|
||||
/// The local (non-iCloud) rig library directory, created if needed.
|
||||
///
|
||||
/// Falls back to a folder in the system temporary directory if Application Support cannot be
|
||||
/// resolved. Used as the iCloud-unavailable fallback and directly by tests.
|
||||
///
|
||||
/// - Returns: A local `URL` for the rigs directory.
|
||||
public static func localDirectory() -> URL {
|
||||
let fileManager: FileManager = FileManager.default
|
||||
let base: URL = (try? fileManager.url(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: true
|
||||
)) ?? fileManager.temporaryDirectory
|
||||
let directory: URL = base
|
||||
.appendingPathComponent(localFolderName, isDirectory: true)
|
||||
.appendingPathComponent(rigsFolderName, isDirectory: true)
|
||||
try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
return directory
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
// RigLibraryStore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
/// The user's library of saved rigs, persisted as one JSON file per rig and (when available)
|
||||
/// synced across devices and apps through a shared iCloud container.
|
||||
///
|
||||
/// `RigLibraryStore` is `@Observable`, so SwiftUI views refresh automatically as `entries`
|
||||
/// changes — whether the change came from a local edit or from a remote iCloud update. All
|
||||
/// mutations run on the main actor.
|
||||
///
|
||||
/// ## Storage model
|
||||
///
|
||||
/// Each ``RigEntry`` is written as a separate pretty-printed JSON file named
|
||||
/// `<sanitized-name>-<id>.json` (see ``sanitizePresetFilename(_:maxLength:)``) inside the
|
||||
/// directory resolved by ``RigLibraryLocation``. One file per rig keeps iCloud merges
|
||||
/// conflict-free at rig granularity: editing rig A never rewrites rig B's file.
|
||||
///
|
||||
/// When the directory is an iCloud ubiquity container, reads and writes are wrapped in
|
||||
/// `NSFileCoordinator`, and an `NSMetadataQuery` watches for remote changes so a rig saved on one
|
||||
/// device appears on another without relaunching. Call ``start()`` once after construction to load
|
||||
/// the current contents and begin watching.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// // Off the main thread at launch (the ubiquity lookup blocks):
|
||||
/// let resolved = RigLibraryLocation.resolve()
|
||||
/// // Back on the main actor:
|
||||
/// let store = RigLibraryStore(resolved: resolved)
|
||||
/// store.start()
|
||||
/// // …
|
||||
/// try store.save(shoeGaze.captureEntry(name: "Ambient Wash"))
|
||||
/// ```
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class RigLibraryStore {
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// All known rigs, sorted by name (case-insensitive), then most-recently-saved first.
|
||||
public private(set) var entries: [RigEntry] = []
|
||||
|
||||
/// `true` when the library is backed by the iCloud container (changes sync); `false` for the
|
||||
/// local-only fallback. Resolved during ``start()`` for an auto-resolving store.
|
||||
public private(set) var isICloud: Bool
|
||||
|
||||
/// The directory holding the per-rig JSON files. May be repointed from local to iCloud during
|
||||
/// ``start()`` for an auto-resolving store (before any writes, so no migration is needed).
|
||||
public private(set) var directory: URL
|
||||
|
||||
/// `false` until the first load completes. Views can show a loading state and callers should
|
||||
/// wait for this (or `await start()`) before deciding whether the library is empty — otherwise a
|
||||
/// first-launch seed would race a not-yet-loaded iCloud library.
|
||||
public private(set) var isLoaded: Bool = false
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// Live query over the iCloud documents scope; `nil` when local-only or not yet started.
|
||||
@ObservationIgnored private var metadataQuery: NSMetadataQuery?
|
||||
|
||||
/// Retained NotificationCenter tokens for the metadata-query observers.
|
||||
@ObservationIgnored private var observerTokens: [NSObjectProtocol] = []
|
||||
|
||||
/// Serial queue for all disk writes/deletes. Mutations update the in-memory `entries` on the
|
||||
/// main actor immediately (so the UI never blocks on disk or iCloud coordination), then hand the
|
||||
/// file work here. Serial ordering keeps a rename's delete-then-write — and any save/delete on
|
||||
/// the same file — in submission order.
|
||||
@ObservationIgnored private let ioQueue: DispatchQueue =
|
||||
DispatchQueue(label: "net.realizedsound.shoegaze.riglibrary.io", qos: .utility)
|
||||
|
||||
/// File extension of a stored rig.
|
||||
private nonisolated static let fileExtension: String = "json"
|
||||
|
||||
/// When `true`, ``start()`` resolves the iCloud-or-local location off the main thread and
|
||||
/// repoints `directory`/`isICloud` before loading. `false` for the explicit test initializer.
|
||||
private let autoResolve: Bool
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a store rooted at an explicit directory. Used directly by tests with a temporary
|
||||
/// directory; `start()` will not re-resolve the location.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - directory: The directory holding per-rig JSON files. Created if it does not exist.
|
||||
/// - isICloud: Whether `directory` is an iCloud ubiquity container (enables coordination and
|
||||
/// remote-change watching).
|
||||
public init(
|
||||
directory: URL,
|
||||
isICloud: Bool
|
||||
) {
|
||||
self.directory = directory
|
||||
self.isICloud = isICloud
|
||||
self.autoResolve = false
|
||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
}
|
||||
|
||||
/// Creates an auto-resolving store. Constructed instantly with a local placeholder directory;
|
||||
/// ``start()`` resolves the real iCloud-or-local location off the main thread before loading.
|
||||
public init() {
|
||||
self.directory = RigLibraryLocation.localDirectory()
|
||||
self.isICloud = false
|
||||
self.autoResolve = true
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/// Resolves the location (off the main thread, for an auto-resolving store), loads the current
|
||||
/// library contents (off the main thread), and — when iCloud-backed — begins watching for
|
||||
/// remote changes. Awaitable so callers can seed/highlight only once the real library state is
|
||||
/// known. Safe to call once after construction.
|
||||
public func start() async {
|
||||
if autoResolve {
|
||||
let resolved: RigLibraryLocation.Resolved = await RigLibraryStore.resolveOffMain()
|
||||
directory = resolved.directory
|
||||
isICloud = resolved.isICloud
|
||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
}
|
||||
if isICloud {
|
||||
startMetadataQuery()
|
||||
}
|
||||
await reload()
|
||||
isLoaded = true
|
||||
}
|
||||
|
||||
/// Re-reads the library directory off the main thread and republishes `entries`. Ordered after
|
||||
/// any queued background writes (shares `ioQueue`), so a save followed by a reload never drops
|
||||
/// the just-saved rig.
|
||||
public func reload() async {
|
||||
let dir: URL = directory
|
||||
let coordinated: Bool = isICloud
|
||||
let loaded: [RigEntry] = await withCheckedContinuation { continuation in
|
||||
ioQueue.async {
|
||||
continuation.resume(returning: RigLibraryStore.loadEntries(in: dir, coordinated: coordinated))
|
||||
}
|
||||
}
|
||||
entries = RigLibraryStore.sorted(loaded)
|
||||
}
|
||||
|
||||
/// Resolves the iCloud-or-local location on a background queue so the blocking ubiquity lookup
|
||||
/// never runs on the main thread.
|
||||
private static func resolveOffMain() async -> RigLibraryLocation.Resolved {
|
||||
await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
continuation.resume(returning: RigLibraryLocation.resolve())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops watching for remote changes and removes observers. Call when tearing the store down;
|
||||
/// the store otherwise lives for the app's lifetime.
|
||||
public func stop() {
|
||||
metadataQuery?.stop()
|
||||
metadataQuery = nil
|
||||
for token: NSObjectProtocol in observerTokens {
|
||||
NotificationCenter.default.removeObserver(token)
|
||||
}
|
||||
observerTokens.removeAll()
|
||||
}
|
||||
|
||||
// MARK: - Mutations
|
||||
|
||||
/// Saves `entry`, writing its JSON file and updating `entries` in memory.
|
||||
///
|
||||
/// If an entry with the same `id` already exists, its file and in-memory record are replaced
|
||||
/// (the on-disk filename also updates if the name changed). Use this both to add a brand-new
|
||||
/// rig and to overwrite an existing one (`shoeGaze.captureEntry(name:id:)`).
|
||||
///
|
||||
/// - Parameter entry: The rig entry to persist.
|
||||
/// - Throws: `JSONEncoder` errors (encoding happens synchronously). The actual file write runs
|
||||
/// asynchronously on a background queue and only logs on failure — call
|
||||
/// ``flushPendingWrites()`` to wait for it (e.g. in tests or at app termination).
|
||||
public func save(_ entry: RigEntry) throws {
|
||||
// Encode synchronously (cheap, CPU) so an encoding failure is surfaced to the caller; then
|
||||
// update the in-memory list immediately and push the disk write to the background queue.
|
||||
let data: Data = try encode(entry)
|
||||
let target: URL = fileURL(for: entry)
|
||||
let directory: URL = self.directory
|
||||
let id: UUID = entry.id
|
||||
let coordinated: Bool = isICloud
|
||||
upsert(entry)
|
||||
ioQueue.async {
|
||||
// Remove any prior file for this id first (a rename changes the name-prefixed filename).
|
||||
if let stale: URL = RigLibraryStore.existingFileURL(for: id, in: directory),
|
||||
stale.standardizedFileURL != target.standardizedFileURL {
|
||||
try? RigLibraryStore.removeFile(at: stale, coordinated: coordinated)
|
||||
}
|
||||
do {
|
||||
try RigLibraryStore.writeData(data, to: target, coordinated: coordinated)
|
||||
} catch {
|
||||
print("[RigLibraryStore] save write failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes `entry` from memory immediately and removes its file on the background queue.
|
||||
///
|
||||
/// - Parameter entry: The rig entry to remove.
|
||||
/// - Throws: Never throws today; remains `throws` for API stability. File-removal errors are
|
||||
/// logged on the background queue.
|
||||
public func delete(_ entry: RigEntry) throws {
|
||||
entries.removeAll { $0.id == entry.id }
|
||||
let directory: URL = self.directory
|
||||
let id: UUID = entry.id
|
||||
let coordinated: Bool = isICloud
|
||||
ioQueue.async {
|
||||
if let url: URL = RigLibraryStore.existingFileURL(for: id, in: directory) {
|
||||
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
|
||||
catch { print("[RigLibraryStore] delete failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the library in memory immediately and removes every rig file on the background queue.
|
||||
///
|
||||
/// - Throws: Never throws today; remains `throws` for API stability. Per-file removal errors are
|
||||
/// logged on the background queue.
|
||||
public func eraseAll() throws {
|
||||
entries.removeAll()
|
||||
let directory: URL = self.directory
|
||||
let coordinated: Bool = isICloud
|
||||
ioQueue.async {
|
||||
for url: URL in RigLibraryStore.rigFileURLs(in: directory) {
|
||||
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
|
||||
catch { print("[RigLibraryStore] eraseAll: removing \(url.lastPathComponent) failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks until all queued background writes/deletes have completed.
|
||||
///
|
||||
/// Primarily for tests (assert on-disk state right after a mutation) and app termination (ensure
|
||||
/// the last save reaches disk before exit). Avoid calling on the main thread during normal use —
|
||||
/// that would reintroduce the very stall this design removes.
|
||||
public func flushPendingWrites() {
|
||||
ioQueue.sync { }
|
||||
}
|
||||
|
||||
/// Duplicates `entry` under `newName` as an independent entry with a fresh `id`, persists it,
|
||||
/// and returns it.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - entry: The rig to copy.
|
||||
/// - newName: The copy's name.
|
||||
/// - Returns: The newly created entry.
|
||||
/// - Throws: Any error from ``save(_:)``.
|
||||
@discardableResult
|
||||
public func duplicate(
|
||||
_ entry: RigEntry,
|
||||
newName: String
|
||||
) throws -> RigEntry {
|
||||
let copy: RigEntry = entry.duplicated(name: newName)
|
||||
try save(copy)
|
||||
return copy
|
||||
}
|
||||
|
||||
/// Renames `entry` to `newName`, keeping its `id`, and returns the updated entry.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - entry: The rig to rename.
|
||||
/// - newName: The new name.
|
||||
/// - Returns: The renamed entry.
|
||||
/// - Throws: Any error from ``save(_:)``.
|
||||
@discardableResult
|
||||
public func rename(
|
||||
_ entry: RigEntry,
|
||||
to newName: String
|
||||
) throws -> RigEntry {
|
||||
let renamed: RigEntry = entry.renamed(to: newName)
|
||||
try save(renamed)
|
||||
return renamed
|
||||
}
|
||||
|
||||
// MARK: - Archive import / export
|
||||
|
||||
/// Encodes the entire library as a single ``RigArchive`` JSON document.
|
||||
///
|
||||
/// Retained for callers and tests that want the bare archive bytes. The user-facing
|
||||
/// export/share path uses ``exportDocumentData()``, which wraps the same rigs in a
|
||||
/// ``ShoeGazeDocument`` envelope (the `.shoegaze` file type).
|
||||
///
|
||||
/// - Returns: Pretty-printed archive bytes.
|
||||
/// - Throws: `JSONEncoder` errors.
|
||||
public func exportArchiveData() throws -> Data {
|
||||
let archive: RigArchive = RigArchive(rigs: entries)
|
||||
return try RigLibraryStore.makeEncoder().encode(archive)
|
||||
}
|
||||
|
||||
/// Encodes the entire library as a ``ShoeGazeDocument`` for export to a `.shoegaze` file.
|
||||
///
|
||||
/// This is the format written by the library's **Export** action and shared via the system
|
||||
/// share sheet. ``importArchive(from:)`` reads it back, and also still accepts the bare
|
||||
/// ``RigArchive`` and legacy single-rig shapes.
|
||||
///
|
||||
/// - Returns: Pretty-printed `.shoegaze` document bytes.
|
||||
/// - Throws: `JSONEncoder` errors.
|
||||
public func exportDocumentData() throws -> Data {
|
||||
try ShoeGazeDocument(rigs: entries).data()
|
||||
}
|
||||
|
||||
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
|
||||
/// added.
|
||||
///
|
||||
/// Accepts a ``ShoeGazeDocument`` (the `.shoegaze` file type), a bare ``RigArchive`` (the prior
|
||||
/// multi-rig export), or a legacy single-rig file (a bare ``ShoeGazeState``), which is imported
|
||||
/// as one entry named `legacyRigName`. A document carrying a board rather than rigs contributes
|
||||
/// no entries. Imported entries whose `id` already exists in the library are given a fresh `id`
|
||||
/// so an import never silently overwrites an existing rig.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: Archive or legacy-rig JSON bytes.
|
||||
/// - legacyRigName: Name to use when importing a legacy single-rig file. Defaults to
|
||||
/// `"Imported Rig"`.
|
||||
/// - Returns: The number of rigs added to the library.
|
||||
/// - Throws: `JSONDecoder` errors when `data` is neither an archive nor a legacy rig, or any
|
||||
/// error from ``save(_:)``.
|
||||
@discardableResult
|
||||
public func importArchive(
|
||||
from data: Data,
|
||||
legacyRigName: String = "Imported Rig"
|
||||
) throws -> Int {
|
||||
let imported: [RigEntry] = try decodeImportable(data, legacyRigName: legacyRigName)
|
||||
let existingIDs: Set<UUID> = Set(entries.map(\.id))
|
||||
var added: Int = 0
|
||||
for entry: RigEntry in imported {
|
||||
// Avoid clobbering an existing rig that happens to share this id.
|
||||
let toSave: RigEntry = existingIDs.contains(entry.id)
|
||||
? entry.duplicated(name: entry.name, date: entry.savedAt)
|
||||
: entry
|
||||
try save(toSave)
|
||||
added += 1
|
||||
}
|
||||
return added
|
||||
}
|
||||
|
||||
// MARK: - Loading from disk
|
||||
|
||||
/// Rescans the directory and rebuilds `entries`. Files that cannot be read or decoded are
|
||||
/// skipped so one bad file never blocks the rest. Not-yet-downloaded iCloud placeholders (which
|
||||
/// are hidden `*.icloud` files) are naturally ignored and picked up on a later metadata update.
|
||||
private nonisolated static func loadEntries(in directory: URL, coordinated: Bool) -> [RigEntry] {
|
||||
var loaded: [RigEntry] = []
|
||||
let decoder: JSONDecoder = makeDecoder()
|
||||
for url: URL in rigFileURLs(in: directory) {
|
||||
guard let data: Data = try? readData(at: url, coordinated: coordinated) else { continue }
|
||||
guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue }
|
||||
loaded.append(entry)
|
||||
}
|
||||
return loaded
|
||||
}
|
||||
|
||||
// MARK: - iCloud metadata query
|
||||
|
||||
/// Starts the live query over the iCloud documents scope and wires update handlers.
|
||||
private func startMetadataQuery() {
|
||||
guard metadataQuery == nil else { return }
|
||||
let query: NSMetadataQuery = NSMetadataQuery()
|
||||
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
|
||||
query.predicate = NSPredicate(
|
||||
format: "%K LIKE %@",
|
||||
NSMetadataItemFSNameKey,
|
||||
"*.\(RigLibraryStore.fileExtension)"
|
||||
)
|
||||
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
let handler: @Sendable (Notification) -> Void = { [weak self] _ in
|
||||
// queue: .main delivers on the main thread; we are a main-actor type.
|
||||
MainActor.assumeIsolated { self?.handleMetadataUpdate() }
|
||||
}
|
||||
observerTokens.append(center.addObserver(
|
||||
forName: .NSMetadataQueryDidFinishGathering, object: query, queue: .main, using: handler
|
||||
))
|
||||
observerTokens.append(center.addObserver(
|
||||
forName: .NSMetadataQueryDidUpdate, object: query, queue: .main, using: handler
|
||||
))
|
||||
|
||||
metadataQuery = query
|
||||
query.start()
|
||||
}
|
||||
|
||||
/// Handles a metadata-query result: triggers downloads for any rig files not yet present
|
||||
/// locally, then rescans the directory for whatever is now readable.
|
||||
private func handleMetadataUpdate() {
|
||||
guard let query: NSMetadataQuery = metadataQuery else { return }
|
||||
query.disableUpdates()
|
||||
defer { query.enableUpdates() }
|
||||
|
||||
let fileManager: FileManager = FileManager.default
|
||||
for index: Int in 0..<query.resultCount {
|
||||
guard let item: NSMetadataItem = query.result(at: index) as? NSMetadataItem,
|
||||
let url: URL = item.value(forAttribute: NSMetadataItemURLKey) as? URL,
|
||||
RigLibraryStore.isInLibrary(url, directory: directory) else { continue }
|
||||
let status: String? =
|
||||
item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
|
||||
if status != NSMetadataUbiquitousItemDownloadingStatusCurrent {
|
||||
try? fileManager.startDownloadingUbiquitousItem(at: url)
|
||||
}
|
||||
}
|
||||
// Re-read off the main thread; the in-memory list republishes when it completes.
|
||||
Task { await self.reload() }
|
||||
}
|
||||
|
||||
// MARK: - File helpers
|
||||
|
||||
/// The write URL for `entry`: `<sanitized-name>-<id>.json` inside the library directory.
|
||||
private func fileURL(for entry: RigEntry) -> URL {
|
||||
let sanitized: String = sanitizePresetFilename(entry.name)
|
||||
let filename: String = "\(sanitized)-\(entry.id.uuidString).\(RigLibraryStore.fileExtension)"
|
||||
return directory.appendingPathComponent(filename)
|
||||
}
|
||||
|
||||
/// Finds the existing file for `id` by matching the `-<uuid>.json` suffix, so renames (which
|
||||
/// change the name prefix) are still located. `nil` if no file is present. `static` so the
|
||||
/// background I/O queue can call it without touching actor state.
|
||||
private nonisolated static func existingFileURL(for id: UUID, in directory: URL) -> URL? {
|
||||
let suffix: String = "-\(id.uuidString).\(fileExtension)"
|
||||
return rigFileURLs(in: directory).first { $0.lastPathComponent.hasSuffix(suffix) }
|
||||
}
|
||||
|
||||
/// All `*.json` files currently in `directory` (hidden iCloud placeholders excluded).
|
||||
private nonisolated static func rigFileURLs(in directory: URL) -> [URL] {
|
||||
let contents: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: nil,
|
||||
options: .skipsHiddenFiles
|
||||
)) ?? []
|
||||
return contents.filter { $0.pathExtension == fileExtension }
|
||||
}
|
||||
|
||||
/// Whether `url` is a rig file directly inside `directory`.
|
||||
private nonisolated static func isInLibrary(_ url: URL, directory: URL) -> Bool {
|
||||
url.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL
|
||||
&& url.pathExtension == fileExtension
|
||||
}
|
||||
|
||||
// MARK: - Coordinated I/O (background-queue safe)
|
||||
|
||||
/// Writes `data` to `url`, coordinating the write through `NSFileCoordinator` when iCloud-backed.
|
||||
private nonisolated static func writeData(_ data: Data, to url: URL, coordinated: Bool) throws {
|
||||
guard coordinated else {
|
||||
try data.write(to: url, options: .atomic)
|
||||
return
|
||||
}
|
||||
try coordinateWriting(url, options: .forReplacing) { target in
|
||||
try data.write(to: target, options: .atomic)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the contents of `url`, coordinating the read when iCloud-backed.
|
||||
private nonisolated static func readData(at url: URL, coordinated: Bool) throws -> Data {
|
||||
guard coordinated else {
|
||||
return try Data(contentsOf: url)
|
||||
}
|
||||
var result: Data = Data()
|
||||
try coordinateReading(url, options: .withoutChanges) { target in
|
||||
result = try Data(contentsOf: target)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Removes `url`, coordinating the delete when iCloud-backed.
|
||||
private nonisolated static func removeFile(at url: URL, coordinated: Bool) throws {
|
||||
guard coordinated else {
|
||||
try FileManager.default.removeItem(at: url)
|
||||
return
|
||||
}
|
||||
try coordinateWriting(url, options: .forDeleting) { target in
|
||||
try FileManager.default.removeItem(at: target)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `body` inside an `NSFileCoordinator` write block, surfacing both the coordinator's error
|
||||
/// and any error thrown by `body`.
|
||||
private nonisolated static func coordinateWriting(
|
||||
_ url: URL,
|
||||
options: NSFileCoordinator.WritingOptions,
|
||||
_ body: (URL) throws -> Void
|
||||
) throws {
|
||||
let coordinator: NSFileCoordinator = NSFileCoordinator()
|
||||
var coordinatorError: NSError?
|
||||
var thrown: Error?
|
||||
coordinator.coordinate(writingItemAt: url, options: options, error: &coordinatorError) { target in
|
||||
do { try body(target) } catch { thrown = error }
|
||||
}
|
||||
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
|
||||
if let thrown: Error = thrown { throw thrown }
|
||||
}
|
||||
|
||||
/// Runs `body` inside an `NSFileCoordinator` read block.
|
||||
private nonisolated static func coordinateReading(
|
||||
_ url: URL,
|
||||
options: NSFileCoordinator.ReadingOptions,
|
||||
_ body: (URL) throws -> Void
|
||||
) throws {
|
||||
let coordinator: NSFileCoordinator = NSFileCoordinator()
|
||||
var coordinatorError: NSError?
|
||||
var thrown: Error?
|
||||
coordinator.coordinate(readingItemAt: url, options: options, error: &coordinatorError) { target in
|
||||
do { try body(target) } catch { thrown = error }
|
||||
}
|
||||
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
|
||||
if let thrown: Error = thrown { throw thrown }
|
||||
}
|
||||
|
||||
// MARK: - Codec
|
||||
|
||||
/// Encodes a single entry as a per-rig file would store it.
|
||||
private func encode(_ entry: RigEntry) throws -> Data {
|
||||
try RigLibraryStore.makeEncoder().encode(entry)
|
||||
}
|
||||
|
||||
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
|
||||
private nonisolated static func makeEncoder() -> JSONEncoder {
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
return encoder
|
||||
}
|
||||
|
||||
/// A JSON decoder matching ``makeEncoder()``.
|
||||
private nonisolated static func makeDecoder() -> JSONDecoder {
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
return decoder
|
||||
}
|
||||
|
||||
/// Decodes import bytes into rig entries, accepting the `.shoegaze` ``ShoeGazeDocument``
|
||||
/// envelope plus the bare ``RigArchive`` and legacy ``ShoeGazeState`` shapes (see
|
||||
/// ``ShoeGazeDocument/decoded(from:legacyRigName:)``). A board-carrying document yields no rigs.
|
||||
private func decodeImportable(
|
||||
_ data: Data,
|
||||
legacyRigName: String
|
||||
) throws -> [RigEntry] {
|
||||
let document: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data, legacyRigName: legacyRigName)
|
||||
return document.rigEntries ?? []
|
||||
}
|
||||
|
||||
// MARK: - In-memory helpers
|
||||
|
||||
/// Inserts or replaces `entry` in `entries` by `id`, keeping the list sorted.
|
||||
private func upsert(_ entry: RigEntry) {
|
||||
var next: [RigEntry] = entries.filter { $0.id != entry.id }
|
||||
next.append(entry)
|
||||
entries = RigLibraryStore.sorted(next)
|
||||
}
|
||||
|
||||
/// Sorts entries by name (case-insensitive), then most-recently-saved first, then id for a
|
||||
/// fully deterministic order.
|
||||
private static func sorted(_ entries: [RigEntry]) -> [RigEntry] {
|
||||
entries.sorted { lhs, rhs in
|
||||
let byName: ComparisonResult = lhs.name.localizedCaseInsensitiveCompare(rhs.name)
|
||||
if byName != .orderedSame { return byName == .orderedAscending }
|
||||
if lhs.savedAt != rhs.savedAt { return lhs.savedAt > rhs.savedAt }
|
||||
return lhs.id.uuidString < rhs.id.uuidString
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,6 +117,83 @@ extension ShoeGaze {
|
||||
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments))
|
||||
}
|
||||
|
||||
/// Moves a pedal from one lane to another (e.g. the main chain into a stereo-unzip lane, or
|
||||
/// between branches), preserving its parameter values. The moved pedal is appended to the end
|
||||
/// of the destination lane.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sourceLane: The lane the pedal currently lives in.
|
||||
/// - sourceIndex: The pedal's index within `sourceLane`.
|
||||
/// - destinationLane: The lane to move the pedal into.
|
||||
/// - board: The board to edit.
|
||||
/// - Returns: The rebuilt board occupying the same slot in `boards`.
|
||||
/// - Throws: `ShoeGazeError.pedalIndexOutOfRange`, `.notABranchRegion`, or any rebuild error.
|
||||
@discardableResult
|
||||
public func movePedal(
|
||||
from sourceLane: PedalLane,
|
||||
at sourceIndex: Int,
|
||||
to destinationLane: PedalLane,
|
||||
in board: PedalBoard
|
||||
) throws -> PedalBoard {
|
||||
var segments: [BoardSegmentState] = board.captureState().segments
|
||||
|
||||
// 1. Remove the pedal from its source lane, capturing its full state. Removing a main
|
||||
// pedal deletes a top-level segment; record where so the destination region index can
|
||||
// be corrected if it sat after the removal.
|
||||
let moved: PedalState
|
||||
var removedTopLevelIndex: Int?
|
||||
switch sourceLane {
|
||||
case .main:
|
||||
let positions: [Int] = linearPedalSegmentIndices(segments)
|
||||
guard sourceIndex >= 0, sourceIndex < positions.count else {
|
||||
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: positions.count)
|
||||
}
|
||||
let absolute: Int = positions[sourceIndex]
|
||||
guard case .pedal(let state) = segments[absolute] else {
|
||||
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: positions.count)
|
||||
}
|
||||
moved = state
|
||||
segments.remove(at: absolute)
|
||||
removedTopLevelIndex = absolute
|
||||
case .left, .right:
|
||||
var captured: PedalState?
|
||||
try mutateBranch(&segments, lane: sourceLane) { branch in
|
||||
guard sourceIndex >= 0, sourceIndex < branch.count else {
|
||||
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: branch.count)
|
||||
}
|
||||
captured = branch.remove(at: sourceIndex)
|
||||
}
|
||||
guard let capturedState: PedalState = captured else {
|
||||
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: 0)
|
||||
}
|
||||
moved = capturedState
|
||||
}
|
||||
|
||||
// 2. Correct the destination region index if a top-level segment before it was removed.
|
||||
var destination: PedalLane = destinationLane
|
||||
if let region: Int = destinationLane.regionIndex,
|
||||
let removed: Int = removedTopLevelIndex, removed < region {
|
||||
destination = destinationLane.isLeftBranch ? .left(region: region - 1) : .right(region: region - 1)
|
||||
}
|
||||
|
||||
// 3. Append the moved pedal to the destination lane.
|
||||
switch destination {
|
||||
case .main:
|
||||
let positions: [Int] = linearPedalSegmentIndices(segments)
|
||||
if let lastPedal: Int = positions.last {
|
||||
segments.insert(.pedal(moved), at: lastPedal + 1)
|
||||
} else {
|
||||
segments.append(.pedal(moved))
|
||||
}
|
||||
case .left, .right:
|
||||
try mutateBranch(&segments, lane: destination) { branch in
|
||||
branch.append(moved)
|
||||
}
|
||||
}
|
||||
|
||||
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments))
|
||||
}
|
||||
|
||||
// MARK: - Branch regions
|
||||
|
||||
/// Appends an empty stereo split region (two independently authored L/R lanes) to the board.
|
||||
|
||||
@@ -21,6 +21,23 @@ extension ShoeGaze {
|
||||
return ShoeGazeState(boards: boardStates)
|
||||
}
|
||||
|
||||
/// Captures the current rig as a named ``RigEntry`` suitable for the rig library.
|
||||
///
|
||||
/// Wraps ``captureState()`` with a name, a fresh `id`, and a `savedAt` timestamp. The engine
|
||||
/// graph is not modified; this is a read-only operation.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: Human-readable name for the entry (e.g. `"Ambient Wash"`).
|
||||
/// - id: Stable identifier. Defaults to a newly generated `UUID()`; pass an existing entry's
|
||||
/// `id` to overwrite that entry in place.
|
||||
/// - Returns: A ``RigEntry`` reflecting the current rig.
|
||||
public func captureEntry(
|
||||
name: String,
|
||||
id: UUID = UUID()
|
||||
) -> RigEntry {
|
||||
RigEntry(id: id, name: name, state: captureState())
|
||||
}
|
||||
|
||||
// MARK: - Save / Load
|
||||
|
||||
/// Saves the current rig to a JSON file at `url`.
|
||||
@@ -58,6 +75,20 @@ extension ShoeGaze {
|
||||
public func loadRig(from data: Data) throws {
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
|
||||
try loadRig(from: state)
|
||||
}
|
||||
|
||||
/// Rebuilds the engine graph from an already-decoded ``ShoeGazeState``.
|
||||
///
|
||||
/// Shared core of the `Data` / `URL` loaders, and the entry point the rig library uses to
|
||||
/// recall a stored ``RigEntry`` (`loadRig(from: entry.state)`) without re-encoding. Rejects a
|
||||
/// snapshot whose `version` exceeds `presetFormatVersion`, tears down the current rig, then
|
||||
/// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``.
|
||||
///
|
||||
/// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``.
|
||||
/// - Parameter state: The rig snapshot to restore.
|
||||
/// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error.
|
||||
public func loadRig(from state: ShoeGazeState) throws {
|
||||
guard state.version <= presetFormatVersion else {
|
||||
throw PresetError.unsupportedVersion(state.version)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// ShoeGazeDocument.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Format version written into every `.shoegaze` document.
|
||||
///
|
||||
/// Increment when the `ShoeGazeDocument` envelope schema changes in a way that requires
|
||||
/// migration on load. The payload types (``RigArchive`` / ``BoardVersion``) carry their own
|
||||
/// independent version fields.
|
||||
public let shoeGazeDocumentFormatVersion: Int = 1
|
||||
|
||||
/// The portable `.shoegaze` document — the single file type ShoeGaze writes when a user shares
|
||||
/// or exports their work, and reads when opening a shared file.
|
||||
///
|
||||
/// A document is a small versioned envelope around one of two payloads:
|
||||
///
|
||||
/// - ``Payload/rigs(_:)`` — one or more rigs, carried as a ``RigArchive`` (a single shared rig is
|
||||
/// a one-rig archive; the whole-library export is a many-rig archive).
|
||||
/// - ``Payload/board(_:)`` — a single named board snapshot (``BoardVersion``).
|
||||
///
|
||||
/// Files are written pretty-printed with sorted keys and `secondsSince1970` dates, so they stay
|
||||
/// hand-readable and round-trip losslessly.
|
||||
///
|
||||
/// ## Backward compatibility
|
||||
///
|
||||
/// ``decoded(from:)`` accepts three on-disk shapes so older files keep opening:
|
||||
/// 1. A `ShoeGazeDocument` envelope (the current format).
|
||||
/// 2. A bare ``RigArchive`` (the previous multi-rig export).
|
||||
/// 3. A bare ``ShoeGazeState`` (the original single-rig save).
|
||||
///
|
||||
/// Shapes 2 and 3 are normalised into a ``Payload/rigs(_:)`` document on load.
|
||||
public struct ShoeGazeDocument: Codable, Equatable {
|
||||
|
||||
/// The two things a `.shoegaze` file can carry.
|
||||
public enum Payload: Equatable {
|
||||
|
||||
/// One or more rigs, as a portable archive.
|
||||
case rigs(RigArchive)
|
||||
|
||||
/// A single named board snapshot.
|
||||
case board(BoardVersion)
|
||||
}
|
||||
|
||||
/// Filename extension and the basis for the document's UTType (`net.realizedsound.shoegaze`).
|
||||
public static let fileExtension: String = "shoegaze"
|
||||
|
||||
/// Document envelope version. Written as `shoeGazeDocumentFormatVersion` at save time.
|
||||
public let version: Int
|
||||
|
||||
/// What this document carries.
|
||||
public let payload: Payload
|
||||
|
||||
/// Creates a document with an explicit payload.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: Envelope version. Defaults to `shoeGazeDocumentFormatVersion`.
|
||||
/// - payload: The rigs or board this document carries.
|
||||
public init(
|
||||
version: Int = shoeGazeDocumentFormatVersion,
|
||||
payload: Payload
|
||||
) {
|
||||
self.version = version
|
||||
self.payload = payload
|
||||
}
|
||||
|
||||
// MARK: - Convenience constructors
|
||||
|
||||
/// Creates a single-rig document by wrapping one ``RigEntry`` in a one-rig ``RigArchive``.
|
||||
///
|
||||
/// - Parameter entry: The rig to share.
|
||||
public init(rig entry: RigEntry) {
|
||||
self.init(payload: .rigs(RigArchive(rigs: [entry])))
|
||||
}
|
||||
|
||||
/// Creates a multi-rig document from a list of entries.
|
||||
///
|
||||
/// - Parameter entries: The rigs to bundle, in listing order.
|
||||
public init(rigs entries: [RigEntry]) {
|
||||
self.init(payload: .rigs(RigArchive(rigs: entries)))
|
||||
}
|
||||
|
||||
/// Creates a single-board document.
|
||||
///
|
||||
/// - Parameter version: The board snapshot to share.
|
||||
public init(board version: BoardVersion) {
|
||||
self.init(payload: .board(version))
|
||||
}
|
||||
|
||||
// MARK: - Payload accessors
|
||||
|
||||
/// The rigs this document carries, or `nil` when it carries a board.
|
||||
public var rigEntries: [RigEntry]? {
|
||||
if case .rigs(let archive) = payload { return archive.rigs }
|
||||
return nil
|
||||
}
|
||||
|
||||
/// The board this document carries, or `nil` when it carries rigs.
|
||||
public var boardVersion: BoardVersion? {
|
||||
if case .board(let version) = payload { return version }
|
||||
return nil
|
||||
}
|
||||
|
||||
// MARK: - Encoding
|
||||
|
||||
/// Encodes this document to pretty-printed, hand-editable `.shoegaze` JSON.
|
||||
///
|
||||
/// - Returns: The encoded document bytes.
|
||||
/// - Throws: Any error from `JSONEncoder`.
|
||||
public func data() throws -> Data {
|
||||
try ShoeGazeDocument.makeEncoder().encode(self)
|
||||
}
|
||||
|
||||
/// Decodes a `.shoegaze` document, tolerating the two legacy on-disk shapes.
|
||||
///
|
||||
/// Tries the `ShoeGazeDocument` envelope first, then a bare ``RigArchive``, then a bare
|
||||
/// ``ShoeGazeState`` — normalising the latter two into a rigs document. A bare state with no
|
||||
/// name becomes a one-rig archive named `legacyRigName`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: The document bytes.
|
||||
/// - legacyRigName: Name applied when normalising a bare ``ShoeGazeState``. Defaults to
|
||||
/// `"Imported Rig"`.
|
||||
/// - Returns: A normalised document.
|
||||
/// - Throws: `JSONDecoder` errors when `data` matches none of the three shapes.
|
||||
public static func decoded(
|
||||
from data: Data,
|
||||
legacyRigName: String = "Imported Rig"
|
||||
) throws -> ShoeGazeDocument {
|
||||
let decoder: JSONDecoder = makeDecoder()
|
||||
if let document: ShoeGazeDocument = try? decoder.decode(ShoeGazeDocument.self, from: data) {
|
||||
return document
|
||||
}
|
||||
if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) {
|
||||
return ShoeGazeDocument(payload: .rigs(archive))
|
||||
}
|
||||
// Original single-rig save: a bare ShoeGazeState. Let a genuine decode failure surface here.
|
||||
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
|
||||
return ShoeGazeDocument(rig: RigEntry(name: legacyRigName, state: state))
|
||||
}
|
||||
|
||||
/// A JSON encoder configured for human-readable, round-trip-stable document files.
|
||||
static func makeEncoder() -> JSONEncoder {
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
return encoder
|
||||
}
|
||||
|
||||
/// A JSON decoder matching ``makeEncoder()``.
|
||||
static func makeDecoder() -> JSONDecoder {
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
return decoder
|
||||
}
|
||||
|
||||
// MARK: - Codable
|
||||
|
||||
/// Discriminator written into the JSON so a payload reads back unambiguously.
|
||||
private enum Kind: String, Codable {
|
||||
case rigs
|
||||
case board
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case version
|
||||
case kind
|
||||
case rigs
|
||||
case board
|
||||
}
|
||||
|
||||
/// Encodes the envelope with an explicit `kind` discriminator and the matching payload key.
|
||||
public func encode(to encoder: any Encoder) throws {
|
||||
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(version, forKey: .version)
|
||||
switch payload {
|
||||
case .rigs(let archive):
|
||||
try container.encode(Kind.rigs, forKey: .kind)
|
||||
try container.encode(archive, forKey: .rigs)
|
||||
case .board(let boardVersion):
|
||||
try container.encode(Kind.board, forKey: .kind)
|
||||
try container.encode(boardVersion, forKey: .board)
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes the envelope, reading the payload named by the `kind` discriminator.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.version = try container.decode(Int.self, forKey: .version)
|
||||
let kind: Kind = try container.decode(Kind.self, forKey: .kind)
|
||||
switch kind {
|
||||
case .rigs:
|
||||
self.payload = .rigs(try container.decode(RigArchive.self, forKey: .rigs))
|
||||
case .board:
|
||||
self.payload = .board(try container.decode(BoardVersion.self, forKey: .board))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -218,6 +218,16 @@ public struct BoardEditorView: View {
|
||||
Button("Load") {
|
||||
loadVersion(version)
|
||||
}
|
||||
// Encoding a fully-concrete BoardVersion to JSON does not fail in practice; on the
|
||||
// unreachable failure path the Share item is simply omitted.
|
||||
if let shareItem: BoardShareItem = try? BoardShareItem(board: version) {
|
||||
ShareLink(
|
||||
item: shareItem,
|
||||
preview: SharePreview(version.name)
|
||||
) {
|
||||
Label("Share…", systemImage: "square.and.arrow.up")
|
||||
}
|
||||
}
|
||||
Button("Delete", role: .destructive) {
|
||||
versionStore.remove(version)
|
||||
try? versionStore.deleteFromDisk(version, in: BoardVersionStore.defaultDirectory())
|
||||
|
||||
@@ -325,6 +325,10 @@ public struct BoardFlowView: View {
|
||||
}
|
||||
}
|
||||
.frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading)
|
||||
// Make the whole lane frame hit-testable: an empty lane is mostly transparent, so without
|
||||
// this the drop target has almost no area and releases land on nothing (the bug where
|
||||
// dropping into an empty Stereo Unzip / Split / Parallel lane did nothing).
|
||||
.contentShape(Rectangle())
|
||||
.overlay { dropOutline(active: dropTarget == laneID) }
|
||||
.dropDestination(for: String.self) { items, _ in
|
||||
handleLaneDrop(items, lane: lane)
|
||||
@@ -396,16 +400,19 @@ public struct BoardFlowView: View {
|
||||
reorderMain(from: src, onto: ontoLinear)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
// A branch pedal dragged back onto the main chain → cross-lane move.
|
||||
return moveAcross(payload, toLane: .main)
|
||||
}
|
||||
|
||||
private func handleLaneDrop(_ items: [String], lane: PedalLane) -> Bool {
|
||||
dropTarget = nil
|
||||
guard let payload: String = parse(items), let type: String = payload.afterPrefix("add:") else {
|
||||
return false
|
||||
guard let payload: String = parse(items) else { return false }
|
||||
if let type: String = payload.afterPrefix("add:") {
|
||||
append(type: type, lane: lane)
|
||||
return true
|
||||
}
|
||||
append(type: type, lane: lane)
|
||||
return true
|
||||
// A pedal from the main chain or another lane dragged into this lane → cross-lane move.
|
||||
return moveAcross(payload, toLane: lane)
|
||||
}
|
||||
|
||||
private func handleBranchCardDrop(_ items: [String], lane: PedalLane, ontoIndex: Int) -> Bool {
|
||||
@@ -422,7 +429,7 @@ public struct BoardFlowView: View {
|
||||
append(type: type, lane: lane)
|
||||
return true
|
||||
}
|
||||
// Reorder within the same lane only: "movebranch:<region>:<side>:<index>".
|
||||
// Reorder within the same lane: "movebranch:<region>:<side>:<index>".
|
||||
let parts: [Substring] = payload.split(separator: ":")
|
||||
if parts.count == 4, parts[0] == "movebranch",
|
||||
Int(parts[1]) == lane.regionIndex,
|
||||
@@ -431,7 +438,35 @@ public struct BoardFlowView: View {
|
||||
reorderBranch(from: src, onto: ontoIndex, lane: lane)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
// A pedal from the main chain or a different lane dropped onto a card here → cross-lane move.
|
||||
return moveAcross(payload, toLane: lane)
|
||||
}
|
||||
|
||||
/// Moves a pedal addressed by a `movemain:`/`movebranch:` payload into `destination`,
|
||||
/// preserving its parameters. Returns `false` if the payload isn't a recognised move.
|
||||
private func moveAcross(_ payload: String, toLane destination: PedalLane) -> Bool {
|
||||
guard let board: PedalBoard = board else { return false }
|
||||
let sourceLane: PedalLane
|
||||
let sourceIndex: Int
|
||||
if let mainIndex: Int = payload.afterPrefix("movemain:").flatMap(Int.init) {
|
||||
sourceLane = .main
|
||||
sourceIndex = mainIndex
|
||||
} else {
|
||||
let parts: [Substring] = payload.split(separator: ":")
|
||||
guard parts.count == 4, parts[0] == "movebranch",
|
||||
let region: Int = Int(parts[1]), let index: Int = Int(parts[3]) else {
|
||||
return false
|
||||
}
|
||||
sourceLane = (parts[2] == "L") ? .left(region: region) : .right(region: region)
|
||||
sourceIndex = index
|
||||
}
|
||||
do {
|
||||
_ = try shoeGaze.movePedal(from: sourceLane, at: sourceIndex, to: destination, in: board)
|
||||
return true
|
||||
} catch {
|
||||
print("[BoardFlowView] cross-lane move failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Edit actions
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// BoardShareItem.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import CoreTransferable
|
||||
import UniformTypeIdentifiers
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// A `Transferable` wrapper that lets a `ShareLink` send a single board as a `.shoegaze` document.
|
||||
///
|
||||
/// Mirrors ``RigShareItem`` for a board snapshot: it holds the already-encoded document bytes and,
|
||||
/// via `FileRepresentation`, writes them to a temporary `<board>.shoegaze` file when a share
|
||||
/// destination is picked — giving the share sheet a real file so AirDrop, Messages, Mail, Notes,
|
||||
/// and Files all appear (raw data collapses the macOS menu to Copy / Edit Extensions).
|
||||
struct BoardShareItem: Transferable, Sendable {
|
||||
|
||||
/// Filesystem-safe base name for the shared file (no extension).
|
||||
let filenameBase: String
|
||||
|
||||
/// Encoded `.shoegaze` document bytes.
|
||||
let data: Data
|
||||
|
||||
/// Encodes `version` as a single-board `.shoegaze` document.
|
||||
///
|
||||
/// - Parameter version: The board snapshot to share.
|
||||
/// - Throws: Any `JSONEncoder` error from ``ShoeGazeDocument/data()``.
|
||||
init(board version: BoardVersion) throws {
|
||||
self.filenameBase = shareFilenameBase(version.name)
|
||||
self.data = try ShoeGazeDocument(board: version).data()
|
||||
}
|
||||
|
||||
static var transferRepresentation: some TransferRepresentation {
|
||||
FileRepresentation(exportedContentType: .shoeGaze) { item in
|
||||
SentTransferredFile(try writeShoeGazeShareFile(item.data, base: item.filenameBase))
|
||||
}
|
||||
.suggestedFileName { item in
|
||||
"\(item.filenameBase).\(ShoeGazeDocument.fileExtension)"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -123,6 +123,32 @@ public struct EngineConfigView: View {
|
||||
pendingInputs = shoeGaze.engine.numInputChannels
|
||||
pendingOutputs = shoeGaze.engine.numOutputChannels
|
||||
}
|
||||
// Apply config edits to the (stopped) engine immediately so dependent UI — notably the
|
||||
// input-source picker, which lists `0..<engine.numInputChannels` — reflects the new channel
|
||||
// counts before Start. While running, the controls are disabled, so these never fire then.
|
||||
.onChange(of: pendingInputs) { applyConfigWhileStopped() }
|
||||
.onChange(of: pendingOutputs) { applyConfigWhileStopped() }
|
||||
.onChange(of: pendingSampleRate) { applyConfigWhileStopped() }
|
||||
}
|
||||
|
||||
/// Reconfigures the stopped engine with the pending values and notifies the host so views that
|
||||
/// read non-observable engine state refresh. No-op while the engine is running.
|
||||
private func applyConfigWhileStopped() {
|
||||
guard !shoeGaze.engine.isRunning else { return }
|
||||
do {
|
||||
if let applyConfig: (Double, Int, Int) throws -> Void = applyConfig {
|
||||
try applyConfig(pendingSampleRate, pendingInputs, pendingOutputs)
|
||||
} else {
|
||||
try shoeGaze.reconfigureEngine(
|
||||
sampleRate: pendingSampleRate,
|
||||
inputChannels: pendingInputs,
|
||||
outputChannels: pendingOutputs
|
||||
)
|
||||
}
|
||||
onConfigApplied()
|
||||
} catch {
|
||||
print("[EngineConfigView] live reconfigure failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
private func label(_ text: String) -> some View {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// PedalCategory.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// A presentation grouping for pedals in the palette — used to colour-code the picker cards and to
|
||||
/// drive the "filter by type" menu. Purely a UI concern: the mapping from a pedal's `displayName`
|
||||
/// to its category lives here, keyed by name like ``PedalPaletteView``'s preferred order.
|
||||
enum PedalCategory: String, CaseIterable, Identifiable {
|
||||
case gain = "Gain"
|
||||
case dynamics = "Dynamics"
|
||||
case filter = "EQ & Filter"
|
||||
case modulation = "Modulation"
|
||||
case pitch = "Pitch"
|
||||
case delay = "Delay"
|
||||
case reverb = "Reverb"
|
||||
case texture = "Texture"
|
||||
|
||||
var id: String { rawValue }
|
||||
|
||||
/// Accent colour used to tint the palette card and the filter chip.
|
||||
var color: Color {
|
||||
switch self {
|
||||
case .gain: return Color(red: 0.82, green: 0.38, blue: 0.12)
|
||||
case .dynamics: return Color(red: 0.20, green: 0.50, blue: 0.32)
|
||||
case .filter: return Color(red: 0.14, green: 0.46, blue: 0.55)
|
||||
case .modulation: return Color(red: 0.40, green: 0.34, blue: 0.74)
|
||||
case .pitch: return Color(red: 0.60, green: 0.26, blue: 0.50)
|
||||
case .delay: return Color(red: 0.10, green: 0.52, blue: 0.62)
|
||||
case .reverb: return Color(red: 0.34, green: 0.22, blue: 0.66)
|
||||
case .texture: return Color(red: 0.48, green: 0.42, blue: 0.30)
|
||||
}
|
||||
}
|
||||
|
||||
/// The category for a pedal `displayName`. Unknown (e.g. third-party) names fall back to
|
||||
/// ``texture`` so they remain visible and tinted.
|
||||
static func category(for displayName: String) -> PedalCategory {
|
||||
mapping[displayName] ?? .texture
|
||||
}
|
||||
|
||||
private static let mapping: [String: PedalCategory] = [
|
||||
"Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain,
|
||||
"Compressor": .dynamics, "Sustainer": .dynamics, "Limiter": .dynamics, "Noise Gate": .dynamics,
|
||||
"Graphic EQ": .filter, "Auto-Wah": .filter, "Mutant": .filter,
|
||||
"Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation,
|
||||
"Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation,
|
||||
"Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch,
|
||||
"Delay": .delay, "Feedback Delay": .delay, "Multi-Tap Delay": .delay, "Ping-Pong": .delay,
|
||||
"Reverse Delay": .delay,
|
||||
"Reverb": .reverb, "Shimmer Reverb": .reverb,
|
||||
"Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture,
|
||||
]
|
||||
}
|
||||
@@ -38,6 +38,9 @@ public struct PedalPaletteView: View {
|
||||
private static let cardBorderWidth: CGFloat = 1
|
||||
private static let pedalCardBrightness: Double = 0.18
|
||||
private static let routingCardBrightness: Double = 0.1
|
||||
/// Category-colour fill / border opacity for the colour-coded pedal cards.
|
||||
private static let categoryFillOpacity: Double = 0.22
|
||||
private static let categoryBorderOpacity: Double = 0.65
|
||||
private static let routingCaptionOpacity: Double = 0.5
|
||||
private static let routingCaptionFontSize: CGFloat = 10
|
||||
private static let addGlyphOpacity: Double = 0.4
|
||||
@@ -45,14 +48,18 @@ public struct PedalPaletteView: View {
|
||||
private static let rowSubtitleSpacing: CGFloat = 2
|
||||
/// Opacity of the pedal-row description subtitle.
|
||||
private static let summaryOpacity: Double = 0.55
|
||||
/// Fixed card width when laid out horizontally (the vertical layout stretches to fill instead).
|
||||
private static let horizontalCardWidth: CGFloat = 150
|
||||
|
||||
/// Preferred display order for the built-in pedals. Any registered pedal not listed here is
|
||||
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
|
||||
private static let preferredOrder: [String] = [
|
||||
"Overdrive", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
|
||||
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus",
|
||||
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter",
|
||||
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb",
|
||||
"Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
|
||||
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
|
||||
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator",
|
||||
"Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer",
|
||||
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
|
||||
"Shimmer Reverb",
|
||||
]
|
||||
|
||||
/// Routing/branching topologies the user can insert into the board.
|
||||
@@ -74,19 +81,28 @@ public struct PedalPaletteView: View {
|
||||
|
||||
private let onAdd: (String) -> Void
|
||||
private let onRouting: (RoutingAction) -> Void
|
||||
private let axis: Axis
|
||||
|
||||
/// Active type filter; `nil` shows all pedals.
|
||||
@State private var filter: PedalCategory?
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a pedal palette.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - axis: `.vertical` (default) lays the catalog out as a full-width column for a sidebar;
|
||||
/// `.horizontal` lays it out as a fixed-width-card row for a horizontal scroller. The host
|
||||
/// wraps the view in a `ScrollView` of the matching axis.
|
||||
/// - onAdd: Invoked with a pedal's `displayName` when its row is tapped (append to main chain).
|
||||
/// Rows are also `.draggable` carrying `"add:<displayName>"` for drop-onto-lane targeting.
|
||||
/// - onRouting: Invoked when a routing row is tapped. Defaults to a no-op.
|
||||
public init(
|
||||
axis: Axis = .vertical,
|
||||
onAdd: @escaping (String) -> Void,
|
||||
onRouting: @escaping (RoutingAction) -> Void = { _ in }
|
||||
) {
|
||||
self.axis = axis
|
||||
self.onAdd = onAdd
|
||||
self.onRouting = onRouting
|
||||
}
|
||||
@@ -101,13 +117,31 @@ public struct PedalPaletteView: View {
|
||||
return ordered + extras
|
||||
}
|
||||
|
||||
/// Pedal names after applying the active type filter.
|
||||
private var visiblePedalNames: [String] {
|
||||
guard let filter: PedalCategory = filter else { return orderedPedalNames }
|
||||
return orderedPedalNames.filter { PedalCategory.category(for: $0) == filter }
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
switch axis {
|
||||
case .horizontal: horizontalBody
|
||||
default: verticalBody
|
||||
}
|
||||
}
|
||||
|
||||
/// Full-width column for a left sidebar.
|
||||
private var verticalBody: some View {
|
||||
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
|
||||
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
|
||||
sectionTitle("PEDALS")
|
||||
ForEach(orderedPedalNames, id: \.self) { name in
|
||||
HStack {
|
||||
sectionTitle("PEDALS")
|
||||
Spacer(minLength: 0)
|
||||
filterMenu
|
||||
}
|
||||
ForEach(visiblePedalNames, id: \.self) { name in
|
||||
pedalRow(name)
|
||||
}
|
||||
}
|
||||
@@ -121,6 +155,28 @@ public struct PedalPaletteView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Horizontal scroller: a PEDALS row (leading filter + colour-coded cards) with the ROUTING
|
||||
/// row stacked beneath it.
|
||||
private var horizontalBody: some View {
|
||||
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
|
||||
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
|
||||
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
|
||||
sectionTitle("PEDALS")
|
||||
filterMenu
|
||||
}
|
||||
ForEach(visiblePedalNames, id: \.self) { name in
|
||||
pedalRow(name)
|
||||
}
|
||||
}
|
||||
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
|
||||
sectionTitle("ROUTING")
|
||||
ForEach(PedalPaletteView.routingOptions, id: \.title) { option in
|
||||
routingCard(title: option.title, caption: option.caption, action: option.action)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
private func sectionTitle(_ text: String) -> some View {
|
||||
@@ -129,6 +185,26 @@ public struct PedalPaletteView: View {
|
||||
.foregroundStyle(Color.white.opacity(PedalPaletteView.titleOpacity))
|
||||
}
|
||||
|
||||
/// "Filter by type" menu — defaults to **All** (no filtering).
|
||||
private var filterMenu: some View {
|
||||
Menu {
|
||||
Button("All Types") { filter = nil }
|
||||
Divider()
|
||||
ForEach(PedalCategory.allCases) { category in
|
||||
Button(category.rawValue) { filter = category }
|
||||
}
|
||||
} label: {
|
||||
HStack(spacing: 3) {
|
||||
Image(systemName: "line.3.horizontal.decrease.circle")
|
||||
Text(filter?.rawValue ?? "All").lineLimit(1)
|
||||
}
|
||||
.font(.system(size: PedalPaletteView.titleFontSize))
|
||||
.foregroundStyle((filter?.color ?? Color.white).opacity(0.9))
|
||||
}
|
||||
.menuStyle(.borderlessButton)
|
||||
.fixedSize()
|
||||
}
|
||||
|
||||
/// A full-width pedal row: tap appends to the main chain; drag carries `"add:<name>"` so it can
|
||||
/// be dropped onto a stereo/parallel lane.
|
||||
private func pedalRow(_ name: String) -> some View {
|
||||
@@ -158,13 +234,25 @@ public struct PedalPaletteView: View {
|
||||
}
|
||||
.padding(.horizontal, PedalPaletteView.cardPaddingH)
|
||||
.padding(.vertical, PedalPaletteView.cardPaddingV)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(cardBackground(brightness: PedalPaletteView.pedalCardBrightness))
|
||||
.modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth))
|
||||
.background(categoryCardBackground(PedalCategory.category(for: name).color))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.draggable("add:\(name)")
|
||||
}
|
||||
|
||||
/// Category-tinted card background — a low-opacity fill plus a stronger border in the category
|
||||
/// colour, so palette blocks are colour-coded by type.
|
||||
private func categoryCardBackground(_ color: Color) -> some View {
|
||||
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
|
||||
.fill(color.opacity(PedalPaletteView.categoryFillOpacity))
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
|
||||
.stroke(color.opacity(PedalPaletteView.categoryBorderOpacity),
|
||||
lineWidth: PedalPaletteView.cardBorderWidth)
|
||||
)
|
||||
}
|
||||
|
||||
/// A tappable routing row that inserts a region/node into the board.
|
||||
private func routingCard(title: String, caption: String, action: RoutingAction) -> some View {
|
||||
Button {
|
||||
@@ -180,12 +268,27 @@ public struct PedalPaletteView: View {
|
||||
}
|
||||
.padding(.horizontal, PedalPaletteView.cardPaddingH)
|
||||
.padding(.vertical, PedalPaletteView.cardPaddingV)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth))
|
||||
.background(cardBackground(brightness: PedalPaletteView.routingCardBrightness))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
|
||||
/// Stretches a card to fill width in a vertical column, or pins it to a fixed width in a
|
||||
/// horizontal row.
|
||||
private struct CardFrame: ViewModifier {
|
||||
let axis: Axis
|
||||
let width: CGFloat
|
||||
func body(content: Content) -> some View {
|
||||
switch axis {
|
||||
case .horizontal:
|
||||
content.frame(width: width, alignment: .leading)
|
||||
default:
|
||||
content.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func cardBackground(brightness: Double) -> some View {
|
||||
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
|
||||
.fill(Color(white: brightness))
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// PedalSelectorKnobView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Renders a ``PedalSelectorKnob`` — a rotary knob that snaps to a fixed set of labelled stops.
|
||||
///
|
||||
/// Visually matches `ParameterKnob` (same dial + indicator), but drag quantises to discrete
|
||||
/// positions and the caption shows the current stop's title rather than a numeric value. Drag up to
|
||||
/// advance clockwise through the stops, down to go back.
|
||||
struct PedalSelectorKnobView: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
private static let dialSize: CGFloat = 50
|
||||
private static let indicatorWidth: CGFloat = 2
|
||||
private static let indicatorHeight: CGFloat = 14
|
||||
private static let indicatorInset: CGFloat = 3
|
||||
private static let startAngle: Double = -135.0
|
||||
private static let totalArc: Double = 270.0
|
||||
/// Pixels of vertical drag per stop step.
|
||||
private static let pixelsPerStep: CGFloat = 22
|
||||
private static let labelSpacing: CGFloat = 4
|
||||
|
||||
// MARK: - Input
|
||||
|
||||
private let selector: PedalSelectorKnob
|
||||
|
||||
// MARK: - Drag state
|
||||
|
||||
@State private var dragStartIndex: Int = 0
|
||||
@State private var dragInProgress: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
init(_ selector: PedalSelectorKnob) {
|
||||
self.selector = selector
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: PedalSelectorKnobView.labelSpacing) {
|
||||
dial
|
||||
.frame(width: PedalSelectorKnobView.dialSize, height: PedalSelectorKnobView.dialSize)
|
||||
.gesture(dragGesture)
|
||||
Text(selector.label)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white)
|
||||
Text(currentStop.title)
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Dial
|
||||
|
||||
private var dial: some View {
|
||||
let count: Int = selector.stops.count
|
||||
let normalised: Double = count > 1 ? Double(currentIndex) / Double(count - 1) : 0
|
||||
let rotation: Double = PedalSelectorKnobView.startAngle + normalised * PedalSelectorKnobView.totalArc
|
||||
let offset: CGFloat = -(PedalSelectorKnobView.dialSize / 2
|
||||
- PedalSelectorKnobView.indicatorHeight / 2
|
||||
- PedalSelectorKnobView.indicatorInset)
|
||||
|
||||
return ZStack {
|
||||
Circle()
|
||||
.fill(Color.lyrebirdControlBackground)
|
||||
.overlay(Circle().stroke(Color.lyrebirdSeparator, lineWidth: 1))
|
||||
Rectangle()
|
||||
.fill(Color.accentColor)
|
||||
.frame(
|
||||
width: PedalSelectorKnobView.indicatorWidth,
|
||||
height: PedalSelectorKnobView.indicatorHeight
|
||||
)
|
||||
.offset(y: offset)
|
||||
.rotationEffect(.degrees(rotation))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Drag
|
||||
|
||||
private var dragGesture: some Gesture {
|
||||
DragGesture(minimumDistance: 1)
|
||||
.onChanged { gesture in
|
||||
if !dragInProgress {
|
||||
dragInProgress = true
|
||||
dragStartIndex = currentIndex
|
||||
}
|
||||
let delta: CGFloat = gesture.translation.height // down = positive
|
||||
// Up should advance (increase index), so subtract the downward delta.
|
||||
let steps: Int = Int((-delta / PedalSelectorKnobView.pixelsPerStep).rounded())
|
||||
let target: Int = min(max(dragStartIndex + steps, 0), selector.stops.count - 1)
|
||||
let value: Double = selector.stops[target].value
|
||||
if value != selector.node.value {
|
||||
selector.node.update(value)
|
||||
}
|
||||
}
|
||||
.onEnded { _ in dragInProgress = false }
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Index of the stop whose value is nearest the node's current value.
|
||||
private var currentIndex: Int {
|
||||
let value: Double = selector.node.value
|
||||
var bestIndex: Int = 0
|
||||
var bestDistance: Double = .greatestFiniteMagnitude
|
||||
for (index, stop) in selector.stops.enumerated() {
|
||||
let distance: Double = abs(stop.value - value)
|
||||
if distance < bestDistance {
|
||||
bestDistance = distance
|
||||
bestIndex = index
|
||||
}
|
||||
}
|
||||
return bestIndex
|
||||
}
|
||||
|
||||
private var currentStop: PedalSelectorKnob.Stop {
|
||||
selector.stops[currentIndex]
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,10 @@ import LyrebirdShoeGaze
|
||||
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 "Distortion": return Color(red: 0.80, green: 0.26, blue: 0.12) // hot rust
|
||||
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 "Shimmer Reverb": return Color(red: 0.46, green: 0.52, blue: 0.78) // icy periwinkle
|
||||
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
|
||||
@@ -28,13 +30,21 @@ private func enclosureColor(for displayName: String) -> Color {
|
||||
case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold
|
||||
case "Feedback Delay": return Color(red: 0.48, green: 0.30, blue: 0.14) // tape sepia
|
||||
case "Multi-Tap Delay": return Color(red: 0.08, green: 0.48, blue: 0.68) // cyan
|
||||
case "Reverse Delay": return Color(red: 0.10, green: 0.44, blue: 0.60) // deep cyan-teal
|
||||
case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red
|
||||
case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal
|
||||
case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal
|
||||
case "Chorus": return Color(red: 0.16, green: 0.50, blue: 0.64) // aqua
|
||||
case "Flanger": return Color(red: 0.28, green: 0.52, blue: 0.78) // steel blue
|
||||
case "Vibrato": return Color(red: 0.42, green: 0.30, blue: 0.70) // violet-blue
|
||||
case "Rotary": return Color(red: 0.45, green: 0.34, blue: 0.20) // Leslie cabinet walnut
|
||||
case "Sustainer": return Color(red: 0.22, green: 0.46, blue: 0.30) // pine green
|
||||
case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber
|
||||
case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle
|
||||
case "Harmonizer": return Color(red: 0.52, green: 0.20, blue: 0.40) // wine / mauve
|
||||
case "Bitcrusher": return Color(red: 0.30, green: 0.34, blue: 0.40) // slate / digital gray
|
||||
case "Granulator": return Color(red: 0.20, green: 0.55, blue: 0.50) // sea green
|
||||
case "Auto Granulator": return Color(red: 0.24, green: 0.50, blue: 0.56) // teal-aqua
|
||||
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
|
||||
}
|
||||
}
|
||||
@@ -216,8 +226,11 @@ public struct PedalView: View {
|
||||
private static let screwHalfSize: CGFloat = 4
|
||||
private static let namePlateBackgroundOpacity: Double = 0.35
|
||||
private static let fontSizeNamePlate: CGFloat = 13
|
||||
/// Opacity of the trailing ⓘ info button on the name plate.
|
||||
/// Opacity of the ⓘ info button.
|
||||
private static let infoButtonOpacity: Double = 0.7
|
||||
/// Insets placing the ⓘ info button just under the top-left corner screw.
|
||||
private static let infoButtonLeading: CGFloat = 5
|
||||
private static let infoButtonTop: CGFloat = 20
|
||||
private static let outerBorderLineWidth: CGFloat = 1.5
|
||||
private static let innerHighlightLineWidth: CGFloat = 1
|
||||
private static let innerHighlightPadding: CGFloat = 1
|
||||
@@ -274,6 +287,7 @@ public struct PedalView: View {
|
||||
VStack(spacing: PedalView.sectionSpacing) {
|
||||
namePlate
|
||||
knobGrid
|
||||
selectorRow
|
||||
switchRow
|
||||
sliderBank(sliders)
|
||||
Spacer(minLength: 0)
|
||||
@@ -283,6 +297,11 @@ public struct PedalView: View {
|
||||
|
||||
// Corner screws — overlaid at the four corners
|
||||
screwCorners
|
||||
|
||||
// Info button, tucked just under the top-left corner screw.
|
||||
infoButton
|
||||
.padding(.leading, PedalView.infoButtonLeading)
|
||||
.padding(.top, PedalView.infoButtonTop)
|
||||
}
|
||||
.frame(width: enclosureWidth(for: sliders))
|
||||
.shadow(
|
||||
@@ -299,7 +318,7 @@ public struct PedalView: View {
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
/// Capsule name plate near the top of the enclosure, with a trailing info button.
|
||||
/// 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))
|
||||
@@ -308,18 +327,19 @@ public struct PedalView: View {
|
||||
.padding(.vertical, PedalView.namePlatePaddingV)
|
||||
.background(Color.black.opacity(PedalView.namePlateBackgroundOpacity))
|
||||
.clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius))
|
||||
.frame(maxWidth: .infinity)
|
||||
.overlay(alignment: .trailing) {
|
||||
Button {
|
||||
showInfo = true
|
||||
} label: {
|
||||
Image(systemName: "info.circle")
|
||||
.font(.system(size: PedalView.fontSizeNamePlate))
|
||||
.foregroundStyle(Color.white.opacity(PedalView.infoButtonOpacity))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("About this pedal")
|
||||
}
|
||||
}
|
||||
|
||||
/// Info button tucked just under the top-left corner screw.
|
||||
private var infoButton: some View {
|
||||
Button {
|
||||
showInfo = true
|
||||
} label: {
|
||||
Image(systemName: "info.circle")
|
||||
.font(.system(size: PedalView.fontSizeNamePlate))
|
||||
.foregroundStyle(Color.white.opacity(PedalView.infoButtonOpacity))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help("About this pedal")
|
||||
}
|
||||
|
||||
/// Grid of the effect knobs, in rows of up to `knobColumnCount`.
|
||||
@@ -362,6 +382,22 @@ public struct PedalView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid.
|
||||
/// Renders nothing when the pedal publishes no selectors.
|
||||
@ViewBuilder
|
||||
private var selectorRow: some View {
|
||||
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
|
||||
if !selectors.isEmpty {
|
||||
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
|
||||
Spacer(minLength: 0)
|
||||
ForEach(Array(selectors.enumerated()), id: \.offset) { pair in
|
||||
PedalSelectorKnobView(pair.element)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Row of segmented switches drawn from `pedal.effectSwitches`, one per row, beneath
|
||||
/// the knob grid. Renders nothing when the pedal publishes no switches.
|
||||
@ViewBuilder
|
||||
|
||||
@@ -7,15 +7,18 @@
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// A minimal JSON `FileDocument` wrapping a ShoeGaze rig's encoded bytes.
|
||||
/// A minimal `FileDocument` wrapping a ShoeGaze document's encoded bytes.
|
||||
///
|
||||
/// Used by ``ShoeGazeBuilderView``'s iOS `.fileExporter` to write the result of
|
||||
/// `ShoeGaze.rigData()` to a user-chosen location. macOS uses an `NSSavePanel` directly and does
|
||||
/// not need this type.
|
||||
/// Used by ``ShoeGazeBuilderView``'s `.fileExporter` to write the result of
|
||||
/// `RigLibraryStore.exportDocumentData()` (a `.shoegaze` ``ShoeGazeDocument``) to a user-chosen
|
||||
/// location.
|
||||
struct RigFileDocument: FileDocument {
|
||||
|
||||
/// The rig presets are plain JSON.
|
||||
static var readableContentTypes: [UTType] { [.json] }
|
||||
/// Writes the `.shoegaze` document type.
|
||||
static var writableContentTypes: [UTType] { [.shoeGaze] }
|
||||
|
||||
/// Reads `.shoegaze` documents and the legacy plain-JSON exports.
|
||||
static var readableContentTypes: [UTType] { [.shoeGaze, .json] }
|
||||
|
||||
/// Encoded rig JSON.
|
||||
let data: Data
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// RigLibraryBootstrap.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
|
||||
///
|
||||
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
|
||||
/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work —
|
||||
/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the
|
||||
/// library from the current working rig **only after** the real (possibly iCloud) contents are
|
||||
/// known, so a first launch can't create a duplicate "Default" rig on every synced device.
|
||||
@MainActor
|
||||
public enum RigLibraryBootstrap {
|
||||
|
||||
/// Creates an auto-resolving store. Construct this synchronously at launch; call
|
||||
/// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
|
||||
public static func makeStore() -> RigLibraryStore {
|
||||
RigLibraryStore()
|
||||
}
|
||||
|
||||
/// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still
|
||||
/// empty after loading (first run). Idempotent enough to call once at launch.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - store: The store from ``makeStore()``.
|
||||
/// - shoeGaze: The session whose current rig seeds the library when it is first empty.
|
||||
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`.
|
||||
public static func start(
|
||||
_ store: RigLibraryStore,
|
||||
seedFrom shoeGaze: ShoeGaze,
|
||||
seedName: String = "Default"
|
||||
) async {
|
||||
await store.start()
|
||||
|
||||
// Seed only after the (possibly iCloud) library has loaded: an empty library here means a
|
||||
// genuine first run, not a not-yet-synced one.
|
||||
guard store.entries.isEmpty, !shoeGaze.boards.isEmpty else { return }
|
||||
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
|
||||
do {
|
||||
try store.save(entry)
|
||||
UserDefaults.standard.set(
|
||||
entry.id.uuidString,
|
||||
forKey: ShoeGazeBuilderView.currentRigDefaultsKey
|
||||
)
|
||||
} catch {
|
||||
print("[RigLibraryBootstrap] seeding library failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// RigLibraryCommands.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Notifications the macOS app shell posts from its menu bar so the in-window
|
||||
/// ``ShoeGazeBuilderView`` — which owns the current-rig state — performs the action with the
|
||||
/// correct UI (naming prompts, highlight updates). iOS has no menu bar and simply never posts them.
|
||||
public extension Notification.Name {
|
||||
|
||||
/// Save the current rig to the library (overwrites the loaded entry, or prompts for a name).
|
||||
static let shoeGazeSaveRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.saveRig")
|
||||
|
||||
/// Create a new, named, empty rig and make it current.
|
||||
static let shoeGazeNewRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.newRig")
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// RigLibrarySidebarView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// The rig library: a persistent left-hand listing of every saved rig, with controls to start a
|
||||
/// new rig, save / save-as, duplicate, rename, delete, erase all, and import / export an archive.
|
||||
///
|
||||
/// Selecting a rig replaces the current working session (the host stops the engine, rebuilds the
|
||||
/// graph, and restarts). This view is purely presentational — every action is delegated to the
|
||||
/// host (`ShoeGazeBuilderView`) via closures so engine lifecycle and naming prompts stay in one
|
||||
/// place.
|
||||
struct RigLibrarySidebarView: View {
|
||||
|
||||
// MARK: - Layout constants
|
||||
|
||||
private static let width: CGFloat = 200
|
||||
private static let rowSpacing: CGFloat = 4
|
||||
private static let rowPadding: CGFloat = 8
|
||||
private static let rowCorner: CGFloat = 6
|
||||
private static let selectedOpacity: Double = 0.22
|
||||
private static let subtitleOpacity: Double = 0.5
|
||||
private static let headerOpacity: Double = 0.65
|
||||
private static let emptyOpacity: Double = 0.4
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
let store: RigLibraryStore
|
||||
|
||||
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig.
|
||||
@Binding var currentRigID: UUID?
|
||||
|
||||
let onSelect: (RigEntry) -> Void
|
||||
let onNew: () -> Void
|
||||
let onSave: () -> Void
|
||||
let onSaveAs: () -> Void
|
||||
let onDuplicate: (RigEntry) -> Void
|
||||
let onRename: (RigEntry) -> Void
|
||||
let onDelete: (RigEntry) -> Void
|
||||
let onEraseAll: () -> Void
|
||||
let onImportArchive: () -> Void
|
||||
let onExportArchive: () -> Void
|
||||
|
||||
private static let timestampFormat: Date.FormatStyle =
|
||||
Date.FormatStyle(date: .abbreviated, time: .shortened)
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
||||
header
|
||||
Divider().overlay(Color.white.opacity(0.12))
|
||||
rigList
|
||||
Divider().overlay(Color.white.opacity(0.12))
|
||||
actionBar
|
||||
}
|
||||
.frame(width: RigLibrarySidebarView.width)
|
||||
}
|
||||
|
||||
// MARK: - Header
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 6) {
|
||||
Text("Rigs")
|
||||
.font(.headline)
|
||||
.foregroundStyle(Color.white)
|
||||
Spacer()
|
||||
// Cloud icon when the library is iCloud-backed; a slash when local-only.
|
||||
Image(systemName: store.isICloud ? "icloud" : "icloud.slash")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
|
||||
.help(store.isICloud
|
||||
? "Synced with iCloud across your devices"
|
||||
: "iCloud unavailable — rigs are stored on this device only")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - List
|
||||
|
||||
private var rigList: some View {
|
||||
ScrollView(.vertical, showsIndicators: true) {
|
||||
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
||||
if !store.isLoaded {
|
||||
HStack(spacing: 6) {
|
||||
ProgressView().controlSize(.small)
|
||||
Text("Loading…")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||
}
|
||||
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
||||
} else if store.entries.isEmpty {
|
||||
Text("No saved rigs yet.\nTap New or Save to add one.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
||||
}
|
||||
ForEach(store.entries) { entry in
|
||||
rigRow(entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(maxHeight: .infinity)
|
||||
}
|
||||
|
||||
private func rigRow(_ entry: RigEntry) -> some View {
|
||||
let isSelected: Bool = entry.id == currentRigID
|
||||
return Button {
|
||||
onSelect(entry)
|
||||
} label: {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(entry.name)
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(Color.white)
|
||||
.lineLimit(1)
|
||||
Text(entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat))
|
||||
.font(.caption2)
|
||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity))
|
||||
.lineLimit(1)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(RigLibrarySidebarView.rowPadding)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: RigLibrarySidebarView.rowCorner)
|
||||
.fill(Color.orange.opacity(isSelected ? RigLibrarySidebarView.selectedOpacity : 0))
|
||||
)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.contextMenu {
|
||||
Button("Rename…") { onRename(entry) }
|
||||
Button("Duplicate…") { onDuplicate(entry) }
|
||||
// Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the
|
||||
// unreachable failure path the Share item is simply omitted.
|
||||
if let shareItem: RigShareItem = try? RigShareItem(rig: entry) {
|
||||
ShareLink(
|
||||
item: shareItem,
|
||||
preview: SharePreview(entry.name)
|
||||
) {
|
||||
Label("Share…", systemImage: "square.and.arrow.up")
|
||||
}
|
||||
}
|
||||
Divider()
|
||||
Button("Delete", role: .destructive) { onDelete(entry) }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Action bar
|
||||
|
||||
private var actionBar: some View {
|
||||
HStack(spacing: 6) {
|
||||
Button { onNew() } label: { Image(systemName: "plus") }
|
||||
.help("New rig")
|
||||
Button { onSave() } label: { Image(systemName: "square.and.arrow.down") }
|
||||
.help("Save the current rig")
|
||||
Button { onSaveAs() } label: { Image(systemName: "doc.on.doc") }
|
||||
.help("Save the current rig as a new entry")
|
||||
Spacer()
|
||||
Menu {
|
||||
Button("Import Archive…") { onImportArchive() }
|
||||
Button("Export Archive…") { onExportArchive() }
|
||||
Divider()
|
||||
Button("Erase All Rigs…", role: .destructive) { onEraseAll() }
|
||||
} label: {
|
||||
Image(systemName: "ellipsis.circle")
|
||||
}
|
||||
.menuStyle(.borderlessButton)
|
||||
.fixedSize()
|
||||
.help("Archive and library options")
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(.orange)
|
||||
.padding(.top, 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// RigNamePrompt.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// A request to prompt the user for a rig name (New, Save As, Rename, Duplicate).
|
||||
///
|
||||
/// Presented via the ``SwiftUI/View/rigNamePrompt(_:)`` modifier. Setting a non-`nil` value shows a
|
||||
/// text-entry alert seeded with `initialText`; committing a non-empty, trimmed name invokes
|
||||
/// `onCommit`. Cancelling dismisses without calling `onCommit`.
|
||||
struct RigNamePrompt: Identifiable {
|
||||
|
||||
let id: UUID = UUID()
|
||||
|
||||
/// Alert title, e.g. `"Save Rig As"`.
|
||||
let title: String
|
||||
|
||||
/// Text the field is pre-filled with (e.g. the existing name for a rename).
|
||||
let initialText: String
|
||||
|
||||
/// Confirm-button label, e.g. `"Save"` or `"Rename"`.
|
||||
let confirmLabel: String
|
||||
|
||||
/// Invoked with the trimmed, non-empty name when the user confirms.
|
||||
let onCommit: (String) -> Void
|
||||
}
|
||||
|
||||
private struct RigNamePromptModifier: ViewModifier {
|
||||
|
||||
@Binding var prompt: RigNamePrompt?
|
||||
@State private var text: String = ""
|
||||
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.onChange(of: prompt?.id) {
|
||||
// Seed the field whenever a new prompt is presented.
|
||||
text = prompt?.initialText ?? ""
|
||||
}
|
||||
.alert(
|
||||
prompt?.title ?? "",
|
||||
isPresented: isPresented,
|
||||
presenting: prompt
|
||||
) { active in
|
||||
TextField("Name", text: $text)
|
||||
Button(active.confirmLabel) {
|
||||
let trimmed: String = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
if !trimmed.isEmpty { active.onCommit(trimmed) }
|
||||
}
|
||||
Button("Cancel", role: .cancel) { }
|
||||
}
|
||||
}
|
||||
|
||||
private var isPresented: Binding<Bool> {
|
||||
Binding(
|
||||
get: { prompt != nil },
|
||||
set: { presented in if !presented { prompt = nil } }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
extension View {
|
||||
|
||||
/// Presents a rig-name entry alert driven by `prompt`. Set the binding to a ``RigNamePrompt``
|
||||
/// to show it; it clears itself on dismiss.
|
||||
func rigNamePrompt(_ prompt: Binding<RigNamePrompt?>) -> some View {
|
||||
modifier(RigNamePromptModifier(prompt: prompt))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// RigShareItem.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import CoreTransferable
|
||||
import UniformTypeIdentifiers
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// A `Transferable` wrapper that lets a `ShareLink` send a single rig as a `.shoegaze` document.
|
||||
///
|
||||
/// Holds the already-encoded document bytes (a value type, so the wrapper is `Sendable` as
|
||||
/// `Transferable` requires). The encode happens when the share menu is built for the focused row —
|
||||
/// cheap, one rig — via the throwing ``init(rig:)``.
|
||||
///
|
||||
/// Uses `FileRepresentation` (not `DataRepresentation`): the share sheet — AirDrop, Messages,
|
||||
/// Mail, Notes, Files — only offers its full service list when handed a real file on disk. The
|
||||
/// bytes are written to a temporary `<rig>.shoegaze` when a destination is picked. Sharing raw
|
||||
/// data instead collapses the macOS menu to just Copy / Edit Extensions.
|
||||
struct RigShareItem: Transferable, Sendable {
|
||||
|
||||
/// Filesystem-safe base name for the shared file (no extension).
|
||||
let filenameBase: String
|
||||
|
||||
/// Encoded `.shoegaze` document bytes.
|
||||
let data: Data
|
||||
|
||||
/// Encodes `entry` as a single-rig `.shoegaze` document.
|
||||
///
|
||||
/// - Parameter entry: The library entry to share.
|
||||
/// - Throws: Any `JSONEncoder` error from ``ShoeGazeDocument/data()``.
|
||||
init(rig entry: RigEntry) throws {
|
||||
self.filenameBase = shareFilenameBase(entry.name)
|
||||
self.data = try ShoeGazeDocument(rig: entry).data()
|
||||
}
|
||||
|
||||
static var transferRepresentation: some TransferRepresentation {
|
||||
FileRepresentation(exportedContentType: .shoeGaze) { item in
|
||||
SentTransferredFile(try writeShoeGazeShareFile(item.data, base: item.filenameBase))
|
||||
}
|
||||
.suggestedFileName { item in
|
||||
"\(item.filenameBase).\(ShoeGazeDocument.fileExtension)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reduces a user-supplied name to a filesystem-safe base for a shared file, mirroring the preset
|
||||
/// stores' sanitisation at the UI boundary (the core sanitiser is module-internal to
|
||||
/// `LyrebirdShoeGaze`). Path separators and whitespace become underscores; an empty result falls
|
||||
/// back to a generic name. Shared by ``RigShareItem`` and ``BoardShareItem``.
|
||||
func shareFilenameBase(_ name: String) -> String {
|
||||
let forbidden: Set<Character> = ["/", "\\", ":", "\0"]
|
||||
let mapped: String = String(name.map { character -> Character in
|
||||
(character.isWhitespace || forbidden.contains(character)) ? "_" : character
|
||||
})
|
||||
let trimmed: String = mapped.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
|
||||
return trimmed.isEmpty ? "ShoeGaze" : trimmed
|
||||
}
|
||||
|
||||
/// Writes `data` to a uniquely-named temporary `<base>.shoegaze` file and returns its URL, for a
|
||||
/// `FileRepresentation` to hand the share sheet a real file. A fresh per-share subdirectory avoids
|
||||
/// collisions when the same name is shared twice. Shared by ``RigShareItem`` and ``BoardShareItem``.
|
||||
func writeShoeGazeShareFile(_ data: Data, base: String) throws -> URL {
|
||||
let directory: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("ShoeGazeShare-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let url: URL = directory
|
||||
.appendingPathComponent(base)
|
||||
.appendingPathExtension(ShoeGazeDocument.fileExtension)
|
||||
try data.write(to: url, options: .atomic)
|
||||
return url
|
||||
}
|
||||
@@ -43,6 +43,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
private static let minWidth: CGFloat = 720
|
||||
private static let minHeight: CGFloat = 460
|
||||
private static let sidebarWidth: CGFloat = 168
|
||||
/// Width of the scope/CPU block in the bottom strip — matches `BoardBarView`'s Solo/Blend/All
|
||||
/// control column so the scope aligns under it.
|
||||
private static let scopeWidth: CGFloat = 188
|
||||
private static let columnSpacing: CGFloat = 14
|
||||
private static let backgroundRed: Double = 0.08
|
||||
private static let backgroundGreen: Double = 0.07
|
||||
@@ -50,17 +53,24 @@ public struct ShoeGazeBuilderView: View {
|
||||
private static let testLoopTag: Int = -1
|
||||
/// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel).
|
||||
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
|
||||
/// UserDefaults key persisting the loaded rig's id (its `uuidString`) so the same rig can be
|
||||
/// highlighted on the next launch. Read by the app shells to seed `initialRigID`.
|
||||
public static let currentRigDefaultsKey: String = "ShoeGaze.currentRigID"
|
||||
/// Maximum crossfade duration honoured by board-switch keyboard shortcuts.
|
||||
private static let maxCrossfadeSeconds: Double = 10.0
|
||||
/// Highest board reachable via a ⌘-number switch shortcut.
|
||||
private static let maxBoardShortcuts: Int = 9
|
||||
private static let defaultRigFileName: String = "ShoeGazeRig"
|
||||
/// Default filename offered when exporting the whole library as an archive.
|
||||
private static let defaultArchiveFileName: String = "ShoeGaze Library"
|
||||
/// Extra width reserved for the rig-library sidebar on top of the builder's minimum width.
|
||||
private static let librarySidebarReserve: CGFloat = 216
|
||||
private static let recordDotSize: CGFloat = 9
|
||||
private static let folderLabelOpacity: Double = 0.55
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let shoeGaze: ShoeGaze
|
||||
private let library: RigLibraryStore
|
||||
private let hardwareSampleRate: () -> Double?
|
||||
|
||||
/// Host hook to enable live input when the current engine has no input channel (iOS).
|
||||
@@ -87,18 +97,46 @@ public struct ShoeGazeBuilderView: View {
|
||||
/// Presentation flag for the board-manager sheet (rename / reorder / delete).
|
||||
@State private var showBoardsSheet: Bool = false
|
||||
|
||||
/// Confirmation dialog for the Clear action, and a flag to clear once a chosen save completes.
|
||||
/// Confirmation dialog for the Clear action.
|
||||
@State private var showClearDialog: Bool = false
|
||||
@State private var pendingClearAfterSave: Bool = false
|
||||
|
||||
/// Rig-save export state. Cross-platform: the in-view exporter backs both the Save action and
|
||||
/// the "Save & Clear" flow on macOS and iOS (macOS additionally has a File-menu Save).
|
||||
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig. Drives
|
||||
/// the sidebar highlight and decides whether Save overwrites or prompts for a name.
|
||||
@State private var currentRigID: UUID?
|
||||
|
||||
/// Guards the one-time `currentRigID` seed from `initialRigID` on appear.
|
||||
@State private var didRestoreRig: Bool = false
|
||||
|
||||
/// Drives the shared rig-name entry alert (New / Save As / Rename / Duplicate).
|
||||
@State private var namePrompt: RigNamePrompt?
|
||||
|
||||
/// Confirmation dialog for the "Erase All Rigs" library action.
|
||||
@State private var showEraseAllDialog: Bool = false
|
||||
|
||||
/// Save-before-switch prompt: the rig the user asked to switch to while the current rig has
|
||||
/// unsaved changes, and the flag presenting the dialog.
|
||||
@State private var pendingSwitchEntry: RigEntry?
|
||||
@State private var showSwitchSaveDialog: Bool = false
|
||||
|
||||
/// A failed edit (add pedal / routing / board) to surface as an alert. `nil` = no alert.
|
||||
@State private var actionError: ActionError?
|
||||
|
||||
/// A user-facing failure message for the action-error alert.
|
||||
private struct ActionError: Identifiable {
|
||||
let id: UUID = UUID()
|
||||
let title: String
|
||||
let message: String
|
||||
}
|
||||
|
||||
/// Archive export state. Cross-platform: backs the sidebar's Export Archive and the
|
||||
/// "Save & Clear" flow is separate (it saves to the library, not a file).
|
||||
@State private var showExporter: Bool = false
|
||||
@State private var exportDocument: RigFileDocument = RigFileDocument(data: Data())
|
||||
|
||||
#if !os(macOS)
|
||||
/// iOS file-dialog presentation flags. (macOS uses the File menu for load + recording folder.)
|
||||
/// Archive import state (cross-platform).
|
||||
@State private var showImporter: Bool = false
|
||||
|
||||
#if !os(macOS)
|
||||
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
|
||||
@State private var showRecordingFolderImporter: Bool = false
|
||||
#endif
|
||||
@@ -117,12 +155,17 @@ public struct ShoeGazeBuilderView: View {
|
||||
/// engine with one input channel (preserving the rig), and select live input. Defaults to
|
||||
/// `nil` — on macOS the engine already has an input channel, so live input is selected
|
||||
/// directly without a rebuild.
|
||||
/// - library: The rig library store. The host should `start()` it (e.g. via
|
||||
/// `RigLibraryBootstrap`); the view shows a loading state until then and highlights the
|
||||
/// persisted current rig once the library has loaded.
|
||||
public init(
|
||||
shoeGaze: ShoeGaze,
|
||||
library: RigLibraryStore,
|
||||
hardwareSampleRate: @escaping () -> Double? = { nil },
|
||||
onEnableLiveInput: (() -> Void)? = nil
|
||||
) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self.library = library
|
||||
self.hardwareSampleRate = hardwareSampleRate
|
||||
self.onEnableLiveInput = onEnableLiveInput
|
||||
}
|
||||
@@ -130,34 +173,16 @@ public struct ShoeGazeBuilderView: View {
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||||
transportRow
|
||||
ioRow
|
||||
#if !os(macOS)
|
||||
recordingRow
|
||||
#endif
|
||||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
|
||||
rigSidebar
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
BoardBarView(
|
||||
shoeGaze: shoeGaze,
|
||||
editingBoardIndex: $selectedBoardIndex,
|
||||
crossfadeSeconds: $crossfadeSeconds,
|
||||
onAddBoard: { addBoard() }
|
||||
)
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
|
||||
paletteSidebar
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
boardArea
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
// Scope + CPU meters sit under the pedal palette, matching its width.
|
||||
ShoeGazeScopeView(shoeGaze: shoeGaze)
|
||||
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
|
||||
LyrebirdStatusView(engine: shoeGaze.engine)
|
||||
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
|
||||
builderColumn
|
||||
}
|
||||
.padding(ShoeGazeBuilderView.outerPadding)
|
||||
.frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight)
|
||||
.frame(
|
||||
minWidth: ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve,
|
||||
minHeight: ShoeGazeBuilderView.minHeight
|
||||
)
|
||||
.background(
|
||||
Color(
|
||||
red: ShoeGazeBuilderView.backgroundRed,
|
||||
@@ -165,28 +190,68 @@ public struct ShoeGazeBuilderView: View {
|
||||
blue: ShoeGazeBuilderView.backgroundBlue
|
||||
)
|
||||
)
|
||||
// The builder is always dark-themed; force the dark scheme so system controls (nav title,
|
||||
// steppers, the Record button) use light text instead of black-on-dark in light mode.
|
||||
.preferredColorScheme(.dark)
|
||||
.background(boardSwitchShortcuts)
|
||||
.onAppear { restoreInputSelection() }
|
||||
// Each presentation (sheet / importers / exporter / alert) lives on its own anchor
|
||||
// node. SwiftUI reliably drives only one presentation per view node, so stacking them
|
||||
// all on the root view silently swallowed some (e.g. the iOS Load file importer).
|
||||
.onAppear {
|
||||
restoreInputSelection()
|
||||
restoreCurrentRig()
|
||||
}
|
||||
.onChange(of: library.isLoaded) { restoreCurrentRig() }
|
||||
.onChange(of: currentRigID) { persistCurrentRigID() }
|
||||
.background(boardsSheetAnchor)
|
||||
.background(rigExportAnchor)
|
||||
.background(rigImportAnchor)
|
||||
.background(actionErrorAnchor)
|
||||
.rigNamePrompt($namePrompt)
|
||||
.confirmationDialog(
|
||||
"Erase all rigs?",
|
||||
isPresented: $showEraseAllDialog,
|
||||
titleVisibility: .visible
|
||||
) {
|
||||
Button("Erase All Rigs", role: .destructive) { eraseAllRigs() }
|
||||
Button("Cancel", role: .cancel) { }
|
||||
} message: {
|
||||
Text("This permanently removes every saved rig from the library"
|
||||
+ (library.isICloud ? " on all your devices." : "."))
|
||||
}
|
||||
.confirmationDialog(
|
||||
"Save changes to the current rig?",
|
||||
isPresented: $showSwitchSaveDialog,
|
||||
titleVisibility: .visible,
|
||||
presenting: pendingSwitchEntry
|
||||
) { target in
|
||||
Button("Save") {
|
||||
pendingSwitchEntry = nil
|
||||
saveCurrentRig(then: { loadEntry(target) })
|
||||
}
|
||||
Button("Don't Save", role: .destructive) {
|
||||
pendingSwitchEntry = nil
|
||||
loadEntry(target)
|
||||
}
|
||||
Button("Cancel", role: .cancel) { pendingSwitchEntry = nil }
|
||||
} message: { target in
|
||||
Text("Switching to \"\(target.name)\" will discard unsaved changes to the current rig.")
|
||||
}
|
||||
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeSaveRig)) { _ in
|
||||
saveCurrentRig()
|
||||
}
|
||||
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeNewRig)) { _ in
|
||||
promptNewRig()
|
||||
}
|
||||
.confirmationDialog(
|
||||
"Clear all boards?",
|
||||
isPresented: $showClearDialog,
|
||||
titleVisibility: .visible
|
||||
) {
|
||||
Button("Save & Clear") {
|
||||
pendingClearAfterSave = true
|
||||
saveAction()
|
||||
saveCurrentRig(then: { performClear() })
|
||||
}
|
||||
Button("Clear Without Saving", role: .destructive) {
|
||||
performClear()
|
||||
}
|
||||
Button("Cancel", role: .cancel) {
|
||||
pendingClearAfterSave = false
|
||||
}
|
||||
Button("Cancel", role: .cancel) { }
|
||||
} message: {
|
||||
Text("This removes every pedal and board. Save your current setup first?")
|
||||
}
|
||||
@@ -197,11 +262,87 @@ public struct ShoeGazeBuilderView: View {
|
||||
+ "Security › Microphone, then select the input again.")
|
||||
}
|
||||
#if !os(macOS)
|
||||
.background(rigImportAnchor)
|
||||
.background(recordingFolderImportAnchor)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/
|
||||
/// delete/erase and archive import/export. Selecting a rig replaces the current session.
|
||||
private var rigSidebar: some View {
|
||||
RigLibrarySidebarView(
|
||||
store: library,
|
||||
currentRigID: $currentRigID,
|
||||
onSelect: { entry in requestLoad(entry) },
|
||||
onNew: { promptNewRig() },
|
||||
onSave: { saveCurrentRig() },
|
||||
onSaveAs: { promptSaveAs() },
|
||||
onDuplicate: { entry in promptDuplicate(entry) },
|
||||
onRename: { entry in promptRename(entry) },
|
||||
onDelete: { entry in deleteEntry(entry) },
|
||||
onEraseAll: { showEraseAllDialog = true },
|
||||
onImportArchive: { showImporter = true },
|
||||
onExportArchive: { exportArchiveAction() }
|
||||
)
|
||||
}
|
||||
|
||||
/// The main builder column: transport, IO, the scope-plus-mixer/picker top section, then the
|
||||
/// board canvas.
|
||||
private var builderColumn: some View {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||||
transportRow
|
||||
ioRow
|
||||
#if !os(macOS)
|
||||
recordingRow
|
||||
#endif
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
topSection
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
boardArea
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
}
|
||||
|
||||
/// Top section: the scope + CPU meters on the left (sized to align with the mixer's
|
||||
/// Solo/Blend/All control column), and a right column stacking the board mixer over the
|
||||
/// horizontal pedal picker.
|
||||
private var topSection: some View {
|
||||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||||
ShoeGazeScopeView(shoeGaze: shoeGaze)
|
||||
LyrebirdStatusView(engine: shoeGaze.engine)
|
||||
}
|
||||
.frame(width: ShoeGazeBuilderView.scopeWidth, alignment: .leading)
|
||||
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
|
||||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||||
BoardBarView(
|
||||
shoeGaze: shoeGaze,
|
||||
editingBoardIndex: $selectedBoardIndex,
|
||||
crossfadeSeconds: $crossfadeSeconds,
|
||||
onAddBoard: { addBoard() }
|
||||
)
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
pedalPickerRow
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
|
||||
/// A compact horizontal pedal-picker strip (sits below the board mixer in the top section).
|
||||
private var pedalPickerRow: some View {
|
||||
ScrollView(.horizontal, showsIndicators: true) {
|
||||
PedalPaletteView(
|
||||
axis: .horizontal,
|
||||
onAdd: { type in addPedal(type: type) },
|
||||
onRouting: { action in performRouting(action) }
|
||||
)
|
||||
.padding(.bottom, 2)
|
||||
}
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
|
||||
// MARK: - Presentation anchors
|
||||
|
||||
/// Hosts the board-manager sheet on its own node so it does not collide with the file
|
||||
@@ -219,37 +360,70 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hosts the rig-save (`.json`) exporter on its own node. Cross-platform: backs both the
|
||||
/// Save action and the "Save & Clear" flow. On a successful save during "Save & Clear", the
|
||||
/// pending clear runs; cancelling the save leaves the boards untouched.
|
||||
/// Hosts the library-export (`.shoegaze`) exporter on its own node. Writes the whole library as
|
||||
/// one ``ShoeGazeDocument`` file for backup or transfer.
|
||||
private var rigExportAnchor: some View {
|
||||
Color.clear
|
||||
.fileExporter(
|
||||
isPresented: $showExporter,
|
||||
document: exportDocument,
|
||||
contentType: .json,
|
||||
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
|
||||
contentType: .shoeGaze,
|
||||
defaultFilename: ShoeGazeBuilderView.defaultArchiveFileName
|
||||
) { result in
|
||||
switch result {
|
||||
case .failure(let error):
|
||||
print("[ShoeGazeBuilderView] export failed: \(error)")
|
||||
pendingClearAfterSave = false
|
||||
case .success:
|
||||
if pendingClearAfterSave { performClear() }
|
||||
pendingClearAfterSave = false
|
||||
if case .failure(let error) = result {
|
||||
print("[ShoeGazeBuilderView] library export failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(macOS)
|
||||
/// Hosts the rig-load (`.json`) importer on its own node.
|
||||
/// Hosts the library-import (`.shoegaze`) importer on its own node (cross-platform). Accepts a
|
||||
/// ``ShoeGazeDocument`` or a legacy archive / single-rig file; imported rigs are added to the
|
||||
/// library.
|
||||
private var rigImportAnchor: some View {
|
||||
Color.clear
|
||||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in
|
||||
handleImport(result)
|
||||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.shoeGaze, .json]) { result in
|
||||
handleArchiveImport(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Hosts the action-failure alert on its own node (one presentation per node).
|
||||
private var actionErrorAnchor: some View {
|
||||
Color.clear
|
||||
.alert(
|
||||
actionError?.title ?? "",
|
||||
isPresented: Binding(
|
||||
get: { actionError != nil },
|
||||
set: { presented in if !presented { actionError = nil } }
|
||||
),
|
||||
presenting: actionError
|
||||
) { _ in
|
||||
Button("OK", role: .cancel) { }
|
||||
} message: { error in
|
||||
Text(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
/// Surfaces a failed edit as an alert (and logs it). Maps the common stereo-width / merge errors
|
||||
/// to player-facing wording (no API names); otherwise uses the error's `LocalizedError` text.
|
||||
private func reportError(_ title: String, _ error: Error) {
|
||||
actionError = ActionError(title: title, message: friendlyMessage(for: error))
|
||||
}
|
||||
|
||||
private func friendlyMessage(for error: Error) -> String {
|
||||
switch error as? ShoeGazeError {
|
||||
case .stereoWidthExceeded, .cannotSplitStereoChain:
|
||||
return "This board is already in stereo. Add a “Merge to Mono” before another stereo "
|
||||
+ "(widening) pedal such as Chorus, Rotary, or a Granulator."
|
||||
case .cannotMergeMonoChain:
|
||||
return "This board is already mono — there’s no stereo signal to merge."
|
||||
case .cannotUnzipMonoChain:
|
||||
return "This board is mono — there’s no stereo signal to split into left/right lanes."
|
||||
default:
|
||||
return (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(macOS)
|
||||
/// Hosts the recording-folder importer on its own node.
|
||||
private var recordingFolderImportAnchor: some View {
|
||||
Color.clear
|
||||
@@ -316,35 +490,12 @@ public struct ShoeGazeBuilderView: View {
|
||||
|
||||
Button("Clear") { showClearDialog = true }
|
||||
.buttonStyle(.bordered).tint(.red)
|
||||
.help("Remove all boards (with the option to save first)")
|
||||
.help("Remove all boards in the current rig (with the option to save first)")
|
||||
|
||||
Spacer()
|
||||
|
||||
// On macOS, Load lives in the app's File menu (see the app shell's AppDelegate); on
|
||||
// iOS it stays in-view via fileImporter. Save is in-view on both (cross-platform
|
||||
// exporter) so the "Save & Clear" flow works everywhere.
|
||||
Button("Save…") { saveAction() }
|
||||
.buttonStyle(.bordered).tint(.blue)
|
||||
#if !os(macOS)
|
||||
Button("Load…") { loadAction() }
|
||||
.buttonStyle(.bordered).tint(.blue)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Palette sidebar
|
||||
|
||||
private var paletteSidebar: some View {
|
||||
ScrollView(.vertical, showsIndicators: true) {
|
||||
PedalPaletteView(
|
||||
onAdd: { type in addPedal(type: type) },
|
||||
onRouting: { action in performRouting(action) }
|
||||
)
|
||||
.padding(.trailing, 2)
|
||||
}
|
||||
.frame(width: ShoeGazeBuilderView.sidebarWidth)
|
||||
}
|
||||
|
||||
// MARK: - Board area
|
||||
|
||||
private var boardArea: some View {
|
||||
@@ -370,6 +521,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] routing \(action) failed: \(error)")
|
||||
reportError("Couldn’t add routing", error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,6 +566,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
autosave()
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
|
||||
reportError("Couldn’t add \(type)", error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -428,6 +581,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
} catch {
|
||||
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
|
||||
print("[ShoeGazeBuilderView] addBoard failed: \(error)")
|
||||
reportError("Couldn’t add board", error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -559,11 +713,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
shoeGaze.soloBoard(shoeGaze.boards[index], crossfadeSeconds: seconds)
|
||||
}
|
||||
|
||||
// MARK: - Save / Load (iOS)
|
||||
// MARK: - Recording (iOS)
|
||||
|
||||
// Save is in-view on both platforms (cross-platform fileExporter) so "Save & Clear" works
|
||||
// everywhere. Load is the macOS File menu / iOS fileImporter; recording controls are iOS
|
||||
// in-view (macOS uses the Record menu).
|
||||
// Recording controls are iOS in-view (macOS uses the Record menu).
|
||||
#if !os(macOS)
|
||||
/// iOS recording controls: choose an output folder, then start/stop recording.
|
||||
private var recordingRow: some View {
|
||||
@@ -610,47 +762,239 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Presents the cross-platform rig-save exporter (also used by the "Save & Clear" flow).
|
||||
private func saveAction() {
|
||||
do {
|
||||
exportDocument = RigFileDocument(data: try shoeGaze.rigData())
|
||||
showExporter = true
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] rigData failed: \(error)")
|
||||
// MARK: - Rig library
|
||||
|
||||
/// Highlights the persisted current rig once the library has loaded. Runs once; only sets the
|
||||
/// highlight when nothing is selected yet and the saved id still exists in the library.
|
||||
private func restoreCurrentRig() {
|
||||
guard !didRestoreRig, library.isLoaded else { return }
|
||||
didRestoreRig = true
|
||||
guard currentRigID == nil,
|
||||
let stored: String = UserDefaults.standard.string(
|
||||
forKey: ShoeGazeBuilderView.currentRigDefaultsKey),
|
||||
let id: UUID = UUID(uuidString: stored),
|
||||
library.entries.contains(where: { $0.id == id }) else { return }
|
||||
currentRigID = id
|
||||
}
|
||||
|
||||
/// Persists `currentRigID` so the same rig is highlighted on the next launch.
|
||||
private func persistCurrentRigID() {
|
||||
let defaults: UserDefaults = UserDefaults.standard
|
||||
if let id: UUID = currentRigID {
|
||||
defaults.set(id.uuidString, forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
|
||||
} else {
|
||||
defaults.removeObject(forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(macOS)
|
||||
private func loadAction() {
|
||||
showImporter = true
|
||||
}
|
||||
|
||||
/// Loads a rig from a URL, stopping/restarting the engine around the rebuild and resetting the
|
||||
/// board selection to a valid index (load replaces all boards).
|
||||
private func loadRig(from url: URL) {
|
||||
/// Loads a library entry into the session, replacing the current rig. Stops/restarts the engine
|
||||
/// around the rebuild, resets the board selection, and records the entry as current.
|
||||
private func loadEntry(_ entry: RigEntry) {
|
||||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||||
if wasRunning { shoeGaze.engine.stop() }
|
||||
do {
|
||||
try shoeGaze.loadRig(from: url)
|
||||
try shoeGaze.loadRig(from: entry.state)
|
||||
currentRigID = entry.id
|
||||
selectedBoardIndex = 0
|
||||
autosave()
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] loadRig failed: \(error)")
|
||||
print("[ShoeGazeBuilderView] loadEntry failed: \(error)")
|
||||
}
|
||||
if wasRunning { try? shoeGaze.engine.start() }
|
||||
transportTick.toggle()
|
||||
}
|
||||
|
||||
private func handleImport(_ result: Result<URL, Error>) {
|
||||
switch result {
|
||||
case .success(let url):
|
||||
// A `.fileImporter` URL is security-scoped on iOS; access must be started to read it.
|
||||
let scoped: Bool = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
loadRig(from: url)
|
||||
case .failure(let error):
|
||||
print("[ShoeGazeBuilderView] import failed: \(error)")
|
||||
/// Switches to `entry`, prompting to save first when the current rig has unsaved changes.
|
||||
/// No-op when `entry` is already the current rig.
|
||||
private func requestLoad(_ entry: RigEntry) {
|
||||
guard entry.id != currentRigID else { return }
|
||||
if isCurrentRigDirty() {
|
||||
pendingSwitchEntry = entry
|
||||
showSwitchSaveDialog = true
|
||||
} else {
|
||||
loadEntry(entry)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Whether the working rig differs from the library entry it was loaded from. A working rig with
|
||||
/// no backing entry counts as dirty when it has any boards.
|
||||
private func isCurrentRigDirty() -> Bool {
|
||||
guard let id: UUID = currentRigID,
|
||||
let entry: RigEntry = library.entries.first(where: { $0.id == id }) else {
|
||||
return !shoeGaze.boards.isEmpty
|
||||
}
|
||||
return shoeGaze.captureState() != entry.state
|
||||
}
|
||||
|
||||
/// Saves the current session over the loaded library entry, or prompts for a name when no entry
|
||||
/// is loaded (a new, never-saved rig).
|
||||
///
|
||||
/// - Parameter completion: Runs only after a successful save (e.g. clear the boards, or load the
|
||||
/// rig the user was switching to). Cancelling the name prompt cancels it too — no save, no
|
||||
/// follow-up.
|
||||
private func saveCurrentRig(then completion: @escaping () -> Void = { }) {
|
||||
guard let id: UUID = currentRigID,
|
||||
let existing: RigEntry = library.entries.first(where: { $0.id == id }) else {
|
||||
// No current entry — prompt for a name; the follow-up runs only on commit.
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "Save Rig As",
|
||||
initialText: currentRigName() ?? defaultNewRigName(),
|
||||
confirmLabel: "Save"
|
||||
) { name in
|
||||
persist(shoeGaze.captureEntry(name: name), then: completion)
|
||||
}
|
||||
return
|
||||
}
|
||||
persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion)
|
||||
}
|
||||
|
||||
/// Prompts for a name, then creates a brand-new empty rig (one empty board) and selects it.
|
||||
private func promptNewRig() {
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "New Rig",
|
||||
initialText: defaultNewRigName(),
|
||||
confirmLabel: "Create"
|
||||
) { name in
|
||||
createNewRig(named: name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts for a name and saves the current session as a new library entry (new id).
|
||||
private func promptSaveAs() {
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "Save Rig As",
|
||||
initialText: currentRigName() ?? defaultNewRigName(),
|
||||
confirmLabel: "Save"
|
||||
) { name in
|
||||
persist(shoeGaze.captureEntry(name: name))
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts for a name and duplicates `entry`, loading the copy as the current rig.
|
||||
private func promptDuplicate(_ entry: RigEntry) {
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "Duplicate Rig",
|
||||
initialText: "\(entry.name) copy",
|
||||
confirmLabel: "Duplicate"
|
||||
) { name in
|
||||
do {
|
||||
let copy: RigEntry = try library.duplicate(entry, newName: name)
|
||||
loadEntry(copy)
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] duplicate failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts for a new name and renames `entry` in the library.
|
||||
private func promptRename(_ entry: RigEntry) {
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "Rename Rig",
|
||||
initialText: entry.name,
|
||||
confirmLabel: "Rename"
|
||||
) { name in
|
||||
do { _ = try library.rename(entry, to: name) }
|
||||
catch { print("[ShoeGazeBuilderView] rename failed: \(error)") }
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes `entry` from the library. Clears the current-rig marker if it was the loaded rig.
|
||||
private func deleteEntry(_ entry: RigEntry) {
|
||||
do {
|
||||
try library.delete(entry)
|
||||
if currentRigID == entry.id { currentRigID = nil }
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] delete failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Erases the entire library and clears the current-rig marker.
|
||||
private func eraseAllRigs() {
|
||||
do {
|
||||
try library.eraseAll()
|
||||
currentRigID = nil
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] eraseAll failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Captures the whole library into the `.shoegaze` document exporter.
|
||||
private func exportArchiveAction() {
|
||||
do {
|
||||
exportDocument = RigFileDocument(data: try library.exportDocumentData())
|
||||
showExporter = true
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] exportDocumentData failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Imports an archive (or legacy single-rig file) into the library.
|
||||
private func handleArchiveImport(_ result: Result<URL, Error>) {
|
||||
switch result {
|
||||
case .success(let url):
|
||||
// A `.fileImporter` URL is security-scoped; access must be started to read it.
|
||||
let scoped: Bool = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
do {
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
_ = try library.importArchive(from: data)
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] archive import failed: \(error)")
|
||||
}
|
||||
case .failure(let error):
|
||||
print("[ShoeGazeBuilderView] archive import pick failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Persists `entry`, marks it current, and runs `completion` (e.g. the "Save & Clear" clear).
|
||||
private func persist(
|
||||
_ entry: RigEntry,
|
||||
then completion: () -> Void = { }
|
||||
) {
|
||||
do {
|
||||
try library.save(entry)
|
||||
currentRigID = entry.id
|
||||
// Only run the follow-up (e.g. the "Save & Clear" clear) once the save succeeded —
|
||||
// otherwise a failed save would still wipe the boards, losing the rig.
|
||||
completion()
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] save failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a fresh single-board rig, saves it under `name`, and makes it current.
|
||||
private func createNewRig(named name: String) {
|
||||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||||
if wasRunning { shoeGaze.engine.stop() }
|
||||
// Replace the working graph with a single empty board.
|
||||
for board: PedalBoard in Array(shoeGaze.boards) {
|
||||
shoeGaze.removeBoard(board)
|
||||
}
|
||||
do {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
board.label = "Board 1"
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] createNewRig seed failed: \(error)")
|
||||
}
|
||||
selectedBoardIndex = 0
|
||||
if wasRunning { try? shoeGaze.engine.start() }
|
||||
transportTick.toggle()
|
||||
persist(shoeGaze.captureEntry(name: name))
|
||||
}
|
||||
|
||||
/// The name of the currently loaded library entry, if any.
|
||||
private func currentRigName() -> String? {
|
||||
guard let id: UUID = currentRigID else { return nil }
|
||||
return library.entries.first(where: { $0.id == id })?.name
|
||||
}
|
||||
|
||||
/// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names.
|
||||
private func defaultNewRigName() -> String {
|
||||
let base: String = "Rig"
|
||||
let existing: Set<String> = Set(library.entries.map(\.name))
|
||||
var index: Int = library.entries.count + 1
|
||||
while existing.contains("\(base) \(index)") { index += 1 }
|
||||
return "\(base) \(index)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// UTType+ShoeGaze.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
public extension UTType {
|
||||
|
||||
/// The `.shoegaze` document type — a versioned JSON envelope carrying a shared rig or board.
|
||||
///
|
||||
/// Identifier `net.realizedsound.shoegaze`, conforming to `public.json` so the file stays
|
||||
/// text-readable and is recognised by tools that understand JSON. The hosting app must also
|
||||
/// declare this type in its `Info.plist` (`UTExportedTypeDeclarations` + `CFBundleDocumentTypes`)
|
||||
/// for the system to associate the `.shoegaze` extension with the app and offer it in Share /
|
||||
/// Open dialogs; this property mirrors that declaration so SwiftUI `fileExporter` / `fileImporter`
|
||||
/// and `ShareLink` can reference it in code.
|
||||
static let shoeGaze: UTType = UTType(exportedAs: "net.realizedsound.shoegaze", conformingTo: .json)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// AutoGranulatorPedalTests.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("AutoGranulatorPedal")
|
||||
struct AutoGranulatorPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (AutoGranulatorPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
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: 2)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: AutoGranulatorPedal = AutoGranulatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { pedal in pedal.minGrain = 0.01; pedal.maxGrain = 0.03 }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "auto granulator output was silent")
|
||||
}
|
||||
|
||||
@Test func responseSwitchChangesOutput() throws {
|
||||
let loudShort: [Float] = try render { pedal in pedal.minGrain = 0.008; pedal.maxGrain = 0.02; pedal.response = 0.0; pedal.mix = 1.0 }
|
||||
let loudLong: [Float] = try render { pedal in pedal.minGrain = 0.008; pedal.maxGrain = 0.02; pedal.response = 1.0; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(loudLong), "flipped-response granulator was silent")
|
||||
#expect(totalSSD(loudShort, loudLong) > 0, "flipping the response did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesKnobsAndResponseSwitch() throws {
|
||||
let pedal: AutoGranulatorPedal = AutoGranulatorPedal()
|
||||
#expect(pedal.effectKnobs.map { $0.label } == ["Min Grain", "Max Grain", "Overlap", "Spread"])
|
||||
#expect(pedal.effectSwitches.map { $0.label } == ["Response"])
|
||||
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Loud→Short", "Loud→Long"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesResponse() throws {
|
||||
let pedal: AutoGranulatorPedal = AutoGranulatorPedal()
|
||||
pedal.response = 1.0
|
||||
pedal.minGrain = 0.03
|
||||
let state: PedalState = pedal.captureState()
|
||||
|
||||
let restored: AutoGranulatorPedal = AutoGranulatorPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.response == 1.0)
|
||||
#expect(restored.minGrain == 0.03)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Auto Granulator")
|
||||
#expect(pedal is AutoGranulatorPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// BitReduceTests.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("BitReduce")
|
||||
struct BitReduceTests {
|
||||
|
||||
/// Minimal synth: a constant DC value through a `BitReduce`, written to a mono bus.
|
||||
private final class CrushSynth: SynthesizerBase {
|
||||
private let value: Double
|
||||
private let bits: Double
|
||||
private let outBus: Int
|
||||
|
||||
init(value: Double, bits: Double, outBus: Int) {
|
||||
self.value = value
|
||||
self.bits = bits
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: outBus, source: BitReduce(input: value, bits: bits))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(value: Double, bits: Double) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: CrushSynth = CrushSynth(value: value, bits: bits, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
// Asserts are scale-independent: the test harness applies a fixed output gain/pan, so compare
|
||||
// quantisation *levels* rather than absolute amplitudes.
|
||||
|
||||
@Test func snapsToDiscreteLevels() throws {
|
||||
// 8 bits over [-1, 1]: step = 2/256, inverseStep = 128.
|
||||
// 0.896 → round(114.688) = 115; 0.901 → round(115.328) = 115 (same level);
|
||||
// 0.910 → round(116.48) = 116 (different level).
|
||||
let sameA: [Float] = try render(value: 0.896, bits: 8.0)
|
||||
let sameB: [Float] = try render(value: 0.901, bits: 8.0)
|
||||
let other: [Float] = try render(value: 0.910, bits: 8.0)
|
||||
#expect(sameA[200] == sameB[200], "values in the same 8-bit level should quantise identically")
|
||||
#expect(sameA[200] != other[200], "values in different 8-bit levels should differ")
|
||||
}
|
||||
|
||||
@Test func oneBitFloorsSmallValuesToZero() throws {
|
||||
// 1 bit: levels = 2, step = 1.0; round(0.4) = 0 → exactly zero regardless of output gain.
|
||||
let samples: [Float] = try render(value: 0.4, bits: 1.0)
|
||||
#expect(abs(samples[200]) < 1e-5, "1-bit quantiser should floor 0.4 to 0")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// BitcrusherPedalTests.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("BitcrusherPedal")
|
||||
struct BitcrusherPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (BitcrusherPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
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: BitcrusherPedal = BitcrusherPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "bitcrusher output was silent")
|
||||
}
|
||||
|
||||
@Test func crushChangesOutput() throws {
|
||||
let light: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
|
||||
let heavy: [Float] = try render { pedal in pedal.crush = 32.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(heavy), "decimated bitcrusher was silent")
|
||||
#expect(totalSSD(light, heavy) > 0, "changing crush did not change the output")
|
||||
}
|
||||
|
||||
@Test func bitsChangeOutput() throws {
|
||||
let clean: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
|
||||
let crushed: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 3.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(crushed), "bit-reduced output was silent")
|
||||
#expect(totalSSD(clean, crushed) > 0, "changing bit depth did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesCrushBitsToneKnobs() throws {
|
||||
let pedal: BitcrusherPedal = BitcrusherPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Crush", "Bits", "Tone"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Bitcrusher")
|
||||
#expect(pedal is BitcrusherPedal)
|
||||
}
|
||||
}
|
||||
@@ -582,4 +582,54 @@ struct BoardEditAPITests {
|
||||
let samples: [Float] = try render(engine2, url2)
|
||||
#expect(hasNonSilentOutput(samples), "loaded edited rig should render audio")
|
||||
}
|
||||
|
||||
// MARK: - Cross-lane move (drag a pedal into a region lane)
|
||||
|
||||
@Test func moveMainPedalIntoStereoUnzipLanePreservingParams() throws {
|
||||
// Ping-Pong (stereo) then Overdrive on the main chain; unzip after Ping-Pong.
|
||||
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
|
||||
try makeRig(pedals: ["Ping-Pong", "Overdrive"])
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 0, in: board)
|
||||
// Tweak the live Overdrive so we can verify its params survive the move.
|
||||
let overdrive: OverdrivePedal? = live.pedals.compactMap { $0 as? OverdrivePedal }.first
|
||||
overdrive?.drive = 11.0
|
||||
|
||||
// Move the Overdrive (main linear index 1) into the unzip's left lane (region segment 1).
|
||||
live = try sg.movePedal(from: .main, at: 1, to: .left(region: 1), in: live)
|
||||
|
||||
#expect(names(live) == ["Ping-Pong"], "Overdrive should leave the main chain")
|
||||
guard let state: StereoUnzipState = unzipState(live) else {
|
||||
Issue.record("No stereo unzip segment")
|
||||
return
|
||||
}
|
||||
#expect(state.left.map { $0.type } == ["Overdrive"], "Overdrive should land in the left lane")
|
||||
#expect(state.left.first?.knobValues.first == 11.0, "Drive param should survive the move")
|
||||
|
||||
let samples: [Float] = try render(engine, url)
|
||||
#expect(hasNonSilentOutput(samples), "board renders after the cross-lane move")
|
||||
}
|
||||
|
||||
@Test func moveMainPedalBeforeUnzipRegionAdjustsIndex() throws {
|
||||
// Overdrive (mono) then Ping-Pong (stereo); unzip after Ping-Pong. Moving the Overdrive —
|
||||
// which sits BEFORE the unzip region — exercises the destination-index adjustment.
|
||||
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
|
||||
try makeRig(pedals: ["Overdrive", "Ping-Pong"])
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 1, in: board)
|
||||
// Unzip is top-level segment 2; Overdrive is main linear index 0 (top-level segment 0).
|
||||
live = try sg.movePedal(from: .main, at: 0, to: .left(region: 2), in: live)
|
||||
|
||||
#expect(names(live) == ["Ping-Pong"], "Overdrive should leave the main chain")
|
||||
guard let state: StereoUnzipState = unzipState(live) else {
|
||||
Issue.record("No stereo unzip segment")
|
||||
return
|
||||
}
|
||||
#expect(state.left.map { $0.type } == ["Overdrive"], "Overdrive should land in the left lane")
|
||||
|
||||
let samples: [Float] = try render(engine, url)
|
||||
#expect(hasNonSilentOutput(samples), "board renders after the index-adjusted move")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// DistortionPedalTests.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("DistortionPedal")
|
||||
struct DistortionPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (DistortionPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
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: DistortionPedal = DistortionPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 2048
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "distortion output was silent")
|
||||
}
|
||||
|
||||
@Test func driveChangesOutput() throws {
|
||||
let low: [Float] = try render { pedal in pedal.drive = 2.0 }
|
||||
let high: [Float] = try render { pedal in pedal.drive = 45.0 }
|
||||
#expect(hasNonSilentOutput(high), "high-drive distortion was silent")
|
||||
#expect(windowedSSD(low, high) > 0, "changing drive did not change the output")
|
||||
}
|
||||
|
||||
@Test func toneChangesOutput() throws {
|
||||
let dark: [Float] = try render { pedal in pedal.drive = 30.0; pedal.tone = 700.0 }
|
||||
let bright: [Float] = try render { pedal in pedal.drive = 30.0; pedal.tone = 5500.0 }
|
||||
#expect(hasNonSilentOutput(bright), "bright distortion was silent")
|
||||
#expect(windowedSSD(dark, bright) > 0, "changing tone did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesDriveToneKnobs() throws {
|
||||
let pedal: DistortionPedal = DistortionPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Drive", "Tone"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Distortion")
|
||||
#expect(pedal is DistortionPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// FlangerPedalTests.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("FlangerPedal")
|
||||
struct FlangerPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (FlangerPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
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: FlangerPedal = FlangerPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 2048
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "flanger output was silent")
|
||||
}
|
||||
|
||||
@Test func depthChangesOutput() throws {
|
||||
let shallow: [Float] = try render { pedal in pedal.depth = 0.1; pedal.mix = 1.0 }
|
||||
let deep: [Float] = try render { pedal in pedal.depth = 0.95; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(deep), "deep flanger was silent")
|
||||
#expect(windowedSSD(shallow, deep) > 0, "changing depth did not change the output")
|
||||
}
|
||||
|
||||
@Test func feedbackChangesOutput() throws {
|
||||
let dry: [Float] = try render { pedal in pedal.feedback = 0.0; pedal.mix = 1.0 }
|
||||
let resonant: [Float] = try render { pedal in pedal.feedback = 0.85; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(resonant), "resonant flanger was silent")
|
||||
#expect(windowedSSD(dry, resonant) > 0, "changing feedback did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesRateDepthFeedbackKnobs() throws {
|
||||
let pedal: FlangerPedal = FlangerPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Rate", "Depth", "Feedback"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Flanger")
|
||||
#expect(pedal is FlangerPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// GranulatorPedalTests.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("GranulatorPedal")
|
||||
struct GranulatorPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (GranulatorPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
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: 2)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: GranulatorPedal = GranulatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { pedal in pedal.grain = 0.02 }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "granulator output was silent")
|
||||
}
|
||||
|
||||
@Test func spreadChangesOutput() throws {
|
||||
let mono: [Float] = try render { pedal in pedal.grain = 0.01; pedal.spread = 0.0; pedal.mix = 1.0 }
|
||||
let wide: [Float] = try render { pedal in pedal.grain = 0.01; pedal.spread = 1.0; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(wide), "spread granulator was silent")
|
||||
#expect(totalSSD(mono, wide) > 0, "changing spread did not change the channel output")
|
||||
}
|
||||
|
||||
@Test func grainSizeChangesOutput() throws {
|
||||
let small: [Float] = try render { pedal in pedal.grain = 0.01; pedal.mix = 1.0 }
|
||||
let large: [Float] = try render { pedal in pedal.grain = 0.04; pedal.mix = 1.0 }
|
||||
#expect(totalSSD(small, large) > 0, "changing grain size did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesGrainOverlapSpreadKnobs() throws {
|
||||
let pedal: GranulatorPedal = GranulatorPedal()
|
||||
#expect(pedal.effectKnobs.map { $0.label } == ["Grain", "Overlap", "Spread"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Granulator")
|
||||
#expect(pedal is GranulatorPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// HarmonizerPedalTests.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("HarmonizerPedal")
|
||||
struct HarmonizerPedalTests {
|
||||
|
||||
/// Renders the pedal through an NRT engine with the given configuration and returns the output.
|
||||
private func render(
|
||||
configure: (HarmonizerPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.3
|
||||
let numAudioBuses: Int = 64
|
||||
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: HarmonizerPedal = HarmonizerPedal(
|
||||
inputBus: srcBus.index,
|
||||
outputBus: dstBus.index
|
||||
)
|
||||
configure(pedal)
|
||||
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)
|
||||
}
|
||||
|
||||
/// Sum of squared differences over a stable window of two renders.
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 4096
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { pedal in
|
||||
pedal.direct = 1.0
|
||||
pedal.voice1Level = 0.6
|
||||
pedal.voice2Level = 0.5
|
||||
}
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "harmonizer output was silent")
|
||||
}
|
||||
|
||||
@Test func changingVoiceIntervalChangesOutput() throws {
|
||||
let third: [Float] = try render { pedal in
|
||||
pedal.direct = 0.0
|
||||
pedal.voice1Level = 1.0
|
||||
pedal.voice2Level = 0.0
|
||||
pedal.voice1 = 3.0 // minor third up
|
||||
}
|
||||
let fifth: [Float] = try render { pedal in
|
||||
pedal.direct = 0.0
|
||||
pedal.voice1Level = 1.0
|
||||
pedal.voice2Level = 0.0
|
||||
pedal.voice1 = 7.0 // perfect fifth up
|
||||
}
|
||||
#expect(hasNonSilentOutput(third), "minor-third voice was silent")
|
||||
#expect(hasNonSilentOutput(fifth), "fifth voice was silent")
|
||||
#expect(windowedSSD(third, fifth) > 0, "changing the interval did not change the output")
|
||||
}
|
||||
|
||||
@Test func harmonyVoicesDifferFromDirectOnly() throws {
|
||||
let directOnly: [Float] = try render { pedal in
|
||||
pedal.direct = 1.0
|
||||
pedal.voice1Level = 0.0
|
||||
pedal.voice2Level = 0.0
|
||||
}
|
||||
let withVoices: [Float] = try render { pedal in
|
||||
pedal.direct = 1.0
|
||||
pedal.voice1Level = 1.0
|
||||
pedal.voice2Level = 1.0
|
||||
}
|
||||
#expect(hasNonSilentOutput(directOnly), "direct-only render was silent")
|
||||
#expect(windowedSSD(directOnly, withVoices) > 0, "adding harmony voices did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesLevelKnobs() throws {
|
||||
let pedal: HarmonizerPedal = HarmonizerPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["V1 Level", "V2 Level", "Direct"])
|
||||
}
|
||||
|
||||
@Test func exposesTwoIntervalSelectors() throws {
|
||||
let pedal: HarmonizerPedal = HarmonizerPedal()
|
||||
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
|
||||
#expect(selectors.map { $0.label } == ["Voice 1", "Voice 2"])
|
||||
// Both minor- and major-thirds above and below must be available.
|
||||
let titles: [String] = selectors.first?.stops.map { $0.title } ?? []
|
||||
#expect(titles.contains("m3"))
|
||||
#expect(titles.contains("M3"))
|
||||
#expect(titles.contains("-m3"))
|
||||
#expect(titles.contains("-M3"))
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesIntervalsAndLevels() throws {
|
||||
let pedal: HarmonizerPedal = HarmonizerPedal()
|
||||
pedal.voice1 = -3.0
|
||||
pedal.voice2 = 12.0
|
||||
pedal.voice1Level = 0.3
|
||||
|
||||
let state: PedalState = pedal.captureState()
|
||||
#expect(state.selectorValues == [-3.0, 12.0])
|
||||
|
||||
let restored: HarmonizerPedal = HarmonizerPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.voice1 == -3.0)
|
||||
#expect(restored.voice2 == 12.0)
|
||||
#expect(restored.voice1Level == 0.3)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Harmonizer")
|
||||
#expect(pedal is HarmonizerPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// ReverseDelayPedalTests.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("ReverseDelayPedal")
|
||||
struct ReverseDelayPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (ReverseDelayPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.6
|
||||
let numAudioBuses: Int = 64
|
||||
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: ReverseDelayPedal = ReverseDelayPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
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)
|
||||
}
|
||||
|
||||
/// Sum of squared differences over the full overlapping length. Feedback only diverges once a
|
||||
/// fed-back segment is replayed (the third segment), so a narrow window can miss it; comparing
|
||||
/// the whole readable buffer (the reader returns the first 4096 frames) is robust.
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
// Short segment so reversed playback begins within the reader's 4096-frame window.
|
||||
let samples: [Float] = try render { pedal in pedal.time = 0.03; pedal.mix = 1.0 }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "reverse delay output was silent")
|
||||
}
|
||||
|
||||
@Test func feedbackChangesOutput() throws {
|
||||
let dry: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.0; pedal.mix = 1.0 }
|
||||
let trails: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.6; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(trails), "feedback reverse delay was silent")
|
||||
#expect(totalSSD(dry, trails) > 0, "changing feedback did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesTimeFeedbackKnobs() throws {
|
||||
let pedal: ReverseDelayPedal = ReverseDelayPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Time", "Feedback"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesKnobs() throws {
|
||||
let pedal: ReverseDelayPedal = ReverseDelayPedal()
|
||||
pedal.time = 1.2
|
||||
pedal.feedback = 0.7
|
||||
let state: PedalState = pedal.captureState()
|
||||
|
||||
let restored: ReverseDelayPedal = ReverseDelayPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.time == 1.2)
|
||||
#expect(restored.feedback == 0.7)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Reverse Delay")
|
||||
#expect(pedal is ReverseDelayPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// ReverseDelayTests.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("ReverseDelay")
|
||||
struct ReverseDelayTests {
|
||||
|
||||
/// Minimal synth: a DC value through a `ReverseDelay`, written to a mono bus.
|
||||
private final class ReverseSynth: SynthesizerBase {
|
||||
private let value: Double
|
||||
private let delay: Double
|
||||
private let outBus: Int
|
||||
|
||||
init(value: Double, delay: Double, outBus: Int) {
|
||||
self.value = value
|
||||
self.delay = delay
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
output(bus: outBus, source: ReverseDelay(
|
||||
input: value,
|
||||
maxDelay: 0.1,
|
||||
delay: delay,
|
||||
feedback: 0.0,
|
||||
sampleRate: 44100.0
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(value: Double, delay: Double) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: ReverseSynth = ReverseSynth(value: value, delay: delay, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: 44100.0)
|
||||
}
|
||||
|
||||
private func left(_ samples: [Float], _ frame: Int) -> Float {
|
||||
samples[frame * 2]
|
||||
}
|
||||
|
||||
@Test func firstSegmentIsSilentThenReplaysRecordedValue() throws {
|
||||
// delay 0.02 s @ 44100 = 882-frame segments. Segment 1 [0, 882) plays the still-empty
|
||||
// buffer (silence); segment 2 [882, 1764) reverses the recorded DC. Asserts are
|
||||
// scale-independent (the harness applies a fixed output gain/pan): check silence vs.
|
||||
// non-silent, and that the replayed DC is flat (reverse of a constant is the same constant).
|
||||
let samples: [Float] = try render(value: 0.5, delay: 0.02)
|
||||
|
||||
// Mid segment 1: still recording, play buffer empty → silent.
|
||||
#expect(abs(left(samples, 441)) < 1e-3, "first segment should be silent (nothing recorded yet)")
|
||||
|
||||
// Segment 2, clear of the edge fades → non-silent and constant (reversed DC).
|
||||
let a: Float = left(samples, 1200)
|
||||
let b: Float = left(samples, 1400)
|
||||
#expect(abs(a) > 1e-2, "second segment should replay the recorded value (non-silent)")
|
||||
#expect(abs(a - b) < 1e-3, "reversed DC should be flat across the segment")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// RigArchiveTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@Suite("RigArchive")
|
||||
struct RigArchiveTests {
|
||||
|
||||
private func makeEntry(_ name: String) -> RigEntry {
|
||||
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
|
||||
}
|
||||
|
||||
@Test func jsonRoundTripIsLossless() throws {
|
||||
let archive: RigArchive = RigArchive(rigs: [makeEntry("A"), makeEntry("B")])
|
||||
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
|
||||
let data: Data = try encoder.encode(archive)
|
||||
let decoded: RigArchive = try decoder.decode(RigArchive.self, from: data)
|
||||
#expect(decoded == archive)
|
||||
#expect(decoded.version == rigArchiveFormatVersion)
|
||||
#expect(decoded.rigs.count == 2)
|
||||
}
|
||||
|
||||
@Test func emptyArchiveRoundTrips() throws {
|
||||
let archive: RigArchive = RigArchive(rigs: [])
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
let data: Data = try encoder.encode(archive)
|
||||
let decoded: RigArchive = try decoder.decode(RigArchive.self, from: data)
|
||||
#expect(decoded.rigs.isEmpty)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// RigEntryTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@Suite("RigEntry")
|
||||
struct RigEntryTests {
|
||||
|
||||
/// A minimal two-board rig state for snapshotting without an engine.
|
||||
private func makeState() -> ShoeGazeState {
|
||||
let board: BoardState = BoardState(label: "Lead", segments: [])
|
||||
let other: BoardState = BoardState(label: "Clean", segments: [])
|
||||
return ShoeGazeState(boards: [board, other])
|
||||
}
|
||||
|
||||
@Test func jsonRoundTripIsLossless() throws {
|
||||
let entry: RigEntry = RigEntry(name: "Ambient Wash", state: makeState())
|
||||
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
|
||||
let data: Data = try encoder.encode(entry)
|
||||
let decoded: RigEntry = try decoder.decode(RigEntry.self, from: data)
|
||||
#expect(decoded == entry)
|
||||
}
|
||||
|
||||
@Test func savedAtIsRoundedToWholeSeconds() {
|
||||
let fractional: Date = Date(timeIntervalSince1970: 1_700_000_000.789)
|
||||
let entry: RigEntry = RigEntry(name: "x", savedAt: fractional, state: makeState())
|
||||
#expect(entry.savedAt.timeIntervalSince1970 == 1_700_000_001)
|
||||
}
|
||||
|
||||
@Test func duplicatedGetsNewIdSameState() {
|
||||
let original: RigEntry = RigEntry(name: "A", state: makeState())
|
||||
let copy: RigEntry = original.duplicated(name: "A copy")
|
||||
#expect(copy.id != original.id)
|
||||
#expect(copy.name == "A copy")
|
||||
#expect(copy.state == original.state)
|
||||
}
|
||||
|
||||
@Test func renamedKeepsIdSameState() {
|
||||
let original: RigEntry = RigEntry(name: "A", state: makeState())
|
||||
let renamed: RigEntry = original.renamed(to: "B")
|
||||
#expect(renamed.id == original.id)
|
||||
#expect(renamed.name == "B")
|
||||
#expect(renamed.state == original.state)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// RigLibraryStoreTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("RigLibraryStore")
|
||||
struct RigLibraryStoreTests {
|
||||
|
||||
/// A fresh, unique temp directory for an isolated, local (non-iCloud) store.
|
||||
private func makeTempDirectory() -> URL {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("RigLibraryTests-\(UUID().uuidString)", isDirectory: true)
|
||||
return url
|
||||
}
|
||||
|
||||
private func makeStore() async -> (RigLibraryStore, URL) {
|
||||
let dir: URL = makeTempDirectory()
|
||||
let store: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||
await store.start()
|
||||
return (store, dir)
|
||||
}
|
||||
|
||||
private func makeEntry(_ name: String) -> RigEntry {
|
||||
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
|
||||
}
|
||||
|
||||
@Test func saveAddsEntryAndReloadsAcrossInstances() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
try store.save(makeEntry("Ambient"))
|
||||
try store.save(makeEntry("Crunch"))
|
||||
#expect(store.entries.count == 2)
|
||||
// Sorted by name, case-insensitive.
|
||||
#expect(store.entries.map(\.name) == ["Ambient", "Crunch"])
|
||||
|
||||
store.flushPendingWrites()
|
||||
// A fresh store over the same directory sees the persisted files.
|
||||
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||
await reopened.start()
|
||||
#expect(reopened.entries.count == 2)
|
||||
#expect(reopened.entries.map(\.name) == ["Ambient", "Crunch"])
|
||||
}
|
||||
|
||||
@Test func saveSameIdReplacesInPlace() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
let entry: RigEntry = makeEntry("Original")
|
||||
try store.save(entry)
|
||||
// Overwrite under the same id with a new name — no duplicate file should remain.
|
||||
try store.save(entry.renamed(to: "Renamed"))
|
||||
|
||||
#expect(store.entries.count == 1)
|
||||
#expect(store.entries.first?.name == "Renamed")
|
||||
|
||||
store.flushPendingWrites()
|
||||
let files: [URL] = try FileManager.default.contentsOfDirectory(
|
||||
at: dir, includingPropertiesForKeys: nil
|
||||
).filter { $0.pathExtension == "json" }
|
||||
#expect(files.count == 1, "rename must not leave the old-name file behind")
|
||||
}
|
||||
|
||||
@Test func renameKeepsIdChangesName() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
let entry: RigEntry = makeEntry("Before")
|
||||
try store.save(entry)
|
||||
let renamed: RigEntry = try store.rename(entry, to: "After")
|
||||
#expect(renamed.id == entry.id)
|
||||
#expect(store.entries.map(\.name) == ["After"])
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func duplicateCreatesIndependentEntry() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
let entry: RigEntry = makeEntry("Base")
|
||||
try store.save(entry)
|
||||
let copy: RigEntry = try store.duplicate(entry, newName: "Base 2")
|
||||
#expect(copy.id != entry.id)
|
||||
#expect(store.entries.count == 2)
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func deleteRemovesFileAndEntry() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
let entry: RigEntry = makeEntry("Doomed")
|
||||
try store.save(entry)
|
||||
try store.delete(entry)
|
||||
#expect(store.entries.isEmpty)
|
||||
|
||||
store.flushPendingWrites()
|
||||
let files: [URL] = try FileManager.default.contentsOfDirectory(
|
||||
at: dir, includingPropertiesForKeys: nil
|
||||
).filter { $0.pathExtension == "json" }
|
||||
#expect(files.isEmpty)
|
||||
}
|
||||
|
||||
@Test func eraseAllClearsLibrary() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
try store.save(makeEntry("A"))
|
||||
try store.save(makeEntry("B"))
|
||||
try store.save(makeEntry("C"))
|
||||
try store.eraseAll()
|
||||
#expect(store.entries.isEmpty)
|
||||
|
||||
store.flushPendingWrites()
|
||||
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||
await reopened.start()
|
||||
#expect(reopened.entries.isEmpty)
|
||||
}
|
||||
|
||||
@Test func exportThenImportRoundTrips() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
try store.save(makeEntry("One"))
|
||||
try store.save(makeEntry("Two"))
|
||||
let archiveData: Data = try store.exportArchiveData()
|
||||
|
||||
// Import into a fresh, empty store.
|
||||
let (other, otherDir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: otherDir) }
|
||||
let added: Int = try other.importArchive(from: archiveData)
|
||||
#expect(added == 2)
|
||||
#expect(other.entries.map(\.name) == ["One", "Two"])
|
||||
store.flushPendingWrites()
|
||||
other.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func importColludingIdGetsFreshId() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
let entry: RigEntry = makeEntry("Shared")
|
||||
try store.save(entry)
|
||||
|
||||
// An archive carrying the SAME id must not overwrite the existing rig on import.
|
||||
// Encode with the on-disk strategy (.secondsSince1970) so dates survive the import decoder.
|
||||
let archive: RigArchive = RigArchive(rigs: [entry])
|
||||
let data: Data = try ShoeGazeDocument.makeEncoder().encode(archive)
|
||||
let added: Int = try store.importArchive(from: data)
|
||||
#expect(added == 1)
|
||||
#expect(store.entries.count == 2, "colliding id should be imported as a new entry")
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func importLegacySingleRigFile() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
// A legacy file is a bare ShoeGazeState (no `rigs` array).
|
||||
let legacyState: ShoeGazeState = ShoeGazeState(boards: [BoardState(label: "Legacy", segments: [])])
|
||||
let data: Data = try ShoeGazeDocument.makeEncoder().encode(legacyState)
|
||||
let added: Int = try store.importArchive(from: data, legacyRigName: "Recovered")
|
||||
#expect(added == 1)
|
||||
#expect(store.entries.first?.name == "Recovered")
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func exportDocumentThenImportRoundTrips() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
try store.save(makeEntry("One"))
|
||||
try store.save(makeEntry("Two"))
|
||||
// The user-facing export is a `.shoegaze` ShoeGazeDocument envelope.
|
||||
let documentData: Data = try store.exportDocumentData()
|
||||
#expect(try ShoeGazeDocument.decoded(from: documentData).rigEntries?.count == 2)
|
||||
|
||||
let (other, otherDir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: otherDir) }
|
||||
let added: Int = try other.importArchive(from: documentData)
|
||||
#expect(added == 2)
|
||||
#expect(other.entries.map(\.name) == ["One", "Two"])
|
||||
store.flushPendingWrites()
|
||||
other.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func importBoardDocumentAddsNoRigs() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||
defer { try? FileManager.default.removeItem(at: dir) }
|
||||
|
||||
// A board-carrying `.shoegaze` document is valid but contributes no library rigs.
|
||||
let boardDocument: ShoeGazeDocument =
|
||||
ShoeGazeDocument(board: BoardVersion(name: "Lead", state: BoardState(label: "Lead", segments: [])))
|
||||
let added: Int = try store.importArchive(from: try boardDocument.data())
|
||||
#expect(added == 0)
|
||||
#expect(store.entries.isEmpty)
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// RotaryPedalTests.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("RotaryPedal")
|
||||
struct RotaryPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (RotaryPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.3
|
||||
let numAudioBuses: Int = 64
|
||||
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: 2)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: RotaryPedal = RotaryPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 4096
|
||||
let windowSize: Int = 4096
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "rotary output was silent")
|
||||
}
|
||||
|
||||
@Test func speedChangesOutput() throws {
|
||||
let chorale: [Float] = try render { pedal in pedal.speed = 0.0; pedal.accel = 0.05 }
|
||||
let tremolo: [Float] = try render { pedal in pedal.speed = 1.0; pedal.accel = 0.05 }
|
||||
#expect(hasNonSilentOutput(tremolo), "fast rotary was silent")
|
||||
#expect(windowedSSD(chorale, tremolo) > 0, "changing speed did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesDepthAccelKnobsAndSpeedSwitch() throws {
|
||||
let pedal: RotaryPedal = RotaryPedal()
|
||||
#expect(pedal.effectKnobs.map { $0.label } == ["Depth", "Accel"])
|
||||
#expect(pedal.effectSwitches.map { $0.label } == ["Speed"])
|
||||
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Chorale", "Tremolo"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesSpeed() throws {
|
||||
let pedal: RotaryPedal = RotaryPedal()
|
||||
pedal.speed = 1.0
|
||||
pedal.depth = 0.4
|
||||
let state: PedalState = pedal.captureState()
|
||||
|
||||
let restored: RotaryPedal = RotaryPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.speed == 1.0)
|
||||
#expect(restored.depth == 0.4)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Rotary")
|
||||
#expect(pedal is RotaryPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
// SampleRateDecimateTests.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("SampleRateDecimate")
|
||||
struct SampleRateDecimateTests {
|
||||
|
||||
/// Minimal synth: a sine through a `SampleRateDecimate`, written to a mono bus.
|
||||
private final class DecimateSynth: SynthesizerBase {
|
||||
private let freq: Double
|
||||
private let factor: Double
|
||||
private let outBus: Int
|
||||
|
||||
init(freq: Double, factor: Double, outBus: Int) {
|
||||
self.freq = freq
|
||||
self.factor = factor
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
output(bus: outBus, source: SampleRateDecimate(input: osc, downsample: factor))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(freq: Double, factor: Double) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: DecimateSynth = DecimateSynth(freq: freq, factor: factor, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
/// Left-channel frame `i` (interleaved stereo).
|
||||
private func left(_ samples: [Float], _ frame: Int) -> Float {
|
||||
samples[frame * 2]
|
||||
}
|
||||
|
||||
@Test func holdsEachSampleForTheFactor() throws {
|
||||
// Factor 4: frames latch at 0, 4, 8, … and hold for four output samples each.
|
||||
let samples: [Float] = try render(freq: 2000.0, factor: 4.0)
|
||||
// Group [8, 11] holds the value latched at frame 8 (a non-zero point on the sine).
|
||||
#expect(left(samples, 8) == left(samples, 9))
|
||||
#expect(left(samples, 8) == left(samples, 10))
|
||||
#expect(left(samples, 8) == left(samples, 11))
|
||||
// The next group latches a fresh value.
|
||||
#expect(left(samples, 8) != left(samples, 12), "decimator did not re-latch at the group boundary")
|
||||
}
|
||||
|
||||
@Test func factorOneIsTransparent() throws {
|
||||
let samples: [Float] = try render(freq: 2000.0, factor: 1.0)
|
||||
// No two adjacent samples forced equal — a moving sine should differ frame-to-frame.
|
||||
#expect(left(samples, 8) != left(samples, 9), "factor 1 should pass the signal through unheld")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// ShimmerReverbPedalTests.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("ShimmerReverbPedal")
|
||||
struct ShimmerReverbPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (ShimmerReverbPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
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: ShimmerReverbPedal = ShimmerReverbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "shimmer reverb output was silent")
|
||||
}
|
||||
|
||||
@Test func shimmerChangesOutput() throws {
|
||||
let none: [Float] = try render { pedal in pedal.shimmer = 0.0; pedal.decay = 0.8; pedal.mix = 1.0 }
|
||||
let glassy: [Float] = try render { pedal in pedal.shimmer = 0.8; pedal.decay = 0.8; pedal.mix = 1.0 }
|
||||
#expect(hasNonSilentOutput(glassy), "shimmered reverb was silent")
|
||||
#expect(totalSSD(none, glassy) > 0, "changing shimmer did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesSizeDecayShimmerDampKnobs() throws {
|
||||
let pedal: ShimmerReverbPedal = ShimmerReverbPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Size", "Decay", "Shimmer", "Damp"])
|
||||
}
|
||||
|
||||
@Test func presetRoundTripPreservesKnobs() throws {
|
||||
let pedal: ShimmerReverbPedal = ShimmerReverbPedal()
|
||||
pedal.decay = 0.5
|
||||
pedal.shimmer = 0.7
|
||||
let state: PedalState = pedal.captureState()
|
||||
|
||||
let restored: ShimmerReverbPedal = ShimmerReverbPedal()
|
||||
restored.applyState(state)
|
||||
#expect(restored.decay == 0.5)
|
||||
#expect(restored.shimmer == 0.7)
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Shimmer Reverb")
|
||||
#expect(pedal is ShimmerReverbPedal)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
// ShimmerReverbTests.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("ShimmerReverb")
|
||||
struct ShimmerReverbTests {
|
||||
|
||||
/// Minimal synth: an input source through a `ShimmerReverb`, written to a mono bus.
|
||||
private final class ShimmerSynth: SynthesizerBase {
|
||||
private let oscFreq: Double?
|
||||
private let dc: Double
|
||||
private let size: Double
|
||||
private let decay: Double
|
||||
private let shimmer: Double
|
||||
private let outBus: Int
|
||||
|
||||
init(oscFreq: Double?, dc: Double, size: Double, decay: Double, shimmer: Double, outBus: Int) {
|
||||
self.oscFreq = oscFreq
|
||||
self.dc = dc
|
||||
self.size = size
|
||||
self.decay = decay
|
||||
self.shimmer = shimmer
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let source: any ValidGeneratorInput = oscFreq.map { OscSin.Audio(freq: $0) } ?? dc
|
||||
output(bus: outBus, source: ShimmerReverb(
|
||||
input: source,
|
||||
maxDelay: 0.12,
|
||||
size: size,
|
||||
decay: decay,
|
||||
shimmer: shimmer,
|
||||
damp: 0.4,
|
||||
sampleRate: 44100.0
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(
|
||||
oscFreq: Double?,
|
||||
dc: Double,
|
||||
size: Double = 0.05,
|
||||
decay: Double,
|
||||
shimmer: Double
|
||||
) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: ShimmerSynth = ShimmerSynth(
|
||||
oscFreq: oscFreq, dc: dc, size: size, decay: decay, shimmer: shimmer, outBus: dstBus.index
|
||||
)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: 44100.0)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func silentInputProducesSilence() throws {
|
||||
// No input energy → the feedback loop has nothing to sustain → output stays at zero.
|
||||
let samples: [Float] = try render(oscFreq: nil, dc: 0.0, decay: 0.9, shimmer: 0.8)
|
||||
#expect(!hasNonSilentOutput(samples), "shimmer reverb rang with no input")
|
||||
}
|
||||
|
||||
@Test func passesDCWithUnityGainAndLinearScaling() throws {
|
||||
// With decay = shimmer = damp = 0, the tank is just the input through two Schroeder
|
||||
// allpasses (unity at DC steady state) delayed by `size`. The output is therefore a fixed
|
||||
// gain (the harness output gain/pan) times the DC input — exactly linear. Compare two DC
|
||||
// levels at a settled frame so the harness scale cancels: the ratio must be 2.0.
|
||||
let high: [Float] = try render(oscFreq: nil, dc: 1.0, size: 0.01, decay: 0.0, shimmer: 0.0)
|
||||
let low: [Float] = try render(oscFreq: nil, dc: 0.5, size: 0.01, decay: 0.0, shimmer: 0.0)
|
||||
let frame: Int = 1500 // past the size delay + allpass settling, within the read window
|
||||
let h: Double = Double(high[frame * 2])
|
||||
let l: Double = Double(low[frame * 2])
|
||||
#expect(abs(h) > 1e-3, "settled DC output should be non-zero")
|
||||
#expect(abs(h / l - 2.0) < 0.01, "DC gain should be exactly linear (ratio 2.0)")
|
||||
}
|
||||
|
||||
@Test func nonFiniteControlsProduceFiniteOutput() throws {
|
||||
// NaN control reads must be sanitised (not trap the seconds→frames conversion nor poison
|
||||
// the feedback): the output must stay finite.
|
||||
let samples: [Float] = try render(
|
||||
oscFreq: 440.0, dc: 0.0, size: Double.nan, decay: Double.nan, shimmer: Double.nan
|
||||
)
|
||||
#expect(samples.allSatisfy { $0.isFinite }, "non-finite controls produced NaN/inf output")
|
||||
}
|
||||
|
||||
@Test func highShimmerDoesNotAccumulateDCOffset() throws {
|
||||
// The octave-up of DC is DC and the damping filter passes DC, so without a feedback
|
||||
// DC-blocker the loop DC gain (~decay + shimmer) exceeds 1 at high settings and builds an
|
||||
// offset. Aggressive small-tank settings iterate the loop many times within the read window.
|
||||
func meanDC(_ shimmer: Double) throws -> Double {
|
||||
let s: [Float] = try render(oscFreq: 440.0, dc: 0.0, size: 0.005, decay: 0.92, shimmer: shimmer)
|
||||
return s.reduce(0.0) { $0 + Double($1) } / Double(max(s.count, 1))
|
||||
}
|
||||
let noShimmer: Double = try meanDC(0.0)
|
||||
let maxShimmer: Double = try meanDC(0.85)
|
||||
#expect(abs(maxShimmer) < 0.015, "high shimmer accumulated a DC offset (mean = \(maxShimmer))")
|
||||
#expect(abs(maxShimmer - noShimmer) < 0.012, "shimmer added DC vs the no-shimmer baseline")
|
||||
}
|
||||
|
||||
@Test func decayChangesTheTail() throws {
|
||||
// Small tank so feedback round-trips compound within the reader's window; different decay
|
||||
// must change the tail (direction-agnostic — a tuned comb is not monotonic in level).
|
||||
let low: [Float] = try render(oscFreq: 440.0, dc: 0.0, size: 0.01, decay: 0.1, shimmer: 0.0)
|
||||
let high: [Float] = try render(oscFreq: 440.0, dc: 0.0, size: 0.01, decay: 0.9, shimmer: 0.0)
|
||||
#expect(hasNonSilentOutput(high), "decayed tail was silent")
|
||||
#expect(totalSSD(low, high) > 0, "changing decay did not change the tail")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// ShoeGazeDocumentTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@Suite("ShoeGazeDocument — share/export envelope")
|
||||
struct ShoeGazeDocumentTests {
|
||||
|
||||
/// A minimal two-board rig state for snapshotting without an engine.
|
||||
private func makeState(lead: String = "Lead") -> ShoeGazeState {
|
||||
let board: BoardState = BoardState(label: lead, segments: [])
|
||||
let other: BoardState = BoardState(label: "Clean", segments: [])
|
||||
return ShoeGazeState(boards: [board, other])
|
||||
}
|
||||
|
||||
private func makeEntry(name: String = "Ambient Wash") -> RigEntry {
|
||||
RigEntry(name: name, state: makeState())
|
||||
}
|
||||
|
||||
private func makeBoardVersion(name: String = "Lead Crunch") -> BoardVersion {
|
||||
BoardVersion(name: name, state: BoardState(label: "Lead", segments: []))
|
||||
}
|
||||
|
||||
// MARK: - Round trips
|
||||
|
||||
@Test func singleRigRoundTripIsLossless() throws {
|
||||
let entry: RigEntry = makeEntry()
|
||||
let document: ShoeGazeDocument = ShoeGazeDocument(rig: entry)
|
||||
|
||||
let data: Data = try document.data()
|
||||
let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
|
||||
|
||||
#expect(decoded == document)
|
||||
#expect(decoded.rigEntries == [entry])
|
||||
#expect(decoded.boardVersion == nil)
|
||||
#expect(decoded.version == shoeGazeDocumentFormatVersion)
|
||||
}
|
||||
|
||||
@Test func multiRigRoundTripIsLossless() throws {
|
||||
let entries: [RigEntry] = [makeEntry(name: "A"), makeEntry(name: "B")]
|
||||
let document: ShoeGazeDocument = ShoeGazeDocument(rigs: entries)
|
||||
|
||||
let data: Data = try document.data()
|
||||
let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
|
||||
|
||||
#expect(decoded == document)
|
||||
#expect(decoded.rigEntries == entries)
|
||||
}
|
||||
|
||||
@Test func boardRoundTripIsLossless() throws {
|
||||
let boardVersion: BoardVersion = makeBoardVersion()
|
||||
let document: ShoeGazeDocument = ShoeGazeDocument(board: boardVersion)
|
||||
|
||||
let data: Data = try document.data()
|
||||
let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
|
||||
|
||||
#expect(decoded == document)
|
||||
#expect(decoded.boardVersion == boardVersion)
|
||||
#expect(decoded.rigEntries == nil)
|
||||
}
|
||||
|
||||
// MARK: - Backward compatibility
|
||||
|
||||
@Test func decodesLegacyRigArchive() throws {
|
||||
let entries: [RigEntry] = [makeEntry(name: "Old A"), makeEntry(name: "Old B")]
|
||||
let archive: RigArchive = RigArchive(rigs: entries)
|
||||
|
||||
let encoder: JSONEncoder = ShoeGazeDocument.makeEncoder()
|
||||
let data: Data = try encoder.encode(archive)
|
||||
|
||||
let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
|
||||
#expect(decoded.rigEntries == entries)
|
||||
}
|
||||
|
||||
@Test func decodesLegacyBareState() throws {
|
||||
let state: ShoeGazeState = makeState()
|
||||
|
||||
let encoder: JSONEncoder = ShoeGazeDocument.makeEncoder()
|
||||
let data: Data = try encoder.encode(state)
|
||||
|
||||
let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data, legacyRigName: "Recovered")
|
||||
#expect(decoded.rigEntries?.count == 1)
|
||||
#expect(decoded.rigEntries?.first?.name == "Recovered")
|
||||
#expect(decoded.rigEntries?.first?.state == state)
|
||||
}
|
||||
|
||||
@Test func rejectsGarbage() {
|
||||
let data: Data = Data("not a shoegaze document".utf8)
|
||||
#expect(throws: (any Error).self) {
|
||||
_ = try ShoeGazeDocument.decoded(from: data)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - On-disk shape
|
||||
|
||||
@Test func envelopeCarriesKindDiscriminator() throws {
|
||||
let rigData: Data = try ShoeGazeDocument(rig: makeEntry()).data()
|
||||
let boardData: Data = try ShoeGazeDocument(board: makeBoardVersion()).data()
|
||||
|
||||
let rigJSON: String = String(decoding: rigData, as: UTF8.self)
|
||||
let boardJSON: String = String(decoding: boardData, as: UTF8.self)
|
||||
|
||||
#expect(rigJSON.contains("\"kind\" : \"rigs\""))
|
||||
#expect(boardJSON.contains("\"kind\" : \"board\""))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// StereoGranulatorTests.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("StereoGranulator")
|
||||
struct StereoGranulatorTests {
|
||||
|
||||
/// Minimal synth: a sine through a seeded `StereoGranulator`, routing one of its two channels
|
||||
/// to a mono bus so the offline render captures that channel's content.
|
||||
private final class GranSynth: SynthesizerBase {
|
||||
private let channel: Int
|
||||
private let spread: Double
|
||||
private let seed: UInt64
|
||||
private let outBus: Int
|
||||
|
||||
init(channel: Int, spread: Double, seed: UInt64, outBus: Int) {
|
||||
self.channel = channel
|
||||
self.spread = spread
|
||||
self.seed = seed
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: 220.0)
|
||||
let gran: StereoGranulator = StereoGranulator(
|
||||
input: osc,
|
||||
maxGrainSize: 0.2,
|
||||
grainSize: 0.05,
|
||||
overlap: 4.0,
|
||||
spread: spread,
|
||||
sampleRate: 44100.0,
|
||||
seed: seed
|
||||
)
|
||||
output(bus: outBus, source: channel == 0 ? gran.left : gran.right)
|
||||
}
|
||||
}
|
||||
|
||||
private func renderChannel(_ channel: Int, spread: Double, seed: UInt64) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: GranSynth = GranSynth(channel: channel, spread: spread, seed: seed, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: 44100.0)
|
||||
}
|
||||
|
||||
private func totalSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
zip(a, b).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func producesNonSilentOutput() throws {
|
||||
let samples: [Float] = try renderChannel(0, spread: 0.7, seed: 7)
|
||||
#expect(hasNonSilentOutput(samples), "granulator output was silent")
|
||||
}
|
||||
|
||||
@Test func deterministicForAFixedSeed() throws {
|
||||
let a: [Float] = try renderChannel(0, spread: 1.0, seed: 7)
|
||||
let b: [Float] = try renderChannel(0, spread: 1.0, seed: 7)
|
||||
#expect(totalSSD(a, b) == 0.0, "same seed must produce identical output")
|
||||
}
|
||||
|
||||
@Test func zeroSpreadCentersBothChannels() throws {
|
||||
// spread 0 → every grain pans to centre → left and right channels are identical.
|
||||
let left: [Float] = try renderChannel(0, spread: 0.0, seed: 7)
|
||||
let right: [Float] = try renderChannel(1, spread: 0.0, seed: 7)
|
||||
#expect(totalSSD(left, right) == 0.0, "zero spread should center grains (L == R)")
|
||||
}
|
||||
|
||||
@Test func fullSpreadSeparatesChannels() throws {
|
||||
// spread 1 → grains scatter → left and right differ.
|
||||
let left: [Float] = try renderChannel(0, spread: 1.0, seed: 7)
|
||||
let right: [Float] = try renderChannel(1, spread: 1.0, seed: 7)
|
||||
#expect(hasNonSilentOutput(left) && hasNonSilentOutput(right), "spread channels were silent")
|
||||
#expect(totalSSD(left, right) > 0.0, "full spread should separate L and R")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// VibratoPedalTests.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("VibratoPedal")
|
||||
struct VibratoPedalTests {
|
||||
|
||||
private func render(
|
||||
configure: (VibratoPedal) -> Void
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.2
|
||||
let numAudioBuses: Int = 64
|
||||
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: VibratoPedal = VibratoPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||
configure(pedal)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
|
||||
return readStereoCAF(url: url)
|
||||
}
|
||||
|
||||
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||
let skipSamples: Int = 2048
|
||||
let windowSize: Int = 2048
|
||||
guard a.count >= skipSamples + windowSize,
|
||||
b.count >= skipSamples + windowSize else { return 0.0 }
|
||||
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
|
||||
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
|
||||
return zip(aWindow, bWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
}
|
||||
|
||||
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||
let samples: [Float] = try render { _ in }
|
||||
#expect(!samples.isEmpty)
|
||||
#expect(hasNonSilentOutput(samples), "vibrato output was silent")
|
||||
}
|
||||
|
||||
@Test func depthChangesOutput() throws {
|
||||
let shallow: [Float] = try render { pedal in pedal.depth = 0.0006 }
|
||||
let deep: [Float] = try render { pedal in pedal.depth = 0.006 }
|
||||
#expect(hasNonSilentOutput(deep), "deep vibrato was silent")
|
||||
#expect(windowedSSD(shallow, deep) > 0, "changing depth did not change the output")
|
||||
}
|
||||
|
||||
@Test func exposesRateDepthKnobs() throws {
|
||||
let pedal: VibratoPedal = VibratoPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Rate", "Depth"])
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Vibrato")
|
||||
#expect(pedal is VibratoPedal)
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 884 KiB After Width: | Height: | Size: 401 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.3 MiB After Width: | Height: | Size: 559 KiB |
@@ -0,0 +1,193 @@
|
||||
# 1.2 New Pedals — Plan
|
||||
|
||||
Eight pedals targeted for 1.2 (Wah deferred — pending MIDI-control hardware). Grounded against the
|
||||
Lyrebird generators actually available. Each entry lists the signal path, the generators used,
|
||||
controls, channel kind, the per-pedal checklist (registry / `PedalType` / enclosure color / palette
|
||||
order / tests), and effort.
|
||||
|
||||
Effort legend: **S** = thin wrapper over existing generators; **M** = composite graph; **L** =
|
||||
needs a new RT-safe generator first.
|
||||
|
||||
Build order recommendation: Flanger → Vibrato → Distortion → Harmonizer → Rotary → Shimmer Reverb →
|
||||
Reverse Delay → Bitcrusher. (Cheap/whole-cloth-available first; new-generator pedals last.)
|
||||
|
||||
---
|
||||
|
||||
## 1. Flanger — **S**
|
||||
|
||||
Lyrebird already ships `Flanger.Audio(input:delayTime:depth:rate:feedback:mix:sampleRate:maxDelayTime:)`.
|
||||
Thin wrapper like `ModulationPedal`.
|
||||
|
||||
- **Path:** `dry → Flanger.Audio → wet` (base `mix`/`level`/bypass handle blend).
|
||||
- **Controls (knobs):** Rate (0.05–8 Hz), Depth (0–1), Feedback (0–0.95), Manual/center delay
|
||||
(0.001–0.01 s, optional). Mix inherited.
|
||||
- **Channel:** `.processor` (mono). A stereo `.widener` variant (two LFOs anti-phase, like
|
||||
`ChorusPedal`) is a nice follow-up but not required.
|
||||
- **Effort:** S.
|
||||
|
||||
## 2. Vibrato — **S**
|
||||
|
||||
Pitch wobble = a single swept delay line, fully wet (no dry blend). Mirrors `ChorusPedal.voice` but
|
||||
`initialMix = 1.0` and one voice.
|
||||
|
||||
- **Path:** `dry → DelayLine(delay: OscSin(rate, mul: depth, add: base)) → wet`, `mix = 1.0`.
|
||||
- **Controls:** Rate (0.1–8 Hz), Depth (0.0005–0.006 s). (Expose Depth as "Depth"; keep mix locked
|
||||
fully wet — vibrato is not a blend effect.)
|
||||
- **Channel:** `.processor`.
|
||||
- **Effort:** S. Distinct from Tremolo (amplitude) — document the difference in `summary`.
|
||||
|
||||
## 3. Distortion — **S**
|
||||
|
||||
Mid-gain clipper between Overdrive (soft) and Fuzz (extreme). Reuse the `Tanh.Audio` drive trick
|
||||
from `BassOctaverPedal`, plus a tone tilt and output clamp.
|
||||
|
||||
- **Path:** `dry → HPF(~80) → Tanh(mul: drive) → tone (RBJLowPass, freq from Tone knob) → Clip(-1,1)
|
||||
→ wet`. (Optionally `Waveshaper` with a fixed asymmetric table for more character.)
|
||||
- **Controls:** Drive (1–50), Tone (500–6000 Hz), Level (inherited). Mix default 1.0.
|
||||
- **Channel:** `.processor`.
|
||||
- **Effort:** S. Pick clipping flavor at impl: `Tanh` (smooth), `Clip` (hard), or `Fold` (octave-y).
|
||||
Recommend `Tanh` → `Clip` cascade.
|
||||
|
||||
## 4. Harmonizer — **M** (user priority)
|
||||
|
||||
Two pitch-shifted harmony voices at **fixed, user-picked interval ratios**, mixed under the dry
|
||||
signal. Uses `PitchShift.Audio` (granular, real-time, mono, `pitchRatio` clamped 0.25–4.0).
|
||||
|
||||
- **Path:**
|
||||
```
|
||||
dry ─┬───────────────────────────────── direct·directLevel
|
||||
├─ PitchShift(pitchRatio: r1) ····· × voice1Level
|
||||
└─ PitchShift(pitchRatio: r2) ····· × voice2Level → sum
|
||||
```
|
||||
- **Interval ratios:** semitone → ratio `2^(n/12)`. Offer a musical set, e.g.
|
||||
`-12, -7, -5, -3, 0, +3, +4, +5, +7, +12` semitones (octave/5th/4th/3rds). Map each option's
|
||||
`value` to the ratio at build time.
|
||||
- **Controls:**
|
||||
- **Voice 1 Interval** + **Voice 2 Interval** — the "knob pickers" for fixed ratios.
|
||||
- **Voice 1 Level**, **Voice 2 Level**, **Direct** (dry) level knobs (OC-2-style, like
|
||||
`BassOctaverPedal`).
|
||||
- **Picker control (decided):** add a new **`PedalSelectorKnob`** — a knob that snaps to labeled
|
||||
stops. Reusable for future discrete-knob pedals. Interval stops must include minor- and major-3rd
|
||||
**above and below**: `-12, -7, -5, -4, -3, 0, +3, +4, +5, +7, +12` semitones (m3 = ±3, M3 = ±4,
|
||||
P4 = ±5, P5 = ±7, octave = ±12, 0 = unison/off). Each stop's value maps to ratio `2^(n/12)`.
|
||||
Default voices: Voice 1 = +4 (M3 up), Voice 2 = +7 (P5 up).
|
||||
- **Channel:** `.processor` (sum to mono). Optional `.widener` (pan the two voices L/R) as a follow-up.
|
||||
- **Effort:** M. Watch granular latency/CPU with two `PitchShift` instances; verify under the
|
||||
512-block engine. Consider `windowSize` tuning per voice for smoothness.
|
||||
|
||||
## 5. Rotary / Leslie — **M**
|
||||
|
||||
Leslie = amplitude modulation (volume throb) + frequency modulation (Doppler pitch wobble) +
|
||||
stereo spread, with a two-speed (Chorale/Tremolo) ramp.
|
||||
|
||||
- **Path (per channel, `.widener`):**
|
||||
`dry → DelayLine(delay: OscSin(rate, mul: depth, add: base)) → ×(0.5 + 0.5·OscSin(rate, phase))`,
|
||||
left/right LFOs offset (≈180°) for rotating stereo image. AM and FM share the rotor `rate`.
|
||||
- **Controls:** Speed switch (Chorale ≈0.8 Hz / Tremolo ≈6.5 Hz) via `PedalSwitch`; **Accel** knob
|
||||
(ramp time between speeds); **Depth**/**Mix**. Acceleration ramp = a `Lag`/`Decay` on the rate
|
||||
target so speed changes glide (authentic spin-up/down).
|
||||
- **Alternative:** `PanAzDistance.Audio` gives real Doppler but outputs 4 channels — would need a
|
||||
4→2 downmix; the LFO-AM+FM approach above stays stereo and is simpler. Recommend the simple path
|
||||
for 1.2.
|
||||
- **Channel:** `.widener`.
|
||||
- **Effort:** M.
|
||||
|
||||
## 6. Shimmer Reverb — **M** (with caveat)
|
||||
|
||||
Octave-up sparkle over a reverb tail. Built on an existing reverb (`PlateReverb` or `GVerb`) plus
|
||||
`PitchShift(pitchRatio: 2.0)`.
|
||||
|
||||
- **Caveat — no true regeneration:** Lyrebird's per-synth graph is an acyclic DAG, so a real
|
||||
*regenerating* shimmer feedback loop (tail → pitch-up → back into tail) isn't expressible inside
|
||||
one pedal. For 1.2 ship the **parallel** approximation:
|
||||
```
|
||||
dry ─┬─ Reverb ───────────────── tail
|
||||
└─ PitchShift(×2) → Reverb → shimmer → blend
|
||||
```
|
||||
This gives the shimmer character without infinite regeneration. True regenerative shimmer needs a
|
||||
bus-feedback structure (cross-block) or a new feedback-capable generator — note as a future item.
|
||||
- **Controls:** Room/Decay, Shimmer amount (pitch-voice level), Damp, Mix.
|
||||
- **Channel:** `.widener` (reverbs output stereo — keep L/R).
|
||||
- **Effort:** M. Confirm which reverb `ReverbPedal` already uses to avoid duplication; pick the other
|
||||
(or add an algorithm switch).
|
||||
|
||||
## 7. Reverse Delay — **L** (needs new generator)
|
||||
|
||||
No reverse-capable delay exists in Lyrebird. Add a new RT-safe generator (in ShoeGaze, or upstream
|
||||
in Lyrebird Delays).
|
||||
|
||||
- **New generator `ReverseDelay`:** pre-allocated segment buffer (max length fixed at init, no RT
|
||||
alloc); record forward into a segment, play it back reversed; segment length = delay time;
|
||||
optional feedback. Crossfade at segment boundaries to avoid clicks. Follow Lyrebird generator
|
||||
rules (`GeneratorBase`, `_checkCount`, pre-allocated buffers, no RT alloc/locks).
|
||||
- **Pedal path:** `dry → ReverseDelay(time, feedback) → wet`.
|
||||
- **Controls:** Time (0.05–2 s), Feedback (0–0.9), Mix.
|
||||
- **Channel:** `.processor`.
|
||||
- **Effort:** L (generator + tests first, then the thin pedal). Run `lyrebird_external_review` on the
|
||||
new generator for RT safety.
|
||||
|
||||
## 8. Bitcrusher / Lo-Fi — **L** (needs new generators)
|
||||
|
||||
No decimation/bit-reduction generators exist. Add two small RT-safe generators.
|
||||
|
||||
- **New generators:**
|
||||
- `SampleRateDecimate` — sample-and-hold at a reduced rate (hold last sample for N input samples;
|
||||
rate or downsample-factor parameter).
|
||||
- `BitReduce` — quantize amplitude to `2^bits` levels.
|
||||
(Both trivial per-sample math, pre-allocated state only.)
|
||||
- **Pedal path:** `dry → SampleRateDecimate(rate) → BitReduce(bits) → (optional RBJLowPass tone) →
|
||||
wet`.
|
||||
- **Controls:** Sample Rate / Downsample (knob), Bits (1–16, stepped), Tone, Mix.
|
||||
- **Channel:** `.processor`.
|
||||
- **Effort:** L (two generators + tests, then pedal). Consider contributing the generators upstream
|
||||
to Lyrebird since they're broadly useful.
|
||||
|
||||
---
|
||||
|
||||
## Cross-cutting checklist (every pedal)
|
||||
|
||||
Per `CLAUDE.md` "Adding a new pedal":
|
||||
1. `Sources/LyrebirdShoeGaze/Pedals/<Name>Pedal.swift` — subclass `Pedal`, override `effect`/
|
||||
`wideEffect`, `effectKnobs`/`effectSwitches`/`effectSliders`.
|
||||
2. **`summary`** (mandatory, one line).
|
||||
3. Register in `PedalRegistry.builtIn["<DisplayName>"]`.
|
||||
4. Add `PedalType.<name>`.
|
||||
5. Enclosure color in `PedalView.enclosureColor(for:)`.
|
||||
6. Add to `PedalPaletteView.preferredOrder` (group with family: gain near Overdrive/Fuzz; modulation
|
||||
near Chorus/Phaser; pitch near the octavers; delay/reverb near their families).
|
||||
7. Tests in `Tests/LyrebirdShoeGazeTests/<Name>PedalTests.swift` — builds + non-silent, each param
|
||||
measurably changes output, knob/switch list assertions, preset round-trip if it has
|
||||
switches/sliders.
|
||||
8. Use `PedalType` static members at call sites.
|
||||
|
||||
## Shimmer scope (true regenerative) — findings
|
||||
|
||||
Investigated the regenerative path. The per-pedal graph is acyclic; the only feedback mechanisms in
|
||||
Lyrebird are (a) generators that close their own loop internally (`DelayLineFeedback`, the reverbs)
|
||||
and (b) cross-block bus read/write. Pedals use inherited `input(bus:)` / `output(bus:)` In/Out
|
||||
nodes, but **no pedal allocates an internal scratch/feedback bus** — there's no precedent or
|
||||
lifecycle hook for that. A bus-feedback shimmer would mean new pedal infrastructure (allocate +
|
||||
release an internal feedback bus, ordered Out→In with a one-block delay) — fragile and off-pattern.
|
||||
|
||||
**Conclusion:** true regenerative shimmer is best built as a **new closed-loop generator**
|
||||
(`ShimmerReverb`) that holds a reverb + an in-loop pitch-shift + damped feedback internally, the same
|
||||
way `DelayLineFeedback` contains its own feedback. That's a substantial RT-safe DSP generator
|
||||
(pre-allocated buffers, denormal guards, feedback clamp for stability, granular/FFT pitch latency in
|
||||
the loop) — larger than Reverse Delay or Bitcrush, and needing its own stability tuning + RT review.
|
||||
|
||||
**Recommendation:** build Reverse Delay and Bitcrusher first (self-contained), then take
|
||||
`ShimmerReverb` as its own focused task. If it proves too large for the 1.2 window, ship the
|
||||
parallel-pitch-into-reverb approximation for 1.2 and schedule the regenerative generator for 1.3.
|
||||
**Decision pending:** regenerative `ShimmerReverb` now, or parallel approximation for 1.2 + defer.
|
||||
|
||||
## Decisions (resolved)
|
||||
|
||||
- **Harmonizer picker:** new `PedalSelectorKnob` (stepped knob) with the ±3rd interval set above.
|
||||
Build the Harmonizer first to evaluate the control.
|
||||
- **New generators (Reverse Delay, Bitcrush):** land in the **ShoeGaze package** (self-contained;
|
||||
no Lyrebird-release dependency for 1.2).
|
||||
- **Shimmer:** built the **true regenerative** version — a new closed-loop `ShimmerReverb`
|
||||
generator (damped feedback tank + in-loop two-grain Hann octave-up reader + Schroeder input
|
||||
diffusion + safety clamp), not the parallel approximation. `ShimmerReverbPedal` wraps it
|
||||
(Size/Decay/Shimmer/Damp). Mono generator; a stereo widener variant is a possible follow-up.
|
||||
Needs an ear/tuning pass on a device (built without audio audition).
|
||||
@@ -0,0 +1,79 @@
|
||||
# Rig Library (iCloud-synced rigs)
|
||||
|
||||
Replaces the single hand-saved rig file with a managed **library of named rigs** persisted in app
|
||||
storage and synced across devices and both apps via a shared iCloud container. A rig is a whole
|
||||
session (`ShoeGazeState`) and may contain multiple boards.
|
||||
|
||||
## What shipped
|
||||
|
||||
**Core (`LyrebirdShoeGaze/Presets/`)**
|
||||
- `RigEntry` — a named, timestamped `ShoeGazeState` (rig-level analogue of `BoardVersion`).
|
||||
- `RigArchive` — a portable bundle of many `RigEntry` in one JSON file (Export/Import Archive). A
|
||||
legacy single-rig file (bare `ShoeGazeState`) imports as a one-rig archive.
|
||||
- `RigLibraryLocation` — resolves the library directory: shared iCloud container `Documents/Rigs/`
|
||||
when available, else local Application Support (`LyrebirdShoeGaze/Rigs/`).
|
||||
- `RigLibraryStore` (`@MainActor @Observable`) — one JSON file per rig
|
||||
(`<sanitized-name>-<uuid>.json`); save/delete/duplicate/rename/eraseAll/import/export. iCloud
|
||||
reads/writes are coordinated via `NSFileCoordinator`; remote changes are watched with
|
||||
`NSMetadataQuery` so a rig saved on one device appears on another live.
|
||||
- `ShoeGaze.loadRig(from: ShoeGazeState)` overload + `ShoeGaze.captureEntry(name:id:)`.
|
||||
- `sanitizePresetFilename` factored out of `BoardVersionStore` and shared.
|
||||
|
||||
**UI (`LyrebirdShoeGazeUI/`)**
|
||||
- `RigLibrarySidebarView` — persistent left listing; rows show name + timestamp, context menu
|
||||
(Rename / Duplicate / Delete), bottom bar (New / Save / Save As / ⋯ → Import / Export / Erase
|
||||
All), and an iCloud status glyph.
|
||||
- `RigNamePrompt` — shared name-entry alert (New / Save As / Rename / Duplicate).
|
||||
- `RigLibraryBootstrap` — one-call shell setup: resolve location, start the store, seed it from the
|
||||
working rig on first run, resolve the launch highlight.
|
||||
- `ShoeGazeBuilderView` gains the sidebar; selecting a rig **replaces** the current session
|
||||
(engine stopped/restarted around the rebuild). When the current rig has unsaved changes
|
||||
(`captureState()` differs from its library entry), switching first prompts **Save /
|
||||
Don't Save / Cancel** (both platforms). The old single-rig Save/Load is gone; the File menu /
|
||||
sidebar now do whole-library **Archive** import/export.
|
||||
|
||||
**Shells / entitlements**
|
||||
- macOS `AppDelegate` and iOS app model own + start the store and pass it to the view; macOS File
|
||||
menu = New Rig (⌘N), Save Rig (⌘S), Export/Import Archive (⌘E/⌘I). The per-rig menu items forward
|
||||
to the builder view via `Notification.Name` (`shoeGazeNewRig` / `shoeGazeSaveRig`) so naming
|
||||
prompts and the current-rig highlight stay in the view that owns that state.
|
||||
- Both builder targets carry the iCloud entitlement for container
|
||||
`iCloud.net.realizedsound.ShoeGazeData`; `NSUbiquitousContainers` exposes `Documents/Rigs` in the
|
||||
Files app.
|
||||
|
||||
## Manual provisioning (required before iCloud sync works)
|
||||
|
||||
Code is in place but signing is not provisionable from here. In Xcode, for **both** builder targets
|
||||
(`ShoeGazeBuilder`, `ShoeGazeBuilderiOS`), under Signing & Capabilities:
|
||||
1. Confirm the **iCloud** capability is present with **iCloud Documents** checked and the container
|
||||
`iCloud.net.realizedsound.ShoeGazeData` selected (entitlement files already declare it).
|
||||
2. Register that container on **both** App IDs in the developer account (same Team `HE5VJFE9E4`).
|
||||
3. Build signed to a device/Mac signed into iCloud to verify cross-device sync.
|
||||
|
||||
If iCloud is unavailable the library transparently falls back to local storage (no sync) — the app
|
||||
still works; the sidebar shows the `icloud.slash` glyph.
|
||||
|
||||
## Notes / follow-ups
|
||||
|
||||
- Editing a loaded rig does not auto-save to its library entry — Save is explicit. `RigStore`
|
||||
autosave still preserves unsaved working state across restarts.
|
||||
|
||||
### Known limitations / deferred (from pre-PR review)
|
||||
|
||||
- **Off-main I/O end to end.** Save/delete/erase update the in-memory `entries` on the main actor
|
||||
instantly (UI never blocks) and run the file write/delete — including `NSFileCoordinator` — on a
|
||||
serial background queue (`ioQueue`). Location resolution (`RigLibraryLocation.resolve()`, the
|
||||
blocking ubiquity lookup) and the initial/refresh *reads* now also run off the main thread:
|
||||
`RigLibraryStore` constructs instantly with a local placeholder, and `await start()` resolves the
|
||||
real iCloud-or-local location, loads via `ioQueue`, then sets `isLoaded`. Reads share `ioQueue`
|
||||
with writes, so a reload never drops a just-saved rig. `flushPendingWrites()` drains the queue
|
||||
(tests, app termination / iOS background).
|
||||
- **Loading + correct first-run seeding.** The sidebar shows a "Loading…" state until `isLoaded`.
|
||||
`RigLibraryBootstrap.start(_:seedFrom:)` seeds the working rig as "Default" **only after** the
|
||||
(possibly iCloud) library has loaded and is still empty — so a first launch on a device that
|
||||
already has synced rigs does not create a duplicate "Default" everywhere. The builder restores the
|
||||
persisted current-rig highlight once `isLoaded` flips true.
|
||||
- **`eraseAll()`** clears the in-memory list even if a file deletion fails (it still throws the
|
||||
first error). A re-`start()` re-scans and re-surfaces any undeleted rigs, so state self-heals.
|
||||
- Possible later work: conflict UI for simultaneous multi-device edits; the async-resolve redesign
|
||||
above.
|
||||
@@ -0,0 +1,48 @@
|
||||
# 1.3 — Rig sharing & the `.shoegaze` document type
|
||||
|
||||
Goal: a single registered file type for sharing rigs and boards, migrate export/import onto it, and
|
||||
add an OS share sheet to the rig library and board-version menu. Local only — no backend, no accounts.
|
||||
|
||||
## File type
|
||||
|
||||
- **Extension:** `.shoegaze`. **UTType:** `net.realizedsound.shoegaze`, conforms to `public.json`
|
||||
(stays text-readable). `UTType.shoeGaze` lives in `LyrebirdShoeGazeUI`.
|
||||
- Declared by all four demo apps and both CLI scaffolder templates
|
||||
(`CFBundleDocumentTypes` Editor/Owner + `UTExportedTypeDeclarations`) so the system associates the
|
||||
type with the app for Open and Share.
|
||||
|
||||
## Document model — `LyrebirdShoeGaze`
|
||||
|
||||
`ShoeGazeDocument` — versioned envelope (`shoeGazeDocumentFormatVersion = 1`) around one payload:
|
||||
|
||||
- `.rigs(RigArchive)` — one or many rigs (a single shared rig is a one-rig archive).
|
||||
- `.board(BoardVersion)` — a single board snapshot.
|
||||
|
||||
`data()` encodes pretty-printed JSON (`secondsSince1970` dates). `decoded(from:legacyRigName:)` is
|
||||
tolerant: tries the envelope, then a bare `RigArchive`, then a bare `ShoeGazeState` (normalised to a
|
||||
one-rig document). On-disk JSON carries an explicit `kind` discriminator.
|
||||
|
||||
## Migration
|
||||
|
||||
- `RigLibraryStore.exportDocumentData()` writes the library as a `.shoegaze` document; the prior
|
||||
`exportArchiveData()` (bare `RigArchive`) is retained for callers/tests.
|
||||
- `importArchive(from:)` now decodes via `ShoeGazeDocument.decoded` — accepts `.shoegaze`, bare
|
||||
archive, and legacy single-rig files. A board document contributes no rigs.
|
||||
- `RigFileDocument` writes `.shoeGaze`, reads `[.shoeGaze, .json]`. The Builder's `fileExporter`
|
||||
uses `.shoeGaze`; the `fileImporter` accepts `[.shoeGaze, .json]`.
|
||||
- **Internal** per-rig library files and board-version files stay plain `.json` (app-private; no
|
||||
churn). `.shoegaze` is the share/export surface only.
|
||||
|
||||
## Share UI — `LyrebirdShoeGazeUI`
|
||||
|
||||
- `RigShareItem` / `BoardShareItem` — `Transferable` wrappers holding pre-encoded `.shoegaze` bytes
|
||||
(value-type payload keeps them `Sendable`). Suggested filename `<name>.shoegaze`.
|
||||
- Rig library sidebar: `Share…` per rig (context menu). Board editor Versions menu: `Share…` per
|
||||
version. Both via SwiftUI `ShareLink` → AirDrop / Mail / Messages / Files.
|
||||
|
||||
## Tests
|
||||
|
||||
- `ShoeGazeDocumentTests` — rig/board round-trip, legacy archive + bare-state decode, garbage
|
||||
rejection, `kind` discriminator on disk.
|
||||
- `RigLibraryStoreTests` — `.shoegaze` export→import round-trip; board document imports zero rigs.
|
||||
- Lyrebird `ProjectScaffolderTests` — generated macOS/iOS `Info.plist` registers the document type.
|
||||
@@ -0,0 +1,78 @@
|
||||
# ShoeGaze 1.2.0
|
||||
|
||||
Ten new pedals, an iCloud-synced rig library, and a reworked builder layout.
|
||||
|
||||
## New pedals
|
||||
|
||||
Ten additions bring the built-in catalog to 32:
|
||||
|
||||
**Gain**
|
||||
- **Distortion** — mid-gain saturation between Overdrive and Fuzz (Drive / Tone).
|
||||
|
||||
**Modulation**
|
||||
- **Flanger** — sweeping comb-filter jet with feedback (Rate / Depth / Feedback).
|
||||
- **Vibrato** — pure pitch wobble, fully wet (Rate / Depth).
|
||||
- **Rotary** — Leslie rotary-speaker: Doppler pitch wobble + volume throb, two-speed
|
||||
(Chorale / Tremolo) with an acceleration ramp (Depth / Accel + Speed switch).
|
||||
|
||||
**Pitch**
|
||||
- **Harmonizer** — two pitch-shifted harmony voices at fixed musical intervals, picked with a new
|
||||
stepped knob (octave / 5th / 4th / major & minor 3rd & 6th, above and below) with per-voice and
|
||||
direct levels.
|
||||
|
||||
**Delay / Reverb**
|
||||
- **Reverse Delay** — backward-tape segments with feedback trails (Time / Feedback).
|
||||
- **Shimmer Reverb** — regenerative ambient reverb whose tail climbs an octave as it sustains
|
||||
(Size / Decay / Shimmer / Damp).
|
||||
|
||||
**Texture**
|
||||
- **Bitcrusher** — sample-rate decimation + bit-depth reduction + tone (Crush / Bits / Tone).
|
||||
- **Granulator** — stereo grain cloud; grains scattered across the stereo field by Spread
|
||||
(Grain / Overlap / Spread).
|
||||
- **Auto Granulator** — granulator whose grain size tracks your dynamics, with a Response switch to
|
||||
flip the loud↔short / loud↔long relationship (Min Grain / Max Grain / Overlap / Spread + Response).
|
||||
|
||||
## Rig library (iCloud)
|
||||
|
||||
- Rigs are now a managed **library** in the left sidebar instead of one hand-saved file. New, Save,
|
||||
Save As, Duplicate, Rename, Delete, and Erase All — each rig holds multiple boards.
|
||||
- **iCloud sync** across your devices and both apps (macOS + iPad) via a shared container, with a
|
||||
local fallback when iCloud is unavailable. The library loads on launch and shows a loading state.
|
||||
- Selecting a rig prompts to save unsaved changes first (macOS + iOS).
|
||||
- **Archive** import/export bundles the whole library as one hand-editable JSON file (replaces the
|
||||
old single-rig save/load); legacy single-rig files still import.
|
||||
- macOS **File menu**: New Rig (⌘N), Save Rig (⌘S), Export / Import Archive (⌘E / ⌘I).
|
||||
- Saves and loads run off the main thread, so the UI never stalls on disk or iCloud.
|
||||
|
||||
## Builder UI
|
||||
|
||||
- Reworked top layout: scope + CPU meters beside a stacked board-mixer / horizontal pedal-picker,
|
||||
giving the board canvas the full width below.
|
||||
- **Pedal picker** cards are now **colour-coded by type**, with a **filter-by-type** menu
|
||||
(Gain / Dynamics / EQ & Filter / Modulation / Pitch / Delay / Reverb / Texture; defaults to All).
|
||||
- The builder is pinned to a dark color scheme, fixing black-on-dark system controls (nav title,
|
||||
steppers, Record button) on iOS in light mode.
|
||||
- The input-source picker reflects the **In** channel count as soon as you change it (the stopped
|
||||
engine reconfigures immediately), so you can choose the input before Start.
|
||||
- Failed edits now surface as an **alert** instead of a console log — e.g. adding a second stereo
|
||||
(widening) pedal explains that the board is already stereo and to add a Merge to Mono first.
|
||||
- The routing cards sit in their own row beneath the pedal picker.
|
||||
|
||||
## Fixes
|
||||
|
||||
- The granulators are now **latency-free** — grains window and pan the live input directly
|
||||
(straight-through), instead of replaying buffered history.
|
||||
- Shimmer Reverb no longer accumulates a DC offset at high shimmer (DC-blocked feedback path).
|
||||
|
||||
## Under the hood
|
||||
|
||||
- New RT-safe generators: `ReverseDelay`, `SampleRateDecimate`, `BitReduce`, `ShimmerReverb`,
|
||||
`StereoGranulator`; a reusable `PedalSelectorKnob` control with preset round-trip.
|
||||
- All new generators sanitise control inputs (finite + clamped) and pre-allocate buffers.
|
||||
- 271 tests; RT-safety reviewed.
|
||||
|
||||
## Setup notes
|
||||
|
||||
- **iCloud:** enable the `iCloud.net.realizedsound.ShoeGazeData` container on both builder App IDs
|
||||
(iCloud Documents) and sign with the same team for cross-device sync.
|
||||
- Shimmer Reverb and the granulators reward a tuning pass to taste.
|
||||
Reference in New Issue
Block a user