// 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 } } extension ChainRouter { /// Constructs a concrete pedal, applies `configure`, and appends it to board A of the router. /// /// The concrete-type `configure` closure keeps every parameter compile-checked, exactly like /// ``PedalBoard/append(_:configure:)``. Uses ``addToA(_:)`` so ``finalize()`` ordering stays correct. @discardableResult func appendToA(_ pedal: P, configure: (P) -> Void) throws -> P { configure(pedal) try addToA(pedal) return pedal } /// Constructs a concrete pedal, applies `configure`, and appends it to board B of the router. @discardableResult func appendToB(_ pedal: P, configure: (P) -> Void) throws -> P { configure(pedal) try addToB(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 { /// Catalog seed version. Bump this whenever the shipped starter rigs change — new rigs added, or /// an existing rig's definition corrected — so launch catch-up re-runs on already-populated /// libraries and refreshes every starter to its current form. Within a single version the marker /// only advances once, so a starter the user deletes stays deleted until the next bump. public static let seedVersion: Int = 4 /// 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) } /// The ``FactoryRigCategory`` of the shipped rig with this id, or `nil` for a user rig. /// /// - Parameter id: A ``RigEntry/id`` from the rig library. /// - Returns: The rig's category, or `nil` if `id` is not a factory rig. public static func category(for id: UUID) -> FactoryRigCategory? { all.first(where: { $0.id == id })?.category } /// The shipped rigs of a given category, in catalog order. /// /// - Parameter category: The category to filter by. /// - Returns: The `FactoryRig`s in `category`, in the order they appear in ``all``. public static func rigs(in category: FactoryRigCategory) -> [FactoryRig] { all.filter { $0.category == category } } /// 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, funkEnvelopeClav, postRockCrescendo, nashvilleCleanComp, dubDelayThrow, ringModTexture, rockabillySlapback, psychVibeLead, comfortablyNumbLead, doomRiffWall, garciaOBELSplit, ] // 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 = 1.5 } try board.append(ShimmerReverbPedal()) { p in // Keep decay + shimmer well below self-oscillation — the loop gain is ~decay + shimmer, so // high values screech into runaway feedback with little or no input. p.size = 0.09 p.decay = 0.5 p.shimmer = 0.25 p.damp = 0.5 } } // 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 // Long ambient tail, but decay + shimmer kept under ~0.8 so it never self-oscillates; the // room reverb downstream supplies the extra length. p.size = 0.11 p.decay = 0.6 p.shimmer = 0.2 p.damp = 0.5 } 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: More classic voices /// Envelope filter into light overdrive and a clean amp — funky, vocal, touch-sensitive. static let funkEnvelopeClav: FactoryRig = FactoryRig( id: stableID("Funk Envelope Clav"), name: "Funk Envelope Clav", blurb: "An envelope filter that opens with your picking, into light grit and a clean amp — " + "funky and vocal, the classic auto-wah clav voice. Play staccato and let your " + "dynamics work the filter.", category: .classic ) { _, board in try board.append(MutantPedal()) { p in p.sensitivity = 3.0 p.resonance = 6.0 } try board.append(OverdrivePedal()) { p in p.drive = 3.0 p.tone = 4500.0 } try board.append(JazzCleanAmpPedal()) { p in p.gain = 4.0 p.bass = 0.5 p.mid = 0.6 p.treble = 0.6 p.reverb = 0.15 p.chorusEnabled = 0.0 } } /// Compressed clean into slapback echo and spring — bright, springy country/rockabilly. static let nashvilleCleanComp: FactoryRig = FactoryRig( id: stableID("Nashville Clean Comp"), name: "Nashville Clean Comp", blurb: "Squashed clean tone into a short slapback and spring reverb — bright, snappy and " + "articulate, the Nashville country voice. Hybrid-pick and let the compressor even it " + "out.", category: .classic ) { _, board in try board.append(CompressorPedal()) { p in p.inputGain = 3.0 p.threshold = -16.0 p.ratio = 4.0 } try board.append(FullertonReverbAmpPedal()) { p in p.gain = 3.0 p.bass = 0.5 p.mid = 0.55 p.treble = 0.65 p.reverb = 0.3 p.reverbEnabled = 1.0 p.vibratoEnabled = 0.0 } try board.append(DelayPedal()) { p in // Short slapback. p.time = 0.11 p.feedback = 0.3 } } /// Compressed chime into tight slapback and spring — classic rockabilly. static let rockabillySlapback: FactoryRig = FactoryRig( id: stableID("Rockabilly Slapback"), name: "Rockabilly Slapback", blurb: "Compressed chime with a tight tape-style slapback and spring — the rockabilly " + "bounce. Palm-mute and dig in for the classic '50s snap.", category: .classic ) { _, board in try board.append(CompressorPedal()) { p in p.inputGain = 2.0 p.threshold = -14.0 p.ratio = 3.0 } try board.append(ChimeTopBoostAmpPedal()) { p in p.gain = 4.0 p.bass = 0.5 p.mid = 0.5 p.treble = 0.65 p.cut = 0.2 } try board.append(DelayPedal()) { p in // Very short slapback echo. p.time = 0.09 p.feedback = 0.25 } try board.append(SpringReverbPedal()) { p in p.decay = 1.2 p.tension = 0.6 p.damp = 0.3 } } // MARK: More ambient / experimental voices /// Overdriven arpeggios into long delay and shimmer — a swelling post-rock build. static let postRockCrescendo: FactoryRig = FactoryRig( id: stableID("Post-Rock Crescendo"), name: "Post-Rock Crescendo", blurb: "Warm overdrive into a long delay and octave-up shimmer — a swelling, cinematic " + "post-rock build. Layer arpeggios and let the wash grow into a crescendo.", category: .ambient ) { _, board in try board.append(OverdrivePedal()) { p in p.drive = 6.0 p.tone = 4000.0 } try board.append(DelayPedal()) { p in p.time = 0.5 p.feedback = 2.5 } try board.append(ShimmerReverbPedal()) { p in p.size = 0.1 p.decay = 0.55 p.shimmer = 0.25 p.damp = 0.5 } } /// A dub-style feedback echo washing into deep spring — sparse, spacious, delay-forward. static let dubDelayThrow: FactoryRig = FactoryRig( id: stableID("Dub Delay Throw"), name: "Dub Delay Throw", blurb: "A long, dark feedback echo washing into deep spring reverb — the dub delay-throw. " + "Play sparse skanks and ride the feedback for runaway repeats.", category: .ambient ) { _, board in try board.append(CompressorPedal()) { p in p.inputGain = 2.0 p.threshold = -16.0 p.ratio = 3.0 } try board.append(FeedbackDelayPedal()) { p in p.time = 0.45 p.feedback = 6.0 p.tone = 2500.0 } try board.append(SpringReverbPedal()) { p in p.decay = 2.5 p.tension = 0.5 p.damp = 0.35 } } /// Ring modulation into delay and reverb — clangorous, inharmonic, otherworldly. static let ringModTexture: FactoryRig = FactoryRig( id: stableID("Ring-Mod Texture"), name: "Ring-Mod Texture", blurb: "Ring modulation into delay and a wide room — clangorous, inharmonic and " + "otherworldly. Try single notes and let the metallic overtones ring out.", category: .experimental ) { _, board in try board.append(RingModulatorPedal()) { p in p.frequency = 180.0 } try board.append(DelayPedal()) { p in p.time = 0.3 p.feedback = 1.8 } try board.append(ReverbPedal()) { p in p.roomSize = 0.75 p.damping = 0.4 } } /// Fuzz swirled by a throbbing vibe into delay and plate — vintage psychedelic lead. static let psychVibeLead: FactoryRig = FactoryRig( id: stableID("Psych Vibe Lead"), name: "Psychedelic Vibe Lead", blurb: "Thick fuzz swirled by a throbbing photocell vibe, into delay and plate — the " + "late-'60s psychedelic lead voice. Hold notes and let the vibe pulse underneath.", category: .classic ) { _, board in try board.append(FuzzPedal()) { p in p.fuzz = 30.0 p.tone = 3000.0 } try board.append(VibePedal()) { p in p.speed = 2.5 p.intensity = 0.6 // Chorus mode: dry + swept, the classic vibe throb. p.mode = 0.0 } try board.append(DelayPedal()) { p in p.time = 0.4 p.feedback = 2.0 } try board.append(PlateReverbPedal()) { p in p.decay = 0.6 p.tone = 0.75 p.damp = 0.3 p.mod = 0.5 } } /// Compressed sustaining fuzz into a dotted delay and shimmer — a soaring, singing lead. static let comfortablyNumbLead: FactoryRig = FactoryRig( id: stableID("Comfortably Numb Lead"), name: "Comfortably Numb Lead", blurb: "Compressed, mid-scooped sustain fuzz into a dotted delay and octave-up shimmer — a " + "soaring, singing lead that holds forever. Bend into long notes and let them bloom.", category: .classic ) { _, board in try board.append(CompressorPedal()) { p in p.inputGain = 4.0 p.threshold = -18.0 p.ratio = 4.0 } try board.append(SustainFuzzPedal()) { p in p.sustain = 14.0 p.tone = 3000.0 p.scoop = 10.0 } try board.append(DelayPedal()) { p in // Dotted eighth at ~100 BPM. p.time = 0.45 p.feedback = 2.2 } try board.append(ShimmerReverbPedal()) { p in p.size = 0.09 p.decay = 0.55 p.shimmer = 0.25 p.damp = 0.5 } } /// Sub-octave under a huge scooped fuzz into a cavernous room — heavy, slow doom. static let doomRiffWall: FactoryRig = FactoryRig( id: stableID("Doom Riff Wall"), name: "Doom Riff Wall", blurb: "A sub-octave stacked under a huge mid-scooped fuzz, into a cavernous room — crushing, " + "slow doom. Down-tune, play half-time and let the low end swallow the room.", category: .experimental ) { _, board in try board.append(BassOctaverPedal()) { p in p.oct1 = 0.8 p.oct2 = 0.3 p.direct = 0.9 // Track mode: follow the played pitch. p.mode = 1.0 } try board.append(SustainFuzzPedal()) { p in p.sustain = 22.0 p.tone = 2200.0 p.scoop = 6.0 } try board.append(RoomReverbPedal()) { p in p.size = 70.0 p.decay = 6.0 p.damp = 0.55 p.tail = 0.7 } } // MARK: Two-board split /// Two boards — a full effects chain and a clean direct path — switched with the board selector. static let garciaOBELSplit: FactoryRig = FactoryRig( id: stableID("Garcia OBEL Split"), name: "Garcia OBEL Clean/Effects Split", blurb: "Two boards, one selector: Board 1 is an effects/lead chain (octave, envelope filter, " + "overdrive, graphic EQ, phaser, delay, reverb); Board 2 is a fuller direct voice " + "(overdrive, graphic EQ, compression, reverb). Use the board Solo / Blend control at the " + "top to switch between them, like an on-board effects loop. In the spirit of a certain " + "improvising guitarist's late-'80s rig.", category: .classic, // Hand-authored in the app and shipped as a captured state — transcribing the exact pedal // values (mix, graphic-EQ sliders, cab selector, amp sag/bias) is more faithful than // re-deriving them through typed setters. Input source / channel counts are intentionally // omitted so the rig is input-agnostic. state: garciaState ) /// The shipped Garcia rig content. `static let` so its (default) pedal ids are stable per process, /// keeping seeding deterministic. private static let garciaState: ShoeGazeState = ShoeGazeState( boards: [ BoardState(label: "Board 1", pedals: [ PedalState(type: "Bass Octaver", knobValues: [0.5, 0, 1, 1, 1], switchValues: [1], bypass: 0), PedalState(type: "Mutant", knobValues: [2.5, 4.45515625, 1, 1], switchValues: [1, 0], bypass: 0), PedalState(type: "Overdrive", knobValues: [5, 4200, 1, 1], bypass: 0), PedalState(type: "Graphic EQ", knobValues: [1, 1], sliderValues: [-4.7786931818181815, -2.214204545454546, 1.552840909090909, 1.8536931818181799, -3.3426136363636374, -0.45852272727272947], bypass: 0), PedalState(type: "Phaser", knobValues: [0.4, 0.4, 0.5, 1], bypass: 0), PedalState(type: "Delay", knobValues: [0.35, 1.8, 0.35, 1], bypass: 0), PedalState(type: "Fullerton Reverb", knobValues: [2.5505078125, 0.5, 0.5, 0.6, 0.25, 4, 0, 1, 1], switchValues: [0, 1, 0], selectorValues: [4], advancedValues: [0, 0.5, 0], bypass: 0), ]), BoardState(label: "Board 2", pedals: [ PedalState(type: "Overdrive", knobValues: [6.54533203125, 4000, 1, 1], bypass: 0), PedalState(type: "Graphic EQ", knobValues: [1, 1], sliderValues: [2.957386363636365, 0, 2.7741477272727266, 1.940624999999999, -0.6767045454545446, 0], bypass: 0), PedalState(type: "Compressor", knobValues: [2, -16, 3, 1, 1], switchValues: [0], bypass: 0), PedalState(type: "Fullerton Reverb", knobValues: [5.08, 0.5, 0.5, 0.6, 0.13624999999999998, 4, 0, 1, 1], switchValues: [0, 1, 0], selectorValues: [4], advancedValues: [0, 0.5, 0], bypass: 0), ]), ], bpm: 120, tempoEnabled: true ) // 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 { // A state-backed rig needs no live session — build its entry directly from the state. if case .state(let makeState) = rig.build { entries.append(RigEntry(id: rig.id, name: rig.name, state: makeState())) continue } let session: ShoeGaze = try makeSession() // Tear down on every exit from this iteration, including a throw from a builder, so a // failing rig never leaks its throwaway engine's buses/nodes. defer { session.teardown() } switch rig.build { case .singleBoard(let build): let board: PedalBoard = try session.addBoard() try build(session, board) try session.finalizeBoard(board) case .session(let build): // The builder owns its own board/router lifecycle (addBoard/finalizeBoard, // makeChainRouter/finalize). try build(session) case .state: continue // handled above } 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) } }