From 4eb1cbdd618c8961e26c71a3d2b4ac7824905b7e Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sun, 9 Aug 2026 12:37:34 -0700 Subject: [PATCH] feat(rigs): ship built-in factory starter rigs Add a factory rig library: 8 curated starter pedalboard rigs seeded into an empty rig library on first launch. Rigs are compile-checked builders (construct concrete pedals, set typed @UIParam values, board.add) rather than hand-written JSON, so a renamed pedal control is a build error, not a silently corrupted preset. Seeding builds each rig in a throwaway offline (never-started) engine, captures a RigEntry with a stable per-rig UUID (idempotent re-seed), and saves to the store. Bootstrap rolls back this run's saves if any store.save fails, so a partial library can't freeze future seeding (gated on isEmpty). Rigs are named/described by sound, not trademarked products or artists; a test guards against brand names leaking into names/blurbs. Full ship-path test loads and renders every rig to non-silent output. Co-Authored-By: Claude Opus 4.8 --- .../Presets/Factory/FactoryRig.swift | 70 +++ .../Presets/Factory/FactoryRigCategory.swift | 33 ++ .../Presets/Factory/FactoryRigLibrary.swift | 438 ++++++++++++++++++ .../RigLibraryBootstrap.swift | 58 ++- .../FactoryRigLibraryTests.swift | 105 +++++ 5 files changed, 700 insertions(+), 4 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigCategory.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift create mode 100644 Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift new file mode 100644 index 0000000..97f63cc --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRig.swift @@ -0,0 +1,70 @@ +// FactoryRig.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// A single built-in starter rig: a named, described pedal chain shipped with the app and seeded +/// into a fresh rig library on first launch. +/// +/// A `FactoryRig` is a *builder*, not a stored snapshot. Its ``build`` closure constructs the chain +/// against a live ``ShoeGaze`` session using the concrete pedal editing API, so the recipe is +/// type-checked against the real pedal parameters at compile time — a renamed pedal control breaks +/// the build (a compile error) rather than silently corrupting a hand-written JSON preset. The +/// builder is run once at seed time (see ``FactoryRigLibrary/makeEntries(makeSession:)``), captured +/// to a ``RigEntry`` via ``ShoeGaze/captureEntry(name:id:)``, and thereafter behaves exactly like a +/// user-saved rig. +/// +/// The rig names and blurbs are deliberately descriptive of the *sound*, not any trademarked pedal, +/// amplifier, or artist; a blurb may nod at the era or style a tone evokes, but a factory rig is +/// never presented as a named product or a specific performer's endorsed setup. +public struct FactoryRig: Identifiable, Sendable { + + /// Stable identifier for this rig. + /// + /// Fixed per rig (a literal, not freshly generated) so re-seeding an already-populated library + /// overwrites the same entry in place rather than creating a duplicate — `RigLibraryStore.save` + /// keys on the entry `id`. + public let id: UUID + + /// Human-readable rig name shown in the picker and used as the saved ``RigEntry`` name. + public let name: String + + /// One- or two-sentence, user-facing description of the sound and how to play it. Shown as the + /// picker subtitle / info blurb. Descriptive of the tone only — never a trademarked product or + /// an artist endorsement. + public let blurb: String + + /// Sonic family this rig belongs to, for grouping in a picker. Presentational only. + public let category: FactoryRigCategory + + /// Builds the rig's pedal chain into `board`, an empty board freshly returned by + /// `session.addBoard()`. Set pedal parameters via the typed `configure` closures of + /// ``FactoryRigLibrary``'s helpers. Do **not** call `finalizeBoard` / `captureEntry` here — the + /// seeding driver owns that lifecycle. + public let build: @MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void + + /// Creates a factory rig descriptor. + /// + /// - Parameters: + /// - id: Stable identifier (a fixed literal per rig — see ``id``). + /// - name: Rig name (picker title + saved entry name). + /// - blurb: User-facing description of the sound. + /// - category: Sonic family for picker grouping. + /// - build: Chain-building closure run against a fresh, empty board at seed time. + public init( + id: UUID, + name: String, + blurb: String, + category: FactoryRigCategory, + build: @escaping @MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void + ) { + self.id = id + self.name = name + self.blurb = blurb + self.category = category + self.build = build + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigCategory.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigCategory.swift new file mode 100644 index 0000000..4e5dd81 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigCategory.swift @@ -0,0 +1,33 @@ +// FactoryRigCategory.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Broad sonic grouping for a built-in ``FactoryRig``. +/// +/// Purely presentational: the category lets a rig picker cluster the shipped starter rigs into +/// recognisable families ("Shoegaze Walls", "Dreampop", …). It is **not** persisted in the saved +/// ``RigEntry`` — a recalled rig is just a board, indistinguishable from a user rig once loaded. +public enum FactoryRigCategory: String, CaseIterable, Sendable { + + /// Dense fuzz-and-reverb "wall of sound" textures. + case shoegazeWalls = "Shoegaze Walls" + + /// Lush, clean, chorused and delayed dream-pop voices. + case dreamPop = "Dreampop" + + /// Classic overdrive / fuzz / wah lead and rhythm tones. + case classic = "Classic" + + /// Slow, evolving, reverb-heavy ambient beds. + case ambient = "Ambient" + + /// Lo-fi, bit-crushed, and otherwise experimental noise textures. + case experimental = "Experimental" + + /// Human-readable name shown as a section header in a rig picker. + public var displayName: String { rawValue } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift new file mode 100644 index 0000000..3cb1942 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/Factory/FactoryRigLibrary.swift @@ -0,0 +1,438 @@ +// FactoryRigLibrary.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdSynth + +// MARK: - Typed board-building helper + +extension PedalBoard { + + /// Constructs a concrete pedal, applies `configure` to its typed parameters, and appends it to + /// the end of the chain. + /// + /// This is the building block for ``FactoryRig`` recipes: because `configure` receives the + /// concrete pedal type, every parameter it touches (`$0.fuzz`, `$0.time`, …) is checked by the + /// compiler against the real pedal API — a renamed control is a build error, not a silently + /// broken preset. Bus wiring is handled by ``add(_:after:)``. + /// + /// - Parameters: + /// - pedal: A freshly-constructed pedal (its default buses are overwritten by the board). + /// - configure: Sets the pedal's parameters before it is inserted. + /// - Returns: The same pedal, now wired into the chain. + /// - Throws: `BusAllocatorError.noFreeBus`, `EngineAddError`, or `ShoeGazeError.stereoWidthExceeded`. + @discardableResult + func append( + _ pedal: P, + configure: (P) -> Void + ) throws -> P { + configure(pedal) + try add(pedal) + return pedal + } +} + +// MARK: - Factory rig catalog + +/// The built-in starter rigs shipped with the app and seeded into an empty rig library on first +/// launch. +/// +/// Each entry is a ``FactoryRig`` — a compile-checked builder, not a stored JSON blob. Call +/// ``makeEntries(makeSession:)`` at seed time to materialise them into ``RigEntry`` snapshots. +/// +/// Rig names and blurbs describe the *sound*; a blurb may reference an era or style but never a +/// trademarked product or a specific artist's endorsed setup. +@MainActor +public enum FactoryRigLibrary { + + /// Every built-in rig, in the order a picker should present them. + public static let all: [FactoryRig] = [ + glideWall, + chorusCathedral, + fuzzWahClassic, + dottedEighthAnthem, + ambientShimmerBed, + springReverbSurf, + octaveFuzzLead, + bitcrushNoiseTexture, + ] + + // MARK: Shoegaze walls + + /// Dense detuned fuzz + reverse swells + plate bloom. + static let glideWall: FactoryRig = FactoryRig( + id: stableID("Glide Wall"), + name: "90s Glide Wall", + blurb: "A dense, saturated fuzz wall with reverse swells blooming around it. Hold big open " + + "chords and let the reverse delay and plate wash carry them — early-'90s British " + + "shoegaze territory.", + category: .shoegazeWalls + ) { _, board in + try board.append(FuzzPedal()) { p in + p.fuzz = 42.0 + p.tone = 2600.0 + } + try board.append(ChimeTopBoostAmpPedal()) { p in + p.gain = 6.5 + p.bass = 0.6 + p.mid = 0.4 + p.treble = 0.7 + p.cut = 0.3 + p.brilliant = 1.0 + } + try board.append(ReverseDelayPedal()) { p in + p.time = 0.45 + p.feedback = 0.4 + } + try board.append(PlateReverbPedal()) { p in + p.decay = 0.8 + p.tone = 0.7 + p.damp = 0.25 + p.mod = 0.7 + } + } + + // MARK: Dreampop + + /// Glassy clean chorus into cascading delay and octave-up shimmer. + static let chorusCathedral: FactoryRig = FactoryRig( + id: stableID("Chorus Cathedral"), + name: "Dreampop Chorus Cathedral", + blurb: "Glassy clean chorus into cascading delay and octave-up shimmer — lush and " + + "weightless. Play slow arpeggios and let every note ring into the next.", + category: .dreamPop + ) { _, board in + try board.append(CompressorPedal()) { p in + p.inputGain = 3.0 + p.threshold = -18.0 + p.ratio = 3.0 + } + try board.append(FullertonReverbAmpPedal()) { p in + p.gain = 3.5 + p.bass = 0.5 + p.mid = 0.5 + p.treble = 0.6 + // Lean on the shimmer reverb downstream rather than the amp's own tank. + p.reverbEnabled = 0.0 + p.vibratoEnabled = 0.0 + } + // Chorus is a mono→stereo widener; keep it the only width change in the chain. + try board.append(ChorusPedal()) { p in + p.rate = 0.5 + p.depth = 0.005 + } + try board.append(DelayPedal()) { p in + p.time = 0.4 + p.feedback = 2.2 + } + try board.append(ShimmerReverbPedal()) { p in + p.size = 0.09 + p.decay = 0.85 + p.shimmer = 0.55 + p.damp = 0.35 + } + } + + // MARK: Classic + + /// Envelope-wah into thick fuzz and a cranked British stack. + static let fuzzWahClassic: FactoryRig = FactoryRig( + id: stableID("Fuzz Wah Classic"), + name: "Fuzz + Wah Classic", + blurb: "Envelope-wah into thick fuzz and a cranked British stack — an expressive, vocal " + + "lead voice with a touch of spring. Dig in and the wah opens up under your picking.", + category: .classic + ) { _, board in + try board.append(AutoWahPedal()) { p in + p.sensitivity = 2.5 + p.resonance = 4.0 + p.range = 2600.0 + } + try board.append(FuzzPedal()) { p in + p.fuzz = 38.0 + p.tone = 3200.0 + } + try board.append(BritishPlexiAmpPedal()) { p in + p.gain = 8.0 + p.bass = 0.6 + p.mid = 0.6 + p.treble = 0.6 + p.presence = 0.5 + p.bright = 1.0 + } + try board.append(SpringReverbPedal()) { p in + p.decay = 1.8 + p.tension = 0.5 + p.damp = 0.3 + } + } + + /// Chiming overdrive with a rhythmic dotted-eighth delay. + static let dottedEighthAnthem: FactoryRig = FactoryRig( + id: stableID("Dotted Eighth Anthem"), + name: "Dotted-Eighth Anthem", + blurb: "Chiming overdrive with a dotted-eighth delay that turns single notes into " + + "cascading patterns — bright, anthemic, arena-sized. Tuned to a dotted eighth at 120 " + + "BPM; play on the beat and let the echoes fill the gaps.", + category: .classic + ) { _, board in + try board.append(OverdrivePedal()) { p in + p.drive = 5.0 + p.tone = 4200.0 + } + try board.append(ChimeTopBoostAmpPedal()) { p in + p.gain = 5.0 + p.bass = 0.5 + p.mid = 0.5 + p.treble = 0.65 + p.cut = 0.25 + } + try board.append(DelayPedal()) { p in + // Dotted eighth at 120 BPM = 0.375 s. + p.time = 0.375 + p.feedback = 1.6 + } + try board.append(PlateReverbPedal()) { p in + p.decay = 0.6 + p.tone = 0.8 + p.damp = 0.3 + p.mod = 0.4 + } + } + + /// Wet spring reverb and throbbing tremolo through a clean combo. + static let springReverbSurf: FactoryRig = FactoryRig( + id: stableID("Spring Reverb Surf"), + name: "Spring-Reverb Surf", + blurb: "Drippy spring reverb and throbbing tremolo through a clean Fullerton-style combo — " + + "classic surf voicing. Stab chords and ride the tremolo.", + category: .classic + ) { _, board in + try board.append(TremoloPedal()) { p in + p.rate = 5.5 + p.depth = 0.6 + } + try board.append(FullertonReverbAmpPedal()) { p in + p.gain = 3.5 + p.bass = 0.55 + p.mid = 0.5 + p.treble = 0.6 + p.reverb = 0.5 + p.reverbEnabled = 1.0 + p.vibratoEnabled = 0.0 + } + try board.append(SpringReverbPedal()) { p in + p.decay = 2.2 + p.tension = 0.6 + p.damp = 0.25 + } + } + + // MARK: Ambient + + /// Long feedback echoes into octave-up shimmer and a cavernous room. + static let ambientShimmerBed: FactoryRig = FactoryRig( + id: stableID("Ambient Shimmer Bed"), + name: "Ambient Shimmer Bed", + blurb: "Long feedback echoes wash into octave-up shimmer and a cavernous room — a slow, " + + "evolving bed for swells and volume-knob fades. Play sparse and let it bloom.", + category: .ambient + ) { _, board in + try board.append(CompressorPedal()) { p in + p.inputGain = 4.0 + p.threshold = -20.0 + p.ratio = 4.0 + } + try board.append(FeedbackDelayPedal()) { p in + p.time = 0.6 + p.feedback = 5.0 + p.tone = 3500.0 + } + try board.append(ShimmerReverbPedal()) { p in + p.size = 0.11 + p.decay = 0.9 + p.shimmer = 0.7 + p.damp = 0.3 + } + try board.append(RoomReverbPedal()) { p in + p.size = 60.0 + p.decay = 8.0 + p.damp = 0.5 + p.tail = 0.7 + } + } + + // MARK: Experimental + + /// A sub-octave layered under saturated fuzz for a thick, synth-like lead. + static let octaveFuzzLead: FactoryRig = FactoryRig( + id: stableID("Octave Fuzz Lead"), + name: "Octave-Fuzz Lead", + blurb: "A sub-octave layered under saturated fuzz for a thick, synth-like lead, pushed " + + "through a British master-volume voice. Single-note lines turn huge.", + category: .experimental + ) { _, board in + try board.append(BassOctaverPedal()) { p in + p.oct1 = 0.8 + p.oct2 = 0.2 + p.direct = 0.9 + // Track mode: follow the played pitch rather than octave-flip. + p.mode = 1.0 + } + try board.append(FuzzPedal()) { p in + p.fuzz = 45.0 + p.tone = 2800.0 + } + try board.append(BritishMasterAmpPedal()) { p in + p.gain = 7.0 + p.master = 0.5 + p.bass = 0.55 + p.mid = 0.6 + p.treble = 0.55 + p.presence = 0.4 + } + try board.append(DelayPedal()) { p in + p.time = 0.28 + p.feedback = 1.4 + } + } + + /// Gritty sample-rate crushing into runaway feedback delay and a wide room. + static let bitcrushNoiseTexture: FactoryRig = FactoryRig( + id: stableID("Bitcrush Noise Texture"), + name: "Bitcrush Noise Texture", + blurb: "Gritty sample-rate crushing into runaway feedback delay and a wide room — harsh, " + + "lo-fi and unstable in the best way. Made for drones and glitch textures.", + category: .experimental + ) { _, board in + try board.append(BitcrusherPedal()) { p in + p.crush = 6.0 + p.bits = 5.0 + p.tone = 3200.0 + } + try board.append(FeedbackDelayPedal()) { p in + p.time = 0.33 + p.feedback = 4.0 + p.tone = 2800.0 + } + try board.append(ReverbPedal()) { p in + p.roomSize = 0.8 + p.damping = 0.4 + } + } + + // MARK: - Seeding + + /// Builds every factory rig into a ``RigEntry`` snapshot suitable for the rig library. + /// + /// Each rig is constructed in a fresh, **never-started** ``ShoeGaze`` session (capturing a rig + /// only reads `@UIParam` values — no audio is rendered), captured with the rig's stable `id`, and + /// the session is torn down before the next. Because ids are stable, re-running this against an + /// already-seeded library overwrites entries in place rather than duplicating them. + /// + /// - Parameter makeSession: Returns a fresh, empty session (typically backed by an offline + /// engine). Called once per rig. + /// - Returns: One ``RigEntry`` per ``all`` rig, in catalog order. + /// - Throws: Any error from session creation, board building, or finalisation. + public static func makeEntries( + makeSession: @MainActor () throws -> ShoeGaze + ) throws -> [RigEntry] { + var entries: [RigEntry] = [] + entries.reserveCapacity(all.count) + for rig: FactoryRig in all { + let session: ShoeGaze = try makeSession() + // Tear down on every exit from this iteration, including a throw from `build` / + // `finalizeBoard`, so a failing rig never leaks its throwaway engine's buses/nodes. + defer { session.teardown() } + let board: PedalBoard = try session.addBoard() + try rig.build(session, board) + try session.finalizeBoard(board) + entries.append(session.captureEntry(name: rig.name, id: rig.id)) + } + return entries + } + + /// Builds every factory rig using a self-contained offline engine per rig. + /// + /// Convenience over ``makeEntries(makeSession:)`` for callers with no session of their own (the + /// first-launch seeding path). Each rig gets a fresh ``NRTDriver``-backed engine that is never + /// started — no audio is rendered and no output file is written (the driver only touches disk in + /// `start()`), so the temporary URL handed to the driver never comes into existence. + /// + /// - Returns: One ``RigEntry`` per ``all`` rig, in catalog order. + /// - Throws: Any error from board building or finalisation. + public static func makeEntries() throws -> [RigEntry] { + try makeEntries(makeSession: makeOfflineSeedSession) + } + + /// Block size for the throwaway seeding engine. Matches the framework default; never renders. + private static let seedBlockSize: Int = 512 + + /// Sample rate for the throwaway seeding engine. Only affects `@UIParam` capture indirectly; no + /// audio is produced. + private static let seedSampleRate: Double = 44_100.0 + + /// Audio bus count for the throwaway seeding engine — generous headroom for the longest chain. + private static let seedAudioBusCount: Int = 128 + + /// Control bus count for the throwaway seeding engine. + private static let seedControlBusCount: Int = 512 + + /// Nominal render duration handed to the offline driver. Unused — the engine is never started. + private static let seedRenderDuration: Double = 0.05 + + /// Creates a fresh, never-started offline ``ShoeGaze`` session for building one factory rig. + private static func makeOfflineSeedSession() -> ShoeGaze { + let outputURL: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".caf") + let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: seedRenderDuration) + let engine: SynthesisEngine = SynthesisEngine( + blockSize: seedBlockSize, + sampleRate: seedSampleRate, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: seedAudioBusCount, + numControlBuses: seedControlBusCount, + driver: driver + ) + return ShoeGaze(engine: engine, inputSource: .testLoop) + } + + // MARK: - Stable identifiers + + /// Deterministic UUID derived from a rig's identity string via two FNV-1a hashes. + /// + /// Gives each rig a stable library id across launches without a hand-written UUID literal, and + /// keeps seeding idempotent (same id ⇒ overwrite in place). Not a cryptographic identifier — + /// only stability and per-rig uniqueness matter here. + static func stableID(_ seed: String) -> UUID { + let fnvOffset: UInt64 = 0xcbf2_9ce4_8422_2325 + let fnvPrime: UInt64 = 0x0000_0100_0000_01b3 + + func hash(_ string: String) -> UInt64 { + var value: UInt64 = fnvOffset + for byte: UInt8 in string.utf8 { + value = (value ^ UInt64(byte)) &* fnvPrime + } + return value + } + + let high: UInt64 = hash(seed) + let low: UInt64 = hash(seed + "\u{1}salt") + + func byte(_ source: UInt64, _ shift: UInt64) -> UInt8 { + UInt8((source >> shift) & 0xFF) + } + + let bytes: uuid_t = ( + byte(high, 56), byte(high, 48), byte(high, 40), byte(high, 32), + byte(high, 24), byte(high, 16), byte(high, 8), byte(high, 0), + byte(low, 56), byte(low, 48), byte(low, 40), byte(low, 32), + byte(low, 24), byte(low, 16), byte(low, 8), byte(low, 0) + ) + return UUID(uuid: bytes) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift index 8c3f876..902e2a1 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift @@ -39,15 +39,65 @@ public enum RigLibraryBootstrap { // 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 } + guard store.entries.isEmpty else { return } + + // First run: populate the library with the shipped starter rigs. These are built in + // throwaway offline sessions, so they are independent of the current working graph. The + // working session is intentionally left as-is (no `currentRigID`) — the user picks a starter + // rig from the sidebar to load it, rather than the highlight pointing at a rig the working + // graph has not actually loaded. + let entries: [RigEntry] + do { + entries = try FactoryRigLibrary.makeEntries() + } catch { + // Building the shipped rigs is deterministic and should never fail at runtime; if it + // somehow does, fall back to seeding the working rig so the library is not left empty. + print("[RigLibraryBootstrap] building factory rigs failed: \(error)") + seedWorkingRig(store, seedFrom: shoeGaze, seedName: seedName) + return + } + + // Save sequentially, rolling back on failure. Seeding is gated on `store.entries.isEmpty`, + // so a partially-saved library would be frozen forever (never retried, never completed). If + // any save fails, delete the entries saved this run so the library returns to empty and a + // later launch retries the full seed. (This is best-effort, not truly atomic: if a rollback + // `delete` itself fails, a partial set can still be left behind and frozen — the residual + // hole a non-transactional store cannot fully close.) + var savedThisRun: [RigEntry] = [] + do { + for entry: RigEntry in entries { + try store.save(entry) + savedThisRun.append(entry) + } + } catch { + print("[RigLibraryBootstrap] seeding factory rigs failed after " + + "\(savedThisRun.count)/\(entries.count); rolling back: \(error)") + for entry: RigEntry in savedThisRun { + do { + try store.delete(entry) + } catch { + print("[RigLibraryBootstrap] rollback of '\(entry.name)' failed: \(error)") + } + } + } + } + + /// Seeds the working session's current rig as a single named library entry. + /// + /// Last-resort fallback used only when the factory rigs could not be built; keeps the library + /// from being left empty on first run. + private static func seedWorkingRig( + _ store: RigLibraryStore, + seedFrom shoeGaze: ShoeGaze, + seedName: String + ) { + guard !shoeGaze.boards.isEmpty else { return } let entry: RigEntry = shoeGaze.captureEntry(name: seedName) do { try store.save(entry) - // The seeded entry was captured from the working graph, so it is the session's source - // rig — record it so the sidebar highlights it and the autosave envelope carries it. shoeGaze.currentRigID = entry.id } catch { - print("[RigLibraryBootstrap] seeding library failed: \(error)") + print("[RigLibraryBootstrap] fallback seeding failed: \(error)") } } } diff --git a/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift new file mode 100644 index 0000000..650a1e6 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/FactoryRigLibraryTests.swift @@ -0,0 +1,105 @@ +// FactoryRigLibraryTests.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("FactoryRigLibrary") +struct FactoryRigLibraryTests { + + // MARK: - Catalog integrity + + @Test func catalogIsWellFormed() { + let rigs: [FactoryRig] = FactoryRigLibrary.all + #expect(rigs.count >= 6, "expected a full starter slate") + + let ids: Set = Set(rigs.map { $0.id }) + #expect(ids.count == rigs.count, "rig ids must be unique") + + let names: Set = Set(rigs.map { $0.name }) + #expect(names.count == rigs.count, "rig names must be unique") + + let minBlurbLength: Int = 20 + for rig: FactoryRig in rigs { + #expect(!rig.name.isEmpty, "\(rig.name) has empty name") + #expect(rig.blurb.count >= minBlurbLength, "\(rig.name) blurb too short") + } + + // The slate should span more than one sonic family. + let categories: Set = Set(rigs.map { $0.category }) + #expect(categories.count >= 3, "starter slate should cover several categories") + } + + @Test func blurbsAvoidTrademarkedProductNames() { + // Guard against a blurb accidentally naming a real amp/pedal brand: factory rigs describe + // the sound, never a trademarked product. + let forbidden: [String] = [ + "marshall", "fender", "vox", "mesa", "boss", "orange", "dumble", "roland", "ibanez", + ] + for rig: FactoryRig in FactoryRigLibrary.all { + let haystack: String = (rig.name + " " + rig.blurb).lowercased() + for brand: String in forbidden { + #expect(!haystack.contains(brand), "\(rig.name) mentions '\(brand)'") + } + } + } + + // MARK: - Seeding entries + + @Test func makeEntriesMatchesCatalogAndIsStable() throws { + let entries: [RigEntry] = try FactoryRigLibrary.makeEntries() + let rigs: [FactoryRig] = FactoryRigLibrary.all + + #expect(entries.count == rigs.count, "one entry per rig") + for (entry, rig): (RigEntry, FactoryRig) in zip(entries, rigs) { + #expect(entry.id == rig.id, "entry id must be the rig's stable id") + #expect(entry.name == rig.name) + #expect(entry.state.boards.count == 1, "\(rig.name) should build exactly one board") + let pedalCount: Int = entry.state.boards.first?.pedals.count ?? 0 + #expect(pedalCount >= 3, "\(rig.name) should build a non-trivial chain") + } + + // Stable ids: re-seeding yields identical ids (so a re-seed overwrites in place). + let again: [RigEntry] = try FactoryRigLibrary.makeEntries() + #expect(entries.map { $0.id } == again.map { $0.id }) + } + + @Test func entriesRoundTripThroughJSON() throws { + let encoder: JSONEncoder = JSONEncoder() + let decoder: JSONDecoder = JSONDecoder() + for entry: RigEntry in try FactoryRigLibrary.makeEntries() { + let data: Data = try encoder.encode(entry) + let decoded: RigEntry = try decoder.decode(RigEntry.self, from: data) + #expect(decoded == entry, "\(entry.name) did not survive a JSON round-trip") + } + } + + // MARK: - Load + render (full ship path) + + @Test func everyFactoryEntryLoadsAndRenders() throws { + let renderDuration: Double = 0.2 + let numAudioBuses: Int = 128 + + for entry: RigEntry in try FactoryRigLibrary.makeEntries() { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: renderDuration, + numAudioBuses: numAudioBuses + ) + defer { try? FileManager.default.removeItem(at: url) } + + let session: ShoeGaze = ShoeGaze(engine: engine) + try session.loadRig(from: entry.state) + + try engine.start() + let samples: [Float] = readStereoCAF(url: url) + #expect(hasNonSilentOutput(samples), "\(entry.name) rendered silence") + } + } +}