53 Commits

Author SHA1 Message Date
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
josh b6a9dbbb91 Bump builder apps to 1.3.0
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 18:18:33 -07:00
josh ef20a0eb95 Open .shoegaze files: wire document handlers, scope type to builders
Registering the document type made the apps claim .shoegaze, but without an
open handler macOS reported "cannot open files in the ShoeGaze Document
format." Wire actual opening:

- macOS Builder: implement application(_:open:) — decode the document and
  import its rigs into the library (board files get an explanatory note),
  with a confirmation alert. Also migrate the File-menu Export/Import panels
  to .shoegaze (still importing legacy JSON).
- iOS Builder: add .onOpenURL and an importDocument(at:) on the app model.
- Drop the document-type declaration from the two minimal player demos
  (ShoeGazeDemo, ShoeGazeiOSDemo); they have no open/share UI, so only the
  two Builder apps should claim the type.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 18:11:44 -07:00
josh aeab19236b Share a real file so the macOS share sheet offers full services
ShareLink with a DataRepresentation hands the share sheet raw bytes, which
on macOS collapses the menu to just Copy / Edit Extensions — AirDrop,
Messages, Mail, and Notes only appear for an actual file on disk.

Switch RigShareItem / BoardShareItem to FileRepresentation: write the
encoded .shoegaze document to a unique temporary file when a destination is
picked, and hand its URL to the share sheet. Extract the shared temp-file
writer alongside shareFilenameBase.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 18:03:13 -07:00
josh 8c4b2ab1e7 Update README pedal catalog and release notes
- README: refresh the pedal catalog to all 32 pedals across the eight
  current categories (Gain / Dynamics / EQ & Filter / Modulation / Pitch /
  Delay / Reverb / Texture), bump the count, and add a Sharing feature
  bullet for the .shoegaze file type.
- RELEASES.md: add the 1.3.0 sharing entry and backfill the 1.2.0 entry
  (ten new pedals + iCloud rig library + builder UI rework).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 17:57:02 -07:00
josh 3322400b7c Merge rig-sharing-1.3: .shoegaze document type and rig/board sharing 2026-06-28 17:50:51 -07:00
josh 9e09eb284a Add .shoegaze document type and rig/board sharing
Introduce a single shareable document type for rigs and boards:

- ShoeGazeDocument: versioned JSON envelope wrapping either a RigArchive
  (one or many rigs) or a BoardVersion, with a tolerant decoder that also
  reads the legacy bare-RigArchive and bare-ShoeGazeState shapes.
- Register the .shoegaze UTType (net.realizedsound.shoegaze, conforms to
  public.json) in all four demo app Info.plists.
- Migrate library export/import onto the envelope: exportDocumentData() and
  a decoder-tolerant importArchive(); RigFileDocument and the Builder
  exporter/importer now use .shoegaze. Internal per-rig and board-version
  files stay app-private JSON.
- Add OS share-sheet entries via SwiftUI ShareLink: Share per rig in the
  library sidebar, Share per version in the board editor, backed by the
  Transferable wrappers RigShareItem / BoardShareItem.

Tests: ShoeGazeDocument round-trip and legacy decode, library .shoegaze
export/import round-trip, and a board-document-imports-no-rigs case.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 17:49:20 -07:00
josh 657ecaf4f4 updated screenshots 2026-06-28 16:51:33 -07:00
josh 957a99d802 docs: round out 1.2.0 release notes with late refinements + fixes
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 16:05:12 -07:00
josh e839447aa8 Stack the routing row under the pedal picker
Move the ROUTING cards (Stereo Split / Parallel Split / Merge to Mono) from
the right of the horizontal pedal strip to their own row beneath the pedal
cards, using the space under the picker.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 16:01:07 -07:00
josh a21121e120 Remove granulator latency: window+pan the live input (no delay buffer)
The granulators read grains from behind the write head, so each grain
replayed the last grainSize of audio — an audible delay. Rework
StereoGranulator to the straight-through approach (matching Lyrebird's
InputGrain at position 0): grains apply their Hann window and random pan to
the LIVE input sample with no look-back buffer, so there is zero added
latency. Output is normalised by overlap so density doesn't change level.
Drops the circular buffer entirely.

