5 Commits

Author SHA1 Message Date
josh e1ed4e348c fix(cab): NaN-safe selector compare; correct applyState doc contract
Re-review follow-ups:
- rebuildSelectorValues sanitizes non-finite node values to a sentinel so the
  before/after recall compare (uses !=) can't be forced true by NaN != NaN,
  which would trigger a needless rebuild on every recall.
- ShoeGaze.applyState doc no longer claims "without rebuilding the engine graph":
  it now documents that a board is rebuilt (with the one-block-glitch caveat)
  when a rebuildsOnChange selector value differs from the live rig.

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-02 18:49:08 -07:00
13 changed files with 360 additions and 55 deletions
@@ -15,7 +15,8 @@ private let cabinetPeakingGainDivisor: 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
/// peak → presence peak) and capturing the result into a mono ``LyrebirdBuffer``. /// peak → presence peak → cone-breakup peak → mid notch) and capturing the result into a mono
/// ``LyrebirdBuffer``.
/// ///
/// This runs **off the RT thread** (at pedal build time), so it uses plain `Double` math with /// This runs **off the RT thread** (at pedal build time), so it uses plain `Double` math with
/// no allocation constraints. The produced buffer is a normal IR consumed by `ConvolutionReverb`. /// no allocation constraints. The produced buffer is a normal IR consumed by `ConvolutionReverb`.
@@ -32,6 +33,10 @@ public enum CabinetIRFactory {
private static let lowPassCascadeQ: [Double] = [0.541_196_100_146_197, 1.306_562_964_876_377] private static let lowPassCascadeQ: [Double] = [0.541_196_100_146_197, 1.306_562_964_876_377]
/// Q for the resonant body / presence peaks. /// Q for the resonant body / presence peaks.
private static let peakQ: Double = 1.2 private static let peakQ: Double = 1.2
/// Q for the narrower cone-breakup peak (higher than the body/presence peaks).
private static let breakupQ: Double = 2.0
/// Q for the mid interference notch (narrow, so it dips without gutting the midrange).
private static let notchQ: Double = 2.5
/// Builds the impulse response for `voice` at `sampleRate`. /// Builds the impulse response for `voice` at `sampleRate`.
/// ///
@@ -51,6 +56,8 @@ public enum CabinetIRFactory {
OfflineBiquad.lowPass(freq: voice.lowPassHz, q: lowPassCascadeQ[1], sampleRate: sampleRate), OfflineBiquad.lowPass(freq: voice.lowPassHz, q: lowPassCascadeQ[1], sampleRate: sampleRate),
OfflineBiquad.peaking(freq: voice.bodyHz, q: peakQ, gainDb: voice.bodyGainDb, sampleRate: sampleRate), OfflineBiquad.peaking(freq: voice.bodyHz, q: peakQ, gainDb: voice.bodyGainDb, sampleRate: sampleRate),
OfflineBiquad.peaking(freq: voice.presenceHz, q: peakQ, gainDb: voice.presenceGainDb, sampleRate: sampleRate), OfflineBiquad.peaking(freq: voice.presenceHz, q: peakQ, gainDb: voice.presenceGainDb, sampleRate: sampleRate),
OfflineBiquad.peaking(freq: voice.breakupHz, q: breakupQ, gainDb: voice.breakupGainDb, sampleRate: sampleRate),
OfflineBiquad.peaking(freq: voice.notchHz, q: notchQ, gainDb: voice.notchGainDb, sampleRate: sampleRate),
] ]
var ir: [Double] = [Double](repeating: 0.0, count: frames) var ir: [Double] = [Double](repeating: 0.0, count: frames)
@@ -6,17 +6,37 @@
/// A built-in guitar-speaker-cabinet voicing. /// A built-in guitar-speaker-cabinet voicing.
/// ///
/// Each voice is a compact set of target-response parameters (low/high rolloff, a low-mid /// Each voice is a compact set of target-response parameters — low/high rolloff, a low-mid
/// "body" bump, and a presence peak) from which ``CabinetIRFactory`` synthesizes a short /// "body" bump, an upper-mid "presence" peak, a higher cone-"breakup" peak, and a mid
/// impulse response entirely in code. These IRs are **our own content** (MIT, generated, no /// interference "notch" — from which ``CabinetIRFactory`` synthesizes a short impulse response
/// third-party capture), so they ship with the pedal without licensing concerns. (Loading a /// entirely in code. These IRs are **our own content** (MIT, generated, no third-party capture),
/// user-supplied captured `.wav` cab IR is a planned follow-up.) /// so they ship with the pedal without licensing concerns. (Loading a user-supplied captured
/// `.wav` cab IR is a planned follow-up.)
/// ///
/// The values are deliberately broad-strokes voicings, not measurements of specific hardware. /// The values are deliberately broad-strokes voicings, not measurements of specific hardware.
public enum CabinetVoice: String, CaseIterable, Sendable { public enum CabinetVoice: String, CaseIterable, Sendable {
case americanCombo case americanCombo
case britishStack case britishStack
case vintageDark case vintageDark
case modernStack
case boutiqueOpen
case brightCombo
case fullRange
case loFiBox
/// The voice at a selector value (an index into ``allCases``), rounded and clamped to the valid
/// range. Used by the cab selector to pick the single voice to instantiate on a board rebuild.
///
/// - Parameter selectorValue: The live selector node value (nominally an integer index).
/// - Returns: The corresponding voice, clamped to `allCases`.
public static func voice(atSelectorValue selectorValue: Double) -> CabinetVoice {
let all: [CabinetVoice] = allCases
guard selectorValue.isFinite else { return all[0] }
// Clamp in Double space first so a huge/NaN-adjacent value can never trap `Int(_:)`.
let bounded: Double = Swift.min(Swift.max(selectorValue, 0.0), Double(all.count - 1))
let index: Int = Int(bounded.rounded())
return all[index]
}
/// Human-readable name for pickers. /// Human-readable name for pickers.
public var displayName: String { public var displayName: String {
@@ -24,6 +44,11 @@ public enum CabinetVoice: String, CaseIterable, Sendable {
case .americanCombo: return "American 1×12" case .americanCombo: return "American 1×12"
case .britishStack: return "British 4×12" case .britishStack: return "British 4×12"
case .vintageDark: return "Vintage Dark" case .vintageDark: return "Vintage Dark"
case .modernStack: return "Modern 4×12"
case .boutiqueOpen: return "Boutique 2×12"
case .brightCombo: return "Bright 1×12"
case .fullRange: return "Full-Range (FRFR)"
case .loFiBox: return "Lo-Fi 1×8"
} }
} }
@@ -33,6 +58,11 @@ public enum CabinetVoice: String, CaseIterable, Sendable {
case .americanCombo: return 80.0 case .americanCombo: return 80.0
case .britishStack: return 95.0 case .britishStack: return 95.0
case .vintageDark: return 90.0 case .vintageDark: return 90.0
case .modernStack: return 100.0
case .boutiqueOpen: return 70.0
case .brightCombo: return 85.0
case .fullRange: return 45.0
case .loFiBox: return 180.0
} }
} }
@@ -43,6 +73,11 @@ public enum CabinetVoice: String, CaseIterable, Sendable {
case .americanCombo: return 5500.0 case .americanCombo: return 5500.0
case .britishStack: return 4500.0 case .britishStack: return 4500.0
case .vintageDark: return 3800.0 case .vintageDark: return 3800.0
case .modernStack: return 4000.0
case .boutiqueOpen: return 6000.0
case .brightCombo: return 6500.0
case .fullRange: return 9000.0
case .loFiBox: return 3000.0
} }
} }
@@ -52,6 +87,11 @@ public enum CabinetVoice: String, CaseIterable, Sendable {
case .americanCombo: return 420.0 case .americanCombo: return 420.0
case .britishStack: return 700.0 case .britishStack: return 700.0
case .vintageDark: return 500.0 case .vintageDark: return 500.0
case .modernStack: return 900.0
case .boutiqueOpen: return 450.0
case .brightCombo: return 550.0
case .fullRange: return 300.0
case .loFiBox: return 900.0
} }
} }
@@ -61,6 +101,11 @@ public enum CabinetVoice: String, CaseIterable, Sendable {
case .americanCombo: return 1.5 case .americanCombo: return 1.5
case .britishStack: return -2.0 case .britishStack: return -2.0
case .vintageDark: return 2.0 case .vintageDark: return 2.0
case .modernStack: return 2.0
case .boutiqueOpen: return -1.0
case .brightCombo: return 1.0
case .fullRange: return 0.0
case .loFiBox: return 4.0
} }
} }
@@ -70,6 +115,11 @@ public enum CabinetVoice: String, CaseIterable, Sendable {
case .americanCombo: return 3000.0 case .americanCombo: return 3000.0
case .britishStack: return 2500.0 case .britishStack: return 2500.0
case .vintageDark: return 2200.0 case .vintageDark: return 2200.0
case .modernStack: return 3200.0
case .boutiqueOpen: return 3500.0
case .brightCombo: return 3800.0
case .fullRange: return 4000.0
case .loFiBox: return 2400.0
} }
} }
@@ -79,6 +129,69 @@ public enum CabinetVoice: String, CaseIterable, Sendable {
case .americanCombo: return 3.0 case .americanCombo: return 3.0
case .britishStack: return 4.0 case .britishStack: return 4.0
case .vintageDark: return 2.0 case .vintageDark: return 2.0
case .modernStack: return 5.0
case .boutiqueOpen: return 2.0
case .brightCombo: return 4.0
case .fullRange: return 1.0
case .loFiBox: return 1.0
}
}
/// Cone-"breakup" peak centre in Hz — the higher, narrower bite/clank a real driver adds as
/// the cone breaks up. Sits above the presence peak.
var breakupHz: Double {
switch self {
case .americanCombo: return 4200.0
case .britishStack: return 3800.0
case .vintageDark: return 3500.0
case .modernStack: return 3800.0
case .boutiqueOpen: return 5000.0
case .brightCombo: return 5200.0
case .fullRange: return 6000.0
case .loFiBox: return 2600.0
}
}
/// Cone-breakup peak gain in dB. Small; `0` disables the peak (identity).
var breakupGainDb: Double {
switch self {
case .americanCombo: return 2.0
case .britishStack: return 3.0
case .vintageDark: return 1.5
case .modernStack: return 3.0
case .boutiqueOpen: return 1.5
case .brightCombo: return 3.0
case .fullRange: return 0.5
case .loFiBox: return 2.0
}
}
/// Mid interference "notch" centre in Hz — the characteristic dip from cone/mic
/// comb-filtering, typically ~1.2–2.5 kHz.
var notchHz: Double {
switch self {
case .americanCombo: return 1800.0
case .britishStack: return 1600.0
case .vintageDark: return 1500.0
case .modernStack: return 1700.0
case .boutiqueOpen: return 2000.0
case .brightCombo: return 2100.0
case .fullRange: return 2000.0
case .loFiBox: return 1200.0
}
}
/// Notch depth in dB (negative). `0` disables the notch (identity).
var notchGainDb: Double {
switch self {
case .americanCombo: return -3.0
case .britishStack: return -4.0
case .vintageDark: return -2.5
case .modernStack: return -5.0
case .boutiqueOpen: return -2.0
case .brightCombo: return -2.0
case .fullRange: return 0.0
case .loFiBox: return -1.0
} }
} }
} }
+12
View File
@@ -237,6 +237,18 @@ open class Pedal: SynthesizerBase {
[] []
} }
/// Current values of every ``effectSelectors`` entry flagged `rebuildsOnChange` — the selectors
/// whose choice changes the graph topology (e.g. a cabinet voice). A lightweight recall compares
/// this before/after applying a snapshot to decide whether the board must be rebuilt (a plain
/// node write does not re-enter `effect(_:)`). Empty for pedals with no such selectors.
public var rebuildSelectorValues: [Double] {
// Sanitize non-finite to a fixed sentinel: the before/after compare in a recall uses `!=`,
// and `NaN != NaN` would force a spurious rebuild on every recall.
effectSelectors
.filter { $0.rebuildsOnChange }
.map { $0.node.value.isFinite ? $0.node.value : 0.0 }
}
/// Effect-specific transport controls, rendered as a row directly below the knobs — above /// Effect-specific transport controls, rendered as a row directly below the knobs — above
/// ``effectButtons``. Use for the persistent state toggles and transport stops that read as /// ``effectButtons``. Use for the persistent state toggles and transport stops that read as
/// a group distinct from the momentary "do it now" actions (e.g. a looper's Loop / Stop / /// a group distinct from the momentary "do it now" actions (e.g. a looper's Loop / Stop /
@@ -49,20 +49,31 @@ public struct PedalSelectorKnob {
/// contain at least two. /// contain at least two.
public let stops: [Stop] public let stops: [Stop]
/// When `true`, committing a new stop asks the host to rebuild the board (as the Neural Amp
/// model loader does) instead of relying on the live graph to react to the node value. Use for
/// selectors whose choice changes the *graph topology* — e.g. a cabinet whose voice picks which
/// single convolver is instantiated — rather than a value an always-running node reads live.
/// Defaults to `false`.
public let rebuildsOnChange: Bool
/// Creates a selector-knob descriptor. /// Creates a selector-knob descriptor.
/// ///
/// - Parameters: /// - Parameters:
/// - label: Short label shown beneath the knob. /// - label: Short label shown beneath the knob.
/// - node: The `UIParamNode` projected value of an `@UIParam` property (`pedal.$voice1`, …). /// - node: The `UIParamNode` projected value of an `@UIParam` property (`pedal.$voice1`, …).
/// - stops: Ordered stops, CCW → CW. At least two. /// - stops: Ordered stops, CCW → CW. At least two.
/// - rebuildsOnChange: Ask the host to rebuild the board when a new stop is committed. Use for
/// selectors that change graph topology. Defaults to `false`.
public init( public init(
label: String, label: String,
node: UIParamNode, node: UIParamNode,
stops: [Stop] stops: [Stop],
rebuildsOnChange: Bool = false
) { ) {
precondition(stops.count >= 2, "PedalSelectorKnob requires at least two stops") precondition(stops.count >= 2, "PedalSelectorKnob requires at least two stops")
self.label = label self.label = label
self.node = node self.node = node
self.stops = stops self.stops = stops
self.rebuildsOnChange = rebuildsOnChange
} }
} }
@@ -16,7 +16,7 @@ import LyrebirdUI
/// → ToneStack(bass, mid, treble, model) (fixed per amp) /// → ToneStack(bass, mid, treble, model) (fixed per amp)
/// → TriodeStage(power-amp drive) (power-amp warmth) /// → TriodeStage(power-amp drive) (power-amp warmth)
/// → shapeVoice(_:) (subclass signature filter) /// → shapeVoice(_:) (subclass signature filter)
/// → ConvolutionReverb(cab IR) (speaker cabinet — live-selectable voice) /// → ConvolutionReverb(cab IR) (speaker cabinet — voice-selectable, rebuild on change)
/// ``` /// ```
/// 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.
/// ///
@@ -120,7 +120,8 @@ open class AmpVoicePedal: Pedal {
public override var effectSelectors: [PedalSelectorKnob] { public override var effectSelectors: [PedalSelectorKnob] {
[ [
PedalSelectorKnob(label: "Cab", node: $cab, stops: AmpVoicePedal.cabStops), PedalSelectorKnob(
label: "Cab", node: $cab, stops: AmpVoicePedal.cabStops, rebuildsOnChange: true),
] ]
} }
@@ -128,9 +129,10 @@ open class AmpVoicePedal: Pedal {
/// Preamp → fixed tone stack → power amp → signature shaping → cabinet (voice-selected). /// Preamp → fixed tone stack → power amp → signature shaping → cabinet (voice-selected).
/// ///
/// > Note: the cabinet is a `Select` over one `ConvolutionReverb` per `CabinetVoice`. Per /// > Note: only the voice named by the live `cab` selector is instantiated, so exactly one
/// > `Select`'s SC-parity contract every input is evaluated each block, so all cab convolvers /// > `ConvolutionReverb` runs. The `cab` selector is `rebuildsOnChange`, so switching cabs
/// > run continuously regardless of the `cab` selection — a bounded, fixed CPU cost. /// > rebuilds the board (re-entering `effect(_:)` with the new voice) rather than running every
/// > voice at once.
/// ///
/// - Parameter dry: Dry mono input signal. /// - Parameter dry: Dry mono input signal.
/// - Returns: The amped, cab-convolved mono output. /// - Returns: The amped, cab-convolved mono output.
@@ -142,13 +144,11 @@ open class AmpVoicePedal: Pedal {
let powerAmp: TriodeStage = TriodeStage( let powerAmp: TriodeStage = TriodeStage(
input: toned, drive: powerAmpDrive, bias: powerAmpBias, oversample: 2) input: toned, drive: powerAmpDrive, bias: powerAmpBias, oversample: 2)
let shaped: any ValidGeneratorInput = shapeVoice(powerAmp) let shaped: any ValidGeneratorInput = shapeVoice(powerAmp)
let cabinets: [any ValidGeneratorInput] = CabinetVoice.allCases.map { (voice: CabinetVoice) in let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cab)
ConvolutionReverb.Audio( return ConvolutionReverb.Audio(
input: shaped, input: shaped,
ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sr), ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sr),
mix: cabinetMix mix: cabinetMix
) )
} }
return Select.Audio(which: $cab, inputs: cabinets)
}
} }
@@ -10,14 +10,15 @@ import LyrebirdUI
/// Speaker-cabinet simulation via impulse-response convolution. /// Speaker-cabinet simulation via impulse-response convolution.
/// ///
/// Convolves the input against a cabinet impulse response using Lyrebird's partitioned FFT /// Convolves the input against a cabinet impulse response using Lyrebird's partitioned FFT
/// convolver (`ConvolutionReverb`). One convolver per built-in ``CabinetVoice`` is built at /// convolver (`ConvolutionReverb`). A single convolver is built at `build()` time for the voice the
/// `build()` time (each voicing's IR is synthesized in code — our own MIT content, see /// ``cabinet`` selector currently names (each voicing's IR is synthesized in code — our own MIT
/// ``CabinetIRFactory``); a `Select` driven by the ``cabinet`` knob picks the active one, so /// content, see ``CabinetIRFactory``). Changing the selector asks the host to rebuild the board so
/// switching cabs is live and round-trips through the rig save format like every other pedal. /// only the selected voice's convolver ever runs — one partitioned-FFT convolver, not one per
/// voice. The selection round-trips through the rig save format like every other pedal.
/// ///
/// Signal path (inside `effect(_:)`): /// Signal path (inside `effect(_:)`):
/// ``` /// ```
/// dry → [ConvolutionReverb(ir: voice0), …] → Select(which: cabinet) → mono out /// dry → ConvolutionReverb(ir: selectedVoice) → 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.
@@ -41,7 +42,8 @@ public final class CabinetPedal: Pedal {
// 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 live by the `Select` in `effect(_:)`. /// stops via the ``cabinet`` selector; read at board-build time by `effect(_:)`, which
/// instantiates only that voice's convolver (the selector is `rebuildsOnChange`).
@UIParam public var cabinet: Double = 0.0 @UIParam public var cabinet: Double = 0.0
// MARK: - Constants // MARK: - Constants
@@ -82,31 +84,30 @@ public final class CabinetPedal: Pedal {
public override var effectSelectors: [PedalSelectorKnob] { public override var effectSelectors: [PedalSelectorKnob] {
[ [
PedalSelectorKnob(label: "Cab", node: $cabinet, stops: CabinetPedal.voiceStops), PedalSelectorKnob(
label: "Cab", node: $cabinet, stops: CabinetPedal.voiceStops, rebuildsOnChange: true),
] ]
} }
// MARK: - Effect // MARK: - Effect
/// Convolves the dry signal against every built-in cabinet IR and selects the active one. /// Convolves the dry signal against the single selected cabinet IR.
/// ///
/// All voices' convolvers are built at `build()` time; `Select` picks per the live `cabinet` /// Only the voice named by the live `cabinet` selector is instantiated, so exactly one
/// index each block. Every convolver keeps running (SC `Select` semantics), so their internal /// partitioned-FFT convolver runs. Changing the selector triggers a board rebuild (the selector
/// state stays in sync across a switch — but the output changes on the switch sample, so a /// is `rebuildsOnChange`), which re-enters `effect(_:)` with the new voice — so switching cabs
/// hard cab change can click; cabs are normally set-and-forget, and a smooth crossfade is a /// costs a brief rebuild rather than running every voice at once. Synthesizing the short IR
/// possible later refinement. Synthesizing the short IRs happens off the RT thread in `build()`. /// happens off the RT thread in `build()`.
/// ///
/// - Parameter dry: Dry mono input signal. /// - Parameter dry: Dry mono input signal.
/// - Returns: The cabinet-convolved mono output. /// - Returns: The cabinet-convolved 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 convolvers: [any ValidGeneratorInput] = CabinetVoice.allCases.map { (voice: CabinetVoice) in let voice: CabinetVoice = CabinetVoice.voice(atSelectorValue: cabinet)
ConvolutionReverb.Audio( return ConvolutionReverb.Audio(
input: dry, input: dry,
ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sr), ir: CabinetIRFactory.makeIR(voice: voice, sampleRate: sr),
mix: convolutionMix mix: convolutionMix
) )
} }
return Select.Audio(which: $cabinet, inputs: convolvers)
}
} }
@@ -334,8 +334,8 @@ extension ShoeGaze {
// MARK: - Lightweight recall // MARK: - Lightweight recall
/// Applies parameter values from `state` to the current rig topology without /// Applies parameter values from `state` to the current rig topology, rebuilding only the
/// rebuilding the engine graph. /// boards where a graph-topology selector changed.
/// ///
/// This is a lightweight "recall settings" path intended for topologically identical /// This is a lightweight "recall settings" path intended for topologically identical
/// rigs (same board count, same segment order, same pedal types). Boards, segments, and /// rigs (same board count, same segment order, same pedal types). Boards, segments, and
@@ -345,12 +345,28 @@ extension ShoeGaze {
/// is thrown and remaining /// is thrown and remaining
/// entries continue to be processed. /// entries continue to be processed.
/// ///
/// Most parameters apply live with no graph change. The exception is a `rebuildsOnChange`
/// selector (e.g. a cabinet voice, which picks which convolver is instantiated): if such a
/// selector's value differs from the live rig, that board is rebuilt via `rebuildBoard(_:from:)`
/// so the new selection takes effect — which carries the same at-most-one-block glitch as any
/// rebuild on a running engine. Boards without such a selector stay fully live.
///
/// Use `loadRig(from:)` when you need a full topology rebuild. /// Use `loadRig(from:)` when you need a full topology rebuild.
/// ///
/// - Parameter state: The `ShoeGazeState` whose parameter values should be applied. /// - Parameter state: The `ShoeGazeState` whose parameter values should be applied.
public func applyState(_ state: ShoeGazeState) { public func applyState(_ state: ShoeGazeState) {
for (board, boardState) in zip(boards, state.boards) { for (board, boardState) in zip(boards, state.boards) {
applySegmentParams(boardState.segments, to: board.orderedSegments) let topologyChanged: Bool = applySegmentParams(boardState.segments, to: board.orderedSegments)
// A `rebuildsOnChange` selector (e.g. a cabinet voice) picks which nodes exist in the
// graph, so a plain node write during recall is invisible until the board is rebuilt.
// Rebuild only the boards where such a selector actually changed value.
if topologyChanged {
do {
_ = try rebuildBoard(board, from: board.captureState())
} catch {
print("[ShoeGaze] board rebuild after recall failed: \(error)")
}
}
} }
// 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 —
@@ -363,30 +379,39 @@ extension ShoeGaze {
/// 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).
/// - Returns: `true` if any pedal's `rebuildsOnChange` selector value changed, meaning the board
/// must be rebuilt for the new selection to take effect.
@discardableResult
private func applySegmentParams( private func applySegmentParams(
_ states: [BoardSegmentState], _ states: [BoardSegmentState],
to segments: [BoardSegment] to segments: [BoardSegment]
) { ) -> Bool {
var topologyChanged: Bool = false
for (segment, segmentState) in zip(segments, states) { for (segment, segmentState) in zip(segments, states) {
switch (segment, segmentState) { switch (segment, segmentState) {
case let (.pedal(pedal), .pedal(pedalState)): case let (.pedal(pedal), .pedal(pedalState)):
if pedal.displayName == pedalState.type { if pedal.displayName == pedalState.type {
let before: [Double] = pedal.rebuildSelectorValues
pedal.applyState(pedalState) pedal.applyState(pedalState)
if pedal.rebuildSelectorValues != before { topologyChanged = true }
} }
case let (.parallel(section), .parallel(parallelState)): case let (.parallel(section), .parallel(parallelState)):
applyBranchParams(parallelState.branchA, to: section.branchA.pedals) let a: Bool = applyBranchParams(parallelState.branchA, to: section.branchA.pedals)
applyBranchParams(parallelState.branchB, to: section.branchB.pedals) let b: Bool = applyBranchParams(parallelState.branchB, to: section.branchB.pedals)
if a || b { topologyChanged = true }
section.splitter.mode = parallelState.mode section.splitter.mode = parallelState.mode
case let (.stereoSplit(section), .stereoSplit(stereoState)): case let (.stereoSplit(section), .stereoSplit(stereoState)):
applyBranchParams(stereoState.left, to: section.left.pedals) let l: Bool = applyBranchParams(stereoState.left, to: section.left.pedals)
applyBranchParams(stereoState.right, to: section.right.pedals) let r: Bool = applyBranchParams(stereoState.right, to: section.right.pedals)
if l || r { topologyChanged = true }
section.route = stereoState.route section.route = stereoState.route
case let (.stereoUnzip(section), .stereoUnzip(unzipState)): case let (.stereoUnzip(section), .stereoUnzip(unzipState)):
applyBranchParams(unzipState.left, to: section.left.pedals) let l: Bool = applyBranchParams(unzipState.left, to: section.left.pedals)
applyBranchParams(unzipState.right, to: section.right.pedals) let r: Bool = applyBranchParams(unzipState.right, to: section.right.pedals)
if l || r { topologyChanged = true }
section.route = unzipState.route section.route = unzipState.route
default: default:
@@ -394,12 +419,20 @@ extension ShoeGaze {
continue continue
} }
} }
return topologyChanged
} }
/// Positionally applies branch pedal snapshots to live branch pedals, matching by type. /// Positionally applies branch pedal snapshots to live branch pedals, matching by type.
private func applyBranchParams(_ states: [PedalState], to pedals: [Pedal]) { ///
/// - Returns: `true` if any branch pedal's `rebuildsOnChange` selector value changed.
@discardableResult
private func applyBranchParams(_ states: [PedalState], to pedals: [Pedal]) -> Bool {
var topologyChanged: Bool = false
for (pedal, pedalState) in zip(pedals, states) where pedal.displayName == pedalState.type { for (pedal, pedalState) in zip(pedals, states) where pedal.displayName == pedalState.type {
let before: [Double] = pedal.rebuildSelectorValues
pedal.applyState(pedalState) pedal.applyState(pedalState)
if pedal.rebuildSelectorValues != before { topologyChanged = true }
} }
return topologyChanged
} }
} }
@@ -29,6 +29,9 @@ struct PedalSelectorKnobView: View {
// MARK: - Input // MARK: - Input
private let selector: PedalSelectorKnob private let selector: PedalSelectorKnob
/// Called once when a drag ends on a different stop than it began — used to trigger a board
/// rebuild for `rebuildsOnChange` selectors. `nil` for plain live-value selectors.
private let onCommit: (() -> Void)?
// MARK: - Drag state // MARK: - Drag state
@@ -37,8 +40,9 @@ struct PedalSelectorKnobView: View {
// MARK: - Init // MARK: - Init
init(_ selector: PedalSelectorKnob) { init(_ selector: PedalSelectorKnob, onCommit: (() -> Void)? = nil) {
self.selector = selector self.selector = selector
self.onCommit = onCommit
} }
// MARK: - Body // MARK: - Body
@@ -100,7 +104,11 @@ struct PedalSelectorKnobView: View {
selector.node.update(value) selector.node.update(value)
} }
} }
.onEnded { _ in dragInProgress = false } .onEnded { _ in
let changed: Bool = currentIndex != dragStartIndex
dragInProgress = false
if changed { onCommit?() }
}
} }
// MARK: - Helpers // MARK: - Helpers
+6 -1
View File
@@ -777,7 +777,12 @@ public struct PedalView: View {
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 ForEach(Array(selectors.enumerated()), id: \.offset) { pair in
PedalSelectorKnobView(pair.element) PedalSelectorKnobView(
pair.element,
onCommit: pair.element.rebuildsOnChange
? { [pedal, pedalRebuildAction] in pedalRebuildAction(pedal) }
: nil
)
} }
Spacer(minLength: 0) Spacer(minLength: 0)
} }
@@ -126,6 +126,8 @@ struct AmpVoicePedalTests {
for voice in voices { for voice in voices {
let pedal: AmpVoicePedal = voice.make() let pedal: AmpVoicePedal = voice.make()
#expect(pedal.effectSelectors.map { $0.label } == ["Cab"], "\(voice.name) selectors") #expect(pedal.effectSelectors.map { $0.label } == ["Cab"], "\(voice.name) selectors")
#expect(pedal.effectSelectors.first?.rebuildsOnChange == true,
"\(voice.name) cab selector should rebuild on change")
#expect(pedal.widthUnits == 2, "\(voice.name) amp head should use a double-width card") #expect(pedal.widthUnits == 2, "\(voice.name) amp head should use a double-width card")
#expect(pedal.showsMixControl == false, "\(voice.name) should be fully wet") #expect(pedal.showsMixControl == false, "\(voice.name) should be fully wet")
} }
@@ -66,4 +66,48 @@ struct CabinetIRFactoryTests {
let darkHigh: Double = responseMagnitude(dark, hz: 5000.0) let darkHigh: Double = responseMagnitude(dark, hz: 5000.0)
#expect(americanHigh > darkHigh, "vintageDark should be darker at 5 kHz") #expect(americanHigh > darkHigh, "vintageDark should be darker at 5 kHz")
} }
@Test func fullRangeExtendsHigherThanCombo() {
// Full-Range (FRFR) has a ~9 kHz low-pass vs the American combo's ~5.5 kHz, so it keeps
// markedly more energy at 8 kHz.
let frfr: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .fullRange, sampleRate: sampleRate)
let combo: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .americanCombo, sampleRate: sampleRate)
let frfrHigh: Double = responseMagnitude(frfr, hz: 8000.0)
let comboHigh: Double = responseMagnitude(combo, hz: 8000.0)
#expect(frfrHigh > comboHigh * 2.0, "FRFR should keep more 8 kHz than the combo")
}
@Test func notchCreatesMidDip() {
// Modern 4×12 has a deep interference notch at 1.7 kHz. Its response there should dip below
// the surrounding midrange (points chosen clear of the body / presence peaks).
let ir: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .modernStack, sampleRate: sampleRate)
let atNotch: Double = responseMagnitude(ir, hz: 1700.0)
let below: Double = responseMagnitude(ir, hz: 1100.0)
let above: Double = responseMagnitude(ir, hz: 2400.0)
#expect(atNotch < below, "notch did not dip below the lower midrange")
#expect(atNotch < above, "notch did not dip below the upper midrange")
}
@Test func loFiIsDarkerThanFullRange() {
// Lo-Fi 1×8 rolls off at ~3 kHz vs Full-Range's ~9 kHz, so it is markedly darker at 4 kHz.
let loFi: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .loFiBox, sampleRate: sampleRate)
let frfr: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .fullRange, sampleRate: sampleRate)
#expect(responseMagnitude(frfr, hz: 4000.0) > responseMagnitude(loFi, hz: 4000.0),
"Lo-Fi should be darker than Full-Range at 4 kHz")
}
@Test func breakupPeakLiftsUpperMid() {
// Bright 1×12 (breakup +3 dB @ 5.2 kHz, LP 6.5 kHz) keeps more ~5.1 kHz energy than
// Boutique 2×12 (breakup +1.5 dB @ 5.0 kHz, LP 6.0 kHz) — both the stronger breakup boost
// and the higher low-pass push the same direction.
let bright: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .brightCombo, sampleRate: sampleRate)
let boutique: LyrebirdBuffer = CabinetIRFactory.makeIR(voice: .boutiqueOpen, sampleRate: sampleRate)
#expect(responseMagnitude(bright, hz: 5100.0) > responseMagnitude(boutique, hz: 5100.0),
"brightCombo should have more upper-mid bite than boutiqueOpen at 5.1 kHz")
}
@Test func voiceNamesAreUnique() {
let names: [String] = CabinetVoice.allCases.map { $0.displayName }
#expect(Set(names).count == names.count, "duplicate cabinet display names")
}
} }
@@ -68,6 +68,21 @@ struct CabinetPedalTests {
#expect(stops == CabinetVoice.allCases.map { $0.displayName }) #expect(stops == CabinetVoice.allCases.map { $0.displayName })
} }
@Test func cabinetSelectorRebuildsOnChange() throws {
// Only the selected voice's convolver is built, so changing it must rebuild the board.
let pedal: CabinetPedal = CabinetPedal()
#expect(pedal.effectSelectors.first?.rebuildsOnChange == true)
}
@Test func voiceAtSelectorValueClampsAndRounds() throws {
let all: [CabinetVoice] = CabinetVoice.allCases
#expect(CabinetVoice.voice(atSelectorValue: 0.0) == all[0])
#expect(CabinetVoice.voice(atSelectorValue: 2.0) == all[2])
#expect(CabinetVoice.voice(atSelectorValue: 1.4) == all[1], "should round to nearest stop")
#expect(CabinetVoice.voice(atSelectorValue: -5.0) == all[0], "clamp below 0")
#expect(CabinetVoice.voice(atSelectorValue: 999.0) == all[all.count - 1], "clamp above max")
}
@Test func cabinetSelectionRoundTripsThroughState() throws { @Test func cabinetSelectionRoundTripsThroughState() throws {
// The selector value must survive capture/apply (preset round-trip). // The selector value must survive capture/apply (preset round-trip).
let pedal: CabinetPedal = CabinetPedal() let pedal: CabinetPedal = CabinetPedal()
@@ -275,6 +275,60 @@ struct PresetTests {
#expect(section.route == .stereo, "Route should be recalled") #expect(section.route == .stereo, "Route should be recalled")
} }
@Test func applyStateRebuildsBoardWhenCabinetVoiceChanges() throws {
// A cabinet voice is a `rebuildsOnChange` selector: only the selected voice's convolver is
// built, so a lightweight recall that changes it must rebuild the board (a plain node write
// would leave audio on the previously-built convolver).
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(CabinetPedal())
try sg.finalizeBoard(board)
guard let original: CabinetPedal = board.pedals.first as? CabinetPedal else {
Issue.record("No CabinetPedal in board")
return
}
// Snapshot at voice 3, then move the live pedal to voice 0 and recall the snapshot.
original.cabinet = 3.0
let snapshot: ShoeGazeState = sg.captureState()
original.cabinet = 0.0
sg.applyState(snapshot)
// The rebuild replaces the instance — the recalled voice must be reflected on the new one.
guard let rebuilt: CabinetPedal = sg.boards[0].pedals.first as? CabinetPedal else {
Issue.record("No CabinetPedal after recall")
return
}
#expect(rebuilt !== original, "board should rebuild when the cabinet voice changes")
#expect(rebuilt.cabinet == 3.0, "recalled cabinet voice should be applied")
}
@Test func applyStateDoesNotRebuildWhenCabinetVoiceUnchanged() throws {
// Recall with the same cabinet voice must NOT rebuild — the lightweight path stays cheap.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
try board.add(CabinetPedal())
try sg.finalizeBoard(board)
guard let original: CabinetPedal = board.pedals.first as? CabinetPedal else {
Issue.record("No CabinetPedal in board")
return
}
original.cabinet = 2.0
let snapshot: ShoeGazeState = sg.captureState()
sg.applyState(snapshot)
#expect(sg.boards[0].pedals.first === original, "unchanged cabinet voice should not rebuild")
}
// MARK: - In-memory round-trip // MARK: - In-memory round-trip
@Test func captureStateRoundTripEquality() throws { @Test func captureStateRoundTripEquality() throws {