35 Commits

Author SHA1 Message Date
josh 4e58c9bd9b Looper UI: make the selected track dot read as active
A selected-but-empty track (e.g. A in the clear state) previously showed only a
thin white ring on a dim dot — easy to read as "not lit." Give the selected
track a bright letter and a lighter fill so the active track is obvious even
before it's recorded. Combined with the poll re-subscribe fix, the dots now
track the live selection.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 22:19:14 -07:00
josh 2ce6dda9da Looper UI: re-subscribe polls when the pedal instance changes
The looper timeline and the transport buttons' live captions poll the pedal
via SwiftUI `.task`, which captures the pedal at task-start and never
re-subscribes. When a rig load swaps in a new LooperPedal instance, the
buttons/LEDs (read live in `body`) tracked the new pedal while the polled
state text and captions stayed frozen on the old one — the state indicator and
"Record/Set End/…" captions never updated even though transport worked.

Key the timeline poll on ObjectIdentifier(pedal) (`.task(id:)`) and tag the
transport button row with `.id(ObjectIdentifier(pedal))`, so both re-subscribe
to the current instance. Board edits reuse the same instance (identity stable),
so this only refreshes on an actual instance swap — no per-render churn.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 22:17:40 -07:00
josh b6f1d78066 Looper: MIDI-mappable A/B/C/D track taps
Add looperTrack(index:) PedalActionKind dispatched to LooperPedal.tapTrack, and
Track A–D rows in the MIDI mapping sheet (one per track, up to trackCount). A
mapped switch/Program Change taps the dot — selecting the track, or muting it
when it's already selected and recorded — matching the timeline dots. Covered
by pedalActionTapsLooperTrack.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 18:54:47 -07:00
josh 296ca1b24e Looper: per-track mute via the A/B/C/D dots
Each track player now runs through a smoothed per-track mute gate. Tapping a
track dot selects it (as before); tapping the already-selected, recorded track
toggles its mute (tapTrack). Muted dots dim and show a slash. Mutes clear on
reset and don't survive a rebuild. Covered by tapTrackSelectsThenMutesRecordedTrack.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:29:16 -07:00
josh 3ef39a7a0d Looper: MIDI-mappable Sync, cycling through the switch options
Add a looperSyncToggle PedalActionKind (dispatched to LooperPedal.cycleSyncMode)
and a Sync row in the MIDI mapping sheet. A mapped switch/Program Change
oscillates the control through its positions on each press, via a reusable
PedalSwitch.nextValue(after:) that advances to the next option and wraps — so
this generalises to any multi-position switch, not just the two-state Sync.

Tests: cycleSyncModeOscillatesThroughOptions, pedalActionCyclesLooperSync.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:24:50 -07:00
josh 5dafc00d98 Looper: add Sync / Free transport mode toggle
New syncToBeat switch (Free / Sync, default Sync) rendered as a segmented
control below the knobs and persisted with the rig. When off, runQuantized
applies transport immediately (freeform — loop length is whatever you play,
not beat-measured) even with a clock present; when on, record start / loop
close arm to the next beat as before. Not reset by resetLoop / resetForRebuild
so the mode sticks. Covered by freeformModeRecordsImmediatelyDespiteClock.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:16:13 -07:00
josh fb3e2d2653 Looper: make effect() idempotent across graph rebuilds
The engine re-invokes build()/effect() via rebuildGraph() on every add —
including the re-adds a board edit (reorder, insert/remove a neighbour, toggle
a split) or a rig load performs on the same instance. effect() appended to the
per-track arrays (buffers/players/overdubRecorders/overdubGates) each time, so a
second build doubled them, desyncing the generators from the fixed-size state
arrays and leaving the whole looper UI/transport wrong — a broken state that
stuck and reproduced from a saved rig. Reset the arrays and transport state at
the top of effect() (resetForRebuild) so a rebuild starts clean; the freshly
re-allocated buffers are empty, so returning to the clear state is correct.

Regression: rebuildDoesNotDoubleTrackGenerators (two effect() calls keep each
array at trackCount).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 17:07:48 -07:00
josh ae067ac6d7 Looper: regression coverage for record-after-reset (both paths)
Add quantizedRecordsAgainAfterReset, driving the beat-quantized
applyQuantizedTransport generation-guard path across a reset, plus the
immediate-path recordsAgainAfterReset. Both confirm the transport state
machine re-enters recording/playing correctly after a reset. Expose
applyQuantizedTransport / QuantizedAction as internal for the test seam.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 16:58:18 -07:00
josh 6f651b6e17 Looper: reset also clears reverse and the transient notice
resetLoop() left `reverse` untouched, so after a reset with reverse engaged the
next take's auto-overdub on track A was silently blocked (closeMasterAndPlay
skips overdub while reversed) and playback ran backward — the "record/overdub
after reset looks broken" report. Reset now returns to forward playback and
also clears any lingering engine-stop/rig-change notice so it can't mask the
fresh state indicator. Covered by recordsAgainAfterReset.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 16:52:18 -07:00
josh 67d4434220 Looper: address review — router pedals + doc fixes
allPedals() (used by stopEngine / teardown to notify pedals) now also walks
ChainRouter branch boards, so a looper placed in a parallel-router branch gets
engineDidStop() / rigWillTeardown() like any other. Factor the per-board walk
into pedals(in:).

Restore addBoard()'s doc comment (it was displaced above stopEngine when that
method was inserted) and document the engine-stopped precondition on
Pedal.rigWillTeardown().

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 16:34:45 -07:00
josh b99a526df6 Looper: MIDI-mappable transport; clean-through + Playback balance
MIDI: add looperStop / looperCueStop / looperReverse PedalActionKind cases and
dispatch them (stopPlayback / toggleStopAtLoopEnd / toggleReverse). The MIDI
mapping sheet now lists Record / Stop / Cue Stop / Reverse / Reset as
Program-Change-mappable switch actions for each looper pedal (previously only
Bypass was surfaced).

Mix: the clean guitar now always passes through at full level and the loop bank
is summed on top (dry + loop·gate) instead of crossfading dry against the loop.
The Playback knob therefore sets the looped-vs-live balance. Hide the confusing
wet/dry Mix knob for the looper via a new Pedal.showsMixControl (mix stays fully
wet); other pedals are unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 16:08:25 -07:00
josh d728bfa72a Looper: also reset on rig teardown
Add a Pedal.rigWillTeardown() hook fired for every pedal at the top of
ShoeGaze.teardown() (rig load / clear / input-source change), while the pedal
is still live. LooperPedal resets and posts a notice, sharing the path with
engineDidStop() — so a looper stops its background routines cleanly and logs
before its instance is discarded across a rig change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 15:25:12 -07:00
josh fee7892101 Looper: stomp-style Reset button; reset on engine stop
Reset now renders as an LED + footswitch like the other transport buttons —
its LED lights whenever there's something to reset (any non-clear state),
driven off a phase didSet.

Add a Pedal.engineDidStop() hook, invoked for every pedal by a new
ShoeGaze.stopEngine() that the user-facing Stop control now calls (transient
stop-around-rebuild sequences still call engine.stop() directly, so pedals
keep state across a restart). LooperPedal overrides it to return to the clear
state, post to LyrebirdMessageCenter, and briefly show "Looper reset — engine
stopped." on its own card via the state indicator.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 15:20:33 -07:00
josh 83b8fff74b Looper: fix multitrack RT-safety findings from review
Phase-lock: reset the overdub recorder write heads (requestReset) and the
player play-heads (playTrigger rising edge) synchronously in startPlayback so
both re-anchor on the same audio block, instead of deferring the trigger an
extra run-loop turn; playTrigger is zeroed on every stop for a clean 0→1 edge.
This also makes overdub actually record under NRT.

Reverse vs overdub: overdub records forward-in-time and can't follow a reversed
play-head. Block engaging overdub while reversed, and make Reverse a
toggleReverse() action that ends any active overdub when engaging reverse (the
footswitch keeps its LED via indicator: $reverse).

resetLoop: gate isPlaying off before clear() so the buffer-clear overlaps at
most one in-flight RT block; corrected the rationale comment.

Docs: fix stale $overdubOn / .empty / .recording references.

Tests: overdubbingTrackAAddsEnergyToTheLoop (NRT overdub records),
overdubBlockedWhileReversed, engagingReverseWhileOverdubbingEndsOverdub.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 15:07:41 -07:00
josh 3007b76798 Looper: multitrack redesign with smart Loop footswitch
Replace the one-at-a-time slot model with a synchronized multitrack looper:
four track players summed to one output, track A's first take defining the
master loop length, and tracks B–D recorded as phase-locked overdub layers
on the same grid (overdub recorders run continuously while playing, reset to
the top at play-start, gated per-track by recLevel so only the selected
track layers new input — instant, drift-free overdub toggles).

A single smart Loop footswitch drives the whole transport by state:
record A → set end (quantized) → auto-overdub on wrap → toggle overdub/play;
B–D toggle overdub aligned to A's play-head. Selecting a track ends the
prior overdub. Stop / Cue Stop pause; Loop resumes. Reset returns to clear.

UI: transport row is now Loop / Stop / Cue Stop / Reverse / Reset; the old
action row is replaced by a one-line state indicator; the A/B/C/D timeline
dots are tappable to select a track; every stomp button shows a live caption
of what its next press does (Record → Set End → Overdub → Play, etc.).

Overdub-undo dropped. All transport routines keep the transportGeneration
guard on deferred beat/stop callbacks.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 14:24:46 -07:00
josh 465e3e6dfd Looper: multi-slot + timeline + stop/cue-stop, quantized transport
Checkpoint before the multitrack redesign. Adds 4 loop slots (one player
swapped via setBuffer), a play-head timeline with A/B/C/D dots, Loop/Stop/
Cue Stop/Reverse stomp toggles below the knobs, beat-quantized transport,
overdub undo, reverse, and feedback-decay overdub — all reviewed for RT
safety (transportGeneration guards on deferred beat/undo/cue callbacks).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 14:14:46 -07:00
josh 947dfe427a Add looper pedal: beat-quantized transport, undo, reverse, timeline
Extend the looper into a double-width tempo-aware pedal:

- Beat-quantized transport: record start and loop close both snap to the
  next beat via a LyrebirdRoutine waiting on the shared clock; loop length
  is an exact whole-beat span. Falls back to immediate/unquantized when no
  clock is present.
- Loop-length read-outs (frames/seconds/beats), transport state, and a
  sample-clock-derived play-head position for the UI timeline.
- Overdub undo (pre-dub snapshot + restore), reverse playback (live rate
  flip), and feedback-decay overdub (overdub preLevel via a Feedback knob).
- Inject the shared LyrebirdClock + SynthesisEngine into Pedal via
  PedalBoard/ChainRouter so tempo-aware pedals can reach them.
- New double-width LooperTimelineView (state badge, length read-out,
  sweeping play-head) wired into PedalView via Pedal.widthUnits.

Concurrency hardening from RT-safety review: a transportGeneration counter
drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop()
cannot recall once enqueued; the undo restore is deferred past the RT
overdub gate-close; transport routines use non-blocking stop().

Note: this commit also snapshots pre-existing uncommitted work-in-progress
already in the tree (MIDI control refactor, Tuner, Tempo, preset changes),
which is interleaved with the looper changes through shared files and could
not be split into a separately-building commit.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-03 09:22:20 -07:00
josh 097253b410 Document 1.4.0: MIDI control, rig volume/mute, new reverbs, Help
Update README's feature list and pedal catalog, add the 1.4.0 RELEASES.md
entry, and bump both builder apps to 1.4.0.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-01 19:32:59 -07:00
josh 9ccdada4f1 sync 2026-07-01 19:31:51 -07:00
josh 75edf44b64 Add rig-wide output volume + hard mute, MIDI-mappable
Volume is a CC-mappable [0,1] gain applied after every board's output; mute
is a separate hard gate (not the existing dry bypass), togglable via
Program Change. Both are lagged to avoid clicks and fan out across all
boards from a single ShoeGaze-level setter.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-01 19:28:09 -07:00
josh d4664b3c1f Persist the source rig id inside the autosave; single source of truth
The rig-highlight/graph mismatch kept returning because the highlight (a
UserDefault) and the working graph (the autosave file) were two separate stores
that could diverge — and once an earlier build failed to load and autosaved a
fallback Default over the real graph, the divergence was permanent.

Fix the class of bug: the loaded rig's id now lives on ShoeGaze.currentRigID and
is written *inside* the autosave envelope alongside the graph (one atomic file).
RigStore.restore sets it from the envelope (nil for pre-envelope files or a
fallback seed); the sidebar highlight reads it directly. The separate
UserDefault key, restoreCurrentRig, and persistCurrentRigID are removed. When
the app falls back to seeding Default, no rig is highlighted — honest, and it
can never mislabel the graph again.

339 tests pass; both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 17:11:20 -07:00
josh bab4fdd087 Add in-app Help (macOS Help menu + iOS button)
New shared HelpView in LyrebirdShoeGazeUI: a sectioned guide covering setup &
starting the engine, choosing an input, boards & rigs, saving & autosave,
iCloud documents, and MIDI control. Text + SF Symbols for now; each topic
leaves a slot for a bundled screenshot to be added later.

- macOS: a Help menu ("ShoeGaze Help", ⌘?) opens the guide in a LyrebirdWindow.
- iOS/both: a ? button in the transport row opens it in a sheet.

Both app targets build; suite green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 16:50:42 -07:00
josh 9cb8788cc0 Add Plate, Room, and Spring reverb pedals
Wrap three Lyrebird 1.2.0 reverb algorithms as pedals, mirroring ReverbPedal
(run the generator pure-wet, let the base Pedal mix blend):
- Plate Reverb — PlateReverb.Audio (Dattorro plate), stereo folded to mono.
  Knobs: Decay, Tone, Damp, Mod.
- Room Reverb — GVerb.Audio (FDN room/hall), stereo folded to mono.
  Knobs: Size (m), Decay (T60 s), Damp, Tail.
- Spring Reverb — SpringReverb.Audio in mono (stereo:false, no fold).
  Knobs: Decay, Tension, Damp.

Each registered across the six touchpoints (type, registry, category .reverb,
palette order, enclosure colour) with a test suite (build+render, param
changes output, knob labels, preset round-trip, registry membership).

339 tests pass; both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 16:47:47 -07:00
josh 401682d266 Make the whole rig cell tappable, not just the label
Add .contentShape(Rectangle()) to the rig-row button label so the entire padded
cell selects the rig, instead of only the text glyphs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 14:27:26 -07:00
josh 4fef5aed7b Decode midiMap resiliently so a bad map can't drop the whole rig
Root cause of the "highlight right, wrong graph" restart: the autosave held a
midiMap written by an older binding schema (CCTarget was a struct before it
became an enum). Decoding threw, loadRig threw, RigStore.restore failed, and the
app fell back to seeding a single default board — so the graph showed Default
while the highlight (correctly) showed the loaded rig.

ShoeGazeState now decodes midiMap with try?, so an unreadable/incompatible map
drops just the (re-learnable) bindings while version + boards decode strictly.
The rig survives.

Test: a malformed midiMap decodes to nil without throwing. 324 green; both app
targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 14:10:00 -07:00
josh dee1c29744 Restore rig highlight by id, paired with autosave
The previous fix derived the highlight by full-state equality against library
entries, which broke as soon as the working rig was edited — e.g. after
learning a MIDI binding, the working midiMap no longer equalled the saved
entry, so nothing was highlighted on restart.

Revert to an id-based highlight (survives edits, since edits don't change which
saved rig the session derives from) and additionally persist the current-rig id
on every autosave, so the stored id can never drift from the autosaved graph —
which was the original cause of the highlight/graph mismatch.

Both app targets build; suite green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 14:03:22 -07:00
josh 48ac573489 Let one footswitch drive multiple toggles (scenes)
captureSwitch stole a Program Change from any prior action, so one footswitch
could only drive one toggle. applyProgram already fires every matching binding,
so this just drops the steal-by-program: one binding per action (re-learning an
action replaces it), and a single PC may drive MANY actions — a "scene" (e.g.
bypass two pedals, or solo a board and bypass another, from one press). Mirrors
the CC multi-target change.

Tests: one PC drives two actions and toggles both; re-learning an action
replaces its program. 323 green; both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 13:45:13 -07:00
josh e25b75a880 Fix CC crossfade steal + rig highlight/graph mismatch; review nits
Bug: assigning a CC to a second control invalidated the first. captureCC
stole any binding sharing the CC number, which directly defeats the crossfade
use case. Now one binding per CONTROL (re-learning a control replaces it), and
a single CC may drive MANY controls — map two board levels to one CC, invert
one, for a crossfade.

Bug: at launch the sidebar could highlight a different rig than the loaded
graph. restoreCurrentRig() highlighted a rig from a separate UserDefault that
drifts from the autosave working graph (restored independently). It now derives
the highlight from the actual working graph — matching the library entry whose
state equals it — so the highlight can never disagree with what's shown; an
edited/unsaved session highlights nothing.

Review nits: cache ccMappableControls in resolveCC (one array build per CC
instead of two); explicit type annotations on the mapping-sheet for-loops.

Test: one CC drives two controls with one inverted (crossfade). 322 green;
both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 13:42:16 -07:00
josh 4d8464282e Add per-binding CC invert toggle
Each CC binding gains an "Invert" toggle in the mapping sheet (shown once the
control is bound). Inverting swaps the sweep — CC 0 drives the control to its
max, 127 to its min — so a single expression pedal can crossfade two controls:
map both to the same CC and invert one.

The MIDICCBinding.inverted field and applyCC already honored inversion; this
adds isCCInverted / setCCInverted plus the sheet toggle, and the binding label
now notes "· inverted".

Test: an inverted binding reverses the mapped output. 321 green; both app
targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 13:09:18 -07:00
josh a7bbda4166 Add "All Boards On" as a mappable switch action
Maps the rig's "All" button (selectAllBoards — cancel any solo, bring every
board back up) to a Program Change. One-shot (no latch); rig-level, so no
board hint. Appears in the Switches section under Rig Bypass.

Test: PC fires selectAllBoards, clearing an active solo. 320 green; both app
targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 12:40:27 -07:00
josh 1ba622a611 Fix CC section: stop switch actions leaking in; add board-level target
The MIDI Mapping sheet's two sections both keyed their ForEach rows on the
enumeration offset (0,1,2…) and the Expression section mixed a bare header
Text with a ForEach. SwiftUI's List reused structurally identical row views
across the sections, so Program-Change switch rows (e.g. "Board 1 · Solo",
"Board 1 · Overdrive · Bypass") leaked into the Expression (CC) section and
their Learn button armed a Program Change instead of a Control Change.

- Rebuild both sections from precomputed row models with globally-unique,
  section-namespaced string ids and a single ForEach each; no bare headers.
- CC target is now an enum: `.pedalControl` (a knob/slider) or `.boardLevel`
  (the board fader). Board master level is now CC-assignable, shown as
  "<Board> · Level".
- CC rows are labelled "<Pedal> · <Control>" (e.g. "Overdrive · Drive").
- Stale-binding + steal-on-reassign now key off an address matcher on the
  target enum.

Tests updated for the enum target; added a board-level CC test. 319 green;
both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 12:25:59 -07:00
josh ae8f370fa8 Address review; make all pedal controls (incl. sliders) CC-mappable
Review fixes:
- Remove stale phase-plan references from MIDIController / MIDIMappingSheet
  doc-comments (describe current behavior instead).
- insertPedal: a board with no linear pedals but a trailing routing region
  now inserts at the head (before the region) instead of appending after it.
- Drop the unused MIDIController.retarget (the app recreates the controller
  against a fresh engine rather than re-pointing it).
- CC steal now matches controller AND channel, so per-channel CC bindings
  can coexist.

Feature (requested): CC mapping now covers every continuous pedal control,
not just rotary knobs. New PedalControl descriptor + Pedal.ccMappableControls
(knobs followed by effect sliders); the Expression sheet lists them grouped
per pedal with a header, so slider params (e.g. EQ bands) are assignable and
labelled clearly. Knob-first ordering keeps existing CC bindings stable.

Tests: +2 (CC drives a slider control; insert into a region-only board lands
before the region). 318 total green; both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 08:34:30 -07:00
josh 1893576718 Add MIDI foot-controller control; board/rig bypass; iOS fixes
Headline: MIDI control for a Behringer FCB1010 (four phases).
- MIDIController (Lyrebird MIDI client): connection indicator via source
  polling, background-queue->main-actor hop, MIDI Learn.
- Volume and Wah pedals (Wah reuses the SVF bandpass sweep, driven by
  pedal position instead of an envelope follower).
- CC -> any pedal knob (0-127 mapped across the knob range).
- Program Change -> pedal/board/rig toggles: software latch for booleans,
  exclusive radio for board solo. Positional addressing with display-name
  hints; stale/out-of-range bindings are skipped, not fired.
- Per-rig MIDIMap embedded in ShoeGazeState as an optional field (old rigs
  decode to nil; no preset version bump). Central MIDI Mapping sheet with
  Learn/Clear per control.

Also included (same working branch):
- Full board bypass and rig bypass (dry passthrough via cascaded
  crossfades in BoardOutputMaster), with UI toggles.
- Horizontal pedal picker grouped by category in filter order.
- Drag a palette pedal onto a chain card to insert before it
  (ShoeGaze.insertPedal); tap still appends.
- iOS: guard macOS-only .menuStyle(.borderlessButton) to silence the
  _UIReparentingView warning; iCloud-unavailable alert; keep the device
  awake while audio runs.

