1.0 release
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
// BoardState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Serialisable snapshot of one `PedalBoard`'s label and pedal chain.
|
||||
///
|
||||
/// `label` is the board's display name. `pedals` contains one `PedalState` per
|
||||
/// pedal in signal-flow order. Unknown pedal types in the array are skipped
|
||||
/// silently during `ShoeGaze.loadRig(from:)`.
|
||||
public struct BoardState: Codable, Equatable {
|
||||
|
||||
/// The board's display label (e.g. `"Board 1"`).
|
||||
public let label: String
|
||||
|
||||
/// Ordered list of pedal snapshots in signal-flow order.
|
||||
public let pedals: [PedalState]
|
||||
|
||||
/// Creates a board state snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: The board's display label.
|
||||
/// - pedals: Ordered list of pedal state snapshots.
|
||||
public init(
|
||||
label: String,
|
||||
pedals: [PedalState]
|
||||
) {
|
||||
self.label = label
|
||||
self.pedals = pedals
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// BoardVersion.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A named, timestamped snapshot of a single `PedalBoard`'s label and pedal chain.
|
||||
///
|
||||
/// `BoardVersion` is the unit stored and retrieved by `BoardVersionStore`. Each version
|
||||
/// captures a complete `BoardState` (pedal types, knob values, bypass flags) alongside
|
||||
/// a human-readable `name` (e.g. `"Lead Crunch"`) and a `savedAt` timestamp.
|
||||
///
|
||||
/// `BoardVersion` is `Codable` so it can be written to and read from JSON files by
|
||||
/// `BoardVersionStore`. It is `Identifiable` (via `UUID`) so SwiftUI `List` and
|
||||
/// `ForEach` views can use it directly, and `Equatable` for round-trip testing.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let store = BoardVersionStore()
|
||||
/// store.capture(myBoard, name: "Lead Crunch")
|
||||
/// try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - id: Stable unique identifier for this version.
|
||||
/// - name: Human-readable label (e.g. `"Lead Crunch"`).
|
||||
/// - savedAt: The `Date` when this version was captured.
|
||||
/// - state: The full `BoardState` snapshot.
|
||||
public struct BoardVersion: Codable, Identifiable, Equatable {
|
||||
|
||||
/// Stable unique identifier for this version entry.
|
||||
public let id: UUID
|
||||
|
||||
/// Human-readable name for this version (e.g. `"Lead Crunch"`, `"Clean Wash"`).
|
||||
public let name: String
|
||||
|
||||
/// Date and time at which this version was captured, at **whole-second precision**.
|
||||
///
|
||||
/// The timestamp is rounded to the nearest second at init so it survives a JSON
|
||||
/// round-trip exactly (a `Date` serialised as a fractional `secondsSince1970` Double
|
||||
/// otherwise loses precision through the decimal text form, which would break
|
||||
/// `Equatable` after `writeToDisk` / `loadAllFromDisk`).
|
||||
public let savedAt: Date
|
||||
|
||||
/// The full `BoardState` snapshot — label, pedal types, knob values, and bypass flags.
|
||||
public let state: BoardState
|
||||
|
||||
/// Creates a board version snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - id: Stable unique identifier. Defaults to a newly generated `UUID()`.
|
||||
/// - name: Human-readable name for this version.
|
||||
/// - savedAt: Capture timestamp. Defaults to `Date()` (now). Rounded to the
|
||||
/// nearest whole second so persistence round-trips are lossless.
|
||||
/// - state: The `BoardState` to store.
|
||||
public init(
|
||||
id: UUID = UUID(),
|
||||
name: String,
|
||||
savedAt: Date = Date(),
|
||||
state: BoardState
|
||||
) {
|
||||
self.id = id
|
||||
self.name = name
|
||||
// Round to whole seconds: a fractional Date loses precision through the JSON
|
||||
// `secondsSince1970` Double text form, which would break `Equatable` after a
|
||||
// disk round-trip.
|
||||
self.savedAt = Date(timeIntervalSince1970: savedAt.timeIntervalSince1970.rounded())
|
||||
self.state = state
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
// BoardVersionStore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
/// In-memory list of `BoardVersion` snapshots with optional disk persistence.
|
||||
///
|
||||
/// `BoardVersionStore` is `@Observable` so SwiftUI views automatically update when the
|
||||
/// `versions` list changes. All mutations run on the main actor.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// let store = BoardVersionStore()
|
||||
/// store.capture(myBoard, name: "Lead Crunch") // add a version
|
||||
/// try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory())
|
||||
///
|
||||
/// // Restore on next launch:
|
||||
/// let freshStore = BoardVersionStore()
|
||||
/// try freshStore.loadAllFromDisk(in: BoardVersionStore.defaultDirectory())
|
||||
/// if let v = freshStore.versions.first {
|
||||
/// try shoeGaze.rebuildBoard(myBoard, from: v.state)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Disk format
|
||||
///
|
||||
/// Each `BoardVersion` is written as a separate pretty-printed JSON file named
|
||||
/// `<sanitized-name>-<id>.json` inside the chosen directory. File names are
|
||||
/// sanitised by replacing `/`, `\`, `:`, NUL, leading `.`, and whitespace with
|
||||
/// underscores; the sanitised prefix is capped at 200 UTF-8 bytes; all-whitespace
|
||||
/// or all-separator names fall back to `"unnamed"`. `Date` values are encoded as
|
||||
/// seconds since the Unix epoch (`TimeInterval`) for lossless round-trip equality.
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class BoardVersionStore {
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// All in-memory `BoardVersion` entries, sorted by `savedAt` after any disk load.
|
||||
public private(set) var versions: [BoardVersion] = []
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates an empty store. Call `loadAllFromDisk(in:)` to populate from disk.
|
||||
public init() {}
|
||||
|
||||
// MARK: - Capture
|
||||
|
||||
/// Captures the current state of `board` and appends a new `BoardVersion` to `versions`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - board: The `PedalBoard` to snapshot.
|
||||
/// - name: Human-readable label for this version (e.g. `"Lead Crunch"`).
|
||||
public func capture(
|
||||
_ board: PedalBoard,
|
||||
name: String
|
||||
) {
|
||||
let version: BoardVersion = BoardVersion(
|
||||
id: UUID(),
|
||||
name: name,
|
||||
savedAt: Date(),
|
||||
state: board.captureState()
|
||||
)
|
||||
versions.append(version)
|
||||
}
|
||||
|
||||
// MARK: - Remove
|
||||
|
||||
/// Removes a version from the in-memory list. Matching is by `id`.
|
||||
///
|
||||
/// This is **memory-only**. Any JSON file previously written by `writeToDisk(_:in:)` is
|
||||
/// not touched; call `deleteFromDisk(_:in:)` first if you also need to remove the file
|
||||
/// so that the deletion survives `loadAllFromDisk`.
|
||||
///
|
||||
/// - Parameter version: The `BoardVersion` to remove.
|
||||
public func remove(_ version: BoardVersion) {
|
||||
versions.removeAll { $0.id == version.id }
|
||||
}
|
||||
|
||||
// MARK: - Disk delete
|
||||
|
||||
/// Deletes the JSON file for `version` from `directory`.
|
||||
///
|
||||
/// The filename is derived using the same `<sanitized-name>-<id>.json` scheme as
|
||||
/// `writeToDisk(_:in:)`. No-op if the file does not exist. Use this alongside
|
||||
/// `remove(_:)` to make a deletion persist across `loadAllFromDisk`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: The `BoardVersion` whose file should be removed.
|
||||
/// - directory: The directory that was passed to `writeToDisk(_:in:)`.
|
||||
/// - Throws: `FileManager` errors other than "file not found".
|
||||
public func deleteFromDisk(
|
||||
_ version: BoardVersion,
|
||||
in directory: URL
|
||||
) throws {
|
||||
let sanitized: String = sanitizeFilename(version.name)
|
||||
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
|
||||
let fileURL: URL = directory.appendingPathComponent(filename)
|
||||
do {
|
||||
try FileManager.default.removeItem(at: fileURL)
|
||||
} catch let error as NSError
|
||||
where error.domain == NSCocoaErrorDomain && error.code == NSFileNoSuchFileError {
|
||||
// File does not exist — treat as a no-op.
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Disk write
|
||||
|
||||
/// Writes a single `BoardVersion` to `directory` as pretty-printed JSON.
|
||||
///
|
||||
/// The filename is `<sanitized-name>-<id>.json`. The sanitised name replaces `/`,
|
||||
/// `:`, newlines, and other whitespace with underscores so the filename is safe on
|
||||
/// HFS+ and APFS. The directory is created if it does not already exist.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: The `BoardVersion` to write.
|
||||
/// - directory: Destination directory URL. Created recursively if absent.
|
||||
/// - Throws:
|
||||
/// - `FileManager` errors if directory creation fails.
|
||||
/// - `JSONEncoder` errors on encode failure.
|
||||
/// - `Data.write(to:options:)` errors on write failure.
|
||||
public func writeToDisk(
|
||||
_ version: BoardVersion,
|
||||
in directory: URL
|
||||
) throws {
|
||||
try FileManager.default.createDirectory(
|
||||
at: directory,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil
|
||||
)
|
||||
|
||||
let sanitized: String = sanitizeFilename(version.name)
|
||||
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
|
||||
let fileURL: URL = directory.appendingPathComponent(filename)
|
||||
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
let data: Data = try encoder.encode(version)
|
||||
try data.write(to: fileURL, options: .atomic)
|
||||
}
|
||||
|
||||
/// Writes every in-memory `BoardVersion` to `directory`.
|
||||
///
|
||||
/// Each version is written as a separate file (see `writeToDisk(_:in:)`).
|
||||
/// The directory is created if it does not already exist. A failure on one file
|
||||
/// propagates immediately and stops the remaining writes.
|
||||
///
|
||||
/// - Parameter directory: Destination directory URL. Created recursively if absent.
|
||||
/// - Throws: The first error encountered during write.
|
||||
public func writeAllToDisk(in directory: URL) throws {
|
||||
for version: BoardVersion in versions {
|
||||
try writeToDisk(version, in: directory)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Disk load
|
||||
|
||||
/// Loads all `*.json` files in `directory` as `BoardVersion` entries, replacing the
|
||||
/// current in-memory `versions` list.
|
||||
///
|
||||
/// Files that cannot be **read** (e.g. permission errors) and files that cannot be
|
||||
/// **decoded** (corrupt or unrecognised JSON) are both silently skipped — a single
|
||||
/// bad file does not prevent the rest from loading. After loading, the list is sorted
|
||||
/// ascending by `savedAt`.
|
||||
///
|
||||
/// - Parameter directory: The directory to scan. If the directory does not exist or
|
||||
/// is empty, `versions` is set to `[]` without throwing.
|
||||
/// - Throws: `FileManager` errors for directory enumeration failures (not for
|
||||
/// individual file read/decode failures — those are silently skipped).
|
||||
public func loadAllFromDisk(in directory: URL) throws {
|
||||
var loaded: [BoardVersion] = []
|
||||
|
||||
// Early exit if the directory doesn't exist yet.
|
||||
var isDirectory: ObjCBool = false
|
||||
guard FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory),
|
||||
isDirectory.boolValue else {
|
||||
versions = []
|
||||
return
|
||||
}
|
||||
|
||||
let contents: [URL] = try FileManager.default.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: nil,
|
||||
options: .skipsHiddenFiles
|
||||
)
|
||||
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
|
||||
for fileURL: URL in contents {
|
||||
guard fileURL.pathExtension == "json" else { continue }
|
||||
guard let data: Data = try? Data(contentsOf: fileURL) else { continue }
|
||||
guard let version: BoardVersion = try? decoder.decode(BoardVersion.self, from: data) else {
|
||||
continue
|
||||
}
|
||||
loaded.append(version)
|
||||
}
|
||||
|
||||
loaded.sort { $0.savedAt < $1.savedAt }
|
||||
versions = loaded
|
||||
}
|
||||
|
||||
// MARK: - Default directory
|
||||
|
||||
/// Returns the recommended directory for storing board version files.
|
||||
///
|
||||
/// Resolves to `<Application Support>/LyrebirdShoeGaze/ShoeGazeVersions/` for the
|
||||
/// current user. Falls back to a `ShoeGazeVersions/` subdirectory inside the
|
||||
/// system temporary directory if Application Support is unavailable.
|
||||
///
|
||||
/// The directory is **not** created by this method — call `writeToDisk(_:in:)` or
|
||||
/// `writeAllToDisk(in:)` (which create the directory automatically) before writing.
|
||||
///
|
||||
/// - Returns: A `URL` for the ShoeGaze versions directory.
|
||||
public static func defaultDirectory() -> URL {
|
||||
let appSupportDir: URL? = try? FileManager.default.url(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: false
|
||||
)
|
||||
let base: URL = appSupportDir ?? FileManager.default.temporaryDirectory
|
||||
return base
|
||||
.appendingPathComponent("LyrebirdShoeGaze", isDirectory: true)
|
||||
.appendingPathComponent("ShoeGazeVersions", isDirectory: true)
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
/// Maximum UTF-8 byte length for the sanitised name prefix before the `-<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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
// Pedal+Preset.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
extension Pedal {
|
||||
|
||||
/// Captures the current parameter values of this pedal as a `PedalState`.
|
||||
///
|
||||
/// The returned snapshot includes:
|
||||
/// - `type`: the pedal's `displayName` (used as a factory key on load).
|
||||
/// - `knobValues`: one `Double` per entry in `knobs`, in order
|
||||
/// (effect-specific knobs first, then Mix, then Level).
|
||||
/// - `bypass`: the current bypass parameter value.
|
||||
///
|
||||
/// - Returns: A `PedalState` reflecting the pedal's current parameter values.
|
||||
public func captureState() -> PedalState {
|
||||
let values: [Double] = knobs.map { $0.node.value }
|
||||
return PedalState(
|
||||
type: displayName,
|
||||
knobValues: values,
|
||||
bypass: bypass
|
||||
)
|
||||
}
|
||||
|
||||
/// Applies a previously captured `PedalState` to this pedal's parameters.
|
||||
///
|
||||
/// For each (knob, value) pair in `zip(knobs, state.knobValues)`, the knob's
|
||||
/// `UIParamNode` is updated via `node.update(_:)`. If `state.knobValues` has
|
||||
/// fewer entries than `knobs`, the trailing knobs retain their current values.
|
||||
/// Extra values beyond `knobs.count` are ignored. The `bypass` parameter is
|
||||
/// always applied regardless of knob-count mismatches.
|
||||
///
|
||||
/// - Parameter state: The state to restore. The `state.type` is not validated
|
||||
/// against `displayName` — the caller is responsible for matching types before
|
||||
/// calling this method.
|
||||
public func applyState(_ state: PedalState) {
|
||||
for (knob, value) in zip(knobs, state.knobValues) {
|
||||
knob.node.update(value)
|
||||
}
|
||||
bypass = state.bypass
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// PedalBoard+Preset.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
extension PedalBoard {
|
||||
|
||||
/// Captures the current state of this board's label and pedal chain as a `BoardState`.
|
||||
///
|
||||
/// Each pedal's `displayName`, knob values, and bypass flag are snapshotted in
|
||||
/// signal-flow order. The engine graph is not modified; this is a read-only operation.
|
||||
///
|
||||
/// - Returns: A `BoardState` reflecting the board's current label and pedal parameters.
|
||||
public func captureState() -> BoardState {
|
||||
let pedalStates: [PedalState] = pedals.map { $0.captureState() }
|
||||
return BoardState(label: label, pedals: pedalStates)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// PedalRegistry.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A factory registry mapping built-in pedal display names to their constructors.
|
||||
///
|
||||
/// `PedalRegistry` is the authoritative lookup used by `ShoeGaze.loadRig(from:)` to
|
||||
/// instantiate the correct `Pedal` subclass for each `PedalState.type` string found
|
||||
/// in a saved preset. Unknown type strings return `nil` from `makePedal(type:)` and
|
||||
/// are silently skipped by the loader.
|
||||
///
|
||||
/// To register custom pedal types, extend `builtIn` by building your own dictionary
|
||||
/// and merging it before calling `loadRig`. The built-in registry covers the eight
|
||||
/// factory pedals: Overdrive, Delay, Reverb, Modulation, Fuzz, Tremolo, Phaser, and
|
||||
/// Compressor.
|
||||
public enum PedalRegistry {
|
||||
|
||||
/// Maps each built-in pedal display name to a `@MainActor` no-argument constructor.
|
||||
///
|
||||
/// Keys are the `displayName` values returned by the corresponding `Pedal` subclass.
|
||||
/// Values are closures that allocate a fresh instance with default bus indices —
|
||||
/// `ShoeGaze.loadRig(from:)` updates `inputBus`/`outputBus` when adding the pedal
|
||||
/// to a board via `board.add(_:)`.
|
||||
public static let builtIn: [String: @MainActor () -> Pedal] = [
|
||||
"Overdrive": { OverdrivePedal() },
|
||||
"Delay": { DelayPedal() },
|
||||
"Reverb": { ReverbPedal() },
|
||||
"Modulation": { ModulationPedal() },
|
||||
"Fuzz": { FuzzPedal() },
|
||||
"Tremolo": { TremoloPedal() },
|
||||
"Phaser": { PhaserPedal() },
|
||||
"Compressor": { CompressorPedal() },
|
||||
]
|
||||
|
||||
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
|
||||
/// is not in the built-in registry.
|
||||
///
|
||||
/// The returned pedal has default bus indices (`inputBus: 0`, `outputBus: 0`);
|
||||
/// the caller is responsible for routing it via `board.add(_:)` before the engine
|
||||
/// processes any audio.
|
||||
///
|
||||
/// - Parameter type: The `displayName` of the pedal (e.g. `"Overdrive"`, `"Delay"`).
|
||||
/// - Returns: A freshly allocated `Pedal` subclass instance, or `nil` for unknown types.
|
||||
@MainActor
|
||||
public static func makePedal(type: String) -> Pedal? {
|
||||
guard let constructor: @MainActor () -> Pedal = builtIn[type] else { return nil }
|
||||
return constructor()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// PedalState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Serialisable snapshot of one pedal's parameter values.
|
||||
///
|
||||
/// `type` stores the pedal's `displayName` and is used by `PedalRegistry` to
|
||||
/// reconstruct the correct subclass on load. `knobValues` mirrors `Pedal.knobs`
|
||||
/// in order — effect-specific knobs first, then `mix`, then `level`. `bypass`
|
||||
/// stores the bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
///
|
||||
/// - Note: Extra knob values beyond the pedal's current knob count are silently
|
||||
/// ignored on apply; missing values (fewer entries than knobs) leave trailing
|
||||
/// knobs at their current value.
|
||||
public struct PedalState: Codable, Equatable {
|
||||
|
||||
/// The pedal's `displayName` — used as a factory key by `PedalRegistry`.
|
||||
public let type: String
|
||||
|
||||
/// Knob values in the same order as `Pedal.knobs` (effect knobs then Mix, Level).
|
||||
public let knobValues: [Double]
|
||||
|
||||
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
|
||||
public let bypass: Double
|
||||
|
||||
/// Creates a pedal state snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - type: The pedal's `displayName`, used to identify the pedal type on load.
|
||||
/// - knobValues: Current knob values in `Pedal.knobs` order.
|
||||
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
public init(
|
||||
type: String,
|
||||
knobValues: [Double],
|
||||
bypass: Double
|
||||
) {
|
||||
self.type = type
|
||||
self.knobValues = knobValues
|
||||
self.bypass = bypass
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// PresetError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Errors thrown by preset load and version-check operations.
|
||||
///
|
||||
/// - `unsupportedVersion`: The serialised preset's `version` field exceeds
|
||||
/// `presetFormatVersion`. The associated value carries the version number that
|
||||
/// was found in the file so callers can surface a meaningful error message.
|
||||
public enum PresetError: Error, Equatable {
|
||||
|
||||
/// The preset file was written by a newer version of the format than this
|
||||
/// build understands. The associated `Int` is the version found in the file.
|
||||
case unsupportedVersion(Int)
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// ShoeGaze+Preset.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
extension ShoeGaze {
|
||||
|
||||
// MARK: - Capture
|
||||
|
||||
/// Captures the current rig topology and parameter values as a `ShoeGazeState`.
|
||||
///
|
||||
/// Each board's label and pedal parameters are snapshotted in order. The engine
|
||||
/// graph is not modified; this is a read-only operation.
|
||||
///
|
||||
/// - Returns: A `ShoeGazeState` reflecting the current rig.
|
||||
public func captureState() -> ShoeGazeState {
|
||||
let boardStates: [BoardState] = boards.map { board in
|
||||
let pedalStates: [PedalState] = board.pedals.map { $0.captureState() }
|
||||
return BoardState(label: board.label, pedals: pedalStates)
|
||||
}
|
||||
return ShoeGazeState(boards: boardStates)
|
||||
}
|
||||
|
||||
// MARK: - Save / Load
|
||||
|
||||
/// Saves the current rig to a JSON file at `url`.
|
||||
///
|
||||
/// The file is pretty-printed for readability and human-editability. Existing
|
||||
/// files at `url` are overwritten.
|
||||
///
|
||||
/// - Parameter url: Destination file URL. The directory must already exist.
|
||||
/// - Throws: Any error from `JSONEncoder` or `Data.write(to:options:)`.
|
||||
public func saveRig(to url: URL) throws {
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
let data: Data = try encoder.encode(captureState())
|
||||
try data.write(to: url, options: .atomic)
|
||||
}
|
||||
|
||||
/// Loads a rig from a JSON preset file and rebuilds the engine graph.
|
||||
///
|
||||
/// This method:
|
||||
/// 1. Calls `teardown()` to remove all current nodes and release all buses.
|
||||
/// 2. For each `BoardState`, calls `addBoard()`, sets `board.label`, adds each
|
||||
/// pedal (skipping unknown types without throwing), applies the saved parameter
|
||||
/// values via `pedal.applyState(_:)`, and calls `finalizeBoard(_:)`.
|
||||
///
|
||||
/// - Important: Call this method with the engine **stopped** (before `engine.start()`
|
||||
/// or after `engine.stop()`). The same async-removal caveat as `teardown()` applies:
|
||||
/// the engine processes one more block after `remove` is enqueued. Unknown pedal
|
||||
/// types in the preset are silently skipped — the board is still created and finalized
|
||||
/// with however many pedals were successfully reconstructed.
|
||||
///
|
||||
/// - Parameter url: Source file URL pointing to a JSON preset written by `saveRig(to:)`.
|
||||
/// - Throws: Any error from `Data(contentsOf:)`, `JSONDecoder`, `PedalBoard.init`,
|
||||
/// `board.add(_:)`, or `finalizeBoard(_:)`. Also throws
|
||||
/// `PresetError.unsupportedVersion` when the file's version exceeds
|
||||
/// `presetFormatVersion`.
|
||||
public func loadRig(from url: URL) throws {
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
|
||||
guard state.version <= presetFormatVersion else {
|
||||
throw PresetError.unsupportedVersion(state.version)
|
||||
}
|
||||
|
||||
teardown()
|
||||
|
||||
for boardState: BoardState in state.boards {
|
||||
let board: PedalBoard = try addBoard()
|
||||
board.label = boardState.label
|
||||
|
||||
for pedalState: PedalState in boardState.pedals {
|
||||
guard let pedal: Pedal = PedalRegistry.makePedal(type: pedalState.type) else {
|
||||
// Unknown pedal type — skip without crashing.
|
||||
continue
|
||||
}
|
||||
pedal.applyState(pedalState)
|
||||
try board.add(pedal)
|
||||
}
|
||||
|
||||
try finalizeBoard(board)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Per-board rebuild
|
||||
|
||||
/// Tears down a single board and recreates it from a saved `BoardState`, preserving
|
||||
/// its position in `boards` so UI ordering remains stable.
|
||||
///
|
||||
/// ## Behaviour
|
||||
///
|
||||
/// 1. Finds `board` in `boards` by identity (`===`). If absent, the board is treated as
|
||||
/// unmanaged: a fresh board is built, finalised, and returned without reordering.
|
||||
/// 2. Calls `addBoard()` to allocate a new board and sets `newBoard.label = state.label`.
|
||||
/// 3. For each `PedalState` in `state.pedals`, calls `PedalRegistry.makePedal(type:)`;
|
||||
/// unknown types are logged and skipped so presets with missing custom pedals degrade
|
||||
/// gracefully. Known pedals have `applyState(_:)` called before `board.add(_:)`.
|
||||
/// 4. Calls `finalizeBoard(_:)` to connect the output master.
|
||||
/// 5. Only after the new board is fully wired does `removeBoard(_:)` tear down the old
|
||||
/// board — so a failure during steps 2–4 leaves the original board intact.
|
||||
/// 6. Moves the new board to `oldIndex` in `boards` so it occupies the same slot as the
|
||||
/// removed board.
|
||||
///
|
||||
/// - Important: Call with the engine **stopped** (or accept one block of glitch on a
|
||||
/// running engine). Both boards exist briefly while the new one is being built;
|
||||
/// this requires two additional buses but is safe because the bus pool has headroom
|
||||
/// and the documented precondition is engine-stopped. `removeBoard(_:)` enqueues
|
||||
/// removal; the engine processes one more block before the node is dequeued.
|
||||
/// Unknown pedal types are silently skipped.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - board: The board to replace. Must have been returned by `addBoard()` on this instance.
|
||||
/// - state: The `BoardState` snapshot to restore.
|
||||
/// - Returns: The newly created `PedalBoard` at the same index as the replaced board.
|
||||
/// - Throws:
|
||||
/// - `BusAllocatorError.noFreeBus` if no mono audio bus is available during rebuild.
|
||||
/// - `EngineAddError` if the engine rejects any node insertion.
|
||||
@discardableResult
|
||||
public func rebuildBoard(
|
||||
_ board: PedalBoard,
|
||||
from state: BoardState
|
||||
) throws -> PedalBoard {
|
||||
// Record the existing position before allocating the new board so the slot
|
||||
// can be restored. May be nil when `board` is unmanaged (not in `boards`).
|
||||
let oldIndex: Int? = boards.firstIndex(where: { $0 === board })
|
||||
|
||||
// Build the new board FIRST so that any failure leaves the old board intact.
|
||||
let newBoard: PedalBoard = try addBoard()
|
||||
do {
|
||||
newBoard.label = state.label
|
||||
|
||||
for pedalState: PedalState in state.pedals {
|
||||
guard let pedal: Pedal = PedalRegistry.makePedal(type: pedalState.type) else {
|
||||
// Unknown pedal type — log for diagnosability, then skip.
|
||||
print("[ShoeGaze] rebuildBoard: skipping unknown pedal type \(pedalState.type)")
|
||||
continue
|
||||
}
|
||||
pedal.applyState(pedalState)
|
||||
try newBoard.add(pedal)
|
||||
}
|
||||
|
||||
try finalizeBoard(newBoard)
|
||||
} catch {
|
||||
// New board is partial — clean it up while the old board is still intact.
|
||||
removeBoard(newBoard)
|
||||
throw error
|
||||
}
|
||||
|
||||
// New board fully wired — now remove the old one and restore its position.
|
||||
if let targetIndex: Int = oldIndex {
|
||||
removeBoard(board)
|
||||
// `addBoard()` always appends; move the new board back to the original slot.
|
||||
// `moveBoard(_:to:)` locates by identity so the correct element is repositioned
|
||||
// even if `removeBoard` shifted indices.
|
||||
moveBoard(newBoard, to: targetIndex)
|
||||
}
|
||||
|
||||
return newBoard
|
||||
}
|
||||
|
||||
// MARK: - Lightweight recall
|
||||
|
||||
/// Applies parameter values from `state` to the current rig topology without
|
||||
/// rebuilding the engine graph.
|
||||
///
|
||||
/// This is a lightweight "recall settings" path intended for topologically identical
|
||||
/// rigs (same board count, same pedal count and types in the same order). Boards
|
||||
/// and pedals are matched positionally; any count or type mismatch at the board or
|
||||
/// pedal level is silently ignored for that entry — no error is thrown and remaining
|
||||
/// entries continue to be processed.
|
||||
///
|
||||
/// Use `loadRig(from:)` when you need a full topology rebuild.
|
||||
///
|
||||
/// - Parameter state: The `ShoeGazeState` whose parameter values should be applied.
|
||||
public func applyState(_ state: ShoeGazeState) {
|
||||
for (board, boardState) in zip(boards, state.boards) {
|
||||
for (pedal, pedalState) in zip(board.pedals, boardState.pedals) {
|
||||
guard pedal.displayName == pedalState.type else { continue }
|
||||
pedal.applyState(pedalState)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// ShoeGazeState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Format version written into every saved preset file.
|
||||
///
|
||||
/// Increment this constant when the `ShoeGazeState` schema changes in a way that
|
||||
/// requires migration logic on load.
|
||||
public let presetFormatVersion: Int = 1
|
||||
|
||||
/// Serialisable snapshot of an entire `ShoeGaze` rig — all boards and their pedals.
|
||||
///
|
||||
/// Use `ShoeGaze.saveRig(to:)` to write and `ShoeGaze.loadRig(from:)` to restore.
|
||||
/// The `version` field allows future migrations: loaders that read a file with a
|
||||
/// higher `version` than `presetFormatVersion` should reject or warn, while loaders
|
||||
/// reading older versions may apply forward-compatibility mappings.
|
||||
///
|
||||
/// Unknown pedal types encountered during load are silently skipped so presets made
|
||||
/// with custom third-party pedals degrade gracefully on systems without those pedals.
|
||||
public struct ShoeGazeState: Codable, Equatable {
|
||||
|
||||
/// Preset format version. Written as `presetFormatVersion` at save time.
|
||||
public let version: Int
|
||||
|
||||
/// All board snapshots in the order they were created.
|
||||
public let boards: [BoardState]
|
||||
|
||||
/// Creates a rig state snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - version: Preset format version. Defaults to `presetFormatVersion`.
|
||||
/// - boards: Ordered list of board state snapshots.
|
||||
public init(
|
||||
version: Int = presetFormatVersion,
|
||||
boards: [BoardState]
|
||||
) {
|
||||
self.version = version
|
||||
self.boards = boards
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user