9 Commits

Author SHA1 Message Date
josh b55df174a6 Fix dragging an existing pedal into a region lane (cross-lane move)
Drag/drop only supported add: (palette→anywhere) and same-lane reorders, so
dragging a pedal from the main chain (or another lane) into a Stereo Unzip /
Split / Parallel lane highlighted the lane but the drop was a no-op.

- New core ShoeGaze.movePedal(from:at:to:in:) moves a pedal across lanes,
  preserving its PedalState (params), with destination-index correction when the
  removal deletes a top-level segment before the target region.
- BoardFlowView routes movemain:/movebranch: payloads dropped on a lane (or the
  main chain, or another lane's card) through it via moveAcross(_:toLane:).

Tests: move a main pedal into an unzip lane (params preserved); move a pedal
that sits before the region (index-adjust path).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 20:24:32 -07:00
josh f87fc1d4b1 1.1.1: move info button to top-left; fix empty-lane drag-drop
- PedalView: the ⓘ info button now sits under the top-left corner screw instead
  of on the name plate.
- BoardFlowView: empty region lanes (Stereo Unzip / Split / Parallel) were nearly
  transparent, so their drop target had no hit area and releases landed on
  nothing. Add contentShape(Rectangle()) so the whole lane frame accepts drops.
  (Core lane append already worked — verified by existing API tests.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:43:57 -07:00
josh a99c3e86ce Date the 1.1.0 release 2026-06-26 19:34:31 -07:00
josh 900b441082 Review fixes: cache pedal summaries; stop engine around Clear
- PedalRegistry.summaries caches displayName→summary once, so the picker no
  longer constructs a fresh Pedal per row on every render.
- performClear stops the engine around the remove-all + reseed and restarts it,
  avoiding a one-block bus-reuse glitch (same pattern as loadRig/setInputSource).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:29:06 -07:00
josh 8c701af128 Add stereo Diffuser pedal
A .widener pedal that splits the dry signal into overlapping RBJ band-pass bands
and pans each by frequency (low to left, high to right); the spread knob fans the
spectrum from mono (spread 0) to a wide diffuse image (spread 1), using linear
pan expressed purely as node arithmetic.

Registered, with PedalType.diffuser, enclosure color, palette order, summary,
and tests (non-silent stereo; L == R at spread 0; L != R at full spread).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:14:00 -07:00
josh 12c7dc60f7 Add RELEASES.md (1.0 baseline + 1.1 changes)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 19:08:47 -07:00
josh 0d17ed260b Persist board across restarts + Clear button with save prompt
Persistence (macOS + iOS):
- RigStore autosaves the rig (rigData JSON) to Application Support and restores
  it on launch. App models restore-or-seed at init; macOS saves on terminate +
  resignActive, iOS saves on scenePhase leaving .active. The builder also
  autosaves after structural edits (add board/pedal, load, clear).

Clear (both platforms):
- A Clear button in the builder opens a confirmation dialog: Save & Clear /
  Clear Without Saving / Cancel. Clear removes all boards and seeds one fresh
  empty board, then autosaves. Save & Clear triggers the save mechanism and only
  clears once the save completes (cancelling the save leaves the rig intact).
- The rig-save exporter is now cross-platform (was iOS-only) so Save and the
  Save & Clear flow work on macOS too; macOS keeps its File-menu Load.

Tests: RigStore save/restore round-trip across instances; restore is a no-op
with no autosave. 186 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:54:03 -07:00
josh f29ab609bd Add Chorus, Sustainer, Ring Modulator pedals + pedal-info UI
Pedals (each registered, with PedalType static, enclosure color, palette order,
summary, and tests):
- Chorus: true-stereo widener (two anti-phase modulated delay lines), distinct
  from the mono-summed Modulation chorus.
- Sustainer: one-knob compressor (sustain drives threshold/ratio/makeup via
  LinLin) + tone low-pass.
- Ring Modulator: dry × tunable sine carrier.

Pedal-info UI:
- Pedal.summary (open var, overridden by all 21 pedals; mandatory going forward).
- PedalRegistry.summary(for:) for the picker.
- PedalPaletteView rows show the summary as a subtitle.
- PedalView gains an ⓘ button → PedalInfoView sheet showing the description and
  the effect controls (knobs/sliders/switches) with ranges/options — excludes
  the common Mix/Level/bypass.

Tests: per-pedal build/param-change/knob-list; every built-in pedal has a
non-empty summary; info excludes common controls. 183 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:05:30 -07:00
josh 9bc049d8a3 Add 1.1 feature plans + ShoeGaze CLAUDE.md (mandatory pedal summary)
docs/plans: chorus (stereo), sustainer, ring modulator, and pedal-info UI.
CLAUDE.md: project conventions + a required checklist for new pedals, including
a mandatory user-facing summary used by the pedal-info UI.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 17:44:47 -07:00
50 changed files with 1900 additions and 59 deletions
+64
View File
@@ -0,0 +1,64 @@
# ShoeGaze — Claude Context
A virtual guitar-pedalboard framework built on Lyrebird. Two products:
`LyrebirdShoeGaze` (core pedal/board framework, no SwiftUI) and `LyrebirdShoeGazeUI`
(SwiftUI views). Depends on the published Lyrebird package.
## Conventions
- **MIT SPDX header** on every new `.swift` file (first 5 lines): file name, `// Lyrebird`,
blank comment, `// Copyright (c) 2026 Joshua Parmenter / realizedsound`,
`// SPDX-License-Identifier: MIT`, then a blank line.
- **Explicit type annotations** on `let`/`var` bindings, named constants for non-trivial
literals, doc comments on public init params — matches the Lyrebird house style.
- Pedals subclass `Pedal` (in `Sources/LyrebirdShoeGaze/Pedals/`), expose parameters as
`@UIParam`, and surface them via `effectKnobs` / `effectSwitches` / `effectSliders`.
- A pedal's `displayName` **is** its serialization key and its `PedalType.rawValue`, and the
`PedalRegistry.builtIn` key. Keep all three identical when adding a pedal.
## Adding a new pedal — required checklist
1. `Sources/LyrebirdShoeGaze/Pedals/<Name>Pedal.swift` — subclass `Pedal`, override `effect`
(or `wideEffect`/`stereoEffect`), `effectKnobs`/`effectSwitches`/`effectSliders`.
2. **`summary`** — override `open var summary: String` with a one-line, user-facing
description. **This is mandatory for every pedal** (see "Pedal info" below).
3. Register in `PedalRegistry.builtIn["<DisplayName>"]`.
4. Add `PedalType.<name> = PedalType("<DisplayName>")`.
5. Enclosure color case in `PedalView.enclosureColor(for:)`.
6. Add to `PedalPaletteView.preferredOrder`.
7. Tests in `Tests/LyrebirdShoeGazeTests/<Name>PedalTests.swift` — at minimum: builds +
non-silent, each effect parameter measurably changes the output, knob-list assertion,
and (if it has switches/sliders) a preset round-trip.
8. Use `PedalType` static members at call sites (`appendPedal(.overdrive, to:)`), never raw
strings, except where a string is inherently dynamic (registry / preset load).
## Pedal info (mandatory)
Every pedal participates in the pedal-info UI:
- **`summary`** (required): a short, non-proprietary, user-facing sentence describing what
the pedal does. The picker shows it as a subtitle; the pedal's ⓘ info panel shows it as
the description. A new pedal without a non-empty `summary` is incomplete — a test asserts
every registered pedal has one.
- The info panel lists the **effect controls only** (`effectKnobs` + `effectSliders` +
`effectSwitches`) with their ranges/options — never the common Mix / Level / bypass. Put
the meaningful range and a clear unit in each control's `label`/`range` so the info panel
reads well.
## dB parameters
There is no dB→linear generator for a control-rate node. To apply a dB gain to a signal,
convert in the graph: `Exp.Audio($gainDB * dbToLinExpScale)` where
`dbToLinExpScale = ln(10)/20 ≈ 0.11512925464970229` (gives `10^(dB/20)`). RBJ shelving/peaking
filters take gain in dB directly, so pass dB nodes straight through.
## Build / test
- Package: `swift build` / `swift test --no-parallel` (the multi-engine suite can hit
Lyrebird's parallel-teardown flake without `--no-parallel`).
- Apps: `Demo/ShoeGaze.xcworkspace` (macOS builder, iPad builder, demos). iOS targets are
iPad-only, landscape.
## Planned work
`docs/plans/` holds the next-version feature plans.
@@ -163,7 +163,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 2;
CURRENT_PROJECT_VERSION = 3;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
@@ -176,7 +176,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 0.91;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -194,7 +194,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 2;
CURRENT_PROJECT_VERSION = 3;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
@@ -206,7 +206,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 0.91;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
+10 -1
View File
@@ -83,7 +83,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
)
super.init()
seedInitialBoard()
// Restore the autosaved rig if there is one; otherwise seed a default board.
if !RigStore.restore(into: shoeGaze) {
seedInitialBoard()
}
}
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
@@ -134,9 +137,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
}
func applicationWillTerminate(_ notification: Notification) {
RigStore.save(shoeGaze)
engine.stop()
}
func applicationDidResignActive(_ notification: Notification) {
// Persist on every deactivation too, so state survives an unexpected exit.
RigStore.save(shoeGaze)
}
// MARK: - Main menu
/// Builds a minimal menu bar: an application menu with About / Hide / Quit (⌘Q).
@@ -19,6 +19,7 @@ import LyrebirdShoeGazeUI
struct ShoeGazeBuilderiOSApp: App {
@State private var model: ShoeGazeBuilderiOSAppModel = ShoeGazeBuilderiOSAppModel()
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
@@ -33,5 +34,9 @@ struct ShoeGazeBuilderiOSApp: App {
}
.onDisappear { model.stop() }
}
.onChange(of: scenePhase) { _, phase in
// Persist the rig whenever the app leaves the foreground.
if phase != .active { model.save() }
}
}
}
@@ -61,15 +61,17 @@ final class ShoeGazeBuilderiOSAppModel {
self.iosDriver = built.driver
self.shoeGaze = built.shoeGaze
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.appendPedal(ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
} catch {
print("[ShoeGazeBuilderiOS] seed board failed: \(error)")
// Restore the autosaved rig if there is one; otherwise seed a default board.
if !RigStore.restore(into: shoeGaze) {
seedFallbackBoard()
}
}
/// Persists the current rig. Call when the app moves to the background.
func save() {
RigStore.save(shoeGaze)
}
// MARK: - Audio session / engine construction
/// Activates the play-and-record audio session once. Idempotent; safe to call before each
+3 -3
View File
@@ -11,7 +11,7 @@ signal (no hardware needed) or on live guitar through an audio input.
## Features
- **18 modeled pedals** across drive, dynamics, EQ/filter, modulation, delay/reverb, and
- **22 modeled pedals** across drive, dynamics, EQ/filter, modulation, delay/reverb, and
pitch — see the catalog below.
- **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel
style) or **Blend** any subset, each with its own level and a click-free crossfade.
@@ -28,9 +28,9 @@ signal (no hardware needed) or on live guitar through an audio input.
| Category | Pedals |
|---|---|
| Drive & dynamics | Overdrive, Fuzz, Compressor, Limiter, Noise Gate |
| Drive & dynamics | Overdrive, Fuzz, Compressor, Sustainer, Limiter, Noise Gate |
| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Phaser |
| Modulation | Tremolo, Modulation |
| Modulation | Tremolo, Modulation, Chorus, Ring Modulator, Diffuser |
| Delay & reverb | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverb |
| Pitch & octave | Octave Splitter, Bass Octaver |
+71
View File
@@ -0,0 +1,71 @@
# Releases
## 1.1.1 — 2026-06-26
### Fixes
- Pedal **ⓘ info button** moved to the top-left corner (under the corner screw),
out of the way of the name plate.
- Fixed **dragging a pedal into a Stereo Unzip / Split / Parallel lane**. Dropping a pedal
from the main chain (or another lane) into a region lane now moves it there, preserving its
parameters — previously the drop was silently ignored. Empty lanes are also fully
hit-testable now.
## 1.1.0 — 2026-06-24
### New pedals
- **Chorus** — true-stereo chorus (two anti-phase modulated delay voices), distinct from the
mono Modulation chorus.
- **Sustainer** — one-knob compressor tuned for long, even sustain, with a tone control.
- **Ring Modulator** — multiplies the signal by a tunable sine carrier for metallic / bell /
robotic tones.
- **Diffuser** — stereo widener that fans the frequency spectrum across L/R, with a `spread`
control from mono to a wide, diffuse image.
### Pedal info UI
- Every pedal now has a one-line description (`summary`).
- The pedal picker shows each pedal's description as a subtitle.
- Each pedal has an ⓘ info button opening a panel with its description and effect controls
(knobs / sliders / switches) and their value ranges — excluding the common Mix/Level/bypass.
### Board persistence
- The board(s) persist across app restarts on macOS and iPadOS — the rig is autosaved to
Application Support and restored on launch (falls back to a default board if none).
- New **Clear** button removes all boards; it first prompts **Save & Clear / Clear Without
Saving / Cancel**, and "Save & Clear" only clears once the save completes.
- Rig save is now available in-view on macOS too (previously File-menu only).
### Developer notes
- Added `docs/plans/` (feature plans) and a project `CLAUDE.md` (conventions + a required
checklist for new pedals, including a mandatory `summary`).
---
## 1.0.0 — 2026-06-24
First stable release: a virtual guitar-pedalboard framework built on Lyrebird, for macOS and
iPadOS, in two products — `LyrebirdShoeGaze` (core) and `LyrebirdShoeGazeUI` (SwiftUI).
### Pedals (18)
Overdrive, Fuzz, Compressor (with input gain), Limiter, Noise Gate, Graphic EQ, Auto-Wah,
Mutant, Phaser, Tremolo, Modulation, Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverb,
Octave Splitter, Bass Octaver. Delay-family "decay" controls are labelled **Decay Time**.
### Boards & mixing
- Multiple boards with a board-mixer bar: **Solo** one (amp-channel style) or **Blend** any
subset, each with its own level and a click-free crossfade.
- A board-manager sheet (rename, drag-reorder, swipe-delete) and ⌘1–9 board switching.
- Signal-flow editor: add pedals from the palette; parallel and stereo-split lanes; merge to mono.
- One shared, phase-locked test signal across all boards (no per-board polyrhythm).
### Audio I/O
- Test-loop signal or live hardware input.
- macOS and iPadOS (iPad-only, landscape). iOS live input via a permission-gated engine rebuild;
the last input choice is remembered.
### Files & capture
- Save / load rigs as JSON.
- Record output to timestamped files.
### API
- Type-safe `PedalType` tokens for the board-edit API (`appendPedal(.overdrive, to:)`); the rig
JSON format is keyed on pedal display names.
+11
View File
@@ -128,6 +128,17 @@ open class Pedal: SynthesizerBase {
self.mix = initialMix
}
// MARK: - Description
/// One-line, user-facing description of what this pedal does.
///
/// Shown as a subtitle in the pedal picker and as the body of the pedal's info panel.
/// **Every pedal must override this** with a short, non-proprietary sentence — the empty
/// default is a placeholder only (a test asserts every registered pedal sets it).
open var summary: String {
""
}
// MARK: - UI knob descriptors
/// Effect-specific knobs for this pedal, listed before the common knobs in the UI.
+6
View File
@@ -59,6 +59,12 @@ public extension PedalType {
// Modulation
static let tremolo = PedalType("Tremolo")
static let modulation = PedalType("Modulation")
static let chorus = PedalType("Chorus")
static let ringModulator = PedalType("Ring Modulator")
static let diffuser = PedalType("Diffuser")
// Dynamics (additional)
static let sustainer = PedalType("Sustainer")
// Delay & reverb
static let delay = PedalType("Delay")
@@ -27,6 +27,11 @@ import LyrebirdUI
/// - `range`: Upper cutoff in Hz reached at full envelope. Sets the sweep span over `freqLo`.
public final class AutoWahPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Touch-sensitive wah that sweeps a resonant filter from your playing dynamics."
}
// MARK: - Parameters
/// Envelope drive into the cutoff sweep. Higher values open the filter on quieter input.
@@ -35,6 +35,11 @@ import LyrebirdUI
/// - `mode` (two-state): `0` = Flip-flop (authentic OC-2), `1` = Tracking (pitch-tracked).
public final class BassOctaverPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Adds a sub-octave below your note for bass-like weight."
}
// MARK: - Parameters
/// −1 octave voice level in `[0, 1]`.
@@ -0,0 +1,129 @@
// ChorusPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// True-stereo chorus pedal.
///
/// Two modulated delay lines, fed the same dry signal but driven by sine LFOs 180° apart,
/// produce a wide left/right shimmer. Unlike `ModulationPedal` (which sums Lyrebird's
/// `Chorus` to mono), this pedal is a ``PedalChannelKind/widener`` — it keeps the two voices
/// on separate channels for genuine stereo width.
///
/// Signal path (per channel, inside `wideEffect(_:)`):
/// ```
/// dry → DelayLine(delay: base ± depth·sin(rate)) → wet L / wet R
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - rate: LFO rate in Hz. Range `[0.05, 6]`. Defaults to `0.8`.
/// - depth: Delay-sweep depth in seconds (half-swing around the base delay). Range
/// `[0.0005, 0.008]`. Defaults to `0.003`.
public final class ChorusPedal: Pedal {
// MARK: - Parameters
/// LFO rate in Hz. Range [0.05, 6].
@UIParam public var rate: Double = 0.8
/// Delay-sweep depth in seconds. Range [0.0005, 0.008].
@UIParam public var depth: Double = 0.003
// MARK: - Constants
/// Default wet/dry blend — chorus sits under the dry signal.
private static let defaultMix: Double = 0.5
/// Base delay around which the LFO sweeps, in seconds.
private let baseDelayTime: Double = 0.012
/// Maximum delay the lines are allocated for, in seconds. Covers `baseDelayTime + max depth`.
private let maxDelayTime: Double = 0.03
/// LFO phase for the left voice, in cycles.
private let leftPhase: Double = 0.0
/// LFO phase for the right voice, in cycles — a half cycle (180°) opposite the left.
private let rightPhase: Double = 0.5
// MARK: - UI knobs
private let rateRange: ClosedRange<Double> = 0.05 ... 6.0
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.008
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
PedalKnob(label: "Depth", node: $depth, range: depthRange),
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates a stereo chorus pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Chorus",
inputBus: inputBus,
outputBus: outputBus,
initialMix: ChorusPedal.defaultMix
)
}
public override var summary: String {
"Lush stereo chorus: two detuned voices panned wide for shimmer and depth."
}
// MARK: - Effect
/// Builds one modulated delay line per channel, with the two LFOs in anti-phase.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The left and right wet voices.
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
(voice(dry, phase: leftPhase), voice(dry, phase: rightPhase))
}
/// One chorus voice: a delay line whose time is swept by a sine LFO around `baseDelayTime`.
private func voice(
_ dry: any ValidGeneratorInput,
phase: Double
) -> any ValidGeneratorInput {
let sweep: OscSin.Audio = OscSin.Audio(
freq: $rate,
phase: phase,
mul: $depth,
add: baseDelayTime
)
return DelayLine(
input: dry,
maxDelay: maxDelayTime,
delay: sweep,
sampleRate: sampleRate,
interpolation: .linear
)
}
}
@@ -34,6 +34,11 @@ import LyrebirdUI
/// Range `[1, 20]`. Defaults to `4.0`.
public final class CompressorPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Feed-forward compressor that evens out dynamics, with a pre-gain input stage."
}
// MARK: - Parameters
/// Pre-compression input gain in dB. Range [-12, 24]. `0` = unity.
@@ -28,6 +28,11 @@ import LyrebirdUI
/// repeats. Range `[0.05, 6.0]` seconds. Defaults to `1.0`.
public final class DelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Echo delay with adjustable time and decay, from slapback to long repeats."
}
// MARK: - Parameters
/// Delay time in seconds. Range [0.01, 1.5].
@@ -0,0 +1,130 @@
// DiffuserPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Stereo diffuser pedal: fans the frequency spectrum across the left and right channels.
///
/// A `.widener` pedal. The dry signal is split into overlapping frequency bands; each band is
/// panned by its centre frequency — lows toward the left, highs toward the right — and the
/// `spread` knob sets how far the bands fan out. At `spread = 0` every band sits centre (a mono
/// collapse); at `spread = 1` the spectrum is splayed hard across the stereo field, giving a
/// wide, diffuse image without time smearing.
///
/// Signal path (inside `wideEffect(_:)`), per band `k` at position `pos_k ∈ [-1, 1]`:
/// ```
/// dry → RBJBandPass(freq_k) → ×gainL_k → Σ → left
/// → ×gainR_k → Σ → right
/// gainL_k = 0.5 − 0.5·pos_k·spread, gainR_k = 0.5 + 0.5·pos_k·spread (linear pan)
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - spread: Stereo spectral spread. `0` = centred (mono), `1` = fully fanned L↔R.
/// Range `[0, 1]`. Defaults to `0.6`.
public final class DiffuserPedal: Pedal {
// MARK: - Parameters
/// Stereo spectral spread in [0, 1]. `0` = mono, `1` = full fan.
@UIParam public var spread: Double = 0.6
// MARK: - Constants
private static let defaultMix: Double = 1.0
/// Centre pan gain (each band's gain when `spread == 0` or it sits dead-centre).
private let centerGain: Double = 0.5
/// RBJ band-pass width in octaves — wide enough that adjacent bands overlap and recombine.
private let bandwidthOctaves: Double = 1.5
/// The frequency bands and their base stereo positions (low = left, high = right).
/// `position ∈ [-1, 1]`; multiplied by `spread` to place the band.
private let bands: [(freq: Double, position: Double)] = [
(150.0, -1.0),
(400.0, -0.5),
(1000.0, 0.0),
(2500.0, 0.5),
(6000.0, 1.0),
]
// MARK: - UI knobs
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates a stereo diffuser pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Diffuser",
inputBus: inputBus,
outputBus: outputBus,
initialMix: DiffuserPedal.defaultMix
)
}
public override var summary: String {
"Stereo diffuser that fans the frequency spectrum across the left and right channels."
}
// MARK: - Effect
/// Splits the dry signal into frequency bands and pans each across the field by `spread`.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The left and right diffused signals.
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
var left: (any ValidGeneratorInput)?
var right: (any ValidGeneratorInput)?
for band: (freq: Double, position: Double) in bands {
let bandPass: RBJBandPass.Audio = RBJBandPass.Audio(
input: dry,
freq: band.freq,
bandwidth: bandwidthOctaves
)
// Linear pan, fully expressible as node arithmetic (no per-sample trig):
// gainL = centerGain − (0.5·position)·spread
// gainR = centerGain + (0.5·position)·spread
let halfPosition: Double = centerGain * band.position
let gainL: any ValidGeneratorInput = ($spread * (-halfPosition)) + centerGain
let gainR: any ValidGeneratorInput = ($spread * halfPosition) + centerGain
let leftContribution: any ValidGeneratorInput = bandPass * gainL
let rightContribution: any ValidGeneratorInput = bandPass * gainR
left = left.map { $0 + leftContribution } ?? leftContribution
right = right.map { $0 + rightContribution } ?? rightContribution
}
return (left ?? dry, right ?? dry)
}
}
@@ -26,6 +26,11 @@ import LyrebirdUI
/// - `tone`: Lowpass cutoff in Hz applied to the wet signal; lower darkens the echoes.
public final class FeedbackDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Feedback delay with a tone-shaped repeat for dub-style echoes."
}
// MARK: - Parameters
/// Delay time between repeats, in seconds.
@@ -36,6 +36,11 @@ import LyrebirdUI
/// Range `[200, 8000]` Hz. Defaults to `3500.0`.
public final class FuzzPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Thick, saturated fuzz for aggressive, sustaining distortion."
}
// MARK: - Parameters
/// Pre-gain drive into the saturator. Range [1, 60]; higher = more fuzz.
@@ -39,6 +39,11 @@ import LyrebirdUI
/// Defaults to `0.0`.
public final class GraphicEQPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Five-band graphic EQ with per-band faders and a master output level."
}
// MARK: - Parameters
/// Low-shelf gain in dB. Range [-12, 12].
@@ -31,6 +31,11 @@ import LyrebirdUI
/// never exceeds this absolute value. Range `[0.1, 1.0]`. Defaults to `0.95`.
public final class LimiterPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Brick-wall limiter with an input boost to push level safely to the ceiling."
}
// MARK: - Parameters
/// Pre-limit input gain (linear multiplier). Range [1, 12].
@@ -32,6 +32,11 @@ import LyrebirdUI
/// Smaller values (0.001–0.01) produce classic chorus width. Defaults to `0.002`.
public final class ModulationPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Classic mono chorus for subtle thickening and shimmer."
}
// MARK: - Parameters
/// Chorus LFO rate in Hz. Range [0.1, 10].
@@ -28,6 +28,11 @@ import LyrebirdUI
/// - `vol1`, `vol2`, `vol3`: Linear output level of each tap in `[0, 1]`.
public final class MultiTapDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Multi-tap delay producing rhythmic patterns of echoes."
}
// MARK: - Tap times
/// Tap 1 delay time, in seconds.
@@ -26,6 +26,11 @@ import LyrebirdUI
/// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass.
public final class MutantPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Envelope-following auto-wah / funk filter that opens with your picking."
}
// MARK: - Parameters
/// Filter response selector. `0` = lowpass, `1` = bandpass, `2` = highpass. Driven by a three-state switch.
@@ -37,6 +37,11 @@ import LyrebirdUI
/// mute, `1` = no gating. Range `[0, 1]`. Defaults to `0.0`.
public final class NoiseGatePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Noise gate that silences hiss and hum below a tunable threshold."
}
// MARK: - Parameters
/// Gate close threshold (linear amplitude). Range [0, 0.2].
@@ -31,6 +31,11 @@ import LyrebirdUI
/// - tone: Octave-channel low-pass cutoff in Hz. Range `[500, 8000]`. Defaults to `4000.0`.
public final class OctaveUpSplitterPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Splits a clean octave-up voice alongside your dry signal in stereo."
}
// MARK: - Parameters
/// Pre-gain into the octave-channel saturator. Range [1, 40]; higher = thicker octave fuzz.
@@ -27,6 +27,11 @@ import LyrebirdUI
/// Range `(0, 20000]`. Defaults to `4000.0`.
public final class OverdrivePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Warm soft-clip overdrive with a tone control, from gentle grit to singing sustain."
}
// MARK: - Parameters
/// Saturation drive amount. Range [1, 20]; higher = more clipping.
@@ -30,6 +30,11 @@ import LyrebirdUI
/// Range `[0.0, 0.9]`. Defaults to `0.5`.
public final class PhaserPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Sweeping phase shifter for swirling, watery motion."
}
// MARK: - Parameters
/// LFO sweep rate in Hz. Range [0.05, 5.0].
@@ -37,6 +37,11 @@ import LyrebirdUI
/// Range `[0.05, 6.0]`. Defaults to `1.2`.
public final class PingPongDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Stereo ping-pong delay bouncing echoes between left and right."
}
// MARK: - Parameters
/// Delay time per tap in seconds. Range [0.05, 1.0].
@@ -31,6 +31,11 @@ import LyrebirdUI
/// shorter tails. Defaults to `0.5`.
public final class ReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Reverb adding space and ambience, from small rooms to vast halls."
}
// MARK: - Parameters
/// Room size in [0, 1]. Larger = longer reverb tail.
@@ -0,0 +1,84 @@
// RingModulatorPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Ring modulator pedal.
///
/// Multiplies the input by a tunable sine carrier, producing sum-and-difference sidebands —
/// metallic, bell-like, and robotic tones. Below ~30 Hz the carrier reads as tremolo-style
/// amplitude modulation; in the audio range it becomes classic ring modulation.
///
/// Signal path (inside `effect(_:)`):
/// ```
/// dry × OscSin(frequency) → wet
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - frequency: Carrier frequency in Hz. Range `[20, 2000]`. Defaults to `220.0`.
public final class RingModulatorPedal: Pedal {
// MARK: - Parameters
/// Carrier frequency in Hz. Range [20, 2000].
@UIParam public var frequency: Double = 220.0
// MARK: - Constants
/// Default wet/dry blend — ring mod is harsh, so keep the dry signal present.
private static let defaultMix: Double = 0.5
// MARK: - UI knobs
private let frequencyRange: ClosedRange<Double> = 20.0 ... 2000.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Frequency", node: $frequency, range: frequencyRange),
]
}
// MARK: - Init
/// Creates a ring modulator pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Ring Modulator",
inputBus: inputBus,
outputBus: outputBus,
initialMix: RingModulatorPedal.defaultMix
)
}
public override var summary: String {
"Multiplies your signal by a tunable carrier for metallic, bell-like, and robotic tones."
}
// MARK: - Effect
/// Multiplies the dry signal by the sine carrier.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The ring-modulated wet signal.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let carrier: OscSin.Audio = OscSin.Audio(freq: $frequency)
return dry * carrier
}
}
@@ -0,0 +1,144 @@
// SustainerPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Sustainer pedal: a one-knob compressor tuned for long, even sustain.
///
/// A single `sustain` control drives a feed-forward compressor harder as it climbs — lowering
/// the threshold, raising the ratio, and adding makeup gain together — so notes bloom and hold
/// without the user juggling threshold/ratio (that's what the `Compressor` pedal is for). A
/// `tone` low-pass rounds off the squashed top end.
///
/// Signal path (inside `effect(_:)`):
/// ```
/// dry → Compressor(threshold↓, ratio↑, makeup↑ with sustain) → RBJLowPass(tone) → wet
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - sustain: Amount of sustain/compression. `0` = gentle, `10` = maximum squash and hold.
/// Range `[0, 10]`. Defaults to `5.0`.
/// - tone: Output low-pass cutoff in Hz. Range `[800, 8000]`. Defaults to `6000.0`.
public final class SustainerPedal: Pedal {
// MARK: - Parameters
/// Sustain amount in [0, 10]. Higher = more compression, makeup, and hold.
@UIParam public var sustain: Double = 5.0
/// Output low-pass cutoff in Hz. Range [800, 8000].
@UIParam public var tone: Double = 6000.0
// MARK: - Constants
private static let defaultMix: Double = 1.0
/// Compressor envelope times, in seconds — fast attack to catch picks, slow release to hold.
private let attackTime: Double = 0.005
private let releaseTime: Double = 0.4
/// Hard knee for a defined, punchy sustain.
private let kneeWidth: Double = 0.0
/// Butterworth tone low-pass (no resonant peak).
private let toneQ: Double = 0.707
/// `sustain` knob span, mapped to the compressor settings below.
private let sustainMin: Double = 0.0
private let sustainMax: Double = 10.0
/// Threshold in dB at min / max sustain (lower threshold = more of the signal compressed).
private let thresholdAtMin: Double = -6.0
private let thresholdAtMax: Double = -36.0
/// Compression ratio at min / max sustain.
private let ratioAtMin: Double = 2.0
private let ratioAtMax: Double = 10.0
/// Makeup gain in dB at min / max sustain (compensates for the added gain reduction).
private let makeupAtMin: Double = 0.0
private let makeupAtMax: Double = 18.0
// MARK: - UI knobs
private let sustainRange: ClosedRange<Double> = 0.0 ... 10.0
private let toneRange: ClosedRange<Double> = 800.0 ... 8000.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Sustain", node: $sustain, range: sustainRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
// MARK: - Init
/// Creates a sustainer pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Sustainer",
inputBus: inputBus,
outputBus: outputBus,
initialMix: SustainerPedal.defaultMix
)
}
public override var summary: String {
"Compressor tuned for long, even sustain — one knob to make notes bloom and hold."
}
// MARK: - Effect
/// Drives a compressor from the single `sustain` knob, then rolls off the top with `tone`.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The sustained, tone-shaped wet signal.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let threshold: LinLin.Audio = mapSustain(to: thresholdAtMin, thresholdAtMax)
let ratio: LinLin.Audio = mapSustain(to: ratioAtMin, ratioAtMax)
let makeup: LinLin.Audio = mapSustain(to: makeupAtMin, makeupAtMax)
let compressed: Compressor.Audio = Compressor.Audio(
in: dry,
threshold: threshold,
ratio: ratio,
attack: attackTime,
release: releaseTime,
kneeWidth: kneeWidth,
makeupGain: makeup
)
return RBJLowPass.Audio(
input: compressed,
freq: $tone,
q: toneQ
)
}
/// Maps the `sustain` knob `[sustainMin, sustainMax]` to `[outLo, outHi]`.
private func mapSustain(to outLo: Double, _ outHi: Double) -> LinLin.Audio {
LinLin.Audio(
$sustain,
inLo: sustainMin,
inHi: sustainMax,
outLo: outLo,
outHi: outHi
)
}
}
@@ -31,6 +31,11 @@ import LyrebirdUI
/// Defaults to `0.7`.
public final class TremoloPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Rhythmic volume modulation, from a gentle throb to choppy stutter."
}
// MARK: - Parameters
/// LFO rate in Hz. Range [0.5, 12].
@@ -49,6 +49,10 @@ public enum PedalRegistry {
"Limiter": { LimiterPedal() },
"Noise Gate": { NoiseGatePedal() },
"Graphic EQ": { GraphicEQPedal() },
"Chorus": { ChorusPedal() },
"Sustainer": { SustainerPedal() },
"Ring Modulator": { RingModulatorPedal() },
"Diffuser": { DiffuserPedal() },
]
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
@@ -65,4 +69,25 @@ public enum PedalRegistry {
guard let constructor: @MainActor () -> Pedal = builtIn[type] else { return nil }
return constructor()
}
/// Cached `displayName → summary` map for all built-in pedals, built once by instantiating
/// each pedal a single time (no `build()` / engine work). Lets the picker look up
/// descriptions per row without reconstructing a pedal on every render.
@MainActor
public static let summaries: [String: String] = {
var map: [String: String] = [:]
for type: String in builtIn.keys {
map[type] = makePedal(type: type)?.summary ?? ""
}
return map
}()
/// Returns the `summary` description for a built-in pedal type, or `""` if unknown.
///
/// - Parameter type: The `displayName` of the pedal.
/// - Returns: The pedal's one-line `summary`, or `""` for unknown types.
@MainActor
public static func summary(for type: String) -> String {
summaries[type] ?? ""
}
}
@@ -0,0 +1,72 @@
// RigStore.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Autosaves the current rig to disk and restores it on launch, so a board survives app restarts.
///
/// Writes the same JSON produced by `ShoeGaze.rigData()` to a fixed file in the user's
/// Application Support directory. Callers save on app background/terminate (and after notable
/// edits) and restore once at startup, before seeding any default board.
@MainActor
public enum RigStore {
private static let folderName: String = "ShoeGaze"
private static let fileName: String = "autosave-rig.json"
/// Location of the autosave file, creating the containing folder if needed. `nil` if the
/// Application Support directory can't be resolved.
public static var autosaveURL: URL? {
let fileManager: FileManager = FileManager.default
guard let base: URL = try? fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
) else { return nil }
let dir: URL = base.appendingPathComponent(folderName, isDirectory: true)
try? fileManager.createDirectory(at: dir, withIntermediateDirectories: true)
return dir.appendingPathComponent(fileName)
}
/// Writes the rig's current state to the autosave file. Returns `false` on any failure.
@discardableResult
public static func save(_ shoeGaze: ShoeGaze) -> Bool {
guard let url: URL = autosaveURL else { return false }
do {
let data: Data = try shoeGaze.rigData()
try data.write(to: url, options: .atomic)
return true
} catch {
print("[RigStore] autosave failed: \(error)")
return false
}
}
/// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet.
///
/// - Returns: `true` if an autosave existed and produced at least one board; `false` if there
/// was nothing to restore or the load failed (in which case the caller should seed a default).
@discardableResult
public static func restore(into shoeGaze: ShoeGaze) -> Bool {
guard let url: URL = autosaveURL,
FileManager.default.fileExists(atPath: url.path) else { return false }
do {
let data: Data = try Data(contentsOf: url)
try shoeGaze.loadRig(from: data)
return !shoeGaze.boards.isEmpty
} catch {
print("[RigStore] restore failed: \(error)")
return false
}
}
/// Deletes the autosave file (e.g. after the user clears the board without saving).
public static func clear() {
guard let url: URL = autosaveURL else { return }
try? FileManager.default.removeItem(at: url)
}
}
@@ -117,6 +117,83 @@ extension ShoeGaze {
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments))
}
/// Moves a pedal from one lane to another (e.g. the main chain into a stereo-unzip lane, or
/// between branches), preserving its parameter values. The moved pedal is appended to the end
/// of the destination lane.
///
/// - Parameters:
/// - sourceLane: The lane the pedal currently lives in.
/// - sourceIndex: The pedal's index within `sourceLane`.
/// - destinationLane: The lane to move the pedal into.
/// - board: The board to edit.
/// - Returns: The rebuilt board occupying the same slot in `boards`.
/// - Throws: `ShoeGazeError.pedalIndexOutOfRange`, `.notABranchRegion`, or any rebuild error.
@discardableResult
public func movePedal(
from sourceLane: PedalLane,
at sourceIndex: Int,
to destinationLane: PedalLane,
in board: PedalBoard
) throws -> PedalBoard {
var segments: [BoardSegmentState] = board.captureState().segments
// 1. Remove the pedal from its source lane, capturing its full state. Removing a main
// pedal deletes a top-level segment; record where so the destination region index can
// be corrected if it sat after the removal.
let moved: PedalState
var removedTopLevelIndex: Int?
switch sourceLane {
case .main:
let positions: [Int] = linearPedalSegmentIndices(segments)
guard sourceIndex >= 0, sourceIndex < positions.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: positions.count)
}
let absolute: Int = positions[sourceIndex]
guard case .pedal(let state) = segments[absolute] else {
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: positions.count)
}
moved = state
segments.remove(at: absolute)
removedTopLevelIndex = absolute
case .left, .right:
var captured: PedalState?
try mutateBranch(&segments, lane: sourceLane) { branch in
guard sourceIndex >= 0, sourceIndex < branch.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: branch.count)
}
captured = branch.remove(at: sourceIndex)
}
guard let capturedState: PedalState = captured else {
throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: 0)
}
moved = capturedState
}
// 2. Correct the destination region index if a top-level segment before it was removed.
var destination: PedalLane = destinationLane
if let region: Int = destinationLane.regionIndex,
let removed: Int = removedTopLevelIndex, removed < region {
destination = destinationLane.isLeftBranch ? .left(region: region - 1) : .right(region: region - 1)
}
// 3. Append the moved pedal to the destination lane.
switch destination {
case .main:
let positions: [Int] = linearPedalSegmentIndices(segments)
if let lastPedal: Int = positions.last {
segments.insert(.pedal(moved), at: lastPedal + 1)
} else {
segments.append(.pedal(moved))
}
case .left, .right:
try mutateBranch(&segments, lane: destination) { branch in
branch.append(moved)
}
}
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments))
}
// MARK: - Branch regions
/// Appends an empty stereo split region (two independently authored L/R lanes) to the board.
+42 -7
View File
@@ -325,6 +325,10 @@ public struct BoardFlowView: View {
}
}
.frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading)
// Make the whole lane frame hit-testable: an empty lane is mostly transparent, so without
// this the drop target has almost no area and releases land on nothing (the bug where
// dropping into an empty Stereo Unzip / Split / Parallel lane did nothing).
.contentShape(Rectangle())
.overlay { dropOutline(active: dropTarget == laneID) }
.dropDestination(for: String.self) { items, _ in
handleLaneDrop(items, lane: lane)
@@ -396,16 +400,19 @@ public struct BoardFlowView: View {
reorderMain(from: src, onto: ontoLinear)
return true
}
return false
// A branch pedal dragged back onto the main chain → cross-lane move.
return moveAcross(payload, toLane: .main)
}
private func handleLaneDrop(_ items: [String], lane: PedalLane) -> Bool {
dropTarget = nil
guard let payload: String = parse(items), let type: String = payload.afterPrefix("add:") else {
return false
guard let payload: String = parse(items) else { return false }
if let type: String = payload.afterPrefix("add:") {
append(type: type, lane: lane)
return true
}
append(type: type, lane: lane)
return true
// A pedal from the main chain or another lane dragged into this lane → cross-lane move.
return moveAcross(payload, toLane: lane)
}
private func handleBranchCardDrop(_ items: [String], lane: PedalLane, ontoIndex: Int) -> Bool {
@@ -422,7 +429,7 @@ public struct BoardFlowView: View {
append(type: type, lane: lane)
return true
}
// Reorder within the same lane only: "movebranch:<region>:<side>:<index>".
// Reorder within the same lane: "movebranch:<region>:<side>:<index>".
let parts: [Substring] = payload.split(separator: ":")
if parts.count == 4, parts[0] == "movebranch",
Int(parts[1]) == lane.regionIndex,
@@ -431,7 +438,35 @@ public struct BoardFlowView: View {
reorderBranch(from: src, onto: ontoIndex, lane: lane)
return true
}
return false
// A pedal from the main chain or a different lane dropped onto a card here → cross-lane move.
return moveAcross(payload, toLane: lane)
}
/// Moves a pedal addressed by a `movemain:`/`movebranch:` payload into `destination`,
/// preserving its parameters. Returns `false` if the payload isn't a recognised move.
private func moveAcross(_ payload: String, toLane destination: PedalLane) -> Bool {
guard let board: PedalBoard = board else { return false }
let sourceLane: PedalLane
let sourceIndex: Int
if let mainIndex: Int = payload.afterPrefix("movemain:").flatMap(Int.init) {
sourceLane = .main
sourceIndex = mainIndex
} else {
let parts: [Substring] = payload.split(separator: ":")
guard parts.count == 4, parts[0] == "movebranch",
let region: Int = Int(parts[1]), let index: Int = Int(parts[3]) else {
return false
}
sourceLane = (parts[2] == "L") ? .left(region: region) : .right(region: region)
sourceIndex = index
}
do {
_ = try shoeGaze.movePedal(from: sourceLane, at: sourceIndex, to: destination, in: board)
return true
} catch {
print("[BoardFlowView] cross-lane move failed: \(error)")
return false
}
}
// MARK: - Edit actions
@@ -0,0 +1,129 @@
// PedalInfoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdUI
import LyrebirdShoeGaze
/// An info panel for a single pedal: its description and the effect controls with their ranges.
///
/// Shows `pedal.summary` and lists the **effect** controls only — `effectKnobs` + `effectSliders`
/// + `effectSwitches`, each with its value range or switch positions. The common Mix / Level /
/// bypass controls are intentionally omitted (they behave the same on every pedal). Presented
/// from the pedal's ⓘ button.
public struct PedalInfoView: View {
// MARK: - Layout constants
private static let sectionSpacing: CGFloat = 16
private static let rowSpacing: CGFloat = 8
private static let labelColumnWidth: CGFloat = 110
private static let summaryOpacity: Double = 0.85
private static let valueOpacity: Double = 0.7
private static let headerOpacity: Double = 0.5
// MARK: - Properties
private let pedal: Pedal
@Environment(\.dismiss) private var dismiss
// MARK: - Init
/// Creates an info panel for `pedal`.
public init(pedal: Pedal) {
self.pedal = pedal
}
// MARK: - Body
public var body: some View {
NavigationStack {
ScrollView {
VStack(alignment: .leading, spacing: PedalInfoView.sectionSpacing) {
if !pedal.summary.isEmpty {
Text(pedal.summary)
.font(.body)
.foregroundStyle(.primary.opacity(PedalInfoView.summaryOpacity))
.fixedSize(horizontal: false, vertical: true)
}
if !controlRows.isEmpty {
VStack(alignment: .leading, spacing: PedalInfoView.rowSpacing) {
Text("CONTROLS")
.font(.caption2.weight(.semibold))
.foregroundStyle(.secondary.opacity(PedalInfoView.headerOpacity))
ForEach(Array(controlRows.enumerated()), id: \.offset) { pair in
controlRow(pair.element)
}
}
}
}
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
.navigationTitle(pedal.displayName)
#if !os(macOS)
.navigationBarTitleDisplayMode(.inline)
#endif
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") { dismiss() }
}
}
}
}
// MARK: - Control rows
private func controlRow(_ row: ControlRow) -> some View {
HStack(alignment: .firstTextBaseline) {
Text(row.label)
.font(.callout.weight(.medium))
.frame(width: PedalInfoView.labelColumnWidth, alignment: .leading)
Text(row.value)
.font(.callout.monospacedDigit())
.foregroundStyle(.secondary.opacity(PedalInfoView.valueOpacity))
Spacer(minLength: 0)
}
}
/// One displayed control: a label and its range / options string.
private struct ControlRow {
let label: String
let value: String
}
/// Effect controls only (knobs + sliders + switches), in display order.
private var controlRows: [ControlRow] {
var rows: [ControlRow] = []
for knob: PedalKnob in pedal.effectKnobs {
rows.append(ControlRow(label: knob.label, value: PedalInfoView.rangeText(knob.range)))
}
for slider: PedalSlider in pedal.effectSliders {
rows.append(ControlRow(label: slider.label, value: PedalInfoView.rangeText(slider.range)))
}
for pedalSwitch: PedalSwitch in pedal.effectSwitches {
let options: String = pedalSwitch.options.map { $0.title }.joined(separator: " / ")
rows.append(ControlRow(label: pedalSwitch.label, value: options))
}
return rows
}
// MARK: - Formatting
/// Formats a value range as `"lo – hi"`, using integers when both bounds are whole.
private static func rangeText(_ range: ClosedRange<Double>) -> String {
"\(number(range.lowerBound)) – \(number(range.upperBound))"
}
private static func number(_ value: Double) -> String {
if value == value.rounded() {
return String(format: "%.0f", value)
}
return String(format: "%.3g", value)
}
}
@@ -41,13 +41,17 @@ public struct PedalPaletteView: View {
private static let routingCaptionOpacity: Double = 0.5
private static let routingCaptionFontSize: CGFloat = 10
private static let addGlyphOpacity: Double = 0.4
/// Vertical gap between a pedal row's name and its description subtitle.
private static let rowSubtitleSpacing: CGFloat = 2
/// Opacity of the pedal-row description subtitle.
private static let summaryOpacity: Double = 0.55
/// Preferred display order for the built-in pedals. Any registered pedal not listed here is
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
private static let preferredOrder: [String] = [
"Overdrive", "Compressor", "Limiter", "Noise Gate", "Fuzz",
"Graphic EQ", "Tremolo", "Phaser", "Modulation",
"Auto-Wah", "Mutant", "Bass Octaver", "Octave Splitter",
"Overdrive", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus",
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter",
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb",
]
@@ -128,18 +132,29 @@ public struct PedalPaletteView: View {
/// A full-width pedal row: tap appends to the main chain; drag carries `"add:<name>"` so it can
/// be dropped onto a stereo/parallel lane.
private func pedalRow(_ name: String) -> some View {
Button {
let summary: String = PedalRegistry.summary(for: name)
return Button {
onAdd(name)
} label: {
HStack(spacing: 4) {
Text(name)
.font(.callout)
.foregroundStyle(Color.white)
.lineLimit(1)
Spacer(minLength: 0)
Image(systemName: "plus")
.font(.caption2)
.foregroundStyle(Color.white.opacity(PedalPaletteView.addGlyphOpacity))
VStack(alignment: .leading, spacing: PedalPaletteView.rowSubtitleSpacing) {
HStack(spacing: 4) {
Text(name)
.font(.callout)
.foregroundStyle(Color.white)
.lineLimit(1)
Spacer(minLength: 0)
Image(systemName: "plus")
.font(.caption2)
.foregroundStyle(Color.white.opacity(PedalPaletteView.addGlyphOpacity))
}
if !summary.isEmpty {
Text(summary)
.font(.caption2)
.foregroundStyle(Color.white.opacity(PedalPaletteView.summaryOpacity))
.lineLimit(2)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
}
}
.padding(.horizontal, PedalPaletteView.cardPaddingH)
.padding(.vertical, PedalPaletteView.cardPaddingV)
@@ -31,6 +31,10 @@ private func enclosureColor(for displayName: String) -> Color {
case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red
case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal
case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal
case "Chorus": return Color(red: 0.16, green: 0.50, blue: 0.64) // aqua
case "Sustainer": return Color(red: 0.22, green: 0.46, blue: 0.30) // pine green
case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber
case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
}
}
@@ -212,6 +216,11 @@ public struct PedalView: View {
private static let screwHalfSize: CGFloat = 4
private static let namePlateBackgroundOpacity: Double = 0.35
private static let fontSizeNamePlate: CGFloat = 13
/// Opacity of the ⓘ info button.
private static let infoButtonOpacity: Double = 0.7
/// Insets placing the ⓘ info button just under the top-left corner screw.
private static let infoButtonLeading: CGFloat = 5
private static let infoButtonTop: CGFloat = 20
private static let outerBorderLineWidth: CGFloat = 1.5
private static let innerHighlightLineWidth: CGFloat = 1
private static let innerHighlightPadding: CGFloat = 1
@@ -221,6 +230,9 @@ public struct PedalView: View {
private let pedal: Pedal
/// Presentation flag for the pedal info panel (description + control ranges).
@State private var showInfo: Bool = false
// MARK: - Init
/// Creates a stompbox pedal view for the given pedal.
@@ -274,6 +286,11 @@ public struct PedalView: View {
// Corner screws — overlaid at the four corners
screwCorners
// Info button, tucked just under the top-left corner screw.
infoButton
.padding(.leading, PedalView.infoButtonLeading)
.padding(.top, PedalView.infoButtonTop)
}
.frame(width: enclosureWidth(for: sliders))
.shadow(
@@ -282,6 +299,10 @@ public struct PedalView: View {
x: PedalView.shadowXOffset,
y: PedalView.shadowYOffset
)
.sheet(isPresented: $showInfo) {
PedalInfoView(pedal: pedal)
.presentationDetents([.medium, .large])
}
}
// MARK: - Subviews
@@ -297,6 +318,19 @@ public struct PedalView: View {
.clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius))
}
/// Info button tucked just under the top-left corner screw.
private var infoButton: some View {
Button {
showInfo = true
} label: {
Image(systemName: "info.circle")
.font(.system(size: PedalView.fontSizeNamePlate))
.foregroundStyle(Color.white.opacity(PedalView.infoButtonOpacity))
}
.buttonStyle(.plain)
.help("About this pedal")
}
/// Grid of the effect knobs, in rows of up to `knobColumnCount`.
///
/// The trailing `Mix` and `Level` knobs (the last two entries of `pedal.knobs`) are
@@ -87,11 +87,18 @@ public struct ShoeGazeBuilderView: View {
/// Presentation flag for the board-manager sheet (rename / reorder / delete).
@State private var showBoardsSheet: Bool = false
#if !os(macOS)
/// iOS file-dialog presentation flags + the document to export. (macOS uses the File menu.)
@State private var showImporter: Bool = false
/// Confirmation dialog for the Clear action, and a flag to clear once a chosen save completes.
@State private var showClearDialog: Bool = false
@State private var pendingClearAfterSave: Bool = false
/// Rig-save export state. Cross-platform: the in-view exporter backs both the Save action and
/// the "Save & Clear" flow on macOS and iOS (macOS additionally has a File-menu Save).
@State private var showExporter: Bool = false
@State private var exportDocument: RigFileDocument = RigFileDocument(data: Data())
#if !os(macOS)
/// iOS file-dialog presentation flags. (macOS uses the File menu for load + recording folder.)
@State private var showImporter: Bool = false
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
@State private var showRecordingFolderImporter: Bool = false
#endif
@@ -164,6 +171,25 @@ public struct ShoeGazeBuilderView: View {
// node. SwiftUI reliably drives only one presentation per view node, so stacking them
// all on the root view silently swallowed some (e.g. the iOS Load file importer).
.background(boardsSheetAnchor)
.background(rigExportAnchor)
.confirmationDialog(
"Clear all boards?",
isPresented: $showClearDialog,
titleVisibility: .visible
) {
Button("Save & Clear") {
pendingClearAfterSave = true
saveAction()
}
Button("Clear Without Saving", role: .destructive) {
performClear()
}
Button("Cancel", role: .cancel) {
pendingClearAfterSave = false
}
} message: {
Text("This removes every pedal and board. Save your current setup first?")
}
.alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) {
Button("OK", role: .cancel) { }
} message: {
@@ -173,7 +199,6 @@ public struct ShoeGazeBuilderView: View {
#if !os(macOS)
.background(rigImportAnchor)
.background(recordingFolderImportAnchor)
.background(rigExportAnchor)
#endif
}
@@ -194,6 +219,28 @@ public struct ShoeGazeBuilderView: View {
}
}
/// Hosts the rig-save (`.json`) exporter on its own node. Cross-platform: backs both the
/// Save action and the "Save & Clear" flow. On a successful save during "Save & Clear", the
/// pending clear runs; cancelling the save leaves the boards untouched.
private var rigExportAnchor: some View {
Color.clear
.fileExporter(
isPresented: $showExporter,
document: exportDocument,
contentType: .json,
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
) { result in
switch result {
case .failure(let error):
print("[ShoeGazeBuilderView] export failed: \(error)")
pendingClearAfterSave = false
case .success:
if pendingClearAfterSave { performClear() }
pendingClearAfterSave = false
}
}
}
#if !os(macOS)
/// Hosts the rig-load (`.json`) importer on its own node.
private var rigImportAnchor: some View {
@@ -210,21 +257,6 @@ public struct ShoeGazeBuilderView: View {
handleRecordingFolderImport(result)
}
}
/// Hosts the rig-save (`.json`) exporter on its own node.
private var rigExportAnchor: some View {
Color.clear
.fileExporter(
isPresented: $showExporter,
document: exportDocument,
contentType: .json,
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
) { result in
if case .failure(let error) = result {
print("[ShoeGazeBuilderView] export failed: \(error)")
}
}
}
#endif
// MARK: - Transport row
@@ -282,13 +314,18 @@ public struct ShoeGazeBuilderView: View {
.buttonStyle(.bordered).tint(.orange)
.help("Rename, reorder, or delete boards")
Button("Clear") { showClearDialog = true }
.buttonStyle(.bordered).tint(.red)
.help("Remove all boards (with the option to save first)")
Spacer()
// On macOS, Save/Load live in the app's File menu (see the app shell's AppDelegate);
// on iOS they stay in-view, driven by fileExporter/fileImporter.
#if !os(macOS)
// On macOS, Load lives in the app's File menu (see the app shell's AppDelegate); on
// iOS it stays in-view via fileImporter. Save is in-view on both (cross-platform
// exporter) so the "Save & Clear" flow works everywhere.
Button("Save…") { saveAction() }
.buttonStyle(.bordered).tint(.blue)
#if !os(macOS)
Button("Load…") { loadAction() }
.buttonStyle(.bordered).tint(.blue)
#endif
@@ -374,6 +411,7 @@ public struct ShoeGazeBuilderView: View {
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
do {
_ = try shoeGaze.appendPedal(PedalType(type), to: board)
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
}
@@ -386,12 +424,45 @@ public struct ShoeGazeBuilderView: View {
created = board
try shoeGaze.finalizeBoard(board)
selectedBoardIndex = shoeGaze.boards.count - 1
autosave()
} catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilderView] addBoard failed: \(error)")
}
}
/// Persists the current rig to the autosave file. Called after structural edits so state
/// survives a restart even without an explicit Save; the app shells also save on background.
private func autosave() {
RigStore.save(shoeGaze)
}
/// Removes every board, then seeds one fresh empty board so the builder is never boardless.
/// Resets the edit target and autosaves the cleared state.
private func performClear() {
// Stop around the rebuild so removing every board and immediately re-adding a fresh one
// can't reuse a bus a just-removed master is still draining (one-block glitch).
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeBuilderView] clear failed to seed a fresh board: \(error)")
}
selectedBoardIndex = 0
if wasRunning { try? shoeGaze.engine.start() }
autosave()
transportTick.toggle()
}
/// Switches input source, stopping/restarting the engine around the graph rebuild.
///
/// Live input requires microphone authorisation first — without it macOS feeds the AUHAL
@@ -490,9 +561,9 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Save / Load (iOS)
// On macOS, Save/Load are driven from the app's File menu (the app shell owns the
// NSSavePanel/NSOpenPanel and calls `shoeGaze.saveRig`/`loadRig` directly). On iOS they are
// in-view, presenting `fileExporter`/`fileImporter`.
// Save is in-view on both platforms (cross-platform fileExporter) so "Save & Clear" works
// everywhere. Load is the macOS File menu / iOS fileImporter; recording controls are iOS
// in-view (macOS uses the Record menu).
#if !os(macOS)
/// iOS recording controls: choose an output folder, then start/stop recording.
private var recordingRow: some View {
@@ -537,7 +608,9 @@ public struct ShoeGazeBuilderView: View {
print("[ShoeGazeBuilderView] recording folder pick failed: \(error)")
}
}
#endif
/// Presents the cross-platform rig-save exporter (also used by the "Save & Clear" flow).
private func saveAction() {
do {
exportDocument = RigFileDocument(data: try shoeGaze.rigData())
@@ -547,6 +620,7 @@ public struct ShoeGazeBuilderView: View {
}
}
#if !os(macOS)
private func loadAction() {
showImporter = true
}
@@ -559,6 +633,7 @@ public struct ShoeGazeBuilderView: View {
do {
try shoeGaze.loadRig(from: url)
selectedBoardIndex = 0
autosave()
} catch {
print("[ShoeGazeBuilderView] loadRig failed: \(error)")
}
@@ -582,4 +582,54 @@ struct BoardEditAPITests {
let samples: [Float] = try render(engine2, url2)
#expect(hasNonSilentOutput(samples), "loaded edited rig should render audio")
}
// MARK: - Cross-lane move (drag a pedal into a region lane)
@Test func moveMainPedalIntoStereoUnzipLanePreservingParams() throws {
// Ping-Pong (stereo) then Overdrive on the main chain; unzip after Ping-Pong.
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Ping-Pong", "Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 0, in: board)
// Tweak the live Overdrive so we can verify its params survive the move.
let overdrive: OverdrivePedal? = live.pedals.compactMap { $0 as? OverdrivePedal }.first
overdrive?.drive = 11.0
// Move the Overdrive (main linear index 1) into the unzip's left lane (region segment 1).
live = try sg.movePedal(from: .main, at: 1, to: .left(region: 1), in: live)
#expect(names(live) == ["Ping-Pong"], "Overdrive should leave the main chain")
guard let state: StereoUnzipState = unzipState(live) else {
Issue.record("No stereo unzip segment")
return
}
#expect(state.left.map { $0.type } == ["Overdrive"], "Overdrive should land in the left lane")
#expect(state.left.first?.knobValues.first == 11.0, "Drive param should survive the move")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "board renders after the cross-lane move")
}
@Test func moveMainPedalBeforeUnzipRegionAdjustsIndex() throws {
// Overdrive (mono) then Ping-Pong (stereo); unzip after Ping-Pong. Moving the Overdrive —
// which sits BEFORE the unzip region — exercises the destination-index adjustment.
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Ping-Pong"])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.insertStereoUnzip(afterSegment: 1, in: board)
// Unzip is top-level segment 2; Overdrive is main linear index 0 (top-level segment 0).
live = try sg.movePedal(from: .main, at: 0, to: .left(region: 2), in: live)
#expect(names(live) == ["Ping-Pong"], "Overdrive should leave the main chain")
guard let state: StereoUnzipState = unzipState(live) else {
Issue.record("No stereo unzip segment")
return
}
#expect(state.left.map { $0.type } == ["Overdrive"], "Overdrive should land in the left lane")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "board renders after the index-adjusted move")
}
}
@@ -0,0 +1,131 @@
// ChorusPedalTests.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("ChorusPedal")
struct ChorusPedalTests {
private func render(configure: (ChorusPedal) -> Void = { _ in }) throws -> [Float] {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: ChorusPedal = ChorusPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
private func ssd(_ a: [Float], _ b: [Float]) -> Double {
let skip: Int = 2048, window: Int = 2048
guard a.count >= skip + window, b.count >= skip + window else { return 0 }
return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render()
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "ChorusPedal produced silence")
}
@Test func rateChangesOutput() throws {
let slow: [Float] = try render { $0.rate = 0.1 }
let fast: [Float] = try render { $0.rate = 5.0 }
#expect(hasNonSilentOutput(slow) && hasNonSilentOutput(fast))
#expect(ssd(slow, fast) > 0, "rate had no effect on output")
}
@Test func depthChangesOutput() throws {
let shallow: [Float] = try render { $0.depth = 0.0005 }
let deep: [Float] = try render { $0.depth = 0.008 }
#expect(ssd(shallow, deep) > 0, "depth had no effect on output")
}
@Test func leftAndRightVoicesDiffer() throws {
// The point of the widener: anti-phase LFOs make the two voices distinct. Activate the
// right channel (which a stereo board region does via PedalBoard.add) by setting
// `outputBusRight`, route each board bus to a separate hardware channel, and compare.
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstL: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstR: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstL)
engine.busAllocator.releaseAudioBus(dstR)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: ChorusPedal = ChorusPedal(inputBus: srcBus.index, outputBus: dstL.index)
pedal.outputBusRight = dstR.index // emulate the stereo region a board would create
let master: StereoSplitTestMaster = StereoSplitTestMaster(left: dstL.index, right: dstR.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
// readStereoCAF returns interleaved [L, R, L, R, …]; even = left voice, odd = right voice.
let samples: [Float] = readStereoCAF(url: url)
let skipFrames: Int = 2048
let windowFrames: Int = 2048
guard samples.count >= 2 * (skipFrames + windowFrames) else { return }
var lefts: [Float] = []
var rights: [Float] = []
for frame: Int in skipFrames ..< (skipFrames + windowFrames) {
lefts.append(samples[2 * frame])
rights.append(samples[2 * frame + 1])
}
#expect(hasNonSilentOutput(lefts) && hasNonSilentOutput(rights), "a chorus voice was silent")
let ssdLR: Double = zip(lefts, rights).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssdLR > 0, "left and right chorus voices are identical — no stereo width")
}
}
/// Routes two mono board buses to hardware left (bus 0) and right (bus 1) so a stereo widener's
/// channels can be captured separately by `readStereoCAF`.
@MainActor
private final class StereoSplitTestMaster: SynthesizerBase {
private let left: Int
private let right: Int
init(left: Int, right: Int) {
self.left = left
self.right = right
super.init()
}
override func build() {
output(bus: 0, source: input(bus: left))
output(bus: 1, source: input(bus: right))
}
}
@@ -0,0 +1,98 @@
// DiffuserPedalTests.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("DiffuserPedal")
struct DiffuserPedalTests {
/// Renders the diffuser as a stereo widener, returning (leftSamples, rightSamples).
private func renderStereo(spread: Double) throws -> (left: [Float], right: [Float]) {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstL: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstR: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstL)
engine.busAllocator.releaseAudioBus(dstR)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: DiffuserPedal = DiffuserPedal(inputBus: srcBus.index, outputBus: dstL.index)
pedal.outputBusRight = dstR.index
pedal.spread = spread
let master: DiffuserStereoSplitMaster = DiffuserStereoSplitMaster(left: dstL.index, right: dstR.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
let skipFrames: Int = 2048
let windowFrames: Int = 2048
var left: [Float] = []
var right: [Float] = []
guard samples.count >= 2 * (skipFrames + windowFrames) else { return ([], []) }
for frame: Int in skipFrames ..< (skipFrames + windowFrames) {
left.append(samples[2 * frame])
right.append(samples[2 * frame + 1])
}
return (left, right)
}
private func ssd(_ a: [Float], _ b: [Float]) -> Double {
zip(a, b).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let (left, right): ([Float], [Float]) = try renderStereo(spread: 0.6)
#expect(hasNonSilentOutput(left), "diffuser left channel was silent")
#expect(hasNonSilentOutput(right), "diffuser right channel was silent")
}
@Test func zeroSpreadIsMono() throws {
// At spread 0 every band sits centre → left and right are identical.
let (left, right): ([Float], [Float]) = try renderStereo(spread: 0.0)
#expect(hasNonSilentOutput(left))
#expect(ssd(left, right) == 0, "spread 0 should collapse to mono (L == R)")
}
@Test func spreadWidensTheImage() throws {
// At full spread the spectrum fans across the field → channels differ.
let (left, right): ([Float], [Float]) = try renderStereo(spread: 1.0)
#expect(ssd(left, right) > 0, "full spread should make L and R differ")
}
}
/// Routes two mono board buses to hardware left (0) and right (1) so a widener's channels can be
/// captured separately by `readStereoCAF`.
@MainActor
private final class DiffuserStereoSplitMaster: SynthesizerBase {
private let left: Int
private let right: Int
init(left: Int, right: Int) {
self.left = left
self.right = right
super.init()
}
override func build() {
output(bus: 0, source: input(bus: left))
output(bus: 1, source: input(bus: right))
}
}
@@ -0,0 +1,43 @@
// PedalInfoTests.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("Pedal info")
struct PedalInfoTests {
@Test func everyBuiltInPedalHasASummary() throws {
for type: String in PedalRegistry.builtIn.keys {
let pedal: Pedal? = PedalRegistry.makePedal(type: type)
#expect(pedal != nil, "registry could not build \(type)")
let summary: String = pedal?.summary ?? ""
#expect(!summary.isEmpty, "\(type) has an empty summary — every pedal must set one")
}
}
@Test func registrySummaryHelperMatchesInstance() throws {
#expect(PedalRegistry.summary(for: "Overdrive") == OverdrivePedal().summary)
#expect(PedalRegistry.summary(for: "Ring Modulator") == RingModulatorPedal().summary)
#expect(PedalRegistry.summary(for: "Nope") == "")
}
@Test func effectControlsExcludeCommonControls() throws {
// The info panel lists effect controls only; the common Mix / Level / bypass live in the
// base `Pedal` and must never appear in effectKnobs/effectSliders/effectSwitches.
let pedal: GraphicEQPedal = GraphicEQPedal()
let effectLabels: [String] =
pedal.effectKnobs.map { $0.label }
+ pedal.effectSliders.map { $0.label }
+ pedal.effectSwitches.map { $0.label }
#expect(!effectLabels.contains("Mix"))
#expect(!effectLabels.contains("Level"))
}
}
@@ -0,0 +1,52 @@
// RigStoreTests.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("RigStore")
struct RigStoreTests {
@Test func savesAndRestoresAcrossInstances() throws {
RigStore.clear()
defer { RigStore.clear() }
// Build a rig and autosave it.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: urlA) }
let a: ShoeGaze = ShoeGaze(engine: engineA)
let lead: PedalBoard = try a.addBoard()
lead.label = "Lead"
try a.appendPedal(.overdrive, to: lead)
try a.finalizeBoard(lead)
let clean: PedalBoard = try a.addBoard()
clean.label = "Clean"
try a.appendPedal(.graphicEQ, to: clean)
try a.finalizeBoard(clean)
#expect(RigStore.save(a))
// A fresh, boardless instance restores the autosaved rig.
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: urlB) }
let b: ShoeGaze = ShoeGaze(engine: engineB)
#expect(RigStore.restore(into: b))
#expect(b.boards.count == 2)
#expect(b.boards.first?.label == "Lead")
#expect(b.boards.last?.label == "Clean")
}
@Test func restoreReturnsFalseWhenNoAutosave() throws {
RigStore.clear()
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
#expect(!RigStore.restore(into: sg), "restore should report nothing to load after clear()")
}
}
@@ -0,0 +1,58 @@
// RingModulatorPedalTests.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("RingModulatorPedal")
struct RingModulatorPedalTests {
private func render(frequency: Double) throws -> [Float] {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: RingModulatorPedal = RingModulatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.frequency = frequency
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render(frequency: 220.0)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "RingModulatorPedal produced silence")
}
@Test func frequencyChangesOutput() throws {
let low: [Float] = try render(frequency: 100.0)
let high: [Float] = try render(frequency: 800.0)
#expect(hasNonSilentOutput(low) && hasNonSilentOutput(high))
let skip: Int = 1024, window: Int = 2048
guard low.count >= skip + window, high.count >= skip + window else { return }
let ssd: Double = zip(low[skip..<(skip + window)], high[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "carrier frequency had no effect on output")
}
}
@@ -0,0 +1,64 @@
// SustainerPedalTests.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("SustainerPedal")
struct SustainerPedalTests {
private func render(configure: (SustainerPedal) -> Void = { _ in }) throws -> [Float] {
let renderDuration: Double = 0.1
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: SustainerPedal = SustainerPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render()
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "SustainerPedal produced silence")
}
@Test func exposesSustainAndToneKnobs() throws {
let pedal: SustainerPedal = SustainerPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Sustain", "Tone"])
}
@Test func sustainAmountChangesOutput() throws {
// Min vs max sustain drive the compressor very differently → measurably different output.
let gentle: [Float] = try render { $0.sustain = 0.0 }
let squashed: [Float] = try render { $0.sustain = 10.0 }
#expect(hasNonSilentOutput(gentle) && hasNonSilentOutput(squashed))
let skip: Int = 1024, window: Int = 2048
guard gentle.count >= skip + window, squashed.count >= skip + window else { return }
let ssd: Double = zip(gentle[skip..<(skip + window)], squashed[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "sustain knob had no effect on output")
}
}
+34
View File
@@ -0,0 +1,34 @@
# 1.1 — Chorus pedal (true stereo)
## Why distinct from Modulation
`ModulationPedal` already wraps Lyrebird's `Chorus.Audio` and **sums to mono**
(`SumChannels`). The new **Chorus** keeps the signal **stereo** (a `widener` pedal) and
exposes more control — a lusher, wider voice than the mono Modulation classic. Keep both.
## Implementation
`Sources/LyrebirdShoeGaze/Pedals/ChorusPedal.swift`
- `override var channelKind: PedalChannelKind { .widener }`
- Override `wideEffect(_ dry:) -> (left:right:)` (not `effect`): build one
`Chorus.Audio(input: dry, delayTime:, depth: $depth, rate: $rate, mix: 1.0,
sampleRate: sampleRate, maxDelayTime:)` and return its two channels as L/R
(do **not** `SumChannels`).
- Knobs (`effectKnobs`): `rate` 0.05–6 Hz (def ~0.8), `depth` 0.0005–0.01 s (def ~0.003).
Wet/dry via the base `mix` (`initialMix` ~0.5).
- Constants: `delayTime` ~0.025 s, `maxDelayTime` ~0.1 s (match Modulation).
## Wiring
- `PedalRegistry.builtIn["Chorus"] = { ChorusPedal() }`
- `PedalType.chorus = PedalType("Chorus")`
- `PedalView` enclosure color case `"Chorus"`
- `PedalPaletteView.preferredOrder` — near Modulation / Phaser
- `summary` override (see info-UI plan)
## Tests (`Tests/LyrebirdShoeGazeTests/ChorusPedalTests.swift`)
- builds + non-silent
- stereo: L channel ≠ R channel (the point of the pedal)
- rate and depth each change the output
## Open question
Keep both Modulation (mono) and Chorus (stereo) — recommended. Alternative: rename
Modulation → "Vibrato". Not doing that here.
+40
View File
@@ -0,0 +1,40 @@
# 1.1 — Pedal info UI (description + control ranges)
Show a short description of each pedal in the picker, and an info button on the pedal that
opens a panel with the description and the **effect controls** (knobs / sliders / switches)
plus their value ranges — excluding the common Mix / Level / bypass controls.
## Model (core, `LyrebirdShoeGaze`)
- Add to `Pedal`: `open var summary: String { "" }` — one-line description, overridden by
every pedal. Single source of truth.
- `PedalRegistry.summary(for displayName: String) -> String` for the palette: instantiates
`builtIn[name]?()` and reads `.summary`. No `engine.add`, so `build()` never runs — only a
cheap object alloc. Cache in the palette view.
- (Optional stretch) richer rows: add `detail: String?` and/or `unit: String?` to
`PedalKnob` / `PedalSlider` / `PedalSwitch`. Not required — `range` / `options` already
carry enough to show ranges.
## Palette (`PedalPaletteView`)
- Row → `VStack(alignment: .leading)`: name (callout) + `summary` (caption2, secondary,
~2 lines). Keep the `+` glyph and `.draggable`.
## Pedal info affordance (`PedalView`)
- Small **ⓘ button** in the name-plate (top-right of the enclosure header).
- Tap → `.sheet` / `.popover` on its **own anchor node** (one presentation per node — same
pattern as the file pickers) presenting a new `PedalInfoView(pedal:)`.
## `PedalInfoView` (`LyrebirdShoeGazeUI`)
- Title = `pedal.displayName`; body = `pedal.summary`.
- Controls list from `effectKnobs` + `effectSliders` + `effectSwitches` **only** (not
`knobs`, which includes Mix/Level; not bypass):
- knob / slider → `label` + range, e.g. `"200 – 8000"` (raw range; add `unit` later).
- switch → `label` + option titles.
## Wiring
- Override `summary` on **all** pedals (short sentences).
- Going forward, every new pedal MUST set `summary` — see CLAUDE.md.
## Tests
- every entry in `PedalRegistry.builtIn` produces a pedal with non-empty `summary`.
- `PedalInfoView` (or a helper that builds its rows) lists exactly the effect controls,
not the common three.
+31
View File
@@ -0,0 +1,31 @@
# 1.1 — Ring Modulator pedal
Multiplies the signal by a tunable carrier → metallic / bell / robot sidebands (sum &
difference of input and carrier). Classic ring mod = `dry × carrier` — no dedicated
Lyrebird generator needed. (`Ring1–4` are SC math variants; `FrequencyShifter` is SSB,
a possible stretch mode.)
## Implementation
`Sources/LyrebirdShoeGaze/Pedals/RingModulatorPedal.swift`
- `effect`: `let carrier = OscSin.Audio(freq: $frequency); return dry * carrier`
- Knobs:
- **`frequency`** carrier in Hz. Range ~**20–2000** (def ~220). <~30 Hz ≈ tremolo/AM;
audio range = classic ring mod.
- wet/dry via inherited **`mix`** (`initialMix` ~0.5 — harsh, keep dry present).
- **Optional waveform switch** (`PedalSwitch`): Sine / Square carrier (square = more
sidebands, harsher) — square via `LFSquare`/`OscSquare`. If added, preset round-trip test.
- **Stretch — Mode switch (Ring / Shift):** add an SSB pitch mode wrapping Lyrebird's
`FrequencyShifter`. Base pass = Ring only; Shift is a follow-up.
## Wiring
- `PedalRegistry.builtIn["Ring Modulator"] = { RingModulatorPedal() }`
- `PedalType.ringModulator = PedalType("Ring Modulator")`
- enclosure color, palette order (group with Phaser / Mutant "filter / weird" section)
- `summary` override, e.g. *"Multiplies your signal by a tunable carrier for metallic,
bell-like, and robotic tones."*
## Tests (`Tests/LyrebirdShoeGazeTests/RingModulatorPedalTests.swift`)
- builds + non-silent
- frequency change alters output (e.g. 100 Hz vs 800 Hz windows differ)
- (if switch added) square vs sine differ; preset round-trip of the switch
+33
View File
@@ -0,0 +1,33 @@
# 1.1 — Sustainer pedal
A one-knob sustain: heavy compression + makeup gain to hold notes, distinct from the
`Compressor` pedal (which exposes threshold/ratio directly).
## Implementation
`Sources/LyrebirdShoeGaze/Pedals/SustainerPedal.swift`
- `effect`: `Compressor.Audio(in: dry, threshold:, ratio:, attack: ~0.005,
release: ~0.4, kneeWidth: 0, makeupGain:)`.
- **`sustain` knob (0–10, def ~5)** — the single perceptual control. Maps internally:
- threshold: `-6 dB → -36 dB` as sustain rises
- ratio: `2 → 10`
- makeupGain: tracks the added gain reduction (so output stays even)
Implement the map with `LinLin` on the `$sustain` node (or fold into Compressor's
`ValidGeneratorInput` params via arithmetic on `$sustain`).
- **`tone` knob (optional)** — `RBJLowPass.Audio(input:, freq: $tone, q: 0.707)` to round the squashed top end. Range ~800–8000 Hz.
- `level` (inherited) for output trim. `initialMix` = 1.0 (in-line).
- **Stretch — floor/gate:** reuse the NoiseGate idea (`AmplitudeFollower` → `Schmidt` →
`LinLin` floor → `Lag` → ×) so infinite sustain doesn't surface hiss. Optional knob
`floor`, or a fixed gentle gate. Defer if it complicates the one-knob feel.
## Wiring
- `PedalRegistry.builtIn["Sustainer"] = { SustainerPedal() }`
- `PedalType.sustainer = PedalType("Sustainer")`
- enclosure color, palette order (near Compressor / Limiter)
- `summary` override
## Tests (`Tests/LyrebirdShoeGazeTests/SustainerPedalTests.swift`)
- builds + non-silent
- sustain knob changes dynamics: low vs high sustain → measurable RMS/level difference on
a decaying input window
- knob list assertion