GranulatorPedal / AutoGranulatorPedal are unchanged (same generator API).
Generator tests (seeded determinism, zero-spread centering, full-spread
L/R separation) still hold. Suite 271.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 15:49:50 -07:00
josh bc6e6286df Surface pedal/board edit failures as a UI alert
Adding a second stereo (widener) pedal — e.g. two Granulators in a row —
threw ShoeGazeError.stereoWidthExceeded, which was only printed to the
console. Route the addPedal / routing / addBoard catch blocks to an alert
with player-facing wording (stereo-width / merge cases mapped to plain text;
others fall back to the error's LocalizedError description). Alert lives on
its own presentation anchor.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 15:30:31 -07:00
josh bc7157b7ee Reflect input-channel count in the input picker before Start
Engine config edits (In/Out/Rate) now apply to the stopped engine
immediately rather than only at Start, so the input-source picker — which
lists 0..<engine.numInputChannels — updates as soon as the In stepper
changes, letting the user choose the input before starting. No-op while
running (controls are disabled). Reuses the existing onConfigApplied
refresh path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 15:26:14 -07:00
josh 7d3bafe200 Release 1.2.0
Bump MARKETING_VERSION / CFBundleShortVersionString to 1.2.0 (both apps)
and add docs/release-notes-1.2.0.md.

Highlights: ten new pedals (Distortion, Flanger, Vibrato, Rotary,
Harmonizer, Reverse Delay, Shimmer Reverb, Bitcrusher, Granulator, Auto
Granulator), an iCloud-synced rig library, and a reworked builder layout
with a colour-coded, type-filterable pedal picker.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 15:20:11 -07:00
josh 284093c302 Granulator review fixes: use shared xorshift helper + init param docs
- Use Lyrebird's @_spi xorshift64Next(_:) instead of an inlined copy
  (@_spi(LyrebirdExtensions) import LyrebirdSynth); drop the local nextBipolar.
- Add the init-level /// - Parameters: block to StereoGranulator.

Suite 271; both apps build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 15:08:09 -07:00
josh a5f3aab237 Add Granulator and Auto Granulator pedals; color-code + filter pedal picker
- StereoGranulator generator: records mono input into a circular buffer and
  replays overlapping Hann-windowed grains, each randomly panned by `spread`
  (0 = centred, 1 = full field). Voice pool + control-rate grain size /
  overlap / spread, all pre-allocated; inlined xorshift64 for grain pans.
- GranulatorPedal (.widener): Grain / Overlap / Spread.
- AutoGranulatorPedal (.widener): grain size tracks input level via
  AmplitudeFollower → LinLin, with a Response switch (Loud→Short / Loud→Long)
  selected by a CrossFade. Min/Max Grain / Overlap / Spread.
- Pedal picker (PedalPaletteView): cards colour-coded by a new PedalCategory
  (Gain/Dynamics/EQ&Filter/Modulation/Pitch/Delay/Reverb/Texture) plus a
  "filter by type" menu defaulting to All.

Tests: generator (seeded determinism + stereo-spread L/R separation) and
both pedals (build/non-silent, param/response changes, knobs, registry,
preset round-trip). Suite 271.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 15:01:53 -07:00
josh f573d1e9a6 Fix Shimmer DC offset: DC-block the feedback path
High shimmer built a DC offset: the octave-up of DC is DC and the damping
one-pole passes DC, so the loop DC gain (~decay + shimmer) exceeds 1 above
~shimmer 0.25 at high decay and accumulates a clamped offset. Add a one-pole
DC blocker (~7 Hz, sub-bass only) on the feedback path so the loop has no DC
gain; the shimmer wash is unaffected.

Adds a regression test (zero-mean input, max shimmer/decay, small tank →
no DC offset vs the no-shimmer baseline). Suite 257.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 14:40:18 -07:00
josh 8775134d4f Harden new generators against non-finite control inputs
Sanitise control-rate reads (finite check + clamp) before they reach
seconds→frames Int conversions or feedback math, so a NaN/inf/huge size,
delay, downsample, bits, decay, shimmer, damp, or feedback can never trap
the Int() conversion nor poison a feedback loop:
- ShimmerReverb: clamp() helper; bound size to maxSizeSeconds before Int.
- ReverseDelay: finite-clamp delay (to maxDelaySeconds) and feedback.
- SampleRateDecimate: clamp downsample to [1, maximumFactor] before Int.
- BitReduce: finite-guard bits before Int(bits.rounded()).

Adds a ShimmerReverb regression test (NaN controls → finite output).
Keeps `import Foundation` in ShimmerReverb (cos for the init-time Hann
table) with a clarifying comment. Suite 256.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 11:14:42 -07:00
josh 7a39a2477e ShimmerReverb: flush denormals in tank feedback; clarify grain-read doc
Review nits: denormal-flush the recirculated tank value (not just the
damping state) so denormals can't persist in the buffer and burn RT CPU;
document that the octave-up grains read the recent wet tank content.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 09:33:24 -07:00
josh a12f58e1d1 chore: gitignore review.diff (transient review artifact)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 09:26:30 -07:00
josh 16f837ee10 Address Shimmer review: init param docs + deterministic generator test
- Add init-level /// - Parameters: block to ShimmerReverb (dual-location docs).
- Add a pinned-value generator test: with decay/shimmer/damp = 0 the tank is
  a unity-DC allpass chain, so two DC levels scale exactly linearly (ratio 2.0,
  output-gain independent).

Suite 256.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 22:07:31 -07:00
josh 0d75108fb1 docs: mark Shimmer Reverb done (regenerative) in 1.2 pedal plan
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 22:00:17 -07:00
josh 17f74a4ede Add regenerative Shimmer Reverb pedal and ShimmerReverb generator
New RT-safe ShimmerReverb generator: a damped feedback tank with a
two-grain, 50%-overlap, Hann-windowed octave-up reader INSIDE the feedback
path, so the pitched tail recirculates into an ascending wash (true
regenerative shimmer, not a one-shot parallel pitch-into-reverb). Two
series Schroeder allpasses diffuse the input; a per-sample safety clamp +
denormal flush bound the loop. Buffers pre-allocated for maxDelay + grain;
Hann table precomputed at init; size/decay/shimmer/damp read at control
rate.

ShimmerReverbPedal wraps it (Size/Decay/Shimmer/Damp), registered with
enclosure color + palette slot. Tests: generator silent-in→silent-out,
decay-changes-tail; pedal build/non-silent, shimmer-changes-output, knobs,
preset round-trip, registry. Suite 254.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 22:00:00 -07:00
josh 077a8ad9f0 Address external review: generator tests, class param docs, nits
- Add deterministic generator-level tests: BitReduceTests (level snapping +
  1-bit floor), SampleRateDecimateTests (sample-and-hold groups), and
  ReverseDelayTests (silent-then-flat-replay). Asserts are output-gain
  independent.
- Add class-level `- Parameters:` doc blocks to BitReduce, SampleRateDecimate,
  and ReverseDelay (dual-location param docs).
- BitReduce: clamp the shift amount directly and note shift-safety; clarify
  mid-tread wording.
- ReverseDelay: comment the unreachable baseAddress guard.

Suite 247.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 21:46:23 -07:00
josh 7ceb93e411 Add Bitcrusher pedal with SampleRateDecimate and BitReduce generators
Two new RT-safe generators (ShoeGaze): SampleRateDecimate (sample-and-hold
decimator, control-rate downsample factor) and BitReduce (quantise to
2^bits levels via integer shift, control-rate bit depth). BitcrusherPedal
chains decimate → bit-reduce → tone low-pass (Crush/Bits/Tone).

Registered with enclosure color + palette slot. Tests: build/non-silent,
crush-changes-output, bits-change-output, knobs, registry. Suite 242.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 21:32:03 -07:00
josh a334a76f7c Add Reverse Delay pedal and ReverseDelay generator
New RT-safe ReverseDelay generator (ShoeGaze): double-buffered segmented
recorder that plays each segment back reversed, ping-ponging record/play
buffers at each boundary with a linear edge-fade to de-click the wrap and
optional feedback for layered reverse trails. Buffers pre-allocated for
maxDelay; delay/feedback read at control rate; segment length changes only
at a boundary.

ReverseDelayPedal wraps it (Time/Feedback), registered with enclosure
color + palette slot. Tests: build/non-silent, feedback-changes-output,
knobs, preset round-trip, registry. Suite 237.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 21:28:45 -07:00
josh 5af4230038 Add Rotary (Leslie) pedal
Stereo rotary-speaker emulation: per-channel Doppler-swept delay (FM) plus
correlated amplitude throb (AM) from one rotor LFO, left/right rotors in
anti-phase for a rotating stereo image. Two-speed Chorale/Tremolo switch
with an Accel knob that ramps the rotor rate via a Lag for authentic
spin-up/spin-down. Depth scales both AM and FM. Runs as a .widener.

Registered (PedalType + registry + enclosure color + palette slot) with
build/non-silent, speed-change, control-surface, preset round-trip, and
registry tests. Suite 232.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 21:00:23 -07:00
josh 0f69c27772 Add Flanger, Vibrato, and Distortion pedals; 6th intervals on Harmonizer
- Flanger: wraps Lyrebird Flanger (Rate/Depth/Feedback), run fully wet.
- Vibrato: sine-swept delay line, fully wet pitch wobble (Rate/Depth).
- Distortion: DC-block → tanh drive → tone LPF → hard clip (Drive/Tone);
  sits between Overdrive and Fuzz.
- Harmonizer interval pickers gain minor/major sixths above and below.

Each registered (PedalType + registry + enclosure color + palette slot)
with build/non-silent + parameter-change + registry tests. Suite 227.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 20:54:35 -07:00
josh eafc68d283 Add Harmonizer pedal and a stepped selector-knob control
Harmonizer: two granular PitchShift voices at fixed musical intervals
(ratio 2^(semitones/12) via Exp), mixed under the dry signal with V1/V2/
Direct level knobs. Two interval "knob pickers" snap through octave,
fifth, fourth, and minor/major third and sixth above and below.

New reusable control:
- PedalSelectorKnob (model) + PedalSelectorKnobView (rotary knob that snaps
  to labelled stops; drag up/down to step, shows the stop caption).
- Pedal.effectSelectors hook; PedalView renders a selector row.
- PedalState.selectorValues for preset round-trip (forward-compatible).

Registered + PedalType.harmonizer + enclosure color + palette slot.
Tests: build/non-silent, interval-change-changes-output, selector preset
round-trip, registry. Full suite 213 passing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 20:50:22 -07:00
josh f0b30379c7 Force dark color scheme in the builder
On iOS in light mode, system controls (nav title, engine steppers, the
Record button) rendered black text over the builder's always-dark
background. The builder is dark-themed regardless of system appearance, so
pin its color scheme to .dark.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 20:22:30 -07:00
josh de4d650378 Merge rig-library: iCloud rig library + builder layout rework 2026-06-27 20:17:37 -07:00
josh 6e299b9d38 Rework builder layout: scope beside stacked mixer + horizontal pedal picker
Reclaim vertical space in ShoeGazeBuilderView. The top section now places
the scope + CPU meters on the left (width matched to the mixer's
Solo/Blend/All control column) and a right column that stacks the board
mixer over a horizontal pedal picker. The board canvas takes the full
width below.

- PedalPaletteView gains an `axis` parameter: `.vertical` keeps the
  full-width sidebar column; `.horizontal` lays the catalog out as a row of
  fixed-width cards for a horizontal scroller.
- Remove the old left palette sidebar and the stacked-under-palette scope.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 20:11:18 -07:00
josh 9a8e5461c0 Make rig library loads/resolve fully off-main
Move the remaining synchronous main-thread I/O off the main actor:

- RigLibraryStore now constructs instantly with a local placeholder and
  exposes an awaitable async start(): it resolves the iCloud-or-local
  location off-main (the blocking ubiquity lookup), loads entries off-main
  via the shared ioQueue (so a reload can't drop a just-saved rig), then
  sets isLoaded. reload() is async; iCloud metadata updates re-read via it.
- Seeding moves into RigLibraryBootstrap.start(_:seedFrom:), which seeds a
  "Default" rig only AFTER the (possibly iCloud) library has loaded and is
  still empty — preventing a duplicate "Default" on every synced device on
  first launch.
- Sidebar shows a Loading state until isLoaded; the builder restores the
  persisted current-rig highlight when isLoaded flips true (initialRigID
  param dropped).
- Shells construct the store synchronously and start it asynchronously
  (macOS via Task in didFinishLaunching; iOS via .task). Codec + file
  helpers are nonisolated static so background work needs no actor hop.
- Tests await store.start().

Full suite: 206 passing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 19:50:38 -07:00
josh 849240e6e2 Make rig saves non-blocking (background disk I/O)
Save/delete/eraseAll now update the in-memory entries on the main actor
immediately and run the file write/delete — including NSFileCoordinator —
on a serial background queue, removing the UI stall the synchronous
coordinated write caused (especially on the iCloud path).

- Encoding stays synchronous so encode errors still surface to the caller;
  only the disk write is deferred (logs on failure).
- File-system helpers and coordinated I/O are now nonisolated static so the
  background queue can call them without touching actor state.
- Add flushPendingWrites() to drain the queue; called by tests asserting
  on-disk state and by both app shells at termination / background.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 19:40:02 -07:00
josh e8e134499d Add macOS New/Save Rig menu items and save-on-switch prompt
- macOS File menu gains New Rig (⌘N) and Save Rig (⌘S), which forward to
  the in-window builder via shoeGazeNewRig / shoeGazeSaveRig notifications
  so the naming prompt and current-rig highlight update correctly.
- Selecting a different rig while the current one has unsaved changes now
  prompts Save / Don't Save / Cancel (both platforms). Dirtiness is
  captureState() != the loaded entry's state; a backing-less working rig
  with boards counts as dirty.
- Generalize saveCurrentRig to take a completion (used by Save & Clear and
  by save-then-switch).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 18:04:55 -07:00
josh dc42db0c59 Add iCloud-synced rig library
Replace the single hand-saved rig file with a managed library of named
rigs persisted in app storage and synced across devices and both builder
apps via a shared iCloud container (iCloud.net.realizedsound.ShoeGazeData),
falling back to local storage when iCloud is unavailable.

Core (LyrebirdShoeGaze/Presets):
- RigEntry: named, timestamped ShoeGazeState (a whole multi-board rig).
- RigArchive: portable multi-rig JSON bundle for backup/transfer; legacy
  single-rig files import as a one-rig archive.
- RigLibraryStore (@MainActor @Observable): one JSON file per rig, with
  NSFileCoordinator writes and NSMetadataQuery live remote-change watching.
- RigLibraryLocation: iCloud-or-local directory resolver (skips the slow
  ubiquity lookup when no iCloud account is signed in).
- ShoeGaze.loadRig(from: ShoeGazeState) + captureEntry; shared filename
  sanitizer factored out of BoardVersionStore.

UI (LyrebirdShoeGazeUI):
- RigLibrarySidebarView: persistent left listing with new/save/save-as/
  duplicate/rename/delete/erase-all and archive import/export.
- RigNamePrompt; RigLibraryBootstrap one-call shell setup.
- ShoeGazeBuilderView: sidebar wired in; selecting a rig replaces the
  session; File menu / sidebar do whole-library archive import/export.

Shells/entitlements: both builder targets own+start the store and carry
the iCloud Documents entitlement; NSUbiquitousContainers exposes the rigs
in the Files app. (macOS pbxproj also carries a pre-existing 1.0->1.1.1
version bump.)

Tests: RigEntry/RigArchive round-trip + RigLibraryStore CRUD/import/export
(15 new; full suite 206 passing).

Provisioning (manual, not done here): enable the iCloud container on both
App IDs and select it in Signing & Capabilities for both targets.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-27 17:56:10 -07:00
112 changed files with 10629 additions and 257 deletions
+1
View File
@@ -19,3 +19,4 @@ DerivedData/
# Note: Package.resolved is intentionally tracked to pin the Lyrebird dependency.
icon-source.png
review.diff
@@ -163,7 +163,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 3;
CURRENT_PROJECT_VERSION = 5;
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.0;
MARKETING_VERSION = 1.3.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 = 3;
CURRENT_PROJECT_VERSION = 5;
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.0;
MARKETING_VERSION = 1.3.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
+154 -33
View File
@@ -55,11 +55,21 @@ 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?
/// Default file name offered by the Save panel.
private static let defaultRigFileName: String = "ShoeGazeRig"
/// 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"
// MARK: - Init
@@ -73,24 +83,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
numAudioBuses: AppDelegate.numAudioBuses,
driver: coreDriver
)
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine)
self.coreDriver = coreDriver
self.engine = engine
self.shoeGaze = ShoeGaze(engine: engine)
self.shoeGaze = shoeGaze
self.midi = MIDIController(engine: engine, shoeGaze: shoeGaze)
self.window = LyrebirdWindow(
title: "ShoeGaze Builder — Lyrebird Pedalboard",
width: AppDelegate.windowWidth,
height: AppDelegate.windowHeight
)
super.init()
// Restore the autosaved rig if there is one; otherwise seed a default board.
// Stored `let`s must be set before `super.init()`. Restore the autosaved working rig (or
// seed a board) — operating on `shoeGaze`, not on `self` methods (unavailable pre-super).
if !RigStore.restore(into: shoeGaze) {
seedInitialBoard()
AppDelegate.seedInitialBoard(into: shoeGaze)
}
// The library constructs instantly; it resolves iCloud + loads asynchronously after launch.
self.library = RigLibraryBootstrap.makeStore()
super.init()
}
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
private func seedInitialBoard() {
private static func seedInitialBoard(into shoeGaze: ShoeGaze) {
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
@@ -106,12 +122,29 @@ 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, hardwareSampleRate: { driver.deviceSampleRate })
ShoeGazeBuilderView(
shoeGaze: session,
library: rigLibrary,
hardwareSampleRate: { driver.deviceSampleRate },
midi: midiController
)
}
anchorWindowLeft()
// Resolve iCloud + load the library off the main thread, then seed from the working rig if
// it is still empty (first run).
let rigSession: ShoeGaze = shoeGaze
Task { await RigLibraryBootstrap.start(rigLibrary, seedFrom: rigSession) }
}
/// Anchors the window `leftMargin` points from the left of the visible screen and sizes it to
@@ -136,8 +169,61 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
true
}
/// Opens `.shoegaze` files handed to the app by Finder, AirDrop, "Open With", or a double-click.
///
/// Rig documents are imported into the library (they appear in the sidebar, ready to load);
/// board documents are surfaced with a note that boards are opened from a rig's board editor.
func application(_ application: NSApplication, open urls: [URL]) {
for url: URL in urls {
openShoeGazeDocument(at: url)
}
}
/// Reads and imports a single `.shoegaze` document, reporting the outcome to the user.
private func openShoeGazeDocument(at url: URL) {
// A LaunchServices-supplied URL is security-scoped; start access to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let data: Data = try Data(contentsOf: url)
let document: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
if document.rigEntries?.isEmpty == false {
let added: Int = try library.importArchive(from: data)
presentOpenInfo(
title: added == 1 ? "Rig Imported" : "Rigs Imported",
message: added == 1
? "Added 1 rig to your library. Select it in the Rigs sidebar to load it."
: "Added \(added) rigs to your library. Select one in the Rigs sidebar to load it."
)
} else if document.boardVersion != nil {
presentOpenInfo(
title: "Board Document",
message: "This file is a single board. Open a rig, then load the board from the "
+ "board editor's Versions menu."
)
}
} catch {
presentOpenInfo(
title: "Couldn’t Open File",
message: "“\(url.lastPathComponent)” is not a readable ShoeGaze document."
)
print("[ShoeGazeBuilder] open document failed: \(error)")
}
}
/// Shows a one-button informational alert for a document-open outcome.
private func presentOpenInfo(title: String, message: String) {
let alert: NSAlert = NSAlert()
alert.messageText = title
alert.informativeText = message
alert.addButton(withTitle: "OK")
alert.runModal()
}
func applicationWillTerminate(_ notification: Notification) {
RigStore.save(shoeGaze)
// Ensure any in-flight background rig-library writes finish before exit.
library.flushPendingWrites()
engine.stop()
}
@@ -180,8 +266,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
mainMenu.addItem(fileMenuItem)
let fileMenu: NSMenu = NSMenu(title: "File")
fileMenuItem.submenu = fileMenu
addItem(to: fileMenu, title: "Save Rig…", action: #selector(saveRigAction(_:)), key: "s")
addItem(to: fileMenu, title: "Load Rig…", action: #selector(loadRigAction(_:)), key: "o")
// Per-rig commands forward to the in-window builder (which owns the current-rig state and
// the naming prompts) via notifications.
addItem(to: fileMenu, title: "New Rig", action: #selector(newRigAction(_:)), key: "n")
addItem(to: fileMenu, title: "Save Rig", action: #selector(saveRigAction(_:)), key: "s")
fileMenu.addItem(NSMenuItem.separator())
// The whole-library archive: a single file holding every rig, for backup or transfer.
addItem(to: fileMenu, title: "Export Archive…", action: #selector(exportArchiveAction(_:)), key: "e")
addItem(to: fileMenu, title: "Import Archive…", action: #selector(importArchiveAction(_:)), key: "i")
// Board menu — add board + transport.
let boardMenuItem: NSMenuItem = NSMenuItem()
@@ -211,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
}
@@ -230,34 +329,56 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Menu actions
@objc private func saveRigAction(_ sender: Any?) {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.json]
panel.nameFieldStringValue = "\(AppDelegate.defaultRigFileName).json"
panel.canCreateDirectories = true
let session: ShoeGaze = shoeGaze
panel.begin { response in
guard response == .OK, let url: URL = panel.url else { return }
do { try session.saveRig(to: url) }
catch { print("[ShoeGazeBuilder] saveRig failed: \(error)") }
/// 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 loadRigAction(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.json]
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
let session: ShoeGaze = shoeGaze
let activeEngine: SynthesisEngine = engine
@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)
}
@objc private func saveRigAction(_ sender: Any?) {
NotificationCenter.default.post(name: .shoeGazeSaveRig, object: nil)
}
@objc private func exportArchiveAction(_ sender: Any?) {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.shoeGaze]
panel.nameFieldStringValue =
"\(AppDelegate.defaultArchiveFileName).\(ShoeGazeDocument.fileExtension)"
panel.canCreateDirectories = true
let rigLibrary: RigLibraryStore = library
panel.begin { response in
guard response == .OK, let url: URL = panel.url else { return }
// loadRig rebuilds the graph; stop the engine around it and restart if it was running.
let wasRunning: Bool = activeEngine.isRunning
if wasRunning { activeEngine.stop() }
do { try session.loadRig(from: url) }
catch { print("[ShoeGazeBuilder] loadRig failed: \(error)") }
if wasRunning { try? activeEngine.start() }
do { try rigLibrary.exportDocumentData().write(to: url, options: .atomic) }
catch { print("[ShoeGazeBuilder] export library failed: \(error)") }
}
}
@objc private func importArchiveAction(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
// Accept the .shoegaze document plus legacy plain-JSON archives.
panel.allowedContentTypes = [.shoeGaze, .json]
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
let rigLibrary: RigLibraryStore = library
panel.begin { response in
guard response == .OK, let url: URL = panel.url else { return }
do {
let data: Data = try Data(contentsOf: url)
_ = try rigLibrary.importArchive(from: data)
} catch {
print("[ShoeGazeBuilder] import library failed: \(error)")
}
}
}
+52 -1
View File
@@ -13,7 +13,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<string>1.4.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSApplicationCategoryType</key>
@@ -28,5 +28,56 @@
<string>ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.net.realizedsound.ShoeGazeData</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>ShoeGaze</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>ShoeGaze Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.realizedsound.shoegaze</string>
</array>
</dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>shoegaze</string>
</array>
<key>public.mime-type</key>
<array>
<string>application/json</string>
</array>
</dict>
</dict>
</array>
</dict>
</plist>
@@ -4,5 +4,17 @@
<dict>
<key>com.apple.security.device.audio-input</key>
<true/>
<key>com.apple.developer.icloud-container-identifiers</key>
<array>
<string>iCloud.net.realizedsound.ShoeGazeData</string>
</array>
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudDocuments</string>
</array>
<key>com.apple.developer.ubiquity-container-identifiers</key>
<array>
<string>iCloud.net.realizedsound.ShoeGazeData</string>
</array>
</dict>
</plist>
@@ -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,6 +172,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.3;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -183,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;
@@ -194,6 +201,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
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"
+52 -1
View File
@@ -13,7 +13,7 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<string>1.4.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
@@ -41,5 +41,56 @@
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.net.realizedsound.ShoeGazeData</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>ShoeGaze</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>ShoeGaze Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.realizedsound.shoegaze</string>
</array>
</dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>shoegaze</string>
</array>
<key>public.mime-type</key>
<array>
<string>application/json</string>
</array>
</dict>
</dict>
</array>
</dict>
</plist>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.developer.icloud-container-identifiers</key>
<array>
<string>iCloud.net.realizedsound.ShoeGazeData</string>
</array>
<key>com.apple.developer.icloud-services</key>
<array>
<string>CloudDocuments</string>
</array>
<key>com.apple.developer.ubiquity-container-identifiers</key>
<array>
<string>iCloud.net.realizedsound.ShoeGazeData</string>
</array>
</dict>
</plist>
@@ -26,13 +26,17 @@ struct ShoeGazeBuilderiOSApp: App {
NavigationStack {
ShoeGazeBuilderView(
shoeGaze: model.shoeGaze,
library: model.library,
hardwareSampleRate: { model.hardwareSampleRate },
onEnableLiveInput: { model.enableLiveInput() }
onEnableLiveInput: { model.enableLiveInput() },
midi: model.midi
)
.navigationTitle("ShoeGaze Builder")
.navigationBarTitleDisplayMode(.inline)
.task { await model.startLibrary() }
}
.onDisappear { model.stop() }
.onOpenURL { url in model.importDocument(at: url) }
}
.onChange(of: scenePhase) { _, phase in
// Persist the rig whenever the app leaves the foreground.
@@ -8,6 +8,7 @@ import AVFoundation
import Observation
import LyrebirdSynth
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Observable model owning the `SynthesisEngine` and `ShoeGaze` session for the iOS builder.
///
@@ -48,28 +49,76 @@ 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
/// The sample rate the audio session actually committed to (for the config mismatch warning).
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
/// Resolves iCloud + loads the library off the main thread, then seeds it from the working rig
/// on first run. Call once from the app's `.task`. Safe to call again (no-op once non-empty).
func startLibrary() async {
await RigLibraryBootstrap.start(library, seedFrom: shoeGaze)
}
// MARK: - Init
init() {
ShoeGazeBuilderiOSAppModel.configureAudioSession()
let built: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: ShoeGazeBuilderiOSAppModel.inputChannels)
let shoeGaze: ShoeGaze = built.shoeGaze
self.engine = built.engine
self.iosDriver = built.driver
self.shoeGaze = built.shoeGaze
self.shoeGaze = shoeGaze
// Restore the autosaved rig if there is one; otherwise seed a default board.
// Restore the autosaved working rig if there is one; otherwise seed a default board. Operate
// on the local `shoeGaze`, not `self.shoeGaze`: self may not be touched until every stored
// property (including `library`) is initialized.
if !RigStore.restore(into: shoeGaze) {
seedFallbackBoard()
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
}
// 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.
func save() {
RigStore.save(shoeGaze)
// Flush any in-flight background rig-library writes while we still have time in the
// background.
library.flushPendingWrites()
}
// MARK: - Document open
/// Imports a `.shoegaze` file opened from Files, AirDrop, or another app into the rig library.
/// Rig documents add their rigs (they appear in the sidebar, ready to load); board documents are
/// ignored here. Returns the number of rigs added.
@discardableResult
func importDocument(at url: URL) -> Int {
// A document opened from outside the sandbox is security-scoped; start access to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let data: Data = try Data(contentsOf: url)
return try library.importArchive(from: data)
} catch {
print("[ShoeGazeBuilderiOS] open document failed: \(error)")
return 0
}
}
// MARK: - Audio session / engine construction
@@ -158,9 +207,16 @@ final class ShoeGazeBuilderiOSAppModel {
try shoeGaze.loadRig(from: snapshot)
} catch {
print("[ShoeGazeBuilderiOS] rig restore after rebuild failed: \(error)")
seedFallbackBoard()
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() }
@@ -180,7 +236,7 @@ final class ShoeGazeBuilderiOSAppModel {
}
/// Seeds a single default board so the rig is never empty after a failed restore.
private func seedFallbackBoard() {
private static func seedFallbackBoard(into shoeGaze: ShoeGaze) {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
+21 -9
View File
@@ -11,16 +11,25 @@ signal (no hardware needed) or on live guitar through an audio input.
## Features
- **22 modeled pedals** across drive, dynamics, EQ/filter, modulation, delay/reverb, and
pitch — see the catalog below.
- **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.
- **Save / load rigs** as JSON, on both platforms.
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across
your devices and both apps via iCloud.
- **Sharing** — send a rig or a saved board to anyone as a `.shoegaze` file via the system share
sheet (AirDrop, Mail, Messages, Files); export/import the whole library the same way.
- **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.
@@ -28,11 +37,14 @@ signal (no hardware needed) or on live guitar through an audio input.
| Category | Pedals |
|---|---|
| Drive & dynamics | Overdrive, Fuzz, Compressor, Sustainer, Limiter, Noise Gate |
| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Phaser |
| Modulation | Tremolo, Modulation, Chorus, Ring Modulator, Diffuser |
| Delay & reverb | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverb |
| Pitch & octave | Octave Splitter, Bass Octaver |
| Gain | Overdrive, Distortion, Fuzz |
| Dynamics | Compressor, Sustainer, Limiter, Noise Gate |
| EQ & filter | Graphic EQ, Auto-Wah, Mutant |
| 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, 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.
+85
View File
@@ -1,5 +1,90 @@
# 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
- New shareable file type **`.shoegaze`** (`net.realizedsound.shoegaze`, conforming to
`public.json`) registered by every app, so the system associates the file with ShoeGaze for
Open and Share.
- **Share a rig** from the library sidebar (per-rig) and **share a saved board** from the board
editor's Versions menu, via the OS share sheet — AirDrop, Mail, Messages, Files. Local only; no
account or backend.
- Library **export/import migrated** to `.shoegaze`. A document wraps either a whole rig (or many)
or a single board; legacy archive and single-rig JSON files still import.
- Internal per-rig and board-version files stay app-private JSON — only the share/export surface
uses `.shoegaze`.
## 1.2.0 — 2026-06-28
### New pedals (catalog now 32)
- **Distortion** — mid-gain saturation between Overdrive and Fuzz.
- **Flanger** — sweeping comb-filter jet with feedback.
- **Vibrato** — pure pitch wobble, fully wet.
- **Rotary** — Leslie rotary-speaker: Doppler wobble + volume throb, two-speed with accel ramp.
- **Harmonizer** — two pitch-shifted harmony voices at fixed musical intervals (stepped knob).
- **Reverse Delay** — backward-tape segments with feedback trails.
- **Shimmer Reverb** — regenerative reverb whose tail climbs an octave as it sustains.
- **Bitcrusher** — sample-rate decimation + bit-depth reduction + tone.
- **Granulator** — stereo grain cloud, scattered across the field by Spread.
- **Auto Granulator** — granulator whose grain size tracks your dynamics (Response switch).
### Rig library (iCloud)
- Rigs are a managed **library** in the sidebar (New, Save, Save As, Duplicate, Rename, Delete,
Erase All), each holding multiple boards.
- **iCloud sync** across devices and both apps via a shared container, with a local fallback.
- **Archive** import/export bundles the whole library as one hand-editable JSON file (replaced the
old single-rig save/load); legacy single-rig files still import.
- macOS File menu: New Rig (⌘N), Save Rig (⌘S), Export / Import Archive (⌘E / ⌘I). Saves/loads run
off the main thread.
### Builder UI
- Reworked top layout (scope + CPU beside a stacked board-mixer / pedal-picker); **colour-coded**
pedal cards with a **filter-by-type** menu; routing cards in their own row.
- Dark color scheme pinned (fixes black-on-dark system controls on iOS); input-source picker
reflects the In channel count immediately; failed edits surface as alerts.
### Fixes / under the hood
- Granulators are now latency-free; Shimmer Reverb DC-blocked. New RT-safe generators
(`ReverseDelay`, `SampleRateDecimate`, `BitReduce`, `ShimmerReverb`, `StereoGranulator`) and a
reusable `PedalSelectorKnob`. 271 tests; RT-safety reviewed.
## 1.1.1 — 2026-06-26
### Fixes
@@ -0,0 +1,33 @@
{
"originHash" : "bf2bd285202c1d5cb51cc77815e3eb9675170cb3bef2db60c355d2222c555750",
"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" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
}
},
{
"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,87 @@
// BitReduce.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
private let bitReduceZeroBlock: [Double] = makeSampleBuffer()
/// Bit-depth reducer: quantises the signal to `2^bits` amplitude levels, producing the gritty
/// quantisation noise of the "bit" half of a lo-fi / bitcrusher effect.
///
/// `bits` is read at control rate (once per block) and clamped to `[1, 16]`. Each sample is
/// rounded to the nearest of `2^bits` levels over the `[-1, 1]` range (mid-tread). Output is mono.
///
/// - Parameters:
/// - input: Audio-rate signal to quantise.
/// - bits: Bit depth — quantises to `2^bits` levels. Control rate; clamped to `[1, 16]`.
public final class BitReduce: GeneratorBase, AudioGenerator {
/// Resolved input signal.
let _input: any ValidGeneratorInput
/// `true` when `_input` resolved to a generator; classified once so the RT path runs no
/// `is`/`as?` check.
let _inputIsGenerator: Bool
/// Quantisation bit depth, read at block rate. Pass a control-rate node or scalar.
let _bits: any ValidGeneratorInput
/// Quantisation bounds.
private let minimumBits: Double = 1.0
private let maximumBits: Double = 16.0
/// Creates a bit-depth reducer.
///
/// - Parameters:
/// - input: Signal to quantise.
/// - bits: Bit depth (control rate). Clamped to `[1, 16]`.
public init(
input: any ValidGeneratorInput,
bits: any ValidGeneratorInput
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_inputIsGenerator = resolvedInput is any Generator
_bits = bits._resolvedInput()
super.init()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
// Sanitise the control read (finite + clamped) so `Int(bits.rounded())` can't trap on a
// NaN/inf input.
let rawBits: Double = _bits.floatValue(graph: graph)
let bits: Double = rawBits.isFinite ? min(max(rawBits, minimumBits), maximumBits) : minimumBits
// Number of quantisation levels = 2^bits, via an integer shift (avoids importing `pow`).
// Clamp the shift amount directly too: `1 << bitsInt` is only safe while bits ∈ [1, 16].
let bitsInt: Int = min(max(Int(bits.rounded()), 1), 16)
let levels: Double = Double(1 << bitsInt)
// Step between adjacent levels over [-1, 1], and its reciprocal for the round.
let step: Double = 2.0 / levels
let inverseStep: Double = levels / 2.0
let inputSamples: [Double] = _inputIsGenerator
? (_input.calculatedSamples(graph: graph, count: count).first ?? bitReduceZeroBlock)
: bitReduceZeroBlock
let inputCount: Int = inputSamples.count
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
for i: Int in 0..<count {
let x: Double = _inputIsGenerator
? (i < inputCount ? inputSamples[i] : 0.0)
: inputScalar
_result[0][i] = (x * inverseStep).rounded() * step
}
return _result
}
}
@@ -0,0 +1,220 @@
// ReverseDelay.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream input
/// yields no channel for a `_computeSamples` call, so the RT path never allocates.
private let reverseDelayZeroBlock: [Double] = makeSampleBuffer()
/// Segmented reverse delay: records the input in fixed-length segments and plays each segment back
/// **reversed**, so phrases come out backwards.
///
/// Two segment buffers ping-pong: one records the incoming signal while the other is read back from
/// its end to its start. At each segment boundary the buffers swap. A short raised-edge (linear)
/// fade at both ends of every reversed segment hides the wrap discontinuity, and an optional
/// feedback term recirculates the reversed output into the record buffer for layered reverse trails.
///
/// `delay` and `feedback` are read at **control rate** (once per block via `floatValue`); a changed
/// `delay` takes effect at the next segment boundary, so the segment length never changes mid-read.
/// Output is mono (channel 0 of the input is processed).
///
/// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds — the RT path never
/// allocates or resizes. Keep `delay <= maxDelay`; larger values are clamped.
///
/// - Parameters:
/// - input: Audio-rate signal to reverse.
/// - maxDelay: Maximum segment length in seconds; sizes the pre-allocated buffers.
/// - delay: Segment length in seconds. Control rate; clamped to `[1 frame, maxDelay]`; a change
/// applies at the next segment boundary.
/// - feedback: Reverse-trail feedback factor. Control rate; clamped to `[0, 0.95]`.
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
/// - fadeTime: Edge-fade length in seconds hiding the segment wrap. Defaults to `0.004`.
public final class ReverseDelay: GeneratorBase, AudioGenerator {
// MARK: - Inputs (classified once at init)
/// Resolved input signal.
let _input: any ValidGeneratorInput
/// `true` when `_input` resolved to a generator; `false` for a scalar constant. Classified once
/// so the RT path never runs an `is`/`as?` check.
let _inputIsGenerator: Bool
/// Resolved control inputs. Read at block rate via `floatValue` — pass control-rate nodes
/// (`@UIParam` projections) or scalars, not audio-rate generators.
let _delay: any ValidGeneratorInput
let _feedback: any ValidGeneratorInput
// MARK: - Buffers + state
/// The two ping-pong segment buffers, each `_maxFrames` long. One records while the other plays.
private var _bufferA: [Double]
private var _bufferB: [Double]
/// Maximum segment length in frames (`maxDelay · sampleRate`).
private let _maxFrames: Int
/// `true` when buffer A is the record buffer (B plays); toggled at each segment boundary.
var _recordIsA: Bool = true
/// Read/write position within the current segment, `0 ..< _segLen`.
var _phase: Int = 0
/// Current segment length in frames.
var _segLen: Int
/// `false` until the first render block adopts the live `delay` as the segment length (the node
/// value isn't available at `init`).
var _segLenInitialized: Bool = false
/// Edge-fade length in frames, clamped to half the segment per call.
private let _fadeFrames: Int
// MARK: - Constants
/// Largest stable feedback factor.
private let maxFeedback: Double = 0.95
// MARK: - Init
/// Creates a reverse delay.
///
/// - Parameters:
/// - input: Signal to reverse.
/// - maxDelay: Maximum segment length in seconds. Sizes the pre-allocated buffers.
/// - delay: Segment length in seconds (control rate). Clamped to `[1 frame, maxDelay]`; a
/// change applies at the next segment boundary.
/// - feedback: Reverse-trail feedback factor (control rate). Clamped to `[0, 0.95]`. Defaults
/// to `0`.
/// - sampleRate: Sample rate used to size the buffers and convert seconds → frames.
/// - fadeTime: Edge-fade length in seconds, hiding the segment wrap. Defaults to `0.004`.
public init(
input: any ValidGeneratorInput,
maxDelay: Double,
delay: any ValidGeneratorInput,
feedback: any ValidGeneratorInput = 0.0,
sampleRate: Double,
fadeTime: Double = 0.004
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_inputIsGenerator = resolvedInput is any Generator
_delay = delay._resolvedInput()
_feedback = feedback._resolvedInput()
let frames: Int = max(1, Int((maxDelay * sampleRate).rounded()))
_maxFrames = frames
_bufferA = [Double](repeating: 0.0, count: frames)
_bufferB = [Double](repeating: 0.0, count: frames)
_segLen = frames
_fadeFrames = max(0, Int((fadeTime * sampleRate).rounded()))
super.init()
}
// MARK: - Render
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let sampleRate: Double = graph.engine.sampleRate
// Sanitise control reads (finite + clamped): a NaN/inf/huge `delay` would otherwise trap the
// seconds→frames `Int` conversion, and a NaN `feedback` would poison the loop.
let maxDelaySeconds: Double = Double(_maxFrames) / sampleRate
let rawDelay: Double = _delay.floatValue(graph: graph)
let delaySeconds: Double = rawDelay.isFinite ? min(max(rawDelay, 0.0), maxDelaySeconds) : 0.0
let rawFeedback: Double = _feedback.floatValue(graph: graph)
let feedback: Double = rawFeedback.isFinite ? min(max(rawFeedback, 0.0), maxFeedback) : 0.0
// Target segment length, applied at the next boundary so a read never changes length mid-segment.
// `delaySeconds` is bounded to `maxDelaySeconds`, so the `Int` conversion cannot overflow.
let targetLen: Int = min(max(Int((delaySeconds * sampleRate).rounded()), 1), _maxFrames)
let inputSamples: [Double] = _inputIsGenerator
? (_input.calculatedSamples(graph: graph, count: count).first ?? reverseDelayZeroBlock)
: reverseDelayZeroBlock
let inputCount: Int = inputSamples.count
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
var phase: Int = _phase
var segLen: Int = _segLen
var recordIsA: Bool = _recordIsA
let fadeFrames: Int = _fadeFrames
// Adopt the live delay length on the first block — at `init` the node value isn't known, so
// the segment must not start at the full buffer length (that would delay the first reversed
// segment by `maxDelay`).
if !_segLenInitialized {
segLen = targetLen
phase = 0
_segLenInitialized = true
}
_bufferA.withUnsafeMutableBufferPointer { aBuffer in
_bufferB.withUnsafeMutableBufferPointer { bBuffer in
// `baseAddress` is non-nil for these always-non-empty buffers (sized `_maxFrames >= 1`
// at init), so this guard never fires; it satisfies the optional without an RT trap.
guard let aPointer: UnsafeMutablePointer<Double> = aBuffer.baseAddress,
let bPointer: UnsafeMutablePointer<Double> = bBuffer.baseAddress else { return }
_result[0].withUnsafeMutableBufferPointer { outBuffer in
guard let outPointer: UnsafeMutablePointer<Double> = outBuffer.baseAddress else { return }
for i: Int in 0..<count {
let x: Double = _inputIsGenerator
? (i < inputCount ? inputSamples[i] : 0.0)
: inputScalar
let recordPointer: UnsafeMutablePointer<Double> = recordIsA ? aPointer : bPointer
let playPointer: UnsafeMutablePointer<Double> = recordIsA ? bPointer : aPointer
// Reversed read: end of the play segment first.
let readIndex: Int = segLen - 1 - phase
let raw: Double = playPointer[readIndex]
let envelope: Double = ReverseDelay.edgeFade(
phase: phase, segLen: segLen, fadeFrames: fadeFrames
)
let out: Double = raw * envelope
recordPointer[phase] = x + feedback * out
outPointer[i] = out
phase += 1
if phase >= segLen {
phase = 0
recordIsA.toggle()
segLen = targetLen
}
}
}
}
}
_phase = phase
_segLen = segLen
_recordIsA = recordIsA
return _result
}
/// Linear raised-edge fade in `[0, 1]`: ramps up over the first `fadeFrames` of a segment and
/// down over the last `fadeFrames`, flat `1` in the middle. De-clicks the reverse wrap.
private static func edgeFade(
phase: Int,
segLen: Int,
fadeFrames: Int
) -> Double {
let fade: Int = min(fadeFrames, segLen / 2)
guard fade > 0 else { return 1.0 }
let fromStart: Int = phase
let fromEnd: Int = segLen - 1 - phase
let nearestEdge: Int = min(fromStart, fromEnd)
guard nearestEdge < fade else { return 1.0 }
return Double(nearestEdge) / Double(fade)
}
}
@@ -0,0 +1,103 @@
// SampleRateDecimate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
private let sampleRateDecimateZeroBlock: [Double] = makeSampleBuffer()
/// Sample-rate reducer (decimator): a sample-and-hold that latches a new input value only once
/// every `downsample` samples, holding it in between. The aliased, stair-stepped result is the
/// "crushed sample rate" half of a lo-fi / bitcrusher effect.
///
/// `downsample` is read at control rate (once per block). `1` passes the signal through; `N` holds
/// each sample for `N` output samples (effective rate `sampleRate / N`). Output is mono (channel 0).
///
/// - Parameters:
/// - input: Audio-rate signal to decimate.
/// - downsample: Hold length in samples — effective rate is `sampleRate / downsample`. Control
/// rate; clamped to `>= 1` (`1` is transparent).
public final class SampleRateDecimate: GeneratorBase, AudioGenerator {
/// Resolved input signal.
let _input: any ValidGeneratorInput
/// `true` when `_input` resolved to a generator; classified once so the RT path runs no
/// `is`/`as?` check.
let _inputIsGenerator: Bool
/// Downsample factor, read at block rate. Pass a control-rate node or scalar.
let _downsample: any ValidGeneratorInput
/// Samples remaining before the next latch. `0` latches a fresh input on the current sample.
var _countdown: Int = 0
/// Currently held output value.
var _held: Double = 0.0
/// Smallest decimation factor (pass-through).
private let minimumFactor: Int = 1
/// Largest accepted decimation factor — bounds the control read so the `Int` conversion can
/// never overflow on a NaN/inf/huge input.
private let maximumFactor: Double = 1_048_576.0
/// Creates a sample-rate decimator.
///
/// - Parameters:
/// - input: Signal to decimate.
/// - downsample: Hold length in samples (control rate). Clamped to `>= 1`; `1` is transparent.
public init(
input: any ValidGeneratorInput,
downsample: any ValidGeneratorInput
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_inputIsGenerator = resolvedInput is any Generator
_downsample = downsample._resolvedInput()
super.init()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
// Sanitise the control read (finite + clamped) so the `Int` conversion can't overflow.
let raw: Double = _downsample.floatValue(graph: graph)
let safeFactor: Double = raw.isFinite
? min(max(raw, Double(minimumFactor)), maximumFactor)
: Double(minimumFactor)
let factor: Int = Int(safeFactor.rounded())
let inputSamples: [Double] = _inputIsGenerator
? (_input.calculatedSamples(graph: graph, count: count).first ?? sampleRateDecimateZeroBlock)
: sampleRateDecimateZeroBlock
let inputCount: Int = inputSamples.count
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
var countdown: Int = _countdown
var held: Double = _held
for i: Int in 0..<count {
let x: Double = _inputIsGenerator
? (i < inputCount ? inputSamples[i] : 0.0)
: inputScalar
if countdown <= 0 {
held = x
countdown = factor
}
countdown -= 1
_result[0][i] = held
}
_countdown = countdown
_held = held
return _result
}
}
@@ -0,0 +1,297 @@
// ShimmerReverb.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation // `cos` for the init-time Hann window (not used on the RT path)
import LyrebirdSynth
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
private let shimmerReverbZeroBlock: [Double] = makeSampleBuffer()
/// Regenerative shimmer reverb: a damped feedback tank with an octave-up grain reader **inside**
/// the feedback path, so the pitched-up tail recirculates and the shimmer builds and sustains
/// (rather than the one-shot parallel pitch-into-reverb approximation).
///
/// Signal path per sample:
/// ```
/// input → 2 series Schroeder allpasses (diffusion) ─┐
/// ▼
/// tank delay (size) → damping one-pole → ┬─────────→ output (wet tail)
/// │
/// octave-up grains read from the tank ───┤ (× shimmer)
/// ▼
/// feedback = decay·damped + shimmer·pitched → written back into the tank
/// ```
///
/// The octave-up is a two-grain, 50%-overlap, Hann-windowed reader running at 2× over the most
/// recent `grain` samples of the tank (the live wet content), a tape-style pitch raise whose
/// pitched output recirculates through the feedback. A per-sample safety clamp + denormal flush
/// keep the loop bounded even at high `decay` / `shimmer`.
///
/// `size`, `decay`, `shimmer`, and `damp` are read at control rate (once per block). Output is mono.
///
/// - Important: All buffers are pre-allocated at `init` for `maxDelay` seconds plus the grain
/// length — the RT path never allocates or resizes.
///
/// - Parameters:
/// - input: Audio-rate signal to reverberate.
/// - maxDelay: Maximum tank delay in seconds; sizes the pre-allocated buffer.
/// - size: Tank delay in seconds. Control rate; clamped to `[0.005, maxDelay]`.
/// - decay: Feedback gain (tail length). Control rate; clamped to `[0, 0.92]`.
/// - shimmer: Octave-up feedback amount. Control rate; clamped to `[0, 0.85]`.
/// - damp: High-frequency damping in the feedback `[0, 1]` (0 = bright, 1 = dark). Control rate.
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
public final class ShimmerReverb: GeneratorBase, AudioGenerator {
// MARK: - Inputs
let _input: any ValidGeneratorInput
let _inputIsGenerator: Bool
let _size: any ValidGeneratorInput
let _decay: any ValidGeneratorInput
let _shimmer: any ValidGeneratorInput
let _damp: any ValidGeneratorInput
// MARK: - Buffers + state
/// Tank delay/grain buffer (circular), length `_bufLen`.
private var _tank: [Double]
/// Two Schroeder input-diffusion allpass buffers.
private var _allpassA: [Double]
private var _allpassB: [Double]
/// Precomputed Hann window over one grain, length `_grainFrames`.
private var _hann: [Double]
private let _bufLen: Int
private let _grainFrames: Int
private let _maxDelayFrames: Int
private let _allpassALen: Int
private let _allpassBLen: Int
private var _writePos: Int = 0
private var _allpassAPos: Int = 0
private var _allpassBPos: Int = 0
private var _grainCounter: Int = 0
private var _dampState: Double = 0.0
/// DC-blocker state (previous input/output) on the feedback path.
private var _dcX1: Double = 0.0
private var _dcY1: Double = 0.0
// MARK: - Constants
private let minSizeSeconds: Double = 0.005
private let maxDecay: Double = 0.92
private let maxShimmer: Double = 0.85
private let grainSeconds: Double = 0.05
/// Schroeder allpass coefficient and (prime-ish) lengths in samples for input diffusion.
private let allpassGain: Double = 0.7
private let allpassAFrames: Int = 142
private let allpassBFrames: Int = 107
/// Hard safety bound on the recirculated value — prevents runaway / NaN at extreme settings.
private let safetyClamp: Double = 8.0
/// Below this magnitude feedback state is flushed to zero (denormal guard).
private let denormalFloor: Double = 1.0e-15
/// DC-blocker pole — a one-pole high-pass on the feedback path. Without it the octave-up of DC
/// (≈ DC) plus the DC-passing damping filter gives the loop a DC gain near `decay + shimmer`,
/// which exceeds 1 at higher settings and accumulates into a DC offset. ~7 Hz cutoff @ 44.1 kHz
/// — sub-bass only, so the shimmer wash is unaffected.
private let dcBlockCoeff: Double = 0.999
// MARK: - Init
/// Creates a shimmer reverb.
///
/// - Parameters:
/// - input: Audio-rate signal to reverberate.
/// - maxDelay: Maximum tank delay in seconds; sizes the pre-allocated buffer.
/// - size: Tank delay in seconds. Control rate; clamped to `[0.005, maxDelay]`.
/// - decay: Feedback gain (tail length). Control rate; clamped to `[0, 0.92]`.
/// - shimmer: Octave-up feedback amount. Control rate; clamped to `[0, 0.85]`.
/// - damp: High-frequency damping in the feedback `[0, 1]` (0 = bright, 1 = dark). Control rate.
/// - sampleRate: Sample rate used to size buffers and convert seconds → frames; match the engine.
public init(
input: any ValidGeneratorInput,
maxDelay: Double,
size: any ValidGeneratorInput,
decay: any ValidGeneratorInput,
shimmer: any ValidGeneratorInput,
damp: any ValidGeneratorInput,
sampleRate: Double
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_inputIsGenerator = resolvedInput is any Generator
_size = size._resolvedInput()
_decay = decay._resolvedInput()
_shimmer = shimmer._resolvedInput()
_damp = damp._resolvedInput()
let maxFrames: Int = max(1, Int((maxDelay * sampleRate).rounded()))
let grain: Int = max(2, Int((grainSeconds * sampleRate).rounded()))
_maxDelayFrames = maxFrames
_grainFrames = grain
// Buffer holds the deepest tank read plus a full grain look-back, with headroom.
_bufLen = maxFrames + grain + 2
_allpassALen = allpassAFrames
_allpassBLen = allpassBFrames
_tank = [Double](repeating: 0.0, count: _bufLen)
_allpassA = [Double](repeating: 0.0, count: allpassAFrames)
_allpassB = [Double](repeating: 0.0, count: allpassBFrames)
// Precompute the Hann window for the grain (off the RT thread).
var hann: [Double] = [Double](repeating: 0.0, count: grain)
let twoPi: Double = 2.0 * Double.pi
for i: Int in 0..<grain {
hann[i] = 0.5 - 0.5 * cos(twoPi * Double(i) / Double(grain))
}
_hann = hann
super.init()
}
// MARK: - Render
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let sampleRate: Double = graph.engine.sampleRate
// Sanitise control reads (finite + clamped) so a NaN/inf/huge value can never reach the
// feedback math or trap the seconds→frames `Int` conversion.
let maxSizeSeconds: Double = Double(_maxDelayFrames) / sampleRate
let sizeSeconds: Double = ShimmerReverb.clamp(_size.floatValue(graph: graph), minSizeSeconds, maxSizeSeconds)
let decay: Double = ShimmerReverb.clamp(_decay.floatValue(graph: graph), 0.0, maxDecay)
let shimmer: Double = ShimmerReverb.clamp(_shimmer.floatValue(graph: graph), 0.0, maxShimmer)
let damp: Double = ShimmerReverb.clamp(_damp.floatValue(graph: graph), 0.0, 1.0)
let minFrames: Int = max(1, Int((minSizeSeconds * sampleRate).rounded()))
// `sizeSeconds` is bounded to `maxSizeSeconds`, so `sizeSeconds · sampleRate <= _maxDelayFrames`
// and the `Int` conversion cannot overflow.
let sizeFrames: Int = min(max(Int((sizeSeconds * sampleRate).rounded()), minFrames), _maxDelayFrames)
let halfGrain: Int = _grainFrames / 2
let inputSamples: [Double] = _inputIsGenerator
? (_input.calculatedSamples(graph: graph, count: count).first ?? shimmerReverbZeroBlock)
: shimmerReverbZeroBlock
let inputCount: Int = inputSamples.count
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
var writePos: Int = _writePos
var grainCounter: Int = _grainCounter
var dampState: Double = _dampState
var allpassAPos: Int = _allpassAPos
var allpassBPos: Int = _allpassBPos
var dcX1: Double = _dcX1
var dcY1: Double = _dcY1
_tank.withUnsafeMutableBufferPointer { tankBuffer in
_allpassA.withUnsafeMutableBufferPointer { apABuffer in
_allpassB.withUnsafeMutableBufferPointer { apBBuffer in
_hann.withUnsafeBufferPointer { hannBuffer in
_result[0].withUnsafeMutableBufferPointer { outBuffer in
guard let tank: UnsafeMutablePointer<Double> = tankBuffer.baseAddress,
let apA: UnsafeMutablePointer<Double> = apABuffer.baseAddress,
let apB: UnsafeMutablePointer<Double> = apBBuffer.baseAddress,
let hann: UnsafePointer<Double> = hannBuffer.baseAddress,
let out: UnsafeMutablePointer<Double> = outBuffer.baseAddress
else { return }
for i: Int in 0..<count {
let x: Double = _inputIsGenerator
? (i < inputCount ? inputSamples[i] : 0.0)
: inputScalar
// Input diffusion: two series Schroeder allpasses.
let diffused: Double = ShimmerReverb.allpass(
ShimmerReverb.allpass(x, apA, &allpassAPos, _allpassALen, allpassGain),
apB, &allpassBPos, _allpassBLen, allpassGain
)
// Delayed tank read → one-pole damping (HF absorption).
let readTail: Double = tank[ShimmerReverb.wrap(writePos - sizeFrames, _bufLen)]
dampState = dampState + (1.0 - damp) * (readTail - dampState)
let damped: Double = dampState
// Octave-up: two 50%-overlapped Hann grains read at 2× over the tank.
let offsetA: Int = _grainFrames - grainCounter
let phaseB: Int = (grainCounter + halfGrain) % _grainFrames
let offsetB: Int = _grainFrames - phaseB
let pitched: Double =
hann[grainCounter] * tank[ShimmerReverb.wrap(writePos - offsetA, _bufLen)]
+ hann[phaseB] * tank[ShimmerReverb.wrap(writePos - offsetB, _bufLen)]
// Feedback: decayed damped tail + pitched shimmer, DC-blocked so the
// loop has no DC gain (the octave-up of DC is DC), then add the input.
let feedbackRaw: Double = decay * damped + shimmer * pitched
let feedback: Double = feedbackRaw - dcX1 + dcBlockCoeff * dcY1
dcX1 = feedbackRaw
dcY1 = feedback
var writeVal: Double = diffused + feedback
if writeVal > safetyClamp { writeVal = safetyClamp }
else if writeVal < -safetyClamp { writeVal = -safetyClamp }
// Flush denormals so they never recirculate in the tank (RT CPU guard).
if abs(writeVal) < denormalFloor { writeVal = 0.0 }
tank[writePos] = writeVal
out[i] = damped
writePos += 1
if writePos >= _bufLen { writePos = 0 }
grainCounter += 1
if grainCounter >= _grainFrames { grainCounter = 0 }
}
if abs(dampState) < denormalFloor { dampState = 0.0 }
if abs(dcY1) < denormalFloor { dcY1 = 0.0 }
}
}
}
}
}
_writePos = writePos
_grainCounter = grainCounter
_dampState = dampState
_allpassAPos = allpassAPos
_allpassBPos = allpassBPos
_dcX1 = dcX1
_dcY1 = dcY1
return _result
}
/// One Schroeder allpass step over a circular buffer; advances `pos`. `y = -g·x + d;
/// buf = x + g·y` where `d` is the delayed sample.
private static func allpass(
_ x: Double,
_ buffer: UnsafeMutablePointer<Double>,
_ pos: inout Int,
_ length: Int,
_ gain: Double
) -> Double {
let delayed: Double = buffer[pos]
let y: Double = -gain * x + delayed
buffer[pos] = x + gain * y
pos += 1
if pos >= length { pos = 0 }
return y
}
/// Returns `v` clamped to `[lo, hi]`, or `lo` when `v` is not finite — sanitising control reads
/// before they reach the feedback math or an `Int` frame conversion.
private static func clamp(_ v: Double, _ lo: Double, _ hi: Double) -> Double {
guard v.isFinite else { return lo }
return min(max(v, lo), hi)
}
/// Wraps `index` into `[0, length)` (handles a single negative wrap, as produced by
/// `writePos - offset` with `offset <= length`).
private static func wrap(_ index: Int, _ length: Int) -> Int {
let m: Int = index % length
return m < 0 ? m + length : m
}
}
@@ -0,0 +1,224 @@
// StereoGranulator.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation // `cos`/`sin` for the init-time Hann table and per-grain pan gains
@_spi(LyrebirdExtensions) import LyrebirdSynth
/// Shared zero-fill fallback block, allocated once at module load, so the RT path never allocates.
private let stereoGranulatorZeroBlock: [Double] = makeSampleBuffer()
/// Stereo input granulator (straight-through): windows and pans the **live** input directly,
/// without a delay/look-back buffer, so there is no latency.
///
/// A pool of overlapping grain voices each apply a Hann envelope to the incoming sample and pan it
/// to a fresh random position in `[-1, 1] × spread`; the windowed, panned copies sum to the stereo
/// output. Because every active grain reads the current input sample (not buffered history), the
/// effect adds stereo width and a shimmering amplitude texture with **no time delay**. `spread = 0`
/// collapses every grain to centre (mono); `spread = 1` scatters grains across the full field.
/// Output is normalised by `overlap` so density doesn't change the level.
///
/// `grainSize`, `overlap`, and `spread` are read at control rate (once per block). Output is two
/// channels (`[0]` = left, `[1]` = right) — use the ``left`` / ``right`` accessors.
///
/// - Important: The grain voice pool is pre-allocated at `init` — the RT path never allocates.
public final class StereoGranulator: GeneratorBase, AudioGenerator {
// MARK: - Inputs
let _input: any ValidGeneratorInput
let _inputIsGenerator: Bool
let _grainSize: any ValidGeneratorInput
let _overlap: any ValidGeneratorInput
let _spread: any ValidGeneratorInput
// MARK: - State
/// Precomputed unit Hann window, indexed by `phase · hannSize / grainLen`.
private var _hann: [Double]
private let _hannSize: Int = 2048
private let _maxGrainFrames: Int
private let _minGrainFrames: Int
// Grain voice pool (fixed size; a grain that can't find a free voice is skipped).
private static let maxVoices: Int = 24
private var _vActive: [Bool]
private var _vPhase: [Int]
private var _vLen: [Int]
private var _vGainL: [Double]
private var _vGainR: [Double]
private var _spawnCountdown: Int = 0
private var _rng: UInt64
// MARK: - Constants
private let minGrainSeconds: Double = 0.003
/// Equal-power pan: `angle = (pan + 1) · π/4`, `gainL = cos`, `gainR = sin`.
private let panAngleScale: Double = Double.pi / 4.0
/// Non-zero fallback PRNG seed (golden-ratio constant).
private static let defaultSeed: UInt64 = 0x9E37_79B9_7F4A_7C15
public override var outputChannelCount: Int { 2 }
// MARK: - Init
/// Creates a stereo granulator.
///
/// - Parameters:
/// - input: Audio-rate mono signal to granulate.
/// - maxGrainSize: Largest grain length in seconds; bounds the grain-length clamp.
/// - grainSize: Grain (window) length in seconds. Control rate; clamped to `[~0.003, maxGrainSize]`.
/// - overlap: Number of overlapping grains (density); also the level normaliser. Control rate;
/// clamped to `[1, 24]`.
/// - spread: Stereo spread `[0, 1]` — scales each grain's random pan. Control rate.
/// - sampleRate: Sample rate used to convert grain seconds → frames.
/// - seed: Optional PRNG seed for deterministic grain panning (tests). Defaults to a constant.
public init(
input: any ValidGeneratorInput,
maxGrainSize: Double,
grainSize: any ValidGeneratorInput,
overlap: any ValidGeneratorInput,
spread: any ValidGeneratorInput,
sampleRate: Double,
seed: UInt64? = nil
) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
_input = resolvedInput
_inputIsGenerator = resolvedInput is any Generator
_grainSize = grainSize._resolvedInput()
_overlap = overlap._resolvedInput()
_spread = spread._resolvedInput()
_maxGrainFrames = max(1, Int((maxGrainSize * sampleRate).rounded()))
_minGrainFrames = max(1, Int((minGrainSeconds * sampleRate).rounded()))
_vActive = [Bool](repeating: false, count: StereoGranulator.maxVoices)
_vPhase = [Int](repeating: 0, count: StereoGranulator.maxVoices)
_vLen = [Int](repeating: 1, count: StereoGranulator.maxVoices)
_vGainL = [Double](repeating: 0.0, count: StereoGranulator.maxVoices)
_vGainR = [Double](repeating: 0.0, count: StereoGranulator.maxVoices)
var hann: [Double] = [Double](repeating: 0.0, count: _hannSize)
let twoPi: Double = 2.0 * Double.pi
for i: Int in 0..<_hannSize {
hann[i] = 0.5 - 0.5 * cos(twoPi * Double(i) / Double(_hannSize))
}
_hann = hann
let requestedSeed: UInt64 = seed ?? StereoGranulator.defaultSeed
_rng = requestedSeed == 0 ? StereoGranulator.defaultSeed : requestedSeed
super.init(channels: 2)
}
// MARK: - Render
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let sampleRate: Double = graph.engine.sampleRate
let rawGrain: Double = _grainSize.floatValue(graph: graph)
let grainSeconds: Double = rawGrain.isFinite
? min(max(rawGrain, minGrainSeconds), Double(_maxGrainFrames) / sampleRate)
: minGrainSeconds
let grainLen: Int = min(max(Int((grainSeconds * sampleRate).rounded()), _minGrainFrames), _maxGrainFrames)
let rawOverlap: Double = _overlap.floatValue(graph: graph)
let overlap: Int = rawOverlap.isFinite
? min(max(Int(rawOverlap.rounded()), 1), StereoGranulator.maxVoices)
: 1
let rawSpread: Double = _spread.floatValue(graph: graph)
let spread: Double = rawSpread.isFinite ? min(max(rawSpread, 0.0), 1.0) : 0.0
let spawnPeriod: Int = max(1, grainLen / overlap)
// Normalise so denser overlap doesn't raise the level (≈ sum of overlapping Hann windows).
let norm: Double = 1.0 / Double(overlap)
let inputSamples: [Double] = _inputIsGenerator
? (_input.calculatedSamples(graph: graph, count: count).first ?? stereoGranulatorZeroBlock)
: stereoGranulatorZeroBlock
let inputCount: Int = inputSamples.count
let inputScalar: Double = _inputIsGenerator ? 0.0 : _input.floatValue(graph: graph)
var spawnCountdown: Int = _spawnCountdown
var rng: UInt64 = _rng
for i: Int in 0..<count {
let x: Double = _inputIsGenerator
? (i < inputCount ? inputSamples[i] : 0.0)
: inputScalar
var left: Double = 0.0
var right: Double = 0.0
for v: Int in 0..<StereoGranulator.maxVoices where _vActive[v] {
let phase: Int = _vPhase[v]
let len: Int = _vLen[v]
let windowIndex: Int = phase * _hannSize / len
// Straight-through: window + pan the LIVE sample (no delay buffer).
let windowed: Double = x * _hann[windowIndex]
left += windowed * _vGainL[v]
right += windowed * _vGainR[v]
let nextPhase: Int = phase + 1
if nextPhase >= len {
_vActive[v] = false
} else {
_vPhase[v] = nextPhase
}
}
spawnCountdown -= 1
if spawnCountdown <= 0 {
spawnCountdown = spawnPeriod
spawnGrain(grainLen: grainLen, spread: spread, rng: &rng)
}
_result[0][i] = left * norm
_result[1][i] = right * norm
}
_spawnCountdown = spawnCountdown
_rng = rng
return _result
}
/// Activates the first free grain voice (no-op if all are busy — overlap saturates gracefully).
private func spawnGrain(
grainLen: Int,
spread: Double,
rng: inout UInt64
) {
var voice: Int = -1
for v: Int in 0..<StereoGranulator.maxVoices where !_vActive[v] {
voice = v
break
}
guard voice >= 0 else { return }
_vActive[voice] = true
_vPhase[voice] = 0
_vLen[voice] = grainLen
let pan: Double = xorshift64Next(&rng) * spread // shared RT-safe PRNG, [-1, 1) × spread
let angle: Double = (pan + 1.0) * panAngleScale
_vGainL[voice] = cos(angle)
_vGainR[voice] = sin(angle)
}
}
// MARK: - Channel accessors
public extension StereoGranulator {
/// Left output channel.
var left: ChannelSelect.Audio { self[0] }
/// Right output channel.
var right: ChannelSelect.Audio { self[1] }
}
@@ -0,0 +1,438 @@
// 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(boardIndex, pedalIndex, controlIndex, nameHint, labelHint):
guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return nil }
let controls: [PedalControl] = pedal.ccMappableControls
guard controlIndex >= 0, controlIndex < controls.count else { return nil }
let control: PedalControl = controls[controlIndex]
if let nameHint: String = nameHint, nameHint != pedal.displayName { return nil }
if let labelHint: String = labelHint, labelHint != control.label { return nil }
let hinted: MIDIMap.CCTarget = .pedalControl(
boardIndex: boardIndex,
pedalIndex: pedalIndex,
controlIndex: controlIndex,
pedalNameHint: pedal.displayName,
controlLabelHint: control.label
)
return ResolvedCC(node: control.node, range: control.range, hinted: hinted)
case let .boardLevel(boardIndex, labelHint):
guard let board: PedalBoard = board(at: boardIndex),
let node: UIParamNode = board.masterGainNode else { return nil }
if let labelHint: String = labelHint, labelHint != board.label { return nil }
let hinted: MIDIMap.CCTarget = .boardLevel(boardIndex: boardIndex, 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, hint: binding.displayNameHint)
}
}
/// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch;
/// `boardSolo` is exclusive (radio). Stale bindings (chain edited under the positional address)
/// are skipped via bounds + display-name checks.
private func perform(_ action: MIDIMap.Action, hint: String?) {
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 boardIndex):
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade)
case .boardAudible(let boardIndex):
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
shoeGaze.setBoard(board, audible: !shoeGaze.isBoardAudible(board),
crossfadeSeconds: boardActionCrossfade)
case .boardBypass(let boardIndex):
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board))
case .pedalBypass(let boardIndex, let pedalIndex):
guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return }
if let hint: String = hint, hint != pedal.displayName { return }
let engagedThreshold: Double = 0.5
let node: UIParamNode = pedal.$bypass
node.update(node.value < engagedThreshold ? 1.0 : 0.0)
}
}
/// A display-name hint for an action, captured at learn time for stale-binding detection.
private func hint(for action: MIDIMap.Action) -> String? {
switch action {
case .rigBypass, .rigMute, .allBoards:
return nil
case .boardSolo(let index), .boardAudible(let index), .boardBypass(let index):
return board(at: index)?.label
case .pedalBypass(let boardIndex, let pedalIndex):
return pedal(boardIndex: boardIndex, pedalIndex: pedalIndex)?.displayName
}
}
/// `true` when a board still matches its captured hint (or no hint was captured).
private func matchesBoard(_ board: PedalBoard, _ hint: String?) -> Bool {
guard let hint: String = hint else { return true }
return board.label == hint
}
/// Resolves a board by index, or `nil` if out of range.
private func board(at index: Int) -> PedalBoard? {
guard let shoeGaze: ShoeGaze = shoeGaze, index >= 0, index < shoeGaze.boards.count else {
return nil
}
return shoeGaze.boards[index]
}
/// Resolves a pedal by board + pedal index, or `nil` if either index is out of range.
private func pedal(boardIndex: Int, pedalIndex: Int) -> Pedal? {
guard let shoeGaze: ShoeGaze = shoeGaze,
boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return nil }
let board: PedalBoard = shoeGaze.boards[boardIndex]
guard pedalIndex >= 0, pedalIndex < board.pedals.count else { return nil }
return board.pedals[pedalIndex]
}
// 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
}
}
+167
View File
@@ -0,0 +1,167 @@
// MIDIMap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// 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. Controls are
/// addressed **positionally** (board index, pedal index, knob index) since boards and pedals have no
/// stable identity; the `*Hint` fields carry the resolved display name at learn time so a binding
/// that no longer matches (chain edited) can be detected and skipped rather than mis-fire.
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(boardIndex: Int)
case boardAudible(boardIndex: Int)
case boardBypass(boardIndex: Int)
case pedalBypass(boardIndex: Int, pedalIndex: 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(
boardIndex: Int,
pedalIndex: Int,
controlIndex: Int,
pedalNameHint: String?,
controlLabelHint: String?
)
/// A board's master output level (the board fader).
case boardLevel(boardIndex: Int, 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(b1, p1, c1, _, _), .pedalControl(b2, p2, c2, _, _)):
return b1 == b2 && 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
}
}
}
+25
View File
@@ -168,6 +168,15 @@ open class Pedal: SynthesizerBase {
[]
}
/// Effect-specific stepped "knob picker" controls for this pedal, rendered as a row of rotary
/// knobs that snap to labelled stops, beneath the knob grid.
///
/// Override in subclasses to publish each discrete `@UIParam` parameter that reads best as a
/// knob that snaps through fixed positions (e.g. a harmony interval selector). Defaults to empty.
open var effectSelectors: [PedalSelectorKnob] {
[]
}
/// 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.
@@ -178,6 +187,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.
+16
View File
@@ -105,6 +105,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?
@@ -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
}
}
@@ -0,0 +1,68 @@
// PedalSelectorKnob.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// A UI-agnostic description of a knob that snaps to a fixed set of labelled stops.
///
/// Where ``PedalKnob`` is a continuous rotary and ``PedalSwitch`` is a segmented strip, a
/// `PedalSelectorKnob` reads like a rotary knob but quantises to discrete positions — a knob picker.
/// Dragging rotates through the stops; the knob shows the current stop's caption. A `Pedal`
/// publishes an array of these via ``Pedal/effectSelectors`` so a generic pedalboard UI can render
/// a stepped knob per discrete parameter without knowing the concrete type.
///
/// Each stop pairs a short caption with the exact `Double` written to the live ``UIParamNode`` when
/// that position is selected; the lit position is the stop whose `value` is nearest the node's
/// current value.
public struct PedalSelectorKnob {
/// One labelled position of a ``PedalSelectorKnob``.
public struct Stop {
/// Short caption shown under the knob when this position is selected (e.g. "M3", "Oct").
public let title: String
/// Value written to the node when this position is selected.
public let value: Double
/// Creates a selector stop.
///
/// - Parameters:
/// - title: Short caption shown when this position is selected.
/// - value: Value written to the node when this position is selected.
public init(title: String, value: Double) {
self.title = title
self.value = value
}
}
/// Short label shown beneath the knob (e.g. "Voice 1").
public let label: String
/// The live parameter node the knob reads and writes. Pass `pedal.$paramName`.
public let node: UIParamNode
/// Ordered stops the knob snaps through, from fully counter-clockwise to fully clockwise. Must
/// contain at least two.
public let stops: [Stop]
/// Creates a selector-knob descriptor.
///
/// - Parameters:
/// - label: Short label shown beneath the knob.
/// - node: The `UIParamNode` projected value of an `@UIParam` property (`pedal.$voice1`, …).
/// - stops: Ordered stops, CCW → CW. At least two.
public init(
label: String,
node: UIParamNode,
stops: [Stop]
) {
precondition(stops.count >= 2, "PedalSelectorKnob requires at least two stops")
self.label = label
self.node = node
self.stops = stops
}
}
+17
View File
@@ -45,6 +45,7 @@ public extension PedalType {
// Drive & dynamics
static let overdrive = PedalType("Overdrive")
static let distortion = PedalType("Distortion")
static let fuzz = PedalType("Fuzz")
static let compressor = PedalType("Compressor")
static let limiter = PedalType("Limiter")
@@ -53,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")
@@ -60,20 +62,35 @@ public extension PedalType {
static let tremolo = PedalType("Tremolo")
static let modulation = PedalType("Modulation")
static let chorus = PedalType("Chorus")
static let flanger = PedalType("Flanger")
static let vibrato = PedalType("Vibrato")
static let rotary = PedalType("Rotary")
static let ringModulator = PedalType("Ring Modulator")
static let diffuser = PedalType("Diffuser")
static let bitcrusher = PedalType("Bitcrusher")
static let granulator = PedalType("Granulator")
static let autoGranulator = PedalType("Auto Granulator")
// 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")
static let multiTapDelay = PedalType("Multi-Tap Delay")
static let pingPong = PedalType("Ping-Pong")
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")
}
@@ -0,0 +1,155 @@
// AutoGranulatorPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Amplitude-tracking stereo granulator.
///
/// Like ``GranulatorPedal``, but the grain size follows the input level: by default louder playing
/// uses the **minimum** grain size and softer playing the **maximum** (so dynamics shrink and grow
/// the grains). The `Response` switch flips that relationship. Grains are randomly scattered across
/// the stereo field by `Spread`. Wraps ``StereoGranulator`` as a `.widener`.
///
/// The level → grain-size map is `AmplitudeFollower` → `LinLin`, with a `CrossFade` selecting the
/// normal vs flipped mapping from the `Response` switch.
///
/// ## Knobs
/// - `minGrain`: Minimum grain size in seconds. Range `[0.005, 0.1]`.
/// - `maxGrain`: Maximum grain size in seconds. Range `[0.05, 0.4]`.
/// - `overlap`: Overlapping grain count (density). Range `[1, 16]`.
/// - `spread`: Stereo spread `[0, 1]`.
///
/// ## Switches
/// - `response` (two-state): `0` = Loud → Short grains, `1` = Loud → Long grains.
public final class AutoGranulatorPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Granular wash whose grain size tracks your dynamics — loud shrinks grains, soft grows them."
}
// MARK: - Parameters
/// Minimum grain size in seconds. Range [0.005, 0.1].
@UIParam public var minGrain: Double = 0.02
/// Maximum grain size in seconds. Range [0.05, 0.4].
@UIParam public var maxGrain: Double = 0.25
/// Overlapping grain count (density). Range [1, 16].
@UIParam public var overlap: Double = 4.0
/// Stereo spread [0, 1].
@UIParam public var spread: Double = 0.7
/// Level → grain-size response. `0` = Loud → Short, `1` = Loud → Long. Two-state switch.
@UIParam public var response: Double = 0.0
// MARK: - Constants
private static let defaultMix: Double = 0.5
/// Largest grain the buffer is allocated for, in seconds (≥ the `maxGrain` knob maximum).
private let maxGrainSize: Double = 0.4
/// Amplitude at which the grain size reaches its loud-end value (follower output is unbounded;
/// this sets the sensitivity). Values above it are clamped by the generator's grain-size clamp.
private let ampSensitivity: Double = 0.5
private let amplitudeAttack: Double = 0.01
private let amplitudeRelease: Double = 0.2
// MARK: - Ranges
private let minGrainRange: ClosedRange<Double> = 0.005 ... 0.1
private let maxGrainRange: ClosedRange<Double> = 0.05 ... 0.4
private let overlapRange: ClosedRange<Double> = 1.0 ... 16.0
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Min Grain", node: $minGrain, range: minGrainRange),
PedalKnob(label: "Max Grain", node: $maxGrain, range: maxGrainRange),
PedalKnob(label: "Overlap", node: $overlap, range: overlapRange),
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
]
}
// MARK: - Switches
private let responseLoudShortValue: Double = 0.0
private let responseLoudLongValue: Double = 1.0
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Response",
node: $response,
options: [
PedalSwitch.Option(title: "Loud→Short", value: responseLoudShortValue),
PedalSwitch.Option(title: "Loud→Long", value: responseLoudLongValue),
]
)
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates an amplitude-tracking granulator 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: "Auto Granulator",
inputBus: inputBus,
outputBus: outputBus,
initialMix: AutoGranulatorPedal.defaultMix
)
}
// MARK: - Effect
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
let amplitude: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
in: dry,
attackTime: amplitudeAttack,
releaseTime: amplitudeRelease
)
// Loud → short: amp 0 → maxGrain, amp ampSensitivity → minGrain.
let loudShort: LinLin.Audio = LinLin.Audio(
amplitude, inLo: 0.0, inHi: ampSensitivity, outLo: $maxGrain, outHi: $minGrain
)
// Loud → long: amp 0 → minGrain, amp ampSensitivity → maxGrain.
let loudLong: LinLin.Audio = LinLin.Audio(
amplitude, inLo: 0.0, inHi: ampSensitivity, outLo: $minGrain, outHi: $maxGrain
)
// `response` 0 → pan −1 → loudShort; 1 → pan +1 → loudLong (endpoints are full A / full B).
let grainSize: CrossFade.Audio = CrossFade.Audio(
inA: loudShort, inB: loudLong, pan: $response * 2.0 - 1.0
)
let granulator: StereoGranulator = StereoGranulator(
input: dry,
maxGrainSize: maxGrainSize,
grainSize: grainSize,
overlap: $overlap,
spread: $spread,
sampleRate: sampleRate
)
return (granulator.left, granulator.right)
}
}
@@ -0,0 +1,89 @@
// BitcrusherPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Lo-fi bitcrusher: sample-rate decimation followed by bit-depth reduction.
///
/// A sample-and-hold drops the effective sample rate (aliasing, stair-stepping); a quantiser then
/// reduces the bit depth (gritty quantisation noise). A post `Tone` low-pass tames the harsh
/// aliasing for a more usable lo-fi voice. Wraps the ``SampleRateDecimate`` and ``BitReduce``
/// generators, run fully wet so the pedal's `Mix` knob sets the blend.
///
/// ## Knobs
/// - `crush`: Sample-rate decimation factor (hold length in samples). Range `[1, 50]`.
/// - `bits`: Bit depth. Range `[1, 16]`.
/// - `tone`: Post low-pass cutoff in Hz. Range `[800, 8000]`.
public final class BitcrusherPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Lo-fi crusher: drops the sample rate and bit depth for gritty digital grunge."
}
// MARK: - Parameters
/// Sample-rate decimation factor (hold length in samples). Range [1, 50].
@UIParam public var crush: Double = 8.0
/// Bit depth. Range [1, 16].
@UIParam public var bits: Double = 8.0
/// Post low-pass cutoff in Hz. Range [800, 8000].
@UIParam public var tone: Double = 4000.0
// MARK: - Constants
/// Bitcrusher is heard fully wet; the `Mix` knob can dial it back.
private static let defaultMix: Double = 1.0
/// Butterworth Q (no resonant peak) for the tone low-pass.
private let filterQ: Double = 0.707
// MARK: - Ranges
private let crushRange: ClosedRange<Double> = 1.0 ... 50.0
private let bitsRange: ClosedRange<Double> = 1.0 ... 16.0
private let toneRange: ClosedRange<Double> = 800.0 ... 8000.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Crush", node: $crush, range: crushRange),
PedalKnob(label: "Bits", node: $bits, range: bitsRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
// MARK: - Init
/// Creates a bitcrusher 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: "Bitcrusher",
inputBus: inputBus,
outputBus: outputBus,
initialMix: BitcrusherPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let decimated: SampleRateDecimate = SampleRateDecimate(input: dry, downsample: $crush)
let crushed: BitReduce = BitReduce(input: decimated, bits: $bits)
return RBJLowPass.Audio(input: crushed, freq: $tone, q: filterQ)
}
}
@@ -0,0 +1,98 @@
// DistortionPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Mid-gain distortion — more saturated than `OverdrivePedal`, more controlled than `FuzzPedal`.
///
/// A DC-blocking high-pass feeds a `tanh` soft-clipper driven hard by the `Drive` knob; a
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip guarantees the
/// output stays bounded.
///
/// ## Knobs
/// - `drive`: Pre-clip gain into the `tanh` stage. Range `[1, 50]`.
/// - `tone`: Post-clip low-pass cutoff in Hz. Range `[500, 6000]`.
public final class DistortionPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Mid-gain saturated distortion sitting between overdrive and fuzz."
}
// MARK: - Parameters
/// Pre-clip gain into the `tanh` stage. Range [1, 50].
@UIParam public var drive: Double = 12.0
/// Post-clip low-pass cutoff in Hz. Range [500, 6000].
@UIParam public var tone: Double = 3000.0
// MARK: - Constants
/// Distortion is heard fully wet; the `Level` knob sets output gain.
private static let defaultMix: Double = 1.0
/// DC-blocking high-pass cutoff in Hz, applied before the clipper.
private let dcBlockFreq: Double = 80.0
/// Butterworth Q (no resonant peak) for the conditioning filters.
private let filterQ: Double = 0.707
/// Output hard-clip bounds — guarantees a bounded signal after tone shaping.
private let clipLow: Double = -1.0
private let clipHigh: Double = 1.0
// MARK: - Ranges
private let driveRange: ClosedRange<Double> = 1.0 ... 50.0
private let toneRange: ClosedRange<Double> = 500.0 ... 6000.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Drive", node: $drive, range: driveRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
// MARK: - Init
/// Creates a distortion 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: "Distortion",
inputBus: inputBus,
outputBus: outputBus,
initialMix: DistortionPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let dcBlocked: RBJHighPass.Audio = RBJHighPass.Audio(
input: dry,
freq: dcBlockFreq,
q: filterQ
)
let driven: Tanh.Audio = Tanh.Audio(dcBlocked, mul: $drive)
let toned: RBJLowPass.Audio = RBJLowPass.Audio(
input: driven,
freq: $tone,
q: filterQ
)
return Clip.Audio(toned, lo: clipLow, hi: clipHigh)
}
}
@@ -0,0 +1,101 @@
// FlangerPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Classic jet-flanger.
///
/// A short LFO-swept delay summed with the dry signal produces the sweeping comb-filter notches;
/// feedback sharpens them into the metallic "jet" whoosh. Wraps Lyrebird's `Flanger` generator,
/// run fully wet so the pedal's own `Mix` knob sets the wet/dry blend.
///
/// ## Knobs
/// - `rate`: LFO sweep rate in Hz. Range `[0.05, 8]`.
/// - `depth`: Sweep depth as a fraction of the center delay. Range `[0, 1]`.
/// - `feedback`: Comb feedback (resonance). Range `[0, 0.95]`.
public final class FlangerPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Sweeping comb-filter jet flanger, with feedback for that metallic whoosh."
}
// MARK: - Parameters
/// LFO sweep rate in Hz. Range [0.05, 8].
@UIParam public var rate: Double = 0.4
/// Sweep depth as a fraction of the center delay. Range [0, 1].
@UIParam public var depth: Double = 0.6
/// Comb feedback (resonance). Range [0, 0.95].
@UIParam public var feedback: Double = 0.3
// MARK: - Constants
/// Default wet/dry blend — flanger sits under the dry signal.
private static let defaultMix: Double = 0.5
/// Center delay the LFO sweeps around, in seconds.
private let centerDelayTime: Double = 0.005
/// Maximum delay the line is allocated for, in seconds. Covers `centerDelayTime · (1 + maxDepth)`.
private let maxDelayTime: Double = 0.05
/// The wrapped generator runs fully wet; the `Pedal` base `Mix` knob does the blend.
private let fullyWetMix: Double = 1.0
// MARK: - Ranges
private let rateRange: ClosedRange<Double> = 0.05 ... 8.0
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
PedalKnob(label: "Depth", node: $depth, range: depthRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
]
}
// MARK: - Init
/// Creates a flanger 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: "Flanger",
inputBus: inputBus,
outputBus: outputBus,
initialMix: FlangerPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
Flanger.Audio(
input: dry,
delayTime: centerDelayTime,
depth: $depth,
rate: $rate,
feedback: $feedback,
mix: fullyWetMix,
sampleRate: sampleRate,
maxDelayTime: maxDelayTime
)
}
}
@@ -0,0 +1,98 @@
// GranulatorPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Stereo input granulator.
///
/// Chops the input into a cloud of overlapping windowed grains, each randomly scattered across the
/// stereo field by `Spread`, for a lush, smeared, widened texture. Wraps the ``StereoGranulator``
/// generator (mono in → stereo out) as a `.widener`.
///
/// ## Knobs
/// - `grain`: Grain size in seconds. Range `[0.01, 0.5]`.
/// - `overlap`: Overlapping grain count (density). Range `[1, 16]`.
/// - `spread`: Stereo spread `[0, 1]` — 0 = centred (mono), 1 = full field.
public final class GranulatorPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Scatters overlapping grains of your sound across the stereo field — a lush, smeared wash."
}
// MARK: - Parameters
/// Grain size in seconds. Range [0.01, 0.5].
@UIParam public var grain: Double = 0.08
/// Overlapping grain count (density). Range [1, 16].
@UIParam public var overlap: Double = 4.0
/// Stereo spread [0, 1].
@UIParam public var spread: Double = 0.7
// MARK: - Constants
private static let defaultMix: Double = 0.5
/// Largest grain the buffer is allocated for, in seconds (≥ the `grain` knob maximum).
private let maxGrainSize: Double = 0.5
// MARK: - Ranges
private let grainRange: ClosedRange<Double> = 0.01 ... 0.5
private let overlapRange: ClosedRange<Double> = 1.0 ... 16.0
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Grain", node: $grain, range: grainRange),
PedalKnob(label: "Overlap", node: $overlap, range: overlapRange),
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates a granulator 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: "Granulator",
inputBus: inputBus,
outputBus: outputBus,
initialMix: GranulatorPedal.defaultMix
)
}
// MARK: - Effect
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
let granulator: StereoGranulator = StereoGranulator(
input: dry,
maxGrainSize: maxGrainSize,
grainSize: $grain,
overlap: $overlap,
spread: $spread,
sampleRate: sampleRate
)
return (granulator.left, granulator.right)
}
}
@@ -0,0 +1,146 @@
// HarmonizerPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Two-voice diatonic-interval harmonizer.
///
/// Adds two pitch-shifted harmony voices at fixed musical intervals above or below the input,
/// mixed against the dry signal — an OC-2-style level layout (Voice 1 / Voice 2 / Direct) with a
/// knob picker selecting each voice's interval.
///
/// Each voice is a granular `PitchShift` whose ratio is `2^(semitones/12)`, driven live from the
/// voice's interval selector. Intervals include minor and major thirds above and below, plus
/// fourths, fifths, and octaves.
///
/// ## Knobs
/// - `voice1Level`: Voice 1 level in `[0, 1]`.
/// - `voice2Level`: Voice 2 level in `[0, 1]`.
/// - `direct`: Dry signal level in `[0, 1]`.
///
/// ## Selectors (knob pickers)
/// - `voice1`: Voice 1 interval in semitones (snaps to musical intervals).
/// - `voice2`: Voice 2 interval in semitones.
public final class HarmonizerPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Two pitch-shifted harmony voices at intervals you pick, stacked under your note."
}
// MARK: - Parameters
/// Voice 1 interval in semitones. Snaps to musical-interval stops.
@UIParam public var voice1: Double = 4.0
/// Voice 2 interval in semitones. Snaps to musical-interval stops.
@UIParam public var voice2: Double = 7.0
/// Voice 1 level in `[0, 1]`.
@UIParam public var voice1Level: Double = 0.6
/// Voice 2 level in `[0, 1]`.
@UIParam public var voice2Level: Double = 0.45
/// Dry (direct) signal level in `[0, 1]`.
@UIParam public var direct: Double = 1.0
// MARK: - Constants
/// Pedal blends internally via the level knobs, so the base wet/dry stays fully wet.
private static let defaultMix: Double = 1.0
/// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio`.
private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12
/// Granular pitch-shift window in seconds. Larger = smoother but more latency.
private let windowSize: Double = 0.1
// MARK: - Ranges
private let levelRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "V1 Level", node: $voice1Level, range: levelRange),
PedalKnob(label: "V2 Level", node: $voice2Level, range: levelRange),
PedalKnob(label: "Direct", node: $direct, range: levelRange),
]
}
// MARK: - Selectors
/// Musical-interval stops for the voice pickers, low to high. Values are semitones; captions are
/// short interval names (`m3`/`M3` = minor/major third, `4`/`5` = perfect fourth/fifth,
/// `8ve` = octave, `Uni` = unison). Minus = below the input.
private static let intervalStops: [PedalSelectorKnob.Stop] = [
PedalSelectorKnob.Stop(title: "-8ve", value: -12.0),
PedalSelectorKnob.Stop(title: "-M6", value: -9.0),
PedalSelectorKnob.Stop(title: "-m6", value: -8.0),
PedalSelectorKnob.Stop(title: "-5", value: -7.0),
PedalSelectorKnob.Stop(title: "-4", value: -5.0),
PedalSelectorKnob.Stop(title: "-M3", value: -4.0),
PedalSelectorKnob.Stop(title: "-m3", value: -3.0),
PedalSelectorKnob.Stop(title: "Uni", value: 0.0),
PedalSelectorKnob.Stop(title: "m3", value: 3.0),
PedalSelectorKnob.Stop(title: "M3", value: 4.0),
PedalSelectorKnob.Stop(title: "4", value: 5.0),
PedalSelectorKnob.Stop(title: "5", value: 7.0),
PedalSelectorKnob.Stop(title: "m6", value: 8.0),
PedalSelectorKnob.Stop(title: "M6", value: 9.0),
PedalSelectorKnob.Stop(title: "8ve", value: 12.0),
]
public override var effectSelectors: [PedalSelectorKnob] {
[
PedalSelectorKnob(label: "Voice 1", node: $voice1, stops: HarmonizerPedal.intervalStops),
PedalSelectorKnob(label: "Voice 2", node: $voice2, stops: HarmonizerPedal.intervalStops),
]
}
// MARK: - Init
/// Creates a harmonizer pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Harmonizer",
inputBus: inputBus,
outputBus: outputBus,
initialMix: HarmonizerPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let voice1Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice1)
let voice2Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice2)
let directVoice: any ValidGeneratorInput = dry * $direct
let harmony1: any ValidGeneratorInput = voice1Signal * $voice1Level
let harmony2: any ValidGeneratorInput = voice2Signal * $voice2Level
return directVoice + harmony1 + harmony2
}
/// One pitch-shifted voice: ratio `2^(semitones/12)` via `Exp`, fed to a granular `PitchShift`.
private func harmonyVoice(
_ dry: any ValidGeneratorInput,
semitones: any ValidGeneratorInput
) -> any ValidGeneratorInput {
let ratio: Exp.Audio = Exp.Audio(semitones * semitoneToRatioScale)
return PitchShift.Audio(input: dry, pitchRatio: ratio, windowSize: windowSize)
}
}
@@ -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,87 @@
// ReverseDelayPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Reverse delay.
///
/// Records the input in fixed-length segments and plays each one back reversed, so notes and
/// phrases swell in backwards — the classic backwards-tape effect. `Feedback` recirculates the
/// reversed output for layered backward trails. Wraps the ``ReverseDelay`` generator, run fully wet
/// so the pedal's `Mix` knob sets the wet/dry blend.
///
/// ## Knobs
/// - `time`: Reverse segment length in seconds. Range `[0.05, 2.0]`.
/// - `feedback`: Reverse-trail feedback. Range `[0, 0.95]`.
public final class ReverseDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Plays your phrases back in reverse — the backwards-tape swell, with feedback trails."
}
// MARK: - Parameters
/// Reverse segment length in seconds. Range [0.05, 2.0].
@UIParam public var time: Double = 0.5
/// Reverse-trail feedback. Range [0, 0.95].
@UIParam public var feedback: Double = 0.3
// MARK: - Constants
/// Default wet/dry blend — reverse delay sits under the dry signal.
private static let defaultMix: Double = 0.5
/// Maximum segment length the buffers are allocated for, in seconds.
private let maxDelayTime: Double = 2.0
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.05 ... 2.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
]
}
// MARK: - Init
/// Creates a reverse-delay 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: "Reverse Delay",
inputBus: inputBus,
outputBus: outputBus,
initialMix: ReverseDelayPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
ReverseDelay(
input: dry,
maxDelay: maxDelayTime,
delay: $time,
feedback: $feedback,
sampleRate: sampleRate
)
}
}
@@ -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,173 @@
// RotaryPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Rotary-speaker (Leslie) emulation.
///
/// A spinning speaker produces correlated amplitude modulation (volume throb) and frequency
/// modulation (Doppler pitch wobble). This pedal builds both from one rotor LFO per channel, with
/// the left and right rotors in anti-phase so the image rotates across the stereo field. A two-speed
/// switch (Chorale / Tremolo) selects the rotor speed, and the **Accel** knob sets how quickly the
/// rotor ramps between speeds — the authentic spin-up / spin-down glide — via a `Lag` on the rate.
///
/// Signal path (per channel, inside `wideEffect(_:)`):
/// ```
/// dry → DelayLine(delay: base ± fm·sin(rate)) → × (1 ± am·sin(rate)) → wet
/// ```
///
/// ## Knobs
/// - `depth`: Rotor intensity — scales both the AM throb and the FM Doppler. Range `[0, 1]`.
/// - `accel`: Spin-up / spin-down ramp time in seconds. Range `[0.05, 3]`.
///
/// ## Switches
/// - `speed` (two-state): `0` = Chorale (slow), `1` = Tremolo (fast).
public final class RotaryPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Spinning Leslie rotor: Doppler pitch wobble plus volume throb, two-speed with ramp."
}
// MARK: - Parameters
/// Rotor intensity — scales both AM and FM. Range [0, 1].
@UIParam public var depth: Double = 0.7
/// Spin-up / spin-down ramp time in seconds. Range [0.05, 3].
@UIParam public var accel: Double = 0.5
/// Rotor speed selector. `0` = Chorale (slow), `1` = Tremolo (fast). Driven by a two-state switch.
@UIParam public var speed: Double = 0.0
// MARK: - Constants
/// Rotary is heard fully wet; the `Mix` knob can dial it back if desired.
private static let defaultMix: Double = 1.0
/// Chorale (slow) rotor rate in Hz.
private let slowRateHz: Double = 0.8
/// Tremolo (fast) rotor rate in Hz.
private let fastRateHz: Double = 6.5
/// Maximum FM (Doppler) sweep half-swing in seconds, at full depth.
private let fmDepthScale: Double = 0.0008
/// Maximum AM (throb) depth, at full depth.
private let amDepthScale: Double = 0.4
/// Center delay the FM sweeps around, in seconds.
private let baseDelayTime: Double = 0.004
/// Maximum delay the lines are allocated for, in seconds.
private let maxDelayTime: Double = 0.02
/// LFO phase (cycles) for the left rotor.
private let leftPhase: Double = 0.0
/// LFO phase (cycles) for the right rotor — a half cycle opposite the left.
private let rightPhase: Double = 0.5
// MARK: - Ranges
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
private let accelRange: ClosedRange<Double> = 0.05 ... 3.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Depth", node: $depth, range: depthRange),
PedalKnob(label: "Accel", node: $accel, range: accelRange),
]
}
// MARK: - Switches
private let speedChoraleValue: Double = 0.0
private let speedTremoloValue: Double = 1.0
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Speed",
node: $speed,
options: [
PedalSwitch.Option(title: "Chorale", value: speedChoraleValue),
PedalSwitch.Option(title: "Tremolo", value: speedTremoloValue),
]
)
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates a rotary-speaker 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: "Rotary",
inputBus: inputBus,
outputBus: outputBus,
initialMix: RotaryPedal.defaultMix
)
}
// MARK: - Effect
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
// Rotor rate glides between the two speeds — the spin-up / spin-down ramp. Shared by both
// rotors (fan-out is cached per block).
let rateTarget: any ValidGeneratorInput = $speed * (fastRateHz - slowRateHz) + slowRateHz
let rate: Lag.Audio = Lag.Audio(input: rateTarget, time: $accel)
return (voice(dry, rate: rate, phase: leftPhase),
voice(dry, rate: rate, phase: rightPhase))
}
/// One rotor voice: a Doppler-swept delay line whose output is amplitude-modulated by the same
/// rotor LFO, both at `rate` and the given `phase`.
private func voice(
_ dry: any ValidGeneratorInput,
rate: any ValidGeneratorInput,
phase: Double
) -> any ValidGeneratorInput {
let fmSweep: OscSin.Audio = OscSin.Audio(
freq: rate,
phase: phase,
mul: $depth * fmDepthScale,
add: baseDelayTime
)
let delayed: DelayLine = DelayLine(
input: dry,
maxDelay: maxDelayTime,
delay: fmSweep,
sampleRate: sampleRate,
interpolation: .linear
)
// Throb gain in [1 - 2·depth·amScale, 1].
let amGain: OscSin.Audio = OscSin.Audio(
freq: rate,
phase: phase,
mul: $depth * amDepthScale,
add: 1.0 - $depth * amDepthScale
)
return delayed * amGain
}
}
@@ -0,0 +1,100 @@
// ShimmerReverbPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Shimmer reverb — an ambient reverb whose tail rises an octave as it sustains.
///
/// Wraps the ``ShimmerReverb`` generator: a damped feedback tank with an octave-up grain reader
/// inside the feedback path, so the pitched tail regenerates into a glassy, ever-ascending wash.
/// Run fully wet internally; the pedal's `Mix` knob sets the wet/dry blend.
///
/// ## Knobs
/// - `size`: Tank size (delay) in seconds. Range `[0.01, 0.12]`.
/// - `decay`: Tail length (feedback). Range `[0, 0.92]`.
/// - `shimmer`: Octave-up regeneration amount. Range `[0, 0.85]`.
/// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark).
public final class ShimmerReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Ambient reverb whose tail climbs an octave as it sustains — glassy, ascending wash."
}
// MARK: - Parameters
/// Tank size (delay) in seconds. Range [0.01, 0.12].
@UIParam public var size: Double = 0.06
/// Tail length (feedback). Range [0, 0.92].
@UIParam public var decay: Double = 0.8
/// Octave-up regeneration amount. Range [0, 0.85].
@UIParam public var shimmer: Double = 0.5
/// High-frequency damping. Range [0, 1].
@UIParam public var damp: Double = 0.4
// MARK: - Constants
/// Default wet/dry blend — reverb sits under the dry signal.
private static let defaultMix: Double = 0.35
/// Maximum tank delay the buffers are allocated for, in seconds.
private let maxDelayTime: Double = 0.12
// MARK: - Ranges
private let sizeRange: ClosedRange<Double> = 0.01 ... 0.12
private let decayRange: ClosedRange<Double> = 0.0 ... 0.92
private let shimmerRange: ClosedRange<Double> = 0.0 ... 0.85
private let dampRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Size", node: $size, range: sizeRange),
PedalKnob(label: "Decay", node: $decay, range: decayRange),
PedalKnob(label: "Shimmer", node: $shimmer, range: shimmerRange),
PedalKnob(label: "Damp", node: $damp, range: dampRange),
]
}
// MARK: - Init
/// Creates a shimmer-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: "Shimmer Reverb",
inputBus: inputBus,
outputBus: outputBus,
initialMix: ShimmerReverbPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
ShimmerReverb(
input: dry,
maxDelay: maxDelayTime,
size: $size,
decay: $decay,
shimmer: $shimmer,
damp: $damp,
sampleRate: sampleRate
)
}
}
@@ -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,96 @@
// VibratoPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Pitch vibrato.
///
/// A single delay line whose time is swept by a sine LFO produces a periodic pitch wobble. Unlike
/// `TremoloPedal` (which modulates *volume*), vibrato modulates *pitch*, and unlike `ChorusPedal`
/// it is heard fully wet — there is no dry voice underneath, so the result is pure pitch movement.
///
/// ## Knobs
/// - `rate`: LFO rate in Hz. Range `[0.1, 8]`.
/// - `depth`: Delay-sweep depth in seconds (half-swing around the base delay). Range
/// `[0.0005, 0.006]`.
public final class VibratoPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Periodic pitch wobble — a sine-swept delay heard fully wet."
}
// MARK: - Parameters
/// LFO rate in Hz. Range [0.1, 8].
@UIParam public var rate: Double = 5.0
/// Delay-sweep depth in seconds. Range [0.0005, 0.006].
@UIParam public var depth: Double = 0.002
// MARK: - Constants
/// Vibrato is pure pitch movement — fully wet, no dry voice underneath.
private static let defaultMix: Double = 1.0
/// Base delay around which the LFO sweeps, in seconds.
private let baseDelayTime: Double = 0.006
/// Maximum delay the line is allocated for, in seconds. Covers `baseDelayTime + max depth`.
private let maxDelayTime: Double = 0.02
// MARK: - Ranges
private let rateRange: ClosedRange<Double> = 0.1 ... 8.0
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.006
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
PedalKnob(label: "Depth", node: $depth, range: depthRange),
]
}
// MARK: - Init
/// Creates a vibrato 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: "Vibrato",
inputBus: inputBus,
outputBus: outputBus,
initialMix: VibratoPedal.defaultMix
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let sweep: OscSin.Audio = OscSin.Audio(
freq: $rate,
phase: 0.0,
mul: $depth,
add: baseDelayTime
)
return DelayLine(
input: dry,
maxDelay: maxDelayTime,
delay: sweep,
sampleRate: sampleRate,
interpolation: .linear
)
}
}
@@ -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
}
}
@@ -98,7 +98,7 @@ public final class BoardVersionStore {
_ version: BoardVersion,
in directory: URL
) throws {
let sanitized: String = sanitizeFilename(version.name)
let sanitized: String = sanitizePresetFilename(version.name, maxLength: maxNameLength)
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
let fileURL: URL = directory.appendingPathComponent(filename)
do {
@@ -134,7 +134,7 @@ public final class BoardVersionStore {
attributes: nil
)
let sanitized: String = sanitizeFilename(version.name)
let sanitized: String = sanitizePresetFilename(version.name, maxLength: maxNameLength)
let filename: String = "\(sanitized)-\(version.id.uuidString).json"
let fileURL: URL = directory.appendingPathComponent(filename)
@@ -236,53 +236,4 @@ public final class BoardVersionStore {
/// Maximum UTF-8 byte length for the sanitised name prefix before the `-<uuid>.json`
/// suffix is appended, so the full filename stays well under the 255-byte component limit.
private let maxNameLength: Int = 200
/// Sanitises a string so it is safe as a file-system component on HFS+ and APFS.
///
/// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace characters with underscores.
/// - Replaces a leading `.` (which would produce hidden-file or `.`/`..` names) with an
/// underscore.
/// - Trims leading and trailing underscores that resulted from whitespace or separator
/// substitution (cosmetic only — the result is always safe even before trimming).
/// - Caps the UTF-8 byte length of the result at `maxNameLength` so the full filename
/// (`<name>-<uuid>.json`, 54 extra bytes) cannot exceed the 255-byte component limit.
/// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely
/// to separator characters after substitution.
private func sanitizeFilename(_ name: String) -> String {
let replacementCharacter: Character = "_"
let forbiddenCharacters: Set<Character> = ["/", "\\", ":", "\0"]
var sanitized: String = name.map { character -> Character in
if character.isWhitespace || forbiddenCharacters.contains(character) {
return replacementCharacter
}
return character
}.reduce(into: "") { $0.append($1) }
// Replace a leading dot so the filename is never `.`, `..`, or a hidden file.
if sanitized.first == "." {
sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_")
}
// Trim whitespace-replacement underscores at both ends (cosmetic).
sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
// Treat all-empty or all-separator results as unnamed.
guard !sanitized.isEmpty else { return "unnamed" }
// Cap to maxNameLength UTF-8 bytes so the full filename stays within 255 bytes.
if sanitized.utf8.count > maxNameLength {
var truncated: String = ""
var byteCount: Int = 0
for scalar: Unicode.Scalar in sanitized.unicodeScalars {
let encodedLength: Int = UTF8.width(scalar)
guard byteCount + encodedLength <= maxNameLength else { break }
truncated.unicodeScalars.append(scalar)
byteCount += encodedLength
}
sanitized = truncated
}
return sanitized.isEmpty ? "unnamed" : sanitized
}
}
@@ -19,11 +19,13 @@ extension Pedal {
let values: [Double] = knobs.map { $0.node.value }
let switchValues: [Double] = effectSwitches.map { $0.node.value }
let sliderValues: [Double] = effectSliders.map { $0.node.value }
let selectorValues: [Double] = effectSelectors.map { $0.node.value }
return PedalState(
type: displayName,
knobValues: values,
switchValues: switchValues,
sliderValues: sliderValues,
selectorValues: selectorValues,
bypass: bypass
)
}
@@ -51,6 +53,9 @@ extension Pedal {
for (slider, value) in zip(effectSliders, state.sliderValues) {
slider.node.update(value)
}
for (selector, value) in zip(effectSelectors, state.selectorValues) {
selector.node.update(value)
}
bypass = state.bypass
}
}
@@ -32,6 +32,7 @@ public enum PedalRegistry {
/// to a board via `board.add(_:)`.
public static let builtIn: [String: @MainActor () -> Pedal] = [
"Overdrive": { OverdrivePedal() },
"Distortion": { DistortionPedal() },
"Delay": { DelayPedal() },
"Reverb": { ReverbPedal() },
"Modulation": { ModulationPedal() },
@@ -41,18 +42,32 @@ public enum PedalRegistry {
"Compressor": { CompressorPedal() },
"Mutant": { MutantPedal() },
"Auto-Wah": { AutoWahPedal() },
"Wah": { WahPedal() },
"Volume": { VolumePedal() },
"Feedback Delay": { FeedbackDelayPedal() },
"Multi-Tap Delay": { MultiTapDelayPedal() },
"Octave Splitter": { OctaveUpSplitterPedal() },
"Bass Octaver": { BassOctaverPedal() },
"Harmonizer": { HarmonizerPedal() },
"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() },
"Chorus": { ChorusPedal() },
"Flanger": { FlangerPedal() },
"Vibrato": { VibratoPedal() },
"Rotary": { RotaryPedal() },
"Sustainer": { SustainerPedal() },
"Ring Modulator": { RingModulatorPedal() },
"Diffuser": { DiffuserPedal() },
"Bitcrusher": { BitcrusherPedal() },
"Granulator": { GranulatorPedal() },
"Auto Granulator": { AutoGranulatorPedal() },
]
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
@@ -30,6 +30,10 @@ public struct PedalState: Codable, Equatable {
/// no sliders. Absent in presets saved before sliders existed — decodes to `[]`.
public let sliderValues: [Double]
/// Selector-knob values in the same order as `Pedal.effectSelectors`. Empty for pedals with
/// no selectors. Absent in presets saved before selectors existed — decodes to `[]`.
public let selectorValues: [Double]
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
public let bypass: Double
@@ -40,18 +44,21 @@ public struct PedalState: Codable, Equatable {
/// - knobValues: Current knob values in `Pedal.knobs` order.
/// - switchValues: Current switch values in `Pedal.effectSwitches` order. Defaults to empty.
/// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty.
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
public init(
type: String,
knobValues: [Double],
switchValues: [Double] = [],
sliderValues: [Double] = [],
selectorValues: [Double] = [],
bypass: Double
) {
self.type = type
self.knobValues = knobValues
self.switchValues = switchValues
self.sliderValues = sliderValues
self.selectorValues = selectorValues
self.bypass = bypass
}
@@ -60,17 +67,19 @@ public struct PedalState: Codable, Equatable {
case knobValues
case switchValues
case sliderValues
case selectorValues
case bypass
}
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues`
/// existed by defaulting the missing keys to an empty array.
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` /
/// `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.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) ?? []
self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? []
self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? []
self.bypass = try container.decode(Double.self, forKey: .bypass)
}
}
@@ -0,0 +1,65 @@
// PresetFilename.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Sanitises a user-supplied name so it is safe as a file-system component on HFS+ and APFS.
///
/// Shared by the preset stores (`BoardVersionStore`, `RigLibraryStore`) so every on-disk preset
/// filename follows one scheme: `<sanitized-name>-<uuid>.json`.
///
/// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace with underscores.
/// - Replaces a leading `.` (which would produce a hidden file or `.`/`..`) with an underscore.
/// - Trims leading and trailing underscores that resulted from the substitutions (cosmetic).
/// - Caps the UTF-8 byte length of the result at `maxLength` so the full filename
/// (`<name>-<uuid>.json`, 54 extra bytes) stays within the 255-byte component limit.
/// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely to
/// separator characters after substitution.
///
/// - Parameters:
/// - name: The raw, user-supplied name.
/// - maxLength: Maximum UTF-8 byte length of the sanitised prefix. Defaults to `200`.
/// - Returns: A file-system-safe name, never empty.
func sanitizePresetFilename(
_ name: String,
maxLength: Int = 200
) -> String {
let replacementCharacter: Character = "_"
let forbiddenCharacters: Set<Character> = ["/", "\\", ":", "\0"]
var sanitized: String = name.map { character -> Character in
if character.isWhitespace || forbiddenCharacters.contains(character) {
return replacementCharacter
}
return character
}.reduce(into: "") { $0.append($1) }
// Replace a leading dot so the filename is never `.`, `..`, or a hidden file.
if sanitized.first == "." {
sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_")
}
// Trim whitespace-replacement underscores at both ends (cosmetic).
sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
// Treat all-empty or all-separator results as unnamed.
guard !sanitized.isEmpty else { return "unnamed" }
// Cap to maxLength UTF-8 bytes so the full filename stays within 255 bytes.
if sanitized.utf8.count > maxLength {
var truncated: String = ""
var byteCount: Int = 0
for scalar: Unicode.Scalar in sanitized.unicodeScalars {
let encodedLength: Int = UTF8.width(scalar)
guard byteCount + encodedLength <= maxLength else { break }
truncated.unicodeScalars.append(scalar)
byteCount += encodedLength
}
sanitized = truncated
}
return sanitized.isEmpty ? "unnamed" : sanitized
}
@@ -0,0 +1,44 @@
// RigArchive.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Format version written into every exported ``RigArchive``.
///
/// Increment when the archive schema changes in a way that requires migration on load.
public let rigArchiveFormatVersion: Int = 1
/// A portable bundle of one or more ``RigEntry`` rigs in a single JSON document.
///
/// `RigArchive` is the hand-editable, shareable file format used by the library's
/// **Export Archive** / **Import Archive** actions — the way to back up or move an entire
/// collection of rigs as one file. It is the multi-rig successor to the old single-rig file
/// save/load: a legacy single-rig file (a bare ``ShoeGazeState``) is still importable and is
/// treated as a one-rig archive (see `RigLibraryStore.importArchive`).
///
/// The document is written pretty-printed with sorted keys, so it stays readable and editable by
/// hand. `Date` values inside each ``RigEntry`` are encoded as `secondsSince1970`.
public struct RigArchive: Codable, Equatable {
/// Archive format version. Written as `rigArchiveFormatVersion` at export time.
public let version: Int
/// The rigs contained in this archive, in listing order.
public let rigs: [RigEntry]
/// Creates a rig archive.
///
/// - Parameters:
/// - version: Archive format version. Defaults to `rigArchiveFormatVersion`.
/// - rigs: The rigs to bundle.
public init(
version: Int = rigArchiveFormatVersion,
rigs: [RigEntry]
) {
self.version = version
self.rigs = rigs
}
}
@@ -0,0 +1,98 @@
// RigEntry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A named, timestamped rig in the user's library.
///
/// `RigEntry` is the unit stored and retrieved by `RigLibraryStore`. Each entry pairs a complete
/// ``ShoeGazeState`` snapshot (every board and its pedals) with a human-readable `name`
/// (e.g. `"Ambient Wash"`) and a `savedAt` timestamp. It is the rig-level analogue of
/// `BoardVersion`, which captures a single board.
///
/// `RigEntry` is `Codable` so it round-trips through the per-rig JSON files written by
/// `RigLibraryStore` and through the bundled ``RigArchive`` export. It is `Identifiable`
/// (via `UUID`) for direct use in SwiftUI `List` / `ForEach`, and `Equatable` for round-trip tests.
///
/// ## Typical usage
///
/// ```swift
/// let entry = shoeGaze.captureEntry(name: "Ambient Wash")
/// try store.save(entry)
/// // later …
/// try shoeGaze.loadRig(from: entry.state)
/// ```
public struct RigEntry: Codable, Identifiable, Equatable {
/// Stable unique identifier for this entry. Also seeds the on-disk filename.
public let id: UUID
/// Human-readable name (e.g. `"Ambient Wash"`, `"Live Set A"`).
public let name: String
/// Date and time at which this entry was last saved, at **whole-second precision**.
///
/// Rounded to the nearest second at init so it survives a JSON `secondsSince1970`
/// round-trip exactly — otherwise the fractional `Double` text form loses precision and
/// breaks `Equatable` after a `RigLibraryStore` write/load cycle.
public let savedAt: Date
/// The full rig snapshot — every board, segment, and pedal parameter.
public let state: ShoeGazeState
/// Creates a rig library entry.
///
/// - Parameters:
/// - id: Stable unique identifier. Defaults to a newly generated `UUID()`.
/// - name: Human-readable name for this rig.
/// - savedAt: Save timestamp. Defaults to `Date()` (now). Rounded to the nearest
/// whole second so persistence round-trips are lossless.
/// - state: The ``ShoeGazeState`` rig snapshot to store.
public init(
id: UUID = UUID(),
name: String,
savedAt: Date = Date(),
state: ShoeGazeState
) {
self.id = id
self.name = name
// Round to whole seconds: a fractional Date loses precision through the JSON
// `secondsSince1970` Double text form, which would break `Equatable` after a
// disk round-trip.
self.savedAt = Date(timeIntervalSince1970: savedAt.timeIntervalSince1970.rounded())
self.state = state
}
/// Returns a copy of this entry with a new `name`, a fresh `id`, and `savedAt` updated to
/// `date`. Used by the library's "duplicate" action so a copied rig becomes an independent
/// entry rather than overwriting the original's file.
///
/// - Parameters:
/// - name: The new entry's name.
/// - date: The new save timestamp. Defaults to `Date()` (now).
/// - Returns: A new `RigEntry` carrying the same `state` under a new identity.
public func duplicated(
name: String,
date: Date = Date()
) -> RigEntry {
RigEntry(id: UUID(), name: name, savedAt: date, state: state)
}
/// Returns a copy of this entry with a new `name` and `savedAt` updated to `date`, keeping
/// the same `id`. Used by the library's "rename" action so the entry's identity and file
/// association are preserved.
///
/// - Parameters:
/// - name: The new name.
/// - date: The new save timestamp. Defaults to `Date()` (now).
/// - Returns: A new `RigEntry` with the same `id` and `state` under the new name.
public func renamed(
to name: String,
date: Date = Date()
) -> RigEntry {
RigEntry(id: id, name: name, savedAt: date, state: state)
}
}
@@ -0,0 +1,96 @@
// RigLibraryLocation.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Resolves where the rig library lives on disk: the shared iCloud container when available,
/// otherwise a local Application Support folder.
///
/// Both the macOS and iOS builder apps declare the **same** iCloud container
/// (``containerIdentifier``) in their entitlements — even though their bundle identifiers differ —
/// so a single rig library is shared across a user's devices and across both apps. When iCloud is
/// unavailable (not signed in, entitlement missing, or running in a context without provisioning)
/// the library falls back to a local folder and simply does not sync.
public enum RigLibraryLocation {
/// The shared iCloud container identifier. Both builder targets must list this exact value in
/// `com.apple.developer.icloud-container-identifiers` / `ubiquity-container-identifiers`, and
/// the container must be enabled on both App IDs in the developer account.
public static let containerIdentifier: String = "iCloud.net.realizedsound.ShoeGazeData"
/// Subfolder (inside the container's `Documents/` or inside Application Support) holding the
/// per-rig JSON files.
private static let rigsFolderName: String = "Rigs"
/// Local Application Support namespace, matching `BoardVersionStore.defaultDirectory()`.
private static let localFolderName: String = "LyrebirdShoeGaze"
/// iCloud documents subfolder. Storing rigs under `Documents/` (rather than the container root)
/// makes them eligible to appear in the Files app when `NSUbiquitousContainers` is configured.
private static let documentsFolderName: String = "Documents"
/// A resolved library directory and whether it is backed by iCloud.
public struct Resolved: Equatable {
/// The directory holding per-rig JSON files (created if needed).
public let directory: URL
/// `true` when `directory` is inside the iCloud ubiquity container (sync active);
/// `false` for the local Application Support fallback.
public let isICloud: Bool
}
/// Resolves the rig library directory, preferring iCloud.
///
/// - Important: When an iCloud account is signed in,
/// `FileManager.url(forUbiquityContainerIdentifier:)` performs **blocking** I/O that can be
/// slow on its first call. Prefer calling this **once at app startup, off the main thread**.
/// When no iCloud account is present, the cheap `ubiquityIdentityToken` check short-circuits
/// straight to the local fallback without the blocking call. The created directory is returned
/// ready to use.
///
/// - Parameter containerIdentifier: The ubiquity container to use. Defaults to
/// ``containerIdentifier``.
/// - Returns: The resolved directory and whether iCloud backing is active.
public static func resolve(
containerIdentifier identifier: String = containerIdentifier
) -> Resolved {
let fileManager: FileManager = FileManager.default
// No iCloud account signed in → skip the potentially-slow container lookup entirely.
guard fileManager.ubiquityIdentityToken != nil else {
return Resolved(directory: localDirectory(), isICloud: false)
}
if let container: URL = fileManager.url(forUbiquityContainerIdentifier: identifier) {
let directory: URL = container
.appendingPathComponent(documentsFolderName, isDirectory: true)
.appendingPathComponent(rigsFolderName, isDirectory: true)
try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
return Resolved(directory: directory, isICloud: true)
}
return Resolved(directory: localDirectory(), isICloud: false)
}
/// The local (non-iCloud) rig library directory, created if needed.
///
/// Falls back to a folder in the system temporary directory if Application Support cannot be
/// resolved. Used as the iCloud-unavailable fallback and directly by tests.
///
/// - Returns: A local `URL` for the rigs directory.
public static func localDirectory() -> URL {
let fileManager: FileManager = FileManager.default
let base: URL = (try? fileManager.url(
for: .applicationSupportDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)) ?? fileManager.temporaryDirectory
let directory: URL = base
.appendingPathComponent(localFolderName, isDirectory: true)
.appendingPathComponent(rigsFolderName, isDirectory: true)
try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
return directory
}
}
@@ -0,0 +1,562 @@
// RigLibraryStore.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Observation
/// The user's library of saved rigs, persisted as one JSON file per rig and (when available)
/// synced across devices and apps through a shared iCloud container.
///
/// `RigLibraryStore` is `@Observable`, so SwiftUI views refresh automatically as `entries`
/// changes — whether the change came from a local edit or from a remote iCloud update. All
/// mutations run on the main actor.
///
/// ## Storage model
///
/// Each ``RigEntry`` is written as a separate pretty-printed JSON file named
/// `<sanitized-name>-<id>.json` (see ``sanitizePresetFilename(_:maxLength:)``) inside the
/// directory resolved by ``RigLibraryLocation``. One file per rig keeps iCloud merges
/// conflict-free at rig granularity: editing rig A never rewrites rig B's file.
///
/// When the directory is an iCloud ubiquity container, reads and writes are wrapped in
/// `NSFileCoordinator`, and an `NSMetadataQuery` watches for remote changes so a rig saved on one
/// device appears on another without relaunching. Call ``start()`` once after construction to load
/// the current contents and begin watching.
///
/// ## Typical usage
///
/// ```swift
/// // Off the main thread at launch (the ubiquity lookup blocks):
/// let resolved = RigLibraryLocation.resolve()
/// // Back on the main actor:
/// let store = RigLibraryStore(resolved: resolved)
/// store.start()
/// // …
/// try store.save(shoeGaze.captureEntry(name: "Ambient Wash"))
/// ```
@MainActor
@Observable
public final class RigLibraryStore {
// MARK: - State
/// All known rigs, sorted by name (case-insensitive), then most-recently-saved first.
public private(set) var entries: [RigEntry] = []
/// `true` when the library is backed by the iCloud container (changes sync); `false` for the
/// local-only fallback. Resolved during ``start()`` for an auto-resolving store.
public private(set) var isICloud: Bool
/// The directory holding the per-rig JSON files. May be repointed from local to iCloud during
/// ``start()`` for an auto-resolving store (before any writes, so no migration is needed).
public private(set) var directory: URL
/// `false` until the first load completes. Views can show a loading state and callers should
/// wait for this (or `await start()`) before deciding whether the library is empty — otherwise a
/// first-launch seed would race a not-yet-loaded iCloud library.
public private(set) var isLoaded: Bool = false
// MARK: - Private
/// Live query over the iCloud documents scope; `nil` when local-only or not yet started.
@ObservationIgnored private var metadataQuery: NSMetadataQuery?
/// Retained NotificationCenter tokens for the metadata-query observers.
@ObservationIgnored private var observerTokens: [NSObjectProtocol] = []
/// Serial queue for all disk writes/deletes. Mutations update the in-memory `entries` on the
/// main actor immediately (so the UI never blocks on disk or iCloud coordination), then hand the
/// file work here. Serial ordering keeps a rename's delete-then-write — and any save/delete on
/// the same file — in submission order.
@ObservationIgnored private let ioQueue: DispatchQueue =
DispatchQueue(label: "net.realizedsound.shoegaze.riglibrary.io", qos: .utility)
/// File extension of a stored rig.
private nonisolated static let fileExtension: String = "json"
/// When `true`, ``start()`` resolves the iCloud-or-local location off the main thread and
/// repoints `directory`/`isICloud` before loading. `false` for the explicit test initializer.
private let autoResolve: Bool
// MARK: - Init
/// Creates a store rooted at an explicit directory. Used directly by tests with a temporary
/// directory; `start()` will not re-resolve the location.
///
/// - Parameters:
/// - directory: The directory holding per-rig JSON files. Created if it does not exist.
/// - isICloud: Whether `directory` is an iCloud ubiquity container (enables coordination and
/// remote-change watching).
public init(
directory: URL,
isICloud: Bool
) {
self.directory = directory
self.isICloud = isICloud
self.autoResolve = false
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
/// Creates an auto-resolving store. Constructed instantly with a local placeholder directory;
/// ``start()`` resolves the real iCloud-or-local location off the main thread before loading.
public init() {
self.directory = RigLibraryLocation.localDirectory()
self.isICloud = false
self.autoResolve = true
}
// MARK: - Lifecycle
/// Resolves the location (off the main thread, for an auto-resolving store), loads the current
/// library contents (off the main thread), and — when iCloud-backed — begins watching for
/// remote changes. Awaitable so callers can seed/highlight only once the real library state is
/// known. Safe to call once after construction.
public func start() async {
if autoResolve {
let resolved: RigLibraryLocation.Resolved = await RigLibraryStore.resolveOffMain()
directory = resolved.directory
isICloud = resolved.isICloud
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
if isICloud {
startMetadataQuery()
}
await reload()
isLoaded = true
}
/// Re-reads the library directory off the main thread and republishes `entries`. Ordered after
/// any queued background writes (shares `ioQueue`), so a save followed by a reload never drops
/// the just-saved rig.
public func reload() async {
let dir: URL = directory
let coordinated: Bool = isICloud
let loaded: [RigEntry] = await withCheckedContinuation { continuation in
ioQueue.async {
continuation.resume(returning: RigLibraryStore.loadEntries(in: dir, coordinated: coordinated))
}
}
entries = RigLibraryStore.sorted(loaded)
}
/// Resolves the iCloud-or-local location on a background queue so the blocking ubiquity lookup
/// never runs on the main thread.
private static func resolveOffMain() async -> RigLibraryLocation.Resolved {
await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
continuation.resume(returning: RigLibraryLocation.resolve())
}
}
}
/// Stops watching for remote changes and removes observers. Call when tearing the store down;
/// the store otherwise lives for the app's lifetime.
public func stop() {
metadataQuery?.stop()
metadataQuery = nil
for token: NSObjectProtocol in observerTokens {
NotificationCenter.default.removeObserver(token)
}
observerTokens.removeAll()
}
// MARK: - Mutations
/// Saves `entry`, writing its JSON file and updating `entries` in memory.
///
/// If an entry with the same `id` already exists, its file and in-memory record are replaced
/// (the on-disk filename also updates if the name changed). Use this both to add a brand-new
/// rig and to overwrite an existing one (`shoeGaze.captureEntry(name:id:)`).
///
/// - Parameter entry: The rig entry to persist.
/// - Throws: `JSONEncoder` errors (encoding happens synchronously). The actual file write runs
/// asynchronously on a background queue and only logs on failure — call
/// ``flushPendingWrites()`` to wait for it (e.g. in tests or at app termination).
public func save(_ entry: RigEntry) throws {
// Encode synchronously (cheap, CPU) so an encoding failure is surfaced to the caller; then
// update the in-memory list immediately and push the disk write to the background queue.
let data: Data = try encode(entry)
let target: URL = fileURL(for: entry)
let directory: URL = self.directory
let id: UUID = entry.id
let coordinated: Bool = isICloud
upsert(entry)
ioQueue.async {
// Remove any prior file for this id first (a rename changes the name-prefixed filename).
if let stale: URL = RigLibraryStore.existingFileURL(for: id, in: directory),
stale.standardizedFileURL != target.standardizedFileURL {
try? RigLibraryStore.removeFile(at: stale, coordinated: coordinated)
}
do {
try RigLibraryStore.writeData(data, to: target, coordinated: coordinated)
} catch {
print("[RigLibraryStore] save write failed: \(error)")
}
}
}
/// Deletes `entry` from memory immediately and removes its file on the background queue.
///
/// - Parameter entry: The rig entry to remove.
/// - Throws: Never throws today; remains `throws` for API stability. File-removal errors are
/// logged on the background queue.
public func delete(_ entry: RigEntry) throws {
entries.removeAll { $0.id == entry.id }
let directory: URL = self.directory
let id: UUID = entry.id
let coordinated: Bool = isICloud
ioQueue.async {
if let url: URL = RigLibraryStore.existingFileURL(for: id, in: directory) {
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
catch { print("[RigLibraryStore] delete failed: \(error)") }
}
}
}
/// Clears the library in memory immediately and removes every rig file on the background queue.
///
/// - Throws: Never throws today; remains `throws` for API stability. Per-file removal errors are
/// logged on the background queue.
public func eraseAll() throws {
entries.removeAll()
let directory: URL = self.directory
let coordinated: Bool = isICloud
ioQueue.async {
for url: URL in RigLibraryStore.rigFileURLs(in: directory) {
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
catch { print("[RigLibraryStore] eraseAll: removing \(url.lastPathComponent) failed: \(error)") }
}
}
}
/// Blocks until all queued background writes/deletes have completed.
///
/// Primarily for tests (assert on-disk state right after a mutation) and app termination (ensure
/// the last save reaches disk before exit). Avoid calling on the main thread during normal use —
/// that would reintroduce the very stall this design removes.
public func flushPendingWrites() {
ioQueue.sync { }
}
/// Duplicates `entry` under `newName` as an independent entry with a fresh `id`, persists it,
/// and returns it.
///
/// - Parameters:
/// - entry: The rig to copy.
/// - newName: The copy's name.
/// - Returns: The newly created entry.
/// - Throws: Any error from ``save(_:)``.
@discardableResult
public func duplicate(
_ entry: RigEntry,
newName: String
) throws -> RigEntry {
let copy: RigEntry = entry.duplicated(name: newName)
try save(copy)
return copy
}
/// Renames `entry` to `newName`, keeping its `id`, and returns the updated entry.
///
/// - Parameters:
/// - entry: The rig to rename.
/// - newName: The new name.
/// - Returns: The renamed entry.
/// - Throws: Any error from ``save(_:)``.
@discardableResult
public func rename(
_ entry: RigEntry,
to newName: String
) throws -> RigEntry {
let renamed: RigEntry = entry.renamed(to: newName)
try save(renamed)
return renamed
}
// MARK: - Archive import / export
/// Encodes the entire library as a single ``RigArchive`` JSON document.
///
/// Retained for callers and tests that want the bare archive bytes. The user-facing
/// export/share path uses ``exportDocumentData()``, which wraps the same rigs in a
/// ``ShoeGazeDocument`` envelope (the `.shoegaze` file type).
///
/// - Returns: Pretty-printed archive bytes.
/// - Throws: `JSONEncoder` errors.
public func exportArchiveData() throws -> Data {
let archive: RigArchive = RigArchive(rigs: entries)
return try RigLibraryStore.makeEncoder().encode(archive)
}
/// Encodes the entire library as a ``ShoeGazeDocument`` for export to a `.shoegaze` file.
///
/// This is the format written by the library's **Export** action and shared via the system
/// share sheet. ``importArchive(from:)`` reads it back, and also still accepts the bare
/// ``RigArchive`` and legacy single-rig shapes.
///
/// - Returns: Pretty-printed `.shoegaze` document bytes.
/// - Throws: `JSONEncoder` errors.
public func exportDocumentData() throws -> Data {
try ShoeGazeDocument(rigs: entries).data()
}
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
/// added.
///
/// Accepts a ``ShoeGazeDocument`` (the `.shoegaze` file type), a bare ``RigArchive`` (the prior
/// multi-rig export), or a legacy single-rig file (a bare ``ShoeGazeState``), which is imported
/// as one entry named `legacyRigName`. A document carrying a board rather than rigs contributes
/// no entries. Imported entries whose `id` already exists in the library are given a fresh `id`
/// so an import never silently overwrites an existing rig.
///
/// - Parameters:
/// - data: Archive or legacy-rig JSON bytes.
/// - legacyRigName: Name to use when importing a legacy single-rig file. Defaults to
/// `"Imported Rig"`.
/// - Returns: The number of rigs added to the library.
/// - Throws: `JSONDecoder` errors when `data` is neither an archive nor a legacy rig, or any
/// error from ``save(_:)``.
@discardableResult
public func importArchive(
from data: Data,
legacyRigName: String = "Imported Rig"
) throws -> Int {
let imported: [RigEntry] = try decodeImportable(data, legacyRigName: legacyRigName)
let existingIDs: Set<UUID> = Set(entries.map(\.id))
var added: Int = 0
for entry: RigEntry in imported {
// Avoid clobbering an existing rig that happens to share this id.
let toSave: RigEntry = existingIDs.contains(entry.id)
? entry.duplicated(name: entry.name, date: entry.savedAt)
: entry
try save(toSave)
added += 1
}
return added
}
// MARK: - Loading from disk
/// Rescans the directory and rebuilds `entries`. Files that cannot be read or decoded are
/// skipped so one bad file never blocks the rest. Not-yet-downloaded iCloud placeholders (which
/// are hidden `*.icloud` files) are naturally ignored and picked up on a later metadata update.
private nonisolated static func loadEntries(in directory: URL, coordinated: Bool) -> [RigEntry] {
var loaded: [RigEntry] = []
let decoder: JSONDecoder = makeDecoder()
for url: URL in rigFileURLs(in: directory) {
guard let data: Data = try? readData(at: url, coordinated: coordinated) else { continue }
guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue }
loaded.append(entry)
}
return loaded
}
// MARK: - iCloud metadata query
/// Starts the live query over the iCloud documents scope and wires update handlers.
private func startMetadataQuery() {
guard metadataQuery == nil else { return }
let query: NSMetadataQuery = NSMetadataQuery()
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
query.predicate = NSPredicate(
format: "%K LIKE %@",
NSMetadataItemFSNameKey,
"*.\(RigLibraryStore.fileExtension)"
)
let center: NotificationCenter = NotificationCenter.default
let handler: @Sendable (Notification) -> Void = { [weak self] _ in
// queue: .main delivers on the main thread; we are a main-actor type.
MainActor.assumeIsolated { self?.handleMetadataUpdate() }
}
observerTokens.append(center.addObserver(
forName: .NSMetadataQueryDidFinishGathering, object: query, queue: .main, using: handler
))
observerTokens.append(center.addObserver(
forName: .NSMetadataQueryDidUpdate, object: query, queue: .main, using: handler
))
metadataQuery = query
query.start()
}
/// Handles a metadata-query result: triggers downloads for any rig files not yet present
/// locally, then rescans the directory for whatever is now readable.
private func handleMetadataUpdate() {
guard let query: NSMetadataQuery = metadataQuery else { return }
query.disableUpdates()
defer { query.enableUpdates() }
let fileManager: FileManager = FileManager.default
for index: Int in 0..<query.resultCount {
guard let item: NSMetadataItem = query.result(at: index) as? NSMetadataItem,
let url: URL = item.value(forAttribute: NSMetadataItemURLKey) as? URL,
RigLibraryStore.isInLibrary(url, directory: directory) else { continue }
let status: String? =
item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
if status != NSMetadataUbiquitousItemDownloadingStatusCurrent {
try? fileManager.startDownloadingUbiquitousItem(at: url)
}
}
// Re-read off the main thread; the in-memory list republishes when it completes.
Task { await self.reload() }
}
// MARK: - File helpers
/// The write URL for `entry`: `<sanitized-name>-<id>.json` inside the library directory.
private func fileURL(for entry: RigEntry) -> URL {
let sanitized: String = sanitizePresetFilename(entry.name)
let filename: String = "\(sanitized)-\(entry.id.uuidString).\(RigLibraryStore.fileExtension)"
return directory.appendingPathComponent(filename)
}
/// Finds the existing file for `id` by matching the `-<uuid>.json` suffix, so renames (which
/// change the name prefix) are still located. `nil` if no file is present. `static` so the
/// background I/O queue can call it without touching actor state.
private nonisolated static func existingFileURL(for id: UUID, in directory: URL) -> URL? {
let suffix: String = "-\(id.uuidString).\(fileExtension)"
return rigFileURLs(in: directory).first { $0.lastPathComponent.hasSuffix(suffix) }
}
/// All `*.json` files currently in `directory` (hidden iCloud placeholders excluded).
private nonisolated static func rigFileURLs(in directory: URL) -> [URL] {
let contents: [URL] = (try? FileManager.default.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles
)) ?? []
return contents.filter { $0.pathExtension == fileExtension }
}
/// Whether `url` is a rig file directly inside `directory`.
private nonisolated static func isInLibrary(_ url: URL, directory: URL) -> Bool {
url.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL
&& url.pathExtension == fileExtension
}
// MARK: - Coordinated I/O (background-queue safe)
/// Writes `data` to `url`, coordinating the write through `NSFileCoordinator` when iCloud-backed.
private nonisolated static func writeData(_ data: Data, to url: URL, coordinated: Bool) throws {
guard coordinated else {
try data.write(to: url, options: .atomic)
return
}
try coordinateWriting(url, options: .forReplacing) { target in
try data.write(to: target, options: .atomic)
}
}
/// Reads the contents of `url`, coordinating the read when iCloud-backed.
private nonisolated static func readData(at url: URL, coordinated: Bool) throws -> Data {
guard coordinated else {
return try Data(contentsOf: url)
}
var result: Data = Data()
try coordinateReading(url, options: .withoutChanges) { target in
result = try Data(contentsOf: target)
}
return result
}
/// Removes `url`, coordinating the delete when iCloud-backed.
private nonisolated static func removeFile(at url: URL, coordinated: Bool) throws {
guard coordinated else {
try FileManager.default.removeItem(at: url)
return
}
try coordinateWriting(url, options: .forDeleting) { target in
try FileManager.default.removeItem(at: target)
}
}
/// Runs `body` inside an `NSFileCoordinator` write block, surfacing both the coordinator's error
/// and any error thrown by `body`.
private nonisolated static func coordinateWriting(
_ url: URL,
options: NSFileCoordinator.WritingOptions,
_ body: (URL) throws -> Void
) throws {
let coordinator: NSFileCoordinator = NSFileCoordinator()
var coordinatorError: NSError?
var thrown: Error?
coordinator.coordinate(writingItemAt: url, options: options, error: &coordinatorError) { target in
do { try body(target) } catch { thrown = error }
}
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
if let thrown: Error = thrown { throw thrown }
}
/// Runs `body` inside an `NSFileCoordinator` read block.
private nonisolated static func coordinateReading(
_ url: URL,
options: NSFileCoordinator.ReadingOptions,
_ body: (URL) throws -> Void
) throws {
let coordinator: NSFileCoordinator = NSFileCoordinator()
var coordinatorError: NSError?
var thrown: Error?
coordinator.coordinate(readingItemAt: url, options: options, error: &coordinatorError) { target in
do { try body(target) } catch { thrown = error }
}
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
if let thrown: Error = thrown { throw thrown }
}
// MARK: - Codec
/// Encodes a single entry as a per-rig file would store it.
private func encode(_ entry: RigEntry) throws -> Data {
try RigLibraryStore.makeEncoder().encode(entry)
}
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
private nonisolated static func makeEncoder() -> JSONEncoder {
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .secondsSince1970
return encoder
}
/// A JSON decoder matching ``makeEncoder()``.
private nonisolated static func makeDecoder() -> JSONDecoder {
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}
/// Decodes import bytes into rig entries, accepting the `.shoegaze` ``ShoeGazeDocument``
/// envelope plus the bare ``RigArchive`` and legacy ``ShoeGazeState`` shapes (see
/// ``ShoeGazeDocument/decoded(from:legacyRigName:)``). A board-carrying document yields no rigs.
private func decodeImportable(
_ data: Data,
legacyRigName: String
) throws -> [RigEntry] {
let document: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data, legacyRigName: legacyRigName)
return document.rigEntries ?? []
}
// MARK: - In-memory helpers
/// Inserts or replaces `entry` in `entries` by `id`, keeping the list sorted.
private func upsert(_ entry: RigEntry) {
var next: [RigEntry] = entries.filter { $0.id != entry.id }
next.append(entry)
entries = RigLibraryStore.sorted(next)
}
/// Sorts entries by name (case-insensitive), then most-recently-saved first, then id for a
/// fully deterministic order.
private static func sorted(_ entries: [RigEntry]) -> [RigEntry] {
entries.sorted { lhs, rhs in
let byName: ComparisonResult = lhs.name.localizedCaseInsensitiveCompare(rhs.name)
if byName != .orderedSame { return byName == .orderedAscending }
if lhs.savedAt != rhs.savedAt { return lhs.savedAt > rhs.savedAt }
return lhs.id.uuidString < rhs.id.uuidString
}
}
}
@@ -32,12 +32,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 +60,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 +74,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,24 @@ 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.
///
/// Wraps ``captureState()`` with a name, a fresh `id`, and a `savedAt` timestamp. The engine
/// graph is not modified; this is a read-only operation.
///
/// - Parameters:
/// - name: Human-readable name for the entry (e.g. `"Ambient Wash"`).
/// - id: Stable identifier. Defaults to a newly generated `UUID()`; pass an existing entry's
/// `id` to overwrite that entry in place.
/// - Returns: A ``RigEntry`` reflecting the current rig.
public func captureEntry(
name: String,
id: UUID = UUID()
) -> RigEntry {
RigEntry(id: id, name: name, state: captureState())
}
// MARK: - Save / Load
@@ -58,12 +75,29 @@ extension ShoeGaze {
public func loadRig(from data: Data) throws {
let decoder: JSONDecoder = JSONDecoder()
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
try loadRig(from: state)
}
/// Rebuilds the engine graph from an already-decoded ``ShoeGazeState``.
///
/// Shared core of the `Data` / `URL` loaders, and the entry point the rig library uses to
/// recall a stored ``RigEntry`` (`loadRig(from: entry.state)`) without re-encoding. Rejects a
/// snapshot whose `version` exceeds `presetFormatVersion`, tears down the current rig, then
/// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``.
///
/// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``.
/// - Parameter state: The rig snapshot to restore.
/// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error.
public func loadRig(from state: ShoeGazeState) throws {
guard state.version <= presetFormatVersion else {
throw PresetError.unsupportedVersion(state.version)
}
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.
@@ -0,0 +1,201 @@
// ShoeGazeDocument.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Format version written into every `.shoegaze` document.
///
/// Increment when the `ShoeGazeDocument` envelope schema changes in a way that requires
/// migration on load. The payload types (``RigArchive`` / ``BoardVersion``) carry their own
/// independent version fields.
public let shoeGazeDocumentFormatVersion: Int = 1
/// The portable `.shoegaze` document — the single file type ShoeGaze writes when a user shares
/// or exports their work, and reads when opening a shared file.
///
/// A document is a small versioned envelope around one of two payloads:
///
/// - ``Payload/rigs(_:)`` — one or more rigs, carried as a ``RigArchive`` (a single shared rig is
/// a one-rig archive; the whole-library export is a many-rig archive).
/// - ``Payload/board(_:)`` — a single named board snapshot (``BoardVersion``).
///
/// Files are written pretty-printed with sorted keys and `secondsSince1970` dates, so they stay
/// hand-readable and round-trip losslessly.
///
/// ## Backward compatibility
///
/// ``decoded(from:)`` accepts three on-disk shapes so older files keep opening:
/// 1. A `ShoeGazeDocument` envelope (the current format).
/// 2. A bare ``RigArchive`` (the previous multi-rig export).
/// 3. A bare ``ShoeGazeState`` (the original single-rig save).
///
/// Shapes 2 and 3 are normalised into a ``Payload/rigs(_:)`` document on load.
public struct ShoeGazeDocument: Codable, Equatable {
/// The two things a `.shoegaze` file can carry.
public enum Payload: Equatable {
/// One or more rigs, as a portable archive.
case rigs(RigArchive)
/// A single named board snapshot.
case board(BoardVersion)
}
/// Filename extension and the basis for the document's UTType (`net.realizedsound.shoegaze`).
public static let fileExtension: String = "shoegaze"
/// Document envelope version. Written as `shoeGazeDocumentFormatVersion` at save time.
public let version: Int
/// What this document carries.
public let payload: Payload
/// Creates a document with an explicit payload.
///
/// - Parameters:
/// - version: Envelope version. Defaults to `shoeGazeDocumentFormatVersion`.
/// - payload: The rigs or board this document carries.
public init(
version: Int = shoeGazeDocumentFormatVersion,
payload: Payload
) {
self.version = version
self.payload = payload
}
// MARK: - Convenience constructors
/// Creates a single-rig document by wrapping one ``RigEntry`` in a one-rig ``RigArchive``.
///
/// - Parameter entry: The rig to share.
public init(rig entry: RigEntry) {
self.init(payload: .rigs(RigArchive(rigs: [entry])))
}
/// Creates a multi-rig document from a list of entries.
///
/// - Parameter entries: The rigs to bundle, in listing order.
public init(rigs entries: [RigEntry]) {
self.init(payload: .rigs(RigArchive(rigs: entries)))
}
/// Creates a single-board document.
///
/// - Parameter version: The board snapshot to share.
public init(board version: BoardVersion) {
self.init(payload: .board(version))
}
// MARK: - Payload accessors
/// The rigs this document carries, or `nil` when it carries a board.
public var rigEntries: [RigEntry]? {
if case .rigs(let archive) = payload { return archive.rigs }
return nil
}
/// The board this document carries, or `nil` when it carries rigs.
public var boardVersion: BoardVersion? {
if case .board(let version) = payload { return version }
return nil
}
// MARK: - Encoding
/// Encodes this document to pretty-printed, hand-editable `.shoegaze` JSON.
///
/// - Returns: The encoded document bytes.
/// - Throws: Any error from `JSONEncoder`.
public func data() throws -> Data {
try ShoeGazeDocument.makeEncoder().encode(self)
}
/// Decodes a `.shoegaze` document, tolerating the two legacy on-disk shapes.
///
/// Tries the `ShoeGazeDocument` envelope first, then a bare ``RigArchive``, then a bare
/// ``ShoeGazeState`` — normalising the latter two into a rigs document. A bare state with no
/// name becomes a one-rig archive named `legacyRigName`.
///
/// - Parameters:
/// - data: The document bytes.
/// - legacyRigName: Name applied when normalising a bare ``ShoeGazeState``. Defaults to
/// `"Imported Rig"`.
/// - Returns: A normalised document.
/// - Throws: `JSONDecoder` errors when `data` matches none of the three shapes.
public static func decoded(
from data: Data,
legacyRigName: String = "Imported Rig"
) throws -> ShoeGazeDocument {
let decoder: JSONDecoder = makeDecoder()
if let document: ShoeGazeDocument = try? decoder.decode(ShoeGazeDocument.self, from: data) {
return document
}
if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) {
return ShoeGazeDocument(payload: .rigs(archive))
}
// Original single-rig save: a bare ShoeGazeState. Let a genuine decode failure surface here.
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
return ShoeGazeDocument(rig: RigEntry(name: legacyRigName, state: state))
}
/// A JSON encoder configured for human-readable, round-trip-stable document files.
static func makeEncoder() -> JSONEncoder {
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .secondsSince1970
return encoder
}
/// A JSON decoder matching ``makeEncoder()``.
static func makeDecoder() -> JSONDecoder {
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}
// MARK: - Codable
/// Discriminator written into the JSON so a payload reads back unambiguously.
private enum Kind: String, Codable {
case rigs
case board
}
private enum CodingKeys: String, CodingKey {
case version
case kind
case rigs
case board
}
/// Encodes the envelope with an explicit `kind` discriminator and the matching payload key.
public func encode(to encoder: any Encoder) throws {
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
try container.encode(version, forKey: .version)
switch payload {
case .rigs(let archive):
try container.encode(Kind.rigs, forKey: .kind)
try container.encode(archive, forKey: .rigs)
case .board(let boardVersion):
try container.encode(Kind.board, forKey: .kind)
try container.encode(boardVersion, forKey: .board)
}
}
/// Decodes the envelope, reading the payload named by the `kind` discriminator.
public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.version = try container.decode(Int.self, forKey: .version)
let kind: Kind = try container.decode(Kind.self, forKey: .kind)
switch kind {
case .rigs:
self.payload = .rigs(try container.decode(RigArchive.self, forKey: .rigs))
case .board:
self.payload = .board(try container.decode(BoardVersion.self, forKey: .board))
}
}
}
@@ -27,16 +27,44 @@ 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 OR malformed `midiMap`.
///
/// The MIDI map is decoded with `try?` so a binding format that this build can't read (e.g. an
/// autosave written by an older schema) drops just the bindings — which are re-learnable —
/// rather than throwing and losing the entire 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)
self.boards = try container.decode([BoardState].self, forKey: .boards)
self.midiMap = try? container.decodeIfPresent(MIDIMap.self, forKey: .midiMap) ?? nil
}
}
@@ -280,8 +280,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
+120 -1
View File
@@ -66,6 +66,17 @@ public final class ShoeGaze {
/// 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.
@@ -237,7 +248,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 +268,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 +280,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 +297,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,6 +388,78 @@ 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.
///
@@ -388,6 +500,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.
@@ -531,5 +644,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()
}
}
@@ -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 {
@@ -218,6 +218,16 @@ public struct BoardEditorView: View {
Button("Load") {
loadVersion(version)
}
// Encoding a fully-concrete BoardVersion to JSON does not fail in practice; on the
// unreachable failure path the Share item is simply omitted.
if let shareItem: BoardShareItem = try? BoardShareItem(board: version) {
ShareLink(
item: shareItem,
preview: SharePreview(version.name)
) {
Label("Share…", systemImage: "square.and.arrow.up")
}
}
Button("Delete", role: .destructive) {
versionStore.remove(version)
try? versionStore.deleteFromDisk(version, in: BoardVersionStore.defaultDirectory())
+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`:
@@ -0,0 +1,43 @@
// BoardShareItem.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import CoreTransferable
import UniformTypeIdentifiers
import LyrebirdShoeGaze
/// A `Transferable` wrapper that lets a `ShareLink` send a single board as a `.shoegaze` document.
///
/// Mirrors ``RigShareItem`` for a board snapshot: it holds the already-encoded document bytes and,
/// via `FileRepresentation`, writes them to a temporary `<board>.shoegaze` file when a share
/// destination is picked — giving the share sheet a real file so AirDrop, Messages, Mail, Notes,
/// and Files all appear (raw data collapses the macOS menu to Copy / Edit Extensions).
struct BoardShareItem: Transferable, Sendable {
/// Filesystem-safe base name for the shared file (no extension).
let filenameBase: String
/// Encoded `.shoegaze` document bytes.
let data: Data
/// Encodes `version` as a single-board `.shoegaze` document.
///
/// - Parameter version: The board snapshot to share.
/// - Throws: Any `JSONEncoder` error from ``ShoeGazeDocument/data()``.
init(board version: BoardVersion) throws {
self.filenameBase = shareFilenameBase(version.name)
self.data = try ShoeGazeDocument(board: version).data()
}
static var transferRepresentation: some TransferRepresentation {
FileRepresentation(exportedContentType: .shoeGaze) { item in
SentTransferredFile(try writeShoeGazeShareFile(item.data, base: item.filenameBase))
}
.suggestedFileName { item in
"\(item.filenameBase).\(ShoeGazeDocument.fileExtension)"
}
}
}
@@ -123,6 +123,32 @@ public struct EngineConfigView: View {
pendingInputs = shoeGaze.engine.numInputChannels
pendingOutputs = shoeGaze.engine.numOutputChannels
}
// Apply config edits to the (stopped) engine immediately so dependent UI — notably the
// input-source picker, which lists `0..<engine.numInputChannels` — reflects the new channel
// counts before Start. While running, the controls are disabled, so these never fire then.
.onChange(of: pendingInputs) { applyConfigWhileStopped() }
.onChange(of: pendingOutputs) { applyConfigWhileStopped() }
.onChange(of: pendingSampleRate) { applyConfigWhileStopped() }
}
/// Reconfigures the stopped engine with the pending values and notifies the host so views that
/// read non-observable engine state refresh. No-op while the engine is running.
private func applyConfigWhileStopped() {
guard !shoeGaze.engine.isRunning else { return }
do {
if let applyConfig: (Double, Int, Int) throws -> Void = applyConfig {
try applyConfig(pendingSampleRate, pendingInputs, pendingOutputs)
} else {
try shoeGaze.reconfigureEngine(
sampleRate: pendingSampleRate,
inputChannels: pendingInputs,
outputChannels: pendingOutputs
)
}
onConfigApplied()
} catch {
print("[EngineConfigView] live reconfigure failed: \(error)")
}
}
private func label(_ text: String) -> some View {
+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,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,258 @@
// 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 boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() {
let boardIndex: Int = boardPair.offset
let board: PedalBoard = boardPair.element
rows.append(SwitchRowModel(id: "sw-solo-\(boardIndex)",
action: .boardSolo(boardIndex: boardIndex),
label: "\(board.label) · Solo"))
rows.append(SwitchRowModel(id: "sw-aud-\(boardIndex)",
action: .boardAudible(boardIndex: boardIndex),
label: "\(board.label) · Audible"))
rows.append(SwitchRowModel(id: "sw-byp-\(boardIndex)",
action: .boardBypass(boardIndex: boardIndex),
label: "\(board.label) · Bypass"))
for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() {
rows.append(SwitchRowModel(
id: "sw-pb-\(boardIndex)-\(pedalPair.offset)",
action: .pedalBypass(boardIndex: boardIndex, pedalIndex: pedalPair.offset),
label: "\(board.label) · \(pedalPair.element.displayName) · Bypass"))
}
}
return rows
}
private var ccRowModels: [CCRowModel] {
var rows: [CCRowModel] = [
CCRowModel(id: "cc-rigvol", target: .rigVolume, label: "Rig · Volume"),
]
for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() {
let boardIndex: Int = boardPair.offset
let board: PedalBoard = boardPair.element
// Board master level (the board fader).
rows.append(CCRowModel(
id: "cc-blvl-\(boardIndex)",
target: .boardLevel(boardIndex: boardIndex, boardLabelHint: nil),
label: "\(board.label) · Level"))
for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() {
let pedalIndex: Int = pedalPair.offset
let pedal: Pedal = pedalPair.element
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
rows.append(CCRowModel(
id: "cc-\(boardIndex)-\(pedalIndex)-\(controlPair.offset)",
target: .pedalControl(
boardIndex: boardIndex,
pedalIndex: pedalIndex,
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,57 @@
// PedalCategory.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
/// A presentation grouping for pedals in the palette — used to colour-code the picker cards and to
/// drive the "filter by type" menu. Purely a UI concern: the mapping from a pedal's `displayName`
/// to its category lives here, keyed by name like ``PedalPaletteView``'s preferred order.
enum PedalCategory: String, CaseIterable, Identifiable {
case gain = "Gain"
case dynamics = "Dynamics"
case filter = "EQ & Filter"
case modulation = "Modulation"
case pitch = "Pitch"
case delay = "Delay"
case reverb = "Reverb"
case texture = "Texture"
var id: String { rawValue }
/// Accent colour used to tint the palette card and the filter chip.
var color: Color {
switch self {
case .gain: return Color(red: 0.82, green: 0.38, blue: 0.12)
case .dynamics: return Color(red: 0.20, green: 0.50, blue: 0.32)
case .filter: return Color(red: 0.14, green: 0.46, blue: 0.55)
case .modulation: return Color(red: 0.40, green: 0.34, blue: 0.74)
case .pitch: return Color(red: 0.60, green: 0.26, blue: 0.50)
case .delay: return Color(red: 0.10, green: 0.52, blue: 0.62)
case .reverb: return Color(red: 0.34, green: 0.22, blue: 0.66)
case .texture: return Color(red: 0.48, green: 0.42, blue: 0.30)
}
}
/// The category for a pedal `displayName`. Unknown (e.g. third-party) names fall back to
/// ``texture`` so they remain visible and tinted.
static func category(for displayName: String) -> PedalCategory {
mapping[displayName] ?? .texture
}
private static let mapping: [String: PedalCategory] = [
"Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain, "Volume": .gain,
"Compressor": .dynamics, "Sustainer": .dynamics, "Limiter": .dynamics, "Noise Gate": .dynamics,
"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,
]
}
@@ -38,6 +38,9 @@ public struct PedalPaletteView: View {
private static let cardBorderWidth: CGFloat = 1
private static let pedalCardBrightness: Double = 0.18
private static let routingCardBrightness: Double = 0.1
/// Category-colour fill / border opacity for the colour-coded pedal cards.
private static let categoryFillOpacity: Double = 0.22
private static let categoryBorderOpacity: Double = 0.65
private static let routingCaptionOpacity: Double = 0.5
private static let routingCaptionFontSize: CGFloat = 10
private static let addGlyphOpacity: Double = 0.4
@@ -45,14 +48,19 @@ public struct PedalPaletteView: View {
private static let rowSubtitleSpacing: CGFloat = 2
/// Opacity of the pedal-row description subtitle.
private static let summaryOpacity: Double = 0.55
/// Fixed card width when laid out horizontally (the vertical layout stretches to fill instead).
private static let horizontalCardWidth: CGFloat = 150
/// Preferred display order for the built-in pedals. Any registered pedal not listed here is
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
private static let preferredOrder: [String] = [
"Overdrive", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus",
"Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter",
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb",
"Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
"Volume",
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
"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", "Plate Reverb", "Room Reverb", "Spring Reverb",
]
/// Routing/branching topologies the user can insert into the board.
@@ -74,19 +82,28 @@ public struct PedalPaletteView: View {
private let onAdd: (String) -> Void
private let onRouting: (RoutingAction) -> Void
private let axis: Axis
/// Active type filter; `nil` shows all pedals.
@State private var filter: PedalCategory?
// MARK: - Init
/// Creates a pedal palette.
///
/// - Parameters:
/// - axis: `.vertical` (default) lays the catalog out as a full-width column for a sidebar;
/// `.horizontal` lays it out as a fixed-width-card row for a horizontal scroller. The host
/// wraps the view in a `ScrollView` of the matching axis.
/// - onAdd: Invoked with a pedal's `displayName` when its row is tapped (append to main chain).
/// Rows are also `.draggable` carrying `"add:<displayName>"` for drop-onto-lane targeting.
/// - onRouting: Invoked when a routing row is tapped. Defaults to a no-op.
public init(
axis: Axis = .vertical,
onAdd: @escaping (String) -> Void,
onRouting: @escaping (RoutingAction) -> Void = { _ in }
) {
self.axis = axis
self.onAdd = onAdd
self.onRouting = onRouting
}
@@ -101,13 +118,42 @@ public struct PedalPaletteView: View {
return ordered + extras
}
/// Pedal names after applying the active type filter.
private var visiblePedalNames: [String] {
guard let filter: PedalCategory = filter else { return orderedPedalNames }
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 {
switch axis {
case .horizontal: horizontalBody
default: verticalBody
}
}
/// Full-width column for a left sidebar.
private var verticalBody: some View {
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
sectionTitle("PEDALS")
ForEach(orderedPedalNames, id: \.self) { name in
HStack {
sectionTitle("PEDALS")
Spacer(minLength: 0)
filterMenu
}
ForEach(visiblePedalNames, id: \.self) { name in
pedalRow(name)
}
}
@@ -121,6 +167,35 @@ public struct PedalPaletteView: View {
}
}
/// Horizontal scroller: a PEDALS row (leading filter + colour-coded cards) with the ROUTING
/// row stacked beneath it.
private var horizontalBody: some View {
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
HStack(alignment: .top, spacing: PedalPaletteView.sectionSpacing) {
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
sectionTitle("PEDALS")
filterMenu
}
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) {
sectionTitle("ROUTING")
ForEach(PedalPaletteView.routingOptions, id: \.title) { option in
routingCard(title: option.title, caption: option.caption, action: option.action)
}
}
}
}
// MARK: - Subviews
private func sectionTitle(_ text: String) -> some View {
@@ -129,6 +204,36 @@ 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 {
Button("All Types") { filter = nil }
Divider()
ForEach(PedalCategory.allCases) { category in
Button(category.rawValue) { filter = category }
}
} label: {
HStack(spacing: 3) {
Image(systemName: "line.3.horizontal.decrease.circle")
Text(filter?.rawValue ?? "All").lineLimit(1)
}
.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
/// be dropped onto a stereo/parallel lane.
private func pedalRow(_ name: String) -> some View {
@@ -158,13 +263,25 @@ public struct PedalPaletteView: View {
}
.padding(.horizontal, PedalPaletteView.cardPaddingH)
.padding(.vertical, PedalPaletteView.cardPaddingV)
.frame(maxWidth: .infinity, alignment: .leading)
.background(cardBackground(brightness: PedalPaletteView.pedalCardBrightness))
.modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth))
.background(categoryCardBackground(PedalCategory.category(for: name).color))
}
.buttonStyle(.plain)
.draggable("add:\(name)")
}
/// Category-tinted card background — a low-opacity fill plus a stronger border in the category
/// colour, so palette blocks are colour-coded by type.
private func categoryCardBackground(_ color: Color) -> some View {
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
.fill(color.opacity(PedalPaletteView.categoryFillOpacity))
.overlay(
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
.stroke(color.opacity(PedalPaletteView.categoryBorderOpacity),
lineWidth: PedalPaletteView.cardBorderWidth)
)
}
/// A tappable routing row that inserts a region/node into the board.
private func routingCard(title: String, caption: String, action: RoutingAction) -> some View {
Button {
@@ -180,12 +297,27 @@ public struct PedalPaletteView: View {
}
.padding(.horizontal, PedalPaletteView.cardPaddingH)
.padding(.vertical, PedalPaletteView.cardPaddingV)
.frame(maxWidth: .infinity, alignment: .leading)
.modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth))
.background(cardBackground(brightness: PedalPaletteView.routingCardBrightness))
}
.buttonStyle(.plain)
}
/// Stretches a card to fill width in a vertical column, or pins it to a fixed width in a
/// horizontal row.
private struct CardFrame: ViewModifier {
let axis: Axis
let width: CGFloat
func body(content: Content) -> some View {
switch axis {
case .horizontal:
content.frame(width: width, alignment: .leading)
default:
content.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
private func cardBackground(brightness: Double) -> some View {
RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius)
.fill(Color(white: brightness))
@@ -0,0 +1,126 @@
// PedalSelectorKnobView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// Renders a ``PedalSelectorKnob`` — a rotary knob that snaps to a fixed set of labelled stops.
///
/// Visually matches `ParameterKnob` (same dial + indicator), but drag quantises to discrete
/// positions and the caption shows the current stop's title rather than a numeric value. Drag up to
/// advance clockwise through the stops, down to go back.
struct PedalSelectorKnobView: View {
// MARK: - Layout constants
private static let dialSize: CGFloat = 50
private static let indicatorWidth: CGFloat = 2
private static let indicatorHeight: CGFloat = 14
private static let indicatorInset: CGFloat = 3
private static let startAngle: Double = -135.0
private static let totalArc: Double = 270.0
/// Pixels of vertical drag per stop step.
private static let pixelsPerStep: CGFloat = 22
private static let labelSpacing: CGFloat = 4
// MARK: - Input
private let selector: PedalSelectorKnob
// MARK: - Drag state
@State private var dragStartIndex: Int = 0
@State private var dragInProgress: Bool = false
// MARK: - Init
init(_ selector: PedalSelectorKnob) {
self.selector = selector
}
// MARK: - Body
var body: some View {
VStack(spacing: PedalSelectorKnobView.labelSpacing) {
dial
.frame(width: PedalSelectorKnobView.dialSize, height: PedalSelectorKnobView.dialSize)
.gesture(dragGesture)
Text(selector.label)
.font(.caption)
.foregroundStyle(Color.white)
Text(currentStop.title)
.font(.caption)
.foregroundStyle(Color.white)
}
}
// MARK: - Dial
private var dial: some View {
let count: Int = selector.stops.count
let normalised: Double = count > 1 ? Double(currentIndex) / Double(count - 1) : 0
let rotation: Double = PedalSelectorKnobView.startAngle + normalised * PedalSelectorKnobView.totalArc
let offset: CGFloat = -(PedalSelectorKnobView.dialSize / 2
- PedalSelectorKnobView.indicatorHeight / 2
- PedalSelectorKnobView.indicatorInset)
return ZStack {
Circle()
.fill(Color.lyrebirdControlBackground)
.overlay(Circle().stroke(Color.lyrebirdSeparator, lineWidth: 1))
Rectangle()
.fill(Color.accentColor)
.frame(
width: PedalSelectorKnobView.indicatorWidth,
height: PedalSelectorKnobView.indicatorHeight
)
.offset(y: offset)
.rotationEffect(.degrees(rotation))
}
}
// MARK: - Drag
private var dragGesture: some Gesture {
DragGesture(minimumDistance: 1)
.onChanged { gesture in
if !dragInProgress {
dragInProgress = true
dragStartIndex = currentIndex
}
let delta: CGFloat = gesture.translation.height // down = positive
// Up should advance (increase index), so subtract the downward delta.
let steps: Int = Int((-delta / PedalSelectorKnobView.pixelsPerStep).rounded())
let target: Int = min(max(dragStartIndex + steps, 0), selector.stops.count - 1)
let value: Double = selector.stops[target].value
if value != selector.node.value {
selector.node.update(value)
}
}
.onEnded { _ in dragInProgress = false }
}
// MARK: - Helpers
/// Index of the stop whose value is nearest the node's current value.
private var currentIndex: Int {
let value: Double = selector.node.value
var bestIndex: Int = 0
var bestDistance: Double = .greatestFiniteMagnitude
for (index, stop) in selector.stops.enumerated() {
let distance: Double = abs(stop.value - value)
if distance < bestDistance {
bestDistance = distance
bestIndex = index
}
}
return bestIndex
}
private var currentStop: PedalSelectorKnob.Stop {
selector.stops[currentIndex]
}
}
@@ -17,8 +17,13 @@ import LyrebirdShoeGaze
private func enclosureColor(for displayName: String) -> Color {
switch displayName {
case "Overdrive": return Color(red: 0.85, green: 0.42, blue: 0.08) // warm orange
case "Distortion": return Color(red: 0.80, green: 0.26, blue: 0.12) // hot rust
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
@@ -26,15 +31,25 @@ 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
case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red
case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal
case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal
case "Chorus": return Color(red: 0.16, green: 0.50, blue: 0.64) // aqua
case "Flanger": return Color(red: 0.28, green: 0.52, blue: 0.78) // steel blue
case "Vibrato": return Color(red: 0.42, green: 0.30, blue: 0.70) // violet-blue
case "Rotary": return Color(red: 0.45, green: 0.34, blue: 0.20) // Leslie cabinet walnut
case "Sustainer": return Color(red: 0.22, green: 0.46, blue: 0.30) // pine green
case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber
case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle
case "Harmonizer": return Color(red: 0.52, green: 0.20, blue: 0.40) // wine / mauve
case "Bitcrusher": return Color(red: 0.30, green: 0.34, blue: 0.40) // slate / digital gray
case "Granulator": return Color(red: 0.20, green: 0.55, blue: 0.50) // sea green
case "Auto Granulator": return Color(red: 0.24, green: 0.50, blue: 0.56) // teal-aqua
default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray
}
}
@@ -277,6 +292,7 @@ public struct PedalView: View {
VStack(spacing: PedalView.sectionSpacing) {
namePlate
knobGrid
selectorRow
switchRow
sliderBank(sliders)
Spacer(minLength: 0)
@@ -371,6 +387,22 @@ public struct PedalView: View {
}
}
/// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid.
/// Renders nothing when the pedal publishes no selectors.
@ViewBuilder
private var selectorRow: some View {
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
if !selectors.isEmpty {
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(selectors.enumerated()), id: \.offset) { pair in
PedalSelectorKnobView(pair.element)
}
Spacer(minLength: 0)
}
}
}
/// Row of segmented switches drawn from `pedal.effectSwitches`, one per row, beneath
/// the knob grid. Renders nothing when the pedal publishes no switches.
@ViewBuilder
@@ -7,15 +7,18 @@
import SwiftUI
import UniformTypeIdentifiers
/// A minimal JSON `FileDocument` wrapping a ShoeGaze rig's encoded bytes.
/// A minimal `FileDocument` wrapping a ShoeGaze document's encoded bytes.
///
/// Used by ``ShoeGazeBuilderView``'s iOS `.fileExporter` to write the result of
/// `ShoeGaze.rigData()` to a user-chosen location. macOS uses an `NSSavePanel` directly and does
/// not need this type.
/// Used by ``ShoeGazeBuilderView``'s `.fileExporter` to write the result of
/// `RigLibraryStore.exportDocumentData()` (a `.shoegaze` ``ShoeGazeDocument``) to a user-chosen
/// location.
struct RigFileDocument: FileDocument {
/// The rig presets are plain JSON.
static var readableContentTypes: [UTType] { [.json] }
/// Writes the `.shoegaze` document type.
static var writableContentTypes: [UTType] { [.shoeGaze] }
/// Reads `.shoegaze` documents and the legacy plain-JSON exports.
static var readableContentTypes: [UTType] { [.shoeGaze, .json] }
/// Encoded rig JSON.
let data: Data
@@ -0,0 +1,53 @@
// RigLibraryBootstrap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdShoeGaze
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
///
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work —
/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the
/// library from the current working rig **only after** the real (possibly iCloud) contents are
/// known, so a first launch can't create a duplicate "Default" rig on every synced device.
@MainActor
public enum RigLibraryBootstrap {
/// Creates an auto-resolving store. Construct this synchronously at launch; call
/// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
public static func makeStore() -> RigLibraryStore {
RigLibraryStore()
}
/// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still
/// empty after loading (first run). Idempotent enough to call once at launch.
///
/// - Parameters:
/// - store: The store from ``makeStore()``.
/// - shoeGaze: The session whose current rig seeds the library when it is first empty.
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`.
public static func start(
_ store: RigLibraryStore,
seedFrom shoeGaze: ShoeGaze,
seedName: String = "Default"
) async {
await store.start()
// Seed only after the (possibly iCloud) library has loaded: an empty library here means a
// genuine first run, not a not-yet-synced one.
guard store.entries.isEmpty, !shoeGaze.boards.isEmpty else { return }
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
do {
try store.save(entry)
// 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)")
}
}
}
@@ -0,0 +1,19 @@
// RigLibraryCommands.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Notifications the macOS app shell posts from its menu bar so the in-window
/// ``ShoeGazeBuilderView`` — which owns the current-rig state — performs the action with the
/// correct UI (naming prompts, highlight updates). iOS has no menu bar and simply never posts them.
public extension Notification.Name {
/// Save the current rig to the library (overwrites the loaded entry, or prompts for a name).
static let shoeGazeSaveRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.saveRig")
/// Create a new, named, empty rig and make it current.
static let shoeGazeNewRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.newRig")
}
@@ -0,0 +1,199 @@
// RigLibrarySidebarView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// The rig library: a persistent left-hand listing of every saved rig, with controls to start a
/// new rig, save / save-as, duplicate, rename, delete, erase all, and import / export an archive.
///
/// Selecting a rig replaces the current working session (the host stops the engine, rebuilds the
/// graph, and restarts). This view is purely presentational — every action is delegated to the
/// host (`ShoeGazeBuilderView`) via closures so engine lifecycle and naming prompts stay in one
/// place.
struct RigLibrarySidebarView: View {
// MARK: - Layout constants
private static let width: CGFloat = 200
private static let rowSpacing: CGFloat = 4
private static let rowPadding: CGFloat = 8
private static let rowCorner: CGFloat = 6
private static let selectedOpacity: Double = 0.22
private static let subtitleOpacity: Double = 0.5
private static let headerOpacity: Double = 0.65
private static let emptyOpacity: Double = 0.4
// MARK: - Inputs
let store: RigLibraryStore
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig.
@Binding var currentRigID: UUID?
let onSelect: (RigEntry) -> Void
let onNew: () -> Void
let onSave: () -> Void
let onSaveAs: () -> Void
let onDuplicate: (RigEntry) -> Void
let onRename: (RigEntry) -> Void
let onDelete: (RigEntry) -> Void
let onEraseAll: () -> Void
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)
// MARK: - Body
var body: some View {
VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
header
Divider().overlay(Color.white.opacity(0.12))
rigList
Divider().overlay(Color.white.opacity(0.12))
actionBar
}
.frame(width: RigLibrarySidebarView.width)
}
// MARK: - Header
private var header: some View {
HStack(spacing: 6) {
Text("Rigs")
.font(.headline)
.foregroundStyle(Color.white)
Spacer()
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("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")
}
}
// MARK: - List
private var rigList: some View {
ScrollView(.vertical, showsIndicators: true) {
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
if !store.isLoaded {
HStack(spacing: 6) {
ProgressView().controlSize(.small)
Text("Loading…")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
}
.padding(.vertical, RigLibrarySidebarView.rowPadding)
} else if store.entries.isEmpty {
Text("No saved rigs yet.\nTap New or Save to add one.")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
.padding(.vertical, RigLibrarySidebarView.rowPadding)
}
ForEach(store.entries) { entry in
rigRow(entry)
}
}
}
.frame(maxHeight: .infinity)
}
private func rigRow(_ entry: RigEntry) -> some View {
let isSelected: Bool = entry.id == currentRigID
return Button {
onSelect(entry)
} label: {
VStack(alignment: .leading, spacing: 2) {
Text(entry.name)
.font(.subheadline)
.foregroundStyle(Color.white)
.lineLimit(1)
Text(entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat))
.font(.caption2)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity))
.lineLimit(1)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(RigLibrarySidebarView.rowPadding)
.background(
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 {
Button("Rename…") { onRename(entry) }
Button("Duplicate…") { onDuplicate(entry) }
// Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the
// unreachable failure path the Share item is simply omitted.
if let shareItem: RigShareItem = try? RigShareItem(rig: entry) {
ShareLink(
item: shareItem,
preview: SharePreview(entry.name)
) {
Label("Share…", systemImage: "square.and.arrow.up")
}
}
Divider()
Button("Delete", role: .destructive) { onDelete(entry) }
}
}
// MARK: - Action bar
private var actionBar: some View {
HStack(spacing: 6) {
Button { onNew() } label: { Image(systemName: "plus") }
.help("New rig")
Button { onSave() } label: { Image(systemName: "square.and.arrow.down") }
.help("Save the current rig")
Button { onSaveAs() } label: { Image(systemName: "doc.on.doc") }
.help("Save the current rig as a new entry")
Spacer()
Menu {
Button("Import Archive…") { onImportArchive() }
Button("Export Archive…") { onExportArchive() }
Divider()
Button("Erase All Rigs…", role: .destructive) { onEraseAll() }
} label: {
Image(systemName: "ellipsis.circle")
}
#if os(macOS)
.menuStyle(.borderlessButton)
.fixedSize()
#endif
.help("Archive and library options")
}
.buttonStyle(.bordered)
.tint(.orange)
.padding(.top, 2)
}
}
@@ -0,0 +1,71 @@
// RigNamePrompt.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
/// A request to prompt the user for a rig name (New, Save As, Rename, Duplicate).
///
/// Presented via the ``SwiftUI/View/rigNamePrompt(_:)`` modifier. Setting a non-`nil` value shows a
/// text-entry alert seeded with `initialText`; committing a non-empty, trimmed name invokes
/// `onCommit`. Cancelling dismisses without calling `onCommit`.
struct RigNamePrompt: Identifiable {
let id: UUID = UUID()
/// Alert title, e.g. `"Save Rig As"`.
let title: String
/// Text the field is pre-filled with (e.g. the existing name for a rename).
let initialText: String
/// Confirm-button label, e.g. `"Save"` or `"Rename"`.
let confirmLabel: String
/// Invoked with the trimmed, non-empty name when the user confirms.
let onCommit: (String) -> Void
}
private struct RigNamePromptModifier: ViewModifier {
@Binding var prompt: RigNamePrompt?
@State private var text: String = ""
func body(content: Content) -> some View {
content
.onChange(of: prompt?.id) {
// Seed the field whenever a new prompt is presented.
text = prompt?.initialText ?? ""
}
.alert(
prompt?.title ?? "",
isPresented: isPresented,
presenting: prompt
) { active in
TextField("Name", text: $text)
Button(active.confirmLabel) {
let trimmed: String = text.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmed.isEmpty { active.onCommit(trimmed) }
}
Button("Cancel", role: .cancel) { }
}
}
private var isPresented: Binding<Bool> {
Binding(
get: { prompt != nil },
set: { presented in if !presented { prompt = nil } }
)
}
}
extension View {
/// Presents a rig-name entry alert driven by `prompt`. Set the binding to a ``RigNamePrompt``
/// to show it; it clears itself on dismiss.
func rigNamePrompt(_ prompt: Binding<RigNamePrompt?>) -> some View {
modifier(RigNamePromptModifier(prompt: prompt))
}
}
@@ -0,0 +1,74 @@
// RigShareItem.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import CoreTransferable
import UniformTypeIdentifiers
import LyrebirdShoeGaze
/// A `Transferable` wrapper that lets a `ShareLink` send a single rig as a `.shoegaze` document.
///
/// Holds the already-encoded document bytes (a value type, so the wrapper is `Sendable` as
/// `Transferable` requires). The encode happens when the share menu is built for the focused row —
/// cheap, one rig — via the throwing ``init(rig:)``.
///
/// Uses `FileRepresentation` (not `DataRepresentation`): the share sheet — AirDrop, Messages,
/// Mail, Notes, Files — only offers its full service list when handed a real file on disk. The
/// bytes are written to a temporary `<rig>.shoegaze` when a destination is picked. Sharing raw
/// data instead collapses the macOS menu to just Copy / Edit Extensions.
struct RigShareItem: Transferable, Sendable {
/// Filesystem-safe base name for the shared file (no extension).
let filenameBase: String
/// Encoded `.shoegaze` document bytes.
let data: Data
/// Encodes `entry` as a single-rig `.shoegaze` document.
///
/// - Parameter entry: The library entry to share.
/// - Throws: Any `JSONEncoder` error from ``ShoeGazeDocument/data()``.
init(rig entry: RigEntry) throws {
self.filenameBase = shareFilenameBase(entry.name)
self.data = try ShoeGazeDocument(rig: entry).data()
}
static var transferRepresentation: some TransferRepresentation {
FileRepresentation(exportedContentType: .shoeGaze) { item in
SentTransferredFile(try writeShoeGazeShareFile(item.data, base: item.filenameBase))
}
.suggestedFileName { item in
"\(item.filenameBase).\(ShoeGazeDocument.fileExtension)"
}
}
}
/// Reduces a user-supplied name to a filesystem-safe base for a shared file, mirroring the preset
/// stores' sanitisation at the UI boundary (the core sanitiser is module-internal to
/// `LyrebirdShoeGaze`). Path separators and whitespace become underscores; an empty result falls
/// back to a generic name. Shared by ``RigShareItem`` and ``BoardShareItem``.
func shareFilenameBase(_ name: String) -> String {
let forbidden: Set<Character> = ["/", "\\", ":", "\0"]
let mapped: String = String(name.map { character -> Character in
(character.isWhitespace || forbidden.contains(character)) ? "_" : character
})
let trimmed: String = mapped.trimmingCharacters(in: CharacterSet(charactersIn: "_"))
return trimmed.isEmpty ? "ShoeGaze" : trimmed
}
/// Writes `data` to a uniquely-named temporary `<base>.shoegaze` file and returns its URL, for a
/// `FileRepresentation` to hand the share sheet a real file. A fresh per-share subdirectory avoids
/// collisions when the same name is shared twice. Shared by ``RigShareItem`` and ``BoardShareItem``.
func writeShoeGazeShareFile(_ data: Data, base: String) throws -> URL {
let directory: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("ShoeGazeShare-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let url: URL = directory
.appendingPathComponent(base)
.appendingPathExtension(ShoeGazeDocument.fileExtension)
try data.write(to: url, options: .atomic)
return url
}
@@ -7,6 +7,9 @@
#if canImport(AppKit)
import AppKit
#endif
#if canImport(UIKit)
import UIKit
#endif
import SwiftUI
import UniformTypeIdentifiers
import LyrebirdSynth
@@ -43,6 +46,9 @@ public struct ShoeGazeBuilderView: View {
private static let minWidth: CGFloat = 720
private static let minHeight: CGFloat = 460
private static let sidebarWidth: CGFloat = 168
/// Width of the scope/CPU block in the bottom strip — matches `BoardBarView`'s Solo/Blend/All
/// control column so the scope aligns under it.
private static let scopeWidth: CGFloat = 188
private static let columnSpacing: CGFloat = 14
private static let backgroundRed: Double = 0.08
private static let backgroundGreen: Double = 0.07
@@ -54,15 +60,23 @@ public struct ShoeGazeBuilderView: View {
private static let maxCrossfadeSeconds: Double = 10.0
/// Highest board reachable via a ⌘-number switch shortcut.
private static let maxBoardShortcuts: Int = 9
private static let defaultRigFileName: String = "ShoeGazeRig"
/// Default filename offered when exporting the whole library as an archive.
private static let defaultArchiveFileName: String = "ShoeGaze Library"
/// Extra width reserved for the rig-library sidebar on top of the builder's minimum width.
private static let librarySidebarReserve: CGFloat = 216
private static let recordDotSize: CGFloat = 9
private static let folderLabelOpacity: Double = 0.55
// MARK: - Properties
private let shoeGaze: ShoeGaze
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
@@ -81,24 +95,69 @@ 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
/// Presentation flag for the board-manager sheet (rename / reorder / delete).
@State private var showBoardsSheet: Bool = false
/// Confirmation dialog for the Clear action, and a flag to clear once a chosen save completes.
/// Confirmation dialog for the Clear action.
@State private var showClearDialog: Bool = false
@State private var pendingClearAfterSave: Bool = false
/// Rig-save export state. Cross-platform: the in-view exporter backs both the Save action and
/// the "Save & Clear" flow on macOS and iOS (macOS additionally has a File-menu Save).
/// 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.
///
/// 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?
/// Confirmation dialog for the "Erase All Rigs" library action.
@State private var showEraseAllDialog: Bool = false
/// Save-before-switch prompt: the rig the user asked to switch to while the current rig has
/// unsaved changes, and the flag presenting the dialog.
@State private var pendingSwitchEntry: RigEntry?
@State private var showSwitchSaveDialog: Bool = false
/// A failed edit (add pedal / routing / board) to surface as an alert. `nil` = no alert.
@State private var actionError: ActionError?
/// A user-facing failure message for the action-error alert.
private struct ActionError: Identifiable {
let id: UUID = UUID()
let title: String
let message: String
}
/// Archive export state. Cross-platform: backs the sidebar's Export Archive and the
/// "Save & Clear" flow is separate (it saves to the library, not a file).
@State private var showExporter: Bool = false
@State private var exportDocument: RigFileDocument = RigFileDocument(data: Data())
#if !os(macOS)
/// iOS file-dialog presentation flags. (macOS uses the File menu for load + recording folder.)
/// 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
#endif
@@ -117,47 +176,38 @@ public struct ShoeGazeBuilderView: View {
/// engine with one input channel (preserving the rig), and select live input. Defaults to
/// `nil` — on macOS the engine already has an input channel, so live input is selected
/// directly without a rebuild.
/// - 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
public var body: some View {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
transportRow
ioRow
#if !os(macOS)
recordingRow
#endif
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
rigSidebar
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
BoardBarView(
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
paletteSidebar
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
// Scope + CPU meters sit under the pedal palette, matching its width.
ShoeGazeScopeView(shoeGaze: shoeGaze)
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
LyrebirdStatusView(engine: shoeGaze.engine)
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
builderColumn
}
.padding(ShoeGazeBuilderView.outerPadding)
.frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight)
.frame(
minWidth: ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve,
minHeight: ShoeGazeBuilderView.minHeight
)
.background(
Color(
red: ShoeGazeBuilderView.backgroundRed,
@@ -165,28 +215,72 @@ public struct ShoeGazeBuilderView: View {
blue: ShoeGazeBuilderView.backgroundBlue
)
)
// The builder is always dark-themed; force the dark scheme so system controls (nav title,
// steppers, the Record button) use light text instead of black-on-dark in light mode.
.preferredColorScheme(.dark)
.background(boardSwitchShortcuts)
.onAppear { restoreInputSelection() }
// Each presentation (sheet / importers / exporter / alert) lives on its own anchor
// node. SwiftUI reliably drives only one presentation per view node, so stacking them
// all on the root view silently swallowed some (e.g. the iOS Load file importer).
.onAppear {
restoreInputSelection()
syncIdleTimer()
maybeWarnICloudUnavailable()
}
.onDisappear { releaseIdleTimer() }
.onChange(of: transportTick) { syncIdleTimer() }
.onChange(of: library.isLoaded) {
maybeWarnICloudUnavailable()
}
.background(boardsSheetAnchor)
.background(rigExportAnchor)
.background(rigImportAnchor)
.background(actionErrorAnchor)
.rigNamePrompt($namePrompt)
.confirmationDialog(
"Erase all rigs?",
isPresented: $showEraseAllDialog,
titleVisibility: .visible
) {
Button("Erase All Rigs", role: .destructive) { eraseAllRigs() }
Button("Cancel", role: .cancel) { }
} message: {
Text("This permanently removes every saved rig from the library"
+ (library.isICloud ? " on all your devices." : "."))
}
.confirmationDialog(
"Save changes to the current rig?",
isPresented: $showSwitchSaveDialog,
titleVisibility: .visible,
presenting: pendingSwitchEntry
) { target in
Button("Save") {
pendingSwitchEntry = nil
saveCurrentRig(then: { loadEntry(target) })
}
Button("Don't Save", role: .destructive) {
pendingSwitchEntry = nil
loadEntry(target)
}
Button("Cancel", role: .cancel) { pendingSwitchEntry = nil }
} message: { target in
Text("Switching to \"\(target.name)\" will discard unsaved changes to the current rig.")
}
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeSaveRig)) { _ in
saveCurrentRig()
}
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeNewRig)) { _ in
promptNewRig()
}
.confirmationDialog(
"Clear all boards?",
isPresented: $showClearDialog,
titleVisibility: .visible
) {
Button("Save & Clear") {
pendingClearAfterSave = true
saveAction()
saveCurrentRig(then: { performClear() })
}
Button("Clear Without Saving", role: .destructive) {
performClear()
}
Button("Cancel", role: .cancel) {
pendingClearAfterSave = false
}
Button("Cancel", role: .cancel) { }
} message: {
Text("This removes every pedal and board. Save your current setup first?")
}
@@ -196,10 +290,152 @@ 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(rigImportAnchor)
.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/
/// delete/erase and archive import/export. Selecting a rig replaces the current session.
private var rigSidebar: some View {
RigLibrarySidebarView(
store: library,
currentRigID: Binding(get: { shoeGaze.currentRigID }, set: { shoeGaze.currentRigID = $0 }),
onSelect: { entry in requestLoad(entry) },
onNew: { promptNewRig() },
onSave: { saveCurrentRig() },
onSaveAs: { promptSaveAs() },
onDuplicate: { entry in promptDuplicate(entry) },
onRename: { entry in promptRename(entry) },
onDelete: { entry in deleteEntry(entry) },
onEraseAll: { showEraseAllDialog = true },
onImportArchive: { showImporter = true },
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 {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
transportRow
ioRow
#if !os(macOS)
recordingRow
#endif
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
topSection
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
/// Top section: the scope + CPU meters on the left (sized to align with the mixer's
/// Solo/Blend/All control column), and a right column stacking the board mixer over the
/// horizontal pedal picker.
private var topSection: some View {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
ShoeGazeScopeView(shoeGaze: shoeGaze)
LyrebirdStatusView(engine: shoeGaze.engine)
}
.frame(width: ShoeGazeBuilderView.scopeWidth, alignment: .leading)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
BoardBarView(
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
pedalPickerRow
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.fixedSize(horizontal: false, vertical: true)
}
/// A compact horizontal pedal-picker strip (sits below the board mixer in the top section).
private var pedalPickerRow: some View {
ScrollView(.horizontal, showsIndicators: true) {
PedalPaletteView(
axis: .horizontal,
onAdd: { type in addPedal(type: type) },
onRouting: { action in performRouting(action) }
)
.padding(.bottom, 2)
}
.fixedSize(horizontal: false, vertical: true)
}
// MARK: - Presentation anchors
@@ -219,37 +455,70 @@ public struct ShoeGazeBuilderView: View {
}
}
/// Hosts the rig-save (`.json`) exporter on its own node. Cross-platform: backs both the
/// Save action and the "Save & Clear" flow. On a successful save during "Save & Clear", the
/// pending clear runs; cancelling the save leaves the boards untouched.
/// Hosts the library-export (`.shoegaze`) exporter on its own node. Writes the whole library as
/// one ``ShoeGazeDocument`` file for backup or transfer.
private var rigExportAnchor: some View {
Color.clear
.fileExporter(
isPresented: $showExporter,
document: exportDocument,
contentType: .json,
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
contentType: .shoeGaze,
defaultFilename: ShoeGazeBuilderView.defaultArchiveFileName
) { result in
switch result {
case .failure(let error):
print("[ShoeGazeBuilderView] export failed: \(error)")
pendingClearAfterSave = false
case .success:
if pendingClearAfterSave { performClear() }
pendingClearAfterSave = false
if case .failure(let error) = result {
print("[ShoeGazeBuilderView] library export failed: \(error)")
}
}
}
#if !os(macOS)
/// Hosts the rig-load (`.json`) importer on its own node.
/// Hosts the library-import (`.shoegaze`) importer on its own node (cross-platform). Accepts a
/// ``ShoeGazeDocument`` or a legacy archive / single-rig file; imported rigs are added to the
/// library.
private var rigImportAnchor: some View {
Color.clear
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in
handleImport(result)
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.shoeGaze, .json]) { result in
handleArchiveImport(result)
}
}
/// Hosts the action-failure alert on its own node (one presentation per node).
private var actionErrorAnchor: some View {
Color.clear
.alert(
actionError?.title ?? "",
isPresented: Binding(
get: { actionError != nil },
set: { presented in if !presented { actionError = nil } }
),
presenting: actionError
) { _ in
Button("OK", role: .cancel) { }
} message: { error in
Text(error.message)
}
}
/// Surfaces a failed edit as an alert (and logs it). Maps the common stereo-width / merge errors
/// to player-facing wording (no API names); otherwise uses the error's `LocalizedError` text.
private func reportError(_ title: String, _ error: Error) {
actionError = ActionError(title: title, message: friendlyMessage(for: error))
}
private func friendlyMessage(for error: Error) -> String {
switch error as? ShoeGazeError {
case .stereoWidthExceeded, .cannotSplitStereoChain:
return "This board is already in stereo. Add a “Merge to Mono” before another stereo "
+ "(widening) pedal such as Chorus, Rotary, or a Granulator."
case .cannotMergeMonoChain:
return "This board is already mono — there’s no stereo signal to merge."
case .cannotUnzipMonoChain:
return "This board is mono — there’s no stereo signal to split into left/right lanes."
default:
return (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
}
}
#if !os(macOS)
/// Hosts the recording-folder importer on its own node.
private var recordingFolderImportAnchor: some View {
Color.clear
@@ -280,6 +549,11 @@ public struct ShoeGazeBuilderView: View {
}
}
Spacer()
if let midi: MIDIController = midi {
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
}
helpButton
rigBypassButton
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
@@ -288,6 +562,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 {
@@ -316,35 +618,12 @@ public struct ShoeGazeBuilderView: View {
Button("Clear") { showClearDialog = true }
.buttonStyle(.bordered).tint(.red)
.help("Remove all boards (with the option to save first)")
.help("Remove all boards in the current rig (with the option to save first)")
Spacer()
// On macOS, Load lives in the app's File menu (see the app shell's AppDelegate); on
// iOS it stays in-view via fileImporter. Save is in-view on both (cross-platform
// exporter) so the "Save & Clear" flow works everywhere.
Button("Save…") { saveAction() }
.buttonStyle(.bordered).tint(.blue)
#if !os(macOS)
Button("Load…") { loadAction() }
.buttonStyle(.bordered).tint(.blue)
#endif
}
}
// MARK: - Palette sidebar
private var paletteSidebar: some View {
ScrollView(.vertical, showsIndicators: true) {
PedalPaletteView(
onAdd: { type in addPedal(type: type) },
onRouting: { action in performRouting(action) }
)
.padding(.trailing, 2)
}
.frame(width: ShoeGazeBuilderView.sidebarWidth)
}
// MARK: - Board area
private var boardArea: some View {
@@ -370,6 +649,7 @@ public struct ShoeGazeBuilderView: View {
}
} catch {
print("[ShoeGazeBuilderView] routing \(action) failed: \(error)")
reportError("Couldn’t add routing", error)
}
}
@@ -414,6 +694,7 @@ public struct ShoeGazeBuilderView: View {
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
reportError("Couldn’t add \(type)", error)
}
}
@@ -428,12 +709,15 @@ public struct ShoeGazeBuilderView: View {
} catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilderView] addBoard failed: \(error)")
reportError("Couldn’t add board", error)
}
}
/// Persists the current rig to the autosave file. Called after structural edits so state
/// survives a restart even without an explicit Save; the app shells also save on background.
private func autosave() {
// 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)
}
@@ -559,11 +843,9 @@ public struct ShoeGazeBuilderView: View {
shoeGaze.soloBoard(shoeGaze.boards[index], crossfadeSeconds: seconds)
}
// MARK: - Save / Load (iOS)
// MARK: - Recording (iOS)
// Save is in-view on both platforms (cross-platform fileExporter) so "Save & Clear" works
// everywhere. Load is the macOS File menu / iOS fileImporter; recording controls are iOS
// in-view (macOS uses the Record menu).
// Recording controls are iOS in-view (macOS uses the Record menu).
#if !os(macOS)
/// iOS recording controls: choose an output folder, then start/stop recording.
private var recordingRow: some View {
@@ -610,47 +892,216 @@ public struct ShoeGazeBuilderView: View {
}
#endif
/// Presents the cross-platform rig-save exporter (also used by the "Save & Clear" flow).
private func saveAction() {
do {
exportDocument = RigFileDocument(data: try shoeGaze.rigData())
showExporter = true
} catch {
print("[ShoeGazeBuilderView] rigData failed: \(error)")
}
}
// MARK: - Rig library
#if !os(macOS)
private func loadAction() {
showImporter = true
}
/// Loads a rig from a URL, stopping/restarting the engine around the rebuild and resetting the
/// board selection to a valid index (load replaces all boards).
private func loadRig(from url: URL) {
/// 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) {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
do {
try shoeGaze.loadRig(from: url)
try shoeGaze.loadRig(from: entry.state)
currentRigID = entry.id
selectedBoardIndex = 0
autosave()
} catch {
print("[ShoeGazeBuilderView] loadRig failed: \(error)")
print("[ShoeGazeBuilderView] loadEntry failed: \(error)")
}
if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle()
}
private func handleImport(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
// A `.fileImporter` URL is security-scoped on iOS; access must be started to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
loadRig(from: url)
case .failure(let error):
print("[ShoeGazeBuilderView] import failed: \(error)")
/// Switches to `entry`, prompting to save first when the current rig has unsaved changes.
/// No-op when `entry` is already the current rig.
private func requestLoad(_ entry: RigEntry) {
guard entry.id != currentRigID else { return }
if isCurrentRigDirty() {
pendingSwitchEntry = entry
showSwitchSaveDialog = true
} else {
loadEntry(entry)
}
}
#endif
/// Whether the working rig differs from the library entry it was loaded from. A working rig with
/// no backing entry counts as dirty when it has any boards.
private func isCurrentRigDirty() -> Bool {
guard let id: UUID = currentRigID,
let entry: RigEntry = library.entries.first(where: { $0.id == id }) else {
return !shoeGaze.boards.isEmpty
}
return shoeGaze.captureState() != entry.state
}
/// Saves the current session over the loaded library entry, or prompts for a name when no entry
/// is loaded (a new, never-saved rig).
///
/// - Parameter completion: Runs only after a successful save (e.g. clear the boards, or load the
/// rig the user was switching to). Cancelling the name prompt cancels it too — no save, no
/// follow-up.
private func saveCurrentRig(then completion: @escaping () -> Void = { }) {
guard let id: UUID = currentRigID,
let existing: RigEntry = library.entries.first(where: { $0.id == id }) else {
// No current entry — prompt for a name; the follow-up runs only on commit.
namePrompt = RigNamePrompt(
title: "Save Rig As",
initialText: currentRigName() ?? defaultNewRigName(),
confirmLabel: "Save"
) { name in
persist(shoeGaze.captureEntry(name: name), then: completion)
}
return
}
persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion)
}
/// Prompts for a name, then creates a brand-new empty rig (one empty board) and selects it.
private func promptNewRig() {
namePrompt = RigNamePrompt(
title: "New Rig",
initialText: defaultNewRigName(),
confirmLabel: "Create"
) { name in
createNewRig(named: name)
}
}
/// Prompts for a name and saves the current session as a new library entry (new id).
private func promptSaveAs() {
namePrompt = RigNamePrompt(
title: "Save Rig As",
initialText: currentRigName() ?? defaultNewRigName(),
confirmLabel: "Save"
) { name in
persist(shoeGaze.captureEntry(name: name))
}
}
/// Prompts for a name and duplicates `entry`, loading the copy as the current rig.
private func promptDuplicate(_ entry: RigEntry) {
namePrompt = RigNamePrompt(
title: "Duplicate Rig",
initialText: "\(entry.name) copy",
confirmLabel: "Duplicate"
) { name in
do {
let copy: RigEntry = try library.duplicate(entry, newName: name)
loadEntry(copy)
} catch {
print("[ShoeGazeBuilderView] duplicate failed: \(error)")
}
}
}
/// Prompts for a new name and renames `entry` in the library.
private func promptRename(_ entry: RigEntry) {
namePrompt = RigNamePrompt(
title: "Rename Rig",
initialText: entry.name,
confirmLabel: "Rename"
) { name in
do { _ = try library.rename(entry, to: name) }
catch { print("[ShoeGazeBuilderView] rename failed: \(error)") }
}
}
/// Deletes `entry` from the library. Clears the current-rig marker if it was the loaded rig.
private func deleteEntry(_ entry: RigEntry) {
do {
try library.delete(entry)
if currentRigID == entry.id { currentRigID = nil }
} catch {
print("[ShoeGazeBuilderView] delete failed: \(error)")
}
}
/// Erases the entire library and clears the current-rig marker.
private func eraseAllRigs() {
do {
try library.eraseAll()
currentRigID = nil
} catch {
print("[ShoeGazeBuilderView] eraseAll failed: \(error)")
}
}
/// Captures the whole library into the `.shoegaze` document exporter.
private func exportArchiveAction() {
do {
exportDocument = RigFileDocument(data: try library.exportDocumentData())
showExporter = true
} catch {
print("[ShoeGazeBuilderView] exportDocumentData failed: \(error)")
}
}
/// Imports an archive (or legacy single-rig file) into the library.
private func handleArchiveImport(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
// A `.fileImporter` URL is security-scoped; access must be started to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let data: Data = try Data(contentsOf: url)
_ = try library.importArchive(from: data)
} catch {
print("[ShoeGazeBuilderView] archive import failed: \(error)")
}
case .failure(let error):
print("[ShoeGazeBuilderView] archive import pick failed: \(error)")
}
}
/// Persists `entry`, marks it current, and runs `completion` (e.g. the "Save & Clear" clear).
private func persist(
_ entry: RigEntry,
then completion: () -> Void = { }
) {
do {
try library.save(entry)
currentRigID = entry.id
// Only run the follow-up (e.g. the "Save & Clear" clear) once the save succeeded —
// otherwise a failed save would still wipe the boards, losing the rig.
completion()
} catch {
print("[ShoeGazeBuilderView] save failed: \(error)")
}
}
/// Creates a fresh single-board rig, saves it under `name`, and makes it current.
private func createNewRig(named name: String) {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
// Replace the working graph with a single empty board.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeBuilderView] createNewRig seed failed: \(error)")
}
selectedBoardIndex = 0
if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle()
persist(shoeGaze.captureEntry(name: name))
}
/// The name of the currently loaded library entry, if any.
private func currentRigName() -> String? {
guard let id: UUID = currentRigID else { return nil }
return library.entries.first(where: { $0.id == id })?.name
}
/// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names.
private func defaultNewRigName() -> String {
let base: String = "Rig"
let existing: Set<String> = Set(library.entries.map(\.name))
var index: Int = library.entries.count + 1
while existing.contains("\(base) \(index)") { index += 1 }
return "\(base) \(index)"
}
}
@@ -0,0 +1,20 @@
// UTType+ShoeGaze.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import UniformTypeIdentifiers
public extension UTType {
/// The `.shoegaze` document type — a versioned JSON envelope carrying a shared rig or board.
///
/// Identifier `net.realizedsound.shoegaze`, conforming to `public.json` so the file stays
/// text-readable and is recognised by tools that understand JSON. The hosting app must also
/// declare this type in its `Info.plist` (`UTExportedTypeDeclarations` + `CFBundleDocumentTypes`)
/// for the system to associate the `.shoegaze` extension with the app and offer it in Share /
/// Open dialogs; this property mirrors that declaration so SwiftUI `fileExporter` / `fileImporter`
/// and `ShareLink` can reference it in code.
static let shoeGaze: UTType = UTType(exportedAs: "net.realizedsound.shoegaze", conformingTo: .json)
}
@@ -0,0 +1,91 @@
// AutoGranulatorPedalTests.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("AutoGranulatorPedal")
struct AutoGranulatorPedalTests {
private func render(
configure: (AutoGranulatorPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.2
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: AutoGranulatorPedal = AutoGranulatorPedal(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 { pedal in pedal.minGrain = 0.01; pedal.maxGrain = 0.03 }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "auto granulator output was silent")
}
@Test func responseSwitchChangesOutput() throws {
let loudShort: [Float] = try render { pedal in pedal.minGrain = 0.008; pedal.maxGrain = 0.02; pedal.response = 0.0; pedal.mix = 1.0 }
let loudLong: [Float] = try render { pedal in pedal.minGrain = 0.008; pedal.maxGrain = 0.02; pedal.response = 1.0; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(loudLong), "flipped-response granulator was silent")
#expect(totalSSD(loudShort, loudLong) > 0, "flipping the response did not change the output")
}
@Test func exposesKnobsAndResponseSwitch() throws {
let pedal: AutoGranulatorPedal = AutoGranulatorPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Min Grain", "Max Grain", "Overlap", "Spread"])
#expect(pedal.effectSwitches.map { $0.label } == ["Response"])
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Loud→Short", "Loud→Long"])
}
@Test func presetRoundTripPreservesResponse() throws {
let pedal: AutoGranulatorPedal = AutoGranulatorPedal()
pedal.response = 1.0
pedal.minGrain = 0.03
let state: PedalState = pedal.captureState()
let restored: AutoGranulatorPedal = AutoGranulatorPedal()
restored.applyState(state)
#expect(restored.response == 1.0)
#expect(restored.minGrain == 0.03)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Auto Granulator")
#expect(pedal is AutoGranulatorPedal)
}
}
@@ -0,0 +1,67 @@
// BitReduceTests.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("BitReduce")
struct BitReduceTests {
/// Minimal synth: a constant DC value through a `BitReduce`, written to a mono bus.
private final class CrushSynth: SynthesizerBase {
private let value: Double
private let bits: Double
private let outBus: Int
init(value: Double, bits: Double, outBus: Int) {
self.value = value
self.bits = bits
self.outBus = outBus
super.init()
}
override func build() {
output(bus: outBus, source: BitReduce(input: value, bits: bits))
}
}
private func render(value: Double, bits: Double) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: CrushSynth = CrushSynth(value: value, bits: bits, outBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url)
}
// Asserts are scale-independent: the test harness applies a fixed output gain/pan, so compare
// quantisation *levels* rather than absolute amplitudes.
@Test func snapsToDiscreteLevels() throws {
// 8 bits over [-1, 1]: step = 2/256, inverseStep = 128.
// 0.896 → round(114.688) = 115; 0.901 → round(115.328) = 115 (same level);
// 0.910 → round(116.48) = 116 (different level).
let sameA: [Float] = try render(value: 0.896, bits: 8.0)
let sameB: [Float] = try render(value: 0.901, bits: 8.0)
let other: [Float] = try render(value: 0.910, bits: 8.0)
#expect(sameA[200] == sameB[200], "values in the same 8-bit level should quantise identically")
#expect(sameA[200] != other[200], "values in different 8-bit levels should differ")
}
@Test func oneBitFloorsSmallValuesToZero() throws {
// 1 bit: levels = 2, step = 1.0; round(0.4) = 0 → exactly zero regardless of output gain.
let samples: [Float] = try render(value: 0.4, bits: 1.0)
#expect(abs(samples[200]) < 1e-5, "1-bit quantiser should floor 0.4 to 0")
}
}
@@ -0,0 +1,85 @@
// BitcrusherPedalTests.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("BitcrusherPedal")
struct BitcrusherPedalTests {
private func render(
configure: (BitcrusherPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.2
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
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: BitcrusherPedal = BitcrusherPedal(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), "bitcrusher output was silent")
}
@Test func crushChangesOutput() throws {
let light: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
let heavy: [Float] = try render { pedal in pedal.crush = 32.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(heavy), "decimated bitcrusher was silent")
#expect(totalSSD(light, heavy) > 0, "changing crush did not change the output")
}
@Test func bitsChangeOutput() throws {
let clean: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 16.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
let crushed: [Float] = try render { pedal in pedal.crush = 1.0; pedal.bits = 3.0; pedal.tone = 8000.0; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(crushed), "bit-reduced output was silent")
#expect(totalSSD(clean, crushed) > 0, "changing bit depth did not change the output")
}
@Test func exposesCrushBitsToneKnobs() throws {
let pedal: BitcrusherPedal = BitcrusherPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Crush", "Bits", "Tone"])
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Bitcrusher")
#expect(pedal is BitcrusherPedal)
}
}
@@ -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,91 @@
// DistortionPedalTests.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("DistortionPedal")
struct DistortionPedalTests {
private func render(
configure: (DistortionPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.2
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
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: DistortionPedal = DistortionPedal(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 windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
let skipSamples: Int = 2048
let windowSize: Int = 2048
guard a.count >= skipSamples + windowSize,
b.count >= skipSamples + windowSize else { return 0.0 }
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
return zip(aWindow, bWindow).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), "distortion output was silent")
}
@Test func driveChangesOutput() throws {
let low: [Float] = try render { pedal in pedal.drive = 2.0 }
let high: [Float] = try render { pedal in pedal.drive = 45.0 }
#expect(hasNonSilentOutput(high), "high-drive distortion was silent")
#expect(windowedSSD(low, high) > 0, "changing drive did not change the output")
}
@Test func toneChangesOutput() throws {
let dark: [Float] = try render { pedal in pedal.drive = 30.0; pedal.tone = 700.0 }
let bright: [Float] = try render { pedal in pedal.drive = 30.0; pedal.tone = 5500.0 }
#expect(hasNonSilentOutput(bright), "bright distortion was silent")
#expect(windowedSSD(dark, bright) > 0, "changing tone did not change the output")
}
@Test func exposesDriveToneKnobs() throws {
let pedal: DistortionPedal = DistortionPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Drive", "Tone"])
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Distortion")
#expect(pedal is DistortionPedal)
}
}
@@ -0,0 +1,91 @@
// FlangerPedalTests.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("FlangerPedal")
struct FlangerPedalTests {
private func render(
configure: (FlangerPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.2
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
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: FlangerPedal = FlangerPedal(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 windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
let skipSamples: Int = 2048
let windowSize: Int = 2048
guard a.count >= skipSamples + windowSize,
b.count >= skipSamples + windowSize else { return 0.0 }
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
return zip(aWindow, bWindow).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), "flanger output was silent")
}
@Test func depthChangesOutput() throws {
let shallow: [Float] = try render { pedal in pedal.depth = 0.1; pedal.mix = 1.0 }
let deep: [Float] = try render { pedal in pedal.depth = 0.95; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(deep), "deep flanger was silent")
#expect(windowedSSD(shallow, deep) > 0, "changing depth did not change the output")
}
@Test func feedbackChangesOutput() throws {
let dry: [Float] = try render { pedal in pedal.feedback = 0.0; pedal.mix = 1.0 }
let resonant: [Float] = try render { pedal in pedal.feedback = 0.85; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(resonant), "resonant flanger was silent")
#expect(windowedSSD(dry, resonant) > 0, "changing feedback did not change the output")
}
@Test func exposesRateDepthFeedbackKnobs() throws {
let pedal: FlangerPedal = FlangerPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Rate", "Depth", "Feedback"])
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Flanger")
#expect(pedal is FlangerPedal)
}
}
@@ -0,0 +1,83 @@
// GranulatorPedalTests.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("GranulatorPedal")
struct GranulatorPedalTests {
private func render(
configure: (GranulatorPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.2
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: GranulatorPedal = GranulatorPedal(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 { pedal in pedal.grain = 0.02 }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "granulator output was silent")
}
@Test func spreadChangesOutput() throws {
let mono: [Float] = try render { pedal in pedal.grain = 0.01; pedal.spread = 0.0; pedal.mix = 1.0 }
let wide: [Float] = try render { pedal in pedal.grain = 0.01; pedal.spread = 1.0; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(wide), "spread granulator was silent")
#expect(totalSSD(mono, wide) > 0, "changing spread did not change the channel output")
}
@Test func grainSizeChangesOutput() throws {
let small: [Float] = try render { pedal in pedal.grain = 0.01; pedal.mix = 1.0 }
let large: [Float] = try render { pedal in pedal.grain = 0.04; pedal.mix = 1.0 }
#expect(totalSSD(small, large) > 0, "changing grain size did not change the output")
}
@Test func exposesGrainOverlapSpreadKnobs() throws {
let pedal: GranulatorPedal = GranulatorPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Grain", "Overlap", "Spread"])
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Granulator")
#expect(pedal is GranulatorPedal)
}
}
@@ -0,0 +1,147 @@
// HarmonizerPedalTests.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("HarmonizerPedal")
struct HarmonizerPedalTests {
/// Renders the pedal through an NRT engine with the given configuration and returns the output.
private func render(
configure: (HarmonizerPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.3
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
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: HarmonizerPedal = HarmonizerPedal(
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)
}
/// Sum of squared differences over a stable window of two renders.
private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
let skipSamples: Int = 4096
let windowSize: Int = 2048
guard a.count >= skipSamples + windowSize,
b.count >= skipSamples + windowSize else { return 0.0 }
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
return zip(aWindow, bWindow).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 { pedal in
pedal.direct = 1.0
pedal.voice1Level = 0.6
pedal.voice2Level = 0.5
}
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "harmonizer output was silent")
}
@Test func changingVoiceIntervalChangesOutput() throws {
let third: [Float] = try render { pedal in
pedal.direct = 0.0
pedal.voice1Level = 1.0
pedal.voice2Level = 0.0
pedal.voice1 = 3.0 // minor third up
}
let fifth: [Float] = try render { pedal in
pedal.direct = 0.0
pedal.voice1Level = 1.0
pedal.voice2Level = 0.0
pedal.voice1 = 7.0 // perfect fifth up
}
#expect(hasNonSilentOutput(third), "minor-third voice was silent")
#expect(hasNonSilentOutput(fifth), "fifth voice was silent")
#expect(windowedSSD(third, fifth) > 0, "changing the interval did not change the output")
}
@Test func harmonyVoicesDifferFromDirectOnly() throws {
let directOnly: [Float] = try render { pedal in
pedal.direct = 1.0
pedal.voice1Level = 0.0
pedal.voice2Level = 0.0
}
let withVoices: [Float] = try render { pedal in
pedal.direct = 1.0
pedal.voice1Level = 1.0
pedal.voice2Level = 1.0
}
#expect(hasNonSilentOutput(directOnly), "direct-only render was silent")
#expect(windowedSSD(directOnly, withVoices) > 0, "adding harmony voices did not change the output")
}
@Test func exposesLevelKnobs() throws {
let pedal: HarmonizerPedal = HarmonizerPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["V1 Level", "V2 Level", "Direct"])
}
@Test func exposesTwoIntervalSelectors() throws {
let pedal: HarmonizerPedal = HarmonizerPedal()
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
#expect(selectors.map { $0.label } == ["Voice 1", "Voice 2"])
// Both minor- and major-thirds above and below must be available.
let titles: [String] = selectors.first?.stops.map { $0.title } ?? []
#expect(titles.contains("m3"))
#expect(titles.contains("M3"))
#expect(titles.contains("-m3"))
#expect(titles.contains("-M3"))
}
@Test func presetRoundTripPreservesIntervalsAndLevels() throws {
let pedal: HarmonizerPedal = HarmonizerPedal()
pedal.voice1 = -3.0
pedal.voice2 = 12.0
pedal.voice1Level = 0.3
let state: PedalState = pedal.captureState()
#expect(state.selectorValues == [-3.0, 12.0])
let restored: HarmonizerPedal = HarmonizerPedal()
restored.applyState(state)
#expect(restored.voice1 == -3.0)
#expect(restored.voice2 == 12.0)
#expect(restored.voice1Level == 0.3)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Harmonizer")
#expect(pedal is HarmonizerPedal)
}
}
@@ -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 (hints filled at capture time).
private func pedalControl(_ board: Int, _ pedal: Int, _ control: Int) -> MIDIMap.CCTarget {
.pedalControl(boardIndex: board, pedalIndex: pedal, controlIndex: control,
pedalNameHint: nil, controlLabelHint: nil)
}
@Test func learnCapturesBindingAndFiresCallback() throws {
let (controller, sg, _, 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(0, 0, 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(0, 0, 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(0, 0, 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(boardIndex: 0, 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(0, 0, 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(0, 0, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.setCCInverted(for: pedalControl(0, 0, 0), true)
#expect(controller.isCCInverted(for: pedalControl(0, 0, 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(0, 0, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.armCCLearn(pedalControl(0, 0, 1))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.setCCInverted(for: pedalControl(0, 0, 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(0, 0, 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(0, 0, 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, _, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
controller.armCCLearn(pedalControl(0, 0, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
#expect(sg.midiMap?.ccs.isEmpty == false)
controller.clearCCBinding(for: pedalControl(0, 0, 0))
#expect(controller.ccBinding(for: pedalControl(0, 0, 0)) == nil)
#expect(sg.midiMap?.ccs.isEmpty == true)
}
}
@@ -0,0 +1,212 @@
// 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(boardIndex: 0, pedalIndex: 0))
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(boardIndex: 0))
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(boardIndex: 1))
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 index that doesn't exist; applying it must be a safe no-op.
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 9))
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // apply — no crash
#expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 9)) != 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(boardIndex: 0, pedalIndex: 0))
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(boardIndex: 0, pedalIndex: 0))?.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)
}
}
}
@@ -0,0 +1,70 @@
// 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 {
private func sampleMap() -> MIDIMap {
MIDIMap(
switches: [
MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"),
MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardIndex: 1), displayNameHint: "Board 2"),
],
ccs: [
MIDIMap.CCBinding(
controller: 7,
channel: 0,
target: .pedalControl(
boardIndex: 0, pedalIndex: 1, controlIndex: 0,
pedalNameHint: "Volume", controlLabelHint: "Position"
)
),
MIDIMap.CCBinding(
controller: 11,
channel: 0,
target: .boardLevel(boardIndex: 0, 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,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)
}
}
@@ -0,0 +1,94 @@
// ReverseDelayPedalTests.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("ReverseDelayPedal")
struct ReverseDelayPedalTests {
private func render(
configure: (ReverseDelayPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.6
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
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: ReverseDelayPedal = ReverseDelayPedal(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)
}
/// Sum of squared differences over the full overlapping length. Feedback only diverges once a
/// fed-back segment is replayed (the third segment), so a narrow window can miss it; comparing
/// the whole readable buffer (the reader returns the first 4096 frames) is robust.
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 {
// Short segment so reversed playback begins within the reader's 4096-frame window.
let samples: [Float] = try render { pedal in pedal.time = 0.03; pedal.mix = 1.0 }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "reverse delay output was silent")
}
@Test func feedbackChangesOutput() throws {
let dry: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.0; pedal.mix = 1.0 }
let trails: [Float] = try render { pedal in pedal.time = 0.03; pedal.feedback = 0.6; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(trails), "feedback reverse delay was silent")
#expect(totalSSD(dry, trails) > 0, "changing feedback did not change the output")
}
@Test func exposesTimeFeedbackKnobs() throws {
let pedal: ReverseDelayPedal = ReverseDelayPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Time", "Feedback"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: ReverseDelayPedal = ReverseDelayPedal()
pedal.time = 1.2
pedal.feedback = 0.7
let state: PedalState = pedal.captureState()
let restored: ReverseDelayPedal = ReverseDelayPedal()
restored.applyState(state)
#expect(restored.time == 1.2)
#expect(restored.feedback == 0.7)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Reverse Delay")
#expect(pedal is ReverseDelayPedal)
}
}
@@ -0,0 +1,74 @@
// ReverseDelayTests.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("ReverseDelay")
struct ReverseDelayTests {
/// Minimal synth: a DC value through a `ReverseDelay`, written to a mono bus.
private final class ReverseSynth: SynthesizerBase {
private let value: Double
private let delay: Double
private let outBus: Int
init(value: Double, delay: Double, outBus: Int) {
self.value = value
self.delay = delay
self.outBus = outBus
super.init()
}
override func build() {
output(bus: outBus, source: ReverseDelay(
input: value,
maxDelay: 0.1,
delay: delay,
feedback: 0.0,
sampleRate: 44100.0
))
}
}
private func render(value: Double, delay: Double) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: ReverseSynth = ReverseSynth(value: value, delay: delay, outBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url, sampleRate: 44100.0)
}
private func left(_ samples: [Float], _ frame: Int) -> Float {
samples[frame * 2]
}
@Test func firstSegmentIsSilentThenReplaysRecordedValue() throws {
// delay 0.02 s @ 44100 = 882-frame segments. Segment 1 [0, 882) plays the still-empty
// buffer (silence); segment 2 [882, 1764) reverses the recorded DC. Asserts are
// scale-independent (the harness applies a fixed output gain/pan): check silence vs.
// non-silent, and that the replayed DC is flat (reverse of a constant is the same constant).
let samples: [Float] = try render(value: 0.5, delay: 0.02)
// Mid segment 1: still recording, play buffer empty → silent.
#expect(abs(left(samples, 441)) < 1e-3, "first segment should be silent (nothing recorded yet)")
// Segment 2, clear of the edge fades → non-silent and constant (reversed DC).
let a: Float = left(samples, 1200)
let b: Float = left(samples, 1400)
#expect(abs(a) > 1e-2, "second segment should replay the recorded value (non-silent)")
#expect(abs(a - b) < 1e-3, "reversed DC should be flat across the segment")
}
}
@@ -0,0 +1,43 @@
// RigArchiveTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@Suite("RigArchive")
struct RigArchiveTests {
private func makeEntry(_ name: String) -> RigEntry {
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
}
@Test func jsonRoundTripIsLossless() throws {
let archive: RigArchive = RigArchive(rigs: [makeEntry("A"), makeEntry("B")])
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let data: Data = try encoder.encode(archive)
let decoded: RigArchive = try decoder.decode(RigArchive.self, from: data)
#expect(decoded == archive)
#expect(decoded.version == rigArchiveFormatVersion)
#expect(decoded.rigs.count == 2)
}
@Test func emptyArchiveRoundTrips() throws {
let archive: RigArchive = RigArchive(rigs: [])
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let data: Data = try encoder.encode(archive)
let decoded: RigArchive = try decoder.decode(RigArchive.self, from: data)
#expect(decoded.rigs.isEmpty)
}
}
@@ -0,0 +1,55 @@
// RigEntryTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@Suite("RigEntry")
struct RigEntryTests {
/// A minimal two-board rig state for snapshotting without an engine.
private func makeState() -> ShoeGazeState {
let board: BoardState = BoardState(label: "Lead", segments: [])
let other: BoardState = BoardState(label: "Clean", segments: [])
return ShoeGazeState(boards: [board, other])
}
@Test func jsonRoundTripIsLossless() throws {
let entry: RigEntry = RigEntry(name: "Ambient Wash", state: makeState())
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
let data: Data = try encoder.encode(entry)
let decoded: RigEntry = try decoder.decode(RigEntry.self, from: data)
#expect(decoded == entry)
}
@Test func savedAtIsRoundedToWholeSeconds() {
let fractional: Date = Date(timeIntervalSince1970: 1_700_000_000.789)
let entry: RigEntry = RigEntry(name: "x", savedAt: fractional, state: makeState())
#expect(entry.savedAt.timeIntervalSince1970 == 1_700_000_001)
}
@Test func duplicatedGetsNewIdSameState() {
let original: RigEntry = RigEntry(name: "A", state: makeState())
let copy: RigEntry = original.duplicated(name: "A copy")
#expect(copy.id != original.id)
#expect(copy.name == "A copy")
#expect(copy.state == original.state)
}
@Test func renamedKeepsIdSameState() {
let original: RigEntry = RigEntry(name: "A", state: makeState())
let renamed: RigEntry = original.renamed(to: "B")
#expect(renamed.id == original.id)
#expect(renamed.name == "B")
#expect(renamed.state == original.state)
}
}
@@ -0,0 +1,205 @@
// RigLibraryStoreTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@MainActor
@Suite("RigLibraryStore")
struct RigLibraryStoreTests {
/// A fresh, unique temp directory for an isolated, local (non-iCloud) store.
private func makeTempDirectory() -> URL {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("RigLibraryTests-\(UUID().uuidString)", isDirectory: true)
return url
}
private func makeStore() async -> (RigLibraryStore, URL) {
let dir: URL = makeTempDirectory()
let store: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
await store.start()
return (store, dir)
}
private func makeEntry(_ name: String) -> RigEntry {
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
}
@Test func saveAddsEntryAndReloadsAcrossInstances() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
try store.save(makeEntry("Ambient"))
try store.save(makeEntry("Crunch"))
#expect(store.entries.count == 2)
// Sorted by name, case-insensitive.
#expect(store.entries.map(\.name) == ["Ambient", "Crunch"])
store.flushPendingWrites()
// A fresh store over the same directory sees the persisted files.
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
await reopened.start()
#expect(reopened.entries.count == 2)
#expect(reopened.entries.map(\.name) == ["Ambient", "Crunch"])
}
@Test func saveSameIdReplacesInPlace() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Original")
try store.save(entry)
// Overwrite under the same id with a new name — no duplicate file should remain.
try store.save(entry.renamed(to: "Renamed"))
#expect(store.entries.count == 1)
#expect(store.entries.first?.name == "Renamed")
store.flushPendingWrites()
let files: [URL] = try FileManager.default.contentsOfDirectory(
at: dir, includingPropertiesForKeys: nil
).filter { $0.pathExtension == "json" }
#expect(files.count == 1, "rename must not leave the old-name file behind")
}
@Test func renameKeepsIdChangesName() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Before")
try store.save(entry)
let renamed: RigEntry = try store.rename(entry, to: "After")
#expect(renamed.id == entry.id)
#expect(store.entries.map(\.name) == ["After"])
store.flushPendingWrites()
}
@Test func duplicateCreatesIndependentEntry() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Base")
try store.save(entry)
let copy: RigEntry = try store.duplicate(entry, newName: "Base 2")
#expect(copy.id != entry.id)
#expect(store.entries.count == 2)
store.flushPendingWrites()
}
@Test func deleteRemovesFileAndEntry() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Doomed")
try store.save(entry)
try store.delete(entry)
#expect(store.entries.isEmpty)
store.flushPendingWrites()
let files: [URL] = try FileManager.default.contentsOfDirectory(
at: dir, includingPropertiesForKeys: nil
).filter { $0.pathExtension == "json" }
#expect(files.isEmpty)
}
@Test func eraseAllClearsLibrary() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
try store.save(makeEntry("A"))
try store.save(makeEntry("B"))
try store.save(makeEntry("C"))
try store.eraseAll()
#expect(store.entries.isEmpty)
store.flushPendingWrites()
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
await reopened.start()
#expect(reopened.entries.isEmpty)
}
@Test func exportThenImportRoundTrips() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
try store.save(makeEntry("One"))
try store.save(makeEntry("Two"))
let archiveData: Data = try store.exportArchiveData()
// Import into a fresh, empty store.
let (other, otherDir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: otherDir) }
let added: Int = try other.importArchive(from: archiveData)
#expect(added == 2)
#expect(other.entries.map(\.name) == ["One", "Two"])
store.flushPendingWrites()
other.flushPendingWrites()
}
@Test func importColludingIdGetsFreshId() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
let entry: RigEntry = makeEntry("Shared")
try store.save(entry)
// An archive carrying the SAME id must not overwrite the existing rig on import.
// Encode with the on-disk strategy (.secondsSince1970) so dates survive the import decoder.
let archive: RigArchive = RigArchive(rigs: [entry])
let data: Data = try ShoeGazeDocument.makeEncoder().encode(archive)
let added: Int = try store.importArchive(from: data)
#expect(added == 1)
#expect(store.entries.count == 2, "colliding id should be imported as a new entry")
store.flushPendingWrites()
}
@Test func importLegacySingleRigFile() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
// A legacy file is a bare ShoeGazeState (no `rigs` array).
let legacyState: ShoeGazeState = ShoeGazeState(boards: [BoardState(label: "Legacy", segments: [])])
let data: Data = try ShoeGazeDocument.makeEncoder().encode(legacyState)
let added: Int = try store.importArchive(from: data, legacyRigName: "Recovered")
#expect(added == 1)
#expect(store.entries.first?.name == "Recovered")
store.flushPendingWrites()
}
@Test func exportDocumentThenImportRoundTrips() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
try store.save(makeEntry("One"))
try store.save(makeEntry("Two"))
// The user-facing export is a `.shoegaze` ShoeGazeDocument envelope.
let documentData: Data = try store.exportDocumentData()
#expect(try ShoeGazeDocument.decoded(from: documentData).rigEntries?.count == 2)
let (other, otherDir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: otherDir) }
let added: Int = try other.importArchive(from: documentData)
#expect(added == 2)
#expect(other.entries.map(\.name) == ["One", "Two"])
store.flushPendingWrites()
other.flushPendingWrites()
}
@Test func importBoardDocumentAddsNoRigs() async throws {
let (store, dir): (RigLibraryStore, URL) = await makeStore()
defer { try? FileManager.default.removeItem(at: dir) }
// A board-carrying `.shoegaze` document is valid but contributes no library rigs.
let boardDocument: ShoeGazeDocument =
ShoeGazeDocument(board: BoardVersion(name: "Lead", state: BoardState(label: "Lead", segments: [])))
let added: Int = try store.importArchive(from: try boardDocument.data())
#expect(added == 0)
#expect(store.entries.isEmpty)
store.flushPendingWrites()
}
}
@@ -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,97 @@
// RotaryPedalTests.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("RotaryPedal")
struct RotaryPedalTests {
private func render(
configure: (RotaryPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.3
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: RotaryPedal = RotaryPedal(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 windowedSSD(_ a: [Float], _ b: [Float]) -> Double {
let skipSamples: Int = 4096
let windowSize: Int = 4096
guard a.count >= skipSamples + windowSize,
b.count >= skipSamples + windowSize else { return 0.0 }
let aWindow: ArraySlice<Float> = a[skipSamples..<(skipSamples + windowSize)]
let bWindow: ArraySlice<Float> = b[skipSamples..<(skipSamples + windowSize)]
return zip(aWindow, bWindow).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), "rotary output was silent")
}
@Test func speedChangesOutput() throws {
let chorale: [Float] = try render { pedal in pedal.speed = 0.0; pedal.accel = 0.05 }
let tremolo: [Float] = try render { pedal in pedal.speed = 1.0; pedal.accel = 0.05 }
#expect(hasNonSilentOutput(tremolo), "fast rotary was silent")
#expect(windowedSSD(chorale, tremolo) > 0, "changing speed did not change the output")
}
@Test func exposesDepthAccelKnobsAndSpeedSwitch() throws {
let pedal: RotaryPedal = RotaryPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Depth", "Accel"])
#expect(pedal.effectSwitches.map { $0.label } == ["Speed"])
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Chorale", "Tremolo"])
}
@Test func presetRoundTripPreservesSpeed() throws {
let pedal: RotaryPedal = RotaryPedal()
pedal.speed = 1.0
pedal.depth = 0.4
let state: PedalState = pedal.captureState()
let restored: RotaryPedal = RotaryPedal()
restored.applyState(state)
#expect(restored.speed == 1.0)
#expect(restored.depth == 0.4)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Rotary")
#expect(pedal is RotaryPedal)
}
}
@@ -0,0 +1,70 @@
// SampleRateDecimateTests.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("SampleRateDecimate")
struct SampleRateDecimateTests {
/// Minimal synth: a sine through a `SampleRateDecimate`, written to a mono bus.
private final class DecimateSynth: SynthesizerBase {
private let freq: Double
private let factor: Double
private let outBus: Int
init(freq: Double, factor: Double, outBus: Int) {
self.freq = freq
self.factor = factor
self.outBus = outBus
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
output(bus: outBus, source: SampleRateDecimate(input: osc, downsample: factor))
}
}
private func render(freq: Double, factor: Double) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: DecimateSynth = DecimateSynth(freq: freq, factor: factor, outBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url)
}
/// Left-channel frame `i` (interleaved stereo).
private func left(_ samples: [Float], _ frame: Int) -> Float {
samples[frame * 2]
}
@Test func holdsEachSampleForTheFactor() throws {
// Factor 4: frames latch at 0, 4, 8, … and hold for four output samples each.
let samples: [Float] = try render(freq: 2000.0, factor: 4.0)
// Group [8, 11] holds the value latched at frame 8 (a non-zero point on the sine).
#expect(left(samples, 8) == left(samples, 9))
#expect(left(samples, 8) == left(samples, 10))
#expect(left(samples, 8) == left(samples, 11))
// The next group latches a fresh value.
#expect(left(samples, 8) != left(samples, 12), "decimator did not re-latch at the group boundary")
}
@Test func factorOneIsTransparent() throws {
let samples: [Float] = try render(freq: 2000.0, factor: 1.0)
// No two adjacent samples forced equal — a moving sine should differ frame-to-frame.
#expect(left(samples, 8) != left(samples, 9), "factor 1 should pass the signal through unheld")
}
}
@@ -0,0 +1,90 @@
// ShimmerReverbPedalTests.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("ShimmerReverbPedal")
struct ShimmerReverbPedalTests {
private func render(
configure: (ShimmerReverbPedal) -> Void
) throws -> [Float] {
let renderDuration: Double = 0.2
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
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: ShimmerReverbPedal = ShimmerReverbPedal(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), "shimmer reverb output was silent")
}
@Test func shimmerChangesOutput() throws {
let none: [Float] = try render { pedal in pedal.shimmer = 0.0; pedal.decay = 0.8; pedal.mix = 1.0 }
let glassy: [Float] = try render { pedal in pedal.shimmer = 0.8; pedal.decay = 0.8; pedal.mix = 1.0 }
#expect(hasNonSilentOutput(glassy), "shimmered reverb was silent")
#expect(totalSSD(none, glassy) > 0, "changing shimmer did not change the output")
}
@Test func exposesSizeDecayShimmerDampKnobs() throws {
let pedal: ShimmerReverbPedal = ShimmerReverbPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label }
#expect(labels == ["Size", "Decay", "Shimmer", "Damp"])
}
@Test func presetRoundTripPreservesKnobs() throws {
let pedal: ShimmerReverbPedal = ShimmerReverbPedal()
pedal.decay = 0.5
pedal.shimmer = 0.7
let state: PedalState = pedal.captureState()
let restored: ShimmerReverbPedal = ShimmerReverbPedal()
restored.applyState(state)
#expect(restored.decay == 0.5)
#expect(restored.shimmer == 0.7)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Shimmer Reverb")
#expect(pedal is ShimmerReverbPedal)
}
}
@@ -0,0 +1,129 @@
// ShimmerReverbTests.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("ShimmerReverb")
struct ShimmerReverbTests {
/// Minimal synth: an input source through a `ShimmerReverb`, written to a mono bus.
private final class ShimmerSynth: SynthesizerBase {
private let oscFreq: Double?
private let dc: Double
private let size: Double
private let decay: Double
private let shimmer: Double
private let outBus: Int
init(oscFreq: Double?, dc: Double, size: Double, decay: Double, shimmer: Double, outBus: Int) {
self.oscFreq = oscFreq
self.dc = dc
self.size = size
self.decay = decay
self.shimmer = shimmer
self.outBus = outBus
super.init()
}
override func build() {
let source: any ValidGeneratorInput = oscFreq.map { OscSin.Audio(freq: $0) } ?? dc
output(bus: outBus, source: ShimmerReverb(
input: source,
maxDelay: 0.12,
size: size,
decay: decay,
shimmer: shimmer,
damp: 0.4,
sampleRate: 44100.0
))
}
}
private func render(
oscFreq: Double?,
dc: Double,
size: Double = 0.05,
decay: Double,
shimmer: Double
) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, sampleRate: 44100.0)
defer { try? FileManager.default.removeItem(at: url) }
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(dstBus) }
let synth: ShimmerSynth = ShimmerSynth(
oscFreq: oscFreq, dc: dc, size: size, decay: decay, shimmer: shimmer, outBus: dstBus.index
)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(synth)
try engine.add(master, position: NodePosition.after(synth))
try engine.start()
return readStereoCAF(url: url, sampleRate: 44100.0)
}
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 silentInputProducesSilence() throws {
// No input energy → the feedback loop has nothing to sustain → output stays at zero.
let samples: [Float] = try render(oscFreq: nil, dc: 0.0, decay: 0.9, shimmer: 0.8)
#expect(!hasNonSilentOutput(samples), "shimmer reverb rang with no input")
}
@Test func passesDCWithUnityGainAndLinearScaling() throws {
// With decay = shimmer = damp = 0, the tank is just the input through two Schroeder
// allpasses (unity at DC steady state) delayed by `size`. The output is therefore a fixed
// gain (the harness output gain/pan) times the DC input — exactly linear. Compare two DC
// levels at a settled frame so the harness scale cancels: the ratio must be 2.0.
let high: [Float] = try render(oscFreq: nil, dc: 1.0, size: 0.01, decay: 0.0, shimmer: 0.0)
let low: [Float] = try render(oscFreq: nil, dc: 0.5, size: 0.01, decay: 0.0, shimmer: 0.0)
let frame: Int = 1500 // past the size delay + allpass settling, within the read window
let h: Double = Double(high[frame * 2])
let l: Double = Double(low[frame * 2])
#expect(abs(h) > 1e-3, "settled DC output should be non-zero")
#expect(abs(h / l - 2.0) < 0.01, "DC gain should be exactly linear (ratio 2.0)")
}
@Test func nonFiniteControlsProduceFiniteOutput() throws {
// NaN control reads must be sanitised (not trap the seconds→frames conversion nor poison
// the feedback): the output must stay finite.
let samples: [Float] = try render(
oscFreq: 440.0, dc: 0.0, size: Double.nan, decay: Double.nan, shimmer: Double.nan
)
#expect(samples.allSatisfy { $0.isFinite }, "non-finite controls produced NaN/inf output")
}
@Test func highShimmerDoesNotAccumulateDCOffset() throws {
// The octave-up of DC is DC and the damping filter passes DC, so without a feedback
// DC-blocker the loop DC gain (~decay + shimmer) exceeds 1 at high settings and builds an
// offset. Aggressive small-tank settings iterate the loop many times within the read window.
func meanDC(_ shimmer: Double) throws -> Double {
let s: [Float] = try render(oscFreq: 440.0, dc: 0.0, size: 0.005, decay: 0.92, shimmer: shimmer)
return s.reduce(0.0) { $0 + Double($1) } / Double(max(s.count, 1))
}
let noShimmer: Double = try meanDC(0.0)
let maxShimmer: Double = try meanDC(0.85)
#expect(abs(maxShimmer) < 0.015, "high shimmer accumulated a DC offset (mean = \(maxShimmer))")
#expect(abs(maxShimmer - noShimmer) < 0.012, "shimmer added DC vs the no-shimmer baseline")
}
@Test func decayChangesTheTail() throws {
// Small tank so feedback round-trips compound within the reader's window; different decay
// must change the tail (direction-agnostic — a tuned comb is not monotonic in level).
let low: [Float] = try render(oscFreq: 440.0, dc: 0.0, size: 0.01, decay: 0.1, shimmer: 0.0)
let high: [Float] = try render(oscFreq: 440.0, dc: 0.0, size: 0.01, decay: 0.9, shimmer: 0.0)
#expect(hasNonSilentOutput(high), "decayed tail was silent")
#expect(totalSSD(low, high) > 0, "changing decay did not change the tail")
}
}

Some files were not shown because too many files have changed in this diff Show More