// 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 { /// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig. /// /// Because factory rigs are seeded with their fixed ``FactoryRig/id``, an entry recalled from the /// library can be identified as shipped-vs-user by id membership here. Callers use this to guard /// destructive actions (e.g. warn before overwriting a starter rig). public static let factoryIDs: Set = Set(all.map { $0.id }) /// Whether `id` belongs to a shipped factory rig. /// /// - Parameter id: A ``RigEntry/id`` from the rig library. /// - Returns: `true` if the entry is one of the built-in starter rigs. public static func isFactory(_ id: UUID) -> Bool { factoryIDs.contains(id) } /// 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) } }