// 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 (the **Tuning** selector): **Free** sweeps the continuous **Tune** /// Hz knob; **Note** tunes the root to a musical pitch chosen with the **Note** (C…B) and **Octave** /// selectors in equal temperament (A4 = 440 Hz, so A3 = 220 Hz). /// /// ## Knobs /// - `tune`: Root frequency of the string bank in Hz (used in **Free** tuning). Range `[40, 400]`. /// - `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. /// /// ## Selectors (all rebuild on change) /// - `voicing`: Chord the four strings are tuned to: Drone, Octaves, Shimmer. /// - `tuning`: Root source — Free (the Tune Hz knob) or Note (the Note + Octave selectors). /// - `note`: Pitch class of the root in **Note** tuning: C … B. /// - `octave`: Octave of the root in **Note** tuning: `1 … 6`. 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. Range `[40, 400]`. @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` = Note (the Note + Octave selectors). @UIParam public var tuning: Double = 0.0 /// Pitch class of the root in Note tuning: `0` = C … `11` = B. A knob-picker; rebuilds on change. @UIParam public var note: Double = 9.0 // A /// Octave of the root in Note tuning (`1 … 6`). A knob-picker; rebuilds on change. @UIParam public var octave: Double = 3.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`` selector. private static let tuningFreeValue: Double = 0.0 private static let tuningNoteValue: Double = 1.0 /// Pitch-class captions for the ``note`` selector, index `0 … 11`. private static let pitchClassNames: [String] = [ "C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B", ] /// Octaves offered by the ``octave`` selector (the value stored is the octave number itself). private static let octaveChoices: [Int] = [1, 2, 3, 4, 5, 6] /// 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 /// Equal-tempered frequency in Hz for a pitch class (`0 = C … 11 = B`) and octave, using the /// scientific-pitch convention where C4 is middle C (MIDI 60), so A3 (pitch class `9`, octave /// `3`) is MIDI 57 → 220 Hz. /// /// - Parameters: /// - pitchClass: `0 … 11` (C … B). /// - octave: Scientific-pitch octave number. /// - Returns: The note's frequency in Hz. static func noteFrequency(pitchClass: Int, octave: Int) -> Double { let midiNote: Int = (octave + 1) * semitonesPerOctave + pitchClass let semitonesFromReference: Double = Double(midiNote - referenceMidiNote) / Double(semitonesPerOctave) return referenceFrequency * pow(2.0, semitonesFromReference) } // 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 Note root is C1 (≈ 32.7 Hz), and the /// Octaves voicing drops a string half an octave below that (≈ 16.4 Hz, a ~0.061 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 private let tuneRange: ClosedRange = 40.0 ... 400.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: - 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)) } let tuningStops: [PedalSelectorKnob.Stop] = [ PedalSelectorKnob.Stop(title: "Free", value: KarplusResonatorPedal.tuningFreeValue), PedalSelectorKnob.Stop(title: "Note", value: KarplusResonatorPedal.tuningNoteValue), ] let noteStops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.pitchClassNames.enumerated().map { index, name in PedalSelectorKnob.Stop(title: name, value: Double(index)) } let octaveStops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.octaveChoices.map { octaveValue in PedalSelectorKnob.Stop(title: String(octaveValue), value: Double(octaveValue)) } return [ // Each selector feeds a build-time structural choice (voicing ratios size each string's // delay line; the tuning root picks the live knob vs a fixed Hz), so each rebuilds. PedalSelectorKnob(label: "Voicing", node: $voicing, stops: voicingStops, rebuildsOnChange: true), PedalSelectorKnob(label: "Tuning", node: $tuning, stops: tuningStops, rebuildsOnChange: true), PedalSelectorKnob(label: "Note", node: $note, stops: noteStops, rebuildsOnChange: true), PedalSelectorKnob(label: "Octave", node: $octave, stops: octaveStops, rebuildsOnChange: true), ] } // 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. // Note: a fixed equal-tempered frequency from the Note + Octave selectors. let rootFreq: any ValidGeneratorInput if Int(tuning.rounded()) == Int(KarplusResonatorPedal.tuningNoteValue) { let pitchClass: Int = min(max(0, Int(note.rounded())), KarplusResonatorPedal.pitchClassNames.count - 1) let octaveValue: Int = Int(octave.rounded()) rootFreq = KarplusResonatorPedal.noteFrequency(pitchClass: pitchClass, octave: octaveValue) } 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 } }