138 Commits

Author SHA1 Message Date
josh 7720fbec7b bump versions 2026-07-12 12:32:36 -07:00
josh 3228614071 Release notes for 2.1.1: input mute + rig-persisted I/O
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 12:30:36 -07:00
josh e207728a12 Review nits: name pulse-settle constant, fix stale comments
Non-blocking cleanups from the clean review pass:
- EngineConfigView.startEngine: collapse the redundant early-return in the
  sample-rate-mismatch branch into the shared tail.
- InputMuteButton: hoist the 0.2s settle duration to a named pulseSettleDuration.
- InputMuteTests: correct a stale "input defaults muted" comment (library default
  is audible; the test mutes explicitly).
- Plan doc: setInputMuted(true) runs before engine.start(), not after; note the
  addBoard priming.

464 tests pass; macOS app builds.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 21:41:57 -07:00
josh e36074e9d3 Review fix: prime input-mute ramp + mute before engine start
Two blocking findings from external review:

1. UIParamNode itself ramps from previousOutputValue (seeded at the compile-time
   default, advanced only by RT render — update() doesn't touch it) to the target
   over the first block. So a node told to start muted still ramped full-gain→0
   across block 0; the earlier "hard gate" only moved the leak from Lag to the
   param's own ramp. The mutedInputRendersSilent test passed by accident (the
   test-loop tone is quiet in that first block).
   Fix: prime previousOutputValue to the target. Race-free before a node is
   spliced into the graph (addBoard) and safe on a spliced node while the engine
   is stopped; a running engine keeps the ramp as a click-free live toggle. New
   setInputMuteGain(_:muted:seedRamp:) / primeInputMute helpers; setInputMuted
   seeds only when engine.isRunning == false.

2. EngineConfigView.startEngine called setInputMuted(true) AFTER engine.start(),
   so the engine came up unmuted for the first blocks. Moved it before start()
   (engine stopped there, so the gain is seeded with no ramp).

Also: correct the setInputMuted doc (abrupt kill-switch, not "smoothed").
Regression test stoppedMutePrimesNodesSoTheresNoStartRamp asserts the ramp start
equals the target (no pending ramp) after a stopped mute and for a board added
while muted. 464 tests pass; both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 21:34:46 -07:00
josh b29c8848ef Review fix: exact-silence input mute (hard kill-switch gate)
External review found the lagged mute gate leaks a faint transient (~-54 dB) on
its first blocks: Lag seeds its state at 0, so gating on a lagged value never
starts at exactly zero on a rig that comes up muted — the moment the mute is
meant to keep things quiet. Measured directly via an NRT render.

- Gate the input with a hard, un-lagged kill switch `(inputMute - 1) * -1` in
  both HardwareInputPassThrough and TestLoopTap. A muted node is then exactly
  silent from the first sample; a kill-switch mute is expected to be abrupt.
  Drop the now-unused muteLagTime constant.
- Flip the library default to `inputMuted = false` (audible). Muting is the app's
  Start-time policy (EngineConfigView already re-asserts muted on user Start), so
  headless/offline library use isn't forced silent and render tests that route the
  test-loop through a board no longer depend on a leak to see signal. The pulsing
  glow now also starts at engine Start rather than before it.
- Tests: add render-level mutedInputRendersSilent (exact silence) and
  unmutedInputRendersSignal; update the default-state and MIDI-latch expectations;
  drop the StereoRouting un-mutes that the leak had made necessary.
- Plan doc: correct the mute default / gate description and the UserDefaults note.

463 tests pass; both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 16:03:50 -07:00
josh be0e3d118b Declare LSSupportsOpeningDocumentsInPlace on iOS
The iOS app declares a .shoegaze document type but didn't state whether it opens
documents in place. Incoming files are read and imported into the rig library (a
copy), never edited in place, so declare false — silencing the launch warning.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 15:45:43 -07:00
josh 5542ee5b5a Document input mute in Help; pulsing glow while muted
- Help: cover the input mute in Setup ("input starts muted on every Start"),
  Choosing an Input (hard input gate vs the output Rig Mute, MIDI-mappable), and
  the MIDI switch list (Rig Mute / Input Mute).
- Input-mute button is now its own view with a pulsing red ring + shadow that
  oscillates under a repeatForever animation while muted, so new users see why
  the rig is silent. The glow settles out when un-muted and never intercepts taps.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 15:44:02 -07:00
josh b0294612f8 Fix mapping-badge actor warnings; un-crowd the transport row
- MappingBadge.pcFill/ccFill/keyFill are marked nonisolated so the nonisolated
  MappingBadgeKind.fill can read them (a SwiftUI View's statics are otherwise
  main-actor-isolated). Clears three "actor-isolated ... from a nonisolated
  context" warnings.
- The input-mute button pushed the docked desktop transport cluster past the row
  width, clipping the Rate picker and I/O steppers. Render the three rig toggles
  (Bypass / Mute / Input) icon-only there via .labelStyle(.iconOnly); the .help
  tooltips remain and the compact layout still shows text labels.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 15:38:22 -07:00
josh cc3a986cde Persist I/O + input via the rig, not UserDefaults
The rig snapshot already stores inputSource + input/output channel counts and
syncs them via the autosave envelope and the iCloud rig library. Make that the
single source of truth instead of the parallel UserDefaults path.

