57 Commits

Author SHA1 Message Date
josh f8926ecfb8 fix(mutant): double-width pedal so switch captions don't wrap — 3.1.1
The Mutant envelope filter's three segmented switches (Direction / Mode /
Range — seven segments total) were crammed into a single-width pedal, so the
"Down" caption wrapped to "Do wn". Mutant is now double-width, like the
Cabinet and amp pedals, giving the switch row room for its captions.

Bumps both apps to MARKETING_VERSION 3.1.1 and records the fix in
CHANGELOG.md / RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-13 20:04:56 -07:00
josh 9873dd258b fix(rigs): don't let starter overwrites be reverted by reseeding
External-review findings for 3.1.0:

- A starter rig can no longer be overwritten in place. Saving over a loaded
  starter previously stored the edited content under the rig's fixed factory
  id, so the next starter-catalog update (or Restore Starter Rigs) would
  silently revert it to the shipped version. The confirmation now offers only
  Save as New Rig / Cancel — a starter is managed content, and the player's
  changes are kept as their own rig (a new id) instead.
- restoreStarterRigs advances the seed-version marker only on success, matching
  start(), so a failed manual restore no longer suppresses the next launch's
  automatic catch-up seed.
- CHANGELOG: correct the starter-rig count (18, not 19).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-13 10:38:26 -07:00
josh fc6ddb8d9a Merge branch 'feature/factory-rig-library' — ShoeGaze 3.1.0
Starter rigs (19 shipped, category-grouped, Mine/Starters sidebar),
Vibe and Sustain Fuzz pedals, a deeper Mutant envelope filter
(Range/Sweep/Attack/Release), input-preserved rig switching, tamed
shimmer defaults, an overwrite guard for starter rigs, ChainRouter
persistence, and refreshed release docs.
2026-08-13 10:19:18 -07:00
josh 812a240e55 chore(release): prep 3.1.0 (RELEASES backfill, version + dep pin)
- RELEASES.md: backfill the 3.0.0 (amp modeling) and 3.1.0 (starter rigs)
  narrative entries so the release doc is current again.
- Bump the macOS app to MARKETING_VERSION 3.1.0 (build 19).
- Pin the iOS app's resolved Lyrebird to 1.7.2 (was 1.2.3).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-13 10:17:21 -07:00
josh 93ca9076d2 docs: 3.1.0 release notes, README refresh, Help + version bump
- CHANGELOG: add the 3.1.0 entry (starter rigs, Mine/Starters sidebar, Vibe
  and Sustain Fuzz pedals, Mutant Range/Sweep/Attack/Release, input-preserved
  rig switching, shimmer defaults, overwrite guard, router persistence).
- README: correct the pedal count (36 -> 67, incl. 26 amp models), add the
  Amp Model and Cabinet catalog rows and the new pedals, add a Starter Rigs
  feature, and bump the Lyrebird requirement to 1.7.0+.
- Help: add a "Starter Rigs" topic and note that switching rigs keeps the
  current input.
- Bump the iOS app MARKETING_VERSION to 3.1.0 to match macOS.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-13 09:58:34 -07:00
josh 4a9bf0fb30 feat(mutant): add Range switch, Sweep, and Attack/Release controls
The envelope filter's cutoff sweep was fixed (80 Hz -> 3200 Hz, 5 ms / 150 ms),
so it read as either muted (resting too low) or extreme (40x span). The
underlying MuTronIII generator already takes freqLo/freqHi/attack/release as
live params, so expose them:

- Range switch (Lo/Hi) on the face — shifts the whole sweep window low
  (rhythm/bass) or high (harmonics/solos), matching the original Mu-Tron III.
- Sweep, Attack, Release in the advanced pop-over — Sweep sets how far input
  amplitude drives the cutoff (peak = resting x sweep); Attack/Release shape
  the envelope response.
- Tamer defaults: resting 80 -> 120 Hz, span 40x -> 20x.

Serialization-safe: new continuous params live in advancedValues and Range is
a trailing switch, so a rig saved with the old 2-switch / no-advanced layout
loads unchanged with the new controls at their defaults (test covers it).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-13 09:42:52 -07:00
josh 850b86209a fix(shimmer): lower default + starter decay/shimmer to avoid self-oscillation
The shimmer reverb's regenerating loop gain is ~decay + shimmer, so hot
values screech into sustained feedback with little or no input. The pedal
defaults summed to 1.3 (0.8 + 0.5) — over unity on a fresh add — and several
starter rigs ran 1.3–1.6.

- Pedal defaults: decay 0.8 -> 0.5, shimmer 0.5 -> 0.25, damp 0.4 -> 0.5
  (sum 0.75), with a doc note on keeping decay + shimmer < 1.
- Starter rigs using it (Dreampop Chorus Cathedral, Ambient Shimmer Bed,
  Post-Rock Crescendo, Comfortably Numb Lead): decay/shimmer pulled down so
  each sums to ~0.8 or less; damping raised. Bumped seedVersion to 4 so
  existing libraries refresh.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 14:59:58 -07:00
josh 2aea609f34 feat(rigs): ship the tweaked Garcia rig as a captured state
Replace the code-built Garcia with the user's hand-authored version,
transcribed verbatim as a ShoeGazeState: Board 1 (Bass Octaver, Mutant,
Overdrive, Graphic EQ, Phaser, Delay, Fullerton Reverb) and Board 2
(Overdrive, Graphic EQ, Compressor, Fullerton Reverb), preserving exact mix,
graphic-EQ slider, cab-selector and amp sag/bias values. Input source and
channel counts are omitted so the rig stays input-agnostic.

Adds a FactoryRigBuild.state case (and matching FactoryRig init) for rigs
shipped as a pre-captured state rather than a live builder, and bumps
seedVersion to 3 so existing libraries refresh Garcia to the new version.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-10 17:04:58 -07:00
josh 44e6c35550 fix(rigs): don't flag a rig dirty over input/channel differences
Switching between starter rigs prompted "save changes?" even when nothing
was edited. The unsaved-changes check compared full ShoeGazeState snapshots
(`captureState() != entry.state`), which include the live input source and
engine channel counts — and those legitimately differ from a factory rig's
saved values now that a rig switch preserves the player's current input
instead of adopting the rig's saved one.

Add ShoeGazeState.hasSameRigContent(as:) comparing only rig content (boards,
routers, MIDI map, tempo) and use it for the dirty check, so session/engine
settings no longer register as unsaved changes. Test added.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-10 16:40:35 -07:00
josh 5decdd8693 fix(rigs): refresh stale starters on update; tab follows current rig
- Seeding now (re)installs every starter by stable id, so a corrected rig
  definition replaces the stale copy already in a library (save upserts by
  id, keeping its position) — user rigs untouched. Bumped seedVersion to 2
  so existing libraries pick up the two-board Garcia rig (the old router
  version showed "No board at index 0" because the builder UI renders boards,
  not routers, and the stale entry was never refreshed). "Restore Starter
  Rigs" likewise refreshes all starters, not just missing ones.
- The Mine/Starters toggle now opens on the group containing the currently
  loaded rig (Starters when a factory rig like Garcia is active, else Mine),
  and follows the selection when the current rig changes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 17:57:57 -07:00
josh 132515b4cd fix(rigs): address starter-rig feedback (toggle, Garcia, shimmer, input)
- Center the Mine/Starters toggle in the sidebar column.
- Garcia rig: build it as two plain boards (effects + clean) selected via
  the multi-board Solo/Blend control, instead of a ChainRouter — the builder
  UI renders boards, not routers, so the router version showed empty boards.
- Dreampop Chorus Cathedral: lower shimmer decay/feedback and delay feedback
  so the octave-up regeneration no longer screeches into runaway feedback.
- Preserve the current input across rig switches: loadRig gains a
  keepingCurrentInput flag (default false → file open / launch restore still
  apply the rig's saved input; RigStore session-restore continuity intact),
  and the rig-switch path (loadEntry) passes true so a live guitar isn't
  snapped back to the test tone when changing rigs. Tests updated to cover
  both directions.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 14:36:49 -07:00
josh 392ae1525a fix(ui): split builder presentation chain to satisfy the type-checker
The factory-overwrite confirmation dialog pushed ShoeGazeBuilderView's
already-large presentation modifier chain past the Swift expression
type-checker's budget — it compiled under `swift build` but failed the
Xcode app build with "unable to type-check this expression in reasonable
time". Extract the first half of the chain into a `chromeWithPrompts`
computed property so each half type-checks quickly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 14:20:04 -07:00
josh ad6ed41674 feat(ui): Mine/Starters rig toggle + seed starters into existing libraries
Two fixes so shipped starter rigs are actually reachable:

- Seeding no longer requires an empty library. On launch it installs any
  factory rigs whose stable ids are missing, once per FactoryRigLibrary
  .seedVersion (a per-device UserDefaults marker). Existing users therefore
  receive the starters on their next launch; a starter the user later
  deletes stays deleted (the marker has advanced); bumping seedVersion when
  new starters ship re-runs catch-up for just the new ones. Idempotent by id,
  so iCloud-synced devices never duplicate.
- Sidebar gains a segmented Mine / Starters toggle. "Mine" is the flat,
  reorderable user list; "Starters" groups the shipped rigs by category. A
  "Restore Starter Rigs" action (Starters empty-state button + library menu)
  re-installs missing starters on demand via RigLibraryBootstrap.restoreStarterRigs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 14:11:22 -07:00
josh fba32ff0aa feat(ui): group factory rigs by category in the rig sidebar
The rig-library sidebar now presents shipped starter rigs under their
FactoryRigCategory headers (Shoegaze Walls, Dreampop, Classic, Ambient,
Experimental) in fixed catalog order, with the user's own rigs under a
"My Rigs" header. Starter rows show a "Starter rig" subtitle and are not
reorderable; user rows keep drag-to-reorder and Move Up/Down (now scoped to
the user's own rigs). Grouping is presentational, so it stays correct
regardless of underlying library order.

Adds FactoryRigLibrary.category(for:) and rigs(in:) with tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 13:53:56 -07:00
josh 2c970aa344 refactor(rigs): address external-review findings
- Recall router state in applyState: the lightweight (no-rebuild) recall path
  now positionally applies router branch pedal params and the splitter/merger
  blend, instead of silently dropping them for routed rigs. Test added.
- Simplify first-run seeding: RigLibraryStore.save persists asynchronously
  (best-effort, logged not thrown), so the previous per-entry rollback could
  never fire for a real disk failure. Replaced with an honest best-effort
  save + working-rig fallback, and a comment stating the semantics.
- Move FactoryRigBuild to its own file (one public type per file).
- Document that a router's output master gain is intentionally not persisted,
  matching BoardState's treatment of board master gain.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 13:32:58 -07:00
josh 7dccf596f4 feat(rigs): persist chain routers + add Garcia two-board split rig
Add ChainRouter persistence so routed multi-board rigs survive save/load —
previously captureState/loadRig only handled plain boards, so any A/B router
rig was silently lost on save (a latent gap this fixes for user rigs too).

- New ChainRouterState (Codable): each router's two linear branches as
  [PedalState] plus splitter branch levels and merger output levels.
- ShoeGazeState gains an additive `routers` field decoded with
  decodeIfPresent (nil for old rigs) — no format-version bump; routerless
  rigs stay byte-identical (nil, not []).
- captureState snapshots routers; rebuildAllBoards reconstructs each via
  makeChainRouter/addTo{A,B}/finalize and restores the blend.

FactoryRig gains a session-scoped builder variant (FactoryRigBuild enum) so
a rig can create its own boards/routers; makeEntries branches on it.

Ships the Garcia OBEL Clean/Effects Split: an effects/lead board (octave,
envelope filter, overdrive, phaser, delay, amp) vs a clean direct board,
selectable via the router — showcasing the multi-board capability.

Tests: full router capture -> JSON -> load round-trip with structure and
branch-level assertions plus a render check, backward-compat (no routers
key when routerless), and the Garcia rig via the factory load+render suite.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 13:19:42 -07:00
josh 75b99a547b feat(pedals): add Sustain Fuzz pedal + Gilmour/doom rigs
New "Sustain Fuzz": a mid-scooped, high-sustain fuzz distinct from the
single-stage Fuzz. Two cascaded soft-clip (softClipNormalized) stages
compress and stack harmonics for smooth violin-like sustain; a fixed
midrange scoop (RBJPeakingEQ cut at 750 Hz) hollows the mids; a tone
low-pass sets the top end. Sustain/Tone/Scoop knobs. Composed in effect(),
no new RT generator.

Registered in PedalType/PedalRegistry, enclosure colour, palette order.
Tests cover build+non-silent, each knob changing output, knob listing,
preset round-trip.

Adds two factory rigs: Comfortably Numb Lead and Doom Riff Wall.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 13:10:16 -07:00
josh 965633de34 feat(pedals): add Vibe pedal + Psychedelic Vibe Lead rig
New "Vibe" pedal: a photocell-style vibe built as four staggered all-pass
stages swept by one shared sine LFO (unequal centre frequencies give the
uneven, vocal throb that distinguishes a vibe from a phaser). Speed and
Intensity knobs, Chorus/Vibrato mode switch (chorus blends dry+swept,
vibrato passes swept only). Composed from RBJAllPass in effect(), mirroring
PhaserPedal — no new RT generator.

Registered in PedalType/PedalRegistry, enclosure colour, and palette order.
Tests cover build+non-silent, each control measurably changing output, the
knob/switch listing, and preset round-trip.

Adds the Psychedelic Vibe Lead factory rig (Fuzz -> Vibe -> Delay -> Plate).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 13:06:17 -07:00
josh 779c55493d feat(rigs): add six more single-board starter rigs
Extend the factory catalog from 8 to 14 using existing pedals: Funk
Envelope Clav, Nashville Clean Comp, Rockabilly Slapback (classic),
Post-Rock Crescendo, Dub Delay Throw (ambient), and Ring-Mod Texture
(experimental). All build/load/render green via the existing tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 12:58:23 -07:00
josh bb418ca2e8 feat(rigs): confirm before overwriting a built-in factory rig
Saving over a currently-loaded factory rig now shows a confirmation dialog
instead of silently replacing the shipped original: Overwrite (destructive),
Save as New Rig… (new id, keeps the original), or Cancel. The pending
follow-up (e.g. the Save & Clear clear step) is threaded through all three
paths.

Adds FactoryRigLibrary.factoryIDs / isFactory(_:) so the UI can tell a
shipped rig from a user rig by id, with a test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 12:42:03 -07:00
josh 4eb1cbdd61 feat(rigs): ship built-in factory starter rigs
Add a factory rig library: 8 curated starter pedalboard rigs seeded into
an empty rig library on first launch. Rigs are compile-checked builders
(construct concrete pedals, set typed @UIParam values, board.add) rather
than hand-written JSON, so a renamed pedal control is a build error, not a
silently corrupted preset.

Seeding builds each rig in a throwaway offline (never-started) engine,
captures a RigEntry with a stable per-rig UUID (idempotent re-seed), and
saves to the store. Bootstrap rolls back this run's saves if any store.save
fails, so a partial library can't freeze future seeding (gated on isEmpty).

Rigs are named/described by sound, not trademarked products or artists; a
test guards against brand names leaking into names/blurbs. Full ship-path
test loads and renders every rig to non-silent output.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-09 12:37:34 -07:00
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
90 changed files with 5296 additions and 434 deletions
+126
View File
@@ -4,6 +4,132 @@ 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 [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[semantic versioning](https://semver.org/spec/v2.0.0.html). [semantic versioning](https://semver.org/spec/v2.0.0.html).
## [3.1.1] — 2026-08-13
### Fixed
- **Mutant switch captions no longer wrap.** The envelope filter's three segmented switches
(Direction / Mode / Range — seven segments in all) were crammed into a single-width pedal,
wrapping the "Down" caption to "Do wn". Mutant is now double-width, like the Cabinet and amp
pedals, so the switch captions have room.
## [3.1.0] — 2026-08-13
Starter rigs and a deeper envelope filter. ShoeGaze now ships a library of ready-to-play
rigs grouped by style, two new pedals, and a much more expressive Mutant envelope filter —
plus a batch of rig-switching and reverb fixes.
### Added
- **18 built-in starter rigs**, seeded into the library on first launch and grouped by
style — **Shoegaze Walls**, **Dreampop**, **Classic**, **Ambient**, and **Experimental**.
A **Mine / Starters** toggle at the top of the rig sidebar switches between your own rigs
and the shipped ones (grouped under category headers); the sidebar opens on whichever
group holds the current rig. A **Restore Starter Rigs** action (rig-library menu, or the
Starters empty state) reinstalls the shipped rigs at any time.
- **Two-board starter rig** — a Garcia-style clean/effects split across two boards, switched
with the board Solo / Blend control, showing off multi-board rigs.
- **Vibe pedal** — a photocell "vibe": four staggered all-pass stages swept by one LFO, with
**Chorus** and **Vibrato** modes and Speed / Intensity controls.
- **Sustain Fuzz pedal** — a mid-scooped, high-sustain fuzz (two cascaded soft-clip stages),
distinct from the brighter single-stage Fuzz. Sustain / Tone / Scoop controls.
- **Mutant (envelope filter) controls** — a **Range** switch (Lo / Hi) that shifts the whole
sweep band, matching the original Mu-Tron III, plus **Sweep**, **Attack**, and **Release**
in the advanced pop-over. Sweep sets how far your picking drives the cutoff; Attack /
Release shape how quickly the filter follows.
### Changed
- **Switching rigs keeps your current input.** Loading a rig from the library no longer snaps
the input back to the test loop (or the input a rig was saved with) — your live guitar (or
whatever input you have selected) carries across the switch. Opening or restoring a rig
file still applies its saved input.
- **Shimmer Reverb backed off.** The regenerating loop gain is roughly `decay + shimmer`, so
the old defaults (0.8 + 0.5) self-oscillated into a screech with little or no input.
Defaults are now decay 0.5 / shimmer 0.25 / damp 0.5, and the starter rigs that use it were
re-tuned to stay well below self-oscillation.
- **Mutant sweep defaults tamed** — resting cutoff 80 → 120 Hz and sweep span 40× → 20×, so
the filter is neither muted at rest nor extreme when it opens.
- **Starter rigs refresh on update.** Shipped rigs install (and refresh to their current
form) by catalog version, so a corrected starter reaches libraries that were seeded
earlier — without touching your own rigs.
### Fixed
- **No more spurious "Save changes?" prompt when switching rigs.** The unsaved-changes check
compared live session settings (input source, engine channel counts) that legitimately
differ from a rig's saved values; it now compares rig content only.
- **Overwrite guard for starter rigs.** Saving over a loaded starter rig now asks first,
offering **Overwrite**, **Save as New Rig**, or **Cancel**, so a shipped rig isn't replaced
by accident.
- **Multi-board signal-router rigs now save and load.** Routed A/B rigs were previously lost
on save; their branch chains and blend now persist.
## [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 ## [2.1.3] — 2026-07-13
A tuner fix. Engaging the chromatic tuner could crackle or pop through the output — A tuner fix. Engaging the chromatic tuner could crackle or pop through the output —
@@ -163,7 +163,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES; COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 14; CURRENT_PROJECT_VERSION = "21``";
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf; DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_HARDENED_RUNTIME = YES; ENABLE_HARDENED_RUNTIME = YES;
@@ -175,7 +175,7 @@
"@executable_path/../Frameworks", "@executable_path/../Frameworks",
); );
MACOSX_DEPLOYMENT_TARGET = 15.0; MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 2.1.6; MARKETING_VERSION = 3.1.1;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_EMIT_LOC_STRINGS = YES;
@@ -193,7 +193,7 @@
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES; COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 14; CURRENT_PROJECT_VERSION = "21``";
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
ENABLE_HARDENED_RUNTIME = YES; ENABLE_HARDENED_RUNTIME = YES;
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist; INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
@@ -204,7 +204,7 @@
"@executable_path/../Frameworks", "@executable_path/../Frameworks",
); );
MACOSX_DEPLOYMENT_TARGET = 15.0; MACOSX_DEPLOYMENT_TARGET = 15.0;
MARKETING_VERSION = 2.1.6; MARKETING_VERSION = 3.1.1;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_EMIT_LOC_STRINGS = YES;
@@ -165,7 +165,7 @@
CODE_SIGNING_REQUIRED = NO; CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements; CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7; CURRENT_PROJECT_VERSION = 8;
DEBUG_INFORMATION_FORMAT = dwarf; DEBUG_INFORMATION_FORMAT = dwarf;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist; INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze; INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
@@ -175,7 +175,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 2.0.0; MARKETING_VERSION = 3.1.1;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos; SDKROOT = iphoneos;
@@ -194,7 +194,7 @@
CODE_SIGNING_REQUIRED = NO; CODE_SIGNING_REQUIRED = NO;
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements; CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
CODE_SIGN_STYLE = Automatic; CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 7; CURRENT_PROJECT_VERSION = 8;
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist; INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze; INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music"; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
@@ -203,7 +203,7 @@
"$(inherited)", "$(inherited)",
"@executable_path/Frameworks", "@executable_path/Frameworks",
); );
MARKETING_VERSION = 2.0.0; MARKETING_VERSION = 3.1.1;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos; SDKROOT = iphoneos;
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird", "location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : { "state" : {
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0", "revision" : "77580ee98e05cb4a94aac367097d27b91d3776c0",
"version" : "1.2.3" "version" : "1.7.2"
} }
}, },
{ {
+3 -3
View File
@@ -1,5 +1,5 @@
{ {
"originHash" : "bc2a61a4b15bd882ede79ecb295b7878eca7ce7b55f4832eaf9bd7e7f557dd4f", "originHash" : "eed06b1870eecb6b28d2417331f105ea1cc25e9d6fe588c9d2eff8ca3af096f0",
"pins" : [ "pins" : [
{ {
"identity" : "linenoise-swift", "identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird", "location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : { "state" : {
"revision" : "ea0aa84ca796d9a21667e4b5a7d76a1ac2c280b6", "revision" : "77580ee98e05cb4a94aac367097d27b91d3776c0",
"version" : "1.7.1" "version" : "1.7.2"
} }
}, },
{ {
+1 -1
View File
@@ -24,7 +24,7 @@ let package = Package(
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]), .library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
], ],
dependencies: [ dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.7.1"), .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.7.2"),
], ],
targets: [ targets: [
// The core target depends on LyrebirdUI as well as the synthesis core: // The core target depends on LyrebirdUI as well as the synthesis core:
+18 -10
View File
@@ -11,8 +11,13 @@ signal (no hardware needed) or on live guitar through an audio input.
## Features ## Features
- **36 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and - **67 modeled pedals** — effects across gain, dynamics, EQ/filter, modulation, pitch, delay,
texture — see the catalog below. reverb, and texture, plus **26 tube-amp models** with their own tone stacks and a deep
speaker-cabinet / microphone section. All original DSP built on the Lyrebird engine — no
third-party captures or IR packs. See the catalog below.
- **Starter rigs** — a library of ready-to-play rigs ships with the app, grouped by style
(Shoegaze Walls, Dreampop, Classic, Ambient, Experimental) and reachable from a **Mine /
Starters** toggle in the rig sidebar.
- **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel - **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel
style) or **Blend** any subset, each with its own level and a click-free crossfade, plus a 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. rig-wide **output volume and mute** on top.
@@ -21,8 +26,9 @@ signal (no hardware needed) or on live guitar through an audio input.
volume, with per-binding invert for crossfades. MIDI Learn, one binding per rig. 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 - **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or
stereo lanes, and merge back to mono. stereo lanes, and merge back to mono.
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across - **Rig library** — name, save, duplicate, and switch between rigs from a sidebar (your own rigs
your devices and both apps via iCloud. and the shipped starters on separate tabs); synced across your devices and both apps via iCloud.
Switching rigs keeps your current input, and saving over a starter rig asks first.
- **Sharing** — send a rig or a saved board to anyone as a `.shoegaze` file via the system share - **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. sheet (AirDrop, Mail, Messages, Files); export/import the whole library the same way.
- **Recording** — capture your output to timestamped files. - **Recording** — capture your output to timestamped files.
@@ -37,14 +43,16 @@ signal (no hardware needed) or on live guitar through an audio input.
| Category | Pedals | | Category | Pedals |
|---|---| |---|---|
| Gain | Overdrive, Distortion, Fuzz | | Gain | Overdrive, Distortion, Fuzz, Sustain Fuzz |
| Dynamics | Compressor, Sustainer, Limiter, Noise Gate | | Dynamics | Compressor, Sustainer, Limiter, Noise Gate, Volume |
| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Cabinet | | EQ & filter | Graphic EQ, Auto-Wah, Wah, Mutant |
| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Rotary, Ring Modulator | | Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator |
| Pitch | Bass Octaver, Octave Splitter, Harmonizer | | Pitch | Bass Octaver, Octave Splitter, Harmonizer |
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay | | Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay |
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb | | Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb |
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator | | Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Looper |
| Amp Model | Fullerton Reverb / Deluxe / Ivy League / Drive, California, Jazz Clean, British / Plexi / JTM / Bluesbreaker / Master / Dual, Chime / Chime Top Boost / 15 / Normal / Baby, Boutique Lead / OD, Cali Hi-Gain, Modern High-Gain, Command, Citrus, Sixties Combo, Magna Vibrato, Anaheim |
| Cabinet | Cabinet (speaker-voice + microphone modeling) |
Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format. Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format.
@@ -52,7 +60,7 @@ Every pedal exposes its parameters as knobs/switches and round-trips through the
- macOS 15+ / iPadOS 18+ (iPad, landscape) - macOS 15+ / iPadOS 18+ (iPad, landscape)
- Swift 6.0 toolchain / Xcode 16+ - Swift 6.0 toolchain / Xcode 16+
- [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.2.0+ - [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.7.0+
## Packages ## Packages
+54
View File
@@ -1,4 +1,58 @@
# Releases # Releases
## ShoeGaze 3.1.1
A small fix for the Mutant envelope filter's control panel.
### Fixed
- **Mutant switch captions no longer wrap.** Its three segmented switches (Direction / Mode /
Range) were cramped into a single-width pedal, wrapping "Down" to "Do wn". Mutant is now
double-width — like the Cabinet and amp pedals — so the captions fit.
## ShoeGaze 3.1.0
Starter rigs, two new pedals, and a deeper envelope filter — plus smoother rig switching.
### Highlights
- **Starter rigs** — a library of ready-to-play rigs ships with the app, grouped by style
(Shoegaze Walls, Dreampop, Classic, Ambient, Experimental) behind a **Mine / Starters** toggle
in the rig sidebar. Includes a two-board clean/effects split. **Restore Starter Rigs** reinstalls
them any time.
- **Vibe** — a photocell "vibe" (four staggered all-pass stages swept by one LFO) with Chorus and
Vibrato modes.
- **Sustain Fuzz** — a mid-scooped, high-sustain fuzz, distinct from the brighter single-stage Fuzz.
- **A deeper Mutant envelope filter** — a **Range** switch (Lo / Hi) that shifts the whole sweep
band like the original Mu-Tron III, plus **Sweep**, **Attack**, and **Release** in the advanced
pop-over.
- **Rig switching keeps your input** — your live guitar stays selected across a rig change instead
of snapping back to the test loop.
### Fixed
- No more spurious "Save changes?" prompt when switching between rigs.
- Shimmer Reverb no longer self-oscillates into a screech at its defaults.
- Saving over a starter rig asks first (Overwrite / Save as New Rig / Cancel).
- Multi-board signal-router rigs now save and load.
## ShoeGaze 3.0.0
The big one: ShoeGaze becomes an amp-modeling rig — a full lineup of tube-amp voices plus a deep
speaker-cabinet and microphone section, all original DSP built from the Lyrebird engine with no
third-party captures or IR packs.
### Highlights
- **26 amp-model pedals** in their own **Amp Model** palette category — Fullerton blackface combos,
California and Jazz Clean cleans, British stack / combo voices, the Chime top-boost family,
Boutique and high-gain amps, and character amps (Command, Citrus, Sixties Combo, Magna Vibrato,
Anaheim). Each has its own tone stack, a selectable speaker cabinet, and a real master volume that
drives the power-amp stage.
- **Speaker-cabinet + microphone section** on the Cabinet pedal — eight speaker voicings, mic
modeling (Dynamic / Ribbon / Condenser), placement and proximity, and a dual-mic blend.
- **Power-amp feel controls** — Sag, Bias, and Bias X in an advanced pop-over — and analog-style
soft limiting, so a driven amp compresses toward its ceiling instead of clipping harshly.
- **Gain and Drive read 1–11** with a musical taper.
### Fixed
- Noise Gate no longer pops as a note decays.
## ShoeGaze 2.1.3 ## ShoeGaze 2.1.3
A tuner fix. Engaging the chromatic tuner could crackle or pop through the output — even A tuner fix. Engaging the chromatic tuner could crackle or pop through the output — even
@@ -1,5 +1,5 @@
{ {
"originHash" : "f5174c66e77b86ada0723482273f3d43cce9269f39894b2deb371f09e04069ab", "originHash" : "9ce521e7cebf3eed8e20837aba069e3f0c5484a64130b1791e8e6fdb7874b9f0",
"pins" : [ "pins" : [
{ {
"identity" : "linenoise-swift", "identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird", "location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : { "state" : {
"revision" : "ea0aa84ca796d9a21667e4b5a7d76a1ac2c280b6", "revision" : "77580ee98e05cb4a94aac367097d27b91d3776c0",
"version" : "1.7.1" "version" : "1.7.2"
} }
}, },
{ {
@@ -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)
}
}
@@ -10,8 +10,8 @@ import Darwin
/// Fraction of the sample rate above which a filter centre frequency is clamped, so the RBJ /// 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. /// coefficients stay well-behaved below Nyquist even at low sample rates.
private let cabinetBiquadNyquistFraction: Double = 0.49 private let cabinetBiquadNyquistFraction: Double = 0.49
/// RBJ-cookbook divisor converting a peaking-filter gain in dB to its `A` amplitude term. /// RBJ-cookbook divisor converting a filter gain in dB to its `A` amplitude term (peaking + shelves).
private let cabinetPeakingGainDivisor: Double = 40.0 private let cabinetDbToAmplitudeDivisor: Double = 40.0
/// Synthesizes a short cabinet impulse response for a ``CabinetVoice`` by running a unit /// 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 /// impulse through a cascade of RBJ biquads (high-pass → two-stage low-pass → low-mid body
@@ -37,16 +37,24 @@ public enum CabinetIRFactory {
private static let breakupQ: Double = 2.0 private static let breakupQ: Double = 2.0
/// Q for the mid interference notch (narrow, so it dips without gutting the midrange). /// Q for the mid interference notch (narrow, so it dips without gutting the midrange).
private static let notchQ: Double = 2.5 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` at `sampleRate`. /// 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: /// - Parameters:
/// - voice: The cabinet voicing to synthesize. /// - 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. /// - sampleRate: Engine sample rate in Hz.
/// - frames: IR length in frames. Defaults to ``defaultFrames``. /// - frames: IR length in frames. Defaults to ``defaultFrames``.
/// - Returns: A mono `LyrebirdBuffer` holding the normalized IR, tagged with `sampleRate`. /// - Returns: A mono `LyrebirdBuffer` holding the normalized IR, tagged with `sampleRate`.
public static func makeIR( public static func makeIR(
voice: CabinetVoice, voice: CabinetVoice,
mic: MicVoice = .off,
sampleRate: Double, sampleRate: Double,
frames: Int = CabinetIRFactory.defaultFrames frames: Int = CabinetIRFactory.defaultFrames
) -> LyrebirdBuffer { ) -> LyrebirdBuffer {
@@ -60,6 +68,25 @@ public enum CabinetIRFactory {
OfflineBiquad.peaking(freq: voice.notchHz, q: notchQ, gainDb: voice.notchGainDb, 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) var ir: [Double] = [Double](repeating: 0.0, count: frames)
for n: Int in 0..<frames { for n: Int in 0..<frames {
var sample: Double = n == 0 ? 1.0 : 0.0 var sample: Double = n == 0 ? 1.0 : 0.0
@@ -149,7 +176,7 @@ private struct OfflineBiquad {
static func peaking(freq: Double, q: Double, gainDb: Double, sampleRate: Double) -> OfflineBiquad { static func peaking(freq: Double, q: Double, gainDb: Double, sampleRate: Double) -> OfflineBiquad {
let f: Double = clampedFreq(freq, sampleRate: sampleRate) let f: Double = clampedFreq(freq, sampleRate: sampleRate)
let amplitude: Double = pow(10.0, gainDb / cabinetPeakingGainDivisor) let amplitude: Double = pow(10.0, gainDb / cabinetDbToAmplitudeDivisor)
let w0: Double = 2.0 * Double.pi * f / sampleRate let w0: Double = 2.0 * Double.pi * f / sampleRate
let cosW0: Double = cos(w0) let cosW0: Double = cos(w0)
let alpha: Double = sin(w0) / (2.0 * q) let alpha: Double = sin(w0) / (2.0 * q)
@@ -161,4 +188,44 @@ private struct OfflineBiquad {
let a2: Double = 1.0 - alpha / amplitude let a2: Double = 1.0 - alpha / amplitude
return OfflineBiquad(b0: b0 / a0, b1: b1 / a0, b2: b2 / a0, a1: a1 / a0, a2: a2 / a0) 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,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),
]
}
}
}
+27 -7
View File
@@ -143,8 +143,12 @@ open class Pedal: SynthesizerBase {
open func rigWillTeardown() {} open func rigWillTeardown() {}
/// Number of standard enclosure widths this pedal's card occupies in the UI. Defaults /// Number of standard enclosure widths this pedal's card occupies in the UI. Defaults
/// to `1`. A control-dense pedal (e.g. the looper) overrides to `2` for a wider card. /// to `1`. This sets the card's **base width in knob columns**: `1` = a three-wide card, `≥ 2` =
/// The UI multiplies its base enclosure width by this factor; `1` is the normal stompbox. /// 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 } open var widthUnits: Int { 1 }
/// `true` when the board has placed this pedal in a stereo (width-2) region. /// `true` when the board has placed this pedal in a stereo (width-2) region.
@@ -237,6 +241,17 @@ 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 /// Current values of every ``effectSelectors`` and ``effectSwitches`` entry flagged
/// `rebuildsOnChange` — the controls whose choice changes the graph topology (e.g. a cabinet /// `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 /// voice or a clean/drive channel). A lightweight recall compares this before/after applying a
@@ -283,11 +298,13 @@ open class Pedal: SynthesizerBase {
} }
/// Every continuous control on this pedal that a MIDI Control Change can drive — the pedal's /// Every continuous control on this pedal that a MIDI Control Change can drive — the pedal's
/// knobs (effect knobs + Mix + Level) followed by its vertical-fader sliders. Discrete controls /// knobs (effect knobs + Mix + Level), then its vertical-fader sliders, then its advanced
/// (switches, stepped selectors) are excluded; they suit Program Change toggles, not CC sweeps. /// (pop-over) knobs. Discrete controls (switches, stepped selectors) are excluded; they suit
/// Program Change toggles, not CC sweeps.
/// ///
/// Ordering is stable — knobs first, then sliders — so a persisted CC binding addressed by index /// Ordering is stable — knobs, then sliders, then advanced knobs (appended last so existing
/// keeps resolving to the same control across launches. Used by MIDI mapping. /// index-addressed CC bindings keep resolving to the same control across launches). Used by MIDI
/// mapping.
public var ccMappableControls: [PedalControl] { public var ccMappableControls: [PedalControl] {
let knobControls: [PedalControl] = knobs.map { let knobControls: [PedalControl] = knobs.map {
PedalControl(label: $0.label, node: $0.node, range: $0.range) PedalControl(label: $0.label, node: $0.node, range: $0.range)
@@ -295,7 +312,10 @@ open class Pedal: SynthesizerBase {
let sliderControls: [PedalControl] = effectSliders.map { let sliderControls: [PedalControl] = effectSliders.map {
PedalControl(label: $0.label, node: $0.node, range: $0.range) PedalControl(label: $0.label, node: $0.node, range: $0.range)
} }
return knobControls + sliderControls let advancedControls: [PedalControl] = advancedKnobs.map {
PedalControl(label: $0.label, node: $0.node, range: $0.range)
}
return knobControls + sliderControls + advancedControls
} }
// MARK: - Tempo sync // MARK: - Tempo sync
+10 -1
View File
@@ -53,13 +53,20 @@ public extension PedalType {
static let britishDual = PedalType("British Dual") static let britishDual = PedalType("British Dual")
static let boutiqueLead = PedalType("Boutique Lead") static let boutiqueLead = PedalType("Boutique Lead")
static let boutiqueOD = PedalType("Boutique OD") 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 chime = PedalType("Chime")
static let chimeFifteen = PedalType("Chime 15") static let chimeFifteen = PedalType("Chime 15")
static let chimeNormal = PedalType("Chime Normal") static let chimeNormal = PedalType("Chime Normal")
static let chimeBaby = PedalType("Chime Baby") static let chimeBaby = PedalType("Chime Baby")
static let fullertonReverb = PedalType("Fullerton Reverb") static let fullertonReverb = PedalType("Fullerton Reverb")
static let fullertonDeluxe = PedalType("Fullerton Deluxe") static let fullertonDeluxe = PedalType("Fullerton Deluxe")
static let fullertonPrinceton = PedalType("Fullerton Princeton") static let fullertonPrinceton = PedalType("Fullerton Ivy League")
static let fullertonDrive = PedalType("Fullerton Drive") static let fullertonDrive = PedalType("Fullerton Drive")
static let jazzClean = PedalType("Jazz Clean") static let jazzClean = PedalType("Jazz Clean")
static let chimeTopBoost = PedalType("Chime Top Boost") static let chimeTopBoost = PedalType("Chime Top Boost")
@@ -67,6 +74,7 @@ public extension PedalType {
static let overdrive = PedalType("Overdrive") static let overdrive = PedalType("Overdrive")
static let distortion = PedalType("Distortion") static let distortion = PedalType("Distortion")
static let fuzz = PedalType("Fuzz") static let fuzz = PedalType("Fuzz")
static let sustainFuzz = PedalType("Sustain Fuzz")
static let compressor = PedalType("Compressor") static let compressor = PedalType("Compressor")
static let limiter = PedalType("Limiter") static let limiter = PedalType("Limiter")
static let noiseGate = PedalType("Noise Gate") static let noiseGate = PedalType("Noise Gate")
@@ -85,6 +93,7 @@ public extension PedalType {
static let chorus = PedalType("Chorus") static let chorus = PedalType("Chorus")
static let flanger = PedalType("Flanger") static let flanger = PedalType("Flanger")
static let vibrato = PedalType("Vibrato") static let vibrato = PedalType("Vibrato")
static let vibe = PedalType("Vibe")
static let rotary = PedalType("Rotary") static let rotary = PedalType("Rotary")
static let ringModulator = PedalType("Ring Modulator") static let ringModulator = PedalType("Ring Modulator")
static let diffuser = PedalType("Diffuser") static let diffuser = PedalType("Diffuser")
@@ -17,10 +17,13 @@ import LyrebirdUI
/// → TriodeStage(drive: gain) (preamp) /// → TriodeStage(drive: gain) (preamp)
/// → ToneStack(bass, mid, treble, model) (fixed per amp) /// → ToneStack(bass, mid, treble, model) (fixed per amp)
/// → onboardEffects(_:) (subclass hook — e.g. reverb + tremolo; default identity) /// → onboardEffects(_:) (subclass hook — e.g. reverb + tremolo; default identity)
/// → TriodeStage(power-amp drive) (power-amp warmth) /// → powerAmpStage(_:) (power amp — two TriodeStage halves blended by
/// Bias X; single-stage tone at biasX = 0)
/// → shapeVoice(_:) (subclass signature filter) /// → shapeVoice(_:) (subclass signature filter)
/// → ConvolutionReverb(cab IR) (speaker cabinet — voice-selectable, rebuild on change) /// → applySag(_:) (shared power-supply Sag droop; identity at sag = 0)
/// → TriodeStage(bias: 0) → Clip(±1) (output soft-limit + hard safety ceiling) /// → 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. /// Fully wet (the amp replaces the dry signal); `Level` is the master. Double-width amp-head card.
/// ///
@@ -38,8 +41,10 @@ open class AmpVoicePedal: Pedal {
// MARK: - Common parameters // MARK: - Common parameters
/// Preamp drive into the first tube stage. Range [1, 30]. /// Preamp **Gain** dial in `[1, 11]` (yes, it goes to eleven). Mapped to the tube-drive range
@UIParam public var gain: Double = 6.0 /// `[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]. /// Tone-stack bass control in [0, 1].
@UIParam public var bass: Double = 0.5 @UIParam public var bass: Double = 0.5
/// Tone-stack mid control in [0, 1]. /// Tone-stack mid control in [0, 1].
@@ -48,6 +53,20 @@ open class AmpVoicePedal: Pedal {
@UIParam public var treble: Double = 0.6 @UIParam public var treble: Double = 0.6
/// Selected cabinet voice as an index into `CabinetVoice.allCases`. /// Selected cabinet voice as an index into `CabinetVoice.allCases`.
@UIParam public var cab: Double = 0.0 @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 // MARK: - Subclass configuration
@@ -135,7 +154,19 @@ open class AmpVoicePedal: Pedal {
/// - Parameter signal: The post-`inputShaping` input signal. /// - Parameter signal: The post-`inputShaping` input signal.
/// - Returns: The preamp output fed into the tone stack. /// - Returns: The preamp output fed into the tone stack.
open func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { open func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
TriodeStage(input: signal, drive: $gain, bias: preampBias, oversample: preampOversample) 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 /// Drive into the power-amp `TriodeStage`. Defaults to the fixed power-amp drive. Two kinds of
@@ -153,6 +184,61 @@ open class AmpVoicePedal: Pedal {
/// power stage of the standard voices). /// power stage of the standard voices).
open var powerAmpOversample: Int { 2 } 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 // MARK: - Constants
private static let defaultMix: Double = 1.0 private static let defaultMix: Double = 1.0
@@ -160,9 +246,41 @@ open class AmpVoicePedal: Pedal {
private let preampBias: Double = 0.2 private let preampBias: Double = 0.2
/// Oversampling factor for the preamp stage (4× — the preamp can be driven hard by `Gain`). /// Oversampling factor for the preamp stage (4× — the preamp can be driven hard by `Gain`).
let preampOversample: Int = 4 let preampOversample: Int = 4
/// Fixed power-amp stage drive/bias (gentler than the preamp). /// 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 private let powerAmpDrive: Double = 1.5
private let powerAmpBias: Double = 0.0 /// 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 private let cabinetMix: Double = 1.0
/// Output soft-limit drive. `1.0` gives unit small-signal gain (clean playing untouched) with a /// 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 /// hard `tanh` asymptote at ±1 — models output-transformer / speaker compression and keeps the
@@ -177,23 +295,29 @@ open class AmpVoicePedal: Pedal {
/// just above ±1, guaranteeing the amp stage never emits a sample the DAC would clip. /// just above ±1, guaranteeing the amp stage never emits a sample the DAC would clip.
private let outputCeiling: Double = 1.0 private let outputCeiling: Double = 1.0
let gainRange: ClosedRange<Double> = 1.0 ... 30.0 let gainRange: ClosedRange<Double> = 1.0 ... 11.0
let toneRange: ClosedRange<Double> = 0.0 ... 1.0 let toneRange: ClosedRange<Double> = 0.0 ... 1.0
/// Range for a signature control that maps [0, 1] (Bright / Presence / Cut amount). /// Range for a signature control that maps [0, 1] (Bright / Presence / Cut amount).
let signatureRange: ClosedRange<Double> = 0.0 ... 1.0 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 private static let cabStops: [PedalSelectorKnob.Stop] = CabinetVoice.allCases
.enumerated() .enumerated()
.map { (index: Int, voice: CabinetVoice) in .map { (index: Int, voice: CabinetVoice) in
PedalSelectorKnob.Stop(title: voice.displayName, value: Double(index)) PedalSelectorKnob.Stop(title: voice.displayName, value: Double(index))
} }
+ [PedalSelectorKnob.Stop(title: "None (direct)", value: cabinetBypassValue)]
// MARK: - Chrome // MARK: - Chrome
/// The amp is fully wet (it replaces the dry signal); hide the Mix control. /// The amp is fully wet (it replaces the dry signal); hide the Mix control.
public override var showsMixControl: Bool { false } public override var showsMixControl: Bool { false }
/// Amp-head-style double-width card. /// 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 widthUnits: Int { 2 }
public override var summary: String { summaryText } public override var summary: String { summaryText }
@@ -237,23 +361,33 @@ open class AmpVoicePedal: Pedal {
] ]
} }
/// 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 // MARK: - Effect
/// Preamp → fixed tone stack → power amp → signature shaping → cabinet → output soft-limit. /// Preamp → fixed tone stack → power amp → signature shaping → cabinet (or None) → output
/// soft-limit.
/// ///
/// > Note: only the voice named by the live `cab` selector is instantiated, so exactly one /// > Note: at most one `ConvolutionReverb` runs — only the voice named by the live `cab` selector
/// > `ConvolutionReverb` runs. The `cab` selector is `rebuildsOnChange`, so switching cabs /// > is instantiated, and the "None (direct)" stop instantiates none. The `cab` selector is
/// > rebuilds the board (re-entering `effect(_:)` with the new voice) rather than running every /// > `rebuildsOnChange`, so switching cabs (or to/from None) rebuilds the board rather than
/// > voice at once. /// > running every voice at once.
/// ///
/// The closing `TriodeStage(bias: 0)` is a symmetric `tanh` output limiter: the cab convolution /// The output soft-limit (``outputLimit(_:)``) always runs, cabinet or not, so the ±1 ceiling
/// and signature shelves can push peaks past ±1, which a real analog output would soft-compress /// holds even when the cabinet is bypassed for a separate downstream cab block.
/// rather than hard-clip. Unit small-signal gain keeps clean tones intact; peaks soft-limit
/// toward ±1. The trailing `Clip(±1)` is a hard safety clamp for the sub-percent overshoot the
/// `tanh`'s DC-blocker and the halfband filters can leave — so no sample can clip the DAC.
/// ///
/// - Parameter dry: Dry mono input signal. /// - Parameter dry: Dry mono input signal.
/// - Returns: The amped, cab-convolved, soft-limited, ceiling-clamped mono output. /// - Returns: The amped, (optionally) cab-convolved, soft-limited, ceiling-clamped mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
cabinetAndLimit(preCabinetCore(dry)) cabinetAndLimit(preCabinetCore(dry))
} }
@@ -270,32 +404,69 @@ open class AmpVoicePedal: Pedal {
let toned: ToneStack = ToneStack( let toned: ToneStack = ToneStack(
input: preamp, bass: $bass, mid: $mid, treble: $treble, model: toneStackModel) input: preamp, bass: $bass, mid: $mid, treble: $treble, model: toneStackModel)
let processed: any ValidGeneratorInput = onboardEffects(toned) let processed: any ValidGeneratorInput = onboardEffects(toned)
let powerAmp: TriodeStage = TriodeStage( let powerAmp: any ValidGeneratorInput = powerAmpStage(processed)
input: processed, drive: powerAmpDriveInput, bias: powerAmpBias, oversample: powerAmpOversample) return applySag(shapeVoice(powerAmp))
return shapeVoice(powerAmp)
} }
/// The per-channel cabinet + output stage: the selected `CabinetVoice` convolver → `tanh` /// True when the `Cab` selector is on the "None (direct)" stop — the amp emits its limited
/// soft-limit → `Clip(±1)` safety clamp. Applied once in mono, or once per channel by a /// power-amp signal with **no** speaker convolution, so the player can place a separate cabinet
/// widener amp. /// 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. /// - Parameter signal: The post-core signal for one channel.
/// - Returns: The cab-convolved, soft-limited, ceiling-clamped signal. /// - Returns: The (optionally) cab-convolved, soft-limited, ceiling-clamped signal.
func cabinetAndLimit(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { 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) let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cab)
let cabinet: ConvolutionReverb.Audio = ConvolutionReverb.Audio( return ConvolutionReverb.Audio(
input: signal, input: signal,
ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sampleRate), ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sampleRate),
mix: cabinetMix 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( let softLimited: TriodeStage = TriodeStage(
input: cabinet, input: signal,
drive: outputStageDrive, drive: outputStageDrive,
bias: outputStageBias, bias: outputStageBias,
oversample: outputStageOversample oversample: outputStageOversample
) )
// Hard safety clamp: the tanh keeps the signal near ±1, but its DC-blocker and the halfband
// filters can leave a sub-percent transient overshoot — clamp it so no sample can clip the DAC.
return Clip.Audio(softLimited, lo: -outputCeiling, hi: outputCeiling) 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)
}
}
@@ -23,8 +23,8 @@ open class BoutiqueAmpPedal: AmpVoicePedal {
@UIParam public var depth: Double = 0.3 @UIParam public var depth: Double = 0.3
/// Master volume in [0, 1] → power-amp drive in [`masterMinDrive`, `masterMaxDrive`]. /// Master volume in [0, 1] → power-amp drive in [`masterMinDrive`, `masterMaxDrive`].
@UIParam public var master: Double = 0.5 @UIParam public var master: Double = 0.5
/// Lead-channel preamp gain (the cascaded stage). Range [1, 30]. /// Lead-channel preamp gain (the cascaded stage). Dial [1, 11], tapered to tube drive.
@UIParam public var drive: Double = 10.0 @UIParam public var drive: Double = 7.77
/// Channel select: `0` = Clean, `1` = Lead (the cascaded gain stage). /// Channel select: `0` = Clean, `1` = Lead (the cascaded gain stage).
@UIParam public var channel: Double = 0.0 @UIParam public var channel: Double = 0.0
@@ -36,13 +36,9 @@ open class BoutiqueAmpPedal: AmpVoicePedal {
private let depthSlope: Double = 0.7 private let depthSlope: Double = 0.7
private let masterMinDrive: Double = 0.5 private let masterMinDrive: Double = 0.5
private let masterMaxDrive: Double = 5.0 private let masterMaxDrive: Double = 5.0
/// Grid bias of the cascaded lead stage — a little asymmetry for even-harmonic grind.
private let leadBias: Double = 0.15
private let channelThreshold: Double = 0.5 private let channelThreshold: Double = 0.5
private let driveRange: ClosedRange<Double> = 1.0 ... 30.0 private let driveRange: ClosedRange<Double> = 1.0 ... 11.0
let switchOffValue: Double = 0.0
let switchOnValue: Double = 1.0
public override var toneStackModel: ToneStackModel { .marshall } public override var toneStackModel: ToneStackModel { .marshall }
public override var signatureKnobs: [PedalKnob] { public override var signatureKnobs: [PedalKnob] {
@@ -74,15 +70,12 @@ open class BoutiqueAmpPedal: AmpVoicePedal {
} }
public override var powerAmpOversample: Int { 4 } public override var powerAmpOversample: Int { 4 }
/// Wider card for the Presence/Depth/Master/Drive knobs plus the Channel switch.
public override var widthUnits: Int { 4 }
/// Clean preamp, plus a cascaded lead stage on the Lead channel. `channel` is read at /// 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. /// board-build time (the switch is `rebuildsOnChange`), so only the selected channel is built.
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let clean: any ValidGeneratorInput = super.preampStage(signal) let clean: any ValidGeneratorInput = super.preampStage(signal)
guard channel >= channelThreshold else { return clean } guard channel >= channelThreshold else { return clean }
return TriodeStage(input: clean, drive: $drive, bias: leadBias, oversample: preampOversample) 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. /// Presence (top-end high-shelf) then Depth (low-end low-shelf), post power amp.
@@ -10,10 +10,10 @@ import LyrebirdUI
/// Boutique **super-lead** — the SLO-style high-gain singing lead: aggressive cascaded overdrive on /// 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. /// the Lead channel, a Master volume, and Presence / Depth power-amp shaping.
/// ///
/// A ``BoutiqueAmpPedal`` fixed to the aggressive British tone stack, defaulting to a hot Lead drive. /// A ``BoutiqueAmpPedal`` fixed to the Soldano tone stack, defaulting to a hot Lead drive.
public final class BoutiqueLeadAmpPedal: BoutiqueAmpPedal { public final class BoutiqueLeadAmpPedal: BoutiqueAmpPedal {
// toneStackModel inherits the base's .marshall (aggressive British stack). public override var toneStackModel: ToneStackModel { .soldano }
public override var summaryText: String { public override var summaryText: String {
"Boutique super-lead — aggressive cascaded high gain with Master, Presence, and Depth." "Boutique super-lead — aggressive cascaded high gain with Master, Presence, and Depth."
} }
@@ -25,8 +25,8 @@ public final class BoutiqueLeadAmpPedal: BoutiqueAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Boutique Lead", inputBus: inputBus, outputBus: outputBus) super.init(name: "Boutique Lead", inputBus: inputBus, outputBus: outputBus)
gain = 6.0 gain = 6.27
drive = 14.0 // hot singing lead drive = 8.76 // hot singing lead
cab = 1.0 // British 4×12 cab = 1.0 // British 4×12
} }
} }
@@ -47,8 +47,8 @@ public final class BoutiqueODAmpPedal: BoutiqueAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Boutique OD", inputBus: inputBus, outputBus: outputBus) super.init(name: "Boutique OD", inputBus: inputBus, outputBus: outputBus)
gain = 5.0 gain = 5.73
drive = 10.0 drive = 7.77
cab = 0.0 // American 1×12 cab = 0.0 // American 1×12
} }
@@ -57,7 +57,7 @@ public final class BritishAmpPedal: AmpVoicePedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British", inputBus: inputBus, outputBus: outputBus) super.init(name: "British", inputBus: inputBus, outputBus: outputBus)
gain = 10.0 // crunch-leaning default gain = 7.77 // crunch-leaning default
cab = 1.0 // default to the British 4×12 cab cab = 1.0 // default to the British 4×12 cab
} }
@@ -36,9 +36,6 @@ public final class BritishBluesbreakerAmpPedal: BritishComboAmpPedal {
] ]
} }
/// Wider card for the extra tremolo knobs plus the Bright and Tremolo switches.
public override var widthUnits: Int { 3 }
/// The base Bright switch plus a Tremolo footswitch (compose `super` so Bright stays in sync). /// The base Bright switch plus a Tremolo footswitch (compose `super` so Bright stays in sync).
public override var effectSwitches: [PedalSwitch] { public override var effectSwitches: [PedalSwitch] {
super.effectSwitches + [ super.effectSwitches + [
@@ -60,7 +57,7 @@ public final class BritishBluesbreakerAmpPedal: BritishComboAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British Bluesbreaker", inputBus: inputBus, outputBus: outputBus) super.init(name: "British Bluesbreaker", inputBus: inputBus, outputBus: outputBus)
gain = 6.0 gain = 6.27
cab = 1.0 // British 4×12 voice (combo 2×12 tonally close enough among our cabs) cab = 1.0 // British 4×12 voice (combo 2×12 tonally close enough among our cabs)
} }
@@ -29,11 +29,6 @@ open class BritishComboAmpPedal: AmpVoicePedal {
private let brightFreqHz: Double = 3500.0 private let brightFreqHz: Double = 3500.0
private let brightMaxGainDb: Double = 6.0 private let brightMaxGainDb: Double = 6.0
private let brightSlope: Double = 0.7 private let brightSlope: Double = 0.7
let switchOffValue: Double = 0.0
let switchOnValue: Double = 1.0
/// Grid bias of a cascaded lead/drive `TriodeStage` — a little asymmetry for even-harmonic
/// grind. Shared by the master-volume subclasses' cascaded ``preampStage(_:)``.
let leadBias: Double = 0.15
public override var toneStackModel: ToneStackModel { .marshall } public override var toneStackModel: ToneStackModel { .marshall }
public override var signatureKnobs: [PedalKnob] { public override var signatureKnobs: [PedalKnob] {
@@ -18,8 +18,8 @@ public final class BritishDualAmpPedal: BritishComboAmpPedal {
/// Master volume in [0, 1] → power-amp drive in [`masterMinDrive`, `masterMaxDrive`]. /// Master volume in [0, 1] → power-amp drive in [`masterMinDrive`, `masterMaxDrive`].
@UIParam public var master: Double = 0.5 @UIParam public var master: Double = 0.5
/// Lead-channel preamp gain (the cascaded stage). Range [1, 30]. /// Lead-channel preamp gain (the cascaded stage). Dial [1, 11], tapered to tube drive.
@UIParam public var drive: Double = 8.0 @UIParam public var drive: Double = 7.11
/// Spring-reverb wet mix in [0, 1]. /// Spring-reverb wet mix in [0, 1].
@UIParam public var reverb: Double = 0.2 @UIParam public var reverb: Double = 0.2
/// Channel select: `0` = Clean, `1` = Lead (the cascaded gain stage). /// Channel select: `0` = Clean, `1` = Lead (the cascaded gain stage).
@@ -29,7 +29,7 @@ public final class BritishDualAmpPedal: BritishComboAmpPedal {
private let masterMaxDrive: Double = 5.0 private let masterMaxDrive: Double = 5.0
/// Channel-select threshold: `>= this` selects the Lead channel. /// Channel-select threshold: `>= this` selects the Lead channel.
private let channelThreshold: Double = 0.5 private let channelThreshold: Double = 0.5
private let driveRange: ClosedRange<Double> = 1.0 ... 30.0 private let driveRange: ClosedRange<Double> = 1.0 ... 11.0
private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0 private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0
public override var summaryText: String { public override var summaryText: String {
@@ -63,9 +63,6 @@ public final class BritishDualAmpPedal: BritishComboAmpPedal {
} }
public override var powerAmpOversample: Int { 4 } public override var powerAmpOversample: Int { 4 }
/// Wider card for the extra Master/Drive/Reverb knobs plus the Bright and Channel switches.
public override var widthUnits: Int { 4 }
/// Creates a British Dual amp. /// Creates a British Dual amp.
/// ///
/// - Parameters: /// - Parameters:
@@ -73,7 +70,7 @@ public final class BritishDualAmpPedal: BritishComboAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British Dual", inputBus: inputBus, outputBus: outputBus) super.init(name: "British Dual", inputBus: inputBus, outputBus: outputBus)
gain = 5.0 gain = 5.73
cab = 1.0 // British 4×12 cab = 1.0 // British 4×12
} }
@@ -82,7 +79,7 @@ public final class BritishDualAmpPedal: BritishComboAmpPedal {
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let clean: any ValidGeneratorInput = super.preampStage(signal) let clean: any ValidGeneratorInput = super.preampStage(signal)
guard channel >= channelThreshold else { return clean } guard channel >= channelThreshold else { return clean }
return TriodeStage(input: clean, drive: $drive, bias: leadBias, oversample: preampOversample) return TriodeStage(input: clean, drive: taperedDrive($drive), bias: leadBias, oversample: preampOversample)
} }
/// Spring reverb in the onboard-effects slot (after the tone stack). /// Spring reverb in the onboard-effects slot (after the tone stack).
@@ -24,7 +24,7 @@ public final class BritishJTMAmpPedal: BritishComboAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British JTM", inputBus: inputBus, outputBus: outputBus) super.init(name: "British JTM", inputBus: inputBus, outputBus: outputBus)
gain = 5.0 // warmer, lower-gain than the plexi gain = 5.73 // warmer, lower-gain than the plexi
treble = 0.5 // a shade rounder on top treble = 0.5 // a shade rounder on top
cab = 1.0 // British 4×12 cab = 1.0 // British 4×12
} }
@@ -34,9 +34,6 @@ public final class BritishMasterAmpPedal: BritishComboAmpPedal {
} }
public override var powerAmpOversample: Int { 4 } public override var powerAmpOversample: Int { 4 }
/// Wider card for the Presence/Master knobs plus the Bright switch.
public override var widthUnits: Int { 3 }
/// Creates a British Master amp. /// Creates a British Master amp.
/// ///
/// - Parameters: /// - Parameters:
@@ -44,13 +41,13 @@ public final class BritishMasterAmpPedal: BritishComboAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British Master", inputBus: inputBus, outputBus: outputBus) super.init(name: "British Master", inputBus: inputBus, outputBus: outputBus)
gain = 5.0 // cascaded, so already a hot lead at moderate Gain gain = 5.73 // cascaded, so already a hot lead at moderate Gain
cab = 1.0 // British 4×12 cab = 1.0 // British 4×12
} }
/// Cascaded two-stage preamp: the base stage, then a second `TriodeStage` also driven by `Gain`. /// Cascaded two-stage preamp: the base stage, then a second `TriodeStage` also driven by `Gain`.
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let stage1: any ValidGeneratorInput = super.preampStage(signal) let stage1: any ValidGeneratorInput = super.preampStage(signal)
return TriodeStage(input: stage1, drive: $gain, bias: leadBias, oversample: preampOversample) return TriodeStage(input: stage1, drive: taperedDrive($gain), bias: leadBias, oversample: preampOversample)
} }
} }
@@ -25,7 +25,7 @@ public final class BritishPlexiAmpPedal: BritishComboAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "British Plexi", inputBus: inputBus, outputBus: outputBus) super.init(name: "British Plexi", inputBus: inputBus, outputBus: outputBus)
gain = 7.0 // clean-ish until pushed gain = 6.72 // clean-ish until pushed
cab = 1.0 // British 4×12 cab = 1.0 // British 4×12
} }
} }
@@ -18,7 +18,12 @@ import LyrebirdUI
/// ///
/// Signal path (inside `effect(_:)`): /// Signal path (inside `effect(_:)`):
/// ``` /// ```
/// dry → ConvolutionReverb(ir: selectedVoice) → mono out /// 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. /// The wet/dry mix and bypass are handled by the `Pedal` base class.
@@ -32,6 +37,13 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus: /// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
/// ///
/// - `cabinet`: Selects the built-in cabinet voicing (stepped selector over ``CabinetVoice``). /// - `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 { public final class CabinetPedal: Pedal {
/// One-line description shown in the picker and info panel. /// One-line description shown in the picker and info panel.
@@ -39,12 +51,42 @@ public final class CabinetPedal: Pedal {
"Speaker-cabinet impulse-response convolution with selectable built-in voicings." "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 // MARK: - Parameters
/// Selected cabinet voicing as an index into ``CabinetVoice/allCases``. Snaps to integer /// 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 /// stops via the ``cabinet`` selector; read at board-build time by `effect(_:)`, which
/// instantiates only that voice's convolver (the selector is `rebuildsOnChange`). /// instantiates only that voice's convolver (the selector is `rebuildsOnChange`).
@UIParam public var cabinet: Double = 0.0 @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 // MARK: - Constants
@@ -54,6 +96,33 @@ public final class CabinetPedal: Pedal {
/// Convolution is taken fully wet here; the `Pedal` base class provides the user wet/dry mix. /// Convolution is taken fully wet here; the `Pedal` base class provides the user wet/dry mix.
private let convolutionMix: Double = 1.0 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). /// Selector stops, one per ``CabinetVoice`` in `allCases` order (value == index).
private static let voiceStops: [PedalSelectorKnob.Stop] = CabinetVoice.allCases private static let voiceStops: [PedalSelectorKnob.Stop] = CabinetVoice.allCases
.enumerated() .enumerated()
@@ -61,6 +130,13 @@ public final class CabinetPedal: Pedal {
PedalSelectorKnob.Stop(title: voice.displayName, value: Double(index)) 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 // MARK: - Init
/// Creates a cabinet pedal. /// Creates a cabinet pedal.
@@ -86,28 +162,119 @@ public final class CabinetPedal: Pedal {
[ [
PedalSelectorKnob( PedalSelectorKnob(
label: "Cab", node: $cabinet, stops: CabinetPedal.voiceStops, rebuildsOnChange: true), 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 // MARK: - Effect
/// Convolves the dry signal against the single selected cabinet IR. /// Convolves the dry signal against the single selected cabinet + mic IR, then soft-limits.
/// ///
/// Only the voice named by the live `cabinet` selector is instantiated, so exactly one /// Only the voice/mic named by the live selectors is baked, so exactly one partitioned-FFT
/// partitioned-FFT convolver runs. Changing the selector triggers a board rebuild (the selector /// convolver runs; the mic colour is folded into that same IR at no extra render cost. Changing
/// is `rebuildsOnChange`), which re-enters `effect(_:)` with the new voice — so switching cabs /// either selector triggers a board rebuild (both are `rebuildsOnChange`). Synthesizing the short
/// costs a brief rebuild rather than running every voice at once. Synthesizing the short IR /// IR happens off the RT thread in `build()`.
/// 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. /// - Parameter dry: Dry mono input signal.
/// - Returns: The cabinet-convolved mono output. /// - Returns: The cabinet-convolved, mic-voiced, peak-limited mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
let sr: Double = sampleRate let sr: Double = sampleRate
let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cabinet) let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cabinet)
return ConvolutionReverb.Audio( let micVoice: MicVoice = MicVoice.voice(atSelectorValue: mic)
let convolved: ConvolutionReverb.Audio = ConvolutionReverb.Audio(
input: dry, input: dry,
ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sr), ir: CabinetIRFactory.makeIR(voice: voice, mic: micVoice, sampleRate: sr),
mix: convolutionMix 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)
}
}
@@ -34,7 +34,7 @@ public final class CaliforniaAmpPedal: AmpVoicePedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "California", inputBus: inputBus, outputBus: outputBus) super.init(name: "California", inputBus: inputBus, outputBus: outputBus)
gain = 4.0 // clean-leaning default gain = 5.08 // clean-leaning default
} }
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
@@ -10,8 +10,8 @@ import LyrebirdUI
/// Chimey/jangly amp (bell-like top boost) with a **Cut** control that rolls off the high end as /// Chimey/jangly amp (bell-like top boost) with a **Cut** control that rolls off the high end as
/// it's turned up — the classic top-boost "Cut" behavior. /// it's turned up — the classic top-boost "Cut" behavior.
/// ///
/// A ``AmpVoicePedal`` fixed to the chime tone stack. The base of the Vox-voiced family — the /// A ``AmpVoicePedal`` fixed to the chime tone stack. The base of the chime-voiced family — the
/// AC-style variants (Chime 15 / Chime Normal / Chime Baby) subclass it and differ by gain, cab, /// EL84-combo variants (Chime 15 / Chime Normal / Chime Baby) subclass it and differ by gain, cab,
/// and tone defaults (and, for the smaller combos, an earlier power-amp breakup). /// and tone defaults (and, for the smaller combos, an earlier power-amp breakup).
open class ChimeAmpPedal: AmpVoicePedal { open class ChimeAmpPedal: AmpVoicePedal {
@@ -41,7 +41,7 @@ open class ChimeAmpPedal: AmpVoicePedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public convenience init(inputBus: Int = 0, outputBus: Int = 0) { public convenience init(inputBus: Int = 0, outputBus: Int = 0) {
self.init(name: "Chime", inputBus: inputBus, outputBus: outputBus) self.init(name: "Chime", inputBus: inputBus, outputBus: outputBus)
gain = 5.0 gain = 5.73
} }
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
@@ -7,7 +7,7 @@
import LyrebirdSynth import LyrebirdSynth
import LyrebirdUI import LyrebirdUI
/// Vox-voiced **practice combo** — the tiny AC4/AC10-style amp: low headroom, a small boxy /// Chime-family **practice combo** — the tiny, low-power amp: low headroom, a small boxy
/// speaker, and the earliest breakup of the chime family. /// speaker, and the earliest breakup of the chime family.
/// ///
/// A ``ChimeAmpPedal`` (Cut voice) driven hardest into the power stage, with the small lo-fi cab. /// A ``ChimeAmpPedal`` (Cut voice) driven hardest into the power stage, with the small lo-fi cab.
@@ -17,7 +17,7 @@ public final class ChimeBabyAmpPedal: ChimeAmpPedal {
private let babyPowerDrive: Double = 2.5 private let babyPowerDrive: Double = 2.5
public override var summaryText: String { public override var summaryText: String {
"Vox practice combo — tiny, boxy, earliest-breakup chime with a Cut control." "Chime-style practice combo — tiny, boxy, earliest-breakup chime with a Cut control."
} }
/// Driven hardest of the chime family, so 4× oversampling for anti-alias headroom. /// Driven hardest of the chime family, so 4× oversampling for anti-alias headroom.
@@ -31,7 +31,7 @@ public final class ChimeBabyAmpPedal: ChimeAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Chime Baby", inputBus: inputBus, outputBus: outputBus) super.init(name: "Chime Baby", inputBus: inputBus, outputBus: outputBus)
gain = 6.0 gain = 6.27
bass = 0.4 // small speaker, less low end bass = 0.4 // small speaker, less low end
cab = 7.0 // Lo-Fi 1×8 — the small, boxy voice cab = 7.0 // Lo-Fi 1×8 — the small, boxy voice
} }
@@ -7,7 +7,7 @@
import LyrebirdSynth import LyrebirdSynth
import LyrebirdUI import LyrebirdUI
/// Vox-voiced **1×12 EL84 combo** — the lower-powered, earlier-breakup sibling of the AC top-boost /// Chime-family **1×12 EL84 combo** — the lower-powered, earlier-breakup sibling of the top-boost
/// voice. Chimey but grittier: the small power section saturates sooner. /// voice. Chimey but grittier: the small power section saturates sooner.
/// ///
/// A ``ChimeAmpPedal`` (Cut voice) with a higher fixed power-amp drive and a bright cab. /// A ``ChimeAmpPedal`` (Cut voice) with a higher fixed power-amp drive and a bright cab.
@@ -17,7 +17,7 @@ public final class ChimeFifteenAmpPedal: ChimeAmpPedal {
private let fifteenPowerDrive: Double = 2.0 private let fifteenPowerDrive: Double = 2.0
public override var summaryText: String { public override var summaryText: String {
"Vox 1×12 EL84 combo — chimey but earlier-breakup, with a Cut control." "Chime-style 1×12 EL84 combo — chimey but earlier-breakup, with a Cut control."
} }
/// Driven harder than the base, so 4× oversampling for anti-alias headroom. /// Driven harder than the base, so 4× oversampling for anti-alias headroom.
@@ -31,7 +31,7 @@ public final class ChimeFifteenAmpPedal: ChimeAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Chime 15", inputBus: inputBus, outputBus: outputBus) super.init(name: "Chime 15", inputBus: inputBus, outputBus: outputBus)
gain = 6.0 // grittier starting point than the big AC voice gain = 6.27 // grittier starting point than the big AC voice
cab = 5.0 // Bright 1×12 cab = 5.0 // Bright 1×12
} }
} }
@@ -7,15 +7,15 @@
import LyrebirdSynth import LyrebirdSynth
import LyrebirdUI import LyrebirdUI
/// Vox-voiced **Normal channel** — the AC30's non-top-boost side: warmer and rounder than the /// Chime-family **Normal channel** — the big combo's non-top-boost side: warmer and rounder than
/// bright top-boost voice, with the same high clean headroom. /// the bright top-boost voice, with the same high clean headroom.
/// ///
/// A ``ChimeAmpPedal`` (Cut voice) voiced darker (lower treble default, a touch more Cut) to stand /// A ``ChimeAmpPedal`` (Cut voice) voiced darker (lower treble default, a touch more Cut) to stand
/// in for the plainer Normal-channel EQ. /// in for the plainer Normal-channel EQ.
public final class ChimeNormalAmpPedal: ChimeAmpPedal { public final class ChimeNormalAmpPedal: ChimeAmpPedal {
public override var summaryText: String { public override var summaryText: String {
"Vox Normal channel — warm, round, high-headroom chime with a Cut control." "Chime Normal channel — warm, round, high-headroom chime with a Cut control."
} }
/// Creates a Chime Normal amp. /// Creates a Chime Normal amp.
@@ -25,7 +25,7 @@ public final class ChimeNormalAmpPedal: ChimeAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Chime Normal", inputBus: inputBus, outputBus: outputBus) super.init(name: "Chime Normal", inputBus: inputBus, outputBus: outputBus)
gain = 5.0 gain = 5.73
treble = 0.5 // rounder top than the top-boost voice treble = 0.5 // rounder top than the top-boost voice
cut = 0.3 // a shade darker by default cut = 0.3 // a shade darker by default
cab = 0.0 // American 1×12 — plainer than the bright cab cab = 0.0 // American 1×12 — plainer than the bright cab
@@ -50,8 +50,6 @@ public final class ChimeTopBoostAmpPedal: AmpVoicePedal {
private let cutRange: ClosedRange<Double> = 0.0 ... 1.0 private let cutRange: ClosedRange<Double> = 0.0 ... 1.0
private let speedRange: ClosedRange<Double> = 0.5 ... 12.0 private let speedRange: ClosedRange<Double> = 0.5 ... 12.0
private let intensityRange: ClosedRange<Double> = 0.0 ... 1.0 private let intensityRange: ClosedRange<Double> = 0.0 ... 1.0
private let switchOffValue: Double = 0.0
private let switchOnValue: Double = 1.0
// MARK: - Voice configuration // MARK: - Voice configuration
@@ -67,9 +65,6 @@ public final class ChimeTopBoostAmpPedal: AmpVoicePedal {
] ]
} }
/// Wider card for the extra Cut/tremolo knobs plus the Brilliant and Tremolo switches.
public override var widthUnits: Int { 3 }
// MARK: - Init // MARK: - Init
/// Creates a Chime Top Boost amp. /// Creates a Chime Top Boost amp.
@@ -79,7 +74,7 @@ public final class ChimeTopBoostAmpPedal: AmpVoicePedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Chime Top Boost", inputBus: inputBus, outputBus: outputBus) super.init(name: "Chime Top Boost", inputBus: inputBus, outputBus: outputBus)
gain = 5.0 gain = 5.73
cab = 5.0 // Bright 1×12 — the chimey, top-end-forward cab voice cab = 5.0 // Bright 1×12 — the chimey, top-end-forward cab voice
} }
@@ -0,0 +1,55 @@
// CitrusAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// British **mid-forward crunch** — the Citrus voice: a thick, punchy midrange with a single
/// **Shape** control that tilts the top end from dark to bright.
///
/// A ``AmpVoicePedal`` on the `.marshall` stack with a fixed mid bump (the amp's signature push)
/// and a Shape high-shelf whose gain sweeps from cut to boost.
public final class CitrusAmpPedal: AmpVoicePedal {
/// Shape in [0, 1]: `0` = dark (top cut), `0.5` = flat, `1` = bright (top boost).
@UIParam public var shape: Double = 0.5
private let midFreqHz: Double = 800.0
private let midBumpDb: Double = 3.0
private let midQ: Double = 0.8
private let shapeFreqHz: Double = 2600.0
private let shapeMinDb: Double = -6.0
private let shapeMaxDb: Double = 6.0
private let shapeSlope: Double = 0.8
public override var toneStackModel: ToneStackModel { .marshall }
public override var summaryText: String {
"British mid-forward crunch with a single Shape control (dark ↔ bright top end)."
}
public override var signatureKnobs: [PedalKnob] {
[PedalKnob(label: "Shape", node: $shape, range: signatureRange)]
}
/// Creates a Citrus 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: "Citrus", inputBus: inputBus, outputBus: outputBus)
gain = 6.27
cab = 1.0 // British 4×12
}
/// A fixed midrange bump (the Citrus push), then the Shape high-shelf tilt.
public override func shapeVoice(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let midded: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
input: signal, freq: midFreqHz, gain: midBumpDb, q: midQ)
let shapeDb: LinLin.Audio = LinLin.Audio(
$shape, inLo: 0.0, inHi: 1.0, outLo: shapeMinDb, outHi: shapeMaxDb)
return RBJHighShelf.Audio(input: midded, freq: shapeFreqHz, gain: shapeDb, slope: shapeSlope)
}
}
@@ -0,0 +1,32 @@
// CommandAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// British **hi-fi clean** — the Command/DR-style workhorse: very loud, very clean, high headroom,
/// with Presence and a Bright switch. Breaks up late and stays tight.
///
/// A ``BritishComboAmpPedal`` (non-master `.marshall` + Presence + Bright) voiced for maximum
/// headroom — a low default gain so it stays clean far up the dial.
public final class CommandAmpPedal: BritishComboAmpPedal {
public override var summaryText: String {
"British hi-fi clean — loud, tight, high-headroom, with Presence and a Bright switch."
}
/// Creates a Command 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: "Command", inputBus: inputBus, outputBus: outputBus)
gain = 5.08 // headroom-rich clean
treble = 0.55 // a touch of hi-fi top
cab = 1.0 // British 4×12
}
}
@@ -33,7 +33,7 @@ public final class FullertonDeluxeAmpPedal: FullertonReverbAmpPedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Fullerton Deluxe", inputBus: inputBus, outputBus: outputBus) super.init(name: "Fullerton Deluxe", inputBus: inputBus, outputBus: outputBus)
gain = 4.5 // slightly hotter starting point than the Twin gain = 5.42 // slightly hotter starting point than the Twin
bass = 0.45 // a touch less low end than the 2×12 bass = 0.45 // a touch less low end than the 2×12
cab = 0.0 // American 1×12 cab = 0.0 // American 1×12
} }
@@ -19,8 +19,8 @@ public final class FullertonDriveAmpPedal: AmpVoicePedal {
/// Spring-reverb wet mix in [0, 1]. /// Spring-reverb wet mix in [0, 1].
@UIParam public var reverb: Double = 0.25 @UIParam public var reverb: Double = 0.25
/// Drive-channel preamp gain (the cascaded overdrive stage). Range [1, 30]. /// Drive-channel preamp gain (the cascaded overdrive stage). Dial [1, 11], tapered to tube drive.
@UIParam public var drive: Double = 8.0 @UIParam public var drive: Double = 7.11
/// Bright switch: `0` = flat, `1` = treble shelf engaged. /// Bright switch: `0` = flat, `1` = treble shelf engaged.
@UIParam public var bright: Double = 0.0 @UIParam public var bright: Double = 0.0
/// Channel select: `0` = Clean, `1` = Drive (the cascaded overdrive stage). /// Channel select: `0` = Clean, `1` = Drive (the cascaded overdrive stage).
@@ -35,9 +35,7 @@ public final class FullertonDriveAmpPedal: AmpVoicePedal {
private let channelThreshold: Double = 0.5 private let channelThreshold: Double = 0.5
private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0 private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0
private let driveRange: ClosedRange<Double> = 1.0 ... 30.0 private let driveRange: ClosedRange<Double> = 1.0 ... 11.0
private let switchOffValue: Double = 0.0
private let switchOnValue: Double = 1.0
public override var toneStackModel: ToneStackModel { .fender } public override var toneStackModel: ToneStackModel { .fender }
public override var summaryText: String { public override var summaryText: String {
@@ -50,9 +48,6 @@ public final class FullertonDriveAmpPedal: AmpVoicePedal {
] ]
} }
/// Wider card for the Reverb/Drive knobs plus the Bright and Channel switches.
public override var widthUnits: Int { 3 }
public override var effectSwitches: [PedalSwitch] { public override var effectSwitches: [PedalSwitch] {
[ [
PedalSwitch( PedalSwitch(
@@ -82,7 +77,7 @@ public final class FullertonDriveAmpPedal: AmpVoicePedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Fullerton Drive", inputBus: inputBus, outputBus: outputBus) super.init(name: "Fullerton Drive", inputBus: inputBus, outputBus: outputBus)
gain = 4.0 gain = 5.08
cab = 0.0 // American 1×12 cab = 0.0 // American 1×12
} }
@@ -99,7 +94,7 @@ public final class FullertonDriveAmpPedal: AmpVoicePedal {
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let clean: any ValidGeneratorInput = super.preampStage(signal) let clean: any ValidGeneratorInput = super.preampStage(signal)
guard channel >= channelThreshold else { return clean } guard channel >= channelThreshold else { return clean }
return TriodeStage(input: clean, drive: $drive, bias: driveBias, oversample: preampOversample) return TriodeStage(input: clean, drive: taperedDrive($drive), bias: driveBias, oversample: preampOversample)
} }
/// Spring reverb in the onboard-effects slot (after the tone stack). /// Spring reverb in the onboard-effects slot (after the tone stack).
@@ -26,14 +26,14 @@ public final class FullertonPrincetonAmpPedal: FullertonReverbAmpPedal {
public override var powerAmpOversample: Int { 4 } public override var powerAmpOversample: Int { 4 }
public override var powerAmpDriveInput: any ValidGeneratorInput { princetonPowerDrive } public override var powerAmpDriveInput: any ValidGeneratorInput { princetonPowerDrive }
/// Creates a Fullerton Princeton amp. /// Creates a Fullerton Ivy League amp.
/// ///
/// - Parameters: /// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. /// - 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`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Fullerton Princeton", inputBus: inputBus, outputBus: outputBus) super.init(name: "Fullerton Ivy League", inputBus: inputBus, outputBus: outputBus)
gain = 5.0 // hotter still — the small combo grits up soonest gain = 5.73 // hotter still — the small combo grits up soonest
bass = 0.4 // least low end of the trio bass = 0.4 // least low end of the trio
treble = 0.55 // a shade darker treble = 0.55 // a shade darker
cab = 2.0 // Vintage Dark — the small, dark 1×10 voice cab = 2.0 // Vintage Dark — the small, dark 1×10 voice
@@ -53,8 +53,6 @@ open class FullertonReverbAmpPedal: AmpVoicePedal {
private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0 private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0
private let speedRange: ClosedRange<Double> = 0.5 ... 12.0 private let speedRange: ClosedRange<Double> = 0.5 ... 12.0
private let intensityRange: ClosedRange<Double> = 0.0 ... 1.0 private let intensityRange: ClosedRange<Double> = 0.0 ... 1.0
private let switchOffValue: Double = 0.0
private let switchOnValue: Double = 1.0
// MARK: - Voice configuration // MARK: - Voice configuration
@@ -70,9 +68,6 @@ open class FullertonReverbAmpPedal: AmpVoicePedal {
] ]
} }
/// Wider card to hold the extra reverb/tremolo knobs plus the Bright switch.
public override var widthUnits: Int { 3 }
// MARK: - Init // MARK: - Init
/// Creates a Fullerton Reverb amp. /// Creates a Fullerton Reverb amp.
@@ -85,7 +80,7 @@ open class FullertonReverbAmpPedal: AmpVoicePedal {
/// inheriting the shared reverb + tremolo + bright control surface. /// inheriting the shared reverb + tremolo + bright control surface.
public convenience init(inputBus: Int = 0, outputBus: Int = 0) { public convenience init(inputBus: Int = 0, outputBus: Int = 0) {
self.init(name: "Fullerton Reverb", inputBus: inputBus, outputBus: outputBus) self.init(name: "Fullerton Reverb", inputBus: inputBus, outputBus: outputBus)
gain = 4.0 // headroom-rich clean default gain = 5.08 // headroom-rich clean default
} }
// MARK: - Switches // MARK: - Switches
@@ -38,8 +38,8 @@ public final class JazzCleanAmpPedal: AmpVoicePedal {
@UIParam public var bright: Double = 0.0 @UIParam public var bright: Double = 0.0
/// Chorus footswitch: `1` = chorus engaged (stereo), `0` = bypassed (dry, mono-equivalent). /// Chorus footswitch: `1` = chorus engaged (stereo), `0` = bypassed (dry, mono-equivalent).
@UIParam public var chorusEnabled: Double = 1.0 @UIParam public var chorusEnabled: Double = 1.0
/// Drive-channel preamp gain (the onboard distortion). Range [1, 30]. /// Drive-channel preamp gain (the onboard distortion). Dial [1, 11], tapered to tube drive.
@UIParam public var drive: Double = 8.0 @UIParam public var drive: Double = 7.11
/// Channel select: `0` = Clean, `1` = Distortion (the cascaded onboard-distortion stage). /// Channel select: `0` = Clean, `1` = Distortion (the cascaded onboard-distortion stage).
@UIParam public var channel: Double = 0.0 @UIParam public var channel: Double = 0.0
@@ -62,9 +62,7 @@ public final class JazzCleanAmpPedal: AmpVoicePedal {
private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0 private let reverbRange: ClosedRange<Double> = 0.0 ... 1.0
private let chorusRateRange: ClosedRange<Double> = 0.1 ... 5.0 private let chorusRateRange: ClosedRange<Double> = 0.1 ... 5.0
private let chorusDepthRange: ClosedRange<Double> = 0.0005 ... 0.015 private let chorusDepthRange: ClosedRange<Double> = 0.0005 ... 0.015
private let driveRange: ClosedRange<Double> = 1.0 ... 30.0 private let driveRange: ClosedRange<Double> = 1.0 ... 11.0
private let switchOffValue: Double = 0.0
private let switchOnValue: Double = 1.0
// MARK: - Voice configuration // MARK: - Voice configuration
@@ -84,9 +82,6 @@ public final class JazzCleanAmpPedal: AmpVoicePedal {
/// Stereo output — the chorus feeds two independent power-amp/cabinet channels. /// Stereo output — the chorus feeds two independent power-amp/cabinet channels.
public override var channelKind: PedalChannelKind { .widener } public override var channelKind: PedalChannelKind { .widener }
/// Wider card for the reverb/chorus knobs plus the Bright and Chorus switches.
public override var widthUnits: Int { 3 }
// MARK: - Init // MARK: - Init
/// Creates a Jazz Clean amp. /// Creates a Jazz Clean amp.
@@ -96,7 +91,7 @@ public final class JazzCleanAmpPedal: AmpVoicePedal {
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`. /// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
super.init(name: "Jazz Clean", inputBus: inputBus, outputBus: outputBus) super.init(name: "Jazz Clean", inputBus: inputBus, outputBus: outputBus)
gain = 3.0 // clean, low-gain solid-state default gain = 4.23 // clean, low-gain solid-state default
cab = 6.0 // Full-Range (FRFR) — the hi-fi, least-coloured voice cab = 6.0 // Full-Range (FRFR) — the hi-fi, least-coloured voice
} }
@@ -138,7 +133,7 @@ public final class JazzCleanAmpPedal: AmpVoicePedal {
public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func preampStage(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let clean: any ValidGeneratorInput = super.preampStage(signal) let clean: any ValidGeneratorInput = super.preampStage(signal)
guard channel >= channelThreshold else { return clean } guard channel >= channelThreshold else { return clean }
return TriodeStage(input: clean, drive: $drive, bias: driveBias, oversample: preampOversample) return TriodeStage(input: clean, drive: taperedDrive($drive), bias: driveBias, oversample: preampOversample)
} }
// MARK: - Hooks // MARK: - Hooks
@@ -0,0 +1,85 @@
// MagnaVibratoAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// American clean combo with **true pitch vibrato** — the Magnatone voice: a genuine
/// frequency-modulation warble (a swept delay line), not the amplitude-modulation "vibrato" other
/// amps label as such.
///
/// A ``AmpVoicePedal`` (`.fender`) whose onboard effect is a delay line whose read position is swept
/// by an LFO — modulating pitch. `Depth` scales the sweep, `Speed` its rate, and a Vibrato
/// footswitch bypasses it (a fixed short delay, no warble).
public final class MagnaVibratoAmpPedal: AmpVoicePedal {
/// Vibrato LFO rate in Hz. Range [0.5, 12].
@UIParam public var speed: Double = 5.0
/// Vibrato depth in [0, 1] → 0…±`maxSweepSeconds` of delay-time sweep around the base delay
/// (the LFO is bipolar, so the delay swings both above and below `baseDelaySeconds`).
@UIParam public var depth: Double = 0.3
/// Vibrato footswitch: `1` = engaged, `0` = bypassed (`Speed`/`Depth` preserved).
@UIParam public var vibratoEnabled: Double = 1.0
/// Base delay time (the centre the LFO sweeps around), in seconds.
private let baseDelaySeconds: Double = 0.005
/// Maximum ± sweep at full depth, in seconds.
private let maxSweepSeconds: Double = 0.002
/// Delay-line capacity — must exceed base + max sweep.
private let maxDelaySeconds: Double = 0.010
private let speedRange: ClosedRange<Double> = 0.5 ... 12.0
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
public override var toneStackModel: ToneStackModel { .fender }
public override var summaryText: String {
"American clean combo with true pitch vibrato (a swept delay, not tremolo)."
}
public override var signatureKnobs: [PedalKnob] {
[
PedalKnob(label: "Speed", node: $speed, range: speedRange),
PedalKnob(label: "Depth", node: $depth, range: depthRange),
]
}
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Vibrato",
node: $vibratoEnabled,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
]
}
/// Creates a Magna Vibrato 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: "Magna Vibrato", inputBus: inputBus, outputBus: outputBus)
gain = 5.08 // clean platform for the vibrato
cab = 0.0 // American 1×12
}
/// True pitch vibrato: a delay line whose delay time is swept by a sine LFO. The footswitch
/// gates the sweep to zero (a fixed base delay, no warble) while keeping Speed/Depth.
public override func onboardEffects(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let sweepSeconds: any ValidGeneratorInput = ($depth * $vibratoEnabled) * maxSweepSeconds
let delayTime: OscSin.Audio = OscSin.Audio(
freq: $speed, mul: sweepSeconds, add: baseDelaySeconds)
return DelayLine(
input: signal,
maxDelay: maxDelaySeconds,
delay: delayTime,
sampleRate: sampleRate,
interpolation: .linear
)
}
}
@@ -0,0 +1,68 @@
// ModernHighGainAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Modern **high-gain rectifier** — the saturated, scooped metal voice: a hot cascaded lead on the
/// Mesa tone stack, with a **Sag** control (power-supply droop/bloom) and a **Tight** switch that
/// firms up the low end.
///
/// A ``BoutiqueAmpPedal`` (Clean/Lead channel, Master, Presence, Depth) voiced on the `.mesa` stack.
/// **Sag** models the power supply drooping under load: an envelope follower on the power-amp signal
/// reduces gain as it gets loud, then recovers slowly — the compression/"bloom" feel of a
/// tube-rectified amp. **Tight** high-passes the input to tighten the low end for fast riffing.
public final class ModernHighGainAmpPedal: BoutiqueAmpPedal {
/// Tight switch: `0` = full low end, `1` = low-cut engaged (tight riffing).
@UIParam public var tight: Double = 0.0
/// Tight low-cut: high-pass corner is ~20 Hz (loose, no cut) or `tightFreqHz` (tight).
private let tightLooseFreqHz: Double = 20.0
/// Tight-switch-on high-pass corner in Hz.
private let tightFreqHz: Double = 120.0
/// Tight high-pass Q (Butterworth).
private let tightQ: Double = 0.707
public override var toneStackModel: ToneStackModel { .mesa }
public override var summaryText: String {
"Modern high-gain rectifier — scooped Mesa lead with Sag (power-supply bloom) and a Tight switch."
}
public override var effectSwitches: [PedalSwitch] {
super.effectSwitches + [
PedalSwitch(
label: "Tight",
node: $tight,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
]
}
/// Creates a Modern High-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: "Modern High-Gain", inputBus: inputBus, outputBus: outputBus)
gain = 6.72
drive = 9.50 // hottest lead of the lineup
cab = 1.0 // British 4×12 — tight, aggressive
sag = 0.3 // rectifier bloom on by default (shared power-amp Sag from AmpVoicePedal)
}
/// Tight switch: a pre-preamp high-pass whose corner switches between ~20 Hz (loose, negligible
/// cut) and `tightFreqHz` (tight), firming the low end — live, no rebuild.
public override func inputShaping(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
let cutoff: LinLin.Audio = LinLin.Audio(
$tight, inLo: 0.0, inHi: 1.0, outLo: tightLooseFreqHz, outHi: tightFreqHz)
return RBJHighPass.Audio(input: signal, freq: cutoff, q: tightQ)
}
}
@@ -17,6 +17,13 @@ import LyrebirdUI
/// keeps every filter state warmed so switch changes are click-free (SuperCollider /// keeps every filter state warmed so switch changes are click-free (SuperCollider
/// `Select` semantics: every input advances each block). /// `Select` semantics: every input advances each block).
/// ///
/// The cutoff sweeps exponentially from a resting frequency (`freqLo`) up to a peak
/// (`freqHi`) as the envelope opens: `cutoff = freqLo·(freqHi/freqLo)^envelope`. The
/// **Range** switch shifts that whole window low (rhythm / bass) or high (harmonics /
/// solos), matching the original pedal; the **Sweep** knob sets how far above the resting
/// frequency the envelope drives the cutoff (its "openness"), and **Attack** / **Release**
/// shape how quickly the filter follows the input dynamics.
///
/// ## Knobs /// ## Knobs
/// - `sensitivity`: Drive into the envelope follower; higher values open the filter on quieter notes. /// - `sensitivity`: Drive into the envelope follower; higher values open the filter on quieter notes.
/// - `resonance`: Filter peak emphasis at the swept cutoff. /// - `resonance`: Filter peak emphasis at the swept cutoff.
@@ -24,6 +31,12 @@ import LyrebirdUI
/// ## Switches /// ## Switches
/// - `direction` (two-state): `0` = Down (louder closes the filter), `1` = Up (louder opens it). /// - `direction` (two-state): `0` = Down (louder closes the filter), `1` = Up (louder opens it).
/// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass. /// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass.
/// - `range` (two-state): `0` = Low band (rhythm / bass), `1` = High band (harmonics / solos).
///
/// ## Advanced
/// - `sweep`: How far the envelope drives the cutoff above its resting frequency (peak = resting × sweep).
/// - `attack`: Envelope attack time in seconds — how fast the filter opens on a transient.
/// - `release`: Envelope release time in seconds — how fast it closes after a note.
public final class MutantPedal: Pedal { public final class MutantPedal: Pedal {
/// One-line description shown in the picker and info panel. /// One-line description shown in the picker and info panel.
@@ -31,10 +44,6 @@ public final class MutantPedal: Pedal {
"Envelope-following auto-wah / funk filter that opens with your picking." "Envelope-following auto-wah / funk filter that opens with your picking."
} }
/// Double-width so the two switches — Sweep (2-way) and the 3-way Mode — sit side by side
/// without cramping now that switches lay out horizontally.
public override var widthUnits: Int { 2 }
// MARK: - Parameters // MARK: - Parameters
/// Filter response selector. `0` = lowpass, `1` = bandpass, `2` = highpass. Driven by a three-state switch. /// Filter response selector. `0` = lowpass, `1` = bandpass, `2` = highpass. Driven by a three-state switch.
@@ -49,19 +58,29 @@ public final class MutantPedal: Pedal {
/// Filter resonance (Chamberlin SVF peak emphasis). Clamped to `≥ 1.0` internally. /// Filter resonance (Chamberlin SVF peak emphasis). Clamped to `≥ 1.0` internally.
@UIParam public var resonance: Double = 4.0 @UIParam public var resonance: Double = 4.0
/// Frequency-band selector. `0` = Low band, `1` = High band. Shifts the resting cutoff (and with
/// it the whole sweep window) up or down. Driven by a two-state switch.
@UIParam public var range: Double = 0.0
/// Sweep amount: the peak cutoff is `restingCutoff × sweep`, so higher values open the filter
/// further as the input drives it. Advanced knob.
@UIParam public var sweep: Double = 20.0
/// Envelope attack time in seconds — how fast the filter opens on a transient. Advanced knob.
@UIParam public var attack: Double = 0.008
/// Envelope release time in seconds — how fast the filter closes after a note. Advanced knob.
@UIParam public var release: Double = 0.14
// MARK: - Constants // MARK: - Constants
private static let defaultMix: Double = 1.0 private static let defaultMix: Double = 1.0
/// Cutoff at zero envelope, in Hz. /// Resting cutoff (in Hz) at `range == Low`.
private let freqLo: Double = 80.0 private let rangeLowBaseFreq: Double = 120.0
/// Cutoff at maximum envelope, in Hz (≈40× sweep over `freqLo`). /// Resting cutoff (in Hz) at `range == High`.
private let freqHi: Double = 3200.0 private let rangeHighBaseFreq: Double = 380.0
/// Envelope attack/release times, in seconds.
private let attackTime: Double = 0.005
private let releaseTime: Double = 0.15
/// Half-step bias added before each `Select`'s truncate-toward-zero index, turning a /// Half-step bias added before each `Select`'s truncate-toward-zero index, turning a
/// switch parameter into a round-to-nearest position selector. /// switch parameter into a round-to-nearest position selector.
@@ -73,11 +92,17 @@ public final class MutantPedal: Pedal {
private let modeHighpassValue: Double = 2.0 private let modeHighpassValue: Double = 2.0
private let directionDownValue: Double = 0.0 private let directionDownValue: Double = 0.0
private let directionUpValue: Double = 1.0 private let directionUpValue: Double = 1.0
private let rangeLowValue: Double = 0.0
private let rangeHighValue: Double = 1.0
// MARK: - Ranges // MARK: - Ranges
private let sensitivityRange: ClosedRange<Double> = 0.0 ... 4.0 private let sensitivityRange: ClosedRange<Double> = 0.0 ... 4.0
private let resonanceRange: ClosedRange<Double> = 1.0 ... 12.0 private let resonanceRange: ClosedRange<Double> = 1.0 ... 12.0
/// Sweep multiplier: peak cutoff = resting × sweep. `1` = no sweep; `50` ≈ 5.6 octaves.
private let sweepRange: ClosedRange<Double> = 1.0 ... 50.0
private let attackRange: ClosedRange<Double> = 0.001 ... 0.08
private let releaseRange: ClosedRange<Double> = 0.02 ... 0.6
// MARK: - Knobs // MARK: - Knobs
@@ -88,12 +113,20 @@ public final class MutantPedal: Pedal {
] ]
} }
public override var advancedKnobs: [PedalKnob] {
[
PedalKnob(label: "Sweep", node: $sweep, range: sweepRange),
PedalKnob(label: "Attack", node: $attack, range: attackRange),
PedalKnob(label: "Release", node: $release, range: releaseRange),
]
}
// MARK: - Switches // MARK: - Switches
public override var effectSwitches: [PedalSwitch] { public override var effectSwitches: [PedalSwitch] {
[ [
PedalSwitch( PedalSwitch(
label: "Sweep", label: "Direction",
node: $direction, node: $direction,
options: [ options: [
PedalSwitch.Option(title: "Down", value: directionDownValue), PedalSwitch.Option(title: "Down", value: directionDownValue),
@@ -109,9 +142,22 @@ public final class MutantPedal: Pedal {
PedalSwitch.Option(title: "HP", value: modeHighpassValue), PedalSwitch.Option(title: "HP", value: modeHighpassValue),
] ]
), ),
PedalSwitch(
label: "Range",
node: $range,
options: [
PedalSwitch.Option(title: "Lo", value: rangeLowValue),
PedalSwitch.Option(title: "Hi", value: rangeHighValue),
]
),
] ]
} }
/// Double-width so the three segmented switches (Direction / Mode / Range — seven segments in
/// all) have room for their captions instead of wrapping ("Do wn"), the same reason the Cabinet
/// and amp pedals are double-width.
public override var widthUnits: Int { 2 }
// MARK: - Init // MARK: - Init
public init(inputBus: Int = 0, outputBus: Int = 0) { public init(inputBus: Int = 0, outputBus: Int = 0) {
@@ -126,23 +172,29 @@ public final class MutantPedal: Pedal {
// MARK: - Effect // MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Resting cutoff shifts with the Range switch (Low band vs High band); the peak the envelope
// reaches is `restingCutoff × sweep`. Both feed all six warmed filters (fan-out).
let restingFreq: any ValidGeneratorInput =
$range * (rangeHighBaseFreq - rangeLowBaseFreq) + rangeLowBaseFreq
let peakFreq: any ValidGeneratorInput = restingFreq * $sweep
// Inner mode selectors per sweep direction. `Select` rounds the [0, 2] mode switch // Inner mode selectors per sweep direction. `Select` rounds the [0, 2] mode switch
// to the nearest position and advances all three filters each block (warmed state). // to the nearest position and advances all three filters each block (warmed state).
let modeWhich: any ValidGeneratorInput = $mode + selectRoundingBias let modeWhich: any ValidGeneratorInput = $mode + selectRoundingBias
let downModes: Select.Audio = Select.Audio( let downModes: Select.Audio = Select.Audio(
which: modeWhich, which: modeWhich,
inputs: [ inputs: [
makeFilter(dry, mode: .lowpass, direction: .down), makeFilter(dry, mode: .lowpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq),
makeFilter(dry, mode: .bandpass, direction: .down), makeFilter(dry, mode: .bandpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq),
makeFilter(dry, mode: .highpass, direction: .down), makeFilter(dry, mode: .highpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq),
] ]
) )
let upModes: Select.Audio = Select.Audio( let upModes: Select.Audio = Select.Audio(
which: modeWhich, which: modeWhich,
inputs: [ inputs: [
makeFilter(dry, mode: .lowpass, direction: .up), makeFilter(dry, mode: .lowpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq),
makeFilter(dry, mode: .bandpass, direction: .up), makeFilter(dry, mode: .bandpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq),
makeFilter(dry, mode: .highpass, direction: .up), makeFilter(dry, mode: .highpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq),
] ]
) )
@@ -157,7 +209,9 @@ public final class MutantPedal: Pedal {
private func makeFilter( private func makeFilter(
_ dry: any ValidGeneratorInput, _ dry: any ValidGeneratorInput,
mode: MuTronIIIMode, mode: MuTronIIIMode,
direction: MuTronIIISweep direction: MuTronIIISweep,
freqLo: any ValidGeneratorInput,
freqHi: any ValidGeneratorInput
) -> MuTronIII.Audio { ) -> MuTronIII.Audio {
MuTronIII.Audio( MuTronIII.Audio(
input: dry, input: dry,
@@ -167,8 +221,8 @@ public final class MutantPedal: Pedal {
peak: $resonance, peak: $resonance,
freqLo: freqLo, freqLo: freqLo,
freqHi: freqHi, freqHi: freqHi,
attackTime: attackTime, attackTime: $attack,
releaseTime: releaseTime releaseTime: $release
) )
} }
} }
@@ -14,15 +14,17 @@ import LyrebirdUI
/// dry ─┬─────────────────────────────────────────────────────────┐ /// dry ─┬─────────────────────────────────────────────────────────┐
/// └→ AmplitudeFollower → Schmidt(lo: thr, hi: thr×ratio) │ /// └→ AmplitudeFollower → Schmidt(lo: thr, hi: thr×ratio) │
/// → LinLin(0…1 → floor…1) │ /// → LinLin(0…1 → floor…1) │
/// → Lag(smooth) ───────────── × ──┴→ mono out /// → LagUpDown(fast open/slow close) × ─┴→ mono out
/// ``` /// ```
/// ///
/// An `AmplitudeFollower` tracks the dry signal level. A Schmitt trigger turns that /// An `AmplitudeFollower` tracks the dry signal level. A Schmitt trigger turns that
/// envelope into an open/closed gate with hysteresis (opens above `threshold × openRatio`, /// envelope into an open/closed gate with hysteresis (opens above `threshold × openRatio`,
/// closes below `threshold`) so the gate does not chatter around the threshold. The 0/1 /// closes below `threshold`) so the gate does not chatter around the threshold. The 0/1
/// gate is mapped to a gain in `[floor, 1]` and smoothed before multiplying the dry signal: /// gate is mapped to a gain in `[floor, 1]` and smoothed **asymmetrically** — opening fast so a
/// when the gate is closed the signal is attenuated to `floor` rather than hard-muted, so /// note's attack isn't softened, closing slowly so the gate fades shut instead of snapping (a fast
/// `floor` sets how much of the quiet signal/noise tail bleeds through. /// close popped audibly when heavy downstream gain amplified the step). When the gate is closed the
/// signal is attenuated to `floor` rather than hard-muted, so `floor` sets how much of the quiet
/// signal/noise tail bleeds through.
/// ///
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class. /// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
/// ///
@@ -35,6 +37,8 @@ import LyrebirdUI
/// the gate. Range `[0, 0.2]`. Defaults to `0.02`. /// the gate. Range `[0, 0.2]`. Defaults to `0.02`.
/// - floor: Residual gain applied while the gate is closed, in `[0, 1]`. `0` = full /// - floor: Residual gain applied while the gate is closed, in `[0, 1]`. `0` = full
/// mute, `1` = no gating. Range `[0, 1]`. Defaults to `0.0`. /// mute, `1` = no gating. Range `[0, 1]`. Defaults to `0.0`.
/// - attack: Gate open time in seconds (advanced pop-over). Range `[0.001, 0.05]`. Defaults to `0.005`.
/// - release: Gate close time in seconds (advanced pop-over). Range `[0.01, 0.5]`. Defaults to `0.08`.
public final class NoiseGatePedal: Pedal { public final class NoiseGatePedal: Pedal {
/// One-line description shown in the picker and info panel. /// One-line description shown in the picker and info panel.
@@ -50,6 +54,15 @@ public final class NoiseGatePedal: Pedal {
/// Residual gain while closed, [0, 1]. Range [0, 1]. /// Residual gain while closed, [0, 1]. Range [0, 1].
@UIParam public var floor: Double = 0.0 @UIParam public var floor: Double = 0.0
/// Gate **Attack** (open time) in seconds — how fast the gate opens on a note. Short keeps
/// transients crisp. Range `[0.001, 0.05]`. Surfaced in the advanced pop-over.
@UIParam public var attack: Double = 0.005
/// Gate **Release** (close time) in seconds — how gradually the gate fades shut as a note decays
/// through the threshold. Short = a tight, fast gate; long = a gentle swell-down (and it rides
/// out chatter at the threshold). Range `[0.01, 0.5]`. Surfaced in the advanced pop-over.
@UIParam public var release: Double = 0.08
// MARK: - Constants // MARK: - Constants
/// Default wet/dry blend — fully wet; the gate sits in-line. /// Default wet/dry blend — fully wet; the gate sits in-line.
@@ -65,8 +78,11 @@ public final class NoiseGatePedal: Pedal {
/// below `threshold`, giving hysteresis that prevents chatter near the threshold. /// below `threshold`, giving hysteresis that prevents chatter near the threshold.
private let openRatio: Double = 2.0 private let openRatio: Double = 2.0
/// Gain-smoothing lag time, in seconds — removes the click of an instantaneous 0↔1 gate. // Gate-gain smoothing is **asymmetric** (``attack`` open / ``release`` close) so the gate opens
private let gainSmoothTime: Double = 0.01 // promptly (a new note's attack isn't softened) but closes gently. A fast symmetric close
// snapped the gain from unity to `floor` in ~10 ms, which — with heavy downstream gain
// (fuzz/boost) amplifying the step — read as an audible "pop" as a sustained note decayed
// through the threshold. A slower `release` fades the gate shut instead and rides out chatter.
/// Gate signal bounds for the `LinLin` floor map. /// Gate signal bounds for the `LinLin` floor map.
private let gateLo: Double = 0.0 private let gateLo: Double = 0.0
@@ -83,6 +99,12 @@ public final class NoiseGatePedal: Pedal {
/// Floor knob range (residual gain). /// Floor knob range (residual gain).
private let floorRange: ClosedRange<Double> = 0.0 ... 1.0 private let floorRange: ClosedRange<Double> = 0.0 ... 1.0
/// Attack (open-time) knob range, seconds.
private let attackRange: ClosedRange<Double> = 0.001 ... 0.05
/// Release (close-time) knob range, seconds.
private let releaseRange: ClosedRange<Double> = 0.01 ... 0.5
public override var effectKnobs: [PedalKnob] { public override var effectKnobs: [PedalKnob] {
[ [
PedalKnob(label: "Threshold", node: $threshold, range: thresholdRange), PedalKnob(label: "Threshold", node: $threshold, range: thresholdRange),
@@ -90,6 +112,16 @@ public final class NoiseGatePedal: Pedal {
] ]
} }
/// Timing controls, tucked behind the pedal card's advanced pop-over: **Attack** (open time) and
/// **Release** (close time). Live nodes, append-only in `advancedValues` — a gate saved before
/// these existed loads with them at their defaults, no migration.
public override var advancedKnobs: [PedalKnob] {
[
PedalKnob(label: "Attack", node: $attack, range: attackRange),
PedalKnob(label: "Release", node: $release, range: releaseRange),
]
}
// MARK: - Init // MARK: - Init
/// Creates a noise-gate pedal. /// Creates a noise-gate pedal.
@@ -141,10 +173,12 @@ public final class NoiseGatePedal: Pedal {
outHi: openGain outHi: openGain
) )
// Smooth the gain to remove the click of an instantaneous gate transition. // Smooth the gain asymmetrically: open fast (prompt on a note), close slowly (gentle fade,
let smoothed: Lag.Audio = Lag.Audio( // no pop, and it rides out chatter as the envelope hovers at the threshold).
let smoothed: LagUpDown.Audio = LagUpDown.Audio(
input: gain, input: gain,
time: gainSmoothTime lagUp: $attack,
lagDown: $release
) )
return dry * smoothed return dry * smoothed
@@ -31,13 +31,16 @@ public final class ShimmerReverbPedal: Pedal {
@UIParam public var size: Double = 0.06 @UIParam public var size: Double = 0.06
/// Tail length (feedback). Range [0, 0.92]. /// Tail length (feedback). Range [0, 0.92].
@UIParam public var decay: Double = 0.8 ///
/// The regenerating loop gain is roughly `decay + shimmer`; keep their sum well under `1` to avoid
/// self-oscillation (a sustaining screech with little or no input). Defaults sum to `0.75`.
@UIParam public var decay: Double = 0.5
/// Octave-up regeneration amount. Range [0, 0.85]. /// Octave-up regeneration amount. Range [0, 0.85]. See ``decay`` on keeping `decay + shimmer < 1`.
@UIParam public var shimmer: Double = 0.5 @UIParam public var shimmer: Double = 0.25
/// High-frequency damping. Range [0, 1]. /// High-frequency damping. Range [0, 1].
@UIParam public var damp: Double = 0.4 @UIParam public var damp: Double = 0.5
// MARK: - Constants // MARK: - Constants
@@ -0,0 +1,72 @@
// SixtiesComboAmpPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// American **'60s grit combo** — the small Supro/Silvertone-style amp: low headroom, gritty early
/// breakup, and an onboard **tremolo**.
///
/// A ``AmpVoicePedal`` (`.fender`) driven hard into the power stage for early breakup, with a
/// tremolo (Speed / Intensity + footswitch) in the onboard-effects slot.
public final class SixtiesComboAmpPedal: AmpVoicePedal {
/// Tremolo LFO rate in Hz. Range [0.5, 12].
@UIParam public var speed: Double = 5.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
/// Power-amp drive — well above the default fixed value so the small combo grits up early.
private let grittyPowerDrive: Double = 2.4
private let speedRange: ClosedRange<Double> = 0.5 ... 12.0
private let intensityRange: ClosedRange<Double> = 0.0 ... 1.0
public override var toneStackModel: ToneStackModel { .fender }
public override var summaryText: String {
"American '60s grit combo — early-breakup with onboard tremolo."
}
public override var signatureKnobs: [PedalKnob] {
[
PedalKnob(label: "Speed", node: $speed, range: speedRange),
PedalKnob(label: "Intensity", node: $intensity, range: intensityRange),
]
}
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Tremolo",
node: $tremoloEnabled,
options: [
PedalSwitch.Option(title: "Off", value: switchOffValue),
PedalSwitch.Option(title: "On", value: switchOnValue),
]
),
]
}
/// Driven hard into the power stage, so 4× oversampling for anti-alias headroom.
public override var powerAmpOversample: Int { 4 }
public override var powerAmpDriveInput: any ValidGeneratorInput { grittyPowerDrive }
/// Creates a Sixties Combo 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: "Sixties Combo", inputBus: inputBus, outputBus: outputBus)
gain = 6.72 // gritty starting point
cab = 2.0 // Vintage Dark — small, dark
}
/// Onboard tremolo (gated by the Tremolo footswitch), inserted after the tone stack.
public override func onboardEffects(_ signal: any ValidGeneratorInput) -> any ValidGeneratorInput {
tremolo(signal, speed: $speed, depth: $intensity, enabled: $tremoloEnabled)
}
}
@@ -0,0 +1,150 @@
// SustainFuzzPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Sustaining, mid-scooped fuzz: two cascaded soft-clipping stages into a scoop-and-tone filter.
///
/// Signal chain (inside `effect(_:)`):
/// ```
/// dry → Saturator(soft, sustain) → Saturator(soft, sustain) → RBJPeakingEQ(−scoop @ 750 Hz) → RBJLowPass(tone) → out
/// ```
///
/// This is the "wall of sustain" fuzz voice — distinct from the single-stage ``FuzzPedal``. Two
/// cascaded *soft*-clipping stages compress and stack harmonics for long, smooth, violin-like
/// sustain rather than the aggressive bite of a single hard `tanh` stage. A fixed mid **scoop**
/// (a bell cut around 750 Hz) hollows the midrange — the defining character of this fuzz family —
/// and the **tone** low-pass sets how dark or bright the top end sits.
///
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class; base `mix` is fully
/// wet so the fuzz replaces the dry signal.
///
/// ## Parameters
///
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - sustain: Drive into both soft-clip stages. Higher = more sustain and compression.
/// Range `[1, 30]`. Defaults to `6.0`.
/// - tone: Low-pass tone cutoff in Hz. Range `[800, 6000]`. Defaults to `2500.0`.
/// - scoop: Midrange cut depth in dB at 750 Hz (applied as a cut). Range `[0, 18]`. Defaults to `8.0`.
public final class SustainFuzzPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Sustaining, mid-scooped fuzz for smooth, violin-like leads and thick walls of sound."
}
// MARK: - Parameters
/// Drive into both cascaded soft-clip stages. Range [1, 30]; higher = more sustain.
@UIParam public var sustain: Double = 6.0
/// Tone low-pass cutoff in Hz. Range [800, 6000].
@UIParam public var tone: Double = 2500.0
/// Midrange cut depth in dB at 750 Hz. Range [0, 18].
@UIParam public var scoop: Double = 8.0
// MARK: - Constants
/// Default wet/dry blend — fully wet so the fuzz completely replaces the dry signal.
private static let defaultMix: Double = 1.0
/// Oversampling factor for the soft-clip stages — 2× keeps generated harmonics from folding back.
private let oversampleFactor: Int = 2
/// Centre frequency of the midrange scoop in Hz.
private let scoopFreq: Double = 750.0
/// Q of the midrange scoop bell. Moderately wide for a broad, hollow midrange.
private let scoopQ: Double = 0.9
/// Q of the tone low-pass. Butterworth (no resonant peak).
private let toneQ: Double = 0.707
/// Output trim after two soft-clip stages (each ≈ ±1) plus the mid cut, to sit at a sane level.
private let outputTrim: Double = 0.6
// MARK: - UI knobs
/// Sustain knob range (drive into the soft-clip stages).
private let sustainRange: ClosedRange<Double> = 1.0 ... 30.0
/// Tone knob range in Hz (low-pass cutoff).
private let toneRange: ClosedRange<Double> = 800.0 ... 6000.0
/// Scoop knob range in dB (midrange cut depth).
private let scoopRange: ClosedRange<Double> = 0.0 ... 18.0
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Sustain", node: $sustain, range: sustainRange),
PedalKnob(label: "Tone", node: $tone, range: toneRange),
PedalKnob(label: "Scoop", node: $scoop, range: scoopRange),
]
}
// MARK: - Init
/// Creates a sustain-fuzz 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: "Sustain Fuzz",
inputBus: inputBus,
outputBus: outputBus,
initialMix: SustainFuzzPedal.defaultMix
)
}
// MARK: - Effect
/// Cascades two soft-clip stages, scoops the mids, then rolls off the top with the tone control.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: Sustained, mid-scooped, tone-shaped mono output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// Two cascaded soft-clip stages. `softClipNormalized` keeps the level bounded as sustain
// rises, so stacking two stages compresses and sustains rather than runs away.
let stage1: OversampledSaturator = OversampledSaturator(
dry,
drive: $sustain,
curve: .softClipNormalized,
oversample: oversampleFactor
)
let stage2: OversampledSaturator = OversampledSaturator(
stage1,
drive: $sustain,
curve: .softClipNormalized,
oversample: oversampleFactor
)
// Fixed midrange scoop (cut) — the hollow midrange that defines this fuzz family.
let scoopCutDB: any ValidGeneratorInput = 0.0 - $scoop
let scooped: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
input: stage2,
freq: scoopFreq,
gain: scoopCutDB,
q: scoopQ
)
// Tone low-pass rolls off the top end.
let toned: RBJLowPass.Audio = RBJLowPass.Audio(
input: scooped,
freq: $tone,
q: toneQ
)
return toned * outputTrim
}
}
@@ -0,0 +1,154 @@
// VibePedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// Photocell "vibe" pedal: four staggered all-pass stages swept by one shared LFO.
///
/// Signal chain (inside `effect(_:)`):
/// ```
/// dry → RBJAllPass(freq₀(t)) → RBJAllPass(freq₁(t)) → RBJAllPass(freq₂(t)) → RBJAllPass(freq₃(t)) → wet
/// out = wet·wetAmount + dry·dryAmount (mode: chorus blends dry+wet, vibrato is wet only)
/// ```
///
/// Unlike a phaser (evenly-spaced stages producing symmetric notches), the vibe cascades all-pass
/// stages at **staggered** centre frequencies, so the phase relationships between stages produce the
/// characteristic uneven, vocal throb. A single low-frequency sine modulates every stage's centre
/// frequency together; the `intensity` knob scales the sweep depth and the `speed` knob sets the LFO
/// rate. In *chorus* mode the swept signal is blended 50/50 with the dry signal (comb-filter throb);
/// in *vibrato* mode only the swept (phase-modulated) signal passes, for a pitch-vibrato-like warble.
///
/// The bypass switching is handled by the `Pedal` base class. The base `mix` is fixed fully wet — the
/// chorus/vibrato dry blend is handled internally so the two modes behave correctly.
///
/// ## Parameters
///
/// Inherits `bypass` and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - speed: LFO sweep rate in Hz. Range `[0.1, 12.0]`. Defaults to `3.0`.
/// - intensity: Sweep depth as a fraction of each stage's centre frequency. Range `[0, 0.7]`.
/// Defaults to `0.5`.
/// - mode: `0` = chorus (dry + swept), `1` = vibrato (swept only). Defaults to chorus.
public final class VibePedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Throbbing photocell vibe — swirling chorus and warbling pitch-vibrato motion."
}
// MARK: - Parameters
/// LFO sweep rate in Hz. Range [0.1, 12.0].
@UIParam public var speed: Double = 3.0
/// Sweep depth as a fraction of each stage's centre frequency. Range [0, 0.7].
@UIParam public var intensity: Double = 0.5
/// Mode select: `0` = chorus (dry + swept), `1` = vibrato (swept only).
@UIParam public var mode: Double = 0.0
// MARK: - Constants
/// Default wet/dry blend — fully wet; the chorus/vibrato dry mix is handled inside `effect`.
private static let defaultMix: Double = 1.0
/// Q for each all-pass stage. Gentle phase transition for a smooth, vocal vibe (not sharp notches).
private let vibeQ: Double = 0.6
/// Staggered all-pass stage centre frequencies in Hz. Unequal spacing is what distinguishes the
/// vibe's uneven throb from an evenly-spaced phaser.
private let stageCenterFreqs: [Double] = [300.0, 620.0, 1300.0, 2200.0]
/// `mode` value selecting chorus (dry + swept).
private let modeChorusValue: Double = 0.0
/// `mode` value selecting vibrato (swept only).
private let modeVibratoValue: Double = 1.0
/// Wet gain at chorus mode (`mode == 0`); the swept signal sits 50/50 with dry.
private let chorusWetGain: Double = 0.5
// MARK: - UI knobs
/// Speed knob range in Hz (LFO sweep rate).
private let speedRange: ClosedRange<Double> = 0.1 ... 12.0
/// Intensity knob range (sweep depth fraction). Capped below `1.0` so a stage's swept frequency
/// never collapses toward `0 Hz` at the bottom of the sweep.
private let intensityRange: ClosedRange<Double> = 0.0 ... 0.7
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "speed", label: "Speed", node: $speed, kind: .rate, range: speedRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Speed", node: $speed, range: speedRange),
PedalKnob(label: "Intensity", node: $intensity, range: intensityRange),
]
}
public override var effectSwitches: [PedalSwitch] {
[
PedalSwitch(
label: "Mode",
node: $mode,
options: [
PedalSwitch.Option(title: "Chorus", value: modeChorusValue),
PedalSwitch.Option(title: "Vibrato", value: modeVibratoValue),
]
),
]
}
// MARK: - Init
/// Creates a vibe 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: "Vibe",
inputBus: inputBus,
outputBus: outputBus,
initialMix: VibePedal.defaultMix
)
}
// MARK: - Effect
/// Cascades four staggered all-pass stages swept by a shared sine LFO, then blends per mode.
///
/// - Parameter dry: Dry mono input signal.
/// - Returns: Wet mono vibe output.
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// One shared low-frequency sine drives every stage: ±1 scaled by intensity gives the sweep.
let lfo: any ValidGeneratorInput = OscSin.Audio(freq: $speed)
let sweep: any ValidGeneratorInput = lfo * $intensity // ±intensity
// Cascade the stages. Each stage's centre frequency is centre·(1 + sweep) = centre + centre·sweep.
var signal: any ValidGeneratorInput = dry
for center: Double in stageCenterFreqs {
let stageFreq: any ValidGeneratorInput = sweep * center + center
signal = RBJAllPass.Audio(input: signal, freq: stageFreq, q: vibeQ)
}
let wet: any ValidGeneratorInput = signal
// Blend by mode. Chorus (mode 0): 0.5·dry + 0.5·wet. Vibrato (mode 1): wet only.
let wetAmount: any ValidGeneratorInput = $mode * chorusWetGain + chorusWetGain // 0.5 → 1.0
let dryAmount: any ValidGeneratorInput = (modeVibratoValue - $mode) * chorusWetGain // 0.5 → 0.0
return wet * wetAmount + dry * dryAmount
}
}
@@ -0,0 +1,63 @@
// ChainRouterState.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Serialisable snapshot of one ``ChainRouter`` — its two linear board chains and its blend state.
///
/// A router splits one input to two independent boards and blends their outputs. Its branches are
/// built linearly (via ``ChainRouter/addToA(_:)`` / ``ChainRouter/addToB(_:)``), so each is captured
/// as a flat list of ``PedalState``. The splitter's two branch-enable levels capture the A / B / both
/// selection (and any continuous blend between them); the merger's two levels capture the output mix.
///
/// Persisted as part of ``ShoeGazeState/routers`` so a routed multi-board rig survives save / load.
///
/// > Note: The router's output-stage master gain (`masterGainNode`) is intentionally not captured,
/// > matching the existing behaviour for a plain board's `masterGainNode` in `BoardState` — output
/// > level is treated as a live mix control, not part of the saved rig.
public struct ChainRouterState: Codable, Equatable {
/// Pedals on board A (the first branch), in chain order.
public let boardA: [PedalState]
/// Pedals on board B (the second branch), in chain order.
public let boardB: [PedalState]
/// Splitter branch-A enable level in `[0, 1]`. `1` = A audible, `0` = A muted.
public let branchA: Double
/// Splitter branch-B enable level in `[0, 1]`. `1` = B audible, `0` = B muted.
public let branchB: Double
/// Merger board-A output level in `[0, 1]`.
public let mergerLevelA: Double
/// Merger board-B output level in `[0, 1]`.
public let mergerLevelB: Double
/// Creates a router snapshot.
///
/// - Parameters:
/// - boardA: Board A's pedals in chain order.
/// - boardB: Board B's pedals in chain order.
/// - branchA: Splitter branch-A enable level `[0, 1]`.
/// - branchB: Splitter branch-B enable level `[0, 1]`.
/// - mergerLevelA: Merger board-A output level `[0, 1]`.
/// - mergerLevelB: Merger board-B output level `[0, 1]`.
public init(
boardA: [PedalState],
boardB: [PedalState],
branchA: Double,
branchB: Double,
mergerLevelA: Double,
mergerLevelB: Double
) {
self.boardA = boardA
self.boardB = boardB
self.branchA = branchA
self.branchB = branchB
self.mergerLevelA = mergerLevelA
self.mergerLevelB = mergerLevelB
}
}
@@ -0,0 +1,125 @@
// FactoryRig.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A single built-in starter rig: a named, described pedal chain shipped with the app and seeded
/// into a fresh rig library on first launch.
///
/// A `FactoryRig` is a *builder*, not a stored snapshot. Its ``build`` closure constructs the chain
/// against a live ``ShoeGaze`` session using the concrete pedal editing API, so the recipe is
/// type-checked against the real pedal parameters at compile time — a renamed pedal control breaks
/// the build (a compile error) rather than silently corrupting a hand-written JSON preset. The
/// builder is run once at seed time (see ``FactoryRigLibrary/makeEntries(makeSession:)``), captured
/// to a ``RigEntry`` via ``ShoeGaze/captureEntry(name:id:)``, and thereafter behaves exactly like a
/// user-saved rig.
///
/// The rig names and blurbs are deliberately descriptive of the *sound*, not any trademarked pedal,
/// amplifier, or artist; a blurb may nod at the era or style a tone evokes, but a factory rig is
/// never presented as a named product or a specific performer's endorsed setup.
public struct FactoryRig: Identifiable, Sendable {
/// Stable identifier for this rig.
///
/// Fixed per rig (a literal, not freshly generated) so re-seeding an already-populated library
/// overwrites the same entry in place rather than creating a duplicate — `RigLibraryStore.save`
/// keys on the entry `id`.
public let id: UUID
/// Human-readable rig name shown in the picker and used as the saved ``RigEntry`` name.
public let name: String
/// One- or two-sentence, user-facing description of the sound and how to play it. Shown as the
/// picker subtitle / info blurb. Descriptive of the tone only — never a trademarked product or
/// an artist endorsement.
public let blurb: String
/// Sonic family this rig belongs to, for grouping in a picker. Presentational only.
public let category: FactoryRigCategory
/// How this rig builds its graph at seed time.
public let build: FactoryRigBuild
/// Creates a single-board factory rig.
///
/// The `build` closure receives a fresh, empty ``PedalBoard`` (already returned by
/// `session.addBoard()`) and appends pedals to it. Do **not** call `finalizeBoard` /
/// `captureEntry` here — the seeding driver owns that lifecycle.
///
/// - Parameters:
/// - id: Stable identifier (a fixed literal per rig — see ``id``).
/// - name: Rig name (picker title + saved entry name).
/// - blurb: User-facing description of the sound.
/// - category: Sonic family for picker grouping.
/// - build: Chain-building closure run against a fresh, empty board at seed time.
public init(
id: UUID,
name: String,
blurb: String,
category: FactoryRigCategory,
build: @escaping @MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void
) {
self.id = id
self.name = name
self.blurb = blurb
self.category = category
self.build = .singleBoard(build)
}
/// Creates a session-scoped factory rig that builds its own boards and/or routers.
///
/// Use this for rigs the single-board form can't express — e.g. a two-board signal split via
/// ``ShoeGaze/makeChainRouter()``. The `sessionBuild` closure gets the whole session and owns the
/// full lifecycle for what it creates: it must call `addBoard`/`finalizeBoard` (for plain boards)
/// and/or `makeChainRouter`/`addToA`/`addToB`/`finalize` (for routers) itself. Do **not** call
/// `captureEntry` here — the seeding driver owns that.
///
/// - Parameters:
/// - id: Stable identifier (a fixed literal per rig — see ``id``).
/// - name: Rig name (picker title + saved entry name).
/// - blurb: User-facing description of the sound.
/// - category: Sonic family for picker grouping.
/// - sessionBuild: Graph-building closure run against the session at seed time.
public init(
id: UUID,
name: String,
blurb: String,
category: FactoryRigCategory,
sessionBuild: @escaping @MainActor (_ session: ShoeGaze) throws -> Void
) {
self.id = id
self.name = name
self.blurb = blurb
self.category = category
self.build = .session(sessionBuild)
}
/// Creates a factory rig from a pre-captured ``ShoeGazeState``.
///
/// The rig's content is the supplied state verbatim — used for a complex, hand-authored rig
/// captured from the app. Seeding builds the entry directly from `state` (no live session).
///
/// - Parameters:
/// - id: Stable identifier (a fixed literal per rig — see ``id``).
/// - name: Rig name (picker title + saved entry name).
/// - blurb: User-facing description of the sound.
/// - category: Sonic family for picker grouping.
/// - state: The captured rig content to ship.
@MainActor
public init(
id: UUID,
name: String,
blurb: String,
category: FactoryRigCategory,
state: ShoeGazeState
) {
self.id = id
self.name = name
self.blurb = blurb
self.category = category
self.build = .state({ state })
}
}
@@ -0,0 +1,24 @@
// FactoryRigBuild.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// How a ``FactoryRig`` builds its graph at seed time.
public enum FactoryRigBuild: Sendable {
/// Appends pedals to a single pre-made, empty board; the seeding driver calls `addBoard` before
/// and `finalizeBoard` after.
case singleBoard(@MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void)
/// Builds the whole graph against the session (boards and/or routers), owning its own
/// `addBoard`/`finalizeBoard` and `makeChainRouter`/`finalize` lifecycle.
case session(@MainActor (_ session: ShoeGaze) throws -> Void)
/// Ships a pre-captured ``ShoeGazeState`` directly — the entry is built from it with no live
/// session. Use for a complex, hand-authored rig captured from the app, where transcribing the
/// exact `PedalState` arrays (mix, sliders, selectors, advanced values) is more faithful than
/// re-deriving them through typed setters. The closure returns the state so the case stays
/// `Sendable` without requiring `ShoeGazeState` itself to be `Sendable`.
case state(@MainActor () -> ShoeGazeState)
}
@@ -0,0 +1,33 @@
// FactoryRigCategory.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Broad sonic grouping for a built-in ``FactoryRig``.
///
/// Purely presentational: the category lets a rig picker cluster the shipped starter rigs into
/// recognisable families ("Shoegaze Walls", "Dreampop", …). It is **not** persisted in the saved
/// ``RigEntry`` — a recalled rig is just a board, indistinguishable from a user rig once loaded.
public enum FactoryRigCategory: String, CaseIterable, Sendable {
/// Dense fuzz-and-reverb "wall of sound" textures.
case shoegazeWalls = "Shoegaze Walls"
/// Lush, clean, chorused and delayed dream-pop voices.
case dreamPop = "Dreampop"
/// Classic overdrive / fuzz / wah lead and rhythm tones.
case classic = "Classic"
/// Slow, evolving, reverb-heavy ambient beds.
case ambient = "Ambient"
/// Lo-fi, bit-crushed, and otherwise experimental noise textures.
case experimental = "Experimental"
/// Human-readable name shown as a section header in a rig picker.
public var displayName: String { rawValue }
}
@@ -0,0 +1,842 @@
// FactoryRigLibrary.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
// MARK: - Typed board-building helper
extension PedalBoard {
/// Constructs a concrete pedal, applies `configure` to its typed parameters, and appends it to
/// the end of the chain.
///
/// This is the building block for ``FactoryRig`` recipes: because `configure` receives the
/// concrete pedal type, every parameter it touches (`$0.fuzz`, `$0.time`, …) is checked by the
/// compiler against the real pedal API — a renamed control is a build error, not a silently
/// broken preset. Bus wiring is handled by ``add(_:after:)``.
///
/// - Parameters:
/// - pedal: A freshly-constructed pedal (its default buses are overwritten by the board).
/// - configure: Sets the pedal's parameters before it is inserted.
/// - Returns: The same pedal, now wired into the chain.
/// - Throws: `BusAllocatorError.noFreeBus`, `EngineAddError`, or `ShoeGazeError.stereoWidthExceeded`.
@discardableResult
func append<P: Pedal>(
_ pedal: P,
configure: (P) -> Void
) throws -> P {
configure(pedal)
try add(pedal)
return pedal
}
}
extension ChainRouter {
/// Constructs a concrete pedal, applies `configure`, and appends it to board A of the router.
///
/// The concrete-type `configure` closure keeps every parameter compile-checked, exactly like
/// ``PedalBoard/append(_:configure:)``. Uses ``addToA(_:)`` so ``finalize()`` ordering stays correct.
@discardableResult
func appendToA<P: Pedal>(_ pedal: P, configure: (P) -> Void) throws -> P {
configure(pedal)
try addToA(pedal)
return pedal
}
/// Constructs a concrete pedal, applies `configure`, and appends it to board B of the router.
@discardableResult
func appendToB<P: Pedal>(_ pedal: P, configure: (P) -> Void) throws -> P {
configure(pedal)
try addToB(pedal)
return pedal
}
}
// MARK: - Factory rig catalog
/// The built-in starter rigs shipped with the app and seeded into an empty rig library on first
/// launch.
///
/// Each entry is a ``FactoryRig`` — a compile-checked builder, not a stored JSON blob. Call
/// ``makeEntries(makeSession:)`` at seed time to materialise them into ``RigEntry`` snapshots.
///
/// Rig names and blurbs describe the *sound*; a blurb may reference an era or style but never a
/// trademarked product or a specific artist's endorsed setup.
@MainActor
public enum FactoryRigLibrary {
/// Catalog seed version. Bump this whenever the shipped starter rigs change — new rigs added, or
/// an existing rig's definition corrected — so launch catch-up re-runs on already-populated
/// libraries and refreshes every starter to its current form. Within a single version the marker
/// only advances once, so a starter the user deletes stays deleted until the next bump.
public static let seedVersion: Int = 4
/// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig.
///
/// Because factory rigs are seeded with their fixed ``FactoryRig/id``, an entry recalled from the
/// library can be identified as shipped-vs-user by id membership here. Callers use this to guard
/// destructive actions (e.g. warn before overwriting a starter rig).
public static let factoryIDs: Set<UUID> = Set(all.map { $0.id })
/// Whether `id` belongs to a shipped factory rig.
///
/// - Parameter id: A ``RigEntry/id`` from the rig library.
/// - Returns: `true` if the entry is one of the built-in starter rigs.
public static func isFactory(_ id: UUID) -> Bool {
factoryIDs.contains(id)
}
/// The ``FactoryRigCategory`` of the shipped rig with this id, or `nil` for a user rig.
///
/// - Parameter id: A ``RigEntry/id`` from the rig library.
/// - Returns: The rig's category, or `nil` if `id` is not a factory rig.
public static func category(for id: UUID) -> FactoryRigCategory? {
all.first(where: { $0.id == id })?.category
}
/// The shipped rigs of a given category, in catalog order.
///
/// - Parameter category: The category to filter by.
/// - Returns: The `FactoryRig`s in `category`, in the order they appear in ``all``.
public static func rigs(in category: FactoryRigCategory) -> [FactoryRig] {
all.filter { $0.category == category }
}
/// Every built-in rig, in the order a picker should present them.
public static let all: [FactoryRig] = [
glideWall,
chorusCathedral,
fuzzWahClassic,
dottedEighthAnthem,
ambientShimmerBed,
springReverbSurf,
octaveFuzzLead,
bitcrushNoiseTexture,
funkEnvelopeClav,
postRockCrescendo,
nashvilleCleanComp,
dubDelayThrow,
ringModTexture,
rockabillySlapback,
psychVibeLead,
comfortablyNumbLead,
doomRiffWall,
garciaOBELSplit,
]
// MARK: Shoegaze walls
/// Dense detuned fuzz + reverse swells + plate bloom.
static let glideWall: FactoryRig = FactoryRig(
id: stableID("Glide Wall"),
name: "90s Glide Wall",
blurb: "A dense, saturated fuzz wall with reverse swells blooming around it. Hold big open "
+ "chords and let the reverse delay and plate wash carry them — early-'90s British "
+ "shoegaze territory.",
category: .shoegazeWalls
) { _, board in
try board.append(FuzzPedal()) { p in
p.fuzz = 42.0
p.tone = 2600.0
}
try board.append(ChimeTopBoostAmpPedal()) { p in
p.gain = 6.5
p.bass = 0.6
p.mid = 0.4
p.treble = 0.7
p.cut = 0.3
p.brilliant = 1.0
}
try board.append(ReverseDelayPedal()) { p in
p.time = 0.45
p.feedback = 0.4
}
try board.append(PlateReverbPedal()) { p in
p.decay = 0.8
p.tone = 0.7
p.damp = 0.25
p.mod = 0.7
}
}
// MARK: Dreampop
/// Glassy clean chorus into cascading delay and octave-up shimmer.
static let chorusCathedral: FactoryRig = FactoryRig(
id: stableID("Chorus Cathedral"),
name: "Dreampop Chorus Cathedral",
blurb: "Glassy clean chorus into cascading delay and octave-up shimmer — lush and "
+ "weightless. Play slow arpeggios and let every note ring into the next.",
category: .dreamPop
) { _, board in
try board.append(CompressorPedal()) { p in
p.inputGain = 3.0
p.threshold = -18.0
p.ratio = 3.0
}
try board.append(FullertonReverbAmpPedal()) { p in
p.gain = 3.5
p.bass = 0.5
p.mid = 0.5
p.treble = 0.6
// Lean on the shimmer reverb downstream rather than the amp's own tank.
p.reverbEnabled = 0.0
p.vibratoEnabled = 0.0
}
// Chorus is a mono→stereo widener; keep it the only width change in the chain.
try board.append(ChorusPedal()) { p in
p.rate = 0.5
p.depth = 0.005
}
try board.append(DelayPedal()) { p in
p.time = 0.4
p.feedback = 1.5
}
try board.append(ShimmerReverbPedal()) { p in
// Keep decay + shimmer well below self-oscillation — the loop gain is ~decay + shimmer, so
// high values screech into runaway feedback with little or no input.
p.size = 0.09
p.decay = 0.5
p.shimmer = 0.25
p.damp = 0.5
}
}
// MARK: Classic
/// Envelope-wah into thick fuzz and a cranked British stack.
static let fuzzWahClassic: FactoryRig = FactoryRig(
id: stableID("Fuzz Wah Classic"),
name: "Fuzz + Wah Classic",
blurb: "Envelope-wah into thick fuzz and a cranked British stack — an expressive, vocal "
+ "lead voice with a touch of spring. Dig in and the wah opens up under your picking.",
category: .classic
) { _, board in
try board.append(AutoWahPedal()) { p in
p.sensitivity = 2.5
p.resonance = 4.0
p.range = 2600.0
}
try board.append(FuzzPedal()) { p in
p.fuzz = 38.0
p.tone = 3200.0
}
try board.append(BritishPlexiAmpPedal()) { p in
p.gain = 8.0
p.bass = 0.6
p.mid = 0.6
p.treble = 0.6
p.presence = 0.5
p.bright = 1.0
}
try board.append(SpringReverbPedal()) { p in
p.decay = 1.8
p.tension = 0.5
p.damp = 0.3
}
}
/// Chiming overdrive with a rhythmic dotted-eighth delay.
static let dottedEighthAnthem: FactoryRig = FactoryRig(
id: stableID("Dotted Eighth Anthem"),
name: "Dotted-Eighth Anthem",
blurb: "Chiming overdrive with a dotted-eighth delay that turns single notes into "
+ "cascading patterns — bright, anthemic, arena-sized. Tuned to a dotted eighth at 120 "
+ "BPM; play on the beat and let the echoes fill the gaps.",
category: .classic
) { _, board in
try board.append(OverdrivePedal()) { p in
p.drive = 5.0
p.tone = 4200.0
}
try board.append(ChimeTopBoostAmpPedal()) { p in
p.gain = 5.0
p.bass = 0.5
p.mid = 0.5
p.treble = 0.65
p.cut = 0.25
}
try board.append(DelayPedal()) { p in
// Dotted eighth at 120 BPM = 0.375 s.
p.time = 0.375
p.feedback = 1.6
}
try board.append(PlateReverbPedal()) { p in
p.decay = 0.6
p.tone = 0.8
p.damp = 0.3
p.mod = 0.4
}
}
/// Wet spring reverb and throbbing tremolo through a clean combo.
static let springReverbSurf: FactoryRig = FactoryRig(
id: stableID("Spring Reverb Surf"),
name: "Spring-Reverb Surf",
blurb: "Drippy spring reverb and throbbing tremolo through a clean Fullerton-style combo — "
+ "classic surf voicing. Stab chords and ride the tremolo.",
category: .classic
) { _, board in
try board.append(TremoloPedal()) { p in
p.rate = 5.5
p.depth = 0.6
}
try board.append(FullertonReverbAmpPedal()) { p in
p.gain = 3.5
p.bass = 0.55
p.mid = 0.5
p.treble = 0.6
p.reverb = 0.5
p.reverbEnabled = 1.0
p.vibratoEnabled = 0.0
}
try board.append(SpringReverbPedal()) { p in
p.decay = 2.2
p.tension = 0.6
p.damp = 0.25
}
}
// MARK: Ambient
/// Long feedback echoes into octave-up shimmer and a cavernous room.
static let ambientShimmerBed: FactoryRig = FactoryRig(
id: stableID("Ambient Shimmer Bed"),
name: "Ambient Shimmer Bed",
blurb: "Long feedback echoes wash into octave-up shimmer and a cavernous room — a slow, "
+ "evolving bed for swells and volume-knob fades. Play sparse and let it bloom.",
category: .ambient
) { _, board in
try board.append(CompressorPedal()) { p in
p.inputGain = 4.0
p.threshold = -20.0
p.ratio = 4.0
}
try board.append(FeedbackDelayPedal()) { p in
p.time = 0.6
p.feedback = 5.0
p.tone = 3500.0
}
try board.append(ShimmerReverbPedal()) { p in
// Long ambient tail, but decay + shimmer kept under ~0.8 so it never self-oscillates; the
// room reverb downstream supplies the extra length.
p.size = 0.11
p.decay = 0.6
p.shimmer = 0.2
p.damp = 0.5
}
try board.append(RoomReverbPedal()) { p in
p.size = 60.0
p.decay = 8.0
p.damp = 0.5
p.tail = 0.7
}
}
// MARK: Experimental
/// A sub-octave layered under saturated fuzz for a thick, synth-like lead.
static let octaveFuzzLead: FactoryRig = FactoryRig(
id: stableID("Octave Fuzz Lead"),
name: "Octave-Fuzz Lead",
blurb: "A sub-octave layered under saturated fuzz for a thick, synth-like lead, pushed "
+ "through a British master-volume voice. Single-note lines turn huge.",
category: .experimental
) { _, board in
try board.append(BassOctaverPedal()) { p in
p.oct1 = 0.8
p.oct2 = 0.2
p.direct = 0.9
// Track mode: follow the played pitch rather than octave-flip.
p.mode = 1.0
}
try board.append(FuzzPedal()) { p in
p.fuzz = 45.0
p.tone = 2800.0
}
try board.append(BritishMasterAmpPedal()) { p in
p.gain = 7.0
p.master = 0.5
p.bass = 0.55
p.mid = 0.6
p.treble = 0.55
p.presence = 0.4
}
try board.append(DelayPedal()) { p in
p.time = 0.28
p.feedback = 1.4
}
}
/// Gritty sample-rate crushing into runaway feedback delay and a wide room.
static let bitcrushNoiseTexture: FactoryRig = FactoryRig(
id: stableID("Bitcrush Noise Texture"),
name: "Bitcrush Noise Texture",
blurb: "Gritty sample-rate crushing into runaway feedback delay and a wide room — harsh, "
+ "lo-fi and unstable in the best way. Made for drones and glitch textures.",
category: .experimental
) { _, board in
try board.append(BitcrusherPedal()) { p in
p.crush = 6.0
p.bits = 5.0
p.tone = 3200.0
}
try board.append(FeedbackDelayPedal()) { p in
p.time = 0.33
p.feedback = 4.0
p.tone = 2800.0
}
try board.append(ReverbPedal()) { p in
p.roomSize = 0.8
p.damping = 0.4
}
}
// MARK: More classic voices
/// Envelope filter into light overdrive and a clean amp — funky, vocal, touch-sensitive.
static let funkEnvelopeClav: FactoryRig = FactoryRig(
id: stableID("Funk Envelope Clav"),
name: "Funk Envelope Clav",
blurb: "An envelope filter that opens with your picking, into light grit and a clean amp — "
+ "funky and vocal, the classic auto-wah clav voice. Play staccato and let your "
+ "dynamics work the filter.",
category: .classic
) { _, board in
try board.append(MutantPedal()) { p in
p.sensitivity = 3.0
p.resonance = 6.0
}
try board.append(OverdrivePedal()) { p in
p.drive = 3.0
p.tone = 4500.0
}
try board.append(JazzCleanAmpPedal()) { p in
p.gain = 4.0
p.bass = 0.5
p.mid = 0.6
p.treble = 0.6
p.reverb = 0.15
p.chorusEnabled = 0.0
}
}
/// Compressed clean into slapback echo and spring — bright, springy country/rockabilly.
static let nashvilleCleanComp: FactoryRig = FactoryRig(
id: stableID("Nashville Clean Comp"),
name: "Nashville Clean Comp",
blurb: "Squashed clean tone into a short slapback and spring reverb — bright, snappy and "
+ "articulate, the Nashville country voice. Hybrid-pick and let the compressor even it "
+ "out.",
category: .classic
) { _, board in
try board.append(CompressorPedal()) { p in
p.inputGain = 3.0
p.threshold = -16.0
p.ratio = 4.0
}
try board.append(FullertonReverbAmpPedal()) { p in
p.gain = 3.0
p.bass = 0.5
p.mid = 0.55
p.treble = 0.65
p.reverb = 0.3
p.reverbEnabled = 1.0
p.vibratoEnabled = 0.0
}
try board.append(DelayPedal()) { p in
// Short slapback.
p.time = 0.11
p.feedback = 0.3
}
}
/// Compressed chime into tight slapback and spring — classic rockabilly.
static let rockabillySlapback: FactoryRig = FactoryRig(
id: stableID("Rockabilly Slapback"),
name: "Rockabilly Slapback",
blurb: "Compressed chime with a tight tape-style slapback and spring — the rockabilly "
+ "bounce. Palm-mute and dig in for the classic '50s snap.",
category: .classic
) { _, board in
try board.append(CompressorPedal()) { p in
p.inputGain = 2.0
p.threshold = -14.0
p.ratio = 3.0
}
try board.append(ChimeTopBoostAmpPedal()) { p in
p.gain = 4.0
p.bass = 0.5
p.mid = 0.5
p.treble = 0.65
p.cut = 0.2
}
try board.append(DelayPedal()) { p in
// Very short slapback echo.
p.time = 0.09
p.feedback = 0.25
}
try board.append(SpringReverbPedal()) { p in
p.decay = 1.2
p.tension = 0.6
p.damp = 0.3
}
}
// MARK: More ambient / experimental voices
/// Overdriven arpeggios into long delay and shimmer — a swelling post-rock build.
static let postRockCrescendo: FactoryRig = FactoryRig(
id: stableID("Post-Rock Crescendo"),
name: "Post-Rock Crescendo",
blurb: "Warm overdrive into a long delay and octave-up shimmer — a swelling, cinematic "
+ "post-rock build. Layer arpeggios and let the wash grow into a crescendo.",
category: .ambient
) { _, board in
try board.append(OverdrivePedal()) { p in
p.drive = 6.0
p.tone = 4000.0
}
try board.append(DelayPedal()) { p in
p.time = 0.5
p.feedback = 2.5
}
try board.append(ShimmerReverbPedal()) { p in
p.size = 0.1
p.decay = 0.55
p.shimmer = 0.25
p.damp = 0.5
}
}
/// A dub-style feedback echo washing into deep spring — sparse, spacious, delay-forward.
static let dubDelayThrow: FactoryRig = FactoryRig(
id: stableID("Dub Delay Throw"),
name: "Dub Delay Throw",
blurb: "A long, dark feedback echo washing into deep spring reverb — the dub delay-throw. "
+ "Play sparse skanks and ride the feedback for runaway repeats.",
category: .ambient
) { _, board in
try board.append(CompressorPedal()) { p in
p.inputGain = 2.0
p.threshold = -16.0
p.ratio = 3.0
}
try board.append(FeedbackDelayPedal()) { p in
p.time = 0.45
p.feedback = 6.0
p.tone = 2500.0
}
try board.append(SpringReverbPedal()) { p in
p.decay = 2.5
p.tension = 0.5
p.damp = 0.35
}
}
/// Ring modulation into delay and reverb — clangorous, inharmonic, otherworldly.
static let ringModTexture: FactoryRig = FactoryRig(
id: stableID("Ring-Mod Texture"),
name: "Ring-Mod Texture",
blurb: "Ring modulation into delay and a wide room — clangorous, inharmonic and "
+ "otherworldly. Try single notes and let the metallic overtones ring out.",
category: .experimental
) { _, board in
try board.append(RingModulatorPedal()) { p in
p.frequency = 180.0
}
try board.append(DelayPedal()) { p in
p.time = 0.3
p.feedback = 1.8
}
try board.append(ReverbPedal()) { p in
p.roomSize = 0.75
p.damping = 0.4
}
}
/// Fuzz swirled by a throbbing vibe into delay and plate — vintage psychedelic lead.
static let psychVibeLead: FactoryRig = FactoryRig(
id: stableID("Psych Vibe Lead"),
name: "Psychedelic Vibe Lead",
blurb: "Thick fuzz swirled by a throbbing photocell vibe, into delay and plate — the "
+ "late-'60s psychedelic lead voice. Hold notes and let the vibe pulse underneath.",
category: .classic
) { _, board in
try board.append(FuzzPedal()) { p in
p.fuzz = 30.0
p.tone = 3000.0
}
try board.append(VibePedal()) { p in
p.speed = 2.5
p.intensity = 0.6
// Chorus mode: dry + swept, the classic vibe throb.
p.mode = 0.0
}
try board.append(DelayPedal()) { p in
p.time = 0.4
p.feedback = 2.0
}
try board.append(PlateReverbPedal()) { p in
p.decay = 0.6
p.tone = 0.75
p.damp = 0.3
p.mod = 0.5
}
}
/// Compressed sustaining fuzz into a dotted delay and shimmer — a soaring, singing lead.
static let comfortablyNumbLead: FactoryRig = FactoryRig(
id: stableID("Comfortably Numb Lead"),
name: "Comfortably Numb Lead",
blurb: "Compressed, mid-scooped sustain fuzz into a dotted delay and octave-up shimmer — a "
+ "soaring, singing lead that holds forever. Bend into long notes and let them bloom.",
category: .classic
) { _, board in
try board.append(CompressorPedal()) { p in
p.inputGain = 4.0
p.threshold = -18.0
p.ratio = 4.0
}
try board.append(SustainFuzzPedal()) { p in
p.sustain = 14.0
p.tone = 3000.0
p.scoop = 10.0
}
try board.append(DelayPedal()) { p in
// Dotted eighth at ~100 BPM.
p.time = 0.45
p.feedback = 2.2
}
try board.append(ShimmerReverbPedal()) { p in
p.size = 0.09
p.decay = 0.55
p.shimmer = 0.25
p.damp = 0.5
}
}
/// Sub-octave under a huge scooped fuzz into a cavernous room — heavy, slow doom.
static let doomRiffWall: FactoryRig = FactoryRig(
id: stableID("Doom Riff Wall"),
name: "Doom Riff Wall",
blurb: "A sub-octave stacked under a huge mid-scooped fuzz, into a cavernous room — crushing, "
+ "slow doom. Down-tune, play half-time and let the low end swallow the room.",
category: .experimental
) { _, board in
try board.append(BassOctaverPedal()) { p in
p.oct1 = 0.8
p.oct2 = 0.3
p.direct = 0.9
// Track mode: follow the played pitch.
p.mode = 1.0
}
try board.append(SustainFuzzPedal()) { p in
p.sustain = 22.0
p.tone = 2200.0
p.scoop = 6.0
}
try board.append(RoomReverbPedal()) { p in
p.size = 70.0
p.decay = 6.0
p.damp = 0.55
p.tail = 0.7
}
}
// MARK: Two-board split
/// Two boards — a full effects chain and a clean direct path — switched with the board selector.
static let garciaOBELSplit: FactoryRig = FactoryRig(
id: stableID("Garcia OBEL Split"),
name: "Garcia OBEL Clean/Effects Split",
blurb: "Two boards, one selector: Board 1 is an effects/lead chain (octave, envelope filter, "
+ "overdrive, graphic EQ, phaser, delay, reverb); Board 2 is a fuller direct voice "
+ "(overdrive, graphic EQ, compression, reverb). Use the board Solo / Blend control at the "
+ "top to switch between them, like an on-board effects loop. In the spirit of a certain "
+ "improvising guitarist's late-'80s rig.",
category: .classic,
// Hand-authored in the app and shipped as a captured state — transcribing the exact pedal
// values (mix, graphic-EQ sliders, cab selector, amp sag/bias) is more faithful than
// re-deriving them through typed setters. Input source / channel counts are intentionally
// omitted so the rig is input-agnostic.
state: garciaState
)
/// The shipped Garcia rig content. `static let` so its (default) pedal ids are stable per process,
/// keeping seeding deterministic.
private static let garciaState: ShoeGazeState = ShoeGazeState(
boards: [
BoardState(label: "Board 1", pedals: [
PedalState(type: "Bass Octaver",
knobValues: [0.5, 0, 1, 1, 1], switchValues: [1], bypass: 0),
PedalState(type: "Mutant",
knobValues: [2.5, 4.45515625, 1, 1], switchValues: [1, 0], bypass: 0),
PedalState(type: "Overdrive",
knobValues: [5, 4200, 1, 1], bypass: 0),
PedalState(type: "Graphic EQ",
knobValues: [1, 1],
sliderValues: [-4.7786931818181815, -2.214204545454546, 1.552840909090909,
1.8536931818181799, -3.3426136363636374, -0.45852272727272947],
bypass: 0),
PedalState(type: "Phaser",
knobValues: [0.4, 0.4, 0.5, 1], bypass: 0),
PedalState(type: "Delay",
knobValues: [0.35, 1.8, 0.35, 1], bypass: 0),
PedalState(type: "Fullerton Reverb",
knobValues: [2.5505078125, 0.5, 0.5, 0.6, 0.25, 4, 0, 1, 1],
switchValues: [0, 1, 0], selectorValues: [4],
advancedValues: [0, 0.5, 0], bypass: 0),
]),
BoardState(label: "Board 2", pedals: [
PedalState(type: "Overdrive",
knobValues: [6.54533203125, 4000, 1, 1], bypass: 0),
PedalState(type: "Graphic EQ",
knobValues: [1, 1],
sliderValues: [2.957386363636365, 0, 2.7741477272727266,
1.940624999999999, -0.6767045454545446, 0],
bypass: 0),
PedalState(type: "Compressor",
knobValues: [2, -16, 3, 1, 1], switchValues: [0], bypass: 0),
PedalState(type: "Fullerton Reverb",
knobValues: [5.08, 0.5, 0.5, 0.6, 0.13624999999999998, 4, 0, 1, 1],
switchValues: [0, 1, 0], selectorValues: [4],
advancedValues: [0, 0.5, 0], bypass: 0),
]),
],
bpm: 120,
tempoEnabled: true
)
// MARK: - Seeding
/// Builds every factory rig into a ``RigEntry`` snapshot suitable for the rig library.
///
/// Each rig is constructed in a fresh, **never-started** ``ShoeGaze`` session (capturing a rig
/// only reads `@UIParam` values — no audio is rendered), captured with the rig's stable `id`, and
/// the session is torn down before the next. Because ids are stable, re-running this against an
/// already-seeded library overwrites entries in place rather than duplicating them.
///
/// - Parameter makeSession: Returns a fresh, empty session (typically backed by an offline
/// engine). Called once per rig.
/// - Returns: One ``RigEntry`` per ``all`` rig, in catalog order.
/// - Throws: Any error from session creation, board building, or finalisation.
public static func makeEntries(
makeSession: @MainActor () throws -> ShoeGaze
) throws -> [RigEntry] {
var entries: [RigEntry] = []
entries.reserveCapacity(all.count)
for rig: FactoryRig in all {
// A state-backed rig needs no live session — build its entry directly from the state.
if case .state(let makeState) = rig.build {
entries.append(RigEntry(id: rig.id, name: rig.name, state: makeState()))
continue
}
let session: ShoeGaze = try makeSession()
// Tear down on every exit from this iteration, including a throw from a builder, so a
// failing rig never leaks its throwaway engine's buses/nodes.
defer { session.teardown() }
switch rig.build {
case .singleBoard(let build):
let board: PedalBoard = try session.addBoard()
try build(session, board)
try session.finalizeBoard(board)
case .session(let build):
// The builder owns its own board/router lifecycle (addBoard/finalizeBoard,
// makeChainRouter/finalize).
try build(session)
case .state:
continue // handled above
}
entries.append(session.captureEntry(name: rig.name, id: rig.id))
}
return entries
}
/// Builds every factory rig using a self-contained offline engine per rig.
///
/// Convenience over ``makeEntries(makeSession:)`` for callers with no session of their own (the
/// first-launch seeding path). Each rig gets a fresh ``NRTDriver``-backed engine that is never
/// started — no audio is rendered and no output file is written (the driver only touches disk in
/// `start()`), so the temporary URL handed to the driver never comes into existence.
///
/// - Returns: One ``RigEntry`` per ``all`` rig, in catalog order.
/// - Throws: Any error from board building or finalisation.
public static func makeEntries() throws -> [RigEntry] {
try makeEntries(makeSession: makeOfflineSeedSession)
}
/// Block size for the throwaway seeding engine. Matches the framework default; never renders.
private static let seedBlockSize: Int = 512
/// Sample rate for the throwaway seeding engine. Only affects `@UIParam` capture indirectly; no
/// audio is produced.
private static let seedSampleRate: Double = 44_100.0
/// Audio bus count for the throwaway seeding engine — generous headroom for the longest chain.
private static let seedAudioBusCount: Int = 128
/// Control bus count for the throwaway seeding engine.
private static let seedControlBusCount: Int = 512
/// Nominal render duration handed to the offline driver. Unused — the engine is never started.
private static let seedRenderDuration: Double = 0.05
/// Creates a fresh, never-started offline ``ShoeGaze`` session for building one factory rig.
private static func makeOfflineSeedSession() -> ShoeGaze {
let outputURL: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".caf")
let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: seedRenderDuration)
let engine: SynthesisEngine = SynthesisEngine(
blockSize: seedBlockSize,
sampleRate: seedSampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: seedAudioBusCount,
numControlBuses: seedControlBusCount,
driver: driver
)
return ShoeGaze(engine: engine, inputSource: .testLoop)
}
// MARK: - Stable identifiers
/// Deterministic UUID derived from a rig's identity string via two FNV-1a hashes.
///
/// Gives each rig a stable library id across launches without a hand-written UUID literal, and
/// keeps seeding idempotent (same id ⇒ overwrite in place). Not a cryptographic identifier —
/// only stability and per-rig uniqueness matter here.
static func stableID(_ seed: String) -> UUID {
let fnvOffset: UInt64 = 0xcbf2_9ce4_8422_2325
let fnvPrime: UInt64 = 0x0000_0100_0000_01b3
func hash(_ string: String) -> UInt64 {
var value: UInt64 = fnvOffset
for byte: UInt8 in string.utf8 {
value = (value ^ UInt64(byte)) &* fnvPrime
}
return value
}
let high: UInt64 = hash(seed)
let low: UInt64 = hash(seed + "\u{1}salt")
func byte(_ source: UInt64, _ shift: UInt64) -> UInt8 {
UInt8((source >> shift) & 0xFF)
}
let bytes: uuid_t = (
byte(high, 56), byte(high, 48), byte(high, 40), byte(high, 32),
byte(high, 24), byte(high, 16), byte(high, 8), byte(high, 0),
byte(low, 56), byte(low, 48), byte(low, 40), byte(low, 32),
byte(low, 24), byte(low, 16), byte(low, 8), byte(low, 0)
)
return UUID(uuid: bytes)
}
}
@@ -20,6 +20,7 @@ extension Pedal {
let switchValues: [Double] = effectSwitches.map { $0.node.value } let switchValues: [Double] = effectSwitches.map { $0.node.value }
let sliderValues: [Double] = effectSliders.map { $0.node.value } let sliderValues: [Double] = effectSliders.map { $0.node.value }
let selectorValues: [Double] = effectSelectors.map { $0.node.value } let selectorValues: [Double] = effectSelectors.map { $0.node.value }
let advancedValues: [Double] = advancedKnobs.map { $0.node.value }
return PedalState( return PedalState(
id: id, id: id,
type: displayName, type: displayName,
@@ -27,26 +28,74 @@ extension Pedal {
switchValues: switchValues, switchValues: switchValues,
sliderValues: sliderValues, sliderValues: sliderValues,
selectorValues: selectorValues, selectorValues: selectorValues,
advancedValues: advancedValues,
bypass: bypass, bypass: bypass,
tempoSync: tempoSync.isEmpty ? nil : tempoSync, tempoSync: tempoSync.isEmpty ? nil : tempoSync,
resourcePath: resourcePath resourcePath: resourcePath
) )
} }
/// Modern High-Gain's display name — the one shipped amp whose `Sag` control started life as a
/// face knob and later moved to the advanced pop-over. Used to detect its legacy `PedalState`
/// layout in ``legacyMigrated(_:)``.
private static let modernHighGainType: String = "Modern High-Gain"
/// A legacy Modern High-Gain `PedalState` has 11 `knobValues`: `Gain, Bass, Mid, Treble,
/// Presence, Depth, Master, Drive, Sag, Mix, Level`.
private static let modernHighGainLegacyKnobCount: Int = 11
/// Index of `Sag` in that legacy `knobValues` array (the 9th knob).
private static let modernHighGainLegacySagIndex: Int = 8
/// Normalizes a `PedalState` saved under a superseded on-disk layout to the current shape, so old
/// rigs load without corruption.
///
/// Currently one case: **Modern High-Gain** shipped `Sag` as its 9th face knob (`knobValues`
/// index 8, ahead of the trailing `Mix`/`Level`); `Sag` has since moved to the advanced pop-over,
/// so it is no longer in `knobValues`. Because `knobValues` is a flat positional array, loading a
/// legacy preset against the current 10-knob shape would misassign the old `Sag` onto `Mix` and
/// the old `Mix` onto `Level`. Detected by the legacy shape (11 `knobValues`, empty
/// `advancedValues`) and rewritten: `Sag` is lifted out of `knobValues` into `advancedValues`,
/// leaving `Gain…Drive, Mix, Level` in order. `Bias` (the second advanced knob) had no legacy
/// value, so it stays at its default.
///
/// - Parameter state: The decoded state, possibly in a legacy layout.
/// - Returns: The state in the current layout, or `state` unchanged when no migration applies.
private static func legacyMigrated(_ state: PedalState) -> PedalState {
guard state.type == modernHighGainType,
state.advancedValues.isEmpty,
state.knobValues.count == modernHighGainLegacyKnobCount else {
return state
}
let sag: Double = state.knobValues[modernHighGainLegacySagIndex]
var knobValues: [Double] = state.knobValues
knobValues.remove(at: modernHighGainLegacySagIndex)
return PedalState(
id: state.id,
type: state.type,
knobValues: knobValues,
switchValues: state.switchValues,
sliderValues: state.sliderValues,
selectorValues: state.selectorValues,
advancedValues: [sag],
bypass: state.bypass,
tempoSync: state.tempoSync,
resourcePath: state.resourcePath
)
}
/// Applies a previously captured `PedalState` to this pedal's parameters. /// Applies a previously captured `PedalState` to this pedal's parameters.
/// ///
/// For each (knob, value) pair in `zip(knobs, state.knobValues)`, the knob's /// The incoming state is first normalized by ``legacyMigrated(_:)`` for older on-disk layouts.
/// `UIParamNode` is updated via `node.update(_:)`; switch positions are restored the /// For each (knob, value) pair in `zip(knobs, state.knobValues)`, the knob's `UIParamNode` is
/// same way from `zip(effectSwitches, state.switchValues)`. If either array has fewer /// updated via `node.update(_:)`; switch, slider, selector, and advanced-knob positions are
/// entries than its controls, the trailing controls retain their current values; extra /// restored the same way. If either array has fewer entries than its controls, the trailing
/// values are ignored. The `bypass` parameter is always applied regardless of any /// controls retain their current values; extra values are ignored. The `bypass` parameter is
/// count mismatch. Presets saved before switches existed carry an empty /// always applied regardless of any count mismatch. Presets saved before a given control existed
/// `switchValues`, leaving switch positions at their defaults. /// carry an empty array for it, leaving those controls at their defaults.
/// ///
/// - Parameter state: The state to restore. The `state.type` is not validated /// - Parameter rawState: The state to restore. The `state.type` is not validated against
/// against `displayName` — the caller is responsible for matching types before /// `displayName` — the caller is responsible for matching types before calling this method.
/// calling this method. public func applyState(_ rawState: PedalState) {
public func applyState(_ state: PedalState) { let state: PedalState = Pedal.legacyMigrated(rawState)
// Restore the saved identity so the pedal keeps its id across rebuilds; MIDI bindings // Restore the saved identity so the pedal keeps its id across rebuilds; MIDI bindings
// address pedals by this id. // address pedals by this id.
id = state.id id = state.id
@@ -62,6 +111,9 @@ extension Pedal {
for (selector, value) in zip(effectSelectors, state.selectorValues) { for (selector, value) in zip(effectSelectors, state.selectorValues) {
selector.node.update(value) selector.node.update(value)
} }
for (advancedKnob, value) in zip(advancedKnobs, state.advancedValues) {
advancedKnob.node.update(value)
}
bypass = state.bypass bypass = state.bypass
// Restore tempo-sync state. The synced values themselves are recomputed from the rig's // Restore tempo-sync state. The synced values themselves are recomputed from the rig's
// tempo by `ShoeGaze` after the rebuild, so no clock is required here. // tempo by `ShoeGaze` after the rebuild, so no clock is required here.
@@ -40,23 +40,33 @@ public enum PedalRegistry {
"British Dual": { BritishDualAmpPedal() }, "British Dual": { BritishDualAmpPedal() },
"Boutique Lead": { BoutiqueLeadAmpPedal() }, "Boutique Lead": { BoutiqueLeadAmpPedal() },
"Boutique OD": { BoutiqueODAmpPedal() }, "Boutique OD": { BoutiqueODAmpPedal() },
"Cali Hi-Gain": { CaliHiGainAmpPedal() },
"Command": { CommandAmpPedal() },
"Citrus": { CitrusAmpPedal() },
"Sixties Combo": { SixtiesComboAmpPedal() },
"Magna Vibrato": { MagnaVibratoAmpPedal() },
"Anaheim": { AnaheimAmpPedal() },
"Modern High-Gain": { ModernHighGainAmpPedal() },
"Chime": { ChimeAmpPedal() }, "Chime": { ChimeAmpPedal() },
"Chime 15": { ChimeFifteenAmpPedal() }, "Chime 15": { ChimeFifteenAmpPedal() },
"Chime Normal": { ChimeNormalAmpPedal() }, "Chime Normal": { ChimeNormalAmpPedal() },
"Chime Baby": { ChimeBabyAmpPedal() }, "Chime Baby": { ChimeBabyAmpPedal() },
"Fullerton Reverb": { FullertonReverbAmpPedal() }, "Fullerton Reverb": { FullertonReverbAmpPedal() },
"Fullerton Deluxe": { FullertonDeluxeAmpPedal() }, "Fullerton Deluxe": { FullertonDeluxeAmpPedal() },
"Fullerton Princeton": { FullertonPrincetonAmpPedal() }, "Fullerton Ivy League": { FullertonPrincetonAmpPedal() },
"Fullerton Drive": { FullertonDriveAmpPedal() }, "Fullerton Drive": { FullertonDriveAmpPedal() },
"Jazz Clean": { JazzCleanAmpPedal() }, "Jazz Clean": { JazzCleanAmpPedal() },
"Chime Top Boost": { ChimeTopBoostAmpPedal() }, "Chime Top Boost": { ChimeTopBoostAmpPedal() },
"Neural Amp": { NeuralAmpPedal() }, // "Neural Amp" intentionally NOT registered -- hidden from the palette while the neural
// model-loader's security-scoped file access is unresolved. NeuralAmpPedal + its UI are kept
// for later iteration; re-add this entry (and the palette order below) to re-enable.
"Overdrive": { OverdrivePedal() }, "Overdrive": { OverdrivePedal() },
"Distortion": { DistortionPedal() }, "Distortion": { DistortionPedal() },
"Delay": { DelayPedal() }, "Delay": { DelayPedal() },
"Reverb": { ReverbPedal() }, "Reverb": { ReverbPedal() },
"Modulation": { ModulationPedal() }, "Modulation": { ModulationPedal() },
"Fuzz": { FuzzPedal() }, "Fuzz": { FuzzPedal() },
"Sustain Fuzz": { SustainFuzzPedal() },
"Tremolo": { TremoloPedal() }, "Tremolo": { TremoloPedal() },
"Phaser": { PhaserPedal() }, "Phaser": { PhaserPedal() },
"Compressor": { CompressorPedal() }, "Compressor": { CompressorPedal() },
@@ -82,6 +92,7 @@ public enum PedalRegistry {
"Chorus": { ChorusPedal() }, "Chorus": { ChorusPedal() },
"Flanger": { FlangerPedal() }, "Flanger": { FlangerPedal() },
"Vibrato": { VibratoPedal() }, "Vibrato": { VibratoPedal() },
"Vibe": { VibePedal() },
"Rotary": { RotaryPedal() }, "Rotary": { RotaryPedal() },
"Sustainer": { SustainerPedal() }, "Sustainer": { SustainerPedal() },
"Ring Modulator": { RingModulatorPedal() }, "Ring Modulator": { RingModulatorPedal() },
@@ -92,6 +103,15 @@ public enum PedalRegistry {
"Looper": { LooperPedal() }, "Looper": { LooperPedal() },
] ]
/// Maps a pedal `displayName` that has since been renamed to its current registry key, so rigs
/// saved under the old name still load (the `displayName` **is** the serialization key — see
/// ``BoardSegmentState`` — so a bare rename would silently drop the pedal on load). A loaded
/// pedal takes the new name and re-saves under it, so this is self-healing. Extend when renaming
/// any shipped pedal's `displayName`.
static let legacyTypeAliases: [String: String] = [
"Fullerton Princeton": "Fullerton Ivy League",
]
/// Returns a new `Pedal` instance for the given type string, or `nil` if the type /// Returns a new `Pedal` instance for the given type string, or `nil` if the type
/// is not in the built-in registry. /// is not in the built-in registry.
/// ///
@@ -99,11 +119,15 @@ public enum PedalRegistry {
/// the caller is responsible for routing it via `board.add(_:)` before the engine /// the caller is responsible for routing it via `board.add(_:)` before the engine
/// processes any audio. /// processes any audio.
/// ///
/// A ``legacyTypeAliases`` entry is resolved first, so a rig saved under a pedal's old
/// `displayName` still reconstructs the renamed pedal.
///
/// - Parameter type: The `displayName` of the pedal (e.g. `"Overdrive"`, `"Delay"`). /// - Parameter type: The `displayName` of the pedal (e.g. `"Overdrive"`, `"Delay"`).
/// - Returns: A freshly allocated `Pedal` subclass instance, or `nil` for unknown types. /// - Returns: A freshly allocated `Pedal` subclass instance, or `nil` for unknown types.
@MainActor @MainActor
public static func makePedal(type: String) -> Pedal? { public static func makePedal(type: String) -> Pedal? {
guard let constructor: @MainActor () -> Pedal = builtIn[type] else { return nil } let resolvedType: String = legacyTypeAliases[type] ?? type
guard let constructor: @MainActor () -> Pedal = builtIn[resolvedType] else { return nil }
return constructor() return constructor()
} }
@@ -42,6 +42,10 @@ public struct PedalState: Codable, Equatable {
/// no selectors. Absent in presets saved before selectors existed — decodes to `[]`. /// no selectors. Absent in presets saved before selectors existed — decodes to `[]`.
public let selectorValues: [Double] public let selectorValues: [Double]
/// Advanced (pop-over) knob values in the same order as `Pedal.advancedKnobs`. Empty for pedals
/// with no advanced knobs. Absent in presets saved before advanced knobs existed — decodes to `[]`.
public let advancedValues: [Double]
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed. /// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
public let bypass: Double public let bypass: Double
@@ -62,6 +66,7 @@ public struct PedalState: Codable, Equatable {
/// - switchValues: Current switch values in `Pedal.effectSwitches` order. Defaults to empty. /// - switchValues: Current switch values in `Pedal.effectSwitches` order. Defaults to empty.
/// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty. /// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty.
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty. /// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
/// - advancedValues: Current advanced-knob values in `Pedal.advancedKnobs` order. Defaults to empty.
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed). /// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
/// - tempoSync: Tempo-sync state per syncable parameter, or `nil` for none. Defaults to `nil`. /// - tempoSync: Tempo-sync state per syncable parameter, or `nil` for none. Defaults to `nil`.
/// - resourcePath: Path to an external resource the pedal references (e.g. a neural-amp /// - resourcePath: Path to an external resource the pedal references (e.g. a neural-amp
@@ -73,6 +78,7 @@ public struct PedalState: Codable, Equatable {
switchValues: [Double] = [], switchValues: [Double] = [],
sliderValues: [Double] = [], sliderValues: [Double] = [],
selectorValues: [Double] = [], selectorValues: [Double] = [],
advancedValues: [Double] = [],
bypass: Double, bypass: Double,
tempoSync: [String: TempoSync]? = nil, tempoSync: [String: TempoSync]? = nil,
resourcePath: String? = nil resourcePath: String? = nil
@@ -83,6 +89,7 @@ public struct PedalState: Codable, Equatable {
self.switchValues = switchValues self.switchValues = switchValues
self.sliderValues = sliderValues self.sliderValues = sliderValues
self.selectorValues = selectorValues self.selectorValues = selectorValues
self.advancedValues = advancedValues
self.bypass = bypass self.bypass = bypass
self.tempoSync = tempoSync self.tempoSync = tempoSync
self.resourcePath = resourcePath self.resourcePath = resourcePath
@@ -95,13 +102,14 @@ public struct PedalState: Codable, Equatable {
case switchValues case switchValues
case sliderValues case sliderValues
case selectorValues case selectorValues
case advancedValues
case bypass case bypass
case tempoSync case tempoSync
case resourcePath case resourcePath
} }
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` / /// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` /
/// `selectorValues` / `tempoSync` existed by defaulting the missing keys. /// `selectorValues` / `advancedValues` / `tempoSync` existed by defaulting the missing keys.
public init(from decoder: any Decoder) throws { public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self) let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
@@ -110,6 +118,7 @@ public struct PedalState: Codable, Equatable {
self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? [] self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? []
self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? [] self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? []
self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? [] self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? []
self.advancedValues = try container.decodeIfPresent([Double].self, forKey: .advancedValues) ?? []
self.bypass = try container.decode(Double.self, forKey: .bypass) self.bypass = try container.decode(Double.self, forKey: .bypass)
self.tempoSync = try container.decodeIfPresent([String: TempoSync].self, forKey: .tempoSync) self.tempoSync = try container.decodeIfPresent([String: TempoSync].self, forKey: .tempoSync)
self.resourcePath = try container.decodeIfPresent(String.self, forKey: .resourcePath) self.resourcePath = try container.decodeIfPresent(String.self, forKey: .resourcePath)
@@ -18,6 +18,16 @@ extension ShoeGaze {
/// - Returns: A `ShoeGazeState` reflecting the current rig. /// - Returns: A `ShoeGazeState` reflecting the current rig.
public func captureState() -> ShoeGazeState { public func captureState() -> ShoeGazeState {
let boardStates: [BoardState] = boards.map { $0.captureState() } let boardStates: [BoardState] = boards.map { $0.captureState() }
let routerStates: [ChainRouterState] = routers.map { router in
ChainRouterState(
boardA: router.boardA.pedals.map { $0.captureState() },
boardB: router.boardB.pedals.map { $0.captureState() },
branchA: router.splitter.branchAEnabled,
branchB: router.splitter.branchBEnabled,
mergerLevelA: router.merger?.levelA ?? 1.0,
mergerLevelB: router.merger?.levelB ?? 1.0
)
}
return ShoeGazeState( return ShoeGazeState(
boards: boardStates, boards: boardStates,
midiMap: midiMap, midiMap: midiMap,
@@ -25,7 +35,10 @@ extension ShoeGaze {
tempoEnabled: tempoEnabled, tempoEnabled: tempoEnabled,
inputSource: inputSource, inputSource: inputSource,
numInputChannels: engine.numInputChannels, numInputChannels: engine.numInputChannels,
numOutputChannels: engine.numOutputChannels numOutputChannels: engine.numOutputChannels,
// `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is
// unchanged and byte-identical to one saved before router persistence existed.
routers: routerStates.isEmpty ? nil : routerStates
) )
} }
@@ -94,9 +107,18 @@ extension ShoeGaze {
/// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``. /// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``.
/// ///
/// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``. /// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``.
/// - Parameter state: The rig snapshot to restore. /// - Parameters:
/// - state: The rig snapshot to restore.
/// - keepingCurrentInput: When `true`, the session's current ``inputSource`` is preserved and
/// the rig's saved input is ignored — used when the player switches between rigs, so the live
/// input (e.g. a plugged-in guitar) doesn't snap back to the test loop a rig was authored
/// with. When `false` (the default, used by file open and launch restore), the rig's saved
/// input is applied so a saved/loaded rig recreates its authored input. Defaults to `false`.
/// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error. /// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error.
public func loadRig(from state: ShoeGazeState) throws { public func loadRig(
from state: ShoeGazeState,
keepingCurrentInput: Bool = false
) throws {
guard state.version <= presetFormatVersion else { guard state.version <= presetFormatVersion else {
throw PresetError.unsupportedVersion(state.version) throw PresetError.unsupportedVersion(state.version)
} }
@@ -107,11 +129,12 @@ extension ShoeGaze {
// enable-live-input flow (rebuild engine to 1 input, then load a rig saved with 0). Apply a // enable-live-input flow (rebuild engine to 1 input, then load a rig saved with 0). Apply a
// rig's saved layout deliberately via `applyChannelLayout(from:)` / the config UI instead. // rig's saved layout deliberately via `applyChannelLayout(from:)` / the config UI instead.
// Restore the saved input source before rebuilding, since board construction reads it. A // Restore the saved input source before rebuilding, since board construction reads it — unless
// saved live-input channel that no longer exists on this engine falls back to the test loop // the caller is switching rigs (`keepingCurrentInput`), in which case the current input is
// (same guard as reconfigureEngine), so the rebuild's addBoard() can't throw on a stale // kept so the player's live input survives the switch. A saved live-input channel that no
// channel. Absent (older rig) → leave the current input source untouched. // longer exists on this engine falls back to the test loop (same guard as reconfigureEngine),
if let savedInput: InputSource = state.inputSource { // so the rebuild's addBoard() can't throw on a stale channel. Absent (older rig) → untouched.
if !keepingCurrentInput, let savedInput: InputSource = state.inputSource {
if case .liveInput(let channel) = savedInput, if case .liveInput(let channel) = savedInput,
channel < 0 || channel >= engine.numInputChannels { channel < 0 || channel >= engine.numInputChannels {
inputSource = .testLoop inputSource = .testLoop
@@ -162,6 +185,9 @@ extension ShoeGaze {
try rebuildSegments(boardState.segments, into: board) try rebuildSegments(boardState.segments, into: board)
try finalizeBoard(board) try finalizeBoard(board)
} }
for routerState: ChainRouterState in snapshot.routers ?? [] {
try rebuildRouter(routerState)
}
} catch { } catch {
// Leave no partial rig behind: tear down whatever was built, then rethrow. // Leave no partial rig behind: tear down whatever was built, then rethrow.
teardown() teardown()
@@ -169,6 +195,32 @@ extension ShoeGaze {
} }
} }
/// Reconstructs one ``ChainRouter`` from a saved snapshot: creates the router, replays both linear
/// branches (skipping unknown pedal types), finalizes, then restores the splitter branch levels
/// and merger output levels so the saved A / B / blend selection is preserved.
///
/// - Parameter state: The router snapshot to reconstruct.
/// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from router construction.
private func rebuildRouter(_ state: ChainRouterState) throws {
let router: ChainRouter = try makeChainRouter()
for pedalState: PedalState in state.boardA {
if let pedal: Pedal = makeAndApply(pedalState) {
try router.addToA(pedal)
}
}
for pedalState: PedalState in state.boardB {
if let pedal: Pedal = makeAndApply(pedalState) {
try router.addToB(pedal)
}
}
try router.finalize()
// Restore the blend after finalize: the splitter exists from init, the merger only after.
router.splitter.branchAEnabled = state.branchA
router.splitter.branchBEnabled = state.branchB
router.merger?.levelA = state.mergerLevelA
router.merger?.levelB = state.mergerLevelB
}
/// Loads a rig from a JSON preset file and rebuilds the engine graph. /// Loads a rig from a JSON preset file and rebuilds the engine graph.
/// ///
/// This method: /// This method:
@@ -368,6 +420,19 @@ extension ShoeGaze {
} }
} }
} }
// Routers recall positionally too: their branch pedals' params and the splitter/merger
// blend. Topology (pedal counts/types) is assumed identical for a lightweight recall — a
// mismatch is skipped, exactly as for boards. A `rebuildsOnChange` selector inside a router
// branch is not handled here (routers have no per-branch rebuild path); use `loadRig(from:)`
// for that.
for (router, routerState): (ChainRouter, ChainRouterState) in zip(routers, state.routers ?? []) {
applyLinearParams(routerState.boardA, to: router.boardA.pedals)
applyLinearParams(routerState.boardB, to: router.boardB.pedals)
router.splitter.branchAEnabled = routerState.branchA
router.splitter.branchBEnabled = routerState.branchB
router.merger?.levelA = routerState.mergerLevelA
router.merger?.levelB = routerState.mergerLevelB
}
// A recall restores each pedal's tempo-sync state but not its derived values (no clock is // A recall restores each pedal's tempo-sync state but not its derived values (no clock is
// consulted in `Pedal.applyState`), so recompute them against the rig's current tempo — // consulted in `Pedal.applyState`), so recompute them against the rig's current tempo —
// mirroring the full `loadRig(from:)` path. // mirroring the full `loadRig(from:)` path.
@@ -376,6 +441,15 @@ extension ShoeGaze {
} }
} }
/// Positionally applies pedal parameter snapshots to a live linear pedal chain (e.g. a router
/// branch). A position whose live pedal type doesn't match the snapshot is skipped, matching the
/// silent-skip semantics of the board recall path.
private func applyLinearParams(_ states: [PedalState], to pedals: [Pedal]) {
for (pedal, state): (Pedal, PedalState) in zip(pedals, states) where pedal.displayName == state.type {
pedal.applyState(state)
}
}
/// Positionally applies segment parameter snapshots to live board segments, including /// Positionally applies segment parameter snapshots to live board segments, including
/// branch pedals and split routing modes. Type or topology mismatches at any position are /// branch pedals and split routing modes. Type or topology mismatches at any position are
/// skipped silently (lightweight recall is for topologically identical rigs). /// skipped silently (lightweight recall is for topologically identical rigs).
@@ -57,6 +57,11 @@ public struct ShoeGazeState: Codable, Equatable {
/// persistence. Reapplied on load under the same conditions as ``numInputChannels``. /// persistence. Reapplied on load under the same conditions as ``numInputChannels``.
public let numOutputChannels: Int? public let numOutputChannels: Int?
/// The rig's chain routers (two-board split/blend units), or `nil` for a rig saved before router
/// persistence existed. Additive: decoded with `decodeIfPresent`, so older rigs — which never had
/// routers — decode cleanly to `nil` without a format-version bump.
public let routers: [ChainRouterState]?
/// Creates a rig state snapshot. /// Creates a rig state snapshot.
/// ///
/// - Parameters: /// - Parameters:
@@ -68,6 +73,7 @@ public struct ShoeGazeState: Codable, Equatable {
/// - inputSource: The rig's input selection, or `nil` to not persist one. Defaults to `nil`. /// - inputSource: The rig's input selection, or `nil` to not persist one. Defaults to `nil`.
/// - numInputChannels: The engine input-channel count, or `nil`. Defaults to `nil`. /// - numInputChannels: The engine input-channel count, or `nil`. Defaults to `nil`.
/// - numOutputChannels: The engine output-channel count, or `nil`. Defaults to `nil`. /// - numOutputChannels: The engine output-channel count, or `nil`. Defaults to `nil`.
/// - routers: The rig's chain routers, or `nil` when there are none. Defaults to `nil`.
public init( public init(
version: Int = presetFormatVersion, version: Int = presetFormatVersion,
boards: [BoardState], boards: [BoardState],
@@ -76,7 +82,8 @@ public struct ShoeGazeState: Codable, Equatable {
tempoEnabled: Bool? = nil, tempoEnabled: Bool? = nil,
inputSource: InputSource? = nil, inputSource: InputSource? = nil,
numInputChannels: Int? = nil, numInputChannels: Int? = nil,
numOutputChannels: Int? = nil numOutputChannels: Int? = nil,
routers: [ChainRouterState]? = nil
) { ) {
self.version = version self.version = version
self.boards = boards self.boards = boards
@@ -86,6 +93,7 @@ public struct ShoeGazeState: Codable, Equatable {
self.inputSource = inputSource self.inputSource = inputSource
self.numInputChannels = numInputChannels self.numInputChannels = numInputChannels
self.numOutputChannels = numOutputChannels self.numOutputChannels = numOutputChannels
self.routers = routers
} }
private enum CodingKeys: String, CodingKey { private enum CodingKeys: String, CodingKey {
@@ -97,6 +105,7 @@ public struct ShoeGazeState: Codable, Equatable {
case inputSource case inputSource
case numInputChannels case numInputChannels
case numOutputChannels case numOutputChannels
case routers
} }
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`. /// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
@@ -129,5 +138,22 @@ public struct ShoeGazeState: Codable, Equatable {
self.inputSource = try container.decodeIfPresent(InputSource.self, forKey: .inputSource) self.inputSource = try container.decodeIfPresent(InputSource.self, forKey: .inputSource)
self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels) self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels)
self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels) self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels)
self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers)
}
/// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo —
/// ignoring live session settings that are not part of the recalled rig: the input source and the
/// engine's channel counts.
///
/// Use this for unsaved-changes detection. Those session fields are deliberately not applied when
/// switching rigs (see ``ShoeGaze/loadRig(from:keepingCurrentInput:)``), so a plain `==` would
/// report a freshly-loaded rig as "changed" merely because the player's current input differs from
/// the input the rig was saved with — producing a spurious "save changes?" prompt.
public func hasSameRigContent(as other: ShoeGazeState) -> Bool {
boards == other.boards
&& routers == other.routers
&& midiMap == other.midiMap
&& bpm == other.bpm
&& tempoEnabled == other.tempoEnabled
} }
} }
+4 -1
View File
@@ -199,7 +199,10 @@ public final class ShoeGaze {
/// All chain routers created via ``makeChainRouter()``. /// All chain routers created via ``makeChainRouter()``.
/// Routers are torn down (in reverse-creation order) by ``teardown()``. /// Routers are torn down (in reverse-creation order) by ``teardown()``.
private var routers: [ChainRouter] = [] ///
/// `internal` (not `private`) so the preset capture/rebuild path in `ShoeGaze+Preset.swift` can
/// snapshot and reconstruct routers.
var routers: [ChainRouter] = []
// MARK: - Init // MARK: - Init
+73 -5
View File
@@ -93,6 +93,76 @@ public struct HelpView: View {
"Reorder rigs into a set list by dragging a row, or via each rig's Move Up / " "Reorder rigs into a set list by dragging a row, or via each rig's Move Up / "
+ "Move Down menu. The order is saved and travels with an exported archive; " + "Move Down menu. The order is saved and travels with an exported archive; "
+ "the top ten map to ⌘⇧1–⌘⇧0.", + "the top ten map to ⌘⇧1–⌘⇧0.",
"Switching rigs keeps your current input — your live guitar stays selected "
+ "instead of snapping back to the test loop.",
]
)
topicSection(
icon: "guitars",
title: "Starter Rigs",
intro: "ShoeGaze ships a library of ready-to-play rigs so you always have somewhere "
+ "to start.",
steps: [
"The Rigs sidebar has a Mine / Starters toggle at the top: Mine is your own "
+ "saved rigs; Starters is the shipped set, grouped by style — Shoegaze "
+ "Walls, Dreampop, Classic, Ambient, and Experimental.",
"Tap a starter to load it. To keep your tweaks, use Save As or Duplicate to make "
+ "your own copy — saving directly over a starter asks first and offers Save "
+ "as New Rig.",
"Restore Starter Rigs (the rig-library ⋯ menu, or the Starters empty state) "
+ "reinstalls the shipped rigs — handy if you deleted some, or to refresh "
+ "them after an update.",
]
)
topicSection(
icon: "amplifier",
title: "Amp Models",
intro: "Amp Model pedals are complete guitar amplifiers — preamp, tone stack, power "
+ "amp, and a built-in speaker cabinet in one pedal. They live in the Amp Model "
+ "row of the palette.",
steps: [
"Pick an amp from the Amp Model category. Each has its own voice: Gain (preamp "
+ "drive), a Bass / Mid / Treble tone stack, and a Cab selector for its "
+ "built-in speaker. Full-surface amps add signature controls — Master, "
+ "Presence, Reverb, Tremolo, a channel switch, and so on.",
"Gain (and a drive channel's Drive) read 1–11 with a musical taper: most of the "
+ "usable grit spreads across the dial, with full saturation at the top.",
"Master vs Level: Master drives the power-amp stage — turning it up saturates the "
+ "amp like a real master volume. Level is a clean output trim applied after "
+ "the amp; it changes loudness, not tone.",
"No digital clipping: every amp ends in an analog-style soft limiter, so a driven "
+ "amp compresses toward its ceiling instead of clipping harshly.",
"Advanced controls (the sliders button at the top-right of the amp card open a "
+ "pop-over): Sag, Bias, and Bias X — power-amp \"feel\" controls kept off the "
+ "main face. Sag models power-supply droop and bloom (compression and touch "
+ "response as you dig in); Bias sets the power tubes' operating point (cold = "
+ "tighter, more bite; hot = warmer, rounder); Bias X balances the push-pull "
+ "pair to shift the harmonic character. All are subtle set-and-leave voicing "
+ "controls that default to neutral.",
]
)
topicSection(
icon: "hifispeaker",
title: "Cabinets & Microphones",
intro: "Every amp has a built-in cabinet, but you can also run a dedicated Cabinet "
+ "pedal for full speaker-and-microphone control.",
steps: [
"Built-in vs standalone: an amp's Cab selector picks its onboard speaker voicing "
+ "— the quick path, one knob. For deeper control, set the amp's Cab to "
+ "\"None (direct)\" and add a Cabinet pedal after it. (On \"None\" the amp "
+ "sounds raw and fizzy by itself — expected; the Cabinet pedal is what "
+ "supplies the speaker.)",
"The Cabinet pedal's Cab selector chooses the speaker voicing, and Mic chooses the "
+ "microphone — Dynamic, Ribbon, Condenser, or No Mic. The mic colour is baked "
+ "into the same speaker response, so it costs nothing extra.",
"Mic placement (the Cabinet's advanced pop-over, again via the top-right sliders "
+ "button): Position moves the mic from on-axis (bright, on the dust cap) "
+ "toward the cone edge (darker, smoother); Proximity runs from a distant, "
+ "flat low end to a close-mic'd bass lift.",
"Dual-mic (same pop-over): set Mic B to a second microphone to blend two mics. "
+ "Mic Blend sets the A/B balance; Mic Offset spaces them apart for the comb "
+ "colour of a real two-mic setup (a set-and-leave spacing control — sweeping "
+ "it live acts like a flanger).",
] ]
) )
topicSection( topicSection(
@@ -176,15 +246,13 @@ public struct HelpView: View {
"Filter design follows the RBJ Audio EQ Cookbook by Robert Bristow-Johnson — the " "Filter design follows the RBJ Audio EQ Cookbook by Robert Bristow-Johnson — the "
+ "standard biquad coefficient formulas, used to synthesize the Cabinet pedal's " + "standard biquad coefficient formulas, used to synthesize the Cabinet pedal's "
+ "built-in speaker impulse responses.", + "built-in speaker impulse responses.",
"The Cabinet pedal's built-in cab voicings are original impulse responses generated in " "The Cabinet pedal's built-in cab and microphone voicings are original impulse "
+ "code — not captures of any third-party hardware or IR pack.", + "responses generated in code — not captures of any third-party speaker, "
+ "microphone, or IR pack.",
"The tube-amp voice pedals' tone stacks " "The tube-amp voice pedals' tone stacks "
+ "follow the Yeh & Smith analysis of the classic passive tone-stack circuit (\"Discretization " + "follow the Yeh & Smith analysis of the classic passive tone-stack circuit (\"Discretization "
+ "of the '59 Fender Bassman Tone Stack\", DAFx-06); their models are original code, not " + "of the '59 Fender Bassman Tone Stack\", DAFx-06); their models are original code, not "
+ "captures of specific hardware.", + "captures of specific hardware.",
"The Neural Amp pedal loads GuitarML Proteus / NeuralPi capture models (the open LSTM "
+ "format from github.com/GuitarML). You supply the model file; none are bundled, and "
+ "those models are licensed by their respective authors.",
] ]
) )
} }
@@ -11,6 +11,7 @@ import SwiftUI
/// to its category lives here, keyed by name like ``PedalPaletteView``'s preferred order. /// to its category lives here, keyed by name like ``PedalPaletteView``'s preferred order.
public enum PedalCategory: String, CaseIterable, Identifiable, Sendable { public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
case amp = "Amp Model" case amp = "Amp Model"
case cabinet = "Cabinet"
case gain = "Gain" case gain = "Gain"
case dynamics = "Dynamics" case dynamics = "Dynamics"
case filter = "EQ & Filter" case filter = "EQ & Filter"
@@ -26,6 +27,7 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
var color: Color { var color: Color {
switch self { switch self {
case .amp: return Color(red: 0.70, green: 0.45, blue: 0.18) // warm valve-glow copper case .amp: return Color(red: 0.70, green: 0.45, blue: 0.18) // warm valve-glow copper
case .cabinet: return Color(red: 0.50, green: 0.36, blue: 0.18) // tweed / cabinet tan
case .gain: return Color(red: 0.82, green: 0.38, blue: 0.12) case .gain: return Color(red: 0.82, green: 0.38, blue: 0.12)
case .dynamics: return Color(red: 0.20, green: 0.50, blue: 0.32) case .dynamics: return Color(red: 0.20, green: 0.50, blue: 0.32)
case .filter: return Color(red: 0.14, green: 0.46, blue: 0.55) case .filter: return Color(red: 0.14, green: 0.46, blue: 0.55)
@@ -44,11 +46,11 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
} }
private static let mapping: [String: PedalCategory] = [ private static let mapping: [String: PedalCategory] = [
"California": .amp, "British": .amp, "British Plexi": .amp, "British JTM": .amp, "British Bluesbreaker": .amp, "British Master": .amp, "British Dual": .amp, "Boutique Lead": .amp, "Boutique OD": .amp, "Chime": .amp, "Chime 15": .amp, "Chime Normal": .amp, "Chime Baby": .amp, "Fullerton Reverb": .amp, "Fullerton Deluxe": .amp, "Fullerton Princeton": .amp, "Fullerton Drive": .amp, "Jazz Clean": .amp, "Chime Top Boost": .amp, "Neural Amp": .amp, "California": .amp, "British": .amp, "British Plexi": .amp, "British JTM": .amp, "British Bluesbreaker": .amp, "British Master": .amp, "British Dual": .amp, "Boutique Lead": .amp, "Boutique OD": .amp, "Cali Hi-Gain": .amp, "Command": .amp, "Citrus": .amp, "Sixties Combo": .amp, "Magna Vibrato": .amp, "Anaheim": .amp, "Modern High-Gain": .amp, "Chime": .amp, "Chime 15": .amp, "Chime Normal": .amp, "Chime Baby": .amp, "Fullerton Reverb": .amp, "Fullerton Deluxe": .amp, "Fullerton Ivy League": .amp, "Fullerton Drive": .amp, "Jazz Clean": .amp, "Chime Top Boost": .amp, "Neural Amp": .amp,
"Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain, "Volume": .gain, "Overdrive": .gain, "Distortion": .gain, "Fuzz": .gain, "Volume": .gain,
"Compressor": .dynamics, "Sustainer": .dynamics, "Limiter": .dynamics, "Noise Gate": .dynamics, "Compressor": .dynamics, "Sustainer": .dynamics, "Limiter": .dynamics, "Noise Gate": .dynamics,
"Graphic EQ": .filter, "Auto-Wah": .filter, "Wah": .filter, "Mutant": .filter, "Graphic EQ": .filter, "Auto-Wah": .filter, "Wah": .filter, "Mutant": .filter,
"Cabinet": .filter, "Cabinet": .cabinet,
"Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation, "Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation,
"Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation, "Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation,
"Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch, "Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch,
@@ -54,10 +54,10 @@ public struct PedalPaletteView: View {
/// Preferred display order for the built-in pedals. Any registered pedal not listed here is /// Preferred display order for the built-in pedals. Any registered pedal not listed here is
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal. /// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
private static let preferredOrder: [String] = [ private static let preferredOrder: [String] = [
"California", "British", "British Plexi", "British JTM", "British Bluesbreaker", "British Master", "British Dual", "Boutique Lead", "Boutique OD", "Chime", "Chime 15", "Chime Normal", "Chime Baby", "Fullerton Reverb", "Fullerton Deluxe", "Fullerton Princeton", "Fullerton Drive", "Jazz Clean", "Chime Top Boost", "Neural Amp", "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", "California", "British", "British Plexi", "British JTM", "British Bluesbreaker", "British Master", "British Dual", "Boutique Lead", "Boutique OD", "Cali Hi-Gain", "Command", "Citrus", "Sixties Combo", "Magna Vibrato", "Anaheim", "Modern High-Gain", "Chime", "Chime 15", "Chime Normal", "Chime Baby", "Fullerton Reverb", "Fullerton Deluxe", "Fullerton Ivy League", "Fullerton Drive", "Jazz Clean", "Chime Top Boost", "Cabinet", "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", "Sustain Fuzz",
"Volume", "Volume",
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary", "Graphic EQ", "Tremolo", "Phaser", "Vibe", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
"Auto-Wah", "Wah", "Mutant", "Cabinet", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator", "Auto-Wah", "Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator",
"Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer", "Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer",
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb", "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
"Shimmer Reverb", "Plate Reverb", "Room Reverb", "Spring Reverb", "Shimmer Reverb", "Plate Reverb", "Room Reverb", "Spring Reverb",
@@ -159,6 +159,24 @@ public struct PedalPaletteView: View {
} }
} }
/// The `.amp` bucket on its own, or `nil` when no amp models are visible. Split out so the
/// horizontal picker can drop the (large) amp list into the second row (with Routing and the
/// Cabinet) instead of letting it stretch the head of the effects row.
private var ampGroup: (category: PedalCategory, names: [String])? {
groupedVisiblePedals.first { $0.category == .amp }
}
/// The `.cabinet` bucket on its own, or `nil` when no cabinet is visible. Sits on the second row
/// between Routing and the amp models (rig-structure controls grouped together).
private var cabinetGroup: (category: PedalCategory, names: [String])? {
groupedVisiblePedals.first { $0.category == .cabinet }
}
/// Visible pedal groups excluding the amp models and the cabinet — the actual effects row (row 1).
private var effectGroups: [(category: PedalCategory, names: [String])] {
groupedVisiblePedals.filter { $0.category != .amp && $0.category != .cabinet }
}
// MARK: - Body // MARK: - Body
public var body: some View { public var body: some View {
@@ -171,6 +189,12 @@ public struct PedalPaletteView: View {
/// Full-width column for a left sidebar. /// Full-width column for a left sidebar.
private var verticalBody: some View { private var verticalBody: some View {
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) { VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
sectionTitle("ROUTING")
ForEach(PedalPaletteView.routingOptions, id: \.title) { option in
routingCard(title: option.title, caption: option.caption, action: option.action)
}
}
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
HStack { HStack {
sectionTitle("PEDALS") sectionTitle("PEDALS")
@@ -181,18 +205,12 @@ public struct PedalPaletteView: View {
pedalRow(name) pedalRow(name)
} }
} }
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
sectionTitle("ROUTING")
ForEach(PedalPaletteView.routingOptions, id: \.title) { option in
routingCard(title: option.title, caption: option.caption, action: option.action)
}
}
} }
} }
/// Horizontal scroller: a PEDALS row (leading filter + colour-coded cards) with the ROUTING /// Horizontal scroller: a PEDALS row (leading filter + colour-coded effect cards) with a second
/// row stacked beneath it. /// row that carries the amp models alongside the ROUTING cards. Amps live with routing rather
/// than at the head of the effects row so the effects row stays short.
private var horizontalBody: some View { private var horizontalBody: some View {
VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) { VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) {
HStack(alignment: .top, spacing: PedalPaletteView.sectionSpacing) { HStack(alignment: .top, spacing: PedalPaletteView.sectionSpacing) {
@@ -200,7 +218,7 @@ public struct PedalPaletteView: View {
sectionTitle("PEDALS") sectionTitle("PEDALS")
if showsFilterMenu { filterMenu } if showsFilterMenu { filterMenu }
} }
ForEach(groupedVisiblePedals, id: \.category) { group in ForEach(effectGroups, id: \.category) { group in
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
categoryLabel(group.category) categoryLabel(group.category)
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) { HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
@@ -211,10 +229,34 @@ public struct PedalPaletteView: View {
} }
} }
} }
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) { HStack(alignment: .top, spacing: PedalPaletteView.sectionSpacing) {
sectionTitle("ROUTING") VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
ForEach(PedalPaletteView.routingOptions, id: \.title) { option in sectionTitle("ROUTING")
routingCard(title: option.title, caption: option.caption, action: option.action) HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
ForEach(PedalPaletteView.routingOptions, id: \.title) { option in
routingCard(title: option.title, caption: option.caption, action: option.action)
}
}
}
if let cabinet: (category: PedalCategory, names: [String]) = cabinetGroup {
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
categoryLabel(cabinet.category)
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
ForEach(cabinet.names, id: \.self) { name in
pedalRow(name)
}
}
}
}
if let amps: (category: PedalCategory, names: [String]) = ampGroup {
VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) {
categoryLabel(amps.category)
HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) {
ForEach(amps.names, id: \.self) { name in
pedalRow(name)
}
}
}
} }
} }
} }
+108 -17
View File
@@ -26,16 +26,23 @@ private func enclosureColor(for displayName: String) -> Color {
case "British Dual": return Color(red: 0.24, green: 0.13, blue: 0.11) // modern high-gain case "British Dual": return Color(red: 0.24, green: 0.13, blue: 0.11) // modern high-gain
case "Boutique Lead": return Color(red: 0.28, green: 0.12, blue: 0.16) // boutique oxblood case "Boutique Lead": return Color(red: 0.28, green: 0.12, blue: 0.16) // boutique oxblood
case "Boutique OD": return Color(red: 0.30, green: 0.20, blue: 0.10) // D-style amber case "Boutique OD": return Color(red: 0.30, green: 0.20, blue: 0.10) // D-style amber
case "Cali Hi-Gain": return Color(red: 0.16, green: 0.16, blue: 0.18) // Mark-series black
case "Command": return Color(red: 0.20, green: 0.22, blue: 0.16) // hi-fi olive
case "Citrus": return Color(red: 0.85, green: 0.50, blue: 0.10) // orange tolex
case "Sixties Combo": return Color(red: 0.42, green: 0.30, blue: 0.16) // tweed brown
case "Magna Vibrato": return Color(red: 0.34, green: 0.26, blue: 0.44) // vibrato violet
case "Anaheim": return Color(red: 0.24, green: 0.30, blue: 0.32) // hybrid slate
case "Modern High-Gain": return Color(red: 0.12, green: 0.12, blue: 0.14) // recto black
case "Chime": return Color(red: 0.16, green: 0.24, blue: 0.22) // vintage green case "Chime": return Color(red: 0.16, green: 0.24, blue: 0.22) // vintage green
case "Chime 15": return Color(red: 0.18, green: 0.28, blue: 0.22) // brighter vox green case "Chime 15": return Color(red: 0.18, green: 0.28, blue: 0.22) // brighter chime green
case "Chime Normal": return Color(red: 0.20, green: 0.26, blue: 0.20) // warm vox green case "Chime Normal": return Color(red: 0.20, green: 0.26, blue: 0.20) // warm chime green
case "Chime Baby": return Color(red: 0.22, green: 0.30, blue: 0.24) // pale vox green case "Chime Baby": return Color(red: 0.22, green: 0.30, blue: 0.24) // pale chime green
case "Fullerton Reverb": return Color(red: 0.15, green: 0.22, blue: 0.30) // blackface panel case "Fullerton Reverb": return Color(red: 0.15, green: 0.22, blue: 0.30) // blackface panel
case "Fullerton Deluxe": return Color(red: 0.17, green: 0.20, blue: 0.26) // blackface, warmer case "Fullerton Deluxe": return Color(red: 0.17, green: 0.20, blue: 0.26) // blackface, warmer
case "Fullerton Princeton": return Color(red: 0.19, green: 0.19, blue: 0.23) // small blackface case "Fullerton Ivy League": return Color(red: 0.19, green: 0.19, blue: 0.23) // small blackface
case "Fullerton Drive": return Color(red: 0.22, green: 0.18, blue: 0.24) // two-channel combo case "Fullerton Drive": return Color(red: 0.22, green: 0.18, blue: 0.24) // two-channel combo
case "Jazz Clean": return Color(red: 0.14, green: 0.30, blue: 0.34) // solid-state silver-teal case "Jazz Clean": return Color(red: 0.14, green: 0.30, blue: 0.34) // solid-state silver-teal
case "Chime Top Boost": return Color(red: 0.20, green: 0.32, blue: 0.20) // vox-green tolex case "Chime Top Boost": return Color(red: 0.20, green: 0.32, blue: 0.20) // chime-green tolex
case "Neural Amp": return Color(red: 0.22, green: 0.16, blue: 0.30) // deep neural violet case "Neural Amp": return Color(red: 0.22, green: 0.16, blue: 0.30) // deep neural violet
case "Overdrive": return Color(red: 0.85, green: 0.42, blue: 0.08) // warm orange case "Overdrive": return Color(red: 0.85, green: 0.42, blue: 0.08) // warm orange
case "Distortion": return Color(red: 0.80, green: 0.26, blue: 0.12) // hot rust case "Distortion": return Color(red: 0.80, green: 0.26, blue: 0.12) // hot rust
@@ -47,8 +54,10 @@ private func enclosureColor(for displayName: String) -> Color {
case "Spring Reverb": return Color(red: 0.20, green: 0.46, blue: 0.64) // steel cyan case "Spring Reverb": return Color(red: 0.20, green: 0.46, blue: 0.64) // steel cyan
case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green
case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson
case "Sustain Fuzz": return Color(red: 0.72, green: 0.24, blue: 0.10) // rust / burnt orange
case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue
case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet
case "Vibe": return Color(red: 0.28, green: 0.20, blue: 0.62) // deep indigo
case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green
case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum
case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold
@@ -415,9 +424,12 @@ public struct PedalView: View {
// MARK: - Layout constants // MARK: - Layout constants
/// Wide enough for three ~55 pt knobs (dial + label + value) plus padding in a /// Base card width — used by the looper's fixed multi-unit layout. Other pedals size to content
/// single row, so the effect controls never overlap. /// via ``enclosureColumnWidth`` (see `enclosureWidth(for:)`).
private static let enclosureWidth: CGFloat = 220 private static let enclosureWidth: CGFloat = 220
/// Per-column width for the content-sized enclosure — one knob/selector/switch slot (a ~50 pt
/// dial plus its caption). Card width = `2·padding + columns·this + (columns−1)·knobSpacing`.
private static let enclosureColumnWidth: CGFloat = 68
private static let enclosureCornerRadius: CGFloat = 12 private static let enclosureCornerRadius: CGFloat = 12
private static let enclosurePadding: CGFloat = 14 private static let enclosurePadding: CGFloat = 14
private static let screwInset: CGFloat = 6 private static let screwInset: CGFloat = 6
@@ -463,6 +475,14 @@ public struct PedalView: View {
/// Insets placing the ⓘ info button just under the top-left corner screw. /// Insets placing the ⓘ info button just under the top-left corner screw.
private static let infoButtonLeading: CGFloat = 5 private static let infoButtonLeading: CGFloat = 5
private static let infoButtonTop: CGFloat = 20 private static let infoButtonTop: CGFloat = 20
/// Insets placing the advanced (gear) button just under the top-right corner screw, mirroring
/// the info button.
private static let advancedButtonTrailing: CGFloat = 5
private static let advancedButtonTop: CGFloat = 20
/// Layout of the advanced-controls pop-over: knobs per row and the inter-knob gap.
private static let advancedPopoverColumns: Int = 2
private static let advancedPopoverSpacing: CGFloat = 14
private static let advancedPopoverPadding: CGFloat = 16
private static let outerBorderLineWidth: CGFloat = 1.5 private static let outerBorderLineWidth: CGFloat = 1.5
private static let innerHighlightLineWidth: CGFloat = 1 private static let innerHighlightLineWidth: CGFloat = 1
private static let innerHighlightPadding: CGFloat = 1 private static let innerHighlightPadding: CGFloat = 1
@@ -475,6 +495,9 @@ public struct PedalView: View {
/// Presentation flag for the pedal info panel (description + control ranges). /// Presentation flag for the pedal info panel (description + control ranges).
@State private var showInfo: Bool = false @State private var showInfo: Bool = false
/// Presentation flag for the advanced-controls pop-over (amp Sag / Bias).
@State private var showAdvanced: Bool = false
/// Presentation flag for the Neural Amp model-file importer. /// Presentation flag for the Neural Amp model-file importer.
@State private var showModelImporter: Bool = false @State private var showModelImporter: Bool = false
@@ -552,6 +575,15 @@ public struct PedalView: View {
.padding(.leading, PedalView.infoButtonLeading) .padding(.leading, PedalView.infoButtonLeading)
.padding(.top, PedalView.infoButtonTop) .padding(.top, PedalView.infoButtonTop)
} }
// Advanced (gear) button, tucked under the top-right corner screw — only for pedals that
// publish advanced knobs (e.g. an amp's Sag / Bias).
.overlay(alignment: .topTrailing) {
if !pedal.advancedKnobs.isEmpty {
advancedButton
.padding(.trailing, PedalView.advancedButtonTrailing)
.padding(.top, PedalView.advancedButtonTop)
}
}
.shadow( .shadow(
color: Color.black.opacity(PedalView.shadowOpacity), color: Color.black.opacity(PedalView.shadowOpacity),
radius: PedalView.shadowRadius, radius: PedalView.shadowRadius,
@@ -724,6 +756,46 @@ public struct PedalView: View {
.help("About this pedal") .help("About this pedal")
} }
/// Advanced-controls (gear) button tucked under the top-right corner screw. Presents
/// ``advancedPanel`` — the pedal's ``Pedal/advancedKnobs`` — in a popover. Only drawn when the
/// pedal publishes advanced knobs (the caller gates on `advancedKnobs.isEmpty`).
private var advancedButton: some View {
Button {
showAdvanced = true
} label: {
Image(systemName: "slider.horizontal.3")
.font(.system(size: PedalView.fontSizeNamePlate))
.foregroundStyle(Color.white.opacity(PedalView.infoButtonOpacity))
}
.buttonStyle(.plain)
.help("Advanced controls")
.popover(isPresented: $showAdvanced) {
advancedPanel
.presentationCompactAdaptation(.popover)
}
}
/// Grid of the pedal's ``Pedal/advancedKnobs`` shown in the advanced popover, laid out in rows of
/// ``advancedPopoverColumns``. Plain `ParameterKnob`s — these are live, non-topology controls.
private var advancedPanel: some View {
let knobs: [PedalKnob] = pedal.advancedKnobs
let columns: Int = PedalView.advancedPopoverColumns
let rows: [[PedalKnob]] = stride(from: 0, to: knobs.count, by: columns).map { startIndex in
Array(knobs[startIndex ..< min(startIndex + columns, knobs.count)])
}
return VStack(spacing: PedalView.advancedPopoverSpacing) {
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
HStack(alignment: .top, spacing: PedalView.advancedPopoverSpacing) {
ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in
ParameterKnob(knobPair.element.label, node: knobPair.element.node, range: knobPair.element.range)
.foregroundStyle(Color.white)
}
}
}
}
.padding(PedalView.advancedPopoverPadding)
}
/// Grid of the effect knobs, in rows of up to `knobColumnCount`. /// Grid of the effect knobs, in rows of up to `knobColumnCount`.
/// ///
/// The trailing `Mix` and `Level` knobs (the last two entries of `pedal.knobs`) are /// The trailing `Mix` and `Level` knobs (the last two entries of `pedal.knobs`) are
@@ -807,10 +879,13 @@ public struct PedalView: View {
if !selectors.isEmpty { if !selectors.isEmpty {
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) { HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
Spacer(minLength: 0) Spacer(minLength: 0)
ForEach(Array(selectors.enumerated()), id: \.offset) { pair in // Keyed by the (unique-per-pedal) selector label, not the array offset, so each
// selector keeps a stable SwiftUI identity across board rebuilds — a rebuildsOnChange
// selector must not inherit a sibling's drag @State.
ForEach(selectors, id: \.label) { selector in
PedalSelectorKnobView( PedalSelectorKnobView(
pair.element, selector,
onCommit: pair.element.rebuildsOnChange onCommit: selector.rebuildsOnChange
? { [pedal, pedalRebuildAction] in pedalRebuildAction(pedal) } ? { [pedal, pedalRebuildAction] in pedalRebuildAction(pedal) }
: nil : nil
) )
@@ -888,19 +963,35 @@ public struct PedalView: View {
} }
} }
/// Enclosure width — the base stompbox width scaled by the pedal's `widthUnits` /// Enclosure width, sized to the pedal's **content** rather than a flat `widthUnits × base`
/// (a control-dense pedal such as the looper asks for a double-width card), widened /// multiple (which left control-sparse multi-unit cards — amps, the Cabinet — mostly empty).
/// further to fit a wide vertical-fader bank (e.g. a multi-band graphic EQ) so its ///
/// faders are never clipped. /// The card is `columns` wide, where `columns` is the pedal's base knob-grid width from
/// `widthUnits` (`1` → `knobColumnCount`, `≥ 2` → `wideKnobColumnCount`) — so a `widthUnits: 2`
/// pedal is always a four-wide card even if it carries fewer knobs (this is how the Cabinet
/// matches the amps so its selector captions stay readable). A pedal whose selector or switch row
/// is wider than that pushes wider still. It is widened further to fit a vertical-fader bank
/// (e.g. a multi-band graphic EQ) so its faders are never clipped.
///
/// The looper is the exception: its bespoke three-column layout (timeline · knobs · transport)
/// genuinely needs the full multi-unit width, so it keeps the flat multiple.
private func enclosureWidth(for sliders: [PedalSlider]) -> CGFloat { private func enclosureWidth(for sliders: [PedalSlider]) -> CGFloat {
let unitWidth: CGFloat = PedalView.enclosureWidth * CGFloat(max(1, pedal.widthUnits)) if pedal is LooperPedal {
return PedalView.enclosureWidth * CGFloat(max(1, pedal.widthUnits))
}
let gridColumns: Int = pedal.widthUnits >= 2 ? PedalView.wideKnobColumnCount : PedalView.knobColumnCount
let columns: Int = max(gridColumns, inlineSelectors.count, pedal.effectSwitches.count)
let contentWidth: CGFloat = 2 * PedalView.enclosurePadding
+ CGFloat(columns) * PedalView.enclosureColumnWidth
+ CGFloat(max(0, columns - 1)) * PedalView.knobSpacing
let sliderCount: Int = sliders.count let sliderCount: Int = sliders.count
guard sliderCount > 0 else { return unitWidth } guard sliderCount > 0 else { return contentWidth }
let bankContentWidth: CGFloat = let bankContentWidth: CGFloat =
CGFloat(sliderCount) * PedalView.sliderBankItemWidth CGFloat(sliderCount) * PedalView.sliderBankItemWidth
+ CGFloat(max(0, sliderCount - 1)) * PedalView.sliderBankSpacing + CGFloat(max(0, sliderCount - 1)) * PedalView.sliderBankSpacing
let needed: CGFloat = bankContentWidth + 2 * PedalView.enclosurePadding let needed: CGFloat = bankContentWidth + 2 * PedalView.enclosurePadding
return max(unitWidth, needed) return max(contentWidth, needed)
} }
/// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob, /// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob,
@@ -10,44 +10,87 @@ import LyrebirdShoeGaze
/// Setup of the rig library for an app shell, split so nothing blocks the launch path. /// Setup of the rig library for an app shell, split so nothing blocks the launch path.
/// ///
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous /// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work — /// initializer and hand to the UI). ``start(_:seedFrom:)`` then does the blocking work — resolving
/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the /// the iCloud-or-local location and the initial load — off the main thread, then performs a one-time
/// library from the current working rig **only after** the real (possibly iCloud) contents are /// catch-up seed of any missing shipped starter rigs.
/// known, so a first launch can't create a duplicate "Default" rig on every synced device.
@MainActor @MainActor
public enum RigLibraryBootstrap { public enum RigLibraryBootstrap {
/// `UserDefaults` key holding the highest ``FactoryRigLibrary/seedVersion`` this device has
/// already seeded. Per-device (not synced): the seed is idempotent by stable rig id, so a device
/// that receives the rigs via iCloud sync simply finds them already present and seeds nothing.
private static let seedVersionKey: String = "net.realizedsound.shoegaze.factorySeedVersion"
/// Creates an auto-resolving store. Construct this synchronously at launch; call /// Creates an auto-resolving store. Construct this synchronously at launch; call
/// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`). /// ``start(_:seedFrom:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
public static func makeStore() -> RigLibraryStore { public static func makeStore() -> RigLibraryStore {
RigLibraryStore() RigLibraryStore()
} }
/// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still /// Resolves + loads `store` off the main thread, then performs a one-time catch-up install of the
/// empty after loading (first run). Idempotent enough to call once at launch. /// shipped starter rigs. Idempotent — safe to call once at every launch.
///
/// Installing (re)saves every factory rig by its stable id, so it **adds** missing starters and
/// **refreshes** existing ones to their current shipped definition (a corrected rig replaces the
/// stale copy in place, keeping its library position). User rigs are never touched — factory rigs
/// have their own fixed ids. It runs at most once per ``FactoryRigLibrary/seedVersion``: a first
/// launch installs every starter; a launch after a version bump refreshes/adds; and within a
/// version a starter the user deletes stays deleted (the marker has already advanced). This
/// deliberately replaces the old "only seed an empty library" rule so existing users get starters.
/// ///
/// - Parameters: /// - Parameters:
/// - store: The store from ``makeStore()``. /// - store: The store from ``makeStore()``.
/// - shoeGaze: The session whose current rig seeds the library when it is first empty. /// - shoeGaze: The working session (currently unused by seeding; kept for call-site stability
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`. /// and future working-rig seeding needs).
public static func start( public static func start(
_ store: RigLibraryStore, _ store: RigLibraryStore,
seedFrom shoeGaze: ShoeGaze, seedFrom shoeGaze: ShoeGaze
seedName: String = "Default"
) async { ) async {
await store.start() await store.start()
// Seed only after the (possibly iCloud) library has loaded: an empty library here means a let defaults: UserDefaults = .standard
// genuine first run, not a not-yet-synced one. let seededVersion: Int = defaults.integer(forKey: seedVersionKey) // 0 when never seeded
guard store.entries.isEmpty, !shoeGaze.boards.isEmpty else { return } guard seededVersion < FactoryRigLibrary.seedVersion else { return }
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
// Install the starters. Only advance the marker if it succeeded, so a transient failure
// (which should not happen for this deterministic data) is retried on the next launch.
if installFactoryRigs(into: store) != nil {
defaults.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey)
}
}
/// (Re)installs every shipped starter rig to its current definition. Safe to call anytime.
///
/// Drives the user-facing "Restore Starter Rigs" action: it re-adds starters the user deleted,
/// adds newly-shipped ones, and refreshes any stale copies — all without disturbing the user's own
/// rigs — and advances the seed marker so automatic catch-up won't fight the manual restore.
///
/// - Parameter store: The library to install into.
/// - Returns: The number of starter rigs written (0 on a build/encode failure).
@discardableResult
public static func restoreStarterRigs(into store: RigLibraryStore) -> Int {
// Advance the seed marker only on success, mirroring `start()` — a failed restore must not
// suppress the automatic catch-up seed on the next launch.
guard let written: Int = installFactoryRigs(into: store) else { return 0 }
UserDefaults.standard.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey)
return written
}
/// Builds every starter rig and saves it, overwriting any existing entry with the same stable id
/// (`store.save` upserts by id, keeping an overwritten entry's library position).
///
/// - Parameter store: The library to install into.
/// - Returns: The number of rigs written, or `nil` if building/encoding failed.
private static func installFactoryRigs(into store: RigLibraryStore) -> Int? {
do { do {
try store.save(entry) let entries: [RigEntry] = try FactoryRigLibrary.makeEntries()
// The seeded entry was captured from the working graph, so it is the session's source for entry: RigEntry in entries {
// rig — record it so the sidebar highlights it and the autosave envelope carries it. try store.save(entry)
shoeGaze.currentRigID = entry.id }
return entries.count
} catch { } catch {
print("[RigLibraryBootstrap] seeding library failed: \(error)") print("[RigLibraryBootstrap] installing factory rigs failed: \(error)")
return nil
} }
} }
} }
@@ -26,6 +26,7 @@ struct RigLibrarySidebarView: View {
private static let subtitleOpacity: Double = 0.5 private static let subtitleOpacity: Double = 0.5
private static let headerOpacity: Double = 0.65 private static let headerOpacity: Double = 0.65
private static let emptyOpacity: Double = 0.4 private static let emptyOpacity: Double = 0.4
private static let tabPickerWidth: CGFloat = 168
// MARK: - Inputs // MARK: - Inputs
@@ -45,6 +46,9 @@ struct RigLibrarySidebarView: View {
let onImportArchive: () -> Void let onImportArchive: () -> Void
let onExportArchive: () -> Void let onExportArchive: () -> Void
/// Invoked to (re-)install any shipped starter rigs missing from the library. Defaults to a no-op.
var onRestoreStarters: () -> Void = {}
/// Invoked when the local-only (iCloud-unavailable) status icon is tapped, so the host can /// Invoked when the local-only (iCloud-unavailable) status icon is tapped, so the host can
/// explain how to re-enable iCloud sync. Defaults to a no-op. /// explain how to re-enable iCloud sync. Defaults to a no-op.
var onShowCloudStatus: () -> Void = {} var onShowCloudStatus: () -> Void = {}
@@ -52,6 +56,16 @@ struct RigLibrarySidebarView: View {
private static let timestampFormat: Date.FormatStyle = private static let timestampFormat: Date.FormatStyle =
Date.FormatStyle(date: .abbreviated, time: .shortened) Date.FormatStyle(date: .abbreviated, time: .shortened)
/// Which group of rigs the list is currently showing.
private enum RigTab: String, CaseIterable, Identifiable {
case mine = "Mine"
case starters = "Starters"
var id: String { rawValue }
}
/// The selected list tab. Defaults to the user's own rigs.
@State private var tab: RigTab = .mine
// MARK: - Body // MARK: - Body
var body: some View { var body: some View {
@@ -63,6 +77,18 @@ struct RigLibrarySidebarView: View {
actionBar actionBar
} }
.frame(width: RigLibrarySidebarView.width) .frame(width: RigLibrarySidebarView.width)
// Open on the tab that contains the currently-loaded rig, so a session restored on a starter
// rig (e.g. Garcia) shows Starters, and one on a user rig shows Mine.
.onAppear { tab = tabForCurrentRig() }
.onChange(of: currentRigID) { tab = tabForCurrentRig() }
}
/// The tab whose group contains the currently-loaded rig: Starters for a factory rig, else Mine.
private func tabForCurrentRig() -> RigTab {
if let id: UUID = currentRigID, FactoryRigLibrary.isFactory(id) {
return .starters
}
return .mine
} }
// MARK: - Header // MARK: - Header
@@ -99,34 +125,105 @@ struct RigLibrarySidebarView: View {
// MARK: - List // MARK: - List
@ViewBuilder
private var rigList: some View { private var rigList: some View {
ScrollView(.vertical, showsIndicators: true) { if !store.isLoaded {
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) { HStack(spacing: 6) {
if !store.isLoaded { ProgressView().controlSize(.small)
HStack(spacing: 6) { Text("Loading…")
ProgressView().controlSize(.small) .font(.caption)
Text("Loading…") .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
.font(.caption) }
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) .padding(.vertical, RigLibrarySidebarView.rowPadding)
.frame(maxHeight: .infinity, alignment: .top)
} else {
VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
tabPicker
ScrollView(.vertical, showsIndicators: true) {
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
switch tab {
case .mine: mineList
case .starters: startersList
}
} }
.padding(.vertical, RigLibrarySidebarView.rowPadding)
} else if store.entries.isEmpty {
Text("No saved rigs yet.\nTap New or Save to add one.")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
.padding(.vertical, RigLibrarySidebarView.rowPadding)
} }
ForEach(store.entries) { entry in .frame(maxHeight: .infinity)
rigRow(entry) }
}
}
/// Segmented Mine / Starters switch, centered at the top of the list.
private var tabPicker: some View {
Picker("", selection: $tab) {
ForEach(RigTab.allCases) { option in
Text(option.rawValue).tag(option)
}
}
.pickerStyle(.segmented)
.labelsHidden()
// Constrain the control's own width, then center it in the full column width.
.frame(maxWidth: RigLibrarySidebarView.tabPickerWidth)
.frame(maxWidth: .infinity, alignment: .center)
}
/// The user's own rigs — a flat, reorderable list.
@ViewBuilder
private var mineList: some View {
let userRigs: [RigEntry] = userEntries
if userRigs.isEmpty {
Text("No saved rigs yet.\nTap New or Save to add one.")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
.padding(.vertical, RigLibrarySidebarView.rowPadding)
} else {
ForEach(userRigs) { entry in
rigRow(entry, reorderable: true)
}
}
}
/// The shipped starter rigs, grouped by category (fixed catalog order, not reorderable).
@ViewBuilder
private var startersList: some View {
let sections: [(category: FactoryRigCategory, entries: [RigEntry])] = factorySections
if sections.isEmpty {
VStack(alignment: .leading, spacing: 6) {
Text("No starter rigs installed.")
.font(.caption)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
Button("Restore Starter Rigs") { onRestoreStarters() }
.buttonStyle(.bordered)
.tint(.orange)
.controlSize(.small)
}
.padding(.vertical, RigLibrarySidebarView.rowPadding)
} else {
ForEach(sections, id: \.category) { section in
sectionHeader(section.category.displayName)
ForEach(section.entries) { entry in
rigRow(entry, reorderable: false)
} }
} }
} }
.frame(maxHeight: .infinity)
} }
private func rigRow(_ entry: RigEntry) -> some View { /// A small uppercase section header for a group of rigs.
private func sectionHeader(_ title: String) -> some View {
Text(title.uppercased())
.font(.caption2)
.fontWeight(.semibold)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
.padding(.top, RigLibrarySidebarView.rowPadding)
.padding(.horizontal, 2)
.frame(maxWidth: .infinity, alignment: .leading)
}
/// One rig row. `reorderable` rows (the user's own rigs) accept drag-to-reorder and expose
/// Move Up / Down; starter rigs are fixed and show a "Starter rig" subtitle instead of a date.
@ViewBuilder
private func rigRow(_ entry: RigEntry, reorderable: Bool) -> some View {
let isSelected: Bool = entry.id == currentRigID let isSelected: Bool = entry.id == currentRigID
return Button { let button = Button {
onSelect(entry) onSelect(entry)
} label: { } label: {
VStack(alignment: .leading, spacing: 2) { VStack(alignment: .leading, spacing: 2) {
@@ -134,7 +231,9 @@ struct RigLibrarySidebarView: View {
.font(.subheadline) .font(.subheadline)
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
.lineLimit(1) .lineLimit(1)
Text(entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat)) Text(reorderable
? entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat)
: "Starter rig")
.font(.caption2) .font(.caption2)
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity)) .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity))
.lineLimit(1) .lineLimit(1)
@@ -149,45 +248,81 @@ struct RigLibrarySidebarView: View {
.contentShape(Rectangle()) .contentShape(Rectangle())
} }
.buttonStyle(.plain) .buttonStyle(.plain)
// Drag the row onto another to reorder; dropping inserts it just before the target. Works
// on macOS (mouse drag) and iPad (long-press drag); taps still select.
.draggable(entry.id.uuidString)
.dropDestination(for: String.self) { droppedIDs, _ in
guard let first: String = droppedIDs.first else { return false }
moveDragged(first, onto: entry)
return true
}
.contextMenu { .contextMenu {
Button("Move Up") { store.moveUp(entry) } rowContextMenu(entry, reorderable: reorderable)
.disabled(isFirst(entry))
Button("Move Down") { store.moveDown(entry) }
.disabled(isLast(entry))
Divider()
Button("Rename…") { onRename(entry) }
Button("Duplicate…") { onDuplicate(entry) }
// Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the
// unreachable failure path the Share item is simply omitted.
if let shareItem: RigShareItem = try? RigShareItem(rig: entry) {
ShareLink(
item: shareItem,
preview: SharePreview(entry.name)
) {
Label("Share…", systemImage: "square.and.arrow.up")
}
}
Divider()
Button("Delete", role: .destructive) { onDelete(entry) }
} }
if reorderable {
// Drag the row onto another to reorder; dropping inserts it just before the target. Works
// on macOS (mouse drag) and iPad (long-press drag); taps still select.
button
.draggable(entry.id.uuidString)
.dropDestination(for: String.self) { droppedIDs, _ in
guard let first: String = droppedIDs.first else { return false }
moveDragged(first, onto: entry)
return true
}
} else {
button
}
}
/// The context menu for a rig row. Move Up / Down appear only for reorderable (user) rigs.
@ViewBuilder
private func rowContextMenu(_ entry: RigEntry, reorderable: Bool) -> some View {
if reorderable {
Button("Move Up") { store.moveUp(entry) }
.disabled(isFirstUser(entry))
Button("Move Down") { store.moveDown(entry) }
.disabled(isLastUser(entry))
Divider()
}
Button("Rename…") { onRename(entry) }
Button("Duplicate…") { onDuplicate(entry) }
// Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the
// unreachable failure path the Share item is simply omitted.
if let shareItem: RigShareItem = try? RigShareItem(rig: entry) {
ShareLink(
item: shareItem,
preview: SharePreview(entry.name)
) {
Label("Share…", systemImage: "square.and.arrow.up")
}
}
Divider()
Button("Delete", role: .destructive) { onDelete(entry) }
}
// MARK: - Grouping
/// The starter-rig sections: each non-empty ``FactoryRigCategory`` present in the library, in
/// catalog order, paired with its entries (also in catalog order).
private var factorySections: [(category: FactoryRigCategory, entries: [RigEntry])] {
let byID: [UUID: RigEntry] = Dictionary(
store.entries.map { ($0.id, $0) },
uniquingKeysWith: { first, _ in first }
)
return FactoryRigCategory.allCases.compactMap { category in
let entries: [RigEntry] = FactoryRigLibrary.rigs(in: category).compactMap { byID[$0.id] }
return entries.isEmpty ? nil : (category, entries)
}
}
/// The user's own (non-factory) rigs, in library order.
private var userEntries: [RigEntry] {
store.entries.filter { !FactoryRigLibrary.isFactory($0.id) }
} }
// MARK: - Reorder helpers // MARK: - Reorder helpers
private func isFirst(_ entry: RigEntry) -> Bool { /// Whether `entry` is the first among the user's own rigs (so Move Up is disabled for it).
store.entries.first?.id == entry.id private func isFirstUser(_ entry: RigEntry) -> Bool {
userEntries.first?.id == entry.id
} }
private func isLast(_ entry: RigEntry) -> Bool { /// Whether `entry` is the last among the user's own rigs (so Move Down is disabled for it).
store.entries.last?.id == entry.id private func isLastUser(_ entry: RigEntry) -> Bool {
userEntries.last?.id == entry.id
} }
/// Moves the dragged entry (by id string) to sit just before `target` in the set list. /// Moves the dragged entry (by id string) to sit just before `target` in the set list.
@@ -217,6 +352,8 @@ struct RigLibrarySidebarView: View {
Button("Import Archive…") { onImportArchive() } Button("Import Archive…") { onImportArchive() }
Button("Export Archive…") { onExportArchive() } Button("Export Archive…") { onExportArchive() }
Divider() Divider()
Button("Restore Starter Rigs") { onRestoreStarters() }
Divider()
Button("Erase All Rigs…", role: .destructive) { onEraseAll() } Button("Erase All Rigs…", role: .destructive) { onEraseAll() }
} label: { } label: {
Image(systemName: "ellipsis.circle") Image(systemName: "ellipsis.circle")
@@ -149,6 +149,18 @@ public struct ShoeGazeBuilderView: View {
let message: String let message: String
} }
/// A pending confirmation to overwrite a built-in factory rig. Non-`nil` shows the dialog;
/// carries the target entry and the follow-up to run once the user resolves the choice (so the
/// "Save & Clear" flow still clears after a confirmed overwrite).
private struct FactoryOverwriteRequest: Identifiable {
let id: UUID = UUID()
let entry: RigEntry
let completion: () -> Void
}
/// Drives the "overwrite a starter rig?" confirmation dialog. `nil` = not shown.
@State private var factoryOverwrite: FactoryOverwriteRequest?
/// Archive export state. Cross-platform: backs the sidebar's Export Archive and the /// Archive export state. Cross-platform: backs the sidebar's Export Archive and the
/// "Save & Clear" flow is separate (it saves to the library, not a file). /// "Save & Clear" flow is separate (it saves to the library, not a file).
@State private var showExporter: Bool = false @State private var showExporter: Bool = false
@@ -297,13 +309,43 @@ public struct ShoeGazeBuilderView: View {
} }
} }
private var presentationChrome: some View { // Split off the first half of the presentation chain into its own computed property: the full
// modifier chain is long enough to blow the Swift expression type-checker's budget, so this
// boundary keeps each half small enough to type-check quickly.
private var chromeWithPrompts: some View {
layoutChrome layoutChrome
.background(boardsSheetAnchor) .background(boardsSheetAnchor)
.background(rigExportAnchor) .background(rigExportAnchor)
.background(rigImportAnchor) .background(rigImportAnchor)
.background(actionErrorAnchor) .background(actionErrorAnchor)
.rigNamePrompt($namePrompt) .rigNamePrompt($namePrompt)
.confirmationDialog(
"Starter rig",
isPresented: Binding(
get: { factoryOverwrite != nil },
set: { presented in if !presented { factoryOverwrite = nil } }
),
titleVisibility: .visible,
presenting: factoryOverwrite
) { request in
// A starter rig is managed content: it is refreshed to the shipped version whenever the
// starter catalog updates, so it deliberately cannot be overwritten in place — that would
// silently revert on the next update. The player keeps their changes as a new rig instead.
Button("Save as New Rig…") {
// Defer one runloop hop: presenting the name-entry alert while the confirmation
// dialog is still dismissing can drop the new presentation on some SwiftUI versions.
let completion: () -> Void = request.completion
DispatchQueue.main.async { promptSaveAs(then: completion) }
}
Button("Cancel", role: .cancel) { }
} message: { request in
Text("“\(request.entry.name)” is a built-in starter rig and can't be changed in place. "
+ "Save your changes as a new rig to keep them.")
}
}
private var presentationChrome: some View {
chromeWithPrompts
.confirmationDialog( .confirmationDialog(
"Erase all rigs?", "Erase all rigs?",
isPresented: $showEraseAllDialog, isPresented: $showEraseAllDialog,
@@ -607,10 +649,18 @@ public struct ShoeGazeBuilderView: View {
onEraseAll: { showEraseAllDialog = true }, onEraseAll: { showEraseAllDialog = true },
onImportArchive: { showImporter = true }, onImportArchive: { showImporter = true },
onExportArchive: { exportArchiveAction() }, onExportArchive: { exportArchiveAction() },
onRestoreStarters: { restoreStarterRigs() },
onShowCloudStatus: { showICloudUnavailableAlert = true } onShowCloudStatus: { showICloudUnavailableAlert = true }
) )
} }
/// (Re-)installs any shipped starter rigs missing from the library. Non-destructive: user rigs
/// are untouched, and already-present starters are skipped (matched by stable id).
private func restoreStarterRigs() {
let added: Int = RigLibraryBootstrap.restoreStarterRigs(into: library)
print("[ShoeGazeBuilderView] restored \(added) starter rig(s)")
}
// MARK: - Sleep / iCloud status // MARK: - Sleep / iCloud status
/// Platform name for the settings app, used in the iCloud guidance alert. /// Platform name for the settings app, used in the iCloud guidance alert.
@@ -1587,7 +1637,9 @@ public struct ShoeGazeBuilderView: View {
let wasRunning: Bool = shoeGaze.engine.isRunning let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() } if wasRunning { shoeGaze.engine.stop() }
do { do {
try shoeGaze.loadRig(from: entry.state) // Keep the player's currently-chosen input across the switch (e.g. a live guitar), rather
// than snapping to the input the selected rig was authored with.
try shoeGaze.loadRig(from: entry.state, keepingCurrentInput: true)
currentRigID = entry.id currentRigID = entry.id
selectedBoardIndex = 0 selectedBoardIndex = 0
autosave() autosave()
@@ -1622,12 +1674,16 @@ public struct ShoeGazeBuilderView: View {
/// Whether the working rig differs from the library entry it was loaded from. A working rig with /// Whether the working rig differs from the library entry it was loaded from. A working rig with
/// no backing entry counts as dirty when it has any boards. /// no backing entry counts as dirty when it has any boards.
///
/// Compares rig content only (boards, routers, MIDI, tempo) — not the live input source or engine
/// channel counts, which are intentionally kept across a rig switch and so must not register as
/// unsaved changes (otherwise switching between rigs always prompts to save).
private func isCurrentRigDirty() -> Bool { private func isCurrentRigDirty() -> Bool {
guard let id: UUID = currentRigID, guard let id: UUID = currentRigID,
let entry: RigEntry = library.entries.first(where: { $0.id == id }) else { let entry: RigEntry = library.entries.first(where: { $0.id == id }) else {
return !shoeGaze.boards.isEmpty return !shoeGaze.boards.isEmpty
} }
return shoeGaze.captureState() != entry.state return !shoeGaze.captureState().hasSameRigContent(as: entry.state)
} }
/// Saves the current session over the loaded library entry, or prompts for a name when no entry /// Saves the current session over the loaded library entry, or prompts for a name when no entry
@@ -1649,6 +1705,12 @@ public struct ShoeGazeBuilderView: View {
} }
return return
} }
// Overwriting a built-in starter rig replaces it in the library. Confirm first, offering a
// non-destructive "Save as New Rig" so the shipped original can be kept.
if FactoryRigLibrary.isFactory(existing.id) {
factoryOverwrite = FactoryOverwriteRequest(entry: existing, completion: completion)
return
}
persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion) persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion)
} }
@@ -1664,13 +1726,16 @@ public struct ShoeGazeBuilderView: View {
} }
/// Prompts for a name and saves the current session as a new library entry (new id). /// Prompts for a name and saves the current session as a new library entry (new id).
private func promptSaveAs() { ///
/// - Parameter completion: Follow-up run once the new entry is persisted (e.g. the "Save & Clear"
/// clear step, or the pending action from a factory-rig overwrite prompt).
private func promptSaveAs(then completion: @escaping () -> Void = { }) {
namePrompt = RigNamePrompt( namePrompt = RigNamePrompt(
title: "Save Rig As", title: "Save Rig As",
initialText: currentRigName() ?? defaultNewRigName(), initialText: currentRigName() ?? defaultNewRigName(),
confirmLabel: "Save" confirmLabel: "Save"
) { name in ) { name in
persist(shoeGaze.captureEntry(name: name)) persist(shoeGaze.captureEntry(name: name), then: completion)
} }
} }
@@ -87,11 +87,35 @@ struct AmpVoicePedalTests {
@Test func gainChangesOutput() throws { @Test func gainChangesOutput() throws {
for voice in voices { for voice in voices {
let clean: [Float] = try render(voice.make) { $0.gain = 2.0 } let clean: [Float] = try render(voice.make) { $0.gain = 2.0 }
let hot: [Float] = try render(voice.make) { $0.gain = 25.0 } let hot: [Float] = try render(voice.make) { $0.gain = 10.5 }
#expect(windowedSSD(clean, hot) > 0, "\(voice.name) gain had no effect") #expect(windowedSSD(clean, hot) > 0, "\(voice.name) gain had no effect")
} }
} }
@Test func gainDialRunsOneToEleven() throws {
// The Gain knob is a 1–11 dial (it goes to eleven), mapped to tube drive via a taper.
for voice in voices {
let gainKnob: PedalKnob? = voice.make().effectKnobs.first { $0.label == "Gain" }
#expect(gainKnob?.range == 1.0 ... 11.0, "\(voice.name) Gain range should be 1...11")
}
// The Boutique amps' Drive channel is the same 1–11 dial.
let driveKnob: PedalKnob? = BoutiqueLeadAmpPedal().effectKnobs.first { $0.label == "Drive" }
#expect(driveKnob?.range == 1.0 ... 11.0, "Drive range should be 1...11")
}
@Test func gainTaperIsMonotonicAndSaturatesMore() throws {
// Turning the dial up must add saturation (waveshape change), and the exponential taper means
// the jump from 9→11 shapes the wave more than 1→3 — most grind lives up top. Use the
// California voice; RMS-normalize so level differences don't masquerade as waveshape change.
let low: [Float] = try render({ CaliforniaAmpPedal() }) { $0.gain = 1.0 }
let mid: [Float] = try render({ CaliforniaAmpPedal() }) { $0.gain = 3.0 }
let hi: [Float] = try render({ CaliforniaAmpPedal() }) { $0.gain = 9.0 }
let top: [Float] = try render({ CaliforniaAmpPedal() }) { $0.gain = 11.0 }
#expect(rmsNormalizedSSD(low, mid) > 0, "1→3 should change the waveshape")
#expect(rmsNormalizedSSD(hi, top) > rmsNormalizedSSD(low, mid),
"the top of the taper should shape more than the bottom (exponential)")
}
@Test func toneControlsChangeOutput() throws { @Test func toneControlsChangeOutput() throws {
for voice in voices { for voice in voices {
let dark: [Float] = try render(voice.make) { $0.treble = 0.0; $0.bass = 1.0 } let dark: [Float] = try render(voice.make) { $0.treble = 0.0; $0.bass = 1.0 }
@@ -122,7 +146,7 @@ struct AmpVoicePedalTests {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
for voice in voices { for voice in voices {
let hot: [Float] = try render(voice.make) { (pedal: AmpVoicePedal) in let hot: [Float] = try render(voice.make) { (pedal: AmpVoicePedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
} }
@@ -151,8 +175,8 @@ struct AmpVoicePedalTests {
// just the level (which is what `level` would do). RMS-normalize each window before diffing: // just the level (which is what `level` would do). RMS-normalize each window before diffing:
// a pure level change collapses to ~0, so a clearly-positive normalized SSD proves genuine // a pure level change collapses to ~0, so a clearly-positive normalized SSD proves genuine
// power-amp saturation. // power-amp saturation.
let low: [Float] = try render({ BritishAmpPedal() }) { $0.gain = 12.0; $0.master = 0.1 } let low: [Float] = try render({ BritishAmpPedal() }) { $0.gain = 8.3; $0.master = 0.1 }
let high: [Float] = try render({ BritishAmpPedal() }) { $0.gain = 12.0; $0.master = 1.0 } let high: [Float] = try render({ BritishAmpPedal() }) { $0.gain = 8.3; $0.master = 1.0 }
#expect(hasNonSilentOutput(low) && hasNonSilentOutput(high)) #expect(hasNonSilentOutput(low) && hasNonSilentOutput(high))
#expect(rmsNormalizedSSD(low, high) > 1.0e-3, "Master changed level but not tone (no power-amp saturation)") #expect(rmsNormalizedSSD(low, high) > 1.0e-3, "Master changed level but not tone (no power-amp saturation)")
} }
@@ -160,7 +184,7 @@ struct AmpVoicePedalTests {
@Test func britishStaysWithinCeilingAtMaxMaster() throws { @Test func britishStaysWithinCeilingAtMaxMaster() throws {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
let hot: [Float] = try render({ BritishAmpPedal() }) { (pedal: BritishAmpPedal) in let hot: [Float] = try render({ BritishAmpPedal() }) { (pedal: BritishAmpPedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
pedal.master = 1.0 pedal.master = 1.0
@@ -183,6 +207,200 @@ struct AmpVoicePedalTests {
#expect(windowedSSD(open, dark) > 0, "Chime Cut had no effect") #expect(windowedSSD(open, dark) > 0, "Chime Cut had no effect")
} }
// MARK: - Power-amp Sag / Bias (shared)
@Test func sagChangesOutput() throws {
for voice in voices {
let stiff: [Float] = try render(voice.make) { $0.gain = 9.8; $0.sag = 0.0 }
let saggy: [Float] = try render(voice.make) { $0.gain = 9.8; $0.sag = 1.0 }
#expect(windowedSSD(stiff, saggy) > 0, "\(voice.name) Sag had no effect")
}
}
@Test func sagStaysWithinCeilingWithoutPhaseInversion() throws {
// Sag is a gain droop; it must attenuate loud content, never phase-invert it. The envelope
// tracks a post-power-amp signal that can exceed 1, so the droop gain is clamped positive.
// Assert the sagged output correlates positively with the stiff one (not an inverted copy)
// and never breaches the ±1 ceiling.
let ceilingEpsilon: Double = 1.0e-4
for voice in voices {
let cfg: (AmpVoicePedal) -> Void = { (p: AmpVoicePedal) in
p.gain = 10.5; p.bass = 1.0; p.treble = 1.0
}
let stiff: [Float] = try render(voice.make) { cfg($0); $0.sag = 0.0 }
let saggy: [Float] = try render(voice.make) { cfg($0); $0.sag = 1.0 }
let peak: Double = saggy.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon, "\(voice.name) sagged peak \(peak) exceeds ±1")
let skip: Int = 4096, window: Int = 4096
guard stiff.count >= skip + window, saggy.count >= skip + window else {
Issue.record("\(voice.name) render too short"); continue
}
let dotProduct: Double = zip(stiff[skip..<(skip + window)], saggy[skip..<(skip + window)])
.reduce(0.0) { acc, pair in acc + Double(pair.0) * Double(pair.1) }
#expect(dotProduct > 0, "\(voice.name) Sag phase-inverted the signal (dot \(dotProduct) < 0)")
}
}
@Test func biasChangesWaveshape() throws {
// Bias shifts the power-amp tanh operating point → changes the even/odd harmonic mix (a
// waveshape change), not merely the level. RMS-normalize so a pure level difference collapses.
for voice in voices {
let cold: [Float] = try render(voice.make) { $0.gain = 10.2; $0.bias = 0.0 }
let hot: [Float] = try render(voice.make) { $0.gain = 10.2; $0.bias = 1.0 }
#expect(hasNonSilentOutput(cold) && hasNonSilentOutput(hot))
#expect(rmsNormalizedSSD(cold, hot) > 1.0e-4, "\(voice.name) Bias changed level but not waveshape")
}
}
@Test func neutralBiasAndZeroSagAreIdentityDefault() throws {
// The shipped defaults are sag = 0, bias = 0.5, biasX = 0 (all neutral). Setting them
// explicitly to those values must be bit-for-bit identical to leaving them at their defaults
// — proof the pop-over controls don't perturb any existing amp's voice at their neutral point.
for voice in voices {
let byDefault: [Float] = try render(voice.make)
let explicit: [Float] = try render(voice.make) { $0.sag = 0.0; $0.bias = 0.5; $0.biasX = 0.0 }
#expect(windowedSSD(byDefault, explicit) == 0, "\(voice.name) neutral Sag/Bias/Bias X is not identity")
}
}
@Test func biasXChangesWaveshape() throws {
// Bias X spreads the two power-amp half-stages' operating points → changes the even/odd
// harmonic mix (a waveshape change), not merely the level. RMS-normalize so a pure level
// difference collapses.
for voice in voices {
let balanced: [Float] = try render(voice.make) { $0.gain = 10.2; $0.biasX = 0.0 }
let imbalanced: [Float] = try render(voice.make) { $0.gain = 10.2; $0.biasX = 1.0 }
#expect(hasNonSilentOutput(balanced) && hasNonSilentOutput(imbalanced))
#expect(rmsNormalizedSSD(balanced, imbalanced) > 1.0e-4,
"\(voice.name) Bias X changed level but not waveshape")
}
}
@Test func biasXStaysWithinCeiling() throws {
let ceilingEpsilon: Double = 1.0e-4
for voice in voices {
let hot: [Float] = try render(voice.make) { (pedal: AmpVoicePedal) in
pedal.gain = 11.0; pedal.bass = 1.0; pedal.treble = 1.0; pedal.biasX = 1.0
}
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon, "\(voice.name) Bias X peak \(peak) exceeds ±1")
}
}
@Test func extremeBiasAndBiasXStayWithinCeiling() throws {
// Bias (hot) + Bias X (max) together drive a half-stage bias to ±0.6 (base ±0.25 ± spread
// 0.35). The tanh stays bounded and outputLimit clamps — output must stay finite and ≤ ±1.
let ceilingEpsilon: Double = 1.0e-4
for voice in voices {
let hot: [Float] = try render(voice.make) { (pedal: AmpVoicePedal) in
pedal.gain = 11.0; pedal.bass = 1.0; pedal.treble = 1.0; pedal.bias = 1.0; pedal.biasX = 1.0
}
#expect(hot.allSatisfy { $0.isFinite }, "\(voice.name) bias+biasX produced non-finite output")
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon, "\(voice.name) bias+biasX peak \(peak) exceeds ±1")
}
}
@Test func advancedKnobsExposeSagBiasAndBiasX() throws {
for voice in voices {
let pedal: AmpVoicePedal = voice.make()
#expect(pedal.advancedKnobs.map { $0.label } == ["Sag", "Bias", "Bias X"],
"\(voice.name) advanced knobs")
// These are pop-over-only — they must NOT also appear on the pedal face.
let faceLabels: [String] = pedal.effectKnobs.map { $0.label }
#expect(!faceLabels.contains("Sag") && !faceLabels.contains("Bias") && !faceLabels.contains("Bias X"),
"\(voice.name) leaked an advanced knob onto the pedal face")
}
}
@Test func sagBiasRoundTripThroughState() throws {
let pedal: CaliforniaAmpPedal = CaliforniaAmpPedal()
pedal.sag = 0.7
pedal.bias = 0.2
pedal.biasX = 0.6
let restored: CaliforniaAmpPedal = CaliforniaAmpPedal()
restored.applyState(pedal.captureState())
#expect(restored.sag == 0.7 && restored.bias == 0.2 && restored.biasX == 0.6,
"Sag/Bias/Bias X did not round-trip through state")
}
// MARK: - Cabinet decoupling
@Test func cabNoneBypassesConvolution() throws {
for voice in voices {
let withCab: [Float] = try render(voice.make) { $0.cab = 0.0 }
let none: [Float] = try render(voice.make) { $0.cab = AmpVoicePedal.cabinetBypassValue }
#expect(hasNonSilentOutput(none) && none.allSatisfy { $0.isFinite },
"\(voice.name) None-cab output silent or non-finite")
#expect(windowedSSD(withCab, none) > 0, "\(voice.name) None did not bypass the cabinet")
}
}
@Test func cabNoneStillLimitsToCeiling() throws {
// With the cabinet bypassed the output soft-limit must still run — the ±1 ceiling has to hold.
let ceilingEpsilon: Double = 1.0e-4
for voice in voices {
let hot: [Float] = try render(voice.make) { (pedal: AmpVoicePedal) in
pedal.gain = 11.0; pedal.bass = 1.0; pedal.treble = 1.0
pedal.cab = AmpVoicePedal.cabinetBypassValue
}
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon,
"\(voice.name) None-cab peak \(peak) exceeds ±1 (output limiter lost)")
}
}
@Test func extremeCabValuesDoNotTrap() throws {
// A corrupted/hand-edited rig can restore any Double into `cab`. Neither the bypass check nor
// the voice lookup may trap `Int(_:)` — every value must resolve to a defined, finite render.
let extremes: [Double] = [.infinity, -.infinity, 1.0e20, -1.0e20, .nan, 999.0]
for cabValue: Double in extremes {
let out: [Float] = try render({ CaliforniaAmpPedal() }) { $0.cab = cabValue }
#expect(out.allSatisfy { $0.isFinite }, "cab=\(cabValue) produced non-finite output")
}
}
@Test func cabSelectorExposesNoneStop() throws {
let stops: [PedalSelectorKnob.Stop] = CaliforniaAmpPedal().effectSelectors
.first { $0.label == "Cab" }?.stops ?? []
#expect(stops.last?.title == "None (direct)", "Cab selector missing the None stop")
#expect(stops.last?.value == AmpVoicePedal.cabinetBypassValue, "None stop has the wrong value")
}
@Test func ampWithNoneCabIntoStandaloneCabinetWorks() throws {
// Decoupled chain: amp (Cab = None) → standalone Cabinet pedal. The amp emits its limited,
// cab-less signal; the separate Cabinet block does the speaker convolution downstream.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.2, sampleRate: sampleRate, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let midBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(midBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let amp: CaliforniaAmpPedal = CaliforniaAmpPedal(inputBus: srcBus.index, outputBus: midBus.index)
amp.sampleRate = sampleRate
amp.cab = AmpVoicePedal.cabinetBypassValue
let cabinet: CabinetPedal = CabinetPedal(inputBus: midBus.index, outputBus: dstBus.index)
cabinet.sampleRate = sampleRate
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(amp, position: NodePosition.after(source))
try engine.add(cabinet, position: NodePosition.after(amp))
try engine.add(master, position: NodePosition.after(cabinet))
try engine.start()
let out: [Float] = readStereoCAF(url: url, sampleRate: sampleRate)
#expect(hasNonSilentOutput(out) && out.allSatisfy { $0.isFinite }, "decoupled amp+cabinet silent/non-finite")
// Note: the amp guarantees its OWN output ≤ ±1 (see `cabNoneStillLimitsToCeiling`), but a
// downstream standalone Cabinet convolves that signal and — like any post-amp pedal — may
// overshoot ±1. The board's final output stage, not the amp, owns end-of-chain level. So this
// asserts the decoupled chain works (non-silent, finite), not a ±1 ceiling it never promised.
}
// MARK: - Chrome / config // MARK: - Chrome / config
@Test func exposesControls() throws { @Test func exposesControls() throws {
@@ -207,12 +425,12 @@ struct AmpVoicePedalTests {
@Test func selectionsRoundTripThroughState() throws { @Test func selectionsRoundTripThroughState() throws {
let pedal: CaliforniaAmpPedal = CaliforniaAmpPedal() let pedal: CaliforniaAmpPedal = CaliforniaAmpPedal()
pedal.gain = 12.0 pedal.gain = 8.3
pedal.cab = 2.0 pedal.cab = 2.0
pedal.bright = 0.8 pedal.bright = 0.8
let restored: CaliforniaAmpPedal = CaliforniaAmpPedal() let restored: CaliforniaAmpPedal = CaliforniaAmpPedal()
restored.applyState(pedal.captureState()) restored.applyState(pedal.captureState())
#expect(restored.gain == 12.0 && restored.cab == 2.0 && restored.bright == 0.8, #expect(restored.gain == 8.3 && restored.cab == 2.0 && restored.bright == 0.8,
"California controls did not round-trip") "California controls did not round-trip")
} }
@@ -84,7 +84,7 @@ struct BoutiqueAmpPedalTests {
@Test func channelSwitchChangesOutputAndRebuilds() throws { @Test func channelSwitchChangesOutputAndRebuilds() throws {
for v: (name: String, make: () -> BoutiqueAmpPedal) in voices { for v: (name: String, make: () -> BoutiqueAmpPedal) in voices {
let clean: [Float] = try render(v.make) { $0.channel = 0.0 } let clean: [Float] = try render(v.make) { $0.channel = 0.0 }
let lead: [Float] = try render(v.make) { $0.channel = 1.0; $0.drive = 18.0 } let lead: [Float] = try render(v.make) { $0.channel = 1.0; $0.drive = 9.5 }
#expect(windowedSSD(clean, lead) > 0, "\(v.name) channel switch had no effect") #expect(windowedSSD(clean, lead) > 0, "\(v.name) channel switch had no effect")
let channel: PedalSwitch? = v.make().effectSwitches.first { $0.label == "Channel" } let channel: PedalSwitch? = v.make().effectSwitches.first { $0.label == "Channel" }
#expect(channel?.rebuildsOnChange == true, "\(v.name) Channel should rebuild on change") #expect(channel?.rebuildsOnChange == true, "\(v.name) Channel should rebuild on change")
@@ -113,7 +113,7 @@ struct BoutiqueAmpPedalTests {
@Test func driveKnobChangesLeadChannel() throws { @Test func driveKnobChangesLeadChannel() throws {
for v: (name: String, make: () -> BoutiqueAmpPedal) in voices { for v: (name: String, make: () -> BoutiqueAmpPedal) in voices {
let low: [Float] = try render(v.make) { $0.channel = 1.0; $0.drive = 2.0 } let low: [Float] = try render(v.make) { $0.channel = 1.0; $0.drive = 2.0 }
let high: [Float] = try render(v.make) { $0.channel = 1.0; $0.drive = 25.0 } let high: [Float] = try render(v.make) { $0.channel = 1.0; $0.drive = 10.5 }
#expect(windowedSSD(low, high) > 0, "\(v.name) Drive had no effect on the lead channel") #expect(windowedSSD(low, high) > 0, "\(v.name) Drive had no effect on the lead channel")
} }
} }
@@ -121,8 +121,8 @@ struct BoutiqueAmpPedalTests {
@Test func stayWithinCeilingOnLeadChannel() throws { @Test func stayWithinCeilingOnLeadChannel() throws {
for v: (name: String, make: () -> BoutiqueAmpPedal) in voices { for v: (name: String, make: () -> BoutiqueAmpPedal) in voices {
let hot: [Float] = try render(v.make) { (p: BoutiqueAmpPedal) in let hot: [Float] = try render(v.make) { (p: BoutiqueAmpPedal) in
p.gain = 30.0; p.bass = 1.0; p.treble = 1.0 p.gain = 11.0; p.bass = 1.0; p.treble = 1.0
p.presence = 1.0; p.depth = 1.0; p.master = 1.0; p.channel = 1.0; p.drive = 30.0 p.presence = 1.0; p.depth = 1.0; p.master = 1.0; p.channel = 1.0; p.drive = 11.0
} }
#expect(peak(hot) <= 1.0 + 1.0e-4, "\(v.name) exceeds the ±1 ceiling on the lead channel") #expect(peak(hot) <= 1.0 + 1.0e-4, "\(v.name) exceeds the ±1 ceiling on the lead channel")
} }
@@ -133,8 +133,8 @@ struct BoutiqueAmpPedalTests {
#expect(lead.effectKnobs.map { $0.label } #expect(lead.effectKnobs.map { $0.label }
== ["Gain", "Bass", "Mid", "Treble", "Presence", "Depth", "Master", "Drive"]) == ["Gain", "Bass", "Mid", "Treble", "Presence", "Depth", "Master", "Drive"])
#expect(lead.effectSwitches.map { $0.label } == ["Channel"]) #expect(lead.effectSwitches.map { $0.label } == ["Channel"])
#expect(lead.widthUnits == 4) #expect(lead.widthUnits == 2)
#expect(lead.toneStackModel == .marshall) #expect(lead.toneStackModel == .soldano)
#expect(lead.powerAmpOversample == 4) #expect(lead.powerAmpOversample == 4)
let od: BoutiqueODAmpPedal = BoutiqueODAmpPedal() let od: BoutiqueODAmpPedal = BoutiqueODAmpPedal()
@@ -150,12 +150,12 @@ struct BoutiqueAmpPedalTests {
@Test func roundTripsThroughState() throws { @Test func roundTripsThroughState() throws {
let pedal: BoutiqueODAmpPedal = BoutiqueODAmpPedal() let pedal: BoutiqueODAmpPedal = BoutiqueODAmpPedal()
pedal.presence = 0.6; pedal.depth = 0.7; pedal.master = 0.8; pedal.drive = 12.0 pedal.presence = 0.6; pedal.depth = 0.7; pedal.master = 0.8; pedal.drive = 8.3
pedal.channel = 1.0; pedal.midBoost = 1.0; pedal.cab = 2.0 pedal.channel = 1.0; pedal.midBoost = 1.0; pedal.cab = 2.0
let restored: BoutiqueODAmpPedal = BoutiqueODAmpPedal() let restored: BoutiqueODAmpPedal = BoutiqueODAmpPedal()
restored.applyState(pedal.captureState()) restored.applyState(pedal.captureState())
#expect(restored.presence == 0.6 && restored.depth == 0.7 && restored.master == 0.8) #expect(restored.presence == 0.6 && restored.depth == 0.7 && restored.master == 0.8)
#expect(restored.drive == 12.0 && restored.channel == 1.0 && restored.midBoost == 1.0 && restored.cab == 2.0) #expect(restored.drive == 8.3 && restored.channel == 1.0 && restored.midBoost == 1.0 && restored.cab == 2.0)
} }
@Test func registeredInBuiltInRegistry() throws { @Test func registeredInBuiltInRegistry() throws {
@@ -108,7 +108,7 @@ struct BritishComboAmpPedalTests {
let pedal: BritishBluesbreakerAmpPedal = BritishBluesbreakerAmpPedal() let pedal: BritishBluesbreakerAmpPedal = BritishBluesbreakerAmpPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Presence", "Speed", "Intensity"]) #expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Presence", "Speed", "Intensity"])
#expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Tremolo"]) #expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Tremolo"])
#expect(pedal.widthUnits == 3) #expect(pedal.widthUnits == 2)
} }
@Test func bluesbreakerTremoloIntensityChangesOutput() throws { @Test func bluesbreakerTremoloIntensityChangesOutput() throws {
@@ -129,7 +129,7 @@ struct BritishComboAmpPedalTests {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
for v: (name: String, make: () -> BritishComboAmpPedal) in voices { for v: (name: String, make: () -> BritishComboAmpPedal) in voices {
let hot: [Float] = try render(v.make) { (pedal: BritishComboAmpPedal) in let hot: [Float] = try render(v.make) { (pedal: BritishComboAmpPedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
pedal.presence = 1.0 pedal.presence = 1.0
@@ -92,14 +92,14 @@ struct BritishMasterAmpPedalTests {
let pedal: BritishMasterAmpPedal = BritishMasterAmpPedal() let pedal: BritishMasterAmpPedal = BritishMasterAmpPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Presence", "Master"]) #expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Presence", "Master"])
#expect(pedal.effectSwitches.map { $0.label } == ["Bright"]) #expect(pedal.effectSwitches.map { $0.label } == ["Bright"])
#expect(pedal.widthUnits == 3) #expect(pedal.widthUnits == 2)
#expect(pedal.toneStackModel == .marshall) #expect(pedal.toneStackModel == .marshall)
#expect(pedal.powerAmpOversample == 4) #expect(pedal.powerAmpOversample == 4)
} }
@Test func masterStaysWithinCeiling() throws { @Test func masterStaysWithinCeiling() throws {
let hot: [Float] = try render({ BritishMasterAmpPedal() }) { (p: BritishMasterAmpPedal) in let hot: [Float] = try render({ BritishMasterAmpPedal() }) { (p: BritishMasterAmpPedal) in
p.gain = 30.0; p.bass = 1.0; p.treble = 1.0; p.presence = 1.0; p.bright = 1.0; p.master = 1.0 p.gain = 11.0; p.bass = 1.0; p.treble = 1.0; p.presence = 1.0; p.bright = 1.0; p.master = 1.0
} }
#expect(peak(hot) <= 1.0 + 1.0e-4, "British Master exceeds the ±1 ceiling") #expect(peak(hot) <= 1.0 + 1.0e-4, "British Master exceeds the ±1 ceiling")
} }
@@ -116,7 +116,7 @@ struct BritishMasterAmpPedalTests {
@Test func dualChannelSwitchChangesOutput() throws { @Test func dualChannelSwitchChangesOutput() throws {
let clean: [Float] = try render({ BritishDualAmpPedal() }) { $0.channel = 0.0 } let clean: [Float] = try render({ BritishDualAmpPedal() }) { $0.channel = 0.0 }
let lead: [Float] = try render({ BritishDualAmpPedal() }) { $0.channel = 1.0; $0.drive = 15.0 } let lead: [Float] = try render({ BritishDualAmpPedal() }) { $0.channel = 1.0; $0.drive = 9.0 }
#expect(hasNonSilentOutput(clean) && hasNonSilentOutput(lead)) #expect(hasNonSilentOutput(clean) && hasNonSilentOutput(lead))
#expect(windowedSSD(clean, lead) > 0, "channel switch had no effect") #expect(windowedSSD(clean, lead) > 0, "channel switch had no effect")
let channel: PedalSwitch? = BritishDualAmpPedal().effectSwitches.first { $0.label == "Channel" } let channel: PedalSwitch? = BritishDualAmpPedal().effectSwitches.first { $0.label == "Channel" }
@@ -125,7 +125,7 @@ struct BritishMasterAmpPedalTests {
@Test func dualDriveAndReverbAndMasterWork() throws { @Test func dualDriveAndReverbAndMasterWork() throws {
let low: [Float] = try render({ BritishDualAmpPedal() }) { $0.channel = 1.0; $0.drive = 2.0 } let low: [Float] = try render({ BritishDualAmpPedal() }) { $0.channel = 1.0; $0.drive = 2.0 }
let high: [Float] = try render({ BritishDualAmpPedal() }) { $0.channel = 1.0; $0.drive = 25.0 } let high: [Float] = try render({ BritishDualAmpPedal() }) { $0.channel = 1.0; $0.drive = 10.5 }
#expect(windowedSSD(low, high) > 0, "Drive had no effect on the lead channel") #expect(windowedSSD(low, high) > 0, "Drive had no effect on the lead channel")
let dry: [Float] = try render({ BritishDualAmpPedal() }) { $0.reverb = 0.0 } let dry: [Float] = try render({ BritishDualAmpPedal() }) { $0.reverb = 0.0 }
let wet: [Float] = try render({ BritishDualAmpPedal() }) { $0.reverb = 0.9 } let wet: [Float] = try render({ BritishDualAmpPedal() }) { $0.reverb = 0.9 }
@@ -140,26 +140,26 @@ struct BritishMasterAmpPedalTests {
#expect(pedal.effectKnobs.map { $0.label } #expect(pedal.effectKnobs.map { $0.label }
== ["Gain", "Bass", "Mid", "Treble", "Presence", "Master", "Drive", "Reverb"]) == ["Gain", "Bass", "Mid", "Treble", "Presence", "Master", "Drive", "Reverb"])
#expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Channel"]) #expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Channel"])
#expect(pedal.widthUnits == 4) #expect(pedal.widthUnits == 2)
#expect(pedal.toneStackModel == .marshall) #expect(pedal.toneStackModel == .marshall)
#expect(pedal.powerAmpOversample == 4) #expect(pedal.powerAmpOversample == 4)
} }
@Test func dualStaysWithinCeilingOnLeadChannel() throws { @Test func dualStaysWithinCeilingOnLeadChannel() throws {
let hot: [Float] = try render({ BritishDualAmpPedal() }) { (p: BritishDualAmpPedal) in let hot: [Float] = try render({ BritishDualAmpPedal() }) { (p: BritishDualAmpPedal) in
p.gain = 30.0; p.bass = 1.0; p.treble = 1.0; p.presence = 1.0; p.bright = 1.0 p.gain = 11.0; p.bass = 1.0; p.treble = 1.0; p.presence = 1.0; p.bright = 1.0
p.master = 1.0; p.channel = 1.0; p.drive = 30.0; p.reverb = 1.0 p.master = 1.0; p.channel = 1.0; p.drive = 11.0; p.reverb = 1.0
} }
#expect(peak(hot) <= 1.0 + 1.0e-4, "British Dual exceeds the ±1 ceiling on the lead channel") #expect(peak(hot) <= 1.0 + 1.0e-4, "British Dual exceeds the ±1 ceiling on the lead channel")
} }
@Test func dualRoundTrips() throws { @Test func dualRoundTrips() throws {
let pedal: BritishDualAmpPedal = BritishDualAmpPedal() let pedal: BritishDualAmpPedal = BritishDualAmpPedal()
pedal.master = 0.7; pedal.drive = 12.0; pedal.reverb = 0.5; pedal.channel = 1.0 pedal.master = 0.7; pedal.drive = 8.3; pedal.reverb = 0.5; pedal.channel = 1.0
pedal.presence = 0.6; pedal.bright = 1.0; pedal.cab = 2.0 pedal.presence = 0.6; pedal.bright = 1.0; pedal.cab = 2.0
let restored: BritishDualAmpPedal = BritishDualAmpPedal() let restored: BritishDualAmpPedal = BritishDualAmpPedal()
restored.applyState(pedal.captureState()) restored.applyState(pedal.captureState())
#expect(restored.master == 0.7 && restored.drive == 12.0 && restored.reverb == 0.5) #expect(restored.master == 0.7 && restored.drive == 8.3 && restored.reverb == 0.5)
#expect(restored.channel == 1.0 && restored.presence == 0.6 && restored.bright == 1.0 && restored.cab == 2.0) #expect(restored.channel == 1.0 && restored.presence == 0.6 && restored.bright == 1.0 && restored.cab == 2.0)
} }
@@ -110,4 +110,57 @@ struct CabinetIRFactoryTests {
let names: [String] = CabinetVoice.allCases.map { $0.displayName } let names: [String] = CabinetVoice.allCases.map { $0.displayName }
#expect(Set(names).count == names.count, "duplicate cabinet display names") #expect(Set(names).count == names.count, "duplicate cabinet display names")
} }
// MARK: - Mic voicing
/// Ratio of the IR's magnitude at `hz` to a mid-band reference (800 Hz). Peak-normalization
/// scales the whole IR, so it cancels in this ratio — letting a mic's *relative* boost/cut at a
/// frequency be compared across IRs regardless of their independent normalization.
private func tiltRatio(_ ir: LyrebirdBuffer, hz: Double) -> Double {
let reference: Double = responseMagnitude(ir, hz: 800.0)
guard reference > 0.0 else { return 0.0 }
return responseMagnitude(ir, hz: hz) / reference
}
@Test func noMicMatchesRawCabIR() {
// MicVoice.off must append no stages, so the IR is byte-identical to the mic-less default —
// the backward-compatible path for cabs saved before mic voicing existed.
for voice: CabinetVoice in CabinetVoice.allCases {
let raw: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: voice, sampleRate: sampleRate)
let offMic: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: voice, mic: .off, sampleRate: sampleRate)
#expect(raw.count == offMic.count)
var identical: Bool = true
for i: Int in 0..<raw.count where raw[i, 0] != offMic[i, 0] { identical = false; break }
#expect(identical, "\(voice) No-Mic IR differs from the raw cab IR")
}
}
@Test func dynamicMicLiftsPresence() {
// The dynamic mic adds a presence bump at ~5.5 kHz → a higher 5.5 kHz-to-mid tilt than no mic.
let off: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .americanCombo, mic: .off, sampleRate: sampleRate)
let dynamic: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .americanCombo, mic: .dynamic, sampleRate: sampleRate)
#expect(tiltRatio(dynamic, hz: 5500.0) > tiltRatio(off, hz: 5500.0),
"dynamic mic did not lift the presence region")
}
@Test func ribbonMicDarkensTop() {
// The ribbon mic rolls the top off (−7 dB shelf @ 6.5 kHz) → a lower 8 kHz-to-mid tilt.
let off: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .fullRange, mic: .off, sampleRate: sampleRate)
let ribbon: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .fullRange, mic: .ribbon, sampleRate: sampleRate)
#expect(tiltRatio(ribbon, hz: 8000.0) < tiltRatio(off, hz: 8000.0),
"ribbon mic did not darken the top end")
}
@Test func condenserMicAddsAir() {
// The condenser mic lifts the extreme top (+3 dB shelf @ 11 kHz) → a higher 10 kHz-to-mid tilt.
let off: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .fullRange, mic: .off, sampleRate: sampleRate)
let condenser: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .fullRange, mic: .condenser, sampleRate: sampleRate)
#expect(tiltRatio(condenser, hz: 10000.0) > tiltRatio(off, hz: 10000.0),
"condenser mic did not add top-end air")
}
@Test func micNamesAreUnique() {
let names: [String] = MicVoice.allCases.map { $0.displayName }
#expect(Set(names).count == names.count, "duplicate mic display names")
}
} }
@@ -59,13 +59,180 @@ struct CabinetPedalTests {
#expect(ssd > 0, "cabinet selection had no effect on output") #expect(ssd > 0, "cabinet selection had no effect on output")
} }
@Test func exposesCabinetSelector() throws { @Test func exposesCabinetAndMicSelectors() throws {
let pedal: CabinetPedal = CabinetPedal() let pedal: CabinetPedal = CabinetPedal()
let labels: [String] = pedal.effectSelectors.map { $0.label } let labels: [String] = pedal.effectSelectors.map { $0.label }
#expect(labels == ["Cab"]) #expect(labels == ["Cab", "Mic", "Mic B"])
// One stop per voice, in allCases order. // One Cab stop per voice, and one stop per mic voice for both Mic and Mic B, in allCases order.
let stops: [String] = pedal.effectSelectors.first?.stops.map { $0.title } ?? [] let cabStops: [String] = pedal.effectSelectors.first { $0.label == "Cab" }?.stops.map { $0.title } ?? []
#expect(stops == CabinetVoice.allCases.map { $0.displayName }) #expect(cabStops == CabinetVoice.allCases.map { $0.displayName })
let micStops: [String] = pedal.effectSelectors.first { $0.label == "Mic" }?.stops.map { $0.title } ?? []
#expect(micStops == MicVoice.allCases.map { $0.displayName })
let micBStops: [String] = pedal.effectSelectors.first { $0.label == "Mic B" }?.stops.map { $0.title } ?? []
#expect(micBStops == MicVoice.allCases.map { $0.displayName })
}
@Test func micSelectionChangesOutput() throws {
// Mic 0 = No Mic, mic 1 = Dynamic — different baked IRs, different output.
let noMic: [Float] = try render { $0.mic = 0.0 }
let dynamic: [Float] = try render { $0.mic = 1.0 }
#expect(hasNonSilentOutput(noMic) && hasNonSilentOutput(dynamic))
let skip: Int = 4096, window: Int = 4096
guard noMic.count >= skip + window, dynamic.count >= skip + window else { return }
let ssd: Double = zip(noMic[skip..<(skip + window)], dynamic[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "mic selection had no effect on output")
}
@Test func micSelectionRoundTripsThroughState() throws {
let pedal: CabinetPedal = CabinetPedal()
pedal.cabinet = 2.0
pedal.mic = 3.0
let restored: CabinetPedal = CabinetPedal()
restored.applyState(pedal.captureState())
#expect(restored.cabinet == 2.0 && restored.mic == 3.0, "cab/mic selection did not round-trip")
}
@Test func positionChangesOutput() throws {
// Position sweeps a live high-shelf cut (on-axis → cone edge), so it must change the output.
let onAxis: [Float] = try render { $0.position = 0.0 }
let edge: [Float] = try render { $0.position = 1.0 }
let skip: Int = 4096, window: Int = 4096
#expect(onAxis.count >= skip + window && edge.count >= skip + window, "render too short")
guard onAxis.count >= skip + window, edge.count >= skip + window else { return }
let ssd: Double = zip(onAxis[skip..<(skip + window)], edge[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "mic Position had no effect on output")
}
@Test func proximityChangesOutput() throws {
// Proximity sweeps a live low-shelf boost (distant → close), so it must change the output.
let distant: [Float] = try render { $0.proximity = 0.0 }
let close: [Float] = try render { $0.proximity = 1.0 }
let skip: Int = 4096, window: Int = 4096
#expect(distant.count >= skip + window && close.count >= skip + window, "render too short")
guard distant.count >= skip + window, close.count >= skip + window else { return }
let ssd: Double = zip(distant[skip..<(skip + window)], close[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "mic Proximity had no effect on output")
}
@Test func explicitDefaultPlacementMatchesImplicit() throws {
// A default-consistency guard: the shipped defaults are position = 0 / proximity = 0, so
// setting them explicitly must reproduce the default render exactly. (That those defaults are
// a *no-op* on the tone follows from the RBJ shelves collapsing to unity at 0 dB — a Lyrebird
// property; this test pins that the defaults are those values and the render is deterministic.)
let byDefault: [Float] = try render()
let explicit: [Float] = try render { $0.position = 0.0; $0.proximity = 0.0 }
let skip: Int = 4096, window: Int = 4096
#expect(byDefault.count >= skip + window && explicit.count >= skip + window, "render too short")
guard byDefault.count >= skip + window, explicit.count >= skip + window else { return }
let ssd: Double = zip(byDefault[skip..<(skip + window)], explicit[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd == 0, "explicit default placement did not match the default render")
}
@Test func advancedKnobsExposePlacementAndDualMic() throws {
let pedal: CabinetPedal = CabinetPedal()
#expect(pedal.advancedKnobs.map { $0.label } == ["Position", "Proximity", "Mic Blend", "Mic Offset"])
}
// MARK: - Dual mic
@Test func secondMicChangesOutput() throws {
// Engaging Mic B (a second parallel convolver) must change the output vs the single mic.
let single: [Float] = try render { $0.micB = 0.0 }
let dual: [Float] = try render { $0.micB = 2.0 } // Ribbon as the second mic
let skip: Int = 4096, window: Int = 4096
#expect(single.count >= skip + window && dual.count >= skip + window, "render too short")
guard single.count >= skip + window, dual.count >= skip + window else { return }
let ssd: Double = zip(single[skip..<(skip + window)], dual[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd > 0, "engaging Mic B had no effect")
}
@Test func micBOffMakesBlendAndOffsetInert() throws {
// With Mic B = No Mic, the second convolver is not built, so Mic Blend / Mic Offset must have
// no effect — proving the single-mic default path is untouched by the dual-mic controls.
let a: [Float] = try render { $0.micB = 0.0; $0.micBlend = 0.0; $0.micOffset = 0.0 }
let b: [Float] = try render { $0.micB = 0.0; $0.micBlend = 1.0; $0.micOffset = 1.0 }
let skip: Int = 4096, window: Int = 4096
#expect(a.count >= skip + window && b.count >= skip + window, "render too short")
guard a.count >= skip + window, b.count >= skip + window else { return }
let ssd: Double = zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
#expect(ssd == 0, "Mic Blend/Offset changed output while Mic B was Off")
}
@Test func micBlendAndOffsetChangeOutputWhenEngaged() throws {
// With Mic B engaged, both the blend balance and the comb offset must change the output.
let blendA: [Float] = try render { $0.micB = 2.0; $0.micBlend = 0.0 }
let blendB: [Float] = try render { $0.micB = 2.0; $0.micBlend = 1.0 }
let offset0: [Float] = try render { $0.micB = 2.0; $0.micBlend = 0.5; $0.micOffset = 0.0 }
let offset1: [Float] = try render { $0.micB = 2.0; $0.micBlend = 0.5; $0.micOffset = 1.0 }
let skip: Int = 4096, window: Int = 4096
func ssd(_ x: [Float], _ y: [Float]) -> Double {
guard x.count >= skip + window, y.count >= skip + window else { return 0.0 }
return zip(x[skip..<(skip + window)], y[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
}
#expect(ssd(blendA, blendB) > 0, "Mic Blend had no effect when engaged")
#expect(ssd(offset0, offset1) > 0, "Mic Offset (comb) had no effect when engaged")
}
@Test func dualMicRoundTripsThroughState() throws {
let pedal: CabinetPedal = CabinetPedal()
pedal.micB = 3.0
pedal.micBlend = 0.3
pedal.micOffset = 0.6
let restored: CabinetPedal = CabinetPedal()
restored.applyState(pedal.captureState())
#expect(restored.micB == 3.0 && restored.micBlend == 0.3 && restored.micOffset == 0.6,
"dual-mic controls did not round-trip")
}
@Test func dualMicStaysWithinCeiling() throws {
// Two convolvers summed can exceed ±1 pre-limiter; the look-ahead limiter must still bound it.
let ceilingEpsilon: Double = 1.0e-4
let out: [Float] = try render { $0.micB = 1.0; $0.micBlend = 0.5; $0.micOffset = 0.5 }
#expect(out.allSatisfy { $0.isFinite })
let peak: Double = out.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon, "dual-mic peak \(peak) exceeds ±1")
}
@Test func placementRoundTripsThroughState() throws {
let pedal: CabinetPedal = CabinetPedal()
pedal.position = 0.7
pedal.proximity = 0.4
let restored: CabinetPedal = CabinetPedal()
restored.applyState(pedal.captureState())
#expect(restored.position == 0.7 && restored.proximity == 0.4, "placement did not round-trip")
}
@Test func outputStaysWithinCeiling() throws {
// The tanh soft-limit + Clip(±1) bound the output so a decoupled amp → cabinet chain can't
// clip the DAC. No render may exceed ±1.
let ceilingEpsilon: Double = 1.0e-4
for cab: Double in [0.0, 2.0, 6.0] {
for micValue: Double in [0.0, 1.0, 2.0, 3.0] {
let out: [Float] = try render { $0.cabinet = cab; $0.mic = micValue }
#expect(out.allSatisfy { $0.isFinite })
let peak: Double = out.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon, "cab=\(cab) mic=\(micValue) peak \(peak) exceeds ±1")
}
}
// Placement extremes (max proximity bass lift) must still be caught by the limiter.
let placed: [Float] = try render { $0.position = 1.0; $0.proximity = 1.0 }
#expect(placed.allSatisfy { $0.isFinite })
let placedPeak: Double = placed.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(placedPeak <= 1.0 + ceilingEpsilon, "placement extremes peak \(placedPeak) exceeds ±1")
} }
@Test func cabinetSelectorRebuildsOnChange() throws { @Test func cabinetSelectorRebuildsOnChange() throws {
@@ -0,0 +1,105 @@
// CaliHiGainAmpPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("CaliHiGainAmpPedal")
struct CaliHiGainAmpPedalTests {
private let sampleRate: Double = 48000.0
private func render(configure: (CaliHiGainAmpPedal) -> Void = { _ in }) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.3, sampleRate: sampleRate, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: CaliHiGainAmpPedal = CaliHiGainAmpPedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.sampleRate = sampleRate
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
private func windowedSSD(_ a: [Float], _ b: [Float], skip: Int = 4096, window: Int = 4096) -> Double {
guard a.count >= skip + window, b.count >= skip + window else { return 0.0 }
return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
}
@Test func buildsNonSilentFiniteOutput() throws {
let s: [Float] = try render()
#expect(hasNonSilentOutput(s) && s.allSatisfy { $0.isFinite })
}
@Test func graphicEQBandsChangeOutput() throws {
// Each band moves the tone: sweep the mid-scoop band and an outer band.
let midCut: [Float] = try render { $0.eq750 = -12.0 }
let midBoost: [Float] = try render { $0.eq750 = 12.0 }
#expect(windowedSSD(midCut, midBoost) > 0, "750 Hz band had no effect")
let trebleFlat: [Float] = try render { $0.eq6600 = 0.0 }
let trebleBoost: [Float] = try render { $0.eq6600 = 12.0 }
#expect(windowedSSD(trebleFlat, trebleBoost) > 0, "6.6 kHz band had no effect")
}
@Test func inheritedChannelAndMasterWork() throws {
let clean: [Float] = try render { $0.channel = 0.0 }
let lead: [Float] = try render { $0.channel = 1.0 }
#expect(windowedSSD(clean, lead) > 0, "channel switch had no effect")
let channel: PedalSwitch? = CaliHiGainAmpPedal().effectSwitches.first { $0.label == "Channel" }
#expect(channel?.rebuildsOnChange == true)
}
@Test func staysWithinCeilingWithEQAndGainMaxed() throws {
let hot: [Float] = try render { (p: CaliHiGainAmpPedal) in
p.gain = 11.0; p.bass = 1.0; p.treble = 1.0; p.master = 1.0; p.channel = 1.0; p.drive = 11.0
p.eq80 = 12.0; p.eq240 = 12.0; p.eq750 = 12.0; p.eq2200 = 12.0; p.eq6600 = 12.0
}
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + 1.0e-4, "Cali Hi-Gain exceeds the ±1 ceiling with EQ + gain maxed: \(peak)")
}
@Test func exposesControlSurface() throws {
let pedal: CaliHiGainAmpPedal = CaliHiGainAmpPedal()
#expect(pedal.effectKnobs.map { $0.label }
== ["Gain", "Bass", "Mid", "Treble", "Presence", "Depth", "Master", "Drive"])
#expect(pedal.effectSliders.map { $0.label } == ["80", "240", "750", "2.2k", "6.6k"])
#expect(pedal.effectSwitches.map { $0.label } == ["Channel"])
#expect(pedal.widthUnits == 2)
#expect(pedal.toneStackModel == .mesa)
}
@Test func controlsRoundTripThroughState() throws {
let pedal: CaliHiGainAmpPedal = CaliHiGainAmpPedal()
pedal.eq80 = 4.0; pedal.eq750 = -8.0; pedal.eq6600 = 6.0
pedal.channel = 1.0; pedal.master = 0.7; pedal.cab = 2.0
let restored: CaliHiGainAmpPedal = CaliHiGainAmpPedal()
restored.applyState(pedal.captureState())
#expect(restored.eq80 == 4.0 && restored.eq750 == -8.0 && restored.eq6600 == 6.0)
#expect(restored.channel == 1.0 && restored.master == 0.7 && restored.cab == 2.0)
}
@Test func registeredInBuiltInRegistry() throws {
#expect(PedalRegistry.makePedal(type: "Cali Hi-Gain") is CaliHiGainAmpPedal)
}
}
@@ -0,0 +1,105 @@
// ChainRouterPersistenceTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("ChainRouter persistence")
struct ChainRouterPersistenceTests {
@Test func routerRigRoundTripsThroughJSONAndRenders() throws {
// Build a routed session: two-pedal board A, one-pedal board B, selecting board B.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: urlA) }
let sessionA: ShoeGaze = ShoeGaze(engine: engineA)
let router: ChainRouter = try sessionA.makeChainRouter()
try router.addToA(FuzzPedal())
try router.addToA(OverdrivePedal())
try router.addToB(ReverbPedal())
router.mode = .b
try router.finalize()
let state: ShoeGazeState = sessionA.captureState()
#expect(state.routers?.count == 1, "router was not captured")
#expect(state.boards.isEmpty, "router rig should have no plain boards")
// JSON round-trip.
let data: Data = try JSONEncoder().encode(state)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded == state, "router state did not survive a JSON round-trip")
// Load into a fresh session and verify the router was rebuilt structurally.
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.2, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: urlB) }
let sessionB: ShoeGaze = ShoeGaze(engine: engineB)
try sessionB.loadRig(from: decoded)
#expect(sessionB.routers.count == 1, "router was not rebuilt on load")
guard let rebuilt: ChainRouter = sessionB.routers.first else {
Issue.record("no rebuilt router")
return
}
#expect(rebuilt.boardA.pedals.count == 2, "board A pedal count not restored")
#expect(rebuilt.boardB.pedals.count == 1, "board B pedal count not restored")
#expect(rebuilt.boardA.pedals.map { $0.displayName } == ["Fuzz", "Overdrive"])
#expect(rebuilt.boardB.pedals.map { $0.displayName } == ["Reverb"])
// mode == .b → branch A muted, branch B active.
#expect(rebuilt.splitter.branchAEnabled == 0.0, "branch A level not restored")
#expect(rebuilt.splitter.branchBEnabled == 1.0, "branch B level not restored")
// The rebuilt router should render audio (board B is the active path).
try engineB.start()
let samples: [Float] = readStereoCAF(url: urlB)
#expect(hasNonSilentOutput(samples), "rebuilt router produced silence")
}
@Test func applyStateRecallsRouterParamsLive() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let session: ShoeGaze = ShoeGaze(engine: engine)
let router: ChainRouter = try session.makeChainRouter()
let fuzz: FuzzPedal = FuzzPedal()
fuzz.fuzz = 20.0
try router.addToA(fuzz)
try router.addToB(ReverbPedal())
router.mode = .a
try router.finalize()
let original: ShoeGazeState = session.captureState()
// Mutate live: change a router pedal param and flip the A/B selection.
fuzz.fuzz = 55.0
router.mode = .b
// Lightweight recall should restore the router pedal param and blend without a rebuild.
session.applyState(original)
#expect(fuzz.fuzz == 20.0, "router pedal param was not recalled")
#expect(router.splitter.branchAEnabled == 1.0, "branch A level not recalled")
#expect(router.splitter.branchBEnabled == 0.0, "branch B level not recalled")
}
@Test func routerlessRigStoresNoRoutersKey() throws {
// A plain single-board session must not gain a `routers` payload (byte-compat with rigs
// saved before router persistence existed).
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let session: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try session.addBoard()
try board.add(FuzzPedal())
try session.finalizeBoard(board)
let state: ShoeGazeState = session.captureState()
#expect(state.routers == nil, "routerless rig should capture nil routers")
let json: String = String(data: try JSONEncoder().encode(state), encoding: .utf8) ?? ""
#expect(!json.contains("\"routers\""), "routerless JSON should omit the routers key")
}
}
@@ -0,0 +1,162 @@
// CharacterAmpsTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Character amps")
struct CharacterAmpsTests {
private let sampleRate: Double = 48000.0
private func render<P: AmpVoicePedal>(_ make: () -> P, configure: (P) -> Void = { _ in }) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.3, sampleRate: sampleRate, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: P = make()
pedal.inputBus = srcBus.index
pedal.outputBus = dstBus.index
pedal.sampleRate = sampleRate
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
private func windowedSSD(_ a: [Float], _ b: [Float], skip: Int = 4096, window: Int = 4096) -> Double {
guard a.count >= skip + window, b.count >= skip + window else { return 0.0 }
return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
}
private func peak(_ s: [Float]) -> Double { s.reduce(0.0) { Swift.max($0, abs(Double($1))) } }
private let all: [(name: String, make: () -> AmpVoicePedal)] = [
("Command", { CommandAmpPedal() }),
("Citrus", { CitrusAmpPedal() }),
("Sixties Combo", { SixtiesComboAmpPedal() }),
("Magna Vibrato", { MagnaVibratoAmpPedal() }),
("Anaheim", { AnaheimAmpPedal() }),
]
@Test func allBuildNonSilentFiniteWithinCeiling() throws {
for a: (name: String, make: () -> AmpVoicePedal) in all {
let hot: [Float] = try render(a.make) { $0.gain = 11.0; $0.bass = 1.0; $0.treble = 1.0 }
#expect(hasNonSilentOutput(hot), "\(a.name) silent")
#expect(hot.allSatisfy { $0.isFinite }, "\(a.name) non-finite")
#expect(peak(hot) <= 1.0 + 1.0e-4, "\(a.name) exceeds ±1 ceiling: \(peak(hot))")
}
}
@Test func toneStackModels() throws {
#expect(CommandAmpPedal().toneStackModel == .marshall)
#expect(CitrusAmpPedal().toneStackModel == .marshall)
#expect(SixtiesComboAmpPedal().toneStackModel == .fender)
#expect(MagnaVibratoAmpPedal().toneStackModel == .fender)
#expect(AnaheimAmpPedal().toneStackModel == .fender)
}
// MARK: - Command (Hiwatt)
@Test func commandInheritsPresenceAndBright() throws {
let pedal: CommandAmpPedal = CommandAmpPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Presence"])
#expect(pedal.effectSwitches.map { $0.label } == ["Bright"])
let flat: [Float] = try render({ CommandAmpPedal() }) { $0.presence = 0.0 }
let lifted: [Float] = try render({ CommandAmpPedal() }) { $0.presence = 1.0 }
#expect(windowedSSD(flat, lifted) > 0, "Command Presence had no effect")
}
// MARK: - Citrus (Orange)
@Test func citrusShapeChangesOutput() throws {
let dark: [Float] = try render({ CitrusAmpPedal() }) { $0.shape = 0.0 }
let bright: [Float] = try render({ CitrusAmpPedal() }) { $0.shape = 1.0 }
#expect(windowedSSD(dark, bright) > 0, "Citrus Shape had no effect")
#expect(CitrusAmpPedal().effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Shape"])
}
// MARK: - Sixties Combo (Supro)
@Test func sixtiesTremoloWorksAndBypasses() throws {
let off: [Float] = try render({ SixtiesComboAmpPedal() }) { $0.intensity = 0.0 }
let on: [Float] = try render({ SixtiesComboAmpPedal() }) { $0.intensity = 1.0; $0.speed = 6.0 }
#expect(windowedSSD(off, on) > 0, "Sixties tremolo had no effect")
// Footswitch off with intensity up == no tremolo (bit-exact, shared tremolo helper).
let bypassed: [Float] = try render({ SixtiesComboAmpPedal() }) {
$0.intensity = 1.0; $0.speed = 6.0; $0.tremoloEnabled = 0.0
}
let noTrem: [Float] = try render({ SixtiesComboAmpPedal() }) { $0.intensity = 0.0 }
#expect(windowedSSD(bypassed, noTrem) == 0.0, "Sixties tremolo footswitch off should be identity")
}
// MARK: - Magna Vibrato (Magnatone)
@Test func magnaPitchVibratoWorks() throws {
let off: [Float] = try render({ MagnaVibratoAmpPedal() }) { $0.vibratoEnabled = 0.0; $0.depth = 0.5 }
let on: [Float] = try render({ MagnaVibratoAmpPedal() }) { $0.vibratoEnabled = 1.0; $0.depth = 0.5; $0.speed = 6.0 }
#expect(windowedSSD(off, on) > 0, "Magna vibrato had no effect")
// With vibrato off the sweep is zero → the delay is fixed, so Speed is irrelevant (identical).
let offSlow: [Float] = try render({ MagnaVibratoAmpPedal() }) { $0.vibratoEnabled = 0.0; $0.speed = 1.0 }
let offFast: [Float] = try render({ MagnaVibratoAmpPedal() }) { $0.vibratoEnabled = 0.0; $0.speed = 10.0 }
#expect(windowedSSD(offSlow, offFast) == 0.0, "vibrato off should ignore Speed (fixed delay)")
#expect(MagnaVibratoAmpPedal().effectSwitches.map { $0.label } == ["Vibrato"])
}
// MARK: - Anaheim (Music Man)
@Test func anaheimSwitchesWork() throws {
let a: AnaheimAmpPedal = AnaheimAmpPedal()
#expect(a.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble"])
#expect(a.effectSwitches.map { $0.label } == ["Bright", "Deep", "Limiter"])
let flat: [Float] = try render({ AnaheimAmpPedal() }) { $0.bright = 0.0 }
let bright: [Float] = try render({ AnaheimAmpPedal() }) { $0.bright = 1.0 }
#expect(windowedSSD(flat, bright) > 0, "Anaheim Bright had no effect")
let noDeep: [Float] = try render({ AnaheimAmpPedal() }) { $0.deep = 0.0 }
let deep: [Float] = try render({ AnaheimAmpPedal() }) { $0.deep = 1.0 }
#expect(windowedSSD(noDeep, deep) > 0, "Anaheim Deep had no effect")
}
@Test func anaheimLimiterActsWhenDrivenHot() throws {
// Driven hard, the built-in limiter (on) compresses vs bypassed (off) → different output.
let limited: [Float] = try render({ AnaheimAmpPedal() }) { $0.gain = 10.5; $0.limiter = 1.0 }
let unlimited: [Float] = try render({ AnaheimAmpPedal() }) { $0.gain = 10.5; $0.limiter = 0.0 }
#expect(windowedSSD(limited, unlimited) > 0, "Anaheim limiter had no effect")
}
@Test func roundTripThroughState() throws {
let pedal: AnaheimAmpPedal = AnaheimAmpPedal()
pedal.bright = 1.0; pedal.deep = 1.0; pedal.limiter = 0.0; pedal.cab = 2.0
let restored: AnaheimAmpPedal = AnaheimAmpPedal()
restored.applyState(pedal.captureState())
#expect(restored.bright == 1.0 && restored.deep == 1.0 && restored.limiter == 0.0 && restored.cab == 2.0)
}
@Test func registeredInBuiltInRegistry() throws {
#expect(PedalRegistry.makePedal(type: "Command") is CommandAmpPedal)
#expect(PedalRegistry.makePedal(type: "Citrus") is CitrusAmpPedal)
#expect(PedalRegistry.makePedal(type: "Sixties Combo") is SixtiesComboAmpPedal)
#expect(PedalRegistry.makePedal(type: "Magna Vibrato") is MagnaVibratoAmpPedal)
#expect(PedalRegistry.makePedal(type: "Anaheim") is AnaheimAmpPedal)
}
}
@@ -92,7 +92,7 @@ struct ChimeTopBoostAmpPedalTests {
@Test func outputStaysWithinCeilingWithFXEngaged() throws { @Test func outputStaysWithinCeilingWithFXEngaged() throws {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
let hot: [Float] = try render { (pedal: ChimeTopBoostAmpPedal) in let hot: [Float] = try render { (pedal: ChimeTopBoostAmpPedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
pedal.brilliant = 1.0 pedal.brilliant = 1.0
@@ -111,7 +111,7 @@ struct ChimeTopBoostAmpPedalTests {
#expect(pedal.effectSwitches.map { $0.label } == ["Brilliant", "Tremolo"]) #expect(pedal.effectSwitches.map { $0.label } == ["Brilliant", "Tremolo"])
#expect(pedal.effectSelectors.map { $0.label } == ["Cab"]) #expect(pedal.effectSelectors.map { $0.label } == ["Cab"])
#expect(pedal.effectSelectors.first?.rebuildsOnChange == true) #expect(pedal.effectSelectors.first?.rebuildsOnChange == true)
#expect(pedal.widthUnits == 3) #expect(pedal.widthUnits == 2)
#expect(pedal.showsMixControl == false) #expect(pedal.showsMixControl == false)
#expect(pedal.toneStackModel == .vox) #expect(pedal.toneStackModel == .vox)
} }
@@ -11,7 +11,7 @@ import LyrebirdUI
@testable import LyrebirdShoeGaze @testable import LyrebirdShoeGaze
@MainActor @MainActor
@Suite("Chime Vox variants") @Suite("Chime variants")
struct ChimeVariantsTests { struct ChimeVariantsTests {
private let sampleRate: Double = 48000.0 private let sampleRate: Double = 48000.0
@@ -71,7 +71,7 @@ struct ChimeVariantsTests {
} }
} }
@Test func inheritCutSurfaceAndVoxStack() throws { @Test func inheritCutSurfaceAndChimeStack() throws {
for v: (name: String, make: () -> ChimeAmpPedal) in variants { for v: (name: String, make: () -> ChimeAmpPedal) in variants {
let pedal: ChimeAmpPedal = v.make() let pedal: ChimeAmpPedal = v.make()
#expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Cut"], "\(v.name) knobs") #expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Cut"], "\(v.name) knobs")
@@ -100,7 +100,7 @@ struct ChimeVariantsTests {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
for v: (name: String, make: () -> ChimeAmpPedal) in variants { for v: (name: String, make: () -> ChimeAmpPedal) in variants {
let hot: [Float] = try render(v.make) { (pedal: ChimeAmpPedal) in let hot: [Float] = try render(v.make) { (pedal: ChimeAmpPedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
pedal.cut = 0.0 pedal.cut = 0.0
@@ -0,0 +1,136 @@
// FactoryRigLibraryTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("FactoryRigLibrary")
struct FactoryRigLibraryTests {
// MARK: - Catalog integrity
@Test func catalogIsWellFormed() {
let rigs: [FactoryRig] = FactoryRigLibrary.all
#expect(rigs.count >= 6, "expected a full starter slate")
let ids: Set<UUID> = Set(rigs.map { $0.id })
#expect(ids.count == rigs.count, "rig ids must be unique")
let names: Set<String> = Set(rigs.map { $0.name })
#expect(names.count == rigs.count, "rig names must be unique")
let minBlurbLength: Int = 20
for rig: FactoryRig in rigs {
#expect(!rig.name.isEmpty, "\(rig.name) has empty name")
#expect(rig.blurb.count >= minBlurbLength, "\(rig.name) blurb too short")
}
// The slate should span more than one sonic family.
let categories: Set<FactoryRigCategory> = Set(rigs.map { $0.category })
#expect(categories.count >= 3, "starter slate should cover several categories")
}
@Test func blurbsAvoidTrademarkedProductNames() {
// Guard against a blurb accidentally naming a real amp/pedal brand: factory rigs describe
// the sound, never a trademarked product.
let forbidden: [String] = [
"marshall", "fender", "vox", "mesa", "boss", "orange", "dumble", "roland", "ibanez",
]
for rig: FactoryRig in FactoryRigLibrary.all {
let haystack: String = (rig.name + " " + rig.blurb).lowercased()
for brand: String in forbidden {
#expect(!haystack.contains(brand), "\(rig.name) mentions '\(brand)'")
}
}
}
@Test func factoryDetectionRecognisesEveryRigAndRejectsOthers() {
let rigs: [FactoryRig] = FactoryRigLibrary.all
#expect(FactoryRigLibrary.factoryIDs.count == rigs.count)
for rig: FactoryRig in rigs {
#expect(FactoryRigLibrary.isFactory(rig.id), "\(rig.name) not recognised as factory")
}
// A freshly generated id is not a factory rig.
#expect(!FactoryRigLibrary.isFactory(UUID()))
}
@Test func categoryLookupAndGroupingCoverEveryRigOnce() {
for rig: FactoryRig in FactoryRigLibrary.all {
#expect(FactoryRigLibrary.category(for: rig.id) == rig.category,
"\(rig.name) category lookup mismatch")
}
#expect(FactoryRigLibrary.category(for: UUID()) == nil, "a random id has no category")
// Each category grouping contains only its own rigs, in catalog order.
for category: FactoryRigCategory in FactoryRigCategory.allCases {
let rigs: [FactoryRig] = FactoryRigLibrary.rigs(in: category)
#expect(rigs.allSatisfy { $0.category == category })
}
// Grouping by every category partitions the catalog exactly (no rig lost or duplicated).
let grouped: [FactoryRig] = FactoryRigCategory.allCases.flatMap { FactoryRigLibrary.rigs(in: $0) }
#expect(grouped.count == FactoryRigLibrary.all.count, "grouping dropped or duplicated a rig")
}
// MARK: - Seeding entries
@Test func makeEntriesMatchesCatalogAndIsStable() throws {
let entries: [RigEntry] = try FactoryRigLibrary.makeEntries()
let rigs: [FactoryRig] = FactoryRigLibrary.all
#expect(entries.count == rigs.count, "one entry per rig")
for (entry, rig): (RigEntry, FactoryRig) in zip(entries, rigs) {
#expect(entry.id == rig.id, "entry id must be the rig's stable id")
#expect(entry.name == rig.name)
// A rig builds either plain boards or a router (or both) — never nothing.
let routerStates: [ChainRouterState] = entry.state.routers ?? []
#expect(!entry.state.boards.isEmpty || !routerStates.isEmpty, "\(rig.name) built nothing")
let boardPedals: Int = entry.state.boards.reduce(0) { $0 + $1.pedals.count }
let routerPedals: Int = routerStates.reduce(0) { $0 + $1.boardA.count + $1.boardB.count }
#expect(boardPedals + routerPedals >= 3, "\(rig.name) should build a non-trivial chain")
}
// Stable ids: re-seeding yields identical ids (so a re-seed overwrites in place).
let again: [RigEntry] = try FactoryRigLibrary.makeEntries()
#expect(entries.map { $0.id } == again.map { $0.id })
}
@Test func entriesRoundTripThroughJSON() throws {
let encoder: JSONEncoder = JSONEncoder()
let decoder: JSONDecoder = JSONDecoder()
for entry: RigEntry in try FactoryRigLibrary.makeEntries() {
let data: Data = try encoder.encode(entry)
let decoded: RigEntry = try decoder.decode(RigEntry.self, from: data)
#expect(decoded == entry, "\(entry.name) did not survive a JSON round-trip")
}
}
// MARK: - Load + render (full ship path)
@Test func everyFactoryEntryLoadsAndRenders() throws {
let renderDuration: Double = 0.2
let numAudioBuses: Int = 128
for entry: RigEntry in try FactoryRigLibrary.makeEntries() {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: renderDuration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let session: ShoeGaze = ShoeGaze(engine: engine)
try session.loadRig(from: entry.state)
try engine.start()
let samples: [Float] = readStereoCAF(url: url)
#expect(hasNonSilentOutput(samples), "\(entry.name) rendered silence")
}
}
}
@@ -58,14 +58,14 @@ struct FullertonDriveAmpPedalTests {
// The value is read at build time (rebuildsOnChange); configure runs before build, so the // The value is read at build time (rebuildsOnChange); configure runs before build, so the
// Drive channel cascades its extra stage. // Drive channel cascades its extra stage.
let clean: [Float] = try render { $0.channel = 0.0 } let clean: [Float] = try render { $0.channel = 0.0 }
let drive: [Float] = try render { $0.channel = 1.0; $0.drive = 15.0 } let drive: [Float] = try render { $0.channel = 1.0; $0.drive = 9.0 }
#expect(hasNonSilentOutput(clean) && hasNonSilentOutput(drive)) #expect(hasNonSilentOutput(clean) && hasNonSilentOutput(drive))
#expect(windowedSSD(clean, drive) > 0, "channel switch had no effect") #expect(windowedSSD(clean, drive) > 0, "channel switch had no effect")
} }
@Test func driveKnobChangesDriveChannel() throws { @Test func driveKnobChangesDriveChannel() throws {
let low: [Float] = try render { $0.channel = 1.0; $0.drive = 2.0 } let low: [Float] = try render { $0.channel = 1.0; $0.drive = 2.0 }
let high: [Float] = try render { $0.channel = 1.0; $0.drive = 25.0 } let high: [Float] = try render { $0.channel = 1.0; $0.drive = 10.5 }
#expect(windowedSSD(low, high) > 0, "Drive knob had no effect on the drive channel") #expect(windowedSSD(low, high) > 0, "Drive knob had no effect on the drive channel")
} }
@@ -87,13 +87,13 @@ struct FullertonDriveAmpPedalTests {
@Test func outputStaysWithinCeilingOnDriveChannel() throws { @Test func outputStaysWithinCeilingOnDriveChannel() throws {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
let hot: [Float] = try render { (pedal: FullertonDriveAmpPedal) in let hot: [Float] = try render { (pedal: FullertonDriveAmpPedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
pedal.reverb = 1.0 pedal.reverb = 1.0
pedal.bright = 1.0 pedal.bright = 1.0
pedal.channel = 1.0 pedal.channel = 1.0
pedal.drive = 30.0 pedal.drive = 11.0
} }
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) } let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + ceilingEpsilon, "peak \(peak) exceeds the ±1 ceiling on the drive channel") #expect(peak <= 1.0 + ceilingEpsilon, "peak \(peak) exceeds the ±1 ceiling on the drive channel")
@@ -105,20 +105,20 @@ struct FullertonDriveAmpPedalTests {
#expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Reverb", "Drive"]) #expect(pedal.effectKnobs.map { $0.label } == ["Gain", "Bass", "Mid", "Treble", "Reverb", "Drive"])
#expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Channel"]) #expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Channel"])
#expect(pedal.effectSelectors.map { $0.label } == ["Cab"]) #expect(pedal.effectSelectors.map { $0.label } == ["Cab"])
#expect(pedal.widthUnits == 3) #expect(pedal.widthUnits == 2)
#expect(pedal.toneStackModel == .fender) #expect(pedal.toneStackModel == .fender)
} }
@Test func controlsRoundTripThroughState() throws { @Test func controlsRoundTripThroughState() throws {
let pedal: FullertonDriveAmpPedal = FullertonDriveAmpPedal() let pedal: FullertonDriveAmpPedal = FullertonDriveAmpPedal()
pedal.reverb = 0.6 pedal.reverb = 0.6
pedal.drive = 12.0 pedal.drive = 8.3
pedal.bright = 1.0 pedal.bright = 1.0
pedal.channel = 1.0 pedal.channel = 1.0
pedal.cab = 2.0 pedal.cab = 2.0
let restored: FullertonDriveAmpPedal = FullertonDriveAmpPedal() let restored: FullertonDriveAmpPedal = FullertonDriveAmpPedal()
restored.applyState(pedal.captureState()) restored.applyState(pedal.captureState())
#expect(restored.reverb == 0.6 && restored.drive == 12.0) #expect(restored.reverb == 0.6 && restored.drive == 8.3)
#expect(restored.bright == 1.0 && restored.channel == 1.0 && restored.cab == 2.0) #expect(restored.bright == 1.0 && restored.channel == 1.0 && restored.cab == 2.0)
} }
@@ -103,7 +103,7 @@ struct FullertonReverbAmpPedalTests {
@Test func outputStaysWithinCeilingWithFXEngaged() throws { @Test func outputStaysWithinCeilingWithFXEngaged() throws {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
let hot: [Float] = try render { (pedal: FullertonReverbAmpPedal) in let hot: [Float] = try render { (pedal: FullertonReverbAmpPedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
pedal.reverb = 1.0 pedal.reverb = 1.0
@@ -123,7 +123,7 @@ struct FullertonReverbAmpPedalTests {
#expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Reverb FX", "Vibrato"]) #expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Reverb FX", "Vibrato"])
#expect(pedal.effectSelectors.map { $0.label } == ["Cab"]) #expect(pedal.effectSelectors.map { $0.label } == ["Cab"])
#expect(pedal.effectSelectors.first?.rebuildsOnChange == true) #expect(pedal.effectSelectors.first?.rebuildsOnChange == true)
#expect(pedal.widthUnits == 3) #expect(pedal.widthUnits == 2)
#expect(pedal.showsMixControl == false) #expect(pedal.showsMixControl == false)
#expect(pedal.toneStackModel == .fender) #expect(pedal.toneStackModel == .fender)
} }
@@ -51,7 +51,7 @@ struct FullertonVariantsTests {
private let variants: [(name: String, make: () -> FullertonReverbAmpPedal)] = [ private let variants: [(name: String, make: () -> FullertonReverbAmpPedal)] = [
("Fullerton Deluxe", { FullertonDeluxeAmpPedal() }), ("Fullerton Deluxe", { FullertonDeluxeAmpPedal() }),
("Fullerton Princeton", { FullertonPrincetonAmpPedal() }), ("Fullerton Ivy League", { FullertonPrincetonAmpPedal() }),
] ]
@Test func bothBuildNonSilentFinite() throws { @Test func bothBuildNonSilentFinite() throws {
@@ -86,7 +86,7 @@ struct FullertonVariantsTests {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
for v: (name: String, make: () -> FullertonReverbAmpPedal) in variants { for v: (name: String, make: () -> FullertonReverbAmpPedal) in variants {
let hot: [Float] = try render(v.make) { (pedal: FullertonReverbAmpPedal) in let hot: [Float] = try render(v.make) { (pedal: FullertonReverbAmpPedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
pedal.reverb = 1.0 pedal.reverb = 1.0
@@ -105,7 +105,7 @@ struct FullertonVariantsTests {
== ["Gain", "Bass", "Mid", "Treble", "Reverb", "Speed", "Intensity"], "\(v.name) knobs") == ["Gain", "Bass", "Mid", "Treble", "Reverb", "Speed", "Intensity"], "\(v.name) knobs")
#expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Reverb FX", "Vibrato"], "\(v.name) switches") #expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Reverb FX", "Vibrato"], "\(v.name) switches")
#expect(pedal.effectSelectors.map { $0.label } == ["Cab"], "\(v.name) selectors") #expect(pedal.effectSelectors.map { $0.label } == ["Cab"], "\(v.name) selectors")
#expect(pedal.widthUnits == 3, "\(v.name) width") #expect(pedal.widthUnits == 2, "\(v.name) width")
#expect(pedal.toneStackModel == .fender, "\(v.name) tone stack") #expect(pedal.toneStackModel == .fender, "\(v.name) tone stack")
#expect(pedal.powerAmpOversample == 4, "\(v.name) should oversample the harder-driven power amp at 4×") #expect(pedal.powerAmpOversample == 4, "\(v.name) should oversample the harder-driven power amp at 4×")
} }
@@ -122,6 +122,13 @@ struct FullertonVariantsTests {
@Test func registeredInBuiltInRegistry() throws { @Test func registeredInBuiltInRegistry() throws {
#expect(PedalRegistry.makePedal(type: "Fullerton Deluxe") is FullertonDeluxeAmpPedal) #expect(PedalRegistry.makePedal(type: "Fullerton Deluxe") is FullertonDeluxeAmpPedal)
#expect(PedalRegistry.makePedal(type: "Fullerton Ivy League") is FullertonPrincetonAmpPedal)
}
@Test func legacyPrincetonNameStillResolves() throws {
// The pedal's display name was "Fullerton Princeton" when first shipped; rigs saved then key
// on that string. The legacy alias must still reconstruct the (renamed) pedal so it isn't
// silently dropped on load.
#expect(PedalRegistry.makePedal(type: "Fullerton Princeton") is FullertonPrincetonAmpPedal) #expect(PedalRegistry.makePedal(type: "Fullerton Princeton") is FullertonPrincetonAmpPedal)
} }
} }
@@ -127,7 +127,7 @@ struct JazzCleanAmpPedalTests {
// Channel is read at build time (rebuildsOnChange); configure runs before build, so the // Channel is read at build time (rebuildsOnChange); configure runs before build, so the
// Distortion channel cascades its extra gain stage. // Distortion channel cascades its extra gain stage.
let clean: [Float] = try renderStereo { $0.channel = 0.0 }.left let clean: [Float] = try renderStereo { $0.channel = 0.0 }.left
let dist: [Float] = try renderStereo { $0.channel = 1.0; $0.drive = 18.0 }.left let dist: [Float] = try renderStereo { $0.channel = 1.0; $0.drive = 9.5 }.left
#expect(windowedSSD(clean, dist) > 0, "distortion channel had no effect") #expect(windowedSSD(clean, dist) > 0, "distortion channel had no effect")
let channel: PedalSwitch? = JazzCleanAmpPedal().effectSwitches.first { $0.label == "Channel" } let channel: PedalSwitch? = JazzCleanAmpPedal().effectSwitches.first { $0.label == "Channel" }
#expect(channel?.rebuildsOnChange == true, "Channel switch should rebuild on change") #expect(channel?.rebuildsOnChange == true, "Channel switch should rebuild on change")
@@ -136,7 +136,7 @@ struct JazzCleanAmpPedalTests {
@Test func bothChannelsStayWithinCeilingWithFXEngaged() throws { @Test func bothChannelsStayWithinCeilingWithFXEngaged() throws {
let ceilingEpsilon: Double = 1.0e-4 let ceilingEpsilon: Double = 1.0e-4
let (left, right): ([Float], [Float]) = try renderStereo { (pedal: JazzCleanAmpPedal) in let (left, right): ([Float], [Float]) = try renderStereo { (pedal: JazzCleanAmpPedal) in
pedal.gain = 30.0 pedal.gain = 11.0
pedal.bass = 1.0 pedal.bass = 1.0
pedal.treble = 1.0 pedal.treble = 1.0
pedal.reverb = 1.0 pedal.reverb = 1.0
@@ -155,7 +155,7 @@ struct JazzCleanAmpPedalTests {
#expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Chorus", "Channel"]) #expect(pedal.effectSwitches.map { $0.label } == ["Bright", "Chorus", "Channel"])
#expect(pedal.effectSelectors.map { $0.label } == ["Cab"]) #expect(pedal.effectSelectors.map { $0.label } == ["Cab"])
#expect(pedal.effectSelectors.first?.rebuildsOnChange == true) #expect(pedal.effectSelectors.first?.rebuildsOnChange == true)
#expect(pedal.widthUnits == 3) #expect(pedal.widthUnits == 2)
#expect(pedal.showsMixControl == false) #expect(pedal.showsMixControl == false)
#expect(pedal.channelKind == .widener, "Jazz Clean should be a stereo widener") #expect(pedal.channelKind == .widener, "Jazz Clean should be a stereo widener")
#expect(pedal.toneStackModel == .fender) #expect(pedal.toneStackModel == .fender)
@@ -0,0 +1,147 @@
// ModernHighGainAmpPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("ModernHighGainAmpPedal")
struct ModernHighGainAmpPedalTests {
private let sampleRate: Double = 48000.0
private func render(configure: (ModernHighGainAmpPedal) -> Void = { _ in }) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.3, sampleRate: sampleRate, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: ModernHighGainAmpPedal = ModernHighGainAmpPedal(inputBus: srcBus.index, outputBus: dstBus.index)
pedal.sampleRate = sampleRate
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url, sampleRate: sampleRate)
}
private func windowedSSD(_ a: [Float], _ b: [Float], skip: Int = 4096, window: Int = 4096) -> Double {
guard a.count >= skip + window, b.count >= skip + window else { return 0.0 }
return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1); return acc + d * d
}
}
@Test func buildsNonSilentFiniteWithinCeiling() throws {
let hot: [Float] = try render { (p: ModernHighGainAmpPedal) in
p.gain = 11.0; p.bass = 1.0; p.treble = 1.0; p.master = 1.0; p.channel = 1.0
p.drive = 11.0; p.sag = 1.0; p.tight = 1.0
}
#expect(hasNonSilentOutput(hot) && hot.allSatisfy { $0.isFinite })
let peak: Double = hot.reduce(0.0) { Swift.max($0, abs(Double($1))) }
#expect(peak <= 1.0 + 1.0e-4, "Modern High-Gain exceeds the ±1 ceiling: \(peak)")
}
@Test func sagChangesOutput() throws {
let stiff: [Float] = try render { $0.gain = 9.8; $0.channel = 1.0; $0.sag = 0.0 }
let saggy: [Float] = try render { $0.gain = 9.8; $0.channel = 1.0; $0.sag = 1.0 }
#expect(windowedSSD(stiff, saggy) > 0, "Sag had no effect")
}
@Test func sagAttenuatesWithoutPhaseInversion() throws {
// With Presence/Depth maxed the shelf boosts push the sag envelope above 1; the sag gain
// must stay positive (attenuation), never go negative (phase inversion). Assert the sag'd
// output correlates positively with the stiff one (not an inverted copy).
let cfg: (ModernHighGainAmpPedal) -> Void = { (p: ModernHighGainAmpPedal) in
p.gain = 9.8; p.channel = 1.0; p.presence = 1.0; p.depth = 1.0
}
let stiff: [Float] = try render { cfg($0); $0.sag = 0.0 }
let saggy: [Float] = try render { cfg($0); $0.sag = 1.0 }
let skip: Int = 4096, window: Int = 4096
guard stiff.count >= skip + window, saggy.count >= skip + window else {
Issue.record("render too short"); return
}
// Unnormalized dot product — its sign is what matters: negative ⇒ phase-inverted copy.
let dotProduct: Double = zip(stiff[skip..<(skip + window)], saggy[skip..<(skip + window)])
.reduce(0.0) { acc, pair in acc + Double(pair.0) * Double(pair.1) }
#expect(dotProduct > 0, "sag phase-inverted the signal (dot product \(dotProduct) < 0)")
}
@Test func tightSwitchChangesOutput() throws {
let loose: [Float] = try render { $0.tight = 0.0 }
let tight: [Float] = try render { $0.tight = 1.0 }
#expect(windowedSSD(loose, tight) > 0, "Tight switch had no effect")
}
@Test func channelSwitchInherited() throws {
let clean: [Float] = try render { $0.channel = 0.0 }
let lead: [Float] = try render { $0.channel = 1.0 }
#expect(windowedSSD(clean, lead) > 0, "channel switch had no effect")
let channel: PedalSwitch? = ModernHighGainAmpPedal().effectSwitches.first { $0.label == "Channel" }
#expect(channel?.rebuildsOnChange == true)
}
@Test func exposesControlSurface() throws {
let pedal: ModernHighGainAmpPedal = ModernHighGainAmpPedal()
// Sag now lives in the shared advanced pop-over (with Bias), not on the pedal face.
#expect(pedal.effectKnobs.map { $0.label }
== ["Gain", "Bass", "Mid", "Treble", "Presence", "Depth", "Master", "Drive"])
#expect(pedal.advancedKnobs.map { $0.label } == ["Sag", "Bias", "Bias X"])
#expect(pedal.effectSwitches.map { $0.label } == ["Channel", "Tight"])
#expect(pedal.widthUnits == 2)
#expect(pedal.toneStackModel == .mesa)
#expect(pedal.sag == 0.3, "Modern High-Gain keeps rectifier sag on by default")
}
@Test func controlsRoundTripThroughState() throws {
let pedal: ModernHighGainAmpPedal = ModernHighGainAmpPedal()
pedal.sag = 0.8; pedal.tight = 1.0; pedal.channel = 1.0
pedal.drive = 9.8; pedal.master = 0.7; pedal.cab = 2.0
let restored: ModernHighGainAmpPedal = ModernHighGainAmpPedal()
restored.applyState(pedal.captureState())
#expect(restored.sag == 0.8 && restored.tight == 1.0 && restored.channel == 1.0)
#expect(restored.drive == 9.8 && restored.master == 0.7 && restored.cab == 2.0)
}
@Test func registeredInBuiltInRegistry() throws {
#expect(PedalRegistry.makePedal(type: "Modern High-Gain") is ModernHighGainAmpPedal)
}
@Test func legacyPresetWithSagOnFaceMigratesWithoutShiftingMixLevel() throws {
// A rig saved when Sag was the 9th face knob has 11 knobValues (Gain…Drive, Sag, Mix, Level)
// and no advancedValues. Sag has since moved to the advanced pop-over, so the current shape
// has 10 knobValues (Gain…Drive, Mix, Level) + 2 advancedValues (Sag, Bias). Loading the
// legacy preset must lift Sag into advancedValues and keep Mix/Level in place — never shift
// the old Sag onto Mix or the old Mix onto Level.
let legacy: PedalState = PedalState(
id: UUID(),
type: "Modern High-Gain",
knobValues: [10.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 15.0, 0.7, 0.8, 0.9],
bypass: 0.0
)
let pedal: ModernHighGainAmpPedal = ModernHighGainAmpPedal()
pedal.applyState(legacy)
let restored: PedalState = pedal.captureState()
// Gain…Drive, then Mix (0.8), Level (0.9) — the old Sag (0.7) is gone from knobValues.
#expect(restored.knobValues == [10.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 15.0, 0.8, 0.9],
"legacy Sag shifted Mix/Level: \(restored.knobValues)")
// Sag lifted into advanced slot 0; Bias (0.5) and Bias X (0.0) had no legacy value → defaults.
#expect(restored.advancedValues == [0.7, 0.5, 0.0],
"Sag/Bias/Bias X advanced values wrong: \(restored.advancedValues)")
}
}
@@ -100,28 +100,110 @@ struct MutantPedalTests {
pedal.mode = 2.0 // highpass pedal.mode = 2.0 // highpass
pedal.direction = 0.0 // down pedal.direction = 0.0 // down
pedal.range = 1.0 // high band
pedal.sweep = 12.0
pedal.attack = 0.02
pedal.release = 0.3
let state: PedalState = pedal.captureState() let state: PedalState = pedal.captureState()
#expect(state.switchValues == [0.0, 2.0]) // [direction, mode] #expect(state.switchValues == [0.0, 2.0, 1.0]) // [direction, mode, range]
#expect(state.advancedValues == [12.0, 0.02, 0.3]) // [sweep, attack, release]
let restored: MutantPedal = MutantPedal() let restored: MutantPedal = MutantPedal()
restored.applyState(state) restored.applyState(state)
#expect(restored.mode == 2.0) #expect(restored.mode == 2.0)
#expect(restored.direction == 0.0) #expect(restored.direction == 0.0)
#expect(restored.range == 1.0)
#expect(restored.sweep == 12.0)
#expect(restored.attack == 0.02)
#expect(restored.release == 0.3)
}
@Test func oldTwoSwitchStateStillLoads() throws {
// A rig saved before Range / the advanced knobs existed carries only [direction, mode] and
// an empty advancedValues; it must load without mis-mapping, leaving the new controls at
// their defaults.
let legacy: PedalState = PedalState(
type: "Mutant",
knobValues: [2.5, 4.0, 1, 1], // sensitivity, resonance, mix, level
switchValues: [1.0, 0.0], // direction=up, mode=lowpass
bypass: 0
)
let pedal: MutantPedal = MutantPedal()
pedal.applyState(legacy)
#expect(pedal.direction == 1.0)
#expect(pedal.mode == 0.0)
#expect(pedal.sensitivity == 2.5)
#expect(pedal.resonance == 4.0)
// New controls keep their defaults.
#expect(pedal.range == 0.0)
#expect(pedal.sweep == 20.0)
} }
@Test func exposesSensitivityAndResonanceKnobs() throws { @Test func exposesSensitivityAndResonanceKnobs() throws {
let pedal: MutantPedal = MutantPedal() let pedal: MutantPedal = MutantPedal()
let labels: [String] = pedal.effectKnobs.map { $0.label } #expect(pedal.effectKnobs.map { $0.label } == ["Sensitivity", "Resonance"])
#expect(labels == ["Sensitivity", "Resonance"]) #expect(pedal.advancedKnobs.map { $0.label } == ["Sweep", "Attack", "Release"])
} }
@Test func exposesTwoStateSweepAndThreeStateModeSwitches() throws { @Test func exposesDirectionModeAndRangeSwitches() throws {
let pedal: MutantPedal = MutantPedal() let pedal: MutantPedal = MutantPedal()
let switches: [PedalSwitch] = pedal.effectSwitches let switches: [PedalSwitch] = pedal.effectSwitches
#expect(switches.map { $0.label } == ["Sweep", "Mode"]) #expect(switches.map { $0.label } == ["Direction", "Mode", "Range"])
// Two-state sweep (Down/Up), three-state mode (LP/BP/HP). #expect(switches[0].options.map { $0.title } == ["Down", "Up"])
#expect(switches.first?.options.map { $0.title } == ["Down", "Up"]) #expect(switches[1].options.map { $0.title } == ["LP", "BP", "HP"])
#expect(switches.last?.options.map { $0.title } == ["LP", "BP", "HP"]) #expect(switches[2].options.map { $0.title } == ["Lo", "Hi"])
}
/// Renders the test loop through a Mutant configured by `configure`, returning a mid-render window.
private func renderWindow(configure: (MutantPedal) -> Void) throws -> [Float] {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 64)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: MutantPedal = MutantPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
private func windowSSD(_ a: [Float], _ b: [Float]) -> Double {
let skip: Int = 1024
let window: Int = 2048
guard a.count >= skip + window, b.count >= skip + window else { return 0 }
return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1)
return acc + d * d
}
}
@Test func sweepAmountChangesOutput() throws {
let narrow: [Float] = try renderWindow { $0.sweep = 3.0 }
let wide: [Float] = try renderWindow { $0.sweep = 45.0 }
#expect(hasNonSilentOutput(narrow))
#expect(hasNonSilentOutput(wide))
#expect(windowSSD(narrow, wide) > 0, "sweep amount did not change output")
}
@Test func rangeSwitchChangesOutput() throws {
let low: [Float] = try renderWindow { $0.range = 0.0 }
let high: [Float] = try renderWindow { $0.range = 1.0 }
#expect(windowSSD(low, high) > 0, "range band did not change output")
}
@Test func attackReleaseChangesOutput() throws {
let fast: [Float] = try renderWindow { $0.attack = 0.001; $0.release = 0.03 }
let slow: [Float] = try renderWindow { $0.attack = 0.06; $0.release = 0.5 }
#expect(windowSSD(fast, slow) > 0, "attack/release did not change output")
} }
@Test func sweepDirectionChangesOutput() throws { @Test func sweepDirectionChangesOutput() throws {
@@ -113,8 +113,10 @@ struct NeuralAmpPedalTests {
#expect(pedal.effectKnobs.map { $0.label } == ["Gain"]) #expect(pedal.effectKnobs.map { $0.label } == ["Gain"])
} }
@Test func registeredInBuiltInRegistry() throws { @Test func notRegisteredWhileHidden() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "Neural Amp") // Neural Amp is intentionally not in the palette/registry for now (unresolved security-scoped
#expect(pedal is NeuralAmpPedal) // model-file access); the class + UI are kept for later iteration. Re-add to
// PedalRegistry.builtIn + PedalPaletteView.preferredOrder to re-enable.
#expect(PedalRegistry.makePedal(type: "Neural Amp") == nil)
} }
} }
@@ -89,4 +89,85 @@ struct NoiseGatePedalTests {
let samples: [Float] = try render(threshold: 0.95, floor: 1.0) let samples: [Float] = try render(threshold: 0.95, floor: 1.0)
#expect(hasNonSilentOutput(samples), "Unity-floor gate muted the signal") #expect(hasNonSilentOutput(samples), "Unity-floor gate muted the signal")
} }
/// A sine that steps from loud (0.3, gate open) down to a constant below-threshold level (0.03)
/// over 50 ms and holds there — so the gate opens, then closes, while the source level stays
/// constant. That isolates the gate's close fade (release-dependent) from any source decay.
/// `Line` holds its `end` value after `dur`, giving the sustained low tail.
private final class DecaySineSource: SynthesizerBase {
private let bus: Int
init(bus: Int) { self.bus = bus; super.init() }
override func build() {
output(bus: bus, source: OscSin.Audio(freq: 220.0) * Line.Control(start: 0.3, end: 0.03, dur: 0.05))
}
}
/// Energy in the gate's *close window* — the source steps down through the threshold ~50 ms in
/// then holds a constant below-threshold level, so the output energy after that reflects only how
/// long the gate lingers before it finishes fading shut. A longer `release` = more lingering
/// energy; a snap close = little. (floor 0, so once fully closed the tail is silent.)
private func closeWindowEnergy(release: Double) throws -> Double {
let sampleRate: Double = 48000.0
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.6, sampleRate: sampleRate)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer { engine.busAllocator.releaseAudioBus(srcBus); engine.busAllocator.releaseAudioBus(dstBus) }
let source: DecaySineSource = DecaySineSource(bus: srcBus.index)
let gate: NoiseGatePedal = NoiseGatePedal(inputBus: srcBus.index, outputBus: dstBus.index)
gate.sampleRate = sampleRate
gate.threshold = 0.06
gate.floor = 0.0
gate.release = release
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(gate, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(gate))
try engine.start()
let inter: [Float] = readStereoCAF(url: url, sampleRate: sampleRate)
let mono: [Double] = stride(from: 0, to: inter.count, by: 2).map { Double(inter[$0]) }
let start: Int = Int(0.12 * sampleRate) // after the step-down; the gate is closing/closed
var energy: Double = 0.0
for i: Int in start..<mono.count { energy += mono[i] * mono[i] }
return energy
}
@Test func releaseTunesCloseTime() throws {
// A long Release lets the gate linger (more energy through the close) vs a short Release that
// snaps shut — and the shipped default (0.08) lingers well past a near-instant close, so the
// gate fades rather than pops. Guards both the Release control and the pop fix.
let fast: Double = try closeWindowEnergy(release: 0.02)
let slow: Double = try closeWindowEnergy(release: 0.4)
let deflt: Double = try closeWindowEnergy(release: 0.08)
#expect(slow > fast * 1.5, "long Release did not linger longer than short (fast=\(fast) slow=\(slow))")
#expect(deflt > fast * 1.2, "default close is nearly as abrupt as the fast close (\(deflt) vs \(fast))")
}
@Test func exposesAttackReleaseInAdvancedPopover() throws {
#expect(NoiseGatePedal().advancedKnobs.map { $0.label } == ["Attack", "Release"])
// Attack/Release are pop-over only — not on the face.
let face: [String] = NoiseGatePedal().effectKnobs.map { $0.label }
#expect(face == ["Threshold", "Floor"])
}
@Test func attackReleaseRoundTripThroughState() throws {
let pedal: NoiseGatePedal = NoiseGatePedal()
pedal.attack = 0.02
pedal.release = 0.3
let restored: NoiseGatePedal = NoiseGatePedal()
restored.applyState(pedal.captureState())
#expect(restored.attack == 0.02 && restored.release == 0.3, "Attack/Release did not round-trip")
}
@Test func legacyGateWithoutAdvancedValuesDefaultsTiming() throws {
// A gate saved before Attack/Release existed has empty advancedValues → timing defaults, and
// Threshold/Floor still restore correctly (append-only, no migration).
let legacy: PedalState = PedalState(
id: UUID(), type: "Noise Gate",
knobValues: [0.03, 0.4, 1.0, 0.7], selectorValues: [], advancedValues: [], bypass: 0.0)
let pedal: NoiseGatePedal = NoiseGatePedal()
pedal.applyState(legacy)
#expect(pedal.threshold == 0.03 && pedal.floor == 0.4, "legacy Threshold/Floor mis-mapped")
#expect(pedal.attack == 0.005 && pedal.release == 0.08, "legacy gate should default Attack/Release")
}
} }
+75 -22
View File
@@ -422,11 +422,36 @@ struct PresetTests {
try sg.loadRig(from: presetURL) try sg.loadRig(from: presetURL)
#expect(abs(sg.clock.bpm - savedBpm) < 1e-9, "bpm should restore to \(savedBpm)") #expect(abs(sg.clock.bpm - savedBpm) < 1e-9, "bpm should restore to \(savedBpm)")
#expect(sg.tempoEnabled == false, "tempoEnabled should restore to false") #expect(sg.tempoEnabled == false, "tempoEnabled should restore to false")
#expect(sg.inputSource == .testLoop, "input source should restore to test loop") // Input is a live session setting, not part of the recalled rig: the session was on the test
// loop and stays there (load never changes the current input).
#expect(sg.inputSource == .testLoop, "load leaves the current input source unchanged")
} }
@Test func liveInputSourcePersistsAndFallsBackWhenChannelMissing() throws { @Test func rigContentComparisonIgnoresInputAndChannels() throws {
// Engine WITH an input channel: a live-input rig round-trips its source. let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05, numInputChannels: 1, numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
let board: PedalBoard = try sg.addBoard()
try board.add(FuzzPedal())
try sg.finalizeBoard(board)
let saved: ShoeGazeState = sg.captureState()
// Changing only the live input source must NOT read as a rig change (the source of the
// spurious "save changes?" prompt when switching starter rigs).
sg.inputSource = .liveInput(channel: 0)
let afterInputChange: ShoeGazeState = sg.captureState()
#expect(afterInputChange.hasSameRigContent(as: saved), "input change must not be a rig change")
#expect(afterInputChange != saved, "but the raw snapshots still differ on the input field")
// A genuine graph difference IS a content change.
let emptyRig: ShoeGazeState = ShoeGazeState(boards: [])
#expect(!saved.hasSameRigContent(as: emptyRig), "different boards must count as a rig change")
}
@Test func loadPreservesCurrentInputSourceNotTheSavedOne() throws {
// A rig captured with live input still RECORDS its source in the snapshot...
let (engineIn, urlIn): (SynthesisEngine, URL) = makeNRTEngine( let (engineIn, urlIn): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1, duration: 0.1,
numInputChannels: 1, numInputChannels: 1,
@@ -434,29 +459,57 @@ struct PresetTests {
) )
defer { try? FileManager.default.removeItem(at: urlIn) } defer { try? FileManager.default.removeItem(at: urlIn) }
let sgIn: ShoeGaze = ShoeGaze(engine: engineIn, inputSource: .liveInput(channel: 0)) let sgIn: ShoeGaze = ShoeGaze(engine: engineIn, inputSource: .liveInput(channel: 0))
let board: PedalBoard = try sgIn.addBoard() let liveBoard: PedalBoard = try sgIn.addBoard()
try board.add(OverdrivePedal()) try liveBoard.add(OverdrivePedal())
try sgIn.finalizeBoard(board) try sgIn.finalizeBoard(liveBoard)
let liveState: ShoeGazeState = sgIn.captureState()
#expect(liveState.inputSource == .liveInput(channel: 0), "capture records the live input")
let state: ShoeGazeState = sgIn.captureState() // ...but loading a rig NEVER switches the session's current input — switching rigs keeps
#expect(state.inputSource == .liveInput(channel: 0), "capture should record the live input") // whatever input the player has chosen. Here a test-loop session loads a live-input rig on an
// engine that DOES have the channel: under the old "restore saved input" behaviour this would
// Reload into the same input-capable engine: source preserved. // become live input; the new behaviour leaves it on the test loop.
try sgIn.loadRig(from: state) let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
#expect(sgIn.inputSource == .liveInput(channel: 0), "live input should round-trip")
// loadRig does NOT auto-apply the saved channel layout, so loading into an engine with no
// input channels falls back to the test loop rather than clobbering the engine's config.
let (engineNoIn, urlNoIn): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1, duration: 0.1,
numInputChannels: 0, numInputChannels: 1,
numAudioBuses: 128 numAudioBuses: 128
) )
defer { try? FileManager.default.removeItem(at: urlNoIn) } defer { try? FileManager.default.removeItem(at: urlA) }
let sgNoIn: ShoeGaze = ShoeGaze(engine: engineNoIn) let sgA: ShoeGaze = ShoeGaze(engine: engineA) // defaults to .testLoop
try sgNoIn.loadRig(from: state) try sgA.loadRig(from: liveState, keepingCurrentInput: true)
#expect(engineNoIn.numInputChannels == 0, "loadRig must not reconfigure the engine's I/O") #expect(sgA.inputSource == .testLoop, "switch must keep the current input, not adopt the rig's")
#expect(sgNoIn.inputSource == .testLoop, "missing channel should fall back to test loop")
// The reverse: a live-input session loading a test-loop rig stays on live input.
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1,
numInputChannels: 1,
numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlB) }
let sgTestLoop: ShoeGaze = ShoeGaze(engine: engineB) // .testLoop
let plainBoard: PedalBoard = try sgTestLoop.addBoard()
try plainBoard.add(OverdrivePedal())
try sgTestLoop.finalizeBoard(plainBoard)
let testLoopState: ShoeGazeState = sgTestLoop.captureState()
#expect(testLoopState.inputSource == .testLoop)
sgIn.currentRigID = nil
try sgIn.loadRig(from: testLoopState, keepingCurrentInput: true)
#expect(sgIn.inputSource == .liveInput(channel: 0),
"switch must keep the current live input, not adopt the rig's test loop")
// A default load (file open / launch restore) still applies the rig's saved input.
let (engineC, urlC): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.1, numInputChannels: 1, numAudioBuses: 128
)
defer { try? FileManager.default.removeItem(at: urlC) }
let sgDefault: ShoeGaze = ShoeGaze(engine: engineC) // .testLoop
try sgDefault.loadRig(from: liveState) // default: restore saved input
#expect(sgDefault.inputSource == .liveInput(channel: 0),
"a default load restores the rig's saved input")
// loadRig still never reconfigures the engine's channel layout.
#expect(engineA.numInputChannels == 1, "loadRig must not reconfigure the engine's I/O")
} }
@Test func channelCountsPersistButLoadDoesNotReconfigure() throws { @Test func channelCountsPersistButLoadDoesNotReconfigure() throws {
@@ -0,0 +1,100 @@
// SustainFuzzPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("SustainFuzzPedal")
struct SustainFuzzPedalTests {
/// Renders the test loop through a sustain-fuzz configured by `configure`, returning stereo samples.
private func render(configure: (SustainFuzzPedal) -> Void) throws -> [Float] {
let renderDuration: Double = 0.2
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: SustainFuzzPedal = SustainFuzzPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
/// Sum of squared differences over a mid-render window, guarding on length.
private func windowSSD(_ a: [Float], _ b: [Float]) -> Double {
let skip: Int = 1024
let window: Int = 2048
guard a.count >= skip + window, b.count >= skip + window else { return 0 }
let aw: ArraySlice<Float> = a[skip..<(skip + window)]
let bw: ArraySlice<Float> = b[skip..<(skip + window)]
return zip(aw, bw).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1)
return acc + d * d
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render { _ in }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "SustainFuzzPedal produced silence")
}
@Test func sustainChangesOutput() throws {
let low: [Float] = try render { $0.sustain = 2.0 }
let high: [Float] = try render { $0.sustain = 25.0 }
#expect(hasNonSilentOutput(low))
#expect(hasNonSilentOutput(high))
#expect(windowSSD(low, high) > 0, "sustain did not change output")
}
@Test func toneChangesOutput() throws {
let dark: [Float] = try render { $0.tone = 900.0 }
let bright: [Float] = try render { $0.tone = 5500.0 }
#expect(windowSSD(dark, bright) > 0, "tone did not change output")
}
@Test func scoopChangesOutput() throws {
let flat: [Float] = try render { $0.scoop = 0.0 }
let scooped: [Float] = try render { $0.scoop = 16.0 }
#expect(windowSSD(flat, scooped) > 0, "scoop did not change output")
}
@Test func exposesSustainToneScoopKnobs() {
let pedal: SustainFuzzPedal = SustainFuzzPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Sustain", "Tone", "Scoop"])
}
@Test func stateRoundTripsThroughPreset() {
let pedal: SustainFuzzPedal = SustainFuzzPedal()
pedal.sustain = 18.0
pedal.tone = 3200.0
pedal.scoop = 12.0
let state: PedalState = pedal.captureState()
let restored: SustainFuzzPedal = SustainFuzzPedal()
restored.applyState(state)
#expect(restored.sustain == 18.0)
#expect(restored.tone == 3200.0)
#expect(restored.scoop == 12.0)
}
}
@@ -0,0 +1,104 @@
// VibePedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("VibePedal")
struct VibePedalTests {
/// Renders the test loop through a vibe pedal configured by `configure`, returning stereo samples.
private func render(configure: (VibePedal) -> Void) throws -> [Float] {
let renderDuration: Double = 0.2
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
let pedal: VibePedal = VibePedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
/// Sum of squared differences over a mid-render window, guarding on length.
private func windowSSD(_ a: [Float], _ b: [Float]) -> Double {
let skip: Int = 1024
let window: Int = 2048
guard a.count >= skip + window, b.count >= skip + window else { return 0 }
let aw: ArraySlice<Float> = a[skip..<(skip + window)]
let bw: ArraySlice<Float> = b[skip..<(skip + window)]
return zip(aw, bw).reduce(0.0) { acc, pair in
let d: Double = Double(pair.0 - pair.1)
return acc + d * d
}
}
@Test func buildsAndProducesNonSilentOutput() throws {
let samples: [Float] = try render { _ in }
#expect(!samples.isEmpty)
#expect(hasNonSilentOutput(samples), "VibePedal produced silence")
}
@Test func speedChangesOutput() throws {
let slow: [Float] = try render { $0.speed = 1.0 }
let fast: [Float] = try render { $0.speed = 8.0 }
#expect(hasNonSilentOutput(slow))
#expect(hasNonSilentOutput(fast))
#expect(windowSSD(slow, fast) > 0, "vibe speed did not change output")
}
@Test func intensityChangesOutput() throws {
let shallow: [Float] = try render { $0.intensity = 0.1 }
let deep: [Float] = try render { $0.intensity = 0.7 }
#expect(windowSSD(shallow, deep) > 0, "vibe intensity did not change output")
}
@Test func modeChangesOutput() throws {
let chorus: [Float] = try render { $0.mode = 0.0 }
let vibrato: [Float] = try render { $0.mode = 1.0 }
#expect(hasNonSilentOutput(chorus))
#expect(hasNonSilentOutput(vibrato))
#expect(windowSSD(chorus, vibrato) > 0, "chorus and vibrato modes produced identical output")
}
@Test func exposesSpeedIntensityKnobsAndModeSwitch() {
let pedal: VibePedal = VibePedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Speed", "Intensity"])
#expect(pedal.effectSwitches.map { $0.label } == ["Mode"])
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Chorus", "Vibrato"])
}
@Test func stateRoundTripsThroughPreset() {
let pedal: VibePedal = VibePedal()
pedal.speed = 6.5
pedal.intensity = 0.42
pedal.mode = 1.0
let state: PedalState = pedal.captureState()
let restored: VibePedal = VibePedal()
restored.applyState(state)
#expect(restored.speed == 6.5)
#expect(restored.intensity == 0.42)
#expect(restored.mode == 1.0)
}
}