166 Commits

Author SHA1 Message Date
josh 2fd7eaee57 release: finalize 3.0.0 changelog (date 2026-08-04) 2026-08-05 14:14:32 -07:00
josh 654e80e9c8 docs(help): add Amp Models + Cabinets & Microphones help sections
Two new in-app Help topics for the 3.0 amp features:
- Amp Models: picking an amp, the 1–11 Gain taper, Master (power-amp drive)
  vs Level (clean trim), analog soft-limiting, and the advanced pop-over
  (Sag / Bias / Bias X) reached via the top-right sliders button.
- Cabinets & Microphones: an amp's built-in cab vs a standalone Cabinet
  pedal ("None (direct)" + a Cabinet after the amp), cab/mic voicing, and
  the mic-placement + dual-mic pop-over (Position / Proximity / Mic B /
  Blend / Offset). Notes the models are original DSP, not captures.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-05 14:12:52 -07:00
josh 292261a088 refactor(ui): make widthUnits mean "base width in columns" + tidy overrides
Follow-up cleanup now that card width is content-derived. Redefine widthUnits
as the card's base width in knob columns (1 = 3-wide, 2 = 4-wide) — both the
knob-grid column count and the card's minimum width — with selector/switch rows
able to push wider. Values above 2 no longer do anything.

- Delete the now-misleading widthUnits 3/4 overrides on 11 amps; they inherit
  AmpVoicePedal's 2 (all full-surface amps → the same tight 4-wide card).
- Remove Mutant's redundant override (2 knobs + 2 switches → 3-wide either way).
- Cabinet: keep widthUnits 2 so it's 4-wide like the amps — its Cab/Mic/Mic B
  selector captions (voice names) need the room to stay readable (per request).
- Looper keeps widthUnits 3 (the one pedal still using the flat multiple for its
  bespoke timeline/knobs/transport layout).
- Refresh the widthUnits docs (base + AmpVoicePedal + Cabinet); update the amp
  tests' widthUnits assertions (3/4 → 2; Looper stays 3).

675 tests pass; no visual change to the amps, Cabinet now matches their width.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-05 09:05:40 -07:00
josh a1ce308082 ui(layout): size pedal card width to content, not widthUnits × base
Cards were `220 × widthUnits` wide, so control-sparse multi-unit pedals sat
mostly empty (a 3-unit amp was 660px for a 4-knob row needing ~270; the
2-unit Cabinet was 440 for three selectors). Size the enclosure to its widest
actual row instead — knob grid (columns capped by widthUnits), inline
selectors, or switches — floored at the 3-slot Level·Bypass·Mix footer, and
still widened for a vertical-fader bank. New: Cabinet 440→252, Bluesbreaker
660→330, Boutique/Dual 880→330; 1-unit pedals ~252.

widthUnits now only sets the knob-column cap (≥2 packs 4 across), not raw
width, so all 4-knob amps land at the same tight width regardless of their
3/4 unit value. The looper keeps the flat multiple — its bespoke three-column
timeline/knobs/transport layout genuinely needs the wide card.