- RigStore.restore applies the saved channel layout (applyChannelLayout) before
  loadRig, while stopped at launch, so a saved live-input channel validates
  against the restored count instead of falling back to the test loop. The
  general loadRig policy (don't force layout mid-session) is unchanged.
- applyInputSource and the engine-config onConfigApplied now autosave, so input
  and I/O changes are captured into the rig immediately.
- Remove the UserDefaults keys and read/write sites: ShoeGaze.inputSelection
  (builder view + iOS model) and the ShoeGaze.inputChannels/outputChannels keys
  added earlier (EngineConfigView + both app targets build at the default layout
  now; RigStore.restore supplies the rig's layout).
- Fresh-launch default: the seed paths set inputSource = liveInput(0) when the
  engine has an input channel, so a first launch listens to the instrument. A
  restored rig keeps its own saved input; the view's on-appear hook only requests
  mic access for a restored live selection (test-loop fallback on denial).

Test: RigStore.restoreAppliesSavedChannelLayoutAndInput. 461 tests pass; both
app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 15:34:23 -07:00
josh 5987ec7b78 Add input mute + persist engine I/O counts
Input mute: a hard gate on the signal feeding every board (guitar / mic),
distinct from the rig-output mute. Each board input writer (TestLoopTap /
HardwareInputPassThrough) gains a lagged @UIParam mute gain; ShoeGaze holds
inputMuted (default true), drives every input node, and brings newly-added
boards up at the current state. A deliberate user Start re-asserts the mute so
a fresh engine is silent until the player un-mutes — cutting accidental noise.
Toggle sits beside the Start/Stop transport and is MIDI mappable
(MIDIMap.Action.inputMute). First launch now defaults to live In 0 instead of
the test-loop arpeggio.

I/O persistence: the engine's input/output channel counts now persist to
UserDefaults (written by EngineConfigView, restored by the app targets at
engine construction), so a multi-channel setup survives relaunch and a saved
live-input channel stays valid — fixing the input selection reverting to the
test loop after a restart.

Tests: InputMuteTests (default-muted, node driving, per-board adoption, live
path) + a MIDI PC input-mute latch test. StereoRouting render tests un-mute
before rendering. 460 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-11 15:17:51 -07:00
josh f61961b90b Consolidate 2.1.1 into 2.1.0 release notes
Fold the MIDI-CC-vs-tempo-sync note into the single 2.1.0 entry (CHANGELOG + RELEASES);
the CC guard ships as part of 2.1.0 rather than a separate 2.1.1. No code change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 10:14:42 -07:00
josh 7e39842eb2 2.1.1: ignore MIDI CC on tempo-synced parameters
A CC bound to a pedal parameter locked to a note division is now ignored while
synced — the value is tempo-derived and a CC write would be overwritten on the next
tempo change. Index-stable: ccMappableControls is unchanged (persisted bindings resolve
by position), and only the CC *write* is skipped. MIDIController.applyCC checks
Pedal.isNodeTempoSynced(_:) (node-identity match against tempoSyncableParams) and
skips the update; the binding stays intact and resumes control once set back to Free.

Test: MIDIControllerCCTests.ccIsIgnoredWhileParameterIsTempoSynced. 455 tests pass.
Docs: CHANGELOG.md, RELEASES.md, plan MIDI section updated to "implemented".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 09:00:24 -07:00
josh 2772abdc56 Release 2.1.0: tempo-synced pedal parameters, editable BPM, control mapping badges
Tempo sync
- Lock a delay time or modulation LFO rate to a note division (whole..sixteenth,
  dotted, triplet) of the shared clock. Value is derived from the tempo and follows
  tap tempo, the stepper, the editable BPM field, and MIDI.
- Delay time: Delay, FeedbackDelay, PingPong, ReverseDelay, MultiTap (per tap).
  LFO rate (inverse mapping): Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
- Core types NoteDivision / TempoSync / TempoSyncableParam; Pedal.tempoSyncableParams /
  tempoSync / applyTempoSync / setSync; ShoeGaze.setBpm broadcast recomputes all pedals;
  tempoSync persisted in PedalState (lenient decode) and recomputed on load + recall.
- Observable TempoSyncRevision so the sync badge refreshes on any state-change path.

UI
- Division picker with drawn music-notation glyphs (NoteGlyphView + rasterized cache):
  noteheads, stems, flags, augmentation dot, bracketed 3 for triplets. Presented as a
  height-capped popover so it stays on-screen on iOS.
- Editable BPM text field: integer-only, live-filtered, clamped 30-300, commit on
  return / Done / blur.
- Divisions that clamp at the current tempo are disabled in the picker; an active
  clamped sync shows a warning marker.
- In-context control mapping badges (PC / CC / KEY) per pedal control, with a legend.

Delays
- Maximum delay time raised to 5 s across the delay pedals (was 1-2 s).

Docs: CHANGELOG.md, RELEASES.md, docs/plans/2.2-tempo-synced-parameters.md.
All 454 tests pass; passed lyrebird_external_review (RT-safe, main-thread param writes).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:47:22 -07:00
josh a33d5488c9 Add computer-keyboard control mapping
Bind letter/digit keys (with Shift/Control/Option; Command reserved for
menu shortcuts) to the same rig toggle Actions a MIDI Program-Change
footswitch drives. Keys reuse MIDIController's perform(_:) dispatch via a
new .key learn target and ingestKey(_:modifiers:).

Key capture is platform-specific: macOS installs an AppKit
NSEvent.addLocalMonitorForEvents(.keyDown) monitor (SwiftUI .onKeyPress
only delivers to the focused view); iOS uses .onKeyPress with the root
made focusable/focused, reclaiming focus when a text-field modal closes.
Both gate on the first responder not being a text field so typing is
never hijacked, filter key-repeat, and reserve Command for the menu.

MIDIMap gains keys:[KeyBinding] and a KeyModifiers OptionSet, both with
tolerant Codable decode so old rigs (no keys / no modifiers) still load
with switches/ccs intact. The mapping sheet is unified: each switch row
shows its footswitch (PC) and key bindings with per-source learn/clear,
and the sheet is retitled "MIDI / Control Mapping".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 15:03:12 -07:00
josh 2c2ce06797 plist updates 2026-07-05 22:42:00 -07:00
josh 8b72957502 Update RELEASES.md 2026-07-05 20:48:01 +00:00
josh e051521c04 Release 2.0.0: metronome, rig mute + shortcuts, set-list ordering, per-rig persistence
- Visual metronome tempo indicator (pendulum playhead) replacing the flashing LED
- Rig Mute (Cmd-Z) hard-silence, distinct from Bypass Rig; wired to header, board menu, MIDI
- Keyboard shortcuts: Cmd-1..9 board switch, Cmd-Shift-1..0 set-list rig load, Cmd-Z mute
  (macOS native menus + iOS/iPadOS hardware keyboards)
- Rig set-list ordering: drag or Move Up/Down in the picker; order saved and archive-portable
- Persist tempo, input selection, and engine I/O with a rig (I/O applied via opt-in
  applyChannelLayout, not forced on load)
- Fix archive import colliding set-list positions with existing rigs
- Remove ShoeGazeDemo / ShoeGazeiOSDemo apps and projects; keep the two Builder apps
- Bump marketing version to 2.0.0 on both Builder projects; pin Lyrebird 1.2.3
- Add CHANGELOG.md

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-05 12:30:45 -07:00
josh 4b0cf65a2b v1.5.0 release: Looper pedal, iPad/iOS layout rework, Lyrebird 1.2.3
- New multitrack Looper pedal (catalog now 36): smart Loop footswitch,
  4 tracks with per-track mute, undo/reverse/timeline, beat-quantized
  Sync/Free transport, MIDI-mappable transport + track taps + Sync,
  stomp-style Reset, RT-safe.
- iPad/iOS canvas-first compact layout with composition panels in sheets;
  header compaction; scrollable Add-Pedal sheet; compact-sheet fixes.
- Bump Lyrebird dependency to 1.2.3.
- Fixes: transport-only Start no longer reverts Settings; drop stale
  doc + dead looperTimeline property.
- Bump app MARKETING_VERSION to 1.5.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 23:00:28 -07:00
josh 0bfc25ace6 Address external review: transport-only Start must not revert Settings config
Review found a blocking bug: the compact header's transportOnly EngineConfigView
and the Settings-sheet EngineConfigView each own independent @State pending
config. reconfigureEngine mutates the engine in place, so the header instance's
.task(id: engine identity) never re-syncs — pressing Start there re-applied its
stale pending values, reverting rate/channel edits made in Settings. In
transportOnly mode, skip the reconfigure and just start the already-configured
engine.

Also: remove the unused isNarrow / horizontalSizeClass (dead code), and honor
showsFilterMenu in PedalPaletteView.horizontalBody (was only gated in vertical).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 22:13:33 -07:00
josh 426a288002 iPad portrait: give the scope strip its natural height so the legend doesn't overlap
The header scope was clamped to the compact inline height (76pt) in both
orientations; in the portrait full-width strip that clamp made the taller scope
(legend + 120pt lanes) overflow upward into the Rigs/Pedals/Settings row. Clamp
the height only for the inline landscape strip; portrait uses the natural height.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 22:05:18 -07:00
josh 12e83bd172 iPad: drop the header scope to a full-width strip below the rows in portrait
On narrower portrait widths (smaller iPads / split view) the inline scope overlaid
and clipped the header. Detect portrait by actual size (iPad is .regular in both
orientations) and, in portrait, move the scope to a full-width strip beneath the
control rows — using the ample portrait vertical space. Landscape keeps it inline
beside the transport. Header control rows + transport factored into shared
subviews.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 21:56:07 -07:00
josh bf1e09ede3 iPad header: close the gap between rows 1 and 2
The tall scope lived inside row 1, so it set row 1's height and left a gap above
the Tempo/Tuner row. Put the three left rows in their own VStack (tight
rowSpacing) with scope + transport as a right column spanning them.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 21:46:03 -07:00
josh cd3aeb771b iPad header: three rows — rig controls inline, Tempo/Tuner own row
Split the header into the requested three rows:
  Row 1: ShoeGaze title · [Bypass · Mute · Help · MIDI filling to the scope] · scope · Start/Record
  Row 2: Tempo · Tuner
  Row 3: Rigs · Pedals · Settings

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 21:40:23 -07:00
josh e75b50b157 iPad header: place performance controls inline, right of the title
Move the performance row (Tempo / Tuner / Bypass / Mute / Help / MIDI) up onto the
title row, filling the space between the title and the scope. As a horizontal
scroll view it flexes to the available gap — shows in full in landscape, scrolls
when tight in portrait — and no longer sits beneath the scope. The composition
sheet-openers (Rigs / Pedals / Settings) remain on the row beneath.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 21:28:18 -07:00
josh 6a3c4fdca9 iPad header: stop Mute toggle expanding; fix mixer overflow into CPU meters
- The switch Toggle filled the row, pushing Bypass / Mute / Help / MIDI far right
  under the scope. fixedSize keeps them contiguous next to Tempo/Tuner under the
  title.
- BoardBarView's control column (segmented picker + two sliders + bordered mute)
  is taller than 92pt with iOS control metrics and overflowed into the CPU meters;
  raise barHeight to 110.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 21:21:44 -07:00
josh 22ae022143 iPad header: group rig controls with Tempo/Tuner; rename title to "ShoeGaze"
Move the rig-wide controls (Bypass / Mute rig / Help / MIDI) off the composition
row and onto a performance row alongside Tempo/Tuner, under the title — separating
performance controls from the composition sheet-openers (Rigs / Pedals /
Settings), which now get their own row. Both rows are full-width so nothing clips
in portrait.

Rename the header title from "ShoeGaze Builder" to "ShoeGaze" — it's an app now,
not a template placeholder.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 21:12:54 -07:00
josh 722c8d9069 iPad: move header panel row to full width so it isn't clipped in portrait
The panel/toggle row (Rigs / Pedals / Settings / Bypass / Mute rig / help / MIDI)
sat in the header's left column beside the wide scope, so in the narrower
portrait width its right end (Mute rig, help, MIDI) was cut off. Move it to a
full-width row beneath the title + scope + transport; it now fits portrait and
still scrolls on very narrow (split-view) widths. Tempo/Tuner stay under the
title.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 21:02:29 -07:00
josh 1c9979af52 iOS Demo: pin host fill frame to topLeading
Belt-and-suspenders: the host fill frame used the default center alignment, so if
the builder ever reported intrinsic height the window would center it (the portrait
symptom). Pin the host frame to .topLeading.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 20:21:27 -07:00
josh 36202a5e95 iOS Demo: host the builder directly, filled (fix portrait centering)
ShoeGazeBuilderiOSApp wrapped the builder in a NavigationStack with its own
title, duplicating the builder's header and leaving the content vertically
centered in portrait. Host ShoeGazeBuilderView directly with a fill frame and no
NavigationStack/title — the builder provides its own chrome and scroll regions.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 19:44:02 -07:00
josh 19feb03fe8 Add-Pedal sheet: scrollable list, fixed header with type filter, stable size
The sheet couldn't scroll — PedalPaletteView doesn't self-wrap in a ScrollView
(the host must) and the sheet had none, so the list overflowed and drags just
resized the detent. Rework:

- Wrap the palette in a ScrollView; single fixed detent (fraction 0.82) so the
  sheet no longer resizes, and presentationContentInteraction(.scrolls) so drags
  scroll the list.
- Fixed header with the "Add Pedal" title, the type-filter menu, and Done —
  PedalPaletteView gains an external filter binding + showsFilterMenu flag so the
  filter can be hoisted out of the scrolling content.
- PedalCategory made public (+ Sendable) so the filter binding can cross the
  public palette init.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 17:21:49 -07:00
josh f97ba90ea6 iPad: compact the header, fill portrait, fix palette scroll + sheet padding
- Header: the panel-toggle row and Tempo/Tuner move into the left column under
  the title (beside the scope + transport), filling the dead vertical space; the
  top strip is now just the board mixer + CPU meters.
- Portrait: the root fills the window and pins top-leading so content is no
  longer vertically centered with large blank margins.
- Add-Pedal sheet: content scrolls instead of resizing the detent
  (presentationContentInteraction), and a visible toolbar background stops the
  title drawing over the first rows.
- Rigs sheet: add top padding so the "Rigs" title isn't flush to the edge.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 15:54:56 -07:00
josh 67744ec89d iPad: move the scope into the header beside the transport
Reclaim the header's dead space: a narrow scope now sits left of a Start/Record
transport cluster in the compact header. The scope is removed from the top strip
(CPU meters stay), and the Record button moves up next to Start. The recording-
folder chooser (set-and-forget) moves into the Settings sheet.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 15:00:55 -07:00
josh ba80573213 iPad polish: fix Tempo/Tuner truncation, sheet title overlap, cramped strip
- TempoView/TunerView toggles size to content (fixedSize) instead of a fixed
  96pt width that truncated "Tempo: On" to "Tempo:…" at iOS font sizes.
- Add-Pedal sheet uses an inline navigation title so the large title no longer
  draws over the palette list.
- Settings sheet lays the engine controls out in a plain scroll (not a Form),
  so the Start button isn't compressed to "S…"; input picker on its own row.
- Compact top strip separates Tempo/Tuner, the board mixer, and the scope with
  dividers and section spacing so they stop visually colliding.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 14:58:10 -07:00
josh efa193ea37 Fix compact sheets not presenting (one sheet per view node)
The Rigs / Pedals / Settings sheets were stacked as additional .sheet modifiers
on the main view node, which already hosts the MIDI and Help sheets. SwiftUI
presents at most one sheet per node, so the new ones silently never appeared.
Move each onto its own Color.clear anchor node (the pattern already used for the
board-manager sheet and the file importers/exporter).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 14:51:12 -07:00
josh 45b18b5ea8 iPad: use the sheet-based layout at every size; drop forced min width
The docked layout clipped on iPad even at iPad-Pro (regular) width because a
large macOS min-width hint forced content wider than the screen and the header
did not reflow. iPhone is not a target, so gate purely by platform: every iPad
size uses the canvas-first / sheet layout, macOS keeps the docked layout. Drop
the min-width/min-height frame on iOS so nothing is forced past the screen.

Add an isNarrow (horizontalSizeClass == .compact) hook reserved for
size-specific tuning of the smaller iPads / split view.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 14:44:53 -07:00
josh 5b343a2cce iOS compact layout: canvas-first with composition panels in sheets
On narrow widths (iPhone, iPad portrait / split view) the docked desktop layout
overflowed and left the board canvas cramped. Add a size-class-gated compact
layout; regular widths (macOS, wide iPad) are unchanged.

Compact:
- Root drops the always-docked rig sidebar; it opens from a "Rigs" sheet button.
- Header keeps performance controls on screen (title, Start/Stop, Record badge,
  Bypass, Mute rig) with a scrollable row of panel toggles.
- Composition panels move to bottom sheets: Pedals (palette + routing),
  Settings (sample rate / channel counts / input source), Rigs (library).
- Board mixer, scope, CPU meters, and Tempo/Tuner stay docked above the
  full-bleed board canvas.

EngineConfigView gains a transportOnly mode (Start/Stop button only) so the
transport stays in the compact header while the config controls live in the
Settings sheet.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 14:33:19 -07:00
josh d07247e40e Address review: drop stale doc + dead looperTimeline property
- LooperPedal.widthUnits doc updated "double-width" -> triple-width.
- Remove the now-unreachable looperTimeline property (LooperTimelineView is
  rendered from looperColumnarContent; the columnar branch always intercepts
  the looper before defaultContent).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 13:11:12 -07:00
josh bdfbe04713 Looper: wide 3-column layout to fit tall pedal without scrolling
The looper stacked too many sections to fit the board canvas. Render it (only)
in a wide, three-column layout at widthUnits = 3:

- Left column: loop timeline, Free/Sync switch, Reset footswitch.
- Centre column: the four effect knobs (2×2) over a Level + Bypass footer, with
  the Mix slot reserved empty so Bypass stays horizontally centred like a normal
  pedal.
- Right column: transport footswitches in a 2×2 grid — Record / Reverse over
  Stop / Cue Stop (ordered by label).

Every other pedal keeps the default single-column section stack (extracted into
PedalView.defaultContent, no behaviour change).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 13:05:57 -07:00
josh 5090a9255f Looper reverse fix + header layout compaction + tempo toggle
Looper:
- Reverse now continues from the current play-head instead of jumping to
  duration-minus-position; anchor-based position tracking survives direction
  changes. Sync mode defers the flip to the next beat; Free applies immediately.
- Sync switch relabeled "Sync to Tempo".

Tempo/Tuner:
- Add a Tempo on/off toggle (ShoeGaze.setTempoEnabled) that hides the indicator
  and forces every tempo-dependent pedal switch (PedalSwitch.tempoDependent) off;
  PedalSwitchView disables such switches via the shoeGazeTempoEnabled environment.
- Tuner readout laid out inline; Tempo/Tuner pinned to fixed heights so toggling
  state no longer shifts surrounding layout.

Header:
- Collapsed to two rows: title + Tempo/Tuner (left, stacked) and engine options
  over input controls (right, trailing-aligned). TAP is a standard-height button.
- Removed the redundant Boards button; moved Clear into the board bar.
- Fixed the rig mute glyph size so toggling mute doesn't shift the volume row.

Help: added a Looper section documenting transport, Free/Sync, knobs, tracks,
and MIDI-assignable actions.

Tests: TempoEnableTests + looper reverse/deferral coverage.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-04 12:31:11 -07:00
josh 4e58c9bd9b Looper UI: make the selected track dot read as active
A selected-but-empty track (e.g. A in the clear state) previously showed only a
thin white ring on a dim dot — easy to read as "not lit." Give the selected
track a bright letter and a lighter fill so the active track is obvious even
before it's recorded. Combined with the poll re-subscribe fix, the dots now
track the live selection.

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

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

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

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

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

Tests: cycleSyncModeOscillatesThroughOptions, pedalActionCyclesLooperSync.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

339 tests pass; both app targets build.

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

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

Both app targets build; suite green.

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

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

339 tests pass; both app targets build.

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

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

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

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

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

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

Both app targets build; suite green.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 08:18:09 -07:00
josh ec6c97c065 iOS fix for menu display 2026-06-28 21:01:42 -07:00
josh 0b0befe02f update images and xcode. versions 2026-06-28 20:39:51 -07:00
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
josh b55df174a6 Fix dragging an existing pedal into a region lane (cross-lane move)
Drag/drop only supported add: (palette→anywhere) and same-lane reorders, so
dragging a pedal from the main chain (or another lane) into a Stereo Unzip /
Split / Parallel lane highlighted the lane but the drop was a no-op.

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 17:44:47 -07:00
josh 5040ea1518 Rename Mu-Tron pedal to Mutant (de-trademark)
Rename the user-facing 'Mu-Tron' pedal to the non-proprietary 'Mutant':
displayName, registry key, PedalType.mutant, enclosure color, palette order,
and the class (MuTronPedal -> MutantPedal) + test file. The underlying Lyrebird
MuTronIII generator (and its Mode/Sweep types) keep their names — that's the
dependency's DSP type, not user-facing.

Note: displayName doubles as the rig-save key, so rigs saved with 'Mu-Tron'
won't match on load (acceptable pre-1.0; nothing released).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 21:00:02 -07:00
josh 21b9123a87 Replace stringly-typed pedal API with PedalType tokens
appendPedal(type: String, to:) is replaced by appendPedal(_ kind: PedalType, to:),
where PedalType is an extensible RawRepresentable struct with static members for
the built-in pedals:

    try shoeGaze.appendPedal(.overdrive, to: board)

Discoverable/autocompleting call sites, still open for custom pedals
(PedalType("My Pedal")). rawValue == the pedal's displayName, so PedalRegistry
and the rig JSON format are unchanged — saved rigs load exactly as before.

Named PedalType (not PedalKind) to avoid colliding with Lyrebird's score-notation
PedalKind enum, which is visible when both modules are imported. The UI palette
wraps its registry-key strings as PedalType(key); demos/tests use the static
members. PedalRegistry.makePedal(type:) stays string-keyed as the serialization
boundary used by loadRig.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 20:34:45 -07:00
josh 24ce4564e8 Drop screenshot-instructions note from README
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 16:41:19 -07:00
josh b1303a25ae Add README screenshots (builder + board mixer)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 16:10:58 -07:00
josh 21fda7067d Expand README with project overview, pedal catalog, and screenshots
Replace the one-line description with a full README: feature list, the 18-pedal
catalog by category, requirements, products, getting-started snippets (headless
+ SwiftUI builder), demo-app guide, and a Screenshots section wired to
docs/images/ (relative paths render on the git host and in clones).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 14:59:04 -07:00
josh 8c601e2029 Share one global test signal across all boards
Each board previously got its own TestLoopSource, so multiple boards ran
independently-phased arpeggios and any rebuild restarted them out of sync —
audible polyrhythms. Now a single global TestLoopSource writes a shared test
bus, and each board gets a lightweight TestLoopTap (added .after the source)
copying that bus into its head bus. The shared source survives board
add/remove, so the test signal stays phase-locked and never restarts.

- ShoeGaze: globalTestSource + globalTestBus (lazy via ensureGlobalTestSource),
  per-board testLoopTaps; teardown removes taps + source and releases the bus.
- New TestLoopTap (generic bus copy, like HardwareInputPassThrough).
- ShoeGazeError.testBusUnavailable for an exhausted bus pool.
- Test: testLoop boards share the source via taps; removal leaves others intact.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 14:43:50 -07:00
josh 5a07a6d4b4 Add input gain stage to Compressor pedal
A pre-compression input gain knob (Input, dB, range [-12, +24], default 0)
boosts/cuts the signal before it hits the compressor, so driving the input
harder pushes more of the signal past the threshold. The dB value is converted
to a linear multiplier via Exp(dB * ln(10)/20) and applied to the dry signal.

Tests: knob list is [Input, Threshold, Ratio]; input gain changes the output.
The preset recall test now finds the Threshold knob by label, not position.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 12:32:32 -07:00
josh 475dd392e6 Fix iOS Load file picker not opening
Five presentation modifiers (.sheet, .alert, two .fileImporter, .fileExporter)
were stacked on the builder's root view. SwiftUI reliably drives only one
presentation per view node, so adding the Boards .sheet swallowed the iOS rig
Load importer — the Load button toggled its flag but no picker appeared. Move
each presentation onto its own Color.clear background anchor so they no longer
collide.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-24 08:07:37 -07:00
josh dff58175f1 Label delay decay knob 'Decay Time'
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:56:04 -07:00
josh 42268b65a1 Relabel delay Feedback knob as Decay
The Delay, Feedback Delay, and Ping-Pong knobs labelled 'Feedback' actually
drive DelayLineFeedback's decayTime (seconds to -60 dB), not a feedback gain —
the engine clamps the internal feedback coefficient below 1, so the control
can never grow/self-oscillate. Relabel to 'Decay' so the knob reads honestly.
Phaser's feedback is a real coefficient and is unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:40:45 -07:00
josh 2c36de5c0d Widen gap between knobs in short pedal rows
Centred one- and two-knob rows now use a wider, touch-friendly inter-knob gap;
full three-knob rows keep the tight spacing so they still fit the enclosure.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:29:25 -07:00
josh f19dc2c1b3 Centre pedal knob rows
Short knob rows (one or two knobs) now sit centred in the enclosure instead of
left-aligned, via symmetric spacers around each row. Shared PedalView, so it
applies on macOS and iOS.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:26:54 -07:00
josh 6ad813601f Review fixes: reindex activeBoardIndex; safer live-input rebuild
- moveBoard/removeBoard now keep activeBoardIndex pointing at the soloed board
  (track by identity on move; shift down or clear on remove), so the Solo
  highlight no longer lights the wrong cell after reorder or delete.
- rebuildWithLiveInput snapshots the rig before any teardown and aborts if the
  snapshot fails, instead of tearing down then seeding a fallback (no silent
  rig loss). The engine-already-has-input early return now also persists the
  live-input selection, via a shared selectLiveInputAndPersist helper.
- Test: activeBoardIndex tracks reorder and removal.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:22:44 -07:00
josh 652a5a76ca Default iOS builder to one input channel
Construct the iOS engine with one input channel by default so live input is
available immediately and the In: stepper reads 1. Trade-off: iOS prompts for
microphone access at the first Start even while input defaults to test loop.
The permission-gated enableLiveInput() rebuild stays in place for any future
input-less configuration.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 21:10:13 -07:00
josh 9b31be7921 Resync EngineConfigView channel/rate fields on engine rebuild
EngineConfigView seeds its pending In/Out/Rate fields from @State(initialValue:),
which runs only once. After the iOS live-input rebuild swaps in a new engine
with one input channel, the stepper kept showing In: 0 even though audio read
the input. Resync the pending fields in a .task keyed on the engine's object
identity so a rebuilt engine's actual counts are reflected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:57:34 -07:00
josh 705b4ed534 iOS live input via permission-gated engine rebuild
Live input on iOS needs an input channel, but constructing the engine with one
up-front makes iOS prompt for the microphone at the first Start even in
test-loop mode. Instead the engine starts input-less (no prompt) and is rebuilt
on demand:

- ShoeGazeBuilderView gains an optional onEnableLiveInput hook. When the user
  picks live input but the engine has no input channel, the picker offers a
  "Live Input" option that calls the hook; the input binding routes there too.
  On macOS (engine already has an input channel) the hook is nil and live input
  is selected directly.
- The iOS app model implements the hook: request mic access, then on grant
  snapshot the rig (rigData), stop + teardown the engine, rebuild it with one
  input channel, restore the rig (loadRig), and select live input. The new
  ShoeGaze is published so the @Observable host view re-binds.
- Input persistence restores live on relaunch: a saved live choice with the mic
  already authorised triggers the same rebuild silently (no prompt).

Test: a rig captured on a 0-input engine restores onto a freshly built 1-input
engine and live input is then selectable.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:52:11 -07:00
josh 4627b3b800 Boards sheet, ⌘1–9 switching, unified player bar, input persistence
Boards sheet (BoardsSheetView): rename, drag-reorder, swipe-delete, plus
per-board enable/solo/level and a Solo/Blend + crossfade header. Opened from a
"Boards…" button in the builder; presented with medium/large detents on iOS.
Makes ShoeGaze.moveBoard public to back the reorder.

Keyboard switching: hidden ⌘1…⌘9 buttons in the builder solo (live-switch to)
the matching board and select it as the edit target.

Unified player: ShoeGazeView drops its bespoke Active picker + crossfade field
and hosts the shared BoardBarView, matching the builder.

Input persistence: the builder saves the input choice (test loop vs live
channel) to UserDefaults and restores it on appear. With no saved choice it
defaults to live input when the mic is already authorised and an input channel
exists, else stays on the test loop. The iOS builder now opens one input
channel so live input is actually available there.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 20:38:43 -07:00
josh c25d783b71 Lock iOS builder + demo to iPad-only landscape
The board bar and scope/CPU layout already flow to iOS via the shared
ShoeGazeBuilderView. Restrict both iOS apps to iPad (TARGETED_DEVICE_FAMILY=2),
landscape-only orientations, and UIRequiresFullScreen so the wide builder
layout always has the room it needs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 17:25:16 -07:00
josh b4b2f58762 Compact board mixer bar; align scope/CPU to palette width
Shrink BoardBarView to a fixed-height single horizontal scroll group with a
tighter two-row control column, so it wraps its elements and frees vertical
canvas for the pedals. Constrain the scope and CPU-meter views to the pedal
palette width, left-aligned, so they sit under the palette column.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 17:14:04 -07:00
josh c0605d295d Add board mixer bar UI + independent per-board audibility API
Multi-board playback was all-or-one: selectBoard soloed exclusively,
selectAllBoards summed. There was no way to play an arbitrary subset, and
the builder only exposed a dropdown that picked which board to *edit*.

ShoeGaze API:
- setBoard(_:audible:crossfadeSeconds:) toggles one board's select-gain in
  place without disturbing the others (Blend mixing); clears activeBoardIndex.
- soloBoard(_:crossfadeSeconds:) — the "Solo" verb (wraps selectBoard).
- isBoardAudible(_:) reports a board's live select-gain target.

UI — BoardBarView (shared macOS/iOS):
- Horizontal board-mixer strip. Each board is a channel cell: audible LED,
  Solo button, and a master-gain fader. Tapping a cell name sets the edit
  target (independent of what's audible); context menu silences/deletes.
- Solo | Blend mode switch + an All button + a crossfade slider.
- Replaces the builder's board dropdown and Add Board button; the cell's +
  adds a board.

Tests: solo/blend/all audibility transitions and activeBoardIndex tracking;
setBoard no-op for a board owned by another manager.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 16:51:17 -07:00
236 changed files with 23189 additions and 2679 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
+170
View File
@@ -0,0 +1,170 @@
# Changelog
All notable changes to ShoeGaze are recorded here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[semantic versioning](https://semver.org/spec/v2.0.0.html).
## [2.1.1] — 2026-07-12
A quieter, more predictable startup. The input feeding the pedals now has its own
mute — separate from the rig-output mute — that arms every time you start the engine,
so nothing squeals the instant it spins up. New rigs open listening to In 0 instead of
the test-loop phrase, and your input choice and I/O channel counts now travel with the
rig (and iCloud) instead of a separate local setting.
### Added
- **Input mute.** A hard kill-switch on the incoming guitar / mic signal, distinct from
the rig-output mute. It arms automatically every time you press Start (so a fresh
engine is silent until you're ready), sits next to the Start/Stop transport with a
pulsing red glow while active, and is MIDI-mappable (footswitch or key), like Rig Mute.
### Changed
- **New rigs open on In 0** (live input) instead of the built-in test-loop phrase.
- **Input & I/O persist with the rig.** The input selection and the engine's input /
output channel counts are stored in the rig (and sync via iCloud), and are reapplied
on launch — so a multi-channel setup and a chosen input channel survive a restart
instead of reverting to the defaults. Replaces the previous local-only input setting.
- The docked (macOS) transport shows the Bypass / Mute / Input toggles as icons so the
row no longer crowds the sample-rate and channel controls.
### Fixed
- A muted input is now **exactly** silent from the first sample — no brief start-up
transient when the engine begins rendering.
- iOS: the app declares in-place document support, clearing a launch-time console warning.
### Compatibility
Additive: rigs saved before this release load unchanged (input defaults to In 0, or the
test loop when no live input is available), and 2.1.1 rigs still open in older builds —
the input-mute state isn't persisted and the extra I/O fields are ignored there.
## [2.1.0] — 2026-07-10
Tempo comes to the pedals. Delay times and modulation rates can lock to a note
division of the live tempo — a quarter-note delay, a dotted-eighth, an eighth-triplet
LFO — shown with real music-notation glyphs and following the tempo as it changes.
Delays reach further, the BPM is directly editable, and every mappable control shows
its MIDI / key binding right on the pedal.
### Added
- **Tempo-synced pedal parameters.** Lock a delay time or a modulation rate to a note
division — whole down to sixteenth, including dotted and triplet values — and it is
derived from the shared tempo, following tap tempo, the stepper, the BPM field, and
MIDI. Delay time on Delay, Feedback Delay, Ping-Pong, Reverse Delay, and each of
Multi-Tap's three taps; LFO rate on Tremolo, Vibrato, Chorus, Flanger, Phaser, and
Modulation. A MIDI CC bound to a synced parameter is ignored while it stays synced
(the tempo drives the value) and resumes control once the parameter is set to Free.
- **Note-value glyphs.** The division picker uses drawn music-notation glyphs —
noteheads, stems, flags, an augmentation dot for dotted values, and a bracketed "3"
over triplets — instead of text labels.
- **Editable BPM.** The tempo readout is now a text field: type a tempo directly
(integer only, clamped to 30–300 BPM). The stepper and tap tempo still work, and a
synced pedal follows a typed change immediately.
- **In-context control mapping.** Each pedal draws a small badge on every mappable
control showing its binding source — Program Change footswitch (PC), Control Change
expression (CC), or letter Key (KEY) — with a legend above the board. Completes the
computer-keyboard control mapping.
### Changed
- **Longer delays.** Maximum delay time raised to 5 seconds across the delay pedals
(previously 1–2 s), so tempo-synced values at slow tempos (whole and half notes) fit.
- Note divisions that would exceed a parameter's range at the current tempo are shown
disabled in the picker, and an active sync that has to clamp shows a warning marker.
### Compatibility
Additive: rigs saved before this release load unchanged (every parameter defaults to
"free"), and 2.1 rigs still open in older builds — the tempo-sync state is simply
ignored there.
## [2.0.0] — 2026-07-05
Major release. Performance-focused: a visual metronome, a real rig mute with
keyboard control, and rigs that remember their tempo, input, and I/O — plus a
saveable set-list order for hands-free switching between rigs live. The version
jumps to 2.0.0 to align ShoeGaze's numbering with the wider project family.
### Added
- **Visual metronome tempo indicator.** A horizontal playhead sweeps wall-to-wall
once per beat with pendulum easing (it slows into each beat so you can anticipate
it), fades toward center, and flashes a glow on the downbeat. Replaces the single
flashing LED.
- **Rig Mute (⌘Z).** A hard gate that silences the entire rig output — distinct from
Bypass Rig, which passes your dry signal through. Reachable from the header, the
per-board volume row, the macOS Board menu, and MIDI.
- **Keyboard shortcuts** (macOS native menus + iOS/iPadOS hardware keyboards):
- `⌘1`–`⌘9` — switch to / solo boards 1–9.
- `⌘⇧1`–`⌘⇧9` and `⌘⇧0` — load set-list rigs 1–10 in library order.
- `⌘Z` — toggle rig mute.
All are listed in the in-app Help.
- **macOS menus.** Board ▸ Mute Rig and Board ▸ Bypass Rig (with live state), and a
Rigs ▸ Set List submenu whose ten slots map to `⌘⇧1`–`⌘⇧0` and track the current
library order.
- **Set-list ordering.** Reorder rigs in the picker by dragging a row or via each
rig's Move Up / Move Down menu. The order is saved and travels with an exported
archive; the top ten map to the `⌘⇧` shortcuts.
- **Per-rig persistence.** A saved rig now also stores its tempo (BPM + enabled
state) and input selection. Engine input/output channel counts are saved too, and
applied on demand via `applyChannelLayout(from:)` rather than forced on every load.
### Changed
- The header "Mute rig" toggle — which actually only set the tuner-mutes-rig
preference — is now a real rig-mute button. The tuner preference is relabeled
**"Mute while tuning"**.
- The rig library now honors a manual set-list order instead of sorting by name/date.
New rigs append to the end; renaming a rig keeps its position.
### Fixed
- Importing a rig archive into a non-empty library no longer collides set-list
positions with existing rigs — imported rigs append in archive order.
### Removed
- The **ShoeGazeDemo** (macOS) and **ShoeGazeiOSDemo** (iOS) minimal-player apps and
their Xcode projects. Only the full **ShoeGazeBuilder** (macOS) and
**ShoeGazeBuilderiOS** (iPad) apps remain.
### Compatibility
- Despite the major-version bump, rig persistence is backward-compatible: the new
tempo / input / I/O / set-list fields are additive and optional. Rigs saved by
earlier versions load unchanged (missing fields are ignored), and rigs saved by
2.0.0 still open in older builds (the new keys are ignored there). The 2.0.0 bump
reflects the scope of new features and version alignment, not a format break.
## [1.5.0] — 2026-07-04
- Looper pedal, iPad/iOS layout rework, Lyrebird 1.2.3.
## [1.4.0] — 2026-07-01
- Maintenance and refinements.
## [1.3.0] — 2026-06-28
- Rig / board sharing via the `.shoegaze` document type.
## [1.2.0] — 2026-06-28
- Ten new pedals, iCloud rig library, builder UI rework.
## [1.1.1] — 2026-06-26
- Info-button placement and region-lane drag-drop fix.
## [1.1.0] — 2026-06-26
- Refinements over the initial release.
## [1.0.0] — 2026-06-24
- Initial ShoeGaze release.
+64
View File
@@ -0,0 +1,64 @@
# ShoeGaze — Claude Context
A virtual guitar-pedalboard framework built on Lyrebird. Two products:
`LyrebirdShoeGaze` (core pedal/board framework, no SwiftUI) and `LyrebirdShoeGazeUI`
(SwiftUI views). Depends on the published Lyrebird package.
## Conventions
- **MIT SPDX header** on every new `.swift` file (first 5 lines): file name, `// Lyrebird`,
blank comment, `// Copyright (c) 2026 Joshua Parmenter / realizedsound`,
`// SPDX-License-Identifier: MIT`, then a blank line.
- **Explicit type annotations** on `let`/`var` bindings, named constants for non-trivial
literals, doc comments on public init params — matches the Lyrebird house style.
- Pedals subclass `Pedal` (in `Sources/LyrebirdShoeGaze/Pedals/`), expose parameters as
`@UIParam`, and surface them via `effectKnobs` / `effectSwitches` / `effectSliders`.
- A pedal's `displayName` **is** its serialization key and its `PedalType.rawValue`, and the
`PedalRegistry.builtIn` key. Keep all three identical when adding a pedal.
## Adding a new pedal — required checklist
1. `Sources/LyrebirdShoeGaze/Pedals/<Name>Pedal.swift` — subclass `Pedal`, override `effect`
(or `wideEffect`/`stereoEffect`), `effectKnobs`/`effectSwitches`/`effectSliders`.
2. **`summary`** — override `open var summary: String` with a one-line, user-facing
description. **This is mandatory for every pedal** (see "Pedal info" below).
3. Register in `PedalRegistry.builtIn["<DisplayName>"]`.
4. Add `PedalType.<name> = PedalType("<DisplayName>")`.
5. Enclosure color case in `PedalView.enclosureColor(for:)`.
6. Add to `PedalPaletteView.preferredOrder`.
7. Tests in `Tests/LyrebirdShoeGazeTests/<Name>PedalTests.swift` — at minimum: builds +
non-silent, each effect parameter measurably changes the output, knob-list assertion,
and (if it has switches/sliders) a preset round-trip.
8. Use `PedalType` static members at call sites (`appendPedal(.overdrive, to:)`), never raw
strings, except where a string is inherently dynamic (registry / preset load).
## Pedal info (mandatory)
Every pedal participates in the pedal-info UI:
- **`summary`** (required): a short, non-proprietary, user-facing sentence describing what
the pedal does. The picker shows it as a subtitle; the pedal's ⓘ info panel shows it as
the description. A new pedal without a non-empty `summary` is incomplete — a test asserts
every registered pedal has one.
- The info panel lists the **effect controls only** (`effectKnobs` + `effectSliders` +
`effectSwitches`) with their ranges/options — never the common Mix / Level / bypass. Put
the meaningful range and a clear unit in each control's `label`/`range` so the info panel
reads well.
## dB parameters
There is no dB→linear generator for a control-rate node. To apply a dB gain to a signal,
convert in the graph: `Exp.Audio($gainDB * dbToLinExpScale)` where
`dbToLinExpScale = ln(10)/20 ≈ 0.11512925464970229` (gives `10^(dB/20)`). RBJ shelving/peaking
filters take gain in dB directly, so pass dB nodes straight through.
## Build / test
- Package: `swift build` / `swift test --no-parallel` (the multi-engine suite can hit
Lyrebird's parallel-teardown flake without `--no-parallel`).
- Apps: `Demo/ShoeGaze.xcworkspace` (macOS builder, iPad builder, demos). iOS targets are
iPad-only, landscape.
## Planned work
`docs/plans/` holds the next-version feature plans.
@@ -163,7 +163,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 10;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
@@ -176,7 +176,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 0.9;
MARKETING_VERSION = 2.1.1;
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 = 1;
CURRENT_PROJECT_VERSION = 10;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
@@ -206,7 +206,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 0.9;
MARKETING_VERSION = 2.1.1;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
"version" : "1.2.3"
}
},
{
+289 -35
View File
@@ -20,7 +20,7 @@ import LyrebirdShoeGazeUI
/// The engine is **not** started automatically; the user clicks Start in the builder's toolbar.
/// On termination the engine is stopped to release Core Audio resources cleanly.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
// MARK: - Engine configuration constants
@@ -46,7 +46,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private static let heightFraction: CGFloat = 0.88
/// The default pedal the seed board comes up with, so audio is audible immediately on Start.
private static let seedPedalType: String = "Overdrive"
private static let seedPedalType: PedalType = .overdrive
// MARK: - Owned objects
@@ -55,16 +55,48 @@ 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"
/// Rig-mute toggle item, retained so `validateMenuItem(_:)` can flip its title + checkmark to
/// match the current mute state (which may also change from the UI, MIDI, or the tuner).
private var muteMenuItem: NSMenuItem?
/// Rig-bypass toggle item, retained so `validateMenuItem(_:)` can flip its title + checkmark to
/// match the current bypass state (which may also change from the UI or MIDI).
private var bypassMenuItem: NSMenuItem?
/// The Rigs ▸ Set List submenu, retained so its item titles can be refreshed to the current
/// library order each time it opens (via `menuNeedsUpdate(_:)`).
private var setListMenu: NSMenu?
/// The ten fixed ⌘⇧1…⌘⇧0 set-list items (tags 0…9). Their key equivalents fire whether or not
/// the menu is open; `validateMenuItem(_:)` disables slots with no rig, and `menuNeedsUpdate`
/// refreshes their titles to the rig names.
private var setListMenuItems: [NSMenuItem] = []
/// Number of set-list slots exposed as ⌘⇧1…⌘⇧0.
private static let setListSlotCount: Int = 10
/// 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
override init() {
let coreDriver: CoreAudioDriver = CoreAudioDriver()
// The engine is built with the default layout; the autosaved rig's saved I/O layout (if any)
// is applied by `RigStore.restore` below, so a multi-channel setup survives relaunch.
let engine: SynthesisEngine = SynthesisEngine(
blockSize: AppDelegate.blockSize,
sampleRate: AppDelegate.sampleRate,
@@ -73,26 +105,40 @@ 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()
seedInitialBoard()
// 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) {
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) {
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio,
// so the app comes up listening to the instrument. A restored rig keeps its own saved input.
if shoeGaze.engine.numInputChannels > 0 {
shoeGaze.inputSource = .liveInput(channel: 0)
}
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
created = board
try shoeGaze.appendPedal(type: AppDelegate.seedPedalType, to: board)
try shoeGaze.appendPedal(AppDelegate.seedPedalType, to: board)
} catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilder] seed board failed: \(error)")
@@ -103,12 +149,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
@@ -133,10 +196,69 @@ 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()
}
func applicationDidResignActive(_ notification: Notification) {
// Persist on every deactivation too, so state survives an unexpected exit.
RigStore.save(shoeGaze)
}
// MARK: - Main menu
/// Builds a minimal menu bar: an application menu with About / Hide / Quit (⌘Q).
@@ -171,8 +293,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()
@@ -182,6 +310,51 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// Engine start/stop lives in the in-window EngineConfigView (with sample-rate/channel
// config and the mismatch alert), so the Board menu only adds boards.
addItem(to: boardMenu, title: "Add Board", action: #selector(addBoardAction(_:)), key: "b")
boardMenu.addItem(NSMenuItem.separator())
// ⌘Z toggles rig mute (a hard silence of all output; distinct from Bypass Rig's dry
// passthrough). Owns the ⌘Z key equivalent on macOS; the in-window view binds it on iOS.
self.muteMenuItem = addItem(
to: boardMenu,
title: "Mute Rig",
action: #selector(toggleMuteAction(_:)),
key: "z"
)
// Bypass Rig routes every board to its dry input (pedals skipped) — distinct from Mute's
// hard silence. No key equivalent: ⌘B is Add Board, and Bypass has a prominent on-screen button.
self.bypassMenuItem = addItem(
to: boardMenu,
title: "Bypass Rig",
action: #selector(toggleBypassAction(_:)),
key: ""
)
// Rigs menu — a Set List of the top ten library rigs, each on ⌘⇧1…⌘⇧0. The items are
// fixed; their titles refresh to the current library order on open, and their key
// equivalents fire whether or not the menu is showing.
let rigsMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(rigsMenuItem)
let rigsMenu: NSMenu = NSMenu(title: "Rigs")
rigsMenuItem.submenu = rigsMenu
let setListItem: NSMenuItem = NSMenuItem(title: "Set List", action: nil, keyEquivalent: "")
rigsMenu.addItem(setListItem)
let setListSubmenu: NSMenu = NSMenu(title: "Set List")
setListSubmenu.delegate = self
setListItem.submenu = setListSubmenu
for slot: Int in 0 ..< AppDelegate.setListSlotCount {
// Slots 0…8 → ⌘⇧1…⌘⇧9; slot 9 → ⌘⇧0 (matches the physical number row).
let key: String = slot < 9 ? "\(slot + 1)" : "0"
let item: NSMenuItem = NSMenuItem(
title: "\(slot + 1). —",
action: #selector(loadRigSlotAction(_:)),
keyEquivalent: key
)
item.keyEquivalentModifierMask = [.command, .shift]
item.target = self
item.tag = slot
setListSubmenu.addItem(item)
setListMenuItems.append(item)
}
self.setListMenu = setListSubmenu
// Record menu — choose an output folder, then toggle recording.
let recordMenuItem: NSMenuItem = NSMenuItem()
@@ -202,6 +375,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
}
@@ -221,37 +401,78 @@ 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)")
}
}
}
@objc private func toggleMuteAction(_ sender: Any?) {
shoeGaze.toggleRigMuted()
// Reflect the new state immediately, not only on the next menu-open validation.
muteMenuItem?.title = shoeGaze.rigMuted ? "Unmute Rig" : "Mute Rig"
muteMenuItem?.state = shoeGaze.rigMuted ? .on : .off
}
@objc private func toggleBypassAction(_ sender: Any?) {
shoeGaze.toggleRigBypassed()
bypassMenuItem?.title = shoeGaze.rigBypassed ? "Re-engage Rig" : "Bypass Rig"
bypassMenuItem?.state = shoeGaze.rigBypassed ? .on : .off
}
/// Loads the set-list rig at the sender's slot tag. Forwards to the in-window builder (which
/// owns the current-rig state, the unsaved-changes prompt, and engine lifecycle) via notification.
@objc private func loadRigSlotAction(_ sender: NSMenuItem) {
NotificationCenter.default.post(name: .shoeGazeLoadRigSlot, object: sender.tag)
}
@objc private func addBoardAction(_ sender: Any?) {
var created: PedalBoard?
do {
@@ -291,12 +512,45 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
recordMenuItem?.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording"
}
// MARK: - NSMenuDelegate
/// Refreshes the Set List item titles to the current library order each time the submenu opens.
/// Key equivalents fire independently of this (see `setListMenuItems`); this is display only.
func menuNeedsUpdate(_ menu: NSMenu) {
guard menu === setListMenu else { return }
let entries: [RigEntry] = library.entries
for item: NSMenuItem in setListMenuItems {
let slot: Int = item.tag
if slot < entries.count {
item.title = "\(slot + 1). \(entries[slot].name)"
} else {
item.title = "\(slot + 1). —"
}
}
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem == recordMenuItem {
menuItem.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording"
// Can always stop; can only start once a folder has been chosen.
return shoeGaze.isRecording || shoeGaze.recordingFolder != nil
}
if menuItem == muteMenuItem {
// Mute may have changed from the UI, MIDI, or the tuner — resync title + checkmark.
menuItem.title = shoeGaze.rigMuted ? "Unmute Rig" : "Mute Rig"
menuItem.state = shoeGaze.rigMuted ? .on : .off
return true
}
if menuItem == bypassMenuItem {
// Bypass may have changed from the UI or MIDI — resync title + checkmark.
menuItem.title = shoeGaze.rigBypassed ? "Re-engage Rig" : "Bypass Rig"
menuItem.state = shoeGaze.rigBypassed ? .on : .off
return true
}
if setListMenuItems.contains(menuItem) {
// A slot is live only when the library actually holds a rig at that position.
return menuItem.tag < library.entries.count
}
return true
}
}
+53 -2
View File
@@ -2,6 +2,21 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<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>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -13,9 +28,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<string>2.1.2</string>
<key>CFBundleVersion</key>
<string>1</string>
<string>10</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.music</string>
<key>LSMinimumSystemVersion</key>
@@ -28,5 +43,41 @@
<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>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<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 = 7;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
@@ -169,13 +172,14 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 2.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 2;
};
name = Debug;
};
@@ -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 = 7;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
@@ -194,13 +201,14 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 2.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
TARGETED_DEVICE_FAMILY = 2;
};
name = Release;
};
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
"version" : "1.2.3"
}
},
{
@@ -31,7 +31,7 @@
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
+59 -4
View File
@@ -2,6 +2,25 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<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>
<!-- Incoming .shoegaze files are read and imported into the rig library (a copy), never
edited in place, so the app opens a copy rather than the original document. -->
<key>LSSupportsOpeningDocumentsInPlace</key>
<false/>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -13,7 +32,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>
@@ -22,6 +41,18 @@
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
<key>NSMicrophoneUsageDescription</key>
<string>ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</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>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
@@ -29,18 +60,42 @@
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<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>
@@ -13,24 +13,32 @@ import LyrebirdShoeGazeUI
/// lifetime of the app. The audio engine is **not** started automatically — the user presses
/// Start in ``ShoeGazeBuilderView``. The engine is stopped when the view disappears.
///
/// ``ShoeGazeBuilderView`` manages its own scroll regions (palette + builder), so it is hosted
/// directly rather than wrapped in an outer `ScrollView`.
/// ``ShoeGazeBuilderView`` draws its own header/title and manages its own scroll regions (palette
/// + board canvas), so it is hosted directly — no `NavigationStack`, title, or outer `ScrollView`.
/// A fill frame keeps it pinned to the full window so portrait isn't vertically centered.
@main
struct ShoeGazeBuilderiOSApp: App {
@State private var model: ShoeGazeBuilderiOSAppModel = ShoeGazeBuilderiOSAppModel()
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
NavigationStack {
ShoeGazeBuilderView(
shoeGaze: model.shoeGaze,
hardwareSampleRate: { model.hardwareSampleRate }
)
.navigationTitle("ShoeGaze Builder")
.navigationBarTitleDisplayMode(.inline)
}
.onDisappear { model.stop() }
ShoeGazeBuilderView(
shoeGaze: model.shoeGaze,
library: model.library,
hardwareSampleRate: { model.hardwareSampleRate },
onEnableLiveInput: { model.enableLiveInput() },
midi: model.midi
)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.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.
if phase != .active { model.save() }
}
}
}
@@ -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.
///
@@ -24,23 +25,102 @@ final class ShoeGazeBuilderiOSAppModel {
private static let blockSize: Int = 512
private static let outputChannels: Int = 2
// Default to one input channel so live input is available immediately. The trade-off is
// that the iOS driver runs a `.playAndRecord` session with the RemoteIO input element
// enabled, so iOS prompts for microphone access at the first Start even while the input
// still defaults to `.testLoop`. (The permission-gated `enableLiveInput()` rebuild remains
// available for any future build that starts input-less.)
private static let inputChannels: Int = 1
private static let numAudioBuses: Int = 256
private static let seedPedalType: String = "Overdrive"
private static let seedPedalType: PedalType = .overdrive
// MARK: - Owned objects
/// The active ShoeGaze builder session.
/// The active ShoeGaze builder session. Swapped out when live input is enabled (the engine
/// is rebuilt with an input channel); the `@Observable` change re-binds the hosting view.
private(set) var shoeGaze: ShoeGaze
private let engine: SynthesisEngine
private let iosDriver: iOSAudioDriver
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 = shoeGaze
// 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) {
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
/// Activates the play-and-record audio session once. Idempotent; safe to call before each
/// engine build. Activating the session does not by itself prompt for microphone access —
/// the prompt only fires when an input-enabled engine first starts.
private static func configureAudioSession() {
let session: AVAudioSession = AVAudioSession.sharedInstance()
do {
try session.setCategory(.playAndRecord,
@@ -48,31 +128,120 @@ final class ShoeGazeBuilderiOSAppModel {
options: [.defaultToSpeaker, .allowBluetoothHFP])
try session.setActive(true)
} catch {
// Surface the failure: the engine is built from `session.sampleRate` below, which may
// report a stale/default rate if activation failed.
print("[ShoeGazeBuilderiOS] AVAudioSession setup failed: \(error)")
}
let sampleRate: Double = session.sampleRate
}
/// Builds a fresh engine + driver + empty `ShoeGaze` with the given input-channel count.
private static func buildEngine(
inputChannels: Int
) -> (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) {
let sampleRate: Double = AVAudioSession.sharedInstance().sampleRate
let driver: iOSAudioDriver = iOSAudioDriver()
let eng: SynthesisEngine = SynthesisEngine(
// The engine is built with the default layout; the autosaved rig's saved I/O (if any) is
// applied by `RigStore.restore`, so an output change survives relaunch.
let engine: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeBuilderiOSAppModel.blockSize,
sampleRate: sampleRate,
numOutputChannels: ShoeGazeBuilderiOSAppModel.outputChannels,
numInputChannels: 0,
numInputChannels: inputChannels,
numAudioBuses: ShoeGazeBuilderiOSAppModel.numAudioBuses,
driver: driver
)
self.iosDriver = driver
self.engine = eng
self.shoeGaze = ShoeGaze(engine: eng)
return (engine, driver, ShoeGaze(engine: engine))
}
// MARK: - Live input
/// Enables live input on iOS: requests microphone access, then (on grant) rebuilds the
/// engine with one input channel — preserving the current rig — and selects live input.
///
/// The rebuild is required because the input-channel count is fixed at engine construction,
/// and constructing with an input channel up-front would make iOS prompt for the microphone
/// at the first Start even in test-loop mode. Gating the rebuild behind an explicit request
/// keeps the prompt where the user expects it.
func enableLiveInput() {
MicrophonePermission.request { [weak self] granted in
guard let self, granted else { return }
self.rebuildWithLiveInput()
}
}
/// Snapshots the rig, rebuilds the engine with one input channel, restores the rig, and
/// selects live input on channel 0. No-op if the engine already has an input channel.
private func rebuildWithLiveInput() {
guard engine.numInputChannels == 0 else {
// Engine already has an input channel: just select live input, no rebuild.
selectLiveInputAndPersist()
return
}
let wasRunning: Bool = engine.isRunning
// Snapshot the rig BEFORE any teardown. If this fails, abort the rebuild rather than
// tear the engine down and lose the rig — the user stays on the current engine.
let snapshot: Data
do {
snapshot = try shoeGaze.rigData()
} catch {
print("[ShoeGazeBuilderiOS] rig snapshot failed; aborting live-input rebuild: \(error)")
return
}
engine.stop()
shoeGaze.teardown()
ShoeGazeBuilderiOSAppModel.configureAudioSession()
let rebuilt: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) =
ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: 1)
self.engine = rebuilt.engine
self.iosDriver = rebuilt.driver
self.shoeGaze = rebuilt.shoeGaze
do {
// Teardown already happened, so a restore failure can only recover by seeding.
try shoeGaze.loadRig(from: snapshot)
} catch {
print("[ShoeGazeBuilderiOS] rig restore after rebuild failed: \(error)")
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() }
}
/// Selects live input on channel 0 and autosaves so the rig (the source of truth for the input
/// selection) records it for restore-on-relaunch.
private func selectLiveInputAndPersist() {
do {
try shoeGaze.setInputSource(.liveInput(channel: 0))
save()
} catch {
print("[ShoeGazeBuilderiOS] selecting live input failed: \(error)")
}
}
/// Seeds a single default board so the rig is never empty after a failed restore.
private static func seedFallbackBoard(into shoeGaze: ShoeGaze) {
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio.
// A restored rig keeps its own saved input selection.
if shoeGaze.engine.numInputChannels > 0 {
shoeGaze.inputSource = .liveInput(channel: 0)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.appendPedal(type: ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
try shoeGaze.appendPedal(ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
} catch {
print("[ShoeGazeBuilderiOS] seed board failed: \(error)")
print("[ShoeGazeBuilderiOS] fallback seed board failed: \(error)")
}
}
-397
View File
@@ -1,397 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
C3B000000000000000000020 /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3B00000000000000000001E /* LyrebirdShoeGaze */; };
C3B000000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B00000000000000000001F /* LyrebirdShoeGazeUI */; };
C3B000000000000000000022 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3B000000000000000000023 /* Lyrebird */; };
C3B000000000000000000024 /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B000000000000000000025 /* LyrebirdUI */; };
C3B000000000000000000031 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000030 /* Assets.xcassets */; };
C3B0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000007 /* main.swift */; };
C3B0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000008 /* AppDelegate.swift */; };
C3B0000000000000000000E /* DemoRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000009 /* DemoRootView.swift */; };
C3B0000000000000000000F /* ShoeGazeDemoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B00000000000000000000A /* ShoeGazeDemoController.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
C3B000000000000000000004 /* ShoeGazeDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
C3B000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C3B000000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
C3B000000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
C3B000000000000000000009 /* DemoRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoRootView.swift; sourceTree = "<group>"; };
C3B00000000000000000000A /* ShoeGazeDemoController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeDemoController.swift; sourceTree = "<group>"; };
C3B000000000000000000030 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
C3B000000000000000000012 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C3B000000000000000000020 /* LyrebirdShoeGaze in Frameworks */,
C3B000000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */,
C3B000000000000000000022 /* Lyrebird in Frameworks */,
C3B000000000000000000024 /* LyrebirdUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
C3B000000000000000000002 = {
isa = PBXGroup;
children = (
C3B000000000000000000005 /* ShoeGazeDemo */,
C3B000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
C3B000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
C3B000000000000000000004 /* ShoeGazeDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
C3B000000000000000000005 /* ShoeGazeDemo */ = {
isa = PBXGroup;
children = (
C3B000000000000000000007 /* main.swift */,
C3B000000000000000000008 /* AppDelegate.swift */,
C3B000000000000000000009 /* DemoRootView.swift */,
C3B00000000000000000000A /* ShoeGazeDemoController.swift */,
C3B000000000000000000030 /* Assets.xcassets */,
C3B000000000000000000006 /* Info.plist */,
);
path = ShoeGazeDemo;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C3B000000000000000000014 /* ShoeGazeDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = C3B000000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeDemo" */;
buildPhases = (
C3B000000000000000000011 /* Sources */,
C3B000000000000000000012 /* Frameworks */,
C3B000000000000000000013 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = ShoeGazeDemo;
packageProductDependencies = (
C3B00000000000000000001E /* LyrebirdShoeGaze */,
C3B00000000000000000001F /* LyrebirdShoeGazeUI */,
C3B000000000000000000023 /* Lyrebird */,
C3B000000000000000000025 /* LyrebirdUI */,
);
productName = ShoeGazeDemo;
productReference = C3B000000000000000000004 /* ShoeGazeDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C3B000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
C3B000000000000000000014 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = C3B000000000000000000018 /* Build configuration list for PBXProject "ShoeGazeDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = C3B000000000000000000002;
packageReferences = (
C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */,
C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */,
);
productRefGroup = C3B000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C3B000000000000000000014 /* ShoeGazeDemo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
C3B000000000000000000013 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3B000000000000000000031 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
C3B000000000000000000011 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3B0000000000000000000C /* main.swift in Sources */,
C3B0000000000000000000D /* AppDelegate.swift in Sources */,
C3B0000000000000000000E /* DemoRootView.swift in Sources */,
C3B0000000000000000000F /* ShoeGazeDemoController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C3B000000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
C3B000000000000000000017 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
C3B000000000000000000019 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
C3B00000000000000000001A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C3B000000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3B000000000000000000016 /* Debug */,
C3B000000000000000000017 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C3B000000000000000000018 /* Build configuration list for PBXProject "ShoeGazeDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3B000000000000000000019 /* Debug */,
C3B00000000000000000001A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCRemoteSwiftPackageReference section */
C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 1.2.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C3B00000000000000000001E /* LyrebirdShoeGaze */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGaze;
};
C3B00000000000000000001F /* LyrebirdShoeGazeUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGazeUI;
};
C3B000000000000000000023 /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = Lyrebird;
};
C3B000000000000000000025 /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = LyrebirdUI;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = C3B000000000000000000001 /* Project object */;
}
@@ -1,78 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
-153
View File
@@ -1,153 +0,0 @@
// AppDelegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Application delegate for the ShoeGaze demo.
///
/// Creates a `SynthesisEngine`, a `ShoeGazeDemoController` (which builds the default
/// `.boards` showcase automatically), and opens a `LyrebirdWindow` hosting `DemoRootView`.
///
/// The engine is **not** started automatically. The user clicks Start in `DemoRootView`'s
/// toolbar (or presses Stop to halt audio). On application termination, `stop()` is called
/// to release Core Audio resources cleanly.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let sampleRate: Double = 48_000.0
private static let outputChannels: Int = 2
// Built-in mics are mono; default to one input channel so live input works out of the box
// (CoreAudio can't satisfy more input channels than the device provides). Raise in the UI.
private static let inputChannels: Int = 1
private static let numAudioBuses: Int = 256
// MARK: - Window geometry constants
private static let windowWidth: CGFloat = 1_100
private static let windowHeight: CGFloat = 640
// MARK: - Owned objects
private let coreDriver: CoreAudioDriver
private let controller: ShoeGazeDemoController
private let window: LyrebirdWindow
/// The Mute menu item, retained so `validateMenuItem(_:)` can update its checkmark.
private var muteMenuItem: NSMenuItem?
// MARK: - Init
override init() {
let coreDriver: CoreAudioDriver = CoreAudioDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: AppDelegate.blockSize,
sampleRate: AppDelegate.sampleRate,
numOutputChannels: AppDelegate.outputChannels,
numInputChannels: AppDelegate.inputChannels,
numAudioBuses: AppDelegate.numAudioBuses,
driver: coreDriver
)
self.coreDriver = coreDriver
self.controller = ShoeGazeDemoController(engine: engine)
self.window = LyrebirdWindow(
title: "ShoeGaze — Lyrebird Guitar Pedalboard",
width: AppDelegate.windowWidth,
height: AppDelegate.windowHeight
)
super.init()
}
// MARK: - NSApplicationDelegate
func applicationDidFinishLaunching(_ notification: Notification) {
installMainMenu()
let demoController: ShoeGazeDemoController = controller
let driver: CoreAudioDriver = coreDriver
window.open {
DemoRootView(controller: demoController, hardwareSampleRate: { driver.deviceSampleRate })
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
controller.stop()
}
// MARK: - Main menu
/// Builds the app's menu bar: an application menu (About / Hide / Quit ⌘Q) and an
/// Audio menu (Mute ⌘M). Standard items route through the responder chain to
/// `NSApplication`; Mute targets this delegate.
private func installMainMenu() {
let appName: String = ProcessInfo.processInfo.processName
let mainMenu: NSMenu = NSMenu()
// Application menu.
let appMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(appMenuItem)
let appMenu: NSMenu = NSMenu()
appMenuItem.submenu = appMenu
appMenu.addItem(
withTitle: "About \(appName)",
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
keyEquivalent: ""
)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(
withTitle: "Hide \(appName)",
action: #selector(NSApplication.hide(_:)),
keyEquivalent: "h"
)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(
withTitle: "Quit \(appName)",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"
)
// Audio menu.
let audioMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(audioMenuItem)
let audioMenu: NSMenu = NSMenu(title: "Audio")
audioMenuItem.submenu = audioMenu
let mute: NSMenuItem = NSMenuItem(
title: "Mute",
action: #selector(toggleMute(_:)),
keyEquivalent: "m"
)
mute.target = self
audioMenu.addItem(mute)
muteMenuItem = mute
NSApplication.shared.mainMenu = mainMenu
}
/// Toggles audio output (mute). Bound to the Audio ▸ Mute menu item (⌘M).
@objc private func toggleMute(_ sender: Any?) {
controller.toggleMute()
}
/// Shows a checkmark on the Mute item while audio is silenced (engine not running).
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem == muteMenuItem {
menuItem.state = controller.isRunning ? .off : .on
}
return true
}
}
#endif
@@ -1,15 +0,0 @@
{
"images" : [
{"size":"16x16","idiom":"mac","filename":"icon_16x16.png","scale":"1x"},
{"size":"16x16","idiom":"mac","filename":"icon_16x16@2x.png","scale":"2x"},
{"size":"32x32","idiom":"mac","filename":"icon_32x32.png","scale":"1x"},
{"size":"32x32","idiom":"mac","filename":"icon_32x32@2x.png","scale":"2x"},
{"size":"128x128","idiom":"mac","filename":"icon_128x128.png","scale":"1x"},
{"size":"128x128","idiom":"mac","filename":"icon_128x128@2x.png","scale":"2x"},
{"size":"256x256","idiom":"mac","filename":"icon_256x256.png","scale":"1x"},
{"size":"256x256","idiom":"mac","filename":"icon_256x256@2x.png","scale":"2x"},
{"size":"512x512","idiom":"mac","filename":"icon_512x512.png","scale":"1x"},
{"size":"512x512","idiom":"mac","filename":"icon_512x512@2x.png","scale":"2x"}
],
"info" : {"author":"xcode","version":1}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 782 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

@@ -1 +0,0 @@
{ "info" : {"author":"xcode","version":1} }
-303
View File
@@ -1,303 +0,0 @@
// DemoRootView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import SwiftUI
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Root view for the ShoeGaze demo window.
///
/// Presents a top toolbar with a mode picker, an input-source toggle, and a Start/Stop
/// transport button, followed by a content area that switches between four showcase
/// modes as the user selects them.
///
/// Because `ShoeGazeDemoController` is `@Observable`, SwiftUI re-renders this view and
/// all its children whenever `controller.mode`, `controller.shoeGaze.boards`,
/// `controller.router`, `controller.parallelSection`, or `controller.isRunning` change —
/// including after a ``ShoeGazeDemoController/rebuild()`` that replaces `shoeGaze`.
///
/// ## Mode showcases
///
/// - `.boards` → `ShoeGazeView` — two boards, eight pedals, master gain per board.
/// - `.editor` → `BoardEditorView` — board + FlowLayout pedal area + version snapshots.
/// - `.parallel` → `ParallelSectionView` — splitter, two branch rows, merger (via board).
/// - `.router` → `ChainRouterView` — dual-board chain router with splitter + master.
/// - `.stereo` → `StereoSplitSectionView` — stereo split with the four route modes.
struct DemoRootView: View {
// MARK: - Layout constants
private static let toolbarSpacing: CGFloat = 10
private static let toolbarPadding: CGFloat = 12
private static let contentPadding: CGFloat = 16
private static let windowMinWidth: CGFloat = 1_100
private static let windowMinHeight: CGFloat = 640
/// Dark stage-floor background (warm almost-black).
private static let backgroundRed: Double = 0.08
private static let backgroundGreen: Double = 0.07
private static let backgroundBlue: Double = 0.06
private static let dividerOpacity: Double = 0.15
// MARK: - Properties
private let controller: ShoeGazeDemoController
private let hardwareSampleRate: () -> Double?
/// Bumped on each transport press so the buttons re-read `controller.isRunning`
/// (which derives from the non-observable engine).
@State private var transportTick: Bool = false
// MARK: - Init
/// Creates the root demo view bound to the given controller.
///
/// - Parameters:
/// - controller: The `ShoeGazeDemoController` that owns the engine, active `ShoeGaze`
/// session, and current mode. All toolbar actions dispatch through this.
/// - hardwareSampleRate: Returns the actual hardware sample rate (or `nil`), for the engine-
/// config mismatch warning. Defaults to `nil`.
init(
controller: ShoeGazeDemoController,
hardwareSampleRate: @escaping () -> Double? = { nil }
) {
self.controller = controller
self.hardwareSampleRate = hardwareSampleRate
}
// MARK: - Body
var body: some View {
VStack(spacing: 0) {
toolbar
Divider()
.overlay(Color.white.opacity(DemoRootView.dividerOpacity))
contentArea
.padding(DemoRootView.contentPadding)
Divider()
.overlay(Color.white.opacity(DemoRootView.dividerOpacity))
ShoeGazeScopeView(shoeGaze: controller.shoeGaze)
.padding(DemoRootView.contentPadding)
}
.frame(
minWidth: DemoRootView.windowMinWidth,
minHeight: DemoRootView.windowMinHeight
)
.background(
Color(
red: DemoRootView.backgroundRed,
green: DemoRootView.backgroundGreen,
blue: DemoRootView.backgroundBlue
)
)
.alert(
"Microphone Access Needed",
isPresented: Binding(
get: { controller.microphoneAccessDenied },
set: { controller.microphoneAccessDenied = $0 }
)
) {
Button("OK", role: .cancel) { }
} message: {
Text("Live input needs microphone access. Enable it in System Settings › Privacy & "
+ "Security › Microphone, then select the input again.")
}
}
// MARK: - Toolbar
/// Top toolbar: mode picker, input-source picker, transport, and CPU meter.
private var toolbar: some View {
HStack(spacing: DemoRootView.toolbarSpacing) {
modePicker
Spacer()
inputSourcePicker
// In Boards mode the pedalboard view (`ShoeGazeView`) supplies its own
// Start/Stop, so the board starts only when its own button is pressed. The
// other modes have no in-content transport, so show it here for them.
if controller.mode != .boards {
transportButtons
}
}
.padding(DemoRootView.toolbarPadding)
}
/// Segmented picker for `DemoMode`.
///
/// The selection binding's setter delegates to `controller.select(_:)` rather than
/// writing a `@State` directly, so the controller handles the mode switch and rebuild.
private var modePicker: some View {
let modeBinding: Binding<DemoMode> = Binding(
get: { controller.mode },
set: { controller.select($0) }
)
return Picker("Mode", selection: modeBinding) {
ForEach(DemoMode.allCases) { demoMode in
Text(demoMode.title).tag(demoMode)
}
}
.pickerStyle(.segmented)
.frame(maxWidth: 380)
.foregroundStyle(Color.white)
}
/// A `Binding<Int>` mapping the input Picker tag to `InputSource`.
///
/// Tag `-1` = `.testLoop`; tags `0 ..< numInputChannels` = `.liveInput(channel:)`.
/// Setting the binding calls `controller.setInputSource(_:)`.
private var inputSourceBinding: Binding<Int> {
Binding(
get: {
switch controller.inputSource {
case .testLoop:
return -1
case .liveInput(let channel):
return channel
}
},
set: { newValue in
if newValue == -1 {
controller.setInputSource(.testLoop)
} else {
controller.setInputSource(.liveInput(channel: newValue))
}
}
)
}
/// Picker listing "Test Loop" and one option per available hardware input channel.
///
/// When `engine.numInputChannels == 0` only "Test Loop" is shown; the live options
/// are omitted so the picker never offers channels that do not exist.
private var inputSourcePicker: some View {
HStack(spacing: DemoRootView.toolbarSpacing) {
Text("Input:")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(0.65))
Picker("Input", selection: inputSourceBinding) {
Text("Test Loop").tag(-1)
ForEach(Array(0..<max(0, controller.engine.numInputChannels)), id: \.self) { channel in
Text("In \(channel)").tag(channel)
}
}
.pickerStyle(.menu)
.foregroundStyle(Color.white)
}
}
/// Engine configuration + transport (sample rate, ins/outs, Start/Stop, mismatch alert).
private var transportButtons: some View {
EngineConfigView(
shoeGaze: controller.shoeGaze,
hardwareSampleRate: hardwareSampleRate,
applyConfig: { rate, inputs, outputs in
try controller.reconfigure(
sampleRate: rate,
inputChannels: inputs,
outputChannels: outputs
)
},
onConfigApplied: { transportTick.toggle() }
)
}
// MARK: - Content area
/// The main content area switches view based on the active mode.
@ViewBuilder
private var contentArea: some View {
switch controller.mode {
case .boards:
ShoeGazeView(shoeGaze: controller.shoeGaze, hardwareSampleRate: hardwareSampleRate)
case .editor:
editorContent
case .parallel:
parallelContent
case .router:
routerContent
case .stereo:
stereoContent
}
}
/// `.editor` content: `BoardEditorView` bound to the first board in the session.
///
/// Shows a placeholder when the board list is unexpectedly empty (e.g. if
/// `buildEditor()` failed silently).
@ViewBuilder
private var editorContent: some View {
if controller.shoeGaze.boards.isEmpty {
Text("No editor board available.")
.foregroundStyle(Color.white.opacity(0.55))
} else {
BoardEditorView(
shoeGaze: controller.shoeGaze,
boardIndex: 0,
versionStore: controller.versionStore
)
}
}
/// `.parallel` content: the full board view (shows pre/post-split pedals) stacked
/// above `ParallelSectionView` which exposes the splitter mode picker and branch rows.
@ViewBuilder
private var parallelContent: some View {
if let section: ParallelSection = controller.parallelSection,
!controller.shoeGaze.boards.isEmpty {
let board: PedalBoard = controller.shoeGaze.boards[0]
ScrollView(.vertical, showsIndicators: true) {
VStack(alignment: .leading, spacing: 20) {
PedalBoardView(board: board)
ParallelSectionView(section: section)
}
}
} else {
Text("Parallel section unavailable.")
.foregroundStyle(Color.white.opacity(0.55))
}
}
/// `.stereo` content: the full board view (shows the pre-split pedal) stacked above a
/// width badge and `StereoSplitSectionView` (route picker + L/R branch rows).
@ViewBuilder
private var stereoContent: some View {
if let section: StereoSplitSection = controller.stereoSection,
let board: PedalBoard = controller.shoeGaze.boards.first {
ScrollView(.vertical, showsIndicators: true) {
VStack(alignment: .leading, spacing: 20) {
HStack(spacing: 10) {
PedalBoardView(board: board)
StereoWidthBadge(width: board.width)
}
StereoSplitSectionView(section: section)
}
}
} else {
Text("Stereo split unavailable.")
.foregroundStyle(Color.white.opacity(0.55))
}
}
/// `.router` content: `ChainRouterView` bound to the live `ChainRouter`.
@ViewBuilder
private var routerContent: some View {
if let chainRouter: ChainRouter = controller.router {
ScrollView(.vertical, showsIndicators: true) {
ChainRouterView(router: chainRouter)
}
} else {
Text("Chain router unavailable.")
.foregroundStyle(Color.white.opacity(0.55))
}
}
}
#endif
-32
View File
@@ -1,32 +0,0 @@
<?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>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.music</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHighResolutionCapable</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
<key>NSMicrophoneUsageDescription</key>
<string>ShoeGazeDemo can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
@@ -1,8 +0,0 @@
<?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.security.device.audio-input</key>
<true/>
</dict>
</plist>
@@ -1,371 +0,0 @@
// ShoeGazeDemoController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Observation
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
// MARK: - DemoMode
/// The active showcase mode displayed in the demo window.
///
/// Each case corresponds to one full-window showcase of a distinct ShoeGaze feature.
/// Switching modes tears down the current audio graph and rebuilds it fresh.
enum DemoMode: String, CaseIterable, Identifiable {
/// Two full boards, each with four pedals (Board 1: Overdrive → Delay → Reverb → Modulation;
/// Board 2: Fuzz → Tremolo → Phaser → Compressor).
case boards = "Boards"
/// A single board inside `BoardEditorView` with preset version snapshots pre-populated.
case editor = "Editor"
/// A single board with a ``ParallelSection`` (Overdrive → split → Delay|Fuzz → merge → Reverb).
case parallel = "Parallel"
/// A ``ChainRouter`` that splits one input across two independent boards (A: Overdrive + Delay;
/// B: Fuzz + Reverb) and recombines them through a shared master stage.
case router = "Router"
/// A board with a ``StereoSplitSection`` (Overdrive → splitStereo(Delay | PingPong) →
/// collectStereo) showcasing the four ``StereoRoute`` modes and stereo output.
case stereo = "Stereo"
var id: String { rawValue }
/// Short human-readable title used in the mode picker.
var title: String {
switch self {
case .boards: return "Boards"
case .editor: return "Editor"
case .parallel: return "Parallel"
case .router: return "Router"
case .stereo: return "Stereo"
}
}
}
// MARK: - ShoeGazeDemoController
/// Main-actor observable controller that owns the engine and active ShoeGaze session.
///
/// A single `ShoeGaze` instance plus optional `router` / `parallelSection` hold the
/// current showcase. Switching modes via ``select(_:)`` or changing the input source via
/// ``setInputSource(_:)`` calls ``rebuild()`` which:
///
/// 1. Stops the engine if it is running.
/// 2. Calls `shoeGaze.teardown()` to remove all nodes and release all buses.
/// 3. Replaces `shoeGaze` with a fresh instance.
/// 4. Builds the new mode-specific graph.
/// 5. Restarts the engine if it was running before the rebuild.
///
/// This guarantees the engine never holds stale references across mode switches.
@MainActor
@Observable
final class ShoeGazeDemoController {
// MARK: - Public state
/// The synthesis engine. Callers must not call `engine.start()` or `engine.stop()`
/// directly — use ``start()`` and ``stop()`` so `isRunning` stays consistent.
let engine: SynthesisEngine
/// The active ShoeGaze session. Replaced on every ``rebuild()`` call.
private(set) var shoeGaze: ShoeGaze
/// Non-nil only in `.router` mode, after ``buildRouter()`` succeeds.
private(set) var router: ChainRouter?
/// Non-nil only in `.parallel` mode, after ``buildParallel()`` succeeds.
private(set) var parallelSection: ParallelSection?
/// Non-nil only in `.stereo` mode, after ``buildStereo()`` succeeds.
private(set) var stereoSection: StereoSplitSection?
/// Stores named board snapshots for the `.editor` showcase.
let versionStore: BoardVersionStore = BoardVersionStore()
/// Currently selected showcase mode.
private(set) var mode: DemoMode = .boards
/// Current input source policy.
private(set) var inputSource: InputSource = .testLoop
/// `true` while the engine is running. Derived from the engine (the single source
/// of truth) so it stays correct regardless of which control starts/stops it.
var isRunning: Bool { engine.isRunning }
// MARK: - Init
/// Creates a controller, builds the default `.boards` showcase, and does NOT start the engine.
///
/// - Parameter engine: A pre-configured `SynthesisEngine` owned by the caller. The
/// engine must not be running when this initialiser is called.
init(engine: SynthesisEngine) {
self.engine = engine
self.shoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
buildBoards()
}
// MARK: - Mode selection
/// Switches to the given mode if different from the current one, triggering a full rebuild.
///
/// - Parameter newMode: The showcase to activate.
func select(_ newMode: DemoMode) {
guard newMode != mode else { return }
mode = newMode
rebuild()
}
// MARK: - Input source
/// Changes the input source policy and triggers a full rebuild.
///
/// Live input requires microphone authorisation first — without it macOS feeds the AUHAL input
/// silent zeros. The request is asynchronous, so `.liveInput` is applied only once the grant
/// resolves; a denial falls back to the test loop.
///
/// - Parameter source: `.testLoop` for the built-in test signal or `.liveInput(channel:)`
/// for hardware microphone/instrument input on the given channel.
func setInputSource(_ source: InputSource) {
guard case .liveInput = source else {
applyInputSource(source)
return
}
MicrophonePermission.request { [weak self] granted in
if !granted { self?.microphoneAccessDenied = true }
self?.applyInputSource(granted ? source : .testLoop)
}
}
/// Set when live input is requested but microphone access is denied/restricted. The UI observes
/// this and presents an alert, then clears it.
var microphoneAccessDenied: Bool = false
/// Applies an input-source change and triggers a full rebuild.
private func applyInputSource(_ source: InputSource) {
inputSource = source
rebuild()
}
// MARK: - Transport
/// Starts the engine. Updates ``isRunning`` on success; prints on failure.
func start() {
do {
try engine.start()
} catch {
print("[ShoeGazeDemoController] engine.start() failed: \(error)")
}
}
/// Stops the engine and updates ``isRunning``.
func stop() {
engine.stop()
}
/// Toggles audio output on/off (mute). Muting silences output by stopping the engine;
/// unmuting restarts it. `isRunning == false` is the "muted" (silent) state.
func toggleMute() {
if isRunning {
stop()
} else {
start()
}
}
// MARK: - Engine reconfiguration
/// Applies new engine settings (while stopped) and rebuilds the current mode so the showcase
/// is reconstructed at the new sample rate / channel counts. Used by the engine-config UI.
///
/// Tears the session down BEFORE reconfiguring — changing channel counts re-partitions the bus
/// allocator, which would invalidate rig buses still allocated under the old layout.
///
/// - Throws: `SynthesisEngineConfigError` if the engine is running or a value is invalid.
func reconfigure(sampleRate: Double, inputChannels: Int, outputChannels: Int) throws {
let wasRunning: Bool = isRunning
if wasRunning { stop() }
tearDownSession()
try engine.setSampleRate(sampleRate)
try engine.setNumOutputChannels(outputChannels)
try engine.setNumInputChannels(inputChannels)
// A live-input source past the new channel count would make rebuild fail; fall back.
if case .liveInput(let channel) = inputSource, channel >= inputChannels {
inputSource = .testLoop
}
buildSession()
// `buildSession()` creates a fresh `ShoeGaze`, whose `init` installs the scope tap for the
// new channel layout — no explicit `installScopeTap()` needed here.
if wasRunning { start() }
}
// MARK: - Rebuild
/// Tears down the current session and rebuilds the active mode.
///
/// The engine is stopped before teardown and restarted afterward if it was running,
/// satisfying the remove-before-release invariant documented on `ShoeGaze.teardown()`.
private func rebuild() {
let wasRunning: Bool = isRunning
if wasRunning { stop() }
tearDownSession()
buildSession()
if wasRunning { start() }
}
/// Removes the current session's nodes and clears split/router references.
private func tearDownSession() {
shoeGaze.teardown()
router = nil
parallelSection = nil
stereoSection = nil
}
/// Creates a fresh session and builds the active mode's graph.
private func buildSession() {
shoeGaze = ShoeGaze(engine: engine, inputSource: inputSource)
switch mode {
case .boards: buildBoards()
case .editor: buildEditor()
case .parallel: buildParallel()
case .router: buildRouter()
case .stereo: buildStereo()
}
}
// MARK: - Mode builders
/// `.boards` — three full boards covering all twelve pedal types.
///
/// Board 1: Overdrive → Delay → Reverb → Modulation
/// Board 2: Fuzz → Tremolo → Phaser → Compressor
/// Board 3: Mu-Tron → Auto-Wah → Feedback Delay → Multi-Tap Delay
private func buildBoards() {
do {
let board1: PedalBoard = try shoeGaze.addBoard()
board1.label = "Board 1"
try board1.add(OverdrivePedal())
try board1.add(DelayPedal())
try board1.add(ReverbPedal())
try board1.add(ModulationPedal())
try shoeGaze.finalizeBoard(board1)
let board2: PedalBoard = try shoeGaze.addBoard()
board2.label = "Board 2"
try board2.add(FuzzPedal())
try board2.add(TremoloPedal())
try board2.add(PhaserPedal())
try board2.add(CompressorPedal())
try shoeGaze.finalizeBoard(board2)
let board3: PedalBoard = try shoeGaze.addBoard()
board3.label = "Board 3"
try board3.add(MuTronPedal())
try board3.add(AutoWahPedal())
try board3.add(FeedbackDelayPedal())
try board3.add(MultiTapDelayPedal())
try shoeGaze.finalizeBoard(board3)
} catch {
print("[ShoeGazeDemoController] buildBoards failed: \(error)")
}
}
/// `.editor` — one board inside `BoardEditorView` with two pre-captured versions.
///
/// The pre-populated version entries ("Crunch" and "Clean Shimmer") ensure the
/// Versions menu is not empty when the showcase first appears.
private func buildEditor() {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Editor Board"
try board.add(OverdrivePedal())
try board.add(FuzzPedal())
try board.add(DelayPedal())
try board.add(ReverbPedal())
try shoeGaze.finalizeBoard(board)
// Pre-populate two named snapshots so the Versions menu is immediately useful.
versionStore.capture(board, name: "Crunch")
versionStore.capture(board, name: "Clean Shimmer")
} catch {
print("[ShoeGazeDemoController] buildEditor failed: \(error)")
}
}
/// `.parallel` — Overdrive → split(Delay | Fuzz) → merge → Reverb.
///
/// Stores the `ParallelSection` in `parallelSection` so `DemoRootView` can display
/// `ParallelSectionView`.
private func buildParallel() {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Parallel Board"
try board.add(OverdrivePedal())
let section: ParallelSection = try board.split()
try section.branchA.add(DelayPedal())
try section.branchB.add(FuzzPedal())
try board.merge(section)
try board.add(ReverbPedal())
try shoeGaze.finalizeBoard(board)
parallelSection = section
} catch {
print("[ShoeGazeDemoController] buildParallel failed: \(error)")
}
}
/// `.router` — ChainRouter with two independent chains: A (Overdrive + Delay),
/// B (Fuzz + Reverb), merged through a shared master stage.
///
/// Stores the `ChainRouter` in `router` so `DemoRootView` can display
/// `ChainRouterView`.
private func buildRouter() {
do {
let r: ChainRouter = try shoeGaze.makeChainRouter()
try r.addToA(OverdrivePedal())
try r.addToA(DelayPedal())
try r.addToB(FuzzPedal())
try r.addToB(ReverbPedal())
try r.finalize()
router = r
} catch {
print("[ShoeGazeDemoController] buildRouter failed: \(error)")
}
}
/// `.stereo` — Overdrive → splitStereo(left: Delay | right: Ping-Pong) → collectStereo.
///
/// Demonstrates the stereo split mechanism: a mono signal fanned into two independently
/// authored chains that become the left and right output channels, with the four
/// ``StereoRoute`` modes (stereo / left / right / bypass) selectable live. Stores the
/// `StereoSplitSection` so `DemoRootView` can display `StereoSplitSectionView`.
private func buildStereo() {
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Stereo Board"
try board.add(OverdrivePedal())
let section: StereoSplitSection = try board.splitStereo()
try section.left.add(DelayPedal())
try section.right.add(PingPongDelayPedal())
try board.collectStereo(section)
try shoeGaze.finalizeBoard(board)
stereoSection = section
} catch {
print("[ShoeGazeDemoController] buildStereo failed: \(error)")
}
}
}
#endif
-24
View File
@@ -1,24 +0,0 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
// Program entry runs on the main thread; assert main-actor isolation for the
// AppKit bootstrap rather than hopping asynchronously. `AppDelegate.init` builds
// `@MainActor` synthesizers and UI.
MainActor.assumeIsolated {
let app: NSApplication = NSApplication.shared
let delegate: AppDelegate = AppDelegate()
app.setActivationPolicy(.regular)
app.delegate = delegate
app.activate(ignoringOtherApps: true)
app.run()
}
#else
// The ShoeGaze demo is a macOS AppKit application and has no iOS entry point.
print("ShoeGazeDemo runs on macOS only.")
#endif
@@ -1,387 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
C3C000000000000000000009 /* ShoeGazeiOSDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */; };
C3C00000000000000000000A /* ShoeGazeiOSDemoAppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */; };
C3C00000000000000000000B /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001A /* LyrebirdShoeGaze */; };
C3C00000000000000000000C /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001B /* LyrebirdShoeGazeUI */; };
C3C00000000000000000000D /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001C /* LyrebirdUI */; };
C3C00000000000000000001D /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3C00000000000000000001E /* Lyrebird */; };
C3C000000000000000000031 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C3C000000000000000000030 /* Assets.xcassets */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
C3C000000000000000000004 /* ShoeGazeiOSDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeiOSDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
C3C000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeiOSDemoApp.swift; sourceTree = "<group>"; };
C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeiOSDemoAppModel.swift; sourceTree = "<group>"; };
C3C000000000000000000030 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
C3C00000000000000000000F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C3C00000000000000000000B /* LyrebirdShoeGaze in Frameworks */,
C3C00000000000000000000C /* LyrebirdShoeGazeUI in Frameworks */,
C3C00000000000000000000D /* LyrebirdUI in Frameworks */,
C3C00000000000000000001D /* Lyrebird in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
C3C000000000000000000002 = {
isa = PBXGroup;
children = (
C3C000000000000000000005 /* ShoeGazeiOSDemo */,
C3C000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
C3C000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
C3C000000000000000000004 /* ShoeGazeiOSDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
C3C000000000000000000005 /* ShoeGazeiOSDemo */ = {
isa = PBXGroup;
children = (
C3C000000000000000000007 /* ShoeGazeiOSDemoApp.swift */,
C3C000000000000000000008 /* ShoeGazeiOSDemoAppModel.swift */,
C3C000000000000000000030 /* Assets.xcassets */,
C3C000000000000000000006 /* Info.plist */,
);
path = ShoeGazeiOSDemo;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C3C000000000000000000011 /* ShoeGazeiOSDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = C3C000000000000000000012 /* Build configuration list for PBXNativeTarget "ShoeGazeiOSDemo" */;
buildPhases = (
C3C00000000000000000000E /* Sources */,
C3C00000000000000000000F /* Frameworks */,
C3C000000000000000000010 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = ShoeGazeiOSDemo;
packageProductDependencies = (
C3C00000000000000000001A /* LyrebirdShoeGaze */,
C3C00000000000000000001B /* LyrebirdShoeGazeUI */,
C3C00000000000000000001C /* LyrebirdUI */,
C3C00000000000000000001E /* Lyrebird */,
);
productName = ShoeGazeiOSDemo;
productReference = C3C000000000000000000004 /* ShoeGazeiOSDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C3C000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
C3C000000000000000000011 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = C3C000000000000000000015 /* Build configuration list for PBXProject "ShoeGazeiOSDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = C3C000000000000000000002;
packageReferences = (
C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */,
C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */,
);
productRefGroup = C3C000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C3C000000000000000000011 /* ShoeGazeiOSDemo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
C3C000000000000000000010 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3C000000000000000000031 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
C3C00000000000000000000E /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3C000000000000000000009 /* ShoeGazeiOSDemoApp.swift in Sources */,
C3C00000000000000000000A /* ShoeGazeiOSDemoAppModel.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C3C000000000000000000013 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_STYLE = Automatic;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeiOSDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeiOSDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
C3C000000000000000000014 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeiOSDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeiOSDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
SUPPORTS_MACCATALYST = NO;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.0;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Release;
};
C3C000000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
C3C000000000000000000017 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 18.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = iphoneos;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C3C000000000000000000012 /* Build configuration list for PBXNativeTarget "ShoeGazeiOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3C000000000000000000013 /* Debug */,
C3C000000000000000000014 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C3C000000000000000000015 /* Build configuration list for PBXProject "ShoeGazeiOSDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3C000000000000000000016 /* Debug */,
C3C000000000000000000017 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCRemoteSwiftPackageReference section */
C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 1.2.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C3C00000000000000000001A /* LyrebirdShoeGaze */ = {
isa = XCSwiftPackageProductDependency;
package = C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGaze;
};
C3C00000000000000000001B /* LyrebirdShoeGazeUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3C000000000000000000018 /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGazeUI;
};
C3C00000000000000000001C /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = LyrebirdUI;
};
C3C00000000000000000001E /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = C3C000000000000000000019 /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = Lyrebird;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = C3C000000000000000000001 /* Project object */;
}
@@ -1,33 +0,0 @@
{
"originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a",
"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
}
@@ -1,78 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3C000000000000000000011"
BuildableName = "ShoeGazeiOSDemo.app"
BlueprintName = "ShoeGazeiOSDemo"
ReferencedContainer = "container:ShoeGazeiOSDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3C000000000000000000011"
BuildableName = "ShoeGazeiOSDemo.app"
BlueprintName = "ShoeGazeiOSDemo"
ReferencedContainer = "container:ShoeGazeiOSDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3C000000000000000000011"
BuildableName = "ShoeGazeiOSDemo.app"
BlueprintName = "ShoeGazeiOSDemo"
ReferencedContainer = "container:ShoeGazeiOSDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -1,6 +0,0 @@
{
"images" : [
{"filename":"icon_1024.png","idiom":"universal","platform":"ios","size":"1024x1024"}
],
"info" : {"author":"xcode","version":1}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 402 KiB

@@ -1 +0,0 @@
{ "info" : {"author":"xcode","version":1} }
-46
View File
@@ -1,46 +0,0 @@
<?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>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
<key>NSMicrophoneUsageDescription</key>
<string>ShoeGazeiOSDemo can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
@@ -1,33 +0,0 @@
// ShoeGazeiOSDemoApp.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGazeUI
/// iOS entry point for the ShoeGaze in-repo demo.
///
/// Holds the `ShoeGazeiOSDemoAppModel` as `@State` so it is created once and
/// owned for the lifetime of the app. The audio engine is **not** started
/// automatically — the user presses Start in the pedalboard (`ShoeGazeView`) to
/// begin audio. The engine is stopped when the view disappears.
@main
struct ShoeGazeiOSDemoApp: App {
@State private var model: ShoeGazeiOSDemoAppModel = ShoeGazeiOSDemoAppModel()
var body: some Scene {
WindowGroup {
NavigationStack {
ScrollView {
ShoeGazeView(shoeGaze: model.shoeGaze, hardwareSampleRate: { model.hardwareSampleRate })
.padding(.horizontal, 12)
}
.navigationTitle("ShoeGaze")
}
.onDisappear { model.stop() }
}
}
}
@@ -1,103 +0,0 @@
// ShoeGazeiOSDemoAppModel.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AVFoundation
import Observation
import LyrebirdSynth
import LyrebirdShoeGaze
/// Observable model that owns the `SynthesisEngine` and `ShoeGaze` session for
/// the ShoeGaze iOS demo.
///
/// The engine is not started automatically — the pedalboard's Start button
/// (`ShoeGazeView`) drives `engine.start()`. `stop()` is called from `.onDisappear`
/// to release audio resources when the view goes away.
///
/// `AVAudioSession` is activated at init so the hardware sample rate is known
/// before the engine is constructed — iOS devices typically lock to 48 000 Hz
/// regardless of the preferred rate, and querying the session after activation
/// avoids pitch and timing errors.
///
/// The default board (Overdrive → Delay → Reverb → Modulation) uses `.testLoop`
/// as the input source, so no microphone permission is required to run the demo.
/// Switch to `.liveInput(channel: 0)` and set `numInputChannels: 1` in the
/// engine init to route hardware microphone or instrument input through the board.
@Observable
@MainActor
final class ShoeGazeiOSDemoAppModel {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let outputChannels: Int = 2
private static let numAudioBuses: Int = 256
// MARK: - Owned objects
/// The active ShoeGaze pedalboard session.
private(set) var shoeGaze: ShoeGaze
private let engine: SynthesisEngine
private let iosDriver: iOSAudioDriver
/// The sample rate the audio session actually committed to (for the config mismatch warning).
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
// MARK: - Init
init() {
// Activate the session before querying `sampleRate` so the hardware rate
// is reported correctly (iOS locks to 48 000 Hz on most devices).
let session: AVAudioSession = AVAudioSession.sharedInstance()
try? session.setCategory(.playAndRecord,
mode: .default,
options: [.defaultToSpeaker, .allowBluetoothHFP])
try? session.setActive(true)
let sampleRate: Double = session.sampleRate
let driver: iOSAudioDriver = iOSAudioDriver()
let eng: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeiOSDemoAppModel.blockSize,
sampleRate: sampleRate,
numOutputChannels: ShoeGazeiOSDemoAppModel.outputChannels,
numInputChannels: 0,
numAudioBuses: ShoeGazeiOSDemoAppModel.numAudioBuses,
driver: driver
)
self.iosDriver = driver
self.engine = eng
self.shoeGaze = ShoeGaze(engine: eng)
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Demo Board"
try board.add(OverdrivePedal())
try board.add(DelayPedal())
try board.add(ReverbPedal())
try board.add(ModulationPedal())
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeiOSDemo] board build failed: \(error)")
}
}
// MARK: - Transport
/// Starts the audio engine. Not called automatically — the pedalboard's Start
/// button drives `engine.start()`; this is here for callers that want to start it.
func start() {
do {
try engine.start()
} catch {
print("[ShoeGazeiOSDemo] engine.start() failed: \(error)")
}
}
/// Stops the audio engine. Call from `.onDisappear`.
func stop() {
engine.stop()
}
}
+3 -3
View File
@@ -1,5 +1,5 @@
{
"originHash" : "b8327204b102b429067129b94b6ba77dcfa78570af3b9d11cae4d7eb252e388c",
"originHash" : "8bbfcc5441e68d57cefd08aed960cbac3875af1e0f8b1d2d3fbdd4dadc0ac18c",
"pins" : [
{
"identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
"version" : "1.2.3"
}
},
{
+5 -3
View File
@@ -11,8 +11,9 @@
// double-registration. The dynamic-product dance used by `LiveCompile/` is only
// required for runtime dylib hot-swap, which ShoeGaze does not do.
//
// The demo app lives at Demo/ShoeGazeDemo.xcodeproj — open ShoeGaze.xcworkspace
// in Xcode and run the ShoeGazeDemo scheme to build it.
// The apps live at Demo/ShoeGazeBuilder.xcodeproj (macOS) and
// Demo/ShoeGazeBuilderiOS.xcodeproj (iPad) — open ShoeGaze.xcworkspace in Xcode
// and run the matching scheme to build them.
import PackageDescription
let package = Package(
@@ -23,7 +24,7 @@ let package = Package(
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
],
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.0"),
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.3"),
],
targets: [
// The core target depends on LyrebirdUI as well as the synthesis core:
@@ -51,6 +52,7 @@ let package = Package(
name: "LyrebirdShoeGazeTests",
dependencies: [
"LyrebirdShoeGaze",
"LyrebirdShoeGazeUI",
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
+126 -1
View File
@@ -1,3 +1,128 @@
# ShoeGaze
A package depenedent on Lyrebird for creating and storing virtual Guitar Pedal Boards
**A virtual guitar-pedalboard framework for macOS and iPadOS, built on [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird).**
ShoeGaze turns Lyrebird's real-time synthesis engine into a stompbox rig: chain modeled
guitar pedals into one or more signal-flow boards, tweak them live with knobs and switches,
mix or switch between boards, and save the whole rig to disk. Run it on a synthesized test
signal (no hardware needed) or on live guitar through an audio input.
![ShoeGaze Builder](docs/images/builder-macos.png)
## Features
- **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, plus a
rig-wide **output volume and mute** on top.
- **MIDI foot-controller support** — map footswitches (Program Change) to bypass/mute/solo
toggles, and expression pedals (Control Change) to any knob, board level, or the rig-wide
volume, with per-binding invert for crossfades. MIDI Learn, one binding per rig.
- **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or
stereo lanes, and merge back to mono.
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across
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.
## Pedal catalog
| Category | Pedals |
|---|---|
| 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.
## Requirements
- macOS 15+ / iPadOS 18+ (iPad, landscape)
- Swift 6.0 toolchain / Xcode 16+
- [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.2.0+
## Packages
Two library products:
- **`LyrebirdShoeGaze`** — the core pedal/board framework (no SwiftUI).
- **`LyrebirdShoeGazeUI`** — SwiftUI pedalboard views (knobs, switches, faders, board mixer).
Add the dependency in your `Package.swift`:
```swift
.package(url: "https://realizedsound.mooo.com/josh/ShoeGaze", from: "1.0.0"),
```
## Getting started
Build a board and start the engine (macOS):
```swift
import Lyrebird
import LyrebirdShoeGaze
let driver = CoreAudioDriver()
let engine = SynthesisEngine(
blockSize: 512, sampleRate: 48_000,
numOutputChannels: 2, numInputChannels: 1,
numAudioBuses: 256, driver: driver
)
let shoeGaze = ShoeGaze(engine: engine) // defaults to the test-loop signal
let board = try shoeGaze.addBoard()
try shoeGaze.appendPedal(.overdrive, to: board)
try shoeGaze.appendPedal(.delay, to: board)
try shoeGaze.finalizeBoard(board)
try engine.start()
```
Drop in the full builder UI:
```swift
import SwiftUI
import LyrebirdShoeGazeUI
struct ContentView: View {
let shoeGaze: ShoeGaze
var body: some View {
ShoeGazeBuilderView(shoeGaze: shoeGaze)
}
}
```
## Apps
Open `ShoeGaze.xcworkspace` in Xcode and run a scheme from `Demo/`:
- **ShoeGazeBuilder** (macOS) / **ShoeGazeBuilderiOS** (iPad) — the full palette + board builder.
## Screenshots
| macOS builder | Board mixer |
|---|---|
| ![Builder](docs/images/builder-macos.png) | ![Board mixer](docs/images/board-mixer.png) |
## Built on Lyrebird
ShoeGaze is a sample project for [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird), a
native Swift audio-synthesis framework. Pedals are Lyrebird `Synthesizer` graphs of `Generator`
nodes; the board/engine plumbing handles real-time-safe signal routing and scheduling.
## License
MIT — see [LICENSE](LICENSE).
+263
View File
@@ -0,0 +1,263 @@
# Releases
## ShoeGaze 2.1.1
A quieter, more predictable startup. The signal feeding the pedals now has its own mute
that arms every time you start the engine, new rigs open listening to your instrument,
and your input and I/O settings travel with the rig instead of a local-only setting.
### Highlights
- **Input mute** — a hard kill-switch on the incoming guitar / mic signal, separate from
the rig-output mute. Arms automatically on every Start (silent until you're ready),
sits by the Start/Stop transport with a pulsing red glow while active, and is
MIDI-mappable like Rig Mute. A muted input is exactly silent from the first sample.
- **Opens on In 0** — new rigs listen to live input instead of the test-loop phrase.
- **Input & I/O persist with the rig** — the input selection and engine input/output
channel counts are stored in the rig (and iCloud) and reapplied on launch, so a
multi-channel setup and a chosen input survive a restart. Replaces the old local-only
input setting.
- **Tidier transport** — the docked macOS Bypass / Mute / Input toggles are icons so the
row no longer crowds the rate and channel controls.
### Compatibility
Additive: rigs saved before this release load unchanged, and 2.1.1 rigs still open in
older builds (input-mute state isn't persisted; the extra I/O fields are ignored there).
## ShoeGaze 2.1.0
Tempo comes to the pedals. Delay times and LFO rates can lock to note divisions of the
live tempo — shown with real music-notation glyphs and following the tempo as it
changes — plus a directly-editable BPM, longer delays, and per-control MIDI/key mapping
badges on every pedal.
### Highlights
- **Tempo-synced parameters** — lock a delay time or a modulation rate to a note value
(whole → sixteenth, dotted, triplet); it follows tap tempo, the stepper, the BPM
field, and MIDI. Delay, Feedback Delay, Ping-Pong, Reverse, and Multi-Tap (per tap);
Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
- **Notation glyphs** — the picker draws real note glyphs (augmentation dot for dotted
values, a bracketed "3" over triplets) instead of text.
- **Editable BPM** — type a tempo directly (integer, 30–300); the stepper and tap still
work, and synced pedals follow immediately.
- **Longer delays** — maximum delay time raised to 5 s so slow synced values fit.
- **Control mapping badges** — every pedal shows the PC (footswitch), CC (expression),
or KEY (letter key) binding on each control, with a legend above the board.
- **CC respects tempo sync** — a CC bound to a synced parameter is ignored while synced
(the tempo drives it) and resumes control once the parameter is set back to Free.
### Compatibility
Additive persistence — older rigs load unchanged (every parameter defaults to free),
and 2.1 rigs open in older builds with the tempo-sync state ignored.
## ShoeGaze 2.0.0
Major release. Performance-focused: a visual metronome, a real rig mute with
keyboard control, and rigs that remember their tempo, input, and I/O — plus a
saveable set-list order for hands-free switching between rigs live. The version
jumps to 2.0.0 to align ShoeGaze's numbering with the wider project family.
### Highlights
- **Visual metronome** — a horizontal playhead eases wall-to-wall each beat so you
can anticipate the downbeat, replacing the old flashing LED.
- **Rig Mute (⌘Z)** — hard-silences the whole rig; distinct from Bypass Rig (dry passthrough).
- **Keyboard shortcuts** — ⌘1–⌘9 switch/solo boards, ⌘⇧1–⌘⇧0 load set-list rigs 1–10,
⌘Z mutes. macOS menus + iOS/iPadOS hardware keyboards.
- **Set lists** — reorder rigs by drag or Move Up/Down; the order saves, travels with
an exported archive, and drives the ⌘⇧ slots.
- **Per-rig memory** — tempo, input selection, and engine I/O now persist with a rig.
### Fixed
- Archive import no longer collides set-list positions with existing rigs.
### Removed
- The ShoeGazeDemo / ShoeGazeiOSDemo apps — only the ShoeGazeBuilder (macOS) and
ShoeGazeBuilderiOS (iPad) apps remain.
**Compatibility:** rig persistence is additive — older rigs load unchanged, and 2.0.0
rigs still open in older builds. The bump reflects feature scope + version alignment,
not a format break.
## 1.5.0 — 2026-07-04
### New Looper pedal (catalog now 36)
- **Multitrack looper** with a smart Loop footswitch (record → overdub → play), up to four
tracks (A/B/C/D), per-track mute via the track dots, undo, reverse, and a timeline view.
- **Beat-quantized transport** with a **Sync / Free** mode toggle; stop and cue-stop honour the
loop boundary in Sync. Clean-through and a Playback balance let the dry signal pass while
looped layers play back.
- **MIDI-mappable** transport (record/play/stop), per-track A/B/C/D taps, and the Sync toggle.
- Stomp-style **Reset** button that also fires on engine stop and rig teardown; `effect()` is
idempotent across graph rebuilds, and the multitrack engine is RT-safe (findings from review
addressed, with regression coverage for record-after-reset).
### iPad / iOS layout rework
- **Canvas-first compact layout** — composition panels move into sheets so the pedal canvas
fills the screen; the sheet-based layout is now used at every size class (no forced min width).
- **Header compaction** — performance controls sit inline right of the title; rig controls group
with Tempo/Tuner; the scope drops to a full-width strip below the rows in portrait. Fixes
Tempo/Tuner truncation, Mute-toggle expansion, mixer overflow into the CPU meters, and portrait
clipping/centering.
- **Add-Pedal sheet** is a scrollable list with a fixed header and type filter at a stable size;
fixed compact sheets that failed to present (one sheet per view node).
### Dependency
- Bumped to **Lyrebird 1.2.3**. Lyrebird now ships framework-neutral project templates only —
its ShoeGaze-specific CLI scaffolding was removed, since ShoeGaze lives in this standalone repo.
### Fixes
- A transport-only **Start** no longer reverts Settings configuration (external-review fix).
- Dropped a stale doc and a dead `looperTimeline` property.
## 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
- Pedal **ⓘ info button** moved to the top-left corner (under the corner screw),
out of the way of the name plate.
- Fixed **dragging a pedal into a Stereo Unzip / Split / Parallel lane**. Dropping a pedal
from the main chain (or another lane) into a region lane now moves it there, preserving its
parameters — previously the drop was silently ignored. Empty lanes are also fully
hit-testable now.
## 1.1.0 — 2026-06-24
### New pedals
- **Chorus** — true-stereo chorus (two anti-phase modulated delay voices), distinct from the
mono Modulation chorus.
- **Sustainer** — one-knob compressor tuned for long, even sustain, with a tone control.
- **Ring Modulator** — multiplies the signal by a tunable sine carrier for metallic / bell /
robotic tones.
- **Diffuser** — stereo widener that fans the frequency spectrum across L/R, with a `spread`
control from mono to a wide, diffuse image.
### Pedal info UI
- Every pedal now has a one-line description (`summary`).
- The pedal picker shows each pedal's description as a subtitle.
- Each pedal has an ⓘ info button opening a panel with its description and effect controls
(knobs / sliders / switches) and their value ranges — excluding the common Mix/Level/bypass.
### Board persistence
- The board(s) persist across app restarts on macOS and iPadOS — the rig is autosaved to
Application Support and restored on launch (falls back to a default board if none).
- New **Clear** button removes all boards; it first prompts **Save & Clear / Clear Without
Saving / Cancel**, and "Save & Clear" only clears once the save completes.
- Rig save is now available in-view on macOS too (previously File-menu only).
### Developer notes
- Added `docs/plans/` (feature plans) and a project `CLAUDE.md` (conventions + a required
checklist for new pedals, including a mandatory `summary`).
---
## 1.0.0 — 2026-06-24
First stable release: a virtual guitar-pedalboard framework built on Lyrebird, for macOS and
iPadOS, in two products — `LyrebirdShoeGaze` (core) and `LyrebirdShoeGazeUI` (SwiftUI).
### Pedals (18)
Overdrive, Fuzz, Compressor (with input gain), Limiter, Noise Gate, Graphic EQ, Auto-Wah,
Mutant, Phaser, Tremolo, Modulation, Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverb,
Octave Splitter, Bass Octaver. Delay-family "decay" controls are labelled **Decay Time**.
### Boards & mixing
- Multiple boards with a board-mixer bar: **Solo** one (amp-channel style) or **Blend** any
subset, each with its own level and a click-free crossfade.
- A board-manager sheet (rename, drag-reorder, swipe-delete) and ⌘1–9 board switching.
- Signal-flow editor: add pedals from the palette; parallel and stereo-split lanes; merge to mono.
- One shared, phase-locked test signal across all boards (no per-board polyrhythm).
### Audio I/O
- Test-loop signal or live hardware input.
- macOS and iPadOS (iPad-only, landscape). iOS live input via a permission-gated engine rebuild;
the last input choice is remembered.
### Files & capture
- Save / load rigs as JSON.
- Record output to timestamped files.
### API
- Type-safe `PedalType` tokens for the board-edit API (`appendPedal(.overdrive, to:)`); the rig
JSON format is keyed on pedal display names.
-6
View File
@@ -4,12 +4,6 @@
<FileRef
location = "group:.">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeiOSDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeBuilder.xcodeproj">
</FileRef>
@@ -1,5 +1,5 @@
{
"originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a",
"originHash" : "39c6a5f1535f779ef8a83b5ea2ab6f965ee3b28ad8419b94679e422a92f75603",
"pins" : [
{
"identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
"version" : "1.2.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] }
}
@@ -5,6 +5,7 @@
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Internal synthesizer that copies one hardware input bus to a board head bus.
///
@@ -18,6 +19,17 @@ import LyrebirdSynth
/// `teardown()` releases the head bus back to the allocator.
final class HardwareInputPassThrough: SynthesizerBase {
// MARK: - Parameters
/// Input mute — `0` = audible, `1` = muted (a hard gate on the incoming signal, distinct from
/// the rig-output mute). Driven across every board input node by `ShoeGaze.setInputMuted(_:)`,
/// which sets a newly-added node to the session's current mute state. Defaults audible so
/// direct users (e.g. `ChainRouter`) that don't drive the mute pass the signal through.
@UIParam var inputMute: Double = 0.0
/// The live `UIParamNode` backing `inputMute`, driven by `ShoeGaze.setInputMuted(_:)`.
var inputMuteNode: UIParamNode { $inputMute }
// MARK: - Routing
/// Index of the hardware input bus to read from (typically `engine.numOutputChannels`).
@@ -43,6 +55,11 @@ final class HardwareInputPassThrough: SynthesizerBase {
// MARK: - Build
override func build() {
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
// Hard kill-switch gate: `1 − inputMute`, so mute 0 → gain 1 (audible), 1 → gain 0 (exactly
// silent). Unlagged on purpose — a lagged gate never settles to exactly zero on its first
// blocks and leaks a faint transient right when the mute is meant to keep things quiet; a
// kill-switch mute is expected to be abrupt anyway.
let muteGain: any ValidGeneratorInput = ($inputMute - 1.0) * -1.0
output(bus: outputBusIndex, source: input(bus: inputBusIndex) * muteGain)
}
}
@@ -22,6 +22,46 @@ public enum InputSource: Equatable {
case liveInput(channel: Int)
}
// MARK: - Codable
/// Persisted so a saved rig round-trips its input selection. Encoded as a `kind` discriminator
/// plus an optional `channel`, so adding future cases stays forward-tolerant.
extension InputSource: Codable {
private enum Kind: String, Codable {
case testLoop
case liveInput
}
private enum CodingKeys: String, CodingKey {
case kind
case channel
}
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
let kind: Kind = try container.decode(Kind.self, forKey: .kind)
switch kind {
case .testLoop:
self = .testLoop
case .liveInput:
let channel: Int = try container.decode(Int.self, forKey: .channel)
self = .liveInput(channel: channel)
}
}
public func encode(to encoder: Encoder) throws {
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .testLoop:
try container.encode(Kind.testLoop, forKey: .kind)
case .liveInput(let channel):
try container.encode(Kind.liveInput, forKey: .kind)
try container.encode(channel, forKey: .channel)
}
}
}
/// Validates a `.liveInput` channel against the engine and returns the engine audio-bus
/// index of that hardware input channel.
///
@@ -0,0 +1,65 @@
// TestLoopTap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Internal synthesizer that copies the shared global test-loop bus to a board head bus.
///
/// In `.testLoop` mode every board reads the **same** global ``TestLoopSource`` (so all boards
/// stay phase-locked instead of each running an independently-phased arpeggio). A `TestLoopTap`
/// per board reads the global test bus at `inputBusIndex` and writes it to the board's head bus
/// at `outputBusIndex`, so the first pedal still reads from a board-owned bus.
///
/// Added `.after(_:)` the global source so it evaluates once the source has written the test bus
/// for the current block.
///
/// - Note: Must be removed from the engine before the board's `teardown()` releases the head bus.
final class TestLoopTap: SynthesizerBase {
// MARK: - Parameters
/// Input mute — `0` = audible, `1` = muted. Driven across every board input node by
/// `ShoeGaze.setInputMuted(_:)`, which sets a newly-added node to the session's current mute
/// state. Defaults audible so direct users that don't drive the mute pass the signal through.
@UIParam var inputMute: Double = 0.0
/// The live `UIParamNode` backing `inputMute`, driven by `ShoeGaze.setInputMuted(_:)`.
var inputMuteNode: UIParamNode { $inputMute }
// MARK: - Routing
/// Index of the shared global test-loop bus to read from.
private let inputBusIndex: Int
/// Index of the board head bus to write to.
private let outputBusIndex: Int
// MARK: - Init
/// Creates a tap that copies `inputBusIndex` (the global test bus) to `outputBusIndex`
/// (a board head bus).
///
/// - Parameters:
/// - inputBusIndex: Shared global test-loop bus index to read from.
/// - outputBusIndex: Board head bus index to write to.
init(inputBusIndex: Int, outputBusIndex: Int) {
self.inputBusIndex = inputBusIndex
self.outputBusIndex = outputBusIndex
super.init()
}
// MARK: - Build
override func build() {
// Hard kill-switch gate: `1 − inputMute`, so mute 0 → gain 1 (audible), 1 → gain 0 (exactly
// silent). Unlagged on purpose — a lagged gate never settles to exactly zero on its first
// blocks and leaks a faint transient right when the mute is meant to keep things quiet; a
// kill-switch mute is expected to be abrupt anyway.
let muteGain: any ValidGeneratorInput = ($inputMute - 1.0) * -1.0
output(bus: outputBusIndex, source: input(bus: inputBusIndex) * muteGain)
}
}
@@ -0,0 +1,153 @@
// LegacyMIDIMap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Decoder for the **pre-UUID** `MIDIMap` format, which addressed pedals and boards by chain
/// position (`boardIndex` / `pedalIndex`) rather than by stable id.
///
/// Used only on load: `ShoeGazeState.init(from:)` tries the current id-based `MIDIMap` first and,
/// if that fails, decodes this legacy shape and calls ``migrated(boards:)`` to convert each
/// positional binding to the id of the pedal/board now sitting at that position. Because the saved
/// positions are stable, this reconstructs correct id-bindings on every load — even though the ids
/// themselves are freshly assigned to a legacy rig each time it is decoded.
///
/// Bindings whose indices fall outside the loaded rig are dropped.
struct LegacyMIDIMap: Codable {
var switches: [LegacySwitchBinding]
var ccs: [LegacyCCBinding]
enum LegacyAction: Codable {
case rigBypass
case rigMute
case allBoards
case boardSolo(boardIndex: Int)
case boardAudible(boardIndex: Int)
case boardBypass(boardIndex: Int)
case pedalBypass(boardIndex: Int, pedalIndex: Int)
case pedalAction(boardIndex: Int, pedalIndex: Int, kind: MIDIMap.PedalActionKind)
case tunerToggle
case tapTempo
}
enum LegacyCCTarget: Codable {
case pedalControl(
boardIndex: Int,
pedalIndex: Int,
controlIndex: Int,
pedalNameHint: String?,
controlLabelHint: String?
)
case boardLevel(boardIndex: Int, boardLabelHint: String?)
case rigVolume
}
struct LegacySwitchBinding: Codable {
var program: UInt8
var channel: UInt8?
var action: LegacyAction
var displayNameHint: String?
}
struct LegacyCCBinding: Codable {
var controller: UInt8
var channel: UInt8?
var target: LegacyCCTarget
var inverted: Bool
}
// MARK: - Migration
/// Converts this positional map to the current id-based ``MIDIMap`` using the ids of the pedals
/// and boards in `boards` (whose ids were freshly assigned when the rig was decoded). Bindings
/// addressing an out-of-range board/pedal are dropped.
func migrated(boards: [BoardState]) -> MIDIMap {
func boardID(_ index: Int) -> UUID? {
guard index >= 0, index < boards.count else { return nil }
return boards[index].id
}
func pedalID(_ boardIndex: Int, _ pedalIndex: Int) -> UUID? {
guard boardIndex >= 0, boardIndex < boards.count else { return nil }
let pedals: [PedalState] = boards[boardIndex].pedals
guard pedalIndex >= 0, pedalIndex < pedals.count else { return nil }
return pedals[pedalIndex].id
}
let migratedSwitches: [MIDIMap.SwitchBinding] = switches.compactMap { binding in
guard let action: MIDIMap.Action = migrate(binding.action, boardID: boardID, pedalID: pedalID) else {
return nil
}
return MIDIMap.SwitchBinding(
program: binding.program,
channel: binding.channel,
action: action,
displayNameHint: binding.displayNameHint
)
}
let migratedCCs: [MIDIMap.CCBinding] = ccs.compactMap { binding in
guard let target: MIDIMap.CCTarget = migrate(binding.target, boardID: boardID, pedalID: pedalID) else {
return nil
}
return MIDIMap.CCBinding(
controller: binding.controller,
channel: binding.channel,
target: target,
inverted: binding.inverted
)
}
return MIDIMap(switches: migratedSwitches, ccs: migratedCCs)
}
private func migrate(
_ action: LegacyAction,
boardID: (Int) -> UUID?,
pedalID: (Int, Int) -> UUID?
) -> MIDIMap.Action? {
switch action {
case .rigBypass: return .rigBypass
case .rigMute: return .rigMute
case .allBoards: return .allBoards
case .tunerToggle: return .tunerToggle
case .tapTempo: return .tapTempo
case .boardSolo(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardSolo(boardID: id)
case .boardAudible(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardAudible(boardID: id)
case .boardBypass(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardBypass(boardID: id)
case .pedalBypass(let b, let p):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalBypass(pedalID: id)
case .pedalAction(let b, let p, let kind):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalAction(pedalID: id, kind: kind)
}
}
private func migrate(
_ target: LegacyCCTarget,
boardID: (Int) -> UUID?,
pedalID: (Int, Int) -> UUID?
) -> MIDIMap.CCTarget? {
switch target {
case .rigVolume:
return .rigVolume
case .pedalControl(let b, let p, let controlIndex, let nameHint, let labelHint):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalControl(pedalID: id, controlIndex: controlIndex,
pedalNameHint: nameHint, controlLabelHint: labelHint)
case .boardLevel(let b, let labelHint):
guard let id: UUID = boardID(b) else { return nil }
return .boardLevel(boardID: id, boardLabelHint: labelHint)
}
}
}
@@ -0,0 +1,560 @@
// 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)
/// A toggle action awaiting a computer key press.
case key(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 }
// A parameter locked to a note division is driven by the tempo; a CC write would be
// overwritten on the next tempo change, so ignore it here. The binding stays intact and
// resumes control the moment the parameter is set back to Free.
if case let .pedalControl(pedalID, _, _, _) = binding.target,
let pedal: Pedal = pedal(id: pedalID),
pedal.isNodeTempoSynced(resolved.node) {
continue
}
let mapped: Double = resolved.range.lowerBound
+ norm * (resolved.range.upperBound - resolved.range.lowerBound)
resolved.node.update(mapped)
}
}
/// A resolved CC target: the live node + range to drive, plus the target re-stamped with the
/// current display-name hints (for storing at capture time).
private struct ResolvedCC {
let node: UIParamNode
let range: ClosedRange<Double>
let hinted: MIDIMap.CCTarget
}
/// Resolves a CC target to its live node + range, skipping it (returns `nil`) when the positional
/// address is out of range or a captured display-name hint no longer matches (stale binding).
private func resolveCC(_ target: MIDIMap.CCTarget) -> ResolvedCC? {
switch target {
case let .pedalControl(pedalID, controlIndex, _, _):
guard let pedal: Pedal = pedal(id: pedalID) else { return nil }
let controls: [PedalControl] = pedal.ccMappableControls
guard controlIndex >= 0, controlIndex < controls.count else { return nil }
let control: PedalControl = controls[controlIndex]
let hinted: MIDIMap.CCTarget = .pedalControl(
pedalID: pedalID,
controlIndex: controlIndex,
pedalNameHint: pedal.displayName,
controlLabelHint: control.label
)
return ResolvedCC(node: control.node, range: control.range, hinted: hinted)
case let .boardLevel(boardID, _):
guard let board: PedalBoard = board(id: boardID),
let node: UIParamNode = board.masterGainNode else { return nil }
let hinted: MIDIMap.CCTarget = .boardLevel(boardID: boardID, boardLabelHint: board.label)
return ResolvedCC(node: node, range: boardLevelRange, hinted: hinted)
case .rigVolume:
// Applied via `ShoeGaze.setRigVolume` (fans out to every board), not a single node.
return nil
}
}
// MARK: - Switch (Program Change) learn + apply
/// Arms MIDI Learn for a toggle action: the next incoming Program Change binds to it.
public func armSwitchLearn(_ action: MIDIMap.Action) {
learnTarget = .action(action)
}
/// The switch binding currently assigned to an action, or `nil` if unbound.
public func switchBinding(for action: MIDIMap.Action) -> MIDIMap.SwitchBinding? {
shoeGaze?.midiMap?.switches.first { $0.action == action }
}
/// Removes any switch binding assigned to an action.
public func clearSwitchBinding(for action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
let before: Int = map.switches.count
map.switches.removeAll { $0.action == action }
guard map.switches.count != before else { return }
shoeGaze.midiMap = map
onMapChanged?()
}
/// Captures a learned switch binding for the armed action and clears the Learn state.
private func captureSwitch(program: UInt8, channel: UInt8, action: MIDIMap.Action) {
learnTarget = nil
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
let binding: MIDIMap.SwitchBinding = MIDIMap.SwitchBinding(
program: program,
channel: channel,
action: action,
displayNameHint: hint(for: action)
)
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
// One binding per action — re-learning an action replaces its binding. A single footswitch
// (program) may drive MULTIPLE actions on purpose (a "scene": e.g. bypass two pedals, or
// solo a board and bypass another, from one press), so we do NOT steal by program number.
map.switches.removeAll { $0.action == action }
map.switches.append(binding)
shoeGaze.midiMap = map
onMapChanged?()
}
/// Performs every action bound to an incoming Program Change (channel-filtered).
private func applyProgram(program: UInt8, channel: UInt8) {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return }
for binding: MIDIMap.SwitchBinding in map.switches where binding.program == program {
if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue }
perform(binding.action)
}
}
/// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch;
/// `boardSolo` is exclusive (radio). Pedals/boards resolve by UUID, so a binding whose target no
/// longer exists (removed pedal/board) simply no-ops.
private func perform(_ action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
switch action {
case .rigBypass:
shoeGaze.toggleRigBypassed()
case .rigMute:
shoeGaze.toggleRigMuted()
case .inputMute:
shoeGaze.toggleInputMuted()
case .allBoards:
// One-shot: cancel any solo and bring every board back up.
shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade)
case .boardSolo(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade)
case .boardAudible(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.setBoard(board, audible: !shoeGaze.isBoardAudible(board),
crossfadeSeconds: boardActionCrossfade)
case .boardBypass(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board))
case .pedalBypass(let pedalID):
guard let pedal: Pedal = pedal(id: pedalID) else { return }
let engagedThreshold: Double = 0.5
let node: UIParamNode = pedal.$bypass
node.update(node.value < engagedThreshold ? 1.0 : 0.0)
case .pedalAction(let pedalID, let kind):
guard let pedal: Pedal = pedal(id: pedalID) else { return }
performPedalAction(kind, on: pedal)
case .tunerToggle:
shoeGaze.toggleTunerEngaged()
case .tapTempo:
shoeGaze.tapTempo()
}
}
/// Dispatches a pedal-specific momentary action. New `PedalActionKind` cases add a
/// branch here once the pedal type they target exists.
private func performPedalAction(_ kind: MIDIMap.PedalActionKind, on pedal: Pedal) {
let toggleThreshold: Double = 0.5
switch kind {
case .looperRecordStop:
// The smart Loop footswitch drives record / set-end / overdub / play by state.
(pedal as? LooperPedal)?.pressLoop()
case .looperOverdubToggle:
// Overdub is toggled by the same Loop press once a loop is playing.
(pedal as? LooperPedal)?.pressLoop()
case .looperLoopToggle:
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
let node: UIParamNode = looper.$loopOn
node.update(node.value < toggleThreshold ? 1.0 : 0.0)
case .looperReset:
(pedal as? LooperPedal)?.resetLoop()
case .looperStop:
(pedal as? LooperPedal)?.stopPlayback()
case .looperCueStop:
(pedal as? LooperPedal)?.toggleStopAtLoopEnd()
case .looperReverse:
(pedal as? LooperPedal)?.toggleReverse()
case .looperSyncToggle:
(pedal as? LooperPedal)?.cycleSyncMode()
case .looperTrack(let index):
(pedal as? LooperPedal)?.tapTrack(index)
}
}
/// A display-name hint for an action, captured at learn time for the mapping-sheet UI label.
/// Not used for resolution (bindings resolve by UUID) — purely a human-readable snapshot.
private func hint(for action: MIDIMap.Action) -> String? {
switch action {
case .rigBypass, .rigMute, .inputMute, .allBoards:
return nil
case .boardSolo(let boardID), .boardAudible(let boardID), .boardBypass(let boardID):
return board(id: boardID)?.label
case .pedalBypass(let pedalID), .pedalAction(let pedalID, _):
return pedal(id: pedalID)?.displayName
case .tunerToggle, .tapTempo:
return nil
}
}
/// Resolves a board by its stable id, or `nil` if no board in the rig has that id.
private func board(id: UUID) -> PedalBoard? {
shoeGaze?.boards.first { $0.id == id }
}
/// Resolves a pedal by its stable id across all boards' linear pedal chains, or `nil` if no
/// pedal in the rig has that id.
private func pedal(id: UUID) -> Pedal? {
guard let shoeGaze: ShoeGaze = shoeGaze else { return nil }
for board: PedalBoard in shoeGaze.boards {
if let match: Pedal = board.pedals.first(where: { $0.id == id }) { return match }
}
return nil
}
// MARK: - Key learn + apply
/// Arms MIDI Learn for a toggle action awaiting a key: the next ingested key press binds to it.
public func armKeyLearn(_ action: MIDIMap.Action) {
learnTarget = .key(action)
}
/// The key binding currently assigned to an action, or `nil` if unbound.
public func keyBinding(for action: MIDIMap.Action) -> MIDIMap.KeyBinding? {
shoeGaze?.midiMap?.keys.first { $0.action == action }
}
/// Removes any key binding assigned to an action.
public func clearKeyBinding(for action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
let before: Int = map.keys.count
map.keys.removeAll { $0.action == action }
guard map.keys.count != before else { return }
shoeGaze.midiMap = map
onMapChanged?()
}
/// Normalizes a raw key string to the single lowercased character used for storage and matching,
/// or `nil` when the input is not exactly one letter or digit. Restricting to alphanumerics keeps
/// non-printing keys (Return, Tab, Escape, arrows — all single `Character`s) from being learned
/// and then silently swallowed app-wide.
private func normalizedKey(_ raw: String) -> String? {
let lowered: String = raw.lowercased()
guard lowered.count == 1, let character: Character = lowered.first, character.isASCII,
character.isLetter || character.isNumber else { return nil }
return lowered
}
/// Routes a computer key press: captures a binding when armed for key Learn, otherwise performs
/// every action bound to that key + modifier combination. Returns `true` when the press was
/// consumed (learned or matched a binding) so the caller can swallow the event; `false` lets it
/// fall through.
///
/// - Parameters:
/// - rawKey: The pressed key; normalized to a single lowercased character.
/// - modifiers: The modifier keys held with the press. `a` and `⇧a` bind independently.
@discardableResult
public func ingestKey(_ rawKey: String, modifiers: MIDIMap.KeyModifiers = []) -> Bool {
guard let key: String = normalizedKey(rawKey) else { return false }
if case .key(let action) = learnTarget {
captureKey(key: key, modifiers: modifiers, action: action)
return true
}
return applyKey(key, modifiers: modifiers)
}
/// Captures a learned key binding for the armed action and clears the Learn state. One binding
/// per action — re-learning replaces it — but a single key may drive multiple actions (a scene),
/// so we do not steal by key.
private func captureKey(key: String, modifiers: MIDIMap.KeyModifiers, action: MIDIMap.Action) {
learnTarget = nil
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
let binding: MIDIMap.KeyBinding = MIDIMap.KeyBinding(
key: key,
modifiers: modifiers,
action: action,
displayNameHint: hint(for: action)
)
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
map.keys.removeAll { $0.action == action }
map.keys.append(binding)
shoeGaze.midiMap = map
onMapChanged?()
}
/// Performs every action bound to a key + modifier combination. Returns `true` when at least one
/// binding matched (key and modifiers both equal).
private func applyKey(_ key: String, modifiers: MIDIMap.KeyModifiers) -> Bool {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return false }
var matched: Bool = false
for binding: MIDIMap.KeyBinding in map.keys
where binding.key == key && binding.modifiers == modifiers {
perform(binding.action)
matched = true
}
return matched
}
// 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
}
}
+311
View File
@@ -0,0 +1,311 @@
// MIDIMap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A per-rig map of MIDI foot-controller bindings — which Program Change toggles which control, and
/// which Control Change drives which pedal knob.
///
/// Stored inside the rig (embedded in `ShoeGazeState`) so it travels with a saved rig. Pedals and
/// boards are addressed by **stable UUID** (`Pedal.id` / `PedalBoard.id`, persisted in
/// `PedalState`/`BoardState`), so a binding follows its pedal/board through insert, remove, move,
/// and reorder edits with no reindexing — the id survives the capture → rebuild round-trip. A
/// binding whose target no longer exists simply stops resolving (inert). The `*Hint` fields carry
/// the display name at learn time, for UI labels only (not resolution). Control-within-pedal is
/// still indexed into `Pedal.ccMappableControls`, which is stable for a given pedal type.
public struct MIDIMap: Codable, Equatable, Sendable {
/// Program-Change → action bindings (footswitch toggles). Populated in the switch phase.
public var switches: [SwitchBinding]
/// Control-Change → pedal-knob bindings (expression pedals).
public var ccs: [CCBinding]
/// Computer letter/digit key → action bindings. Same toggle ``Action`` set as ``switches`` —
/// a key press is a software footswitch — but keys never drive continuous CC targets.
public var keys: [KeyBinding]
/// 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.
/// - keys: Letter-key bindings. Defaults to empty.
public init(
switches: [SwitchBinding] = [],
ccs: [CCBinding] = [],
keys: [KeyBinding] = []
) {
self.switches = switches
self.ccs = ccs
self.keys = keys
}
private enum CodingKeys: String, CodingKey {
case switches
case ccs
case keys
}
/// Decodes a map, tolerating an absent `keys` list so a rig saved before keyboard mapping
/// existed still decodes with its `switches` / `ccs` intact (synthesized Codable would fail
/// the whole map on the missing key, silently dropping the MIDI bindings too). `encode(to:)`
/// stays synthesized and always writes `keys` (empty when there are none).
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.switches = try container.decode([SwitchBinding].self, forKey: .switches)
self.ccs = try container.decode([CCBinding].self, forKey: .ccs)
self.keys = try container.decodeIfPresent([KeyBinding].self, forKey: .keys) ?? []
}
// 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
/// Mutes/unmutes the input feeding every board (the incoming guitar / mic signal).
case inputMute
/// Cancels any solo and makes every board audible again (the "All" button).
case allBoards
case boardSolo(boardID: UUID)
case boardAudible(boardID: UUID)
case boardBypass(boardID: UUID)
case pedalBypass(pedalID: UUID)
/// A pedal-specific momentary action beyond generic bypass (e.g. a looper's
/// record/stop or reset footswitch). `kind` is opaque to `MIDIMap` — `MIDIController`
/// resolves the target pedal (by id) and dispatches on `kind` itself.
case pedalAction(pedalID: UUID, kind: PedalActionKind)
/// Toggles the rig-level tuner on/off.
case tunerToggle
/// Registers one tap-tempo press (see `ShoeGaze.tapTempo()`).
case tapTempo
}
/// A pedal-specific momentary action addressable by ``Action/pedalAction(pedalID:kind:)``.
/// New pedals with more than a simple bypass toggle add cases here.
public enum PedalActionKind: Codable, Equatable, Sendable {
/// Looper: presses the smart Loop footswitch (record → set end → overdub → play by
/// state) — same as ``looperOverdubToggle``; both dispatch to `LooperPedal.pressLoop()`.
// TODO: collapse looperRecordStop / looperOverdubToggle into one case (both call pressLoop).
case looperRecordStop
/// Looper: presses the smart Loop footswitch (toggles overdub once a loop is playing).
case looperOverdubToggle
/// Looper: flips `loopOn` (loop mute) between `0` and `1`.
case looperLoopToggle
/// Looper: reset — clears all tracks and returns to the clear state.
case looperReset
/// Looper: immediately stops playback (`LooperPedal.stopPlayback()`).
case looperStop
/// Looper: arms / cancels a stop at the loop end (`LooperPedal.toggleStopAtLoopEnd()`).
case looperCueStop
/// Looper: flips playback direction (`LooperPedal.toggleReverse()`).
case looperReverse
/// Looper: cycles the Sync/Free transport mode (`LooperPedal.cycleSyncMode()`).
case looperSyncToggle
/// Looper: taps track `index` (0 = A) — selects it, or mutes it if already selected and
/// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots.
case looperTrack(index: Int)
}
// MARK: - Switch binding
/// A Program-Change number bound to a toggle ``Action``.
public struct SwitchBinding: Codable, Equatable, Sendable {
/// The Program Change number (0–127) that triggers the action.
public var program: UInt8
/// The MIDI channel (0–15), or `nil` to match any channel (omni).
public var channel: UInt8?
/// The control to toggle.
public var action: Action
/// The resolved control's display name at learn time, for stale-binding detection.
public var displayNameHint: String?
/// Creates a switch binding.
///
/// - Parameters:
/// - program: Program Change number (0–127).
/// - channel: MIDI channel (0–15), or `nil` for omni. Defaults to `nil`.
/// - action: The toggle action to perform.
/// - displayNameHint: Resolved control name at learn time. Defaults to `nil`.
public init(
program: UInt8,
channel: UInt8? = nil,
action: Action,
displayNameHint: String? = nil
) {
self.program = program
self.channel = channel
self.action = action
self.displayNameHint = displayNameHint
}
}
// MARK: - Key modifiers
/// The modifier keys that qualify a ``KeyBinding``, so `a` and `⇧a` (and `⌃a`, `⌥a`) are
/// distinct triggers. Shift is a modifier here rather than being folded into the key's case,
/// which keeps the base key a single lowercased character on every platform. Command is
/// deliberately absent — it is reserved for the app's menu keyboard shortcuts.
public struct KeyModifiers: OptionSet, Codable, Equatable, Hashable, Sendable {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
/// The Shift key (`⇧`).
public static let shift: KeyModifiers = KeyModifiers(rawValue: 1 << 0)
/// The Control key (`⌃`).
public static let control: KeyModifiers = KeyModifiers(rawValue: 1 << 1)
/// The Option key (`⌥`).
public static let option: KeyModifiers = KeyModifiers(rawValue: 1 << 2)
}
// MARK: - Key binding
/// A computer letter/digit key bound to a toggle ``Action``. Fires on key-down when no text
/// field is focused; the same latch semantics as a footswitch (booleans flip in software,
/// `boardSolo` is exclusive). `key` is a single lowercased character; ``modifiers`` distinguish
/// `a` from `⇧a`, `⌃a`, and `⌥a`.
public struct KeyBinding: Codable, Equatable, Sendable {
/// The bound key as a single lowercased character (e.g. `"b"`, `"3"`).
public var key: String
/// The modifier keys held with ``key``. Empty for an unmodified press.
public var modifiers: KeyModifiers
/// 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 key binding.
///
/// - Parameters:
/// - key: The bound key, normalized to a single lowercased character.
/// - modifiers: The qualifying modifier keys. Defaults to none.
/// - action: The toggle action to perform.
/// - displayNameHint: Resolved control name at learn time. Defaults to `nil`.
public init(
key: String,
modifiers: KeyModifiers = [],
action: Action,
displayNameHint: String? = nil
) {
self.key = key
self.modifiers = modifiers
self.action = action
self.displayNameHint = displayNameHint
}
private enum CodingKeys: String, CodingKey {
case key
case modifiers
case action
case displayNameHint
}
/// Decodes a key binding, defaulting `modifiers` to none when absent so a binding saved
/// before modifiers existed still decodes (unmodified, as it was learned). `encode(to:)`
/// stays synthesized.
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.key = try container.decode(String.self, forKey: .key)
self.modifiers = try container.decodeIfPresent(KeyModifiers.self, forKey: .modifiers) ?? []
self.action = try container.decode(Action.self, forKey: .action)
self.displayNameHint = try container.decodeIfPresent(String.self, forKey: .displayNameHint)
}
}
// MARK: - CC target
/// A continuous control an expression pedal can drive — either a specific pedal control (a knob
/// or slider, addressed by index into the pedal's ``Pedal/ccMappableControls``) or a board's
/// master level. The `*Hint` payloads capture the resolved display name at learn time so a
/// binding that no longer matches (chain edited) can be detected and skipped.
public enum CCTarget: Codable, Equatable, Sendable {
/// A knob or slider on a pedal, indexed into `pedal.ccMappableControls`.
case pedalControl(
pedalID: UUID,
controlIndex: Int,
pedalNameHint: String?,
controlLabelHint: String?
)
/// A board's master output level (the board fader).
case boardLevel(boardID: UUID, boardLabelHint: String?)
/// The rig-wide output volume (applies to the whole rig).
case rigVolume
/// Whether two targets address the same control, ignoring the display-name hints (used to
/// find and replace a binding regardless of the name captured at learn time).
public func addresses(_ other: CCTarget) -> Bool {
switch (self, other) {
case let (.pedalControl(p1, c1, _, _), .pedalControl(p2, c2, _, _)):
return p1 == p2 && c1 == c2
case let (.boardLevel(b1, _), .boardLevel(b2, _)):
return b1 == b2
case (.rigVolume, .rigVolume):
return true
default:
return false
}
}
}
// MARK: - CC binding
/// A Control-Change number bound to a pedal knob. The incoming value (0–127) is mapped across
/// the knob's own range; `inverted` swaps heel/toe for reversed expression pedals.
public struct CCBinding: Codable, Equatable, Sendable {
/// The Control Change number (0–127).
public var controller: UInt8
/// The MIDI channel (0–15), or `nil` to match any channel (omni).
public var channel: UInt8?
/// The pedal knob this CC drives.
public var target: CCTarget
/// When `true`, CC 0 maps to the knob's maximum and 127 to its minimum.
public var inverted: Bool
/// Creates a CC binding.
///
/// - Parameters:
/// - controller: Control Change number (0–127).
/// - channel: MIDI channel (0–15), or `nil` for omni. Defaults to `nil`.
/// - target: The pedal knob to drive.
/// - inverted: Reverse the sweep direction. Defaults to `false`.
public init(
controller: UInt8,
channel: UInt8? = nil,
target: CCTarget,
inverted: Bool = false
) {
self.controller = controller
self.channel = channel
self.target = target
self.inverted = inverted
}
}
}
+163
View File
@@ -4,6 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
@@ -59,8 +60,37 @@ open class Pedal: SynthesizerBase {
/// safe 48 kHz fallback.
public var sampleRate: Double = 48000.0
// MARK: - Tempo / engine (injected)
/// Shared tempo clock, injected by `PedalBoard.add(_:)` for tempo-aware pedals (the
/// looper's beat-quantized transport). `nil` for pedals added to a board that was
/// created without a clock (e.g. a bare parallel sub-board). Weak: the clock is owned
/// by `ShoeGaze` and outlives every pedal.
public internal(set) weak var clock: LyrebirdClock?
/// The engine that owns this pedal's nodes, injected by `PedalBoard.add(_:)`. Needed by
/// tempo-aware pedals to start a `LyrebirdRoutine` that waits on beat boundaries. Weak:
/// the engine owns the node tree, not the reverse.
public internal(set) weak var hostEngine: SynthesisEngine?
// MARK: - Tempo sync
/// Sync state per tempo-syncable parameter, keyed by ``TempoSyncableParam/key``. A missing
/// key means ``TempoSync/free``. Persisted in ``PedalState`` and restored on rig load.
public internal(set) var tempoSync: [String: TempoSync] = [:]
/// Observable signal bumped on every ``tempoSync`` change so a SwiftUI badge re-renders when the
/// sync state changes through any path (the picker, a preset load, or a lightweight recall).
public let tempoSyncRevision: TempoSyncRevision = TempoSyncRevision()
// MARK: - Identity / routing
/// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI
/// bindings to address the pedal by id rather than by chain position. Defaults to a fresh
/// `UUID` for a newly-created pedal; a rebuild from a saved rig restores the saved id
/// (`board.add(_:)` / preset apply sets it), so a pedal keeps its identity across edits.
public internal(set) var id: UUID = UUID()
/// Human-readable name for the pedal (e.g. "Overdrive", "Delay").
public let displayName: String
@@ -87,6 +117,31 @@ open class Pedal: SynthesizerBase {
/// Override in a widener or stereo-native subclass.
open var channelKind: PedalChannelKind { .mono }
/// Whether the UI shows the common wet/dry `Mix` control for this pedal. Defaults to `true`.
/// A pedal that manages its own dry/wet balance internally (e.g. the looper, where the clean
/// signal always passes through) overrides this to `false` so the confusing Mix knob is hidden
/// and `mix` stays at its fully-wet default.
open var showsMixControl: Bool { true }
/// Called on the main thread when the audio engine is stopped by the user (via
/// `ShoeGaze.stopEngine()`), not during a transient stop-around-rebuild. Stateful pedals
/// (e.g. the looper) override this to return to a clean state. Default: no-op.
open func engineDidStop() {}
/// Called on the main thread just before the rig is torn down (rig load / clear / input-source
/// change), while the pedal is still live. Stateful pedals override this to stop any background
/// work and return to a clean state before their instance is discarded. Default: no-op.
///
/// - Important: Fired from `ShoeGaze.teardown()`, which — like all node-removal paths — must
/// run with the engine already stopped. An override that clears buffers or stops RT-adjacent
/// work relies on that precondition; do not call `teardown()` with the engine running.
open func rigWillTeardown() {}
/// Number of standard enclosure widths this pedal's card occupies in the UI. Defaults
/// to `1`. A control-dense pedal (e.g. the looper) overrides to `2` for a wider card.
/// The UI multiplies its base enclosure width by this factor; `1` is the normal stompbox.
open var widthUnits: Int { 1 }
/// `true` when the board has placed this pedal in a stereo (width-2) region.
public var isStereo: Bool { outputBusRight != nil }
@@ -128,6 +183,17 @@ open class Pedal: SynthesizerBase {
self.mix = initialMix
}
// MARK: - Description
/// One-line, user-facing description of what this pedal does.
///
/// Shown as a subtitle in the pedal picker and as the body of the pedal's info panel.
/// **Every pedal must override this** with a short, non-proprietary sentence — the empty
/// default is a placeholder only (a test asserts every registered pedal sets it).
open var summary: String {
""
}
// MARK: - UI knob descriptors
/// Effect-specific knobs for this pedal, listed before the common knobs in the UI.
@@ -157,6 +223,33 @@ 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] {
[]
}
/// Effect-specific transport controls, rendered as a row directly below the knobs — above
/// ``effectButtons``. Use for the persistent state toggles and transport stops that read as
/// a group distinct from the momentary "do it now" actions (e.g. a looper's Loop / Stop /
/// Cue Stop / Reverse). Defaults to empty; a pedal with none simply skips the row.
open var effectTransportButtons: [PedalButton] {
[]
}
/// Effect-specific action buttons for this pedal, rendered as a row of stomp-style
/// buttons beneath the transport row.
///
/// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset")
/// that need a non-RT side effect beyond writing a single parameter value — see
/// ``PedalButton``. Defaults to empty.
open var effectButtons: [PedalButton] {
[]
}
/// All knobs a generic UI should render for this pedal: effect-specific knobs
/// first, then the common `mix` and `level` knobs. The `bypass` parameter is
/// surfaced separately as a header toggle, not as a knob.
@@ -167,6 +260,76 @@ 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: - Tempo sync
/// Parameters this pedal exposes to tempo sync (delay times, LFO rates). Empty by default —
/// override in subclasses whose time- or rate-based parameters can lock to the tempo.
///
/// Each descriptor's ``TempoSyncableParam/key`` must be unique within the pedal and stable
/// across versions (it is the persistence key). Order is the order the sync controls appear.
open var tempoSyncableParams: [TempoSyncableParam] {
[]
}
/// Recomputes and writes every parameter currently locked to a note division, from the shared
/// clock's tempo. Main-thread only — writing a `@UIParam` is the same path as a knob turn.
///
/// A no-op when no clock is injected. Free parameters are left untouched. A synced value that
/// falls outside the parameter's range (a long division past a delay's maximum time) is clamped.
/// Called by `ShoeGaze` whenever the tempo changes and whenever a parameter's sync state changes.
public func applyTempoSync() {
guard let clock: LyrebirdClock = clock else { return }
let bpm: Double = clock.bpm
guard bpm > 0 else { return }
for param: TempoSyncableParam in tempoSyncableParams {
guard case .division(let division) = tempoSync[param.key] ?? .free else { continue }
param.node.update(param.value(for: division, bpm: bpm).value)
}
}
/// Sets one parameter's sync state and immediately recomputes it. Pass ``TempoSync/free`` to
/// return the parameter to knob control (its value stays at the last synced number until the
/// knob moves it), or `.division(_:)` to lock it to a note value of the live tempo.
///
/// - Parameters:
/// - sync: The new sync state.
/// - key: The ``TempoSyncableParam/key`` of the parameter to update.
public func setSync(_ sync: TempoSync, for key: String) {
tempoSync[key] = sync
tempoSyncRevision.bump()
applyTempoSync()
}
/// Whether `node` backs a tempo-syncable parameter currently locked to a note division.
///
/// Used by MIDI to leave a synced parameter alone: its value is derived from the tempo, so a CC
/// write would be immediately overwritten on the next tempo change. Matches by node identity, so
/// it stays correct regardless of control ordering. Returns `false` for a free or non-syncable node.
public func isNodeTempoSynced(_ node: UIParamNode) -> Bool {
for param: TempoSyncableParam in tempoSyncableParams where param.node === node {
if case .division = tempoSync[param.key] ?? .free {
return true
}
}
return false
}
// MARK: - Subclass hook
/// Returns the processed (wet) mono signal for this pedal.
+33 -1
View File
@@ -4,6 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
@@ -59,6 +60,10 @@ public final class PedalBoard {
private let engine: SynthesisEngine
/// Shared tempo clock, forwarded to each pedal in `add(_:)` so tempo-aware pedals (the
/// looper) can quantize to beats. `nil` for boards created without one.
private let clock: LyrebirdClock?
/// The bus that feeds the first pedal in the chain.
public let headBus: AudioBus
@@ -89,6 +94,11 @@ public final class PedalBoard {
/// call chains the first pedal after this node automatically (no `after:` arg needed).
public internal(set) var headInputNode: (any Synthesizer)?
/// Stable identity for this board, persisted in ``BoardState`` and used by MIDI bindings to
/// address the board by id rather than by position. Defaults to a fresh `UUID`; a rebuild from
/// a saved rig restores the saved id, so a board keeps its identity across edits and reorders.
public internal(set) var id: UUID = UUID()
/// Display label for the board, shown in the UI. Defaults to `"Board"`; `ShoeGaze`
/// assigns a numbered label (`"Board 1"`, `"Board 2"`, …) when it creates the board.
public var label: String = "Board"
@@ -105,6 +115,22 @@ public final class PedalBoard {
/// `nil` until `finalizeBoard(_:)`.
public internal(set) var crossfadeTimeNode: UIParamNode?
/// The live per-board full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough).
/// `nil` until `finalizeBoard(_:)`. Driven by `ShoeGaze.setBoard(_:bypassed:)`.
public internal(set) var boardBypassNode: UIParamNode?
/// The live rig-wide full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough),
/// driven across every board by `ShoeGaze.setRigBypassed(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigBypassNode: UIParamNode?
/// The live rig-wide output-volume `UIParamNode` ([0, 1]), driven across every board by
/// `ShoeGaze.setRigVolume(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigVolumeNode: UIParamNode?
/// The live rig-wide output-mute `UIParamNode` (`0` = audible, `1` = silenced), driven across
/// every board by `ShoeGaze.setRigMuted(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigMuteNode: UIParamNode?
/// The output master synth for this board. Set by `ShoeGaze.finalizeBoard(_:)`;
/// used by `ShoeGaze.removeBoard(_:)` to tear down just this board's master.
internal var outputMaster: BoardOutputMaster?
@@ -137,9 +163,13 @@ public final class PedalBoard {
///
/// - Parameters:
/// - engine: The `SynthesisEngine` that will own the pedal nodes.
/// - clock: Shared tempo clock forwarded to tempo-aware pedals (the looper) for
/// beat-quantized transport. Optional; `nil` disables quantization for pedals on
/// this board.
/// - Throws: `BusAllocatorError.noFreeBus` if no mono audio bus is available.
public init(engine: SynthesisEngine) throws {
public init(engine: SynthesisEngine, clock: LyrebirdClock? = nil) throws {
self.engine = engine
self.clock = clock
let head: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
self.headBus = head
self.outputBus = head
@@ -180,6 +210,8 @@ public final class PedalBoard {
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
public func add(_ pedal: Pedal, after predecessor: (any Synthesizer)? = nil) throws {
pedal.sampleRate = engine.sampleRate
pedal.hostEngine = engine
pedal.clock = clock
// Each arm configures the pedal's buses, inserts it, advances the tail, and only then
// records it in `pedals` — so a pedal is never tracked unless it was fully wired and
@@ -0,0 +1,95 @@
// PedalButton.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// A UI-agnostic description of one pedal button — a momentary action trigger or a
/// node-bound toggle, rendered as a stomp-style button.
///
/// Where ``PedalSwitch`` describes a multi-position segmented control, `PedalButton`
/// describes a single button in one of two styles:
/// - `.momentary`: runs a closure on each press (e.g. "Record / Stop", "Reset"). Use this
/// whenever pressing the button must also perform a non-RT side effect (clearing a
/// buffer, requesting a recorder reset) beyond writing a single parameter value.
/// - `.toggle`: flips a bound ``UIParamNode`` between `0` and `1` on each press, with no
/// side effect required — appropriate only when the live audio graph itself reads the
/// node continuously (so toggling the raw value is sufficient).
///
/// A `Pedal` publishes an array of these via ``Pedal/effectButtons`` so a generic
/// pedalboard UI can render a footswitch-style button per action without knowing the
/// concrete pedal type.
public struct PedalButton {
/// Style of button behavior, mirroring `ParameterButton.Style` in `LyrebirdUI`.
public enum Style: Equatable {
/// Executes `action` on each press.
case momentary
/// Flips `node` between `0` and `1` on each press.
case toggle
}
/// Short label shown on the button (e.g. "Record", "Reset").
public let label: String
/// Button behavior style.
public let style: Style
/// The live parameter node this button toggles. Non-`nil` only for `.toggle` style.
public let node: UIParamNode?
/// The action run on each press. Non-`nil` only for `.momentary` style.
public let action: (() -> Void)?
/// Optional LED-indicator node for a `.momentary` button. When non-`nil`, the button is
/// drawn in the same LED + footswitch style as a `.toggle` button, with the LED lit while
/// this node reads `≥ 0.5` — letting a momentary action reflect a persistent state (e.g. a
/// looper's Stop lit while stopped, Cue Stop lit while armed). `nil` renders a plain button.
public let indicator: UIParamNode?
/// Optional live caption describing what the *next* press does, polled by the UI. When set,
/// the button shows this instead of the static `label` — letting a state-driven control (the
/// looper's Loop footswitch) read "Record" → "Set End" → "Overdub" → "Play" as the state
/// changes. `nil` shows the static `label`.
public let dynamicLabel: (() -> String)?
/// Creates a momentary action button.
///
/// - Parameters:
/// - label: Short label shown on the button.
/// - indicator: Optional state node driving an LED (see ``indicator``). Defaults to `nil`
/// for a plain button.
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
/// - action: Closure run on each press.
public init(
label: String,
indicator: UIParamNode? = nil,
dynamicLabel: (() -> String)? = nil,
action: @escaping () -> Void
) {
self.label = label
self.style = .momentary
self.node = nil
self.action = action
self.indicator = indicator
self.dynamicLabel = dynamicLabel
}
/// Creates a toggle button bound to a `UIParamNode`.
///
/// - Parameters:
/// - label: Short label shown on the button.
/// - node: The `UIParamNode` projected value of an `@UIParam` property
/// (`pedal.$loopOn`, `pedal.$reverse`, …).
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
public init(label: String, node: UIParamNode, dynamicLabel: (() -> String)? = nil) {
self.label = label
self.style = .toggle
self.node = node
self.action = nil
self.indicator = nil
self.dynamicLabel = dynamicLabel
}
}
@@ -0,0 +1,38 @@
// PedalControl.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// A continuous pedal control that can be driven by a MIDI Control Change — the common shape of a
/// ``PedalKnob`` and a ``PedalSlider`` (a labelled `UIParamNode` with a value range).
///
/// Used by MIDI mapping to enumerate every CC-assignable control on a pedal uniformly, regardless of
/// how the pedal chose to present it (rotary knob vs vertical fader). Discrete controls (switches,
/// stepped selectors) are intentionally excluded — they suit momentary Program Change bindings, not
/// continuous expression control.
public struct PedalControl {
/// Short display label (e.g. `"Rate"`, `"Position"`).
public let label: String
/// The live parameter node the CC drives.
public let node: UIParamNode
/// Inclusive value range the control spans, in the parameter's own units.
public let range: ClosedRange<Double>
/// Creates a pedal control descriptor.
///
/// - Parameters:
/// - label: Short display label.
/// - node: The live parameter node.
/// - range: Inclusive value range in the parameter's own units.
public init(label: String, node: UIParamNode, range: ClosedRange<Double>) {
self.label = label
self.node = node
self.range = range
}
}
@@ -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
}
}
+20 -1
View File
@@ -49,6 +49,11 @@ public struct PedalSwitch {
/// three-state switch. Must contain at least two options.
public let options: [Option]
/// `true` when this switch controls a tempo-synced behaviour (e.g. the looper's
/// Sync-to-Tempo mode). A generic UI can disable such switches — and the host can force them
/// to their first (off) option — while the tempo indicator is turned off. Defaults to `false`.
public let tempoDependent: Bool
/// Creates a switch descriptor.
///
/// - Parameters:
@@ -56,14 +61,28 @@ public struct PedalSwitch {
/// - node: The `UIParamNode` projected value of an `@UIParam` property
/// (`pedal.$mode`, `pedal.$direction`, …).
/// - options: Ordered switch positions, left to right. At least two.
/// - tempoDependent: `true` if the switch depends on the tempo/clock. Defaults to `false`.
public init(
label: String,
node: UIParamNode,
options: [Option]
options: [Option],
tempoDependent: Bool = false
) {
precondition(options.count >= 2, "PedalSwitch requires at least two options")
self.label = label
self.node = node
self.options = options
self.tempoDependent = tempoDependent
}
/// The value of the next option after the one nearest `current`, wrapping to the first — so a
/// momentary trigger (e.g. a MIDI switch) can oscillate through the positions on each press.
public func nextValue(after current: Double) -> Double {
guard !options.isEmpty else { return current }
let currentIndex: Int = options.indices.min(by: {
abs(options[$0].value - current) < abs(options[$1].value - current)
}) ?? 0
let nextIndex: Int = (currentIndex + 1) % options.count
return options[nextIndex].value
}
}
+99
View File
@@ -0,0 +1,99 @@
// PedalType.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A type-safe identifier for a pedal type, used by the board-edit API instead of a raw string.
///
/// `PedalType` is an extensible token (the `RawRepresentable` struct pattern, à la
/// `Notification.Name`): the built-in pedals are exposed as static members for discoverable,
/// autocompleting call sites —
///
/// ```swift
/// try shoeGaze.appendPedal(.overdrive, to: board)
/// ```
///
/// — while staying open for custom pedals, since any `PedalType("My Pedal")` is valid and a
/// third party can add their own static members in an extension.
///
/// `rawValue` is the pedal's `displayName`, which is exactly what the rig save format stores
/// (`PedalState.type`) and what ``PedalRegistry`` keys on. `PedalType` therefore changes only the
/// authoring call site — the JSON format and load path are unchanged.
///
/// > Note: named `PedalType` rather than `PedalKind` to avoid colliding with Lyrebird's
/// > score-notation `PedalKind` enum, which is visible whenever both modules are imported.
public struct PedalType: RawRepresentable, Hashable, Sendable {
/// The pedal's `displayName`; the key used by ``PedalRegistry`` and stored in saved rigs.
public let rawValue: String
/// Creates a type from a raw `displayName` string.
public init(rawValue: String) {
self.rawValue = rawValue
}
/// Creates a type from a raw `displayName` string.
public init(_ rawValue: String) {
self.rawValue = rawValue
}
}
// MARK: - Built-in pedals
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")
static let noiseGate = PedalType("Noise Gate")
// 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")
// Modulation
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")
// Looper
static let looper = PedalType("Looper")
}
@@ -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)
}
}
@@ -9,7 +9,7 @@ import LyrebirdUI
/// Amplitude-tracked auto-wah pedal built from discrete tracking + filter stages.
///
/// Unlike `MuTronPedal` (which wraps the single fused `MuTronIII` generator), this pedal
/// Unlike `MutantPedal` (which wraps the single fused `MuTronIII` generator), this pedal
/// wires the envelope path explicitly: an `AmplitudeFollower` tracks the dry signal level,
/// the envelope is scaled by `sensitivity` and clamped to `[0, 1]`, then mapped through an
/// exponential `LinExp` curve to a cutoff frequency that sweeps a resonant `SVF` bandpass.
@@ -27,6 +27,11 @@ import LyrebirdUI
/// - `range`: Upper cutoff in Hz reached at full envelope. Sets the sweep span over `freqLo`.
public final class AutoWahPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Touch-sensitive wah that sweeps a resonant filter from your playing dynamics."
}
// MARK: - Parameters
/// Envelope drive into the cutoff sweep. Higher values open the filter on quieter input.
@@ -35,6 +35,11 @@ import LyrebirdUI
/// - `mode` (two-state): `0` = Flip-flop (authentic OC-2), `1` = Tracking (pitch-tracked).
public final class BassOctaverPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Adds a sub-octave below your note for bass-like weight."
}
// MARK: - Parameters
/// −1 octave voice level in `[0, 1]`.
@@ -0,0 +1,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,135 @@
// ChorusPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// True-stereo chorus pedal.
///
/// Two modulated delay lines, fed the same dry signal but driven by sine LFOs 180° apart,
/// produce a wide left/right shimmer. Unlike `ModulationPedal` (which sums Lyrebird's
/// `Chorus` to mono), this pedal is a ``PedalChannelKind/widener`` — it keeps the two voices
/// on separate channels for genuine stereo width.
///
/// Signal path (per channel, inside `wideEffect(_:)`):
/// ```
/// dry → DelayLine(delay: base ± depth·sin(rate)) → wet L / wet R
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - rate: LFO rate in Hz. Range `[0.05, 6]`. Defaults to `0.8`.
/// - depth: Delay-sweep depth in seconds (half-swing around the base delay). Range
/// `[0.0005, 0.008]`. Defaults to `0.003`.
public final class ChorusPedal: Pedal {
// MARK: - Parameters
/// LFO rate in Hz. Range [0.05, 6].
@UIParam public var rate: Double = 0.8
/// Delay-sweep depth in seconds. Range [0.0005, 0.008].
@UIParam public var depth: Double = 0.003
// MARK: - Constants
/// Default wet/dry blend — chorus sits under the dry signal.
private static let defaultMix: Double = 0.5
/// Base delay around which the LFO sweeps, in seconds.
private let baseDelayTime: Double = 0.012
/// Maximum delay the lines are allocated for, in seconds. Covers `baseDelayTime + max depth`.
private let maxDelayTime: Double = 0.03
/// LFO phase for the left voice, in cycles.
private let leftPhase: Double = 0.0
/// LFO phase for the right voice, in cycles — a half cycle (180°) opposite the left.
private let rightPhase: Double = 0.5
// MARK: - UI knobs
private let rateRange: ClosedRange<Double> = 0.05 ... 6.0
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.008
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
PedalKnob(label: "Depth", node: $depth, range: depthRange),
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates a stereo chorus pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Chorus",
inputBus: inputBus,
outputBus: outputBus,
initialMix: ChorusPedal.defaultMix
)
}
public override var summary: String {
"Lush stereo chorus: two detuned voices panned wide for shimmer and depth."
}
// MARK: - Effect
/// Builds one modulated delay line per channel, with the two LFOs in anti-phase.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The left and right wet voices.
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
(voice(dry, phase: leftPhase), voice(dry, phase: rightPhase))
}
/// One chorus voice: a delay line whose time is swept by a sine LFO around `baseDelayTime`.
private func voice(
_ dry: any ValidGeneratorInput,
phase: Double
) -> any ValidGeneratorInput {
let sweep: OscSin.Audio = OscSin.Audio(
freq: $rate,
phase: phase,
mul: $depth,
add: baseDelayTime
)
return DelayLine(
input: dry,
maxDelay: maxDelayTime,
delay: sweep,
sampleRate: sampleRate,
interpolation: .linear
)
}
}
@@ -11,11 +11,13 @@ import LyrebirdUI
///
/// Signal chain (inside `effect(_:)`):
/// ```
/// dry → Compressor.Audio(threshold:, ratio:, attack:, release:, makeupGain:) → mono out
/// dry → × inputGain → Compressor.Audio(threshold:, ratio:, attack:, release:, makeupGain:) → mono out
/// ```
///
/// Attack, release, knee, and makeup gain are fixed at musically sensible defaults.
/// Knobs expose the two most-musical parameters: threshold and ratio.
/// An input gain stage boosts (or cuts) the signal *before* compression, so driving the
/// input harder pushes more of the signal past the threshold. Attack, release, knee, and
/// makeup gain are fixed at musically sensible defaults; knobs expose input gain, threshold,
/// and ratio.
///
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
///
@@ -24,14 +26,24 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - inputGain: Pre-compression input gain in dB. `0` = unity. Range `[-12, 24]`.
/// Defaults to `0.0`.
/// - threshold: Gain-reduction threshold in dB. Signals above this level are
/// compressed. Range `[-40, 0]` dB. Defaults to `-12.0`.
/// - ratio: Compression ratio `≥ 1.0`. `1.0` = bypass, `4.0` = 4:1 compression.
/// Range `[1, 20]`. Defaults to `4.0`.
public final class CompressorPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Feed-forward compressor that evens out dynamics, with a pre-gain input stage."
}
// MARK: - Parameters
/// Pre-compression input gain in dB. Range [-12, 24]. `0` = unity.
@UIParam public var inputGain: Double = 0.0
/// Compression threshold in dB. Range [-40, 0].
@UIParam public var threshold: Double = -12.0
@@ -43,6 +55,10 @@ public final class CompressorPedal: Pedal {
/// Default wet/dry blend — fully wet; the compressor is inserted in-line.
private static let defaultMix: Double = 1.0
/// dB → natural-exponent scale, `ln(10) / 20`. `exp(dB · scale) == 10^(dB/20)`, the
/// linear amplitude multiplier for a dB gain. Applied to the input-gain stage.
private let dbToLinExpScale: Double = 0.115_129_254_649_702_28
/// Attack time constant in seconds — time to reach full gain reduction on a transient.
private let attackTime: Double = 0.01
@@ -57,6 +73,9 @@ public final class CompressorPedal: Pedal {
// MARK: - UI knobs
/// Input-gain knob range in dB.
private let inputGainRange: ClosedRange<Double> = -12.0 ... 24.0
/// Threshold knob range in dB.
private let thresholdRange: ClosedRange<Double> = -40.0 ... 0.0
@@ -65,6 +84,7 @@ public final class CompressorPedal: Pedal {
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Input", node: $inputGain, range: inputGainRange),
PedalKnob(label: "Threshold", node: $threshold, range: thresholdRange),
PedalKnob(label: "Ratio", node: $ratio, range: ratioRange),
]
@@ -91,15 +111,18 @@ public final class CompressorPedal: Pedal {
// MARK: - Effect
/// Applies feed-forward dynamic range compression.
/// Boosts the input by `inputGain` dB, then applies feed-forward dynamic range compression.
///
/// Output is mono.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: Compressed mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
Compressor.Audio(
in: dry,
// Convert the input-gain dB to a linear multiplier (10^(dB/20)) and apply before compression.
let inputGainLinear: Exp.Audio = Exp.Audio($inputGain * dbToLinExpScale)
let boosted: any ValidGeneratorInput = dry * inputGainLinear
return Compressor.Audio(
in: boosted,
threshold: $threshold,
ratio: $ratio,
attack: attackTime,
@@ -22,15 +22,20 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - time: Delay time in seconds. Range `[0.01, 1.5]`. Defaults to `0.25`.
/// - time: Delay time in seconds. Range `[0.01, 5.0]`. Defaults to `0.25`.
/// - feedback: Feedback amount expressed as decay time in seconds — the time
/// for echoes to fall to `targetAmp` (−60 dB). Longer values produce more
/// repeats. Range `[0.05, 6.0]` seconds. Defaults to `1.0`.
public final class DelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Echo delay with adjustable time and decay, from slapback to long repeats."
}
// MARK: - Parameters
/// Delay time in seconds. Range [0.01, 1.5].
/// Delay time in seconds. Range [0.01, 5.0].
@UIParam public var time: Double = 0.25
/// Feedback decay time in seconds (time to reach −60 dB amplitude).
@@ -39,7 +44,7 @@ public final class DelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes the delay line buffer at init.
private let maxDelayTime: Double = 1.5
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -50,7 +55,7 @@ public final class DelayPedal: Pedal {
// MARK: - UI knobs
/// Delay-time knob range in seconds.
private let timeRange: ClosedRange<Double> = 0.01 ... 1.5
private let timeRange: ClosedRange<Double> = 0.01 ... 5.0
/// Feedback (decay-time) knob range in seconds.
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
@@ -77,7 +82,13 @@ public final class DelayPedal: Pedal {
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
PedalKnob(label: "Decay Time", node: $feedback, range: feedbackRange),
]
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
@@ -0,0 +1,130 @@
// DiffuserPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Stereo diffuser pedal: fans the frequency spectrum across the left and right channels.
///
/// A `.widener` pedal. The dry signal is split into overlapping frequency bands; each band is
/// panned by its centre frequency — lows toward the left, highs toward the right — and the
/// `spread` knob sets how far the bands fan out. At `spread = 0` every band sits centre (a mono
/// collapse); at `spread = 1` the spectrum is splayed hard across the stereo field, giving a
/// wide, diffuse image without time smearing.
///
/// Signal path (inside `wideEffect(_:)`), per band `k` at position `pos_k ∈ [-1, 1]`:
/// ```
/// dry → RBJBandPass(freq_k) → ×gainL_k → Σ → left
/// → ×gainR_k → Σ → right
/// gainL_k = 0.5 − 0.5·pos_k·spread, gainR_k = 0.5 + 0.5·pos_k·spread (linear pan)
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - spread: Stereo spectral spread. `0` = centred (mono), `1` = fully fanned L↔R.
/// Range `[0, 1]`. Defaults to `0.6`.
public final class DiffuserPedal: Pedal {
// MARK: - Parameters
/// Stereo spectral spread in [0, 1]. `0` = mono, `1` = full fan.
@UIParam public var spread: Double = 0.6
// MARK: - Constants
private static let defaultMix: Double = 1.0
/// Centre pan gain (each band's gain when `spread == 0` or it sits dead-centre).
private let centerGain: Double = 0.5
/// RBJ band-pass width in octaves — wide enough that adjacent bands overlap and recombine.
private let bandwidthOctaves: Double = 1.5
/// The frequency bands and their base stereo positions (low = left, high = right).
/// `position ∈ [-1, 1]`; multiplied by `spread` to place the band.
private let bands: [(freq: Double, position: Double)] = [
(150.0, -1.0),
(400.0, -0.5),
(1000.0, 0.0),
(2500.0, 0.5),
(6000.0, 1.0),
]
// MARK: - UI knobs
private let spreadRange: ClosedRange<Double> = 0.0 ... 1.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Spread", node: $spread, range: spreadRange),
]
}
// MARK: - Channel topology
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Init
/// Creates a stereo diffuser pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Diffuser",
inputBus: inputBus,
outputBus: outputBus,
initialMix: DiffuserPedal.defaultMix
)
}
public override var summary: String {
"Stereo diffuser that fans the frequency spectrum across the left and right channels."
}
// MARK: - Effect
/// Splits the dry signal into frequency bands and pans each across the field by `spread`.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The left and right diffused signals.
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
var left: (any ValidGeneratorInput)?
var right: (any ValidGeneratorInput)?
for band: (freq: Double, position: Double) in bands {
let bandPass: RBJBandPass.Audio = RBJBandPass.Audio(
input: dry,
freq: band.freq,
bandwidth: bandwidthOctaves
)
// Linear pan, fully expressible as node arithmetic (no per-sample trig):
// gainL = centerGain − (0.5·position)·spread
// gainR = centerGain + (0.5·position)·spread
let halfPosition: Double = centerGain * band.position
let gainL: any ValidGeneratorInput = ($spread * (-halfPosition)) + centerGain
let gainR: any ValidGeneratorInput = ($spread * halfPosition) + centerGain
let leftContribution: any ValidGeneratorInput = bandPass * gainL
let rightContribution: any ValidGeneratorInput = bandPass * gainR
left = left.map { $0 + leftContribution } ?? leftContribution
right = right.map { $0 + rightContribution } ?? rightContribution
}
return (left ?? dry, right ?? dry)
}
}
@@ -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)
}
}
@@ -26,6 +26,11 @@ import LyrebirdUI
/// - `tone`: Lowpass cutoff in Hz applied to the wet signal; lower darkens the echoes.
public final class FeedbackDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Feedback delay with a tone-shaped repeat for dub-style echoes."
}
// MARK: - Parameters
/// Delay time between repeats, in seconds.
@@ -40,7 +45,7 @@ public final class FeedbackDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes the delay-line buffer at init.
private let maxDelayTime: Double = 1.5
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -53,16 +58,22 @@ public final class FeedbackDelayPedal: Pedal {
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.02 ... 1.5
private let timeRange: ClosedRange<Double> = 0.02 ... 5.0
private let feedbackRange: ClosedRange<Double> = 0.1 ... 8.0
private let toneRange: ClosedRange<Double> = 500.0 ... 8000.0
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
PedalKnob(label: "Decay Time", node: $feedback, range: feedbackRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
]
}
@@ -0,0 +1,107 @@
// 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 tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
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
)
}
}
@@ -36,6 +36,11 @@ import LyrebirdUI
/// Range `[200, 8000]` Hz. Defaults to `3500.0`.
public final class FuzzPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Thick, saturated fuzz for aggressive, sustaining distortion."
}
// MARK: - Parameters
/// Pre-gain drive into the saturator. Range [1, 60]; higher = more fuzz.
@@ -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)
}
}
@@ -39,6 +39,11 @@ import LyrebirdUI
/// Defaults to `0.0`.
public final class GraphicEQPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Five-band graphic EQ with per-band faders and a master output level."
}
// MARK: - Parameters
/// Low-shelf gain in dB. Range [-12, 12].
@@ -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)
}
}
@@ -31,6 +31,11 @@ import LyrebirdUI
/// never exceeds this absolute value. Range `[0.1, 1.0]`. Defaults to `0.95`.
public final class LimiterPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Brick-wall limiter with an input boost to push level safely to the ceiling."
}
// MARK: - Parameters
/// Pre-limit input gain (linear multiplier). Range [1, 12].
@@ -0,0 +1,869 @@
// LooperPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
/// A synchronized multitrack loop pedal. Track A's first take defines the master loop length;
/// tracks B–D are overdub layers recorded onto the same grid. All recorded tracks play at once,
/// summed to one output and locked in phase. When the board supplies a tempo ``LyrebirdClock``
/// the master take is beat-quantized so every loop is a whole number of beats long.
///
/// ## The Loop footswitch drives the transport by state
/// - **Clear** (nothing recorded; only track A selectable): press → record A; press → set the
/// loop end (quantized) and drop into overdub on A when it wraps; press → end overdub, keep
/// playing; further presses toggle overdub ↔ play on the selected track.
/// - **Playing, track B–D selected**: press toggles overdub on that track, aligned to A's
/// play-head. Recording an empty track is just overdub onto silence.
/// - Selecting another track ends any overdub on the previous one (it drops to playback). A
/// newly-selected track records nothing until Loop is pressed.
/// - **Stopped** (via Stop / Cue Stop): press → resume all tracks; next press → toggle overdub.
///
/// > Note: Overdub records forward-in-time, so it cannot be engaged while playback is reversed
/// > (the write head would drift against the backward-reading play-head). Engaging overdub is
/// > blocked while `reverse` is on.
///
/// ## Audio graph (built once in `effect(_:)`)
/// One `PlayBuffer` per track, all summed; one always-running overdub `RecordBuffer` per track
/// whose `recLevel` is gated so only the selected, overdubbing track layers new input; a
/// non-looping master recorder for track A's length-defining take. The overdub recorders run
/// continuously while playing (reset to the top at play-start) so their write head stays locked
/// to the shared play-head — overdub can be toggled on any track without drifting out of phase.
public final class LooperPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Multitrack looper: record track A, then layer synced overdubs on tracks B–D."
}
/// Triple-width card: the looper spreads its timeline, knobs, and transport grid across three
/// columns so the tall pedal fits the canvas without scrolling.
public override var widthUnits: Int { 3 }
/// The looper always passes the clean signal through and adds the loop on top (see `effect`),
/// so the wet/dry Mix knob is meaningless — hide it and keep `mix` fully wet.
public override var showsMixControl: Bool { false }
// MARK: - Knobs
/// Fade time constant, in seconds, for the loop on/off mute and the record→play handoff.
@UIParam public var crossfadeTime: Double = LooperPedal.defaultCrossfadeTime
/// Loop playback gain, in dB.
@UIParam public var playbackLevel: Double = 0.0
/// Overdub input gain, in dB.
@UIParam public var overdubLevel: Double = 0.0
/// Retained level of existing loop content on each overdub pass, `[0, 1]`. `1.0` keeps prior
/// layers indefinitely; lower values fade them for a decaying feedback loop.
@UIParam public var feedback: Double = 1.0
// MARK: - Switches
/// Total loop mute. `0` = muted, `1` = audible. Smoothed by `crossfadeTime`.
@UIParam public var loopOn: Double = 1.0
/// Playback direction. `0` = forward, `1` = reverse. Read as `1 − 2·reverse`.
@UIParam public var reverse: Double = 0.0
/// Transport sync mode. `1` = beat-quantized (record start / loop close snap to the next
/// beat via the shared clock); `0` = freeform (immediate, loop length is whatever you play).
/// Persisted with the rig. Default `1`.
@UIParam public var syncToBeat: Double = 1.0
// MARK: - Internal live state (read by the audio graph / UI LEDs)
/// `1` while the loop bank is playing, else `0`. Gates the whole player sum and the overdub
/// recorders' `run`.
@UIParam public var isPlaying: Double = 0.0
/// Play-head reset trigger for every player. Pulsed `0 → 1` at play-start so all tracks
/// start phase-aligned to frame 0.
@UIParam public var playTrigger: Double = 0.0
/// LED state for the Stop footswitch: `1` while stopped, else `0`.
@UIParam public var stoppedIndicator: Double = 0.0
/// LED state for the Cue Stop footswitch: `1` while a stop-at-loop-end is armed.
@UIParam public var cueStopArmed: Double = 0.0
/// LED state for the Loop footswitch: `1` while overdubbing a track.
@UIParam public var overdubIndicator: Double = 0.0
/// LED state for the Reset footswitch: `1` whenever there is something to reset (any state
/// other than clear). Kept in sync by `phase`'s `didSet`.
@UIParam public var resetIndicator: Double = 0.0
// MARK: - Constants
/// Number of loop tracks (A–D).
public static let trackCount: Int = 4
/// Maximum recordable master length, in seconds (each track allocates a buffer this long, so
/// per-instance memory is roughly `trackCount × maxDurationSeconds × sampleRate × 8 bytes`).
private static let maxDurationSeconds: Double = 60.0
private static let defaultCrossfadeTime: Double = 0.05
private static let reverseRateSpan: Double = 2.0
private static let forwardRate: Double = 1.0
private static let minimumLoopFrames: Int = 1
private let crossfadeTimeRange: ClosedRange<Double> = 0.0 ... 2.0
private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Buffers + generators
private var buffers: [LyrebirdBuffer] = []
private var players: [PlayBuffer.Audio] = []
private var overdubRecorders: [RecordBuffer.Audio] = []
private var overdubGates: [ParameterNode] = []
/// Per-track playback mute gate (`1` = audible, `0` = muted), smoothed by `crossfadeTime` and
/// multiplied into each track's player so a recorded track can be silenced.
private var muteGates: [ParameterNode] = []
/// Per-track mute state (`true` = muted).
private var trackMuted: [Bool] = []
/// Non-looping recorder for track A's length-defining first take.
private var masterRecorder: RecordBuffer.Audio?
// MARK: - Transport state
private enum Phase {
case clear
case armedRecord
case recordingMaster
case armedClose
case playing
case stopped
}
private var phase: Phase = .clear {
didSet { resetIndicator = phase == .clear ? 0.0 : 1.0 }
}
/// The track the Loop footswitch records / overdubs into (`0` = A).
private var selectedTrack: Int = 0
/// The track currently overdubbing, or `nil` when just playing.
private var overdubbingTrack: Int?
/// `true` once a track holds recorded material.
private var trackHasContent: [Bool] = []
/// Master loop length in frames (`0` until track A is closed).
private var masterLength: Int = 0
/// Master loop length in whole beats (`0` unless beat-quantized).
private var masterBeats: Double = 0.0
/// Sample time at which the master take began recording, and at which playback last (re)started.
private var recordStartSample: SampleTime = 0
private var playStartSample: SampleTime = 0
/// Play-head position tracking that survives direction changes. `playHeadAnchor01` is the
/// normalised play-head fraction at the last anchor event (playback start or a reverse flip);
/// `playHeadAnchorSample` is the engine sample at that event. Between events the position is
/// `anchor01 + direction · (elapsed / masterLength)`, wrapped into `[0, 1)`. This mirrors the
/// actual `PlayBuffer` play-head — which reverses smoothly from its live phase — instead of the
/// old `1 − forward` reflection that jumped the read-out to the mirror point on every reverse.
private var playHeadAnchor01: Double = 0.0
private var playHeadAnchorSample: SampleTime = 0
private var transportRoutine: LyrebirdRoutine?
private var stopRoutine: LyrebirdRoutine?
private var reverseRoutine: LyrebirdRoutine?
/// Generation guard for a beat-deferred reverse. Separate from `transportGeneration` so
/// scheduling a reverse never invalidates a pending record/close (and vice versa).
private(set) var reverseGeneration: Int = 0
/// Transient notice shown in place of the state description for `noticeDuration` seconds.
private var noticeText: String?
private var noticeExpiry: Date?
private static let noticeDuration: TimeInterval = 4.0
/// Monotonic action generation guarding deferred beat/stop callbacks (see the single-track
/// history — `LyrebirdRoutine.stop()` cannot recall an already-enqueued main-thread hop).
private(set) var transportGeneration: Int = 0
// MARK: - Init
/// Creates a looper pedal.
///
/// - Parameters:
/// - inputBus: Audio bus to read the dry input from. Defaults to `0`; set by the board.
/// - outputBus: Audio bus to write the output to. Defaults to `0`; set by the board.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
}
// MARK: - Knobs / buttons
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Crossfade", node: $crossfadeTime, range: crossfadeTimeRange),
PedalKnob(label: "Playback", node: $playbackLevel, range: levelRangeDb),
PedalKnob(label: "Overdub", node: $overdubLevel, range: levelRangeDb),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
]
}
/// Beat-sync vs freeform transport mode, as a two-position segmented switch below the knobs.
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Sync to Tempo",
node: $syncToBeat,
options: [
PedalSwitch.Option(title: "Free", value: 0.0),
PedalSwitch.Option(title: "Sync", value: 1.0),
],
tempoDependent: true
),
]
}
/// Transport row: the smart Loop footswitch, the two stops, direction, and reset.
public override var effectTransportButtons: [PedalButton] {
[
PedalButton(label: "Loop", indicator: $overdubIndicator,
dynamicLabel: { [weak self] in self?.loopButtonCaption ?? "Loop" }) { [weak self] in self?.pressLoop() },
PedalButton(label: "Stop", indicator: $stoppedIndicator,
dynamicLabel: { [weak self] in self?.stopButtonCaption ?? "Stop" }) { [weak self] in self?.stopPlayback() },
PedalButton(label: "Cue Stop", indicator: $cueStopArmed,
dynamicLabel: { [weak self] in self?.cueStopButtonCaption ?? "Cue Stop" }) { [weak self] in self?.toggleStopAtLoopEnd() },
PedalButton(label: "Reverse", indicator: $reverse,
dynamicLabel: { [weak self] in self?.reverseButtonCaption ?? "Reverse" }) { [weak self] in self?.toggleReverse() },
PedalButton(label: "Reset", indicator: $resetIndicator) { [weak self] in self?.resetLoop() },
]
}
// MARK: - UI read-outs
/// Publicly-observable transport phase for the state indicator, LEDs, and timeline.
public var transportState: LooperTransportState {
switch phase {
case .clear: return .clear
case .armedRecord: return .armedRecord
case .recordingMaster: return .recordingMaster
case .armedClose: return .armedClose
case .playing: return .playing
case .stopped: return .stopped
}
}
/// Index of the selected track, `0 ..< trackCount`.
public var selectedTrackIndex: Int { selectedTrack }
/// The track currently overdubbing, or `nil`.
public var overdubbingTrackIndex: Int? { overdubbingTrack }
/// `true` if track `index` holds recorded material.
public func trackHasContent(_ index: Int) -> Bool {
index >= 0 && index < trackHasContent.count && trackHasContent[index]
}
/// Per-track generator array counts — internal only so a test can verify a graph rebuild
/// (`effect()` re-run) doesn't accumulate them. All four should equal `trackCount`.
var trackGeneratorCountsForTesting: (buffers: Int, players: Int, overdub: Int, gates: Int) {
(buffers.count, players.count, overdubRecorders.count, overdubGates.count)
}
/// `true` while a stop-at-loop-end is armed.
public var isStopAtLoopEndArmed: Bool { cueStopArmed >= 0.5 }
/// Master loop length in frames (`0` until track A is closed).
public var loopFrameCount: Int { masterLength }
/// Master loop length in seconds.
public var loopLengthSeconds: Double { Double(masterLength) / sampleRate }
/// Master loop length in whole beats (`0` unless beat-quantized).
public var loopLengthBeats: Double { masterBeats }
/// Normalised play-head position in `[0, 1)` while playing, else `nil`. Shared by all tracks.
public func playbackPosition01() -> Double? {
guard phase == .playing, masterLength > 0, let engine: SynthesisEngine = hostEngine else {
return nil
}
return playHeadFraction(at: engine.currentTime)
}
/// The normalised play-head fraction in `[0, 1)` at engine sample `sample`, integrating the
/// signed distance travelled since the last anchor (playback start or reverse flip). Reversal
/// simply changes the sign of the accumulation from the current position — no jump.
func playHeadFraction(at sample: SampleTime) -> Double {
guard masterLength > 0 else { return 0.0 }
let direction: Double = reverse >= 0.5 ? -1.0 : 1.0
let elapsed: Double = Double(sample - playHeadAnchorSample)
let raw: Double = playHeadAnchor01 + direction * elapsed / Double(masterLength)
var frac: Double = raw.truncatingRemainder(dividingBy: 1.0)
if frac < 0 { frac += 1.0 }
return frac
}
/// Caption for the Loop footswitch describing what the *next* press does.
public var loopButtonCaption: String {
switch phase {
case .clear: return "Record"
case .armedRecord: return "Recording"
case .recordingMaster: return "Set End"
case .armedClose: return "Closing"
case .stopped: return "Play"
case .playing:
if overdubbingTrack == selectedTrack { return "Play" }
return trackHasContent(selectedTrack) ? "Overdub" : "Record"
}
}
/// Caption for the Stop footswitch (what the next press does).
public var stopButtonCaption: String { phase == .stopped ? "Stopped" : "Stop" }
/// Caption for the Cue Stop footswitch.
public var cueStopButtonCaption: String { isStopAtLoopEndArmed ? "Cancel" : "Cue Stop" }
/// Caption for the Reverse footswitch (the direction the next press switches to).
public var reverseButtonCaption: String { reverse >= 0.5 ? "Forward" : "Reverse" }
/// One-line description of what the pedal is doing now, for the state indicator. A transient
/// notice (e.g. the engine-stop reset) takes precedence for a few seconds.
public var stateDescription: String {
if let notice: String = noticeText, let expiry: Date = noticeExpiry, Date() < expiry {
return notice
}
let armedSuffix: String = isStopAtLoopEndArmed ? " · stop at end" : ""
switch phase {
case .clear: return "Empty — record track A"
case .armedRecord: return "Waiting for beat…"
case .recordingMaster: return "Recording A"
case .armedClose: return "Closing loop…"
case .stopped: return "Stopped"
case .playing:
if let track: Int = overdubbingTrack {
return "Overdubbing \(LooperPedal.trackLabel(track))" + armedSuffix
}
return "Playing" + armedSuffix
}
}
/// The letter for a track index (0 → "A").
public static func trackLabel(_ index: Int) -> String {
let letters: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
return letters.indices.contains(index) ? letters[index] : "?"
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// `effect()` runs from `build()`, which the engine re-invokes via `rebuildGraph()` on
// EVERY add — including the re-adds that a board edit (reorder, insert/remove a neighbour,
// toggle a split) performs on this same instance. Start from a clean slate so the per-track
// generator arrays don't accumulate across rebuilds, and so stale transport state doesn't
// outlive the freshly re-allocated (empty) buffers built below.
resetForRebuild()
let maxFrames: Int = Int(LooperPedal.maxDurationSeconds * sampleRate)
let playbackRate: any ValidGeneratorInput =
LooperPedal.forwardRate - LooperPedal.reverseRateSpan * $reverse
let unity: Double = 1.0
for _: Int in 0 ..< LooperPedal.trackCount {
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
buffers.append(buffer)
let gate: ParameterNode = ParameterNode(0.0)
overdubGates.append(gate)
let muteGate: ParameterNode = ParameterNode(1.0) // 1 = audible
muteGates.append(muteGate)
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffer,
loop: true,
doneAction: .nothing
)
// Always running while playing; its write head stays locked to the shared play-head.
// `recLevel` is zero unless this track is the one being overdubbed; `preLevel` is 1
// (identity — keep existing content) except while overdubbing, when it is `feedback`.
overdub.$run.source = $isPlaying
overdub.$recLevel.source = gate * DbAmp.Control($overdubLevel)
overdub.$preLevel.source = (unity - gate) + gate * $feedback
overdubRecorders.append(overdub)
let player: PlayBuffer.Audio = PlayBuffer.Audio(
buffer: buffer,
loop: true,
interpolation: .cubic,
rate: playbackRate,
trigger: $playTrigger,
mul: DbAmp.Control($playbackLevel)
)
players.append(player)
}
let master: RecordBuffer.Audio = RecordBuffer.Audio(
input: dry,
buffer: buffers[0],
loop: false,
doneAction: .nothing
)
master.run = 0.0
masterRecorder = master
trackHasContent = [Bool](repeating: false, count: LooperPedal.trackCount)
trackMuted = [Bool](repeating: false, count: LooperPedal.trackCount)
// Loop bank audible only while playing and not muted; smoothed to avoid clicks.
let combinedGate: any ValidGeneratorInput = $isPlaying * $loopOn
let smoothedGate: Lag.Control = Lag.Control(input: combinedGate, time: $crossfadeTime)
// Sum all track players, each scaled by its smoothed per-track mute gate. Empty buffers
// contribute silence. Each player is already scaled by the `Playback` level, so `Playback`
// sets the loop amount against the live signal below.
var loopSum: any ValidGeneratorInput =
players[0] * Lag.Control(input: muteGates[0], time: $crossfadeTime)
for i: Int in 1 ..< players.count {
loopSum = loopSum + players[i] * Lag.Control(input: muteGates[i], time: $crossfadeTime)
}
// The clean (dry) signal always passes through at full level; the loop bank is added on
// top, gated by play/mute. `Playback` controls the looped-vs-live balance.
return dry + (loopSum * smoothedGate)
}
// MARK: - Loop footswitch
/// The smart transport press. Behaviour depends on the current phase and selected track.
public func pressLoop() {
switch phase {
case .clear: armMasterRecording()
case .recordingMaster: armCloseMaster()
case .playing: toggleOverdubSelected()
case .stopped: resumePlayback()
case .armedRecord, .armedClose:
break
}
}
/// Handles a tap on a track dot: selects the track, or — when it is already the selected track
/// and holds recorded material — toggles its mute. So a first tap focuses a track (to overdub
/// or record it), and a second tap on that same recorded track mutes/unmutes it.
public func tapTrack(_ index: Int) {
guard index >= 0, index < LooperPedal.trackCount, !buffers.isEmpty else { return }
if index == selectedTrack, trackHasContent(index) {
toggleTrackMute(index)
} else {
selectTrack(index)
}
}
/// `true` if track `index` is currently muted.
public func isTrackMuted(_ index: Int) -> Bool {
index >= 0 && index < trackMuted.count && trackMuted[index]
}
/// Toggles a recorded track's playback mute (smoothed via `crossfadeTime`).
private func toggleTrackMute(_ index: Int) {
guard trackMuted.indices.contains(index), muteGates.indices.contains(index) else { return }
trackMuted[index].toggle()
muteGates[index].value = trackMuted[index] ? 0.0 : 1.0
}
/// Selects the active track (the one Loop records / overdubs into). Only track A is selectable
/// while clear. Selecting a new track ends any overdub on the previous one (it drops to
/// playback); the new track records nothing until Loop.
public func selectTrack(_ index: Int) {
guard index >= 0, index < LooperPedal.trackCount, index != selectedTrack, !buffers.isEmpty else { return }
switch phase {
case .clear:
return // only track A while clear
case .armedRecord, .recordingMaster, .armedClose:
return // not mid master-record
case .playing, .stopped:
break
}
overdubbingTrack = nil // selecting elsewhere ends the current overdub
selectedTrack = index
updateOverdubGates()
}
// MARK: - Stops / reset
/// Advances the Sync mode through its options (Free ↔ Sync), wrapping — so a MIDI switch can
/// oscillate through the positions on each press, matching the segmented control.
public func cycleSyncMode() {
guard let sync: PedalSwitch = effectSwitches.first(where: { $0.node === $syncToBeat }) else { return }
syncToBeat = sync.nextValue(after: syncToBeat)
}
/// Flips playback direction from the current play-head position. In Sync mode the flip is
/// deferred to the next beat; in Free mode (or with no clock/engine, or when not playing) it
/// applies immediately. Engaging reverse ends any active overdub, since overdub records
/// forward-in-time and can't follow a backward-reading play-head (see the class doc).
public func toggleReverse() {
reverseRoutine?.stop()
reverseRoutine = nil
// Not playing: no live play-head to reverse — just flip the direction for the next start.
guard phase == .playing else {
applyReverse(at: hostEngine?.currentTime ?? playHeadAnchorSample)
return
}
reverseGeneration += 1
let generation: Int = reverseGeneration
// Free mode, or no clock/engine to schedule against → reverse immediately from here.
guard syncToBeat >= 0.5, let clock: LyrebirdClock = clock, let engine: SynthesisEngine = hostEngine else {
applyReverse(at: hostEngine?.currentTime ?? playHeadAnchorSample)
return
}
// Sync mode: reverse on the next beat, from wherever the play-head is at that beat.
let target: SampleTime = clock.nextBeat()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: target)
DispatchQueue.main.async { self?.applyDeferredReverse(generation: generation, at: target) }
}
reverseRoutine = routine
routine.start(engine: engine)
}
/// Applies a beat-deferred reverse once its target beat is reached, unless superseded by a
/// newer reverse press or a transport change.
func applyDeferredReverse(generation: Int, at beatSample: SampleTime) {
guard generation == reverseGeneration, phase == .playing else { return }
reverseRoutine = nil
applyReverse(at: beatSample)
}
/// Flips the playback direction, re-anchoring the position read-out to the current play-head so
/// it continues smoothly in the new direction. `sample` is the point the flip takes effect.
func applyReverse(at sample: SampleTime) {
let engagingReverse: Bool = reverse < 0.5
// Re-anchor at the current play-head fraction *before* flipping, so the new-direction
// accumulation starts from where we actually are.
playHeadAnchor01 = playHeadFraction(at: sample)
playHeadAnchorSample = sample
reverse = engagingReverse ? 1.0 : 0.0
if engagingReverse, overdubbingTrack != nil {
overdubbingTrack = nil
updateOverdubGates()
}
}
/// Immediately halts playback of all tracks; recorded content is retained (resume via Loop).
public func stopPlayback() {
guard phase == .playing else { return }
transportGeneration += 1
stopRoutine?.stop()
stopRoutine = nil
reverseRoutine?.stop()
reverseRoutine = nil
cueStopArmed = 0.0
overdubbingTrack = nil
updateOverdubGates()
isPlaying = 0.0
playTrigger = 0.0 // rearm the play-head reset edge
stoppedIndicator = 1.0
phase = .stopped
}
/// Arms (or cancels) a stop that fires when the loop next reaches its end. No-op unless
/// playing. With no engine to schedule against, stops now.
public func toggleStopAtLoopEnd() {
if isStopAtLoopEndArmed {
stopRoutine?.stop()
stopRoutine = nil
cueStopArmed = 0.0
transportGeneration += 1
return
}
guard phase == .playing, masterLength > 0 else { return }
transportGeneration += 1
let generation: Int = transportGeneration
guard let engine: SynthesisEngine = hostEngine else {
stopPlayback()
return
}
let frames: SampleTime = SampleTime(masterLength)
let elapsed: SampleTime = max(0, engine.currentTime - playStartSample)
let boundary: SampleTime = playStartSample + (elapsed / frames + 1) * frames
cueStopArmed = 1.0
stopRoutine?.stop()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: boundary)
DispatchQueue.main.async { self?.applyStopAtLoopEnd(generation: generation) }
}
stopRoutine = routine
routine.start(engine: engine)
}
/// Applies an armed "stop at end" once the boundary is reached, unless superseded.
func applyStopAtLoopEnd(generation: Int) {
guard generation == transportGeneration, phase == .playing else { return }
cueStopArmed = 0.0
overdubbingTrack = nil
updateOverdubGates()
isPlaying = 0.0
playTrigger = 0.0
stoppedIndicator = 1.0
phase = .stopped
}
/// When the engine is stopped by the user, drop any recorded loop and return to the clear
/// state — a stopped engine can't keep a loop running, and resuming into a half-recorded take
/// is confusing. Posts a notice to the message log and briefly on the pedal's own card.
public override func engineDidStop() {
resetAndNotify("engine stopped")
}
/// The rig is being torn down (load / clear / input-source change) — reset before this looper
/// instance is discarded, stopping any background routines cleanly and logging a notice.
public override func rigWillTeardown() {
resetAndNotify("rig changed")
}
/// Returns to the clear state and posts a notice (message log + briefly on the pedal card),
/// unless already clear. Shared by ``engineDidStop()`` and ``rigWillTeardown()``.
private func resetAndNotify(_ reason: String) {
guard phase != .clear else { return }
resetLoop()
let message: String = "Looper reset — \(reason)."
noticeText = message
noticeExpiry = Date().addingTimeInterval(LooperPedal.noticeDuration)
LyrebirdMessageCenter.shared.info(message, source: displayName)
}
/// Returns the pedal to the clear state: all tracks cleared, track A selected, length reset.
/// If sound is playing it acts as an immediate stop-and-clear.
public func resetLoop() {
transportRoutine?.stop()
transportRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
reverseRoutine?.stop()
reverseRoutine = nil
transportGeneration += 1
// Gate the recorders off (they run off `$isPlaying`) and stop the master BEFORE clearing,
// so the only overlap with `clear()` is at most the one RT block already in flight.
isPlaying = 0.0
masterRecorder?.run = 0.0
masterRecorder?.requestReset()
for recorder: RecordBuffer.Audio in overdubRecorders {
recorder.requestReset()
}
// `clear()` zeroes the buffers on the main thread. `isPlaying = 0` above stops the
// recorders from the next block on, so `clear()` can overlap only the single in-flight
// RT block; that overlap is benign because `LyrebirdBuffer.clear()` (`vDSP_vclrD`) and
// the recorder both write whole 8-byte-aligned `Double` slots — no torn value — and the
// buffer is being zeroed anyway. Deferring the clear would instead race a fast
// reset→re-record, so it runs immediately.
for buffer: LyrebirdBuffer in buffers {
buffer.clear()
buffer.setLoopLength(buffer.count)
}
for i: Int in trackHasContent.indices {
trackHasContent[i] = false
}
for i: Int in trackMuted.indices {
trackMuted[i] = false
}
for gate: ParameterNode in muteGates {
gate.value = 1.0
}
selectedTrack = 0
overdubbingTrack = nil
masterLength = 0
masterBeats = 0.0
loopOn = 1.0
reverse = 0.0 // clean slate: forward playback
playTrigger = 0.0
stoppedIndicator = 0.0
cueStopArmed = 0.0
// Drop any lingering transient notice so it can't mask the fresh state indicator.
noticeText = nil
noticeExpiry = nil
updateOverdubGates()
phase = .clear
}
// MARK: - Transport helpers
/// Clears the per-track generator arrays and returns transport state to clear, so a graph
/// rebuild (`build()` re-run) starts fresh instead of doubling the arrays or leaving state
/// that references the discarded buffers. Called at the top of ``effect(_:)``.
private func resetForRebuild() {
transportRoutine?.stop()
transportRoutine = nil
stopRoutine?.stop()
stopRoutine = nil
reverseRoutine?.stop()
reverseRoutine = nil
buffers.removeAll()
players.removeAll()
overdubRecorders.removeAll()
overdubGates.removeAll()
muteGates.removeAll()
masterRecorder = nil
trackHasContent = []
trackMuted = []
selectedTrack = 0
overdubbingTrack = nil
masterLength = 0
masterBeats = 0.0
isPlaying = 0.0
loopOn = 1.0
reverse = 0.0
playTrigger = 0.0
stoppedIndicator = 0.0
cueStopArmed = 0.0
overdubIndicator = 0.0
noticeText = nil
noticeExpiry = nil
phase = .clear
}
private func updateOverdubGates() {
for i: Int in overdubGates.indices {
overdubGates[i].value = (overdubbingTrack == i) ? 1.0 : 0.0
}
overdubIndicator = overdubbingTrack != nil ? 1.0 : 0.0
}
private func toggleOverdubSelected() {
if overdubbingTrack == selectedTrack {
overdubbingTrack = nil
} else {
// Overdub records forward-in-time; a reversed player reads backward, so engaging
// overdub while reversed would write out of alignment with what's heard. Block it.
guard reverse < 0.5 else { return }
overdubbingTrack = selectedTrack
if trackHasContent.indices.contains(selectedTrack) { trackHasContent[selectedTrack] = true }
}
updateOverdubGates()
}
/// (Re)starts playback of all tracks from the top, optionally overdubbing `overdubTrack`.
///
/// The recorder write heads (`requestReset`) and the player play-heads (`playTrigger` rising
/// edge) are both reset **synchronously here** so they take effect on the same next audio
/// block — keeping overdub writes phase-locked to playback. `playTrigger` is zeroed on every
/// stop so each start is a clean `0 → 1` edge.
private func startPlayback(overdubTrack: Int?, at sample: SampleTime) {
for recorder: RecordBuffer.Audio in overdubRecorders {
recorder.requestReset() // realign every write head to the top
}
playStartSample = sample
// Play head resets to the top (frame 0) via the playTrigger edge below; anchor the
// position read-out there so direction changes accumulate from a known origin.
playHeadAnchor01 = 0.0
playHeadAnchorSample = sample
isPlaying = 1.0
stoppedIndicator = 0.0
overdubbingTrack = overdubTrack
if let track: Int = overdubTrack, trackHasContent.indices.contains(track) {
trackHasContent[track] = true
}
updateOverdubGates()
playTrigger = 1.0 // rising edge, same block as the resets
phase = .playing
}
/// Resumes playback of all active tracks from a stopped state.
private func resumePlayback() {
guard phase == .stopped, masterLength > 0 else { return }
transportGeneration += 1
startPlayback(overdubTrack: nil, at: hostEngine?.currentTime ?? 0)
}
enum QuantizedAction: Sendable {
case beginMaster
case closeMaster
}
private func armMasterRecording() {
selectedTrack = 0 // only track A in the clear state
updateOverdubGates()
phase = .armedRecord
runQuantized(.beginMaster)
}
private func armCloseMaster() {
phase = .armedClose
runQuantized(.closeMaster)
}
private func runQuantized(_ action: QuantizedAction) {
transportGeneration += 1
let generation: Int = transportGeneration
// Freeform (Sync off) or no clock/engine → apply immediately, un-quantized.
guard syncToBeat >= 0.5, let clock: LyrebirdClock = clock, let engine: SynthesisEngine = hostEngine else {
applyQuantizedTransport(action, generation: generation, at: nil)
return
}
transportRoutine?.stop()
let target: SampleTime = clock.nextBeat()
let routine: LyrebirdRoutine = LyrebirdRoutine { [weak self] ctx in
try ctx.waitUntil(sampleTime: target)
DispatchQueue.main.async { self?.applyQuantizedTransport(action, generation: generation, at: target) }
}
transportRoutine = routine
routine.start(engine: engine)
}
func applyQuantizedTransport(_ action: QuantizedAction, generation: Int, at beatSample: SampleTime?) {
guard generation == transportGeneration else { return }
switch action {
case .beginMaster: beginMasterRecording(at: beatSample)
case .closeMaster: closeMasterAndPlay(at: beatSample)
}
}
func beginMasterRecording(at beatSample: SampleTime?) {
guard phase == .armedRecord, let master: RecordBuffer.Audio = masterRecorder else { return }
recordStartSample = beatSample ?? (hostEngine?.currentTime ?? 0)
master.run = 1.0
phase = .recordingMaster
}
func closeMasterAndPlay(at beatSample: SampleTime?) {
guard phase == .armedClose, let master: RecordBuffer.Audio = masterRecorder, !buffers.isEmpty else { return }
master.run = 0.0
let closeSample: SampleTime = beatSample ?? (hostEngine?.currentTime ?? 0)
if let clock: LyrebirdClock = clock, beatSample != nil {
let spanFrames: Int = Int(closeSample - recordStartSample)
masterLength = max(LooperPedal.minimumLoopFrames, spanFrames)
masterBeats = beatsForSpan(frames: masterLength, clock: clock)
} else {
masterLength = max(LooperPedal.minimumLoopFrames, master.recordedFrameCount)
masterBeats = 0.0
}
for buffer: LyrebirdBuffer in buffers {
buffer.setLoopLength(masterLength)
}
if trackHasContent.indices.contains(0) { trackHasContent[0] = true }
// Auto-drop into overdub on track A as it wraps to the top (unless reversed — overdub
// can't follow reverse playback, so just play).
startPlayback(overdubTrack: reverse < 0.5 ? 0 : nil, at: closeSample)
}
/// Whole-beat length of a `frames`-long span at the clock's current tempo (UI read-out only).
func beatsForSpan(frames: Int, clock: LyrebirdClock) -> Double {
let samplesPerBeat: Double = Double(clock.sampleTime(beat: 1.0) - clock.sampleTime(beat: 0.0))
guard samplesPerBeat > 0 else { return 0.0 }
return (Double(frames) / samplesPerBeat).rounded()
}
}
@@ -0,0 +1,34 @@
// LooperTransportState.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Publicly-observable transport phase of the multitrack ``LooperPedal``, surfaced for the UI
/// so it can colour the state indicator, animate the "waiting for the next beat" armed states,
/// and drive the loop timeline.
///
/// The pedal is a synchronized multitrack looper: track A's first take defines the master loop
/// length, and tracks B–D are overdub layers recorded onto the same grid, all playing at once.
public enum LooperTransportState: Sendable, Equatable {
/// No material recorded on any track. Only track A can be selected; press Loop to record it.
case clear
/// A Loop press has been made in the clear state and the pedal is waiting for the next beat
/// to start recording track A.
case armedRecord
/// Recording track A's first take, which defines the master loop length.
case recordingMaster
/// A Loop press closed the master take and the pedal is waiting for the next beat to set the
/// loop end.
case armedClose
/// Looping playback of all recorded tracks. The selected track may be overdubbing.
case playing
/// Playback paused by a stop, with recorded material still loaded (ready to resume).
case stopped
}
@@ -32,6 +32,11 @@ import LyrebirdUI
/// Smaller values (0.001–0.01) produce classic chorus width. Defaults to `0.002`.
public final class ModulationPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Classic mono chorus for subtle thickening and shimmer."
}
// MARK: - Parameters
/// Chorus LFO rate in Hz. Range [0.1, 10].
@@ -85,6 +90,12 @@ public final class ModulationPedal: Pedal {
)
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -28,6 +28,11 @@ import LyrebirdUI
/// - `vol1`, `vol2`, `vol3`: Linear output level of each tap in `[0, 1]`.
public final class MultiTapDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Multi-tap delay producing rhythmic patterns of echoes."
}
// MARK: - Tap times
/// Tap 1 delay time, in seconds.
@@ -53,18 +58,26 @@ public final class MultiTapDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported per-tap delay time in seconds. Sizes each delay-line buffer at init.
private let maxDelayTime: Double = 1.0
private let maxDelayTime: Double = 5.0
/// Partial wet/dry blend so the dry note and its taps coexist.
private static let defaultMix: Double = 0.4
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.01 ... 1.0
private let timeRange: ClosedRange<Double> = 0.01 ... 5.0
private let volRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time1", label: "Time 1", node: $time1, kind: .time, range: timeRange),
TempoSyncableParam(key: "time2", label: "Time 2", node: $time2, kind: .time, range: timeRange),
TempoSyncableParam(key: "time3", label: "Time 3", node: $time3, kind: .time, range: timeRange),
]
}
/// Two rows of three: the three tap times, then the three tap volumes.
public override var effectKnobs: [PedalKnob] {
[
@@ -1,4 +1,4 @@
// MuTronPedal.swift
// MutantPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
@@ -7,7 +7,7 @@
import LyrebirdSynth
import LyrebirdUI
/// Envelope-following filter pedal modeled on the Musitronics Mu-Tron III.
/// Envelope-following auto-wah / funk-filter pedal.
///
/// Wraps the Lyrebird `MuTronIII` generator. The input amplitude drives an exponential
/// cutoff sweep through a resonant Chamberlin state-variable filter. Because `MuTronIII`
@@ -24,7 +24,12 @@ import LyrebirdUI
/// ## Switches
/// - `direction` (two-state): `0` = Down (louder closes the filter), `1` = Up (louder opens it).
/// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass.
public final class MuTronPedal: Pedal {
public final class MutantPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Envelope-following auto-wah / funk filter that opens with your picking."
}
// MARK: - Parameters
@@ -107,10 +112,10 @@ public final class MuTronPedal: Pedal {
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(
name: "Mu-Tron",
name: "Mutant",
inputBus: inputBus,
outputBus: outputBus,
initialMix: MuTronPedal.defaultMix
initialMix: MutantPedal.defaultMix
)
}
@@ -37,6 +37,11 @@ import LyrebirdUI
/// mute, `1` = no gating. Range `[0, 1]`. Defaults to `0.0`.
public final class NoiseGatePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Noise gate that silences hiss and hum below a tunable threshold."
}
// MARK: - Parameters
/// Gate close threshold (linear amplitude). Range [0, 0.2].
@@ -31,6 +31,11 @@ import LyrebirdUI
/// - tone: Octave-channel low-pass cutoff in Hz. Range `[500, 8000]`. Defaults to `4000.0`.
public final class OctaveUpSplitterPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Splits a clean octave-up voice alongside your dry signal in stereo."
}
// MARK: - Parameters
/// Pre-gain into the octave-channel saturator. Range [1, 40]; higher = thicker octave fuzz.
@@ -27,6 +27,11 @@ import LyrebirdUI
/// Range `(0, 20000]`. Defaults to `4000.0`.
public final class OverdrivePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Warm soft-clip overdrive with a tone control, from gentle grit to singing sustain."
}
// MARK: - Parameters
/// Saturation drive amount. Range [1, 20]; higher = more clipping.
@@ -30,6 +30,11 @@ import LyrebirdUI
/// Range `[0.0, 0.9]`. Defaults to `0.5`.
public final class PhaserPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Sweeping phase shifter for swirling, watery motion."
}
// MARK: - Parameters
/// LFO sweep rate in Hz. Range [0.05, 5.0].
@@ -63,6 +68,12 @@ public final class PhaserPedal: Pedal {
/// Feedback knob range (all-pass feedback gain).
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.9
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -32,14 +32,19 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - time: Delay time per tap in seconds. Range `[0.05, 1.0]`. Defaults to `0.3`.
/// - time: Delay time per tap in seconds. Range `[0.05, 5.0]`. Defaults to `0.3`.
/// - feedback: Feedback as decay time in seconds (time for echoes to fall to −60 dB).
/// Range `[0.05, 6.0]`. Defaults to `1.2`.
public final class PingPongDelayPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Stereo ping-pong delay bouncing echoes between left and right."
}
// MARK: - Parameters
/// Delay time per tap in seconds. Range [0.05, 1.0].
/// Delay time per tap in seconds. Range [0.05, 5.0].
@UIParam public var time: Double = 0.3
/// Feedback decay time in seconds (time to reach −60 dB amplitude). Range [0.05, 6.0].
@@ -48,7 +53,7 @@ public final class PingPongDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes both delay lines at init.
private let maxDelayTime: Double = 1.0
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -62,7 +67,7 @@ public final class PingPongDelayPedal: Pedal {
// MARK: - UI knobs
/// Delay-time knob range in seconds.
private let timeRange: ClosedRange<Double> = 0.05 ... 1.0
private let timeRange: ClosedRange<Double> = 0.05 ... 5.0
/// Feedback (decay-time) knob range in seconds.
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
@@ -91,10 +96,16 @@ public final class PingPongDelayPedal: Pedal {
)
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
PedalKnob(label: "Decay Time", node: $feedback, range: feedbackRange),
]
}
@@ -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
)
}
}
@@ -31,6 +31,11 @@ import LyrebirdUI
/// shorter tails. Defaults to `0.5`.
public final class ReverbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Reverb adding space and ambience, from small rooms to vast halls."
}
// MARK: - Parameters
/// Room size in [0, 1]. Larger = longer reverb tail.
@@ -0,0 +1,93 @@
// 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, 5.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, 5.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 = 5.0
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.05 ... 5.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
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,84 @@
// RingModulatorPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Ring modulator pedal.
///
/// Multiplies the input by a tunable sine carrier, producing sum-and-difference sidebands —
/// metallic, bell-like, and robotic tones. Below ~30 Hz the carrier reads as tremolo-style
/// amplitude modulation; in the audio range it becomes classic ring modulation.
///
/// Signal path (inside `effect(_:)`):
/// ```
/// dry × OscSin(frequency) → wet
/// ```
///
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - frequency: Carrier frequency in Hz. Range `[20, 2000]`. Defaults to `220.0`.
public final class RingModulatorPedal: Pedal {
// MARK: - Parameters
/// Carrier frequency in Hz. Range [20, 2000].
@UIParam public var frequency: Double = 220.0
// MARK: - Constants
/// Default wet/dry blend — ring mod is harsh, so keep the dry signal present.
private static let defaultMix: Double = 0.5
// MARK: - UI knobs
private let frequencyRange: ClosedRange<Double> = 20.0 ... 2000.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Frequency", node: $frequency, range: frequencyRange),
]
}
// MARK: - Init
/// Creates a ring modulator pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Ring Modulator",
inputBus: inputBus,
outputBus: outputBus,
initialMix: RingModulatorPedal.defaultMix
)
}
public override var summary: String {
"Multiplies your signal by a tunable carrier for metallic, bell-like, and robotic tones."
}
// MARK: - Effect
/// Multiplies the dry signal by the sine carrier.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The ring-modulated wet signal.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let carrier: OscSin.Audio = OscSin.Audio(freq: $frequency)
return dry * carrier
}
}
@@ -0,0 +1,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
)
}
}

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