// KarplusResonatorPedal.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import LyrebirdSynth import LyrebirdUI /// Sympathetic-string resonator — a bank of tuned Karplus-Strong strings the guitar excites. /// /// A sitar's or a sarangi's sympathetic strings are always coupled to the played note: pluck, and /// a fixed set of tuned strings sing along, ringing on after each note. This pedal models that with /// four `KarplusStrong` strings tuned to a chord above a **Tune** root. An amplitude envelope of /// your playing drives a Schmitt gate whose rising edge plucks the whole bank — capturing the loud /// note onset — and the strings then ring on at their own tuned pitches with their own decay: the /// sympathetic shimmer blooming out of the note's tail. /// /// Distinct from a reverb or a delay: the tails are **pitched** to the Tune root's chord, not a /// diffuse wash or a repeat of what you played. Distinct from the ``PolyOctavePedal`` (which pitch- /// shifts your note in real time): here the resonators have their own fixed tuning and their own /// decay, so holding a drone root under a moving line is the whole point. /// /// Wraps Lyrebird's `KarplusStrong` run fully wet; the base `Pedal` `mix` sets the blend of the /// ringing bank against the dry note (an even mix by default). /// /// The root can be set two ways, chosen by the **Tuning** switch: **Free** sweeps the continuous /// **Tune** Hz knob; **Pitched** tunes the root to a musical note chosen with a single **Root** /// selector that steps through every semitone from E1 up to E5 (the top of the treble staff), /// captioned by name and octave (`E1`, `A3`, `E5`) in equal temperament (A4 = 440 Hz, so A3 = 220). /// In **Pitched** the Tune Hz knob is ignored; in **Free** the Root selector is hidden. /// /// ## Knobs /// - `tune`: Root frequency of the string bank in Hz (used in **Free** tuning). Range `[40, 660]` /// (up to E5, the top of the treble staff). /// - `sustain`: Ring length — the string feedback. Range `[0, 1]` → feedback `[0.9, 0.999]`. /// - `tone`: Brightness of the strings. Range `[0, 1]`: `0` = dark/woody, `1` = bright/metallic. /// - `sensitivity`: How readily playing plucks the strings. Range `[0, 1]`: higher = lower trigger /// threshold, so quieter notes still excite the bank. /// /// ## Switch /// - `tuning`: Root source — **Free** (the Tune Hz knob) or **Pitched** (the Root selector). Rebuilds. /// /// ## Selectors (all rebuild on change) /// - `voicing`: Chord the four strings are tuned to: Drone, Octaves, Shimmer. /// - `pitchedNote`: Root note in **Pitched** tuning — a chromatic stop from E1 to E5 (shown only in /// **Pitched** mode). The value is the MIDI note number; A3 (MIDI 57) = 220 Hz. public final class KarplusResonatorPedal: Pedal { /// One-line description shown in the picker and info panel. public override var summary: String { "A bank of tuned strings that ring along with your note — sympathetic sitar shimmer." } // MARK: - Parameters /// Root frequency of the string bank in Hz (Free tuning). Range `[40, 660]` — up to E5. @UIParam public var tune: Double = 82.41 /// Ring length — the string feedback. Range `[0, 1]` → feedback `[0.9, 0.999]`. @UIParam public var sustain: Double = 0.7 /// Brightness of the strings. Range `[0, 1]`: `0` = dark/woody, `1` = bright/metallic. @UIParam public var tone: Double = 0.4 /// How readily playing plucks the strings. Range `[0, 1]`: higher = lower trigger threshold. @UIParam public var sensitivity: Double = 0.5 /// Selected voicing index into ``voicings``. A knob-picker selector; rebuilds on change. @UIParam public var voicing: Double = 0.0 /// Root-tuning source: `0` = Free (the Tune Hz knob), `1` = Pitched (the Root selector). A /// two-position switch; rebuilds on change. @UIParam public var tuning: Double = 0.0 /// Root note in Pitched tuning, as a MIDI note number. A chromatic selector stepping E1 (MIDI 28) /// to E5 (MIDI 76); rebuilds on change. Defaults to A3 (MIDI 57) = 220 Hz. @UIParam public var pitchedNote: Double = 57.0 // A3 = 220 Hz by default // MARK: - Voicings /// A named chord the four strings are tuned to, as frequency ratios of the Tune root. private struct Voicing { let title: String let ratios: [Double] } /// Fixed string tunings. Each has exactly ``stringCount`` ratios of the Tune root. /// - Drone: root, fifth, octave, octave+fifth — the classic sympathetic drone. /// - Octaves: two octaves down through two up — a wide octave stack. /// - Shimmer: two octave pairs detuned a few cents apart — slow beating for a chorused ring. private static let voicings: [Voicing] = [ Voicing(title: "Drone", ratios: [1.0, 1.5, 2.0, 3.0]), Voicing(title: "Octaves", ratios: [0.5, 1.0, 2.0, 4.0]), Voicing(title: "Shimmer", ratios: [1.0, 1.005, 2.0, 1.99]), ] /// Number of strings in the bank — fixed, so the delay-line allocation is structural. private static let stringCount: Int = 4 // MARK: - Note tuning /// Tuning-source values written by the ``tuning`` switch. private static let tuningFreeValue: Double = 0.0 private static let tuningPitchedValue: Double = 1.0 /// Pitch-class captions, index `0 … 11` (C … B). private static let pitchClassNames: [String] = [ "C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B", ] /// Equal-temperament reference: A4 = 440 Hz is MIDI note 69, 12 semitones per octave. private static let referenceFrequency: Double = 440.0 private static let referenceMidiNote: Int = 69 private static let semitonesPerOctave: Int = 12 /// Lowest Pitched root — E1 (MIDI 28, ≈ 41 Hz), a low bass E mirroring the Free knob's floor. private static let lowestMidiNote: Int = 28 /// Highest Pitched root — E5 (MIDI 76, ≈ 659 Hz), the top space of the treble staff. private static let highestMidiNote: Int = 76 /// Equal-tempered frequency in Hz for a MIDI note number, using A4 = 440 Hz (MIDI 69). A3 /// (MIDI 57) → 220 Hz; C4 (middle C, MIDI 60) → 261.63 Hz. /// /// - Parameter midi: MIDI note number. /// - Returns: The note's frequency in Hz. static func frequency(forMidiNote midi: Int) -> Double { let semitonesFromReference: Double = Double(midi - referenceMidiNote) / Double(semitonesPerOctave) return referenceFrequency * pow(2.0, semitonesFromReference) } /// Name-plus-octave caption for a MIDI note number in scientific-pitch convention (MIDI 60 = C4), /// e.g. MIDI 57 → `"A3"`, MIDI 76 → `"E5"`. /// /// - Parameter midi: MIDI note number (expected `lowestMidiNote … highestMidiNote`). /// - Returns: The note's caption. static func caption(forMidiNote midi: Int) -> String { let pitchClass: Int = ((midi % semitonesPerOctave) + semitonesPerOctave) % semitonesPerOctave let octaveNumber: Int = midi / semitonesPerOctave - 1 return pitchClassNames[pitchClass] + String(octaveNumber) } // MARK: - Constants /// Pedal returns the bank fully wet; the base `mix` blends it against the dry note. An even mix /// so the sympathetic ring sits under the dry signal rather than replacing it. private static let defaultMix: Double = 0.5 /// Maximum delay time for each string, in seconds — sizes the Karplus delay line. Covers the /// lowest resonator across both tuning modes: the lowest root is ≈ 40 Hz (Free floor, or the /// Pitched E1 ≈ 41 Hz), and the Octaves voicing drops a string a full octave below that /// (ratio 0.5 → ≈ 20 Hz, a ~0.05 s period), so `0.08 s` leaves margin. `KarplusStrong` clamps any lower /// frequency to the line length anyway. private let maxStringDelayTime: Double = 0.08 /// Feedback (ring length) mapped from `sustain = 0`: a short, plucky decay. private let feedbackMin: Double = 0.9 /// Feedback mapped from `sustain = 1`: a very long, near-infinite ring. Kept just under `1.0` /// so the bank always decays rather than running away. private let feedbackMax: Double = 0.999 /// One-pole coefficient mapped from `tone = 0`: classic Karplus averaging — dark and woody. private let coefDark: Double = 0.5 /// One-pole coefficient mapped from `tone = 1`: negative, for a bright, metallic sitar-like /// timbre. Kept well inside `|coef| < 1` so the feedback path never grows. private let coefBright: Double = -0.2 /// Schmitt switch-on threshold on the input envelope at `sensitivity = 0` — the least sensitive /// setting, where only loud notes feed the strings. private let gateHiThresholdLow: Double = 0.25 /// Schmitt switch-on threshold at `sensitivity = 1` — the most sensitive setting, where even /// quiet notes feed the strings. private let gateHiThresholdHigh: Double = 0.01 /// Fraction of the switch-on threshold used for the switch-off threshold, giving the gate /// hysteresis so it doesn't chatter around a single level. private let gateLoFactor: Double = 0.5 /// Envelope-follower attack for the gate detector, in seconds — fast, to catch note onsets. private let envAttackTime: Double = 0.005 /// Envelope-follower release for the gate detector, in seconds — slow enough that the gate holds /// through a note and only drops once it has genuinely decayed, at which point the bank rings. private let envReleaseTime: Double = 0.08 /// Output scale on the summed four-string bank — `1/stringCount`, the fully-coherent-sum bound. /// The Octaves and Shimmer voicings share string periods, so a full-scale pluck can momentarily /// align all four; this ceiling keeps the summed bank at or below the dry peak with no limiter. private let bankGain: Double = 0.25 // MARK: - Ranges /// Free-mode root range in Hz. Upper bound reaches E5 (≈ 659 Hz, the top of the treble staff); /// lower bound sits around a low bass E. private let tuneRange: ClosedRange = 40.0 ... 660.0 private let unitRange: ClosedRange = 0.0 ... 1.0 // MARK: - Knobs public override var effectKnobs: [PedalKnob] { [ PedalKnob(label: "Tune", node: $tune, range: tuneRange), PedalKnob(label: "Sustain", node: $sustain, range: unitRange), PedalKnob(label: "Tone", node: $tone, range: unitRange), PedalKnob(label: "Sensitivity", node: $sensitivity, range: unitRange), ] } // MARK: - Switch public override var effectSwitches: [PedalSwitch] { [ // Picks the root source. Rebuilds: it swaps the build-time root (live Tune knob vs a fixed // note Hz) and toggles whether the Root selector is shown. PedalSwitch( label: "Tuning", node: $tuning, options: [ PedalSwitch.Option(title: "Free", value: KarplusResonatorPedal.tuningFreeValue), PedalSwitch.Option(title: "Pitched", value: KarplusResonatorPedal.tuningPitchedValue), ], rebuildsOnChange: true ), ] } // MARK: - Selectors public override var effectSelectors: [PedalSelectorKnob] { let voicingStops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.voicings.enumerated().map { index, voicing in PedalSelectorKnob.Stop(title: voicing.title, value: Double(index)) } // Voicing always shows and stays at selector index 0 — so a preset's positional selector // values line up regardless of tuning mode. The Root selector is appended only in Pitched // mode (and `tuning` is restored in the switch pass before this one, so the count matches). var selectors: [PedalSelectorKnob] = [ // Voicing ratios size each string's delay line, so it is a build-time structural choice. PedalSelectorKnob(label: "Voicing", node: $voicing, stops: voicingStops, rebuildsOnChange: true), ] if Int(tuning.rounded()) == Int(KarplusResonatorPedal.tuningPitchedValue) { let rootStops: [PedalSelectorKnob.Stop] = (KarplusResonatorPedal.lowestMidiNote ... KarplusResonatorPedal.highestMidiNote).map { midi in PedalSelectorKnob.Stop(title: KarplusResonatorPedal.caption(forMidiNote: midi), value: Double(midi)) } // The chosen note sets a fixed root Hz folded into the graph at build time, so it rebuilds. selectors.append( PedalSelectorKnob(label: "Root", node: $pitchedNote, stops: rootStops, rebuildsOnChange: true) ) } return selectors } // MARK: - Init /// Creates a Karplus-Strong sympathetic-resonator 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: "Karplus Resonator", inputBus: inputBus, outputBus: outputBus, initialMix: KarplusResonatorPedal.defaultMix ) } // MARK: - Effect public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { // `voicing` is read as a plain value at build time; the board rebuilds when it changes (the // ratios size each string's delay line). All other controls stay live. let index: Int = min(max(0, Int(voicing.rounded())), KarplusResonatorPedal.voicings.count - 1) let ratios: [Double] = KarplusResonatorPedal.voicings[index].ratios // Root source (read at build time, so switching rebuilds). Free: the live Tune Hz knob. // Pitched: a fixed equal-tempered frequency from the Root note selector. let rootFreq: any ValidGeneratorInput if Int(tuning.rounded()) == Int(KarplusResonatorPedal.tuningPitchedValue) { let midiNote: Int = min( max(KarplusResonatorPedal.lowestMidiNote, Int(pitchedNote.rounded())), KarplusResonatorPedal.highestMidiNote ) rootFreq = KarplusResonatorPedal.frequency(forMidiNote: midiNote) } else { rootFreq = $tune } // Pluck trigger: track the input envelope, then a Schmitt trigger turns it into a 0/1 play // detector. Its rising edge (you start a note) plucks the whole bank — Karplus fills each // delay line from the loud onset — and the strings then ring on at their tuned pitches. The // hysteresis means the gate must fall back below the off-threshold before the next note can // re-pluck, so a single sustained note plucks once rather than chattering. let env: AmplitudeFollower.Audio = AmplitudeFollower.Audio( in: dry, attackTime: envAttackTime, releaseTime: envReleaseTime ) // sensitivity [0, 1] → switch-on threshold [gateHiThresholdLow, gateHiThresholdHigh] // (higher sensitivity = lower threshold); switch-off threshold is a fixed fraction below it. let hiSpan: Double = gateHiThresholdHigh - gateHiThresholdLow let hiThreshold: any ValidGeneratorInput = ($sensitivity * hiSpan) + gateHiThresholdLow let loThreshold: any ValidGeneratorInput = hiThreshold * gateLoFactor let trigger: Schmidt.Audio = Schmidt.Audio(input: env, lo: loThreshold, hi: hiThreshold) // sustain [0, 1] → feedback [feedbackMin, feedbackMax]; tone [0, 1] → coef [coefDark, coefBright]. let feedbackSpan: Double = feedbackMax - feedbackMin let voicedFeedback: any ValidGeneratorInput = ($sustain * feedbackSpan) + feedbackMin let coefSpan: Double = coefBright - coefDark let voicedCoef: any ValidGeneratorInput = ($tone * coefSpan) + coefDark // Four tuned strings, each a KarplusStrong plucked by the shared trigger from the dry onset. var bank: any ValidGeneratorInput = KarplusStrong.Audio( exciter: dry, trigger: trigger, freq: rootFreq * ratios[0], feedback: voicedFeedback, coef: voicedCoef, sampleRate: sampleRate, maxDelayTime: maxStringDelayTime ) for stringIndex: Int in 1 ..< KarplusResonatorPedal.stringCount { let string: KarplusStrong.Audio = KarplusStrong.Audio( exciter: dry, trigger: trigger, freq: rootFreq * ratios[stringIndex], feedback: voicedFeedback, coef: voicedCoef, sampleRate: sampleRate, maxDelayTime: maxStringDelayTime ) bank = bank + string } return bank * bankGain } }