675 tests pass (view geometry; no logic change).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 19:02:50 -07:00
josh 685bf5833e docs(changelog): note the Noise Gate pop fix + Attack/Release under 3.0.0 2026-08-04 16:45:46 -07:00
josh 5a3cbeb372 fix(noise-gate): smooth asymmetric close + Attack/Release knobs
Reported bug: a sustained note popped into a different tone mid-decay (~3.63s
in the user's recording). Root cause confirmed by rendering the user's rig with
their input file: the gate keyed off the raw guitar and, as a note decayed
through the threshold, snapped its gain 1.0 -> floor in ~10 ms (symmetric 10 ms
Lag). With heavy downstream gain (the rig's Fuzz, ~50x) amplifying that step,
the ~-9 dB duck read as an audible pop.

Fix: replace the symmetric Lag with an asymmetric LagUpDown — fast open (so a
note's attack isn't softened) / slow close (fades the gate shut and rides out
envelope chatter at the threshold). Verified against the user's input file: the
gate gain now fades 1.0 -> floor smoothly over ~70 ms, monotonic, no snap.

Feature (per request): expose Attack (open) and Release (close) time as knobs
in the advanced pop-over rather than a separate near-duplicate "Vari" gate.
Placed in advancedKnobs so they persist append-only in advancedValues — gates
saved before this load with the timing at defaults, no migration (verified by
test). Release default 0.08 = the smooth close; range 10 ms..500 ms.

Tests: gate close lingers longer with a longer Release and the default lingers
well past a fast close (guards the pop fix + the Release control); Attack/
Release exposed in the pop-over (not the face), round-trip through state, and a
legacy no-advancedValues preset defaults the timing. 675 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 16:41:27 -07:00
josh 11ce3f47d2 ui(palette): move Cabinet to row 2 between Routing and Amp Model
The Cabinet got its own category (row 1, effects) in the last change; move it
to the second row so the rig-structure blocks read left-to-right as
Routing | Cabinet | Amp Model. Split a cabinetGroup out of effectGroups and
render it between the Routing cards and the amp group in the horizontal picker.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 11:48:18 -07:00
josh da68864f36 chore(release): prep 3.0.0 — amp-modeling suite (no tag yet)
Stamp the amp-modeling release as 3.0.0 (headline major on top of the last
released v2.1.3):

- MARKETING_VERSION -> 3.0.0 on both ShoeGazeBuilder (macOS, was a stray 2.1.6)
  and ShoeGazeBuilderiOS (was 2.0.0); bump build numbers.
- CHANGELOG: add the [3.0.0] entry rolling up the whole amp cycle (26 amps +
  onboard FX, analog output limiting, master volume, Sag/Bias/Bias X pop-over,
  cabinet mic modeling + placement + dual-mic, decoupled cab, 1–11 gain taper,
  palette Amp/Cabinet categories). Dated "Unreleased".

No git tag — the maintainer will tag v3.0.0 after play-testing.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 11:23:26 -07:00
josh ebc660898d docs(amp): reattach powerAmpDrive comment after the dial constants 2026-08-04 10:47:47 -07:00
josh f9ddd6b160 feat(amp): Gain/Drive become a 1–11 dial with a musical taper
Every amp's Gain (and the boutique/drive-channel Drive) is now a 1–11 dial —
yes, it goes to eleven — instead of the raw 1–30 tube-drive number.

- New AmpVoicePedal.taperedDrive(_:) maps the 1–11 dial to the 1–30 tube drive
  through an exponential LinExp taper, so 1 is nearly clean, 11 is full
  saturation, and the useful grind spreads across the dial (fine at the bottom,
  steep at the top) rather than bunching near the low end.
- Wired into the base preampStage and every override that feeds a drive:
  Boutique / Fullerton Drive / Jazz Clean / British Dual (Drive channel),
  Anaheim (SS preamp), British Master (cascaded stage).
- gainRange / driveRange → 1...11; every amp's default gain/drive reconverted
  from drive-space to the equivalent dial value (dial = 1 + 10·ln(drive)/ln(30)),
  so each amp's shipped voicing is preserved.
- No preset migration (nothing shipped — per product owner); all knob work
  stays within ShoeGaze (no core Lyrebird change).
- Tests updated to the 1–11 scale; added range + exponential-taper assertions.

671 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 10:42:35 -07:00
josh da2c3328ee ui(cabinet): own category after amps + double-width card + stable selector id
- Add a dedicated PedalCategory.cabinet (tweed tan), placed right after
  Amp Model, and remap the Cabinet pedal to it (was buried in EQ & Filter).
  Move "Cabinet" in the palette preferredOrder to just after the amps.
- CabinetPedal is now double-width (widthUnits 2): three selectors
  (Cab / Mic / Mic B) crowded at single width, clipping the leading Cab
  caption and overlapping dials (a drag near the Mic/Mic B boundary could
  land on the neighbor's gesture — the "moving Mic moved Mic B" report).
- Harden the selector-row ForEach: key by the (unique-per-pedal) selector
  label instead of the array offset, so each selector keeps a stable SwiftUI
  identity across board rebuilds and can't inherit a sibling's drag state.

669 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 10:01:39 -07:00
josh 9b23f99a58 docs(cabinet): fix doc attachment + class-level surface for dual-mic
Review follow-ups (all doc-only; DSP/RT/preset verified correct):
- The blendSecondMic insertion had detached applyPlacement's summary; give each
  helper its own complete doc block again.
- Update the class-level signal-path diagram + ## Parameters list for micB /
  micBlend / micOffset and the optional parallel second-convolver branch.
- micOffset: note it is a set-and-leave spacing control (live-sweeping it moves
  the comb, a flanger-like effect) — keeps .linear interp so micOffset=0 is a
  true zero-delay alignment.
- Correct the maxMicOffsetSeconds comment (1.5 ms ~ 0.5 m spacing, not "mic
  diameters"; first notch near 330 Hz at full offset).

669 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 09:40:09 -07:00
josh d7eb0690ff feat(cabinet): dual-mic blend with comb (14c)
Phase 14c — the classic two-mic technique. When "Mic B" (a second mic-voice
selector, default No Mic) is engaged, a parallel convolver (same cab voice,
mic B's IR) is delayed by up to 1.5 ms (Mic Offset) and summed with the
aligned primary at the Mic Blend balance — the time offset between the two
coherent copies produces comb filtering (e.g. a 57 + 121 blend).

- Mic B: rebuildsOnChange selector; No Mic (default) builds NO second
  convolver, so the single-mic path is bit-identical to before and costs one
  convolution. Mic Blend / Mic Offset are live smooth knobs (advanced pop-over,
  appended after Position/Proximity — append-only for advancedValues).
- Coherent (same-source) mics sum linearly: A*(1-blend) + Bdelayed*blend.
- The look-ahead limiter still bounds the summed output to ±1.

Tests: second mic changes output; with Mic B Off the blend/offset are inert
(single-mic path untouched); blend + comb offset both change output when
engaged; dual-mic round-trips through state; dual-mic stays within ±1. 669
tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 09:31:14 -07:00
josh 35ae16040a docs+test(cabinet): accurate signal-path diagram + honest placement tests
Review follow-ups (no blockers):
- Update the CabinetPedal class doc signal-path diagram to show the full chain
  (mic baked into the IR -> Position/Proximity shelves -> look-ahead limiter),
  which had drifted to the original convolution-only form.
- Reword the placement "neutral defaults" test: it is a default-consistency /
  determinism guard (explicit defaults == default render), not proof of 0 dB
  shelf identity (both sides run the same shelves) -- that identity is the RBJ
  property the reviewer verified. Add loud render-length assertions so a short
  render fails instead of silently passing the guard.

664 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 09:24:24 -07:00
josh f67a5370ff feat(cabinet): mic placement — Position + Proximity (14b)
Phase 14b of cabinet mic modeling. Two live, continuous placement controls in
the CabinetPedal advanced pop-over:

- Position [0,1]: on-axis (0, bright) -> cone edge / off-axis (1, dark), a live
  RBJ high-shelf cut (0..-9 dB @ 3.5 kHz).
- Proximity [0,1]: distant (0, flat) -> close-mic'd (1), a live RBJ low-shelf
  boost (0..+6 dB @ 150 Hz) modelling the proximity effect.

Both are LIVE post-convolution shelves (not baked), so they are smooth knobs
with no rebuild-on-change, and each maps its knob to 0 dB at 0 -> a bit-exact
identity at the defaults (existing cab presets sound unchanged). Placed in
advancedKnobs (advancedValues), append-only, so old CabinetPedal presets don't
shift Mix/Level positions. The look-ahead limiter still bounds output.

Tests: Position/Proximity change output; neutral (0,0) is a bit-exact identity;
advanced knobs exposed; round-trip through state; placement extremes stay within
the ±1 ceiling. 664 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 09:16:22 -07:00
josh 96ab2a0586 docs(cabinet): note partial-mix comb from the limiter's wet delay 2026-08-04 09:08:29 -07:00
josh 99649c2d89 fix(cabinet): transparent look-ahead limiter instead of always-on tanh
External-review blocker: the tanh soft-limit (drive 1.0) is not unit gain at
realistic levels (tanh(0.5)=0.462, -7.6% plus harmonics), so it silently
colored and compressed EVERY signal through this general-purpose pedal, not
just peaks -- an always-on tone change to all existing CabinetPedal presets.

Replace it with LookAheadLimiter (maxAmplitude 1.0, 2 ms look-ahead, 50 ms
release): a true peak limiter that leaves below-ceiling signals untouched (no
coloration of clean material) and only pulls gain down for the brief peaks a
convolution can push past +/-1. Matches the requested "soft limiting" intent
(peak taming, not saturation); adds a short 2 ms delay.

Also (caveman nits): collapse the duplicate dB->amplitude divisor constant to
one shared name; the wet/dry mix is equal-power, so the doc no longer claims a
partial-mix +/-1 guarantee. 659 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 09:06:15 -07:00
josh 7f1856e8e5 feat(cabinet): mic voicing (14a) + cabinet output soft-limit
Phase 14a of cabinet mic modeling.

- MicVoice (No Mic / Dynamic / Ribbon / Condenser): broad-strokes synthesized
  mic curves (our own MIT content, not captures) as CabIRStage biquad specs
  (presence bump, low/high shelving) that CabinetIRFactory appends to the cab
  cascade before baking — folded into the SAME single convolution IR, so mic
  choice costs nothing at render time. MicVoice.off appends nothing → the IR
  is byte-identical to the raw cab voice (backward compatible).
- CabinetIRFactory.makeIR gains a `mic:` param (default .off) + RBJ low/high
  shelf offline biquads.
- CabinetPedal: Mic selector (rebuildsOnChange, append-only 2nd selector so
  old presets still load with mic defaulting to off) + a tanh soft-limit →
  Clip(±1) output stage, so a decoupled amp → cabinet chain can't clip the
  DAC (a speaker cab is analog; clean signals pass at ~unit gain).
- Help acknowledgment notes the mic voicings are synthesized, not captures.

Tests: No-Mic IR byte-identical to raw cab; dynamic lifts presence, ribbon
darkens top, condenser adds air (peak-normalization-invariant tilt ratios);
mic changes output, round-trips; output stays within ±1 across cab×mic. 659
tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 08:55:11 -07:00
josh a2fcd59e1b docs+test(amp): honest Bias X wording + combined-extreme ceiling test
Review follow-ups (no blockers were found):
- Rewrite Bias X docs: it's a power-amp bias-balance CHARACTER control that
  re-shapes the saturation knee, not a literal push-pull even-harmonic model
  (averaging two same-polarity bias-offset stages doesn't replicate push-pull
  imbalance). Document that both halves are always built (2x power-amp cost
  even at biasX=0 — chosen for a smooth live knob over a rebuild-on-change
  fast path). Fix a public->internal DocC symbol link (plain code font).
- Add extremeBiasAndBiasXStayWithinCeiling: Bias hot + Bias X max drives a
  half-stage bias to ±0.6 (tanh-bounded, outputLimit-clamped) — asserts
  finite, ≤ ±1.

651 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 08:26:56 -07:00
josh 594c501039 feat(amp): Bias X (push-pull balance) in the advanced pop-over
Phase 13. Add a shared power-amp Bias X control modelling push-pull tube
balance. powerAmpStage(_:) runs two TriodeStage halves biased at
powerAmpBiasInput ± (biasX·biasXMaxSpread) and averages them: at biasX = 0
both halves share the base bias, so the average is bit-identical to the
prior single stage (default, no re-voicing); turning it up spreads the
operating points, shifting the even/odd harmonic mix.

Deliberately a character control on the single-ended power model, not a
full push-pull topology rebuild — it reduces to the exact shipped tone at
biasX = 0 (monotonic imbalance amount, default 0). Appended to advancedKnobs
(Sag, Bias, Bias X) — append-only so Phase-11 presets (2 advancedValues)
still load with Bias X defaulting.

Tests: Bias X changes waveshape (RMS-normalized, not level), stays within
±1, is exposed in the pop-over, round-trips through state; neutral
Sag/Bias/Bias X is bit-exact identity. 650 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 08:18:50 -07:00
josh e8b858f1aa fix(amp): clamp cab selector before Int() in isCabinetBypassed
External-review blocker: a huge finite cab value (from a corrupted or
hand-edited rig JSON, restored unclamped via PedalState.selectorValues)
would trap Int(cab.rounded()) at board-build time. Clamp in Double space
first, mirroring CabinetVoice.voice(atSelectorValue:). Regression test
renders infinity / ±1e20 / NaN / out-of-range cab values without trapping.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 21:39:27 -07:00
josh 9daffbbdf3 feat(amp): decouple cabinet — "None (direct)" stop + cabinet as separate block
Phase 12. Split AmpVoicePedal.cabinetAndLimit into cabinet(_:) (the
ConvolutionReverb, or a straight pass) + outputLimit(_:) (tanh soft-limit →
Clip(±1)). The output limit ALWAYS runs on the amp, so the per-amp ±1
guarantee survives cabinet removal.

- Cab selector gains a "None (direct)" stop (value = CabinetVoice.allCases
  .count, appended last so existing preset cab indices stay stable).
  isCabinetBypassed skips the convolver at that stop.
- With Cab = None the amp emits its limited, cab-less power-amp signal; the
  player drops the existing standalone Cabinet pedal (shared CabinetVoice /
  CabinetIRFactory, no DSP dup) after it as a real chain block. Default stays
  cab-on (backward compatible).

Tests: None bypasses the convolver, None still limits to ±1 (limiter
survived), the None stop is exposed, and an amp(None) → standalone Cabinet
chain renders non-silent/finite. Note: a downstream cab can overshoot ±1
like any post-amp pedal — end-of-chain level is the board's stage, not the
amp's.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 21:34:12 -07:00
josh 9c0122f199 docs(preset): reattach applyState doc above its declaration
The legacy-migration fix spliced private declarations between applyState's
doc comment and the method, so the doc silently reattached to the private
modernHighGainType constant. Move it back above applyState (and note the
legacyMigrated normalization + advanced-knob restore). Caught in re-review.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 21:26:35 -07:00
josh 781577b062 fix(amp): preserve legacy rigs across the Sag/Bias rename + move
Addresses two blocking findings from the external review, both legacy
preset-compat (no RT/protocol issues were found):

- Rename compat: "Fullerton Princeton" → display "Fullerton Ivy League"
  would silently drop the pedal from any rig saved under the old name
  (displayName is the serialization key). Add PedalRegistry.legacyTypeAliases
  resolved in makePedal (self-healing: loads, then re-saves under the new
  name). Regression test asserts the old name still resolves.
- Knob-shift compat: moving Modern High-Gain's Sag off the face shrank its
  effectKnobs by one, so an old 11-value knobValues array would misassign
  Sag→Mix and Mix→Level on load. Add a targeted PedalState migration
  (Pedal.legacyMigrated) that lifts Sag into advancedValues and keeps
  Mix/Level in place. Regression test decodes a hand-built legacy preset
  and asserts correct placement.

Also: drop the not-yet-built "Bias X" from a doc comment; de-brand "Vox"
from the Chime variants test names (ToneStackModel .vox enum refs kept).

643 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 21:20:16 -07:00
josh 1de14fd879 feat(amp): shared power-amp Sag + Bias in an advanced pop-over
Phase 11. Promote Sag from Modern High-Gain to a shared AmpVoicePedal
capability and add a Bias control, both surfaced in a new pedal-card
pop-over rather than on the amp face.

- AmpVoicePedal gains `sag` [0,1] (AmplitudeFollower gain-droop, clamped
  [0.15,1] to prevent phase inversion) and `bias` [0,1] mapped to the
  power-amp TriodeStage grid bias ([-0.25,0.25], neutral 0.5 → 0.0 so
  existing voices are unchanged at defaults). Both applied in
  preCabinetCore; new `applySag(_:)` + `powerAmpBiasInput` helpers.
- Modern High-Gain drops its bespoke sag (now inherited); keeps sag=0.3
  default. Sag moves off its face into the pop-over.
- Pedal gains an `advancedKnobs` surface; PedalView draws a gear button
  (top-right) presenting them in a popover, reusing the existing pattern.
- Advanced knobs round-trip through PedalState (new `advancedValues`,
  backward-compatible decode) and are MIDI-CC-mappable (appended last).

De-branding (review nits): "Vox" removed from the Chime family's
user-visible summaries + docs; "Fullerton Princeton" renamed to display
"Fullerton Ivy League". Palette horizontal picker second row now shows
Routing before the Amp Model group.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 21:08:23 -07:00
josh 6cf698dbac ui(palette): move amp models into the routing row of the horizontal picker
The horizontal pedal-picker strip put all 26 amp models at the head of the
PEDALS row, stretching it into a very long horizontal scroll. Split the .amp
category out (ampGroup / effectGroups) and render it on the second row beside
the ROUTING cards, so the effects row stays short. Vertical catalog sheet
(the on-demand full list with a filter) is unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 17:50:03 -07:00
josh 0f6d69819d chore(amps): hide Neural Amp from palette/registry (keep code for later)
Remove Neural Amp from PedalRegistry.builtIn and PedalPaletteView.preferredOrder
so it can't be added — the model loader's security-scoped file access is unresolved
(fails silently under sandboxing; flagged in external review). NeuralAmpPedal, its
neuralModelRow UI, PedalType/category/color mappings, and tests are all kept for
later iteration — re-add the two entries to re-enable. Help acknowledgment for the
GuitarML loader dropped (feature not user-reachable); registry test now asserts it
is not registered.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 17:34:46 -07:00
josh 3cdb8d9ddb docs+test(amps): Modern High-Gain re-review nits
- Note the sagGainFloor 0.15 rationale (~-16 dB, deepest droop before gating).
- Rename the sag test's metric to dotProduct (it's an unnormalized sign check).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 16:28:05 -07:00
josh b4a04f6dc8 fix(amps): clamp Modern High-Gain sag gain (no phase inversion)
Review blocker: sag gain 1 - sag*envelope went negative because the envelope
follows the post-Presence/Depth-shelf signal, which exceeds 1 (shelves add up to
+8/+6 dB) — at high sag+presence+depth it phase-inverted loud content instead of
drooping (verified ~-1.0 correlation). Clamp the sag gain to [sagGainFloor(0.15),
1] so it always attenuates, never inverts. Doc/const nits fixed (per-const docs,
"switches" not "sweeps" for the binary Tight). Regression test asserts positive
correlation (no inversion) at presence/depth/sag maxed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 16:25:26 -07:00
josh f7787c4ba3 feat(amps): Modern High-Gain — rectifier w/ Sag + Tight (Phase 10)
New ModernHighGainAmpPedal: a BoutiqueAmpPedal on the .mesa stack (Clean/Lead +
Master + Presence/Depth) voiced as a hot modern rectifier. Two new controls:
- Sag — power-supply droop/bloom, built from AmplitudeFollower (envelope → gain
  droop, slow release) in shapeVoice. No dedicated Lyrebird block needed, so no
  1.7.3 release: sag = signal × (1 − sag·envelope), envelope of the post-power-amp
  signal; louder → lower gain → recovers slowly.
- Tight switch — a pre-preamp high-pass whose corner sweeps 20→120 Hz (firms the
  low end for fast riffing), live via inputShaping.

Registered across 6 sites as .amp. 7 tests (sag/tight change output, inherited
channel + rebuildsOnChange, ceiling at max with everything cranked, control
surface, round-trip, registry). Completes the amp-expansion plan.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 16:16:48 -07:00
josh 8a8cac3823 feat(amps): Lyrebird 1.7.2 — re-voice Cali/Boutique onto Mesa/Soldano stacks (Phase 9)
Bump the Lyrebird pin to 1.7.2 (brings the sample-rate-invariant TriodeStage
coupling fix — no more low-end thinning at 88.2/96 kHz — plus the new Mesa/Soldano
tone stacks and the GrayNoise clamp). Re-voice onto the accurate stacks:
- Cali Hi-Gain (Mesa Mark): .fender → .mesa.
- Boutique Lead (Soldano SLO): .marshall → .soldano.
Other amps unchanged (tweed = .fender = Bassman; Music Man Fender-derived).

Tone-stack-model test assertions + docs updated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 16:04:09 -07:00
josh d32caf6262 docs(amps): Phase 8 review nits — Magna bipolar sweep, Anaheim latency note
- MagnaVibrato depth doc: the LFO is bipolar (±maxSweepSeconds around base).
- Anaheim: note the LookAheadLimiter stays in-chain both states (only ceiling
  changes), so its ~5 ms look-ahead latency is constant, not toggled.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 15:40:15 -07:00
josh ac61b47d17 feat(amps): character amps — Command/Citrus/Sixties/Magna/Anaheim (Phase 8)
Five character voices:
- Command (Hiwatt) — BritishCombo variant: loud hi-fi clean, high headroom.
- Citrus (Orange) — .marshall, fixed mid bump + a single Shape tilt control.
- Sixties Combo (Supro) — .fender, gritty early breakup + onboard tremolo (shared
  tremolo helper + footswitch).
- Magna Vibrato (Magnatone) — .fender, TRUE pitch vibrato: a DelayLine whose delay
  is swept by an LFO (Speed/Depth + footswitch), not amplitude tremolo.
- Anaheim (Music Man hybrid) — .fender, symmetric-bias (solid-state-flavoured)
  preamp, huge headroom, Bright + Deep switches, and a built-in Limiter
  (LookAheadLimiter, ceiling 0.5 when engaged, before the power amp). True
  oversampled hard-clip SS shaper deferred to Lyrebird 1.7.x.

Registered across 6 sites as .amp. New CharacterAmpsTests suite (10 tests):
per-amp control/effect changes, Sixties tremolo bit-exact bypass, Magna vibrato
on≠off + fixed-delay-when-off, Anaheim switches + limiter engages hot, ceiling at
max for all five, tone-stack models, round-trip, registry.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 15:36:06 -07:00
josh 88ad976b8e docs(amps): per-band doc comments on Cali Hi-Gain graphic EQ
Review nit: document each graphic-EQ band @UIParam individually (freq + dB),
matching the GraphicEQPedal precedent.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 15:21:29 -07:00
josh 95839a9e35 feat(amps): Cali Hi-Gain — Mesa Mark w/ 5-band graphic EQ (Phase 7)
New CaliHiGainAmpPedal: a BoutiqueAmpPedal (Clean/Lead channel, Master, Presence,
Depth) with an onboard 5-band graphic EQ layered in shapeVoice — RBJ low shelf
(80) → peaks (240/750/2200) → high shelf (6600), each a dB fader via
effectSliders, cascaded after the base Presence/Depth shaping. Defaults to a mild
scooped "V" (the Mark-series signature). .fender tone stack (Mark lineage);
gain 6, hot Lead drive 16, British 4×12.

Registered across 6 sites as .amp. 7 tests (EQ bands change output, inherited
channel/master, ceiling with EQ + gain maxed, control surface incl. slider bank,
round-trip, registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 15:18:06 -07:00
josh 573a91f377 refactor(amps): hoist shared switch/leadBias constants to AmpVoicePedal
switchOffValue (0.0) / switchOnValue (1.0) were re-declared in six amp files and
leadBias (0.15) in two. Hoist all three onto AmpVoicePedal as internal `let`s so
every subclass inherits them; remove the per-file duplicates. Pure refactor — no
behavior change; 610 tests stay green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 15:11:32 -07:00
josh 31fa1b9cd3 fix(amps): Phase 6 review nits — reuse signatureRange, private leadBias
- BoutiqueAmpPedal: drop the duplicate signatureAmount range, use the inherited
  AmpVoicePedal.signatureRange; make leadBias private (in-class only).
- BoutiqueLead: drop the redundant toneStackModel override (base is already
  .marshall).

Filed a follow-up task to hoist the shared switchOff/On + leadBias constants onto
AmpVoicePedal (now re-declared across several amp bases).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 14:18:43 -07:00
josh 9c0f89bae6 feat(amps): boutique high-gain — Boutique Lead / OD (Phase 6)
Add a shared BoutiqueAmpPedal base: a rebuildsOnChange Clean/Lead channel switch
(Lead cascades a stage set by Drive), a Master (via masterDrive), and Presence
(top-end high-shelf) + Depth (low-end low-shelf, RBJLowShelf) power-amp shaping;
widthUnits 4, 4× power-amp oversample.

- Boutique Lead — SLO-style aggressive super-lead (.marshall, hot Lead drive).
- Boutique OD — D-style smooth overdrive (.fender) with a Mid Boost switch
  (RBJPeakingEQ peak scaled by the switch, identity when off) layered on the base
  Presence/Depth shaping.

Registered across 6 sites as .amp. 10 tests (channel switch + rebuildsOnChange,
presence/depth, master drives power amp via RMS-normalized SSD, drive, ceiling on
lead channel, control surfaces, OD mid boost, round-trip, registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 14:10:14 -07:00
josh 651706126c fix(amps): Phase 5 review nits — base doc, hoist leadBias, test assert
- BritishComboAmpPedal doc now covers the master-volume subclasses (was
  "non-master only").
- Hoist the duplicated leadBias (0.15) constant into BritishComboAmpPedal;
  British Master / Dual use the inherited one.
- Test: assert British Dual's powerAmpOversample == 4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 13:54:21 -07:00
josh cda596b9d5 feat(amps): master-volume Marshalls — British Master / Dual (Phase 5)
Add a shared AmpVoicePedal.masterDrive(_:minDrive:maxDrive:) helper (Master knob
[0,1] → power-amp drive range) and route British's powerAmpDriveInput through it.
Two new BritishComboAmpPedal subclasses (Presence + Bright inherited):

- British Master — 800-series single-channel lead: preampStage cascades a second
  gain stage (both driven by Gain) + Master + 4× power-amp oversample.
- British Dual — 900/DSL: rebuildsOnChange Clean/Lead Channel switch (Lead
  cascades a stage set by Drive), Master, spring reverb; widthUnits 4.

Registered across 6 sites as .amp. 11 tests (Master drives power amp via
RMS-normalized SSD, cascaded-vs-Plexi, channel switch + rebuildsOnChange, drive/
reverb, ceiling on lead channel at max, control surfaces, round-trips, registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 13:46:08 -07:00
josh a7534a29db refactor(amps): shared tremolo helper (dedup across 3 combo amps)
Factor the duplicated unipolar-sine tremolo block out of Fullerton Reverb,
Chime Top Boost, and British Bluesbreaker onboardEffects into one shared
AmpVoicePedal.tremolo(_:speed:depth:enabled:) — signal × LFO over
[1 − depth·enabled, 1], a bit-exact identity when depth·enabled == 0. The 0.5
depth scale is a single named constant on the base. Same expression tree as
before, so no behavior change — the footswitch bit-exact bypass tests and the
full 589-test suite stay green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 13:16:56 -07:00
josh e88db04686 fix(amps): recall rebuilds on a rebuildsOnChange switch (channel)
Review blocker: lightweight recall (ShoeGaze.applyState) detected topology change
only via Pedal.rebuildSelectorValues (effectSelectors), so a channel switch —
the first rebuildsOnChange *switch* — flipped during a scene recall wrote the
node value but never rebuilt, leaving the stale channel topology (wrong preamp).

- Rename/extend to Pedal.rebuildTopologyValues: folds in effectSwitches flagged
  rebuildsOnChange alongside the selectors (both NaN-sanitized). Recall call sites
  in ShoeGaze+Preset updated.
- FullertonDrive: rename channel constants to generic switchOff/On (used by the
  Bright switch too).
- Test: applyStateRebuildsBoardWhenChannelSwitchChanges — recall flipping the
  channel rebuilds the board and applies the recalled channel.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 13:10:23 -07:00
josh da4d5e23ea feat(amps): channel-switch enabler + drive-channel amps (Phase 4)
Enabler:
- PedalSwitch.rebuildsOnChange (mirrors PedalSelectorKnob): a switch that changes
  graph topology asks the host to rebuild. Wired through PedalSwitchView (onCommit
  on a changed tap) and PedalView.switchRow → pedalRebuildAction.
- AmpVoicePedal.preampStage(_:) overridable hook (default: one TriodeStage at
  Gain). preCabinetCore feeds it; a channel amp cascades an extra stage on its
  drive channel. Named preampOversample constant (4).

Amps:
- Fullerton Drive — American two-channel combo: blackface Clean + an overdrive
  channel (cascaded TriodeStage set by Drive), spring reverb, Bright. Channel
  switch is rebuildsOnChange, so only the selected channel's stages are built.
- Jazz Clean — add the JC onboard Distortion channel (Clean/Dist switch + Drive
  knob) via the same preampStage cascade; flows through its stereo wideEffect.

Registered Fullerton Drive across 6 sites as .amp. 22 tests across the two amps
(channel switch changes output, drive knob, rebuildsOnChange, ceiling on the
drive channel, control surface, round-trip, registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 13:04:06 -07:00
josh 8cd77ad984 fix(amps): Phase 3 review nits — doc ordering, accuracy, test coverage
- ChimeAmpPedal: move the "AC-style variants…" note above the - Parameters:
  block so DocC renders it as its own paragraph (not folded into outputBus).
- Base-class doc no longer claims all variants differ by power-amp breakup (Chime
  Normal keeps the base drive).
- Test: also assert Chime 15 ≠ Chime Baby (the 2.0-vs-2.5 drive pair).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 12:51:30 -07:00
josh 818478ce1b feat(amps): Vox variants — Chime 15 / Normal / Baby (Phase 3)
Make ChimeAmpPedal open with a convenience init, then derive three AC-style Vox
voices that inherit its Cut control + .vox tone stack and differ by voicing:

- Chime 15 — 1×12 EL84 combo: power-amp drive 2.0 (earlier breakup), Bright cab,
  gain 6.
- Chime Normal — AC30 non-top-boost channel: warmer/rounder (treble 0.5, more
  Cut), American cab, base headroom.
- Chime Baby — tiny practice combo: drive 2.5 (breaks up earliest), Lo-Fi 1×8
  cab, less bass.

Chime 15 / Baby override powerAmpDriveInput (fixed higher drive) + oversample 4;
Normal keeps the base. Registered across all 6 sites as .amp. 8 tests (Cut per
voice, inherited surface/.vox, breakup oversample, voices differ, ceiling,
round-trip, registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 12:45:09 -07:00
josh 415e99dd62 feat(ui): amp Cab selector moves to the Level·Bypass footer
For a pedal that hides the Mix knob and publishes exactly one selector (the amps,
whose only selector is Cab), surface that selector in the bottom row's trailing
slot beside Level and Bypass — a compact "Level · Bypass · Cab" footer — instead
of a full-width selector row of its own. The rebuildsOnChange → pedalRebuildAction
wiring is preserved. Pedals that show Mix (e.g. Cabinet) keep Mix there and their
selector in the row; pedals with 0 or >1 selectors are unchanged. UI-only.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 12:25:22 -07:00
josh 71d9b44809 fix(amps): Phase 2 review nits — Help scope, compose switches, test
- HelpView: scope the tone-stack acknowledgment to "tube-amp voice pedals"
  (the genericized "amp pedals" wrongly implied Neural Amp, which is .amp but has
  no tone stack, follows Yeh & Smith).
- BritishBluesbreaker: compose super.effectSwitches for the Bright switch instead
  of re-declaring it, so it stays in sync with the base.
- Test: round-trip now also asserts speed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 12:17:18 -07:00
josh 4de8379cb8 feat(amps): Marshall non-master voices — Plexi / JTM / Bluesbreaker (Phase 2)
Add a shared non-master British base and three voices. BritishComboAmpPedal
(open) provides the common surface: .marshall tone stack, Presence lift
(post-power-amp shelf), Bright switch (pre-preamp shelf), fixed power-amp drive
(loudness from Gain, no Master — distinct from the master-volume BritishAmpPedal).

- British Plexi — non-master Super Lead, higher gain, 4×12.
- British JTM — warmer, lower-gain JTM crunch, darker top.
- British Bluesbreaker — 2×12 combo crunch + onboard tremolo (Speed/Intensity +
  Tremolo footswitch), widthUnits 3.

Registered across all 6 sites as .amp; Help tone-stack acknowledgment genericized
so it no longer needs editing per amp. 12 tests (Presence/Bright per voice,
non-master check, Plexi/JTM surface, voices differ, Bluesbreaker tremolo +
footswitch bit-exact bypass, ceiling, round-trip, registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 12:10:06 -07:00
josh 690030a4c5 fix(amps): Phase 1 review nits — docs, redundant init, test style
- AmpVoicePedal: powerAmpDriveInput / powerAmpOversample docs now cover the
  lower-headroom-variant case (fixed higher drive), not just master-volume amps.
- FullertonReverbAmpPedal: drop the redundant override init(name:) — the class
  inherits AmpVoicePedal's designated init, so the convenience init and the
  subclasses' super.init(name:) resolve without it.
- FullertonDeluxe doc: correct "2×12 Twin"/"Master drives" wording (both share
  the American cab; the difference is a higher fixed power-amp drive).
- Tests: explicit for-loop binding type annotations; accurate diff comment.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 12:02:32 -07:00
josh 8a08264fb4 feat(amps): Fender blackface variants — Fullerton Deluxe & Princeton (Phase 1)
Make FullertonReverbAmpPedal open with a name-taking designated init, then derive
two lower-headroom blackface combos that inherit its reverb + tremolo + bright
control surface and differ only in voicing:

- Fullerton Deluxe — 1×12, power-amp drive 2.2 (earlier breakup than the Twin's
  1.5), americanCombo cab, slightly less bass.
- Fullerton Princeton — 1×10, drive 2.6 (breaks up earliest), Vintage Dark cab,
  least bass, a shade darker.

Both override powerAmpDriveInput (headroom via power-amp saturation) and
powerAmpOversample → 4 for the harder drive. Registered across all 6 sites as
.amp. 7 tests (variants differ from Twin + each other, inherited reverb/bright,
ceiling at max gain, inherited control surface + oversample 4, round-trip,
registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 11:55:23 -07:00
josh e5deb8f94a feat(ui): Amp Model pedal category
Add an "Amp Model" PedalCategory and move the amps (California, British, Chime,
Fullerton Reverb, Jazz Clean, Chime Top Boost, Neural Amp) out of Gain into it.
Overdrive/Distortion/Fuzz/Volume stay in Gain. Purely a palette grouping /
filter-menu change (UI); no audio or pedal behavior. New amps register .amp.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 10:23:25 -07:00
josh 9abc613fc3 chore: gitignore local amp-expansion working plan
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 10:05:54 -07:00
josh 48dce06f5a fix(amps): master review follow-ups — tone-proving test, headroom, default
- britishMasterDrivesPowerAmp now uses an RMS-normalized SSD so it proves Master
  changes the *waveshape* (power-amp saturation), not merely level — a raw SSD
  couldn't distinguish the two, and distinguishing them is the whole point vs
  `level`.
- Add powerAmpOversample hook (default 2); British overrides to 4 so the higher
  Master drive (up to 5.0 vs the fixed 1.5) has anti-alias headroom.
- British Master default 0.3 → 0.22 so it maps to ≈1.5 drive, keeping the amp's
  out-of-box tone unchanged.
- Add a max-Master (gain 30 + Master 1.0) ceiling test; DocC no longer links the
  private powerAmpDrive symbol.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 09:59:59 -07:00
josh b9a63eeaf5 feat(amps): master-volume enabler + Master knob on British
Add powerAmpDriveInput hook to AmpVoicePedal: an overridable drive into the
power-amp TriodeStage, defaulting to the fixed powerAmpDrive so the five existing
amps are byte-for-byte unchanged. A master-volume amp overrides it with a live
knob mapped to a drive range — so Master pushes the power-amp stage into
saturation (real master-volume behaviour), unlike `level`, which only attenuates
the finished output post-cab/post-limiter.

British gains a Master knob (LinLin [0,1] → power-amp drive [0.5, 5.0]): crank
Gain for preamp grind, set Master for power-amp saturation. signatureKnobs now
[Presence, Master]. Other current amps are non-master (Fender blackface, Vox,
JC) and keep the fixed drive.

Tests: Master changes the power-amp tone (not just level), round-trips through
state; British control-surface updated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 09:53:03 -07:00
josh 9588d77137 docs(amps): genericize AmpVoicePedal base doc
Review nit: the base-class doc enumerated every subclass, needing an edit per
new amp. Describe the family generically instead.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 09:23:34 -07:00
josh 5d8e655dab feat(amps): Chime Top Boost — full Vox-style control surface
Full-surface counterpart to the basic Chime voice, modeling the AC-style top-boost
combo. Reuses the AmpVoicePedal hooks:
- inputShaping: Brilliant switch (pre-preamp treble shelf, identity when off).
- onboardEffects: tremolo (Speed/Intensity), gated by a Tremolo footswitch. No
  onboard reverb (always outboard on these amps).
- shapeVoice: the Cut control (post-power-amp low-pass swept 9k→2.5k).

ChimeTopBoostAmpPedal (.vox): Gain/Bass/Mid/Treble + Cut/Speed/Intensity knobs,
Brilliant + Tremolo switches, Cab selector (defaults to Bright 1×12); widthUnits 3.
Registered across registry/type/category/palette/enclosure; Help acknowledgment
lists its tone stack. 10 tests (Cut, tremolo intensity/speed, brilliant, tremolo
footswitch bit-exact bypass, ceiling with FX, control surface, round-trip, registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 09:18:17 -07:00
josh 17a0845225 fix(ui): harden horizontal switch row layout
Switches now lay out side by side (HStack). Polish so it degrades cleanly:
- PedalSwitchView caption: lineLimit(1) — no wrap → no height jitter between
  switches sharing a row.
- switchRow: .top alignment so segment bars stay level; doc updated (no longer
  "one per row").
- MutantPedal: widthUnits 2 so its Sweep (2-way) + Mode (3-way) switches sit
  side by side without cramping in a single-width card.

UI-only; no audio/state changes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 09:07:22 -07:00
josh 29b1747533 fix(amps): Jazz Clean chorus depth range + true stereo tests
Review fixes:
- chorusDepth was defaulted 0.3 with a 0..1 range, but the Chorus generator's
  depth is a fraction of the delay time — that's ~30-300× the classic-chorus
  band and produces pitch wobble, not lush chorus. Retune to default 0.005,
  range 0.0005...0.015 (matching the ModulationPedal precedent).
- Tests now render the widener as true stereo (outputBusRight + split master),
  asserting L≠R when the chorus is engaged and bit-exact L==R when bypassed, and
  checking the ±1 ceiling on BOTH channels — the prior suite only exercised the
  left channel.
- AmpVoicePedal base doc lists Jazz Clean.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 08:20:23 -07:00
josh 102715ded1 feat(amps): Jazz Clean — stereo-chorus solid-state amp
First stereo (widener) amp, modeling the JC-style ultra-clean combo whose
signature is a lush stereo chorus fed to two power amps / speakers.

Refactor AmpVoicePedal.effect() into two reusable, behavior-preserving pieces:
- preCabinetCore(_:)  — inputShaping → preamp → tone → onboardEffects → power → shapeVoice (mono)
- cabinetAndLimit(_:) — selected cab convolver → tanh soft-limit → Clip(±1) (per channel)
effect() = cabinetAndLimit(preCabinetCore(dry)); the four existing amps are
unchanged (verified by their suites).

JazzCleanAmpPedal (widener, .fender): mono core (with spring reverb + bright)
→ Chorus (mono → stereo split) → per-channel cabinetAndLimit. Controls:
Gain/Bass/Mid/Treble + Reverb/Rate/Depth knobs, Bright + Chorus switches, Cab
selector; widthUnits 3; defaults to the Full-Range cab for a hi-fi voice. The
Chorus footswitch gates the wet mix to 0 (dry pass-through, Rate/Depth kept).

Registered across registry/type/category/palette/enclosure; Help acknowledgment
lists its tone stack. 10 tests (chorus rate/depth, reverb, bright, footswitch
bit-exact bypass, ceiling with FX, stereo/control-surface config, round-trip,
registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 08:12:27 -07:00
josh 27fb6e6898 fix(amps): disambiguate Reverb footswitch label; comment bypass test
Review nits: rename the reverb-enable switch "Reverb" → "Reverb FX" so it no
longer collides with the "Reverb" level knob in the flat control surface
(clearer, better for VoiceOver). Note in the vibrato bypass test why the
differing speed between the two renders is intentional (depth gated to 0 makes
the LFO a constant regardless of frequency).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 07:59:12 -07:00
josh a9e91ef08c feat(amps): Reverb + Vibrato footswitches on Fullerton Reverb
Model the amp's two-button footswitch: Reverb and Vibrato switches that bypass
each onboard effect to a dry pass-through while preserving the knob positions.
Both gate live by scaling the wet amount to zero — reverb mix → 0 (SpringReverb
passes dry), tremolo depth → 0 (LFO collapses to a constant 1.0) — so Off is a
true identity and no rebuild is needed.

reverbEnabled / vibratoEnabled default on. Tests assert each footswitch-off is a
bit-exact pass-through (equals the knob-at-zero render) and differs when engaged;
state round-trip and control-surface exposure updated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 07:52:23 -07:00
josh c9795f7305 docs+test(amps): Fullerton review nits
- AmpVoicePedal class doc lists Fullerton Reverb as a subclass.
- Ceiling test exercises the tremolo path (intensity/speed set).
- amp-modeling-2.0-plan S2 notes the Fullerton Reverb full-surface block.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 07:10:46 -07:00
josh 6718914ee0 feat(amps): Fullerton Reverb — full control surface (reverb + tremolo + bright)
First combo amp with onboard effects, modeling the American blackface clean
voice. Adds two overridable hooks to AmpVoicePedal so an amp can insert stages
without touching the fixed chain:
- inputShaping(_:)   — pre-preamp (bright switch here)
- onboardEffects(_:) — after tone stack, before power amp (reverb + tremolo here)

FullertonReverbAmpPedal (.fender):
- Spring reverb (SpringReverb) with a Reverb mix knob.
- Tremolo (unipolar sine gain LFO) with Speed + Intensity knobs; defaults off so
  the amp opens as a clean reverbed platform. ("Vibrato" channel is really AM.)
- Bright switch: a pre-preamp high-shelf whose gain is scaled by the toggle, so
  Off is a true identity and the switch is live (no rebuild).
- Full surface: Gain/Bass/Mid/Treble + Reverb/Speed/Intensity knobs, Bright
  switch, Cab selector; widthUnits 3.

Registered across registry / type / category / palette / enclosure color; Help
acknowledgment lists its tone stack. 9 tests (FX effect, ceiling with FX on,
control surface, state round-trip, registry).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-03 07:03:51 -07:00
josh 544a07d569 fix(amps): true ±1 ceiling — hard safety clamp after the tanh stage
Review follow-up: the tanh output stage soft-limits but does not strictly bound
output — its DC-blocker (Nyquist gain ~1.0025) and the halfband oversampling
filters can leave a sub-percent transient overshoot above ±1, which the DAC
would still clip. The prior "can never overshoot" doc claim was overstated.

Add a final Clip(±1) after the tanh: the tanh does the musical analog-style
soft-limiting, the clamp only catches the inaudible ripple residue, so the amp
stage provably never emits a sample past ±1. Docs corrected (soft-limit is a
digital safety ceiling placed after the cab, not literal circuit order; master
Level ≤ 1 carries the ceiling through). Ceiling test tightened 1.05 → 1.0+1e-4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 21:15:16 -07:00
josh fb50538e84 feat(amps): analog-style tanh output stage (no digital clipping)
The cab convolution and signature shelves can push amp output past ±1, which
would hard-clip the DAC. A real amp has no brickwall — the output transformer /
speaker soft-compress. Add a symmetric tanh output stage (TriodeStage bias 0,
2× oversampled) as the final node of AmpVoicePedal.effect(), after the cab.

Unit small-signal gain leaves clean playing untouched; peaks asymptote to ±1.
Combined with the attenuate-only master Level and fully-wet mix, the amp can no
longer overshoot into a hard digital clip. Test: every voice driven at max gain
+ tone stays within the digital ceiling.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 21:09:30 -07:00
josh e1ed4e348c fix(cab): NaN-safe selector compare; correct applyState doc contract
Re-review follow-ups:
- rebuildSelectorValues sanitizes non-finite node values to a sentinel so the
  before/after recall compare (uses !=) can't be forced true by NaN != NaN,
  which would trigger a needless rebuild on every recall.
- ShoeGaze.applyState doc no longer claims "without rebuilding the engine graph":
  it now documents that a board is rebuilt (with the one-block-glitch caveat)
  when a rebuildsOnChange selector value differs from the live rig.

Iteration-during-mutation in applyState confirmed safe: zip over the stored
[PedalBoard] array snapshots it (COW), and PedalBoard is a final class, so
rebuildBoard mutating self.boards mid-loop does not disturb the iteration.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 20:36:21 -07:00
josh 3fe6b8a50a fix(cab): rebuild board on lightweight recall of a topology selector
Review follow-up to the single-convolver cab change. Now that only the selected
cabinet voice's convolver is built, any path that changes the selector value
without rebuilding leaves audio on the stale convolver. The UI drag already
rebuilds; the gap was ShoeGaze.applyState (lightweight scene recall), which
applies param snapshots to live pedals without a rebuild.

- Pedal.rebuildSelectorValues: values of effectSelectors flagged rebuildsOnChange.
- applyState/applySegmentParams/applyBranchParams: detect when a rebuildsOnChange
  selector value actually changes during recall and rebuild only those boards;
  boards without such a selector keep the cheap live-apply path.
- CabinetVoice.voice(atSelectorValue:): guard non-finite and clamp in Double
  space so Int() can never trap on a corrupt preset value.
- Doc fixes: CabinetPedal.cabinet and AmpVoicePedal chain diagram no longer claim
  a live Select.

MIDI CC is unaffected: selectors are not in ccMappableControls (knobs + sliders
only). Tests: recall changing the cab voice rebuilds and applies; recall with an
unchanged voice does not rebuild.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 20:27:39 -07:00
josh 59370ee5dd perf(cab): instantiate only the selected cabinet convolver
The cab selector was a Select over one ConvolutionReverb per CabinetVoice, and
Select evaluates every input each block — so all 8 voices' partitioned-FFT
convolvers ran continuously (7/8 discarded), per CabinetPedal and per amp voice.

Build only the selected voice's convolver. The cab selector is now
rebuildsOnChange: committing a new stop asks the host to rebuild the board
(same mechanism the Neural Amp model loader uses), which re-enters effect()
with the new voice. One convolver runs instead of N; cost moves to a brief
rebuild on cab switch (cabs are set-and-forget).

- PedalSelectorKnob: add rebuildsOnChange flag.
- PedalSelectorKnobView: fire onCommit on drag-end when the stop changed.
- PedalView: wire onCommit → pedalRebuildAction for rebuildsOnChange selectors.
- CabinetVoice.voice(atSelectorValue:): rounded/clamped index → voice.
- CabinetPedal + AmpVoicePedal: single ConvolutionReverb for the selected voice.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 20:16:42 -07:00
josh 8a266a33dc fix(cab): keep modernStack breakup in-band; doc + test follow-ups
Review fixes:
- modernStack.breakupHz 4500 → 3800 so the cone-breakup peak sits below the
  4000 Hz low-pass (was the only voice with breakup > lowPass, which rolled off
  most of the intended boost).
- CabinetIRFactory class doc: list the full 7-stage chain (breakup + notch were
  missing).
- Tests: add loFiIsDarkerThanFullRange and breakupPeakLiftsUpperMid for
  per-voice differentiation; drop the hard-coded voice count in
  voiceNamesAreUnique.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 18:54:45 -07:00
josh ec4e7dc5a4 feat(cab): 5 new cabinet voices + notch/breakup IR shaping
Expand CabinetVoice from 3 to 8 synthesized voicings (all original code, no
captures): add Modern 4×12, Boutique 2×12, Bright 1×12, Full-Range (FRFR),
and Lo-Fi 1×8.

Extend the IR synthesis model with two per-voice stages so the voices reach
character the old 4-band curve could not:
- cone-"breakup" peak (narrow upper-mid bite/clank, breakupQ 2.0)
- mid interference "notch" (comb-filter dip ~1.2–2.5 kHz, notchQ 2.5)

Both are RBJ peaking biquads; gain 0 = identity, so a voice can disable either
(Full-Range runs a flat notch). Chain is now HP → LP×2 → body → presence →
breakup → notch. New tests: FRFR top-end extension, notch mid-dip, 8-voice
name uniqueness.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 18:49:08 -07:00
josh 733e979c1b docs(amps): restore Select all-inputs CPU note; update 2.0 plan for voice split
Review follow-ups (non-blocking):
- AmpVoicePedal.effect doc: note the cab Select evaluates every ConvolutionReverb
  each block regardless of selection (bounded fixed CPU), carried over from the
  removed AmpPedal.
- amp-modeling-2.0-plan.md S2: describe the three-pedal voice split
  (California/British/Chime + AmpVoicePedal base) instead of the old single
  model-selector design.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 14:53:09 -07:00
josh 1b247cf766 feat(amps): split combined Amp pedal into California/British/Chime voices
Replace the single AmpPedal (a model-selector pedal) with three dedicated
amp-voice blocks, each fixing one tone-stack model and adding a signature
control so the per-amp UI can be customized:

- AmpVoicePedal: open base — shared Gain/Bass/Mid/Treble/Cab chain
  (TriodeStage preamp → ToneStack → TriodeStage power amp → shapeVoice →
  ConvolutionReverb cab), overridable toneStackModel/summary/signatureKnobs/
  shapeVoice.
- CaliforniaAmpPedal (.fender): Bright high-shelf, clean-leaning gain default.
- BritishAmpPedal (.marshall): Presence high-shelf, crunch gain default.
- ChimeAmpPedal (.vox): Cut low-pass, top-boost jangle.

Registered in PedalRegistry / PedalType / PedalCategory / palette order /
enclosure colors. Help acknowledgment updated for the three tone stacks.
12 new tests in AmpVoicePedalTests; removed AmpPedal + its tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 14:47:07 -07:00
josh 23d607b9fc feat(ui): amp-head layout + Neural Amp model loader (S4)
- AmpPedal: double-width (widthUnits 2) amp-head card so the four tone knobs +
  Amp/Cab selectors + master aren't cramped. Uses the generic single-column
  content (no greedy Spacers → no flow-canvas height issue).
- Neural Amp model loader: PedalView renders, for a NeuralAmpPedal, a "Load
  Model…" picker (.fileImporter for .json) plus the loaded model's filename.
  Picking sets Pedal.resourcePath and asks the host to rebuild the board so the
  model applies live. Picker + AppKit stay in the UI layer (core imports none).
- New `pedalRebuildAction` environment value (@MainActor @Sendable), installed by
  ShoeGazeBuilderView; it resolves the pedal's board via a new branch-aware
  `ShoeGaze.board(containing:)` (finds pedals inside parallel / stereo-split
  branches, not just the main chain) and rebuilds it via the live-safe
  `rebuildBoard(_:from:)`.

Tests: AmpPedal widthUnits == 2; board(containing:) finds main + branch pedals
and returns nil for a stranger. Full suite 502. (SwiftUI loader flow needs
on-device visual QA.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 22:26:14 -07:00
josh 40fa590196 feat(pedals): Neural Amp pedal (S3) + PedalState resource path; Lyrebird 1.7.1
Bump Lyrebird to 1.7.1 (ProteusModelImporter) and add a neural amp-capture pedal.

- NeuralAmpPedal: loads a GuitarML Proteus/NeuralPi model (via ProteusModelImporter)
  and runs it with LSTMAmp on the gain-trimmed input; passes through clean when no
  model is loaded. Model files are user-supplied, not bundled (GuitarML = GPL-3.0).
- PedalState gains an optional `resourcePath` (backward-compatible, decodeIfPresent)
  and Pedal a matching `resourcePath` property, wired through captureState/applyState
  — so the loaded model file persists across rig save/load. The neural pedal reads it
  at build() (applied on rebuild). This foundation also unblocks a future
  custom-cabinet-IR path.
- Registered in PedalRegistry / PedalType / PedalCategory (.gain) / palette /
  enclosure color; Help acknowledges the GuitarML model format.

Tests: no-model passthrough; loaded model transforms output & differs from
passthrough; gain affects modeled output; resourcePath round-trips through
PedalState; gain knob exposed; registry resolves "Neural Amp". Full suite 501.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 20:48:44 -07:00
josh fe31eb6d7d feat(pedals): component Amp pedal (S2) on Lyrebird 1.7
Bump Lyrebird dependency to 1.7.0 and add a full white-box amp built on its new
amp-modeling core.

AmpPedal chain: preamp TriodeStage(drive: gain) → ToneStack(bass/mid/treble,
model) → gentle power-amp TriodeStage → speaker-cabinet ConvolutionReverb. The
tone-stack model (Fender/Marshall/Vox) and cabinet voice are each built per
option and picked live with Select, so both round-trip through the rig save
format. Fully wet (Level is master; Mix hidden).

Controls: Gain, Bass, Mid, Treble knobs + Amp / Cab selectors. Registered in
PedalRegistry / PedalType / PedalCategory (.gain) / palette / enclosure color;
Help acknowledgments cite the Yeh & Smith tone-stack model.

Tests: builds/non-silent/finite; gain, tone, amp-model, and cab all change the
output; controls exposed; amp/cab selections round-trip through PedalState;
registry resolves "Amp". Full suite 494.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 20:11:50 -07:00
josh 77df1675cb docs(help): add Acknowledgments section (Lyrebird, RBJ cookbook, original cab IRs)
Credits the resources used: the Lyrebird engine (MIT), the RBJ Audio EQ
Cookbook biquad formulas (used to synthesize the Cabinet pedal's IRs), and a
note that the built-in cab voicings are original code-generated IRs, not
third-party captures.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 17:33:31 -07:00
josh 4a5d4009f6 feat(pedals): Cabinet IR pedal (S1) with synthesized cab voices
First amp-modeling increment (ShoeGaze 2.0, plan S1). No Lyrebird change —
reuses ConvolutionReverb + LyrebirdBuffer.

- CabinetPedal: builds one ConvolutionReverb per built-in voice at build() time
  and picks the active one with a `Select` driven by the persisted `cabinet`
  selector — live cab switching that round-trips through the rig save format.
- CabinetVoice + CabinetIRFactory: three built-in voicings synthesized in code
  (impulse through an RBJ biquad cascade — HP, true 4th-order Butterworth LP,
  body + presence peaks), so the bundled cab set is our own MIT content (no
  third-party IR licensing). Filter centre frequencies are Nyquist-clamped.
- Registered in PedalRegistry / PedalType / PedalCategory (.filter) / palette;
  README pedal count + catalog updated.

User-supplied captured .wav cab IRs are a planned follow-up (needs a persisted
file-path field PedalState doesn't yet carry).

Tests: IR is finite, peak-normalized, mono; rolls off lows and highs; voices
differ; selector exposed; selection changes output and round-trips through
PedalState; pedal builds, non-silent, resolves from the registry. Suite 486.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 17:13:08 -07:00
josh 791fbd1b2c docs: ShoeGaze 2.0 amp-modeling plan (Lyrebird 1.7 core additions)
Cross-repo plan: cabinet-IR pedal ships on 1.6.4 (reuses ConvolutionReverb);
tone-stack / triode / neural-inference land as Lyrebird 1.7; amp pedals + UI
ship as ShoeGaze 2.0. Branch + review gates and versioning strategy included.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 16:38:25 -07:00
josh 323988af7b fix(ui): looper card no longer stretches to the canvas height
The flow canvas offers the pedal row its full viewport height
(BoardFlowView sets the content minHeight to the viewport). The looper's
columnar layout had Spacer(minLength: 0) inside its left and center
columns, making those VStacks greedy vertically, so the looper card
stretched to fill the offered height — pinning the Level/Bypass footer to
the bottom and leaving a large empty gap in the middle.

Remove both spacers so each column sizes to its content, and pin the
columnar content to intrinsic height with fixedSize(vertical:). Other
pedals were unaffected (their default layout has no vertical spacer).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-01 15:52:19 -07:00
josh ed3283f645 release: ShoeGaze 2.1.6 — oversampled drive pedals + dynamics safety
Bump app version to 2.1.6 (build 14). Sync the Xcode workspace's resolved
Lyrebird pin to 1.6.4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-31 20:45:54 -07:00
josh 8983e8829e feat(pedals): oversample nonlinear drive stages; Sustainer safety limiter
Anti-aliasing (Tier 1): every hard nonlinearity ran at the engine rate, so the
harmonics it generated folded back as inharmonic aliasing — worst on loud/bright
input at high drive. Add two oversampled RT generators built on Lyrebird's
halfband up/down-samplers and move the drive pedals onto them:

- OversampledSaturator (+ SaturationCurve) — tanh / normalised soft-clip /
  tanh+hard-clip curves at 2× or 4×. DistortionPedal now does its tanh→gain→hard
  clip at 4× (clip before the tone low-pass), with a final hard clip after the
  low-pass to re-establish the strict output bound; FuzzPedal (tanh) and
  OverdrivePedal (soft-clip) at 2×.
- OversampledRingModulator — input × sine carrier at 2×, carrier synthesized at
  the oversampled rate so the sum sideband can't alias. Phase wraps both
  directions (safe for negative carrier frequencies) and a sampleRate guard
  prevents NaN latching. RingModulatorPedal uses it.

Dynamics (Tier 2): SustainerPedal gains an opt-in Safety switch (off by default)
that inserts a brick-wall LookAheadLimiter after its compressor to catch the
transient overshoot a low-threshold/high-makeup setting can push past full scale.

Tests: generator-level alias-reduction proofs (Goertzel alias/fundamental ratio
vs a naive base-rate baseline) for both oversampled generators, hard-clip/soft
bounds, negative-carrier stability, distortion output-bound at high drive, and
Sustainer safety switch exposure + peak-capping. Full suite 478 pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-31 20:41:06 -07:00
josh e697789bd7 feat(pedals): limiter Release knob + compressor safety limiter; bump Lyrebird 1.6.4
Consume Lyrebird 1.6.4, which decouples LookAheadLimiter's release time from
its look-ahead window.

- LimiterPedal: add a Release knob (0.01–0.5 s) wired to the new
  LookAheadLimiter.releaseTime. A too-fast release modulated the gain within a
  low-frequency cycle and distorted sustained notes when driven hard.
- CompressorPedal: add an opt-in Safety switch (off by default) that inserts a
  brick-wall LookAheadLimiter after the compressor to catch transient overshoot
  that could clip the output. Built as both branches with Select picking live;
  engaging it adds the limiter's short look-ahead delay.

Tests cover the new knob/switch exposure, release-time effect, and that the
safety limiter caps peaks.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-31 18:22:43 -07:00
josh 09fa4e8d4b app icon and splash screen updates 2026-07-27 20:35:16 -07:00
josh 37777826d1 scheme updates 2026-07-17 14:32:51 -07:00
josh a1a7683bc9 Bump Lyrebird dependency to 1.2.4
Picks up the bus-rate guard (Out/In/ReplaceOut constructors trap a cross-rate
bus), and raises the floor accordingly. 465 tests pass against 1.2.4.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 17:19:03 -07:00
josh 3d67c7b450 Release notes for 2.1.3: tuner output-leak fix
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 20:37:12 -07:00
josh 551b650d45 Fix tuner leaking its pitch signal into the audio output
TunerTap wrote its pitch-capture generator to the scratch bus via output(bus:),
which always builds an Out.Audio — so the write went to *audio*-bus memory at the
control bus's index. Control-bus indices are low, so they collide with the
hardware output buses (e.g. index 1 = right channel), and because the tap runs
.after(mainGroup) the write lands after the master's rig-mute gate. Result: the
tracked frequency (e.g. 82 Hz) was summed onto an output channel, bypassing the
mute — audible as crackle while the pitch was unstable, stopping once a note
locked. Confirmed by render: the leaked value appears verbatim on the output bus.

Route through controlOutput (Out.Control → control-bus memory) instead. The
scratch bus is a control bus; it was only ever meant to give the engine a reason
to evaluate the side-effecting capture generator, and nothing reads it.

Test engagedTunerDoesNotLeakIntoOutput renders a muted rig with the tuner engaged
and asserts the settled output tail is silent (fails without the fix — the tail
carries the leaked pitch value; passes with it). 465 tests pass.

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

464 tests pass; macOS app builds.

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

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

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

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

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

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

463 tests pass; both app targets build.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Tests: TempoEnableTests + looper reverse/deferral coverage.

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

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

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

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

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

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

Tests: cycleSyncModeOscillatesThroughOptions, pedalActionCyclesLooperSync.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

339 tests pass; both app targets build.

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

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

Both app targets build; suite green.

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

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

339 tests pass; both app targets build.

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

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

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

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

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

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

Both app targets build; suite green.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-01 08:18:09 -07:00
josh ec6c97c065 iOS fix for menu display 2026-06-28 21:01:42 -07:00
josh 0b0befe02f update images and xcode. versions 2026-06-28 20:39:51 -07:00
josh b6a9dbbb91 Bump builder apps to 1.3.0
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 18:18:33 -07:00
josh ef20a0eb95 Open .shoegaze files: wire document handlers, scope type to builders
Registering the document type made the apps claim .shoegaze, but without an
open handler macOS reported "cannot open files in the ShoeGaze Document
format." Wire actual opening:

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 17:57:02 -07:00
josh 3322400b7c Merge rig-sharing-1.3: .shoegaze document type and rig/board sharing 2026-06-28 17:50:51 -07:00
246 changed files with 21481 additions and 2729 deletions
+3
View File
@@ -20,3 +20,6 @@ DerivedData/
# Note: Package.resolved is intentionally tracked to pin the Lyrebird dependency.
icon-source.png
review.diff
# Local working plan (not shared)
docs/plans/amp-expansion-plan.md
+248
View File
@@ -0,0 +1,248 @@
# Changelog
All notable changes to ShoeGaze are recorded here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[semantic versioning](https://semver.org/spec/v2.0.0.html).
## [3.0.0] — 2026-08-04
The big one: ShoeGaze becomes an amp-modeling rig. This release adds a full lineup of
tube-amp voices — each with its own tone stack, onboard effects, and control surface —
plus a deep speaker-cabinet and microphone section. Everything is original DSP built in
code from the Lyrebird engine; there are no third-party captures or IR packs.
### Added
- **26 amp-model pedals**, grouped in their own **Amp Model** palette category:
- **Fullerton** blackface combos — Fullerton Reverb, Deluxe, Ivy League, Drive — with
spring reverb, tremolo, and a Bright switch.
- **California** and **Jazz Clean** clean machines.
- **British** stack and combo voices — British, Plexi, JTM, Bluesbreaker, Master, Dual —
from early crunch to hot-rodded master-volume lead.
- **Chime** top-boost family — Chime, Chime 15, Chime Normal, Chime Baby, Chime Top
Boost — with the classic Cut control.
- **Boutique and high-gain** — Boutique Lead, Boutique OD, Cali Hi-Gain (with an onboard
5-band graphic EQ), and Modern High-Gain (Sag + Tight).
- **Character amps** — Command, Citrus, Sixties Combo, Magna Vibrato (true pitch
vibrato), and Anaheim (a solid-state-preamp / tube-power-amp hybrid with a built-in
limiter).
Each amp carries its own tone-stack voicing, a selectable speaker cabinet, and a real
**master volume** that drives the power-amp stage — not just an output trim.
- **Analog-style output limiting.** Every amp ends in a soft `tanh` saturation into a hard
±1 ceiling, so a driven amp compresses like the real thing instead of digitally clipping.
- **Power-amp feel controls**, tucked behind an advanced pop-over (the sliders button at the
top-right of the amp card): **Sag** (power-supply droop and bloom), **Bias**, and **Bias X**
(bias balance).
- **A full speaker-cabinet and microphone section** on the Cabinet pedal, now in its own
**Cabinet** palette category next to the amps:
- **Cabinet voices** — eight synthesized speaker voicings.
- **Microphone modeling** — No Mic / Dynamic / Ribbon / Condenser, folded into the cab
response.
- **Mic placement** — Position (on-axis ↔ cone edge) and Proximity (distance / bass lift).
- **Dual-mic blend** — add a second mic with its own blend and spacing (comb) control,
the classic two-mic technique.
- A transparent look-ahead limiter on the cabinet output.
### Changed
- **Gain and Drive now read 1–11** — yes, they go to eleven — with a musical taper: fine
control at the bottom of the dial, full saturation at the top, instead of a raw internal
number.
- **The cabinet is now a separate pedal you place in the chain.** Amps keep a built-in cab,
plus a **None (direct)** option so you can run a dedicated Cabinet block (and, later, your
own impulse response) after the amp.
- **Palette:** the Amp Model and Cabinet categories sit together, and the Cabinet card is
double-width to fit its cab / mic / second-mic selectors.
### Fixed
- **Noise Gate no longer pops as a note decays.** The gate now opens fast and closes gently
(a slow, tunable fade) instead of snapping shut when a sustained note falls through the
threshold — previously that abrupt step, amplified by downstream gain (e.g. a fuzz), was
audible as a pop / sudden tone change. New **Attack** and **Release** timing knobs (in the
gate's advanced pop-over) dial the close from tight to a gradual swell.
### Notes
- All amp, cabinet, and microphone models are original DSP generated in code — not captures
of any specific hardware, speaker, microphone, or IR pack. Tube tone stacks follow the
published Yeh & Smith analysis of the classic passive tone-stack circuit.
## [2.1.3] — 2026-07-13
A tuner fix. Engaging the chromatic tuner could crackle or pop through the output —
even with "Mute while tuning" on — until a steady note was detected.
### Fixed
- **Tuner no longer leaks into the audio output.** The tuner's pitch-detection stage
was mistakenly written to an audio output bus instead of its internal analysis bus,
so the tracked frequency was summed onto an output channel — bypassing the rig mute
and crackling while the pitch was still unstable (it stopped once a note locked). The
tuner now writes only to its analysis bus; engaging it leaves the output untouched.
## [2.1.1] — 2026-07-12
A quieter, more predictable startup. The input feeding the pedals now has its own
mute — separate from the rig-output mute — that arms every time you start the engine,
so nothing squeals the instant it spins up. New rigs open listening to In 0 instead of
the test-loop phrase, and your input choice and I/O channel counts now travel with the
rig (and iCloud) instead of a separate local setting.
### Added
- **Input mute.** A hard kill-switch on the incoming guitar / mic signal, distinct from
the rig-output mute. It arms automatically every time you press Start (so a fresh
engine is silent until you're ready), sits next to the Start/Stop transport with a
pulsing red glow while active, and is MIDI-mappable (footswitch or key), like Rig Mute.
### Changed
- **New rigs open on In 0** (live input) instead of the built-in test-loop phrase.
- **Input & I/O persist with the rig.** The input selection and the engine's input /
output channel counts are stored in the rig (and sync via iCloud), and are reapplied
on launch — so a multi-channel setup and a chosen input channel survive a restart
instead of reverting to the defaults. Replaces the previous local-only input setting.
- The docked (macOS) transport shows the Bypass / Mute / Input toggles as icons so the
row no longer crowds the sample-rate and channel controls.
### Fixed
- A muted input is now **exactly** silent from the first sample — no brief start-up
transient when the engine begins rendering.
- iOS: the app declares in-place document support, clearing a launch-time console warning.
### Compatibility
Additive: rigs saved before this release load unchanged (input defaults to In 0, or the
test loop when no live input is available), and 2.1.1 rigs still open in older builds —
the input-mute state isn't persisted and the extra I/O fields are ignored there.
## [2.1.0] — 2026-07-10
Tempo comes to the pedals. Delay times and modulation rates can lock to a note
division of the live tempo — a quarter-note delay, a dotted-eighth, an eighth-triplet
LFO — shown with real music-notation glyphs and following the tempo as it changes.
Delays reach further, the BPM is directly editable, and every mappable control shows
its MIDI / key binding right on the pedal.
### Added
- **Tempo-synced pedal parameters.** Lock a delay time or a modulation rate to a note
division — whole down to sixteenth, including dotted and triplet values — and it is
derived from the shared tempo, following tap tempo, the stepper, the BPM field, and
MIDI. Delay time on Delay, Feedback Delay, Ping-Pong, Reverse Delay, and each of
Multi-Tap's three taps; LFO rate on Tremolo, Vibrato, Chorus, Flanger, Phaser, and
Modulation. A MIDI CC bound to a synced parameter is ignored while it stays synced
(the tempo drives the value) and resumes control once the parameter is set to Free.
- **Note-value glyphs.** The division picker uses drawn music-notation glyphs —
noteheads, stems, flags, an augmentation dot for dotted values, and a bracketed "3"
over triplets — instead of text labels.
- **Editable BPM.** The tempo readout is now a text field: type a tempo directly
(integer only, clamped to 30–300 BPM). The stepper and tap tempo still work, and a
synced pedal follows a typed change immediately.
- **In-context control mapping.** Each pedal draws a small badge on every mappable
control showing its binding source — Program Change footswitch (PC), Control Change
expression (CC), or letter Key (KEY) — with a legend above the board. Completes the
computer-keyboard control mapping.
### Changed
- **Longer delays.** Maximum delay time raised to 5 seconds across the delay pedals
(previously 1–2 s), so tempo-synced values at slow tempos (whole and half notes) fit.
- Note divisions that would exceed a parameter's range at the current tempo are shown
disabled in the picker, and an active sync that has to clamp shows a warning marker.
### Compatibility
Additive: rigs saved before this release load unchanged (every parameter defaults to
"free"), and 2.1 rigs still open in older builds — the tempo-sync state is simply
ignored there.
## [2.0.0] — 2026-07-05
Major release. Performance-focused: a visual metronome, a real rig mute with
keyboard control, and rigs that remember their tempo, input, and I/O — plus a
saveable set-list order for hands-free switching between rigs live. The version
jumps to 2.0.0 to align ShoeGaze's numbering with the wider project family.
### Added
- **Visual metronome tempo indicator.** A horizontal playhead sweeps wall-to-wall
once per beat with pendulum easing (it slows into each beat so you can anticipate
it), fades toward center, and flashes a glow on the downbeat. Replaces the single
flashing LED.
- **Rig Mute (⌘Z).** A hard gate that silences the entire rig output — distinct from
Bypass Rig, which passes your dry signal through. Reachable from the header, the
per-board volume row, the macOS Board menu, and MIDI.
- **Keyboard shortcuts** (macOS native menus + iOS/iPadOS hardware keyboards):
- `⌘1`–`⌘9` — switch to / solo boards 1–9.
- `⌘⇧1`–`⌘⇧9` and `⌘⇧0` — load set-list rigs 1–10 in library order.
- `⌘Z` — toggle rig mute.
All are listed in the in-app Help.
- **macOS menus.** Board ▸ Mute Rig and Board ▸ Bypass Rig (with live state), and a
Rigs ▸ Set List submenu whose ten slots map to `⌘⇧1`–`⌘⇧0` and track the current
library order.
- **Set-list ordering.** Reorder rigs in the picker by dragging a row or via each
rig's Move Up / Move Down menu. The order is saved and travels with an exported
archive; the top ten map to the `⌘⇧` shortcuts.
- **Per-rig persistence.** A saved rig now also stores its tempo (BPM + enabled
state) and input selection. Engine input/output channel counts are saved too, and
applied on demand via `applyChannelLayout(from:)` rather than forced on every load.
### Changed
- The header "Mute rig" toggle — which actually only set the tuner-mutes-rig
preference — is now a real rig-mute button. The tuner preference is relabeled
**"Mute while tuning"**.
- The rig library now honors a manual set-list order instead of sorting by name/date.
New rigs append to the end; renaming a rig keeps its position.
### Fixed
- Importing a rig archive into a non-empty library no longer collides set-list
positions with existing rigs — imported rigs append in archive order.
### Removed
- The **ShoeGazeDemo** (macOS) and **ShoeGazeiOSDemo** (iOS) minimal-player apps and
their Xcode projects. Only the full **ShoeGazeBuilder** (macOS) and
**ShoeGazeBuilderiOS** (iPad) apps remain.
### Compatibility
- Despite the major-version bump, rig persistence is backward-compatible: the new
tempo / input / I/O / set-list fields are additive and optional. Rigs saved by
earlier versions load unchanged (missing fields are ignored), and rigs saved by
2.0.0 still open in older builds (the new keys are ignored there). The 2.0.0 bump
reflects the scope of new features and version alignment, not a format break.
## [1.5.0] — 2026-07-04
- Looper pedal, iPad/iOS layout rework, Lyrebird 1.2.3.
## [1.4.0] — 2026-07-01
- Maintenance and refinements.
## [1.3.0] — 2026-06-28
- Rig / board sharing via the `.shoegaze` document type.
## [1.2.0] — 2026-06-28
- Ten new pedals, iCloud rig library, builder UI rework.
## [1.1.1] — 2026-06-26
- Info-button placement and region-lane drag-drop fix.
## [1.1.0] — 2026-06-26
- Refinements over the initial release.
## [1.0.0] — 2026-06-24
- Initial ShoeGaze release.
@@ -100,7 +100,7 @@
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
LastUpgradeCheck = 2660;
TargetAttributes = {
C3B100000000000000000014 = {
CreatedOnToolsVersion = 16.0;
@@ -163,10 +163,9 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 4;
CURRENT_PROJECT_VERSION = 15;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
@@ -176,7 +175,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 1.2.0;
MARKETING_VERSION = 3.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -194,9 +193,8 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 4;
CURRENT_PROJECT_VERSION = 15;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
@@ -206,7 +204,7 @@
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 1.2.0;
MARKETING_VERSION = 3.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
@@ -249,6 +247,7 @@
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -311,6 +310,7 @@
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
"version" : "1.2.3"
}
},
{
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
LastUpgradeVersion = "2660"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
+219 -8
View File
@@ -20,7 +20,7 @@ import LyrebirdShoeGazeUI
/// The engine is **not** started automatically; the user clicks Start in the builder's toolbar.
/// On termination the engine is stopped to release Core Audio resources cleanly.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
// MARK: - Engine configuration constants
@@ -55,12 +55,39 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
private let shoeGaze: ShoeGaze
private let window: LyrebirdWindow
/// Foot-controller MIDI input. The macOS engine is never rebuilt, so this is created once and
/// started at launch.
private let midi: MIDIController
/// The rig library; constructed in `init`, resolved + loaded asynchronously after launch.
private let library: RigLibraryStore
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
private var recordMenuItem: NSMenuItem?
/// Rig-mute toggle item, retained so `validateMenuItem(_:)` can flip its title + checkmark to
/// match the current mute state (which may also change from the UI, MIDI, or the tuner).
private var muteMenuItem: NSMenuItem?
/// Rig-bypass toggle item, retained so `validateMenuItem(_:)` can flip its title + checkmark to
/// match the current bypass state (which may also change from the UI or MIDI).
private var bypassMenuItem: NSMenuItem?
/// The Rigs ▸ Set List submenu, retained so its item titles can be refreshed to the current
/// library order each time it opens (via `menuNeedsUpdate(_:)`).
private var setListMenu: NSMenu?
/// The ten fixed ⌘⇧1…⌘⇧0 set-list items (tags 0…9). Their key equivalents fire whether or not
/// the menu is open; `validateMenuItem(_:)` disables slots with no rig, and `menuNeedsUpdate`
/// refreshes their titles to the rig names.
private var setListMenuItems: [NSMenuItem] = []
/// Number of set-list slots exposed as ⌘⇧1…⌘⇧0.
private static let setListSlotCount: Int = 10
/// The Help window, created lazily on first open and reused thereafter.
private var helpWindow: LyrebirdWindow?
/// Default file name offered by the archive Export panel.
private static let defaultArchiveFileName: String = "ShoeGaze Library"
@@ -68,6 +95,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
override init() {
let coreDriver: CoreAudioDriver = CoreAudioDriver()
// The engine is built with the default layout; the autosaved rig's saved I/O layout (if any)
// is applied by `RigStore.restore` below, so a multi-channel setup survives relaunch.
let engine: SynthesisEngine = SynthesisEngine(
blockSize: AppDelegate.blockSize,
sampleRate: AppDelegate.sampleRate,
@@ -80,6 +109,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
self.coreDriver = coreDriver
self.engine = engine
self.shoeGaze = shoeGaze
self.midi = MIDIController(engine: engine, shoeGaze: shoeGaze)
self.window = LyrebirdWindow(
title: "ShoeGaze Builder — Lyrebird Pedalboard",
width: AppDelegate.windowWidth,
@@ -99,6 +129,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
private static func seedInitialBoard(into shoeGaze: ShoeGaze) {
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio,
// so the app comes up listening to the instrument. A restored rig keeps its own saved input.
if shoeGaze.engine.numInputChannels > 0 {
shoeGaze.inputSource = .liveInput(channel: 0)
}
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
@@ -114,14 +149,21 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
installMainMenu()
midi.start()
midi.onMapChanged = { [weak self] in
guard let self: AppDelegate = self else { return }
RigStore.save(self.shoeGaze)
}
let session: ShoeGaze = shoeGaze
let driver: CoreAudioDriver = coreDriver
let rigLibrary: RigLibraryStore = library
let midiController: MIDIController = midi
window.open {
ShoeGazeBuilderView(
shoeGaze: session,
library: rigLibrary,
hardwareSampleRate: { driver.deviceSampleRate }
hardwareSampleRate: { driver.deviceSampleRate },
midi: midiController
)
}
anchorWindowLeft()
@@ -154,6 +196,57 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
true
}
/// Opens `.shoegaze` files handed to the app by Finder, AirDrop, "Open With", or a double-click.
///
/// Rig documents are imported into the library (they appear in the sidebar, ready to load);
/// board documents are surfaced with a note that boards are opened from a rig's board editor.
func application(_ application: NSApplication, open urls: [URL]) {
for url: URL in urls {
openShoeGazeDocument(at: url)
}
}
/// Reads and imports a single `.shoegaze` document, reporting the outcome to the user.
private func openShoeGazeDocument(at url: URL) {
// A LaunchServices-supplied URL is security-scoped; start access to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let data: Data = try Data(contentsOf: url)
let document: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
if document.rigEntries?.isEmpty == false {
let added: Int = try library.importArchive(from: data)
presentOpenInfo(
title: added == 1 ? "Rig Imported" : "Rigs Imported",
message: added == 1
? "Added 1 rig to your library. Select it in the Rigs sidebar to load it."
: "Added \(added) rigs to your library. Select one in the Rigs sidebar to load it."
)
} else if document.boardVersion != nil {
presentOpenInfo(
title: "Board Document",
message: "This file is a single board. Open a rig, then load the board from the "
+ "board editor's Versions menu."
)
}
} catch {
presentOpenInfo(
title: "Couldn’t Open File",
message: "“\(url.lastPathComponent)” is not a readable ShoeGaze document."
)
print("[ShoeGazeBuilder] open document failed: \(error)")
}
}
/// Shows a one-button informational alert for a document-open outcome.
private func presentOpenInfo(title: String, message: String) {
let alert: NSAlert = NSAlert()
alert.messageText = title
alert.informativeText = message
alert.addButton(withTitle: "OK")
alert.runModal()
}
func applicationWillTerminate(_ notification: Notification) {
RigStore.save(shoeGaze)
// Ensure any in-flight background rig-library writes finish before exit.
@@ -217,6 +310,51 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// Engine start/stop lives in the in-window EngineConfigView (with sample-rate/channel
// config and the mismatch alert), so the Board menu only adds boards.
addItem(to: boardMenu, title: "Add Board", action: #selector(addBoardAction(_:)), key: "b")
boardMenu.addItem(NSMenuItem.separator())
// ⌘Z toggles rig mute (a hard silence of all output; distinct from Bypass Rig's dry
// passthrough). Owns the ⌘Z key equivalent on macOS; the in-window view binds it on iOS.
self.muteMenuItem = addItem(
to: boardMenu,
title: "Mute Rig",
action: #selector(toggleMuteAction(_:)),
key: "z"
)
// Bypass Rig routes every board to its dry input (pedals skipped) — distinct from Mute's
// hard silence. No key equivalent: ⌘B is Add Board, and Bypass has a prominent on-screen button.
self.bypassMenuItem = addItem(
to: boardMenu,
title: "Bypass Rig",
action: #selector(toggleBypassAction(_:)),
key: ""
)
// Rigs menu — a Set List of the top ten library rigs, each on ⌘⇧1…⌘⇧0. The items are
// fixed; their titles refresh to the current library order on open, and their key
// equivalents fire whether or not the menu is showing.
let rigsMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(rigsMenuItem)
let rigsMenu: NSMenu = NSMenu(title: "Rigs")
rigsMenuItem.submenu = rigsMenu
let setListItem: NSMenuItem = NSMenuItem(title: "Set List", action: nil, keyEquivalent: "")
rigsMenu.addItem(setListItem)
let setListSubmenu: NSMenu = NSMenu(title: "Set List")
setListSubmenu.delegate = self
setListItem.submenu = setListSubmenu
for slot: Int in 0 ..< AppDelegate.setListSlotCount {
// Slots 0…8 → ⌘⇧1…⌘⇧9; slot 9 → ⌘⇧0 (matches the physical number row).
let key: String = slot < 9 ? "\(slot + 1)" : "0"
let item: NSMenuItem = NSMenuItem(
title: "\(slot + 1). —",
action: #selector(loadRigSlotAction(_:)),
keyEquivalent: key
)
item.keyEquivalentModifierMask = [.command, .shift]
item.target = self
item.tag = slot
setListSubmenu.addItem(item)
setListMenuItems.append(item)
}
self.setListMenu = setListSubmenu
// Record menu — choose an output folder, then toggle recording.
let recordMenuItem: NSMenuItem = NSMenuItem()
@@ -237,6 +375,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
key: "R" // ⇧⌘R
)
// Help menu — opens the in-app guide.
let helpMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(helpMenuItem)
let helpMenu: NSMenu = NSMenu(title: "Help")
helpMenuItem.submenu = helpMenu
addItem(to: helpMenu, title: "ShoeGaze Help", action: #selector(showHelpAction(_:)), key: "?")
NSApplication.shared.mainMenu = mainMenu
}
@@ -256,6 +401,18 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Menu actions
/// Opens (or re-opens) the Help window hosting the shared ``HelpView``.
@objc private func showHelpAction(_ sender: Any?) {
let helpWidth: CGFloat = 560
let helpHeight: CGFloat = 720
if helpWindow == nil {
helpWindow = LyrebirdWindow(title: "ShoeGaze Help", width: helpWidth, height: helpHeight)
}
helpWindow?.open {
HelpView()
}
}
@objc private func newRigAction(_ sender: Any?) {
// Forward to the builder view, which owns the current-rig state and naming prompt.
NotificationCenter.default.post(name: .shoeGazeNewRig, object: nil)
@@ -267,20 +424,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
@objc private func exportArchiveAction(_ sender: Any?) {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.json]
panel.nameFieldStringValue = "\(AppDelegate.defaultArchiveFileName).json"
panel.allowedContentTypes = [.shoeGaze]
panel.nameFieldStringValue =
"\(AppDelegate.defaultArchiveFileName).\(ShoeGazeDocument.fileExtension)"
panel.canCreateDirectories = true
let rigLibrary: RigLibraryStore = library
panel.begin { response in
guard response == .OK, let url: URL = panel.url else { return }
do { try rigLibrary.exportArchiveData().write(to: url, options: .atomic) }
catch { print("[ShoeGazeBuilder] export archive failed: \(error)") }
do { try rigLibrary.exportDocumentData().write(to: url, options: .atomic) }
catch { print("[ShoeGazeBuilder] export library failed: \(error)") }
}
}
@objc private func importArchiveAction(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.json]
// Accept the .shoegaze document plus legacy plain-JSON archives.
panel.allowedContentTypes = [.shoeGaze, .json]
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
let rigLibrary: RigLibraryStore = library
@@ -290,11 +449,30 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
let data: Data = try Data(contentsOf: url)
_ = try rigLibrary.importArchive(from: data)
} catch {
print("[ShoeGazeBuilder] import archive failed: \(error)")
print("[ShoeGazeBuilder] import library failed: \(error)")
}
}
}
@objc private func toggleMuteAction(_ sender: Any?) {
shoeGaze.toggleRigMuted()
// Reflect the new state immediately, not only on the next menu-open validation.
muteMenuItem?.title = shoeGaze.rigMuted ? "Unmute Rig" : "Mute Rig"
muteMenuItem?.state = shoeGaze.rigMuted ? .on : .off
}
@objc private func toggleBypassAction(_ sender: Any?) {
shoeGaze.toggleRigBypassed()
bypassMenuItem?.title = shoeGaze.rigBypassed ? "Re-engage Rig" : "Bypass Rig"
bypassMenuItem?.state = shoeGaze.rigBypassed ? .on : .off
}
/// Loads the set-list rig at the sender's slot tag. Forwards to the in-window builder (which
/// owns the current-rig state, the unsaved-changes prompt, and engine lifecycle) via notification.
@objc private func loadRigSlotAction(_ sender: NSMenuItem) {
NotificationCenter.default.post(name: .shoeGazeLoadRigSlot, object: sender.tag)
}
@objc private func addBoardAction(_ sender: Any?) {
var created: PedalBoard?
do {
@@ -334,12 +512,45 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
recordMenuItem?.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording"
}
// MARK: - NSMenuDelegate
/// Refreshes the Set List item titles to the current library order each time the submenu opens.
/// Key equivalents fire independently of this (see `setListMenuItems`); this is display only.
func menuNeedsUpdate(_ menu: NSMenu) {
guard menu === setListMenu else { return }
let entries: [RigEntry] = library.entries
for item: NSMenuItem in setListMenuItems {
let slot: Int = item.tag
if slot < entries.count {
item.title = "\(slot + 1). \(entries[slot].name)"
} else {
item.title = "\(slot + 1). —"
}
}
}
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem == recordMenuItem {
menuItem.title = shoeGaze.isRecording ? "Stop Recording" : "Start Recording"
// Can always stop; can only start once a folder has been chosen.
return shoeGaze.isRecording || shoeGaze.recordingFolder != nil
}
if menuItem == muteMenuItem {
// Mute may have changed from the UI, MIDI, or the tuner — resync title + checkmark.
menuItem.title = shoeGaze.rigMuted ? "Unmute Rig" : "Mute Rig"
menuItem.state = shoeGaze.rigMuted ? .on : .off
return true
}
if menuItem == bypassMenuItem {
// Bypass may have changed from the UI or MIDI — resync title + checkmark.
menuItem.title = shoeGaze.rigBypassed ? "Re-engage Rig" : "Bypass Rig"
menuItem.state = shoeGaze.rigBypassed ? .on : .off
return true
}
if setListMenuItems.contains(menuItem) {
// A slot is live only when the library actually holds a rig at that position.
return menuItem.tag < library.entries.count
}
return true
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 782 B

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

After

Width:  |  Height:  |  Size: 200 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 643 KiB

+21 -21
View File
@@ -2,6 +2,21 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>ShoeGaze Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.realizedsound.shoegaze</string>
</array>
</dict>
</array>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
@@ -13,9 +28,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.2.0</string>
<string>${MARKETING_VERSION}</string>
<key>CFBundleVersion</key>
<string>1</string>
<string>${CURRENT_PROJECT_VERSION}</string>
<key>LSApplicationCategoryType</key>
<string>public.app-category.music</string>
<key>LSMinimumSystemVersion</key>
@@ -40,32 +55,17 @@
<string>Any</string>
</dict>
</dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>ShoeGaze Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.realizedsound.shoegaze</string>
</array>
</dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
@@ -14,6 +14,7 @@
C3C10000000000000000000D /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C10000000000000000001C /* LyrebirdUI */; };
C3C10000000000000000001D /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3C10000000000000000001E /* Lyrebird */; };
C3C100000000000000000031 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C3C100000000000000000030 /* Assets.xcassets */; };
C3C1000000000000000000B1 /* SplashView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C1000000000000000000B0 /* SplashView.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -22,6 +23,7 @@
C3C100000000000000000007 /* ShoeGazeBuilderiOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeBuilderiOSApp.swift; sourceTree = "<group>"; };
C3C100000000000000000008 /* ShoeGazeBuilderiOSAppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeBuilderiOSAppModel.swift; sourceTree = "<group>"; };
C3C100000000000000000030 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
C3C1000000000000000000B0 /* SplashView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SplashView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -60,6 +62,7 @@
children = (
C3C100000000000000000007 /* ShoeGazeBuilderiOSApp.swift */,
C3C100000000000000000008 /* ShoeGazeBuilderiOSAppModel.swift */,
C3C1000000000000000000B0 /* SplashView.swift */,
C3C100000000000000000030 /* Assets.xcassets */,
C3C100000000000000000006 /* Info.plist */,
);
@@ -100,7 +103,7 @@
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
LastUpgradeCheck = 2660;
TargetAttributes = {
C3C100000000000000000011 = {
CreatedOnToolsVersion = 16.0;
@@ -147,6 +150,7 @@
files = (
C3C100000000000000000009 /* ShoeGazeBuilderiOSApp.swift in Sources */,
C3C10000000000000000000A /* ShoeGazeBuilderiOSAppModel.swift in Sources */,
C3C1000000000000000000B1 /* SplashView.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -157,10 +161,12 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 8;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
@@ -169,7 +175,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
MARKETING_VERSION = 3.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -184,9 +190,11 @@
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = HE5VJFE9E4;
CURRENT_PROJECT_VERSION = 8;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
@@ -195,7 +203,7 @@
"$(inherited)",
"@executable_path/Frameworks",
);
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
MARKETING_VERSION = 3.0.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@@ -240,6 +248,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -302,6 +311,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : {
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
"version" : "1.2.0"
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
"version" : "1.2.3"
}
},
{
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
LastUpgradeVersion = "2660"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -31,7 +31,7 @@
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
Binary file not shown.

Before

Width:  |  Height:  |  Size: 402 KiB

After

Width:  |  Height:  |  Size: 643 KiB

@@ -0,0 +1,12 @@
{
"colors" : [
{
"idiom" : "universal",
"color" : {
"color-space" : "srgb",
"components" : { "red" : "0.080", "green" : "0.070", "blue" : "0.060", "alpha" : "1.000" }
}
}
],
"info" : { "author" : "xcode", "version" : 1 }
}
@@ -0,0 +1,8 @@
{
"images" : [
{ "idiom" : "universal", "filename" : "splashlogo.png", "scale" : "1x" },
{ "idiom" : "universal", "filename" : "splashlogo@2x.png", "scale" : "2x" },
{ "idiom" : "universal", "filename" : "splashlogo@3x.png", "scale" : "3x" }
],
"info" : { "author" : "xcode", "version" : 1 }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 420 KiB

+63 -55
View File
@@ -2,57 +2,6 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.2.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
<key>NSMicrophoneUsageDescription</key>
<string>ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<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>
@@ -68,17 +17,76 @@
</array>
</dict>
</array>
<!-- Incoming .shoegaze files are read and imported into the rig library (a copy), never
edited in place, so the app opens a copy rather than the original document. -->
<key>LSSupportsOpeningDocumentsInPlace</key>
<false/>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.4.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
<key>NSMicrophoneUsageDescription</key>
<string>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>
<false/>
</dict>
<key>UILaunchScreen</key>
<dict>
<key>UIColorName</key>
<string>LaunchBackground</string>
</dict>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<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,28 +13,37 @@ import LyrebirdShoeGazeUI
/// lifetime of the app. The audio engine is **not** started automatically — the user presses
/// Start in ``ShoeGazeBuilderView``. The engine is stopped when the view disappears.
///
/// ``ShoeGazeBuilderView`` manages its own scroll regions (palette + builder), so it is hosted
/// directly rather than wrapped in an outer `ScrollView`.
/// ``ShoeGazeBuilderView`` draws its own header/title and manages its own scroll regions (palette
/// + board canvas), so it is hosted directly — no `NavigationStack`, title, or outer `ScrollView`.
/// A fill frame keeps it pinned to the full window so portrait isn't vertically centered.
@main
struct ShoeGazeBuilderiOSApp: App {
@State private var model: ShoeGazeBuilderiOSAppModel = ShoeGazeBuilderiOSAppModel()
@State private var showSplash: Bool = true
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
NavigationStack {
ZStack {
ShoeGazeBuilderView(
shoeGaze: model.shoeGaze,
library: model.library,
hardwareSampleRate: { model.hardwareSampleRate },
onEnableLiveInput: { model.enableLiveInput() }
onEnableLiveInput: { model.enableLiveInput() },
midi: model.midi
)
.navigationTitle("ShoeGaze Builder")
.navigationBarTitleDisplayMode(.inline)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.task { await model.startLibrary() }
.onDisappear { model.stop() }
.onOpenURL { url in model.importDocument(at: url) }
if showSplash {
SplashView(isActive: $showSplash)
.transition(.opacity)
.zIndex(1)
}
}
.onDisappear { model.stop() }
}
.onChange(of: scenePhase) { _, phase in
// Persist the rig whenever the app leaves the foreground.
@@ -34,12 +34,6 @@ final class ShoeGazeBuilderiOSAppModel {
private static let numAudioBuses: Int = 256
private static let seedPedalType: PedalType = .overdrive
/// UserDefaults key persisting the input selection. Must match the key written by the
/// builder view (`ShoeGazeBuilderView.inputSelectionDefaultsKey`).
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
/// Persisted value meaning "live input, channel 0".
private static let liveInputChannelZeroTag: Int = 0
// MARK: - Owned objects
/// The active ShoeGaze builder session. Swapped out when live input is enabled (the engine
@@ -49,6 +43,10 @@ final class ShoeGazeBuilderiOSAppModel {
private var engine: SynthesisEngine
private var iosDriver: iOSAudioDriver
/// Foot-controller MIDI input. Owned here so it outlives the live-input engine rebuild; the
/// underlying Core MIDI client is engine-bound, so it is recreated against each new engine.
private(set) var midi: MIDIController
/// The shared rig library (iCloud-or-local). Independent of the engine, so it survives the
/// live-input engine rebuild.
private(set) var library: RigLibraryStore
@@ -83,6 +81,11 @@ final class ShoeGazeBuilderiOSAppModel {
// Construct the library instantly; it resolves iCloud + loads asynchronously via
// startLibrary() from the app's .task.
self.library = RigLibraryBootstrap.makeStore()
// Connect MIDI foot-controller input and begin listening for devices.
self.midi = MIDIController(engine: built.engine, shoeGaze: shoeGaze)
self.midi.start()
self.midi.onMapChanged = { [weak self] in self?.save() }
}
/// Persists the current rig. Call when the app moves to the background.
@@ -93,6 +96,25 @@ final class ShoeGazeBuilderiOSAppModel {
library.flushPendingWrites()
}
// MARK: - Document open
/// Imports a `.shoegaze` file opened from Files, AirDrop, or another app into the rig library.
/// Rig documents add their rigs (they appear in the sidebar, ready to load); board documents are
/// ignored here. Returns the number of rigs added.
@discardableResult
func importDocument(at url: URL) -> Int {
// A document opened from outside the sandbox is security-scoped; start access to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
do {
let data: Data = try Data(contentsOf: url)
return try library.importArchive(from: data)
} catch {
print("[ShoeGazeBuilderiOS] open document failed: \(error)")
return 0
}
}
// MARK: - Audio session / engine construction
/// Activates the play-and-record audio session once. Idempotent; safe to call before each
@@ -116,6 +138,8 @@ final class ShoeGazeBuilderiOSAppModel {
) -> (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) {
let sampleRate: Double = AVAudioSession.sharedInstance().sampleRate
let driver: iOSAudioDriver = iOSAudioDriver()
// The engine is built with the default layout; the autosaved rig's saved I/O (if any) is
// applied by `RigStore.restore`, so an output change survives relaunch.
let engine: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeBuilderiOSAppModel.blockSize,
sampleRate: sampleRate,
@@ -182,19 +206,24 @@ final class ShoeGazeBuilderiOSAppModel {
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
}
// The Core MIDI client is bound to the old engine — recreate it against the new one and
// point it at the rebuilt rig, preserving the "MIDI outlives the rebuild" contract.
midi.stop()
midi = MIDIController(engine: rebuilt.engine, shoeGaze: shoeGaze)
midi.start()
midi.onMapChanged = { [weak self] in self?.save() }
selectLiveInputAndPersist()
if wasRunning { try? engine.start() }
}
/// Selects live input on channel 0 and persists the choice for restore-on-relaunch.
/// Selects live input on channel 0 and autosaves so the rig (the source of truth for the input
/// selection) records it for restore-on-relaunch.
private func selectLiveInputAndPersist() {
do {
try shoeGaze.setInputSource(.liveInput(channel: 0))
UserDefaults.standard.set(
ShoeGazeBuilderiOSAppModel.liveInputChannelZeroTag,
forKey: ShoeGazeBuilderiOSAppModel.inputSelectionDefaultsKey
)
save()
} catch {
print("[ShoeGazeBuilderiOS] selecting live input failed: \(error)")
}
@@ -202,6 +231,11 @@ final class ShoeGazeBuilderiOSAppModel {
/// Seeds a single default board so the rig is never empty after a failed restore.
private static func seedFallbackBoard(into shoeGaze: ShoeGaze) {
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio.
// A restored rig keeps its own saved input selection.
if shoeGaze.engine.numInputChannels > 0 {
shoeGaze.inputSource = .liveInput(channel: 0)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
+82
View File
@@ -0,0 +1,82 @@
// SplashView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
/// Animated launch splash shown over the app on cold start.
///
/// The native launch screen (`UILaunchScreen` → `LaunchBackground`) paints an instant dark
/// backdrop with no visible jump; this view then fades and scales the ShoeGaze pedal logo in,
/// holds briefly, and fades the whole overlay away to reveal ``ShoeGazeBuilderView``. Colors match
/// the app background so the hand-off is seamless. Respects Reduce Motion by skipping the scale.
struct SplashView: View {
/// Background matching the builder's app background (`0.08, 0.07, 0.06`).
private static let backgroundColor: Color = Color(red: 0.08, green: 0.07, blue: 0.06)
private static let logoSize: CGFloat = 200
private static let logoCornerRadius: CGFloat = 44
private static let logoStartScale: CGFloat = 0.86
private static let wordmarkKerning: CGFloat = 4
private static let logoFadeInDuration: Double = 0.55
private static let wordmarkFadeInDelay: Double = 0.30
private static let wordmarkFadeInDuration: Double = 0.45
private static let holdDuration: Double = 0.85
private static let fadeOutDuration: Double = 0.45
@Environment(\.accessibilityReduceMotion) private var reduceMotion
/// Set false to fade the overlay out; parent removes it when the fade completes.
@Binding var isActive: Bool
@State private var logoOpacity: Double = 0
@State private var logoScale: CGFloat = SplashView.logoStartScale
@State private var wordmarkOpacity: Double = 0
var body: some View {
ZStack {
SplashView.backgroundColor
.ignoresSafeArea()
VStack(spacing: 22) {
Image("SplashLogo")
.resizable()
.scaledToFit()
.frame(width: SplashView.logoSize, height: SplashView.logoSize)
.clipShape(RoundedRectangle(cornerRadius: SplashView.logoCornerRadius,
style: .continuous))
.opacity(logoOpacity)
.scaleEffect(logoScale)
Text("ShoeGaze")
.font(.system(size: 34, weight: .semibold, design: .rounded))
.kerning(SplashView.wordmarkKerning)
.foregroundStyle(.white)
.opacity(wordmarkOpacity)
}
}
.onAppear { runSequence() }
}
private func runSequence() {
withAnimation(.easeOut(duration: SplashView.logoFadeInDuration)) {
logoOpacity = 1
if !reduceMotion { logoScale = 1 }
}
withAnimation(.easeOut(duration: SplashView.wordmarkFadeInDuration)
.delay(SplashView.wordmarkFadeInDelay)) {
wordmarkOpacity = 1
}
let holdUntil: Double = SplashView.logoFadeInDuration + SplashView.holdDuration
DispatchQueue.main.asyncAfter(deadline: .now() + holdUntil) {
withAnimation(.easeIn(duration: SplashView.fadeOutDuration)) {
isActive = false
}
}
}
}
-397
View File
@@ -1,397 +0,0 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 60;
objects = {
/* Begin PBXBuildFile section */
C3B000000000000000000020 /* LyrebirdShoeGaze in Frameworks */ = {isa = PBXBuildFile; productRef = C3B00000000000000000001E /* LyrebirdShoeGaze */; };
C3B000000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B00000000000000000001F /* LyrebirdShoeGazeUI */; };
C3B000000000000000000022 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3B000000000000000000023 /* Lyrebird */; };
C3B000000000000000000024 /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3B000000000000000000025 /* LyrebirdUI */; };
C3B000000000000000000031 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000030 /* Assets.xcassets */; };
C3B0000000000000000000C /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000007 /* main.swift */; };
C3B0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000008 /* AppDelegate.swift */; };
C3B0000000000000000000E /* DemoRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B000000000000000000009 /* DemoRootView.swift */; };
C3B0000000000000000000F /* ShoeGazeDemoController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3B00000000000000000000A /* ShoeGazeDemoController.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
C3B000000000000000000004 /* ShoeGazeDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ShoeGazeDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
C3B000000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
C3B000000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
C3B000000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
C3B000000000000000000009 /* DemoRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoRootView.swift; sourceTree = "<group>"; };
C3B00000000000000000000A /* ShoeGazeDemoController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeDemoController.swift; sourceTree = "<group>"; };
C3B000000000000000000030 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
C3B000000000000000000012 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
C3B000000000000000000020 /* LyrebirdShoeGaze in Frameworks */,
C3B000000000000000000021 /* LyrebirdShoeGazeUI in Frameworks */,
C3B000000000000000000022 /* Lyrebird in Frameworks */,
C3B000000000000000000024 /* LyrebirdUI in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
C3B000000000000000000002 = {
isa = PBXGroup;
children = (
C3B000000000000000000005 /* ShoeGazeDemo */,
C3B000000000000000000003 /* Products */,
);
sourceTree = "<group>";
};
C3B000000000000000000003 /* Products */ = {
isa = PBXGroup;
children = (
C3B000000000000000000004 /* ShoeGazeDemo.app */,
);
name = Products;
sourceTree = "<group>";
};
C3B000000000000000000005 /* ShoeGazeDemo */ = {
isa = PBXGroup;
children = (
C3B000000000000000000007 /* main.swift */,
C3B000000000000000000008 /* AppDelegate.swift */,
C3B000000000000000000009 /* DemoRootView.swift */,
C3B00000000000000000000A /* ShoeGazeDemoController.swift */,
C3B000000000000000000030 /* Assets.xcassets */,
C3B000000000000000000006 /* Info.plist */,
);
path = ShoeGazeDemo;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
C3B000000000000000000014 /* ShoeGazeDemo */ = {
isa = PBXNativeTarget;
buildConfigurationList = C3B000000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeDemo" */;
buildPhases = (
C3B000000000000000000011 /* Sources */,
C3B000000000000000000012 /* Frameworks */,
C3B000000000000000000013 /* Resources */,
);
buildRules = (
);
dependencies = (
);
name = ShoeGazeDemo;
packageProductDependencies = (
C3B00000000000000000001E /* LyrebirdShoeGaze */,
C3B00000000000000000001F /* LyrebirdShoeGazeUI */,
C3B000000000000000000023 /* Lyrebird */,
C3B000000000000000000025 /* LyrebirdUI */,
);
productName = ShoeGazeDemo;
productReference = C3B000000000000000000004 /* ShoeGazeDemo.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
C3B000000000000000000001 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
TargetAttributes = {
C3B000000000000000000014 = {
CreatedOnToolsVersion = 16.0;
};
};
};
buildConfigurationList = C3B000000000000000000018 /* Build configuration list for PBXProject "ShoeGazeDemo" */;
compatibilityVersion = "Xcode 14.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = C3B000000000000000000002;
packageReferences = (
C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */,
C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */,
);
productRefGroup = C3B000000000000000000003 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
C3B000000000000000000014 /* ShoeGazeDemo */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
C3B000000000000000000013 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3B000000000000000000031 /* Assets.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
C3B000000000000000000011 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
C3B0000000000000000000C /* main.swift in Sources */,
C3B0000000000000000000D /* AppDelegate.swift in Sources */,
C3B0000000000000000000E /* DemoRootView.swift in Sources */,
C3B0000000000000000000F /* ShoeGazeDemoController.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
C3B000000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Debug;
};
C3B000000000000000000017 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeDemo/ShoeGazeDemo.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeDemo/Info.plist;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 5.0;
};
name = Release;
};
C3B000000000000000000019 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
C3B00000000000000000001A /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_ENABLE_OBJC_WEAK = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu17;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
STRING_CATALOG_GENERATE_SYMBOLS = YES;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
C3B000000000000000000015 /* Build configuration list for PBXNativeTarget "ShoeGazeDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3B000000000000000000016 /* Debug */,
C3B000000000000000000017 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
C3B000000000000000000018 /* Build configuration list for PBXProject "ShoeGazeDemo" */ = {
isa = XCConfigurationList;
buildConfigurations = (
C3B000000000000000000019 /* Debug */,
C3B00000000000000000001A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCLocalSwiftPackageReference section */
C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */ = {
isa = XCLocalSwiftPackageReference;
relativePath = ..;
};
/* End XCLocalSwiftPackageReference section */
/* Begin XCRemoteSwiftPackageReference section */
C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 1.2.0;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
C3B00000000000000000001E /* LyrebirdShoeGaze */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGaze;
};
C3B00000000000000000001F /* LyrebirdShoeGazeUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001B /* XCLocalSwiftPackageReference ".." */;
productName = LyrebirdShoeGazeUI;
};
C3B000000000000000000023 /* Lyrebird */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = Lyrebird;
};
C3B000000000000000000025 /* LyrebirdUI */ = {
isa = XCSwiftPackageProductDependency;
package = C3B00000000000000000001C /* XCRemoteSwiftPackageReference "Lyrebird" */;
productName = LyrebirdUI;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = C3B000000000000000000001 /* Project object */;
}
@@ -1,78 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2620"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES"
buildArchitectures = "Automatic">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
shouldAutocreateTestPlan = "YES">
</TestAction>
<LaunchAction
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "C3B000000000000000000014"
BuildableName = "ShoeGazeDemo.app"
BlueprintName = "ShoeGazeDemo"
ReferencedContainer = "container:ShoeGazeDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
-153
View File
@@ -1,153 +0,0 @@
// AppDelegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
import LyrebirdShoeGazeUI
/// Application delegate for the ShoeGaze demo.
///
/// Creates a `SynthesisEngine`, a `ShoeGazeDemoController` (which builds the default
/// `.boards` showcase automatically), and opens a `LyrebirdWindow` hosting `DemoRootView`.
///
/// The engine is **not** started automatically. The user clicks Start in `DemoRootView`'s
/// toolbar (or presses Stop to halt audio). On application termination, `stop()` is called
/// to release Core Audio resources cleanly.
@MainActor
final class AppDelegate: NSObject, NSApplicationDelegate {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let sampleRate: Double = 48_000.0
private static let outputChannels: Int = 2
// Built-in mics are mono; default to one input channel so live input works out of the box
// (CoreAudio can't satisfy more input channels than the device provides). Raise in the UI.
private static let inputChannels: Int = 1
private static let numAudioBuses: Int = 256
// MARK: - Window geometry constants
private static let windowWidth: CGFloat = 1_100
private static let windowHeight: CGFloat = 640
// MARK: - Owned objects
private let coreDriver: CoreAudioDriver
private let controller: ShoeGazeDemoController
private let window: LyrebirdWindow
/// The Mute menu item, retained so `validateMenuItem(_:)` can update its checkmark.
private var muteMenuItem: NSMenuItem?
// MARK: - Init
override init() {
let coreDriver: CoreAudioDriver = CoreAudioDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: AppDelegate.blockSize,
sampleRate: AppDelegate.sampleRate,
numOutputChannels: AppDelegate.outputChannels,
numInputChannels: AppDelegate.inputChannels,
numAudioBuses: AppDelegate.numAudioBuses,
driver: coreDriver
)
self.coreDriver = coreDriver
self.controller = ShoeGazeDemoController(engine: engine)
self.window = LyrebirdWindow(
title: "ShoeGaze — Lyrebird Guitar Pedalboard",
width: AppDelegate.windowWidth,
height: AppDelegate.windowHeight
)
super.init()
}
// MARK: - NSApplicationDelegate
func applicationDidFinishLaunching(_ notification: Notification) {
installMainMenu()
let demoController: ShoeGazeDemoController = controller
let driver: CoreAudioDriver = coreDriver
window.open {
DemoRootView(controller: demoController, hardwareSampleRate: { driver.deviceSampleRate })
}
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
func applicationWillTerminate(_ notification: Notification) {
controller.stop()
}
// MARK: - Main menu
/// Builds the app's menu bar: an application menu (About / Hide / Quit ⌘Q) and an
/// Audio menu (Mute ⌘M). Standard items route through the responder chain to
/// `NSApplication`; Mute targets this delegate.
private func installMainMenu() {
let appName: String = ProcessInfo.processInfo.processName
let mainMenu: NSMenu = NSMenu()
// Application menu.
let appMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(appMenuItem)
let appMenu: NSMenu = NSMenu()
appMenuItem.submenu = appMenu
appMenu.addItem(
withTitle: "About \(appName)",
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
keyEquivalent: ""
)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(
withTitle: "Hide \(appName)",
action: #selector(NSApplication.hide(_:)),
keyEquivalent: "h"
)
appMenu.addItem(NSMenuItem.separator())
appMenu.addItem(
withTitle: "Quit \(appName)",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"
)
// Audio menu.
let audioMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(audioMenuItem)
let audioMenu: NSMenu = NSMenu(title: "Audio")
audioMenuItem.submenu = audioMenu
let mute: NSMenuItem = NSMenuItem(
title: "Mute",
action: #selector(toggleMute(_:)),
keyEquivalent: "m"
)
mute.target = self
audioMenu.addItem(mute)
muteMenuItem = mute
NSApplication.shared.mainMenu = mainMenu
}
/// Toggles audio output (mute). Bound to the Audio ▸ Mute menu item (⌘M).
@objc private func toggleMute(_ sender: Any?) {
controller.toggleMute()
}
/// Shows a checkmark on the Mute item while audio is silenced (engine not running).
func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
if menuItem == muteMenuItem {
menuItem.state = controller.isRunning ? .off : .on
}
return true
}
}
#endif
@@ -1,15 +0,0 @@
{
"images" : [
{"size":"16x16","idiom":"mac","filename":"icon_16x16.png","scale":"1x"},
{"size":"16x16","idiom":"mac","filename":"icon_16x16@2x.png","scale":"2x"},
{"size":"32x32","idiom":"mac","filename":"icon_32x32.png","scale":"1x"},
{"size":"32x32","idiom":"mac","filename":"icon_32x32@2x.png","scale":"2x"},
{"size":"128x128","idiom":"mac","filename":"icon_128x128.png","scale":"1x"},
{"size":"128x128","idiom":"mac","filename":"icon_128x128@2x.png","scale":"2x"},
{"size":"256x256","idiom":"mac","filename":"icon_256x256.png","scale":"1x"},
{"size":"256x256","idiom":"mac","filename":"icon_256x256@2x.png","scale":"2x"},
{"size":"512x512","idiom":"mac","filename":"icon_512x512.png","scale":"1x"},
{"size":"512x512","idiom":"mac","filename":"icon_512x512@2x.png","scale":"2x"}
],
"info" : {"author":"xcode","version":1}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 782 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 345 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

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

Before

Width:  |  Height:  |  Size: 402 KiB

@@ -1 +0,0 @@
{ "info" : {"author":"xcode","version":1} }
-84
View File
@@ -1,84 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSHumanReadableCopyright</key>
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
<key>NSMicrophoneUsageDescription</key>
<string>ShoeGazeiOSDemo can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
<key>UIApplicationSceneManifest</key>
<dict>
<key>UIApplicationSupportsMultipleScenes</key>
<false/>
</dict>
<key>UILaunchScreen</key>
<dict/>
<key>UIRequiresFullScreen</key>
<true/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key>
<string>ShoeGaze Document</string>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>LSHandlerRank</key>
<string>Owner</string>
<key>LSItemContentTypes</key>
<array>
<string>net.realizedsound.shoegaze</string>
</array>
</dict>
</array>
<key>UTExportedTypeDeclarations</key>
<array>
<dict>
<key>UTTypeIdentifier</key>
<string>net.realizedsound.shoegaze</string>
<key>UTTypeDescription</key>
<string>ShoeGaze Document</string>
<key>UTTypeConformsTo</key>
<array>
<string>public.json</string>
</array>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>shoegaze</string>
</array>
<key>public.mime-type</key>
<array>
<string>application/json</string>
</array>
</dict>
</dict>
</array>
</dict>
</plist>
@@ -1,33 +0,0 @@
// ShoeGazeiOSDemoApp.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGazeUI
/// iOS entry point for the ShoeGaze in-repo demo.
///
/// Holds the `ShoeGazeiOSDemoAppModel` as `@State` so it is created once and
/// owned for the lifetime of the app. The audio engine is **not** started
/// automatically — the user presses Start in the pedalboard (`ShoeGazeView`) to
/// begin audio. The engine is stopped when the view disappears.
@main
struct ShoeGazeiOSDemoApp: App {
@State private var model: ShoeGazeiOSDemoAppModel = ShoeGazeiOSDemoAppModel()
var body: some Scene {
WindowGroup {
NavigationStack {
ScrollView {
ShoeGazeView(shoeGaze: model.shoeGaze, hardwareSampleRate: { model.hardwareSampleRate })
.padding(.horizontal, 12)
}
.navigationTitle("ShoeGaze")
}
.onDisappear { model.stop() }
}
}
}
@@ -1,103 +0,0 @@
// ShoeGazeiOSDemoAppModel.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import AVFoundation
import Observation
import LyrebirdSynth
import LyrebirdShoeGaze
/// Observable model that owns the `SynthesisEngine` and `ShoeGaze` session for
/// the ShoeGaze iOS demo.
///
/// The engine is not started automatically — the pedalboard's Start button
/// (`ShoeGazeView`) drives `engine.start()`. `stop()` is called from `.onDisappear`
/// to release audio resources when the view goes away.
///
/// `AVAudioSession` is activated at init so the hardware sample rate is known
/// before the engine is constructed — iOS devices typically lock to 48 000 Hz
/// regardless of the preferred rate, and querying the session after activation
/// avoids pitch and timing errors.
///
/// The default board (Overdrive → Delay → Reverb → Modulation) uses `.testLoop`
/// as the input source, so no microphone permission is required to run the demo.
/// Switch to `.liveInput(channel: 0)` and set `numInputChannels: 1` in the
/// engine init to route hardware microphone or instrument input through the board.
@Observable
@MainActor
final class ShoeGazeiOSDemoAppModel {
// MARK: - Engine configuration constants
private static let blockSize: Int = 512
private static let outputChannels: Int = 2
private static let numAudioBuses: Int = 256
// MARK: - Owned objects
/// The active ShoeGaze pedalboard session.
private(set) var shoeGaze: ShoeGaze
private let engine: SynthesisEngine
private let iosDriver: iOSAudioDriver
/// The sample rate the audio session actually committed to (for the config mismatch warning).
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
// MARK: - Init
init() {
// Activate the session before querying `sampleRate` so the hardware rate
// is reported correctly (iOS locks to 48 000 Hz on most devices).
let session: AVAudioSession = AVAudioSession.sharedInstance()
try? session.setCategory(.playAndRecord,
mode: .default,
options: [.defaultToSpeaker, .allowBluetoothHFP])
try? session.setActive(true)
let sampleRate: Double = session.sampleRate
let driver: iOSAudioDriver = iOSAudioDriver()
let eng: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeiOSDemoAppModel.blockSize,
sampleRate: sampleRate,
numOutputChannels: ShoeGazeiOSDemoAppModel.outputChannels,
numInputChannels: 0,
numAudioBuses: ShoeGazeiOSDemoAppModel.numAudioBuses,
driver: driver
)
self.iosDriver = driver
self.engine = eng
self.shoeGaze = ShoeGaze(engine: eng)
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Demo Board"
try board.add(OverdrivePedal())
try board.add(DelayPedal())
try board.add(ReverbPedal())
try board.add(ModulationPedal())
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeiOSDemo] board build failed: \(error)")
}
}
// MARK: - Transport
/// Starts the audio engine. Not called automatically — the pedalboard's Start
/// button drives `engine.start()`; this is here for callers that want to start it.
func start() {
do {
try engine.start()
} catch {
print("[ShoeGazeiOSDemo] engine.start() failed: \(error)")
}
}
/// Stops the audio engine. Call from `.onDisappear`.
func stop() {
engine.stop()
}
}
+3 -3
View File
@@ -1,5 +1,5 @@
{
"originHash" : "b8327204b102b429067129b94b6ba77dcfa78570af3b9d11cae4d7eb252e388c",
"originHash" : "eed06b1870eecb6b28d2417331f105ea1cc25e9d6fe588c9d2eff8ca3af096f0",
"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" : "77580ee98e05cb4a94aac367097d27b91d3776c0",
"version" : "1.7.2"
}
},
{
+5 -3
View File
@@ -11,8 +11,9 @@
// double-registration. The dynamic-product dance used by `LiveCompile/` is only
// required for runtime dylib hot-swap, which ShoeGaze does not do.
//
// The demo app lives at Demo/ShoeGazeDemo.xcodeproj — open ShoeGaze.xcworkspace
// in Xcode and run the ShoeGazeDemo scheme to build it.
// The apps live at Demo/ShoeGazeBuilder.xcodeproj (macOS) and
// Demo/ShoeGazeBuilderiOS.xcodeproj (iPad) — open ShoeGaze.xcworkspace in Xcode
// and run the matching scheme to build them.
import PackageDescription
let package = Package(
@@ -23,7 +24,7 @@ let package = Package(
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
],
dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.0"),
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.7.2"),
],
targets: [
// The core target depends on LyrebirdUI as well as the synthesis core:
@@ -51,6 +52,7 @@ let package = Package(
name: "LyrebirdShoeGazeTests",
dependencies: [
"LyrebirdShoeGaze",
"LyrebirdShoeGazeUI",
.product(name: "Lyrebird", package: "Lyrebird"),
.product(name: "LyrebirdUI", package: "Lyrebird"),
],
+21 -11
View File
@@ -11,17 +11,25 @@ signal (no hardware needed) or on live guitar through an audio input.
## Features
- **22 modeled pedals** across drive, dynamics, EQ/filter, modulation, delay/reverb, and
pitch — see the catalog below.
- **36 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and
texture — see the catalog below.
- **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel
style) or **Blend** any subset, each with its own level and a click-free crossfade.
style) or **Blend** any subset, each with its own level and a click-free crossfade, plus a
rig-wide **output volume and mute** on top.
- **MIDI foot-controller support** — map footswitches (Program Change) to bypass/mute/solo
toggles, and expression pedals (Control Change) to any knob, board level, or the rig-wide
volume, with per-binding invert for crossfades. MIDI Learn, one binding per rig.
- **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or
stereo lanes, and merge back to mono.
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across
your devices and both apps via iCloud, with JSON archive import/export for backup.
your devices and both apps via iCloud.
- **Sharing** — send a rig or a saved board to anyone as a `.shoegaze` file via the system share
sheet (AirDrop, Mail, Messages, Files); export/import the whole library the same way.
- **Recording** — capture your output to timestamped files.
- **Test signal or live input** — a built-in arpeggiated test loop (shared across all boards so
they stay phase-locked) or a hardware input channel.
- **In-app Help** — setup, rigs/boards, saving, iCloud, and MIDI control, from the macOS Help
menu or an iOS help button.
- **SwiftUI views** — a complete stompbox UI (`LyrebirdShoeGazeUI`) or just the headless
framework (`LyrebirdShoeGaze`) to drive your own interface.
@@ -29,11 +37,14 @@ signal (no hardware needed) or on live guitar through an audio input.
| Category | Pedals |
|---|---|
| Drive & dynamics | Overdrive, Fuzz, Compressor, Sustainer, Limiter, Noise Gate |
| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Phaser |
| Modulation | Tremolo, Modulation, Chorus, Ring Modulator, Diffuser |
| Delay & reverb | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverb |
| Pitch & octave | Octave Splitter, Bass Octaver |
| Gain | Overdrive, Distortion, Fuzz |
| Dynamics | Compressor, Sustainer, Limiter, Noise Gate |
| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Cabinet |
| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Rotary, Ring Modulator |
| Pitch | Bass Octaver, Octave Splitter, Harmonizer |
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay |
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb |
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator |
Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format.
@@ -94,12 +105,11 @@ struct ContentView: View {
}
```
## Demo apps
## Apps
Open `ShoeGaze.xcworkspace` in Xcode and run a scheme from `Demo/`:
- **ShoeGazeBuilder** (macOS) / **ShoeGazeBuilderiOS** (iPad) — the full palette + board builder.
- **ShoeGazeDemo** / **ShoeGazeiOSDemo** — a minimal player view.
## Screenshots
+203
View File
@@ -1,4 +1,207 @@
# Releases
## ShoeGaze 2.1.3
A tuner fix. Engaging the chromatic tuner could crackle or pop through the output — even
with "Mute while tuning" on — until you played a steady note.
### Fixed
- **Tuner no longer leaks into the output.** The pitch-detection stage was written to an
audio output bus instead of its internal analysis bus, so the tracked frequency was
summed onto an output channel — bypassing the rig mute and crackling while the pitch was
unstable (it stopped once a note locked). The tuner now writes only to its analysis bus.
## ShoeGaze 2.1.1
A quieter, more predictable startup. The signal feeding the pedals now has its own mute
that arms every time you start the engine, new rigs open listening to your instrument,
and your input and I/O settings travel with the rig instead of a local-only setting.
### Highlights
- **Input mute** — a hard kill-switch on the incoming guitar / mic signal, separate from
the rig-output mute. Arms automatically on every Start (silent until you're ready),
sits by the Start/Stop transport with a pulsing red glow while active, and is
MIDI-mappable like Rig Mute. A muted input is exactly silent from the first sample.
- **Opens on In 0** — new rigs listen to live input instead of the test-loop phrase.
- **Input & I/O persist with the rig** — the input selection and engine input/output
channel counts are stored in the rig (and iCloud) and reapplied on launch, so a
multi-channel setup and a chosen input survive a restart. Replaces the old local-only
input setting.
- **Tidier transport** — the docked macOS Bypass / Mute / Input toggles are icons so the
row no longer crowds the rate and channel controls.
### Compatibility
Additive: rigs saved before this release load unchanged, and 2.1.1 rigs still open in
older builds (input-mute state isn't persisted; the extra I/O fields are ignored there).
## ShoeGaze 2.1.0
Tempo comes to the pedals. Delay times and LFO rates can lock to note divisions of the
live tempo — shown with real music-notation glyphs and following the tempo as it
changes — plus a directly-editable BPM, longer delays, and per-control MIDI/key mapping
badges on every pedal.
### Highlights
- **Tempo-synced parameters** — lock a delay time or a modulation rate to a note value
(whole → sixteenth, dotted, triplet); it follows tap tempo, the stepper, the BPM
field, and MIDI. Delay, Feedback Delay, Ping-Pong, Reverse, and Multi-Tap (per tap);
Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
- **Notation glyphs** — the picker draws real note glyphs (augmentation dot for dotted
values, a bracketed "3" over triplets) instead of text.
- **Editable BPM** — type a tempo directly (integer, 30–300); the stepper and tap still
work, and synced pedals follow immediately.
- **Longer delays** — maximum delay time raised to 5 s so slow synced values fit.
- **Control mapping badges** — every pedal shows the PC (footswitch), CC (expression),
or KEY (letter key) binding on each control, with a legend above the board.
- **CC respects tempo sync** — a CC bound to a synced parameter is ignored while synced
(the tempo drives it) and resumes control once the parameter is set back to Free.
### Compatibility
Additive persistence — older rigs load unchanged (every parameter defaults to free),
and 2.1 rigs open in older builds with the tempo-sync state ignored.
## ShoeGaze 2.0.0
Major release. Performance-focused: a visual metronome, a real rig mute with
keyboard control, and rigs that remember their tempo, input, and I/O — plus a
saveable set-list order for hands-free switching between rigs live. The version
jumps to 2.0.0 to align ShoeGaze's numbering with the wider project family.
### Highlights
- **Visual metronome** — a horizontal playhead eases wall-to-wall each beat so you
can anticipate the downbeat, replacing the old flashing LED.
- **Rig Mute (⌘Z)** — hard-silences the whole rig; distinct from Bypass Rig (dry passthrough).
- **Keyboard shortcuts** — ⌘1–⌘9 switch/solo boards, ⌘⇧1–⌘⇧0 load set-list rigs 1–10,
⌘Z mutes. macOS menus + iOS/iPadOS hardware keyboards.
- **Set lists** — reorder rigs by drag or Move Up/Down; the order saves, travels with
an exported archive, and drives the ⌘⇧ slots.
- **Per-rig memory** — tempo, input selection, and engine I/O now persist with a rig.
### Fixed
- Archive import no longer collides set-list positions with existing rigs.
### Removed
- The ShoeGazeDemo / ShoeGazeiOSDemo apps — only the ShoeGazeBuilder (macOS) and
ShoeGazeBuilderiOS (iPad) apps remain.
**Compatibility:** rig persistence is additive — older rigs load unchanged, and 2.0.0
rigs still open in older builds. The bump reflects feature scope + version alignment,
not a format break.
## 1.5.0 — 2026-07-04
### New Looper pedal (catalog now 36)
- **Multitrack looper** with a smart Loop footswitch (record → overdub → play), up to four
tracks (A/B/C/D), per-track mute via the track dots, undo, reverse, and a timeline view.
- **Beat-quantized transport** with a **Sync / Free** mode toggle; stop and cue-stop honour the
loop boundary in Sync. Clean-through and a Playback balance let the dry signal pass while
looped layers play back.
- **MIDI-mappable** transport (record/play/stop), per-track A/B/C/D taps, and the Sync toggle.
- Stomp-style **Reset** button that also fires on engine stop and rig teardown; `effect()` is
idempotent across graph rebuilds, and the multitrack engine is RT-safe (findings from review
addressed, with regression coverage for record-after-reset).
### iPad / iOS layout rework
- **Canvas-first compact layout** — composition panels move into sheets so the pedal canvas
fills the screen; the sheet-based layout is now used at every size class (no forced min width).
- **Header compaction** — performance controls sit inline right of the title; rig controls group
with Tempo/Tuner; the scope drops to a full-width strip below the rows in portrait. Fixes
Tempo/Tuner truncation, Mute-toggle expansion, mixer overflow into the CPU meters, and portrait
clipping/centering.
- **Add-Pedal sheet** is a scrollable list with a fixed header and type filter at a stable size;
fixed compact sheets that failed to present (one sheet per view node).
### Dependency
- Bumped to **Lyrebird 1.2.3**. Lyrebird now ships framework-neutral project templates only —
its ShoeGaze-specific CLI scaffolding was removed, since ShoeGaze lives in this standalone repo.
### Fixes
- A transport-only **Start** no longer reverts Settings configuration (external-review fix).
- Dropped a stale doc and a dead `looperTimeline` property.
## 1.4.0 — 2026-07-01
### MIDI foot-controller support
- **Program Change switches** — map a footswitch to Rig Bypass, Rig Mute, All Boards On, board
Solo/Audible/Bypass, or any pedal's Bypass. MIDI Learn captures the incoming program number;
one Program Change can drive **multiple actions at once** ("scenes").
- **Control Change (expression pedal) mapping** — bind a CC to any pedal knob/slider, a board's
master level, or the new rig-wide output volume. Per-binding **invert**, so one expression
pedal can crossfade two controls in opposite directions.
- Bindings are per-rig, travel with the saved rig file, and decode resiliently — an
incompatible/malformed MIDI map drops just the bindings (re-learnable) rather than the whole
rig.
- New **MIDI Mapping** sheet (from the transport row) lists every switch/expression target with
live Learn / Clear / Invert controls, plus a connected-device list.
### Rig-wide output volume + mute
- New **Volume** slider and **Mute** button in the board-mixer bar, alongside Solo / Blend / All
and Crossfade — applies after every board's output, independent of per-board levels.
- Mute is a hard output gate, distinct from the existing dry-signal Bypass. Both volume and mute
are MIDI-mappable (CC for volume, Program Change for mute) and click-free (lagged).
### New reverb pedals (catalog now 35)
- **Plate Reverb** — dense, bright metallic-plate character (Decay / Tone / Damp / Mod).
- **Room Reverb** — natural room/hall ambience (Size / Decay / Damp / Tail).
- **Spring Reverb** — classic amp-tank boing and drip (Decay / Tension / Damp).
### In-app Help
- New **Help** view covering setup & starting the engine, input sources, boards & rigs, saving &
autosave, iCloud documents, and MIDI control — reachable from the macOS **Help menu** and an
iOS help button.
### Fixes
- Fixed a rig-library bug where the sidebar's highlighted rig could disagree with the actually
loaded pedal graph after a restart — the current rig id and its saved state now live in one
atomic autosave file instead of two files that could drift apart.
- The whole rig-library sidebar row is now tappable, not just its text label.
## 1.3.0 — 2026-06-28
### Sharing — the `.shoegaze` document type
- New shareable file type **`.shoegaze`** (`net.realizedsound.shoegaze`, conforming to
`public.json`) registered by every app, so the system associates the file with ShoeGaze for
Open and Share.
- **Share a rig** from the library sidebar (per-rig) and **share a saved board** from the board
editor's Versions menu, via the OS share sheet — AirDrop, Mail, Messages, Files. Local only; no
account or backend.
- Library **export/import migrated** to `.shoegaze`. A document wraps either a whole rig (or many)
or a single board; legacy archive and single-rig JSON files still import.
- Internal per-rig and board-version files stay app-private JSON — only the share/export surface
uses `.shoegaze`.
## 1.2.0 — 2026-06-28
### New pedals (catalog now 32)
- **Distortion** — mid-gain saturation between Overdrive and Fuzz.
- **Flanger** — sweeping comb-filter jet with feedback.
- **Vibrato** — pure pitch wobble, fully wet.
- **Rotary** — Leslie rotary-speaker: Doppler wobble + volume throb, two-speed with accel ramp.
- **Harmonizer** — two pitch-shifted harmony voices at fixed musical intervals (stepped knob).
- **Reverse Delay** — backward-tape segments with feedback trails.
- **Shimmer Reverb** — regenerative reverb whose tail climbs an octave as it sustains.
- **Bitcrusher** — sample-rate decimation + bit-depth reduction + tone.
- **Granulator** — stereo grain cloud, scattered across the field by Spread.
- **Auto Granulator** — granulator whose grain size tracks your dynamics (Response switch).
### Rig library (iCloud)
- Rigs are a managed **library** in the sidebar (New, Save, Save As, Duplicate, Rename, Delete,
Erase All), each holding multiple boards.
- **iCloud sync** across devices and both apps via a shared container, with a local fallback.
- **Archive** import/export bundles the whole library as one hand-editable JSON file (replaced the
old single-rig save/load); legacy single-rig files still import.
- macOS File menu: New Rig (⌘N), Save Rig (⌘S), Export / Import Archive (⌘E / ⌘I). Saves/loads run
off the main thread.
### Builder UI
- Reworked top layout (scope + CPU beside a stacked board-mixer / pedal-picker); **colour-coded**
pedal cards with a **filter-by-type** menu; routing cards in their own row.
- Dark color scheme pinned (fixes black-on-dark system controls on iOS); input-source picker
reflects the In channel count immediately; failed edits surface as alerts.
### Fixes / under the hood
- Granulators are now latency-free; Shimmer Reverb DC-blocked. New RT-safe generators
(`ReverseDelay`, `SampleRateDecimate`, `BitReduce`, `ShimmerReverb`, `StereoGranulator`) and a
reusable `PedalSelectorKnob`. 271 tests; RT-safety reviewed.
## 1.1.1 — 2026-06-26
-6
View File
@@ -4,12 +4,6 @@
<FileRef
location = "group:.">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeiOSDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Demo/ShoeGazeBuilder.xcodeproj">
</FileRef>
@@ -1,5 +1,5 @@
{
"originHash" : "cfdd71f4b32d744c862bbe26a8265d75aa9e906275b0fb1b63575b7d68be1b6a",
"originHash" : "9ce521e7cebf3eed8e20837aba069e3f0c5484a64130b1791e8e6fdb7874b9f0",
"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" : "77580ee98e05cb4a94aac367097d27b91d3776c0",
"version" : "1.7.2"
}
},
{
@@ -28,6 +28,14 @@ final class BoardOutputMaster: SynthesizerBase {
/// Defaults to a short 20 ms so normal use is click-free; raise it for a slow crossfade.
@UIParam var crossfadeTime: Double = 0.02
/// Per-board full-bypass state. `0` = board engaged (processed output), `1` = bypassed
/// (dry input passes straight through, skipping every pedal). Smoothed by `bypassLagTime`.
@UIParam var boardBypass: Double = 0.0
/// Rig-wide full-bypass state, driven across every board at once. `0` = engaged,
/// `1` = bypassed (dry). Independent of `boardBypass`; either engaged routes to dry.
@UIParam var rigBypass: Double = 0.0
/// The live `UIParamNode` backing `masterGain`, exposed so the board (and its UI)
/// can bind a master-volume knob to this stage.
var gainNode: UIParamNode { $masterGain }
@@ -38,6 +46,26 @@ final class BoardOutputMaster: SynthesizerBase {
/// The live `UIParamNode` backing `crossfadeTime` (board crossfade seconds).
var crossfadeTimeNode: UIParamNode { $crossfadeTime }
/// The live `UIParamNode` backing `boardBypass` (per-board full bypass).
var boardBypassNode: UIParamNode { $boardBypass }
/// The live `UIParamNode` backing `rigBypass` (rig-wide full bypass).
var rigBypassNode: UIParamNode { $rigBypass }
/// Rig-wide output volume in [0, 1], applied to the final output. Driven across every board by
/// `ShoeGaze.setRigVolume(_:)`. Defaults to `1` (unity).
@UIParam var rigVolume: Double = 1.0
/// Rig-wide output mute — `0` = audible, `1` = silenced (a hard gate, not a dry bypass). Driven
/// across every board by `ShoeGaze.setRigMuted(_:)`. Defaults to `0`.
@UIParam var rigMute: Double = 0.0
/// The live `UIParamNode` backing `rigVolume` (rig-wide output volume).
var rigVolumeNode: UIParamNode { $rigVolume }
/// The live `UIParamNode` backing `rigMute` (rig-wide output mute).
var rigMuteNode: UIParamNode { $rigMute }
// MARK: - Routing
/// Left / mono board output bus index.
@@ -48,11 +76,23 @@ final class BoardOutputMaster: SynthesizerBase {
/// bypassing the mono `Pan2` spread.
private let boardOutputBusRightIndex: Int?
/// The board's dry head-bus index (the mono input feeding the first pedal). Read as the
/// bypass source so a bypassed board passes its untouched input straight through.
private let dryInputBusIndex: Int
// MARK: - Constants
/// Pan position for the board in the stereo field. Centre = 0.0. Used only for a mono board.
private let stereoPan: Double = 0.0
/// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed
/// transitions to prevent clicks. Matches the per-pedal bypass lag.
private let bypassLagTime: Double = 0.02
/// Remaps a `[0, 1]` bypass value to CrossFade's `[-1, +1]` equal-power pan.
private let bipolarSpan: Double = 2.0
private let bipolarOffset: Double = 1.0
// MARK: - Init
/// Creates a board output master.
@@ -61,9 +101,11 @@ final class BoardOutputMaster: SynthesizerBase {
/// - boardOutputBusIndex: Left / mono board output bus index.
/// - boardOutputBusRightIndex: Right board output bus index for a stereo (width-2) board,
/// or `nil` for a mono board (the signal is panned to centre instead).
init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil) {
/// - dryInputBusIndex: The board's head-bus index, read as the dry bypass source.
init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil, dryInputBusIndex: Int) {
self.boardOutputBusIndex = boardOutputBusIndex
self.boardOutputBusRightIndex = boardOutputBusRightIndex
self.dryInputBusIndex = dryInputBusIndex
super.init()
}
@@ -74,13 +116,24 @@ final class BoardOutputMaster: SynthesizerBase {
// seconds rather than clicking. The user master-gain knob is applied directly.
let smoothedSelect: Lag.Control = Lag.Control(input: $selectGain, time: $crossfadeTime)
// Rig-wide output volume × mute, shared across both channels (like `smoothedSelect`).
let rigOutputGain: any ValidGeneratorInput = rigOutputGainStage()
// The dry input tap — read once, used as the bypass source for both channels (the head
// bus is mono, so a bypassed stereo board passes the same dry signal to both sides).
let dry: In.Audio = input(bus: dryInputBusIndex)
let boardOutLeft: In.Audio = input(bus: boardOutputBusIndex)
let gainedLeft: any ValidGeneratorInput = (boardOutLeft * smoothedSelect) * $masterGain
let switchedLeft: any ValidGeneratorInput = applyBypass(wet: boardOutLeft, dry: dry)
let gainedLeft: any ValidGeneratorInput =
((switchedLeft * smoothedSelect) * $masterGain) * rigOutputGain
if let rightIndex: Int = boardOutputBusRightIndex {
// Stereo board: left tail → hardware 0, right tail → hardware 1, no pan spread.
let boardOutRight: In.Audio = input(bus: rightIndex)
let gainedRight: any ValidGeneratorInput = (boardOutRight * smoothedSelect) * $masterGain
let switchedRight: any ValidGeneratorInput = applyBypass(wet: boardOutRight, dry: dry)
let gainedRight: any ValidGeneratorInput =
((switchedRight * smoothedSelect) * $masterGain) * rigOutputGain
output(bus: 0, source: gainedLeft)
output(bus: 1, source: gainedRight)
} else {
@@ -88,4 +141,30 @@ final class BoardOutputMaster: SynthesizerBase {
output(bus: 0, source: Pan2(input: gainedLeft, pan: stereoPan))
}
}
/// Rig-wide output gain: the smoothed rig volume gated by the smoothed mute. Mute `0` → gain 1
/// (audible), mute `1` → gain 0 (silent). Both lagged to avoid clicks.
private func rigOutputGainStage() -> any ValidGeneratorInput {
let rigVol: Lag.Control = Lag.Control(input: $rigVolume, time: bypassLagTime)
let muteLagged: Lag.Control = Lag.Control(input: $rigMute, time: bypassLagTime)
// (mute − 1) × −1 ⇒ 0→1, 1→0, using only generator−scalar and generator×scalar.
let muteGain: any ValidGeneratorInput = (muteLagged - 1.0) * -1.0
return rigVol * muteGain
}
/// Routes `wet` to `dry` when either the per-board or rig-wide bypass is engaged. Two cascaded
/// equal-power crossfades (each lagged to prevent clicks) give an independent "OR" of the two
/// bypass sources: rig bypass overrides even a board that is otherwise engaged.
private func applyBypass(
wet: any ValidGeneratorInput,
dry: any ValidGeneratorInput
) -> any ValidGeneratorInput {
let boardLagged: Lag.Control = Lag.Control(input: $boardBypass, time: bypassLagTime)
let boardPan: any ValidGeneratorInput = (boardLagged * bipolarSpan) - bipolarOffset
let afterBoard: CrossFade.Audio = CrossFade.Audio(inA: wet, inB: dry, pan: boardPan)
let rigLagged: Lag.Control = Lag.Control(input: $rigBypass, time: bypassLagTime)
let rigPan: any ValidGeneratorInput = (rigLagged * bipolarSpan) - bipolarOffset
return CrossFade.Audio(inA: afterBoard, inB: dry, pan: rigPan)
}
}
@@ -0,0 +1,43 @@
// CabIRStage.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// One filter stage in an off-RT cabinet-IR cascade, as a kind plus parameters.
///
/// Consumed by ``CabinetIRFactory`` when it bakes an impulse response: the cab voice contributes a
/// fixed cascade, and a ``MicVoice`` contributes extra stages (presence bump, top-end/low-end
/// shelving) appended to it. `q` is used by high-pass / low-pass / peaking stages; `gainDb` by
/// peaking and the shelves; shelves use a fixed slope set by the factory.
struct CabIRStage {
/// The biquad kind this stage bakes into.
enum Kind {
case highPass
case lowPass
case peaking
case lowShelf
case highShelf
}
let kind: Kind
let freq: Double
let q: Double
let gainDb: Double
/// A resonant peak/dip at `freq`.
static func peaking(_ freq: Double, q: Double, gainDb: Double) -> CabIRStage {
CabIRStage(kind: .peaking, freq: freq, q: q, gainDb: gainDb)
}
/// A low-frequency shelf at `freq` (slope fixed by the factory).
static func lowShelf(_ freq: Double, gainDb: Double) -> CabIRStage {
CabIRStage(kind: .lowShelf, freq: freq, q: 0.0, gainDb: gainDb)
}
/// A high-frequency shelf at `freq` (slope fixed by the factory).
static func highShelf(_ freq: Double, gainDb: Double) -> CabIRStage {
CabIRStage(kind: .highShelf, freq: freq, q: 0.0, gainDb: gainDb)
}
}
@@ -0,0 +1,231 @@
// CabinetIRFactory.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import Darwin
/// Fraction of the sample rate above which a filter centre frequency is clamped, so the RBJ
/// coefficients stay well-behaved below Nyquist even at low sample rates.
private let cabinetBiquadNyquistFraction: Double = 0.49
/// RBJ-cookbook divisor converting a filter gain in dB to its `A` amplitude term (peaking + shelves).
private let cabinetDbToAmplitudeDivisor: Double = 40.0
/// Synthesizes a short cabinet impulse response for a ``CabinetVoice`` by running a unit
/// impulse through a cascade of RBJ biquads (high-pass → two-stage low-pass → low-mid body
/// peak → presence peak → cone-breakup peak → mid notch) and capturing the result into a mono
/// ``LyrebirdBuffer``.
///
/// This runs **off the RT thread** (at pedal build time), so it uses plain `Double` math with
/// no allocation constraints. The produced buffer is a normal IR consumed by `ConvolutionReverb`.
public enum CabinetIRFactory {
/// Default IR length in frames. 1024 taps (~21 ms at 48 kHz) is ample for a speaker-cab
/// magnitude curve, which has no long tail.
public static let defaultFrames: Int = 1024
/// Butterworth Q for the high-pass (low rolloff) stage.
private static let highPassQ: Double = 0.707
/// Per-stage Q values for a true 4th-order Butterworth low-pass built as two cascaded
/// biquads (maximally flat passband). Q ≈ 0.5412 and 1.3066.
private static let lowPassCascadeQ: [Double] = [0.541_196_100_146_197, 1.306_562_964_876_377]
/// Q for the resonant body / presence peaks.
private static let peakQ: Double = 1.2
/// Q for the narrower cone-breakup peak (higher than the body/presence peaks).
private static let breakupQ: Double = 2.0
/// Q for the mid interference notch (narrow, so it dips without gutting the midrange).
private static let notchQ: Double = 2.5
/// Fixed shelf slope for the ``MicVoice`` low-/high-shelf stages (gentle, like the amp shelves).
private static let micShelfSlope: Double = 0.7
/// Builds the impulse response for `voice` (optionally mic'd by `mic`) at `sampleRate`.
///
/// The cab voice's fixed cascade is baked first; any ``MicVoice`` stages are appended before the
/// impulse is run, so the mic colour is folded into the same single IR (no extra render-time
/// cost). ``MicVoice/off`` appends nothing, so the result is byte-for-byte the raw cab voice.
///
/// - Parameters:
/// - voice: The cabinet voicing to synthesize.
/// - mic: The microphone voicing layered on top. Defaults to ``MicVoice/off`` (no mic).
/// - sampleRate: Engine sample rate in Hz.
/// - frames: IR length in frames. Defaults to ``defaultFrames``.
/// - Returns: A mono `LyrebirdBuffer` holding the normalized IR, tagged with `sampleRate`.
public static func makeIR(
voice: CabinetVoice,
mic: MicVoice = .off,
sampleRate: Double,
frames: Int = CabinetIRFactory.defaultFrames
) -> LyrebirdBuffer {
var chain: [OfflineBiquad] = [
OfflineBiquad.highPass(freq: voice.highPassHz, q: highPassQ, sampleRate: sampleRate),
OfflineBiquad.lowPass(freq: voice.lowPassHz, q: lowPassCascadeQ[0], sampleRate: sampleRate),
OfflineBiquad.lowPass(freq: voice.lowPassHz, q: lowPassCascadeQ[1], sampleRate: sampleRate),
OfflineBiquad.peaking(freq: voice.bodyHz, q: peakQ, gainDb: voice.bodyGainDb, sampleRate: sampleRate),
OfflineBiquad.peaking(freq: voice.presenceHz, q: peakQ, gainDb: voice.presenceGainDb, sampleRate: sampleRate),
OfflineBiquad.peaking(freq: voice.breakupHz, q: breakupQ, gainDb: voice.breakupGainDb, sampleRate: sampleRate),
OfflineBiquad.peaking(freq: voice.notchHz, q: notchQ, gainDb: voice.notchGainDb, sampleRate: sampleRate),
]
// Append the mic voicing's stages (none for `.off`) so its colour bakes into the same IR.
for stage: CabIRStage in mic.stages {
switch stage.kind {
case .highPass:
chain.append(OfflineBiquad.highPass(freq: stage.freq, q: stage.q, sampleRate: sampleRate))
case .lowPass:
chain.append(OfflineBiquad.lowPass(freq: stage.freq, q: stage.q, sampleRate: sampleRate))
case .peaking:
chain.append(OfflineBiquad.peaking(
freq: stage.freq, q: stage.q, gainDb: stage.gainDb, sampleRate: sampleRate))
case .lowShelf:
chain.append(OfflineBiquad.lowShelf(
freq: stage.freq, gainDb: stage.gainDb, slope: micShelfSlope, sampleRate: sampleRate))
case .highShelf:
chain.append(OfflineBiquad.highShelf(
freq: stage.freq, gainDb: stage.gainDb, slope: micShelfSlope, sampleRate: sampleRate))
}
}
var ir: [Double] = [Double](repeating: 0.0, count: frames)
for n: Int in 0..<frames {
var sample: Double = n == 0 ? 1.0 : 0.0
for i: Int in chain.indices {
sample = chain[i].process(sample)
}
ir[n] = sample
}
// Peak-normalize so the cab contributes unity-ish level regardless of the filter gains.
let peak: Double = ir.reduce(0.0) { Swift.max($0, abs($1)) }
if peak > 0.0 {
let inv: Double = 1.0 / peak
for i: Int in ir.indices { ir[i] *= inv }
}
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frames, channelCount: 1)
buffer.fill(using: { (frame: Int, _: Int) -> Double in ir[frame] })
buffer.setSampleRate(sampleRate)
return buffer
}
}
/// A minimal off-RT RBJ biquad (transposed Direct Form II) used only to render cabinet IRs.
private struct OfflineBiquad {
private let b0: Double
private let b1: Double
private let b2: Double
private let a1: Double
private let a2: Double
private var z1: Double = 0.0
private var z2: Double = 0.0
private init(
b0: Double,
b1: Double,
b2: Double,
a1: Double,
a2: Double
) {
self.b0 = b0
self.b1 = b1
self.b2 = b2
self.a1 = a1
self.a2 = a2
}
/// Centre frequency clamped below Nyquist for the given sample rate.
private static func clampedFreq(_ freq: Double, sampleRate: Double) -> Double {
Swift.min(freq, sampleRate * cabinetBiquadNyquistFraction)
}
mutating func process(_ x: Double) -> Double {
let y: Double = b0 * x + z1
z1 = b1 * x - a1 * y + z2
z2 = b2 * x - a2 * y
return y
}
static func highPass(freq: Double, q: Double, sampleRate: Double) -> OfflineBiquad {
let f: Double = clampedFreq(freq, sampleRate: sampleRate)
let w0: Double = 2.0 * Double.pi * f / sampleRate
let cosW0: Double = cos(w0)
let alpha: Double = sin(w0) / (2.0 * q)
let a0: Double = 1.0 + alpha
let b0: Double = (1.0 + cosW0) / 2.0
let b1: Double = -(1.0 + cosW0)
let b2: Double = (1.0 + cosW0) / 2.0
let a1: Double = -2.0 * cosW0
let a2: Double = 1.0 - alpha
return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0)
}
static func lowPass(freq: Double, q: Double, sampleRate: Double) -> OfflineBiquad {
let f: Double = clampedFreq(freq, sampleRate: sampleRate)
let w0: Double = 2.0 * Double.pi * f / sampleRate
let cosW0: Double = cos(w0)
let alpha: Double = sin(w0) / (2.0 * q)
let a0: Double = 1.0 + alpha
let b0: Double = (1.0 - cosW0) / 2.0
let b1: Double = 1.0 - cosW0
let b2: Double = (1.0 - cosW0) / 2.0
let a1: Double = -2.0 * cosW0
let a2: Double = 1.0 - alpha
return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0)
}
static func peaking(freq: Double, q: Double, gainDb: Double, sampleRate: Double) -> OfflineBiquad {
let f: Double = clampedFreq(freq, sampleRate: sampleRate)
let amplitude: Double = pow(10.0, gainDb / cabinetDbToAmplitudeDivisor)
let w0: Double = 2.0 * Double.pi * f / sampleRate
let cosW0: Double = cos(w0)
let alpha: Double = sin(w0) / (2.0 * q)
let a0: Double = 1.0 + alpha / amplitude
let b0: Double = 1.0 + alpha * amplitude
let b1: Double = -2.0 * cosW0
let b2: Double = 1.0 - alpha * amplitude
let a1: Double = -2.0 * cosW0
let a2: Double = 1.0 - alpha / amplitude
return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0)
}
/// RBJ low-shelf. `slope` is the cookbook `S` (1.0 = steepest without overshoot).
static func lowShelf(freq: Double, gainDb: Double, slope: Double, sampleRate: Double) -> OfflineBiquad {
let f: Double = clampedFreq(freq, sampleRate: sampleRate)
let amplitude: Double = pow(10.0, gainDb / cabinetDbToAmplitudeDivisor)
let w0: Double = 2.0 * Double.pi * f / sampleRate
let cosW0: Double = cos(w0)
let sinW0: Double = sin(w0)
let alpha: Double = sinW0 / 2.0 * sqrt((amplitude + 1.0 / amplitude) * (1.0 / slope - 1.0) + 2.0)
let twoSqrtAAlpha: Double = 2.0 * sqrt(amplitude) * alpha
let ap1: Double = amplitude + 1.0
let am1: Double = amplitude - 1.0
let b0: Double = amplitude * (ap1 - am1 * cosW0 + twoSqrtAAlpha)
let b1: Double = 2.0 * amplitude * (am1 - ap1 * cosW0)
let b2: Double = amplitude * (ap1 - am1 * cosW0 - twoSqrtAAlpha)
let a0: Double = ap1 + am1 * cosW0 + twoSqrtAAlpha
let a1: Double = -2.0 * (am1 + ap1 * cosW0)
let a2: Double = ap1 + am1 * cosW0 - twoSqrtAAlpha
return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0)
}
/// RBJ high-shelf. `slope` is the cookbook `S` (1.0 = steepest without overshoot).
static func highShelf(freq: Double, gainDb: Double, slope: Double, sampleRate: Double) -> OfflineBiquad {
let f: Double = clampedFreq(freq, sampleRate: sampleRate)
let amplitude: Double = pow(10.0, gainDb / cabinetDbToAmplitudeDivisor)
let w0: Double = 2.0 * Double.pi * f / sampleRate
let cosW0: Double = cos(w0)
let sinW0: Double = sin(w0)
let alpha: Double = sinW0 / 2.0 * sqrt((amplitude + 1.0 / amplitude) * (1.0 / slope - 1.0) + 2.0)
let twoSqrtAAlpha: Double = 2.0 * sqrt(amplitude) * alpha
let ap1: Double = amplitude + 1.0
let am1: Double = amplitude - 1.0
let b0: Double = amplitude * (ap1 + am1 * cosW0 + twoSqrtAAlpha)
let b1: Double = -2.0 * amplitude * (am1 + ap1 * cosW0)
let b2: Double = amplitude * (ap1 + am1 * cosW0 - twoSqrtAAlpha)
let a0: Double = ap1 - am1 * cosW0 + twoSqrtAAlpha
let a1: Double = 2.0 * (am1 - ap1 * cosW0)
let a2: Double = ap1 - am1 * cosW0 - twoSqrtAAlpha
return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0)
}
}
@@ -0,0 +1,197 @@
// CabinetVoice.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A built-in guitar-speaker-cabinet voicing.
///
/// Each voice is a compact set of target-response parameters — low/high rolloff, a low-mid
/// "body" bump, an upper-mid "presence" peak, a higher cone-"breakup" peak, and a mid
/// interference "notch" — from which ``CabinetIRFactory`` synthesizes a short impulse response
/// entirely in code. These IRs are **our own content** (MIT, generated, no third-party capture),
/// so they ship with the pedal without licensing concerns. (Loading a user-supplied captured
/// `.wav` cab IR is a planned follow-up.)
///
/// The values are deliberately broad-strokes voicings, not measurements of specific hardware.
public enum CabinetVoice: String, CaseIterable, Sendable {
case americanCombo
case britishStack
case vintageDark
case modernStack
case boutiqueOpen
case brightCombo
case fullRange
case loFiBox
/// The voice at a selector value (an index into ``allCases``), rounded and clamped to the valid
/// range. Used by the cab selector to pick the single voice to instantiate on a board rebuild.
///
/// - Parameter selectorValue: The live selector node value (nominally an integer index).
/// - Returns: The corresponding voice, clamped to `allCases`.
public static func voice(atSelectorValue selectorValue: Double) -> CabinetVoice {
let all: [CabinetVoice] = allCases
guard selectorValue.isFinite else { return all[0] }
// Clamp in Double space first so a huge/NaN-adjacent value can never trap `Int(_:)`.
let bounded: Double = Swift.min(Swift.max(selectorValue, 0.0), Double(all.count - 1))
let index: Int = Int(bounded.rounded())
return all[index]
}
/// Human-readable name for pickers.
public var displayName: String {
switch self {
case .americanCombo: return "American 1×12"
case .britishStack: return "British 4×12"
case .vintageDark: return "Vintage Dark"
case .modernStack: return "Modern 4×12"
case .boutiqueOpen: return "Boutique 2×12"
case .brightCombo: return "Bright 1×12"
case .fullRange: return "Full-Range (FRFR)"
case .loFiBox: return "Lo-Fi 1×8"
}
}
/// Low-frequency rolloff (high-pass cutoff) in Hz — the speaker's bass limit.
var highPassHz: Double {
switch self {
case .americanCombo: return 80.0
case .britishStack: return 95.0
case .vintageDark: return 90.0
case .modernStack: return 100.0
case .boutiqueOpen: return 70.0
case .brightCombo: return 85.0
case .fullRange: return 45.0
case .loFiBox: return 180.0
}
}
/// High-frequency rolloff (low-pass cutoff) in Hz — the speaker's top-end limit. Applied as a
/// two-stage cascade for a steeper, more speaker-like slope.
var lowPassHz: Double {
switch self {
case .americanCombo: return 5500.0
case .britishStack: return 4500.0
case .vintageDark: return 3800.0
case .modernStack: return 4000.0
case .boutiqueOpen: return 6000.0
case .brightCombo: return 6500.0
case .fullRange: return 9000.0
case .loFiBox: return 3000.0
}
}
/// Low-mid "body" peak centre in Hz.
var bodyHz: Double {
switch self {
case .americanCombo: return 420.0
case .britishStack: return 700.0
case .vintageDark: return 500.0
case .modernStack: return 900.0
case .boutiqueOpen: return 450.0
case .brightCombo: return 550.0
case .fullRange: return 300.0
case .loFiBox: return 900.0
}
}
/// Low-mid body peak gain in dB (may be negative for a scoop).
var bodyGainDb: Double {
switch self {
case .americanCombo: return 1.5
case .britishStack: return -2.0
case .vintageDark: return 2.0
case .modernStack: return 2.0
case .boutiqueOpen: return -1.0
case .brightCombo: return 1.0
case .fullRange: return 0.0
case .loFiBox: return 4.0
}
}
/// Presence peak centre in Hz — the upper-mid "bite".
var presenceHz: Double {
switch self {
case .americanCombo: return 3000.0
case .britishStack: return 2500.0
case .vintageDark: return 2200.0
case .modernStack: return 3200.0
case .boutiqueOpen: return 3500.0
case .brightCombo: return 3800.0
case .fullRange: return 4000.0
case .loFiBox: return 2400.0
}
}
/// Presence peak gain in dB.
var presenceGainDb: Double {
switch self {
case .americanCombo: return 3.0
case .britishStack: return 4.0
case .vintageDark: return 2.0
case .modernStack: return 5.0
case .boutiqueOpen: return 2.0
case .brightCombo: return 4.0
case .fullRange: return 1.0
case .loFiBox: return 1.0
}
}
/// Cone-"breakup" peak centre in Hz — the higher, narrower bite/clank a real driver adds as
/// the cone breaks up. Sits above the presence peak.
var breakupHz: Double {
switch self {
case .americanCombo: return 4200.0
case .britishStack: return 3800.0
case .vintageDark: return 3500.0
case .modernStack: return 3800.0
case .boutiqueOpen: return 5000.0
case .brightCombo: return 5200.0
case .fullRange: return 6000.0
case .loFiBox: return 2600.0
}
}
/// Cone-breakup peak gain in dB. Small; `0` disables the peak (identity).
var breakupGainDb: Double {
switch self {
case .americanCombo: return 2.0
case .britishStack: return 3.0
case .vintageDark: return 1.5
case .modernStack: return 3.0
case .boutiqueOpen: return 1.5
case .brightCombo: return 3.0
case .fullRange: return 0.5
case .loFiBox: return 2.0
}
}
/// Mid interference "notch" centre in Hz — the characteristic dip from cone/mic
/// comb-filtering, typically ~1.2–2.5 kHz.
var notchHz: Double {
switch self {
case .americanCombo: return 1800.0
case .britishStack: return 1600.0
case .vintageDark: return 1500.0
case .modernStack: return 1700.0
case .boutiqueOpen: return 2000.0
case .brightCombo: return 2100.0
case .fullRange: return 2000.0
case .loFiBox: return 1200.0
}
}
/// Notch depth in dB (negative). `0` disables the notch (identity).
var notchGainDb: Double {
switch self {
case .americanCombo: return -3.0
case .britishStack: return -4.0
case .vintageDark: return -2.5
case .modernStack: return -5.0
case .boutiqueOpen: return -2.0
case .brightCombo: return -2.0
case .fullRange: return 0.0
case .loFiBox: return -1.0
}
}
}
@@ -0,0 +1,76 @@
// MicVoice.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A microphone voicing baked into the cabinet impulse response — the frequency signature of the
/// mic in front of the speaker, layered on top of the ``CabinetVoice`` cab curve.
///
/// Each voice is a compact set of ``CabIRStage`` filter stages (a presence bump, low-end and
/// top-end shelving) that ``CabinetIRFactory`` appends to the cab cascade before baking, so mic
/// choice costs nothing extra at render time — it is folded into the single convolution IR. These
/// are **broad-strokes synthesized curves** (our own MIT content, not captures of any specific
/// microphone), analogous to ``CabinetVoice``.
///
/// ``off`` contributes no stages, so a cab with no mic bakes exactly the raw cab voice — the
/// original, mic-less behaviour.
public enum MicVoice: String, CaseIterable, Sendable {
case off
case dynamic
case ribbon
case condenser
/// The voice at a selector value (an index into ``allCases``), rounded and clamped to the valid
/// range. Mirrors ``CabinetVoice/voice(atSelectorValue:)`` so a huge / NaN selector never traps.
///
/// - Parameter selectorValue: The live selector node value (nominally an integer index).
/// - Returns: The corresponding voice, clamped to `allCases`.
public static func voice(atSelectorValue selectorValue: Double) -> MicVoice {
let all: [MicVoice] = allCases
guard selectorValue.isFinite else { return all[0] }
let bounded: Double = Swift.min(Swift.max(selectorValue, 0.0), Double(all.count - 1))
let index: Int = Int(bounded.rounded())
return all[index]
}
/// Human-readable name for pickers.
public var displayName: String {
switch self {
case .off: return "No Mic"
case .dynamic: return "Dynamic"
case .ribbon: return "Ribbon"
case .condenser: return "Condenser"
}
}
/// The mic's filter stages, appended to the cab cascade before baking. Empty for ``off``.
///
/// Broad-strokes voicings: the **dynamic** (moving-coil, close-mic staple) adds an upper-mid
/// presence bump with a tightened low end and rolled-off extreme top; the **ribbon** is dark and
/// smooth (warm low-mid, steep top rolloff, no presence spike); the **condenser** is the most
/// extended and airy (gentle top-end lift, light presence sheen).
var stages: [CabIRStage] {
switch self {
case .off:
return []
case .dynamic:
return [
CabIRStage.lowShelf(120.0, gainDb: -2.0),
CabIRStage.peaking(5500.0, q: 1.0, gainDb: 4.0),
CabIRStage.highShelf(9000.0, gainDb: -3.0),
]
case .ribbon:
return [
CabIRStage.lowShelf(200.0, gainDb: 2.5),
CabIRStage.peaking(2500.0, q: 0.8, gainDb: -1.5),
CabIRStage.highShelf(6500.0, gainDb: -7.0),
]
case .condenser:
return [
CabIRStage.peaking(8000.0, q: 1.0, gainDb: 1.5),
CabIRStage.highShelf(11000.0, gainDb: 3.0),
]
}
}
}
@@ -0,0 +1,143 @@
// OversampledRingModulator.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import Darwin
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream
/// input yields no channel for a `_computeSamples` call, so the RT path never allocates.
private let oversampledRingModZeroBlock: [Double] = makeSampleBuffer()
/// Ring modulator (`input × sine carrier`) evaluated at 2× or 4× the engine sample rate.
///
/// A ring modulator's product produces sum-and-difference sidebands at `f_in ± f_carrier`. The
/// sum sideband can land above the engine Nyquist and fold back as an inharmonic alias —
/// worst with a high carrier and bright input. Evaluating the multiply at an oversampled rate
/// (the input upsampled through a halfband FIR, the carrier generated directly at the
/// oversampled rate) pushes the sum term below the upsampled Nyquist, then the matching
/// downsampler filters it out before returning to the engine rate.
///
/// Output is mono (channel 0 of the input is used).
///
/// - Parameters:
/// - input: Signal to modulate.
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
public final class OversampledRingModulator: GeneratorBase, AudioGenerator {
/// Resolved input signal (classified once at `init`, never on the RT thread).
private let inputSource: any ValidGeneratorInput
/// Resolved carrier-frequency control. Read once per block.
private let freqInput: any ValidGeneratorInput
/// Oversampling factor — `2` or `4`, fixed at init.
private let oversampleFactor: Int
/// Carrier phase in radians, advanced at the oversampled rate and wrapped to `[0, 2π)`.
private var phase: Double = 0.0
/// 2× halfband oversampling state (used when `oversampleFactor == 2`).
private var upsampler2x: HalfbandUpsampler2x
private var downsampler2x: HalfbandDownsampler2x
/// 4× halfband oversampling state (used when `oversampleFactor == 4`).
private var upsampler4x: HalfbandUpsampler4x
private var downsampler4x: HalfbandDownsampler4x
private let twoPi: Double = 2.0 * Double.pi
/// Creates an oversampled ring modulator.
///
/// - Parameters:
/// - input: Signal to modulate.
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
public init(
_ input: any ValidGeneratorInput,
freq: any ValidGeneratorInput = 220.0,
oversample: Int = 2
) {
precondition(
oversample == 2 || oversample == 4,
"OversampledRingModulator: oversample must be 2 or 4"
)
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
inputSource = resolvedInput
freqInput = resolvedFreq
oversampleFactor = oversample
upsampler2x = HalfbandUpsampler2x()
downsampler2x = HalfbandDownsampler2x()
upsampler4x = HalfbandUpsampler4x()
downsampler4x = HalfbandDownsampler4x()
super.init()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first
?? oversampledRingModZeroBlock
let sr: Double = graph.engine.sampleRate
// A degenerate sample rate would make phaseInc NaN/Inf and latch NaN into the
// persisted phase; zero-fill and bail, matching MoogLadder's guard.
guard sr >= 1.0 else {
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
for i: Int in 0..<count { dstP[i] = 0 }
}
return _result
}
let freq: Double = freqInput.floatValue(graph: graph)
let inCount: Int = input.count
let useFourX: Bool = oversampleFactor == 4
// Phase increment per oversampled sample.
let factor: Double = useFourX ? 4.0 : 2.0
let phaseInc: Double = twoPi * freq / (sr * factor)
var localPhase: Double = phase
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
if useFourX {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b, c, d) = upsampler4x.process(x)
let ya: Double = a * sin(localPhase); localPhase += phaseInc
let yb: Double = b * sin(localPhase); localPhase += phaseInc
let yc: Double = c * sin(localPhase); localPhase += phaseInc
let yd: Double = d * sin(localPhase); localPhase += phaseInc
// Wrap both directions — a negative carrier frequency drives phaseInc
// negative, so an upward-only wrap would let the phase grow unbounded.
if localPhase >= twoPi || localPhase < 0 {
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
if localPhase < 0 { localPhase += twoPi }
}
dstP[i] = downsampler4x.process(ya, yb, yc, yd)
}
} else {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b) = upsampler2x.process(x)
let ya: Double = a * sin(localPhase); localPhase += phaseInc
let yb: Double = b * sin(localPhase); localPhase += phaseInc
// Wrap both directions (see 4× branch).
if localPhase >= twoPi || localPhase < 0 {
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
if localPhase < 0 { localPhase += twoPi }
}
dstP[i] = downsampler2x.process(ya, yb)
}
}
}
phase = localPhase
return _result
}
}
@@ -0,0 +1,130 @@
// OversampledSaturator.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream
/// input yields no channel for a `_computeSamples` call, so the RT path never allocates.
private let oversampledSaturatorZeroBlock: [Double] = makeSampleBuffer()
/// A waveshaping saturator that evaluates its nonlinearity at 2× or 4× the engine sample
/// rate to keep the harmonics it generates from folding back into the audible band as
/// aliasing.
///
/// A hard or steep nonlinearity (`tanh` driven hard, a hard clipper) produces harmonics well
/// above the engine Nyquist. Evaluated at the base rate those harmonics alias — an
/// inharmonic, buzzy "crackle" that gets worse the louder and brighter the input and the
/// harder the drive. This generator upsamples the input, applies the ``SaturationCurve``
/// per oversampled sample, then downsamples with the matching halfband FIR, so the aliased
/// content is filtered out before returning to the engine rate.
///
/// Linear stages (DC-block high-pass, tone low-pass, output trim) do **not** alias and should
/// stay as ordinary graph nodes around this one — only the nonlinearity needs oversampling.
///
/// Output is mono (channel 0 of the input is used).
///
/// - Parameters:
/// - input: Signal to saturate.
/// - drive: Drive amount fed to the curve. Clamped to a small positive floor. Defaults to `1.0`.
/// - curve: The ``SaturationCurve`` to apply per oversampled sample.
/// - oversample: Oversampling factor — `2` or `4`. Use `4` for hard-clipping curves whose
/// harmonics extend furthest; `2` is enough for `tanh`-family soft saturation. Defaults to `2`.
public final class OversampledSaturator: GeneratorBase, AudioGenerator {
/// Resolved input signal (classified once at `init`, never on the RT thread).
private let inputSource: any ValidGeneratorInput
/// Resolved drive control. Read once per block.
private let driveInput: any ValidGeneratorInput
/// The waveshaping curve applied per oversampled sample.
private let curve: SaturationCurve
/// Oversampling factor — `2` or `4`, fixed at init.
private let oversampleFactor: Int
/// Lower bound on drive so `softClipNormalized`'s `tanh(drive)` denominator is never zero.
private let minDrive: Double = 1.0e-4
/// 2× halfband oversampling state (used when `oversampleFactor == 2`).
private var upsampler2x: HalfbandUpsampler2x
private var downsampler2x: HalfbandDownsampler2x
/// 4× halfband oversampling state (used when `oversampleFactor == 4`).
private var upsampler4x: HalfbandUpsampler4x
private var downsampler4x: HalfbandDownsampler4x
/// Creates an oversampled saturator.
///
/// - Parameters:
/// - input: Signal to saturate.
/// - drive: Drive amount fed to the curve. Clamped to a small positive floor. Defaults to `1.0`.
/// - curve: The ``SaturationCurve`` to apply per oversampled sample.
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
public init(
_ input: any ValidGeneratorInput,
drive: any ValidGeneratorInput = 1.0,
curve: SaturationCurve,
oversample: Int = 2
) {
precondition(
oversample == 2 || oversample == 4,
"OversampledSaturator: oversample must be 2 or 4"
)
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
let resolvedDrive: any ValidGeneratorInput = drive._resolvedInput()
inputSource = resolvedInput
driveInput = resolvedDrive
self.curve = curve
oversampleFactor = oversample
upsampler2x = HalfbandUpsampler2x()
downsampler2x = HalfbandDownsampler2x()
upsampler4x = HalfbandUpsampler4x()
downsampler4x = HalfbandDownsampler4x()
super.init()
}
public func _computeSamples(
graph: SynthGraph,
count: Int
) -> [[Double]] {
_checkCount(count)
guard count > 0 else { return _result }
let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first
?? oversampledSaturatorZeroBlock
let driveRaw: Double = driveInput.floatValue(graph: graph)
let drive: Double = Swift.max(minDrive, driveRaw)
let inCount: Int = input.count
let useFourX: Bool = oversampleFactor == 4
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
if useFourX {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b, c, d) = upsampler4x.process(x)
dstP[i] = downsampler4x.process(
curve.apply(a, drive: drive),
curve.apply(b, drive: drive),
curve.apply(c, drive: drive),
curve.apply(d, drive: drive)
)
}
} else {
for i: Int in 0..<count {
let x: Double = i < inCount ? input[i] : 0
let (a, b) = upsampler2x.process(x)
dstP[i] = downsampler2x.process(
curve.apply(a, drive: drive),
curve.apply(b, drive: drive)
)
}
}
}
return _result
}
}
@@ -0,0 +1,46 @@
// SaturationCurve.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Darwin
/// The waveshaping curve applied per (oversampled) sample by ``OversampledSaturator``.
///
/// Each case reproduces the nonlinearity a specific drive pedal used to build inline from
/// stock generators, so moving that pedal onto the oversampled path is voicing-preserving:
///
/// - `tanhPreGain` — `tanh(drive · x)`. Symmetric soft saturation with the drive applied
/// *before* the `tanh` (the fuzz voicing: hard pre-gain squares the wave off).
/// - `softClipNormalized` — `tanh(drive · x) / tanh(drive)`. The same curve normalised so a
/// unity-drive signal passes near-linearly (the overdrive voicing).
/// - `tanhPostGainHardClip(low:high:)` — `clip(tanh(x) · drive, low, high)`. A gentle `tanh`
/// stage, post-gained by drive into a hard clipper (the distortion voicing). The hard clip
/// is the dominant harmonic source and the reason this curve wants the highest oversampling
/// factor.
public enum SaturationCurve: Sendable {
case tanhPreGain
case softClipNormalized
case tanhPostGainHardClip(low: Double, high: Double)
/// Applies the curve to a single sample.
///
/// - Parameters:
/// - x: Input sample (already at the oversampled rate).
/// - drive: Drive amount. The caller clamps this to a small positive floor so
/// `softClipNormalized`'s `tanh(drive)` denominator is never zero.
/// - Returns: The shaped sample.
@inline(__always)
func apply(_ x: Double, drive: Double) -> Double {
switch self {
case .tanhPreGain:
return tanh(drive * x)
case .softClipNormalized:
return tanh(drive * x) / tanh(drive)
case .tanhPostGainHardClip(let low, let high):
let shaped: Double = tanh(x) * drive
return Swift.min(high, Swift.max(low, shaped))
}
}
}
@@ -5,6 +5,7 @@
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Internal synthesizer that copies one hardware input bus to a board head bus.
///
@@ -18,6 +19,17 @@ import LyrebirdSynth
/// `teardown()` releases the head bus back to the allocator.
final class HardwareInputPassThrough: SynthesizerBase {
// MARK: - Parameters
/// Input mute — `0` = audible, `1` = muted (a hard gate on the incoming signal, distinct from
/// the rig-output mute). Driven across every board input node by `ShoeGaze.setInputMuted(_:)`,
/// which sets a newly-added node to the session's current mute state. Defaults audible so
/// direct users (e.g. `ChainRouter`) that don't drive the mute pass the signal through.
@UIParam var inputMute: Double = 0.0
/// The live `UIParamNode` backing `inputMute`, driven by `ShoeGaze.setInputMuted(_:)`.
var inputMuteNode: UIParamNode { $inputMute }
// MARK: - Routing
/// Index of the hardware input bus to read from (typically `engine.numOutputChannels`).
@@ -43,6 +55,11 @@ final class HardwareInputPassThrough: SynthesizerBase {
// MARK: - Build
override func build() {
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
// Hard kill-switch gate: `1 − inputMute`, so mute 0 → gain 1 (audible), 1 → gain 0 (exactly
// silent). Unlagged on purpose — a lagged gate never settles to exactly zero on its first
// blocks and leaks a faint transient right when the mute is meant to keep things quiet; a
// kill-switch mute is expected to be abrupt anyway.
let muteGain: any ValidGeneratorInput = ($inputMute - 1.0) * -1.0
output(bus: outputBusIndex, source: input(bus: inputBusIndex) * muteGain)
}
}
@@ -22,6 +22,46 @@ public enum InputSource: Equatable {
case liveInput(channel: Int)
}
// MARK: - Codable
/// Persisted so a saved rig round-trips its input selection. Encoded as a `kind` discriminator
/// plus an optional `channel`, so adding future cases stays forward-tolerant.
extension InputSource: Codable {
private enum Kind: String, Codable {
case testLoop
case liveInput
}
private enum CodingKeys: String, CodingKey {
case kind
case channel
}
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
let kind: Kind = try container.decode(Kind.self, forKey: .kind)
switch kind {
case .testLoop:
self = .testLoop
case .liveInput:
let channel: Int = try container.decode(Int.self, forKey: .channel)
self = .liveInput(channel: channel)
}
}
public func encode(to encoder: Encoder) throws {
var container: KeyedEncodingContainer<CodingKeys> = encoder.container(keyedBy: CodingKeys.self)
switch self {
case .testLoop:
try container.encode(Kind.testLoop, forKey: .kind)
case .liveInput(let channel):
try container.encode(Kind.liveInput, forKey: .kind)
try container.encode(channel, forKey: .channel)
}
}
}
/// Validates a `.liveInput` channel against the engine and returns the engine audio-bus
/// index of that hardware input channel.
///
@@ -5,6 +5,7 @@
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Internal synthesizer that copies the shared global test-loop bus to a board head bus.
///
@@ -19,6 +20,16 @@ import LyrebirdSynth
/// - Note: Must be removed from the engine before the board's `teardown()` releases the head bus.
final class TestLoopTap: SynthesizerBase {
// MARK: - Parameters
/// Input mute — `0` = audible, `1` = muted. Driven across every board input node by
/// `ShoeGaze.setInputMuted(_:)`, which sets a newly-added node to the session's current mute
/// state. Defaults audible so direct users that don't drive the mute pass the signal through.
@UIParam var inputMute: Double = 0.0
/// The live `UIParamNode` backing `inputMute`, driven by `ShoeGaze.setInputMuted(_:)`.
var inputMuteNode: UIParamNode { $inputMute }
// MARK: - Routing
/// Index of the shared global test-loop bus to read from.
@@ -44,6 +55,11 @@ final class TestLoopTap: SynthesizerBase {
// MARK: - Build
override func build() {
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
// Hard kill-switch gate: `1 − inputMute`, so mute 0 → gain 1 (audible), 1 → gain 0 (exactly
// silent). Unlagged on purpose — a lagged gate never settles to exactly zero on its first
// blocks and leaks a faint transient right when the mute is meant to keep things quiet; a
// kill-switch mute is expected to be abrupt anyway.
let muteGain: any ValidGeneratorInput = ($inputMute - 1.0) * -1.0
output(bus: outputBusIndex, source: input(bus: inputBusIndex) * muteGain)
}
}
@@ -0,0 +1,153 @@
// LegacyMIDIMap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Decoder for the **pre-UUID** `MIDIMap` format, which addressed pedals and boards by chain
/// position (`boardIndex` / `pedalIndex`) rather than by stable id.
///
/// Used only on load: `ShoeGazeState.init(from:)` tries the current id-based `MIDIMap` first and,
/// if that fails, decodes this legacy shape and calls ``migrated(boards:)`` to convert each
/// positional binding to the id of the pedal/board now sitting at that position. Because the saved
/// positions are stable, this reconstructs correct id-bindings on every load — even though the ids
/// themselves are freshly assigned to a legacy rig each time it is decoded.
///
/// Bindings whose indices fall outside the loaded rig are dropped.
struct LegacyMIDIMap: Codable {
var switches: [LegacySwitchBinding]
var ccs: [LegacyCCBinding]
enum LegacyAction: Codable {
case rigBypass
case rigMute
case allBoards
case boardSolo(boardIndex: Int)
case boardAudible(boardIndex: Int)
case boardBypass(boardIndex: Int)
case pedalBypass(boardIndex: Int, pedalIndex: Int)
case pedalAction(boardIndex: Int, pedalIndex: Int, kind: MIDIMap.PedalActionKind)
case tunerToggle
case tapTempo
}
enum LegacyCCTarget: Codable {
case pedalControl(
boardIndex: Int,
pedalIndex: Int,
controlIndex: Int,
pedalNameHint: String?,
controlLabelHint: String?
)
case boardLevel(boardIndex: Int, boardLabelHint: String?)
case rigVolume
}
struct LegacySwitchBinding: Codable {
var program: UInt8
var channel: UInt8?
var action: LegacyAction
var displayNameHint: String?
}
struct LegacyCCBinding: Codable {
var controller: UInt8
var channel: UInt8?
var target: LegacyCCTarget
var inverted: Bool
}
// MARK: - Migration
/// Converts this positional map to the current id-based ``MIDIMap`` using the ids of the pedals
/// and boards in `boards` (whose ids were freshly assigned when the rig was decoded). Bindings
/// addressing an out-of-range board/pedal are dropped.
func migrated(boards: [BoardState]) -> MIDIMap {
func boardID(_ index: Int) -> UUID? {
guard index >= 0, index < boards.count else { return nil }
return boards[index].id
}
func pedalID(_ boardIndex: Int, _ pedalIndex: Int) -> UUID? {
guard boardIndex >= 0, boardIndex < boards.count else { return nil }
let pedals: [PedalState] = boards[boardIndex].pedals
guard pedalIndex >= 0, pedalIndex < pedals.count else { return nil }
return pedals[pedalIndex].id
}
let migratedSwitches: [MIDIMap.SwitchBinding] = switches.compactMap { binding in
guard let action: MIDIMap.Action = migrate(binding.action, boardID: boardID, pedalID: pedalID) else {
return nil
}
return MIDIMap.SwitchBinding(
program: binding.program,
channel: binding.channel,
action: action,
displayNameHint: binding.displayNameHint
)
}
let migratedCCs: [MIDIMap.CCBinding] = ccs.compactMap { binding in
guard let target: MIDIMap.CCTarget = migrate(binding.target, boardID: boardID, pedalID: pedalID) else {
return nil
}
return MIDIMap.CCBinding(
controller: binding.controller,
channel: binding.channel,
target: target,
inverted: binding.inverted
)
}
return MIDIMap(switches: migratedSwitches, ccs: migratedCCs)
}
private func migrate(
_ action: LegacyAction,
boardID: (Int) -> UUID?,
pedalID: (Int, Int) -> UUID?
) -> MIDIMap.Action? {
switch action {
case .rigBypass: return .rigBypass
case .rigMute: return .rigMute
case .allBoards: return .allBoards
case .tunerToggle: return .tunerToggle
case .tapTempo: return .tapTempo
case .boardSolo(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardSolo(boardID: id)
case .boardAudible(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardAudible(boardID: id)
case .boardBypass(let b):
guard let id: UUID = boardID(b) else { return nil }
return .boardBypass(boardID: id)
case .pedalBypass(let b, let p):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalBypass(pedalID: id)
case .pedalAction(let b, let p, let kind):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalAction(pedalID: id, kind: kind)
}
}
private func migrate(
_ target: LegacyCCTarget,
boardID: (Int) -> UUID?,
pedalID: (Int, Int) -> UUID?
) -> MIDIMap.CCTarget? {
switch target {
case .rigVolume:
return .rigVolume
case .pedalControl(let b, let p, let controlIndex, let nameHint, let labelHint):
guard let id: UUID = pedalID(b, p) else { return nil }
return .pedalControl(pedalID: id, controlIndex: controlIndex,
pedalNameHint: nameHint, controlLabelHint: labelHint)
case .boardLevel(let b, let labelHint):
guard let id: UUID = boardID(b) else { return nil }
return .boardLevel(boardID: id, boardLabelHint: labelHint)
}
}
}
@@ -0,0 +1,560 @@
// MIDIController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
/// Owns the Core MIDI connection for a ShoeGaze session and routes incoming messages to the rig.
///
/// Constructed once by the app (it is recreated against a fresh engine when the engine is rebuilt),
/// and started with ``start()``. Handlers fire on Lyrebird's background MIDI queue; this controller
/// hops to the main actor before touching any `@MainActor` rig state.
///
/// It establishes the Core MIDI connection, publishes device-connection state for the UI indicator,
/// and routes incoming messages to the rig: Control Change drives bound pedal controls, and Program
/// Change toggles bound pedal / board / rig actions. MIDI Learn arms a control so the next matching
/// message binds to it.
@MainActor
@Observable
public final class MIDIController {
// MARK: - Connection state
/// `true` when at least one MIDI input source is currently connected.
public private(set) var isConnected: Bool = false
/// Names of the connected MIDI input sources (e.g. `"FCB1010"`), for the indicator's tooltip.
public private(set) var connectedDeviceNames: [String] = []
// MARK: - Learn
/// A control armed for MIDI Learn: the next matching message captures a binding to it.
public enum LearnTarget: Equatable, Sendable {
/// A continuous control awaiting a Control Change (address-only; hints are `nil`).
case cc(MIDIMap.CCTarget)
/// A toggle action awaiting a Program Change.
case action(MIDIMap.Action)
/// A toggle action awaiting a computer key press.
case key(MIDIMap.Action)
}
/// The control currently armed for Learn, or `nil` when not learning. Observable so the UI can
/// show a "Listening…" state and a global learn banner.
public private(set) var learnTarget: LearnTarget?
/// Invoked on the main actor after the map changes (a binding learned or cleared), so the host
/// can persist the rig. Optional — when unset, the map still persists on the next rig autosave.
public var onMapChanged: (() -> Void)?
// MARK: - Private
private let midi: MIDI
private var handlerToken: MIDIHandlerToken?
/// The rig this controller drives. Weak + retargetable: the app owns both, and an iOS engine
/// rebuild swaps `ShoeGaze` out from under us.
private weak var shoeGaze: ShoeGaze?
/// Main-queue timer that re-reads `midi.sources` to publish connection state. Polling is used
/// because Lyrebird 1.2.0's `MIDI` refreshes endpoints internally but exposes no change callback.
private var detectionTimer: DispatchSourceTimer?
/// Poll interval for connection state, in seconds. A foot controller is plugged in before a set,
/// so ~1 s latency is imperceptible.
private let detectionInterval: Double = 1.0
/// Crossfade time (seconds) applied to board solo/audible changes triggered by a footswitch.
private let boardActionCrossfade: Double = 0.05
// MARK: - Init
/// Creates a MIDI controller bound to an engine.
///
/// - Parameters:
/// - engine: The engine the underlying `MIDI` client attaches to. On iOS this is rebuilt when
/// live input is enabled; recreate the controller against the new engine in that case.
/// - shoeGaze: The rig to drive. May be set later via ``retarget(_:)``.
/// - clientName: Core MIDI client name. Defaults to `"ShoeGaze"`.
public init(
engine: SynthesisEngine,
shoeGaze: ShoeGaze? = nil,
clientName: String = "ShoeGaze"
) {
self.midi = MIDI(engine: engine, clientName: clientName)
self.shoeGaze = shoeGaze
}
// MARK: - Lifecycle
/// Starts the MIDI client, installs the message handler, and begins polling for devices.
/// Safe to call once; a failed `MIDI.start()` is logged and leaves the controller inert.
public func start() {
do {
try midi.start()
} catch {
print("[MIDIController] MIDI start failed: \(error)")
}
installHandler()
refreshDevices()
startDetectionTimer()
}
/// Removes the handler, stops polling, and tears down the MIDI client.
public func stop() {
stopDetectionTimer()
if let token: MIDIHandlerToken = handlerToken {
midi.removeHandler(token)
handlerToken = nil
}
midi.stop()
}
// MARK: - Message handling
private func installHandler() {
handlerToken = midi.addHandler(name: "shoegaze.midi") { [weak self] message, _ in
// Handlers fire on the background `lyrebird.midi` queue. Hop to the main actor (FIFO on
// the main queue) before touching any `@MainActor` rig state.
DispatchQueue.main.async {
MainActor.assumeIsolated {
self?.handle(message)
}
}
}
}
/// Routes one incoming message to the rig: captures a binding when armed for Learn, otherwise
/// applies any matching binding. Control Change drives bound controls; Program Change toggles
/// bound actions.
private func handle(_ message: MIDIMessage) {
switch message {
case .controlChange(let channel, let controller, let value):
if case .cc(let target) = learnTarget {
captureCC(controller: controller, channel: channel, target: target)
} else {
applyCC(controller: controller, channel: channel, value: value)
}
case .programChange(let channel, let program):
if case .action(let action) = learnTarget {
captureSwitch(program: program, channel: channel, action: action)
} else {
applyProgram(program: program, channel: channel)
}
default:
break
}
}
#if DEBUG
/// Test hook: routes a message synchronously, bypassing the background-queue hop. The queue hop
/// is exercised only in a live session; tests drive `handle` directly on the main actor.
func ingestForTesting(_ message: MIDIMessage) {
handle(message)
}
#endif
// MARK: - Learn API
/// Master-level range for a board fader, mirroring the UI slider.
private let boardLevelRange: ClosedRange<Double> = 0.0 ... 1.0
/// Arms MIDI Learn for a continuous control: the next incoming Control Change binds to it. Pass
/// an address-only target (hints `nil`); hints are captured from the live rig at bind time.
public func armCCLearn(_ target: MIDIMap.CCTarget) {
learnTarget = .cc(target)
}
/// Cancels any in-progress Learn.
public func cancelLearn() {
learnTarget = nil
}
/// The CC binding currently assigned to a control, or `nil` if unbound.
public func ccBinding(for target: MIDIMap.CCTarget) -> MIDIMap.CCBinding? {
shoeGaze?.midiMap?.ccs.first { $0.target.addresses(target) }
}
/// Whether the CC binding on a control is inverted (CC 0 → control max), or `false` if unbound.
public func isCCInverted(for target: MIDIMap.CCTarget) -> Bool {
ccBinding(for: target)?.inverted ?? false
}
/// Sets the invert flag on the CC binding assigned to a control. Inverting swaps the sweep so a
/// single expression pedal can crossfade — e.g. fade one control down as it moves, another up.
public func setCCInverted(for target: MIDIMap.CCTarget, _ inverted: Bool) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap,
let index: Int = map.ccs.firstIndex(where: { $0.target.addresses(target) }),
map.ccs[index].inverted != inverted else { return }
map.ccs[index].inverted = inverted
shoeGaze.midiMap = map
onMapChanged?()
}
/// Removes any CC binding assigned to a control.
public func clearCCBinding(for target: MIDIMap.CCTarget) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
let before: Int = map.ccs.count
map.ccs.removeAll { $0.target.addresses(target) }
guard map.ccs.count != before else { return }
shoeGaze.midiMap = map
onMapChanged?()
}
// MARK: - CC handling
/// Captures a learned CC binding for the armed control and clears the Learn state.
private func captureCC(controller: UInt8, channel: UInt8, target: MIDIMap.CCTarget) {
learnTarget = nil
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
// `rigVolume` is applied via a setter (it has no single node) and is always valid, so it
// needs no resolve; pedal/board targets resolve to re-stamp their display-name hints.
let hinted: MIDIMap.CCTarget
if case .rigVolume = target {
hinted = .rigVolume
} else {
guard let resolved: ResolvedCC = resolveCC(target) else { return }
hinted = resolved.hinted
}
let binding: MIDIMap.CCBinding = MIDIMap.CCBinding(
controller: controller,
channel: channel,
target: hinted
)
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
// One binding per control — re-learning a control replaces its binding. A single CC may
// drive MULTIPLE controls on purpose (e.g. map one expression pedal to two board levels and
// invert one for a crossfade), so we deliberately do NOT steal by controller number.
map.ccs.removeAll { $0.target.addresses(hinted) }
map.ccs.append(binding)
shoeGaze.midiMap = map
onMapChanged?()
}
/// Applies an incoming CC to the control it is bound to, if any (channel-filtered).
private func applyCC(controller: UInt8, channel: UInt8, value: UInt8) {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return }
for binding: MIDIMap.CCBinding in map.ccs where binding.controller == controller {
if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue }
let ccMax: Double = 127.0
var norm: Double = Double(value) / ccMax
if binding.inverted { norm = 1.0 - norm }
if case .rigVolume = binding.target {
shoeGaze.setRigVolume(norm) // rig volume spans [0, 1] directly
continue
}
guard let resolved: ResolvedCC = resolveCC(binding.target) else { continue }
// A parameter locked to a note division is driven by the tempo; a CC write would be
// overwritten on the next tempo change, so ignore it here. The binding stays intact and
// resumes control the moment the parameter is set back to Free.
if case let .pedalControl(pedalID, _, _, _) = binding.target,
let pedal: Pedal = pedal(id: pedalID),
pedal.isNodeTempoSynced(resolved.node) {
continue
}
let mapped: Double = resolved.range.lowerBound
+ norm * (resolved.range.upperBound - resolved.range.lowerBound)
resolved.node.update(mapped)
}
}
/// A resolved CC target: the live node + range to drive, plus the target re-stamped with the
/// current display-name hints (for storing at capture time).
private struct ResolvedCC {
let node: UIParamNode
let range: ClosedRange<Double>
let hinted: MIDIMap.CCTarget
}
/// Resolves a CC target to its live node + range, skipping it (returns `nil`) when the positional
/// address is out of range or a captured display-name hint no longer matches (stale binding).
private func resolveCC(_ target: MIDIMap.CCTarget) -> ResolvedCC? {
switch target {
case let .pedalControl(pedalID, controlIndex, _, _):
guard let pedal: Pedal = pedal(id: pedalID) else { return nil }
let controls: [PedalControl] = pedal.ccMappableControls
guard controlIndex >= 0, controlIndex < controls.count else { return nil }
let control: PedalControl = controls[controlIndex]
let hinted: MIDIMap.CCTarget = .pedalControl(
pedalID: pedalID,
controlIndex: controlIndex,
pedalNameHint: pedal.displayName,
controlLabelHint: control.label
)
return ResolvedCC(node: control.node, range: control.range, hinted: hinted)
case let .boardLevel(boardID, _):
guard let board: PedalBoard = board(id: boardID),
let node: UIParamNode = board.masterGainNode else { return nil }
let hinted: MIDIMap.CCTarget = .boardLevel(boardID: boardID, boardLabelHint: board.label)
return ResolvedCC(node: node, range: boardLevelRange, hinted: hinted)
case .rigVolume:
// Applied via `ShoeGaze.setRigVolume` (fans out to every board), not a single node.
return nil
}
}
// MARK: - Switch (Program Change) learn + apply
/// Arms MIDI Learn for a toggle action: the next incoming Program Change binds to it.
public func armSwitchLearn(_ action: MIDIMap.Action) {
learnTarget = .action(action)
}
/// The switch binding currently assigned to an action, or `nil` if unbound.
public func switchBinding(for action: MIDIMap.Action) -> MIDIMap.SwitchBinding? {
shoeGaze?.midiMap?.switches.first { $0.action == action }
}
/// Removes any switch binding assigned to an action.
public func clearSwitchBinding(for action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
let before: Int = map.switches.count
map.switches.removeAll { $0.action == action }
guard map.switches.count != before else { return }
shoeGaze.midiMap = map
onMapChanged?()
}
/// Captures a learned switch binding for the armed action and clears the Learn state.
private func captureSwitch(program: UInt8, channel: UInt8, action: MIDIMap.Action) {
learnTarget = nil
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
let binding: MIDIMap.SwitchBinding = MIDIMap.SwitchBinding(
program: program,
channel: channel,
action: action,
displayNameHint: hint(for: action)
)
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
// One binding per action — re-learning an action replaces its binding. A single footswitch
// (program) may drive MULTIPLE actions on purpose (a "scene": e.g. bypass two pedals, or
// solo a board and bypass another, from one press), so we do NOT steal by program number.
map.switches.removeAll { $0.action == action }
map.switches.append(binding)
shoeGaze.midiMap = map
onMapChanged?()
}
/// Performs every action bound to an incoming Program Change (channel-filtered).
private func applyProgram(program: UInt8, channel: UInt8) {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return }
for binding: MIDIMap.SwitchBinding in map.switches where binding.program == program {
if let boundChannel: UInt8 = binding.channel, boundChannel != channel { continue }
perform(binding.action)
}
}
/// Executes a toggle action by reading the live rig state and flipping it. Boolean actions latch;
/// `boardSolo` is exclusive (radio). Pedals/boards resolve by UUID, so a binding whose target no
/// longer exists (removed pedal/board) simply no-ops.
private func perform(_ action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
switch action {
case .rigBypass:
shoeGaze.toggleRigBypassed()
case .rigMute:
shoeGaze.toggleRigMuted()
case .inputMute:
shoeGaze.toggleInputMuted()
case .allBoards:
// One-shot: cancel any solo and bring every board back up.
shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade)
case .boardSolo(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.soloBoard(board, crossfadeSeconds: boardActionCrossfade)
case .boardAudible(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.setBoard(board, audible: !shoeGaze.isBoardAudible(board),
crossfadeSeconds: boardActionCrossfade)
case .boardBypass(let boardID):
guard let board: PedalBoard = board(id: boardID) else { return }
shoeGaze.setBoard(board, bypassed: !shoeGaze.isBoardBypassed(board))
case .pedalBypass(let pedalID):
guard let pedal: Pedal = pedal(id: pedalID) else { return }
let engagedThreshold: Double = 0.5
let node: UIParamNode = pedal.$bypass
node.update(node.value < engagedThreshold ? 1.0 : 0.0)
case .pedalAction(let pedalID, let kind):
guard let pedal: Pedal = pedal(id: pedalID) else { return }
performPedalAction(kind, on: pedal)
case .tunerToggle:
shoeGaze.toggleTunerEngaged()
case .tapTempo:
shoeGaze.tapTempo()
}
}
/// Dispatches a pedal-specific momentary action. New `PedalActionKind` cases add a
/// branch here once the pedal type they target exists.
private func performPedalAction(_ kind: MIDIMap.PedalActionKind, on pedal: Pedal) {
let toggleThreshold: Double = 0.5
switch kind {
case .looperRecordStop:
// The smart Loop footswitch drives record / set-end / overdub / play by state.
(pedal as? LooperPedal)?.pressLoop()
case .looperOverdubToggle:
// Overdub is toggled by the same Loop press once a loop is playing.
(pedal as? LooperPedal)?.pressLoop()
case .looperLoopToggle:
guard let looper: LooperPedal = pedal as? LooperPedal else { return }
let node: UIParamNode = looper.$loopOn
node.update(node.value < toggleThreshold ? 1.0 : 0.0)
case .looperReset:
(pedal as? LooperPedal)?.resetLoop()
case .looperStop:
(pedal as? LooperPedal)?.stopPlayback()
case .looperCueStop:
(pedal as? LooperPedal)?.toggleStopAtLoopEnd()
case .looperReverse:
(pedal as? LooperPedal)?.toggleReverse()
case .looperSyncToggle:
(pedal as? LooperPedal)?.cycleSyncMode()
case .looperTrack(let index):
(pedal as? LooperPedal)?.tapTrack(index)
}
}
/// A display-name hint for an action, captured at learn time for the mapping-sheet UI label.
/// Not used for resolution (bindings resolve by UUID) — purely a human-readable snapshot.
private func hint(for action: MIDIMap.Action) -> String? {
switch action {
case .rigBypass, .rigMute, .inputMute, .allBoards:
return nil
case .boardSolo(let boardID), .boardAudible(let boardID), .boardBypass(let boardID):
return board(id: boardID)?.label
case .pedalBypass(let pedalID), .pedalAction(let pedalID, _):
return pedal(id: pedalID)?.displayName
case .tunerToggle, .tapTempo:
return nil
}
}
/// Resolves a board by its stable id, or `nil` if no board in the rig has that id.
private func board(id: UUID) -> PedalBoard? {
shoeGaze?.boards.first { $0.id == id }
}
/// Resolves a pedal by its stable id across all boards' linear pedal chains, or `nil` if no
/// pedal in the rig has that id.
private func pedal(id: UUID) -> Pedal? {
guard let shoeGaze: ShoeGaze = shoeGaze else { return nil }
for board: PedalBoard in shoeGaze.boards {
if let match: Pedal = board.pedals.first(where: { $0.id == id }) { return match }
}
return nil
}
// MARK: - Key learn + apply
/// Arms MIDI Learn for a toggle action awaiting a key: the next ingested key press binds to it.
public func armKeyLearn(_ action: MIDIMap.Action) {
learnTarget = .key(action)
}
/// The key binding currently assigned to an action, or `nil` if unbound.
public func keyBinding(for action: MIDIMap.Action) -> MIDIMap.KeyBinding? {
shoeGaze?.midiMap?.keys.first { $0.action == action }
}
/// Removes any key binding assigned to an action.
public func clearKeyBinding(for action: MIDIMap.Action) {
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
let before: Int = map.keys.count
map.keys.removeAll { $0.action == action }
guard map.keys.count != before else { return }
shoeGaze.midiMap = map
onMapChanged?()
}
/// Normalizes a raw key string to the single lowercased character used for storage and matching,
/// or `nil` when the input is not exactly one letter or digit. Restricting to alphanumerics keeps
/// non-printing keys (Return, Tab, Escape, arrows — all single `Character`s) from being learned
/// and then silently swallowed app-wide.
private func normalizedKey(_ raw: String) -> String? {
let lowered: String = raw.lowercased()
guard lowered.count == 1, let character: Character = lowered.first, character.isASCII,
character.isLetter || character.isNumber else { return nil }
return lowered
}
/// Routes a computer key press: captures a binding when armed for key Learn, otherwise performs
/// every action bound to that key + modifier combination. Returns `true` when the press was
/// consumed (learned or matched a binding) so the caller can swallow the event; `false` lets it
/// fall through.
///
/// - Parameters:
/// - rawKey: The pressed key; normalized to a single lowercased character.
/// - modifiers: The modifier keys held with the press. `a` and `⇧a` bind independently.
@discardableResult
public func ingestKey(_ rawKey: String, modifiers: MIDIMap.KeyModifiers = []) -> Bool {
guard let key: String = normalizedKey(rawKey) else { return false }
if case .key(let action) = learnTarget {
captureKey(key: key, modifiers: modifiers, action: action)
return true
}
return applyKey(key, modifiers: modifiers)
}
/// Captures a learned key binding for the armed action and clears the Learn state. One binding
/// per action — re-learning replaces it — but a single key may drive multiple actions (a scene),
/// so we do not steal by key.
private func captureKey(key: String, modifiers: MIDIMap.KeyModifiers, action: MIDIMap.Action) {
learnTarget = nil
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
let binding: MIDIMap.KeyBinding = MIDIMap.KeyBinding(
key: key,
modifiers: modifiers,
action: action,
displayNameHint: hint(for: action)
)
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
map.keys.removeAll { $0.action == action }
map.keys.append(binding)
shoeGaze.midiMap = map
onMapChanged?()
}
/// Performs every action bound to a key + modifier combination. Returns `true` when at least one
/// binding matched (key and modifiers both equal).
private func applyKey(_ key: String, modifiers: MIDIMap.KeyModifiers) -> Bool {
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return false }
var matched: Bool = false
for binding: MIDIMap.KeyBinding in map.keys
where binding.key == key && binding.modifiers == modifiers {
perform(binding.action)
matched = true
}
return matched
}
// MARK: - Device detection
private func refreshDevices() {
let names: [String] = midi.sources.map { $0.name }
connectedDeviceNames = names
isConnected = !names.isEmpty
}
private func startDetectionTimer() {
let timer: DispatchSourceTimer = DispatchSource.makeTimerSource(queue: .main)
timer.schedule(deadline: .now() + detectionInterval, repeating: detectionInterval)
timer.setEventHandler { [weak self] in
MainActor.assumeIsolated {
self?.refreshDevices()
}
}
timer.resume()
detectionTimer = timer
}
private func stopDetectionTimer() {
detectionTimer?.cancel()
detectionTimer = nil
}
}
+311
View File
@@ -0,0 +1,311 @@
// MIDIMap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A per-rig map of MIDI foot-controller bindings — which Program Change toggles which control, and
/// which Control Change drives which pedal knob.
///
/// Stored inside the rig (embedded in `ShoeGazeState`) so it travels with a saved rig. Pedals and
/// boards are addressed by **stable UUID** (`Pedal.id` / `PedalBoard.id`, persisted in
/// `PedalState`/`BoardState`), so a binding follows its pedal/board through insert, remove, move,
/// and reorder edits with no reindexing — the id survives the capture → rebuild round-trip. A
/// binding whose target no longer exists simply stops resolving (inert). The `*Hint` fields carry
/// the display name at learn time, for UI labels only (not resolution). Control-within-pedal is
/// still indexed into `Pedal.ccMappableControls`, which is stable for a given pedal type.
public struct MIDIMap: Codable, Equatable, Sendable {
/// Program-Change → action bindings (footswitch toggles). Populated in the switch phase.
public var switches: [SwitchBinding]
/// Control-Change → pedal-knob bindings (expression pedals).
public var ccs: [CCBinding]
/// Computer letter/digit key → action bindings. Same toggle ``Action`` set as ``switches`` —
/// a key press is a software footswitch — but keys never drive continuous CC targets.
public var keys: [KeyBinding]
/// An empty map (no bindings).
public static let empty: MIDIMap = MIDIMap()
/// Creates a MIDI map.
///
/// - Parameters:
/// - switches: Program-Change bindings. Defaults to empty.
/// - ccs: Control-Change bindings. Defaults to empty.
/// - keys: Letter-key bindings. Defaults to empty.
public init(
switches: [SwitchBinding] = [],
ccs: [CCBinding] = [],
keys: [KeyBinding] = []
) {
self.switches = switches
self.ccs = ccs
self.keys = keys
}
private enum CodingKeys: String, CodingKey {
case switches
case ccs
case keys
}
/// Decodes a map, tolerating an absent `keys` list so a rig saved before keyboard mapping
/// existed still decodes with its `switches` / `ccs` intact (synthesized Codable would fail
/// the whole map on the missing key, silently dropping the MIDI bindings too). `encode(to:)`
/// stays synthesized and always writes `keys` (empty when there are none).
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.switches = try container.decode([SwitchBinding].self, forKey: .switches)
self.ccs = try container.decode([CCBinding].self, forKey: .ccs)
self.keys = try container.decodeIfPresent([KeyBinding].self, forKey: .keys) ?? []
}
// MARK: - Action
/// A toggle-style control a footswitch (Program Change) can drive. Program Change is momentary,
/// so boolean actions latch in software; `boardSolo` is exclusive (radio).
public enum Action: Codable, Equatable, Sendable {
case rigBypass
/// Mutes/unmutes the rig output (a hard silence, not a bypass).
case rigMute
/// Mutes/unmutes the input feeding every board (the incoming guitar / mic signal).
case inputMute
/// Cancels any solo and makes every board audible again (the "All" button).
case allBoards
case boardSolo(boardID: UUID)
case boardAudible(boardID: UUID)
case boardBypass(boardID: UUID)
case pedalBypass(pedalID: UUID)
/// A pedal-specific momentary action beyond generic bypass (e.g. a looper's
/// record/stop or reset footswitch). `kind` is opaque to `MIDIMap` — `MIDIController`
/// resolves the target pedal (by id) and dispatches on `kind` itself.
case pedalAction(pedalID: UUID, kind: PedalActionKind)
/// Toggles the rig-level tuner on/off.
case tunerToggle
/// Registers one tap-tempo press (see `ShoeGaze.tapTempo()`).
case tapTempo
}
/// A pedal-specific momentary action addressable by ``Action/pedalAction(pedalID:kind:)``.
/// New pedals with more than a simple bypass toggle add cases here.
public enum PedalActionKind: Codable, Equatable, Sendable {
/// Looper: presses the smart Loop footswitch (record → set end → overdub → play by
/// state) — same as ``looperOverdubToggle``; both dispatch to `LooperPedal.pressLoop()`.
// TODO: collapse looperRecordStop / looperOverdubToggle into one case (both call pressLoop).
case looperRecordStop
/// Looper: presses the smart Loop footswitch (toggles overdub once a loop is playing).
case looperOverdubToggle
/// Looper: flips `loopOn` (loop mute) between `0` and `1`.
case looperLoopToggle
/// Looper: reset — clears all tracks and returns to the clear state.
case looperReset
/// Looper: immediately stops playback (`LooperPedal.stopPlayback()`).
case looperStop
/// Looper: arms / cancels a stop at the loop end (`LooperPedal.toggleStopAtLoopEnd()`).
case looperCueStop
/// Looper: flips playback direction (`LooperPedal.toggleReverse()`).
case looperReverse
/// Looper: cycles the Sync/Free transport mode (`LooperPedal.cycleSyncMode()`).
case looperSyncToggle
/// Looper: taps track `index` (0 = A) — selects it, or mutes it if already selected and
/// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots.
case looperTrack(index: Int)
}
// MARK: - Switch binding
/// A Program-Change number bound to a toggle ``Action``.
public struct SwitchBinding: Codable, Equatable, Sendable {
/// The Program Change number (0–127) that triggers the action.
public var program: UInt8
/// The MIDI channel (0–15), or `nil` to match any channel (omni).
public var channel: UInt8?
/// The control to toggle.
public var action: Action
/// The resolved control's display name at learn time, for stale-binding detection.
public var displayNameHint: String?
/// Creates a switch binding.
///
/// - Parameters:
/// - program: Program Change number (0–127).
/// - channel: MIDI channel (0–15), or `nil` for omni. Defaults to `nil`.
/// - action: The toggle action to perform.
/// - displayNameHint: Resolved control name at learn time. Defaults to `nil`.
public init(
program: UInt8,
channel: UInt8? = nil,
action: Action,
displayNameHint: String? = nil
) {
self.program = program
self.channel = channel
self.action = action
self.displayNameHint = displayNameHint
}
}
// MARK: - Key modifiers
/// The modifier keys that qualify a ``KeyBinding``, so `a` and `⇧a` (and `⌃a`, `⌥a`) are
/// distinct triggers. Shift is a modifier here rather than being folded into the key's case,
/// which keeps the base key a single lowercased character on every platform. Command is
/// deliberately absent — it is reserved for the app's menu keyboard shortcuts.
public struct KeyModifiers: OptionSet, Codable, Equatable, Hashable, Sendable {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
/// The Shift key (`⇧`).
public static let shift: KeyModifiers = KeyModifiers(rawValue: 1 << 0)
/// The Control key (`⌃`).
public static let control: KeyModifiers = KeyModifiers(rawValue: 1 << 1)
/// The Option key (`⌥`).
public static let option: KeyModifiers = KeyModifiers(rawValue: 1 << 2)
}
// MARK: - Key binding
/// A computer letter/digit key bound to a toggle ``Action``. Fires on key-down when no text
/// field is focused; the same latch semantics as a footswitch (booleans flip in software,
/// `boardSolo` is exclusive). `key` is a single lowercased character; ``modifiers`` distinguish
/// `a` from `⇧a`, `⌃a`, and `⌥a`.
public struct KeyBinding: Codable, Equatable, Sendable {
/// The bound key as a single lowercased character (e.g. `"b"`, `"3"`).
public var key: String
/// The modifier keys held with ``key``. Empty for an unmodified press.
public var modifiers: KeyModifiers
/// The control to toggle.
public var action: Action
/// The resolved control's display name at learn time, for stale-binding detection.
public var displayNameHint: String?
/// Creates a key binding.
///
/// - Parameters:
/// - key: The bound key, normalized to a single lowercased character.
/// - modifiers: The qualifying modifier keys. Defaults to none.
/// - action: The toggle action to perform.
/// - displayNameHint: Resolved control name at learn time. Defaults to `nil`.
public init(
key: String,
modifiers: KeyModifiers = [],
action: Action,
displayNameHint: String? = nil
) {
self.key = key
self.modifiers = modifiers
self.action = action
self.displayNameHint = displayNameHint
}
private enum CodingKeys: String, CodingKey {
case key
case modifiers
case action
case displayNameHint
}
/// Decodes a key binding, defaulting `modifiers` to none when absent so a binding saved
/// before modifiers existed still decodes (unmodified, as it was learned). `encode(to:)`
/// stays synthesized.
public init(from decoder: Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.key = try container.decode(String.self, forKey: .key)
self.modifiers = try container.decodeIfPresent(KeyModifiers.self, forKey: .modifiers) ?? []
self.action = try container.decode(Action.self, forKey: .action)
self.displayNameHint = try container.decodeIfPresent(String.self, forKey: .displayNameHint)
}
}
// MARK: - CC target
/// A continuous control an expression pedal can drive — either a specific pedal control (a knob
/// or slider, addressed by index into the pedal's ``Pedal/ccMappableControls``) or a board's
/// master level. The `*Hint` payloads capture the resolved display name at learn time so a
/// binding that no longer matches (chain edited) can be detected and skipped.
public enum CCTarget: Codable, Equatable, Sendable {
/// A knob or slider on a pedal, indexed into `pedal.ccMappableControls`.
case pedalControl(
pedalID: UUID,
controlIndex: Int,
pedalNameHint: String?,
controlLabelHint: String?
)
/// A board's master output level (the board fader).
case boardLevel(boardID: UUID, boardLabelHint: String?)
/// The rig-wide output volume (applies to the whole rig).
case rigVolume
/// Whether two targets address the same control, ignoring the display-name hints (used to
/// find and replace a binding regardless of the name captured at learn time).
public func addresses(_ other: CCTarget) -> Bool {
switch (self, other) {
case let (.pedalControl(p1, c1, _, _), .pedalControl(p2, c2, _, _)):
return p1 == p2 && c1 == c2
case let (.boardLevel(b1, _), .boardLevel(b2, _)):
return b1 == b2
case (.rigVolume, .rigVolume):
return true
default:
return false
}
}
}
// MARK: - CC binding
/// A Control-Change number bound to a pedal knob. The incoming value (0–127) is mapped across
/// the knob's own range; `inverted` swaps heel/toe for reversed expression pedals.
public struct CCBinding: Codable, Equatable, Sendable {
/// The Control Change number (0–127).
public var controller: UInt8
/// The MIDI channel (0–15), or `nil` to match any channel (omni).
public var channel: UInt8?
/// The pedal knob this CC drives.
public var target: CCTarget
/// When `true`, CC 0 maps to the knob's maximum and 127 to its minimum.
public var inverted: Bool
/// Creates a CC binding.
///
/// - Parameters:
/// - controller: Control Change number (0–127).
/// - channel: MIDI channel (0–15), or `nil` for omni. Defaults to `nil`.
/// - target: The pedal knob to drive.
/// - inverted: Reverse the sweep direction. Defaults to `false`.
public init(
controller: UInt8,
channel: UInt8? = nil,
target: CCTarget,
inverted: Bool = false
) {
self.controller = controller
self.channel = channel
self.target = target
self.inverted = inverted
}
}
}
+185
View File
@@ -4,6 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
@@ -52,6 +53,11 @@ open class Pedal: SynthesizerBase {
/// Output gain as a linear multiplier. `1.0` = unity gain.
@UIParam public var level: Double = 1.0
/// Optional path to an external resource this pedal references (e.g. a neural-amp model file).
/// Not a `@UIParam` — it's a `String`, applied at `build()`, and persisted separately in
/// ``PedalState/resourcePath``. Default `nil`. Pedals that don't use an external file ignore it.
public var resourcePath: String?
// MARK: - Sample rate
/// Engine sample rate, injected by `PedalBoard.add(_:)` before the pedal is added
@@ -59,8 +65,37 @@ open class Pedal: SynthesizerBase {
/// safe 48 kHz fallback.
public var sampleRate: Double = 48000.0
// MARK: - Tempo / engine (injected)
/// Shared tempo clock, injected by `PedalBoard.add(_:)` for tempo-aware pedals (the
/// looper's beat-quantized transport). `nil` for pedals added to a board that was
/// created without a clock (e.g. a bare parallel sub-board). Weak: the clock is owned
/// by `ShoeGaze` and outlives every pedal.
public internal(set) weak var clock: LyrebirdClock?
/// The engine that owns this pedal's nodes, injected by `PedalBoard.add(_:)`. Needed by
/// tempo-aware pedals to start a `LyrebirdRoutine` that waits on beat boundaries. Weak:
/// the engine owns the node tree, not the reverse.
public internal(set) weak var hostEngine: SynthesisEngine?
// MARK: - Tempo sync
/// Sync state per tempo-syncable parameter, keyed by ``TempoSyncableParam/key``. A missing
/// key means ``TempoSync/free``. Persisted in ``PedalState`` and restored on rig load.
public internal(set) var tempoSync: [String: TempoSync] = [:]
/// Observable signal bumped on every ``tempoSync`` change so a SwiftUI badge re-renders when the
/// sync state changes through any path (the picker, a preset load, or a lightweight recall).
public let tempoSyncRevision: TempoSyncRevision = TempoSyncRevision()
// MARK: - Identity / routing
/// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI
/// bindings to address the pedal by id rather than by chain position. Defaults to a fresh
/// `UUID` for a newly-created pedal; a rebuild from a saved rig restores the saved id
/// (`board.add(_:)` / preset apply sets it), so a pedal keeps its identity across edits.
public internal(set) var id: UUID = UUID()
/// Human-readable name for the pedal (e.g. "Overdrive", "Delay").
public let displayName: String
@@ -87,6 +122,35 @@ 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`. This sets the card's **base width in knob columns**: `1` = a three-wide card, `≥ 2` =
/// four-wide (and the knob grid packs that many across). It is both the grid's column count and
/// the card's minimum width, so a `2` pedal is a four-wide card even with few knobs (e.g. the
/// Cabinet, to keep its selector captions readable). A pedal whose selector/switch row is wider
/// still pushes wider; values above `2` add nothing. (The looper is the sole exception: it
/// overrides the UI to a fixed multi-column layout scaled by this value.)
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 +241,52 @@ open class Pedal: SynthesizerBase {
[]
}
/// Secondary "advanced" knobs that read best tucked behind a pop-over rather than on the pedal
/// face — deep-cut controls a player reaches for occasionally, not while performing (e.g. an
/// amp's power-amp Sag / Bias / Bias X). When non-empty the pedal card shows a small button that
/// presents these in a popover; when empty no button is drawn. Defaults to empty.
///
/// These are ordinary live `@UIParam` knobs — they round-trip through `PedalState` and are not
/// topology controls (no `rebuildsOnChange`).
open var advancedKnobs: [PedalKnob] {
[]
}
/// Current values of every ``effectSelectors`` and ``effectSwitches`` entry flagged
/// `rebuildsOnChange` — the controls whose choice changes the graph topology (e.g. a cabinet
/// voice or a clean/drive channel). A lightweight recall compares this before/after applying a
/// snapshot to decide whether the board must be rebuilt (a plain node write does not re-enter
/// `effect(_:)`). Empty for pedals with no such controls.
public var rebuildTopologyValues: [Double] {
// Sanitize non-finite to a fixed sentinel: the before/after compare in a recall uses `!=`,
// and `NaN != NaN` would force a spurious rebuild on every recall.
let selectorValues: [Double] = effectSelectors
.filter { $0.rebuildsOnChange }
.map { $0.node.value.isFinite ? $0.node.value : 0.0 }
let switchValues: [Double] = effectSwitches
.filter { $0.rebuildsOnChange }
.map { $0.node.value.isFinite ? $0.node.value : 0.0 }
return selectorValues + switchValues
}
/// Effect-specific transport controls, rendered as a row directly below the knobs — above
/// ``effectButtons``. Use for the persistent state toggles and transport stops that read as
/// a group distinct from the momentary "do it now" actions (e.g. a looper's Loop / Stop /
/// Cue Stop / Reverse). Defaults to empty; a pedal with none simply skips the row.
open var effectTransportButtons: [PedalButton] {
[]
}
/// Effect-specific action buttons for this pedal, rendered as a row of stomp-style
/// buttons beneath the transport row.
///
/// Override in subclasses to publish momentary actions (e.g. "Record / Stop", "Reset")
/// that need a non-RT side effect beyond writing a single parameter value — see
/// ``PedalButton``. Defaults to empty.
open var effectButtons: [PedalButton] {
[]
}
/// All knobs a generic UI should render for this pedal: effect-specific knobs
/// first, then the common `mix` and `level` knobs. The `bypass` parameter is
/// surfaced separately as a header toggle, not as a knob.
@@ -187,6 +297,81 @@ open class Pedal: SynthesizerBase {
]
}
/// Every continuous control on this pedal that a MIDI Control Change can drive — the pedal's
/// knobs (effect knobs + Mix + Level), then its vertical-fader sliders, then its advanced
/// (pop-over) knobs. Discrete controls (switches, stepped selectors) are excluded; they suit
/// Program Change toggles, not CC sweeps.
///
/// Ordering is stable — knobs, then sliders, then advanced knobs (appended last so existing
/// index-addressed CC bindings keep resolving to the same control across launches). Used by MIDI
/// mapping.
public var ccMappableControls: [PedalControl] {
let knobControls: [PedalControl] = knobs.map {
PedalControl(label: $0.label, node: $0.node, range: $0.range)
}
let sliderControls: [PedalControl] = effectSliders.map {
PedalControl(label: $0.label, node: $0.node, range: $0.range)
}
let advancedControls: [PedalControl] = advancedKnobs.map {
PedalControl(label: $0.label, node: $0.node, range: $0.range)
}
return knobControls + sliderControls + advancedControls
}
// MARK: - Tempo sync
/// Parameters this pedal exposes to tempo sync (delay times, LFO rates). Empty by default —
/// override in subclasses whose time- or rate-based parameters can lock to the tempo.
///
/// Each descriptor's ``TempoSyncableParam/key`` must be unique within the pedal and stable
/// across versions (it is the persistence key). Order is the order the sync controls appear.
open var tempoSyncableParams: [TempoSyncableParam] {
[]
}
/// Recomputes and writes every parameter currently locked to a note division, from the shared
/// clock's tempo. Main-thread only — writing a `@UIParam` is the same path as a knob turn.
///
/// A no-op when no clock is injected. Free parameters are left untouched. A synced value that
/// falls outside the parameter's range (a long division past a delay's maximum time) is clamped.
/// Called by `ShoeGaze` whenever the tempo changes and whenever a parameter's sync state changes.
public func applyTempoSync() {
guard let clock: LyrebirdClock = clock else { return }
let bpm: Double = clock.bpm
guard bpm > 0 else { return }
for param: TempoSyncableParam in tempoSyncableParams {
guard case .division(let division) = tempoSync[param.key] ?? .free else { continue }
param.node.update(param.value(for: division, bpm: bpm).value)
}
}
/// Sets one parameter's sync state and immediately recomputes it. Pass ``TempoSync/free`` to
/// return the parameter to knob control (its value stays at the last synced number until the
/// knob moves it), or `.division(_:)` to lock it to a note value of the live tempo.
///
/// - Parameters:
/// - sync: The new sync state.
/// - key: The ``TempoSyncableParam/key`` of the parameter to update.
public func setSync(_ sync: TempoSync, for key: String) {
tempoSync[key] = sync
tempoSyncRevision.bump()
applyTempoSync()
}
/// Whether `node` backs a tempo-syncable parameter currently locked to a note division.
///
/// Used by MIDI to leave a synced parameter alone: its value is derived from the tempo, so a CC
/// write would be immediately overwritten on the next tempo change. Matches by node identity, so
/// it stays correct regardless of control ordering. Returns `false` for a free or non-syncable node.
public func isNodeTempoSynced(_ node: UIParamNode) -> Bool {
for param: TempoSyncableParam in tempoSyncableParams where param.node === node {
if case .division = tempoSync[param.key] ?? .free {
return true
}
}
return false
}
// MARK: - Subclass hook
/// Returns the processed (wet) mono signal for this pedal.
+33 -1
View File
@@ -4,6 +4,7 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
@@ -59,6 +60,10 @@ public final class PedalBoard {
private let engine: SynthesisEngine
/// Shared tempo clock, forwarded to each pedal in `add(_:)` so tempo-aware pedals (the
/// looper) can quantize to beats. `nil` for boards created without one.
private let clock: LyrebirdClock?
/// The bus that feeds the first pedal in the chain.
public let headBus: AudioBus
@@ -89,6 +94,11 @@ public final class PedalBoard {
/// call chains the first pedal after this node automatically (no `after:` arg needed).
public internal(set) var headInputNode: (any Synthesizer)?
/// Stable identity for this board, persisted in ``BoardState`` and used by MIDI bindings to
/// address the board by id rather than by position. Defaults to a fresh `UUID`; a rebuild from
/// a saved rig restores the saved id, so a board keeps its identity across edits and reorders.
public internal(set) var id: UUID = UUID()
/// Display label for the board, shown in the UI. Defaults to `"Board"`; `ShoeGaze`
/// assigns a numbered label (`"Board 1"`, `"Board 2"`, …) when it creates the board.
public var label: String = "Board"
@@ -105,6 +115,22 @@ public final class PedalBoard {
/// `nil` until `finalizeBoard(_:)`.
public internal(set) var crossfadeTimeNode: UIParamNode?
/// The live per-board full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough).
/// `nil` until `finalizeBoard(_:)`. Driven by `ShoeGaze.setBoard(_:bypassed:)`.
public internal(set) var boardBypassNode: UIParamNode?
/// The live rig-wide full-bypass `UIParamNode` (`0` = engaged, `1` = dry passthrough),
/// driven across every board by `ShoeGaze.setRigBypassed(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigBypassNode: UIParamNode?
/// The live rig-wide output-volume `UIParamNode` ([0, 1]), driven across every board by
/// `ShoeGaze.setRigVolume(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigVolumeNode: UIParamNode?
/// The live rig-wide output-mute `UIParamNode` (`0` = audible, `1` = silenced), driven across
/// every board by `ShoeGaze.setRigMuted(_:)`. `nil` until `finalizeBoard(_:)`.
public internal(set) var rigMuteNode: UIParamNode?
/// The output master synth for this board. Set by `ShoeGaze.finalizeBoard(_:)`;
/// used by `ShoeGaze.removeBoard(_:)` to tear down just this board's master.
internal var outputMaster: BoardOutputMaster?
@@ -137,9 +163,13 @@ public final class PedalBoard {
///
/// - Parameters:
/// - engine: The `SynthesisEngine` that will own the pedal nodes.
/// - clock: Shared tempo clock forwarded to tempo-aware pedals (the looper) for
/// beat-quantized transport. Optional; `nil` disables quantization for pedals on
/// this board.
/// - Throws: `BusAllocatorError.noFreeBus` if no mono audio bus is available.
public init(engine: SynthesisEngine) throws {
public init(engine: SynthesisEngine, clock: LyrebirdClock? = nil) throws {
self.engine = engine
self.clock = clock
let head: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
self.headBus = head
self.outputBus = head
@@ -180,6 +210,8 @@ public final class PedalBoard {
/// - `EngineAddError` if the engine rejects the add (e.g. queue full, double-add).
public func add(_ pedal: Pedal, after predecessor: (any Synthesizer)? = nil) throws {
pedal.sampleRate = engine.sampleRate
pedal.hostEngine = engine
pedal.clock = clock
// Each arm configures the pedal's buses, inserts it, advances the tail, and only then
// records it in `pedals` — so a pedal is never tracked unless it was fully wired and
@@ -0,0 +1,95 @@
// PedalButton.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// A UI-agnostic description of one pedal button — a momentary action trigger or a
/// node-bound toggle, rendered as a stomp-style button.
///
/// Where ``PedalSwitch`` describes a multi-position segmented control, `PedalButton`
/// describes a single button in one of two styles:
/// - `.momentary`: runs a closure on each press (e.g. "Record / Stop", "Reset"). Use this
/// whenever pressing the button must also perform a non-RT side effect (clearing a
/// buffer, requesting a recorder reset) beyond writing a single parameter value.
/// - `.toggle`: flips a bound ``UIParamNode`` between `0` and `1` on each press, with no
/// side effect required — appropriate only when the live audio graph itself reads the
/// node continuously (so toggling the raw value is sufficient).
///
/// A `Pedal` publishes an array of these via ``Pedal/effectButtons`` so a generic
/// pedalboard UI can render a footswitch-style button per action without knowing the
/// concrete pedal type.
public struct PedalButton {
/// Style of button behavior, mirroring `ParameterButton.Style` in `LyrebirdUI`.
public enum Style: Equatable {
/// Executes `action` on each press.
case momentary
/// Flips `node` between `0` and `1` on each press.
case toggle
}
/// Short label shown on the button (e.g. "Record", "Reset").
public let label: String
/// Button behavior style.
public let style: Style
/// The live parameter node this button toggles. Non-`nil` only for `.toggle` style.
public let node: UIParamNode?
/// The action run on each press. Non-`nil` only for `.momentary` style.
public let action: (() -> Void)?
/// Optional LED-indicator node for a `.momentary` button. When non-`nil`, the button is
/// drawn in the same LED + footswitch style as a `.toggle` button, with the LED lit while
/// this node reads `≥ 0.5` — letting a momentary action reflect a persistent state (e.g. a
/// looper's Stop lit while stopped, Cue Stop lit while armed). `nil` renders a plain button.
public let indicator: UIParamNode?
/// Optional live caption describing what the *next* press does, polled by the UI. When set,
/// the button shows this instead of the static `label` — letting a state-driven control (the
/// looper's Loop footswitch) read "Record" → "Set End" → "Overdub" → "Play" as the state
/// changes. `nil` shows the static `label`.
public let dynamicLabel: (() -> String)?
/// Creates a momentary action button.
///
/// - Parameters:
/// - label: Short label shown on the button.
/// - indicator: Optional state node driving an LED (see ``indicator``). Defaults to `nil`
/// for a plain button.
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
/// - action: Closure run on each press.
public init(
label: String,
indicator: UIParamNode? = nil,
dynamicLabel: (() -> String)? = nil,
action: @escaping () -> Void
) {
self.label = label
self.style = .momentary
self.node = nil
self.action = action
self.indicator = indicator
self.dynamicLabel = dynamicLabel
}
/// Creates a toggle button bound to a `UIParamNode`.
///
/// - Parameters:
/// - label: Short label shown on the button.
/// - node: The `UIParamNode` projected value of an `@UIParam` property
/// (`pedal.$loopOn`, `pedal.$reverse`, …).
/// - dynamicLabel: Optional live caption describing the next press (see ``dynamicLabel``).
public init(label: String, node: UIParamNode, dynamicLabel: (() -> String)? = nil) {
self.label = label
self.style = .toggle
self.node = node
self.action = nil
self.indicator = nil
self.dynamicLabel = dynamicLabel
}
}
@@ -0,0 +1,38 @@
// PedalControl.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// A continuous pedal control that can be driven by a MIDI Control Change — the common shape of a
/// ``PedalKnob`` and a ``PedalSlider`` (a labelled `UIParamNode` with a value range).
///
/// Used by MIDI mapping to enumerate every CC-assignable control on a pedal uniformly, regardless of
/// how the pedal chose to present it (rotary knob vs vertical fader). Discrete controls (switches,
/// stepped selectors) are intentionally excluded — they suit momentary Program Change bindings, not
/// continuous expression control.
public struct PedalControl {
/// Short display label (e.g. `"Rate"`, `"Position"`).
public let label: String
/// The live parameter node the CC drives.
public let node: UIParamNode
/// Inclusive value range the control spans, in the parameter's own units.
public let range: ClosedRange<Double>
/// Creates a pedal control descriptor.
///
/// - Parameters:
/// - label: Short display label.
/// - node: The live parameter node.
/// - range: Inclusive value range in the parameter's own units.
public init(label: String, node: UIParamNode, range: ClosedRange<Double>) {
self.label = label
self.node = node
self.range = range
}
}
@@ -49,20 +49,31 @@ public struct PedalSelectorKnob {
/// contain at least two.
public let stops: [Stop]
/// When `true`, committing a new stop asks the host to rebuild the board (as the Neural Amp
/// model loader does) instead of relying on the live graph to react to the node value. Use for
/// selectors whose choice changes the *graph topology* — e.g. a cabinet whose voice picks which
/// single convolver is instantiated — rather than a value an always-running node reads live.
/// Defaults to `false`.
public let rebuildsOnChange: Bool
/// Creates a selector-knob descriptor.
///
/// - Parameters:
/// - label: Short label shown beneath the knob.
/// - node: The `UIParamNode` projected value of an `@UIParam` property (`pedal.$voice1`, …).
/// - stops: Ordered stops, CCW → CW. At least two.
/// - rebuildsOnChange: Ask the host to rebuild the board when a new stop is committed. Use for
/// selectors that change graph topology. Defaults to `false`.
public init(
label: String,
node: UIParamNode,
stops: [Stop]
stops: [Stop],
rebuildsOnChange: Bool = false
) {
precondition(stops.count >= 2, "PedalSelectorKnob requires at least two stops")
self.label = label
self.node = node
self.stops = stops
self.rebuildsOnChange = rebuildsOnChange
}
}
+29 -1
View File
@@ -49,6 +49,16 @@ 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
/// When `true`, committing a new position asks the host to rebuild the board — for switches that
/// change the *graph topology* (e.g. a clean/drive channel that adds or removes a gain stage),
/// the same mechanism as ``PedalSelectorKnob/rebuildsOnChange``. Defaults to `false`.
public let rebuildsOnChange: Bool
/// Creates a switch descriptor.
///
/// - Parameters:
@@ -56,14 +66,32 @@ 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`.
/// - rebuildsOnChange: Ask the host to rebuild the board when a new position is committed. Use
/// for switches that change graph topology (e.g. a channel switch). Defaults to `false`.
public init(
label: String,
node: UIParamNode,
options: [Option]
options: [Option],
tempoDependent: Bool = false,
rebuildsOnChange: Bool = false
) {
precondition(options.count >= 2, "PedalSwitch requires at least two options")
self.label = label
self.node = node
self.options = options
self.tempoDependent = tempoDependent
self.rebuildsOnChange = rebuildsOnChange
}
/// 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
}
}
+38
View File
@@ -44,16 +44,45 @@ public struct PedalType: RawRepresentable, Hashable, Sendable {
public extension PedalType {
// Drive & dynamics
static let california = PedalType("California")
static let british = PedalType("British")
static let britishPlexi = PedalType("British Plexi")
static let britishJTM = PedalType("British JTM")
static let britishBluesbreaker = PedalType("British Bluesbreaker")
static let britishMaster = PedalType("British Master")
static let britishDual = PedalType("British Dual")
static let boutiqueLead = PedalType("Boutique Lead")
static let boutiqueOD = PedalType("Boutique OD")
static let caliHiGain = PedalType("Cali Hi-Gain")
static let command = PedalType("Command")
static let citrus = PedalType("Citrus")
static let sixtiesCombo = PedalType("Sixties Combo")
static let magnaVibrato = PedalType("Magna Vibrato")
static let anaheim = PedalType("Anaheim")
static let modernHighGain = PedalType("Modern High-Gain")
static let chime = PedalType("Chime")
static let chimeFifteen = PedalType("Chime 15")
static let chimeNormal = PedalType("Chime Normal")
static let chimeBaby = PedalType("Chime Baby")
static let fullertonReverb = PedalType("Fullerton Reverb")
static let fullertonDeluxe = PedalType("Fullerton Deluxe")
static let fullertonPrinceton = PedalType("Fullerton Ivy League")
static let fullertonDrive = PedalType("Fullerton Drive")
static let jazzClean = PedalType("Jazz Clean")
static let chimeTopBoost = PedalType("Chime Top Boost")
static let neuralAmp = PedalType("Neural Amp")
static let overdrive = PedalType("Overdrive")
static let distortion = PedalType("Distortion")
static let fuzz = PedalType("Fuzz")
static let compressor = PedalType("Compressor")
static let limiter = PedalType("Limiter")
static let noiseGate = PedalType("Noise Gate")
static let cabinet = PedalType("Cabinet")
// EQ & filter
static let graphicEQ = PedalType("Graphic EQ")
static let autoWah = PedalType("Auto-Wah")
static let wah = PedalType("Wah")
static let mutant = PedalType("Mutant")
static let phaser = PedalType("Phaser")
@@ -73,6 +102,9 @@ public extension PedalType {
// Dynamics (additional)
static let sustainer = PedalType("Sustainer")
// Gain (additional)
static let volume = PedalType("Volume")
// Delay & reverb
static let delay = PedalType("Delay")
static let feedbackDelay = PedalType("Feedback Delay")
@@ -81,9 +113,15 @@ public extension PedalType {
static let reverseDelay = PedalType("Reverse Delay")
static let reverb = PedalType("Reverb")
static let shimmerReverb = PedalType("Shimmer Reverb")
static let plateReverb = PedalType("Plate Reverb")
static let roomReverb = PedalType("Room Reverb")
static let springReverb = PedalType("Spring Reverb")
// Pitch & octave
static let octaveSplitter = PedalType("Octave Splitter")
static let bassOctaver = PedalType("Bass Octaver")
static let harmonizer = PedalType("Harmonizer")
// Looper
static let looper = PedalType("Looper")
}
@@ -0,0 +1,472 @@
// AmpVoicePedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Shared base for the tube-amp voice pedals — the fixed-voicing amps and the full-surface amps
/// (those adding onboard reverb / tremolo / chorus and switches via the hooks below).
///
/// Each concrete amp fixes one tone-stack ``ToneStackModel`` and adds one signature control, but
/// shares the common chain built here:
/// ```
/// dry → inputShaping(_:) (subclass hook — e.g. bright switch; default identity)
/// → TriodeStage(drive: gain) (preamp)
/// → ToneStack(bass, mid, treble, model) (fixed per amp)
/// → onboardEffects(_:) (subclass hook — e.g. reverb + tremolo; default identity)
/// → powerAmpStage(_:) (power amp — two TriodeStage halves blended by
/// Bias X; single-stage tone at biasX = 0)
/// → shapeVoice(_:) (subclass signature filter)
/// → applySag(_:) (shared power-supply Sag droop; identity at sag = 0)
/// → ConvolutionReverb(cab IR) (speaker cabinet — voice-selectable, or None for a
/// separate cab block; rebuild on change)
/// → TriodeStage(bias: 0) → Clip(±1) (output soft-limit + hard safety ceiling — always on)
/// ```
/// Fully wet (the amp replaces the dry signal); `Level` is the master. Double-width amp-head card.
///
/// The `tanh` output stage models output-transformer / speaker compression: a real amp has no
/// brickwall, and its analog output can't digital-clip. Small signals pass at ~unit gain (clean
/// playing largely intact); peaks soft-limit toward ±1, adding gentle output compression. Because
/// that soft-limit sits *after* the cab (the overshoot it guards is a digital convolution /
/// oversampling artifact, not literal circuit order) and the `tanh`'s own DC-blocker can leave a
/// sub-percent overshoot, a final `Clip(±1)` hard-clamps the residue so the amp stage never emits a
/// sample past ±1. At the normal master `Level` (≤ 1) that ceiling carries through to the output.
///
/// Subclasses override ``toneStackModel``, ``summaryText``, ``signatureKnobs``, and
/// ``shapeVoice(_:)``, and may set a voice-appropriate default `gain` in their `init`.
open class AmpVoicePedal: Pedal {
// MARK: - Common parameters
/// Preamp **Gain** dial in `[1, 11]` (yes, it goes to eleven). Mapped to the tube-drive range
/// `[1, 30]` through a musical exponential taper — see ``taperedDrive(_:)`` — so low settings give
/// fine control and the top of the dial pushes hard into saturation.
@UIParam public var gain: Double = 6.27
/// Tone-stack bass control in [0, 1].
@UIParam public var bass: Double = 0.5
/// Tone-stack mid control in [0, 1].
@UIParam public var mid: Double = 0.5
/// Tone-stack treble control in [0, 1].
@UIParam public var treble: Double = 0.6
/// Selected cabinet voice as an index into `CabinetVoice.allCases`.
@UIParam public var cab: Double = 0.0
/// Power-amp **Sag** in `[0, 1]`: `0` = stiff (no droop), `1` = heavy power-supply sag/bloom.
/// Surfaced in the advanced pop-over, not on the pedal face. See ``applySag(_:)``.
@UIParam public var sag: Double = 0.0
/// Power-amp **Bias** in `[0, 1]`, mapped to the power-amp `TriodeStage` grid bias. `0.5` = the
/// neutral (symmetric) operating point; lower = colder (tighter, more odd harmonics), higher =
/// hotter (warmer, more even harmonics). Surfaced in the advanced pop-over. See
/// ``powerAmpBiasInput``.
@UIParam public var bias: Double = 0.5
/// Power-amp **Bias X** (bias balance) in `[0, 1]`, default `0` = balanced. At `0` the power amp
/// is a single stage — the shipped tone, exactly. Turning it up spreads the two power-amp
/// half-stages' bias operating points and averages them, re-shaping the saturation knee for a
/// distinct power-amp character (named after the "bias balance" trim on amps that expose one).
/// Surfaced in the advanced pop-over. See `powerAmpStage(_:)`.
@UIParam public var biasX: Double = 0.0
// MARK: - Subclass configuration
/// The fixed tone-stack model for this amp voice. Subclasses override.
open var toneStackModel: ToneStackModel { .fender }
/// One-line description. Subclasses override.
open var summaryText: String { "Tube amp." }
/// The amp's signature knob(s), appended after Gain/Bass/Mid/Treble. Default none.
open var signatureKnobs: [PedalKnob] { [] }
/// Applies the amp's signature post-power-amp shaping (e.g. a bright/presence shelf or a cut
/// low-pass). Default: identity. Subclasses override.
///
/// - Parameter signal: The post-power-amp signal.
/// - Returns: The shaped signal fed to the cabinet.
open func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
signal
}
/// Shaping applied to the dry input *before* the preamp — e.g. a bright-switch treble lift that
/// hits the tubes pre-distortion. Default: identity. Subclasses override.
///
/// - Parameter signal: The dry input signal.
/// - Returns: The shaped signal fed into the preamp.
open func inputShaping(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
signal
}
/// Onboard effects inserted *after* the tone stack and *before* the power amp — the slot a
/// combo amp's built-in reverb and tremolo occupy. Default: identity. Subclasses override.
///
/// - Parameter signal: The post-tone-stack signal.
/// - Returns: The signal fed into the power-amp stage.
open func onboardEffects(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
signal
}
/// Depth scale for the shared ``tremolo(_:speed:depth:enabled:)`` helper — at full depth the
/// unipolar sine swings over half the normalised range, so the peak gain is `1.0` and the trough
/// is `1 − depth`.
private static let tremoloDepthScale: Double = 0.5
/// A unipolar-sine tremolo: `signal ×` an LFO over `[1 − depth·enabled, 1]`. Returns a bit-exact
/// pass-through (a constant-`1.0` LFO) when `depth·enabled == 0`, so a zeroed depth or a
/// footswitch `enabled = 0` is a true identity. Shared by the combo amps' `onboardEffects(_:)`.
///
/// - Parameters:
/// - signal: The signal to amplitude-modulate.
/// - speed: LFO rate in Hz.
/// - depth: Modulation depth in `[0, 1]`.
/// - enabled: Footswitch gate (`0` or `1`) multiplied into the depth.
/// - Returns: The amplitude-modulated signal.
func tremolo(
_ signal: any ValidGeneratorInput,
speed: any ValidGeneratorInput,
depth: any ValidGeneratorInput,
enabled: any ValidGeneratorInput
) -> any ValidGeneratorInput {
let swing: any ValidGeneratorInput = (depth * enabled) * AmpVoicePedal.tremoloDepthScale
let lfo: OscSin.Audio = OscSin.Audio(freq: speed, mul: swing, add: 1.0 - swing)
return signal * lfo
}
/// Maps a `Master` knob `[0, 1]` to a power-amp drive range — the canonical body of a
/// master-volume amp's ``powerAmpDriveInput`` override. Turning Master up drives the power-amp
/// stage harder (real master-volume saturation, unlike `level`).
///
/// - Parameters:
/// - master: The `Master` knob node (`[0, 1]`).
/// - minDrive: Power-amp drive at `master = 0`.
/// - maxDrive: Power-amp drive at `master = 1`.
/// - Returns: The mapped drive to feed the power-amp stage.
func masterDrive(
_ master: any ValidGeneratorInput,
minDrive: Double,
maxDrive: Double
) -> any ValidGeneratorInput {
LinLin.Audio(master, inLo: 0.0, inHi: 1.0, outLo: minDrive, outHi: maxDrive)
}
/// The preamp gain stage — the (post-`inputShaping`) input driven through the first tube stage
/// at `Gain`. Default: one `TriodeStage`. A channel-switching amp overrides this to cascade an
/// extra stage on its drive channel (call `super.preampStage(_:)` for the clean stage first).
///
/// - Parameter signal: The post-`inputShaping` input signal.
/// - Returns: The preamp output fed into the tone stack.
open func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
TriodeStage(input: signal, drive: taperedDrive($gain), bias: preampBias, oversample: preampOversample)
}
/// Maps a `Gain` / `Drive` dial `[1, 11]` to the tube-drive range `[dialDriveMin, dialDriveMax]`
/// through an exponential (musical) taper: `drive = dialDriveMin · (dialDriveMax/dialDriveMin) ^
/// ((dial − 1) / 10)`. A live node, so the dial stays a smooth knob. Every amp's preamp and
/// drive-channel stage runs its dial through this so `1` is nearly clean, `11` is full saturation,
/// and the useful grind spreads across the dial rather than bunching at the bottom.
///
/// - Parameter dial: A `[1, 11]` Gain/Drive knob node.
/// - Returns: The mapped tube drive to feed a `TriodeStage`.
func taperedDrive(_ dial: any ValidGeneratorInput) -> any ValidGeneratorInput {
LinExp.Audio(dial, inLo: dialMin, inHi: dialMax, outLo: dialDriveMin, outHi: dialDriveMax)
}
/// Drive into the power-amp `TriodeStage`. Defaults to the fixed power-amp drive. Two kinds of
/// amp override it: a **master-volume** amp returns a live `Master` knob mapped to a drive range
/// (turning Master up pushes the power-amp stage into saturation — the real master-volume
/// behaviour, unlike `level`, which only attenuates the finished output); a **lower-headroom
/// variant** returns a fixed value *higher* than the default to model an amp that breaks up
/// earlier. Either way, higher drive = more power-amp saturation.
open var powerAmpDriveInput: any ValidGeneratorInput { powerAmpDrive }
/// Oversampling factor for the power-amp stage — `2` or `4`. Any amp that drives the power amp
/// harder than the default fixed value (a `Master` control, or a lower-headroom variant with a
/// higher fixed drive) should override to `4` for more anti-alias headroom, since higher drive
/// generates more high-order harmonics. Defaults to `2` (ample for the lightly-driven fixed
/// power stage of the standard voices).
open var powerAmpOversample: Int { 2 }
/// Grid bias fed to the power-amp `TriodeStage`, from the live `Bias` knob: `[0, 1]` mapped to
/// `[coldPowerAmpBias, hotPowerAmpBias]`. The neutral `bias = 0.5` maps to `0.0`, so the default
/// leaves the power-amp stage symmetric (unchanged from the old fixed bias).
var powerAmpBiasInput: any ValidGeneratorInput {
LinLin.Audio($bias, inLo: 0.0, inHi: 1.0, outLo: coldPowerAmpBias, outHi: hotPowerAmpBias)
}
/// The power-amp stage. **Bias X** (``biasX``) spreads the two `TriodeStage` halves' bias
/// operating points to `powerAmpBiasInput ± (biasX · biasXMaxSpread)` and averages them. At
/// `biasX = 0` both halves share the base bias, so the average is bit-identical to a single stage
/// (the shipped tone); turning `biasX` up widens the spread, re-shaping the saturation character.
///
/// > Note: a deliberate approximation — a *character* control on the single-ended power-stage
/// > model, not a literal push-pull topology (which would re-voice every amp). It reduces to the
/// > exact prior tone at `biasX = 0`. Both halves are always built, so an amp pays two oversampled
/// > stages even at `biasX = 0` — a smooth, live knob was preferred over a rebuild-on-change
/// > single-stage fast path.
///
/// - Parameter signal: The post-`onboardEffects` signal into the power amp.
/// - Returns: The blended power-amp output.
func powerAmpStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let imbalance: any ValidGeneratorInput = $biasX * biasXMaxSpread
let hotHalf: TriodeStage = TriodeStage(
input: signal,
drive: powerAmpDriveInput,
bias: powerAmpBiasInput + imbalance,
oversample: powerAmpOversample
)
let coldHalf: TriodeStage = TriodeStage(
input: signal,
drive: powerAmpDriveInput,
bias: powerAmpBiasInput - imbalance,
oversample: powerAmpOversample
)
return (hotHalf + coldHalf) * powerAmpHalfBlend
}
/// Applies power-supply **Sag**: an `AmplitudeFollower` on `signal` reduces gain as it gets loud
/// (droop) and recovers slowly (bloom). `Sag` scales the depth; at `sag = 0` the droop is `0` and
/// the gain is a constant `1.0` (an identity multiply), so a sag-less amp is unchanged.
///
/// The droop gain is clamped to `[sagGainFloor, 1]`: the envelope tracks a post-power-amp,
/// post-`shapeVoice` signal that can exceed 1 (Presence/Depth shelves), so an unclamped
/// `1 − sag·env` would go negative and phase-invert loud content instead of attenuating it.
///
/// - Parameter signal: The post-`shapeVoice` signal to apply sag to.
/// - Returns: The sagged signal.
func applySag(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let envelope: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
in: signal, attackTime: sagAttackSeconds, releaseTime: sagReleaseSeconds)
let sagGain: any ValidGeneratorInput = Clip.Audio(
1.0 - ($sag * envelope), lo: sagGainFloor, hi: 1.0)
return signal * sagGain
}
// MARK: - Constants
private static let defaultMix: Double = 1.0
/// Preamp grid bias — a little asymmetry for even-harmonic warmth.
private let preampBias: Double = 0.2
/// Oversampling factor for the preamp stage (4× — the preamp can be driven hard by `Gain`).
let preampOversample: Int = 4
/// Grid bias of a cascaded lead/drive `TriodeStage` — a little asymmetry for even-harmonic
/// grind. Shared by the channel/master amps' cascaded ``preampStage(_:)`` overrides.
let leadBias: Double = 0.15
/// Generic `PedalSwitch` off / on values, shared by every amp that publishes switches.
let switchOffValue: Double = 0.0
let switchOnValue: Double = 1.0
/// Gain/Drive dial endpoints and the tube-drive range they taper onto (see ``taperedDrive(_:)``).
/// `11` is the top of the dial; `30` is the maximum tube drive it reaches. `dialDriveMin > 0` is
/// required by `LinExp`.
let dialMin: Double = 1.0
let dialMax: Double = 11.0
let dialDriveMin: Double = 1.0
let dialDriveMax: Double = 30.0
/// Fixed power-amp stage drive (gentler than the preamp).
private let powerAmpDrive: Double = 1.5
/// Power-amp grid bias at `bias = 0` (coldest) and `bias = 1` (hottest). Symmetric about `0`, so
/// the neutral `bias = 0.5` maps to `0.0` — the old fixed power-amp bias — leaving every amp's
/// default tone unchanged. Modest magnitude so the control colours the harmonics without
/// drastically re-voicing the amp.
private let coldPowerAmpBias: Double = -0.25
private let hotPowerAmpBias: Double = 0.25
/// Maximum push-pull bias imbalance at `biasX = 1` — the offset applied oppositely to the two
/// power-amp half-stages. Modest so the control colours the harmonics without destabilising the amp.
private let biasXMaxSpread: Double = 0.35
/// Equal-weight blend of the two power-amp half-stages. `0.5·(hot + cold)` averages them, so at
/// `biasX = 0` (identical halves) the result is bit-identical to a single stage.
private let powerAmpHalfBlend: Double = 0.5
/// Sag envelope-follower attack — moderately fast (the supply starts drooping under load).
private let sagAttackSeconds: Double = 0.02
/// Sag envelope-follower release — slow, so the sag lingers and blooms back (supply recovery).
private let sagReleaseSeconds: Double = 0.30
/// Lowest the sag gain can droop to (~-16 dB). Bounds sag depth and — crucially — keeps the gain
/// strictly positive: the envelope tracks a post-shelf signal that can exceed 1, so an unclamped
/// `1 − sag·env` would go negative and phase-invert loud content instead of drooping.
private let sagGainFloor: Double = 0.15
private let cabinetMix: Double = 1.0
/// Output soft-limit drive. `1.0` gives unit small-signal gain (clean playing untouched) with a
/// hard `tanh` asymptote at ±1 — models output-transformer / speaker compression and keeps the
/// amp from ever digital-clipping the DAC.
private let outputStageDrive: Double = 1.0
/// Symmetric output stage (no even-harmonic bias) — a pure `tanh` limiter, not a tube colour.
private let outputStageBias: Double = 0.0
/// 2× is enough: the cab low-pass already band-limits the signal feeding this stage.
private let outputStageOversample: Int = 2
/// Absolute digital ceiling. The `tanh` stage does the musical soft-limiting; this hard clamp
/// only ever catches the sub-percent overshoot the oversampling filters and DC-blocker can leave
/// just above ±1, guaranteeing the amp stage never emits a sample the DAC would clip.
private let outputCeiling: Double = 1.0
let gainRange: ClosedRange<Double> = 1.0 ... 11.0
let toneRange: ClosedRange<Double> = 0.0 ... 1.0
/// Range for a signature control that maps [0, 1] (Bright / Presence / Cut amount).
let signatureRange: ClosedRange<Double> = 0.0 ... 1.0
/// Cab selector value for the "None (direct)" stop — no speaker convolution. Placed one past the
/// last `CabinetVoice` index so every existing voice keeps its saved index (append-only).
static let cabinetBypassValue: Double = Double(CabinetVoice.allCases.count)
private static let cabStops: [PedalSelectorKnob.Stop] = CabinetVoice.allCases
.enumerated()
.map { (index: Int, voice: CabinetVoice) in
PedalSelectorKnob.Stop(title: voice.displayName, value: Double(index))
}
+ [PedalSelectorKnob.Stop(title: "None (direct)", value: cabinetBypassValue)]
// MARK: - Chrome
/// The amp is fully wet (it replaces the dry signal); hide the Mix control.
public override var showsMixControl: Bool { false }
/// Amps use a four-wide knob grid for their Gain/Bass/Mid/Treble + signature controls (the card
/// width is sized to content — see `PedalView.enclosureWidth`).
public override var widthUnits: Int { 2 }
public override var summary: String { summaryText }
// MARK: - Init
/// Creates an amp voice pedal.
///
/// - Parameters:
/// - name: Display name (the amp voice, e.g. "California").
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
name: String,
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: name,
inputBus: inputBus,
outputBus: outputBus,
initialMix: AmpVoicePedal.defaultMix
)
}
// MARK: - UI
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Gain", node: $gain, range: gainRange),
PedalKnob(label: "Bass", node: $bass, range: toneRange),
PedalKnob(label: "Mid", node: $mid, range: toneRange),
PedalKnob(label: "Treble", node: $treble, range: toneRange),
] + signatureKnobs
}
public override var effectSelectors: [PedalSelectorKnob] {
[
PedalSelectorKnob(
label: "Cab", node: $cab, stops: AmpVoicePedal.cabStops, rebuildsOnChange: true),
]
}
/// Power-amp deep-cut controls, tucked behind the pedal card's advanced pop-over: **Sag**
/// (power-supply droop/bloom), **Bias** (power-amp grid-bias operating point), and **Bias X**
/// (power-amp bias balance). None is a topology control — all are live nodes that round-trip
/// through the rig save format. Order is append-only (persisted positionally in `advancedValues`).
public override var advancedKnobs: [PedalKnob] {
[
PedalKnob(label: "Sag", node: $sag, range: signatureRange),
PedalKnob(label: "Bias", node: $bias, range: toneRange),
PedalKnob(label: "Bias X", node: $biasX, range: signatureRange),
]
}
// MARK: - Effect
/// Preamp → fixed tone stack → power amp → signature shaping → cabinet (or None) → output
/// soft-limit.
///
/// > Note: at most one `ConvolutionReverb` runs — only the voice named by the live `cab` selector
/// > is instantiated, and the "None (direct)" stop instantiates none. The `cab` selector is
/// > `rebuildsOnChange`, so switching cabs (or to/from None) rebuilds the board rather than
/// > running every voice at once.
///
/// The output soft-limit (``outputLimit(_:)``) always runs, cabinet or not, so the ±1 ceiling
/// holds even when the cabinet is bypassed for a separate downstream cab block.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The amped, (optionally) cab-convolved, soft-limited, ceiling-clamped mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
cabinetAndLimit(preCabinetCore(dry))
}
/// The mono pre-cabinet core: `inputShaping → preamp → tone stack → onboardEffects → power amp →
/// shapeVoice`. Factored out of `effect(_:)` so a stereo (widener) amp can split into a stereo
/// stage (e.g. a stereo chorus) between the core and a per-channel ``cabinetAndLimit(_:)``.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The post-power-amp, pre-cabinet mono signal.
func preCabinetCore(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let preShaped: any ValidGeneratorInput = inputShaping(dry)
let preamp: any ValidGeneratorInput = preampStage(preShaped)
let toned: ToneStack = ToneStack(
input: preamp, bass: $bass, mid: $mid, treble: $treble, model: toneStackModel)
let processed: any ValidGeneratorInput = onboardEffects(toned)
let powerAmp: any ValidGeneratorInput = powerAmpStage(processed)
return applySag(shapeVoice(powerAmp))
}
/// True when the `Cab` selector is on the "None (direct)" stop — the amp emits its limited
/// power-amp signal with **no** speaker convolution, so the player can place a separate cabinet
/// block (the standalone `Cabinet` pedal, or a future IR loader) downstream. Read at board-build
/// time; the selector is `rebuildsOnChange`, so toggling it rebuilds the graph.
///
/// > Warning: with no cabinet, the amp sounds raw and fizzy (the power-amp `tanh` with no speaker
/// > low-pass) — expected; a cabinet is what tames the top end.
var isCabinetBypassed: Bool {
guard cab.isFinite else { return false }
// Clamp in Double space before converting: a huge finite `cab` (from a corrupted/hand-edited
// rig) would otherwise trap `Int(_:)` — same defense as `CabinetVoice.voice(atSelectorValue:)`.
let bounded: Double = Swift.min(Swift.max(cab, 0.0), Double(CabinetVoice.allCases.count))
return Int(bounded.rounded()) >= CabinetVoice.allCases.count
}
/// The per-channel cabinet + output stage: cabinet convolver (or a straight pass at the "None"
/// stop) → `tanh` soft-limit → `Clip(±1)` safety clamp. Applied once in mono, or once per channel
/// by a widener amp.
///
/// - Parameter signal: The post-core signal for one channel.
/// - Returns: The (optionally) cab-convolved, soft-limited, ceiling-clamped signal.
func cabinetAndLimit(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
outputLimit(cabinet(signal))
}
/// The selected `CabinetVoice` speaker convolver, or `signal` unchanged when the `Cab` selector
/// is on "None (direct)". Only the voice named by the live `cab` selector is instantiated, so at
/// most one `ConvolutionReverb` runs.
///
/// - Parameter signal: The post-core signal for one channel.
/// - Returns: The cab-convolved signal, or `signal` unchanged when the cabinet is bypassed.
func cabinet(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
guard !isCabinetBypassed else { return signal }
let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cab)
return ConvolutionReverb.Audio(
input: signal,
ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sampleRate),
mix: cabinetMix
)
}
/// The output soft-limit + hard `Clip(±1)` safety ceiling — **always** applied on the amp,
/// cabinet or not, so the ±1 guarantee holds even at the "None (direct)" stop.
///
/// The `TriodeStage(bias: 0)` is a symmetric `tanh` output limiter: cab convolution and signature
/// shelves can push peaks past ±1, which a real analog output soft-compresses rather than
/// hard-clips. Unit small-signal gain keeps clean tones intact; peaks soft-limit toward ±1. The
/// trailing `Clip(±1)` hard-clamps the sub-percent overshoot the `tanh`'s DC-blocker and the
/// halfband filters can leave, so no sample can clip the DAC.
///
/// - Parameter signal: The (optionally cab-convolved) signal for one channel.
/// - Returns: The soft-limited, ceiling-clamped signal.
func outputLimit(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let softLimited: TriodeStage = TriodeStage(
input: signal,
drive: outputStageDrive,
bias: outputStageBias,
oversample: outputStageOversample
)
return Clip.Audio(softLimited, lo: -outputCeiling, hi: outputCeiling)
}
}
@@ -0,0 +1,125 @@
// AnaheimAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// American **hybrid combo** — the Anaheim voice (Music Man lineage): a solid-state-flavoured
/// preamp into a tube power stage, with huge clean headroom, a **Bright** switch, a **Deep**
/// low-end switch, and a built-in **Limiter**.
///
/// Distinct from the all-tube voices: the preamp stage runs symmetric (grid `bias 0`) — no
/// even-harmonic tube warmth, for the cleaner/more clinical solid-state character — and a
/// `LookAheadLimiter` (the amp's onboard limiter) can be switched into the output.
///
/// > Note: the aggressive hard-knee solid-state clipping when pushed is approximated here by the
/// > symmetric preamp + high headroom; a true oversampled hard-clipper is a Lyrebird 1.7.x follow-up.
public final class AnaheimAmpPedal: AmpVoicePedal {
/// Bright switch: `0` = flat, `1` = treble shelf engaged.
@UIParam public var bright: Double = 0.0
/// Deep switch: `0` = flat, `1` = low-end resonance boost engaged.
@UIParam public var deep: Double = 0.0
/// Limiter footswitch: `1` = the built-in output limiter is engaged, `0` = bypassed.
@UIParam public var limiter: Double = 1.0
/// Symmetric preamp bias (solid-state character — no even-harmonic tube warmth).
private let ssPreampBias: Double = 0.0
private let brightFreqHz: Double = 3200.0
private let brightMaxGainDb: Double = 6.0
private let brightSlope: Double = 1.0
private let deepFreqHz: Double = 100.0
private let deepMaxGainDb: Double = 6.0
private let deepSlope: Double = 0.7
/// Limiter ceiling when engaged — below full scale, so it actually tames peaks (a peak
/// compressor, the amp's built-in limiter); when bypassed the ceiling is raised so it never acts.
private let limiterOnCeiling: Double = 0.5
private let limiterOffCeiling: Double = 10.0
private let limiterLookAhead: Double = 0.005
private let limiterRelease: Double = 0.050
public override var toneStackModel: ToneStackModel { .fender }
public override var summaryText: String {
"American hybrid combo — solid-state-flavoured clean, huge headroom, Bright / Deep / Limiter."
}
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Bright",
node: $bright,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
PedalSwitch(
label: "Deep",
node: $deep,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
PedalSwitch(
label: "Limiter",
node: $limiter,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
]
}
/// Creates an Anaheim amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Anaheim", inputBus: inputBus, outputBus: outputBus)
gain = 4.23 // huge clean headroom
cab = 0.0 // American 1×12
}
/// Bright switch: a high-shelf lift ahead of the preamp (identity when off).
public override func inputShaping(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let shelfGainDb: any ValidGeneratorInput = $bright * brightMaxGainDb
return RBJHighShelf.Audio(
input: signal, freq: brightFreqHz, gain: shelfGainDb, slope: brightSlope)
}
/// Symmetric (solid-state-flavoured) preamp stage — `bias 0`, no even-harmonic tube warmth.
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
TriodeStage(input: signal, drive: taperedDrive($gain), bias: ssPreampBias, oversample: preampOversample)
}
/// The built-in limiter, gated by the Limiter switch — placed *before* the power-amp stage (so
/// it limits the driven preamp/tone-stack signal, which can exceed the ceiling, rather than a
/// signal the power-amp `tanh` has already bounded). Off raises the ceiling so it never acts.
///
/// > Note: the `LookAheadLimiter` stays in the chain in both states (only its ceiling changes),
/// > so the amp carries its ~5 ms look-ahead latency whether or not the Limiter is engaged —
/// > a constant, not something the switch toggles.
public override func onboardEffects(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let ceiling: LinLin.Audio = LinLin.Audio(
$limiter, inLo: 0.0, inHi: 1.0, outLo: limiterOffCeiling, outHi: limiterOnCeiling)
return LookAheadLimiter(
in: signal,
maxAmplitude: ceiling,
lookAheadTime: limiterLookAhead,
releaseTime: limiterRelease,
sampleRate: sampleRate
)
}
/// Deep low-shelf (gated by the Deep switch), post power amp.
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let deepGainDb: any ValidGeneratorInput = $deep * deepMaxGainDb
return RBJLowShelf.Audio(input: signal, freq: deepFreqHz, gain: deepGainDb, slope: deepSlope)
}
}
@@ -0,0 +1,92 @@
// BoutiqueAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Shared base for the boutique high-gain amps (Boutique Lead / Boutique OD) — a footswitchable
/// Clean/Lead channel into a master-volume power section, with **Presence** (top-end) and **Depth**
/// (low-end resonance) shaping.
///
/// The Lead channel cascades a second gain stage (set by `Drive`) via ``preampStage(_:)`` — a
/// `rebuildsOnChange` **Channel** switch, so only the selected channel is built. `Master` drives the
/// power-amp stage via ``AmpVoicePedal/masterDrive(_:minDrive:maxDrive:)``. Concrete voices override
/// ``AmpVoicePedal/toneStackModel`` and gain defaults, and may extend the shaping (e.g. a mid boost).
open class BoutiqueAmpPedal: AmpVoicePedal {
/// Presence amount in [0, 1] → 0…`presenceMaxGainDb` of top-end lift.
@UIParam public var presence: Double = 0.4
/// Depth amount in [0, 1] → 0…`depthMaxGainDb` of low-end resonance lift.
@UIParam public var depth: Double = 0.3
/// Master volume in [0, 1] → power-amp drive in [`masterMinDrive`, `masterMaxDrive`].
@UIParam public var master: Double = 0.5
/// Lead-channel preamp gain (the cascaded stage). Dial [1, 11], tapered to tube drive.
@UIParam public var drive: Double = 7.77
/// Channel select: `0` = Clean, `1` = Lead (the cascaded gain stage).
@UIParam public var channel: Double = 0.0
private let presenceFreqHz: Double = 4500.0
private let presenceMaxGainDb: Double = 8.0
private let presenceSlope: Double = 0.7
private let depthFreqHz: Double = 120.0
private let depthMaxGainDb: Double = 6.0
private let depthSlope: Double = 0.7
private let masterMinDrive: Double = 0.5
private let masterMaxDrive: Double = 5.0
private let channelThreshold: Double = 0.5
private let driveRange: ClosedRange<Double> = 1.0 ... 11.0
public override var toneStackModel: ToneStackModel { .marshall }
public override var signatureKnobs: [PedalKnob] {
[
PedalKnob(label: "Presence", node: $presence, range: signatureRange),
PedalKnob(label: "Depth", node: $depth, range: signatureRange),
PedalKnob(label: "Master", node: $master, range: signatureRange),
PedalKnob(label: "Drive", node: $drive, range: driveRange),
]
}
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Channel",
node: $channel,
options: [
PedalSwitch.Option(title: "Clean", value: switchOffValue),
PedalSwitch.Option(title: "Lead", value: switchOnValue),
],
rebuildsOnChange: true
),
]
}
/// Master drives the power-amp stage. 4× oversampling since it can be driven hard.
public override var powerAmpDriveInput: any ValidGeneratorInput {
masterDrive($master, minDrive: masterMinDrive, maxDrive: masterMaxDrive)
}
public override var powerAmpOversample: Int { 4 }
/// Clean preamp, plus a cascaded lead stage on the Lead channel. `channel` is read at
/// board-build time (the switch is `rebuildsOnChange`), so only the selected channel is built.
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let clean: any ValidGeneratorInput = super.preampStage(signal)
guard channel >= channelThreshold else { return clean }
return TriodeStage(input: clean, drive: taperedDrive($drive), bias: leadBias, oversample: preampOversample)
}
/// Presence (top-end high-shelf) then Depth (low-end low-shelf), post power amp.
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let presenceGainDb: LinLin.Audio = LinLin.Audio(
$presence, inLo: 0.0, inHi: 1.0, outLo: 0.0, outHi: presenceMaxGainDb)
let presenced: RBJHighShelf.Audio = RBJHighShelf.Audio(
input: signal, freq: presenceFreqHz, gain: presenceGainDb, slope: presenceSlope)
let depthGainDb: LinLin.Audio = LinLin.Audio(
$depth, inLo: 0.0, inHi: 1.0, outLo: 0.0, outHi: depthMaxGainDb)
return RBJLowShelf.Audio(
input: presenced, freq: depthFreqHz, gain: depthGainDb, slope: depthSlope)
}
}
@@ -0,0 +1,32 @@
// BoutiqueLeadAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Boutique **super-lead** — the SLO-style high-gain singing lead: aggressive cascaded overdrive on
/// the Lead channel, a Master volume, and Presence / Depth power-amp shaping.
///
/// A ``BoutiqueAmpPedal`` fixed to the Soldano tone stack, defaulting to a hot Lead drive.
public final class BoutiqueLeadAmpPedal: BoutiqueAmpPedal {
public override var toneStackModel: ToneStackModel { .soldano }
public override var summaryText: String {
"Boutique super-lead — aggressive cascaded high gain with Master, Presence, and Depth."
}
/// Creates a Boutique Lead amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Boutique Lead", inputBus: inputBus, outputBus: outputBus)
gain = 6.27
drive = 8.76 // hot singing lead
cab = 1.0 // British 4×12
}
}
@@ -0,0 +1,62 @@
// BoutiqueODAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Boutique **overdrive special** — the smooth D-style voice: a Fender-derived clean plus a fluid
/// overdrive channel, a **Mid Boost** switch, a Master volume, and Presence / Depth shaping.
///
/// A ``BoutiqueAmpPedal`` on the smoother American tone stack. The Mid Boost adds a midrange peak
/// (the D-style "PAB" character) on top of the base Presence/Depth shaping.
public final class BoutiqueODAmpPedal: BoutiqueAmpPedal {
/// Mid Boost switch: `0` = flat, `1` = midrange peak engaged.
@UIParam public var midBoost: Double = 0.0
private let midBoostFreqHz: Double = 650.0
private let midBoostMaxGainDb: Double = 6.0
private let midBoostQ: Double = 1.0
public override var toneStackModel: ToneStackModel { .fender }
public override var summaryText: String {
"Boutique overdrive special — smooth D-style OD with a Mid Boost, Master, Presence, and Depth."
}
/// Base Channel switch plus the Mid Boost switch (compose `super`).
public override var effectSwitches: [PedalSwitch] {
super.effectSwitches + [
PedalSwitch(
label: "Mid Boost",
node: $midBoost,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
]
}
/// Creates a Boutique OD amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Boutique OD", inputBus: inputBus, outputBus: outputBus)
gain = 5.73
drive = 7.77
cab = 0.0 // American 1×12
}
/// The base Presence/Depth shaping, plus a Mid Boost peak when the switch is engaged (its gain
/// scales by the switch value, so Off is a true identity, live, no rebuild).
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let shaped: any ValidGeneratorInput = super.shapeVoice(signal)
let midGainDb: any ValidGeneratorInput = $midBoost * midBoostMaxGainDb
return RBJPeakingEQ.Audio(input: shaped, freq: midBoostFreqHz, gain: midGainDb, q: midBoostQ)
}
}
@@ -0,0 +1,69 @@
// BritishAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// British-voiced amp (mid-forward crunch) with a **Presence** lift and a **Master** volume.
///
/// A ``AmpVoicePedal`` fixed to the British tone stack, defaulting to a higher gain for crunch. The
/// Master control drives the power-amp stage (via ``AmpVoicePedal/powerAmpDriveInput``), so raising
/// it adds power-amp saturation — turn `Gain` up for preamp grind and use `Master` to set how hard
/// that hits the power amp, the classic master-volume interplay.
public final class BritishAmpPedal: AmpVoicePedal {
/// Presence amount in [0, 1] → 0…`presenceMaxGainDb` of lift above `presenceFreqHz`.
@UIParam public var presence: Double = 0.4
/// Master volume in [0, 1] → power-amp drive in [`masterMinDrive`, `masterMaxDrive`]. The
/// default maps to ≈1.5 drive — the amp's prior fixed power-amp drive — so the out-of-box tone
/// is unchanged; turn it up for power-amp saturation.
@UIParam public var master: Double = 0.22
private let presenceFreqHz: Double = 4500.0
private let presenceMaxGainDb: Double = 8.0
private let shelfSlope: Double = 0.7
/// Power-amp drive at `master = 0` — barely driven (cleanest power stage).
private let masterMinDrive: Double = 0.5
/// Power-amp drive at `master = 1` — hard into power-amp saturation.
private let masterMaxDrive: Double = 5.0
public override var toneStackModel: ToneStackModel { .marshall }
public override var summaryText: String {
"British crunch — forward mids and bite, with Presence and a Master volume."
}
public override var signatureKnobs: [PedalKnob] {
[
PedalKnob(label: "Presence", node: $presence, range: signatureRange),
PedalKnob(label: "Master", node: $master, range: signatureRange),
]
}
/// Master drives the power-amp stage: `[0, 1]` → `[masterMinDrive, masterMaxDrive]`.
public override var powerAmpDriveInput: any ValidGeneratorInput {
masterDrive($master, minDrive: masterMinDrive, maxDrive: masterMaxDrive)
}
/// 4× oversampling on the power-amp stage — Master can drive it well past the fixed value used
/// by the non-master amps, so the extra anti-alias headroom keeps the added harmonics clean.
public override var powerAmpOversample: Int { 4 }
/// Creates a British amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British", inputBus: inputBus, outputBus: outputBus)
gain = 7.77 // crunch-leaning default
cab = 1.0 // default to the British 4×12 cab
}
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let gainDB: LinLin.Audio = LinLin.Audio(
$presence, inLo: 0.0, inHi: 1.0, outLo: 0.0, outHi: presenceMaxGainDb)
return RBJHighShelf.Audio(input: signal, freq: presenceFreqHz, gain: gainDB, slope: shelfSlope)
}
}
@@ -0,0 +1,69 @@
// BritishBluesbreakerAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// British non-master **2×12 combo** with onboard **tremolo** — the bluesbreaker voice: lower-power
/// Marshall crunch that cleans up with the guitar volume, plus a bias-tremolo.
///
/// A ``BritishComboAmpPedal`` (Presence + Bright) that overlays a tremolo in the onboard-effects
/// slot, with Speed / Intensity knobs and a Tremolo footswitch.
public final class BritishBluesbreakerAmpPedal: BritishComboAmpPedal {
/// Tremolo LFO rate in Hz. Range [0.5, 12].
@UIParam public var speed: Double = 4.0
/// Tremolo depth in [0, 1]. `0` = off, `1` = full swing.
@UIParam public var intensity: Double = 0.0
/// Tremolo footswitch: `1` = engaged, `0` = bypassed (`Speed`/`Intensity` preserved).
@UIParam public var tremoloEnabled: Double = 1.0
private let speedRange: ClosedRange<Double> = 0.5 ... 12.0
private let intensityRange: ClosedRange<Double> = 0.0 ... 1.0
public override var summaryText: String {
"British 2×12 combo — bluesbreaker crunch with tremolo, Presence, and a Bright switch."
}
public override var signatureKnobs: [PedalKnob] {
[
PedalKnob(label: "Presence", node: $presence, range: signatureRange),
PedalKnob(label: "Speed", node: $speed, range: speedRange),
PedalKnob(label: "Intensity", node: $intensity, range: intensityRange),
]
}
/// The base Bright switch plus a Tremolo footswitch (compose `super` so Bright stays in sync).
public override var effectSwitches: [PedalSwitch] {
super.effectSwitches + [
PedalSwitch(
label: "Tremolo",
node: $tremoloEnabled,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
]
}
/// Creates a British Bluesbreaker amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British Bluesbreaker", inputBus: inputBus, outputBus: outputBus)
gain = 6.27
cab = 1.0 // British 4×12 voice (combo 2×12 tonally close enough among our cabs)
}
/// Tremolo (gated by the Tremolo footswitch), inserted after the tone stack.
public override func onboardEffects(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Identity when depth·enabled == 0.
tremolo(signal, speed: $speed, depth: $intensity, enabled: $tremoloEnabled)
}
}
@@ -0,0 +1,64 @@
// BritishComboAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Shared base for the British (Marshall-voiced) amps — the `.marshall` tone stack plus a common
/// **Presence** lift (post-power-amp high-shelf) and a **Bright** switch (pre-preamp high-shelf).
///
/// The non-master voices (Plexi / JTM / Bluesbreaker) run a fixed power-amp drive — loudness comes
/// from cranking `Gain`; the Bluesbreaker additionally overlays tremolo. The master-volume voices
/// (British Master / British Dual) subclass this too, adding a `Master` (via
/// ``AmpVoicePedal/masterDrive(_:minDrive:maxDrive:)``) and a cascaded lead ``preampStage(_:)``.
///
/// Distinct from ``BritishAmpPedal``, the standalone master-volume crunch voice.
open class BritishComboAmpPedal: AmpVoicePedal {
/// Presence amount in [0, 1] → 0…`presenceMaxGainDb` of lift above `presenceFreqHz`.
@UIParam public var presence: Double = 0.4
/// Bright switch: `0` = flat, `1` = treble shelf engaged.
@UIParam public var bright: Double = 0.0
private let presenceFreqHz: Double = 4500.0
private let presenceMaxGainDb: Double = 8.0
private let presenceSlope: Double = 0.7
private let brightFreqHz: Double = 3500.0
private let brightMaxGainDb: Double = 6.0
private let brightSlope: Double = 0.7
public override var toneStackModel: ToneStackModel { .marshall }
public override var signatureKnobs: [PedalKnob] {
[PedalKnob(label: "Presence", node: $presence, range: signatureRange)]
}
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Bright",
node: $bright,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
]
}
/// Bright switch: a high-shelf lift ahead of the preamp (identity when off, live, no rebuild).
public override func inputShaping(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let shelfGainDb: any ValidGeneratorInput = $bright * brightMaxGainDb
return RBJHighShelf.Audio(
input: signal, freq: brightFreqHz, gain: shelfGainDb, slope: brightSlope)
}
/// Presence: a post-power-amp high-shelf lift, `[0, 1]` → `[0, presenceMaxGainDb]` dB.
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let gainDB: LinLin.Audio = LinLin.Audio(
$presence, inLo: 0.0, inHi: 1.0, outLo: 0.0, outHi: presenceMaxGainDb)
return RBJHighShelf.Audio(input: signal, freq: presenceFreqHz, gain: gainDB, slope: presenceSlope)
}
}
@@ -0,0 +1,89 @@
// BritishDualAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// British **dual-channel master-volume** — the 900/DSL-era Marshall: a footswitchable Clean/Lead
/// channel, a Master volume, spring reverb, Presence, and a Bright switch. The modern high-gain
/// British workhorse.
///
/// A ``BritishComboAmpPedal`` (Presence + Bright) that adds a `rebuildsOnChange` **Channel** switch —
/// the Lead channel cascades a second gain stage (set by `Drive`) via ``preampStage(_:)`` — a
/// `Master` (power-amp drive), and spring reverb in the onboard-effects slot.
public final class BritishDualAmpPedal: BritishComboAmpPedal {
/// Master volume in [0, 1] → power-amp drive in [`masterMinDrive`, `masterMaxDrive`].
@UIParam public var master: Double = 0.5
/// Lead-channel preamp gain (the cascaded stage). Dial [1, 11], tapered to tube drive.
@UIParam public var drive: Double = 7.11
/// Spring-reverb wet mix in [0, 1].
@UIParam public var reverb: Double = 0.2
/// Channel select: `0` = Clean, `1` = Lead (the cascaded gain stage).
@UIParam public var channel: Double = 0.0
private let masterMinDrive: Double = 0.5
private let masterMaxDrive: Double = 5.0
/// Channel-select threshold: `>= this` selects the Lead channel.
private let channelThreshold: Double = 0.5
private let driveRange: ClosedRange<Double> = 1.0 ... 11.0
private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0
public override var summaryText: String {
"British dual-channel master-volume — Clean/Lead switching, reverb, Presence, and Bright."
}
public override var signatureKnobs: [PedalKnob] {
super.signatureKnobs + [
PedalKnob(label: "Master", node: $master, range: signatureRange),
PedalKnob(label: "Drive", node: $drive, range: driveRange),
PedalKnob(label: "Reverb", node: $reverb, range: reverbRange),
]
}
public override var effectSwitches: [PedalSwitch] {
super.effectSwitches + [
PedalSwitch(
label: "Channel",
node: $channel,
options: [
PedalSwitch.Option(title: "Clean", value: switchOffValue),
PedalSwitch.Option(title: "Lead", value: switchOnValue),
],
rebuildsOnChange: true
),
]
}
/// Master drives the power-amp stage. 4× oversampling since it can be driven hard.
public override var powerAmpDriveInput: any ValidGeneratorInput {
masterDrive($master, minDrive: masterMinDrive, maxDrive: masterMaxDrive)
}
public override var powerAmpOversample: Int { 4 }
/// Creates a British Dual amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British Dual", inputBus: inputBus, outputBus: outputBus)
gain = 5.73
cab = 1.0 // British 4×12
}
/// Clean preamp, plus a cascaded lead stage on the Lead channel. `channel` is read at
/// board-build time (the switch is `rebuildsOnChange`), so only the selected channel is built.
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let clean: any ValidGeneratorInput = super.preampStage(signal)
guard channel >= channelThreshold else { return clean }
return TriodeStage(input: clean, drive: taperedDrive($drive), bias: leadBias, oversample: preampOversample)
}
/// Spring reverb in the onboard-effects slot (after the tone stack).
public override func onboardEffects(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
SpringReverb.Audio(input: signal, mix: $reverb, sampleRate: sampleRate)
}
}
@@ -0,0 +1,31 @@
// BritishJTMAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// British non-master **JTM** — the earliest Marshall, Bassman-derived: warmer and lower-gain than
/// the plexi Super Lead, a rounder blues-rock crunch.
///
/// A ``BritishComboAmpPedal`` with lower gain and a slightly darker top end.
public final class BritishJTMAmpPedal: BritishComboAmpPedal {
public override var summaryText: String {
"British non-master combo — warm, lower-gain JTM crunch with Presence and Bright."
}
/// Creates a British JTM amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British JTM", inputBus: inputBus, outputBus: outputBus)
gain = 5.73 // warmer, lower-gain than the plexi
treble = 0.5 // a shade rounder on top
cab = 1.0 // British 4×12
}
}
@@ -0,0 +1,53 @@
// BritishMasterAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// British **master-volume lead** — the 800-series single-channel hot-rodded Marshall: a cascaded
/// two-stage preamp for singing lead gain, a Master volume, Presence, and a Bright switch.
///
/// A ``BritishComboAmpPedal`` (Presence + Bright) whose ``preampStage(_:)`` cascades a second gain
/// stage — both driven by `Gain`, so one knob sets the whole preamp grind — and whose `Master`
/// drives the power-amp stage (via ``AmpVoicePedal/masterDrive(_:minDrive:maxDrive:)``).
public final class BritishMasterAmpPedal: BritishComboAmpPedal {
/// Master volume in [0, 1] → power-amp drive in [`masterMinDrive`, `masterMaxDrive`].
@UIParam public var master: Double = 0.5
private let masterMinDrive: Double = 0.5
private let masterMaxDrive: Double = 5.0
public override var summaryText: String {
"British master-volume lead — cascaded 800-series gain with Presence, Master, and Bright."
}
public override var signatureKnobs: [PedalKnob] {
super.signatureKnobs + [PedalKnob(label: "Master", node: $master, range: signatureRange)]
}
/// Master drives the power-amp stage. 4× oversampling since it can be driven hard.
public override var powerAmpDriveInput: any ValidGeneratorInput {
masterDrive($master, minDrive: masterMinDrive, maxDrive: masterMaxDrive)
}
public override var powerAmpOversample: Int { 4 }
/// Creates a British Master amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British Master", inputBus: inputBus, outputBus: outputBus)
gain = 5.73 // cascaded, so already a hot lead at moderate Gain
cab = 1.0 // British 4×12
}
/// Cascaded two-stage preamp: the base stage, then a second `TriodeStage` also driven by `Gain`.
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let stage1: any ValidGeneratorInput = super.preampStage(signal)
return TriodeStage(input: stage1, drive: taperedDrive($gain), bias: leadBias, oversample: preampOversample)
}
}
@@ -0,0 +1,31 @@
// BritishPlexiAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// British non-master **Super Lead** — the classic plexi-panel stack: big, loud, no master volume,
/// clean-ish until cranked and then a singing midrange roar.
///
/// A ``BritishComboAmpPedal`` with higher gain and the 4×12 cab. Presence + Bright; loudness and
/// breakup both come from `Gain`.
public final class BritishPlexiAmpPedal: BritishComboAmpPedal {
public override var summaryText: String {
"British non-master stack — plexi roar with Presence and a Bright switch."
}
/// Creates a British Plexi amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British Plexi", inputBus: inputBus, outputBus: outputBus)
gain = 6.72 // clean-ish until pushed
cab = 1.0 // British 4×12
}
}
@@ -0,0 +1,280 @@
// CabinetPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Speaker-cabinet simulation via impulse-response convolution.
///
/// Convolves the input against a cabinet impulse response using Lyrebird's partitioned FFT
/// convolver (`ConvolutionReverb`). A single convolver is built at `build()` time for the voice the
/// ``cabinet`` selector currently names (each voicing's IR is synthesized in code — our own MIT
/// content, see ``CabinetIRFactory``). Changing the selector asks the host to rebuild the board so
/// only the selected voice's convolver ever runs — one partitioned-FFT convolver, not one per
/// voice. The selection round-trips through the rig save format like every other pedal.
///
/// Signal path (inside `effect(_:)`):
/// ```
/// dry → ConvolutionReverb(ir: cab voice + mic voice) (one IR — mic colour baked in)
/// ├─ (optional) ConvolutionReverb(ir: cab + mic B) → DelayLine(Mic Offset) (parallel 2nd mic)
/// │ blended A·(1−Mic Blend) + Bdelayed·(Mic Blend) (comb of two mics)
/// → RBJHighShelf (Position) → RBJLowShelf (Proximity) (live mic-placement shelves)
/// → LookAheadLimiter(±1) (transparent peak safety)
/// → mono out
/// ```
///
/// The wet/dry mix and bypass are handled by the `Pedal` base class.
///
/// > Note: Loading a user-supplied captured `.wav` cab IR is a planned follow-up (it needs a
/// > persisted file-path field the current `PedalState` doesn't carry); this first version ships
/// > the built-in voicings only.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - `cabinet`: Selects the built-in cabinet voicing (stepped selector over ``CabinetVoice``).
/// - `mic`: Selects the microphone voicing baked into the IR (stepped selector over ``MicVoice``).
/// - `micB`: Optional second mic (stepped selector over ``MicVoice``; No Mic = single mic). When set,
/// a parallel convolver blends in for the classic two-mic technique.
/// - `position` / `proximity`: Live mic-placement shelves in the advanced pop-over (on-axis ↔ edge,
/// distant ↔ close).
/// - `micBlend` / `micOffset`: Advanced pop-over — the A/B balance and the mic-B time offset (comb
/// spacing) when a second mic is engaged.
public final class CabinetPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Speaker-cabinet impulse-response convolution with selectable built-in voicings."
}
/// Four-wide card (same as the amps), so the Cab / Mic / Mic B selector captions — cabinet and
/// mic voice names — stay readable rather than crowding.
public override var widthUnits: Int { 2 }
// MARK: - Parameters
/// Selected cabinet voicing as an index into ``CabinetVoice/allCases``. Snaps to integer
/// stops via the ``cabinet`` selector; read at board-build time by `effect(_:)`, which
/// instantiates only that voice's convolver (the selector is `rebuildsOnChange`).
@UIParam public var cabinet: Double = 0.0
/// Selected microphone voicing as an index into ``MicVoice/allCases`` (`0` = No Mic). Baked into
/// the same IR as the cab voice, so it costs nothing extra at render time. `rebuildsOnChange`.
@UIParam public var mic: Double = 0.0
/// Mic **Position** on the speaker in `[0, 1]`: `0` = on-axis (bright, centred on the dust cap),
/// `1` = cone edge / off-axis (progressively darker). A live high-shelf cut, so it is a smooth
/// knob (no rebake); `0` is a bit-exact 0 dB identity. Surfaced in the advanced pop-over.
@UIParam public var position: Double = 0.0
/// Mic **Proximity** in `[0, 1]`: `0` = distant (flat lows), `1` = close-mic'd (proximity-effect
/// low-end boost). A live low-shelf boost, so it is a smooth knob (no rebake); `0` is a bit-exact
/// 0 dB identity. Surfaced in the advanced pop-over.
@UIParam public var proximity: Double = 0.0
/// Second microphone voicing as an index into ``MicVoice/allCases`` (`0` = No Mic → single mic,
/// the default). When engaged, a **second** convolver runs in parallel and blends with the first
/// (the classic two-mic technique). `rebuildsOnChange` — toggling it adds/removes the convolver.
@UIParam public var micB: Double = 0.0
/// **Mic Blend** in `[0, 1]` between mic A (`0`) and mic B (`1`); `0.5` = equal. Only active when
/// ``micB`` ≠ No Mic. A live blend, so it is a smooth knob. Surfaced in the advanced pop-over.
@UIParam public var micBlend: Double = 0.5
/// **Mic Offset** in `[0, 1]`: the relative time offset of mic B, `0` = aligned, `1` = the maximum
/// spacing. A short live delay on mic B; summing it with the aligned mic A produces the comb
/// filtering of two spaced mics. Only active when ``micB`` ≠ No Mic. Surfaced in the pop-over.
///
/// > Note: intended as a **set-and-leave** spacing control (dial in the comb, then play). It is a
/// > live delay, so *sweeping* it during playback moves the comb — a flanger-like effect rather
/// > than a static mic position.
@UIParam public var micOffset: Double = 0.0
// MARK: - Constants
/// Default wet/dry blend — fully wet; the cabinet sits in-line.
private static let defaultMix: Double = 1.0
/// Convolution is taken fully wet here; the `Pedal` base class provides the user wet/dry mix.
private let convolutionMix: Double = 1.0
/// Output peak ceiling. A true look-ahead limiter holds `|output| ≤` this, taming the peaks a
/// speaker convolution can push past ±1 (an analog cab can't digital-clip) while leaving signals
/// below the ceiling **untouched** — no always-on saturation of clean, below-ceiling material.
private let outputCeiling: Double = 1.0
/// Limiter look-ahead / output delay. Short (2 ms) so the added latency is negligible in-line
/// while still catching the brief convolution-overshoot transients.
private let limiterLookAheadSeconds: Double = 0.002
/// Limiter gain-release time constant — slow enough not to modulate sustained low frequencies.
private let limiterReleaseSeconds: Double = 0.050
/// Mic-position high-shelf corner (Hz) and its maximum cut (dB) at the cone edge (`position = 1`).
/// Moving off-axis toward the cone rolls the top off; on-axis (`0`) is a 0 dB identity.
private let positionShelfFreqHz: Double = 3500.0
private let positionMaxCutDb: Double = 9.0
/// Mic-proximity low-shelf corner (Hz) and its maximum boost (dB) up close (`proximity = 1`) —
/// the proximity-effect bass lift; distant (`0`) is a 0 dB identity.
private let proximityShelfFreqHz: Double = 150.0
private let proximityMaxBoostDb: Double = 6.0
/// Shelf slope for the position / proximity live shelves (gentle, like the amp shelves).
private let placementShelfSlope: Double = 0.7
/// `[0, 1]` range for the Position / Proximity / Mic Blend / Mic Offset pop-over knobs.
private static let placementRange: ClosedRange<Double> = 0.0 ... 1.0
/// Maximum mic-B time offset (seconds) at `micOffset = 1` — a spaced-mic offset (~0.5 m of path
/// difference). Sets both the delay-line size and the comb range: the first notch is at
/// `1 / (2·offset)` Hz, so full offset places it near 330 Hz (`micOffset = 0` = aligned, no comb).
private let maxMicOffsetSeconds: Double = 0.0015
/// Selector stops, one per ``CabinetVoice`` in `allCases` order (value == index).
private static let voiceStops: [PedalSelectorKnob.Stop] = CabinetVoice.allCases
.enumerated()
.map { (index: Int, voice: CabinetVoice) in
PedalSelectorKnob.Stop(title: voice.displayName, value: Double(index))
}
/// Selector stops, one per ``MicVoice`` in `allCases` order (value == index).
private static let micStops: [PedalSelectorKnob.Stop] = MicVoice.allCases
.enumerated()
.map { (index: Int, mic: MicVoice) in
PedalSelectorKnob.Stop(title: mic.displayName, value: Double(index))
}
// MARK: - Init
/// Creates a cabinet pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "Cabinet",
inputBus: inputBus,
outputBus: outputBus,
initialMix: CabinetPedal.defaultMix
)
}
// MARK: - UI
public override var effectSelectors: [PedalSelectorKnob] {
[
PedalSelectorKnob(
label: "Cab", node: $cabinet, stops: CabinetPedal.voiceStops, rebuildsOnChange: true),
PedalSelectorKnob(
label: "Mic", node: $mic, stops: CabinetPedal.micStops, rebuildsOnChange: true),
PedalSelectorKnob(
label: "Mic B", node: $micB, stops: CabinetPedal.micStops, rebuildsOnChange: true),
]
}
/// Mic-placement + dual-mic deep-cut controls, tucked behind the pedal card's advanced pop-over:
/// **Position** (on-axis ↔ cone edge), **Proximity** (distance / bass lift), and — when a second
/// mic is engaged — **Mic Blend** (A/B) and **Mic Offset** (comb spacing). All live (not baked),
/// so they are smooth knobs; none is a topology control. Persisted positionally in
/// `advancedValues` (append-only order).
public override var advancedKnobs: [PedalKnob] {
[
PedalKnob(label: "Position", node: $position, range: CabinetPedal.placementRange),
PedalKnob(label: "Proximity", node: $proximity, range: CabinetPedal.placementRange),
PedalKnob(label: "Mic Blend", node: $micBlend, range: CabinetPedal.placementRange),
PedalKnob(label: "Mic Offset", node: $micOffset, range: CabinetPedal.placementRange),
]
}
// MARK: - Effect
/// Convolves the dry signal against the single selected cabinet + mic IR, then soft-limits.
///
/// Only the voice/mic named by the live selectors is baked, so exactly one partitioned-FFT
/// convolver runs; the mic colour is folded into that same IR at no extra render cost. Changing
/// either selector triggers a board rebuild (both are `rebuildsOnChange`). Synthesizing the short
/// IR happens off the RT thread in `build()`.
///
/// The closing `LookAheadLimiter` is a transparent peak limiter on the **wet** convolution
/// output: a speaker cab is analog and can't digital-clip, and the convolution can push peaks
/// past ±1. Unlike a `tanh` saturator, a look-ahead limiter leaves signals **below** the ceiling
/// bit-for-bit untouched (no coloration of clean, below-ceiling material) and only pulls gain
/// down for the brief peaks that would exceed ±1. It adds a short (2 ms) output delay. At the
/// default fully-wet `mix` this bounds the pedal output to ±1 (e.g. a decoupled amp → cabinet
/// chain); a partial `mix` re-introduces the dry signal via the base class's equal-power
/// crossfade, so at intermediate settings final level is the board's output-stage concern. The
/// 2 ms wet delay is uniform at the default fully-wet mix; at a partial mix it sits against the
/// undelayed dry path, so a slight comb is expected there (a cab is normally run fully wet).
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: The cabinet-convolved, mic-voiced, peak-limited mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let sr: Double = sampleRate
let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cabinet)
let micVoice: MicVoice = MicVoice.voice(atSelectorValue: mic)
let convolved: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: dry,
ir: CabinetIRFactory.makeIR(voice: voice, mic: micVoice, sampleRate: sr),
mix: convolutionMix
)
let mixed: any ValidGeneratorInput = blendSecondMic(dry: dry, primary: convolved, voice: voice, sr: sr)
let placed: any ValidGeneratorInput = applyPlacement(mixed)
return LookAheadLimiter(
in: placed,
maxAmplitude: outputCeiling,
lookAheadTime: limiterLookAheadSeconds,
releaseTime: limiterReleaseSeconds,
sampleRate: sr
)
}
/// Blends a second microphone into the primary convolution when ``micB`` ≠ No Mic — the classic
/// two-mic technique. A parallel convolver (same cab voice, mic B's IR) is delayed by up to
/// ``maxMicOffsetSeconds`` (``micOffset``) and summed with the aligned primary at the ``micBlend``
/// balance; the time offset between the two coherent copies produces comb filtering. When ``micB``
/// is No Mic (the default) the primary is returned unchanged — no second convolver is built, so
/// the single-mic path costs exactly one convolution and is bit-identical to before this feature.
///
/// - Parameters:
/// - dry: The dry input (fed to the second convolver).
/// - primary: The primary (mic A) convolution output.
/// - voice: The cabinet voice (shared by both mics).
/// - sr: Engine sample rate.
/// - Returns: The single- or dual-mic blended signal.
private func blendSecondMic(
dry: any ValidGeneratorInput,
primary: any ValidGeneratorInput,
voice: CabinetVoice,
sr: Double
) -> any ValidGeneratorInput {
let micBVoice: MicVoice = MicVoice.voice(atSelectorValue: micB)
guard micBVoice != .off else { return primary }
let secondary: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: dry,
ir: CabinetIRFactory.makeIR(voice: voice, mic: micBVoice, sampleRate: sr),
mix: convolutionMix
)
let delaySeconds: LinLin.Audio = LinLin.Audio(
$micOffset, inLo: 0.0, inHi: 1.0, outLo: 0.0, outHi: maxMicOffsetSeconds)
let delayedSecondary: DelayLine = DelayLine(
input: secondary, maxDelay: maxMicOffsetSeconds, delay: delaySeconds, sampleRate: sr)
// Coherent (same-source) mics sum linearly: A·(1−blend) + Bdelayed·blend.
return primary * (1.0 - $micBlend) + delayedSecondary * $micBlend
}
/// Applies the live mic-placement shelves to the convolved signal: a **Position** high-shelf that
/// rolls the top off as the mic moves off-axis toward the cone edge, then a **Proximity**
/// low-shelf that lifts the low end as the mic moves closer. Both map their knob `[0, 1]` to a
/// shelf gain in dB with `0` → `0` dB, so at the default (`0, 0`) each shelf is a bit-exact
/// identity and the cabinet sounds exactly as it did before placement existed.
///
/// - Parameter signal: The (single- or dual-mic) convolved signal.
/// - Returns: The placement-shaped signal.
private func applyPlacement(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let positionCutDb: LinLin.Audio = LinLin.Audio(
$position, inLo: 0.0, inHi: 1.0, outLo: 0.0, outHi: -positionMaxCutDb)
let positioned: RBJHighShelf.Audio = RBJHighShelf.Audio(
input: signal, freq: positionShelfFreqHz, gain: positionCutDb, slope: placementShelfSlope)
let proximityBoostDb: LinLin.Audio = LinLin.Audio(
$proximity, inLo: 0.0, inHi: 1.0, outLo: 0.0, outHi: proximityMaxBoostDb)
return RBJLowShelf.Audio(
input: positioned, freq: proximityShelfFreqHz, gain: proximityBoostDb, slope: placementShelfSlope)
}
}
@@ -0,0 +1,85 @@
// CaliHiGainAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// California **Mark-series high-gain** — the cascaded lead voice defined by its onboard **5-band
/// graphic EQ**: the sliders sculpt the famous scooped "V" lead tone on top of the amp's own gain.
///
/// A ``BoutiqueAmpPedal`` (Clean/Lead channel, Master, Presence, Depth) that adds a graphic-EQ bank
/// in ``shapeVoice(_:)`` — a low shelf, three peaks, and a high shelf, each a dB fader — cascaded
/// after the base Presence/Depth shaping. Defaults to a gentle V.
public final class CaliHiGainAmpPedal: BoutiqueAmpPedal {
/// Graphic-EQ band gains in dB, range [-12, 12]. Defaults form a mild scooped "V" — the
/// Mark-series signature.
/// 80 Hz low-shelf gain in dB.
@UIParam public var eq80: Double = 2.0
/// 240 Hz peaking gain in dB.
@UIParam public var eq240: Double = 0.0
/// 750 Hz peaking gain in dB (the mid-scoop band).
@UIParam public var eq750: Double = -5.0
/// 2.2 kHz peaking gain in dB.
@UIParam public var eq2200: Double = 0.0
/// 6.6 kHz high-shelf gain in dB.
@UIParam public var eq6600: Double = 3.0
private let eq80Freq: Double = 80.0
private let eq240Freq: Double = 240.0
private let eq750Freq: Double = 750.0
private let eq2200Freq: Double = 2200.0
private let eq6600Freq: Double = 6600.0
/// Shelf slope for the outer graphic-EQ bands.
private let eqShelfSlope: Double = 1.0
/// Peaking-band Q — moderate bandwidth so adjacent graphic-EQ bands overlap smoothly.
private let eqPeakQ: Double = 0.9
private let bandGainRange: ClosedRange<Double> = -12.0 ... 12.0
public override var toneStackModel: ToneStackModel { .mesa }
public override var summaryText: String {
"California Mark-series high gain with an onboard 5-band graphic EQ (scooped-V lead)."
}
/// The five graphic-EQ bands as vertical faders (dB), rendered as a slider bank.
public override var effectSliders: [PedalSlider] {
[
PedalSlider(label: "80", node: $eq80, range: bandGainRange),
PedalSlider(label: "240", node: $eq240, range: bandGainRange),
PedalSlider(label: "750", node: $eq750, range: bandGainRange),
PedalSlider(label: "2.2k", node: $eq2200, range: bandGainRange),
PedalSlider(label: "6.6k", node: $eq6600, range: bandGainRange),
]
}
/// Creates a Cali Hi-Gain amp.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Cali Hi-Gain", inputBus: inputBus, outputBus: outputBus)
gain = 6.27
drive = 9.15 // hot Mark-style lead
cab = 1.0 // British 4×12 — tight and aggressive
}
/// Base Presence/Depth shaping, then the 5-band graphic EQ (low shelf → 3 peaks → high shelf),
/// each band's gain in dB from its fader.
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let shaped: any ValidGeneratorInput = super.shapeVoice(signal)
let low: RBJLowShelf.Audio = RBJLowShelf.Audio(
input: shaped, freq: eq80Freq, gain: $eq80, slope: eqShelfSlope)
let lowMid: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
input: low, freq: eq240Freq, gain: $eq240, q: eqPeakQ)
let mid: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
input: lowMid, freq: eq750Freq, gain: $eq750, q: eqPeakQ)
let highMid: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
input: mid, freq: eq2200Freq, gain: $eq2200, q: eqPeakQ)
return RBJHighShelf.Audio(
input: highMid, freq: eq6600Freq, gain: $eq6600, slope: eqShelfSlope)
}
}

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