# ShoeGaze — Guitar Pedalboard Framework ShoeGaze is a nested SwiftPM sub-package (`ShoeGaze/`) that models a guitar-effect signal chain as a sequence of `Pedal` objects managed by a `PedalBoard`, all hosted by a `ShoeGaze` manager that owns the `SynthesisEngine`. --- ## Core Concepts ### `Pedal` A `Pedal` is a `SynthesizerBase` subclass that reads a mono signal from its input bus, runs it through a subclass-supplied `effect(_:)` stage, blends wet/dry with an equal-power crossfade (`mix`), applies a click-free `bypass` crossfade, scales by `level`, and writes to its output bus. Each pedal exposes its knobs as `@UIParam` properties and publishes a `knobs: [PedalKnob]` list so `PedalView` (from `LyrebirdShoeGazeUI`) renders a control per parameter. Eight built-in pedals (the signal chain is mono; stereo-native effects fold to mono internally): | Type | Effect | |---|---| | `OverdrivePedal` | Soft-clip saturation → RBJ low-pass tone. Knobs: `drive`, `tone` | | `DelayPedal` | Feedback delay line. Knobs: `time`, `feedback` | | `ReverbPedal` | Freeverb (stereo, summed to mono). Knobs: `roomSize`, `damping` | | `ModulationPedal` | Chorus (stereo, summed to mono). Knobs: `rate`, `depth` | | `FuzzPedal` | High-gain `tanh` saturation (drive → square-up) → RBJ low-pass tone. Knobs: `fuzz`, `tone` | | `TremoloPedal` | Unipolar sine LFO amplitude modulation. Knobs: `rate`, `depth` | | `PhaserPedal` | Cascaded all-pass stages swept by a sine LFO. Knobs: `rate`, `feedback` | | `CompressorPedal` | Feed-forward dynamic range compressor. Knobs: `threshold`, `ratio` | Every pedal also inherits the common `mix`, `bypass`, and `level` controls from `Pedal`. Write a custom pedal by subclassing `Pedal`, overriding `effect(_:)` to return a mono processed signal, and overriding `effectKnobs` to publish its `@UIParam` knobs. The base class handles wet/dry mixing, bypass, and output gain. ### `PedalBoard` A `PedalBoard` is an ordered collection of pedals. Pedals are appended in signal-flow order with `board.add(pedal)`. A board must be finalised with `shoeGaze.finalizeBoard(board)` before audio flows through it — finalisation wires the signal chain and adds all pedals to the engine. ### `ShoeGaze` `ShoeGaze` owns the `SynthesisEngine` and manages one or more `PedalBoard` instances. The engine lifecycle is caller-owned: `ShoeGaze` itself has no `start()` / `stop()` methods. `ShoeGazeView` provides Start/Stop transport buttons that call `engine.start()` / `engine.stop()`, or the app can drive the engine directly. ```swift let shoeGaze = ShoeGaze(engine: engine) let board = try shoeGaze.addBoard() try board.add(OverdrivePedal()) try board.add(DelayPedal()) try shoeGaze.finalizeBoard(board) ``` ### Input sources Every `PedalBoard` has an `InputSource` that determines what feeds the first pedal in the chain: | Source | Description | |---|---| | `.testLoop` (default) | Built-in synthesized test signal — no audio hardware input needed | | `.liveInput(channel:)` | Routes a hardware input channel (zero-based; bus `numOutputChannels + channel`) from the microphone / audio interface | The source is set on the `ShoeGaze` manager at init; every board it creates uses it: ```swift let shoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: 0)) let board = try shoeGaze.addBoard() ``` `liveInput` requires `numInputChannels > 0` in the `SynthesisEngine` init and the appropriate OS permission (microphone entitlement on macOS, `NSMicrophoneUsageDescription` in Info.plist for iOS). ### Recording `ShoeGaze` can record the raw **input** and the overall **output** to timestamped WAV files (via core `DiskOut.Audio`): - `ShoeGaze.recordingFolder: URL?` — destination folder (set from the UI's folder picker). - `ShoeGaze.startRecording() throws` — writes `output-.wav` (stereo hardware output) and `input-<…>.wav` (the raw input: the hardware input channel for `.liveInput`, or the first board's head bus for `.testLoop`). Throws `ShoeGazeError.recordingFolderNotSet` if no folder is set; creates the folder if missing. - `ShoeGaze.stopRecording()` — removes the taps and flushes/closes the files. - `ShoeGaze.isRecording: Bool`. The record taps are inserted `.after(engine.mainGroup)` so they capture each block's fully processed bus values. `ShoeGazeView` provides a **Choose Folder…** button and a **Record/Stop** button (disabled until a folder is chosen). For the cleanest tail of the file, stop the engine before `stopRecording()` (engine node removal is asynchronous, so the last block or two may be dropped otherwise). ### Board selection & crossfade By default every board's output sums to the hardware output. To make only one board audible at a time — switching between them without clicks — use: - `ShoeGaze.selectBoard(_ board:, crossfadeSeconds:)` — solo `board`, crossfading the others out. - `ShoeGaze.selectAllBoards(crossfadeSeconds:)` — restore the summed (all-audible) state. - `ShoeGaze.activeBoardIndex: Int?` — the soloed board index, or `nil` when all are audible. Each board's output master carries a lagged board-select gain (separate from the master volume knob); `crossfadeSeconds` sets the lag time, so a switch is a click-free crossfade of that duration (`0` = instant). `ShoeGazeView` exposes an "Active" board picker plus a crossfade-seconds field driving these calls. --- ## Parallel routing (split / merge) Two routing primitives let a signal fan out to two parallel paths and recombine: - **`Splitter`** — one input bus → two branch buses, each gated by a click-free, lagged enable (`@UIParam branchAEnabled` / `branchBEnabled`). The `mode: SplitMode` convenience selects `.a` (branch A only), `.b` (branch B only), or `.both` (parallel). A/B switching is click-free. - **`Merger`** — two branch buses → one output bus, each scaled by `@UIParam levelA` / `levelB`, summed. Both are `SynthesizerBase` routing nodes (not `Pedal`s — multi-bus, no wet/dry). They power two layers: ### Intra-board: a parallel section inside one board `PedalBoard.split()` inserts a splitter at the current chain tail and returns a `ParallelSection` with two `BranchChain`s; populate each branch, then `PedalBoard.merge(_:)` sums them back into the chain. Series pedals before and after compose normally. ```swift let board = try shoeGaze.addBoard() try board.add(OverdrivePedal()) // series pre let section = try board.split() // → splitter try section.branchA.add(DelayPedal()) // branch A try section.branchB.add(FuzzPedal()) // branch B try board.merge(section) // → merger try board.add(ReverbPedal()) // series post try shoeGaze.finalizeBoard(board) section.splitter.mode = .both // run both branches ``` Branches use independent buses; the merge node is inserted after both branches so they evaluate first. Node-tree order: `pre → splitter → branch pedals → merger → post`. ### Inter-board: an A/B chain router `ShoeGaze.makeChainRouter()` returns a `ChainRouter` that feeds one shared input through a splitter to **two whole boards** (`boardA` / `boardB`), then a merger + master to the hardware output. `router.mode` toggles which chain is audible (or both). ```swift let router = try shoeGaze.makeChainRouter() try router.boardA.add(OverdrivePedal()) try router.boardA.add(DelayPedal()) try router.boardB.add(FuzzPedal()) try router.boardB.add(ReverbPedal()) try router.finalize() router.mode = .a // chain A live; toggle to .b / .both ``` The router owns its source, splitter, merger, and master (it does not use the per-board source/master of `addBoard`/`finalizeBoard`). `ChainRouter.teardown()` removes all nodes before releasing buses; `ShoeGaze.teardown()` tears down routers too. --- ## SwiftUI — `LyrebirdShoeGazeUI` `LyrebirdShoeGazeUI` provides ready-made SwiftUI views: | View | Description | |---|---| | `ShoeGazeView(shoeGaze:)` | Top-level view: transport controls + all boards | | `PedalBoardView(board:)` | Horizontal scroll of `PedalView` tiles for one board | | `PedalView(pedal:)` | Single pedal tile: bypass toggle + one knob per entry in `pedal.knobs` | | `SplitterView(splitter:)` | 3-way A / B / Both mode selector + per-branch enable LEDs | | `MergerView(merger:)` | Branch A / B level knobs | | `ParallelSectionView(section:)` | Splitter + the two branch pedal rows for an intra-board section | | `ChainRouterView(router:)` | Splitter + master knob, boards A/B, and the merger for an A/B chain router | | `BoardEditorView(shoeGaze:boardIndex:versionStore:)` | Auto-laid-out board editor: wrap-to-fit pedal grid + save/load version toolbar | | `FlowLayout` | A `Layout` that wraps subviews left-to-right to fit the available width (used by the editor) | `PedalView` renders the descriptors a pedal publishes via its `knobs: [PedalKnob]` list (effect knobs, then the common `mix` and `level`). A custom pedal gets knobs by overriding `effectKnobs` — no view code is required. --- ## Board versions & auto-layout editor `BoardEditorView(shoeGaze:boardIndex:versionStore:)` visualizes one board: its pedals are arranged by `FlowLayout`, a SwiftUI `Layout` that flows pedals left-to-right and wraps to the next row to fit the window width (a real pedalboard look). A toolbar saves and recalls **versions** of the board. Backend: - `PedalBoard.captureState() -> BoardState` snapshots a board (label + each pedal's type + knob/bypass values). - `ShoeGaze.rebuildBoard(_:from:) throws -> PedalBoard` tears the board down and recreates it from a `BoardState` — recreating pedals via `PedalRegistry` and restoring knob values — **at the same index** in `boards` (unknown pedal types are skipped). Call with the engine stopped (same async-removal caveat as `teardown`). - `BoardVersionStore` (`@Observable`) holds named `BoardVersion`s (`id`, `name`, `savedAt`, `state`) in memory and persists them as JSON: - `capture(board, name:)` snapshots the current board. - `writeAllToDisk(in:)` / `loadAllFromDisk(in:)` round-trip versions to a directory (`BoardVersionStore.defaultDirectory()` = `/LyrebirdShoeGaze/ShoeGazeVersions/`). ```swift let store = BoardVersionStore() store.capture(board, name: "Crunch rhythm") // snapshot current knobs try store.writeAllToDisk(in: BoardVersionStore.defaultDirectory()) // later — recall, rebuilding the board from the saved version: _ = try shoeGaze.rebuildBoard(board, from: store.versions[0].state) ``` In the UI, "Save Version" snapshots the live board, the Versions menu loads one (rebuilding in place), and Save/Load-to-disk persist the set. Because `ShoeGaze` and `BoardVersionStore` are `@Observable`, the editor re-renders automatically after a capture or rebuild. --- ## Sharing — the `.shoegaze` document type Exporting and sharing use a single registered document type: **`.shoegaze`** (UTType `net.realizedsound.shoegaze`, conforming to `public.json`, so the file stays text-readable). The two builder apps (macOS `ShoeGazeBuilder`, iPad `ShoeGazeBuilderiOS`) declare it (`CFBundleDocumentTypes` + `UTExportedTypeDeclarations`) and implement opening (`application(_:open:)` / `.onOpenURL` → import into the library), so the system associates `.shoegaze` files with them for Open and Share. The minimal player demos do not claim the type — they have no library or share UI. - `ShoeGazeDocument` (in `LyrebirdShoeGaze`) is a versioned envelope around one of two payloads: `.rigs(RigArchive)` (one or many rigs — a single shared rig is a one-rig archive) or `.board(BoardVersion)` (a single board). `data()` encodes pretty-printed JSON; `ShoeGazeDocument.decoded(from:)` reads it back and also accepts the two legacy shapes (a bare `RigArchive`, a bare `ShoeGazeState`). - `RigLibraryStore.exportDocumentData()` writes the whole library as a `.shoegaze` document; `importArchive(from:)` accepts `.shoegaze`, bare `RigArchive`, and legacy single-rig JSON (internal per-rig library files stay plain `.json`). - The rig-library sidebar (`Share…` per rig) and the board editor's Versions menu (`Share…` per version) present the OS share sheet via SwiftUI `ShareLink`, backed by the `Transferable` wrappers `RigShareItem` / `BoardShareItem` (in `LyrebirdShoeGazeUI`). No backend — share targets are AirDrop, Mail, Messages, and Files. ```swift // Export the library to a .shoegaze file: let data = try library.exportDocumentData() // Import a received .shoegaze (or legacy) file: let added = try library.importArchive(from: receivedData) ``` --- ## Demo apps The package ships two in-repo demo apps in the workspace — a macOS app and an iOS app. Both live under `ShoeGaze/Demo/` and share the same workspace: ```sh open ShoeGaze/ShoeGaze.xcworkspace ``` The workspace contains three entries: the `ShoeGaze` SwiftPM package (library targets), `Demo/ShoeGazeDemo.xcodeproj` (macOS), and `Demo/ShoeGazeiOSDemo.xcodeproj` (iOS). Xcode resolves the two local package references (`..` for `LyrebirdShoeGaze`/`LyrebirdShoeGazeUI`, `../..` for `Lyrebird`/`LyrebirdUI`) automatically when you first open the workspace. ### `ShoeGazeDemo` (macOS) Showcases every feature via a mode picker (Boards / Editor / Parallel / Router), an input dropdown, transport, and the board selector + crossfade. Build & Run produces `ShoeGazeDemo.app` with a full menu bar — **Quit ⌘Q**, **Audio ▸ Mute ⌘M** (checkmark while muted): ```sh open ShoeGaze/ShoeGaze.xcworkspace # select the "ShoeGazeDemo" scheme → Run ``` ### `ShoeGazeiOSDemo` (iPhone + iPad) A minimal iOS app wrapping `ShoeGazeView` in a `NavigationStack` + `ScrollView` so the pedalboard scrolls on compact screens. Shows a default board (Overdrive → Delay → Reverb → Modulation) fed by the built-in `.testLoop` source — no microphone permission required. To run: 1. Open `ShoeGaze/ShoeGaze.xcworkspace` in Xcode. 2. Select the **ShoeGazeiOSDemo** scheme. 3. Pick an iPhone or iPad simulator (or a physical device with a provisioning profile). 4. Click **Run**. The app uses `AVAudioSession` to read the hardware sample rate at launch, so pitch and timing are accurate on all devices. To switch to live microphone input: set `numInputChannels: 1` and `.playAndRecord` in `ShoeGazeiOSDemoAppModel.swift`, then pass `.liveInput(channel: 0)` to the `ShoeGaze` init. Note: the CLI `lyrebird new --template shoegaze` / `--template shoegaze-ios` (below) is still the way to scaffold your OWN app project. The demo apps are in-repo only. --- ## `lyrebird new --template shoegaze` Workflow (macOS Xcode app) ```sh lyrebird new MyRig --template shoegaze \ --lyrebird-path /path/to/LyrebirdII \ --shoegaze-path /path/to/LyrebirdII/ShoeGaze ``` Generates a full `.xcodeproj` macOS application (macOS 15+): ``` MyRig/ ├── MyRig.xcodeproj/ │ ├── project.pbxproj │ └── xcshareddata/xcschemes/MyRig.xcscheme ├── MyRig.xcworkspace/ │ └── contents.xcworkspacedata (references MyRig.xcodeproj) └── MyRig/ ├── Info.plist (NSMicrophoneUsageDescription pre-wired) ├── MyRigApp.swift (@main SwiftUI App — ShoeGazeView root + Mute menu) └── MyRigAppModel.swift (@Observable model — engine + ShoeGaze) ``` Open `MyRig.xcworkspace` in Xcode and run. The generated app: - Wires `CoreAudioDriver` at 48 000 Hz with 256 audio buses. - Builds a default board (Overdrive → Delay → Reverb → Modulation) with the `.testLoop` input source. - Exposes an **Audio ▸ Mute ⌘M** command (stops/starts the engine). - Ships `NSMicrophoneUsageDescription` in `Info.plist` so switching to `.liveInput` doesn't require an extra plist edit. - `ShoeGazeView` already provides Choose Folder / Record / Stop recording controls. Key differences between the macOS and iOS shoegaze templates: | | `shoegaze` (macOS Xcode) | `shoegaze-ios` (iOS Xcode) | |---|---|---| | Project type | `.xcodeproj` app bundle | `.xcodeproj` app bundle | | Driver | `CoreAudioDriver` | `iOSAudioDriver` | | Session | — | `AVAudioSession(.playback)` | | Entry point | SwiftUI `@main App` | SwiftUI `@main App` | | Window sizing | `.frame(minWidth:minHeight:)` | device-fill, no min size | | Menu | Audio ▸ Mute ⌘M | — | ### `--shoegaze-path` ShoeGaze is not yet published at a stable remote URL. Passing `--shoegaze-path ` wires it as an `XCLocalSwiftPackageReference` in the generated `.xcodeproj`. If you omit the flag, the pbxproj uses a placeholder URL (`https://github.com/realizedsound/LyrebirdShoeGaze`) — edit `project.pbxproj` or re-generate once ShoeGaze is published. The placeholder URL is stored in `ProjectScaffolder.shoegazePackageURL`. ### Live audio input on macOS The generated template uses `.testLoop` and `numInputChannels: 0`. To switch to microphone or audio interface input: 1. Change `numInputChannels: 0` to the desired channel count in `MyRigAppModel.swift`. 2. Change `ShoeGaze(engine: eng)` to `ShoeGaze(engine: eng, inputSource: .liveInput(channel: 0))`. 3. `NSMicrophoneUsageDescription` is already in `Info.plist` — update the string to describe your use case. 4. If running under App Sandbox, add `com.apple.security.device.audio-input` to the `.entitlements` file. The `shoegaze` template is unsandboxed by default (Hardened Runtime without sandbox), so no entitlement file is needed in the common development workflow. --- ## `lyrebird new --template shoegaze-ios` Workflow (iOS) ```sh lyrebird new MyRig --template shoegaze-ios \ --lyrebird-path /path/to/LyrebirdII \ --shoegaze-path /path/to/LyrebirdII/ShoeGaze ``` Generates a full `.xcodeproj` iOS application (iPhone + iPad, iOS 18+): ``` MyRig/ ├── MyRig.xcodeproj/ │ ├── project.pbxproj │ └── xcshareddata/xcschemes/MyRig.xcscheme ├── MyRig.xcworkspace/ │ └── contents.xcworkspacedata (references MyRig.xcodeproj) └── MyRig/ ├── Info.plist ├── MyRigApp.swift (@main SwiftUI App — ShoeGazeView root) └── MyRigAppModel.swift (@Observable model — engine + ShoeGaze) ``` Open `MyRig.xcworkspace` in Xcode, select an iPhone/iPad simulator or device, and run. The generated app: - Activates `AVAudioSession(.playback)` and queries the hardware sample rate at init so pitch and timing are accurate on all devices. - Builds a default board (Overdrive → Delay → Reverb → Modulation) with the `.testLoop` input source. - Wraps `ShoeGazeView` in a `NavigationStack` + `ScrollView` for compact-screen compatibility. Key differences from the macOS `shoegaze` template: | | `shoegaze` (macOS Xcode) | `shoegaze-ios` (iOS Xcode) | |---|---|---| | Project type | `.xcodeproj` app bundle | `.xcodeproj` app bundle | | Driver | `CoreAudioDriver` | `iOSAudioDriver` | | Session | — | `AVAudioSession(.playback)` | | Entry point | SwiftUI `@main App` | SwiftUI `@main App` | | Window sizing | `.frame(minWidth:minHeight:)` | device-fill, no min size | | Menu | Audio ▸ Mute ⌘M | — | ### Live audio input on iOS The generated template uses `.testLoop` and `numInputChannels: 0`. To switch to microphone input: 1. Change `numInputChannels: 0` to `numInputChannels: 1` in `MyRigAppModel.swift`. 2. Change `.playback` to `.playAndRecord` (mode: `.default`, options: `[.defaultToSpeaker]`) in the `AVAudioSession` setup. 3. Add `NSMicrophoneUsageDescription` to `Info.plist` (required for App Store submission and the system permission prompt). 4. Change `ShoeGaze(engine: eng)` to `ShoeGaze(engine: eng, inputSource: .liveInput(channel: 0))`. --- ## Extending the starter app - Add more pedals in `applicationDidFinishLaunching` with additional `board.add(...)` calls. - Create a second board with `shoeGaze.addBoard()` — `ShoeGazeView` shows all boards. - Write a custom pedal: subclass `Pedal`, override `effect(_:)` (return a mono signal) and `effectKnobs`. The base class handles wet/dry, bypass, and level; `PedalView` picks up the knobs automatically. - Switch to live audio: construct `ShoeGaze(engine:, inputSource: .liveInput(channel: 0))` and set `numInputChannels` ≥ 1 in the engine init (plus the microphone entitlement / `NSMicrophoneUsageDescription`).