Tests: 24 added (Volume/Wah, MIDIMap Codable incl. legacy decode,
CC and PC controller behavior, insert/bypass API). Full suite green;
macOS and iOS app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 08:18:09 -07:00
josh ec6c97c065 iOS fix for menu display 2026-06-28 21:01:42 -07:00
josh 0b0befe02f update images and xcode. versions 2026-06-28 20:39:51 -07:00
81 changed files with 7496 additions and 145 deletions
@@ -163,7 +163,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 4;
CURRENT_PROJECT_VERSION = 6;
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 = 1.2.0;
MARKETING_VERSION = 1.4.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 = 4;
CURRENT_PROJECT_VERSION = 6;
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 = 1.2.0;
MARKETING_VERSION = 1.4.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
+35 -1
View File
@@ -55,12 +55,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private let shoeGaze: ShoeGaze
private let window: LyrebirdWindow
/// Foot-controller MIDI input. The macOS engine is never rebuilt, so this is created once and
/// started at launch.
private let midi: MIDIController
/// The rig library; constructed in `init`, resolved + loaded asynchronously after launch.
private let library: RigLibraryStore
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
private var recordMenuItem: NSMenuItem?
/// The Help window, created lazily on first open and reused thereafter.
private var helpWindow: LyrebirdWindow?
/// Default file name offered by the archive Export panel.
private static let defaultArchiveFileName: String = "ShoeGaze Library"
@@ -80,6 +87,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
self.coreDriver = coreDriver
self.engine = engine
self.shoeGaze = shoeGaze
self.midi = MIDIController(engine: engine, shoeGaze: shoeGaze)
self.window = LyrebirdWindow(
title: "ShoeGaze Builder — Lyrebird Pedalboard",
width: AppDelegate.windowWidth,
@@ -114,14 +122,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
installMainMenu()
midi.start()
midi.onMapChanged = { [weak self] in
guard let self: AppDelegate = self else { return }
RigStore.save(self.shoeGaze)
}
let session: ShoeGaze = shoeGaze
let driver: CoreAudioDriver = coreDriver
let rigLibrary: RigLibraryStore = library
let midiController: MIDIController = midi
window.open {
ShoeGazeBuilderView(
shoeGaze: session,
library: rigLibrary,
hardwareSampleRate: { driver.deviceSampleRate }
hardwareSampleRate: { driver.deviceSampleRate },
midi: midiController
)
}
anchorWindowLeft()
@@ -288,6 +303,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
key: "R" // ⇧⌘R
)
// Help menu — opens the in-app guide.
let helpMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(helpMenuItem)
let helpMenu: NSMenu = NSMenu(title: "Help")
helpMenuItem.submenu = helpMenu
addItem(to: helpMenu, title: "ShoeGaze Help", action: #selector(showHelpAction(_:)), key: "?")
NSApplication.shared.mainMenu = mainMenu
}
@@ -307,6 +329,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Menu actions
/// Opens (or re-opens) the Help window hosting the shared ``HelpView``.
@objc private func showHelpAction(_ sender: Any?) {
let helpWidth: CGFloat = 560
let helpHeight: CGFloat = 720
if helpWindow == nil {
helpWindow = LyrebirdWindow(title: "ShoeGaze Help", width: helpWidth, height: helpHeight)
}
helpWindow?.open {
HelpView()
}
}
@objc private func newRigAction(_ sender: Any?) {
// Forward to the builder view, which owns the current-rig state and naming prompt.
NotificationCenter.default.post(name: .shoeGazeNewRig, object: nil)
+1 -1
View File
@@ -13,7 +13,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.3.0</string>
<string>1.4.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSApplicationCategoryType</key>
@@ -157,8 +157,11 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 5;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
@@ -169,7 +172,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
MARKETING_VERSION = 1.3;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -184,8 +187,11 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 5;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
@@ -195,7 +201,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
MARKETING_VERSION = 1.3;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -31,7 +31,7 @@
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
+1 -1
View File
@@ -13,7 +13,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.3.0</string>
<string>1.4.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
@@ -28,7 +28,8 @@ struct ShoeGazeBuilderiOSApp: App {
shoeGaze: model.shoeGaze,
library: model.library,
hardwareSampleRate: { model.hardwareSampleRate },
onEnableLiveInput: { model.enableLiveInput() }
onEnableLiveInput: { model.enableLiveInput() },
midi: model.midi
)
.navigationTitle("ShoeGaze Builder")
.navigationBarTitleDisplayMode(.inline)
@@ -49,6 +49,10 @@ final class ShoeGazeBuilderiOSAppModel {
private var engine: SynthesisEngine
private var iosDriver: iOSAudioDriver
/// Foot-controller MIDI input. Owned here so it outlives the live-input engine rebuild; the
/// underlying Core MIDI client is engine-bound, so it is recreated against each new engine.
private(set) var midi: MIDIController
/// The shared rig library (iCloud-or-local). Independent of the engine, so it survives the
/// live-input engine rebuild.
private(set) var library: RigLibraryStore
@@ -83,6 +87,11 @@ final class ShoeGazeBuilderiOSAppModel {
// Construct the library instantly; it resolves iCloud + loads asynchronously via
// startLibrary() from the app's .task.
self.library = RigLibraryBootstrap.makeStore()
// Connect MIDI foot-controller input and begin listening for devices.
self.midi = MIDIController(engine: built.engine, shoeGaze: shoeGaze)
self.midi.start()
self.midi.onMapChanged = { [weak self] in self?.save() }
}
/// Persists the current rig. Call when the app moves to the background.
@@ -201,6 +210,13 @@ final class ShoeGazeBuilderiOSAppModel {
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
}
// The Core MIDI client is bound to the old engine — recreate it against the new one and
// point it at the rebuilt rig, preserving the "MIDI outlives the rebuild" contract.
midi.stop()
midi = MIDIController(engine: rebuilt.engine, shoeGaze: shoeGaze)
midi.start()
midi.onMapChanged = { [weak self] in self?.save() }
selectLiveInputAndPersist()
if wasRunning { try? engine.start() }
+3 -3
View File
@@ -1,5 +1,5 @@
{
"originHash" : "b8327204b102b429067129b94b6ba77dcfa78570af3b9d11cae4d7eb252e388c",
"originHash" : "6f168dc2e522f9d35bb2fafd7dab3cd399acd820084d324db174cf1ef0c6c4fa",
"pins" : [
{
"identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
"revision" : "8a2eb191a204a76735ba7eeac94e18f2e65f1b23",
"version" : "1.2.2"
}
},
{
+2 -1
View File
@@ -23,7 +23,7 @@ let package = Package(
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
],
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.0"),
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.2"),
],
targets: [
// The core target depends on LyrebirdUI as well as the synthesis core:
@@ -51,6 +51,7 @@ let package = Package(
name: "LyrebirdShoeGazeTests",
dependencies: [
"LyrebirdShoeGaze",
"LyrebirdShoeGazeUI",
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
+9 -3
View File
@@ -11,10 +11,14 @@ signal (no hardware needed) or on live guitar through an audio input.
## Features
- **32 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and
- **35 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and
texture — 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.
style) or **Blend** any subset, each with its own level and a click-free crossfade, plus a
rig-wide **output volume and mute** on top.
- **MIDI foot-controller support** — map footswitches (Program Change) to bypass/mute/solo
toggles, and expression pedals (Control Change) to any knob, board level, or the rig-wide
volume, with per-binding invert for crossfades. MIDI Learn, one binding per rig.
- **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or
stereo lanes, and merge back to mono.
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across
@@ -24,6 +28,8 @@ signal (no hardware needed) or on live guitar through an audio input.
- **Recording** — capture your output to timestamped files.
- **Test signal or live input** — a built-in arpeggiated test loop (shared across all boards so
they stay phase-locked) or a hardware input channel.
- **In-app Help** — setup, rigs/boards, saving, iCloud, and MIDI control, from the macOS Help
menu or an iOS help button.
- **SwiftUI views** — a complete stompbox UI (`LyrebirdShoeGazeUI`) or just the headless
framework (`LyrebirdShoeGaze`) to drive your own interface.
@@ -37,7 +43,7 @@ signal (no hardware needed) or on live guitar through an audio input.
| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Rotary, Ring Modulator |
| Pitch | Bass Octaver, Octave Splitter, Harmonizer |
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay |
| Reverb | Reverb, Shimmer Reverb |
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb |
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator |
Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format.
+37
View File
@@ -1,5 +1,42 @@
# Releases
## 1.4.0 — 2026-07-01
### MIDI foot-controller support
- **Program Change switches** — map a footswitch to Rig Bypass, Rig Mute, All Boards On, board
Solo/Audible/Bypass, or any pedal's Bypass. MIDI Learn captures the incoming program number;
one Program Change can drive **multiple actions at once** ("scenes").
- **Control Change (expression pedal) mapping** — bind a CC to any pedal knob/slider, a board's
master level, or the new rig-wide output volume. Per-binding **invert**, so one expression
pedal can crossfade two controls in opposite directions.
- Bindings are per-rig, travel with the saved rig file, and decode resiliently — an
incompatible/malformed MIDI map drops just the bindings (re-learnable) rather than the whole
rig.
- New **MIDI Mapping** sheet (from the transport row) lists every switch/expression target with
live Learn / Clear / Invert controls, plus a connected-device list.
### Rig-wide output volume + mute
- New **Volume** slider and **Mute** button in the board-mixer bar, alongside Solo / Blend / All
and Crossfade — applies after every board's output, independent of per-board levels.
- Mute is a hard output gate, distinct from the existing dry-signal Bypass. Both volume and mute
are MIDI-mappable (CC for volume, Program Change for mute) and click-free (lagged).
### New reverb pedals (catalog now 35)
- **Plate Reverb** — dense, bright metallic-plate character (Decay / Tone / Damp / Mod).
- **Room Reverb** — natural room/hall ambience (Size / Decay / Damp / Tail).
- **Spring Reverb** — classic amp-tank boing and drip (Decay / Tension / Damp).
### In-app Help
- New **Help** view covering setup & starting the engine, input sources, boards & rigs, saving &
autosave, iCloud documents, and MIDI control — reachable from the macOS **Help menu** and an
iOS help button.
### Fixes
- Fixed a rig-library bug where the sidebar's highlighted rig could disagree with the actually
loaded pedal graph after a restart — the current rig id and its saved state now live in one
atomic autosave file instead of two files that could drift apart.
- The whole rig-library sidebar row is now tappable, not just its text label.
## 1.3.0 — 2026-06-28
### Sharing — the `.shoegaze` document type
@@ -0,0 +1,33 @@
{
"originHash" : "91598bde27d299c8e3d95f9dc660396f52cf9b8e78f90ff2652c9d34d869f572",
"pins" : [
{
"identity" : "linenoise-swift",
"kind" : "remoteSourceControl",
"location" : "https://github.com/andybest/linenoise-swift",
"state" : {
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
"version" : "0.0.3"
}
},
{
"identity" : "lyrebird",
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "8a2eb191a204a76735ba7eeac94e18f2e65f1b23",
"version" : "1.2.2"
}
},
{
"identity" : "nimble",
"kind" : "remoteSourceControl",
"location" : "https://github.com/Quick/Nimble.git",
"state" : {
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
"version" : "7.3.4"
}
}
],
"version" : 3
}
@@ -28,6 +28,14 @@ final class BoardOutputMaster: SynthesizerBase {
/// Defaults to a short 20 ms so normal use is click-free; raise it for a slow crossfade.
@UIParam var crossfadeTime: Double = 0.02
/// Per-board full-bypass state. `0` = board engaged (processed output), `1` = bypassed
/// (dry input passes straight through, skipping every pedal). Smoothed by `bypassLagTime`.
@UIParam var boardBypass: Double = 0.0
/// Rig-wide full-bypass state, driven across every board at once. `0` = engaged,
/// `1` = bypassed (dry). Independent of `boardBypass`; either engaged routes to dry.
@UIParam var rigBypass: Double = 0.0
/// The live `UIParamNode` backing `masterGain`, exposed so the board (and its UI)
/// can bind a master-volume knob to this stage.
var gainNode: UIParamNode { $masterGain }
@@ -38,6 +46,26 @@ final class BoardOutputMaster: SynthesizerBase {
/// The live `UIParamNode` backing `crossfadeTime` (board crossfade seconds).
var crossfadeTimeNode: UIParamNode { $crossfadeTime }
/// The live `UIParamNode` backing `boardBypass` (per-board full bypass).
var boardBypassNode: UIParamNode { $boardBypass }
/// The live `UIParamNode` backing `rigBypass` (rig-wide full bypass).
var rigBypassNode: UIParamNode { $rigBypass }
/// Rig-wide output volume in [0, 1], applied to the final output. Driven across every board by
/// `ShoeGaze.setRigVolume(_:)`. Defaults to `1` (unity).
@UIParam var rigVolume: Double = 1.0
/// Rig-wide output mute — `0` = audible, `1` = silenced (a hard gate, not a dry bypass). Driven
/// across every board by `ShoeGaze.setRigMuted(_:)`. Defaults to `0`.
@UIParam var rigMute: Double = 0.0
/// The live `UIParamNode` backing `rigVolume` (rig-wide output volume).
var rigVolumeNode: UIParamNode { $rigVolume }
/// The live `UIParamNode` backing `rigMute` (rig-wide output mute).
var rigMuteNode: UIParamNode { $rigMute }
// MARK: - Routing
/// Left / mono board output bus index.
@@ -48,11 +76,23 @@ final class BoardOutputMaster: SynthesizerBase {
/// bypassing the mono `Pan2` spread.
private let boardOutputBusRightIndex: Int?
/// The board's dry head-bus index (the mono input feeding the first pedal). Read as the
/// bypass source so a bypassed board passes its untouched input straight through.
private let dryInputBusIndex: Int
// MARK: - Constants
/// Pan position for the board in the stereo field. Centre = 0.0. Used only for a mono board.
private let stereoPan: Double = 0.0
/// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed
/// transitions to prevent clicks. Matches the per-pedal bypass lag.
private let bypassLagTime: Double = 0.02
/// Remaps a `[0, 1]` bypass value to CrossFade's `[-1, +1]` equal-power pan.
private let bipolarSpan: Double = 2.0
private let bipolarOffset: Double = 1.0
// MARK: - Init
/// Creates a board output master.
@@ -61,9 +101,11 @@ final class BoardOutputMaster: SynthesizerBase {
/// - boardOutputBusIndex: Left / mono board output bus index.
/// - boardOutputBusRightIndex: Right board output bus index for a stereo (width-2) board,
/// or `nil` for a mono board (the signal is panned to centre instead).
init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil) {
/// - dryInputBusIndex: The board's head-bus index, read as the dry bypass source.
init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil, dryInputBusIndex: Int) {
self.boardOutputBusIndex = boardOutputBusIndex
self.boardOutputBusRightIndex = boardOutputBusRightIndex
self.dryInputBusIndex = dryInputBusIndex
super.init()
}
@@ -74,13 +116,24 @@ final class BoardOutputMaster: SynthesizerBase {
// seconds rather than clicking. The user master-gain knob is applied directly.
let smoothedSelect: Lag.Control = Lag.Control(input: $selectGain, time: $crossfadeTime)
// Rig-wide output volume × mute, shared across both channels (like `smoothedSelect`).
let rigOutputGain: any ValidGeneratorInput = rigOutputGainStage()
// The dry input tap — read once, used as the bypass source for both channels (the head
// bus is mono, so a bypassed stereo board passes the same dry signal to both sides).
let dry: In.Audio = input(bus: dryInputBusIndex)
let boardOutLeft: In.Audio = input(bus: boardOutputBusIndex)
let gainedLeft: any ValidGeneratorInput = (boardOutLeft * smoothedSelect) * $masterGain
let switchedLeft: any ValidGeneratorInput = applyBypass(wet: boardOutLeft, dry: dry)
let gainedLeft: any ValidGeneratorInput =
((switchedLeft * smoothedSelect) * $masterGain) * rigOutputGain
if let rightIndex: Int = boardOutputBusRightIndex {
// Stereo board: left tail → hardware 0, right tail → hardware 1, no pan spread.
let boardOutRight: In.Audio = input(bus: rightIndex)
let gainedRight: any ValidGeneratorInput = (boardOutRight * smoothedSelect) * $masterGain
let switchedRight: any ValidGeneratorInput = applyBypass(wet: boardOutRight, dry: dry)
let gainedRight: any ValidGeneratorInput =
((switchedRight * smoothedSelect) * $masterGain) * rigOutputGain
output(bus: 0, source: gainedLeft)
output(bus: 1, source: gainedRight)
} else {
@@ -88,4 +141,30 @@ final class BoardOutputMaster: SynthesizerBase {
output(bus: 0, source: Pan2(input: gainedLeft, pan: stereoPan))
}
}
/// Rig-wide output gain: the smoothed rig volume gated by the smoothed mute. Mute `0` → gain 1
/// (audible), mute `1` → gain 0 (silent). Both lagged to avoid clicks.
private func rigOutputGainStage() -> any ValidGeneratorInput {
let rigVol: Lag.Control = Lag.Control(input: $rigVolume, time: bypassLagTime)
let muteLagged: Lag.Control = Lag.Control(input: $rigMute, time: bypassLagTime)
// (mute − 1) × −1 ⇒ 0→1, 1→0, using only generator−scalar and generator×scalar.
let muteGain: any ValidGeneratorInput = (muteLagged - 1.0) * -1.0
return rigVol * muteGain
}
/// Routes `wet` to `dry` when either the per-board or rig-wide bypass is engaged. Two cascaded
/// equal-power crossfades (each lagged to prevent clicks) give an independent "OR" of the two
/// bypass sources: rig bypass overrides even a board that is otherwise engaged.
private func applyBypass(
wet: any ValidGeneratorInput,
dry: any ValidGeneratorInput
) -> any ValidGeneratorInput {
let boardLagged: Lag.Control = Lag.Control(input: $boardBypass, time: bypassLagTime)
let boardPan: any ValidGeneratorInput = (boardLagged * bipolarSpan) - bipolarOffset
let afterBoard: CrossFade.Audio = CrossFade.Audio(inA: wet, inB: dry, pan: boardPan)
let rigLagged: Lag.Control = Lag.Control(input: $rigBypass, time: bypassLagTime)
let rigPan: any ValidGeneratorInput = (rigLagged * bipolarSpan) - bipolarOffset
return CrossFade.Audio(inA: afterBoard, inB: dry, pan: rigPan)
}
}
@@ -0,0 +1,153 @@
// LegacyMIDIMap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Decoder for the **pre-UUID** `MIDIMap` format, which addressed pedals and boards by chain
/// position (`boardIndex` / `pedalIndex`) rather than by stable id.
///
/// Used only on load: `ShoeGazeState.init(from:)` tries the current id-based `MIDIMap` first and,
/// if that fails, decodes this legacy shape and calls ``migrated(boards:)`` to convert each
/// positional binding to the id of the pedal/board now sitting at that position. Because the saved
/// positions are stable, this reconstructs correct id-bindings on every load — even though the ids
/// themselves are freshly assigned to a legacy rig each time it is decoded.
///
/// Bindings whose indices fall outside the loaded rig are dropped.
struct LegacyMIDIMap: Codable {
var switches: [LegacySwitchBinding]
var ccs: [LegacyCCBinding]
enum LegacyAction: Codable {
case rigBypass
case rigMute
case allBoards
case boardSolo(boardIndex: Int)
case boardAudible(boardIndex: Int)
case boardBypass(boardIndex: Int)
case pedalBypass(boardIndex: Int, pedalIndex: Int)
case pedalAction(boardIndex: Int, pedalIndex: Int, kind: MIDIMap.PedalActionKind)
case tunerToggle
case tapTempo
}
enum LegacyCCTarget: Codable {
case pedalControl(
boardIndex: Int,
pedalIndex: Int,
controlIndex: Int,
pedalNameHint: String?,
controlLabelHint: String?
)
case boardLevel(boardIndex: Int, boardLabelHint: String?)
case rigVolume
}
struct LegacySwitchBinding: Codable {
var program: UInt8
var channel: UInt8?
var action: LegacyAction
var displayNameHint: String?
}
struct LegacyCCBinding: Codable {
var controller: UInt8
var channel: UInt8?
var target: LegacyCCTarget
var inverted: Bool
}
// MARK: - Migration
/// Converts this positional map to the current id-based ``MIDIMap`` using the ids of the pedals
/// and boards in `boards` (whose ids were freshly assigned when the rig was decoded). Bindings
/// addressing an out-of-range board/pedal are dropped.
func migrated(boards: [BoardState]) -> MIDIMap {
func boardID(_ index: Int) -> UUID? {
guard index >= 0, index < boards.count else { return nil }
return boards[index].id
}
func pedalID(_ boardIndex: Int, _ pedalIndex: Int) -> UUID? {
guard boardIndex >= 0, boardIndex < boards.count else { return nil }
let pedals: [PedalState] = boards[boardIndex].pedals
guard pedalIndex >= 0, pedalIndex < pedals.count else { return nil }
return pedals[pedalIndex].id
}
let migratedSwitches: [MIDIMap.SwitchBinding] = switches.compactMap { binding in
guard let action: MIDIMap.Action = migrate(binding.action, boardID: boardID, pedalID: pedalID) else {
return nil
}
return MIDIMap.SwitchBinding(
program: binding.program,
channel: binding.channel,
action: action,
displayNameHint: binding.displayNameHint
)
}
let migratedCCs: [MIDIMap.CCBinding] = ccs.compactMap { binding in
guard let target: MIDIMap.CCTarget = migrate(binding.target, boardID: boardID, pedalID: pedalID) else {
return nil
}
return MIDIMap.CCBinding(
controller: binding.controller,
channel: binding.channel,
target: target,
inverted: binding.inverted
)
}
return MIDIMap(switches: migratedSwitches, ccs: migratedCCs)
}
private func migrate(
_ action: LegacyAction,
boardID: (Int) -> UUID?,
pedalID: (Int, Int) -> UUID?
) -> MIDIMap.Action? {
switch action {
case .rigBypass: return .rigBypass
case .rigMute: return .rigMute
case .allBoards: return .allBoards
case .tunerToggle: return .tunerToggle
case .tapTempo: return .tapTempo
case .boardSolo(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardSolo(boardID: id)
case .boardAudible(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardAudible(boardID: id)
case .boardBypass(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardBypass(boardID: id)
case .pedalBypass(let b, let p):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalBypass(pedalID: id)
case .pedalAction(let b, let p, let kind):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalAction(pedalID: id, kind: kind)
}
}
private func migrate(
_ target: LegacyCCTarget,
boardID: (Int) -> UUID?,
pedalID: (Int, Int) -> UUID?
) -> MIDIMap.CCTarget? {
switch target {
case .rigVolume:
return .rigVolume
case .pedalControl(let b, let p, let controlIndex, let nameHint, let labelHint):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalControl(pedalID: id, controlIndex: controlIndex,
pedalNameHint: nameHint, controlLabelHint: labelHint)
case .boardLevel(let b, let labelHint):
guard let id: UUID = boardID(b) else { return nil }
return .boardLevel(boardID: id, boardLabelHint: labelHint)
}
}
}
@@ -0,0 +1,465 @@
// MIDIController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
/// Owns the Core MIDI connection for a ShoeGaze session and routes incoming messages to the rig.
///
/// Constructed once by the app (it is recreated against a fresh engine when the engine is rebuilt),
/// and started with ``start()``. Handlers fire on Lyrebird's background MIDI queue; this controller
/// hops to the main actor before touching any `@MainActor` rig state.
///
/// It establishes the Core MIDI connection, publishes device-connection state for the UI indicator,
/// and routes incoming messages to the rig: Control Change drives bound pedal controls, and Program
/// Change toggles bound pedal / board / rig actions. MIDI Learn arms a control so the next matching
/// message binds to it.
@MainActor
@Observable
public final class MIDIController {
// MARK: - Connection state
/// `true` when at least one MIDI input source is currently connected.
public private(set) var isConnected: Bool = false
/// Names of the connected MIDI input sources (e.g. `"FCB1010"`), for the indicator's tooltip.
public private(set) var connectedDeviceNames: [String] = []
// MARK: - Learn
/// A control armed for MIDI Learn: the next matching message captures a binding to it.
public enum LearnTarget: Equatable, Sendable {
/// A continuous control awaiting a Control Change (address-only; hints are `nil`).
case cc(MIDIMap.CCTarget)
/// A toggle action awaiting a Program Change.
case action(MIDIMap.Action)
}
/// The control currently armed for Learn, or `nil` when not learning. Observable so the UI can
/// show a "Listening…" state and a global learn banner.
public private(set) var learnTarget: LearnTarget?
/// Invoked on the main actor after the map changes (a binding learned or cleared), so the host
/// can persist the rig. Optional — when unset, the map still persists on the next rig autosave.
public var onMapChanged: (() -> Void)?
// MARK: - Private
private let midi: MIDI
private var handlerToken: MIDIHandlerToken?
/// The rig this controller drives. Weak + retargetable: the app owns both, and an iOS engine
/// rebuild swaps `ShoeGaze` out from under us.
private weak var shoeGaze: ShoeGaze?
/// Main-queue timer that re-reads `midi.sources` to publish connection state. Polling is used
/// because Lyrebird 1.2.0's `MIDI` refreshes endpoints internally but exposes no change callback.
private var detectionTimer: DispatchSourceTimer?
/// Poll interval for connection state, in seconds. A foot controller is plugged in before a set,
/// so ~1 s latency is imperceptible.
private let detectionInterval: Double = 1.0
/// Crossfade time (seconds) applied to board solo/audible changes triggered by a footswitch.
private let boardActionCrossfade: Double = 0.05
// MARK: - Init
/// Creates a MIDI controller bound to an engine.
///
/// - Parameters:
/// - engine: The engine the underlying `MIDI` client attaches to. On iOS this is rebuilt when
/// live input is enabled; recreate the controller against the new engine in that case.
/// - shoeGaze: The rig to drive. May be set later via ``retarget(_:)``.
/// - clientName: Core MIDI client name. Defaults to `"ShoeGaze"`.
public init(
engine: SynthesisEngine,
shoeGaze: ShoeGaze? = nil,
clientName: String = "ShoeGaze"
) {
self.midi = MIDI(engine: engine, clientName: clientName)
self.shoeGaze = shoeGaze
}
// MARK: - Lifecycle
/// Starts the MIDI client, installs the message handler, and begins polling for devices.
/// Safe to call once; a failed `MIDI.start()` is logged and leaves the controller inert.
public func start() {
do {
try midi.start()
} catch {
print("[MIDIController] MIDI start failed: \(error)")
}
installHandler()
refreshDevices()
startDetectionTimer()
}
/// Removes the handler, stops polling, and tears down the MIDI client.
public func stop() {
stopDetectionTimer()
if let token: MIDIHandlerToken = handlerToken {
midi.removeHandler(token)
handlerToken = nil
}
midi.stop()
}
// MARK: - Message handling
private func installHandler() {
handlerToken = midi.addHandler(name: "shoegaze.midi") { [weak self] message, _ in
// Handlers fire on the background `lyrebird.midi` queue. Hop to the main actor (FIFO on
// the main queue) before touching any `@MainActor` rig state.
DispatchQueue.main.async {
MainActor.assumeIsolated {
self?.handle(message)
}
}
}
}
/// Routes one incoming message to the rig: captures a binding when armed for Learn, otherwise
/// applies any matching binding. Control Change drives bound controls; Program Change toggles
/// bound actions.
private func handle(_ message: MIDIMessage) {
switch message {
case .controlChange(let channel, let controller, let value):
if case .cc(let target) = learnTarget {
captureCC(controller: controller, channel: channel, target: target)
} else {
applyCC(controller: controller, channel: channel, value: value)
}
case .programChange(let channel, let program):
if case .action(let action) = learnTarget {
captureSwitch(program: program, channel: channel, action: action)
} else {
applyProgram(program: program, channel: channel)
}
default:
break
}
}
#if DEBUG
/// Test hook: routes a message synchronously, bypassing the background-queue hop. The queue hop
/// is exercised only in a live session; tests drive `handle` directly on the main actor.
func ingestForTesting(_ message: MIDIMessage) {
handle(message)
}
#endif
// MARK: - Learn API
/// Master-level range for a board fader, mirroring the UI slider.
private let boardLevelRange: ClosedRange<Double> = 0.0 ... 1.0
/// Arms MIDI Learn for a continuous control: the next incoming Control Change binds to it. Pass
/// an address-only target (hints `nil`); hints are captured from the live rig at bind time.
public func armCCLearn(_ target: MIDIMap.CCTarget) {
learnTarget = .cc(target)
}
/// Cancels any in-progress Learn.
public func cancelLearn() {
learnTarget = nil
}
/// The CC binding currently assigned to a control, or `nil` if unbound.
public func ccBinding(for target: MIDIMap.CCTarget) -> MIDIMap.CCBinding? {
shoeGaze?.midiMap?.ccs.first { $0.target.addresses(target) }
}
/// Whether the CC binding on a control is inverted (CC 0 → control max), or `false` if unbound.
public func isCCInverted(for target: MIDIMap.CCTarget) -> Bool {
ccBinding(for: target)?.inverted ?? false
}
/// Sets the invert flag on the CC binding assigned to a control. Inverting swaps the sweep so a
/// single expression pedal can crossfade — e.g. fade one control down as it moves, another up.
public func setCCInverted(for target: MIDIMap.CCTarget, _ inverted: Bool) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap,
let index: Int = map.ccs.firstIndex(where: { $0.target.addresses(target) }),
map.ccs[index].inverted != inverted else { return }
map.ccs[index].inverted = inverted
shoeGaze.midiMap = map
onMapChanged?()
}
/// Removes any CC binding assigned to a control.
public func clearCCBinding(for target: MIDIMap.CCTarget) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
let before: Int = map.ccs.count
map.ccs.removeAll { $0.target.addresses(target) }
guard map.ccs.count != before else { return }
shoeGaze.midiMap = map
onMapChanged?()
}
// MARK: - CC handling
/// Captures a learned CC binding for the armed control and clears the Learn state.
private func captureCC(controller: UInt8, channel: UInt8, target: MIDIMap.CCTarget) {
learnTarget = nil
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
// `rigVolume` is applied via a setter (it has no single node) and is always valid, so it
// needs no resolve; pedal/board targets resolve to re-stamp their display-name hints.
let hinted: MIDIMap.CCTarget
if case .rigVolume = target {
hinted = .rigVolume
} else {
guard let resolved: ResolvedCC = resolveCC(target) else { return }
hinted = resolved.hinted
}
let binding: MIDIMap.CCBinding = MIDIMap.CCBinding(
controller: controller,
channel: channel,
target: hinted
)
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
// One binding per control — re-learning a control replaces its binding. A single CC may
// drive MULTIPLE controls on purpose (e.g. map one expression pedal to two board levels and
// invert one for a crossfade), so we deliberately do NOT steal by controller number.
map.ccs.removeAll { $0.target.addresses(hinted) }
map.ccs.append(binding)
shoeGaze.midiMap = map
onMapChanged?()
}
/// Applies an incoming CC to the control it is bound to, if any (channel-filtered).
private func applyCC(controller: UInt8, channel: UInt8, value: UInt8) {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return }
for binding: MIDIMap.CCBinding in map.ccs where binding.controller == controller {
if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue }
let ccMax: Double = 127.0
var norm: Double = Double(value) / ccMax
if binding.inverted { norm = 1.0 - norm }
if case .rigVolume = binding.target {
shoeGaze.setRigVolume(norm) // rig volume spans [0, 1] directly
continue
}
guard let resolved: ResolvedCC = resolveCC(binding.target) else { continue }
let mapped: Double = resolved.range.lowerBound
+ norm * (resolved.range.upperBound - resolved.range.lowerBound)
resolved.node.update(mapped)
}
}
/// A resolved CC target: the live node + range to drive, plus the target re-stamped with the
/// current display-name hints (for storing at capture time).
private struct ResolvedCC {
let node: UIParamNode
let range: ClosedRange<Double>
let hinted: MIDIMap.CCTarget
}
/// Resolves a CC target to its live node + range, skipping it (returns `nil`) when the positional
/// address is out of range or a captured display-name hint no longer matches (stale binding).
private func resolveCC(_ target: MIDIMap.CCTarget) -> ResolvedCC? {
switch target {
case let .pedalControl(pedalID, controlIndex, _, _):
guard let pedal: Pedal = pedal(id: pedalID) else { return nil }
let controls: [PedalControl] = pedal.ccMappableControls
guard controlIndex >= 0, controlIndex < controls.count else { return nil }
let control: PedalControl = controls[controlIndex]
let hinted: MIDIMap.CCTarget = .pedalControl(
pedalID: pedalID,
controlIndex: controlIndex,
pedalNameHint: pedal.displayName,
controlLabelHint: control.label
)
return ResolvedCC(node: control.node, range: control.range, hinted: hinted)
case let .boardLevel(boardID, _):
guard let board: PedalBoard = board(id: boardID),
let node: UIParamNode = board.masterGainNode else { return nil }
let hinted: MIDIMap.CCTarget = .boardLevel(boardID: boardID, boardLabelHint: board.label)
return ResolvedCC(node: node, range: boardLevelRange, hinted: hinted)
case .rigVolume:
// Applied via `ShoeGaze.setRigVolume` (fans out to every board), not a single node.
return nil
}
}
// MARK: - Switch (Program Change) learn + apply
/// Arms MIDI Learn for a toggle action: the next incoming Program Change binds to it.
public func armSwitchLearn(_ action: MIDIMap.Action) {
learnTarget = .action(action)
}
/// The switch binding currently assigned to an action, or `nil` if unbound.
public func switchBinding(for action: MIDIMap.Action) -> MIDIMap.SwitchBinding? {
shoeGaze?.midiMap?.switches.first { $0.action == action }
}
/// Removes any switch binding assigned to an action.
public func clearSwitchBinding(for action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
let before: Int = map.switches.count
map.switches.removeAll { $0.action == action }
guard map.switches.count != before else { return }
shoeGaze.midiMap = map
onMapChanged?()
}
/// Captures a learned switch binding for the armed action and clears the Learn state.
private func captureSwitch(program: UInt8, channel: UInt8, action: MIDIMap.Action) {
learnTarget = nil
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
let binding: MIDIMap.SwitchBinding = MIDIMap.SwitchBinding(
program: program,
channel: channel,
action: action,
displayNameHint: hint(for: action)
)
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
// One binding per action — re-learning an action replaces its binding. A single footswitch
// (program) may drive MULTIPLE actions on purpose (a "scene": e.g. bypass two pedals, or
// solo a board and bypass another, from one press), so we do NOT steal by program number.
map.switches.removeAll { $0.action == action }
map.switches.append(binding)
shoeGaze.midiMap = map
onMapChanged?()
}
/// Performs every action bound to an incoming Program Change (channel-filtered).
private func applyProgram(program: UInt8, channel: UInt8) {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return }
for binding: MIDIMap.SwitchBinding in map.switches where binding.program == program {
if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue }
perform(binding.action)
}
}
/// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch;
/// `boardSolo` is exclusive (radio). Pedals/boards resolve by UUID, so a binding whose target no
/// longer exists (removed pedal/board) simply no-ops.
private func perform(_ action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
switch action {
case .rigBypass:
shoeGaze.toggleRigBypassed()
case .rigMute:
shoeGaze.toggleRigMuted()
case .allBoards:
// One-shot: cancel any solo and bring every board back up.
shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade)
case .boardSolo(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade)
case .boardAudible(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.setBoard(board, audible: !shoeGaze.isBoardAudible(board),
crossfadeSeconds: boardActionCrossfade)
case .boardBypass(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board))
case .pedalBypass(let pedalID):
guard let pedal: Pedal = pedal(id: pedalID) else { return }
let engagedThreshold: Double = 0.5
let node: UIParamNode = pedal.$bypass
node.update(node.value < engagedThreshold ? 1.0 : 0.0)
case .pedalAction(let pedalID, let kind):
guard let pedal: Pedal = pedal(id: pedalID) else { return }
performPedalAction(kind, on: pedal)
case .tunerToggle:
shoeGaze.toggleTunerEngaged()
case .tapTempo:
shoeGaze.tapTempo()
}
}
/// Dispatches a pedal-specific momentary action. New `PedalActionKind` cases add a
/// branch here once the pedal type they target exists.
private func performPedalAction(_ kind: MIDIMap.PedalActionKind, on pedal: Pedal) {
let toggleThreshold: Double = 0.5
switch kind {
case .looperRecordStop:
// The smart Loop footswitch drives record / set-end / overdub / play by state.
(pedal as? LooperPedal)?.pressLoop()
case .looperOverdubToggle:
// Overdub is toggled by the same Loop press once a loop is playing.
(pedal as? LooperPedal)?.pressLoop()
case .looperLoopToggle:
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
let node: UIParamNode = looper.$loopOn
node.update(node.value < toggleThreshold ? 1.0 : 0.0)
case .looperReset:
(pedal as? LooperPedal)?.resetLoop()
case .looperStop:
(pedal as? LooperPedal)?.stopPlayback()
case .looperCueStop:
(pedal as? LooperPedal)?.toggleStopAtLoopEnd()
case .looperReverse:
(pedal as? LooperPedal)?.toggleReverse()
case .looperSyncToggle:
(pedal as? LooperPedal)?.cycleSyncMode()
case .looperTrack(let index):
(pedal as? LooperPedal)?.tapTrack(index)
}
}
/// A display-name hint for an action, captured at learn time for the mapping-sheet UI label.
/// Not used for resolution (bindings resolve by UUID) — purely a human-readable snapshot.
private func hint(for action: MIDIMap.Action) -> String? {
switch action {
case .rigBypass, .rigMute, .allBoards:
return nil
case .boardSolo(let boardID), .boardAudible(let boardID), .boardBypass(let boardID):
return board(id: boardID)?.label
case .pedalBypass(let pedalID), .pedalAction(let pedalID, _):
return pedal(id: pedalID)?.displayName
case .tunerToggle, .tapTempo:
return nil
}
}
/// Resolves a board by its stable id, or `nil` if no board in the rig has that id.
private func board(id: UUID) -> PedalBoard? {
shoeGaze?.boards.first { $0.id == id }
}
/// Resolves a pedal by its stable id across all boards' linear pedal chains, or `nil` if no
/// pedal in the rig has that id.
private func pedal(id: UUID) -> Pedal? {
guard let shoeGaze: ShoeGaze = shoeGaze else { return nil }
for board: PedalBoard in shoeGaze.boards {
if let match: Pedal = board.pedals.first(where: { $0.id == id }) { return match }
}
return nil
}
// MARK: - Device detection
private func refreshDevices() {
let names: [String] = midi.sources.map { $0.name }
connectedDeviceNames = names
isConnected = !names.isEmpty
}
private func startDetectionTimer() {
let timer: DispatchSourceTimer = DispatchSource.makeTimerSource(queue: .main)
timer.schedule(deadline: .now() + detectionInterval, repeating: detectionInterval)
timer.setEventHandler { [weak self] in
MainActor.assumeIsolated {
self?.refreshDevices()
}
}
timer.resume()
detectionTimer = timer
}
private func stopDetectionTimer() {
detectionTimer?.cancel()
detectionTimer = nil
}
}
+205
View File
@@ -0,0 +1,205 @@
// MIDIMap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A per-rig map of MIDI foot-controller bindings — which Program Change toggles which control, and
/// which Control Change drives which pedal knob.
///
/// Stored inside the rig (embedded in `ShoeGazeState`) so it travels with a saved rig. Pedals and
/// boards are addressed by **stable UUID** (`Pedal.id` / `PedalBoard.id`, persisted in
/// `PedalState`/`BoardState`), so a binding follows its pedal/board through insert, remove, move,
/// and reorder edits with no reindexing — the id survives the capture → rebuild round-trip. A
/// binding whose target no longer exists simply stops resolving (inert). The `*Hint` fields carry
/// the display name at learn time, for UI labels only (not resolution). Control-within-pedal is
/// still indexed into `Pedal.ccMappableControls`, which is stable for a given pedal type.
public struct MIDIMap: Codable, Equatable, Sendable {
/// Program-Change → action bindings (footswitch toggles). Populated in the switch phase.
public var switches: [SwitchBinding]
/// Control-Change → pedal-knob bindings (expression pedals).
public var ccs: [CCBinding]
/// An empty map (no bindings).
public static let empty: MIDIMap = MIDIMap()
/// Creates a MIDI map.
///
/// - Parameters:
/// - switches: Program-Change bindings. Defaults to empty.
/// - ccs: Control-Change bindings. Defaults to empty.
public init(
switches: [SwitchBinding] = [],
ccs: [CCBinding] = []
) {
self.switches = switches
self.ccs = ccs
}
// MARK: - Action
/// A toggle-style control a footswitch (Program Change) can drive. Program Change is momentary,
/// so boolean actions latch in software; `boardSolo` is exclusive (radio).
public enum Action: Codable, Equatable, Sendable {
case rigBypass
/// Mutes/unmutes the rig output (a hard silence, not a bypass).
case rigMute
/// Cancels any solo and makes every board audible again (the "All" button).
case allBoards
case boardSolo(boardID: UUID)
case boardAudible(boardID: UUID)
case boardBypass(boardID: UUID)
case pedalBypass(pedalID: UUID)
/// A pedal-specific momentary action beyond generic bypass (e.g. a looper's
/// record/stop or reset footswitch). `kind` is opaque to `MIDIMap` — `MIDIController`
/// resolves the target pedal (by id) and dispatches on `kind` itself.
case pedalAction(pedalID: UUID, kind: PedalActionKind)
/// Toggles the rig-level tuner on/off.
case tunerToggle
/// Registers one tap-tempo press (see `ShoeGaze.tapTempo()`).
case tapTempo
}
/// A pedal-specific momentary action addressable by ``Action/pedalAction(pedalID:kind:)``.
/// New pedals with more than a simple bypass toggle add cases here.
public enum PedalActionKind: Codable, Equatable, Sendable {
/// Looper: presses the smart Loop footswitch (record → set end → overdub → play by
/// state) — same as ``looperOverdubToggle``; both dispatch to `LooperPedal.pressLoop()`.
// TODO: collapse looperRecordStop / looperOverdubToggle into one case (both call pressLoop).
case looperRecordStop
/// Looper: presses the smart Loop footswitch (toggles overdub once a loop is playing).
case looperOverdubToggle
/// Looper: flips `loopOn` (loop mute) between `0` and `1`.
case looperLoopToggle
/// Looper: reset — clears all tracks and returns to the clear state.
case looperReset
/// Looper: immediately stops playback (`LooperPedal.stopPlayback()`).
case looperStop
/// Looper: arms / cancels a stop at the loop end (`LooperPedal.toggleStopAtLoopEnd()`).
case looperCueStop
/// Looper: flips playback direction (`LooperPedal.toggleReverse()`).
case looperReverse
/// Looper: cycles the Sync/Free transport mode (`LooperPedal.cycleSyncMode()`).
case looperSyncToggle
/// Looper: taps track `index` (0 = A) — selects it, or mutes it if already selected and
/// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots.
case looperTrack(index: Int)
}
// MARK: - Switch binding
/// A Program-Change number bound to a toggle ``Action``.
public struct SwitchBinding: Codable, Equatable, Sendable {
/// The Program Change number (0–127) that triggers the action.
public var program: UInt8
/// The MIDI channel (0–15), or `nil` to match any channel (omni).
public var channel: UInt8?
/// The control to toggle.
public var action: Action
/// The resolved control's display name at learn time, for stale-binding detection.
public var displayNameHint: String?
/// Creates a switch binding.
///
/// - Parameters:
/// - program: Program Change number (0–127).
/// - channel: MIDI channel (0–15), or `nil` for omni. Defaults to `nil`.
/// - action: The toggle action to perform.
/// - displayNameHint: Resolved control name at learn time. Defaults to `nil`.
public init(
program: UInt8,
channel: UInt8? = nil,
action: Action,
displayNameHint: String? = nil
) {
self.program = program
self.channel = channel
self.action = action
self.displayNameHint = displayNameHint
}
}
// MARK: - CC target
/// A continuous control an expression pedal can drive — either a specific pedal control (a knob
/// or slider, addressed by index into the pedal's ``Pedal/ccMappableControls``) or a board's
/// master level. The `*Hint` payloads capture the resolved display name at learn time so a
/// binding that no longer matches (chain edited) can be detected and skipped.
public enum CCTarget: Codable, Equatable, Sendable {
/// A knob or slider on a pedal, indexed into `pedal.ccMappableControls`.
case pedalControl(
pedalID: UUID,
controlIndex: Int,
pedalNameHint: String?,
controlLabelHint: String?
)
/// A board's master output level (the board fader).
case boardLevel(boardID: UUID, boardLabelHint: String?)
/// The rig-wide output volume (applies to the whole rig).
case rigVolume
/// Whether two targets address the same control, ignoring the display-name hints (used to
/// find and replace a binding regardless of the name captured at learn time).
public func addresses(_ other: CCTarget) -> Bool {
switch (self, other) {
case let (.pedalControl(p1, c1, _, _), .pedalControl(p2, c2, _, _)):
return p1 == p2 && c1 == c2
case let (.boardLevel(b1, _), .boardLevel(b2, _)):
return b1 == b2
case (.rigVolume, .rigVolume):
return true
default:
return false
}
}
}
// MARK: - CC binding
/// A Control-Change number bound to a pedal knob. The incoming value (0–127) is mapped across
/// the knob's own range; `inverted` swaps heel/toe for reversed expression pedals.
public struct CCBinding: Codable, Equatable, Sendable {
/// The Control Change number (0–127).
public var controller: UInt8
/// The MIDI channel (0–15), or `nil` to match any channel (omni).
public var channel: UInt8?
/// The pedal knob this CC drives.
public var target: CCTarget
/// When `true`, CC 0 maps to the knob's maximum and 127 to its minimum.
public var inverted: Bool
/// Creates a CC binding.
///
/// - Parameters:
/// - controller: Control Change number (0–127).
/// - channel: MIDI channel (0–15), or `nil` for omni. Defaults to `nil`.
/// - target: The pedal knob to drive.
/// - inverted: Reverse the sweep direction. Defaults to `false`.
public init(
controller: UInt8,
channel: UInt8? = nil,
target: CCTarget,
inverted: Bool = false
) {
self.controller = controller
self.channel = channel
self.target = target
self.inverted = inverted
}
}
}
+79
View File
@@ -4,6 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
@@ -59,8 +60,27 @@ open class Pedal: SynthesizerBase {
/// safe 48 kHz fallback.
public var sampleRate: Double = 48000.0
// MARK: - Tempo / engine (injected)
/// Shared tempo clock, injected by `PedalBoard.add(_:)` for tempo-aware pedals (the
/// looper's beat-quantized transport). `nil` for pedals added to a board that was
/// created without a clock (e.g. a bare parallel sub-board). Weak: the clock is owned
/// by `ShoeGaze` and outlives every pedal.
public internal(set) weak var clock: LyrebirdClock?
/// The engine that owns this pedal's nodes, injected by `PedalBoard.add(_:)`. Needed by
/// tempo-aware pedals to start a `LyrebirdRoutine` that waits on beat boundaries. Weak:
/// the engine owns the node tree, not the reverse.
public internal(set) weak var hostEngine: SynthesisEngine?
// MARK: - Identity / routing
/// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI
/// bindings to address the pedal by id rather than by chain position. Defaults to a fresh
/// `UUID` for a newly-created pedal; a rebuild from a saved rig restores the saved id
/// (`board.add(_:)` / preset apply sets it), so a pedal keeps its identity across edits.
public internal(set) var id: UUID = UUID()
/// Human-readable name for the pedal (e.g. "Overdrive", "Delay").
public let displayName: String
@@ -87,6 +107,31 @@ open class Pedal: SynthesizerBase {
/// Override in a widener or stereo-native subclass.
open var channelKind: PedalChannelKind { .mono }
/// Whether the UI shows the common wet/dry `Mix` control for this pedal. Defaults to `true`.
/// A pedal that manages its own dry/wet balance internally (e.g. the looper, where the clean
/// signal always passes through) overrides this to `false` so the confusing Mix knob is hidden
/// and `mix` stays at its fully-wet default.
open var showsMixControl: Bool { true }
/// Called on the main thread when the audio engine is stopped by the user (via
/// `ShoeGaze.stopEngine()`), not during a transient stop-around-rebuild. Stateful pedals
/// (e.g. the looper) override this to return to a clean state. Default: no-op.
open func engineDidStop() {}
/// Called on the main thread just before the rig is torn down (rig load / clear / input-source
/// change), while the pedal is still live. Stateful pedals override this to stop any background
/// work and return to a clean state before their instance is discarded. Default: no-op.
///
/// - Important: Fired from `ShoeGaze.teardown()`, which — like all node-removal paths — must
/// run with the engine already stopped. An override that clears buffers or stops RT-adjacent
/// work relies on that precondition; do not call `teardown()` with the engine running.
open func rigWillTeardown() {}
/// Number of standard enclosure widths this pedal's card occupies in the UI. Defaults
/// to `1`. A control-dense pedal (e.g. the looper) overrides to `2` for a wider card.
/// The UI multiplies its base enclosure width by this factor; `1` is the normal stompbox.
open var widthUnits: Int { 1 }
/// `true` when the board has placed this pedal in a stereo (width-2) region.
public var isStereo: Bool { outputBusRight != nil }
@@ -177,6 +222,24 @@ open class Pedal: SynthesizerBase {
[]
}
/// Effect-specific transport controls, rendered as a row directly below the knobs — above
/// ``effectButtons``. Use for the persistent state toggles and transport stops that read as
/// a group distinct from the momentary "do it now" actions (e.g. a looper's Loop / Stop /
/// Cue Stop / Reverse). Defaults to empty; a pedal with none simply skips the row.
open var effectTransportButtons: [PedalButton] {
[]
}
/// Effect-specific action buttons for this pedal, rendered as a row of stomp-style
/// buttons beneath the transport row.
///
/// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset")
/// that need a non-RT side effect beyond writing a single parameter value — see
/// ``PedalButton``. Defaults to empty.
open var effectButtons: [PedalButton] {
[]
}
/// All knobs a generic UI should render for this pedal: effect-specific knobs
/// first, then the common `mix` and `level` knobs. The `bypass` parameter is
/// surfaced separately as a header toggle, not as a knob.
@@ -187,6 +250,22 @@ open class Pedal: SynthesizerBase {
]
}
/// Every continuous control on this pedal that a MIDI Control Change can drive — the pedal's
/// knobs (effect knobs + Mix + Level) followed by its vertical-fader sliders. Discrete controls
/// (switches, stepped selectors) are excluded; they suit Program Change toggles, not CC sweeps.
///
/// Ordering is stable — knobs first, then sliders — so a persisted CC binding addressed by index
/// keeps resolving to the same control across launches. Used by MIDI mapping.
public var ccMappableControls: [PedalControl] {
let knobControls: [PedalControl] = knobs.map {
PedalControl(label: $0.label, node: $0.node, range: $0.range)
}
let sliderControls: [PedalControl] = effectSliders.map {
PedalControl(label: $0.label, node: $0.node, range: $0.range)
}
return knobControls + sliderControls
}
// MARK: - Subclass hook
/// Returns the processed (wet) mono signal for this pedal.
+33 -1
View File
@@ -4,6 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
@@ -59,6 +60,10 @@ public final class PedalBoard {
private let engine: SynthesisEngine
/// Shared tempo clock, forwarded to each pedal in `add(_:)` so tempo-aware pedals (the
/// looper) can quantize to beats. `nil` for boards created without one.
private let clock: LyrebirdClock?
/// The bus that feeds the first pedal in the chain.
public let headBus: AudioBus
@@ -89,6 +94,11 @@ public final class PedalBoard {
/// call chains the first pedal after this node automatically (no `after:` arg needed).
public internal(set) var headInputNode: (any Synthesizer)?
/// Stable identity for this board, persisted in ``BoardState`` and used by MIDI bindings to
/// address the board by id rather than by position. Defaults to a fresh `UUID`; a rebuild from
/// a saved rig restores the saved id, so a board keeps its identity across edits and reorders.
public internal(set) var id: UUID = UUID()
/// Display label for the board, shown in the UI. Defaults to `"Board"`; `ShoeGaze`
/// assigns a numbered label (`"Board 1"`, `"Board 2"`, …) when it creates the board.
public var label: String = "Board"
@@ -105,6 +115,22 @@ public final class PedalBoard {
/// `nil` until `finalizeBoard(_:)`.
public internal(set) var crossfadeTimeNode: UIParamNode?
/// The live per-board full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough).
/// `nil` until `finalizeBoard(_:)`. Driven by `ShoeGaze.setBoard(_:bypassed:)`.
public internal(set) var boardBypassNode: UIParamNode?
/// The live rig-wide full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough),
/// driven across every board by `ShoeGaze.setRigBypassed(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigBypassNode: UIParamNode?
/// The live rig-wide output-volume `UIParamNode` ([0, 1]), driven across every board by
/// `ShoeGaze.setRigVolume(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigVolumeNode: UIParamNode?
/// The live rig-wide output-mute `UIParamNode` (`0` = audible, `1` = silenced), driven across
/// every board by `ShoeGaze.setRigMuted(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigMuteNode: UIParamNode?
/// The output master synth for this board. Set by `ShoeGaze.finalizeBoard(_:)`;
/// used by `ShoeGaze.removeBoard(_:)` to tear down just this board's master.
internal var outputMaster: BoardOutputMaster?
@@ -137,9 +163,13 @@ public final class PedalBoard {
///
/// - Parameters:
/// - engine: The `SynthesisEngine` that will own the pedal nodes.
/// - clock: Shared tempo clock forwarded to tempo-aware pedals (the looper) for
/// beat-quantized transport. Optional; `nil` disables quantization for pedals on
/// this board.
/// - Throws: `BusAllocatorError.noFreeBus` if no mono audio bus is available.
public init(engine: SynthesisEngine) throws {
public init(engine: SynthesisEngine, clock: LyrebirdClock? = nil) throws {
self.engine = engine
self.clock = clock
let head: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
self.headBus = head
self.outputBus = head
@@ -180,6 +210,8 @@ public final class PedalBoard {
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
public func add(_ pedal: Pedal, after predecessor: (any Synthesizer)? = nil) throws {
pedal.sampleRate = engine.sampleRate
pedal.hostEngine = engine
pedal.clock = clock
// Each arm configures the pedal's buses, inserts it, advances the tail, and only then
// records it in `pedals` — so a pedal is never tracked unless it was fully wired and
@@ -0,0 +1,95 @@
// PedalButton.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// A UI-agnostic description of one pedal button — a momentary action trigger or a
/// node-bound toggle, rendered as a stomp-style button.
///
/// Where ``PedalSwitch`` describes a multi-position segmented control, `PedalButton`
/// describes a single button in one of two styles:
/// - `.momentary`: runs a closure on each press (e.g. "Record / Stop", "Reset"). Use this
/// whenever pressing the button must also perform a non-RT side effect (clearing a
/// buffer, requesting a recorder reset) beyond writing a single parameter value.
/// - `.toggle`: flips a bound ``UIParamNode`` between `0` and `1` on each press, with no
/// side effect required — appropriate only when the live audio graph itself reads the
/// node continuously (so toggling the raw value is sufficient).
///
/// A `Pedal` publishes an array of these via ``Pedal/effectButtons`` so a generic
/// pedalboard UI can render a footswitch-style button per action without knowing the
/// concrete pedal type.
public struct PedalButton {
/// Style of button behavior, mirroring `ParameterButton.Style` in `LyrebirdUI`.
public enum Style: Equatable {
/// Executes `action` on each press.
case momentary
/// Flips `node` between `0` and `1` on each press.
case toggle
}
/// Short label shown on the button (e.g. "Record", "Reset").
public let label: String
/// Button behavior style.
public let style: Style
/// The live parameter node this button toggles. Non-`nil` only for `.toggle` style.
public let node: UIParamNode?
/// The action run on each press. Non-`nil` only for `.momentary` style.
public let action: (() -> Void)?
/// Optional LED-indicator node for a `.momentary` button. When non-`nil`, the button is
/// drawn in the same LED + footswitch style as a `.toggle` button, with the LED lit while
/// this node reads `≥ 0.5` — letting a momentary action reflect a persistent state (e.g. a
/// looper's Stop lit while stopped, Cue Stop lit while armed). `nil` renders a plain button.
public let indicator: UIParamNode?
/// Optional live caption describing what the *next* press does, polled by the UI. When set,
/// the button shows this instead of the static `label` — letting a state-driven control (the
/// looper's Loop footswitch) read "Record" → "Set End" → "Overdub" → "Play" as the state
/// changes. `nil` shows the static `label`.
public let dynamicLabel: (() -> String)?
/// Creates a momentary action button.
///
/// - Parameters:
/// - label: Short label shown on the button.
/// - indicator: Optional state node driving an LED (see ``indicator``). Defaults to `nil`
/// for a plain button.
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
/// - action: Closure run on each press.
public init(
label: String,
indicator: UIParamNode? = nil,
dynamicLabel: (() -> String)? = nil,
action: @escaping () -> Void
) {
self.label = label
self.style = .momentary
self.node = nil
self.action = action
self.indicator = indicator
self.dynamicLabel = dynamicLabel
}
/// Creates a toggle button bound to a `UIParamNode`.
///
/// - Parameters:
/// - label: Short label shown on the button.
/// - node: The `UIParamNode` projected value of an `@UIParam` property
/// (`pedal.$loopOn`, `pedal.$reverse`, …).
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
public init(label: String, node: UIParamNode, dynamicLabel: (() -> String)? = nil) {
self.label = label
self.style = .toggle
self.node = node
self.action = nil
self.indicator = nil
self.dynamicLabel = dynamicLabel
}
}
@@ -0,0 +1,38 @@
// PedalControl.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// A continuous pedal control that can be driven by a MIDI Control Change — the common shape of a
/// ``PedalKnob`` and a ``PedalSlider`` (a labelled `UIParamNode` with a value range).
///
/// Used by MIDI mapping to enumerate every CC-assignable control on a pedal uniformly, regardless of
/// how the pedal chose to present it (rotary knob vs vertical fader). Discrete controls (switches,
/// stepped selectors) are intentionally excluded — they suit momentary Program Change bindings, not
/// continuous expression control.
public struct PedalControl {
/// Short display label (e.g. `"Rate"`, `"Position"`).
public let label: String
/// The live parameter node the CC drives.
public let node: UIParamNode
/// Inclusive value range the control spans, in the parameter's own units.
public let range: ClosedRange<Double>
/// Creates a pedal control descriptor.
///
/// - Parameters:
/// - label: Short display label.
/// - node: The live parameter node.
/// - range: Inclusive value range in the parameter's own units.
public init(label: String, node: UIParamNode, range: ClosedRange<Double>) {
self.label = label
self.node = node
self.range = range
}
}
@@ -66,4 +66,15 @@ public struct PedalSwitch {
self.node = node
self.options = options
}
/// The value of the next option after the one nearest `current`, wrapping to the first — so a
/// momentary trigger (e.g. a MIDI switch) can oscillate through the positions on each press.
public func nextValue(after current: Double) -> Double {
guard !options.isEmpty else { return current }
let currentIndex: Int = options.indices.min(by: {
abs(options[$0].value - current) < abs(options[$1].value - current)
}) ?? 0
let nextIndex: Int = (currentIndex + 1) % options.count
return options[nextIndex].value
}
}
+10
View File
@@ -54,6 +54,7 @@ public extension PedalType {
// EQ & filter
static let graphicEQ = PedalType("Graphic EQ")
static let autoWah = PedalType("Auto-Wah")
static let wah = PedalType("Wah")
static let mutant = PedalType("Mutant")
static let phaser = PedalType("Phaser")
@@ -73,6 +74,9 @@ public extension PedalType {
// Dynamics (additional)
static let sustainer = PedalType("Sustainer")
// Gain (additional)
static let volume = PedalType("Volume")
// Delay & reverb
static let delay = PedalType("Delay")
static let feedbackDelay = PedalType("Feedback Delay")
@@ -81,9 +85,15 @@ public extension PedalType {
static let reverseDelay = PedalType("Reverse Delay")
static let reverb = PedalType("Reverb")
static let shimmerReverb = PedalType("Shimmer Reverb")
static let plateReverb = PedalType("Plate Reverb")
static let roomReverb = PedalType("Room Reverb")
static let springReverb = PedalType("Spring Reverb")
// Pitch & octave
static let octaveSplitter = PedalType("Octave Splitter")
static let bassOctaver = PedalType("Bass Octaver")
static let harmonizer = PedalType("Harmonizer")
// Looper
static let looper = PedalType("Looper")
}
@@ -0,0 +1,789 @@
// LooperPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
/// A synchronized multitrack loop pedal. Track A's first take defines the master loop length;
/// tracks B–D are overdub layers recorded onto the same grid. All recorded tracks play at once,
/// summed to one output and locked in phase. When the board supplies a tempo ``LyrebirdClock``
/// the master take is beat-quantized so every loop is a whole number of beats long.
///
/// ## The Loop footswitch drives the transport by state
/// - **Clear** (nothing recorded; only track A selectable): press → record A; press → set the
/// loop end (quantized) and drop into overdub on A when it wraps; press → end overdub, keep
/// playing; further presses toggle overdub ↔ play on the selected track.
/// - **Playing, track B–D selected**: press toggles overdub on that track, aligned to A's
/// play-head. Recording an empty track is just overdub onto silence.
/// - Selecting another track ends any overdub on the previous one (it drops to playback). A
/// newly-selected track records nothing until Loop is pressed.
/// - **Stopped** (via Stop / Cue Stop): press → resume all tracks; next press → toggle overdub.
///
/// > Note: Overdub records forward-in-time, so it cannot be engaged while playback is reversed
/// > (the write head would drift against the backward-reading play-head). Engaging overdub is
/// > blocked while `reverse` is on.
///
/// ## Audio graph (built once in `effect(_:)`)
/// One `PlayBuffer` per track, all summed; one always-running overdub `RecordBuffer` per track
/// whose `recLevel` is gated so only the selected, overdubbing track layers new input; a
/// non-looping master recorder for track A's length-defining take. The overdub recorders run
/// continuously while playing (reset to the top at play-start) so their write head stays locked
/// to the shared play-head — overdub can be toggled on any track without drifting out of phase.
public final class LooperPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Multitrack looper: record track A, then layer synced overdubs on tracks B–D."
}
/// Double-width card: the looper carries a full transport plus a track strip and timeline.
public override var widthUnits: Int { 2 }
/// The looper always passes the clean signal through and adds the loop on top (see `effect`),
/// so the wet/dry Mix knob is meaningless — hide it and keep `mix` fully wet.
public override var showsMixControl: Bool { false }
// MARK: - Knobs
/// Fade time constant, in seconds, for the loop on/off mute and the record→play handoff.
@UIParam public var crossfadeTime: Double = LooperPedal.defaultCrossfadeTime
/// Loop playback gain, in dB.
@UIParam public var playbackLevel: Double = 0.0
/// Overdub input gain, in dB.
@UIParam public var overdubLevel: Double = 0.0
/// Retained level of existing loop content on each overdub pass, `[0, 1]`. `1.0` keeps prior
/// layers indefinitely; lower values fade them for a decaying feedback loop.
@UIParam public var feedback: Double = 1.0
// MARK: - Switches
/// Total loop mute. `0` = muted, `1` = audible. Smoothed by `crossfadeTime`.
@UIParam public var loopOn: Double = 1.0
/// Playback direction. `0` = forward, `1` = reverse. Read as `1 − 2·reverse`.
@UIParam public var reverse: Double = 0.0
/// Transport sync mode. `1` = beat-quantized (record start / loop close snap to the next
/// beat via the shared clock); `0` = freeform (immediate, loop length is whatever you play).
/// Persisted with the rig. Default `1`.
@UIParam public var syncToBeat: Double = 1.0
// MARK: - Internal live state (read by the audio graph / UI LEDs)
/// `1` while the loop bank is playing, else `0`. Gates the whole player sum and the overdub
/// recorders' `run`.
@UIParam public var isPlaying: Double = 0.0
/// Play-head reset trigger for every player. Pulsed `0 → 1` at play-start so all tracks
/// start phase-aligned to frame 0.
@UIParam public var playTrigger: Double = 0.0
/// LED state for the Stop footswitch: `1` while stopped, else `0`.
@UIParam public var stoppedIndicator: Double = 0.0
/// LED state for the Cue Stop footswitch: `1` while a stop-at-loop-end is armed.
@UIParam public var cueStopArmed: Double = 0.0
/// LED state for the Loop footswitch: `1` while overdubbing a track.
@UIParam public var overdubIndicator: Double = 0.0
/// LED state for the Reset footswitch: `1` whenever there is something to reset (any state
/// other than clear). Kept in sync by `phase`'s `didSet`.
@UIParam public var resetIndicator: Double = 0.0
// MARK: - Constants
/// Number of loop tracks (A–D).
public static let trackCount: Int = 4
/// Maximum recordable master length, in seconds (each track allocates a buffer this long, so
/// per-instance memory is roughly `trackCount × maxDurationSeconds × sampleRate × 8 bytes`).
private static let maxDurationSeconds: Double = 60.0
private static let defaultCrossfadeTime: Double = 0.05
private static let reverseRateSpan: Double = 2.0
private static let forwardRate: Double = 1.0
private static let minimumLoopFrames: Int = 1
private let crossfadeTimeRange: ClosedRange<Double> = 0.0 ... 2.0
private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Buffers + generators
private var buffers: [LyrebirdBuffer] = []
private var players: [PlayBuffer.Audio] = []
private var overdubRecorders: [RecordBuffer.Audio] = []
private var overdubGates: [ParameterNode] = []
/// Per-track playback mute gate (`1` = audible, `0` = muted), smoothed by `crossfadeTime` and
/// multiplied into each track's player so a recorded track can be silenced.
private var muteGates: [ParameterNode] = []
/// Per-track mute state (`true` = muted).
private var trackMuted: [Bool] = []
/// Non-looping recorder for track A's length-defining first take.
private var masterRecorder: RecordBuffer.Audio?
// MARK: - Transport state
private enum Phase {
case clear
case armedRecord
case recordingMaster
case armedClose
case playing
case stopped
}
private var phase: Phase = .clear {
didSet { resetIndicator = phase == .clear ? 0.0 : 1.0 }
}
/// The track the Loop footswitch records / overdubs into (`0` = A).
private var selectedTrack: Int = 0
/// The track currently overdubbing, or `nil` when just playing.
private var overdubbingTrack: Int?
/// `true` once a track holds recorded material.
private var trackHasContent: [Bool] = []
/// Master loop length in frames (`0` until track A is closed).
private var masterLength: Int = 0
/// Master loop length in whole beats (`0` unless beat-quantized).
private var masterBeats: Double = 0.0
/// Sample time at which the master take began recording, and at which playback last (re)started.
private var recordStartSample: SampleTime = 0
private var playStartSample: SampleTime = 0
private var transportRoutine: LyrebirdRoutine?
private var stopRoutine: LyrebirdRoutine?
/// Transient notice shown in place of the state description for `noticeDuration` seconds.
private var noticeText: String?
private var noticeExpiry: Date?
private static let noticeDuration: TimeInterval = 4.0
/// Monotonic action generation guarding deferred beat/stop callbacks (see the single-track
/// history — `LyrebirdRoutine.stop()` cannot recall an already-enqueued main-thread hop).
private(set) var transportGeneration: Int = 0
// MARK: - Init
/// Creates a looper pedal.
///
/// - Parameters:
/// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board.
/// - outputBus: Audio bus to write the output to. Defaults to `0`; set by the board.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
}
// MARK: - Knobs / buttons
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Crossfade", node: $crossfadeTime, range: crossfadeTimeRange),
PedalKnob(label: "Playback", node: $playbackLevel, range: levelRangeDb),
PedalKnob(label: "Overdub", node: $overdubLevel, range: levelRangeDb),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
]
}
/// Beat-sync vs freeform transport mode, as a two-position segmented switch below the knobs.
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Sync",
node: $syncToBeat,
options: [
PedalSwitch.Option(title: "Free", value: 0.0),
PedalSwitch.Option(title: "Sync", value: 1.0),
]
),
]
}
/// Transport row: the smart Loop footswitch, the two stops, direction, and reset.
public override var effectTransportButtons: [PedalButton] {
[
PedalButton(label: "Loop", indicator: $overdubIndicator,
dynamicLabel: { [weak self] in self?.loopButtonCaption ?? "Loop" }) { [weak self] in self?.pressLoop() },
PedalButton(label: "Stop", indicator: $stoppedIndicator,
dynamicLabel: { [weak self] in self?.stopButtonCaption ?? "Stop" }) { [weak self] in self?.stopPlayback() },
PedalButton(label: "Cue Stop", indicator: $cueStopArmed,
dynamicLabel: { [weak self] in self?.cueStopButtonCaption ?? "Cue Stop" }) { [weak self] in self?.toggleStopAtLoopEnd() },
PedalButton(label: "Reverse", indicator: $reverse,
dynamicLabel: { [weak self] in self?.reverseButtonCaption ?? "Reverse" }) { [weak self] in self?.toggleReverse() },
PedalButton(label: "Reset", indicator: $resetIndicator) { [weak self] in self?.resetLoop() },
]
}
// MARK: - UI read-outs
/// Publicly-observable transport phase for the state indicator, LEDs, and timeline.
public var transportState: LooperTransportState {
switch phase {
case .clear: return .clear
case .armedRecord: return .armedRecord
case .recordingMaster: return .recordingMaster
case .armedClose: return .armedClose
case .playing: return .playing
case .stopped: return .stopped
}
}
/// Index of the selected track, `0 ..< trackCount`.
public var selectedTrackIndex: Int { selectedTrack }
/// The track currently overdubbing, or `nil`.
public var overdubbingTrackIndex: Int? { overdubbingTrack }
/// `true` if track `index` holds recorded material.
public func trackHasContent(_ index: Int) -> Bool {
index >= 0 && index < trackHasContent.count && trackHasContent[index]
}
/// Per-track generator array counts — internal only so a test can verify a graph rebuild
/// (`effect()` re-run) doesn't accumulate them. All four should equal `trackCount`.
var trackGeneratorCountsForTesting: (buffers: Int, players: Int, overdub: Int, gates: Int) {
(buffers.count, players.count, overdubRecorders.count, overdubGates.count)
}
/// `true` while a stop-at-loop-end is armed.
public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
/// Master loop length in frames (`0` until track A is closed).
public var loopFrameCount: Int { masterLength }
/// Master loop length in seconds.
public var loopLengthSeconds: Double { Double(masterLength) / sampleRate }
/// Master loop length in whole beats (`0` unless beat-quantized).
public var loopLengthBeats: Double { masterBeats }
/// Normalised play-head position in `[0, 1)` while playing, else `nil`. Shared by all tracks.
public func playbackPosition01() -> Double? {
guard phase == .playing, masterLength > 0, let engine: SynthesisEngine = hostEngine else {
return nil
}
let elapsed: SampleTime = engine.currentTime - playStartSample
guard elapsed >= 0 else { return 0.0 }
let framesInto: Int = Int(elapsed % SampleTime(masterLength))
let forward: Double = Double(framesInto) / Double(masterLength)
return reverse >= 0.5 ? (1.0 - forward) : forward
}
/// Caption for the Loop footswitch describing what the *next* press does.
public var loopButtonCaption: String {
switch phase {
case .clear: return "Record"
case .armedRecord: return "Recording"
case .recordingMaster: return "Set End"
case .armedClose: return "Closing"
case .stopped: return "Play"
case .playing:
if overdubbingTrack == selectedTrack { return "Play" }
return trackHasContent(selectedTrack) ? "Overdub" : "Record"
}
}
/// Caption for the Stop footswitch (what the next press does).
public var stopButtonCaption: String { phase == .stopped ? "Stopped" : "Stop" }
/// Caption for the Cue Stop footswitch.
public var cueStopButtonCaption: String { isStopAtLoopEndArmed ? "Cancel" : "Cue Stop" }
/// Caption for the Reverse footswitch (the direction the next press switches to).
public var reverseButtonCaption: String { reverse >= 0.5 ? "Forward" : "Reverse" }
/// One-line description of what the pedal is doing now, for the state indicator. A transient
/// notice (e.g. the engine-stop reset) takes precedence for a few seconds.
public var stateDescription: String {
if let notice: String = noticeText, let expiry: Date = noticeExpiry, Date() < expiry {
return notice
}
let armedSuffix: String = isStopAtLoopEndArmed ? " · stop at end" : ""
switch phase {
case .clear: return "Empty — record track A"
case .armedRecord: return "Waiting for beat…"
case .recordingMaster: return "Recording A"
case .armedClose: return "Closing loop…"
case .stopped: return "Stopped"
case .playing:
if let track: Int = overdubbingTrack {
return "Overdubbing \(LooperPedal.trackLabel(track))" + armedSuffix
}
return "Playing" + armedSuffix
}
}
/// The letter for a track index (0 → "A").
public static func trackLabel(_ index: Int) -> String {
let letters: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
return letters.indices.contains(index) ? letters[index] : "?"
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// `effect()` runs from `build()`, which the engine re-invokes via `rebuildGraph()` on
// EVERY add — including the re-adds that a board edit (reorder, insert/remove a neighbour,
// toggle a split) performs on this same instance. Start from a clean slate so the per-track
// generator arrays don't accumulate across rebuilds, and so stale transport state doesn't
// outlive the freshly re-allocated (empty) buffers built below.
resetForRebuild()
let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate)
let playbackRate: any ValidGeneratorInput =
LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse
let unity: Double = 1.0
for _: Int in 0 ..< LooperPedal.trackCount {
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
buffers.append(buffer)
let gate: ParameterNode = ParameterNode(0.0)
overdubGates.append(gate)
let muteGate: ParameterNode = ParameterNode(1.0) // 1 = audible
muteGates.append(muteGate)
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffer,
loop: true,
doneAction: .nothing
)
// Always running while playing; its write head stays locked to the shared play-head.
// `recLevel` is zero unless this track is the one being overdubbed; `preLevel` is 1
// (identity — keep existing content) except while overdubbing, when it is `feedback`.
overdub.$run.source = $isPlaying
overdub.$recLevel.source = gate * DbAmp.Control($overdubLevel)
overdub.$preLevel.source = (unity - gate) + gate * $feedback
overdubRecorders.append(overdub)
let player: PlayBuffer.Audio = PlayBuffer.Audio(
buffer: buffer,
loop: true,
interpolation: .cubic,
rate: playbackRate,
trigger: $playTrigger,
mul: DbAmp.Control($playbackLevel)
)
players.append(player)
}
let master: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffers[0],
loop: false,
doneAction: .nothing
)
master.run = 0.0
masterRecorder = master
trackHasContent = [Bool](repeating: false, count: LooperPedal.trackCount)
trackMuted = [Bool](repeating: false, count: LooperPedal.trackCount)
// Loop bank audible only while playing and not muted; smoothed to avoid clicks.
let combinedGate: any ValidGeneratorInput = $isPlaying * $loopOn
let smoothedGate: Lag.Control = Lag.Control(input: combinedGate, time: $crossfadeTime)
// Sum all track players, each scaled by its smoothed per-track mute gate. Empty buffers
// contribute silence. Each player is already scaled by the `Playback` level, so `Playback`
// sets the loop amount against the live signal below.
var loopSum: any ValidGeneratorInput =
players[0] * Lag.Control(input: muteGates[0], time: $crossfadeTime)
for i: Int in 1 ..< players.count {
loopSum = loopSum + players[i] * Lag.Control(input: muteGates[i], time: $crossfadeTime)
}
// The clean (dry) signal always passes through at full level; the loop bank is added on
// top, gated by play/mute. `Playback` controls the looped-vs-live balance.
return dry + (loopSum * smoothedGate)
}
// MARK: - Loop footswitch
/// The smart transport press. Behaviour depends on the current phase and selected track.
public func pressLoop() {
switch phase {
case .clear: armMasterRecording()
case .recordingMaster: armCloseMaster()
case .playing: toggleOverdubSelected()
case .stopped: resumePlayback()
case .armedRecord, .armedClose:
break
}
}
/// Handles a tap on a track dot: selects the track, or — when it is already the selected track
/// and holds recorded material — toggles its mute. So a first tap focuses a track (to overdub
/// or record it), and a second tap on that same recorded track mutes/unmutes it.
public func tapTrack(_ index: Int) {
guard index >= 0, index < LooperPedal.trackCount, !buffers.isEmpty else { return }
if index == selectedTrack, trackHasContent(index) {
toggleTrackMute(index)
} else {
selectTrack(index)
}
}
/// `true` if track `index` is currently muted.
public func isTrackMuted(_ index: Int) -> Bool {
index >= 0 && index < trackMuted.count && trackMuted[index]
}
/// Toggles a recorded track's playback mute (smoothed via `crossfadeTime`).
private func toggleTrackMute(_ index: Int) {
guard trackMuted.indices.contains(index), muteGates.indices.contains(index) else { return }
trackMuted[index].toggle()
muteGates[index].value = trackMuted[index] ? 0.0 : 1.0
}
/// Selects the active track (the one Loop records / overdubs into). Only track A is selectable
/// while clear. Selecting a new track ends any overdub on the previous one (it drops to
/// playback); the new track records nothing until Loop.
public func selectTrack(_ index: Int) {
guard index >= 0, index < LooperPedal.trackCount, index != selectedTrack, !buffers.isEmpty else { return }
switch phase {
case .clear:
return // only track A while clear
case .armedRecord, .recordingMaster, .armedClose:
return // not mid master-record
case .playing, .stopped:
break
}
overdubbingTrack = nil // selecting elsewhere ends the current overdub
selectedTrack = index
updateOverdubGates()
}
// MARK: - Stops / reset
/// Advances the Sync mode through its options (Free ↔ Sync), wrapping — so a MIDI switch can
/// oscillate through the positions on each press, matching the segmented control.
public func cycleSyncMode() {
guard let sync: PedalSwitch = effectSwitches.first(where: { $0.node === $syncToBeat }) else { return }
syncToBeat = sync.nextValue(after: syncToBeat)
}
/// Flips playback direction. Engaging reverse ends any active overdub, since overdub records
/// forward-in-time and can't follow a backward-reading play-head (see the class doc).
public func toggleReverse() {
let engagingReverse: Bool = reverse < 0.5
reverse = engagingReverse ? 1.0 : 0.0
if engagingReverse, overdubbingTrack != nil {
overdubbingTrack = nil
updateOverdubGates()
}
}
/// Immediately halts playback of all tracks; recorded content is retained (resume via Loop).
public func stopPlayback() {
guard phase == .playing else { return }
transportGeneration += 1
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
overdubbingTrack = nil
updateOverdubGates()
isPlaying = 0.0
playTrigger = 0.0 // rearm the play-head reset edge
stoppedIndicator = 1.0
phase = .stopped
}
/// Arms (or cancels) a stop that fires when the loop next reaches its end. No-op unless
/// playing. With no engine to schedule against, stops now.
public func toggleStopAtLoopEnd() {
if isStopAtLoopEndArmed {
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
transportGeneration += 1
return
}
guard phase == .playing, masterLength > 0 else { return }
transportGeneration += 1
let generation: Int = transportGeneration
guard let engine: SynthesisEngine = hostEngine else {
stopPlayback()
return
}
let frames: SampleTime = SampleTime(masterLength)
let elapsed: SampleTime = max(0, engine.currentTime - playStartSample)
let boundary: SampleTime = playStartSample + (elapsed / frames + 1) * frames
cueStopArmed = 1.0
stopRoutine?.stop()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: boundary)
DispatchQueue.main.async { self?.applyStopAtLoopEnd(generation: generation) }
}
stopRoutine = routine
routine.start(engine: engine)
}
/// Applies an armed "stop at end" once the boundary is reached, unless superseded.
func applyStopAtLoopEnd(generation: Int) {
guard generation == transportGeneration, phase == .playing else { return }
cueStopArmed = 0.0
overdubbingTrack = nil
updateOverdubGates()
isPlaying = 0.0
playTrigger = 0.0
stoppedIndicator = 1.0
phase = .stopped
}
/// When the engine is stopped by the user, drop any recorded loop and return to the clear
/// state — a stopped engine can't keep a loop running, and resuming into a half-recorded take
/// is confusing. Posts a notice to the message log and briefly on the pedal's own card.
public override func engineDidStop() {
resetAndNotify("engine stopped")
}
/// The rig is being torn down (load / clear / input-source change) — reset before this looper
/// instance is discarded, stopping any background routines cleanly and logging a notice.
public override func rigWillTeardown() {
resetAndNotify("rig changed")
}
/// Returns to the clear state and posts a notice (message log + briefly on the pedal card),
/// unless already clear. Shared by ``engineDidStop()`` and ``rigWillTeardown()``.
private func resetAndNotify(_ reason: String) {
guard phase != .clear else { return }
resetLoop()
let message: String = "Looper reset — \(reason)."
noticeText = message
noticeExpiry = Date().addingTimeInterval(LooperPedal.noticeDuration)
LyrebirdMessageCenter.shared.info(message, source: displayName)
}
/// Returns the pedal to the clear state: all tracks cleared, track A selected, length reset.
/// If sound is playing it acts as an immediate stop-and-clear.
public func resetLoop() {
transportRoutine?.stop()
transportRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
transportGeneration += 1
// Gate the recorders off (they run off `$isPlaying`) and stop the master BEFORE clearing,
// so the only overlap with `clear()` is at most the one RT block already in flight.
isPlaying = 0.0
masterRecorder?.run = 0.0
masterRecorder?.requestReset()
for recorder: RecordBuffer.Audio in overdubRecorders {
recorder.requestReset()
}
// `clear()` zeroes the buffers on the main thread. `isPlaying = 0` above stops the
// recorders from the next block on, so `clear()` can overlap only the single in-flight
// RT block; that overlap is benign because `LyrebirdBuffer.clear()` (`vDSP_vclrD`) and
// the recorder both write whole 8-byte-aligned `Double` slots — no torn value — and the
// buffer is being zeroed anyway. Deferring the clear would instead race a fast
// reset→re-record, so it runs immediately.
for buffer: LyrebirdBuffer in buffers {
buffer.clear()
buffer.setLoopLength(buffer.count)
}
for i: Int in trackHasContent.indices {
trackHasContent[i] = false
}
for i: Int in trackMuted.indices {
trackMuted[i] = false
}
for gate: ParameterNode in muteGates {
gate.value = 1.0
}
selectedTrack = 0
overdubbingTrack = nil
masterLength = 0
masterBeats = 0.0
loopOn = 1.0
reverse = 0.0 // clean slate: forward playback
playTrigger = 0.0
stoppedIndicator = 0.0
cueStopArmed = 0.0
// Drop any lingering transient notice so it can't mask the fresh state indicator.
noticeText = nil
noticeExpiry = nil
updateOverdubGates()
phase = .clear
}
// MARK: - Transport helpers
/// Clears the per-track generator arrays and returns transport state to clear, so a graph
/// rebuild (`build()` re-run) starts fresh instead of doubling the arrays or leaving state
/// that references the discarded buffers. Called at the top of ``effect(_:)``.
private func resetForRebuild() {
transportRoutine?.stop()
transportRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
buffers.removeAll()
players.removeAll()
overdubRecorders.removeAll()
overdubGates.removeAll()
muteGates.removeAll()
masterRecorder = nil
trackHasContent = []
trackMuted = []
selectedTrack = 0
overdubbingTrack = nil
masterLength = 0
masterBeats = 0.0
isPlaying = 0.0
loopOn = 1.0
reverse = 0.0
playTrigger = 0.0
stoppedIndicator = 0.0
cueStopArmed = 0.0
overdubIndicator = 0.0
noticeText = nil
noticeExpiry = nil
phase = .clear
}
private func updateOverdubGates() {
for i: Int in overdubGates.indices {
overdubGates[i].value = (overdubbingTrack == i) ? 1.0 : 0.0
}
overdubIndicator = overdubbingTrack != nil ? 1.0 : 0.0
}
private func toggleOverdubSelected() {
if overdubbingTrack == selectedTrack {
overdubbingTrack = nil
} else {
// Overdub records forward-in-time; a reversed player reads backward, so engaging
// overdub while reversed would write out of alignment with what's heard. Block it.
guard reverse < 0.5 else { return }
overdubbingTrack = selectedTrack
if trackHasContent.indices.contains(selectedTrack) { trackHasContent[selectedTrack] = true }
}
updateOverdubGates()
}
/// (Re)starts playback of all tracks from the top, optionally overdubbing `overdubTrack`.
///
/// The recorder write heads (`requestReset`) and the player play-heads (`playTrigger` rising
/// edge) are both reset **synchronously here** so they take effect on the same next audio
/// block — keeping overdub writes phase-locked to playback. `playTrigger` is zeroed on every
/// stop so each start is a clean `0 → 1` edge.
private func startPlayback(overdubTrack: Int?, at sample: SampleTime) {
for recorder: RecordBuffer.Audio in overdubRecorders {
recorder.requestReset() // realign every write head to the top
}
playStartSample = sample
isPlaying = 1.0
stoppedIndicator = 0.0
overdubbingTrack = overdubTrack
if let track: Int = overdubTrack, trackHasContent.indices.contains(track) {
trackHasContent[track] = true
}
updateOverdubGates()
playTrigger = 1.0 // rising edge, same block as the resets
phase = .playing
}
/// Resumes playback of all active tracks from a stopped state.
private func resumePlayback() {
guard phase == .stopped, masterLength > 0 else { return }
transportGeneration += 1
startPlayback(overdubTrack: nil, at: hostEngine?.currentTime ?? 0)
}
enum QuantizedAction: Sendable {
case beginMaster
case closeMaster
}
private func armMasterRecording() {
selectedTrack = 0 // only track A in the clear state
updateOverdubGates()
phase = .armedRecord
runQuantized(.beginMaster)
}
private func armCloseMaster() {
phase = .armedClose
runQuantized(.closeMaster)
}
private func runQuantized(_ action: QuantizedAction) {
transportGeneration += 1
let generation: Int = transportGeneration
// Freeform (Sync off) or no clock/engine → apply immediately, un-quantized.
guard syncToBeat >= 0.5, let clock: LyrebirdClock = clock, let engine: SynthesisEngine = hostEngine else {
applyQuantizedTransport(action, generation: generation, at: nil)
return
}
transportRoutine?.stop()
let target: SampleTime = clock.nextBeat()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: target)
DispatchQueue.main.async { self?.applyQuantizedTransport(action, generation: generation, at: target) }
}
transportRoutine = routine
routine.start(engine: engine)
}
func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) {
guard generation == transportGeneration else { return }
switch action {
case .beginMaster: beginMasterRecording(at: beatSample)
case .closeMaster: closeMasterAndPlay(at: beatSample)
}
}
func beginMasterRecording(at beatSample: SampleTime?) {
guard phase == .armedRecord, let master: RecordBuffer.Audio = masterRecorder else { return }
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
master.run = 1.0
phase = .recordingMaster
}
func closeMasterAndPlay(at beatSample: SampleTime?) {
guard phase == .armedClose, let master: RecordBuffer.Audio = masterRecorder, !buffers.isEmpty else { return }
master.run = 0.0
let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0)
if let clock: LyrebirdClock = clock, beatSample != nil {
let spanFrames: Int = Int(closeSample - recordStartSample)
masterLength = max(LooperPedal.minimumLoopFrames, spanFrames)
masterBeats = beatsForSpan(frames: masterLength, clock: clock)
} else {
masterLength = max(LooperPedal.minimumLoopFrames, master.recordedFrameCount)
masterBeats = 0.0
}
for buffer: LyrebirdBuffer in buffers {
buffer.setLoopLength(masterLength)
}
if trackHasContent.indices.contains(0) { trackHasContent[0] = true }
// Auto-drop into overdub on track A as it wraps to the top (unless reversed — overdub
// can't follow reverse playback, so just play).
startPlayback(overdubTrack: reverse < 0.5 ? 0 : nil, at: closeSample)
}
/// Whole-beat length of a `frames`-long span at the clock's current tempo (UI read-out only).
func beatsForSpan(frames: Int, clock: LyrebirdClock) -> Double {
let samplesPerBeat: Double = Double(clock.sampleTime(beat: 1.0) - clock.sampleTime(beat: 0.0))
guard samplesPerBeat > 0 else { return 0.0 }
return (Double(frames) / samplesPerBeat).rounded()
}
}
@@ -0,0 +1,34 @@
// LooperTransportState.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Publicly-observable transport phase of the multitrack ``LooperPedal``, surfaced for the UI
/// so it can colour the state indicator, animate the "waiting for the next beat" armed states,
/// and drive the loop timeline.
///
/// The pedal is a synchronized multitrack looper: track A's first take defines the master loop
/// length, and tracks B–D are overdub layers recorded onto the same grid, all playing at once.
public enum LooperTransportState: Sendable, Equatable {
/// No material recorded on any track. Only track A can be selected; press Loop to record it.
case clear
/// A Loop press has been made in the clear state and the pedal is waiting for the next beat
/// to start recording track A.
case armedRecord
/// Recording track A's first take, which defines the master loop length.
case recordingMaster
/// A Loop press closed the master take and the pedal is waiting for the next beat to set the
/// loop end.
case armedClose
/// Looping playback of all recorded tracks. The selected track may be overdubbing.
case playing
/// Playback paused by a stop, with recorded material still loaded (ready to resume).
case stopped
}
@@ -0,0 +1,117 @@
// PlateReverbPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Plate reverb pedal: a Dattorro figure-of-eight plate, folded to mono.
///
/// Signal chain (inside `effect(_:)`):
/// ```
/// dry → PlateReverb.Audio(mix: 1.0, decay:, bandwidth:, damping:, modDepth:) → stereo (2 ch)
/// → SumChannels.Audio(mul: 0.5) → mono (fold)
/// ```
///
/// `PlateReverb` runs at `mix: 1.0` (pure wet); the base `Pedal` handles the wet/dry blend via its
/// own `mix` parameter. The native-stereo plate output is summed to mono with a ×0.5 gain to
/// compensate for the channel doubling.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - decay: Tail length (tank feedback) in [0, 0.9]. Higher = longer tail. Defaults to `0.7`.
/// - tone: Input brightness (bandwidth) in [0, 1]. `1` = fully bright. Defaults to `0.9`.
/// - damp: High-frequency damping in the tail in [0, 1]. Higher = darker. Defaults to `0.2`.
/// - mod: Tank modulation depth in [0, 1] — subtle movement/chorusing. Defaults to `0.5`.
public final class PlateReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Warm, dense plate reverb with gentle modulation — a lush, classic studio ambience."
}
// MARK: - Parameters
/// Tail length (tank feedback) in [0, 0.9]. Higher = longer tail.
@UIParam public var decay: Double = 0.7
/// Input brightness (bandwidth) in [0, 1]. `1` = fully bright.
@UIParam public var tone: Double = 0.9
/// High-frequency damping in the tail, in [0, 1]. Higher = darker.
@UIParam public var damp: Double = 0.2
/// Tank modulation depth in [0, 1] — subtle movement.
@UIParam public var mod: Double = 0.5
// MARK: - Constants
/// Plate mix value. `1.0` = pure wet; the base `Pedal` handles dry/wet blending.
private let plateWetMix: Double = 1.0
/// Gain applied to the summed stereo→mono fold, compensating for channel doubling.
private let stereoSumGain: Double = 0.5
/// Default wet/dry blend — a partial mix so the dry signal stays up front.
private static let defaultMix: Double = 0.3
// MARK: - Ranges
private let decayRange: ClosedRange<Double> = 0.0 ... 0.9
private let normalizedRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - UI knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Decay", node: $decay, range: decayRange),
PedalKnob(label: "Tone", node: $tone, range: normalizedRange),
PedalKnob(label: "Damp", node: $damp, range: normalizedRange),
PedalKnob(label: "Mod", node: $mod, range: normalizedRange),
]
}
// MARK: - Init
/// Creates a plate reverb 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: "Plate Reverb",
inputBus: inputBus,
outputBus: outputBus,
initialMix: PlateReverbPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// PlateReverb produces a 2-channel stereo output.
let stereoPlate: PlateReverb.Audio = PlateReverb.Audio(
input: dry,
decay: $decay,
bandwidth: $tone,
damping: $damp,
modDepth: $mod,
mix: plateWetMix,
sampleRate: sampleRate
)
// Sum stereo → mono with ×0.5 to avoid level doubling.
return SumChannels.Audio(
input: stereoPlate,
mul: stereoSumGain
)
}
}
@@ -0,0 +1,117 @@
// RoomReverbPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Room reverb pedal: the GVerb FDN room/hall algorithm, folded to mono.
///
/// Signal chain (inside `effect(_:)`):
/// ```
/// dry → GVerb.Audio(dryLevel: 0, roomSize:, reverbTime:, damping:, tailLevel:) → stereo (2 ch)
/// → SumChannels.Audio(mul: 0.5) → mono (fold)
/// ```
///
/// `GVerb` runs with `dryLevel: 0` (pure wet); the base `Pedal` handles the wet/dry blend via its
/// own `mix` parameter. The native-stereo output is summed to mono with a ×0.5 gain.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - size: Room size in metres, in [1, 100]. Larger = bigger space. Defaults to `30`.
/// - decay: Reverb time (T60) in seconds, in [0.2, 12]. Defaults to `3`.
/// - damp: High-frequency damping in [0, 1]. Higher = darker tail. Defaults to `0.5`.
/// - tail: Late-reverb level in [0, 1] — how present the room tail sits. Defaults to `0.6`.
public final class RoomReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Parametric room and hall reverb — dial the space in metres and its decay time."
}
// MARK: - Parameters
/// Room size in metres, in [1, 100]. Larger = bigger space.
@UIParam public var size: Double = 30.0
/// Reverb time (T60) in seconds, in [0.2, 12].
@UIParam public var decay: Double = 3.0
/// High-frequency damping in [0, 1]. Higher = darker tail.
@UIParam public var damp: Double = 0.5
/// Late-reverb level in [0, 1] — how present the room tail sits.
@UIParam public var tail: Double = 0.6
// MARK: - Constants
/// GVerb dry level. `0` = pure wet; the base `Pedal` handles dry/wet blending.
private let gverbDryLevel: Double = 0.0
/// Gain applied to the summed stereo→mono fold, compensating for channel doubling.
private let stereoSumGain: Double = 0.5
/// Default wet/dry blend — a partial mix so the dry signal stays up front.
private static let defaultMix: Double = 0.3
// MARK: - Ranges
private let sizeRange: ClosedRange<Double> = 1.0 ... 100.0
private let decayRange: ClosedRange<Double> = 0.2 ... 12.0
private let normalizedRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - UI knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Size", node: $size, range: sizeRange),
PedalKnob(label: "Decay", node: $decay, range: decayRange),
PedalKnob(label: "Damp", node: $damp, range: normalizedRange),
PedalKnob(label: "Tail", node: $tail, range: normalizedRange),
]
}
// MARK: - Init
/// Creates a room reverb 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: "Room Reverb",
inputBus: inputBus,
outputBus: outputBus,
initialMix: RoomReverbPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// GVerb produces a 2-channel stereo output.
let stereoRoom: GVerb.Audio = GVerb.Audio(
source: dry,
roomSize: $size,
reverbTime: $decay,
damping: $damp,
tailLevel: $tail,
dryLevel: gverbDryLevel,
sampleRate: sampleRate
)
// Sum stereo → mono with ×0.5 to avoid level doubling.
return SumChannels.Audio(
input: stereoRoom,
mul: stereoSumGain
)
}
}
@@ -0,0 +1,97 @@
// SpringReverbPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Spring reverb pedal: a Schroeder spring-tank, the classic surf/amp reverb voice.
///
/// Runs `SpringReverb` in mono (`stereo: false`) so no channel fold is needed. The generator is
/// driven at `mix: 1.0` (pure wet); the base `Pedal` handles the wet/dry blend via its own `mix`.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - decay: Tail length (RT60) in seconds, in [0.1, 5]. Defaults to `2`.
/// - tension: Spring dispersion/chirp in [0, 1] — the boingy spring character. Defaults to `0.5`.
/// - damp: High-frequency damping in [0, 1]. Higher = darker. Defaults to `0.3`.
public final class SpringReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Vintage spring-tank reverb — drippy, boingy surf and amp-style ambience."
}
// MARK: - Parameters
/// Tail length (RT60) in seconds, in [0.1, 5].
@UIParam public var decay: Double = 2.0
/// Spring dispersion/chirp in [0, 1] — the boingy spring character.
@UIParam public var tension: Double = 0.5
/// High-frequency damping in [0, 1]. Higher = darker.
@UIParam public var damp: Double = 0.3
// MARK: - Constants
/// Spring mix value. `1.0` = pure wet; the base `Pedal` handles dry/wet blending.
private let springWetMix: Double = 1.0
/// Default wet/dry blend — a partial mix so the dry signal stays up front.
private static let defaultMix: Double = 0.3
// MARK: - Ranges
private let decayRange: ClosedRange<Double> = 0.1 ... 5.0
private let normalizedRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - UI knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Decay", node: $decay, range: decayRange),
PedalKnob(label: "Tension", node: $tension, range: normalizedRange),
PedalKnob(label: "Damp", node: $damp, range: normalizedRange),
]
}
// MARK: - Init
/// Creates a spring reverb 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: "Spring Reverb",
inputBus: inputBus,
outputBus: outputBus,
initialMix: SpringReverbPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Mono spring tank — no channel fold needed.
SpringReverb.Audio(
input: dry,
decay: $decay,
tension: $tension,
damping: $damp,
mix: springWetMix,
sampleRate: sampleRate,
stereo: false
)
}
}
@@ -0,0 +1,73 @@
// VolumePedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Foot-controlled volume pedal — a single smoothed gain sweep from silence to unity.
///
/// The `position` knob is the expression-pedal position: `0` = heel down (silent), `1` = toe
/// down (unity gain). It is smoothed with a short `Lag` so sweeping the position (by hand or from
/// a MIDI expression pedal) is click-free.
///
/// ## Knobs
/// - `position`: Volume sweep in `[0, 1]`. `0` = silent, `1` = unity.
public final class VolumePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Foot-controlled volume — sweep from silence to unity gain."
}
// MARK: - Parameters
/// Expression-pedal position in `[0, 1]`. `0` = heel (silent), `1` = toe (unity gain).
@UIParam public var position: Double = 1.0
// MARK: - Constants
private static let defaultMix: Double = 1.0
/// Smoothing time constant in seconds for the position sweep — prevents zipper noise when
/// the position jumps (e.g. coarse 0–127 steps from a MIDI expression pedal).
private let smoothingTime: Double = 0.02
// MARK: - Ranges
private let positionRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Position", node: $position, range: positionRange),
]
}
// MARK: - Init
/// Creates a volume pedal.
///
/// - Parameters:
/// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board.
/// - outputBus: Audio bus to write the scaled output to. Defaults to `0`; set by the board.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(
name: "Volume",
inputBus: inputBus,
outputBus: outputBus,
initialMix: VolumePedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Smooth the position so hand/MIDI sweeps don't zipper, then scale the dry signal.
let smoothed: Lag.Control = Lag.Control(input: $position, time: smoothingTime)
return dry * smoothed
}
}
@@ -0,0 +1,105 @@
// WahPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Foot-swept wah pedal — a resonant bandpass whose cutoff follows the expression-pedal position.
///
/// Reuses the same filter voice as ``AutoWahPedal`` (a resonant `SVF` bandpass swept through an
/// exponential `LinExp` frequency map) but drives the sweep from the `position` knob instead of an
/// amplitude follower: `0` = heel (low, dark) → `1` = toe (high, bright). The position is smoothed
/// so hand or MIDI sweeps are click-free.
///
/// ## Signal path
/// ```
/// position → Lag → LinExp(freqLo…freqHi) → SVF.bandpass(q: resonance)
/// ↑freq
/// ```
///
/// ## Knobs
/// - `position`: Sweep position in `[0, 1]`. `0` = low cutoff, `1` = high cutoff.
/// - `resonance`: Bandpass Q. Higher values sharpen the wah vowel.
public final class WahPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Foot-swept resonant filter — the classic wah voice, driven by pedal position."
}
// MARK: - Parameters
/// Expression-pedal position in `[0, 1]`. `0` = heel (low cutoff), `1` = toe (high cutoff).
@UIParam public var position: Double = 0.5
/// Bandpass resonance (SVF quality factor). Higher values sharpen the wah vowel.
@UIParam public var resonance: Double = 3.0
// MARK: - Constants
private static let defaultMix: Double = 1.0
/// Cutoff at heel (`position == 0`), in Hz. `LinExp` requires a strictly positive lower bound.
private let freqLo: Double = 400.0
/// Cutoff at toe (`position == 1`), in Hz.
private let freqHi: Double = 2200.0
/// Smoothing time constant in seconds for the position sweep — prevents zipper noise when the
/// position jumps (e.g. coarse 0–127 steps from a MIDI expression pedal).
private let smoothingTime: Double = 0.02
// MARK: - Ranges
private let positionRange: ClosedRange<Double> = 0.0 ... 1.0
private let resonanceRange: ClosedRange<Double> = 0.5 ... 8.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Position", node: $position, range: positionRange),
PedalKnob(label: "Resonance", node: $resonance, range: resonanceRange),
]
}
// MARK: - Init
/// Creates a wah pedal.
///
/// - Parameters:
/// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board.
/// - outputBus: Audio bus to write the filtered output to. Defaults to `0`; set by the board.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(
name: "Wah",
inputBus: inputBus,
outputBus: outputBus,
initialMix: WahPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Smooth the position, map it exponentially to a cutoff sweep, and drive a resonant
// bandpass — the wah voice following the pedal rather than the signal envelope.
let smoothed: Lag.Control = Lag.Control(input: $position, time: smoothingTime)
let cutoff: LinExp.Audio = LinExp.Audio(
smoothed,
inLo: 0.0,
inHi: 1.0,
outLo: freqLo,
outHi: freqHi
)
let filtered: SVF.Audio = SVF.Audio(
input: dry,
freq: cutoff,
q: $resonance
)
return filtered.bandpass
}
}
@@ -4,6 +4,8 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Serialisable snapshot of one `PedalBoard`'s label and full signal-chain topology.
///
/// `label` is the board's display name. `segments` captures the chain in signal-flow order:
@@ -18,6 +20,11 @@
/// subset (the whole chain for boards with no split regions) for callers that only need it.
public struct BoardState: Codable, Equatable {
/// Stable per-board identity, persisted so MIDI bindings can address a board by id rather
/// than by position. Survives capture → rebuild round-trips. Legacy presets without an id
/// decode to a fresh `UUID()`.
public let id: UUID
/// The board's display label (e.g. `"Board 1"`).
public let label: String
@@ -39,9 +46,11 @@ public struct BoardState: Codable, Equatable {
/// - label: The board's display label.
/// - segments: Ordered signal-chain segments.
public init(
id: UUID = UUID(),
label: String,
segments: [BoardSegmentState]
) {
self.id = id
self.label = label
self.segments = segments
}
@@ -55,14 +64,17 @@ public struct BoardState: Codable, Equatable {
/// - label: The board's display label.
/// - pedals: Ordered list of pedal state snapshots.
public init(
id: UUID = UUID(),
label: String,
pedals: [PedalState]
) {
self.id = id
self.label = label
self.segments = pedals.map { BoardSegmentState.pedal($0) }
}
private enum CodingKeys: String, CodingKey {
case id
case label
case segments
case pedals
@@ -72,6 +84,7 @@ public struct BoardState: Codable, Equatable {
/// wrapping each entry as a `.pedal` segment.
public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
self.label = try container.decode(String.self, forKey: .label)
if let decodedSegments: [BoardSegmentState] =
try container.decodeIfPresent([BoardSegmentState].self, forKey: .segments) {
@@ -94,6 +107,7 @@ public struct BoardState: Codable, Equatable {
/// Encodes the snapshot using the current `segments` representation.
public func encode(to encoder: any Encoder) throws {
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(label, forKey: .label)
try container.encode(segments, forKey: .segments)
}
@@ -21,6 +21,7 @@ extension Pedal {
let sliderValues: [Double] = effectSliders.map { $0.node.value }
let selectorValues: [Double] = effectSelectors.map { $0.node.value }
return PedalState(
id: id,
type: displayName,
knobValues: values,
switchValues: switchValues,
@@ -44,6 +45,9 @@ extension Pedal {
/// against `displayName` — the caller is responsible for matching types before
/// calling this method.
public func applyState(_ state: PedalState) {
// Restore the saved identity so the pedal keeps its id across rebuilds; MIDI bindings
// address pedals by this id.
id = state.id
for (knob, value) in zip(knobs, state.knobValues) {
knob.node.update(value)
}
@@ -45,6 +45,6 @@ extension PedalBoard {
return BoardSegmentState.mergeToMono
}
}
return BoardState(label: label, segments: segmentStates)
return BoardState(id: id, label: label, segments: segmentStates)
}
}
@@ -42,6 +42,8 @@ public enum PedalRegistry {
"Compressor": { CompressorPedal() },
"Mutant": { MutantPedal() },
"Auto-Wah": { AutoWahPedal() },
"Wah": { WahPedal() },
"Volume": { VolumePedal() },
"Feedback Delay": { FeedbackDelayPedal() },
"Multi-Tap Delay": { MultiTapDelayPedal() },
"Octave Splitter": { OctaveUpSplitterPedal() },
@@ -50,6 +52,9 @@ public enum PedalRegistry {
"Ping-Pong": { PingPongDelayPedal() },
"Reverse Delay": { ReverseDelayPedal() },
"Shimmer Reverb": { ShimmerReverbPedal() },
"Plate Reverb": { PlateReverbPedal() },
"Room Reverb": { RoomReverbPedal() },
"Spring Reverb": { SpringReverbPedal() },
"Limiter": { LimiterPedal() },
"Noise Gate": { NoiseGatePedal() },
"Graphic EQ": { GraphicEQPedal() },
@@ -63,6 +68,7 @@ public enum PedalRegistry {
"Bitcrusher": { BitcrusherPedal() },
"Granulator": { GranulatorPedal() },
"Auto Granulator": { AutoGranulatorPedal() },
"Looper": { LooperPedal() },
]
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
@@ -4,6 +4,8 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Serialisable snapshot of one pedal's parameter values.
///
/// `type` stores the pedal's `displayName` and is used by `PedalRegistry` to
@@ -16,6 +18,12 @@
/// knobs at their current value.
public struct PedalState: Codable, Equatable {
/// Stable per-pedal identity, persisted so MIDI bindings can address a pedal by id rather
/// than by chain position. Survives capture → rebuild round-trips (an edit rebuilds the board
/// from captured segments, carrying each pedal's id forward). Legacy presets without an id
/// decode to a fresh `UUID()`.
public let id: UUID
/// The pedal's `displayName` — used as a factory key by `PedalRegistry`.
public let type: String
@@ -47,6 +55,7 @@ public struct PedalState: Codable, Equatable {
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
public init(
id: UUID = UUID(),
type: String,
knobValues: [Double],
switchValues: [Double] = [],
@@ -54,6 +63,7 @@ public struct PedalState: Codable, Equatable {
selectorValues: [Double] = [],
bypass: Double
) {
self.id = id
self.type = type
self.knobValues = knobValues
self.switchValues = switchValues
@@ -63,6 +73,7 @@ public struct PedalState: Codable, Equatable {
}
private enum CodingKeys: String, CodingKey {
case id
case type
case knobValues
case switchValues
@@ -75,6 +86,7 @@ public struct PedalState: Codable, Equatable {
/// `selectorValues` existed by defaulting the missing keys to an empty array.
public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
self.type = try container.decode(String.self, forKey: .type)
self.knobValues = try container.decode([Double].self, forKey: .knobValues)
self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? []
@@ -17,9 +17,19 @@ public enum RigStore {
private static let folderName: String = "ShoeGaze"
private static let fileName: String = "autosave-rig.json"
/// Test-only override for ``autosaveURL``. When non-`nil`, all autosave reads/writes use this
/// path instead of the real Application Support location — so a test suite never overwrites or
/// deletes the user's actual autosaved rig. Production code leaves this `nil`.
///
/// - Important: Any test that calls `save`/`restore`/`clear` **must** set this to a temporary
/// file first (and reset it after), or it will clobber the running app's autosave.
public static var autosaveURLOverride: URL?
/// Location of the autosave file, creating the containing folder if needed. `nil` if the
/// Application Support directory can't be resolved.
/// Application Support directory can't be resolved. Returns ``autosaveURLOverride`` verbatim
/// when set (tests).
public static var autosaveURL: URL? {
if let override: URL = autosaveURLOverride { return override }
let fileManager: FileManager = FileManager.default
guard let base: URL = try? fileManager.url(
for: .applicationSupportDirectory,
@@ -32,12 +42,26 @@ public enum RigStore {
return dir.appendingPathComponent(fileName)
}
/// Writes the rig's current state to the autosave file. Returns `false` on any failure.
/// The autosave file payload: the working graph plus the id of the rig-library entry it derives
/// from, written together so the two can never drift apart.
private struct AutosaveEnvelope: Codable {
let currentRigID: UUID?
let state: ShoeGazeState
}
/// Writes the rig's current state — plus its source-rig id (``ShoeGaze/currentRigID``) — 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()
let envelope: AutosaveEnvelope = AutosaveEnvelope(
currentRigID: shoeGaze.currentRigID,
state: shoeGaze.captureState()
)
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data: Data = try encoder.encode(envelope)
try data.write(to: url, options: .atomic)
return true
} catch {
@@ -46,7 +70,11 @@ public enum RigStore {
}
}
/// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet.
/// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet, and sets
/// ``ShoeGaze/currentRigID`` from the envelope so the highlight matches the restored graph.
///
/// Decodes the current envelope format; falls back to a bare `ShoeGazeState` (pre-envelope
/// autosaves), in which case `currentRigID` is left `nil`.
///
/// - 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).
@@ -56,7 +84,16 @@ public enum RigStore {
FileManager.default.fileExists(atPath: url.path) else { return false }
do {
let data: Data = try Data(contentsOf: url)
try shoeGaze.loadRig(from: data)
let decoder: JSONDecoder = JSONDecoder()
if let envelope: AutosaveEnvelope = try? decoder.decode(AutosaveEnvelope.self, from: data) {
try shoeGaze.loadRig(from: envelope.state)
shoeGaze.currentRigID = envelope.currentRigID
} else {
// Pre-envelope autosave: a bare ShoeGazeState with no recorded source rig.
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
try shoeGaze.loadRig(from: state)
shoeGaze.currentRigID = nil
}
return !shoeGaze.boards.isEmpty
} catch {
print("[RigStore] restore failed: \(error)")
@@ -59,6 +59,67 @@ extension ShoeGaze {
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments))
}
/// Inserts a pedal of the given type at `index` within a lane, shifting later pedals along.
///
/// `index` addresses the lane's own pedal order (`board.pedals` for ``PedalLane/main``; the
/// branch's pedal list for a branch lane) and follows insert-before semantics: the new pedal
/// lands immediately before the pedal currently at `index`. An `index` equal to the lane's pedal
/// count appends to the end (same placement as ``appendPedal(_:to:lane:)``). The pedal is created
/// at its constructor defaults and the board is rebuilt via ``rebuildBoard(_:from:)``.
///
/// - Important: Editing rebuilds the board through the same path as preset load; safe on a
/// running engine with at most one block of glitch (see ``rebuildBoard(_:from:)``).
///
/// - Parameters:
/// - kind: The pedal type. Its `rawValue` must be a key in `PedalRegistry.builtIn`.
/// - index: Insert-before position in the lane's pedal order. Valid range `0...laneCount`.
/// - board: The board to edit. Must have been returned by `addBoard()` on this instance.
/// - lane: Which lane to insert into. Defaults to ``PedalLane/main``.
/// - Returns: The rebuilt board occupying the same slot in `boards`.
/// - Throws: `ShoeGazeError.unknownPedalType`, `.pedalIndexOutOfRange`, `.notABranchRegion`, or
/// any error from ``rebuildBoard(_:from:)``.
@discardableResult
public func insertPedal(
_ kind: PedalType,
at index: Int,
to board: PedalBoard,
lane: PedalLane = .main
) throws -> PedalBoard {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else {
throw ShoeGazeError.unknownPedalType(type)
}
let newState: PedalState = PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0)
var segments: [BoardSegmentState] = board.captureState().segments
switch lane {
case .main:
let pedalPositions: [Int] = linearPedalSegmentIndices(segments)
guard index >= 0 && index <= pedalPositions.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: pedalPositions.count)
}
if index < pedalPositions.count {
segments.insert(.pedal(newState), at: pedalPositions[index])
} else if let lastPedalIndex: Int = pedalPositions.last {
// Inserting at the end: land right after the last linear pedal, before any trailing
// routing node — mirrors `appendPedal`'s placement rule.
segments.insert(.pedal(newState), at: lastPedalIndex + 1)
} else {
// No linear pedals at all: insert-before means the head of the chain, ahead of any
// trailing routing region (e.g. a board that is only a stereo split).
segments.insert(.pedal(newState), at: 0)
}
case .left, .right:
try mutateBranch(&segments, lane: lane) { branch in
guard index >= 0 && index <= branch.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: branch.count)
}
branch.insert(newState, at: index)
}
}
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments))
}
/// Removes the pedal at `index` within a lane.
///
/// `index` addresses the lane's own pedal order (`board.pedals` for ``PedalLane/main``; the
@@ -18,7 +18,7 @@ extension ShoeGaze {
/// - Returns: A `ShoeGazeState` reflecting the current rig.
public func captureState() -> ShoeGazeState {
let boardStates: [BoardState] = boards.map { $0.captureState() }
return ShoeGazeState(boards: boardStates)
return ShoeGazeState(boards: boardStates, midiMap: midiMap)
}
/// Captures the current rig as a named ``RigEntry`` suitable for the rig library.
@@ -95,6 +95,9 @@ extension ShoeGaze {
teardown()
try rebuildAllBoards(from: state)
// Restore the rig's MIDI bindings after the boards exist, so a MIDIController re-reading the
// map resolves against the freshly rebuilt boards.
midiMap = state.midiMap
}
/// Rebuilds every board from a snapshot with all-or-nothing semantics.
@@ -112,6 +115,7 @@ extension ShoeGaze {
do {
for boardState: BoardState in snapshot.boards {
let board: PedalBoard = try addBoard()
board.id = boardState.id
board.label = boardState.label
try rebuildSegments(boardState.segments, into: board)
try finalizeBoard(board)
@@ -257,9 +261,14 @@ extension ShoeGaze {
// can be restored. May be nil when `board` is unmanaged (not in `boards`).
let oldIndex: Int? = boards.firstIndex(where: { $0 === board })
// MIDI bindings address pedals/boards by UUID (persisted in PedalState/BoardState and
// carried through capture → rebuild), so a rebuild needs no binding reconciliation — the
// pedal keeps its id, and its binding resolves to it regardless of chain position.
// Build the new board FIRST so that any failure leaves the old board intact.
let newBoard: PedalBoard = try addBoard()
do {
newBoard.id = state.id
newBoard.label = state.label
try rebuildSegments(state.segments, into: newBoard)
try finalizeBoard(newBoard)
@@ -27,16 +27,57 @@ public struct ShoeGazeState: Codable, Equatable {
/// All board snapshots in the order they were created.
public let boards: [BoardState]
/// The rig's MIDI foot-controller bindings, or `nil` for a rig saved without any.
///
/// Optional so rigs written before MIDI mapping existed decode cleanly (the synthesized
/// `init(from:)` uses `decodeIfPresent`, yielding `nil` for the missing key) — no format
/// version bump is required for this additive field.
public let midiMap: MIDIMap?
/// Creates a rig state snapshot.
///
/// - Parameters:
/// - version: Preset format version. Defaults to `presetFormatVersion`.
/// - boards: Ordered list of board state snapshots.
/// - midiMap: The rig's MIDI bindings, or `nil` when there are none. Defaults to `nil`.
public init(
version: Int = presetFormatVersion,
boards: [BoardState]
boards: [BoardState],
midiMap: MIDIMap? = nil
) {
self.version = version
self.boards = boards
self.midiMap = midiMap
}
private enum CodingKeys: String, CodingKey {
case version
case boards
case midiMap
}
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
///
/// The MIDI map is decoded in three tiers: (1) the current id-based ``MIDIMap``; (2) failing
/// that, the pre-UUID positional ``LegacyMIDIMap``, migrated to id-based via the boards'
/// freshly-decoded ids so old rigs keep their bindings; (3) failing both (absent or unreadable),
/// `nil` — dropping just the bindings, which are re-learnable, rather than losing the whole rig.
/// `version` and `boards` still decode strictly.
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.version = try container.decode(Int.self, forKey: .version)
let decodedBoards: [BoardState] = try container.decode([BoardState].self, forKey: .boards)
self.boards = decodedBoards
if !container.contains(.midiMap) {
self.midiMap = nil
} else if let current: MIDIMap = try? container.decode(MIDIMap.self, forKey: .midiMap) {
self.midiMap = current
} else if let legacy: LegacyMIDIMap = try? container.decode(LegacyMIDIMap.self, forKey: .midiMap) {
// Pre-UUID positional map: convert each binding to the id now at that position.
self.midiMap = legacy.migrated(boards: decodedBoards)
} else {
self.midiMap = nil
}
}
}
@@ -172,7 +172,10 @@ extension ShoeGaze {
/// incorrect bus; the output track is still written.
/// - `.testLoop` → `boards.first?.headBus.index` (the first board's head bus). Returns `nil`
/// if there are no boards; the input track is skipped and a note is printed.
private func resolvedInputBusIndex() -> Int? {
/// Exposed `internal` (not `private`) so other rig-level features that need the clean
/// pre-effects input signal — e.g. `ShoeGaze+Tuner.swift` — can reuse this resolution
/// instead of duplicating the `.liveInput`/`.testLoop` switch.
internal func resolvedInputBusIndex() -> Int? {
switch inputSource {
case .liveInput(let channel):
do {
@@ -104,6 +104,9 @@ public final class ChainRouter {
private let engine: SynthesisEngine
/// Shared tempo clock, forwarded to both sub-boards so tempo-aware pedals quantize to beats.
private let clock: LyrebirdClock?
/// The shared input source (either a `TestLoopSource` or `HardwareInputPassThrough`).
private let source: any Synthesizer
@@ -152,9 +155,11 @@ public final class ChainRouter {
/// - `EngineAddError` if the engine rejects any node insertion.
public init(
engine: SynthesisEngine,
inputSource: InputSource = .testLoop
inputSource: InputSource = .testLoop,
clock: LyrebirdClock? = nil
) throws {
self.engine = engine
self.clock = clock
// Step 1 — allocate the shared input bus.
let inputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
@@ -186,8 +191,8 @@ public final class ChainRouter {
self.source = addedSource
// Step 3 — create both boards (each allocates its own head bus).
let createdBoardA: PedalBoard = try PedalBoard(engine: engine)
let createdBoardB: PedalBoard = try PedalBoard(engine: engine)
let createdBoardA: PedalBoard = try PedalBoard(engine: engine, clock: clock)
let createdBoardB: PedalBoard = try PedalBoard(engine: engine, clock: clock)
self.boardA = createdBoardA
self.boardB = createdBoardB
@@ -280,8 +285,13 @@ public final class ChainRouter {
try engine.add(builtMerger, position: .after(mergerPredecessor))
self.merger = builtMerger
// Finalize step 2 — create the output master and insert it after the merger.
let master: BoardOutputMaster = BoardOutputMaster(boardOutputBusIndex: mixBus.index)
// Finalize step 2 — create the output master and insert it after the merger. The router's
// full-bypass params are never driven (it isn't a board-bar board), so its dry source is
// the mix bus itself — the bypass crossfade is a permanent no-op here.
let master: BoardOutputMaster = BoardOutputMaster(
boardOutputBusIndex: mixBus.index,
dryInputBusIndex: mixBus.index
)
try engine.add(master, position: .after(builtMerger))
self.outputMaster = master
self.masterGainNode = master.gainNode
+213 -3
View File
@@ -60,12 +60,28 @@ public final class ShoeGaze {
/// The engine that owns all nodes.
public let engine: SynthesisEngine
/// Shared tempo clock for the tempo indicator / tap-tempo and any future
/// tempo-synced features. Default `120` BPM. `reconfigureEngine(_:)` rebuilds boards
/// against the same `engine` instance, so this clock stays valid across reconfigures.
public let clock: LyrebirdClock
/// All boards managed by this instance.
public private(set) var boards: [PedalBoard] = []
/// Input source policy. Affects how `addBoard()` routes signal to the head bus.
public var inputSource: InputSource
/// The rig's MIDI foot-controller bindings, or `nil` when none are set. Embedded in the rig
/// snapshot by `captureState()` and restored by `loadRig`, so the map travels with the rig.
/// Read and mutated by `MIDIController`; survives an input-source switch (same rig).
public var midiMap: MIDIMap?
/// The id of the rig-library entry this working session derives from, or `nil` for an unsaved
/// session. Session provenance only — NOT part of a saved/exported rig; it is written into the
/// autosave envelope (see `RigStore`) alongside the graph so the sidebar highlight and the
/// restored graph can never diverge. The UI mirrors this into the rig-library selection.
public var currentRigID: UUID?
// MARK: - Recording state
/// The folder into which `startRecording()` writes timestamped WAV files.
@@ -85,6 +101,34 @@ public final class ShoeGaze {
/// (same module, different file) can mutate it.
internal var recordTaps: [RecordTap] = []
// MARK: - Tuner state
/// `true` while the tuner is engaged (between `engageTuner()` and `disengageTuner()`).
public internal(set) var tunerEngaged: Bool = false
/// Whether ``ShoeGaze/engageTuner()`` also mutes the rig output for the duration.
/// Defaults to `true`. Read and applied only at engage time — toggling this while
/// already engaged takes effect on the next engage/disengage cycle.
public var tunerMutesRig: Bool = true
/// The active `TunerTap`, or `nil` while disengaged. `internal` so
/// `ShoeGaze+Tuner.swift` (same module, different file) can mutate it.
internal var tunerTap: TunerTap?
/// The scratch control bus allocated for `tunerTap`'s unread passthrough output,
/// released on disengage.
internal var tunerScratchControlBus: ControlBus?
/// `rigMuted`'s value at the moment `engageTuner()` muted the rig, so
/// `disengageTuner()` can restore it rather than always unmuting.
internal var tunerRestoreMuteOnDisengage: Bool = false
// MARK: - Tempo state
/// Timestamps of recent `tapTempo()` calls, oldest first. `internal` so
/// `ShoeGaze+Tempo.swift` (same module, different file) can mutate it.
internal var tapTimestamps: [Date] = []
// MARK: - Scope state
/// Scope tap over the hardware input + output buses, feeding the debug scope view.
@@ -128,11 +172,58 @@ public final class ShoeGaze {
) {
self.engine = engine
self.inputSource = inputSource
clock = LyrebirdClock(engine: engine, bpm: ShoeGaze.defaultTempoBpm)
installScopeTap()
}
// MARK: - Board management
/// Stops the audio engine as a deliberate user action: notifies every pedal via
/// ``Pedal/engineDidStop()`` (so stateful pedals like the looper return to a clean state and
/// post a notice) and then stops the engine. Use this for the user-facing Stop control — not
/// for transient stop-around-rebuild sequences, which call `engine.stop()` directly so
/// pedals keep their state across the restart.
public func stopEngine() {
for pedal: Pedal in allPedals() {
pedal.engineDidStop()
}
engine.stop()
}
/// Every live `Pedal` across all main boards and chain-router branches.
private func allPedals() -> [Pedal] {
var result: [Pedal] = []
for board: PedalBoard in boards {
result.append(contentsOf: pedals(in: board))
}
for router: ChainRouter in routers {
result.append(contentsOf: pedals(in: router.boardA))
result.append(contentsOf: pedals(in: router.boardB))
}
return result
}
/// Every live `Pedal` in one board, including pedals inside its parallel and stereo-split
/// branch sections (branch pedals live in their section objects, not as top-level segments).
private func pedals(in board: PedalBoard) -> [Pedal] {
var result: [Pedal] = []
for segment: BoardSegment in board.orderedSegments {
switch segment {
case .pedal(let pedal):
result.append(pedal)
case .parallel(let section):
result.append(contentsOf: section.branchA.pedals)
result.append(contentsOf: section.branchB.pedals)
case .stereoSplit(let section), .stereoUnzip(let section):
result.append(contentsOf: section.left.pedals)
result.append(contentsOf: section.right.pedals)
case .mergeToMono:
break
}
}
return result
}
/// Allocates a new `PedalBoard` connected to the engine, wires the input source,
/// and returns the board ready for pedals to be added via `board.add(_:)`.
///
@@ -151,7 +242,7 @@ public final class ShoeGaze {
/// - `EngineAddError` if the engine rejects a node insertion.
@discardableResult
public func addBoard() throws -> PedalBoard {
let board: PedalBoard = try PedalBoard(engine: engine)
let board: PedalBoard = try PedalBoard(engine: engine, clock: clock)
board.label = "Board \(boards.count + 1)"
// Route the input source to the board head bus.
@@ -237,7 +328,8 @@ public final class ShoeGaze {
public func finalizeBoard(_ board: PedalBoard) throws {
let master: BoardOutputMaster = BoardOutputMaster(
boardOutputBusIndex: board.outputBus.index,
boardOutputBusRightIndex: board.outputBusRight?.index
boardOutputBusRightIndex: board.outputBusRight?.index,
dryInputBusIndex: board.headBus.index
)
// The master evaluates after the entire chain (pedals, splitters, mergers).
// `board.tailNode` returns the last inserted node (any Synthesizer), which covers
@@ -256,6 +348,10 @@ public final class ShoeGaze {
board.masterGainNode = master.gainNode
board.selectGainNode = master.selectGainNode
board.crossfadeTimeNode = master.crossfadeTimeNode
board.boardBypassNode = master.boardBypassNode
board.rigBypassNode = master.rigBypassNode
board.rigVolumeNode = master.rigVolumeNode
board.rigMuteNode = master.rigMuteNode
// If a board is currently soloed, a newly-finalized board must come up silent
// (select-gain 0) so it doesn't leak audio past the active solo.
@@ -264,6 +360,15 @@ public final class ShoeGaze {
newIndex != soloIndex {
master.selectGainNode.update(0.0)
}
// A board finalized while the rig is bypassed must come up bypassed too, so it doesn't
// leak processed audio past the global bypass.
if rigBypassed {
master.rigBypassNode.update(1.0)
}
// Bring a newly-finalized board up at the current rig volume / mute.
master.rigVolumeNode.update(rigVolume)
master.rigMuteNode.update(rigMuted ? 1.0 : 0.0)
}
// MARK: - Board selection / crossfade
@@ -272,6 +377,21 @@ public final class ShoeGaze {
/// are audible (the default — every board's output sums to the hardware output).
public private(set) var activeBoardIndex: Int?
/// `true` when the whole rig is bypassed — every board passes its dry input straight through.
/// A live performance toggle (not persisted); cleared on input-source / engine rebuild.
public private(set) var rigBypassed: Bool = false
/// Rig-wide output volume in [0, 1], applied to every board's output. Survives an input-source
/// rebuild (re-applied to each rebuilt board in `finalizeBoard`).
public private(set) var rigVolume: Double = 1.0
/// `true` when the rig output is muted (hard-silenced, not bypassed). Survives a rebuild.
public private(set) var rigMuted: Bool = false
/// Identities of boards currently in per-board full bypass. Observable so UI toggles refresh;
/// authoritative bypass value lives on each board's `boardBypassNode`. Transient (not persisted).
public private(set) var bypassedBoards: Set<ObjectIdentifier> = []
/// Crossfades so only `board` is audible, fading the others out.
///
/// Sets every board's crossfade time to `crossfadeSeconds`, then ramps the selected
@@ -348,9 +468,85 @@ public final class ShoeGaze {
return (board.selectGainNode?.value ?? 0.0) > selectGainOnThreshold
}
// MARK: - Full bypass (board / rig)
/// Fully bypasses or re-engages a single board. When bypassed, the board's dry input passes
/// straight through, skipping every pedal; the board's master volume and select-gain still
/// apply. The transition is a click-free crossfade. Independent of ``setRigBypassed(_:)``.
///
/// - Parameters:
/// - board: A board managed by this instance. No-op otherwise.
/// - bypassed: `true` to bypass (dry), `false` to re-engage the pedal chain.
public func setBoard(_ board: PedalBoard, bypassed: Bool) {
guard boards.contains(where: { $0 === board }) else { return }
board.boardBypassNode?.update(bypassed ? 1.0 : 0.0)
if bypassed {
bypassedBoards.insert(ObjectIdentifier(board))
} else {
bypassedBoards.remove(ObjectIdentifier(board))
}
}
/// Whether `board` is currently in per-board full bypass.
///
/// - Parameter board: A board managed by this instance.
/// - Returns: `true` when the board's per-board bypass is engaged.
public func isBoardBypassed(_ board: PedalBoard) -> Bool {
bypassedBoards.contains(ObjectIdentifier(board))
}
/// Fully bypasses or re-engages the entire rig — every board passes its dry input straight
/// through at once. Independent of any per-board bypass (either routes a board to dry). The
/// transition is a click-free crossfade on every board.
///
/// - Parameter bypassed: `true` to bypass the whole rig, `false` to re-engage.
public func setRigBypassed(_ bypassed: Bool) {
for managed: PedalBoard in boards {
managed.rigBypassNode?.update(bypassed ? 1.0 : 0.0)
}
rigBypassed = bypassed
}
/// Toggles rig-wide full bypass. See ``setRigBypassed(_:)``.
public func toggleRigBypassed() {
setRigBypassed(!rigBypassed)
}
/// Sets the rig-wide output volume (clamped to [0, 1]), applied to every board. Smoothed per
/// board to avoid clicks.
///
/// - Parameter volume: Output volume in [0, 1].
public func setRigVolume(_ volume: Double) {
let clamped: Double = min(max(volume, 0.0), 1.0)
for managed: PedalBoard in boards {
managed.rigVolumeNode?.update(clamped)
}
rigVolume = clamped
}
/// Mutes or un-mutes the rig output — a hard gate to silence, distinct from the dry-passthrough
/// ``setRigBypassed(_:)``. Applied to every board, smoothed to avoid clicks.
///
/// - Parameter muted: `true` to silence the output, `false` to restore it.
public func setRigMuted(_ muted: Bool) {
for managed: PedalBoard in boards {
managed.rigMuteNode?.update(muted ? 1.0 : 0.0)
}
rigMuted = muted
}
/// Toggles the rig output mute. See ``setRigMuted(_:)``.
public func toggleRigMuted() {
setRigMuted(!rigMuted)
}
/// Removes a single board and its associated input source and output master from
/// the engine, then releases the board's buses. The other boards are unaffected.
///
/// > Note: MIDI bindings address boards/pedals by UUID, so a removed board's bindings simply
/// > stop resolving (inert, and invisible in the mapping UI since there is no board/pedal to
/// > list) — no binding maintenance is needed here.
///
/// - Important: Same async-removal caveat as ``teardown()`` — call with the engine
/// stopped, or accept up to one block of glitch on a still-running engine.
///
@@ -388,6 +584,7 @@ public final class ShoeGaze {
// Remove the pedals and release the board's buses.
board.teardown()
boards.remove(at: index)
bypassedBoards.remove(ObjectIdentifier(board))
// Keep the soloed-board index valid: clear it if the soloed board was removed,
// otherwise shift it down when a board before it was removed.
@@ -435,7 +632,7 @@ public final class ShoeGaze {
/// - `EngineAddError` if the engine rejects any node insertion.
@discardableResult
public func makeChainRouter() throws -> ChainRouter {
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource)
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource, clock: clock)
routers.append(router)
return router
}
@@ -488,6 +685,13 @@ public final class ShoeGaze {
// board buses they reference are released.
stopRecording()
// Notify pedals the rig is being torn down (rig load / clear / input-source change), so
// stateful pedals like the looper stop their background routines cleanly and post a
// notice before their instances are discarded.
for pedal: Pedal in allPedals() {
pedal.rigWillTeardown()
}
// Step 1: Remove all engine nodes that write to board buses.
// Order within this step does not matter; all must finish before bus release.
for tap: TestLoopTap in testLoopTaps {
@@ -531,5 +735,11 @@ public final class ShoeGaze {
router.teardown()
}
routers.removeAll()
// Live performance toggles are transient — a rebuild starts from a clean slate. Board
// identities also change across a rebuild, so the per-board bypass set would be stale.
activeBoardIndex = nil
rigBypassed = false
bypassedBoards.removeAll()
}
}
@@ -0,0 +1,55 @@
// ShoeGaze+Tempo.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - ShoeGaze + Tempo
extension ShoeGaze {
/// Default tempo, in BPM, for a newly-created ``ShoeGaze/clock``.
public static let defaultTempoBpm: Double = 120.0
// MARK: - Tap tempo
/// Minimum plausible interval between taps, in seconds — guards against a double-tap
/// or debounce glitch registering as an implausibly fast tempo (`60 / minTapInterval`
/// ≈ 300 BPM cap).
private static let minTapInterval: TimeInterval = 0.2
/// Maximum interval since the last tap before the tap history resets — a pause this
/// long means the user is starting a new tap-tempo sequence, not continuing one.
private static let tapTimeoutInterval: TimeInterval = 2.0
/// Number of most-recent inter-tap intervals averaged into the computed tempo.
private static let tapHistoryCount: Int = 4
/// Registers one tap-tempo press. Call this each time the user taps (mouse click,
/// screen tap, or MIDI trigger). Averages the last few inter-tap intervals and sets
/// ``ShoeGaze/clock``'s `bpm` once at least two taps have landed within
/// `tapTimeoutInterval` of each other. A pause longer than `tapTimeoutInterval`
/// discards prior taps and starts a fresh sequence.
public func tapTempo() {
let now: Date = Date()
if let last: Date = tapTimestamps.last, now.timeIntervalSince(last) > ShoeGaze.tapTimeoutInterval {
tapTimestamps.removeAll()
}
tapTimestamps.append(now)
if tapTimestamps.count > ShoeGaze.tapHistoryCount + 1 {
tapTimestamps.removeFirst(tapTimestamps.count - (ShoeGaze.tapHistoryCount + 1))
}
guard tapTimestamps.count >= 2 else { return }
let intervals: [TimeInterval] = zip(tapTimestamps, tapTimestamps.dropFirst())
.map { $1.timeIntervalSince($0) }
.filter { $0 >= ShoeGaze.minTapInterval }
guard !intervals.isEmpty else { return }
let averageInterval: TimeInterval = intervals.reduce(0, +) / Double(intervals.count)
let secondsPerMinute: Double = 60.0
clock.bpm = secondsPerMinute / averageInterval
}
}
@@ -0,0 +1,99 @@
// ShoeGaze+Tuner.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// MARK: - ShoeGaze + Tuner
extension ShoeGaze {
// MARK: - Engage / disengage
/// Engages the tuner: taps the clean pre-effects input and, if ``tunerMutesRig`` is on,
/// mutes the rig output for the duration (restoring the prior mute state on disengage).
///
/// A no-op if already engaged. Prints a note and does nothing if no input bus can be
/// resolved (mirrors `startRecording()`'s tolerant `.liveInput`/`.testLoop` fallback).
public func engageTuner() {
guard !tunerEngaged else { return }
guard let busIndex: Int = resolvedInputBusIndex() else {
print("[ShoeGaze] engageTuner: no input bus available — tuner not engaged.")
return
}
do {
// The scratch control bus is allocated once and kept for the session's
// lifetime rather than released on every disengage: `engine.remove(_:)` only
// enqueues the tap's removal for the next render block, so releasing (and
// thus making reallocatable) the bus synchronously here would race a
// not-yet-dequeued write from the outgoing tap.
let scratchBus: ControlBus
if let existing: ControlBus = tunerScratchControlBus {
scratchBus = existing
} else {
scratchBus = try engine.busAllocator.allocateControlBus()
tunerScratchControlBus = scratchBus
}
let tap: TunerTap = TunerTap(inputBusIndex: busIndex, scratchControlBus: scratchBus)
try engine.add(tap, position: .after(engine.mainGroup))
tunerTap = tap
} catch {
print("[ShoeGaze] engageTuner: could not add tuner tap. (\(error))")
return
}
if tunerMutesRig {
tunerRestoreMuteOnDisengage = rigMuted
setRigMuted(true)
}
tunerEngaged = true
}
/// Disengages the tuner and removes its tap. Restores the rig's prior mute state if
/// ``engageTuner()`` muted it.
///
/// The scratch control bus is intentionally NOT released here — see the comment in
/// ``engageTuner()``.
public func disengageTuner() {
guard tunerEngaged else { return }
if let tap: TunerTap = tunerTap {
_ = engine.remove(tap)
}
tunerTap = nil
if tunerMutesRig {
setRigMuted(tunerRestoreMuteOnDisengage)
}
tunerEngaged = false
}
/// Flips ``tunerEngaged`` — convenience for a single stomp-style toggle/MIDI action.
public func toggleTunerEngaged() {
if tunerEngaged {
disengageTuner()
} else {
engageTuner()
}
}
// MARK: - Live pitch read
/// The most recently detected pitch, in Hz, or `nil` while the tuner is not engaged.
/// Safe to poll from a SwiftUI `.task` loop on the main thread.
public var currentPitchHz: Double? {
guard tunerEngaged else { return nil }
return tunerTap?.pitchCapture?.detectedFrequencyHz
}
/// The YIN tracking confidence in `[0, 1]` for the current pitch, or `nil` while the
/// tuner is not engaged. `1.0` = certain, `0.0` = no stable pitch. The UI latches its
/// display when this drops below its threshold (e.g. during a note attack/restrike).
public var currentPitchConfidence: Double? {
guard tunerEngaged else { return nil }
return tunerTap?.pitchCapture?.detectedConfidence
}
}
@@ -0,0 +1,103 @@
// TunerPitchCapture.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import Synchronization
/// Wraps a YIN `FreqTracker` and atomically snapshots its per-block frequency **and
/// confidence** into plain `Double`s readable from any thread — the same RT-writes/non-RT-
/// polls contract as `ParameterNode`'s atomic value storage, sized down to two scalars.
///
/// YIN (via `FreqTracker`) is far steadier than zero-crossing detection on a plucked/
/// harmonic-rich guitar signal, and its confidence output lets the UI latch the last stable
/// reading through low-confidence transients (note attacks, restrikes) instead of ramping
/// toward the new pitch. No smoothing is applied here — the raw YIN estimate is stable
/// enough, and any smoothing would re-introduce the ramp-on-restrike the latch is meant to
/// avoid.
///
/// Bypasses the `ControlGenerator` sub-block ramp path (matching `SendTrigger.Control`'s
/// convention for side-effecting analysis generators).
final class TunerPitchCapture: GeneratorBase, ControlGenerator {
var previousOutputValue: Double = 0.0
/// Input decimation factor for the YIN tracker. Lowers the effective analysis rate so a
/// fixed 512-sample window reaches down to the low guitar / bass range. At 48 kHz, 8×
/// gives an effective 6 kHz rate → ~23 Hz detection floor. The caller (`TunerTap`) must
/// band-limit the input below the decimated Nyquist (`sampleRate / 16`) first.
static let decimation: Int = 8
/// YIN analysis window, in decimated samples (512 is `FreqTracker`'s RT-safe maximum).
private static let fftSize: Int = 512
/// Minimum tracked frequency in Hz — below standard bass E1 (≈41 Hz) for headroom.
private static let minFreqHz: Double = 38.0
/// Maximum tracked frequency in Hz — above guitar high-E (E4 ≈330 Hz) with room for
/// upper strings / light bends, and well below the decimated Nyquist.
private static let maxFreqHz: Double = 660.0
private let tracker: FreqTracker
private let _hzBits: Atomic<UInt64>
private let _confidenceBits: Atomic<UInt64>
/// The most recent tracked frequency, in Hz. Safe to read from any thread.
var detectedFrequencyHz: Double {
Double(bitPattern: _hzBits.load(ordering: .acquiring))
}
/// The most recent tracking confidence in `[0, 1]`. Safe to read from any thread.
var detectedConfidence: Double {
Double(bitPattern: _confidenceBits.load(ordering: .acquiring))
}
/// - Parameter input: Signal to analyse for pitch — must already be band-limited below
/// the decimated Nyquist (see `TunerTap`, which applies the anti-alias lowpass).
init(input: any ValidGeneratorInput) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
tracker = FreqTracker(
in: resolvedInput,
fftSize: TunerPitchCapture.fftSize,
minFreq: TunerPitchCapture.minFreqHz,
maxFreq: TunerPitchCapture.maxFreqHz,
decimation: TunerPitchCapture.decimation
)
_hzBits = Atomic(Double(0.0).bitPattern)
_confidenceBits = Atomic(Double(0.0).bitPattern)
super.init()
_setupSubBlockBuffer()
}
// Bypass sub-block loop — one capture per audio block. `FreqTracker` processes the full
// block internally (per-sample ring fill + periodic YIN hops).
func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
// `_checkCount` only bounds the top; guard the empty block so the `count - 1` last-sample
// reads below can't index `-1` (engine blockSize is ≥1 today, so this is defensive).
guard count > 0 else { return _result }
// FreqTracker is a two-channel AudioGenerator: channel 0 = Hz, channel 1 = confidence.
// Both rows are fully populated for `count` samples.
let trackerBlock: [[Double]] = tracker.calculatedSamples(graph: graph, count: count)
let hz: Double = trackerBlock[0][count - 1]
let confidence: Double = trackerBlock[1][count - 1]
_hzBits.store(hz.bitPattern, ordering: .releasing)
_confidenceBits.store(confidence.bitPattern, ordering: .releasing)
previousOutputValue = hz
for i: Int in 0..<count {
_result[0][i] = trackerBlock[0][i]
}
return _result
}
}
@@ -0,0 +1,60 @@
// TunerTap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// An internal synthesizer that taps the clean pre-effects input bus and runs a
/// `TunerPitchCapture` on it, so `ShoeGaze` can poll the current detected pitch from the
/// main thread while the tuner is engaged.
///
/// Mirrors `RecordTap`'s shape: reads one bus via `input(bus:)`, wires an analysis generator,
/// and writes to a dedicated scratch `ControlBus` purely so the engine evaluates it every
/// block — nothing downstream reads that bus.
final class TunerTap: SynthesizerBase {
/// Anti-alias lowpass cutoff, in Hz, ahead of the decimating YIN tracker. Must sit below
/// the decimated Nyquist (`sampleRate / (2 × decimation)`; ≈3 kHz at 48 kHz / 8×) so
/// decimation doesn't fold high harmonics back into the analysis band. `1200` Hz clears
/// every guitar/bass fundamental (highest is E4 ≈330 Hz) and their first harmonics — which
/// help YIN lock — while giving solid anti-alias margin.
private static let lowpassCutoffHz: Double = 1200.0
/// Butterworth Q (maximally flat, no resonant peak) for the anti-alias lowpass.
private static let lowpassQ: Double = 0.707
/// Index of the input bus to analyse.
private let inputBusIndex: Int
/// Scratch control bus the capture generator's passthrough writes to. Unread by anything
/// else — its only purpose is to give the engine a reason to evaluate the generator.
private let scratchControlBus: ControlBus
/// The pitch-capture generator created during `build()`. `nil` until `build()` has run.
private(set) var pitchCapture: TunerPitchCapture?
/// Creates a tuner tap.
///
/// - Parameters:
/// - inputBusIndex: Audio bus to analyse.
/// - scratchControlBus: A control bus reserved for this tap's unread passthrough output.
init(inputBusIndex: Int, scratchControlBus: ControlBus) {
self.inputBusIndex = inputBusIndex
self.scratchControlBus = scratchControlBus
super.init()
}
override func build() {
let source: In.Audio = input(bus: inputBusIndex)
let filtered: RBJLowPass.Audio = RBJLowPass.Audio(
input: source,
freq: TunerTap.lowpassCutoffHz,
q: TunerTap.lowpassQ
)
let capture: TunerPitchCapture = TunerPitchCapture(input: filtered)
pitchCapture = capture
output(bus: scratchControlBus, source: capture)
}
}
@@ -151,10 +151,38 @@ public struct BoardBarView: View {
.monospacedDigit()
.foregroundStyle(Color.white.opacity(BoardBarView.labelOpacity))
}
rigVolumeRow
}
.frame(width: BoardBarView.controlColumnWidth)
}
/// Rig-wide output volume + mute (applies to the whole rig, after every board).
private var rigVolumeRow: some View {
HStack(spacing: BoardBarView.cellInnerSpacing) {
Text("Vol")
.font(.caption2)
.foregroundStyle(Color.white.opacity(BoardBarView.labelOpacity))
Slider(
value: Binding(
get: { shoeGaze.rigVolume },
set: { shoeGaze.setRigVolume($0) }
),
in: 0.0 ... 1.0
)
.frame(minWidth: BoardBarView.crossfadeSliderMinWidth)
.disabled(shoeGaze.rigMuted)
Button {
shoeGaze.toggleRigMuted()
} label: {
Image(systemName: shoeGaze.rigMuted ? "speaker.slash.fill" : "speaker.wave.2.fill")
}
.buttonStyle(.bordered)
.tint(shoeGaze.rigMuted ? .red : .orange)
.help(shoeGaze.rigMuted ? "Unmute the rig output" : "Mute the rig output")
}
}
// MARK: - Board cell
@ViewBuilder
@@ -162,6 +190,7 @@ public struct BoardBarView: View {
let isEditing: Bool = index == editingBoardIndex
let isAudible: Bool = shoeGaze.isBoardAudible(board)
let isSoloed: Bool = shoeGaze.activeBoardIndex == index
let isBypassed: Bool = shoeGaze.isBoardBypassed(board)
VStack(spacing: BoardBarView.cellInnerSpacing) {
Text(boardLabel(index: index, board: board))
@@ -175,6 +204,7 @@ public struct BoardBarView: View {
HStack(spacing: BoardBarView.cellSpacing) {
ledButton(board: board, isAudible: isAudible)
soloButton(board: board, isSoloed: isSoloed)
bypassButton(board: board, isBypassed: isBypassed)
}
levelFader(board: board)
@@ -257,6 +287,25 @@ public struct BoardBarView: View {
.help("Solo this board (exclusive)")
}
/// Full-bypass footswitch — lit when this board is bypassed (dry passthrough, pedals skipped).
private func bypassButton(board: PedalBoard, isBypassed: Bool) -> some View {
Button {
shoeGaze.setBoard(board, bypassed: !isBypassed)
} label: {
Text("B")
.font(.system(size: BoardBarView.nameFontSize, weight: .bold))
.foregroundStyle(isBypassed ? Color.black : Color.white)
.frame(width: BoardBarView.soloButtonSize, height: BoardBarView.soloButtonSize)
.background(
RoundedRectangle(cornerRadius: 4)
.fill(isBypassed ? Color.orange : Color(white: BoardBarView.ledDimBrightness))
)
}
.buttonStyle(.plain)
.help(isBypassed ? "Board bypassed — tap to re-engage the pedals"
: "Bypass this board (dry passthrough)")
}
/// Board master-gain fader. Hidden until the board's output master is connected.
@ViewBuilder
private func levelFader(board: PedalBoard) -> some View {
+12 -4
View File
@@ -18,8 +18,8 @@ import LyrebirdShoeGaze
/// cached. Region segments are addressed by their index in `board.orderedSegments`.
///
/// Interaction:
/// - Drag a palette pedal (`"add:<type>"`) onto a lane to append it there; tap a palette pedal to
/// append to the main chain.
/// - Drag a palette pedal (`"add:<type>"`) onto an existing card to insert it before that card, or
/// onto empty lane space to append there; tap a palette pedal to append to the main chain.
/// - Drag a card onto another card in the same lane to reorder; the corner trash removes it.
/// - Connector lines render mono (single) or stereo (double) based on the running channel width.
///
@@ -393,7 +393,8 @@ public struct BoardFlowView: View {
dropTarget = nil
guard let payload: String = parse(items) else { return false }
if let type: String = payload.afterPrefix("add:") {
append(type: type, lane: .main)
// Dropped a palette pedal ONTO a chain card → insert before that card.
insert(type: type, at: ontoLinear, lane: .main)
return true
}
if let src: Int = payload.afterPrefix("movemain:").flatMap(Int.init) {
@@ -426,7 +427,8 @@ public struct BoardFlowView: View {
return false
}
if let type: String = payload.afterPrefix("add:") {
append(type: type, lane: lane)
// Dropped a palette pedal ONTO a branch card → insert before that card.
insert(type: type, at: ontoIndex, lane: lane)
return true
}
// Reorder within the same lane: "movebranch:<region>:<side>:<index>".
@@ -482,6 +484,12 @@ public struct BoardFlowView: View {
catch { print("[BoardFlowView] appendPedal failed: \(error)") }
}
private func insert(type: String, at index: Int, lane: PedalLane) {
guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.insertPedal(PedalType(type), at: index, to: board, lane: lane) }
catch { print("[BoardFlowView] insertPedal failed: \(error)") }
}
private func reorderMain(from source: Int, onto target: Int) {
guard source != target, let board: PedalBoard = board else { return }
// Convert "dropped ONTO the card at `target`" into movePedal's insert-before `toOffset`:
@@ -190,7 +190,7 @@ public struct EngineConfigView: View {
}
private func stopEngine() {
shoeGaze.engine.stop()
shoeGaze.stopEngine()
transportTick.toggle()
onConfigApplied()
}
+139
View File
@@ -0,0 +1,139 @@
// HelpView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
/// The in-app user guide, shared by both platforms — presented from the macOS **Help** menu (in a
/// window) and an iOS **?** button (in a sheet).
///
/// A sectioned `List` of topics: setup, the engine, input, boards & rigs, saving, iCloud, and MIDI.
/// Text + SF Symbols only for now; each topic leaves room for a bundled screenshot to be dropped in
/// later (see the commented slot in ``topicSection(icon:title:intro:steps:)``).
public struct HelpView: View {
// MARK: - Constants
private static let windowMinWidth: CGFloat = 520
private static let windowMinHeight: CGFloat = 620
private static let bulletSpacing: CGFloat = 6
// MARK: - Init
/// Creates the help view.
public init() {}
@Environment(\.dismiss) private var dismiss
// MARK: - Body
public var body: some View {
NavigationStack {
List {
topicSection(
icon: "power",
title: "Setup & Starting the Engine",
intro: "ShoeGaze runs your guitar — or a built-in test phrase — through a chain "
+ "of pedals. Configure the audio, then press Start.",
steps: [
"Set the sample Rate and the input/output channel counts in the top-right controls.",
"Press Start to run the engine; press again to Stop. Most controls stay live while running.",
"Bypass Rig compares your sound with and without the whole pedalboard.",
]
)
topicSection(
icon: "waveform",
title: "Choosing an Input",
intro: "Pick what feeds the board.",
steps: [
"Input ▸ Test Loop plays a built-in phrase, so you can hear the rig with no guitar connected.",
"Input ▸ In 0 (Live Input on iOS) uses your audio interface or mic. iOS asks for "
+ "microphone access the first time you enable it.",
]
)
topicSection(
icon: "square.stack.3d.up",
title: "Boards & Rigs",
intro: "A rig is a set of boards; a board is a chain of pedals.",
steps: [
"Drag a pedal from the palette onto the chain to add it; drop it onto a pedal to "
+ "insert before it; tap a palette pedal to append.",
"Add boards with +. Solo / Blend / All choose which boards you hear; XFade sets the "
+ "crossfade time; each board has S (solo) and B (bypass).",
"The Rigs sidebar lists saved rigs, with New, Save, Save As, Duplicate, Rename, "
+ "Delete, and Erase All.",
]
)
topicSection(
icon: "square.and.arrow.down",
title: "Saving & Autosave",
intro: "Your work is kept two ways.",
steps: [
"Save writes the current rig to the highlighted library entry; Save As creates a new one.",
"The working session autosaves continuously, so it returns on relaunch even without an "
+ "explicit Save. The sidebar highlights the rig the session came from.",
]
)
topicSection(
icon: "icloud",
title: "iCloud Documents",
intro: "Keep your rig library in sync across devices.",
steps: [
"With iCloud Drive on, saved rigs sync across your devices. The cloud icon in the Rigs "
+ "header shows the status.",
"A slashed cloud means local-only. Sign in to iCloud and turn on iCloud Drive in "
+ "Settings, then reopen ShoeGaze.",
]
)
topicSection(
icon: "pianokeys",
title: "MIDI Control",
intro: "Map a MIDI foot controller (e.g. a Behringer FCB1010) for hands-free control.",
steps: [
"The keys icon in the top bar lights green when a device is connected. Tap it to open MIDI Mapping.",
"Switches (Program Change): footswitches toggle Rig Bypass, All Boards, and each board's "
+ "Solo / Audible / Bypass or a pedal's bypass. Tap Learn, then press the footswitch. "
+ "One switch can drive several actions at once — a scene.",
"Expression (Control Change): an expression pedal sweeps any pedal knob or slider, or a "
+ "board's Level. Tap Learn, then move the pedal. Invert reverses the sweep — map one "
+ "CC to two controls and invert one for a crossfade.",
]
)
}
.navigationTitle("ShoeGaze Help")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") { dismiss() }
}
}
}
.frame(minWidth: HelpView.windowMinWidth, minHeight: HelpView.windowMinHeight)
}
// MARK: - Topic section
private func topicSection(
icon: String,
title: String,
intro: String,
steps: [String]
) -> some View {
Section {
Text(intro)
.font(.subheadline)
ForEach(steps, id: \.self) { step in
HStack(alignment: .firstTextBaseline, spacing: HelpView.bulletSpacing) {
Text("•")
Text(step)
}
.font(.callout)
}
// Screenshot slot: Image("help-\(icon)", bundle: .module).resizable().scaledToFit()
// once captures are added to a Resources.xcassets on this target.
} header: {
Label(title, systemImage: icon)
}
}
}
@@ -0,0 +1,239 @@
// LooperTimelineView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// The looper's loop timeline: a transport-state badge, tappable A–D track dots, a loop-length
/// read-out, a sweeping play-head track, and a one-line state indicator describing what the
/// pedal is doing. Rendered inside the double-width ``PedalView`` for a `LooperPedal`.
///
/// `LooperPedal`'s transport state is plain (non-`@Observable`) RT-adjacent data, so this view
/// polls it on a `.task` loop — the same convention as `TempoView`'s clock read-out.
struct LooperTimelineView: View {
// MARK: - Constants
private static let trackHeight: CGFloat = 16
private static let trackCornerRadius: CGFloat = 4
private static let playheadWidth: CGFloat = 2
private static let sectionSpacing: CGFloat = 6
private static let labelFontSize: CGFloat = 11
private static let trackBrightness: Double = 0.14
private static let trackBorderOpacity: Double = 0.35
private static let filledOpacity: Double = 0.22
private static let pollIntervalNanoseconds: UInt64 = 33_000_000 // ~30 Hz
private static let ledDiameter: CGFloat = 9
private static let badgeInnerSpacing: CGFloat = 4
private static let lengthLabelOpacity: Double = 0.75
private static let borderLineWidth: CGFloat = 1
private static let dotSpacing: CGFloat = 4
private static let dotDiameter: CGFloat = 18
private static let dotLabelFontSize: CGFloat = 10
private static let dotBrightness: Double = 0.16
private static let selectedDotBrightness: Double = 0.32
private static let dotFilledOpacity: Double = 0.55
private static let dotEmptyOpacity: Double = 0.45
private static let activeRingWidth: CGFloat = 1.5
private static let mutedDotOpacity: Double = 0.4
private static let muteSlashOpacity: Double = 0.9
private static let muteSlashWidth: CGFloat = 1.5
private static let indicatorFontSize: CGFloat = 11
private static let indicatorOpacity: Double = 0.85
private static let overdubRingColor: Color = Color.red
private static let dotLabels: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
// MARK: - Properties
private let pedal: LooperPedal
@State private var position: Double?
@State private var state: LooperTransportState = .clear
@State private var lengthSeconds: Double = 0.0
@State private var lengthBeats: Double = 0.0
@State private var selectedTrack: Int = 0
@State private var overdubbingTrack: Int?
@State private var trackContent: [Bool] = Array(repeating: false, count: LooperPedal.trackCount)
@State private var trackMuted: [Bool] = Array(repeating: false, count: LooperPedal.trackCount)
@State private var stopArmed: Bool = false
@State private var stateDescription: String = ""
init(pedal: LooperPedal) {
self.pedal = pedal
}
// MARK: - Body
var body: some View {
VStack(spacing: LooperTimelineView.sectionSpacing) {
HStack(spacing: LooperTimelineView.sectionSpacing) {
stateBadge
Spacer(minLength: 0)
trackDots
Spacer(minLength: 0)
lengthLabel
}
track
stateIndicator
}
// Key the poll on the pedal instance: if a rig load / rebuild swaps in a new LooperPedal,
// `.task` alone would keep polling the old (captured) instance and freeze. Restart on change.
.task(id: ObjectIdentifier(pedal)) {
while !Task.isCancelled {
position = pedal.playbackPosition01()
state = pedal.transportState
lengthSeconds = pedal.loopLengthSeconds
lengthBeats = pedal.loopLengthBeats
selectedTrack = pedal.selectedTrackIndex
overdubbingTrack = pedal.overdubbingTrackIndex
trackContent = (0 ..< LooperPedal.trackCount).map { pedal.trackHasContent($0) }
trackMuted = (0 ..< LooperPedal.trackCount).map { pedal.isTrackMuted($0) }
stopArmed = pedal.isStopAtLoopEndArmed
stateDescription = pedal.stateDescription
try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds)
}
}
}
// MARK: - Subviews
/// One tappable labelled dot per track: filled when it holds a loop, white-ringed when
/// selected, red-ringed while overdubbing, dimmed with a slash when muted. Tapping selects the
/// track; tapping the already-selected recorded track mutes/unmutes it.
private var trackDots: some View {
HStack(spacing: LooperTimelineView.dotSpacing) {
ForEach(0 ..< LooperPedal.trackCount, id: \.self) { index in
let isSelected: Bool = index == selectedTrack
let isOverdub: Bool = index == overdubbingTrack
let hasContent: Bool = index < trackContent.count && trackContent[index]
let isMuted: Bool = index < trackMuted.count && trackMuted[index]
Button {
pedal.tapTrack(index)
} label: {
Text(LooperTimelineView.dotLabels[index])
.font(.system(size: LooperTimelineView.dotLabelFontSize, weight: .bold, design: .monospaced))
// Selected (or recorded) tracks show a bright letter; other empty tracks dim.
.foregroundStyle((hasContent || isSelected) ? Color.white : Color.white.opacity(LooperTimelineView.dotEmptyOpacity))
.frame(width: LooperTimelineView.dotDiameter, height: LooperTimelineView.dotDiameter)
.background(
Circle().fill(hasContent ? Color.green.opacity(LooperTimelineView.dotFilledOpacity)
: (isSelected ? Color(white: LooperTimelineView.selectedDotBrightness)
: Color(white: LooperTimelineView.dotBrightness)))
)
.overlay(muteSlash(isMuted))
.overlay(
Circle().stroke(isOverdub ? LooperTimelineView.overdubRingColor
: (isSelected ? Color.white : Color.clear),
lineWidth: LooperTimelineView.activeRingWidth)
)
.opacity(isMuted ? LooperTimelineView.mutedDotOpacity : 1.0)
}
.buttonStyle(.plain)
}
}
}
/// A diagonal slash drawn over a muted track's dot.
@ViewBuilder
private func muteSlash(_ muted: Bool) -> some View {
if muted {
GeometryReader { geometry in
Path { path in
path.move(to: CGPoint(x: 0, y: geometry.size.height))
path.addLine(to: CGPoint(x: geometry.size.width, y: 0))
}
.stroke(Color.white.opacity(LooperTimelineView.muteSlashOpacity),
lineWidth: LooperTimelineView.muteSlashWidth)
}
}
}
private var stateBadge: some View {
HStack(spacing: LooperTimelineView.badgeInnerSpacing) {
Circle()
.fill(stateColor)
.frame(width: LooperTimelineView.ledDiameter, height: LooperTimelineView.ledDiameter)
Text(stateText)
.font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.white)
if stopArmed {
Text("→END")
.font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.orange)
}
}
}
private var lengthLabel: some View {
Text(lengthText)
.font(.system(size: LooperTimelineView.labelFontSize, design: .monospaced))
.foregroundStyle(Color.white.opacity(LooperTimelineView.lengthLabelOpacity))
}
/// One-line description of what the pedal is doing now — replaces the old action-button row.
private var stateIndicator: some View {
Text(stateDescription)
.font(.system(size: LooperTimelineView.indicatorFontSize, weight: .medium))
.foregroundStyle(Color.white.opacity(LooperTimelineView.indicatorOpacity))
.frame(maxWidth: .infinity, alignment: .leading)
}
private var track: some View {
GeometryReader { geometry in
let width: CGFloat = geometry.size.width
let pos: CGFloat = CGFloat(position ?? 0.0)
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
.fill(Color(white: LooperTimelineView.trackBrightness))
.overlay(
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
.stroke(Color.white.opacity(LooperTimelineView.trackBorderOpacity),
lineWidth: LooperTimelineView.borderLineWidth)
)
if position != nil {
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
.fill(Color.white.opacity(LooperTimelineView.filledOpacity))
.frame(width: max(0, pos * width))
Rectangle()
.fill(Color.white)
.frame(width: LooperTimelineView.playheadWidth)
.offset(x: min(max(0, pos * width), width - LooperTimelineView.playheadWidth))
}
}
}
.frame(height: LooperTimelineView.trackHeight)
}
// MARK: - State mapping
private var stateColor: Color {
switch state {
case .clear: return Color(white: 0.3)
case .armedRecord, .armedClose: return Color.orange
case .recordingMaster: return Color.red
case .playing: return Color.green
case .stopped: return Color.orange
}
}
private var stateText: String {
switch state {
case .clear: return "CLEAR"
case .armedRecord: return "ARM"
case .recordingMaster: return "REC"
case .armedClose: return "END"
case .playing: return "PLAY"
case .stopped: return "STOP"
}
}
private var lengthText: String {
guard lengthSeconds > 0 else { return "--" }
let seconds: String = String(format: "%.2fs", lengthSeconds)
guard lengthBeats > 0 else { return seconds }
return seconds + " · \(Int(lengthBeats)) beat" + (lengthBeats == 1 ? "" : "s")
}
}
@@ -0,0 +1,64 @@
// MIDIIndicatorView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// A compact transport-row indicator showing whether a MIDI device is connected.
///
/// Green when at least one input source is present, gray otherwise; a badge shows the count when
/// more than one device is connected. Tapping invokes `onTap` (the host presents the MIDI mapping
/// sheet). Observes the `@Observable` ``MIDIController`` so it refreshes automatically as devices
/// connect and disconnect.
public struct MIDIIndicatorView: View {
// MARK: - Constants
private static let iconSize: CGFloat = 13
private static let spacing: CGFloat = 3
private static let badgeFontSize: CGFloat = 10
private static let disconnectedOpacity: Double = 0.5
// MARK: - Inputs
private let controller: MIDIController
private let onTap: () -> Void
/// Creates a MIDI connection indicator.
///
/// - Parameters:
/// - controller: The MIDI controller whose connection state is displayed.
/// - onTap: Invoked when the indicator is tapped (present the MIDI mapping sheet). Defaults to
/// a no-op.
public init(controller: MIDIController, onTap: @escaping () -> Void = {}) {
self.controller = controller
self.onTap = onTap
}
// MARK: - Body
public var body: some View {
let connected: Bool = controller.isConnected
return Button(action: onTap) {
HStack(spacing: MIDIIndicatorView.spacing) {
Image(systemName: connected ? "pianokeys" : "pianokeys.inverse")
.font(.system(size: MIDIIndicatorView.iconSize))
.foregroundStyle(connected
? Color.green
: Color.white.opacity(MIDIIndicatorView.disconnectedOpacity))
if controller.connectedDeviceNames.count > 1 {
Text("\(controller.connectedDeviceNames.count)")
.font(.system(size: MIDIIndicatorView.badgeFontSize, weight: .semibold).monospacedDigit())
.foregroundStyle(Color.green)
}
}
}
.buttonStyle(.plain)
.help(connected
? "MIDI connected: \(controller.connectedDeviceNames.joined(separator: ", "))"
: "No MIDI device detected")
}
}
@@ -0,0 +1,274 @@
// MIDIMappingSheet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
import LyrebirdUI
/// The MIDI mapping panel: shows connected devices and lets the user bind expression-pedal CCs to
/// pedal knobs via MIDI Learn.
///
/// Presented from the transport-row ``MIDIIndicatorView``. Rows are generated by walking the live
/// `ShoeGaze.boards` / `board.pedals` and each pedal's controls, so bindings address controls
/// positionally. A Switches section binds Program Change to toggle actions; an Expression section
/// binds Control Change to continuous pedal controls.
public struct MIDIMappingSheet: View {
// MARK: - Constants
private static let sheetMinWidth: CGFloat = 460
private static let sheetMinHeight: CGFloat = 520
private static let rowVerticalPadding: CGFloat = 2
// MARK: - Inputs
private let controller: MIDIController
private let shoeGaze: ShoeGaze
@Environment(\.dismiss) private var dismiss
/// Creates a MIDI mapping sheet.
///
/// - Parameters:
/// - controller: The MIDI controller that owns the connection, learn state, and bindings.
/// - shoeGaze: The rig whose boards / pedals / knobs are enumerated as binding targets.
public init(controller: MIDIController, shoeGaze: ShoeGaze) {
self.controller = controller
self.shoeGaze = shoeGaze
}
// MARK: - Body
public var body: some View {
NavigationStack {
List {
devicesSection
switchesSection
expressionSection
}
.navigationTitle("MIDI Mapping")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") {
controller.cancelLearn()
dismiss()
}
}
}
}
.frame(minWidth: MIDIMappingSheet.sheetMinWidth, minHeight: MIDIMappingSheet.sheetMinHeight)
}
// MARK: - Devices
private var devicesSection: some View {
Section("Devices") {
if controller.isConnected {
ForEach(controller.connectedDeviceNames, id: \.self) { name in
Label(name, systemImage: "pianokeys")
.foregroundStyle(Color.green)
}
} else {
Label("No MIDI device detected", systemImage: "pianokeys.inverse")
.foregroundStyle(.secondary)
}
}
}
// MARK: - Row models
/// A Program-Change switch row: a toggle action + its display label. `id` is globally unique so
/// SwiftUI never reuses a row view across the two sections (which would leak the wrong Learn
/// action into a row).
private struct SwitchRowModel: Identifiable {
let id: String
let action: MIDIMap.Action
let label: String
}
/// A Control-Change row: a continuous target (address-only, hints `nil`) + its display label.
private struct CCRowModel: Identifiable {
let id: String
let target: MIDIMap.CCTarget
let label: String
}
private var switchRowModels: [SwitchRowModel] {
var rows: [SwitchRowModel] = [
SwitchRowModel(id: "sw-rig", action: .rigBypass, label: "Rig Bypass"),
SwitchRowModel(id: "sw-mute", action: .rigMute, label: "Rig Mute"),
SwitchRowModel(id: "sw-all", action: .allBoards, label: "All Boards On"),
]
for board: PedalBoard in shoeGaze.boards {
let boardID: UUID = board.id
rows.append(SwitchRowModel(id: "sw-solo-\(boardID)",
action: .boardSolo(boardID: boardID),
label: "\(board.label) · Solo"))
rows.append(SwitchRowModel(id: "sw-aud-\(boardID)",
action: .boardAudible(boardID: boardID),
label: "\(board.label) · Audible"))
rows.append(SwitchRowModel(id: "sw-byp-\(boardID)",
action: .boardBypass(boardID: boardID),
label: "\(board.label) · Bypass"))
for pedal: Pedal in board.pedals {
rows.append(SwitchRowModel(
id: "sw-pb-\(pedal.id)",
action: .pedalBypass(pedalID: pedal.id),
label: "\(board.label) · \(pedal.displayName) · Bypass"))
// Loopers expose their transport footswitches as mappable switch actions.
if pedal is LooperPedal {
var looperActions: [(String, String, MIDIMap.PedalActionKind)] = [
("rec", "Record", .looperRecordStop),
("stop", "Stop", .looperStop),
("cue", "Cue Stop", .looperCueStop),
("rev", "Reverse", .looperReverse),
("sync", "Sync", .looperSyncToggle),
("reset", "Reset", .looperReset),
]
// A/B/C/D track taps (select / mute), matching the timeline dots.
for i: Int in 0 ..< LooperPedal.trackCount {
let letter: String = LooperPedal.trackLabel(i)
looperActions.append(("track\(letter)", "Track \(letter)", .looperTrack(index: i)))
}
for (slug, name, kind): (String, String, MIDIMap.PedalActionKind) in looperActions {
rows.append(SwitchRowModel(
id: "sw-la-\(slug)-\(pedal.id)",
action: .pedalAction(pedalID: pedal.id, kind: kind),
label: "\(board.label) · \(pedal.displayName) · \(name)"))
}
}
}
}
return rows
}
private var ccRowModels: [CCRowModel] {
var rows: [CCRowModel] = [
CCRowModel(id: "cc-rigvol", target: .rigVolume, label: "Rig · Volume"),
]
for board: PedalBoard in shoeGaze.boards {
// Board master level (the board fader).
rows.append(CCRowModel(
id: "cc-blvl-\(board.id)",
target: .boardLevel(boardID: board.id, boardLabelHint: nil),
label: "\(board.label) · Level"))
for pedal: Pedal in board.pedals {
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
rows.append(CCRowModel(
id: "cc-\(pedal.id)-\(controlPair.offset)",
target: .pedalControl(
pedalID: pedal.id,
controlIndex: controlPair.offset,
pedalNameHint: nil,
controlLabelHint: nil),
label: "\(pedal.displayName) · \(controlPair.element.label)"))
}
}
}
return rows
}
// MARK: - Switches (Program Change)
private var switchesSection: some View {
Section("Switches (Program Change)") {
ForEach(switchRowModels) { row in
switchRow(row)
}
}
}
private func switchRow(_ row: SwitchRowModel) -> some View {
let isArmed: Bool = controller.learnTarget == .action(row.action)
let binding: MIDIMap.SwitchBinding? = controller.switchBinding(for: row.action)
return HStack {
VStack(alignment: .leading, spacing: 1) {
Text(row.label)
Text(switchBindingLabel(isArmed: isArmed, binding: binding))
.font(.caption)
.foregroundStyle(isArmed ? Color.orange : .secondary)
}
Spacer()
if binding != nil {
Button("Clear") { controller.clearSwitchBinding(for: row.action) }
.buttonStyle(.borderless)
}
Button(isArmed ? "Cancel" : "Learn") {
if isArmed {
controller.cancelLearn()
} else {
controller.armSwitchLearn(row.action)
}
}
.buttonStyle(.bordered)
.tint(.orange)
}
.padding(.vertical, MIDIMappingSheet.rowVerticalPadding)
}
private func switchBindingLabel(isArmed: Bool, binding: MIDIMap.SwitchBinding?) -> String {
if isArmed { return "Listening — press a footswitch…" }
guard let binding: MIDIMap.SwitchBinding = binding else { return "Unassigned" }
let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? ""
return "PC \(binding.program)\(channelText)"
}
// MARK: - Expression (CC)
private var expressionSection: some View {
Section("Expression (Control Change)") {
if shoeGaze.boards.isEmpty {
Text("Add a pedal to assign expression control.")
.foregroundStyle(.secondary)
}
ForEach(ccRowModels) { row in
ccRow(row)
}
}
}
private func ccRow(_ row: CCRowModel) -> some View {
let isArmed: Bool = controller.learnTarget == .cc(row.target)
let binding: MIDIMap.CCBinding? = controller.ccBinding(for: row.target)
return HStack {
VStack(alignment: .leading, spacing: 1) {
Text(row.label)
Text(ccBindingLabel(isArmed: isArmed, binding: binding))
.font(.caption)
.foregroundStyle(isArmed ? Color.orange : .secondary)
}
Spacer()
if binding != nil {
Toggle("Invert", isOn: Binding(
get: { controller.isCCInverted(for: row.target) },
set: { controller.setCCInverted(for: row.target, $0) }
))
.toggleStyle(.button)
.tint(.orange)
Button("Clear") { controller.clearCCBinding(for: row.target) }
.buttonStyle(.borderless)
}
Button(isArmed ? "Cancel" : "Learn") {
if isArmed {
controller.cancelLearn()
} else {
controller.armCCLearn(row.target)
}
}
.buttonStyle(.bordered)
.tint(.orange)
}
.padding(.vertical, MIDIMappingSheet.rowVerticalPadding)
}
private func ccBindingLabel(isArmed: Bool, binding: MIDIMap.CCBinding?) -> String {
if isArmed { return "Listening — move an expression pedal…" }
guard let binding: MIDIMap.CCBinding = binding else { return "Unassigned" }
let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? ""
let invertText: String = binding.inverted ? " · inverted" : ""
return "CC \(binding.controller)\(channelText)\(invertText)"
}
}
@@ -0,0 +1,106 @@
// PedalButtonView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdUI
import LyrebirdShoeGaze
// MARK: - PedalButtonView
/// A stomp-style action button rendered from a ``PedalButton`` descriptor.
///
/// `.momentary` renders a plain `ParameterButton`. `.toggle` renders the same LED +
/// footswitch look as the pedal's own bypass control (`PedalView`'s `LEDIndicator` /
/// `FootswitchButton`), with a caption label beneath — so a looper's Overdub/Loop toggles
/// read as stomp switches with state, not a segmented picker.
///
/// ## Usage
/// ```swift
/// PedalButtonView(pedalButton)
/// ```
public struct PedalButtonView: View {
private static let toggleOnThreshold: Double = 0.5
private static let sectionSpacing: CGFloat = 6
private static let captionFontSize: CGFloat = 11
private let pedalButton: PedalButton
/// Creates a button view from a descriptor.
///
/// - Parameter pedalButton: The button to render.
public init(_ pedalButton: PedalButton) {
self.pedalButton = pedalButton
}
public var body: some View {
switch pedalButton.style {
case .momentary:
if let indicator: UIParamNode = pedalButton.indicator {
// LED + footswitch, same look as a toggle, but the press runs an action and the
// LED reflects a separate state node (e.g. Stop lit while stopped). Reading
// `indicator.value` registers this view for @Observable re-render.
let isOn: Bool = indicator.value >= PedalButtonView.toggleOnThreshold
VStack(spacing: PedalButtonView.sectionSpacing) {
LEDIndicator(isOn: isOn)
FootswitchButton(action: pedalButton.action ?? {})
caption
}
} else {
ParameterButton(pedalButton.label, action: pedalButton.action ?? {})
}
case .toggle:
if let node: UIParamNode = pedalButton.node {
// Reading `node.value` registers this view for @Observable re-render.
let isOn: Bool = node.value >= PedalButtonView.toggleOnThreshold
VStack(spacing: PedalButtonView.sectionSpacing) {
LEDIndicator(isOn: isOn)
FootswitchButton(node: node)
caption
}
}
}
}
/// The button caption — a live "what the next press does" label when the descriptor supplies
/// a `dynamicLabel`, otherwise the static label.
@ViewBuilder
private var caption: some View {
if let provider: () -> String = pedalButton.dynamicLabel {
DynamicCaption(provider: provider, fallback: pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
} else {
Text(pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
}
}
}
// MARK: - DynamicCaption
/// A caption that polls a text provider (RT-adjacent pedal state that isn't `@Observable`), on
/// the same `.task` cadence as the looper timeline, so a state-driven button label stays current.
private struct DynamicCaption: View {
private static let pollIntervalNanoseconds: UInt64 = 33_000_000 // ~30 Hz
let provider: () -> String
let fallback: String
@State private var text: String = ""
var body: some View {
Text(text.isEmpty ? fallback : text)
.task {
while !Task.isCancelled {
text = provider()
try? await Task.sleep(nanoseconds: DynamicCaption.pollIntervalNanoseconds)
}
}
}
}
@@ -42,15 +42,16 @@ enum PedalCategory: String, CaseIterable, Identifiable {
}
private static let mapping: [String: PedalCategory] = [
"Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain,
"Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain, "Volume": .gain,
"Compressor": .dynamics, "Sustainer": .dynamics, "Limiter": .dynamics, "Noise Gate": .dynamics,
"Graphic EQ": .filter, "Auto-Wah": .filter, "Mutant": .filter,
"Graphic EQ": .filter, "Auto-Wah": .filter, "Wah": .filter, "Mutant": .filter,
"Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation,
"Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation,
"Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch,
"Delay": .delay, "Feedback Delay": .delay, "Multi-Tap Delay": .delay, "Ping-Pong": .delay,
"Reverse Delay": .delay,
"Reverb": .reverb, "Shimmer Reverb": .reverb,
"Plate Reverb": .reverb, "Room Reverb": .reverb, "Spring Reverb": .reverb,
"Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture,
]
}
@@ -55,11 +55,12 @@ public struct PedalPaletteView: View {
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
private static let preferredOrder: [String] = [
"Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
"Volume",
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator",
"Auto-Wah", "Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator",
"Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer",
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
"Shimmer Reverb",
"Shimmer Reverb", "Plate Reverb", "Room Reverb", "Spring Reverb",
]
/// Routing/branching topologies the user can insert into the board.
@@ -123,6 +124,17 @@ public struct PedalPaletteView: View {
return orderedPedalNames.filter { PedalCategory.category(for: $0) == filter }
}
/// Visible pedals bucketed by category, in the same order the filter menu lists them
/// (`PedalCategory.allCases`). Within a bucket the preferred order is preserved; empty
/// buckets are dropped so the picker shows only categories that have visible pedals.
private var groupedVisiblePedals: [(category: PedalCategory, names: [String])] {
let visible: [String] = visiblePedalNames
return PedalCategory.allCases.compactMap { category in
let names: [String] = visible.filter { PedalCategory.category(for: $0) == category }
return names.isEmpty ? nil : (category, names)
}
}
// MARK: - Body
public var body: some View {
@@ -159,13 +171,20 @@ public struct PedalPaletteView: View {
/// row stacked beneath it.
private var horizontalBody: some View {
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
HStack(alignment: .top, spacing: PedalPaletteView.sectionSpacing) {
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
sectionTitle("PEDALS")
filterMenu
}
ForEach(visiblePedalNames, id: \.self) { name in
pedalRow(name)
ForEach(groupedVisiblePedals, id: \.category) { group in
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
categoryLabel(group.category)
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
ForEach(group.names, id: \.self) { name in
pedalRow(name)
}
}
}
}
}
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
@@ -185,6 +204,14 @@ public struct PedalPaletteView: View {
.foregroundStyle(Color.white.opacity(PedalPaletteView.titleOpacity))
}
/// A per-group header in the horizontal picker — the category name tinted in its accent colour.
private func categoryLabel(_ category: PedalCategory) -> some View {
Text(category.rawValue.uppercased())
.font(.system(size: PedalPaletteView.titleFontSize, weight: .semibold))
.foregroundStyle(category.color.opacity(0.9))
.lineLimit(1)
}
/// "Filter by type" menu — defaults to **All** (no filtering).
private var filterMenu: some View {
Menu {
@@ -201,8 +228,10 @@ public struct PedalPaletteView: View {
.font(.system(size: PedalPaletteView.titleFontSize))
.foregroundStyle((filter?.color ?? Color.white).opacity(0.9))
}
#if os(macOS)
.menuStyle(.borderlessButton)
.fixedSize()
#endif
}
/// A full-width pedal row: tap appends to the main chain; drag carries `"add:<name>"` so it can
+104 -30
View File
@@ -21,6 +21,9 @@ private func enclosureColor(for displayName: String) -> Color {
case "Delay": return Color(red: 0.10, green: 0.55, blue: 0.55) // teal
case "Reverb": return Color(red: 0.30, green: 0.18, blue: 0.65) // indigo
case "Shimmer Reverb": return Color(red: 0.46, green: 0.52, blue: 0.78) // icy periwinkle
case "Plate Reverb": return Color(red: 0.26, green: 0.30, blue: 0.60) // deep slate blue
case "Room Reverb": return Color(red: 0.24, green: 0.40, blue: 0.66) // ocean blue
case "Spring Reverb": return Color(red: 0.20, green: 0.46, blue: 0.64) // steel cyan
case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green
case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson
case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue
@@ -28,6 +31,8 @@ private func enclosureColor(for displayName: String) -> Color {
case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green
case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum
case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold
case "Wah": return Color(red: 0.72, green: 0.50, blue: 0.06) // amber gold
case "Volume": return Color(red: 0.30, green: 0.30, blue: 0.34) // graphite
case "Feedback Delay": return Color(red: 0.48, green: 0.30, blue: 0.14) // tape sepia
case "Multi-Tap Delay": return Color(red: 0.08, green: 0.48, blue: 0.68) // cyan
case "Reverse Delay": return Color(red: 0.10, green: 0.44, blue: 0.60) // deep cyan-teal
@@ -85,9 +90,11 @@ private struct ScrewDot: View {
/// A small circular LED that glows green when the effect is engaged.
///
/// Bypass polarity: `0` = engaged (effect ON), `1` = bypassed.
/// The LED is lit when `bypassValue < 0.5`.
private struct LEDIndicator: View {
/// A small round LED, lit green when `isOn` and dark otherwise. Polarity-agnostic — the
/// caller decides what `isOn` means for its own control (e.g. bypass's `value < 0.5`, or a
/// plain toggle's `value >= 0.5`). `internal` (not `private`) so other views in this module
/// (e.g. `PedalButtonView`) can reuse the same stompbox LED look.
struct LEDIndicator: View {
private static let diameter: CGFloat = 10
private static let glowRadius: CGFloat = 6
@@ -96,13 +103,11 @@ private struct LEDIndicator: View {
private static let dimBrightness: Double = 0.15
private static let rimStrokeOpacity: Double = 0.30
let bypassValue: Double
private var isEngaged: Bool { bypassValue < 0.5 }
let isOn: Bool
var body: some View {
ZStack {
if isEngaged {
if isOn {
Circle()
.fill(Color.green.opacity(LEDIndicator.glowOpacity))
.frame(
@@ -112,7 +117,7 @@ private struct LEDIndicator: View {
.blur(radius: LEDIndicator.glowRadius / 2)
}
Circle()
.fill(isEngaged ? Color.green : Color(white: LEDIndicator.dimBrightness))
.fill(isOn ? Color.green : Color(white: LEDIndicator.dimBrightness))
.frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter)
.overlay(
Circle()
@@ -127,8 +132,11 @@ private struct LEDIndicator: View {
// MARK: - Footswitch
/// A round footswitch-style button that toggles bypass on/off.
private struct FootswitchButton: View {
/// A round footswitch-style button. Either flips a bound `UIParamNode` between `0` and `1`
/// (toggle) or runs an arbitrary action (momentary) — both render the identical stompbox look.
/// `internal` (not `private`) so other views in this module (e.g. `PedalButtonView`) can reuse
/// it for non-bypass toggles and momentary stomp actions.
struct FootswitchButton: View {
private static let diameter: CGFloat = 44
private static let strokeWidth: CGFloat = 2.5
@@ -137,14 +145,23 @@ private struct FootswitchButton: View {
private static let ringBrightness: Double = 0.50
private static let innerFillBrightness: Double = 0.25
let node: UIParamNode
private let action: () -> Void
/// Flips `node` between `0` and `1` on each press.
init(node: UIParamNode) {
self.action = {
let engaged: Bool = node.value < 0.5
node.update(engaged ? 1.0 : 0.0)
}
}
/// Runs `action` on each press (momentary).
init(action: @escaping () -> Void) {
self.action = action
}
var body: some View {
Button(action: {
let engaged: Bool = node.value < 0.5
// Toggle: engaged (0) → bypassed (1) and vice-versa.
node.update(engaged ? 1.0 : 0.0)
}) {
Button(action: action) {
ZStack {
Circle()
.fill(Color(white: FootswitchButton.outerFillBrightness))
@@ -200,6 +217,8 @@ public struct PedalView: View {
private static let enclosurePadding: CGFloat = 14
private static let screwInset: CGFloat = 6
private static let knobColumnCount: Int = 3
/// Knob columns for a double-width pedal card (fits a four-knob effect bank on one row).
private static let wideKnobColumnCount: Int = 4
private static let knobSpacing: CGFloat = 10
/// Horizontal gap between knobs within a row. Wider than `knobSpacing` so centred
/// rows keep a comfortable, touch-friendly gap between adjacent knobs.
@@ -286,9 +305,15 @@ public struct PedalView: View {
// Content stack
VStack(spacing: PedalView.sectionSpacing) {
namePlate
looperTimeline
knobGrid
selectorRow
switchRow
// Keyed on the pedal instance so the buttons' live captions (which poll the pedal
// via `.task`) re-subscribe when a rig load / rebuild swaps in a new pedal instance.
transportButtonRow
.id(ObjectIdentifier(pedal))
buttonRow
sliderBank(sliders)
Spacer(minLength: 0)
bottomControls
@@ -329,6 +354,15 @@ public struct PedalView: View {
.clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius))
}
/// Loop timeline strip — rendered only for the double-width `LooperPedal`, between the
/// name plate and the knob grid. Other pedals render nothing here.
@ViewBuilder
private var looperTimeline: some View {
if let looper: LooperPedal = pedal as? LooperPedal {
LooperTimelineView(pedal: looper)
}
}
/// Info button tucked just under the top-left corner screw.
private var infoButton: some View {
Button {
@@ -349,24 +383,25 @@ public struct PedalView: View {
/// `Level` on the left, `Mix` on the right — leaving more room for the effect controls
/// at the top and giving every pedal a symmetric footer.
private var knobGrid: some View {
// Wide (double-width) pedals fit four knobs across, so a four-knob effect bank (e.g.
// the looper's Crossfade / Playback / Overdub / Feedback) sits on one row.
let columns: Int = pedal.widthUnits >= 2 ? PedalView.wideKnobColumnCount : PedalView.knobColumnCount
let knobs: [PedalKnob] = Array(pedal.knobs.dropLast(2))
let rows: [[PedalKnob]] = stride(
from: 0,
to: knobs.count,
by: PedalView.knobColumnCount
by: columns
).map { startIndex in
Array(knobs[startIndex ..< min(startIndex + PedalView.knobColumnCount, knobs.count)])
Array(knobs[startIndex ..< min(startIndex + columns, knobs.count)])
}
return VStack(spacing: PedalView.knobSpacing) {
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
let row: [PedalKnob] = rowPair.element
// Centre each row: a short row (one or two knobs) sits centred in the
// enclosure rather than left-aligned. Symmetric spacers also centre a full
// three-knob row, so every row stays horizontally centred.
// A full three-knob row keeps the tight spacing so it fits the enclosure;
// Centre each row: a short row sits centred in the enclosure rather than
// left-aligned. A full row keeps the tight spacing so it fits the enclosure;
// shorter centred rows use a wider, touch-friendly gap.
let rowItemSpacing: CGFloat = row.count >= PedalView.knobColumnCount
let rowItemSpacing: CGFloat = row.count >= columns
? PedalView.knobSpacing
: PedalView.knobRowItemSpacing
HStack(spacing: rowItemSpacing) {
@@ -412,6 +447,40 @@ public struct PedalView: View {
}
}
/// Transport-control row drawn from `pedal.effectTransportButtons`, placed directly below
/// the knobs so persistent state toggles and transport stops (e.g. the looper's Loop /
/// Stop / Cue Stop / Reverse) sit apart from the momentary actions. Renders nothing when
/// the pedal publishes no transport buttons.
@ViewBuilder
private var transportButtonRow: some View {
let buttons: [PedalButton] = pedal.effectTransportButtons
if !buttons.isEmpty {
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(buttons.enumerated()), id: \.offset) { pair in
PedalButtonView(pair.element)
}
Spacer(minLength: 0)
}
}
}
/// Row of momentary stomp-style action buttons drawn from `pedal.effectButtons`, beneath
/// the transport row. Renders nothing when the pedal publishes no buttons.
@ViewBuilder
private var buttonRow: some View {
let buttons: [PedalButton] = pedal.effectButtons
if !buttons.isEmpty {
HStack(spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(buttons.enumerated()), id: \.offset) { pair in
PedalButtonView(pair.element)
}
Spacer(minLength: 0)
}
}
}
/// Row of vertical faders drawn from `pedal.effectSliders`, beneath the switch row.
/// Renders nothing when the pedal publishes no sliders.
@ViewBuilder
@@ -426,16 +495,19 @@ public struct PedalView: View {
}
}
/// Enclosure width — the base stompbox width, widened to fit a wide vertical-fader bank
/// (e.g. a multi-band graphic EQ) so its faders are never clipped.
/// Enclosure width — the base stompbox width scaled by the pedal's `widthUnits`
/// (a control-dense pedal such as the looper asks for a double-width card), widened
/// further to fit a wide vertical-fader bank (e.g. a multi-band graphic EQ) so its
/// faders are never clipped.
private func enclosureWidth(for sliders: [PedalSlider]) -> CGFloat {
let unitWidth: CGFloat = PedalView.enclosureWidth * CGFloat(max(1, pedal.widthUnits))
let sliderCount: Int = sliders.count
guard sliderCount > 0 else { return PedalView.enclosureWidth }
guard sliderCount > 0 else { return unitWidth }
let bankContentWidth: CGFloat =
CGFloat(sliderCount) * PedalView.sliderBankItemWidth
+ CGFloat(max(0, sliderCount - 1)) * PedalView.sliderBankSpacing
let needed: CGFloat = bankContentWidth + 2 * PedalView.enclosurePadding
return max(PedalView.enclosureWidth, needed)
return max(unitWidth, needed)
}
/// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob,
@@ -459,10 +531,11 @@ public struct PedalView: View {
}
/// The `Mix` knob — the second-to-last entry of `pedal.knobs` — placed right of the
/// bypass switch to mirror `Level`.
/// bypass switch to mirror `Level`. Hidden for pedals that manage their own dry/wet balance
/// (``Pedal/showsMixControl``), e.g. the looper.
@ViewBuilder
private var mixControl: some View {
if let mix: PedalKnob = pedal.knobs.dropLast().last {
if pedal.showsMixControl, let mix: PedalKnob = pedal.knobs.dropLast().last {
ParameterKnob(mix.label, node: mix.node, range: mix.range)
.foregroundStyle(Color.white)
}
@@ -474,9 +547,10 @@ public struct PedalView: View {
// re-renders whenever the bypass parameter changes on the main thread
// (UIParamNode is @Observable).
let bypassValue: Double = pedal.$bypass.value
let engagedThreshold: Double = 0.5
return VStack(spacing: PedalView.bypassSectionSpacing) {
LEDIndicator(bypassValue: bypassValue)
LEDIndicator(isOn: bypassValue < engagedThreshold)
FootswitchButton(node: pedal.$bypass)
}
}
@@ -43,10 +43,9 @@ public enum RigLibraryBootstrap {
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
do {
try store.save(entry)
UserDefaults.standard.set(
entry.id.uuidString,
forKey: ShoeGazeBuilderView.currentRigDefaultsKey
)
// The seeded entry was captured from the working graph, so it is the session's source
// rig — record it so the sidebar highlights it and the autosave envelope carries it.
shoeGaze.currentRigID = entry.id
} catch {
print("[RigLibraryBootstrap] seeding library failed: \(error)")
}
@@ -45,6 +45,10 @@ struct RigLibrarySidebarView: View {
let onImportArchive: () -> Void
let onExportArchive: () -> Void
/// Invoked when the local-only (iCloud-unavailable) status icon is tapped, so the host can
/// explain how to re-enable iCloud sync. Defaults to a no-op.
var onShowCloudStatus: () -> Void = {}
private static let timestampFormat: Date.FormatStyle =
Date.FormatStyle(date: .abbreviated, time: .shortened)
@@ -69,13 +73,27 @@ struct RigLibrarySidebarView: View {
.font(.headline)
.foregroundStyle(Color.white)
Spacer()
// Cloud icon when the library is iCloud-backed; a slash when local-only.
Image(systemName: store.isICloud ? "icloud" : "icloud.slash")
cloudStatusIcon
}
}
/// Cloud icon when the library is iCloud-backed; a tappable slash when local-only (tap explains
/// how to re-enable sync).
@ViewBuilder
private var cloudStatusIcon: some View {
if store.isICloud {
Image(systemName: "icloud")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
.help(store.isICloud
? "Synced with iCloud across your devices"
: "iCloud unavailable — rigs are stored on this device only")
.help("Synced with iCloud across your devices")
} else {
Button { onShowCloudStatus() } label: {
Image(systemName: "icloud.slash")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
}
.buttonStyle(.plain)
.help("iCloud unavailable — tap for details. Rigs are stored on this device only")
}
}
@@ -127,6 +145,8 @@ struct RigLibrarySidebarView: View {
RoundedRectangle(cornerRadius: RigLibrarySidebarView.rowCorner)
.fill(Color.orange.opacity(isSelected ? RigLibrarySidebarView.selectedOpacity : 0))
)
// Make the whole padded cell tappable, not just the text glyphs.
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.contextMenu {
@@ -166,8 +186,10 @@ struct RigLibrarySidebarView: View {
} label: {
Image(systemName: "ellipsis.circle")
}
#if os(macOS)
.menuStyle(.borderlessButton)
.fixedSize()
#endif
.help("Archive and library options")
}
.buttonStyle(.bordered)
@@ -7,6 +7,9 @@
#if canImport(AppKit)
import AppKit
#endif
#if canImport(UIKit)
import UIKit
#endif
import SwiftUI
import UniformTypeIdentifiers
import LyrebirdSynth
@@ -53,9 +56,6 @@ public struct ShoeGazeBuilderView: View {
private static let testLoopTag: Int = -1
/// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel).
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
/// UserDefaults key persisting the loaded rig's id (its `uuidString`) so the same rig can be
/// highlighted on the next launch. Read by the app shells to seed `initialRigID`.
public static let currentRigDefaultsKey: String = "ShoeGaze.currentRigID"
/// Maximum crossfade duration honoured by board-switch keyboard shortcuts.
private static let maxCrossfadeSeconds: Double = 10.0
/// Highest board reachable via a ⌘-number switch shortcut.
@@ -73,6 +73,10 @@ public struct ShoeGazeBuilderView: View {
private let library: RigLibraryStore
private let hardwareSampleRate: () -> Double?
/// The MIDI controller for foot-controller input, or `nil` when MIDI is unavailable/disabled.
/// When present, the transport row shows a connection indicator.
private let midi: MIDIController?
/// Host hook to enable live input when the current engine has no input channel (iOS).
/// The host requests microphone access and rebuilds the engine with one input channel,
/// preserving the rig, then swaps in a new `ShoeGaze`. `nil` on platforms (macOS) whose
@@ -91,6 +95,13 @@ public struct ShoeGazeBuilderView: View {
/// Shown when live input is selected but microphone access is denied/restricted.
@State private var showMicDeniedAlert: Bool = false
/// Presents the "iCloud unavailable" guidance alert (rigs saved locally only).
@State private var showICloudUnavailableAlert: Bool = false
/// Guards the automatic one-shot iCloud-unavailable alert so it fires at most once per launch
/// (the tappable status icon can still re-present it on demand).
@State private var didCheckICloudStatus: Bool = false
/// Guards the one-time input-source restore in `.onAppear`.
@State private var didRestoreInput: Bool = false
@@ -102,10 +113,14 @@ public struct ShoeGazeBuilderView: View {
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig. Drives
/// the sidebar highlight and decides whether Save overwrites or prompts for a name.
@State private var currentRigID: UUID?
/// Guards the one-time `currentRigID` seed from `initialRigID` on appear.
@State private var didRestoreRig: Bool = false
///
/// Backed by ``ShoeGaze/currentRigID`` (the single source of truth), so it is persisted inside
/// the autosave envelope together with the graph and restored consistently — the highlight can
/// never drift from the loaded rig. `@Observable` drives sidebar updates when it changes.
private var currentRigID: UUID? {
get { shoeGaze.currentRigID }
nonmutating set { shoeGaze.currentRigID = newValue }
}
/// Drives the shared rig-name entry alert (New / Save As / Rename / Duplicate).
@State private var namePrompt: RigNamePrompt?
@@ -136,6 +151,12 @@ public struct ShoeGazeBuilderView: View {
/// Archive import state (cross-platform).
@State private var showImporter: Bool = false
/// MIDI mapping sheet presentation flag.
@State private var showMIDISheet: Bool = false
/// Help sheet presentation flag (iOS button; macOS uses the Help menu).
@State private var showHelpSheet: Bool = false
#if !os(macOS)
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
@State private var showRecordingFolderImporter: Bool = false
@@ -158,16 +179,20 @@ public struct ShoeGazeBuilderView: View {
/// - library: The rig library store. The host should `start()` it (e.g. via
/// `RigLibraryBootstrap`); the view shows a loading state until then and highlights the
/// persisted current rig once the library has loaded.
/// - midi: The MIDI controller for foot-controller input. When non-`nil`, the transport row
/// shows a connection indicator. Defaults to `nil`.
public init(
shoeGaze: ShoeGaze,
library: RigLibraryStore,
hardwareSampleRate: @escaping () -> Double? = { nil },
onEnableLiveInput: (() -> Void)? = nil
onEnableLiveInput: (() -> Void)? = nil,
midi: MIDIController? = nil
) {
self.shoeGaze = shoeGaze
self.library = library
self.hardwareSampleRate = hardwareSampleRate
self.onEnableLiveInput = onEnableLiveInput
self.midi = midi
}
// MARK: - Body
@@ -196,10 +221,14 @@ public struct ShoeGazeBuilderView: View {
.background(boardSwitchShortcuts)
.onAppear {
restoreInputSelection()
restoreCurrentRig()
syncIdleTimer()
maybeWarnICloudUnavailable()
}
.onDisappear { releaseIdleTimer() }
.onChange(of: transportTick) { syncIdleTimer() }
.onChange(of: library.isLoaded) {
maybeWarnICloudUnavailable()
}
.onChange(of: library.isLoaded) { restoreCurrentRig() }
.onChange(of: currentRigID) { persistCurrentRigID() }
.background(boardsSheetAnchor)
.background(rigExportAnchor)
.background(rigImportAnchor)
@@ -261,9 +290,40 @@ public struct ShoeGazeBuilderView: View {
Text("Live input needs microphone access. Enable it in System Settings › Privacy & "
+ "Security › Microphone, then select the input again.")
}
.alert("iCloud Unavailable", isPresented: $showICloudUnavailableAlert) {
Button("OK", role: .cancel) { }
} message: {
Text("Your rigs are saved on this device only. To sync them across your devices, "
+ "sign in to iCloud and turn on iCloud Drive in "
+ ShoeGazeBuilderView.settingsAppName
+ ", then reopen ShoeGaze.")
}
#if !os(macOS)
.background(recordingFolderImportAnchor)
#endif
.sheet(isPresented: $showMIDISheet) {
if let midi: MIDIController = midi {
MIDIMappingSheet(controller: midi, shoeGaze: shoeGaze)
}
}
.sheet(isPresented: $showHelpSheet) {
HelpView()
}
.overlay(alignment: .top) { midiLearnBanner }
}
/// A banner shown while a control is armed for MIDI Learn, prompting the user to move it.
@ViewBuilder
private var midiLearnBanner: some View {
if let midi: MIDIController = midi, midi.learnTarget != nil {
Text("MIDI Learn — press a footswitch or move an expression pedal to assign it")
.font(.callout.weight(.semibold))
.foregroundStyle(Color.black)
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(Capsule().fill(Color.orange))
.padding(.top, 6)
}
}
/// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/
@@ -271,7 +331,7 @@ public struct ShoeGazeBuilderView: View {
private var rigSidebar: some View {
RigLibrarySidebarView(
store: library,
currentRigID: $currentRigID,
currentRigID: Binding(get: { shoeGaze.currentRigID }, set: { shoeGaze.currentRigID = $0 }),
onSelect: { entry in requestLoad(entry) },
onNew: { promptNewRig() },
onSave: { saveCurrentRig() },
@@ -281,10 +341,45 @@ public struct ShoeGazeBuilderView: View {
onDelete: { entry in deleteEntry(entry) },
onEraseAll: { showEraseAllDialog = true },
onImportArchive: { showImporter = true },
onExportArchive: { exportArchiveAction() }
onExportArchive: { exportArchiveAction() },
onShowCloudStatus: { showICloudUnavailableAlert = true }
)
}
// MARK: - Sleep / iCloud status
/// Platform name for the settings app, used in the iCloud guidance alert.
private static let settingsAppName: String = {
#if os(macOS)
return "System Settings"
#else
return "Settings"
#endif
}()
/// Keeps the device awake while audio is running so a live pedalboard session isn't cut off by
/// auto-lock; the assertion is released as soon as the engine stops. iOS/iPadOS only.
private func syncIdleTimer() {
#if os(iOS)
UIApplication.shared.isIdleTimerDisabled = shoeGaze.engine.isRunning
#endif
}
/// Clears the keep-awake assertion (view left the screen / app backgrounded).
private func releaseIdleTimer() {
#if os(iOS)
UIApplication.shared.isIdleTimerDisabled = false
#endif
}
/// Once the library has resolved, warn the user a single time if it fell back to local-only
/// storage (iCloud Drive signed out or disabled). The status icon can re-present on demand.
private func maybeWarnICloudUnavailable() {
guard library.isLoaded, !library.isICloud, !didCheckICloudStatus else { return }
didCheckICloudStatus = true
showICloudUnavailableAlert = true
}
/// The main builder column: transport, IO, the scope-plus-mixer/picker top section, then the
/// board canvas.
private var builderColumn: some View {
@@ -438,9 +533,12 @@ public struct ShoeGazeBuilderView: View {
private var transportRow: some View {
_ = transportTick
return HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Text("ShoeGaze Builder")
.font(.title2).bold()
.foregroundStyle(Color.white)
VStack(alignment: .leading, spacing: 1) {
Text("ShoeGaze Builder")
.font(.title2).bold()
.foregroundStyle(Color.white)
currentRigLabel
}
if shoeGaze.isRecording {
// Recording indicator (both platforms; recording is driven from the macOS Record
// menu or the iOS controls below).
@@ -454,6 +552,13 @@ public struct ShoeGazeBuilderView: View {
}
}
Spacer()
TempoView(shoeGaze: shoeGaze)
TunerView(shoeGaze: shoeGaze)
if let midi: MIDIController = midi {
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
}
helpButton
rigBypassButton
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
@@ -462,6 +567,34 @@ public struct ShoeGazeBuilderView: View {
}
}
/// Opens the in-app help. Shown on both platforms; macOS also has a Help menu item.
private var helpButton: some View {
Button {
showHelpSheet = true
} label: {
Image(systemName: "questionmark.circle")
.font(.subheadline)
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Open ShoeGaze Help")
}
/// Global rig bypass — routes every board to its dry input at once (pedals skipped). Lit when
/// engaged. A live performance panic/compare control.
private var rigBypassButton: some View {
let bypassed: Bool = shoeGaze.rigBypassed
return Button {
shoeGaze.toggleRigBypassed()
} label: {
Label(bypassed ? "Rig Bypassed" : "Bypass Rig", systemImage: "power")
.font(.subheadline)
}
.buttonStyle(.bordered)
.tint(bypassed ? .orange : .gray)
.help("Bypass the entire rig — every board passes your dry input straight through")
}
// MARK: - Input + board + save/load row
private var ioRow: some View {
@@ -588,6 +721,8 @@ public struct ShoeGazeBuilderView: View {
/// 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() {
// The autosave envelope records `shoeGaze.currentRigID` alongside the graph, so the highlight
// and the restored graph stay consistent without any separate bookkeeping.
RigStore.save(shoeGaze)
}
@@ -599,6 +734,11 @@ public struct ShoeGazeBuilderView: View {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
// Clearing the rig discards its MIDI bindings — they are addressed positionally and
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't
// re-resolve onto the fresh board's pedals.
shoeGaze.midiMap = nil
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
@@ -764,29 +904,6 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Rig library
/// Highlights the persisted current rig once the library has loaded. Runs once; only sets the
/// highlight when nothing is selected yet and the saved id still exists in the library.
private func restoreCurrentRig() {
guard !didRestoreRig, library.isLoaded else { return }
didRestoreRig = true
guard currentRigID == nil,
let stored: String = UserDefaults.standard.string(
forKey: ShoeGazeBuilderView.currentRigDefaultsKey),
let id: UUID = UUID(uuidString: stored),
library.entries.contains(where: { $0.id == id }) else { return }
currentRigID = id
}
/// Persists `currentRigID` so the same rig is highlighted on the next launch.
private func persistCurrentRigID() {
let defaults: UserDefaults = UserDefaults.standard
if let id: UUID = currentRigID {
defaults.set(id.uuidString, forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
} else {
defaults.removeObject(forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
}
}
/// Loads a library entry into the session, replacing the current rig. Stops/restarts the engine
/// around the rebuild, resets the board selection, and records the entry as current.
private func loadEntry(_ entry: RigEntry) {
@@ -989,6 +1106,32 @@ public struct ShoeGazeBuilderView: View {
return library.entries.first(where: { $0.id == id })?.name
}
/// A subtitle under the app title showing which rig is loaded. Resolves the name from the
/// library once it has loaded; shows "Unsaved rig" when the working graph has no source-rig
/// id (a cleared / never-saved session). Reads `shoeGaze.currentRigID` and `library.entries`
/// so it refreshes automatically when a rig is loaded or the library finishes loading.
private var currentRigLabel: some View {
let hasSource: Bool = currentRigID != nil
let name: String
if let resolved: String = currentRigName() {
name = resolved
} else if hasSource {
// Source id exists but the library hasn't resolved it yet (still loading).
name = library.isLoaded ? "Unknown rig" : "Loading…"
} else {
name = "Unsaved rig"
}
return HStack(spacing: 5) {
Image(systemName: hasSource ? "guitars.fill" : "guitars")
.font(.caption2)
Text(name)
.font(.caption)
.lineLimit(1)
}
.foregroundStyle(Color.white.opacity(hasSource ? 0.8 : 0.5))
.help(hasSource ? "Loaded rig: \(name)" : "This rig has not been saved to the library yet")
}
/// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names.
private func defaultNewRigName() -> String {
let base: String = "Rig"
+107
View File
@@ -0,0 +1,107 @@
// TempoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdShoeGaze
/// Tempo indicator: a BPM readout/stepper, a beat-synced flashing LED, and a tap area that
/// responds to mouse/touch taps (call ``ShoeGaze/tapTempo()`` directly for a MIDI trigger).
///
/// Polls ``ShoeGaze/clock``'s `currentBeat` on a `.task` loop (matching the scope/CPU-meter
/// polling convention) since `LyrebirdClock` isn't `@Observable` — it's sample-accurate RT
/// state, not push-notified UI state.
public struct TempoView: View {
// MARK: - Constants
private static let pollIntervalNanoseconds: UInt64 = 33_333_333 // ~30 Hz
/// Fraction of each beat the LED stays lit — a short flash, not a 50% duty-cycle blink.
private static let flashDutyCycle: Double = 0.15
private static let minBpm: Double = 30.0
private static let maxBpm: Double = 300.0
private static let bpmStep: Double = 1.0
private static let ledDiameter: CGFloat = 16
private static let panelSpacing: CGFloat = 10
private static let rowSpacing: CGFloat = 14
private static let tapAreaSize: CGFloat = 64
// MARK: - Properties
private let shoeGaze: ShoeGaze
@State private var displayedBpm: Double
@State private var ledOn: Bool = false
// MARK: - Init
/// - Parameter shoeGaze: The session whose ``ShoeGaze/clock`` this view displays and drives.
public init(shoeGaze: ShoeGaze) {
self.shoeGaze = shoeGaze
self._displayedBpm = State(initialValue: shoeGaze.clock.bpm)
}
// MARK: - Body
public var body: some View {
VStack(spacing: TempoView.panelSpacing) {
HStack(spacing: TempoView.rowSpacing) {
led
Text("\(Int(displayedBpm.rounded())) BPM")
.font(.system(size: 18, weight: .semibold, design: .rounded))
.foregroundStyle(Color.white)
Stepper(
"",
value: Binding(
get: { displayedBpm },
set: { newValue in
let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm)
shoeGaze.clock.bpm = clamped
displayedBpm = clamped
}
),
in: TempoView.minBpm ... TempoView.maxBpm,
step: TempoView.bpmStep
)
.labelsHidden()
}
tapArea
}
.task {
while !Task.isCancelled {
let beat: Double = shoeGaze.clock.currentBeat
let phase: Double = beat - beat.rounded(.down)
ledOn = phase < TempoView.flashDutyCycle
displayedBpm = shoeGaze.clock.bpm
try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds)
}
}
}
// MARK: - Subviews
private var led: some View {
Circle()
.fill(ledOn ? Color.red : Color.red.opacity(0.15))
.frame(width: TempoView.ledDiameter, height: TempoView.ledDiameter)
}
private var tapArea: some View {
Button {
shoeGaze.tapTempo()
displayedBpm = shoeGaze.clock.bpm
} label: {
Text("TAP")
.font(.system(size: 14, weight: .bold, design: .rounded))
.frame(width: TempoView.tapAreaSize, height: TempoView.tapAreaSize)
.background(Color.white.opacity(0.08))
.clipShape(Circle())
}
.buttonStyle(.plain)
.foregroundStyle(Color.white)
}
}
+210
View File
@@ -0,0 +1,210 @@
// TunerView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdShoeGaze
/// Chromatic tuner panel: an engage toggle, a mute-rig-while-tuning toggle, and a live
/// note/cents readout.
///
/// Polls ``ShoeGaze/currentPitchHz`` on a `.task` loop (matching `LyrebirdEngineStatusView`'s
/// CPU-meter convention) since the value is computed from RT-thread state on demand, not an
/// `@Observable`-tracked property. Polling only runs while the tuner is engaged.
public struct TunerView: View {
// MARK: - Constants
private static let pollIntervalNanoseconds: UInt64 = 250_000_000 // 4 Hz, at most
private static let inTuneCentsThreshold: Double = 5.0
private static let closeCentsThreshold: Double = 15.0
/// Below this YIN confidence the reading is treated as untracked — the last stable pitch
/// is latched and the display dims, rather than chasing a transient/attack estimate.
private static let trackingConfidenceThreshold: Double = 0.8
/// Opacity applied to the latched readout while not actively tracking.
private static let untrackedOpacity: Double = 0.35
private static let panelSpacing: CGFloat = 10
private static let rowSpacing: CGFloat = 14
private static let noteFontSize: CGFloat = 34
private static let statusFontSize: CGFloat = 10
// MARK: - Properties
private let shoeGaze: ShoeGaze
/// Last pitch accepted at or above the confidence threshold (latched through dropouts).
@State private var latchedPitch: TunerPitchReading?
/// `true` when the most recent poll was above the confidence threshold.
@State private var isTracking: Bool = false
// MARK: - Init
/// - Parameter shoeGaze: The session whose tuner state this view controls and displays.
public init(shoeGaze: ShoeGaze) {
self.shoeGaze = shoeGaze
}
// MARK: - Body
public var body: some View {
VStack(spacing: TunerView.panelSpacing) {
HStack(spacing: TunerView.rowSpacing) {
Button(shoeGaze.tunerEngaged ? "Tuner: On" : "Tuner: Off") {
shoeGaze.toggleTunerEngaged()
}
.buttonStyle(.bordered)
.tint(shoeGaze.tunerEngaged ? .green : .gray)
Toggle("Mute rig", isOn: Binding(
get: { shoeGaze.tunerMutesRig },
set: { shoeGaze.tunerMutesRig = $0 }
))
.toggleStyle(.switch)
}
if shoeGaze.tunerEngaged {
readout
}
}
.task(id: shoeGaze.tunerEngaged) {
while shoeGaze.tunerEngaged && !Task.isCancelled {
updateReading()
try? await Task.sleep(nanoseconds: TunerView.pollIntervalNanoseconds)
}
if !shoeGaze.tunerEngaged {
latchedPitch = nil
isTracking = false
}
}
}
/// Polls freq + confidence. Above the confidence threshold, updates the latched pitch
/// and marks tracking active; below it, leaves the latched pitch in place (so restrikes
/// don't make the reading ramp) and marks tracking inactive.
private func updateReading() {
let confidence: Double = shoeGaze.currentPitchConfidence ?? 0.0
let hz: Double = shoeGaze.currentPitchHz ?? 0.0
if confidence >= TunerView.trackingConfidenceThreshold && hz > 0 {
latchedPitch = TunerPitchReading(hz: hz)
isTracking = true
} else {
isTracking = false
}
}
// MARK: - Readout
@ViewBuilder
private var readout: some View {
if let pitch: TunerPitchReading = latchedPitch {
VStack(spacing: 6) {
Text(pitch.noteName)
.font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded))
.foregroundStyle(TunerView.color(forCents: pitch.cents))
TunerCentsMeter(cents: pitch.cents)
Text(isTracking ? "TRACKING" : "…")
.font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.white.opacity(0.5))
}
.opacity(isTracking ? 1.0 : TunerView.untrackedOpacity)
} else {
VStack(spacing: 6) {
Text("—")
.font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded))
.foregroundStyle(Color.white.opacity(0.4))
Text("play a note")
.font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.white.opacity(0.4))
}
}
}
static func color(forCents cents: Double) -> Color {
let magnitude: Double = abs(cents)
if magnitude <= TunerView.inTuneCentsThreshold { return .green }
if magnitude <= TunerView.closeCentsThreshold { return .yellow }
return .red
}
}
// MARK: - TunerCentsMeter
/// A horizontal -50…+50 cents meter: a track with a centre "in tune" tick and a vertical
/// marker positioned at the current deviation, coloured with the same red/yellow/green
/// thresholds as the note readout.
struct TunerCentsMeter: View {
private static let range: Double = 50.0
private static let trackWidth: CGFloat = 140
private static let trackHeight: CGFloat = 4
private static let markerWidth: CGFloat = 3
private static let markerHeight: CGFloat = 18
private static let centerTickWidth: CGFloat = 1.5
private static let centerTickHeight: CGFloat = 10
let cents: Double
private var clampedFraction: Double {
// Maps [-range, +range] to [0, 1]; values beyond the range pin to the edge.
let clamped: Double = min(max(cents, -TunerCentsMeter.range), TunerCentsMeter.range)
return (clamped + TunerCentsMeter.range) / (2.0 * TunerCentsMeter.range)
}
var body: some View {
GeometryReader { geometry in
let width: CGFloat = geometry.size.width
let markerX: CGFloat = width * clampedFraction
ZStack(alignment: .leading) {
// Track.
RoundedRectangle(cornerRadius: TunerCentsMeter.trackHeight / 2)
.fill(Color.white.opacity(0.15))
.frame(height: TunerCentsMeter.trackHeight)
.frame(maxWidth: .infinity)
// Centre "in tune" reference tick.
Rectangle()
.fill(Color.white.opacity(0.5))
.frame(width: TunerCentsMeter.centerTickWidth, height: TunerCentsMeter.centerTickHeight)
.position(x: width / 2, y: TunerCentsMeter.trackHeight / 2)
// Deviation marker.
Rectangle()
.fill(TunerView.color(forCents: cents))
.frame(width: TunerCentsMeter.markerWidth, height: TunerCentsMeter.markerHeight)
.position(x: markerX, y: TunerCentsMeter.trackHeight / 2)
}
}
.frame(width: TunerCentsMeter.trackWidth, height: TunerCentsMeter.markerHeight)
}
}
// MARK: - TunerPitchReading
/// Converts a detected frequency into the nearest chromatic note name, octave, and cents
/// deviation. Standard 12-TET sharp spelling — a tuner display doesn't need the full
/// spelling-aware `NoteName`/`Scale` theory toolkit (that's for compositional notation).
struct TunerPitchReading {
private static let chromaticNames: [String] = [
"C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B",
]
private static let semitonesPerOctave: Int = 12
private static let midiOctaveOffset: Int = 1 // MIDI note 0 = C-1
private static let centsPerSemitone: Double = 100.0
let noteName: String
let cents: Double
init(hz: Double) {
let midi: Double = hzToMidi(hz)
let nearestMidi: Int = Int(midi.rounded())
cents = (midi - Double(nearestMidi)) * TunerPitchReading.centsPerSemitone
let pitchClass: Int = ((nearestMidi % TunerPitchReading.semitonesPerOctave)
+ TunerPitchReading.semitonesPerOctave) % TunerPitchReading.semitonesPerOctave
let octave: Int = nearestMidi / TunerPitchReading.semitonesPerOctave - TunerPitchReading.midiOctaveOffset
noteName = "\(TunerPitchReading.chromaticNames[pitchClass])\(octave)"
}
}
@@ -17,10 +17,11 @@ struct BoardEditAPITests {
/// Builds an NRT-backed `ShoeGaze` with a single finalized board of the given pedal types.
private func makeRig(
pedals: [String],
numAudioBuses: Int = 128
numAudioBuses: Int = 128,
duration: Double = 0.1
) throws -> (ShoeGaze, SynthesisEngine, URL, PedalBoard) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
duration: duration,
numAudioBuses: numAudioBuses
)
let sg: ShoeGaze = ShoeGaze(engine: engine)
@@ -118,6 +119,236 @@ struct BoardEditAPITests {
}
}
// MARK: - Insert
@Test func insertPlacesPedalBeforeTargetAndRenders() throws {
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
// Insert before linear index 1 (the Delay) → lands between Overdrive and Delay.
let edited: PedalBoard = try sg.insertPedal(.fuzz, at: 1, to: board)
#expect(names(edited) == ["Overdrive", "Fuzz", "Delay", "Reverb"])
#expect(sg.boards.count == 1, "insert should not change board count")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "board should still render after insert")
}
@Test func insertAtZeroPrependsToChain() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
let edited: PedalBoard = try sg.insertPedal(.reverb, at: 0, to: board)
#expect(names(edited) == ["Reverb", "Overdrive", "Delay"])
}
@Test func insertAtCountAppendsToChain() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// index == pedal count → append, matching appendPedal placement.
let edited: PedalBoard = try sg.insertPedal(.reverb, at: 2, to: board)
#expect(names(edited) == ["Overdrive", "Delay", "Reverb"])
}
@Test func insertUnknownTypeThrows() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(throws: ShoeGazeError.unknownPedalType("Nope")) {
try sg.insertPedal(PedalType("Nope"), at: 0, to: board)
}
}
@Test func insertOutOfRangeThrows() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// Past the end (count is 2, so valid inserts are 0...2): index 3 is out of range.
#expect(throws: ShoeGazeError.pedalIndexOutOfRange(index: 3, count: 2)) {
try sg.insertPedal(.reverb, at: 3, to: board)
}
}
@Test func insertBeforeTrailingRegionStaysInLinearChain() throws {
// Board: [Overdrive, Delay, <stereo split>]. Inserting at the end of the linear chain must
// land before the split region, not after it.
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendStereoSplit(to: board) // segment index 2
live = try sg.insertPedal(.fuzz, at: 2, to: live, lane: .main) // end of linear chain
#expect(names(live) == ["Overdrive", "Delay", "Fuzz"], "Fuzz appends to the linear chain")
guard case .stereoSplit = live.captureState().segments.last else {
Issue.record("Stereo split should remain the trailing segment; pedal jumped past it")
return
}
}
@Test func insertIntoRegionOnlyBoardLandsBeforeRegion() throws {
// A board with no linear pedals but a trailing split region: inserting at index 0 must place
// the pedal at the head of the chain, BEFORE the region — not after it.
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: [])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendStereoSplit(to: board) // region-only board
live = try sg.insertPedal(.fuzz, at: 0, to: live, lane: .main)
#expect(names(live) == ["Fuzz"], "the inserted pedal joins the linear chain")
guard case .pedal = live.captureState().segments.first else {
Issue.record("pedal should be the first segment, ahead of the split region")
return
}
}
@Test func insertIntoBranchLaneBeforeTarget() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
var live: PedalBoard = try sg.appendStereoSplit(to: board)
live = try sg.appendPedal(.delay, to: live, lane: .left(region: 1))
live = try sg.appendPedal(.reverb, to: live, lane: .left(region: 1))
// Left lane is [Delay, Reverb]; insert Fuzz before index 1 → [Delay, Fuzz, Reverb].
live = try sg.insertPedal(.fuzz, at: 1, to: live, lane: .left(region: 1))
#expect(stereoState(live)?.left.map { $0.type } == ["Delay", "Fuzz", "Reverb"],
"Fuzz should land between Delay and Reverb in the left lane")
}
// MARK: - Full bypass (board / rig)
@Test func boardBypassTogglesStateAndStillRenders() throws {
let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(!sg.isBoardBypassed(board), "board starts engaged")
sg.setBoard(board, bypassed: true)
#expect(sg.isBoardBypassed(board), "board reports bypassed after toggle")
// Dry passes straight through — the board still produces audio when bypassed.
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "bypassed board should pass dry audio")
}
@Test func boardBypassReengages() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
sg.setBoard(board, bypassed: true)
sg.setBoard(board, bypassed: false)
#expect(!sg.isBoardBypassed(board), "board should re-engage")
}
@Test func rigBypassTogglesFlagAndRenders() throws {
let (sg, engine, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(!sg.rigBypassed, "rig starts engaged")
sg.toggleRigBypassed()
#expect(sg.rigBypassed, "rig reports bypassed after toggle")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "bypassed rig should pass dry audio")
sg.setRigBypassed(false)
#expect(!sg.rigBypassed, "rig should re-engage")
}
@Test func boardFinalizedWhileRigBypassedComesUpBypassed() throws {
let (sg, _, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
sg.setRigBypassed(true)
// A board added after the rig is bypassed must not leak processed audio: its rig-bypass
// node should come up engaged. We can at least confirm the new board joins cleanly and the
// rig flag stays set.
let board2: PedalBoard = try sg.addBoard()
try board2.add(DelayPedal())
try sg.finalizeBoard(board2)
#expect(sg.rigBypassed, "rig stays bypassed after adding a board")
#expect(board2.rigBypassNode?.value == 1.0, "new board comes up rig-bypassed")
}
@Test func rigVolumeClampsAndAppliesToAllBoards() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(sg.rigVolume == 1.0, "rig volume starts at unity")
sg.setRigVolume(0.5)
#expect(sg.rigVolume == 0.5)
#expect(board.rigVolumeNode?.value == 0.5)
sg.setRigVolume(2.0)
#expect(sg.rigVolume == 1.0, "rig volume clamps to 1")
sg.setRigVolume(-1.0)
#expect(sg.rigVolume == 0.0, "rig volume clamps to 0")
}
@Test func rigMuteSilencesOutputWithoutBypassing() throws {
// Mute is smoothed by a short `Lag` to avoid a click, so the tail (well past the lag time)
// must settle silent — the render must be long enough for that lag to fully resolve.
let (sg, engine, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"], duration: 1.0)
defer { try? FileManager.default.removeItem(at: url) }
#expect(!sg.rigMuted, "rig starts unmuted")
sg.toggleRigMuted()
#expect(sg.rigMuted, "rig reports muted after toggle")
#expect(!sg.rigBypassed, "mute must not engage the dry bypass")
let samples: [Float] = try render(engine, url)
let tail: [Float] = Array(samples.suffix(samples.count / 4))
#expect(!hasNonSilentOutput(tail), "muted rig should settle to silence once the lag resolves")
sg.setRigMuted(false)
#expect(!sg.rigMuted, "rig should unmute")
}
@Test func boardFinalizedWhileRigVolumeAndMuteSetComesUpMatching() throws {
let (sg, _, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
sg.setRigVolume(0.25)
sg.setRigMuted(true)
let board2: PedalBoard = try sg.addBoard()
try board2.add(DelayPedal())
try sg.finalizeBoard(board2)
#expect(board2.rigVolumeNode?.value == 0.25, "new board picks up current rig volume")
#expect(board2.rigMuteNode?.value == 1.0, "new board picks up current rig mute")
}
@Test func rigRebuildClearsTransientBypass() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"], numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url) }
sg.setBoard(board, bypassed: true)
sg.setRigBypassed(true)
// Reconfiguring the engine tears down and rebuilds every board — transient bypass state
// (which is keyed by board identity) must reset rather than linger stale.
try sg.reconfigureEngine(sampleRate: 48_000, inputChannels: 0, outputChannels: 2)
#expect(!sg.rigBypassed, "rig bypass cleared on rebuild")
#expect(sg.bypassedBoards.isEmpty, "per-board bypass set cleared on rebuild")
}
// MARK: - Branch preservation
@Test func editingLinearPedalPreservesStereoSplitRegion() throws {
@@ -0,0 +1,597 @@
// LooperPedalTests.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("LooperPedal")
struct LooperPedalTests {
// MARK: - Test fixtures
/// A constant-frequency sine source with a live-settable amplitude, so tests can silence the
/// live input at an exact scheduled time and attribute any remaining output to the looper.
private final class ToneSource: SynthesizerBase {
let ampNode: ParameterNode = ParameterNode(0.3)
var amplitude: Double {
get { ampNode.value }
set { ampNode.value = newValue }
}
private let targetBus: Int
private let toneFreq: Double
init(targetBus: Int, freq: Double = 220.0) {
self.targetBus = targetBus
self.toneFreq = freq
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq) * ampNode)
}
}
/// Posts a `TriggerEvent` at an exact sample-accurate time within a single NRT render, so a
/// test can flip a looper transport action mid-render.
private final class TimedTrigger: SynthesizerBase {
private let fireTime: Double
private let triggerID: Int32
private static let minRampDuration: Double = 0.001
init(fireTime: Double, id: Int32) {
self.fireTime = fireTime
self.triggerID = id
super.init()
}
override func build() {
let rampDuration: Double = max(fireTime, TimedTrigger.minRampDuration) * 2.0
let ramp: Line.Control = Line.Control(start: -1.0, end: 1.0, dur: rampDuration)
_ = SendTrigger.Control(trig: ramp, id: triggerID)
}
}
private func rms(_ samples: [Float]) -> Double {
guard !samples.isEmpty else { return 0 }
let sumSquares: Double = samples.reduce(0) { $0 + Double($1) * Double($1) }
return (sumSquares / Double(samples.count)).squareRoot()
}
/// Builds a fresh engine + `ToneSource` + `LooperPedal` + master, lets the caller register
/// exact-time actions, then renders and returns the stereo samples. No clock is injected, so
/// the looper transport is immediate (un-quantized).
private func render(
totalDuration: Double,
toneAmplitude: Double = 0.3,
sampleRate: Double = 44100.0,
configure: (
_ engine: SynthesisEngine,
_ source: ToneSource,
_ pedal: LooperPedal,
_ scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void
) throws -> Void
) throws -> [Float] {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".caf")
defer { try? FileManager.default.removeItem(at: url) }
let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 64,
numControlBuses: 512,
driver: driver
)
let listener: TriggerListener = TriggerListener(engine: engine)
driver.triggerListener = listener
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: ToneSource = ToneSource(targetBus: srcBus.index)
source.amplitude = toneAmplitude
let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
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))
var nextTriggerID: Int32 = 0
let scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void = { time, action in
nextTriggerID += 1
let id: Int32 = nextTriggerID
let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id)
try engine.add(trigger)
listener.addHandler(id: id) { _, _ in
MainActor.assumeIsolated { action() }
}
}
try configure(engine, source, pedal, scheduleAction)
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
/// Builds an engine with the pedal added (so `effect()` allocates buffers + recorders) but
/// does NOT start it, so beat-quantized callbacks can be driven deterministically. The caller
/// keeps the returned (weak-referenced) engine + clock alive.
private func makeQuantizedFixture(bpm: Double, sampleRate: Double)
throws -> (engine: SynthesisEngine, clock: LyrebirdClock, pedal: LooperPedal) {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".caf")
let driver: NRTDriver = NRTDriver(outputURL: url, duration: 0.1)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 64,
numControlBuses: 512,
driver: driver
)
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let source: ToneSource = ToneSource(targetBus: srcBus.index)
let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: bpm)
pedal.clock = clock
pedal.hostEngine = engine
pedal.sampleRate = sampleRate
return (engine, clock, pedal)
}
// MARK: - Controls
@Test func exposesLooperControls() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"])
#expect(pedal.effectSwitches.map { $0.label } == ["Sync"])
#expect(pedal.effectButtons.isEmpty)
#expect(pedal.effectTransportButtons.map { $0.label } == ["Loop", "Stop", "Cue Stop", "Reverse", "Reset"])
}
@Test func looperIsDoubleWidth() throws {
#expect(LooperPedal().widthUnits == 2)
#expect(LooperPedal.trackCount == 4)
}
@Test func rebuildDoesNotDoubleTrackGenerators() throws {
// effect() runs from build(), which the engine re-invokes on every add — including the
// re-adds a board edit performs on the same instance. It must be idempotent (not append
// to the per-track arrays each time), or the looper's generators/state desync.
let pedal: LooperPedal = LooperPedal()
pedal.sampleRate = 44100.0
let dry: any ValidGeneratorInput = OscSin.Audio(freq: 100.0)
_ = pedal.effect(dry)
_ = pedal.effect(dry) // simulate a second build()
let counts: (buffers: Int, players: Int, overdub: Int, gates: Int) = pedal.trackGeneratorCountsForTesting
#expect(counts.buffers == LooperPedal.trackCount)
#expect(counts.players == LooperPedal.trackCount)
#expect(counts.overdub == LooperPedal.trackCount)
#expect(counts.gates == LooperPedal.trackCount)
#expect(pedal.transportState == .clear)
}
@Test func looperHidesMixControl() throws {
// The looper always passes the clean signal through and adds the loop on top, so the
// wet/dry Mix knob is hidden; a plain pedal keeps it.
#expect(LooperPedal().showsMixControl == false)
}
@Test func cleanSignalPassesThroughWhilePlaying() throws {
// With the loop muted (loopOn = 0) but a loop recorded and a live tone present, the
// output must still carry the clean signal at full level — it is never gated by the loop.
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.5) { _, _, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() } // play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub
try scheduleAction(0.2) { pedal.loopOn = 0.0 } // mute the loop, keep live tone
}
let tailStart: Int = Int(Double(samples.count) * 0.9)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Clean signal must pass through even with the loop muted")
}
// MARK: - Audio behaviour (immediate / un-quantized)
@Test func clearStatePassesDryThrough() throws {
let samples: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
#expect(hasNonSilentOutput(samples), "Cleared looper should pass the dry signal through")
}
@Test func recordCloseThenPlaysAfterInputSilenced() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.7) { _, source, pedal, scheduleAction in
pedal.pressLoop() // record track A
try scheduleAction(recordDuration) { pedal.pressLoop() } // set end → play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub, keep playing
try scheduleAction(recordDuration + 0.02) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.8)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Recorded loop should keep playing after the input is silenced")
}
@Test func resetReturnsToClearAndSilence() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.5) { _, source, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(0.2) { pedal.resetLoop() }
try scheduleAction(0.2) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
let tail: [Float] = Array(samples[tailStart...])
#expect(!hasNonSilentOutput(tail), "After reset + silenced input, no loop content should remain")
}
@Test func playbackLevelAttenuatesLoop() throws {
let recordDuration: Double = 0.1
func renderLoop(playbackLevelDb: Double) throws -> [Float] {
try render(totalDuration: 0.5) { _, source, pedal, scheduleAction in
pedal.playbackLevel = playbackLevelDb
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { source.amplitude = 0.0 }
}
}
let unityRMS: Double = rms(try renderLoop(playbackLevelDb: 0.0))
let attenuatedRMS: Double = rms(try renderLoop(playbackLevelDb: -6.0))
#expect(attenuatedRMS < unityRMS, "-6 dB playback level should be quieter than 0 dB")
}
@Test func reverseKeepsLoopAudible() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.6) { _, source, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() }
try scheduleAction(0.25) { pedal.reverse = 1.0 }
try scheduleAction(0.25) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Reverse playback should keep the loop audible")
}
@Test func overdubbingTrackAAddsEnergyToTheLoop() throws {
let recordDuration: Double = 0.1
let overdubStart: Double = 0.25
let overdubEnd: Double = 0.35
// Record silence into A, then overdub a tone onto A; the baked-in loop should be audible.
func renderWithOverdub(_ overdub: Bool) throws -> Double {
let samples: [Float] = try render(totalDuration: 0.7, toneAmplitude: 0.0) { _, source, pedal, scheduleAction in
pedal.pressLoop() // record A (silent)
try scheduleAction(recordDuration) { pedal.pressLoop() } // set end → play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub, just play
if overdub {
try scheduleAction(overdubStart) { source.amplitude = 0.3 } // feed a tone
try scheduleAction(overdubStart) { pedal.pressLoop() } // overdub A on
try scheduleAction(overdubEnd) { pedal.pressLoop() } // overdub A off
}
try scheduleAction(overdubEnd) { source.amplitude = 0.0 } // silence input
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
return rms(Array(samples[tailStart...]))
}
let withoutOverdub: Double = try renderWithOverdub(false)
let withOverdub: Double = try renderWithOverdub(true)
#expect(withOverdub > withoutOverdub,
"Overdubbing a tone onto silent track A should bake audible content into the loop")
}
// MARK: - State machine (headless)
@Test func statesProgressFromClearToPlaying() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil // immediate transport
#expect(pedal.transportState == .clear)
#expect(pedal.loopButtonCaption == "Record")
pedal.pressLoop() // → recording A
#expect(pedal.transportState == .recordingMaster)
#expect(pedal.loopButtonCaption == "Set End")
pedal.pressLoop() // → playing + overdubbing A
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
#expect(pedal.loopButtonCaption == "Play") // next press ends overdub
pedal.pressLoop() // → playing, overdub off
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(pedal.trackHasContent(0))
#expect(pedal.loopButtonCaption == "Overdub") // A has content, next press overdubs
} }
}
@Test func masterLengthQuantizesToWholeBeats() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate) // 22 050 frames / beat
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.pressLoop() // arm record (routine won't fire; engine idle)
pedal.beginMasterRecording(at: SampleTime(sampleRate * 0.5))
#expect(pedal.transportState == .recordingMaster)
pedal.pressLoop() // arm close
pedal.closeMasterAndPlay(at: SampleTime(sampleRate * 2.5)) // 2.0 s = 4 beats
#expect(pedal.transportState == .playing)
#expect(pedal.loopFrameCount == Int(sampleRate * 2.0))
#expect(pedal.loopLengthBeats == 4.0)
pedal.resetLoop()
#expect(pedal.transportState == .clear)
#expect(pedal.loopFrameCount == 0)
} }
}
@Test func onlyTrackASelectableWhileClear() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
#expect(pedal.selectedTrackIndex == 0)
pedal.selectTrack(2) // ignored while clear
#expect(pedal.selectedTrackIndex == 0)
} }
}
@Test func selectingTrackWhilePlayingEndsOverdubAndSwitches() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
#expect(pedal.overdubbingTrackIndex == 0)
pedal.selectTrack(1) // select B — ends A's overdub
#expect(pedal.selectedTrackIndex == 1)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(!pedal.trackHasContent(1))
#expect(pedal.loopButtonCaption == "Record") // empty B, next press records it
pedal.pressLoop() // overdub (record) B
#expect(pedal.overdubbingTrackIndex == 1)
#expect(pedal.trackHasContent(1))
} }
}
@Test func overdubBlockedWhileReversed() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
pedal.pressLoop() // end overdub, just playing
#expect(pedal.overdubbingTrackIndex == nil)
pedal.reverse = 1.0 // engage reverse
pedal.pressLoop() // must NOT start overdub while reversed
#expect(pedal.overdubbingTrackIndex == nil, "overdub can't be engaged while reversed")
pedal.reverse = 0.0 // forward again
pedal.pressLoop() // now overdub engages
#expect(pedal.overdubbingTrackIndex == 0)
} }
}
@Test func engagingReverseWhileOverdubbingEndsOverdub() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
#expect(pedal.overdubbingTrackIndex == 0)
pedal.toggleReverse() // engage reverse mid-overdub
#expect(pedal.reverse == 1.0)
#expect(pedal.overdubbingTrackIndex == nil, "engaging reverse must end the overdub")
pedal.toggleReverse() // back to forward — overdub stays off
#expect(pedal.reverse == 0.0)
#expect(pedal.overdubbingTrackIndex == nil)
} }
}
@Test func engineStopResetsLooperAndPostsNotice() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing
#expect(pedal.transportState == .playing)
pedal.engineDidStop()
#expect(pedal.transportState == .clear, "engine stop returns the looper to clear")
#expect(pedal.loopFrameCount == 0)
#expect(pedal.stateDescription == "Looper reset — engine stopped.",
"a transient notice is shown after the engine-stop reset")
// A no-op when already clear (no spurious notice).
let clearPedal: LooperPedal = LooperPedal()
clearPedal.engineDidStop()
#expect(clearPedal.transportState == .clear)
} }
}
@Test func rigTeardownResetsLooper() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop()
pedal.pressLoop() // playing
pedal.rigWillTeardown()
#expect(pedal.transportState == .clear, "a rig teardown returns the looper to clear")
#expect(pedal.stateDescription == "Looper reset — rig changed.")
} }
}
@Test func recordsAgainAfterReset() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing + overdub A
pedal.toggleReverse() // leave reverse engaged before reset
#expect(pedal.reverse == 1.0)
pedal.resetLoop()
#expect(pedal.transportState == .clear)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(pedal.reverse == 0.0, "reset returns to forward playback")
// Second take must behave exactly like the first — including auto-overdub on A,
// which was silently blocked when reset didn't clear a left-on reverse.
pedal.pressLoop()
#expect(pedal.transportState == .recordingMaster, "record after reset should re-enter recording")
#expect(pedal.loopButtonCaption == "Set End")
pedal.pressLoop()
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0, "auto-overdub on A must engage after a reset")
#expect(pedal.trackHasContent(0))
} }
}
@Test func quantizedRecordsAgainAfterReset() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Mimic the real (beat-quantized) app path: pressLoop arms + starts a routine that
// fires applyQuantizedTransport with the generation captured at arm time.
// Session 1
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 0.5))
#expect(pedal.transportState == .recordingMaster)
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 2.5))
#expect(pedal.transportState == .playing)
// Reset, then session 2 — the quantized callbacks must still land.
pedal.resetLoop()
#expect(pedal.transportState == .clear)
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 4.5))
#expect(pedal.transportState == .recordingMaster, "quantized record after reset must reach recording")
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 6.5))
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
} }
}
@Test func freeformModeRecordsImmediatelyDespiteClock() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Sync off: even with a clock present, transport is immediate — no armed/waiting state.
pedal.syncToBeat = 0.0
pedal.pressLoop()
#expect(pedal.transportState == .recordingMaster, "freeform record starts immediately")
pedal.pressLoop()
#expect(pedal.transportState == .playing)
#expect(pedal.loopLengthBeats == 0.0, "freeform loops aren't beat-measured")
// Flip to Sync: the next take arms for the beat instead.
pedal.resetLoop()
pedal.syncToBeat = 1.0
pedal.pressLoop()
#expect(pedal.transportState == .armedRecord, "sync record arms for the next beat")
} }
}
@Test func tapTrackSelectsThenMutesRecordedTrack() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing, A selected + has content
pedal.pressLoop() // end auto-overdub, just playing
#expect(pedal.selectedTrackIndex == 0)
#expect(pedal.trackHasContent(0))
#expect(!pedal.isTrackMuted(0))
// Second tap on the selected, recorded track A mutes it; third un-mutes.
pedal.tapTrack(0)
#expect(pedal.isTrackMuted(0), "tapping the selected recorded track mutes it")
pedal.tapTrack(0)
#expect(!pedal.isTrackMuted(0), "tapping again un-mutes it")
// Tapping a different track selects it (doesn't mute), leaving A audible.
pedal.tapTrack(1)
#expect(pedal.selectedTrackIndex == 1)
#expect(!pedal.isTrackMuted(0))
#expect(!pedal.isTrackMuted(1))
pedal.resetLoop()
#expect(!pedal.isTrackMuted(0), "reset un-mutes all tracks")
} }
}
@Test func cycleSyncModeOscillatesThroughOptions() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.syncToBeat == 1.0) // Sync by default
pedal.cycleSyncMode()
#expect(pedal.syncToBeat == 0.0, "cycle → Free")
pedal.cycleSyncMode()
#expect(pedal.syncToBeat == 1.0, "cycle wraps back → Sync")
}
@Test func stopResumeAndCueStop() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop()
pedal.pressLoop() // playing
#expect(pedal.transportState == .playing)
pedal.stopPlayback()
#expect(pedal.transportState == .stopped)
#expect(pedal.isPlaying == 0.0)
#expect(pedal.loopButtonCaption == "Play")
pedal.pressLoop() // resume
#expect(pedal.transportState == .playing)
#expect(pedal.isPlaying == 1.0)
// Cue Stop arms while playing (routine waits; engine idle so it never fires here).
#expect(!pedal.isStopAtLoopEndArmed)
pedal.toggleStopAtLoopEnd()
#expect(pedal.isStopAtLoopEndArmed)
pedal.toggleStopAtLoopEnd()
#expect(!pedal.isStopAtLoopEndArmed)
} }
}
}
@@ -0,0 +1,226 @@
// MIDIControllerCCTests.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("MIDIController CC")
struct MIDIControllerCCTests {
/// Builds an engine + a one-board rig whose first pedal is a Volume pedal, plus a controller.
private func makeRig() throws -> (MIDIController, ShoeGaze, PedalBoard, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 128)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
// Add the pedal directly (not via appendPedal, which rebuilds and replaces the board and
// would leave this `board` reference stale).
try board.add(VolumePedal())
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
return (controller, sg, board, url)
}
/// An address-only pedal-control CC target by pedal id (hints filled at capture time).
private func pedalControl(_ pedalID: UUID, _ control: Int) -> MIDIMap.CCTarget {
.pedalControl(pedalID: pedalID, controlIndex: control,
pedalNameHint: nil, controlLabelHint: nil)
}
@Test func learnCapturesBindingAndFiresCallback() throws {
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
var mapChanged: Bool = false
controller.onMapChanged = { mapChanged = true }
// Position is control 0 on a Volume pedal.
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64))
#expect(controller.learnTarget == nil, "learn should clear after capture")
#expect(mapChanged, "onMapChanged should fire on capture")
let binding: MIDIMap.CCBinding? = controller.ccBinding(for: pedalControl(board.pedals[0].id, 0))
#expect(binding?.controller == 20)
if case .pedalControl(_, _, let nameHint, let labelHint)? = binding?.target {
#expect(nameHint == "Volume")
#expect(labelHint == "Position")
} else {
Issue.record("expected a pedalControl target with captured hints")
}
#expect(sg.midiMap?.ccs.count == 1)
}
@Test func boundCCDrivesControlAcrossItsRange() throws {
// `sg` must be retained: MIDIController holds it weakly, so binding it to `_` would let the
// rig deallocate and every message no-op.
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node // Position, 0...1
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127))
#expect(abs(node.value - 1.0) < 1e-9, "CC 127 should map to the control max")
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64))
#expect(abs(node.value - 64.0 / 127.0) < 1e-9, "CC 64 should map mid-range")
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
#expect(abs(node.value - 0.0) < 1e-9, "CC 0 should map to the control min")
}
}
@Test func ccCanTargetBoardMasterLevel() throws {
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
guard let levelNode: UIParamNode = board.masterGainNode else {
Issue.record("board should have a master-gain node after finalize")
return
}
let target: MIDIMap.CCTarget = .boardLevel(boardID: board.id, boardLabelHint: nil)
controller.armCCLearn(target)
controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 0)) // learn
controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 127))
#expect(abs(levelNode.value - 1.0) < 1e-9, "CC 127 should drive board level to max")
controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 0))
#expect(abs(levelNode.value - 0.0) < 1e-9, "CC 0 should drive board level to min")
}
}
@Test func ccCanTargetASliderControl() throws {
// A pedal whose controls include vertical-fader sliders (e.g. Graphic EQ bands) must expose
// those sliders as CC targets, not only its rotary knobs.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(GraphicEQPedal())
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
withExtendedLifetime(sg) {
let pedal: Pedal = board.pedals[0]
#expect(pedal.ccMappableControls.count > pedal.knobs.count, "sliders should be mappable")
let sliderIndex: Int = pedal.knobs.count // first control past the knobs is a slider
let control: PedalControl = pedal.ccMappableControls[sliderIndex]
controller.armCCLearn(pedalControl(pedal.id, sliderIndex))
controller.ingestForTesting(.controlChange(channel: 0, controller: 30, value: 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 30, value: 127))
#expect(abs(control.node.value - control.range.upperBound) < 1e-9,
"CC 127 should drive the slider to its max")
}
}
@Test func invertedCCReversesTheSweep() throws {
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.setCCInverted(for: pedalControl(board.pedals[0].id, 0), true)
#expect(controller.isCCInverted(for: pedalControl(board.pedals[0].id, 0)))
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127))
#expect(abs(node.value - 0.0) < 1e-9, "inverted CC 127 should map to the control min")
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
#expect(abs(node.value - 1.0) < 1e-9, "inverted CC 0 should map to the control max")
}
}
@Test func oneCCDrivesMultipleControlsForCrossfade() throws {
// Assigning a second control to a CC must NOT steal it from the first — a single expression
// pedal can crossfade by driving two controls (one inverted).
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Control 0 = Position, control 1 = Mix on a Volume pedal.
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.armCCLearn(pedalControl(board.pedals[0].id, 1))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.setCCInverted(for: pedalControl(board.pedals[0].id, 1), true)
// Both bindings survive — the same CC drives both controls.
#expect(sg.midiMap?.ccs.count == 2, "assigning a 2nd control must not steal the 1st")
#expect(controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) != nil)
let position: UIParamNode = board.pedals[0].ccMappableControls[0].node
let mix: UIParamNode = board.pedals[0].ccMappableControls[1].node
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127))
#expect(abs(position.value - 1.0) < 1e-9, "position sweeps up")
#expect(abs(mix.value - 0.0) < 1e-9, "inverted mix sweeps down — a crossfade")
}
}
@Test func ccCanTargetRigVolume() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armCCLearn(.rigVolume)
controller.ingestForTesting(.controlChange(channel: 0, controller: 40, value: 0)) // learn
controller.ingestForTesting(.controlChange(channel: 0, controller: 40, value: 127))
#expect(abs(sg.rigVolume - 1.0) < 1e-9, "CC 127 should drive rig volume to max")
controller.ingestForTesting(.controlChange(channel: 0, controller: 40, value: 0))
#expect(abs(sg.rigVolume - 0.0) < 1e-9, "CC 0 should drive rig volume to min")
controller.ingestForTesting(.controlChange(channel: 0, controller: 40, value: 64))
#expect(abs(sg.rigVolume - 64.0 / 127.0) < 1e-9, "CC 64 should map mid-range")
}
}
@Test func unboundCCIsIgnored() throws {
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node
let before: Double = node.value
// No binding learned → an incoming CC must not touch anything.
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127))
#expect(node.value == before)
}
}
@Test func channelFilterBlocksOtherChannels() throws {
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Learn on channel 0 (the binding captures that channel).
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node
node.update(0.5)
// A CC on a different channel must not drive the channel-0 binding.
controller.ingestForTesting(.controlChange(channel: 5, controller: 20, value: 127))
#expect(abs(node.value - 0.5) < 1e-9, "CC on a non-matching channel should be ignored")
}
}
@Test func clearRemovesBinding() throws {
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
#expect(sg.midiMap?.ccs.isEmpty == false)
controller.clearCCBinding(for: pedalControl(board.pedals[0].id, 0))
#expect(controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) == nil)
#expect(sg.midiMap?.ccs.isEmpty == true)
}
}
@@ -0,0 +1,336 @@
// MIDIControllerPCTests.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("MIDIController Program Change")
struct MIDIControllerPCTests {
/// Builds an engine + a rig of `boardCount` boards (each with one Volume pedal) + a controller.
private func makeRig(boardCount: Int = 1) throws -> (MIDIController, ShoeGaze, [PedalBoard], URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
var boards: [PedalBoard] = []
for index: Int in 0 ..< boardCount {
let board: PedalBoard = try sg.addBoard()
board.label = "Board \(index + 1)"
try board.add(VolumePedal())
try sg.finalizeBoard(board)
boards.append(board)
}
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
return (controller, sg, boards, url)
}
@Test func learnCapturesSwitchAndFiresCallback() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
var changed: Bool = false
controller.onMapChanged = { changed = true }
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 7))
#expect(controller.learnTarget == nil)
#expect(changed)
#expect(controller.switchBinding(for: .rigBypass)?.program == 7)
#expect(sg.midiMap?.switches.count == 1)
}
}
@Test func rigBypassLatchesOnEachPress() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 1)) // learn only
#expect(sg.rigBypassed == false, "learn must not toggle")
controller.ingestForTesting(.programChange(channel: 0, program: 1))
#expect(sg.rigBypassed == true, "first press engages")
controller.ingestForTesting(.programChange(channel: 0, program: 1))
#expect(sg.rigBypassed == false, "second press releases")
}
}
@Test func rigMuteLatchesOnEachPressAndIsSeparateFromBypass() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigMute)
controller.ingestForTesting(.programChange(channel: 0, program: 1)) // learn only
#expect(sg.rigMuted == false, "learn must not toggle")
controller.ingestForTesting(.programChange(channel: 0, program: 1))
#expect(sg.rigMuted == true, "first press mutes")
#expect(sg.rigBypassed == false, "mute must not engage bypass")
controller.ingestForTesting(.programChange(channel: 0, program: 1))
#expect(sg.rigMuted == false, "second press unmutes")
}
}
@Test func pedalBypassLatches() throws {
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
let node: UIParamNode = boards[0].pedals[0].$bypass
controller.armSwitchLearn(.pedalBypass(pedalID: boards[0].pedals[0].id))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
#expect(node.value == 0.0)
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(abs(node.value - 1.0) < 1e-9, "first press bypasses")
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(abs(node.value - 0.0) < 1e-9, "second press re-engages")
}
}
@Test func boardBypassLatches() throws {
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.boardBypass(boardID: boards[0].id))
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 3))
#expect(sg.isBoardBypassed(boards[0]) == true)
controller.ingestForTesting(.programChange(channel: 0, program: 3))
#expect(sg.isBoardBypassed(boards[0]) == false)
}
}
@Test func boardSoloIsExclusiveRadio() throws {
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) =
try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.boardSolo(boardID: boards[1].id))
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // solo board 2
#expect(sg.activeBoardIndex == 1)
#expect(sg.isBoardAudible(boards[1]) == true)
#expect(sg.isBoardAudible(boards[0]) == false)
}
}
@Test func allBoardsActionCancelsSolo() throws {
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) =
try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Solo board 2 first, then map + fire the All-Boards action.
sg.soloBoard(boards[1], crossfadeSeconds: 0)
#expect(sg.activeBoardIndex == 1)
controller.armSwitchLearn(.allBoards)
controller.ingestForTesting(.programChange(channel: 0, program: 4)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 4)) // fire
#expect(sg.activeBoardIndex == nil, "All Boards should clear the solo")
#expect(sg.isBoardAudible(boards[0]) == true)
#expect(sg.isBoardAudible(boards[1]) == true)
}
}
@Test func channelFilterBlocksOtherChannels() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 1)) // learn on ch 0
controller.ingestForTesting(.programChange(channel: 4, program: 1)) // other channel
#expect(sg.rigBypassed == false, "PC on a non-matching channel should be ignored")
}
}
@Test func staleOutOfRangeBindingIsIgnored() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Bind to a pedal id that doesn't exist in the rig; applying it must be a safe no-op.
let ghostID: UUID = UUID()
controller.armSwitchLearn(.pedalBypass(pedalID: ghostID))
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // apply — no crash
#expect(controller.switchBinding(for: .pedalBypass(pedalID: ghostID)) != nil)
}
}
@Test func oneProgramCanDriveMultipleActions() throws {
// A single footswitch (PC) may drive several toggles at once — a "scene".
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) =
try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 8))
controller.armSwitchLearn(.pedalBypass(pedalID: boards[0].pedals[0].id))
controller.ingestForTesting(.programChange(channel: 0, program: 8)) // same PC, kept
// Both bindings survive — one PC drives two actions.
#expect(controller.switchBinding(for: .rigBypass)?.program == 8)
#expect(controller.switchBinding(for: .pedalBypass(pedalID: boards[0].pedals[0].id))?.program == 8)
#expect(sg.midiMap?.switches.count == 2)
// Firing the PC toggles both at once.
let pedalBypass: UIParamNode = boards[0].pedals[0].$bypass
controller.ingestForTesting(.programChange(channel: 0, program: 8))
#expect(sg.rigBypassed == true)
#expect(abs(pedalBypass.value - 1.0) < 1e-9)
}
}
@Test func reLearningAnActionReplacesItsProgram() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 8))
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 9)) // same action, new PC
#expect(controller.switchBinding(for: .rigBypass)?.program == 9, "re-learn replaces")
#expect(sg.midiMap?.switches.count == 1)
}
}
@Test func tunerToggleFlipsEngagedState() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.tunerToggle)
controller.ingestForTesting(.programChange(channel: 0, program: 10)) // learn only
#expect(!sg.tunerEngaged)
controller.ingestForTesting(.programChange(channel: 0, program: 10))
#expect(sg.tunerEngaged, "first press engages")
controller.ingestForTesting(.programChange(channel: 0, program: 10))
#expect(!sg.tunerEngaged, "second press disengages")
}
}
@Test func tapTempoRegistersEachPress() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.tapTempo)
controller.ingestForTesting(.programChange(channel: 0, program: 11)) // learn only
#expect(sg.tapTimestamps.isEmpty)
controller.ingestForTesting(.programChange(channel: 0, program: 11))
#expect(sg.tapTimestamps.count == 1, "first press registers a tap")
controller.ingestForTesting(.programChange(channel: 0, program: 11))
#expect(sg.tapTimestamps.count == 2, "second press registers a second tap")
}
}
@Test func pedalActionDispatchesLooperRecordStop() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let looper: LooperPedal = LooperPedal()
try board.add(looper)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperRecordStop))
controller.ingestForTesting(.programChange(channel: 0, program: 12)) // learn only
#expect(looper.transportState == .clear)
// The looper was added via the board, so it carries the shared tempo clock and its
// transport is beat-quantized: the mapped press arms recording for the next beat.
// Asserting the arm proves the Program Change dispatched to the pedal's action.
controller.ingestForTesting(.programChange(channel: 0, program: 12))
#expect(looper.transportState == .armedRecord,
"mapped Program Change should dispatch the looper record/stop action")
}
}
@Test func pedalActionDispatchesLooperReverse() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let looper: LooperPedal = LooperPedal()
try board.add(looper)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperReverse))
controller.ingestForTesting(.programChange(channel: 0, program: 20)) // learn only
#expect(looper.reverse == 0.0)
controller.ingestForTesting(.programChange(channel: 0, program: 20)) // fire → toggleReverse
#expect(looper.reverse == 1.0, "mapped Program Change should flip the looper's reverse")
}
}
@Test func pedalActionCyclesLooperSync() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let looper: LooperPedal = LooperPedal()
try board.add(looper)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperSyncToggle))
controller.ingestForTesting(.programChange(channel: 0, program: 21)) // learn only
#expect(looper.syncToBeat == 1.0)
controller.ingestForTesting(.programChange(channel: 0, program: 21)) // fire → cycle
#expect(looper.syncToBeat == 0.0, "mapped Program Change should oscillate Sync through its options")
}
}
@Test func pedalActionTapsLooperTrack() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let looper: LooperPedal = LooperPedal()
try board.add(looper)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Get a recorded, selected track A (immediate transport).
looper.clock = nil
looper.pressLoop()
looper.pressLoop()
#expect(looper.trackHasContent(0))
#expect(!looper.isTrackMuted(0))
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperTrack(index: 0)))
controller.ingestForTesting(.programChange(channel: 0, program: 22)) // learn only
#expect(!looper.isTrackMuted(0))
controller.ingestForTesting(.programChange(channel: 0, program: 22)) // fire → tapTrack(0) → mute A
#expect(looper.isTrackMuted(0), "mapped Program Change should tap (mute) the selected recorded track")
}
}
}
@@ -0,0 +1,82 @@
// MIDIMapCodableTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@MainActor
@Suite("MIDIMap persistence")
struct MIDIMapCodableTests {
// Fixed ids so the round-trip comparison is deterministic.
private static let boardID: UUID = UUID()
private static let looperID: UUID = UUID()
private static let volumeID: UUID = UUID()
private func sampleMap() -> MIDIMap {
MIDIMap(
switches: [
MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"),
MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardID: Self.boardID), displayNameHint: "Board 2"),
MIDIMap.SwitchBinding(program: 5, action: .tunerToggle),
MIDIMap.SwitchBinding(program: 6, action: .tapTempo),
MIDIMap.SwitchBinding(
program: 7,
action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop),
displayNameHint: "Looper"
),
],
ccs: [
MIDIMap.CCBinding(
controller: 7,
channel: 0,
target: .pedalControl(
pedalID: Self.volumeID, controlIndex: 0,
pedalNameHint: "Volume", controlLabelHint: "Position"
)
),
MIDIMap.CCBinding(
controller: 11,
channel: 0,
target: .boardLevel(boardID: Self.boardID, boardLabelHint: "Board 1")
),
]
)
}
@Test func mapRoundTrips() throws {
let map: MIDIMap = sampleMap()
let data: Data = try JSONEncoder().encode(map)
let decoded: MIDIMap = try JSONDecoder().decode(MIDIMap.self, from: data)
#expect(decoded == map)
}
@Test func rigStateEmbedsAndRestoresMap() throws {
let state: ShoeGazeState = ShoeGazeState(boards: [], midiMap: sampleMap())
let data: Data = try JSONEncoder().encode(state)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.midiMap == sampleMap())
}
@Test func malformedMidiMapDropsBindingsNotTheRig() throws {
// A midiMap in a shape this build can't read (e.g. an older binding schema) must NOT throw
// and lose the whole rig — it drops just the (re-learnable) bindings.
let json: String = #"{"version":1,"boards":[],"midiMap":{"switches":"not-an-array","ccs":42}}"#
let data: Data = Data(json.utf8)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.midiMap == nil, "an unreadable midiMap should decode to nil, not throw")
#expect(decoded.version == 1)
}
@Test func oldRigWithoutMapDecodesToNil() throws {
// A rig saved before MIDI mapping existed has no `midiMap` key at all.
let legacyJSON: String = #"{"version":1,"boards":[]}"#
let data: Data = Data(legacyJSON.utf8)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.midiMap == nil, "legacy rig JSON should decode with a nil midiMap")
}
}
@@ -0,0 +1,108 @@
// MIDIMapMigrationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Legacy MIDI map migration")
struct MIDIMapMigrationTests {
/// Two boards; board 0 has two pedals, board 1 has one — with fixed ids to assert against.
private func sampleBoards() -> [BoardState] {
let od: PedalState = PedalState(type: "Overdrive", knobValues: [], bypass: 0)
let rv: PedalState = PedalState(type: "Reverb", knobValues: [], bypass: 0)
let dl: PedalState = PedalState(type: "Delay", knobValues: [], bypass: 0)
return [
BoardState(label: "Board 1", pedals: [od, rv]),
BoardState(label: "Board 2", pedals: [dl]),
]
}
// MARK: - Unit: positional → id conversion
@Test func migratesPositionalBindingsToIds() {
let boards: [BoardState] = sampleBoards()
let legacy: LegacyMIDIMap = LegacyMIDIMap(
switches: [
LegacyMIDIMap.LegacySwitchBinding(program: 1, channel: nil, action: .rigBypass, displayNameHint: nil),
LegacyMIDIMap.LegacySwitchBinding(program: 2, channel: nil, action: .boardBypass(boardIndex: 1), displayNameHint: "Board 2"),
LegacyMIDIMap.LegacySwitchBinding(program: 3, channel: nil, action: .pedalBypass(boardIndex: 0, pedalIndex: 1), displayNameHint: "Reverb"),
],
ccs: [
LegacyMIDIMap.LegacyCCBinding(controller: 7, channel: nil,
target: .pedalControl(boardIndex: 0, pedalIndex: 0, controlIndex: 2, pedalNameHint: "Overdrive", controlLabelHint: "Level"),
inverted: false),
LegacyMIDIMap.LegacyCCBinding(controller: 11, channel: nil,
target: .boardLevel(boardIndex: 1, boardLabelHint: "Board 2"), inverted: false),
]
)
let migrated: MIDIMap = legacy.migrated(boards: boards)
#expect(migrated.switches[0].action == .rigBypass)
#expect(migrated.switches[1].action == .boardBypass(boardID: boards[1].id))
#expect(migrated.switches[2].action == .pedalBypass(pedalID: boards[0].pedals[1].id))
#expect(migrated.ccs[0].target == .pedalControl(
pedalID: boards[0].pedals[0].id, controlIndex: 2,
pedalNameHint: "Overdrive", controlLabelHint: "Level"))
#expect(migrated.ccs[1].target == .boardLevel(boardID: boards[1].id, boardLabelHint: "Board 2"))
}
@Test func dropsOutOfRangeBindings() {
let boards: [BoardState] = sampleBoards()
let legacy: LegacyMIDIMap = LegacyMIDIMap(
switches: [
LegacyMIDIMap.LegacySwitchBinding(program: 1, channel: nil, action: .pedalBypass(boardIndex: 0, pedalIndex: 9), displayNameHint: nil),
LegacyMIDIMap.LegacySwitchBinding(program: 2, channel: nil, action: .boardSolo(boardIndex: 5), displayNameHint: nil),
],
ccs: []
)
let migrated: MIDIMap = legacy.migrated(boards: boards)
#expect(migrated.switches.isEmpty, "bindings addressing a non-existent board/pedal are dropped")
}
// MARK: - Integration: legacy JSON decodes through ShoeGazeState
@Test func legacyFormatJSONDecodesAndMigrates() throws {
let boards: [BoardState] = sampleBoards()
let legacy: LegacyMIDIMap = LegacyMIDIMap(
switches: [
LegacyMIDIMap.LegacySwitchBinding(program: 3, channel: 0, action: .pedalBypass(boardIndex: 0, pedalIndex: 1), displayNameHint: "Reverb"),
],
ccs: []
)
// Build the raw rig JSON with the *legacy* midiMap encoding spliced in — exactly what an
// old saved rig on disk looks like (boards may or may not carry ids; midiMap is positional).
var dict: [String: Any] = [
"version": presetFormatVersion,
"boards": try jsonObject(boards),
"midiMap": try jsonObject(legacy),
]
// Sanity: the spliced midiMap is the positional shape, not the id shape.
#expect(((dict["midiMap"] as? [String: Any])?["switches"] as? [Any])?.isEmpty == false)
let data: Data = try JSONSerialization.data(withJSONObject: dict)
let state: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
let map: MIDIMap = try #require(state.midiMap, "legacy midiMap should migrate, not drop to nil")
#expect(map.switches.count == 1)
// The board ids in `state.boards` are what migration used — assert the binding points at
// the Reverb (board 0, pedal 1) by that board's decoded pedal id.
#expect(map.switches[0].action == .pedalBypass(pedalID: state.boards[0].pedals[1].id))
_ = dict.removeValue(forKey: "midiMap")
}
/// Encodes a `Codable` value and re-reads it as a JSON object for splicing.
private func jsonObject<T: Encodable>(_ value: T) throws -> Any {
let data: Data = try JSONEncoder().encode(value)
return try JSONSerialization.jsonObject(with: data)
}
}
@@ -0,0 +1,148 @@
// MIDIMapReindexTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// MIDI bindings address pedals/boards by stable UUID, so they follow their target through
/// structural edits with no reindexing. These tests assert the identity round-trips through the
/// edit API's capture → rebuild, and that a binding resolves to (and only to) its pedal.
@MainActor
@Suite("MIDIMap identity")
struct MIDIMapReindexTests {
private func makeRig(_ pedals: [String]) throws -> (ShoeGaze, MIDIController, URL, PedalBoard) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
for type: String in pedals {
if let pedal: Pedal = PedalRegistry.makePedal(type: type) { try board.add(pedal) }
}
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
return (sg, controller, url, board)
}
// MARK: - Identity preservation across edits
@Test func pedalKeepsIdThroughInsertAndMove() throws {
let (sg, _, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Overdrive", "Delay", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
let reverbID: UUID = board.pedals[2].id
// Insert a Fuzz at the front → Reverb slides to index 3 but keeps its id.
let afterInsert: PedalBoard = try sg.insertPedal(.fuzz, at: 0, to: board)
#expect(afterInsert.pedals.count == 4)
#expect(afterInsert.pedals[3].id == reverbID, "Reverb keeps its id after an insert before it")
// Move it to the front → still the same id.
let afterMove: PedalBoard = try sg.movePedal(from: 3, to: 0, in: afterInsert)
#expect(afterMove.pedals[0].id == reverbID, "Reverb keeps its id after a move")
}
@Test func pedalIdSurvivesSaveLoadRoundTrip() throws {
let (sg, _, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Overdrive", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
let ids: [UUID] = board.pedals.map { $0.id }
// Full Codable round-trip (what save/load to disk does).
let data: Data = try JSONEncoder().encode(sg.captureState())
let state: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url2) }
let sg2: ShoeGaze = ShoeGaze(engine: engine2)
try sg2.loadRig(from: state)
#expect(sg2.boards.first?.pedals.map { $0.id } == ids, "pedal ids persist across save/load")
}
@Test func boardKeepsIdThroughReorder() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let b0: PedalBoard = try sg.addBoard(); try sg.finalizeBoard(b0)
let b1: PedalBoard = try sg.addBoard(); try sg.finalizeBoard(b1)
let id0: UUID = b0.id
let id1: UUID = b1.id
sg.moveBoard(b1, to: 0)
#expect(sg.boards[0].id == id1)
#expect(sg.boards[1].id == id0)
}
// MARK: - Binding follows the pedal (end-to-end via the controller)
@Test func bypassBindingFollowsPedalAfterInsert() throws {
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Overdrive", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Map program 5 to the Reverb's bypass (pedal index 1).
let reverbID: UUID = board.pedals[1].id
controller.armSwitchLearn(.pedalBypass(pedalID: reverbID))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
// Insert a Fuzz at the front — Reverb moves to index 2, keeps its id.
let edited: PedalBoard = (try? sg.insertPedal(.fuzz, at: 0, to: board)) ?? board
let reverb: Pedal = edited.pedals.first { $0.id == reverbID }!
#expect(edited.pedals.firstIndex { $0.id == reverbID } == 2)
// Firing the binding must still toggle the Reverb (not whatever is at the old index).
#expect(reverb.$bypass.value == 0.0)
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(abs(reverb.$bypass.value - 1.0) < 1e-9, "binding follows the pedal, not the index")
}
}
@Test func bindingToRemovedPedalIsInert() throws {
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Overdrive", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
let overdriveID: UUID = board.pedals[0].id
controller.armSwitchLearn(.pedalBypass(pedalID: overdriveID))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
// Remove the mapped Overdrive. Firing the binding must not crash or touch the Reverb.
let edited: PedalBoard = (try? sg.removePedal(at: 0, from: board)) ?? board
let reverbBypassBefore: Double = edited.pedals[0].$bypass.value
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(edited.pedals[0].$bypass.value == reverbBypassBefore,
"a binding to a removed pedal is inert — it must not fall through to another pedal")
}
}
@Test func sameTypePedalsBindIndependently() throws {
// The case the positional model got wrong: two identical-type pedals, each with its own
// binding, resolve independently by id even after reordering.
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Delay", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
let firstDelayID: UUID = board.pedals[0].id
controller.armSwitchLearn(.pedalBypass(pedalID: firstDelayID))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
// Swap the two Delays.
let edited: PedalBoard = (try? sg.movePedal(from: 0, to: 1, in: board)) ?? board
let firstDelay: Pedal = edited.pedals.first { $0.id == firstDelayID }!
let otherDelay: Pedal = edited.pedals.first { $0.id != firstDelayID }!
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(abs(firstDelay.$bypass.value - 1.0) < 1e-9, "binding drives the originally-mapped Delay")
#expect(otherDelay.$bypass.value == 0.0, "the other same-type Delay is untouched")
}
}
}
@@ -0,0 +1,83 @@
// PlateReverbPedalTests.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("PlateReverbPedal")
struct PlateReverbPedalTests {
private func render(configure: (PlateReverbPedal) -> Void) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.2, 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: PlateReverbPedal = PlateReverbPedal(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 totalSSD(_ a: [Float], _ b: [Float]) -> Double {
zip(a, b).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render { _ in }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "plate reverb output was silent")
}
@Test func toneChangesOutput() throws {
// `tone` (input bandwidth) alters the signal immediately, unlike `decay` whose effect lives
// in the recirculating tail beyond this short render window.
let dark: [Float] = try render { pedal in pedal.tone = 0.1; pedal.mix = 1.0 }
let bright: [Float] = try render { pedal in pedal.tone = 1.0; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(bright), "bright plate was silent")
#expect(totalSSD(dark, bright) > 0, "changing tone did not change the output")
}
@Test func exposesDecayToneDampModKnobs() throws {
let pedal: PlateReverbPedal = PlateReverbPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Decay", "Tone", "Damp", "Mod"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: PlateReverbPedal = PlateReverbPedal()
pedal.decay = 0.5
pedal.mod = 0.25
let state: PedalState = pedal.captureState()
let restored: PlateReverbPedal = PlateReverbPedal()
restored.applyState(state)
#expect(restored.decay == 0.5)
#expect(restored.mod == 0.25)
}
@Test func registeredInBuiltInRegistry() throws {
#expect(PedalRegistry.makePedal(type: "Plate Reverb") is PlateReverbPedal)
}
}
@@ -14,9 +14,25 @@ import LyrebirdUI
@Suite("RigStore")
struct RigStoreTests {
/// Redirects `RigStore` to a unique temp file so the suite never touches — let alone
/// overwrites or deletes — the running app's real autosave in Application Support. Returns
/// the temp file URL (its parent directory is created).
private func isolateAutosave() throws -> URL {
let dir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("RigStoreTests-" + UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let file: URL = dir.appendingPathComponent("autosave-rig.json")
RigStore.autosaveURLOverride = file
return file
}
@Test func savesAndRestoresAcrossInstances() throws {
let autosave: URL = try isolateAutosave()
defer {
RigStore.autosaveURLOverride = nil
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
}
RigStore.clear()
defer { RigStore.clear() }
// Build a rig and autosave it.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
@@ -42,7 +58,37 @@ struct RigStoreTests {
#expect(b.boards.last?.label == "Clean")
}
@Test func restorePreservesCurrentRigID() throws {
let autosave: URL = try isolateAutosave()
defer {
RigStore.autosaveURLOverride = nil
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
}
RigStore.clear()
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 board: PedalBoard = try a.addBoard()
try a.appendPedal(.overdrive, to: board)
try a.finalizeBoard(board)
let rigID: UUID = UUID()
a.currentRigID = rigID
#expect(RigStore.save(a))
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.currentRigID == rigID, "restore must carry the source-rig id so the UI highlights it")
}
@Test func restoreReturnsFalseWhenNoAutosave() throws {
let autosave: URL = try isolateAutosave()
defer {
RigStore.autosaveURLOverride = nil
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
}
RigStore.clear()
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
@@ -0,0 +1,81 @@
// RoomReverbPedalTests.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("RoomReverbPedal")
struct RoomReverbPedalTests {
private func render(configure: (RoomReverbPedal) -> Void) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.2, 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: RoomReverbPedal = RoomReverbPedal(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 totalSSD(_ a: [Float], _ b: [Float]) -> Double {
zip(a, b).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render { _ in }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "room reverb output was silent")
}
@Test func sizeChangesOutput() throws {
let small: [Float] = try render { pedal in pedal.size = 5.0; pedal.mix = 1.0 }
let large: [Float] = try render { pedal in pedal.size = 90.0; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(large), "large-room reverb was silent")
#expect(totalSSD(small, large) > 0, "changing size did not change the output")
}
@Test func exposesSizeDecayDampTailKnobs() throws {
let pedal: RoomReverbPedal = RoomReverbPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Size", "Decay", "Damp", "Tail"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: RoomReverbPedal = RoomReverbPedal()
pedal.size = 50.0
pedal.decay = 6.0
let state: PedalState = pedal.captureState()
let restored: RoomReverbPedal = RoomReverbPedal()
restored.applyState(state)
#expect(restored.size == 50.0)
#expect(restored.decay == 6.0)
}
@Test func registeredInBuiltInRegistry() throws {
#expect(PedalRegistry.makePedal(type: "Room Reverb") is RoomReverbPedal)
}
}
@@ -0,0 +1,81 @@
// SpringReverbPedalTests.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("SpringReverbPedal")
struct SpringReverbPedalTests {
private func render(configure: (SpringReverbPedal) -> Void) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.2, 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: SpringReverbPedal = SpringReverbPedal(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 totalSSD(_ a: [Float], _ b: [Float]) -> Double {
zip(a, b).reduce(0.0) { acc, pair in
let diff: Double = Double(pair.0 - pair.1)
return acc + diff * diff
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render { _ in }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "spring reverb output was silent")
}
@Test func tensionChangesOutput() throws {
let low: [Float] = try render { pedal in pedal.tension = 0.1; pedal.mix = 1.0 }
let high: [Float] = try render { pedal in pedal.tension = 0.9; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(high), "high-tension spring was silent")
#expect(totalSSD(low, high) > 0, "changing tension did not change the output")
}
@Test func exposesDecayTensionDampKnobs() throws {
let pedal: SpringReverbPedal = SpringReverbPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Decay", "Tension", "Damp"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: SpringReverbPedal = SpringReverbPedal()
pedal.decay = 3.0
pedal.tension = 0.2
let state: PedalState = pedal.captureState()
let restored: SpringReverbPedal = SpringReverbPedal()
restored.applyState(state)
#expect(restored.decay == 3.0)
#expect(restored.tension == 0.2)
}
@Test func registeredInBuiltInRegistry() throws {
#expect(PedalRegistry.makePedal(type: "Spring Reverb") is SpringReverbPedal)
}
}
@@ -84,21 +84,30 @@ func readStereoCAF(url: URL, sampleRate: Double = 44100.0) -> [Float] {
&clientFormat
) == noErr else { return [] }
let readFrames: UInt32 = 4096
var samples: [Float] = [Float](repeating: 0, count: Int(readFrames) * 2)
var framesRead: UInt32 = readFrames
samples.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: 2,
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
mData: ptr.baseAddress
// Read the whole file in fixed-size chunks — a single `ExtAudioFileRead` call only
// fills one chunk's worth of frames, so anything past `chunkFrames` would otherwise be
// silently dropped for renders longer than one chunk.
let chunkFrames: UInt32 = 4096
var chunk: [Float] = [Float](repeating: 0, count: Int(chunkFrames) * 2)
var allSamples: [Float] = []
while true {
var framesRead: UInt32 = chunkFrames
chunk.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: 2,
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
mData: ptr.baseAddress
)
)
)
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
}
guard framesRead > 0 else { break }
allSamples.append(contentsOf: chunk.prefix(Int(framesRead) * 2))
if framesRead < chunkFrames { break }
}
return Array(samples.prefix(Int(framesRead) * 2))
return allSamples
}
// MARK: - Signal analysis
@@ -0,0 +1,83 @@
// TempoTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdShoeGaze
@MainActor
@Suite("ShoeGaze Tempo")
struct TempoTests {
private func makeShoeGaze(duration: Double = 0.1) -> (ShoeGaze, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 64)
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
return (shoeGaze, url)
}
@Test func clockDefaultsToStandardTempo() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
#expect(shoeGaze.clock.bpm == ShoeGaze.defaultTempoBpm)
}
@Test func tapTempoAtOneSecondIntervalsSetsSixtyBpm() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
// Simulate taps exactly 1s apart by manipulating the tap history directly —
// real taps come from wall-clock `Date()`, so back-date synthetic timestamps
// instead of sleeping the test for real seconds.
let now: Date = Date()
shoeGaze.tapTimestamps = [
now.addingTimeInterval(-3.0),
now.addingTimeInterval(-2.0),
now.addingTimeInterval(-1.0),
]
shoeGaze.tapTempo() // landing "now", completing four 1s-spaced taps
#expect(abs(shoeGaze.clock.bpm - 60.0) < 0.5)
}
@Test func singleTapDoesNotSetTempo() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
let startingBpm: Double = shoeGaze.clock.bpm
shoeGaze.tapTempo()
#expect(shoeGaze.clock.bpm == startingBpm, "A single tap has no interval to measure — tempo must not change")
}
@Test func longPauseResetsTapHistory() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
let now: Date = Date()
// Two taps 1s apart, then a long pause before the next tap.
shoeGaze.tapTimestamps = [now.addingTimeInterval(-10.0), now.addingTimeInterval(-9.0)]
shoeGaze.tapTempo()
#expect(shoeGaze.tapTimestamps.count == 1, "A >2s gap should discard prior taps and start a fresh sequence")
}
@Test func tapTempoRespectsBpmRangeViaClockPrecondition() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
let now: Date = Date()
// Very fast taps (well under minTapInterval == 0.2s) are filtered out of the average.
shoeGaze.tapTimestamps = [
now.addingTimeInterval(-0.15),
now.addingTimeInterval(-0.05),
]
let startingBpm: Double = shoeGaze.clock.bpm
shoeGaze.tapTempo()
// The sub-threshold interval is filtered; with no valid interval left the tempo
// is left unchanged rather than jumping to an implausible value.
#expect(shoeGaze.clock.bpm == startingBpm)
}
}
@@ -0,0 +1,52 @@
// TunerPitchReadingTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGazeUI
@Suite("TunerPitchReading")
struct TunerPitchReadingTests {
@Test func concertAIsA4WithZeroCents() {
let reading: TunerPitchReading = TunerPitchReading(hz: 440.0)
#expect(reading.noteName == "A4")
#expect(abs(reading.cents) < 0.5)
}
@Test func oneOctaveDownIsA3() {
let reading: TunerPitchReading = TunerPitchReading(hz: 220.0)
#expect(reading.noteName == "A3")
#expect(abs(reading.cents) < 0.5)
}
@Test func middleCIsC4() {
let reading: TunerPitchReading = TunerPitchReading(hz: 261.6256)
#expect(reading.noteName == "C4")
#expect(abs(reading.cents) < 1.0)
}
@Test func slightlySharpReportsPositiveCents() {
// ~20 cents sharp of A4.
let sharpHz: Double = 440.0 * pow(2.0, 20.0 / 1200.0)
let reading: TunerPitchReading = TunerPitchReading(hz: sharpHz)
#expect(reading.noteName == "A4")
#expect(reading.cents > 15.0 && reading.cents < 25.0)
}
@Test func slightlyFlatReportsNegativeCents() {
// ~20 cents flat of A4.
let flatHz: Double = 440.0 * pow(2.0, -20.0 / 1200.0)
let reading: TunerPitchReading = TunerPitchReading(hz: flatHz)
#expect(reading.noteName == "A4")
#expect(reading.cents < -15.0 && reading.cents > -25.0)
}
@Test func lowGuitarStringIsE2() {
let reading: TunerPitchReading = TunerPitchReading(hz: 82.41)
#expect(reading.noteName == "E2")
}
}
@@ -0,0 +1,91 @@
// TunerTapTests.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("TunerTap")
struct TunerTapTests {
/// A constant-frequency sine source — same shape as `LooperPedalTests.ToneSource`.
private final class ToneSource: SynthesizerBase {
private let targetBus: Int
private let toneFreq: Double
private let amplitude: Double
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
self.targetBus = targetBus
self.toneFreq = freq
self.amplitude = amplitude
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq, mul: amplitude))
}
}
@Test func detectsKnownFrequencyWithinTolerance() throws {
let toneFreq: Double = 220.0
// The YIN tracker decimates 8×, so its 512-sample window needs ~4096 input samples
// to fill plus several hops to converge — render generously.
let renderDuration: Double = 2.0
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let scratchControlBus: ControlBus = try engine.busAllocator.allocateControlBus()
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseControlBus(scratchControlBus)
}
let source: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
let tap: TunerTap = TunerTap(inputBusIndex: srcBus.index, scratchControlBus: scratchControlBus)
try engine.add(source)
try engine.add(tap, position: NodePosition.after(source))
try engine.start()
let capture: TunerPitchCapture = try #require(tap.pitchCapture)
let detected: Double = capture.detectedFrequencyHz
let tolerance: Double = 5.0
#expect(abs(detected - toneFreq) < tolerance, "Expected ~\(toneFreq) Hz, got \(detected) Hz")
#expect(capture.detectedConfidence > 0.5, "A pure tone should track with high confidence")
}
@Test func detectsLowGuitarEString() throws {
// E2 ≈ 82.4 Hz — below the undecimated FreqTracker floor (~173 Hz), so this only
// works because the tuner tap decimates before YIN analysis.
let toneFreq: Double = 82.41
let renderDuration: Double = 3.0
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let scratchControlBus: ControlBus = try engine.busAllocator.allocateControlBus()
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseControlBus(scratchControlBus)
}
let source: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
let tap: TunerTap = TunerTap(inputBusIndex: srcBus.index, scratchControlBus: scratchControlBus)
try engine.add(source)
try engine.add(tap, position: NodePosition.after(source))
try engine.start()
let capture: TunerPitchCapture = try #require(tap.pitchCapture)
let detected: Double = capture.detectedFrequencyHz
let tolerance: Double = 3.0
#expect(abs(detected - toneFreq) < tolerance, "Expected ~\(toneFreq) Hz (low E), got \(detected) Hz")
}
}
@@ -0,0 +1,123 @@
// TunerTests.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("ShoeGaze Tuner")
struct TunerTests {
private func makeShoeGaze(duration: Double) -> (ShoeGaze, SynthesisEngine, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 64)
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
return (shoeGaze, engine, url)
}
@Test func engageAddsTapAndDisengageRemovesIt() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.2)
defer { try? FileManager.default.removeItem(at: url) }
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
#expect(!shoeGaze.tunerEngaged)
#expect(shoeGaze.currentPitchHz == nil)
shoeGaze.engageTuner()
#expect(shoeGaze.tunerEngaged)
try engine.start()
#expect(shoeGaze.currentPitchHz != nil)
shoeGaze.disengageTuner()
#expect(!shoeGaze.tunerEngaged)
#expect(shoeGaze.currentPitchHz == nil)
}
@Test func engagingWithMuteOnMutesRigAndDisengageRestores() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.tunerMutesRig = true
#expect(!shoeGaze.rigMuted)
shoeGaze.engageTuner()
#expect(shoeGaze.rigMuted, "Engaging with tunerMutesRig=true should mute the rig")
shoeGaze.disengageTuner()
#expect(!shoeGaze.rigMuted, "Disengaging should restore the pre-engage mute state")
}
@Test func disengageRestoresPriorMutedStateNotAlwaysUnmuted() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.tunerMutesRig = true
shoeGaze.setRigMuted(true) // already muted before engaging, for an unrelated reason
shoeGaze.engageTuner()
#expect(shoeGaze.rigMuted)
shoeGaze.disengageTuner()
#expect(shoeGaze.rigMuted, "Rig was already muted before engaging — disengage must not unmute it")
}
@Test func tunerMutesRigFalseDoesNotTouchRigMute() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.tunerMutesRig = false
shoeGaze.engageTuner()
#expect(!shoeGaze.rigMuted)
shoeGaze.disengageTuner()
#expect(!shoeGaze.rigMuted)
}
@Test func toggleTunerEngagedFlipsState() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.toggleTunerEngaged()
#expect(shoeGaze.tunerEngaged)
shoeGaze.toggleTunerEngaged()
#expect(!shoeGaze.tunerEngaged)
}
@Test func engageIsANoOpWhenAlreadyEngaged() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.engageTuner()
shoeGaze.tunerMutesRig = false // change after first engage — should have no effect until re-engage
shoeGaze.engageTuner()
#expect(shoeGaze.rigMuted, "Second engageTuner() call while already engaged must be a no-op")
}
}
@@ -0,0 +1,73 @@
// VolumePedalTests.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("VolumePedal")
struct VolumePedalTests {
/// Renders a Volume pedal at the given position and returns the stereo output samples.
private func render(position: Double) throws -> [Float] {
let renderDuration: Double = 0.2
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
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: VolumePedal = VolumePedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.position = position
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 rms(_ samples: [Float]) -> Double {
guard !samples.isEmpty else { return 0 }
let sumSquares: Double = samples.reduce(0) { $0 + Double($1) * Double($1) }
return (sumSquares / Double(samples.count)).squareRoot()
}
@Test func buildsAndProducesNonSilentOutputAtUnity() throws {
let samples: [Float] = try render(position: 1.0)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "VolumePedal at unity produced silence")
}
@Test func zeroPositionIsSilent() throws {
let samples: [Float] = try render(position: 0.0)
#expect(!hasNonSilentOutput(samples), "VolumePedal at position 0 should be silent")
}
@Test func positionScalesLevelMonotonically() throws {
let full: Double = rms(try render(position: 1.0))
let half: Double = rms(try render(position: 0.5))
let quarter: Double = rms(try render(position: 0.25))
#expect(full > half, "position 1.0 should be louder than 0.5")
#expect(half > quarter, "position 0.5 should be louder than 0.25")
}
@Test func exposesPositionKnob() throws {
let pedal: VolumePedal = VolumePedal()
// Effect knob (before the common Mix/Level pair) is Position.
#expect(pedal.effectKnobs.map { $0.label } == ["Position"])
}
}
@@ -0,0 +1,80 @@
// WahPedalTests.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("WahPedal")
struct WahPedalTests {
/// Renders a Wah pedal at the given position / resonance and returns the stereo output.
private func render(position: Double, resonance: Double = 3.0) throws -> [Float] {
let renderDuration: Double = 0.2
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
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: WahPedal = WahPedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.position = position
pedal.resonance = resonance
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)
}
/// Mean absolute difference between two equal-length renders.
private func meanAbsDiff(_ a: [Float], _ b: [Float]) -> Double {
let count: Int = min(a.count, b.count)
guard count > 0 else { return 0 }
var sum: Double = 0
for i: Int in 0 ..< count {
sum += abs(Double(a[i]) - Double(b[i]))
}
return sum / Double(count)
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render(position: 0.5)
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "WahPedal produced silence")
}
@Test func differentPositionsProduceDifferentOutput() throws {
let heel: [Float] = try render(position: 0.0)
let toe: [Float] = try render(position: 1.0)
// Sweeping the cutoff must audibly change the filtered signal.
let diff: Double = meanAbsDiff(heel, toe)
#expect(diff > 1e-4, "heel and toe positions produced near-identical output (diff \(diff))")
}
@Test func resonanceChangesOutput() throws {
let low: [Float] = try render(position: 0.5, resonance: 0.7)
let high: [Float] = try render(position: 0.5, resonance: 8.0)
let diff: Double = meanAbsDiff(low, high)
#expect(diff > 1e-4, "resonance change produced near-identical output (diff \(diff))")
}
@Test func exposesPositionAndResonanceKnobs() throws {
let pedal: WahPedal = WahPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Position", "Resonance"])
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 401 KiB

After

Width:  |  Height:  |  Size: 766 KiB