39 Commits

Author SHA1 Message Date
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
61 changed files with 5164 additions and 372 deletions
@@ -163,7 +163,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 5;
CURRENT_PROJECT_VERSION = 7;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
@@ -176,7 +176,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 1.3.0;
MARKETING_VERSION = 1.5;
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 = 5;
CURRENT_PROJECT_VERSION = 7;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
@@ -206,7 +206,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 1.3.0;
MARKETING_VERSION = 1.5;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -161,7 +161,7 @@
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 5;
CURRENT_PROJECT_VERSION = 7;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
@@ -172,7 +172,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.3;
MARKETING_VERSION = 1.7;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -191,7 +191,7 @@
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 5;
CURRENT_PROJECT_VERSION = 7;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
@@ -201,7 +201,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.3;
MARKETING_VERSION = 1.7;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
+32 -31
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>
@@ -22,6 +37,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>
@@ -40,45 +67,19 @@
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>NSUbiquitousContainers</key>
<dict>
<key>iCloud.net.realizedsound.ShoeGazeData</key>
<dict>
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
<true/>
<key>NSUbiquitousContainerName</key>
<string>ShoeGaze</string>
<key>NSUbiquitousContainerSupportedFolderLevels</key>
<string>Any</string>
</dict>
</dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>ShoeGaze Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.realizedsound.shoegaze</string>
</array>
</dict>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
@@ -13,8 +13,9 @@ 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 {
@@ -23,20 +24,17 @@ struct ShoeGazeBuilderiOSApp: App {
var body: some Scene {
WindowGroup {
NavigationStack {
ShoeGazeBuilderView(
shoeGaze: model.shoeGaze,
library: model.library,
hardwareSampleRate: { model.hardwareSampleRate },
onEnableLiveInput: { model.enableLiveInput() },
midi: model.midi
)
.navigationTitle("ShoeGaze Builder")
.navigationBarTitleDisplayMode(.inline)
.task { await model.startLibrary() }
}
.onDisappear { model.stop() }
.onOpenURL { url in model.importDocument(at: url) }
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.
+3 -1
View File
@@ -30,7 +30,7 @@
<key>UILaunchScreen</key>
<dict/>
<key>UIRequiresFullScreen</key>
<true/>
<false/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
@@ -40,6 +40,8 @@
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
</dict>
</plist>
+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"
}
},
{
+2 -1
View File
@@ -23,7 +23,7 @@ let package = Package(
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
],
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.0"),
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.3"),
],
targets: [
// The core target depends on LyrebirdUI as well as the synthesis core:
@@ -51,6 +51,7 @@ let package = Package(
name: "LyrebirdShoeGazeTests",
dependencies: [
"LyrebirdShoeGaze",
"LyrebirdShoeGazeUI",
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
+31
View File
@@ -1,5 +1,36 @@
# Releases
## 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
@@ -1,5 +1,5 @@
{
"originHash" : "bf2bd285202c1d5cb51cc77815e3eb9675170cb3bef2db60c355d2222c555750",
"originHash" : "91598bde27d299c8e3d95f9dc660396f52cf9b8e78f90ff2652c9d34d869f572",
"pins" : [
{
"identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
"revision" : "8a2eb191a204a76735ba7eeac94e18f2e65f1b23",
"version" : "1.2.2"
}
},
{
@@ -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)
}
}
}
@@ -266,26 +266,22 @@ public final class MIDIController {
/// address is out of range or a captured display-name hint no longer matches (stale binding).
private func resolveCC(_ target: MIDIMap.CCTarget) -> ResolvedCC? {
switch target {
case let .pedalControl(boardIndex, pedalIndex, controlIndex, nameHint, labelHint):
guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return nil }
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]
if let nameHint: String = nameHint, nameHint != pedal.displayName { return nil }
if let labelHint: String = labelHint, labelHint != control.label { return nil }
let hinted: MIDIMap.CCTarget = .pedalControl(
boardIndex: boardIndex,
pedalIndex: pedalIndex,
pedalID: pedalID,
controlIndex: controlIndex,
pedalNameHint: pedal.displayName,
controlLabelHint: control.label
)
return ResolvedCC(node: control.node, range: control.range, hinted: hinted)
case let .boardLevel(boardIndex, labelHint):
guard let board: PedalBoard = board(at: boardIndex),
case let .boardLevel(boardID, _):
guard let board: PedalBoard = board(id: boardID),
let node: UIParamNode = board.masterGainNode else { return nil }
if let labelHint: String = labelHint, labelHint != board.label { return nil }
let hinted: MIDIMap.CCTarget = .boardLevel(boardIndex: boardIndex, boardLabelHint: board.label)
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.
@@ -340,14 +336,14 @@ public final class MIDIController {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return }
for binding: MIDIMap.SwitchBinding in map.switches where binding.program == program {
if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue }
perform(binding.action, hint: binding.displayNameHint)
perform(binding.action)
}
}
/// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch;
/// `boardSolo` is exclusive (radio). Stale bindings (chain edited under the positional address)
/// are skipped via bounds + display-name checks.
private func perform(_ action: MIDIMap.Action, hint: String?) {
/// `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:
@@ -357,58 +353,89 @@ public final class MIDIController {
case .allBoards:
// One-shot: cancel any solo and bring every board back up.
shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade)
case .boardSolo(let boardIndex):
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
case .boardSolo(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade)
case .boardAudible(let boardIndex):
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
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 boardIndex):
guard let board: PedalBoard = board(at: boardIndex), matchesBoard(board, hint) else { return }
case .boardBypass(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board))
case .pedalBypass(let boardIndex, let pedalIndex):
guard let pedal: Pedal = pedal(boardIndex: boardIndex, pedalIndex: pedalIndex) else { return }
if let hint: String = hint, hint != pedal.displayName { return }
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()
}
}
/// A display-name hint for an action, captured at learn time for stale-binding detection.
/// Dispatches a pedal-specific momentary action. New `PedalActionKind` cases add a
/// branch here once the pedal type they target exists.
private func performPedalAction(_ kind: MIDIMap.PedalActionKind, on pedal: Pedal) {
let toggleThreshold: Double = 0.5
switch kind {
case .looperRecordStop:
// The smart Loop footswitch drives record / set-end / overdub / play by state.
(pedal as? LooperPedal)?.pressLoop()
case .looperOverdubToggle:
// Overdub is toggled by the same Loop press once a loop is playing.
(pedal as? LooperPedal)?.pressLoop()
case .looperLoopToggle:
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
let node: UIParamNode = looper.$loopOn
node.update(node.value < toggleThreshold ? 1.0 : 0.0)
case .looperReset:
(pedal as? LooperPedal)?.resetLoop()
case .looperStop:
(pedal as? LooperPedal)?.stopPlayback()
case .looperCueStop:
(pedal as? LooperPedal)?.toggleStopAtLoopEnd()
case .looperReverse:
(pedal as? LooperPedal)?.toggleReverse()
case .looperSyncToggle:
(pedal as? LooperPedal)?.cycleSyncMode()
case .looperTrack(let index):
(pedal as? LooperPedal)?.tapTrack(index)
}
}
/// A display-name hint for an action, captured at learn time for the mapping-sheet UI label.
/// Not used for resolution (bindings resolve by UUID) — purely a human-readable snapshot.
private func hint(for action: MIDIMap.Action) -> String? {
switch action {
case .rigBypass, .rigMute, .allBoards:
return nil
case .boardSolo(let index), .boardAudible(let index), .boardBypass(let index):
return board(at: index)?.label
case .pedalBypass(let boardIndex, let pedalIndex):
return pedal(boardIndex: boardIndex, pedalIndex: pedalIndex)?.displayName
}
}
/// `true` when a board still matches its captured hint (or no hint was captured).
private func matchesBoard(_ board: PedalBoard, _ hint: String?) -> Bool {
guard let hint: String = hint else { return true }
return board.label == hint
}
/// Resolves a board by index, or `nil` if out of range.
private func board(at index: Int) -> PedalBoard? {
guard let shoeGaze: ShoeGaze = shoeGaze, index >= 0, index < shoeGaze.boards.count else {
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
}
return shoeGaze.boards[index]
}
/// Resolves a pedal by board + pedal index, or `nil` if either index is out of range.
private func pedal(boardIndex: Int, pedalIndex: Int) -> Pedal? {
guard let shoeGaze: ShoeGaze = shoeGaze,
boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return nil }
let board: PedalBoard = shoeGaze.boards[boardIndex]
guard pedalIndex >= 0, pedalIndex < board.pedals.count else { return nil }
return board.pedals[pedalIndex]
/// Resolves a board by its stable id, or `nil` if no board in the rig has that id.
private func board(id: UUID) -> PedalBoard? {
shoeGaze?.boards.first { $0.id == id }
}
/// Resolves a pedal by its stable id across all boards' linear pedal chains, or `nil` if no
/// pedal in the rig has that id.
private func pedal(id: UUID) -> Pedal? {
guard let shoeGaze: ShoeGaze = shoeGaze else { return nil }
for board: PedalBoard in shoeGaze.boards {
if let match: Pedal = board.pedals.first(where: { $0.id == id }) { return match }
}
return nil
}
// MARK: - Device detection
+51 -13
View File
@@ -4,13 +4,18 @@
// 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. Controls are
/// addressed **positionally** (board index, pedal index, knob index) since boards and pedals have no
/// stable identity; the `*Hint` fields carry the resolved display name at learn time so a binding
/// that no longer matches (chain edited) can be detected and skipped rather than mis-fire.
/// 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.
@@ -45,10 +50,44 @@ public struct MIDIMap: Codable, Equatable, Sendable {
case rigMute
/// Cancels any solo and makes every board audible again (the "All" button).
case allBoards
case boardSolo(boardIndex: Int)
case boardAudible(boardIndex: Int)
case boardBypass(boardIndex: Int)
case pedalBypass(boardIndex: Int, pedalIndex: Int)
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
@@ -98,15 +137,14 @@ public struct MIDIMap: Codable, Equatable, Sendable {
/// A knob or slider on a pedal, indexed into `pedal.ccMappableControls`.
case pedalControl(
boardIndex: Int,
pedalIndex: Int,
pedalID: UUID,
controlIndex: Int,
pedalNameHint: String?,
controlLabelHint: String?
)
/// A board's master output level (the board fader).
case boardLevel(boardIndex: Int, boardLabelHint: String?)
case boardLevel(boardID: UUID, boardLabelHint: String?)
/// The rig-wide output volume (applies to the whole rig).
case rigVolume
@@ -115,8 +153,8 @@ public struct MIDIMap: Codable, Equatable, Sendable {
/// find and replace a binding regardless of the name captured at learn time).
public func addresses(_ other: CCTarget) -> Bool {
switch (self, other) {
case let (.pedalControl(b1, p1, c1, _, _), .pedalControl(b2, p2, c2, _, _)):
return b1 == b2 && p1 == p2 && c1 == c2
case let (.pedalControl(p1, c1, _, _), .pedalControl(p2, c2, _, _)):
return p1 == p2 && c1 == c2
case let (.boardLevel(b1, _), .boardLevel(b2, _)):
return b1 == b2
case (.rigVolume, .rigVolume):
+63
View File
@@ -4,6 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
@@ -59,8 +60,27 @@ open class Pedal: SynthesizerBase {
/// safe 48 kHz fallback.
public var sampleRate: Double = 48000.0
// MARK: - Tempo / engine (injected)
/// Shared tempo clock, injected by `PedalBoard.add(_:)` for tempo-aware pedals (the
/// looper's beat-quantized transport). `nil` for pedals added to a board that was
/// created without a clock (e.g. a bare parallel sub-board). Weak: the clock is owned
/// by `ShoeGaze` and outlives every pedal.
public internal(set) weak var clock: LyrebirdClock?
/// The engine that owns this pedal's nodes, injected by `PedalBoard.add(_:)`. Needed by
/// tempo-aware pedals to start a `LyrebirdRoutine` that waits on beat boundaries. Weak:
/// the engine owns the node tree, not the reverse.
public internal(set) weak var hostEngine: SynthesisEngine?
// MARK: - Identity / routing
/// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI
/// bindings to address the pedal by id rather than by chain position. Defaults to a fresh
/// `UUID` for a newly-created pedal; a rebuild from a saved rig restores the saved id
/// (`board.add(_:)` / preset apply sets it), so a pedal keeps its identity across edits.
public internal(set) var id: UUID = UUID()
/// Human-readable name for the pedal (e.g. "Overdrive", "Delay").
public let displayName: String
@@ -87,6 +107,31 @@ open class Pedal: SynthesizerBase {
/// Override in a widener or stereo-native subclass.
open var channelKind: PedalChannelKind { .mono }
/// Whether the UI shows the common wet/dry `Mix` control for this pedal. Defaults to `true`.
/// A pedal that manages its own dry/wet balance internally (e.g. the looper, where the clean
/// signal always passes through) overrides this to `false` so the confusing Mix knob is hidden
/// and `mix` stays at its fully-wet default.
open var showsMixControl: Bool { true }
/// Called on the main thread when the audio engine is stopped by the user (via
/// `ShoeGaze.stopEngine()`), not during a transient stop-around-rebuild. Stateful pedals
/// (e.g. the looper) override this to return to a clean state. Default: no-op.
open func engineDidStop() {}
/// Called on the main thread just before the rig is torn down (rig load / clear / input-source
/// change), while the pedal is still live. Stateful pedals override this to stop any background
/// work and return to a clean state before their instance is discarded. Default: no-op.
///
/// - Important: Fired from `ShoeGaze.teardown()`, which — like all node-removal paths — must
/// run with the engine already stopped. An override that clears buffers or stops RT-adjacent
/// work relies on that precondition; do not call `teardown()` with the engine running.
open func rigWillTeardown() {}
/// Number of standard enclosure widths this pedal's card occupies in the UI. Defaults
/// to `1`. A control-dense pedal (e.g. the looper) overrides to `2` for a wider card.
/// The UI multiplies its base enclosure width by this factor; `1` is the normal stompbox.
open var widthUnits: Int { 1 }
/// `true` when the board has placed this pedal in a stereo (width-2) region.
public var isStereo: Bool { outputBusRight != nil }
@@ -177,6 +222,24 @@ open class Pedal: SynthesizerBase {
[]
}
/// Effect-specific transport controls, rendered as a row directly below the knobs — above
/// ``effectButtons``. Use for the persistent state toggles and transport stops that read as
/// a group distinct from the momentary "do it now" actions (e.g. a looper's Loop / Stop /
/// Cue Stop / Reverse). Defaults to empty; a pedal with none simply skips the row.
open var effectTransportButtons: [PedalButton] {
[]
}
/// Effect-specific action buttons for this pedal, rendered as a row of stomp-style
/// buttons beneath the transport row.
///
/// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset")
/// that need a non-RT side effect beyond writing a single parameter value — see
/// ``PedalButton``. Defaults to empty.
open var effectButtons: [PedalButton] {
[]
}
/// All knobs a generic UI should render for this pedal: effect-specific knobs
/// first, then the common `mix` and `level` knobs. The `bypass` parameter is
/// surfaced separately as a header toggle, not as a knob.
+17 -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"
@@ -153,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
@@ -196,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
}
}
+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
}
}
+3
View File
@@ -93,4 +93,7 @@ public extension PedalType {
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,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
}
@@ -4,6 +4,8 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Serialisable snapshot of one `PedalBoard`'s label and full signal-chain topology.
///
/// `label` is the board's display name. `segments` captures the chain in signal-flow order:
@@ -18,6 +20,11 @@
/// subset (the whole chain for boards with no split regions) for callers that only need it.
public struct BoardState: Codable, Equatable {
/// Stable per-board identity, persisted so MIDI bindings can address a board by id rather
/// than by position. Survives capture → rebuild round-trips. Legacy presets without an id
/// decode to a fresh `UUID()`.
public let id: UUID
/// The board's display label (e.g. `"Board 1"`).
public let label: String
@@ -39,9 +46,11 @@ public struct BoardState: Codable, Equatable {
/// - label: The board's display label.
/// - segments: Ordered signal-chain segments.
public init(
id: UUID = UUID(),
label: String,
segments: [BoardSegmentState]
) {
self.id = id
self.label = label
self.segments = segments
}
@@ -55,14 +64,17 @@ public struct BoardState: Codable, Equatable {
/// - label: The board's display label.
/// - pedals: Ordered list of pedal state snapshots.
public init(
id: UUID = UUID(),
label: String,
pedals: [PedalState]
) {
self.id = id
self.label = label
self.segments = pedals.map { BoardSegmentState.pedal($0) }
}
private enum CodingKeys: String, CodingKey {
case id
case label
case segments
case pedals
@@ -72,6 +84,7 @@ public struct BoardState: Codable, Equatable {
/// wrapping each entry as a `.pedal` segment.
public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
self.label = try container.decode(String.self, forKey: .label)
if let decodedSegments: [BoardSegmentState] =
try container.decodeIfPresent([BoardSegmentState].self, forKey: .segments) {
@@ -94,6 +107,7 @@ public struct BoardState: Codable, Equatable {
/// Encodes the snapshot using the current `segments` representation.
public func encode(to encoder: any Encoder) throws {
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(label, forKey: .label)
try container.encode(segments, forKey: .segments)
}
@@ -21,6 +21,7 @@ extension Pedal {
let sliderValues: [Double] = effectSliders.map { $0.node.value }
let selectorValues: [Double] = effectSelectors.map { $0.node.value }
return PedalState(
id: id,
type: displayName,
knobValues: values,
switchValues: switchValues,
@@ -44,6 +45,9 @@ extension Pedal {
/// against `displayName` — the caller is responsible for matching types before
/// calling this method.
public func applyState(_ state: PedalState) {
// Restore the saved identity so the pedal keeps its id across rebuilds; MIDI bindings
// address pedals by this id.
id = state.id
for (knob, value) in zip(knobs, state.knobValues) {
knob.node.update(value)
}
@@ -45,6 +45,6 @@ extension PedalBoard {
return BoardSegmentState.mergeToMono
}
}
return BoardState(label: label, segments: segmentStates)
return BoardState(id: id, label: label, segments: segmentStates)
}
}
@@ -68,6 +68,7 @@ public enum PedalRegistry {
"Bitcrusher": { BitcrusherPedal() },
"Granulator": { GranulatorPedal() },
"Auto Granulator": { AutoGranulatorPedal() },
"Looper": { LooperPedal() },
]
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type
@@ -4,6 +4,8 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Serialisable snapshot of one pedal's parameter values.
///
/// `type` stores the pedal's `displayName` and is used by `PedalRegistry` to
@@ -16,6 +18,12 @@
/// knobs at their current value.
public struct PedalState: Codable, Equatable {
/// Stable per-pedal identity, persisted so MIDI bindings can address a pedal by id rather
/// than by chain position. Survives capture → rebuild round-trips (an edit rebuilds the board
/// from captured segments, carrying each pedal's id forward). Legacy presets without an id
/// decode to a fresh `UUID()`.
public let id: UUID
/// The pedal's `displayName` — used as a factory key by `PedalRegistry`.
public let type: String
@@ -47,6 +55,7 @@ public struct PedalState: Codable, Equatable {
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
public init(
id: UUID = UUID(),
type: String,
knobValues: [Double],
switchValues: [Double] = [],
@@ -54,6 +63,7 @@ public struct PedalState: Codable, Equatable {
selectorValues: [Double] = [],
bypass: Double
) {
self.id = id
self.type = type
self.knobValues = knobValues
self.switchValues = switchValues
@@ -63,6 +73,7 @@ public struct PedalState: Codable, Equatable {
}
private enum CodingKeys: String, CodingKey {
case id
case type
case knobValues
case switchValues
@@ -75,6 +86,7 @@ public struct PedalState: Codable, Equatable {
/// `selectorValues` existed by defaulting the missing keys to an empty array.
public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
self.type = try container.decode(String.self, forKey: .type)
self.knobValues = try container.decode([Double].self, forKey: .knobValues)
self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? []
@@ -17,9 +17,19 @@ public enum RigStore {
private static let folderName: String = "ShoeGaze"
private static let fileName: String = "autosave-rig.json"
/// Test-only override for ``autosaveURL``. When non-`nil`, all autosave reads/writes use this
/// path instead of the real Application Support location — so a test suite never overwrites or
/// deletes the user's actual autosaved rig. Production code leaves this `nil`.
///
/// - Important: Any test that calls `save`/`restore`/`clear` **must** set this to a temporary
/// file first (and reset it after), or it will clobber the running app's autosave.
public static var autosaveURLOverride: URL?
/// Location of the autosave file, creating the containing folder if needed. `nil` if the
/// Application Support directory can't be resolved.
/// Application Support directory can't be resolved. Returns ``autosaveURLOverride`` verbatim
/// when set (tests).
public static var autosaveURL: URL? {
if let override: URL = autosaveURLOverride { return override }
let fileManager: FileManager = FileManager.default
guard let base: URL = try? fileManager.url(
for: .applicationSupportDirectory,
@@ -115,6 +115,7 @@ extension ShoeGaze {
do {
for boardState: BoardState in snapshot.boards {
let board: PedalBoard = try addBoard()
board.id = boardState.id
board.label = boardState.label
try rebuildSegments(boardState.segments, into: board)
try finalizeBoard(board)
@@ -260,9 +261,14 @@ extension ShoeGaze {
// can be restored. May be nil when `board` is unmanaged (not in `boards`).
let oldIndex: Int? = boards.firstIndex(where: { $0 === board })
// MIDI bindings address pedals/boards by UUID (persisted in PedalState/BoardState and
// carried through capture → rebuild), so a rebuild needs no binding reconciliation — the
// pedal keeps its id, and its binding resolves to it regardless of chain position.
// Build the new board FIRST so that any failure leaves the old board intact.
let newBoard: PedalBoard = try addBoard()
do {
newBoard.id = state.id
newBoard.label = state.label
try rebuildSegments(state.segments, into: newBoard)
try finalizeBoard(newBoard)
@@ -56,15 +56,28 @@ public struct ShoeGazeState: Codable, Equatable {
case midiMap
}
/// Decodes a rig snapshot, tolerating an absent OR malformed `midiMap`.
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
///
/// The MIDI map is decoded with `try?` so a binding format that this build can't read (e.g. an
/// autosave written by an older schema) drops just the bindings — which are re-learnable —
/// rather than throwing and losing the entire rig. `version` and `boards` still decode strictly.
/// The MIDI map is decoded in three tiers: (1) the current id-based ``MIDIMap``; (2) failing
/// that, the pre-UUID positional ``LegacyMIDIMap``, migrated to id-based via the boards'
/// freshly-decoded ids so old rigs keep their bindings; (3) failing both (absent or unreadable),
/// `nil` — dropping just the bindings, which are re-learnable, rather than losing the whole rig.
/// `version` and `boards` still decode strictly.
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.version = try container.decode(Int.self, forKey: .version)
self.boards = try container.decode([BoardState].self, forKey: .boards)
self.midiMap = try? container.decodeIfPresent(MIDIMap.self, forKey: .midiMap) ?? nil
let decodedBoards: [BoardState] = try container.decode([BoardState].self, forKey: .boards)
self.boards = decodedBoards
if !container.contains(.midiMap) {
self.midiMap = nil
} else if let current: MIDIMap = try? container.decode(MIDIMap.self, forKey: .midiMap) {
self.midiMap = current
} else if let legacy: LegacyMIDIMap = try? container.decode(LegacyMIDIMap.self, forKey: .midiMap) {
// Pre-UUID positional map: convert each binding to the id now at that position.
self.midiMap = legacy.migrated(boards: decodedBoards)
} else {
self.midiMap = nil
}
}
}
@@ -172,7 +172,10 @@ extension ShoeGaze {
/// incorrect bus; the output track is still written.
/// - `.testLoop` → `boards.first?.headBus.index` (the first board's head bus). Returns `nil`
/// if there are no boards; the input track is skipped and a note is printed.
private func resolvedInputBusIndex() -> Int? {
/// Exposed `internal` (not `private`) so other rig-level features that need the clean
/// pre-effects input signal — e.g. `ShoeGaze+Tuner.swift` — can reuse this resolution
/// instead of duplicating the `.liveInput`/`.testLoop` switch.
internal func resolvedInputBusIndex() -> Int? {
switch inputSource {
case .liveInput(let channel):
do {
@@ -104,6 +104,9 @@ public final class ChainRouter {
private let engine: SynthesisEngine
/// Shared tempo clock, forwarded to both sub-boards so tempo-aware pedals quantize to beats.
private let clock: LyrebirdClock?
/// The shared input source (either a `TestLoopSource` or `HardwareInputPassThrough`).
private let source: any Synthesizer
@@ -152,9 +155,11 @@ public final class ChainRouter {
/// - `EngineAddError` if the engine rejects any node insertion.
public init(
engine: SynthesisEngine,
inputSource: InputSource = .testLoop
inputSource: InputSource = .testLoop,
clock: LyrebirdClock? = nil
) throws {
self.engine = engine
self.clock = clock
// Step 1 — allocate the shared input bus.
let inputBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
@@ -186,8 +191,8 @@ public final class ChainRouter {
self.source = addedSource
// Step 3 — create both boards (each allocates its own head bus).
let createdBoardA: PedalBoard = try PedalBoard(engine: engine)
let createdBoardB: PedalBoard = try PedalBoard(engine: engine)
let createdBoardA: PedalBoard = try PedalBoard(engine: engine, clock: clock)
let createdBoardB: PedalBoard = try PedalBoard(engine: engine, clock: clock)
self.boardA = createdBoardA
self.boardB = createdBoardB
+113 -2
View File
@@ -60,6 +60,11 @@ public final class ShoeGaze {
/// The engine that owns all nodes.
public let engine: SynthesisEngine
/// Shared tempo clock for the tempo indicator / tap-tempo and any future
/// tempo-synced features. Default `120` BPM. `reconfigureEngine(_:)` rebuilds boards
/// against the same `engine` instance, so this clock stays valid across reconfigures.
public let clock: LyrebirdClock
/// All boards managed by this instance.
public private(set) var boards: [PedalBoard] = []
@@ -96,6 +101,54 @@ public final class ShoeGaze {
/// (same module, different file) can mutate it.
internal var recordTaps: [RecordTap] = []
// MARK: - Tuner state
/// `true` while the tuner is engaged (between `engageTuner()` and `disengageTuner()`).
public internal(set) var tunerEngaged: Bool = false
/// Whether ``ShoeGaze/engageTuner()`` also mutes the rig output for the duration.
/// Defaults to `true`. Read and applied only at engage time — toggling this while
/// already engaged takes effect on the next engage/disengage cycle.
public var tunerMutesRig: Bool = true
/// The active `TunerTap`, or `nil` while disengaged. `internal` so
/// `ShoeGaze+Tuner.swift` (same module, different file) can mutate it.
internal var tunerTap: TunerTap?
/// The scratch control bus allocated for `tunerTap`'s unread passthrough output,
/// released on disengage.
internal var tunerScratchControlBus: ControlBus?
/// `rigMuted`'s value at the moment `engageTuner()` muted the rig, so
/// `disengageTuner()` can restore it rather than always unmuting.
internal var tunerRestoreMuteOnDisengage: Bool = false
// MARK: - Tempo state
/// `true` when the tempo indicator (BPM readout / TAP / beat LED) is shown and tempo-synced
/// features are available. Toggle with ``setTempoEnabled(_:)``; when turned off, every
/// tempo-dependent pedal switch (e.g. the looper's Sync-to-Tempo mode) is forced to its
/// first (off) position so nothing keeps quantizing to a hidden clock.
public private(set) var tempoEnabled: Bool = true
/// Timestamps of recent `tapTempo()` calls, oldest first. `internal` so
/// `ShoeGaze+Tempo.swift` (same module, different file) can mutate it.
internal var tapTimestamps: [Date] = []
/// Shows or hides the tempo indicator and, when hiding, deactivates every tempo-synced
/// control by forcing each ``PedalSwitch/tempoDependent`` switch to its first option.
public func setTempoEnabled(_ enabled: Bool) {
tempoEnabled = enabled
guard !enabled else { return }
for pedal: Pedal in allPedals() {
for pedalSwitch: PedalSwitch in pedal.effectSwitches where pedalSwitch.tempoDependent {
if let off: PedalSwitch.Option = pedalSwitch.options.first {
pedalSwitch.node.update(off.value)
}
}
}
}
// MARK: - Scope state
/// Scope tap over the hardware input + output buses, feeding the debug scope view.
@@ -139,11 +192,58 @@ public final class ShoeGaze {
) {
self.engine = engine
self.inputSource = inputSource
clock = LyrebirdClock(engine: engine, bpm: ShoeGaze.defaultTempoBpm)
installScopeTap()
}
// MARK: - Board management
/// Stops the audio engine as a deliberate user action: notifies every pedal via
/// ``Pedal/engineDidStop()`` (so stateful pedals like the looper return to a clean state and
/// post a notice) and then stops the engine. Use this for the user-facing Stop control — not
/// for transient stop-around-rebuild sequences, which call `engine.stop()` directly so
/// pedals keep their state across the restart.
public func stopEngine() {
for pedal: Pedal in allPedals() {
pedal.engineDidStop()
}
engine.stop()
}
/// Every live `Pedal` across all main boards and chain-router branches.
private func allPedals() -> [Pedal] {
var result: [Pedal] = []
for board: PedalBoard in boards {
result.append(contentsOf: pedals(in: board))
}
for router: ChainRouter in routers {
result.append(contentsOf: pedals(in: router.boardA))
result.append(contentsOf: pedals(in: router.boardB))
}
return result
}
/// Every live `Pedal` in one board, including pedals inside its parallel and stereo-split
/// branch sections (branch pedals live in their section objects, not as top-level segments).
private func pedals(in board: PedalBoard) -> [Pedal] {
var result: [Pedal] = []
for segment: BoardSegment in board.orderedSegments {
switch segment {
case .pedal(let pedal):
result.append(pedal)
case .parallel(let section):
result.append(contentsOf: section.branchA.pedals)
result.append(contentsOf: section.branchB.pedals)
case .stereoSplit(let section), .stereoUnzip(let section):
result.append(contentsOf: section.left.pedals)
result.append(contentsOf: section.right.pedals)
case .mergeToMono:
break
}
}
return result
}
/// Allocates a new `PedalBoard` connected to the engine, wires the input source,
/// and returns the board ready for pedals to be added via `board.add(_:)`.
///
@@ -162,7 +262,7 @@ public final class ShoeGaze {
/// - `EngineAddError` if the engine rejects a node insertion.
@discardableResult
public func addBoard() throws -> PedalBoard {
let board: PedalBoard = try PedalBoard(engine: engine)
let board: PedalBoard = try PedalBoard(engine: engine, clock: clock)
board.label = "Board \(boards.count + 1)"
// Route the input source to the board head bus.
@@ -463,6 +563,10 @@ public final class ShoeGaze {
/// Removes a single board and its associated input source and output master from
/// the engine, then releases the board's buses. The other boards are unaffected.
///
/// > Note: MIDI bindings address boards/pedals by UUID, so a removed board's bindings simply
/// > stop resolving (inert, and invisible in the mapping UI since there is no board/pedal to
/// > list) — no binding maintenance is needed here.
///
/// - Important: Same async-removal caveat as ``teardown()`` — call with the engine
/// stopped, or accept up to one block of glitch on a still-running engine.
///
@@ -548,7 +652,7 @@ public final class ShoeGaze {
/// - `EngineAddError` if the engine rejects any node insertion.
@discardableResult
public func makeChainRouter() throws -> ChainRouter {
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource)
let router: ChainRouter = try ChainRouter(engine: engine, inputSource: inputSource, clock: clock)
routers.append(router)
return router
}
@@ -601,6 +705,13 @@ public final class ShoeGaze {
// board buses they reference are released.
stopRecording()
// Notify pedals the rig is being torn down (rig load / clear / input-source change), so
// stateful pedals like the looper stop their background routines cleanly and post a
// notice before their instances are discarded.
for pedal: Pedal in allPedals() {
pedal.rigWillTeardown()
}
// Step 1: Remove all engine nodes that write to board buses.
// Order within this step does not matter; all must finish before bus release.
for tap: TestLoopTap in testLoopTaps {
@@ -0,0 +1,55 @@
// ShoeGaze+Tempo.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - ShoeGaze + Tempo
extension ShoeGaze {
/// Default tempo, in BPM, for a newly-created ``ShoeGaze/clock``.
public static let defaultTempoBpm: Double = 120.0
// MARK: - Tap tempo
/// Minimum plausible interval between taps, in seconds — guards against a double-tap
/// or debounce glitch registering as an implausibly fast tempo (`60 / minTapInterval`
/// ≈ 300 BPM cap).
private static let minTapInterval: TimeInterval = 0.2
/// Maximum interval since the last tap before the tap history resets — a pause this
/// long means the user is starting a new tap-tempo sequence, not continuing one.
private static let tapTimeoutInterval: TimeInterval = 2.0
/// Number of most-recent inter-tap intervals averaged into the computed tempo.
private static let tapHistoryCount: Int = 4
/// Registers one tap-tempo press. Call this each time the user taps (mouse click,
/// screen tap, or MIDI trigger). Averages the last few inter-tap intervals and sets
/// ``ShoeGaze/clock``'s `bpm` once at least two taps have landed within
/// `tapTimeoutInterval` of each other. A pause longer than `tapTimeoutInterval`
/// discards prior taps and starts a fresh sequence.
public func tapTempo() {
let now: Date = Date()
if let last: Date = tapTimestamps.last, now.timeIntervalSince(last) > ShoeGaze.tapTimeoutInterval {
tapTimestamps.removeAll()
}
tapTimestamps.append(now)
if tapTimestamps.count > ShoeGaze.tapHistoryCount + 1 {
tapTimestamps.removeFirst(tapTimestamps.count - (ShoeGaze.tapHistoryCount + 1))
}
guard tapTimestamps.count >= 2 else { return }
let intervals: [TimeInterval] = zip(tapTimestamps, tapTimestamps.dropFirst())
.map { $1.timeIntervalSince($0) }
.filter { $0 >= ShoeGaze.minTapInterval }
guard !intervals.isEmpty else { return }
let averageInterval: TimeInterval = intervals.reduce(0, +) / Double(intervals.count)
let secondsPerMinute: Double = 60.0
clock.bpm = secondsPerMinute / averageInterval
}
}
@@ -0,0 +1,99 @@
// ShoeGaze+Tuner.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// MARK: - ShoeGaze + Tuner
extension ShoeGaze {
// MARK: - Engage / disengage
/// Engages the tuner: taps the clean pre-effects input and, if ``tunerMutesRig`` is on,
/// mutes the rig output for the duration (restoring the prior mute state on disengage).
///
/// A no-op if already engaged. Prints a note and does nothing if no input bus can be
/// resolved (mirrors `startRecording()`'s tolerant `.liveInput`/`.testLoop` fallback).
public func engageTuner() {
guard !tunerEngaged else { return }
guard let busIndex: Int = resolvedInputBusIndex() else {
print("[ShoeGaze] engageTuner: no input bus available — tuner not engaged.")
return
}
do {
// The scratch control bus is allocated once and kept for the session's
// lifetime rather than released on every disengage: `engine.remove(_:)` only
// enqueues the tap's removal for the next render block, so releasing (and
// thus making reallocatable) the bus synchronously here would race a
// not-yet-dequeued write from the outgoing tap.
let scratchBus: ControlBus
if let existing: ControlBus = tunerScratchControlBus {
scratchBus = existing
} else {
scratchBus = try engine.busAllocator.allocateControlBus()
tunerScratchControlBus = scratchBus
}
let tap: TunerTap = TunerTap(inputBusIndex: busIndex, scratchControlBus: scratchBus)
try engine.add(tap, position: .after(engine.mainGroup))
tunerTap = tap
} catch {
print("[ShoeGaze] engageTuner: could not add tuner tap. (\(error))")
return
}
if tunerMutesRig {
tunerRestoreMuteOnDisengage = rigMuted
setRigMuted(true)
}
tunerEngaged = true
}
/// Disengages the tuner and removes its tap. Restores the rig's prior mute state if
/// ``engageTuner()`` muted it.
///
/// The scratch control bus is intentionally NOT released here — see the comment in
/// ``engageTuner()``.
public func disengageTuner() {
guard tunerEngaged else { return }
if let tap: TunerTap = tunerTap {
_ = engine.remove(tap)
}
tunerTap = nil
if tunerMutesRig {
setRigMuted(tunerRestoreMuteOnDisengage)
}
tunerEngaged = false
}
/// Flips ``tunerEngaged`` — convenience for a single stomp-style toggle/MIDI action.
public func toggleTunerEngaged() {
if tunerEngaged {
disengageTuner()
} else {
engageTuner()
}
}
// MARK: - Live pitch read
/// The most recently detected pitch, in Hz, or `nil` while the tuner is not engaged.
/// Safe to poll from a SwiftUI `.task` loop on the main thread.
public var currentPitchHz: Double? {
guard tunerEngaged else { return nil }
return tunerTap?.pitchCapture?.detectedFrequencyHz
}
/// The YIN tracking confidence in `[0, 1]` for the current pitch, or `nil` while the
/// tuner is not engaged. `1.0` = certain, `0.0` = no stable pitch. The UI latches its
/// display when this drops below its threshold (e.g. during a note attack/restrike).
public var currentPitchConfidence: Double? {
guard tunerEngaged else { return nil }
return tunerTap?.pitchCapture?.detectedConfidence
}
}
@@ -0,0 +1,103 @@
// TunerPitchCapture.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import Synchronization
/// Wraps a YIN `FreqTracker` and atomically snapshots its per-block frequency **and
/// confidence** into plain `Double`s readable from any thread — the same RT-writes/non-RT-
/// polls contract as `ParameterNode`'s atomic value storage, sized down to two scalars.
///
/// YIN (via `FreqTracker`) is far steadier than zero-crossing detection on a plucked/
/// harmonic-rich guitar signal, and its confidence output lets the UI latch the last stable
/// reading through low-confidence transients (note attacks, restrikes) instead of ramping
/// toward the new pitch. No smoothing is applied here — the raw YIN estimate is stable
/// enough, and any smoothing would re-introduce the ramp-on-restrike the latch is meant to
/// avoid.
///
/// Bypasses the `ControlGenerator` sub-block ramp path (matching `SendTrigger.Control`'s
/// convention for side-effecting analysis generators).
final class TunerPitchCapture: GeneratorBase, ControlGenerator {
var previousOutputValue: Double = 0.0
/// Input decimation factor for the YIN tracker. Lowers the effective analysis rate so a
/// fixed 512-sample window reaches down to the low guitar / bass range. At 48 kHz, 8×
/// gives an effective 6 kHz rate → ~23 Hz detection floor. The caller (`TunerTap`) must
/// band-limit the input below the decimated Nyquist (`sampleRate / 16`) first.
static let decimation: Int = 8
/// YIN analysis window, in decimated samples (512 is `FreqTracker`'s RT-safe maximum).
private static let fftSize: Int = 512
/// Minimum tracked frequency in Hz — below standard bass E1 (≈41 Hz) for headroom.
private static let minFreqHz: Double = 38.0
/// Maximum tracked frequency in Hz — above guitar high-E (E4 ≈330 Hz) with room for
/// upper strings / light bends, and well below the decimated Nyquist.
private static let maxFreqHz: Double = 660.0
private let tracker: FreqTracker
private let _hzBits: Atomic<UInt64>
private let _confidenceBits: Atomic<UInt64>
/// The most recent tracked frequency, in Hz. Safe to read from any thread.
var detectedFrequencyHz: Double {
Double(bitPattern: _hzBits.load(ordering: .acquiring))
}
/// The most recent tracking confidence in `[0, 1]`. Safe to read from any thread.
var detectedConfidence: Double {
Double(bitPattern: _confidenceBits.load(ordering: .acquiring))
}
/// - Parameter input: Signal to analyse for pitch — must already be band-limited below
/// the decimated Nyquist (see `TunerTap`, which applies the anti-alias lowpass).
init(input: any ValidGeneratorInput) {
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
tracker = FreqTracker(
in: resolvedInput,
fftSize: TunerPitchCapture.fftSize,
minFreq: TunerPitchCapture.minFreqHz,
maxFreq: TunerPitchCapture.maxFreqHz,
decimation: TunerPitchCapture.decimation
)
_hzBits = Atomic(Double(0.0).bitPattern)
_confidenceBits = Atomic(Double(0.0).bitPattern)
super.init()
_setupSubBlockBuffer()
}
// Bypass sub-block loop — one capture per audio block. `FreqTracker` processes the full
// block internally (per-sample ring fill + periodic YIN hops).
func calculatedSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_calculatedSamplesBlockRate(graph: graph, count: count)
}
func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
// `_checkCount` only bounds the top; guard the empty block so the `count - 1` last-sample
// reads below can't index `-1` (engine blockSize is ≥1 today, so this is defensive).
guard count > 0 else { return _result }
// FreqTracker is a two-channel AudioGenerator: channel 0 = Hz, channel 1 = confidence.
// Both rows are fully populated for `count` samples.
let trackerBlock: [[Double]] = tracker.calculatedSamples(graph: graph, count: count)
let hz: Double = trackerBlock[0][count - 1]
let confidence: Double = trackerBlock[1][count - 1]
_hzBits.store(hz.bitPattern, ordering: .releasing)
_confidenceBits.store(confidence.bitPattern, ordering: .releasing)
previousOutputValue = hz
for i: Int in 0..<count {
_result[0][i] = trackerBlock[0][i]
}
return _result
}
}
@@ -0,0 +1,60 @@
// TunerTap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// An internal synthesizer that taps the clean pre-effects input bus and runs a
/// `TunerPitchCapture` on it, so `ShoeGaze` can poll the current detected pitch from the
/// main thread while the tuner is engaged.
///
/// Mirrors `RecordTap`'s shape: reads one bus via `input(bus:)`, wires an analysis generator,
/// and writes to a dedicated scratch `ControlBus` purely so the engine evaluates it every
/// block — nothing downstream reads that bus.
final class TunerTap: SynthesizerBase {
/// Anti-alias lowpass cutoff, in Hz, ahead of the decimating YIN tracker. Must sit below
/// the decimated Nyquist (`sampleRate / (2 × decimation)`; ≈3 kHz at 48 kHz / 8×) so
/// decimation doesn't fold high harmonics back into the analysis band. `1200` Hz clears
/// every guitar/bass fundamental (highest is E4 ≈330 Hz) and their first harmonics — which
/// help YIN lock — while giving solid anti-alias margin.
private static let lowpassCutoffHz: Double = 1200.0
/// Butterworth Q (maximally flat, no resonant peak) for the anti-alias lowpass.
private static let lowpassQ: Double = 0.707
/// Index of the input bus to analyse.
private let inputBusIndex: Int
/// Scratch control bus the capture generator's passthrough writes to. Unread by anything
/// else — its only purpose is to give the engine a reason to evaluate the generator.
private let scratchControlBus: ControlBus
/// The pitch-capture generator created during `build()`. `nil` until `build()` has run.
private(set) var pitchCapture: TunerPitchCapture?
/// Creates a tuner tap.
///
/// - Parameters:
/// - inputBusIndex: Audio bus to analyse.
/// - scratchControlBus: A control bus reserved for this tap's unread passthrough output.
init(inputBusIndex: Int, scratchControlBus: ControlBus) {
self.inputBusIndex = inputBusIndex
self.scratchControlBus = scratchControlBus
super.init()
}
override func build() {
let source: In.Audio = input(bus: inputBusIndex)
let filtered: RBJLowPass.Audio = RBJLowPass.Audio(
input: source,
freq: TunerTap.lowpassCutoffHz,
q: TunerTap.lowpassQ
)
let capture: TunerPitchCapture = TunerPitchCapture(input: filtered)
pitchCapture = capture
output(bus: scratchControlBus, source: capture)
}
}
+20 -2
View File
@@ -41,7 +41,9 @@ public struct BoardBarView: View {
// MARK: - Layout constants
private static let barSpacing: CGFloat = 10
private static let barHeight: CGFloat = 92
// Tall enough for the control column's three rows of (iOS-chunky) segmented picker + sliders +
// bordered mute button, so it doesn't overflow into the CPU meters below.
private static let barHeight: CGFloat = 110
private static let cellSpacing: CGFloat = 8
private static let cellWidth: CGFloat = 104
private static let cellInnerSpacing: CGFloat = 5
@@ -56,6 +58,9 @@ public struct BoardBarView: View {
private static let ledDimBrightness: Double = 0.16
private static let ledRimOpacity: Double = 0.30
private static let soloButtonSize: CGFloat = 22
/// Fixed size for the rig mute glyph so the slash / wave states don't shift the volume row.
private static let muteIconWidth: CGFloat = 16
private static let muteIconHeight: CGFloat = 16
private static let editingBorderWidth: CGFloat = 2
private static let idleBorderOpacity: Double = 0.18
private static let cellBackgroundBrightness: Double = 0.14
@@ -71,6 +76,7 @@ public struct BoardBarView: View {
@Binding private var editingBoardIndex: Int
@Binding private var crossfadeSeconds: Double
private let onAddBoard: () -> Void
private let onClearBoards: (() -> Void)?
@State private var mode: PlayMode = .solo
@@ -84,16 +90,20 @@ public struct BoardBarView: View {
/// tap writes this).
/// - crossfadeSeconds: Crossfade duration applied to every board switch / toggle.
/// - onAddBoard: Called when the trailing **+** button is tapped.
/// - onClearBoards: Called when the trailing **Clear** button is tapped. When `nil`
/// (the default) no Clear button is shown.
public init(
shoeGaze: ShoeGaze,
editingBoardIndex: Binding<Int>,
crossfadeSeconds: Binding<Double>,
onAddBoard: @escaping () -> Void
onAddBoard: @escaping () -> Void,
onClearBoards: (() -> Void)? = nil
) {
self.shoeGaze = shoeGaze
self._editingBoardIndex = editingBoardIndex
self._crossfadeSeconds = crossfadeSeconds
self.onAddBoard = onAddBoard
self.onClearBoards = onClearBoards
}
// MARK: - Body
@@ -109,6 +119,11 @@ public struct BoardBarView: View {
boardCell(index: pair.offset, board: pair.element)
}
addButton
if let onClearBoards: () -> Void = onClearBoards {
Button("Clear") { onClearBoards() }
.buttonStyle(.bordered).tint(.red)
.help("Remove all boards in the current rig (with the option to save first)")
}
}
.frame(height: BoardBarView.barHeight)
}
@@ -175,7 +190,10 @@ public struct BoardBarView: View {
Button {
shoeGaze.toggleRigMuted()
} label: {
// Fixed width: the slash / wave glyphs differ in width, which would otherwise
// shift the whole volume row a few pixels when toggling mute.
Image(systemName: shoeGaze.rigMuted ? "speaker.slash.fill" : "speaker.wave.2.fill")
.frame(width: BoardBarView.muteIconWidth, height: BoardBarView.muteIconHeight)
}
.buttonStyle(.bordered)
.tint(shoeGaze.rigMuted ? .red : .orange)
@@ -42,6 +42,10 @@ public struct EngineConfigView: View {
private let hardwareSampleRate: () -> Double?
private let applyConfig: ((Double, Int, Int) throws -> Void)?
private let onConfigApplied: () -> Void
/// When `true`, renders only the Start/Stop transport button (the sample-rate / channel-count
/// controls are hidden). Used by the compact (iPhone / narrow iPad) layout, which keeps the
/// transport on screen and moves the config controls into a Settings sheet.
private let transportOnly: Bool
@State private var pendingSampleRate: Double
@State private var pendingInputs: Int
@@ -63,12 +67,14 @@ public struct EngineConfigView: View {
shoeGaze: ShoeGaze,
hardwareSampleRate: @escaping () -> Double? = { nil },
applyConfig: ((Double, Int, Int) throws -> Void)? = nil,
onConfigApplied: @escaping () -> Void = { }
onConfigApplied: @escaping () -> Void = { },
transportOnly: Bool = false
) {
self.shoeGaze = shoeGaze
self.hardwareSampleRate = hardwareSampleRate
self.applyConfig = applyConfig
self.onConfigApplied = onConfigApplied
self.transportOnly = transportOnly
_pendingSampleRate = State(initialValue: shoeGaze.engine.sampleRate)
_pendingInputs = State(initialValue: shoeGaze.engine.numInputChannels)
_pendingOutputs = State(initialValue: shoeGaze.engine.numOutputChannels)
@@ -78,35 +84,36 @@ public struct EngineConfigView: View {
public var body: some View {
_ = transportTick
let isRunning: Bool = shoeGaze.engine.isRunning
return HStack(spacing: EngineConfigView.rowSpacing) {
label("Rate")
Picker("Rate", selection: $pendingSampleRate) {
ForEach(EngineConfigView.standardRates, id: \.self) { rate in
Text("\(Int(rate)) Hz").tag(rate)
return Group {
if transportOnly {
transportButton
} else {
HStack(spacing: EngineConfigView.rowSpacing) {
label("Rate")
Picker("Rate", selection: $pendingSampleRate) {
ForEach(EngineConfigView.standardRates, id: \.self) { rate in
Text("\(Int(rate)) Hz").tag(rate)
}
}
.labelsHidden()
.pickerStyle(.menu)
.disabled(shoeGaze.engine.isRunning)
Stepper(value: $pendingInputs, in: 0...EngineConfigView.maxInputs) {
Text("In: \(pendingInputs)").foregroundStyle(Color.white)
}
.disabled(shoeGaze.engine.isRunning)
.fixedSize()
Stepper(value: $pendingOutputs, in: 1...EngineConfigView.maxOutputs) {
Text("Out: \(pendingOutputs)").foregroundStyle(Color.white)
}
.disabled(shoeGaze.engine.isRunning)
.fixedSize()
transportButton
}
}
.labelsHidden()
.pickerStyle(.menu)
.disabled(isRunning)
Stepper(value: $pendingInputs, in: 0...EngineConfigView.maxInputs) {
Text("In: \(pendingInputs)").foregroundStyle(Color.white)
}
.disabled(isRunning)
.fixedSize()
Stepper(value: $pendingOutputs, in: 1...EngineConfigView.maxOutputs) {
Text("Out: \(pendingOutputs)").foregroundStyle(Color.white)
}
.disabled(isRunning)
.fixedSize()
Button(isRunning ? "Stop" : "Start") {
if isRunning { stopEngine() } else { startEngine() }
}
.buttonStyle(.borderedProminent)
.tint(isRunning ? .red : .green)
}
.alert(alertTitle, isPresented: $showAlert) {
Button("OK", role: .cancel) { }
@@ -131,6 +138,16 @@ public struct EngineConfigView: View {
.onChange(of: pendingSampleRate) { applyConfigWhileStopped() }
}
/// The Start / Stop transport button, shared by the full and transport-only layouts.
private var transportButton: some View {
let isRunning: Bool = shoeGaze.engine.isRunning
return Button(isRunning ? "Stop" : "Start") {
if isRunning { stopEngine() } else { startEngine() }
}
.buttonStyle(.borderedProminent)
.tint(isRunning ? .red : .green)
}
/// Reconfigures the stopped engine with the pending values and notifies the host so views that
/// read non-observable engine state refresh. No-op while the engine is running.
private func applyConfigWhileStopped() {
@@ -161,14 +178,20 @@ public struct EngineConfigView: View {
private func startEngine() {
do {
if let applyConfig: (Double, Int, Int) throws -> Void = applyConfig {
try applyConfig(pendingSampleRate, pendingInputs, pendingOutputs)
} else {
try shoeGaze.reconfigureEngine(
sampleRate: pendingSampleRate,
inputChannels: pendingInputs,
outputChannels: pendingOutputs
)
// Transport-only mode does not own the config controls — the engine is already
// configured (via the full instance's live apply, or the init defaults). Re-applying
// this instance's cached pending state here would revert edits made in the Settings
// sheet, so skip the reconfigure and just start.
if !transportOnly {
if let applyConfig: (Double, Int, Int) throws -> Void = applyConfig {
try applyConfig(pendingSampleRate, pendingInputs, pendingOutputs)
} else {
try shoeGaze.reconfigureEngine(
sampleRate: pendingSampleRate,
inputChannels: pendingInputs,
outputChannels: pendingOutputs
)
}
}
try shoeGaze.engine.start()
} catch {
@@ -190,7 +213,7 @@ public struct EngineConfigView: View {
}
private func stopEngine() {
shoeGaze.engine.stop()
shoeGaze.stopEngine()
transportTick.toggle()
onConfigApplied()
}
+27
View File
@@ -66,6 +66,33 @@ public struct HelpView: View {
+ "Delete, and Erase All.",
]
)
topicSection(
icon: "repeat",
title: "The Looper Pedal",
intro: "The Looper records a phrase and plays it back in a loop, with up to four "
+ "overdub tracks (A–D). The big Record button is a smart footswitch whose job "
+ "changes with the looper's state.",
steps: [
"Record (smart footswitch): first press records track A; press again to set the "
+ "loop end and start playback (auto-overdubbing A); while playing it toggles "
+ "overdub on the selected track.",
"Free vs Sync to Tempo: Free loops are whatever length you play, captured instantly. "
+ "Sync quantizes record-start and loop-close to the beat clock — so every loop is "
+ "a whole number of beats. Sync needs the Tempo indicator On; it is disabled while "
+ "tempo is off.",
"Knobs: Playback sets loop level against your live signal; Overdub sets the record "
+ "level of new overdubs; Feedback sets how much existing audio survives each pass "
+ "(1.0 = keep forever); Crossfade smooths loop mute/unmute so it doesn't click.",
"Reverse flips playback direction from the current position (in Sync it waits for the "
+ "next beat). Stop halts now; Cue Stop arms a stop at the next loop end (press again "
+ "to cancel); Reset clears every track back to empty.",
"Tracks A–D: tap a dot to select the track Record overdubs into; tap a selected, "
+ "recorded track again to mute or unmute it.",
"MIDI: Record, Stop, Cue Stop, Reverse, Sync, Reset, and each Track A–D map as "
+ "footswitch (Program Change) actions in MIDI Mapping; the Crossfade / Playback / "
+ "Overdub / Feedback knobs sweep from an expression pedal like any pedal knob.",
]
)
topicSection(
icon: "square.and.arrow.down",
title: "Saving & Autosave",
@@ -0,0 +1,239 @@
// LooperTimelineView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// The looper's loop timeline: a transport-state badge, tappable A–D track dots, a loop-length
/// read-out, a sweeping play-head track, and a one-line state indicator describing what the
/// pedal is doing. Rendered inside the double-width ``PedalView`` for a `LooperPedal`.
///
/// `LooperPedal`'s transport state is plain (non-`@Observable`) RT-adjacent data, so this view
/// polls it on a `.task` loop — the same convention as `TempoView`'s clock read-out.
struct LooperTimelineView: View {
// MARK: - Constants
private static let trackHeight: CGFloat = 16
private static let trackCornerRadius: CGFloat = 4
private static let playheadWidth: CGFloat = 2
private static let sectionSpacing: CGFloat = 6
private static let labelFontSize: CGFloat = 11
private static let trackBrightness: Double = 0.14
private static let trackBorderOpacity: Double = 0.35
private static let filledOpacity: Double = 0.22
private static let pollIntervalNanoseconds: UInt64 = 33_000_000 // ~30 Hz
private static let ledDiameter: CGFloat = 9
private static let badgeInnerSpacing: CGFloat = 4
private static let lengthLabelOpacity: Double = 0.75
private static let borderLineWidth: CGFloat = 1
private static let dotSpacing: CGFloat = 4
private static let dotDiameter: CGFloat = 18
private static let dotLabelFontSize: CGFloat = 10
private static let dotBrightness: Double = 0.16
private static let selectedDotBrightness: Double = 0.32
private static let dotFilledOpacity: Double = 0.55
private static let dotEmptyOpacity: Double = 0.45
private static let activeRingWidth: CGFloat = 1.5
private static let mutedDotOpacity: Double = 0.4
private static let muteSlashOpacity: Double = 0.9
private static let muteSlashWidth: CGFloat = 1.5
private static let indicatorFontSize: CGFloat = 11
private static let indicatorOpacity: Double = 0.85
private static let overdubRingColor: Color = Color.red
private static let dotLabels: [String] = ["A", "B", "C", "D", "E", "F", "G", "H"]
// MARK: - Properties
private let pedal: LooperPedal
@State private var position: Double?
@State private var state: LooperTransportState = .clear
@State private var lengthSeconds: Double = 0.0
@State private var lengthBeats: Double = 0.0
@State private var selectedTrack: Int = 0
@State private var overdubbingTrack: Int?
@State private var trackContent: [Bool] = Array(repeating: false, count: LooperPedal.trackCount)
@State private var trackMuted: [Bool] = Array(repeating: false, count: LooperPedal.trackCount)
@State private var stopArmed: Bool = false
@State private var stateDescription: String = ""
init(pedal: LooperPedal) {
self.pedal = pedal
}
// MARK: - Body
var body: some View {
VStack(spacing: LooperTimelineView.sectionSpacing) {
HStack(spacing: LooperTimelineView.sectionSpacing) {
stateBadge
Spacer(minLength: 0)
trackDots
Spacer(minLength: 0)
lengthLabel
}
track
stateIndicator
}
// Key the poll on the pedal instance: if a rig load / rebuild swaps in a new LooperPedal,
// `.task` alone would keep polling the old (captured) instance and freeze. Restart on change.
.task(id: ObjectIdentifier(pedal)) {
while !Task.isCancelled {
position = pedal.playbackPosition01()
state = pedal.transportState
lengthSeconds = pedal.loopLengthSeconds
lengthBeats = pedal.loopLengthBeats
selectedTrack = pedal.selectedTrackIndex
overdubbingTrack = pedal.overdubbingTrackIndex
trackContent = (0 ..< LooperPedal.trackCount).map { pedal.trackHasContent($0) }
trackMuted = (0 ..< LooperPedal.trackCount).map { pedal.isTrackMuted($0) }
stopArmed = pedal.isStopAtLoopEndArmed
stateDescription = pedal.stateDescription
try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds)
}
}
}
// MARK: - Subviews
/// One tappable labelled dot per track: filled when it holds a loop, white-ringed when
/// selected, red-ringed while overdubbing, dimmed with a slash when muted. Tapping selects the
/// track; tapping the already-selected recorded track mutes/unmutes it.
private var trackDots: some View {
HStack(spacing: LooperTimelineView.dotSpacing) {
ForEach(0 ..< LooperPedal.trackCount, id: \.self) { index in
let isSelected: Bool = index == selectedTrack
let isOverdub: Bool = index == overdubbingTrack
let hasContent: Bool = index < trackContent.count && trackContent[index]
let isMuted: Bool = index < trackMuted.count && trackMuted[index]
Button {
pedal.tapTrack(index)
} label: {
Text(LooperTimelineView.dotLabels[index])
.font(.system(size: LooperTimelineView.dotLabelFontSize, weight: .bold, design: .monospaced))
// Selected (or recorded) tracks show a bright letter; other empty tracks dim.
.foregroundStyle((hasContent || isSelected) ? Color.white : Color.white.opacity(LooperTimelineView.dotEmptyOpacity))
.frame(width: LooperTimelineView.dotDiameter, height: LooperTimelineView.dotDiameter)
.background(
Circle().fill(hasContent ? Color.green.opacity(LooperTimelineView.dotFilledOpacity)
: (isSelected ? Color(white: LooperTimelineView.selectedDotBrightness)
: Color(white: LooperTimelineView.dotBrightness)))
)
.overlay(muteSlash(isMuted))
.overlay(
Circle().stroke(isOverdub ? LooperTimelineView.overdubRingColor
: (isSelected ? Color.white : Color.clear),
lineWidth: LooperTimelineView.activeRingWidth)
)
.opacity(isMuted ? LooperTimelineView.mutedDotOpacity : 1.0)
}
.buttonStyle(.plain)
}
}
}
/// A diagonal slash drawn over a muted track's dot.
@ViewBuilder
private func muteSlash(_ muted: Bool) -> some View {
if muted {
GeometryReader { geometry in
Path { path in
path.move(to: CGPoint(x: 0, y: geometry.size.height))
path.addLine(to: CGPoint(x: geometry.size.width, y: 0))
}
.stroke(Color.white.opacity(LooperTimelineView.muteSlashOpacity),
lineWidth: LooperTimelineView.muteSlashWidth)
}
}
}
private var stateBadge: some View {
HStack(spacing: LooperTimelineView.badgeInnerSpacing) {
Circle()
.fill(stateColor)
.frame(width: LooperTimelineView.ledDiameter, height: LooperTimelineView.ledDiameter)
Text(stateText)
.font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.white)
if stopArmed {
Text("→END")
.font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.orange)
}
}
}
private var lengthLabel: some View {
Text(lengthText)
.font(.system(size: LooperTimelineView.labelFontSize, design: .monospaced))
.foregroundStyle(Color.white.opacity(LooperTimelineView.lengthLabelOpacity))
}
/// One-line description of what the pedal is doing now — replaces the old action-button row.
private var stateIndicator: some View {
Text(stateDescription)
.font(.system(size: LooperTimelineView.indicatorFontSize, weight: .medium))
.foregroundStyle(Color.white.opacity(LooperTimelineView.indicatorOpacity))
.frame(maxWidth: .infinity, alignment: .leading)
}
private var track: some View {
GeometryReader { geometry in
let width: CGFloat = geometry.size.width
let pos: CGFloat = CGFloat(position ?? 0.0)
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
.fill(Color(white: LooperTimelineView.trackBrightness))
.overlay(
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
.stroke(Color.white.opacity(LooperTimelineView.trackBorderOpacity),
lineWidth: LooperTimelineView.borderLineWidth)
)
if position != nil {
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
.fill(Color.white.opacity(LooperTimelineView.filledOpacity))
.frame(width: max(0, pos * width))
Rectangle()
.fill(Color.white)
.frame(width: LooperTimelineView.playheadWidth)
.offset(x: min(max(0, pos * width), width - LooperTimelineView.playheadWidth))
}
}
}
.frame(height: LooperTimelineView.trackHeight)
}
// MARK: - State mapping
private var stateColor: Color {
switch state {
case .clear: return Color(white: 0.3)
case .armedRecord, .armedClose: return Color.orange
case .recordingMaster: return Color.red
case .playing: return Color.green
case .stopped: return Color.orange
}
}
private var stateText: String {
switch state {
case .clear: return "CLEAR"
case .armedRecord: return "ARM"
case .recordingMaster: return "REC"
case .armedClose: return "END"
case .playing: return "PLAY"
case .stopped: return "STOP"
}
}
private var lengthText: String {
guard lengthSeconds > 0 else { return "--" }
let seconds: String = String(format: "%.2fs", lengthSeconds)
guard lengthBeats > 0 else { return seconds }
return seconds + " · \(Int(lengthBeats)) beat" + (lengthBeats == 1 ? "" : "s")
}
}
@@ -102,23 +102,44 @@ public struct MIDIMappingSheet: View {
SwitchRowModel(id: "sw-mute", action: .rigMute, label: "Rig Mute"),
SwitchRowModel(id: "sw-all", action: .allBoards, label: "All Boards On"),
]
for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() {
let boardIndex: Int = boardPair.offset
let board: PedalBoard = boardPair.element
rows.append(SwitchRowModel(id: "sw-solo-\(boardIndex)",
action: .boardSolo(boardIndex: boardIndex),
for board: PedalBoard in shoeGaze.boards {
let boardID: UUID = board.id
rows.append(SwitchRowModel(id: "sw-solo-\(boardID)",
action: .boardSolo(boardID: boardID),
label: "\(board.label) · Solo"))
rows.append(SwitchRowModel(id: "sw-aud-\(boardIndex)",
action: .boardAudible(boardIndex: boardIndex),
rows.append(SwitchRowModel(id: "sw-aud-\(boardID)",
action: .boardAudible(boardID: boardID),
label: "\(board.label) · Audible"))
rows.append(SwitchRowModel(id: "sw-byp-\(boardIndex)",
action: .boardBypass(boardIndex: boardIndex),
rows.append(SwitchRowModel(id: "sw-byp-\(boardID)",
action: .boardBypass(boardID: boardID),
label: "\(board.label) · Bypass"))
for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() {
for pedal: Pedal in board.pedals {
rows.append(SwitchRowModel(
id: "sw-pb-\(boardIndex)-\(pedalPair.offset)",
action: .pedalBypass(boardIndex: boardIndex, pedalIndex: pedalPair.offset),
label: "\(board.label) · \(pedalPair.element.displayName) · Bypass"))
id: "sw-pb-\(pedal.id)",
action: .pedalBypass(pedalID: pedal.id),
label: "\(board.label) · \(pedal.displayName) · Bypass"))
// Loopers expose their transport footswitches as mappable switch actions.
if pedal is LooperPedal {
var looperActions: [(String, String, MIDIMap.PedalActionKind)] = [
("rec", "Record", .looperRecordStop),
("stop", "Stop", .looperStop),
("cue", "Cue Stop", .looperCueStop),
("rev", "Reverse", .looperReverse),
("sync", "Sync", .looperSyncToggle),
("reset", "Reset", .looperReset),
]
// A/B/C/D track taps (select / mute), matching the timeline dots.
for i: Int in 0 ..< LooperPedal.trackCount {
let letter: String = LooperPedal.trackLabel(i)
looperActions.append(("track\(letter)", "Track \(letter)", .looperTrack(index: i)))
}
for (slug, name, kind): (String, String, MIDIMap.PedalActionKind) in looperActions {
rows.append(SwitchRowModel(
id: "sw-la-\(slug)-\(pedal.id)",
action: .pedalAction(pedalID: pedal.id, kind: kind),
label: "\(board.label) · \(pedal.displayName) · \(name)"))
}
}
}
}
return rows
@@ -128,23 +149,18 @@ public struct MIDIMappingSheet: View {
var rows: [CCRowModel] = [
CCRowModel(id: "cc-rigvol", target: .rigVolume, label: "Rig · Volume"),
]
for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() {
let boardIndex: Int = boardPair.offset
let board: PedalBoard = boardPair.element
for board: PedalBoard in shoeGaze.boards {
// Board master level (the board fader).
rows.append(CCRowModel(
id: "cc-blvl-\(boardIndex)",
target: .boardLevel(boardIndex: boardIndex, boardLabelHint: nil),
id: "cc-blvl-\(board.id)",
target: .boardLevel(boardID: board.id, boardLabelHint: nil),
label: "\(board.label) · Level"))
for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() {
let pedalIndex: Int = pedalPair.offset
let pedal: Pedal = pedalPair.element
for pedal: Pedal in board.pedals {
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
rows.append(CCRowModel(
id: "cc-\(boardIndex)-\(pedalIndex)-\(controlPair.offset)",
id: "cc-\(pedal.id)-\(controlPair.offset)",
target: .pedalControl(
boardIndex: boardIndex,
pedalIndex: pedalIndex,
pedalID: pedal.id,
controlIndex: controlPair.offset,
pedalNameHint: nil,
controlLabelHint: nil),
@@ -0,0 +1,106 @@
// PedalButtonView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdUI
import LyrebirdShoeGaze
// MARK: - PedalButtonView
/// A stomp-style action button rendered from a ``PedalButton`` descriptor.
///
/// `.momentary` renders a plain `ParameterButton`. `.toggle` renders the same LED +
/// footswitch look as the pedal's own bypass control (`PedalView`'s `LEDIndicator` /
/// `FootswitchButton`), with a caption label beneath — so a looper's Overdub/Loop toggles
/// read as stomp switches with state, not a segmented picker.
///
/// ## Usage
/// ```swift
/// PedalButtonView(pedalButton)
/// ```
public struct PedalButtonView: View {
private static let toggleOnThreshold: Double = 0.5
private static let sectionSpacing: CGFloat = 6
private static let captionFontSize: CGFloat = 11
private let pedalButton: PedalButton
/// Creates a button view from a descriptor.
///
/// - Parameter pedalButton: The button to render.
public init(_ pedalButton: PedalButton) {
self.pedalButton = pedalButton
}
public var body: some View {
switch pedalButton.style {
case .momentary:
if let indicator: UIParamNode = pedalButton.indicator {
// LED + footswitch, same look as a toggle, but the press runs an action and the
// LED reflects a separate state node (e.g. Stop lit while stopped). Reading
// `indicator.value` registers this view for @Observable re-render.
let isOn: Bool = indicator.value >= PedalButtonView.toggleOnThreshold
VStack(spacing: PedalButtonView.sectionSpacing) {
LEDIndicator(isOn: isOn)
FootswitchButton(action: pedalButton.action ?? {})
caption
}
} else {
ParameterButton(pedalButton.label, action: pedalButton.action ?? {})
}
case .toggle:
if let node: UIParamNode = pedalButton.node {
// Reading `node.value` registers this view for @Observable re-render.
let isOn: Bool = node.value >= PedalButtonView.toggleOnThreshold
VStack(spacing: PedalButtonView.sectionSpacing) {
LEDIndicator(isOn: isOn)
FootswitchButton(node: node)
caption
}
}
}
}
/// The button caption — a live "what the next press does" label when the descriptor supplies
/// a `dynamicLabel`, otherwise the static label.
@ViewBuilder
private var caption: some View {
if let provider: () -> String = pedalButton.dynamicLabel {
DynamicCaption(provider: provider, fallback: pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
} else {
Text(pedalButton.label)
.font(.system(size: PedalButtonView.captionFontSize))
.foregroundStyle(Color.white)
}
}
}
// MARK: - DynamicCaption
/// A caption that polls a text provider (RT-adjacent pedal state that isn't `@Observable`), on
/// the same `.task` cadence as the looper timeline, so a state-driven button label stays current.
private struct DynamicCaption: View {
private static let pollIntervalNanoseconds: UInt64 = 33_000_000 // ~30 Hz
let provider: () -> String
let fallback: String
@State private var text: String = ""
var body: some View {
Text(text.isEmpty ? fallback : text)
.task {
while !Task.isCancelled {
text = provider()
try? await Task.sleep(nanoseconds: DynamicCaption.pollIntervalNanoseconds)
}
}
}
}
@@ -9,7 +9,7 @@ import SwiftUI
/// A presentation grouping for pedals in the palette — used to colour-code the picker cards and to
/// drive the "filter by type" menu. Purely a UI concern: the mapping from a pedal's `displayName`
/// to its category lives here, keyed by name like ``PedalPaletteView``'s preferred order.
enum PedalCategory: String, CaseIterable, Identifiable {
public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
case gain = "Gain"
case dynamics = "Dynamics"
case filter = "EQ & Filter"
@@ -19,7 +19,7 @@ enum PedalCategory: String, CaseIterable, Identifiable {
case reverb = "Reverb"
case texture = "Texture"
var id: String { rawValue }
public var id: String { rawValue }
/// Accent colour used to tint the palette card and the filter chip.
var color: Color {
@@ -83,9 +83,25 @@ public struct PedalPaletteView: View {
private let onAdd: (String) -> Void
private let onRouting: (RoutingAction) -> Void
private let axis: Axis
private let showsFilterMenu: Bool
/// Active type filter; `nil` shows all pedals.
@State private var filter: PedalCategory?
/// Active type filter when the palette owns it; `nil` shows all pedals. Ignored when an
/// `externalFilter` binding is supplied (the host hoists the filter into its own header).
@State private var internalFilter: PedalCategory?
private let externalFilter: Binding<PedalCategory?>?
/// The live filter, from the host binding if provided, else the palette's own state.
private var activeFilter: PedalCategory? {
externalFilter?.wrappedValue ?? internalFilter
}
private func setFilter(_ category: PedalCategory?) {
if let externalFilter: Binding<PedalCategory?> = externalFilter {
externalFilter.wrappedValue = category
} else {
internalFilter = category
}
}
// MARK: - Init
@@ -95,15 +111,23 @@ public struct PedalPaletteView: View {
/// - axis: `.vertical` (default) lays the catalog out as a full-width column for a sidebar;
/// `.horizontal` lays it out as a fixed-width-card row for a horizontal scroller. The host
/// wraps the view in a `ScrollView` of the matching axis.
/// - filter: Optional external binding for the type filter, so a host (e.g. a sheet) can put
/// the filter control in its own fixed header. When `nil` the palette manages its own filter.
/// - showsFilterMenu: Whether to draw the built-in filter menu inline. Pass `false` when the
/// host renders its own filter control. Defaults to `true`.
/// - onAdd: Invoked with a pedal's `displayName` when its row is tapped (append to main chain).
/// Rows are also `.draggable` carrying `"add:<displayName>"` for drop-onto-lane targeting.
/// - onRouting: Invoked when a routing row is tapped. Defaults to a no-op.
public init(
axis: Axis = .vertical,
filter: Binding<PedalCategory?>? = nil,
showsFilterMenu: Bool = true,
onAdd: @escaping (String) -> Void,
onRouting: @escaping (RoutingAction) -> Void = { _ in }
) {
self.axis = axis
self.externalFilter = filter
self.showsFilterMenu = showsFilterMenu
self.onAdd = onAdd
self.onRouting = onRouting
}
@@ -120,7 +144,7 @@ public struct PedalPaletteView: View {
/// Pedal names after applying the active type filter.
private var visiblePedalNames: [String] {
guard let filter: PedalCategory = filter else { return orderedPedalNames }
guard let filter: PedalCategory = activeFilter else { return orderedPedalNames }
return orderedPedalNames.filter { PedalCategory.category(for: $0) == filter }
}
@@ -151,7 +175,7 @@ public struct PedalPaletteView: View {
HStack {
sectionTitle("PEDALS")
Spacer(minLength: 0)
filterMenu
if showsFilterMenu { filterMenu }
}
ForEach(visiblePedalNames, id: \.self) { name in
pedalRow(name)
@@ -174,7 +198,7 @@ public struct PedalPaletteView: View {
HStack(alignment: .top, spacing: PedalPaletteView.sectionSpacing) {
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
sectionTitle("PEDALS")
filterMenu
if showsFilterMenu { filterMenu }
}
ForEach(groupedVisiblePedals, id: \.category) { group in
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
@@ -215,18 +239,18 @@ public struct PedalPaletteView: View {
/// "Filter by type" menu — defaults to **All** (no filtering).
private var filterMenu: some View {
Menu {
Button("All Types") { filter = nil }
Button("All Types") { setFilter(nil) }
Divider()
ForEach(PedalCategory.allCases) { category in
Button(category.rawValue) { filter = category }
Button(category.rawValue) { setFilter(category) }
}
} label: {
HStack(spacing: 3) {
Image(systemName: "line.3.horizontal.decrease.circle")
Text(filter?.rawValue ?? "All").lineLimit(1)
Text(activeFilter?.rawValue ?? "All").lineLimit(1)
}
.font(.system(size: PedalPaletteView.titleFontSize))
.foregroundStyle((filter?.color ?? Color.white).opacity(0.9))
.foregroundStyle((activeFilter?.color ?? Color.white).opacity(0.9))
}
#if os(macOS)
.menuStyle(.borderlessButton)
@@ -43,10 +43,15 @@ public struct PedalSwitchView: View {
private static let borderLineWidth: CGFloat = 1
private static let activeTextBrightness: Double = 0.12
/// Opacity applied to a tempo-dependent switch while the tempo indicator is turned off.
private static let tempoDisabledOpacity: Double = 0.4
// MARK: - Properties
private let pedalSwitch: PedalSwitch
@Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool
// MARK: - Init
/// Creates a segmented switch view.
@@ -62,6 +67,8 @@ public struct PedalSwitchView: View {
// Reading `node.value` registers this view for @Observable re-render on change.
let current: Double = pedalSwitch.node.value
let selectedIndex: Int = nearestIndex(to: current)
// A tempo-synced switch is inert while the tempo indicator is turned off.
let inert: Bool = pedalSwitch.tempoDependent && !tempoEnabled
VStack(spacing: PedalSwitchView.labelSpacing) {
HStack(spacing: PedalSwitchView.segmentSpacing) {
@@ -77,10 +84,12 @@ public struct PedalSwitchView: View {
lineWidth: PedalSwitchView.borderLineWidth)
)
Text(pedalSwitch.label)
Text(inert ? "\(pedalSwitch.label) (tempo off)" : pedalSwitch.label)
.font(.system(size: PedalSwitchView.captionFontSize))
.foregroundStyle(Color.white)
}
.disabled(inert)
.opacity(inert ? PedalSwitchView.tempoDisabledOpacity : 1.0)
}
// MARK: - Subviews
+226 -39
View File
@@ -90,9 +90,11 @@ private struct ScrewDot: View {
/// A small circular LED that glows green when the effect is engaged.
///
/// Bypass polarity: `0` = engaged (effect ON), `1` = bypassed.
/// The LED is lit when `bypassValue < 0.5`.
private struct LEDIndicator: View {
/// A small round LED, lit green when `isOn` and dark otherwise. Polarity-agnostic — the
/// caller decides what `isOn` means for its own control (e.g. bypass's `value < 0.5`, or a
/// plain toggle's `value >= 0.5`). `internal` (not `private`) so other views in this module
/// (e.g. `PedalButtonView`) can reuse the same stompbox LED look.
struct LEDIndicator: View {
private static let diameter: CGFloat = 10
private static let glowRadius: CGFloat = 6
@@ -101,13 +103,11 @@ private struct LEDIndicator: View {
private static let dimBrightness: Double = 0.15
private static let rimStrokeOpacity: Double = 0.30
let bypassValue: Double
private var isEngaged: Bool { bypassValue < 0.5 }
let isOn: Bool
var body: some View {
ZStack {
if isEngaged {
if isOn {
Circle()
.fill(Color.green.opacity(LEDIndicator.glowOpacity))
.frame(
@@ -117,7 +117,7 @@ private struct LEDIndicator: View {
.blur(radius: LEDIndicator.glowRadius / 2)
}
Circle()
.fill(isEngaged ? Color.green : Color(white: LEDIndicator.dimBrightness))
.fill(isOn ? Color.green : Color(white: LEDIndicator.dimBrightness))
.frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter)
.overlay(
Circle()
@@ -132,8 +132,11 @@ private struct LEDIndicator: View {
// MARK: - Footswitch
/// A round footswitch-style button that toggles bypass on/off.
private struct FootswitchButton: View {
/// A round footswitch-style button. Either flips a bound `UIParamNode` between `0` and `1`
/// (toggle) or runs an arbitrary action (momentary) — both render the identical stompbox look.
/// `internal` (not `private`) so other views in this module (e.g. `PedalButtonView`) can reuse
/// it for non-bypass toggles and momentary stomp actions.
struct FootswitchButton: View {
private static let diameter: CGFloat = 44
private static let strokeWidth: CGFloat = 2.5
@@ -142,14 +145,23 @@ private struct FootswitchButton: View {
private static let ringBrightness: Double = 0.50
private static let innerFillBrightness: Double = 0.25
let node: UIParamNode
private let action: () -> Void
/// Flips `node` between `0` and `1` on each press.
init(node: UIParamNode) {
self.action = {
let engaged: Bool = node.value < 0.5
node.update(engaged ? 1.0 : 0.0)
}
}
/// Runs `action` on each press (momentary).
init(action: @escaping () -> Void) {
self.action = action
}
var body: some View {
Button(action: {
let engaged: Bool = node.value < 0.5
// Toggle: engaged (0) → bypassed (1) and vice-versa.
node.update(engaged ? 1.0 : 0.0)
}) {
Button(action: action) {
ZStack {
Circle()
.fill(Color(white: FootswitchButton.outerFillBrightness))
@@ -205,6 +217,8 @@ public struct PedalView: View {
private static let enclosurePadding: CGFloat = 14
private static let screwInset: CGFloat = 6
private static let knobColumnCount: Int = 3
/// Knob columns for a double-width pedal card (fits a four-knob effect bank on one row).
private static let wideKnobColumnCount: Int = 4
private static let knobSpacing: CGFloat = 10
/// Horizontal gap between knobs within a row. Wider than `knobSpacing` so centred
/// rows keep a comfortable, touch-friendly gap between adjacent knobs.
@@ -227,6 +241,10 @@ public struct PedalView: View {
private static let shadowOpacity: Double = 0.60
private static let enclosureGradientDarkFraction: Double = 0.30
private static let bypassSectionSpacing: CGFloat = 6
/// Gap between the looper's three content columns.
private static let looperColumnSpacing: CGFloat = 18
/// Fixed width of the looper's left (timeline) column.
private static let looperTimelineColumnWidth: CGFloat = 200
/// Half the screw-dot size — used to centre screws on the corner position.
private static let screwHalfSize: CGFloat = 4
private static let namePlateBackgroundOpacity: Double = 0.35
@@ -288,15 +306,14 @@ public struct PedalView: View {
lineWidth: PedalView.innerHighlightLineWidth)
.padding(PedalView.innerHighlightPadding)
// Content stack
VStack(spacing: PedalView.sectionSpacing) {
namePlate
knobGrid
selectorRow
switchRow
sliderBank(sliders)
Spacer(minLength: 0)
bottomControls
// Content stack — the looper uses a wide, columnar layout to stay short; every other
// pedal uses the default single-column section stack.
Group {
if let looper: LooperPedal = pedal as? LooperPedal {
looperColumnarContent(looper)
} else {
defaultContent(sliders: sliders)
}
}
.padding(PedalView.enclosurePadding)
@@ -321,6 +338,136 @@ public struct PedalView: View {
}
}
// MARK: - Content layouts
/// The default single-column section stack used by every pedal except the looper.
private func defaultContent(sliders: [PedalSlider]) -> some View {
VStack(spacing: PedalView.sectionSpacing) {
namePlate
knobGrid
selectorRow
switchRow
// Keyed on the pedal instance so the buttons' live captions (which poll the pedal
// via `.task`) re-subscribe when a rig load / rebuild swaps in a new pedal instance.
transportButtonRow
.id(ObjectIdentifier(pedal))
buttonRow
sliderBank(sliders)
Spacer(minLength: 0)
bottomControls
}
}
/// Wide, three-column layout for the looper: the loop timeline on the left, the effect knobs
/// over the Free/Sync switch in the centre, and the transport footswitch grid (with bypass) on
/// the right. Laying the sections side-by-side keeps the tall pedal short enough to fit the
/// canvas without scrolling. Requires the looper's `widthUnits` to be wide enough (3×).
private func looperColumnarContent(_ looper: LooperPedal) -> some View {
VStack(spacing: PedalView.sectionSpacing) {
namePlate
HStack(alignment: .top, spacing: PedalView.looperColumnSpacing) {
// Left column: timeline, then the Free/Sync switch, then the Reset footswitch.
VStack(spacing: PedalView.sectionSpacing) {
LooperTimelineView(pedal: looper)
switchRow
looperResetCell
Spacer(minLength: 0)
}
.frame(width: PedalView.looperTimelineColumnWidth)
// Centre column: the four effect knobs (2×2), with the Level + Bypass footer at the
// bottom. The Mix slot is reserved (empty) so Bypass stays horizontally centred,
// matching a normal pedal's footer.
VStack(spacing: PedalView.sectionSpacing) {
looperEffectKnobs(columns: 2)
Spacer(minLength: 0)
looperFooter
}
// Right column: the transport footswitches (minus Reset) in a 2×2 grid.
looperTransportGrid(columns: 2)
.id(ObjectIdentifier(pedal))
}
Spacer(minLength: 0)
}
}
/// The looper's effect knobs (everything except the trailing `Mix` / `Level`) laid out in
/// rows of `columns`.
private func looperEffectKnobs(columns: Int) -> some View {
let knobs: [PedalKnob] = Array(pedal.knobs.dropLast(2))
let rows: [[PedalKnob]] = stride(from: 0, to: knobs.count, by: columns).map { start in
Array(knobs[start ..< min(start + columns, knobs.count)])
}
return VStack(spacing: PedalView.knobSpacing) {
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
HStack(spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in
let knob: PedalKnob = knobPair.element
ParameterKnob(knob.label, node: knob.node, range: knob.range)
.foregroundStyle(Color.white)
}
Spacer(minLength: 0)
}
}
}
}
/// Preferred grid order for the looper's transport footswitches (row-major), so the 2×2 grid
/// reads Record / Reverse over Stop / Cue Stop. Buttons not listed keep their original order
/// and follow. Matched by label to stay robust if the descriptor order changes.
private static let looperTransportOrder: [String] = ["Loop", "Reverse", "Stop", "Cue Stop"]
/// The looper's transport footswitches — everything except the trailing Reset (which sits in
/// the left column) — laid out in rows of `columns` in ``looperTransportOrder``.
private func looperTransportGrid(columns: Int) -> some View {
let buttons: [PedalButton] = Array(pedal.effectTransportButtons.dropLast())
let ordered: [PedalButton] =
PedalView.looperTransportOrder.compactMap { label in buttons.first { $0.label == label } }
+ buttons.filter { !PedalView.looperTransportOrder.contains($0.label) }
let rows: [[PedalButton]] = stride(from: 0, to: ordered.count, by: columns).map { start in
Array(ordered[start ..< min(start + columns, ordered.count)])
}
return VStack(spacing: PedalView.knobSpacing) {
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(rowPair.element.enumerated()), id: \.offset) { pair in
PedalButtonView(pair.element)
}
Spacer(minLength: 0)
}
}
}
}
/// The looper's footer: Level on the left, Bypass in the centre, and an empty third where a
/// normal pedal's Mix knob would sit — so Bypass stays horizontally centred in the column.
private var looperFooter: some View {
HStack(spacing: 0) {
levelControl
.frame(maxWidth: .infinity)
bypassControl
.frame(maxWidth: .infinity)
Color.clear
.frame(maxWidth: .infinity, maxHeight: 0) // reserved Mix slot
}
}
/// The Reset footswitch (the trailing transport button), centred — sits at the bottom of the
/// looper's left (timeline) column.
@ViewBuilder
private var looperResetCell: some View {
if let reset: PedalButton = pedal.effectTransportButtons.last {
HStack(spacing: 0) {
Spacer(minLength: 0)
PedalButtonView(reset)
Spacer(minLength: 0)
}
}
}
// MARK: - Subviews
/// Capsule name plate near the top of the enclosure.
@@ -354,24 +501,25 @@ public struct PedalView: View {
/// `Level` on the left, `Mix` on the right — leaving more room for the effect controls
/// at the top and giving every pedal a symmetric footer.
private var knobGrid: some View {
// Wide (double-width) pedals fit four knobs across, so a four-knob effect bank (e.g.
// the looper's Crossfade / Playback / Overdub / Feedback) sits on one row.
let columns: Int = pedal.widthUnits >= 2 ? PedalView.wideKnobColumnCount : PedalView.knobColumnCount
let knobs: [PedalKnob] = Array(pedal.knobs.dropLast(2))
let rows: [[PedalKnob]] = stride(
from: 0,
to: knobs.count,
by: PedalView.knobColumnCount
by: columns
).map { startIndex in
Array(knobs[startIndex ..< min(startIndex + PedalView.knobColumnCount, knobs.count)])
Array(knobs[startIndex ..< min(startIndex + columns, knobs.count)])
}
return VStack(spacing: PedalView.knobSpacing) {
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
let row: [PedalKnob] = rowPair.element
// Centre each row: a short row (one or two knobs) sits centred in the
// enclosure rather than left-aligned. Symmetric spacers also centre a full
// three-knob row, so every row stays horizontally centred.
// A full three-knob row keeps the tight spacing so it fits the enclosure;
// Centre each row: a short row sits centred in the enclosure rather than
// left-aligned. A full row keeps the tight spacing so it fits the enclosure;
// shorter centred rows use a wider, touch-friendly gap.
let rowItemSpacing: CGFloat = row.count >= PedalView.knobColumnCount
let rowItemSpacing: CGFloat = row.count >= columns
? PedalView.knobSpacing
: PedalView.knobRowItemSpacing
HStack(spacing: rowItemSpacing) {
@@ -417,6 +565,40 @@ public struct PedalView: View {
}
}
/// Transport-control row drawn from `pedal.effectTransportButtons`, placed directly below
/// the knobs so persistent state toggles and transport stops (e.g. the looper's Loop /
/// Stop / Cue Stop / Reverse) sit apart from the momentary actions. Renders nothing when
/// the pedal publishes no transport buttons.
@ViewBuilder
private var transportButtonRow: some View {
let buttons: [PedalButton] = pedal.effectTransportButtons
if !buttons.isEmpty {
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(buttons.enumerated()), id: \.offset) { pair in
PedalButtonView(pair.element)
}
Spacer(minLength: 0)
}
}
}
/// Row of momentary stomp-style action buttons drawn from `pedal.effectButtons`, beneath
/// the transport row. Renders nothing when the pedal publishes no buttons.
@ViewBuilder
private var buttonRow: some View {
let buttons: [PedalButton] = pedal.effectButtons
if !buttons.isEmpty {
HStack(spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(buttons.enumerated()), id: \.offset) { pair in
PedalButtonView(pair.element)
}
Spacer(minLength: 0)
}
}
}
/// Row of vertical faders drawn from `pedal.effectSliders`, beneath the switch row.
/// Renders nothing when the pedal publishes no sliders.
@ViewBuilder
@@ -431,16 +613,19 @@ public struct PedalView: View {
}
}
/// Enclosure width — the base stompbox width, widened to fit a wide vertical-fader bank
/// (e.g. a multi-band graphic EQ) so its faders are never clipped.
/// Enclosure width — the base stompbox width scaled by the pedal's `widthUnits`
/// (a control-dense pedal such as the looper asks for a double-width card), widened
/// further to fit a wide vertical-fader bank (e.g. a multi-band graphic EQ) so its
/// faders are never clipped.
private func enclosureWidth(for sliders: [PedalSlider]) -> CGFloat {
let unitWidth: CGFloat = PedalView.enclosureWidth * CGFloat(max(1, pedal.widthUnits))
let sliderCount: Int = sliders.count
guard sliderCount > 0 else { return PedalView.enclosureWidth }
guard sliderCount > 0 else { return unitWidth }
let bankContentWidth: CGFloat =
CGFloat(sliderCount) * PedalView.sliderBankItemWidth
+ CGFloat(max(0, sliderCount - 1)) * PedalView.sliderBankSpacing
let needed: CGFloat = bankContentWidth + 2 * PedalView.enclosurePadding
return max(PedalView.enclosureWidth, needed)
return max(unitWidth, needed)
}
/// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob,
@@ -464,10 +649,11 @@ public struct PedalView: View {
}
/// The `Mix` knob — the second-to-last entry of `pedal.knobs` — placed right of the
/// bypass switch to mirror `Level`.
/// bypass switch to mirror `Level`. Hidden for pedals that manage their own dry/wet balance
/// (``Pedal/showsMixControl``), e.g. the looper.
@ViewBuilder
private var mixControl: some View {
if let mix: PedalKnob = pedal.knobs.dropLast().last {
if pedal.showsMixControl, let mix: PedalKnob = pedal.knobs.dropLast().last {
ParameterKnob(mix.label, node: mix.node, range: mix.range)
.foregroundStyle(Color.white)
}
@@ -479,9 +665,10 @@ public struct PedalView: View {
// re-renders whenever the bypass parameter changes on the main thread
// (UIParamNode is @Observable).
let bypassValue: Double = pedal.$bypass.value
let engagedThreshold: Double = 0.5
return VStack(spacing: PedalView.bypassSectionSpacing) {
LEDIndicator(bypassValue: bypassValue)
LEDIndicator(isOn: bypassValue < engagedThreshold)
FootswitchButton(node: pedal.$bypass)
}
}
@@ -49,6 +49,11 @@ public struct ShoeGazeBuilderView: View {
/// Width of the scope/CPU block in the bottom strip — matches `BoardBarView`'s Solo/Blend/All
/// control column so the scope aligns under it.
private static let scopeWidth: CGFloat = 188
/// Narrow scope shown in the compact (iPad) header, tucked left of the transport buttons.
private static let compactHeaderScopeWidth: CGFloat = 340
private static let compactHeaderScopeHeight: CGFloat = 76
/// Stable height (fraction of the screen) for the Add-Pedal sheet — a single, non-resizable detent.
private static let paletteSheetHeightFraction: CGFloat = 0.82
private static let columnSpacing: CGFloat = 14
private static let backgroundRed: Double = 0.08
private static let backgroundGreen: Double = 0.07
@@ -157,6 +162,21 @@ public struct ShoeGazeBuilderView: View {
/// Help sheet presentation flag (iOS button; macOS uses the Help menu).
@State private var showHelpSheet: Bool = false
/// Compact-layout sheet flags — the composition panels docked in the regular layout become
/// bottom sheets so the board canvas gets the full screen.
@State private var showRigsSheet: Bool = false
@State private var showPaletteSheet: Bool = false
@State private var showSettingsSheet: Bool = false
/// Type filter for the compact Add-Pedal sheet, hoisted so it sits in the sheet's fixed header.
@State private var pedalFilter: PedalCategory?
/// `true` when the window is taller than it is wide (portrait). iPad is `.regular` in both
/// orientations, so this is derived from the actual size, not the size class. In portrait the
/// header scope moves to a full-width strip below the controls (it would otherwise overlay /
/// clip the header on narrower iPads); landscape keeps it inline beside the transport.
@State private var isPortrait: Bool = false
#if !os(macOS)
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
@State private var showRecordingFolderImporter: Bool = false
@@ -197,16 +217,30 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Body
/// `true` on iPad (any size) — the canvas-first layout with composition panels in sheets. The
/// docked desktop layout is macOS-only; on iPad it overflowed and clipped even at iPad-Pro
/// width, so every iPad size uses the sheet-based layout. macOS always uses the docked layout.
private var isCompact: Bool {
#if os(iOS)
return true
#else
return false
#endif
}
public var body: some View {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
rigSidebar
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
builderColumn
}
rootContent
.padding(ShoeGazeBuilderView.outerPadding)
// A large min width is a macOS window sizing hint; on iPad it would force content wider than
// the screen and clip it, so the sheet-based iPad layout imposes no minimum width. Fill the
// whole window and pin to the top-leading corner so portrait isn't vertically centered.
.frame(
minWidth: ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve,
minHeight: ShoeGazeBuilderView.minHeight
minWidth: isCompact ? nil : ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve,
maxWidth: isCompact ? .infinity : nil,
minHeight: isCompact ? nil : ShoeGazeBuilderView.minHeight,
maxHeight: isCompact ? .infinity : nil,
alignment: .topLeading
)
.background(
Color(
@@ -215,6 +249,14 @@ public struct ShoeGazeBuilderView: View {
blue: ShoeGazeBuilderView.backgroundBlue
)
)
// Track portrait vs landscape by actual size (iPad is `.regular` in both orientations).
.background(
GeometryReader { proxy in
Color.clear.task(id: proxy.size) {
isPortrait = proxy.size.height > proxy.size.width
}
}
)
// The builder is always dark-themed; force the dark scheme so system controls (nav title,
// steppers, the Record button) use light text instead of black-on-dark in light mode.
.preferredColorScheme(.dark)
@@ -309,9 +351,57 @@ public struct ShoeGazeBuilderView: View {
.sheet(isPresented: $showHelpSheet) {
HelpView()
}
// Each compact composition sheet lives on its own anchor node — SwiftUI presents at most one
// sheet per node, so stacking them on the main node would silently swallow all but one.
.background(rigsSheetAnchor)
.background(paletteSheetAnchor)
.background(settingsSheetAnchor)
.overlay(alignment: .top) { midiLearnBanner }
}
/// Hosts the compact rig-library sheet on its own node.
private var rigsSheetAnchor: some View {
Color.clear
.sheet(isPresented: $showRigsSheet) {
rigSidebar
.padding(.top, ShoeGazeBuilderView.outerPadding)
.presentationDetents([.large])
.preferredColorScheme(.dark)
}
}
/// Hosts the compact Add-pedal palette sheet on its own node.
private var paletteSheetAnchor: some View {
Color.clear
.sheet(isPresented: $showPaletteSheet) {
paletteSheet
}
}
/// Hosts the compact engine-settings sheet on its own node.
private var settingsSheetAnchor: some View {
Color.clear
.sheet(isPresented: $showSettingsSheet) {
settingsSheet
.presentationDetents([.medium, .large])
}
}
/// The whole-view layout: docked desktop layout on regular widths, canvas-first on compact.
@ViewBuilder
private var rootContent: some View {
if isCompact {
// No docked sidebar — the rig library is a sheet reached from the header.
builderColumn
} else {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
rigSidebar
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
builderColumn
}
}
}
/// A banner shown while a control is armed for MIDI Learn, prompting the user to move it.
@ViewBuilder
private var midiLearnBanner: some View {
@@ -384,17 +474,297 @@ public struct ShoeGazeBuilderView: View {
/// board canvas.
private var builderColumn: some View {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
transportRow
ioRow
#if !os(macOS)
recordingRow
#endif
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
topSection
if isCompact {
compactHeader
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
compactTopSection
} else {
headerSection
#if !os(macOS)
recordingRow
#endif
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
topSection
}
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
}
// MARK: - Compact layout (iPhone / narrow iPad)
/// The compact header: a performance row (title, transport, mute) always visible, plus a
/// horizontally scrollable row of panel toggles that open the composition sheets.
private var compactHeader: some View {
_ = transportTick
// The three control rows stack tight on the left; the transport sits top-right. The scope
// is inline (right, spanning the rows) in landscape, but on narrower portrait widths it
// would overlay/clip the header — so there it drops to a full-width strip below the rows.
// Row 1: title · [Bypass · Mute · Help · MIDI] Row 2: Tempo · Tuner Row 3: Rigs/Pedals/Settings
return VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
headerControlRows
if !isPortrait {
// Inline: clamped to the compact header height (a short strip beside transport).
headerScope
.frame(
width: ShoeGazeBuilderView.compactHeaderScopeWidth,
height: ShoeGazeBuilderView.compactHeaderScopeHeight
)
}
headerTransport
}
if isPortrait {
// Full-width strip at the scope's natural height (legend + lanes), so the legend
// doesn't overflow up into the panel row.
headerScope
.frame(maxWidth: .infinity)
}
}
}
/// The three stacked control rows shared by both orientations.
private var headerControlRows: some View {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
VStack(alignment: .leading, spacing: 1) {
Text("ShoeGaze").font(.headline).bold()
.foregroundStyle(Color.white)
currentRigLabel
}
if shoeGaze.isRecording { recordingBadge }
compactRigControlsRow
}
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
TempoView(shoeGaze: shoeGaze)
TunerView(shoeGaze: shoeGaze)
}
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
compactPanelRow
}
.frame(maxWidth: .infinity, alignment: .leading)
}
/// The oscilloscope. The caller sizes it: a fixed short strip inline (landscape) or a
/// full-width strip at natural height (portrait).
private var headerScope: some View {
ShoeGazeScopeView(shoeGaze: shoeGaze)
}
/// The Start / Stop over Record transport cluster (top-right in both orientations).
private var headerTransport: some View {
VStack(alignment: .trailing, spacing: ShoeGazeBuilderView.rowSpacing) {
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() },
transportOnly: true
)
#if !os(macOS)
recordButton
#endif
}
}
/// The rig-wide controls shown inline on the title row: Bypass / Mute / Help / MIDI.
private var compactRigControlsRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
rigBypassButton
// fixedSize stops the switch Toggle from expanding to fill the row (which pushed
// the following controls far to the right, under the scope).
Toggle("Mute rig", isOn: Binding(
get: { shoeGaze.tunerMutesRig },
set: { shoeGaze.tunerMutesRig = $0 }
))
.toggleStyle(.switch)
.fixedSize()
helpButton
if let midi: MIDIController = midi {
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
}
}
}
}
/// The composition-panel row: buttons that open the Rigs / Pedals / Settings sheets.
private var compactPanelRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
compactPanelButton("Rigs", systemImage: "tray.full") { showRigsSheet = true }
compactPanelButton("Pedals", systemImage: "plus.app") { showPaletteSheet = true }
compactPanelButton("Settings", systemImage: "gearshape") { showSettingsSheet = true }
}
}
}
/// The recording indicator badge (extracted so both header variants can show it).
private var recordingBadge: some View {
HStack(spacing: 4) {
Circle()
.fill(Color.red)
.frame(width: ShoeGazeBuilderView.recordDotSize, height: ShoeGazeBuilderView.recordDotSize)
Text("REC")
.font(.caption.monospaced())
.foregroundStyle(Color.red)
}
}
/// A labelled icon button that opens one of the compact composition sheets.
private func compactPanelButton(
_ title: String,
systemImage: String,
action: @escaping () -> Void
) -> some View {
Button(action: action) {
Label(title, systemImage: systemImage)
.font(.subheadline)
}
.buttonStyle(.bordered)
.tint(.gray)
}
/// Compact top strip: performance monitoring kept on screen — the board switch/mixer bar, the
/// scope, and the CPU meters. Tempo / Tuner sit below so they don't crowd the transport row.
private var compactTopSection: some View {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
BoardBarView(
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() },
onClearBoards: { showClearDialog = true }
)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
// Scope + Tempo/Tuner moved to the header; the CPU meters stay here.
LyrebirdStatusView(engine: shoeGaze.engine)
}
}
/// The Add-a-pedal palette + routing options, presented as a compact sheet.
private var paletteSheet: some View {
// A fixed header (title, type filter, Done) over a scrolling list. Not a NavigationStack —
// its transparent bar let the list scroll under the title. The palette does not self-wrap in
// a ScrollView (the host must), so it is wrapped here.
VStack(spacing: 0) {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Text("Add Pedal")
.font(.headline)
.foregroundStyle(Color.white)
Spacer()
pedalFilterMenu
Button("Done") { showPaletteSheet = false }
.fontWeight(.semibold)
}
.padding()
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
ScrollView {
PedalPaletteView(
axis: .vertical,
filter: $pedalFilter,
showsFilterMenu: false,
onAdd: { type in addPedal(type: type); showPaletteSheet = false },
onRouting: { action in performRouting(action); showPaletteSheet = false }
)
.padding()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
.preferredColorScheme(.dark)
// One fixed detent (no resize-drag) and drags scroll the list instead of the sheet.
.presentationDetents([.fraction(ShoeGazeBuilderView.paletteSheetHeightFraction)])
.presentationContentInteraction(.scrolls)
}
/// The type-filter menu shown in the Add-Pedal sheet header, bound to `pedalFilter`.
private var pedalFilterMenu: some View {
Menu {
Button("All Types") { pedalFilter = nil }
Divider()
ForEach(PedalCategory.allCases) { category in
Button(category.rawValue) { pedalFilter = category }
}
} label: {
HStack(spacing: 3) {
Image(systemName: "line.3.horizontal.decrease.circle")
Text(pedalFilter?.rawValue ?? "All").lineLimit(1)
}
}
}
/// Engine configuration (sample rate, input/output channel counts, input source), presented as
/// a compact sheet — the set-and-forget composition controls.
private var settingsSheet: some View {
NavigationStack {
// A plain scroll (not a Form) so the engine controls' horizontal row has the full sheet
// width — a Form row compresses it and clips the Start button to "S…".
ScrollView {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
Text("Engine")
.font(.headline)
.foregroundStyle(Color.white)
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() }
)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
HStack {
Text("Input")
.font(.headline)
.foregroundStyle(Color.white)
Spacer()
Picker("Input", selection: inputBinding) {
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
if shoeGaze.engine.numInputChannels > 0 {
ForEach(Array(0..<shoeGaze.engine.numInputChannels), id: \.self) { channel in
Text("In \(channel)").tag(channel)
}
} else if onEnableLiveInput != nil {
Text("Live Input").tag(0)
}
}
.labelsHidden()
.pickerStyle(.menu)
}
#if !os(macOS)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
Text("Recording")
.font(.headline)
.foregroundStyle(Color.white)
recordingFolderPicker
#endif
Spacer(minLength: 0)
}
.padding()
.frame(maxWidth: .infinity, alignment: .leading)
}
.navigationTitle("Settings")
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") { showSettingsSheet = false }
}
}
}
.preferredColorScheme(.dark)
}
/// Top section: the scope + CPU meters on the left (sized to align with the mixer's
@@ -415,7 +785,8 @@ public struct ShoeGazeBuilderView: View {
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
onAddBoard: { addBoard() },
onClearBoards: { showClearDialog = true }
)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
pedalPickerRow
@@ -530,12 +901,18 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Transport row
private var transportRow: some View {
/// Two-row header. Left: the title with the Tempo / Tuner toggles stacked and left-aligned
/// beside it. Right: the engine options (row 1) over the input controls (row 2), trailing-
/// aligned so both right edges line up. Keeping it two rows tall frees canvas for the pedals.
private var headerSection: some View {
_ = transportTick
return HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Text("ShoeGaze Builder")
.font(.title2).bold()
.foregroundStyle(Color.white)
return HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
VStack(alignment: .leading, spacing: 1) {
Text("ShoeGaze")
.font(.title2).bold()
.foregroundStyle(Color.white)
currentRigLabel
}
if shoeGaze.isRecording {
// Recording indicator (both platforms; recording is driven from the macOS Record
// menu or the iOS controls below).
@@ -548,17 +925,60 @@ public struct ShoeGazeBuilderView: View {
.foregroundStyle(Color.red)
}
}
Spacer()
if let midi: MIDIController = midi {
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
// Tempo over Tuner, left-aligned to each other.
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
TempoView(shoeGaze: shoeGaze)
TunerView(shoeGaze: shoeGaze)
}
Spacer()
// Right column: engine options over input controls, both right-aligned.
VStack(alignment: .trailing, spacing: ShoeGazeBuilderView.rowSpacing) {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
if let midi: MIDIController = midi {
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
}
helpButton
rigBypassButton
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() }
)
}
.frame(height: TempoView.enabledHeight)
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
// Mute-rig-while-tuning toggle sits to the left of the input selector.
Toggle("Mute rig", isOn: Binding(
get: { shoeGaze.tunerMutesRig },
set: { shoeGaze.tunerMutesRig = $0 }
))
.toggleStyle(.switch)
Text("Input:")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
Picker("Input", selection: inputBinding) {
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
if shoeGaze.engine.numInputChannels > 0 {
ForEach(Array(0..<shoeGaze.engine.numInputChannels), id: \.self) { channel in
Text("In \(channel)").tag(channel)
}
} else if onEnableLiveInput != nil {
// No input channel yet: offer live input; selecting it asks the host to
// request mic access and rebuild the engine with one (channel 0).
Text("Live Input").tag(0)
}
}
.labelsHidden()
.pickerStyle(.menu)
.foregroundStyle(Color.white)
}
.frame(height: TempoView.enabledHeight)
}
helpButton
rigBypassButton
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() }
)
}
}
@@ -590,40 +1010,6 @@ public struct ShoeGazeBuilderView: View {
.help("Bypass the entire rig — every board passes your dry input straight through")
}
// MARK: - Input + board + save/load row
private var ioRow: some View {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Text("Input:")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
Picker("Input", selection: inputBinding) {
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
if shoeGaze.engine.numInputChannels > 0 {
ForEach(Array(0..<shoeGaze.engine.numInputChannels), id: \.self) { channel in
Text("In \(channel)").tag(channel)
}
} else if onEnableLiveInput != nil {
// No input channel yet: offer live input; selecting it asks the host to
// request mic access and rebuild the engine with one (channel 0).
Text("Live Input").tag(0)
}
}
.pickerStyle(.menu)
.foregroundStyle(Color.white)
Button("Boards…") { showBoardsSheet = true }
.buttonStyle(.bordered).tint(.orange)
.help("Rename, reorder, or delete boards")
Button("Clear") { showClearDialog = true }
.buttonStyle(.bordered).tint(.red)
.help("Remove all boards in the current rig (with the option to save first)")
Spacer()
}
}
// MARK: - Board area
private var boardArea: some View {
@@ -729,6 +1115,11 @@ public struct ShoeGazeBuilderView: View {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
// Clearing the rig discards its MIDI bindings — they are addressed positionally and
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't
// re-resolve onto the fresh board's pedals.
shoeGaze.midiMap = nil
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
@@ -849,6 +1240,26 @@ public struct ShoeGazeBuilderView: View {
#if !os(macOS)
/// iOS recording controls: choose an output folder, then start/stop recording.
private var recordingRow: some View {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
recordingFolderPicker
Spacer()
recordButton
}
}
/// The Record / Stop-Recording button (performance control; lives in the compact header).
private var recordButton: some View {
Button(shoeGaze.isRecording ? "Stop Recording" : "Record") {
toggleRecording()
}
.buttonStyle(.borderedProminent)
.tint(shoeGaze.isRecording ? .red : .accentColor)
.disabled(shoeGaze.recordingFolder == nil && !shoeGaze.isRecording)
}
/// The recording-folder chooser + current folder name (a set-and-forget control; shown in the
/// compact Settings sheet).
private var recordingFolderPicker: some View {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Button("Recording Folder…") { showRecordingFolderImporter = true }
.buttonStyle(.bordered).tint(.blue)
@@ -857,13 +1268,6 @@ public struct ShoeGazeBuilderView: View {
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.folderLabelOpacity))
.lineLimit(1)
.truncationMode(.middle)
Spacer()
Button(shoeGaze.isRecording ? "Stop Recording" : "Record") {
toggleRecording()
}
.buttonStyle(.borderedProminent)
.tint(shoeGaze.isRecording ? .red : .accentColor)
.disabled(shoeGaze.recordingFolder == nil && !shoeGaze.isRecording)
}
}
@@ -1096,6 +1500,32 @@ public struct ShoeGazeBuilderView: View {
return library.entries.first(where: { $0.id == id })?.name
}
/// A subtitle under the app title showing which rig is loaded. Resolves the name from the
/// library once it has loaded; shows "Unsaved rig" when the working graph has no source-rig
/// id (a cleared / never-saved session). Reads `shoeGaze.currentRigID` and `library.entries`
/// so it refreshes automatically when a rig is loaded or the library finishes loading.
private var currentRigLabel: some View {
let hasSource: Bool = currentRigID != nil
let name: String
if let resolved: String = currentRigName() {
name = resolved
} else if hasSource {
// Source id exists but the library hasn't resolved it yet (still loading).
name = library.isLoaded ? "Unknown rig" : "Loading…"
} else {
name = "Unsaved rig"
}
return HStack(spacing: 5) {
Image(systemName: hasSource ? "guitars.fill" : "guitars")
.font(.caption2)
Text(name)
.font(.caption)
.lineLimit(1)
}
.foregroundStyle(Color.white.opacity(hasSource ? 0.8 : 0.5))
.help(hasSource ? "Loaded rig: \(name)" : "This rig has not been saved to the library yet")
}
/// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names.
private func defaultNewRigName() -> String {
let base: String = "Rig"
@@ -0,0 +1,22 @@
// TempoEnabledEnvironment.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
/// Environment flag mirroring ``ShoeGaze/tempoEnabled`` so leaf views (e.g. ``PedalSwitchView``)
/// can disable tempo-synced controls without each needing a reference to the session. Set once
/// near the builder root; defaults to `true`.
private struct TempoEnabledKey: EnvironmentKey {
static let defaultValue: Bool = true
}
extension EnvironmentValues {
/// `true` when the tempo indicator is shown and tempo-synced features are active.
var shoeGazeTempoEnabled: Bool {
get { self[TempoEnabledKey.self] }
set { self[TempoEnabledKey.self] = newValue }
}
}
+118
View File
@@ -0,0 +1,118 @@
// TempoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdShoeGaze
/// Tempo indicator: a BPM readout/stepper, a beat-synced flashing LED, and a tap area that
/// responds to mouse/touch taps (call ``ShoeGaze/tapTempo()`` directly for a MIDI trigger).
///
/// Polls ``ShoeGaze/clock``'s `currentBeat` on a `.task` loop (matching the scope/CPU-meter
/// polling convention) since `LyrebirdClock` isn't `@Observable` — it's sample-accurate RT
/// state, not push-notified UI state.
public struct TempoView: View {
// MARK: - Constants
private static let pollIntervalNanoseconds: UInt64 = 33_333_333 // ~30 Hz
/// Fraction of each beat the LED stays lit — a short flash, not a 50% duty-cycle blink.
private static let flashDutyCycle: Double = 0.15
private static let minBpm: Double = 30.0
private static let maxBpm: Double = 300.0
private static let bpmStep: Double = 1.0
private static let ledDiameter: CGFloat = 14
private static let rowSpacing: CGFloat = 10
/// Fixed row height = the enabled (BPM/TAP-visible) height, so toggling doesn't shift layout.
static let enabledHeight: CGFloat = 34
// MARK: - Properties
private let shoeGaze: ShoeGaze
@State private var displayedBpm: Double
@State private var ledOn: Bool = false
// MARK: - Init
/// - Parameter shoeGaze: The session whose ``ShoeGaze/clock`` this view displays and drives.
public init(shoeGaze: ShoeGaze) {
self.shoeGaze = shoeGaze
self._displayedBpm = State(initialValue: shoeGaze.clock.bpm)
}
// MARK: - Body
public var body: some View {
HStack(spacing: TempoView.rowSpacing) {
Button(shoeGaze.tempoEnabled ? "Tempo: On" : "Tempo: Off") {
shoeGaze.setTempoEnabled(!shoeGaze.tempoEnabled)
}
.buttonStyle(.bordered)
.tint(shoeGaze.tempoEnabled ? .green : .gray)
.fixedSize()
.help("Show the tempo indicator and enable tempo-synced controls")
if shoeGaze.tempoEnabled {
led
Text("\(Int(displayedBpm.rounded())) BPM")
.font(.system(size: 18, weight: .semibold, design: .rounded))
.foregroundStyle(Color.white)
Stepper(
"",
value: Binding(
get: { displayedBpm },
set: { newValue in
let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm)
shoeGaze.clock.bpm = clamped
displayedBpm = clamped
}
),
in: TempoView.minBpm ... TempoView.maxBpm,
step: TempoView.bpmStep
)
.labelsHidden()
tapArea
}
}
// Pin to the enabled height (BPM / stepper / TAP visible) so toggling tempo on/off never
// shifts the surrounding layout.
.frame(height: TempoView.enabledHeight)
.task(id: shoeGaze.tempoEnabled) {
while shoeGaze.tempoEnabled && !Task.isCancelled {
let beat: Double = shoeGaze.clock.currentBeat
let phase: Double = beat - beat.rounded(.down)
ledOn = phase < TempoView.flashDutyCycle
displayedBpm = shoeGaze.clock.bpm
try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds)
}
}
}
// MARK: - Subviews
private var led: some View {
Circle()
.fill(ledOn ? Color.red : Color.red.opacity(0.15))
.frame(width: TempoView.ledDiameter, height: TempoView.ledDiameter)
}
private var tapArea: some View {
// A standard-height bordered button (not a tall circle) so the tempo row matches the
// height of the title and the engine-option buttons and top-aligns cleanly with them.
Button {
shoeGaze.tapTempo()
displayedBpm = shoeGaze.clock.bpm
} label: {
Text("TAP")
.font(.system(size: 13, weight: .bold, design: .rounded))
}
.buttonStyle(.bordered)
.tint(.gray)
.foregroundStyle(Color.white)
}
}
+210
View File
@@ -0,0 +1,210 @@
// TunerView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdSynth
import LyrebirdShoeGaze
/// Chromatic tuner panel: an engage toggle, a mute-rig-while-tuning toggle, and a live
/// note/cents readout.
///
/// Polls ``ShoeGaze/currentPitchHz`` on a `.task` loop (matching `LyrebirdEngineStatusView`'s
/// CPU-meter convention) since the value is computed from RT-thread state on demand, not an
/// `@Observable`-tracked property. Polling only runs while the tuner is engaged.
public struct TunerView: View {
// MARK: - Constants
private static let pollIntervalNanoseconds: UInt64 = 250_000_000 // 4 Hz, at most
private static let inTuneCentsThreshold: Double = 5.0
private static let closeCentsThreshold: Double = 15.0
/// Below this YIN confidence the reading is treated as untracked — the last stable pitch
/// is latched and the display dims, rather than chasing a transient/attack estimate.
private static let trackingConfidenceThreshold: Double = 0.8
/// Opacity applied to the latched readout while not actively tracking.
private static let untrackedOpacity: Double = 0.35
private static let rowSpacing: CGFloat = 14
private static let readoutSpacing: CGFloat = 10
private static let noteFontSize: CGFloat = 24
private static let statusFontSize: CGFloat = 10
/// Fixed row height = the engaged (readout-visible) height, so toggling doesn't shift layout.
static let engagedHeight: CGFloat = 34
// MARK: - Properties
private let shoeGaze: ShoeGaze
/// Last pitch accepted at or above the confidence threshold (latched through dropouts).
@State private var latchedPitch: TunerPitchReading?
/// `true` when the most recent poll was above the confidence threshold.
@State private var isTracking: Bool = false
// MARK: - Init
/// - Parameter shoeGaze: The session whose tuner state this view controls and displays.
public init(shoeGaze: ShoeGaze) {
self.shoeGaze = shoeGaze
}
// MARK: - Body
public var body: some View {
// Single horizontal row so engaging the tuner grows it sideways, not downward — the
// transport row keeps its height and the pedals below don't jump.
HStack(spacing: TunerView.rowSpacing) {
Button(shoeGaze.tunerEngaged ? "Tuner: On" : "Tuner: Off") {
shoeGaze.toggleTunerEngaged()
}
.buttonStyle(.bordered)
.tint(shoeGaze.tunerEngaged ? .green : .gray)
.fixedSize()
if shoeGaze.tunerEngaged {
readout
}
}
// Pin to the engaged height (the taller readout state) so toggling the tuner on/off never
// shifts the surrounding layout by a few pixels.
.frame(height: TunerView.engagedHeight)
.task(id: shoeGaze.tunerEngaged) {
while shoeGaze.tunerEngaged && !Task.isCancelled {
updateReading()
try? await Task.sleep(nanoseconds: TunerView.pollIntervalNanoseconds)
}
if !shoeGaze.tunerEngaged {
latchedPitch = nil
isTracking = false
}
}
}
/// Polls freq + confidence. Above the confidence threshold, updates the latched pitch
/// and marks tracking active; below it, leaves the latched pitch in place (so restrikes
/// don't make the reading ramp) and marks tracking inactive.
private func updateReading() {
let confidence: Double = shoeGaze.currentPitchConfidence ?? 0.0
let hz: Double = shoeGaze.currentPitchHz ?? 0.0
if confidence >= TunerView.trackingConfidenceThreshold && hz > 0 {
latchedPitch = TunerPitchReading(hz: hz)
isTracking = true
} else {
isTracking = false
}
}
// MARK: - Readout
@ViewBuilder
private var readout: some View {
if let pitch: TunerPitchReading = latchedPitch {
HStack(spacing: TunerView.readoutSpacing) {
Text(pitch.noteName)
.font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded))
.foregroundStyle(TunerView.color(forCents: pitch.cents))
TunerCentsMeter(cents: pitch.cents)
Text(isTracking ? "TRACKING" : "…")
.font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.white.opacity(0.5))
}
.opacity(isTracking ? 1.0 : TunerView.untrackedOpacity)
} else {
HStack(spacing: TunerView.readoutSpacing) {
Text("—")
.font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded))
.foregroundStyle(Color.white.opacity(0.4))
Text("play a note")
.font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced))
.foregroundStyle(Color.white.opacity(0.4))
}
}
}
static func color(forCents cents: Double) -> Color {
let magnitude: Double = abs(cents)
if magnitude <= TunerView.inTuneCentsThreshold { return .green }
if magnitude <= TunerView.closeCentsThreshold { return .yellow }
return .red
}
}
// MARK: - TunerCentsMeter
/// A horizontal -50…+50 cents meter: a track with a centre "in tune" tick and a vertical
/// marker positioned at the current deviation, coloured with the same red/yellow/green
/// thresholds as the note readout.
struct TunerCentsMeter: View {
private static let range: Double = 50.0
private static let trackWidth: CGFloat = 140
private static let trackHeight: CGFloat = 4
private static let markerWidth: CGFloat = 3
private static let markerHeight: CGFloat = 18
private static let centerTickWidth: CGFloat = 1.5
private static let centerTickHeight: CGFloat = 10
let cents: Double
private var clampedFraction: Double {
// Maps [-range, +range] to [0, 1]; values beyond the range pin to the edge.
let clamped: Double = min(max(cents, -TunerCentsMeter.range), TunerCentsMeter.range)
return (clamped + TunerCentsMeter.range) / (2.0 * TunerCentsMeter.range)
}
var body: some View {
GeometryReader { geometry in
let width: CGFloat = geometry.size.width
let markerX: CGFloat = width * clampedFraction
ZStack(alignment: .leading) {
// Track.
RoundedRectangle(cornerRadius: TunerCentsMeter.trackHeight / 2)
.fill(Color.white.opacity(0.15))
.frame(height: TunerCentsMeter.trackHeight)
.frame(maxWidth: .infinity)
// Centre "in tune" reference tick.
Rectangle()
.fill(Color.white.opacity(0.5))
.frame(width: TunerCentsMeter.centerTickWidth, height: TunerCentsMeter.centerTickHeight)
.position(x: width / 2, y: TunerCentsMeter.trackHeight / 2)
// Deviation marker.
Rectangle()
.fill(TunerView.color(forCents: cents))
.frame(width: TunerCentsMeter.markerWidth, height: TunerCentsMeter.markerHeight)
.position(x: markerX, y: TunerCentsMeter.trackHeight / 2)
}
}
.frame(width: TunerCentsMeter.trackWidth, height: TunerCentsMeter.markerHeight)
}
}
// MARK: - TunerPitchReading
/// Converts a detected frequency into the nearest chromatic note name, octave, and cents
/// deviation. Standard 12-TET sharp spelling — a tuner display doesn't need the full
/// spelling-aware `NoteName`/`Scale` theory toolkit (that's for compositional notation).
struct TunerPitchReading {
private static let chromaticNames: [String] = [
"C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B",
]
private static let semitonesPerOctave: Int = 12
private static let midiOctaveOffset: Int = 1 // MIDI note 0 = C-1
private static let centsPerSemitone: Double = 100.0
let noteName: String
let cents: Double
init(hz: Double) {
let midi: Double = hzToMidi(hz)
let nearestMidi: Int = Int(midi.rounded())
cents = (midi - Double(nearestMidi)) * TunerPitchReading.centsPerSemitone
let pitchClass: Int = ((nearestMidi % TunerPitchReading.semitonesPerOctave)
+ TunerPitchReading.semitonesPerOctave) % TunerPitchReading.semitonesPerOctave
let octave: Int = nearestMidi / TunerPitchReading.semitonesPerOctave - TunerPitchReading.midiOctaveOffset
noteName = "\(TunerPitchReading.chromaticNames[pitchClass])\(octave)"
}
}
@@ -0,0 +1,666 @@
// LooperPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("LooperPedal")
struct LooperPedalTests {
// MARK: - Test fixtures
/// A constant-frequency sine source with a live-settable amplitude, so tests can silence the
/// live input at an exact scheduled time and attribute any remaining output to the looper.
private final class ToneSource: SynthesizerBase {
let ampNode: ParameterNode = ParameterNode(0.3)
var amplitude: Double {
get { ampNode.value }
set { ampNode.value = newValue }
}
private let targetBus: Int
private let toneFreq: Double
init(targetBus: Int, freq: Double = 220.0) {
self.targetBus = targetBus
self.toneFreq = freq
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq) * ampNode)
}
}
/// Posts a `TriggerEvent` at an exact sample-accurate time within a single NRT render, so a
/// test can flip a looper transport action mid-render.
private final class TimedTrigger: SynthesizerBase {
private let fireTime: Double
private let triggerID: Int32
private static let minRampDuration: Double = 0.001
init(fireTime: Double, id: Int32) {
self.fireTime = fireTime
self.triggerID = id
super.init()
}
override func build() {
let rampDuration: Double = max(fireTime, TimedTrigger.minRampDuration) * 2.0
let ramp: Line.Control = Line.Control(start: -1.0, end: 1.0, dur: rampDuration)
_ = SendTrigger.Control(trig: ramp, id: triggerID)
}
}
private func rms(_ samples: [Float]) -> Double {
guard !samples.isEmpty else { return 0 }
let sumSquares: Double = samples.reduce(0) { $0 + Double($1) * Double($1) }
return (sumSquares / Double(samples.count)).squareRoot()
}
/// Builds a fresh engine + `ToneSource` + `LooperPedal` + master, lets the caller register
/// exact-time actions, then renders and returns the stereo samples. No clock is injected, so
/// the looper transport is immediate (un-quantized).
private func render(
totalDuration: Double,
toneAmplitude: Double = 0.3,
sampleRate: Double = 44100.0,
configure: (
_ engine: SynthesisEngine,
_ source: ToneSource,
_ pedal: LooperPedal,
_ scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void
) throws -> Void
) throws -> [Float] {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".caf")
defer { try? FileManager.default.removeItem(at: url) }
let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 64,
numControlBuses: 512,
driver: driver
)
let listener: TriggerListener = TriggerListener(engine: engine)
driver.triggerListener = listener
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: ToneSource = ToneSource(targetBus: srcBus.index)
source.amplitude = toneAmplitude
let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
var nextTriggerID: Int32 = 0
let scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void = { time, action in
nextTriggerID += 1
let id: Int32 = nextTriggerID
let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id)
try engine.add(trigger)
listener.addHandler(id: id) { _, _ in
MainActor.assumeIsolated { action() }
}
}
try configure(engine, source, pedal, scheduleAction)
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
/// Builds an engine with the pedal added (so `effect()` allocates buffers + recorders) but
/// does NOT start it, so beat-quantized callbacks can be driven deterministically. The caller
/// keeps the returned (weak-referenced) engine + clock alive.
private func makeQuantizedFixture(bpm: Double, sampleRate: Double)
throws -> (engine: SynthesisEngine, clock: LyrebirdClock, pedal: LooperPedal) {
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".caf")
let driver: NRTDriver = NRTDriver(outputURL: url, duration: 0.1)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: 512,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: 64,
numControlBuses: 512,
driver: driver
)
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let source: ToneSource = ToneSource(targetBus: srcBus.index)
let pedal: LooperPedal = LooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: bpm)
pedal.clock = clock
pedal.hostEngine = engine
pedal.sampleRate = sampleRate
return (engine, clock, pedal)
}
// MARK: - Controls
@Test func exposesLooperControls() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Crossfade", "Playback", "Overdub", "Feedback"])
#expect(pedal.effectSwitches.map { $0.label } == ["Sync to Tempo"])
#expect(pedal.effectButtons.isEmpty)
#expect(pedal.effectTransportButtons.map { $0.label } == ["Loop", "Stop", "Cue Stop", "Reverse", "Reset"])
}
@Test func looperIsTripleWidth() throws {
#expect(LooperPedal().widthUnits == 3)
#expect(LooperPedal.trackCount == 4)
}
@Test func rebuildDoesNotDoubleTrackGenerators() throws {
// effect() runs from build(), which the engine re-invokes on every add — including the
// re-adds a board edit performs on the same instance. It must be idempotent (not append
// to the per-track arrays each time), or the looper's generators/state desync.
let pedal: LooperPedal = LooperPedal()
pedal.sampleRate = 44100.0
let dry: any ValidGeneratorInput = OscSin.Audio(freq: 100.0)
_ = pedal.effect(dry)
_ = pedal.effect(dry) // simulate a second build()
let counts: (buffers: Int, players: Int, overdub: Int, gates: Int) = pedal.trackGeneratorCountsForTesting
#expect(counts.buffers == LooperPedal.trackCount)
#expect(counts.players == LooperPedal.trackCount)
#expect(counts.overdub == LooperPedal.trackCount)
#expect(counts.gates == LooperPedal.trackCount)
#expect(pedal.transportState == .clear)
}
@Test func looperHidesMixControl() throws {
// The looper always passes the clean signal through and adds the loop on top, so the
// wet/dry Mix knob is hidden; a plain pedal keeps it.
#expect(LooperPedal().showsMixControl == false)
}
@Test func cleanSignalPassesThroughWhilePlaying() throws {
// With the loop muted (loopOn = 0) but a loop recorded and a live tone present, the
// output must still carry the clean signal at full level — it is never gated by the loop.
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.5) { _, _, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() } // play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub
try scheduleAction(0.2) { pedal.loopOn = 0.0 } // mute the loop, keep live tone
}
let tailStart: Int = Int(Double(samples.count) * 0.9)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Clean signal must pass through even with the loop muted")
}
// MARK: - Audio behaviour (immediate / un-quantized)
@Test func clearStatePassesDryThrough() throws {
let samples: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
#expect(hasNonSilentOutput(samples), "Cleared looper should pass the dry signal through")
}
@Test func recordCloseThenPlaysAfterInputSilenced() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.7) { _, source, pedal, scheduleAction in
pedal.pressLoop() // record track A
try scheduleAction(recordDuration) { pedal.pressLoop() } // set end → play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub, keep playing
try scheduleAction(recordDuration + 0.02) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.8)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Recorded loop should keep playing after the input is silenced")
}
@Test func resetReturnsToClearAndSilence() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.5) { _, source, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(0.2) { pedal.resetLoop() }
try scheduleAction(0.2) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
let tail: [Float] = Array(samples[tailStart...])
#expect(!hasNonSilentOutput(tail), "After reset + silenced input, no loop content should remain")
}
@Test func playbackLevelAttenuatesLoop() throws {
let recordDuration: Double = 0.1
func renderLoop(playbackLevelDb: Double) throws -> [Float] {
try render(totalDuration: 0.5) { _, source, pedal, scheduleAction in
pedal.playbackLevel = playbackLevelDb
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { source.amplitude = 0.0 }
}
}
let unityRMS: Double = rms(try renderLoop(playbackLevelDb: 0.0))
let attenuatedRMS: Double = rms(try renderLoop(playbackLevelDb: -6.0))
#expect(attenuatedRMS < unityRMS, "-6 dB playback level should be quieter than 0 dB")
}
@Test func reverseKeepsLoopAudible() throws {
let recordDuration: Double = 0.1
let samples: [Float] = try render(totalDuration: 0.6) { _, source, pedal, scheduleAction in
pedal.pressLoop()
try scheduleAction(recordDuration) { pedal.pressLoop() }
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() }
try scheduleAction(0.25) { pedal.reverse = 1.0 }
try scheduleAction(0.25) { source.amplitude = 0.0 }
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
let tail: [Float] = Array(samples[tailStart...])
#expect(hasNonSilentOutput(tail), "Reverse playback should keep the loop audible")
}
@Test func overdubbingTrackAAddsEnergyToTheLoop() throws {
let recordDuration: Double = 0.1
let overdubStart: Double = 0.25
let overdubEnd: Double = 0.35
// Record silence into A, then overdub a tone onto A; the baked-in loop should be audible.
func renderWithOverdub(_ overdub: Bool) throws -> Double {
let samples: [Float] = try render(totalDuration: 0.7, toneAmplitude: 0.0) { _, source, pedal, scheduleAction in
pedal.pressLoop() // record A (silent)
try scheduleAction(recordDuration) { pedal.pressLoop() } // set end → play + overdub A
try scheduleAction(recordDuration + 0.02) { pedal.pressLoop() } // end overdub, just play
if overdub {
try scheduleAction(overdubStart) { source.amplitude = 0.3 } // feed a tone
try scheduleAction(overdubStart) { pedal.pressLoop() } // overdub A on
try scheduleAction(overdubEnd) { pedal.pressLoop() } // overdub A off
}
try scheduleAction(overdubEnd) { source.amplitude = 0.0 } // silence input
}
let tailStart: Int = Int(Double(samples.count) * 0.85)
return rms(Array(samples[tailStart...]))
}
let withoutOverdub: Double = try renderWithOverdub(false)
let withOverdub: Double = try renderWithOverdub(true)
#expect(withOverdub > withoutOverdub,
"Overdubbing a tone onto silent track A should bake audible content into the loop")
}
// MARK: - State machine (headless)
@Test func statesProgressFromClearToPlaying() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil // immediate transport
#expect(pedal.transportState == .clear)
#expect(pedal.loopButtonCaption == "Record")
pedal.pressLoop() // → recording A
#expect(pedal.transportState == .recordingMaster)
#expect(pedal.loopButtonCaption == "Set End")
pedal.pressLoop() // → playing + overdubbing A
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
#expect(pedal.loopButtonCaption == "Play") // next press ends overdub
pedal.pressLoop() // → playing, overdub off
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(pedal.trackHasContent(0))
#expect(pedal.loopButtonCaption == "Overdub") // A has content, next press overdubs
} }
}
@Test func masterLengthQuantizesToWholeBeats() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate) // 22 050 frames / beat
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.pressLoop() // arm record (routine won't fire; engine idle)
pedal.beginMasterRecording(at: SampleTime(sampleRate * 0.5))
#expect(pedal.transportState == .recordingMaster)
pedal.pressLoop() // arm close
pedal.closeMasterAndPlay(at: SampleTime(sampleRate * 2.5)) // 2.0 s = 4 beats
#expect(pedal.transportState == .playing)
#expect(pedal.loopFrameCount == Int(sampleRate * 2.0))
#expect(pedal.loopLengthBeats == 4.0)
pedal.resetLoop()
#expect(pedal.transportState == .clear)
#expect(pedal.loopFrameCount == 0)
} }
}
@Test func onlyTrackASelectableWhileClear() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
#expect(pedal.selectedTrackIndex == 0)
pedal.selectTrack(2) // ignored while clear
#expect(pedal.selectedTrackIndex == 0)
} }
}
@Test func selectingTrackWhilePlayingEndsOverdubAndSwitches() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
#expect(pedal.overdubbingTrackIndex == 0)
pedal.selectTrack(1) // select B — ends A's overdub
#expect(pedal.selectedTrackIndex == 1)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(!pedal.trackHasContent(1))
#expect(pedal.loopButtonCaption == "Record") // empty B, next press records it
pedal.pressLoop() // overdub (record) B
#expect(pedal.overdubbingTrackIndex == 1)
#expect(pedal.trackHasContent(1))
} }
}
@Test func overdubBlockedWhileReversed() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
pedal.pressLoop() // end overdub, just playing
#expect(pedal.overdubbingTrackIndex == nil)
pedal.reverse = 1.0 // engage reverse
pedal.pressLoop() // must NOT start overdub while reversed
#expect(pedal.overdubbingTrackIndex == nil, "overdub can't be engaged while reversed")
pedal.reverse = 0.0 // forward again
pedal.pressLoop() // now overdub engages
#expect(pedal.overdubbingTrackIndex == 0)
} }
}
@Test func engagingReverseWhileOverdubbingEndsOverdub() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // play + overdub A
#expect(pedal.overdubbingTrackIndex == 0)
pedal.toggleReverse() // engage reverse mid-overdub
#expect(pedal.reverse == 1.0)
#expect(pedal.overdubbingTrackIndex == nil, "engaging reverse must end the overdub")
pedal.toggleReverse() // back to forward — overdub stays off
#expect(pedal.reverse == 0.0)
#expect(pedal.overdubbingTrackIndex == nil)
} }
}
@Test func reverseDoesNotJumpPlayHeadPosition() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Record a 1-second master (record start at 0, close at 44100) → masterLength = 44100.
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(0))
let closeSample: SampleTime = SampleTime(sampleRate)
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: closeSample)
#expect(pedal.transportState == .playing)
// A quarter of the way in, moving forward.
let quarter: SampleTime = closeSample + SampleTime(sampleRate * 0.25)
#expect(abs(pedal.playHeadFraction(at: quarter) - 0.25) < 0.001)
// Reversing here must NOT jump the read-out to the mirror point (0.75) — it stays at 0.25.
pedal.applyReverse(at: quarter)
#expect(abs(pedal.playHeadFraction(at: quarter) - 0.25) < 0.001,
"reverse must continue from the current position, not jump to duration − position")
// Advancing time now walks the position backward from 0.25.
let laterBy: SampleTime = SampleTime(sampleRate * 0.10)
#expect(abs(pedal.playHeadFraction(at: quarter + laterBy) - 0.15) < 0.001,
"reversed play head moves backward from the reverse point")
} }
}
@Test func reverseDefersToNextBeatInSyncMode() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(0))
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate))
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
// Sync mode (default): the press is deferred — direction and overdub are untouched.
pedal.toggleReverse()
#expect(pedal.reverse == 0.0, "sync-mode reverse waits for the next beat")
#expect(pedal.overdubbingTrackIndex == 0, "overdub survives until the deferred reverse fires")
// The beat arrives: direction flips and the overdub ends.
pedal.applyDeferredReverse(generation: pedal.reverseGeneration, at: SampleTime(sampleRate * 2))
#expect(pedal.reverse == 1.0)
#expect(pedal.overdubbingTrackIndex == nil, "engaging reverse ends the overdub")
} }
}
@Test func reverseIsImmediateInFreeMode() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.syncToBeat = 0.0
pedal.pressLoop() // record A (immediate)
pedal.pressLoop() // play + overdub A (immediate)
#expect(pedal.transportState == .playing)
// Free mode: reverse applies right away, even with a clock present.
pedal.toggleReverse()
#expect(pedal.reverse == 1.0, "free-mode reverse is immediate")
#expect(pedal.overdubbingTrackIndex == nil, "engaging reverse ends the overdub")
} }
}
@Test func engineStopResetsLooperAndPostsNotice() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing
#expect(pedal.transportState == .playing)
pedal.engineDidStop()
#expect(pedal.transportState == .clear, "engine stop returns the looper to clear")
#expect(pedal.loopFrameCount == 0)
#expect(pedal.stateDescription == "Looper reset — engine stopped.",
"a transient notice is shown after the engine-stop reset")
// A no-op when already clear (no spurious notice).
let clearPedal: LooperPedal = LooperPedal()
clearPedal.engineDidStop()
#expect(clearPedal.transportState == .clear)
} }
}
@Test func rigTeardownResetsLooper() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop()
pedal.pressLoop() // playing
pedal.rigWillTeardown()
#expect(pedal.transportState == .clear, "a rig teardown returns the looper to clear")
#expect(pedal.stateDescription == "Looper reset — rig changed.")
} }
}
@Test func recordsAgainAfterReset() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing + overdub A
pedal.toggleReverse() // leave reverse engaged before reset
#expect(pedal.reverse == 1.0)
pedal.resetLoop()
#expect(pedal.transportState == .clear)
#expect(pedal.overdubbingTrackIndex == nil)
#expect(pedal.reverse == 0.0, "reset returns to forward playback")
// Second take must behave exactly like the first — including auto-overdub on A,
// which was silently blocked when reset didn't clear a left-on reverse.
pedal.pressLoop()
#expect(pedal.transportState == .recordingMaster, "record after reset should re-enter recording")
#expect(pedal.loopButtonCaption == "Set End")
pedal.pressLoop()
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0, "auto-overdub on A must engage after a reset")
#expect(pedal.trackHasContent(0))
} }
}
@Test func quantizedRecordsAgainAfterReset() throws {
let sampleRate: Double = 44100.0
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: sampleRate)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Mimic the real (beat-quantized) app path: pressLoop arms + starts a routine that
// fires applyQuantizedTransport with the generation captured at arm time.
// Session 1
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 0.5))
#expect(pedal.transportState == .recordingMaster)
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 2.5))
#expect(pedal.transportState == .playing)
// Reset, then session 2 — the quantized callbacks must still land.
pedal.resetLoop()
#expect(pedal.transportState == .clear)
pedal.pressLoop()
pedal.applyQuantizedTransport(.beginMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 4.5))
#expect(pedal.transportState == .recordingMaster, "quantized record after reset must reach recording")
pedal.pressLoop()
pedal.applyQuantizedTransport(.closeMaster, generation: pedal.transportGeneration, at: SampleTime(sampleRate * 6.5))
#expect(pedal.transportState == .playing)
#expect(pedal.overdubbingTrackIndex == 0)
} }
}
@Test func freeformModeRecordsImmediatelyDespiteClock() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
// Sync off: even with a clock present, transport is immediate — no armed/waiting state.
pedal.syncToBeat = 0.0
pedal.pressLoop()
#expect(pedal.transportState == .recordingMaster, "freeform record starts immediately")
pedal.pressLoop()
#expect(pedal.transportState == .playing)
#expect(pedal.loopLengthBeats == 0.0, "freeform loops aren't beat-measured")
// Flip to Sync: the next take arms for the beat instead.
pedal.resetLoop()
pedal.syncToBeat = 1.0
pedal.pressLoop()
#expect(pedal.transportState == .armedRecord, "sync record arms for the next beat")
} }
}
@Test func tapTrackSelectsThenMutesRecordedTrack() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop() // record A
pedal.pressLoop() // playing, A selected + has content
pedal.pressLoop() // end auto-overdub, just playing
#expect(pedal.selectedTrackIndex == 0)
#expect(pedal.trackHasContent(0))
#expect(!pedal.isTrackMuted(0))
// Second tap on the selected, recorded track A mutes it; third un-mutes.
pedal.tapTrack(0)
#expect(pedal.isTrackMuted(0), "tapping the selected recorded track mutes it")
pedal.tapTrack(0)
#expect(!pedal.isTrackMuted(0), "tapping again un-mutes it")
// Tapping a different track selects it (doesn't mute), leaving A audible.
pedal.tapTrack(1)
#expect(pedal.selectedTrackIndex == 1)
#expect(!pedal.isTrackMuted(0))
#expect(!pedal.isTrackMuted(1))
pedal.resetLoop()
#expect(!pedal.isTrackMuted(0), "reset un-mutes all tracks")
} }
}
@Test func cycleSyncModeOscillatesThroughOptions() throws {
let pedal: LooperPedal = LooperPedal()
#expect(pedal.syncToBeat == 1.0) // Sync by default
pedal.cycleSyncMode()
#expect(pedal.syncToBeat == 0.0, "cycle → Free")
pedal.cycleSyncMode()
#expect(pedal.syncToBeat == 1.0, "cycle wraps back → Sync")
}
@Test func stopResumeAndCueStop() throws {
let (engine, clock, pedal): (SynthesisEngine, LyrebirdClock, LooperPedal) =
try makeQuantizedFixture(bpm: 120.0, sampleRate: 44100.0)
withExtendedLifetime(engine) { withExtendedLifetime(clock) {
pedal.clock = nil
pedal.pressLoop()
pedal.pressLoop() // playing
#expect(pedal.transportState == .playing)
pedal.stopPlayback()
#expect(pedal.transportState == .stopped)
#expect(pedal.isPlaying == 0.0)
#expect(pedal.loopButtonCaption == "Play")
pedal.pressLoop() // resume
#expect(pedal.transportState == .playing)
#expect(pedal.isPlaying == 1.0)
// Cue Stop arms while playing (routine waits; engine idle so it never fires here).
#expect(!pedal.isStopAtLoopEndArmed)
pedal.toggleStopAtLoopEnd()
#expect(pedal.isStopAtLoopEndArmed)
pedal.toggleStopAtLoopEnd()
#expect(!pedal.isStopAtLoopEndArmed)
} }
}
}
@@ -27,28 +27,28 @@ struct MIDIControllerCCTests {
return (controller, sg, board, url)
}
/// An address-only pedal-control CC target (hints filled at capture time).
private func pedalControl(_ board: Int, _ pedal: Int, _ control: Int) -> MIDIMap.CCTarget {
.pedalControl(boardIndex: board, pedalIndex: pedal, controlIndex: control,
/// An address-only pedal-control CC target by pedal id (hints filled at capture time).
private func pedalControl(_ pedalID: UUID, _ control: Int) -> MIDIMap.CCTarget {
.pedalControl(pedalID: pedalID, controlIndex: control,
pedalNameHint: nil, controlLabelHint: nil)
}
@Test func learnCapturesBindingAndFiresCallback() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
var mapChanged: Bool = false
controller.onMapChanged = { mapChanged = true }
// Position is control 0 on a Volume pedal.
controller.armCCLearn(pedalControl(0, 0, 0))
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 64))
#expect(controller.learnTarget == nil, "learn should clear after capture")
#expect(mapChanged, "onMapChanged should fire on capture")
let binding: MIDIMap.CCBinding? = controller.ccBinding(for: pedalControl(0, 0, 0))
let binding: MIDIMap.CCBinding? = controller.ccBinding(for: pedalControl(board.pedals[0].id, 0))
#expect(binding?.controller == 20)
if case .pedalControl(_, _, _, let nameHint, let labelHint)? = binding?.target {
if case .pedalControl(_, _, let nameHint, let labelHint)? = binding?.target {
#expect(nameHint == "Volume")
#expect(labelHint == "Position")
} else {
@@ -64,7 +64,7 @@ struct MIDIControllerCCTests {
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armCCLearn(pedalControl(0, 0, 0))
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node // Position, 0...1
@@ -86,7 +86,7 @@ struct MIDIControllerCCTests {
Issue.record("board should have a master-gain node after finalize")
return
}
let target: MIDIMap.CCTarget = .boardLevel(boardIndex: 0, boardLabelHint: nil)
let target: MIDIMap.CCTarget = .boardLevel(boardID: board.id, boardLabelHint: nil)
controller.armCCLearn(target)
controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 0)) // learn
controller.ingestForTesting(.controlChange(channel: 0, controller: 11, value: 127))
@@ -113,7 +113,7 @@ struct MIDIControllerCCTests {
let sliderIndex: Int = pedal.knobs.count // first control past the knobs is a slider
let control: PedalControl = pedal.ccMappableControls[sliderIndex]
controller.armCCLearn(pedalControl(0, 0, sliderIndex))
controller.armCCLearn(pedalControl(pedal.id, sliderIndex))
controller.ingestForTesting(.controlChange(channel: 0, controller: 30, value: 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 30, value: 127))
#expect(abs(control.node.value - control.range.upperBound) < 1e-9,
@@ -126,10 +126,10 @@ struct MIDIControllerCCTests {
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armCCLearn(pedalControl(0, 0, 0))
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.setCCInverted(for: pedalControl(0, 0, 0), true)
#expect(controller.isCCInverted(for: pedalControl(0, 0, 0)))
controller.setCCInverted(for: pedalControl(board.pedals[0].id, 0), true)
#expect(controller.isCCInverted(for: pedalControl(board.pedals[0].id, 0)))
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 127))
@@ -147,15 +147,15 @@ struct MIDIControllerCCTests {
withExtendedLifetime(sg) {
// Control 0 = Position, control 1 = Mix on a Volume pedal.
controller.armCCLearn(pedalControl(0, 0, 0))
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.armCCLearn(pedalControl(0, 0, 1))
controller.armCCLearn(pedalControl(board.pedals[0].id, 1))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
controller.setCCInverted(for: pedalControl(0, 0, 1), true)
controller.setCCInverted(for: pedalControl(board.pedals[0].id, 1), true)
// Both bindings survive — the same CC drives both controls.
#expect(sg.midiMap?.ccs.count == 2, "assigning a 2nd control must not steal the 1st")
#expect(controller.ccBinding(for: pedalControl(0, 0, 0)) != nil)
#expect(controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) != nil)
let position: UIParamNode = board.pedals[0].ccMappableControls[0].node
let mix: UIParamNode = board.pedals[0].ccMappableControls[1].node
@@ -200,7 +200,7 @@ struct MIDIControllerCCTests {
withExtendedLifetime(sg) {
// Learn on channel 0 (the binding captures that channel).
controller.armCCLearn(pedalControl(0, 0, 0))
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
let node: UIParamNode = board.pedals[0].ccMappableControls[0].node
@@ -212,15 +212,15 @@ struct MIDIControllerCCTests {
}
@Test func clearRemovesBinding() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
controller.armCCLearn(pedalControl(0, 0, 0))
controller.armCCLearn(pedalControl(board.pedals[0].id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 20, value: 0))
#expect(sg.midiMap?.ccs.isEmpty == false)
controller.clearCCBinding(for: pedalControl(0, 0, 0))
#expect(controller.ccBinding(for: pedalControl(0, 0, 0)) == nil)
controller.clearCCBinding(for: pedalControl(board.pedals[0].id, 0))
#expect(controller.ccBinding(for: pedalControl(board.pedals[0].id, 0)) == nil)
#expect(sg.midiMap?.ccs.isEmpty == true)
}
}
@@ -86,7 +86,7 @@ struct MIDIControllerPCTests {
withExtendedLifetime(sg) {
let node: UIParamNode = boards[0].pedals[0].$bypass
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 0))
controller.armSwitchLearn(.pedalBypass(pedalID: boards[0].pedals[0].id))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
#expect(node.value == 0.0)
controller.ingestForTesting(.programChange(channel: 0, program: 5))
@@ -101,7 +101,7 @@ struct MIDIControllerPCTests {
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.boardBypass(boardIndex: 0))
controller.armSwitchLearn(.boardBypass(boardID: boards[0].id))
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 3))
#expect(sg.isBoardBypassed(boards[0]) == true)
@@ -116,7 +116,7 @@ struct MIDIControllerPCTests {
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.boardSolo(boardIndex: 1))
controller.armSwitchLearn(.boardSolo(boardID: boards[1].id))
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // solo board 2
#expect(sg.activeBoardIndex == 1)
@@ -162,11 +162,12 @@ struct MIDIControllerPCTests {
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Bind to a pedal index that doesn't exist; applying it must be a safe no-op.
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 9))
// Bind to a pedal id that doesn't exist in the rig; applying it must be a safe no-op.
let ghostID: UUID = UUID()
controller.armSwitchLearn(.pedalBypass(pedalID: ghostID))
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // learn
controller.ingestForTesting(.programChange(channel: 0, program: 6)) // apply — no crash
#expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 9)) != nil)
#expect(controller.switchBinding(for: .pedalBypass(pedalID: ghostID)) != nil)
}
}
@@ -179,12 +180,12 @@ struct MIDIControllerPCTests {
withExtendedLifetime(sg) {
controller.armSwitchLearn(.rigBypass)
controller.ingestForTesting(.programChange(channel: 0, program: 8))
controller.armSwitchLearn(.pedalBypass(boardIndex: 0, pedalIndex: 0))
controller.armSwitchLearn(.pedalBypass(pedalID: boards[0].pedals[0].id))
controller.ingestForTesting(.programChange(channel: 0, program: 8)) // same PC, kept
// Both bindings survive — one PC drives two actions.
#expect(controller.switchBinding(for: .rigBypass)?.program == 8)
#expect(controller.switchBinding(for: .pedalBypass(boardIndex: 0, pedalIndex: 0))?.program == 8)
#expect(controller.switchBinding(for: .pedalBypass(pedalID: boards[0].pedals[0].id))?.program == 8)
#expect(sg.midiMap?.switches.count == 2)
// Firing the PC toggles both at once.
@@ -209,4 +210,127 @@ struct MIDIControllerPCTests {
#expect(sg.midiMap?.switches.count == 1)
}
}
@Test func tunerToggleFlipsEngagedState() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.tunerToggle)
controller.ingestForTesting(.programChange(channel: 0, program: 10)) // learn only
#expect(!sg.tunerEngaged)
controller.ingestForTesting(.programChange(channel: 0, program: 10))
#expect(sg.tunerEngaged, "first press engages")
controller.ingestForTesting(.programChange(channel: 0, program: 10))
#expect(!sg.tunerEngaged, "second press disengages")
}
}
@Test func tapTempoRegistersEachPress() throws {
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.tapTempo)
controller.ingestForTesting(.programChange(channel: 0, program: 11)) // learn only
#expect(sg.tapTimestamps.isEmpty)
controller.ingestForTesting(.programChange(channel: 0, program: 11))
#expect(sg.tapTimestamps.count == 1, "first press registers a tap")
controller.ingestForTesting(.programChange(channel: 0, program: 11))
#expect(sg.tapTimestamps.count == 2, "second press registers a second tap")
}
}
@Test func pedalActionDispatchesLooperRecordStop() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let looper: LooperPedal = LooperPedal()
try board.add(looper)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperRecordStop))
controller.ingestForTesting(.programChange(channel: 0, program: 12)) // learn only
#expect(looper.transportState == .clear)
// The looper was added via the board, so it carries the shared tempo clock and its
// transport is beat-quantized: the mapped press arms recording for the next beat.
// Asserting the arm proves the Program Change dispatched to the pedal's action.
controller.ingestForTesting(.programChange(channel: 0, program: 12))
#expect(looper.transportState == .armedRecord,
"mapped Program Change should dispatch the looper record/stop action")
}
}
@Test func pedalActionDispatchesLooperReverse() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let looper: LooperPedal = LooperPedal()
try board.add(looper)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperReverse))
controller.ingestForTesting(.programChange(channel: 0, program: 20)) // learn only
#expect(looper.reverse == 0.0)
controller.ingestForTesting(.programChange(channel: 0, program: 20)) // fire → toggleReverse
#expect(looper.reverse == 1.0, "mapped Program Change should flip the looper's reverse")
}
}
@Test func pedalActionCyclesLooperSync() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let looper: LooperPedal = LooperPedal()
try board.add(looper)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperSyncToggle))
controller.ingestForTesting(.programChange(channel: 0, program: 21)) // learn only
#expect(looper.syncToBeat == 1.0)
controller.ingestForTesting(.programChange(channel: 0, program: 21)) // fire → cycle
#expect(looper.syncToBeat == 0.0, "mapped Program Change should oscillate Sync through its options")
}
}
@Test func pedalActionTapsLooperTrack() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let looper: LooperPedal = LooperPedal()
try board.add(looper)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Get a recorded, selected track A (immediate transport).
looper.clock = nil
looper.pressLoop()
looper.pressLoop()
#expect(looper.trackHasContent(0))
#expect(!looper.isTrackMuted(0))
controller.armSwitchLearn(.pedalAction(pedalID: looper.id, kind: .looperTrack(index: 0)))
controller.ingestForTesting(.programChange(channel: 0, program: 22)) // learn only
#expect(!looper.isTrackMuted(0))
controller.ingestForTesting(.programChange(channel: 0, program: 22)) // fire → tapTrack(0) → mute A
#expect(looper.isTrackMuted(0), "mapped Program Change should tap (mute) the selected recorded track")
}
}
}
@@ -12,25 +12,37 @@ import Foundation
@Suite("MIDIMap persistence")
struct MIDIMapCodableTests {
// Fixed ids so the round-trip comparison is deterministic.
private static let boardID: UUID = UUID()
private static let looperID: UUID = UUID()
private static let volumeID: UUID = UUID()
private func sampleMap() -> MIDIMap {
MIDIMap(
switches: [
MIDIMap.SwitchBinding(program: 3, channel: 0, action: .rigBypass, displayNameHint: "Rig"),
MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardIndex: 1), displayNameHint: "Board 2"),
MIDIMap.SwitchBinding(program: 4, action: .boardSolo(boardID: Self.boardID), displayNameHint: "Board 2"),
MIDIMap.SwitchBinding(program: 5, action: .tunerToggle),
MIDIMap.SwitchBinding(program: 6, action: .tapTempo),
MIDIMap.SwitchBinding(
program: 7,
action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop),
displayNameHint: "Looper"
),
],
ccs: [
MIDIMap.CCBinding(
controller: 7,
channel: 0,
target: .pedalControl(
boardIndex: 0, pedalIndex: 1, controlIndex: 0,
pedalID: Self.volumeID, controlIndex: 0,
pedalNameHint: "Volume", controlLabelHint: "Position"
)
),
MIDIMap.CCBinding(
controller: 11,
channel: 0,
target: .boardLevel(boardIndex: 0, boardLabelHint: "Board 1")
target: .boardLevel(boardID: Self.boardID, boardLabelHint: "Board 1")
),
]
)
@@ -0,0 +1,108 @@
// MIDIMapMigrationTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Legacy MIDI map migration")
struct MIDIMapMigrationTests {
/// Two boards; board 0 has two pedals, board 1 has one — with fixed ids to assert against.
private func sampleBoards() -> [BoardState] {
let od: PedalState = PedalState(type: "Overdrive", knobValues: [], bypass: 0)
let rv: PedalState = PedalState(type: "Reverb", knobValues: [], bypass: 0)
let dl: PedalState = PedalState(type: "Delay", knobValues: [], bypass: 0)
return [
BoardState(label: "Board 1", pedals: [od, rv]),
BoardState(label: "Board 2", pedals: [dl]),
]
}
// MARK: - Unit: positional → id conversion
@Test func migratesPositionalBindingsToIds() {
let boards: [BoardState] = sampleBoards()
let legacy: LegacyMIDIMap = LegacyMIDIMap(
switches: [
LegacyMIDIMap.LegacySwitchBinding(program: 1, channel: nil, action: .rigBypass, displayNameHint: nil),
LegacyMIDIMap.LegacySwitchBinding(program: 2, channel: nil, action: .boardBypass(boardIndex: 1), displayNameHint: "Board 2"),
LegacyMIDIMap.LegacySwitchBinding(program: 3, channel: nil, action: .pedalBypass(boardIndex: 0, pedalIndex: 1), displayNameHint: "Reverb"),
],
ccs: [
LegacyMIDIMap.LegacyCCBinding(controller: 7, channel: nil,
target: .pedalControl(boardIndex: 0, pedalIndex: 0, controlIndex: 2, pedalNameHint: "Overdrive", controlLabelHint: "Level"),
inverted: false),
LegacyMIDIMap.LegacyCCBinding(controller: 11, channel: nil,
target: .boardLevel(boardIndex: 1, boardLabelHint: "Board 2"), inverted: false),
]
)
let migrated: MIDIMap = legacy.migrated(boards: boards)
#expect(migrated.switches[0].action == .rigBypass)
#expect(migrated.switches[1].action == .boardBypass(boardID: boards[1].id))
#expect(migrated.switches[2].action == .pedalBypass(pedalID: boards[0].pedals[1].id))
#expect(migrated.ccs[0].target == .pedalControl(
pedalID: boards[0].pedals[0].id, controlIndex: 2,
pedalNameHint: "Overdrive", controlLabelHint: "Level"))
#expect(migrated.ccs[1].target == .boardLevel(boardID: boards[1].id, boardLabelHint: "Board 2"))
}
@Test func dropsOutOfRangeBindings() {
let boards: [BoardState] = sampleBoards()
let legacy: LegacyMIDIMap = LegacyMIDIMap(
switches: [
LegacyMIDIMap.LegacySwitchBinding(program: 1, channel: nil, action: .pedalBypass(boardIndex: 0, pedalIndex: 9), displayNameHint: nil),
LegacyMIDIMap.LegacySwitchBinding(program: 2, channel: nil, action: .boardSolo(boardIndex: 5), displayNameHint: nil),
],
ccs: []
)
let migrated: MIDIMap = legacy.migrated(boards: boards)
#expect(migrated.switches.isEmpty, "bindings addressing a non-existent board/pedal are dropped")
}
// MARK: - Integration: legacy JSON decodes through ShoeGazeState
@Test func legacyFormatJSONDecodesAndMigrates() throws {
let boards: [BoardState] = sampleBoards()
let legacy: LegacyMIDIMap = LegacyMIDIMap(
switches: [
LegacyMIDIMap.LegacySwitchBinding(program: 3, channel: 0, action: .pedalBypass(boardIndex: 0, pedalIndex: 1), displayNameHint: "Reverb"),
],
ccs: []
)
// Build the raw rig JSON with the *legacy* midiMap encoding spliced in — exactly what an
// old saved rig on disk looks like (boards may or may not carry ids; midiMap is positional).
var dict: [String: Any] = [
"version": presetFormatVersion,
"boards": try jsonObject(boards),
"midiMap": try jsonObject(legacy),
]
// Sanity: the spliced midiMap is the positional shape, not the id shape.
#expect(((dict["midiMap"] as? [String: Any])?["switches"] as? [Any])?.isEmpty == false)
let data: Data = try JSONSerialization.data(withJSONObject: dict)
let state: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
let map: MIDIMap = try #require(state.midiMap, "legacy midiMap should migrate, not drop to nil")
#expect(map.switches.count == 1)
// The board ids in `state.boards` are what migration used — assert the binding points at
// the Reverb (board 0, pedal 1) by that board's decoded pedal id.
#expect(map.switches[0].action == .pedalBypass(pedalID: state.boards[0].pedals[1].id))
_ = dict.removeValue(forKey: "midiMap")
}
/// Encodes a `Codable` value and re-reads it as a JSON object for splicing.
private func jsonObject<T: Encodable>(_ value: T) throws -> Any {
let data: Data = try JSONEncoder().encode(value)
return try JSONSerialization.jsonObject(with: data)
}
}
@@ -0,0 +1,148 @@
// MIDIMapReindexTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// MIDI bindings address pedals/boards by stable UUID, so they follow their target through
/// structural edits with no reindexing. These tests assert the identity round-trips through the
/// edit API's capture → rebuild, and that a binding resolves to (and only to) its pedal.
@MainActor
@Suite("MIDIMap identity")
struct MIDIMapReindexTests {
private func makeRig(_ pedals: [String]) throws -> (ShoeGaze, MIDIController, URL, PedalBoard) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
for type: String in pedals {
if let pedal: Pedal = PedalRegistry.makePedal(type: type) { try board.add(pedal) }
}
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
return (sg, controller, url, board)
}
// MARK: - Identity preservation across edits
@Test func pedalKeepsIdThroughInsertAndMove() throws {
let (sg, _, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Overdrive", "Delay", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
let reverbID: UUID = board.pedals[2].id
// Insert a Fuzz at the front → Reverb slides to index 3 but keeps its id.
let afterInsert: PedalBoard = try sg.insertPedal(.fuzz, at: 0, to: board)
#expect(afterInsert.pedals.count == 4)
#expect(afterInsert.pedals[3].id == reverbID, "Reverb keeps its id after an insert before it")
// Move it to the front → still the same id.
let afterMove: PedalBoard = try sg.movePedal(from: 3, to: 0, in: afterInsert)
#expect(afterMove.pedals[0].id == reverbID, "Reverb keeps its id after a move")
}
@Test func pedalIdSurvivesSaveLoadRoundTrip() throws {
let (sg, _, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Overdrive", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
let ids: [UUID] = board.pedals.map { $0.id }
// Full Codable round-trip (what save/load to disk does).
let data: Data = try JSONEncoder().encode(sg.captureState())
let state: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url2) }
let sg2: ShoeGaze = ShoeGaze(engine: engine2)
try sg2.loadRig(from: state)
#expect(sg2.boards.first?.pedals.map { $0.id } == ids, "pedal ids persist across save/load")
}
@Test func boardKeepsIdThroughReorder() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let b0: PedalBoard = try sg.addBoard(); try sg.finalizeBoard(b0)
let b1: PedalBoard = try sg.addBoard(); try sg.finalizeBoard(b1)
let id0: UUID = b0.id
let id1: UUID = b1.id
sg.moveBoard(b1, to: 0)
#expect(sg.boards[0].id == id1)
#expect(sg.boards[1].id == id0)
}
// MARK: - Binding follows the pedal (end-to-end via the controller)
@Test func bypassBindingFollowsPedalAfterInsert() throws {
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Overdrive", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// Map program 5 to the Reverb's bypass (pedal index 1).
let reverbID: UUID = board.pedals[1].id
controller.armSwitchLearn(.pedalBypass(pedalID: reverbID))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
// Insert a Fuzz at the front — Reverb moves to index 2, keeps its id.
let edited: PedalBoard = (try? sg.insertPedal(.fuzz, at: 0, to: board)) ?? board
let reverb: Pedal = edited.pedals.first { $0.id == reverbID }!
#expect(edited.pedals.firstIndex { $0.id == reverbID } == 2)
// Firing the binding must still toggle the Reverb (not whatever is at the old index).
#expect(reverb.$bypass.value == 0.0)
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(abs(reverb.$bypass.value - 1.0) < 1e-9, "binding follows the pedal, not the index")
}
}
@Test func bindingToRemovedPedalIsInert() throws {
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Overdrive", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
let overdriveID: UUID = board.pedals[0].id
controller.armSwitchLearn(.pedalBypass(pedalID: overdriveID))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
// Remove the mapped Overdrive. Firing the binding must not crash or touch the Reverb.
let edited: PedalBoard = (try? sg.removePedal(at: 0, from: board)) ?? board
let reverbBypassBefore: Double = edited.pedals[0].$bypass.value
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(edited.pedals[0].$bypass.value == reverbBypassBefore,
"a binding to a removed pedal is inert — it must not fall through to another pedal")
}
}
@Test func sameTypePedalsBindIndependently() throws {
// The case the positional model got wrong: two identical-type pedals, each with its own
// binding, resolve independently by id even after reordering.
let (sg, controller, url, board): (ShoeGaze, MIDIController, URL, PedalBoard) =
try makeRig(["Delay", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
let firstDelayID: UUID = board.pedals[0].id
controller.armSwitchLearn(.pedalBypass(pedalID: firstDelayID))
controller.ingestForTesting(.programChange(channel: 0, program: 5)) // learn
// Swap the two Delays.
let edited: PedalBoard = (try? sg.movePedal(from: 0, to: 1, in: board)) ?? board
let firstDelay: Pedal = edited.pedals.first { $0.id == firstDelayID }!
let otherDelay: Pedal = edited.pedals.first { $0.id != firstDelayID }!
controller.ingestForTesting(.programChange(channel: 0, program: 5))
#expect(abs(firstDelay.$bypass.value - 1.0) < 1e-9, "binding drives the originally-mapped Delay")
#expect(otherDelay.$bypass.value == 0.0, "the other same-type Delay is untouched")
}
}
}
@@ -14,9 +14,25 @@ import LyrebirdUI
@Suite("RigStore")
struct RigStoreTests {
/// Redirects `RigStore` to a unique temp file so the suite never touches — let alone
/// overwrites or deletes — the running app's real autosave in Application Support. Returns
/// the temp file URL (its parent directory is created).
private func isolateAutosave() throws -> URL {
let dir: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("RigStoreTests-" + UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let file: URL = dir.appendingPathComponent("autosave-rig.json")
RigStore.autosaveURLOverride = file
return file
}
@Test func savesAndRestoresAcrossInstances() throws {
let autosave: URL = try isolateAutosave()
defer {
RigStore.autosaveURLOverride = nil
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
}
RigStore.clear()
defer { RigStore.clear() }
// Build a rig and autosave it.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
@@ -42,7 +58,37 @@ struct RigStoreTests {
#expect(b.boards.last?.label == "Clean")
}
@Test func restorePreservesCurrentRigID() throws {
let autosave: URL = try isolateAutosave()
defer {
RigStore.autosaveURLOverride = nil
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
}
RigStore.clear()
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: urlA) }
let a: ShoeGaze = ShoeGaze(engine: engineA)
let board: PedalBoard = try a.addBoard()
try a.appendPedal(.overdrive, to: board)
try a.finalizeBoard(board)
let rigID: UUID = UUID()
a.currentRigID = rigID
#expect(RigStore.save(a))
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: urlB) }
let b: ShoeGaze = ShoeGaze(engine: engineB)
#expect(RigStore.restore(into: b))
#expect(b.currentRigID == rigID, "restore must carry the source-rig id so the UI highlights it")
}
@Test func restoreReturnsFalseWhenNoAutosave() throws {
let autosave: URL = try isolateAutosave()
defer {
RigStore.autosaveURLOverride = nil
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
}
RigStore.clear()
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
@@ -84,21 +84,30 @@ func readStereoCAF(url: URL, sampleRate: Double = 44100.0) -> [Float] {
&clientFormat
) == noErr else { return [] }
let readFrames: UInt32 = 4096
var samples: [Float] = [Float](repeating: 0, count: Int(readFrames) * 2)
var framesRead: UInt32 = readFrames
samples.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: 2,
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
mData: ptr.baseAddress
// Read the whole file in fixed-size chunks — a single `ExtAudioFileRead` call only
// fills one chunk's worth of frames, so anything past `chunkFrames` would otherwise be
// silently dropped for renders longer than one chunk.
let chunkFrames: UInt32 = 4096
var chunk: [Float] = [Float](repeating: 0, count: Int(chunkFrames) * 2)
var allSamples: [Float] = []
while true {
var framesRead: UInt32 = chunkFrames
chunk.withUnsafeMutableBufferPointer { ptr in
var bufList: AudioBufferList = AudioBufferList(
mNumberBuffers: 1,
mBuffers: AudioBuffer(
mNumberChannels: 2,
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
mData: ptr.baseAddress
)
)
)
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
_ = ExtAudioFileRead(fileRef, &framesRead, &bufList)
}
guard framesRead > 0 else { break }
allSamples.append(contentsOf: chunk.prefix(Int(framesRead) * 2))
if framesRead < chunkFrames { break }
}
return Array(samples.prefix(Int(framesRead) * 2))
return allSamples
}
// MARK: - Signal analysis
@@ -0,0 +1,55 @@
// TempoEnableTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Tempo enable")
struct TempoEnableTests {
private func makeRigWithLooper() throws -> (ShoeGaze, SynthesisEngine, URL, LooperPedal) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
guard let looper: LooperPedal = PedalRegistry.makePedal(type: "Looper") as? LooperPedal else {
fatalError("Looper pedal must be registered")
}
try board.add(looper)
try sg.finalizeBoard(board)
return (sg, engine, url, looper)
}
@Test func tempoEnabledDefaultsOn() throws {
let (sg, _, url, _): (ShoeGaze, SynthesisEngine, URL, LooperPedal) = try makeRigWithLooper()
defer { try? FileManager.default.removeItem(at: url) }
#expect(sg.tempoEnabled, "tempo indicator is on by default")
}
@Test func looperSyncSwitchIsTempoDependent() throws {
let (_, _, url, looper): (ShoeGaze, SynthesisEngine, URL, LooperPedal) = try makeRigWithLooper()
defer { try? FileManager.default.removeItem(at: url) }
let syncSwitch: PedalSwitch? = looper.effectSwitches.first { $0.tempoDependent }
#expect(syncSwitch != nil, "the looper Sync-to-Tempo switch must be marked tempo-dependent")
}
@Test func disablingTempoForcesSyncSwitchesOff() throws {
let (sg, _, url, looper): (ShoeGaze, SynthesisEngine, URL, LooperPedal) = try makeRigWithLooper()
defer { try? FileManager.default.removeItem(at: url) }
looper.syncToBeat = 1.0 // engage Sync
sg.setTempoEnabled(false)
#expect(!sg.tempoEnabled)
#expect(looper.syncToBeat == 0.0, "disabling tempo forces the looper back to Free")
// Re-enabling leaves it Free — the user re-selects Sync if wanted.
sg.setTempoEnabled(true)
#expect(sg.tempoEnabled)
#expect(looper.syncToBeat == 0.0)
}
}
@@ -0,0 +1,83 @@
// TempoTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdShoeGaze
@MainActor
@Suite("ShoeGaze Tempo")
struct TempoTests {
private func makeShoeGaze(duration: Double = 0.1) -> (ShoeGaze, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 64)
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
return (shoeGaze, url)
}
@Test func clockDefaultsToStandardTempo() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
#expect(shoeGaze.clock.bpm == ShoeGaze.defaultTempoBpm)
}
@Test func tapTempoAtOneSecondIntervalsSetsSixtyBpm() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
// Simulate taps exactly 1s apart by manipulating the tap history directly —
// real taps come from wall-clock `Date()`, so back-date synthetic timestamps
// instead of sleeping the test for real seconds.
let now: Date = Date()
shoeGaze.tapTimestamps = [
now.addingTimeInterval(-3.0),
now.addingTimeInterval(-2.0),
now.addingTimeInterval(-1.0),
]
shoeGaze.tapTempo() // landing "now", completing four 1s-spaced taps
#expect(abs(shoeGaze.clock.bpm - 60.0) < 0.5)
}
@Test func singleTapDoesNotSetTempo() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
let startingBpm: Double = shoeGaze.clock.bpm
shoeGaze.tapTempo()
#expect(shoeGaze.clock.bpm == startingBpm, "A single tap has no interval to measure — tempo must not change")
}
@Test func longPauseResetsTapHistory() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
let now: Date = Date()
// Two taps 1s apart, then a long pause before the next tap.
shoeGaze.tapTimestamps = [now.addingTimeInterval(-10.0), now.addingTimeInterval(-9.0)]
shoeGaze.tapTempo()
#expect(shoeGaze.tapTimestamps.count == 1, "A >2s gap should discard prior taps and start a fresh sequence")
}
@Test func tapTempoRespectsBpmRangeViaClockPrecondition() throws {
let (shoeGaze, url): (ShoeGaze, URL) = makeShoeGaze()
defer { try? FileManager.default.removeItem(at: url) }
let now: Date = Date()
// Very fast taps (well under minTapInterval == 0.2s) are filtered out of the average.
shoeGaze.tapTimestamps = [
now.addingTimeInterval(-0.15),
now.addingTimeInterval(-0.05),
]
let startingBpm: Double = shoeGaze.clock.bpm
shoeGaze.tapTempo()
// The sub-threshold interval is filtered; with no valid interval left the tempo
// is left unchanged rather than jumping to an implausible value.
#expect(shoeGaze.clock.bpm == startingBpm)
}
}
@@ -0,0 +1,52 @@
// TunerPitchReadingTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGazeUI
@Suite("TunerPitchReading")
struct TunerPitchReadingTests {
@Test func concertAIsA4WithZeroCents() {
let reading: TunerPitchReading = TunerPitchReading(hz: 440.0)
#expect(reading.noteName == "A4")
#expect(abs(reading.cents) < 0.5)
}
@Test func oneOctaveDownIsA3() {
let reading: TunerPitchReading = TunerPitchReading(hz: 220.0)
#expect(reading.noteName == "A3")
#expect(abs(reading.cents) < 0.5)
}
@Test func middleCIsC4() {
let reading: TunerPitchReading = TunerPitchReading(hz: 261.6256)
#expect(reading.noteName == "C4")
#expect(abs(reading.cents) < 1.0)
}
@Test func slightlySharpReportsPositiveCents() {
// ~20 cents sharp of A4.
let sharpHz: Double = 440.0 * pow(2.0, 20.0 / 1200.0)
let reading: TunerPitchReading = TunerPitchReading(hz: sharpHz)
#expect(reading.noteName == "A4")
#expect(reading.cents > 15.0 && reading.cents < 25.0)
}
@Test func slightlyFlatReportsNegativeCents() {
// ~20 cents flat of A4.
let flatHz: Double = 440.0 * pow(2.0, -20.0 / 1200.0)
let reading: TunerPitchReading = TunerPitchReading(hz: flatHz)
#expect(reading.noteName == "A4")
#expect(reading.cents < -15.0 && reading.cents > -25.0)
}
@Test func lowGuitarStringIsE2() {
let reading: TunerPitchReading = TunerPitchReading(hz: 82.41)
#expect(reading.noteName == "E2")
}
}
@@ -0,0 +1,91 @@
// TunerTapTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("TunerTap")
struct TunerTapTests {
/// A constant-frequency sine source — same shape as `LooperPedalTests.ToneSource`.
private final class ToneSource: SynthesizerBase {
private let targetBus: Int
private let toneFreq: Double
private let amplitude: Double
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
self.targetBus = targetBus
self.toneFreq = freq
self.amplitude = amplitude
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq, mul: amplitude))
}
}
@Test func detectsKnownFrequencyWithinTolerance() throws {
let toneFreq: Double = 220.0
// The YIN tracker decimates 8×, so its 512-sample window needs ~4096 input samples
// to fill plus several hops to converge — render generously.
let renderDuration: Double = 2.0
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let scratchControlBus: ControlBus = try engine.busAllocator.allocateControlBus()
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseControlBus(scratchControlBus)
}
let source: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
let tap: TunerTap = TunerTap(inputBusIndex: srcBus.index, scratchControlBus: scratchControlBus)
try engine.add(source)
try engine.add(tap, position: NodePosition.after(source))
try engine.start()
let capture: TunerPitchCapture = try #require(tap.pitchCapture)
let detected: Double = capture.detectedFrequencyHz
let tolerance: Double = 5.0
#expect(abs(detected - toneFreq) < tolerance, "Expected ~\(toneFreq) Hz, got \(detected) Hz")
#expect(capture.detectedConfidence > 0.5, "A pure tone should track with high confidence")
}
@Test func detectsLowGuitarEString() throws {
// E2 ≈ 82.4 Hz — below the undecimated FreqTracker floor (~173 Hz), so this only
// works because the tuner tap decimates before YIN analysis.
let toneFreq: Double = 82.41
let renderDuration: Double = 3.0
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let scratchControlBus: ControlBus = try engine.busAllocator.allocateControlBus()
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseControlBus(scratchControlBus)
}
let source: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
let tap: TunerTap = TunerTap(inputBusIndex: srcBus.index, scratchControlBus: scratchControlBus)
try engine.add(source)
try engine.add(tap, position: NodePosition.after(source))
try engine.start()
let capture: TunerPitchCapture = try #require(tap.pitchCapture)
let detected: Double = capture.detectedFrequencyHz
let tolerance: Double = 3.0
#expect(abs(detected - toneFreq) < tolerance, "Expected ~\(toneFreq) Hz (low E), got \(detected) Hz")
}
}
@@ -0,0 +1,123 @@
// TunerTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("ShoeGaze Tuner")
struct TunerTests {
private func makeShoeGaze(duration: Double) -> (ShoeGaze, SynthesisEngine, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 64)
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
return (shoeGaze, engine, url)
}
@Test func engageAddsTapAndDisengageRemovesIt() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.2)
defer { try? FileManager.default.removeItem(at: url) }
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
#expect(!shoeGaze.tunerEngaged)
#expect(shoeGaze.currentPitchHz == nil)
shoeGaze.engageTuner()
#expect(shoeGaze.tunerEngaged)
try engine.start()
#expect(shoeGaze.currentPitchHz != nil)
shoeGaze.disengageTuner()
#expect(!shoeGaze.tunerEngaged)
#expect(shoeGaze.currentPitchHz == nil)
}
@Test func engagingWithMuteOnMutesRigAndDisengageRestores() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.tunerMutesRig = true
#expect(!shoeGaze.rigMuted)
shoeGaze.engageTuner()
#expect(shoeGaze.rigMuted, "Engaging with tunerMutesRig=true should mute the rig")
shoeGaze.disengageTuner()
#expect(!shoeGaze.rigMuted, "Disengaging should restore the pre-engage mute state")
}
@Test func disengageRestoresPriorMutedStateNotAlwaysUnmuted() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.tunerMutesRig = true
shoeGaze.setRigMuted(true) // already muted before engaging, for an unrelated reason
shoeGaze.engageTuner()
#expect(shoeGaze.rigMuted)
shoeGaze.disengageTuner()
#expect(shoeGaze.rigMuted, "Rig was already muted before engaging — disengage must not unmute it")
}
@Test func tunerMutesRigFalseDoesNotTouchRigMute() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.tunerMutesRig = false
shoeGaze.engageTuner()
#expect(!shoeGaze.rigMuted)
shoeGaze.disengageTuner()
#expect(!shoeGaze.rigMuted)
}
@Test func toggleTunerEngagedFlipsState() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.toggleTunerEngaged()
#expect(shoeGaze.tunerEngaged)
shoeGaze.toggleTunerEngaged()
#expect(!shoeGaze.tunerEngaged)
}
@Test func engageIsANoOpWhenAlreadyEngaged() throws {
let (shoeGaze, engine, url): (ShoeGaze, SynthesisEngine, URL) = makeShoeGaze(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
_ = engine
let board: PedalBoard = try shoeGaze.addBoard()
try shoeGaze.finalizeBoard(board)
shoeGaze.engageTuner()
shoeGaze.tunerMutesRig = false // change after first engage — should have no effect until re-engage
shoeGaze.engageTuner()
#expect(shoeGaze.rigMuted, "Second engageTuner() call while already engaged must be a no-op")
}
}