diff --git a/Sources/LyrebirdShoeGaze/Pedals/KarplusResonatorPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/KarplusResonatorPedal.swift index 78e44cc..e76442a 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/KarplusResonatorPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/KarplusResonatorPedal.swift @@ -4,6 +4,7 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +import Foundation import LyrebirdSynth import LyrebirdUI @@ -24,15 +25,22 @@ import LyrebirdUI /// 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. Range `[40, 400]`. +/// - `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 -/// - `voicing`: Chord the four strings are tuned to (rebuilds on change): Drone, Octaves, Shimmer. +/// ## 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. @@ -57,6 +65,15 @@ public final class KarplusResonatorPedal: Pedal { /// 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. @@ -78,6 +95,39 @@ public final class KarplusResonatorPedal: Pedal { /// 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 @@ -85,8 +135,10 @@ public final class KarplusResonatorPedal: Pedal { private static let defaultMix: Double = 0.5 /// Maximum delay time for each string, in seconds — sizes the Karplus delay line. Covers the - /// lowest resonator (`tune.min × voicing.min = 40 × 0.5 = 20 Hz`, a 0.05 s period) with margin. - private let maxStringDelayTime: Double = 0.06 + /// 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 @@ -145,13 +197,26 @@ public final class KarplusResonatorPedal: Pedal { // MARK: - Selectors public override var effectSelectors: [PedalSelectorKnob] { - let stops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.voicings.enumerated().map { index, voicing in + 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 voicing tunes the strings to a different chord — a build-time structural choice - // (the ratios set each string's delay length), so switching it must rebuild the board. - PedalSelectorKnob(label: "Voicing", node: $voicing, stops: stops, rebuildsOnChange: true), + // 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), ] } @@ -182,6 +247,17 @@ public final class KarplusResonatorPedal: Pedal { 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 @@ -209,7 +285,7 @@ public final class KarplusResonatorPedal: Pedal { var bank: any ValidGeneratorInput = KarplusStrong.Audio( exciter: dry, trigger: trigger, - freq: $tune * ratios[0], + freq: rootFreq * ratios[0], feedback: voicedFeedback, coef: voicedCoef, sampleRate: sampleRate, @@ -219,7 +295,7 @@ public final class KarplusResonatorPedal: Pedal { let string: KarplusStrong.Audio = KarplusStrong.Audio( exciter: dry, trigger: trigger, - freq: $tune * ratios[stringIndex], + freq: rootFreq * ratios[stringIndex], feedback: voicedFeedback, coef: voicedCoef, sampleRate: sampleRate, diff --git a/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift b/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift index f879463..9fce7a4 100644 --- a/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift +++ b/Tests/LyrebirdShoeGazeTests/KarplusResonatorPedalTests.swift @@ -352,12 +352,51 @@ struct KarplusResonatorPedalTests { // MARK: - Wiring - @Test func exposesKnobsAndVoicingSelector() throws { + @Test func exposesKnobsAndSelectors() throws { let pedal: KarplusResonatorPedal = KarplusResonatorPedal() #expect(pedal.effectKnobs.map { $0.label } == ["Tune", "Sustain", "Tone", "Sensitivity"]) let selectors: [PedalSelectorKnob] = pedal.effectSelectors - #expect(selectors.map { $0.label } == ["Voicing"]) + #expect(selectors.map { $0.label } == ["Voicing", "Tuning", "Note", "Octave"]) #expect(selectors.first?.stops.map { $0.title } == ["Drone", "Octaves", "Shimmer"]) + let tuning: PedalSelectorKnob? = selectors.first { $0.label == "Tuning" } + #expect(tuning?.stops.map { $0.title } == ["Free", "Note"]) + let note: PedalSelectorKnob? = selectors.first { $0.label == "Note" } + #expect(note?.stops.count == 12) + #expect(note?.stops.first?.title == "C") + } + + @Test func noteFrequencyMapsEqualTemperament() throws { + // A4 = 440, so A3 = 220 and A4 = 440; C4 (middle C, MIDI 60) ≈ 261.63. + #expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 9, octave: 3) - 220.0) < 0.01) + #expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 9, octave: 4) - 440.0) < 0.01) + #expect(abs(KarplusResonatorPedal.noteFrequency(pitchClass: 0, octave: 4) - 261.6256) < 0.01) + } + + @Test func noteModeTunesTheRootToThePitch() throws { + // Tuning = Note, A3, Drone voicing → the ring's fundamental sits at 220 Hz regardless of the + // 110 Hz pluck or the Tune Hz knob. + let out: [Float] = try renderPluck { pedal in + pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6 + pedal.tune = 60.0 // deliberately off, to prove Note overrides it + pedal.tuning = 1.0; pedal.note = 9.0; pedal.octave = 3.0 + } + let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 400.0) + #expect(abs(f - 220.0) / 220.0 < 0.1, "Note A3 should ring near 220 Hz, got \(f)") + } + + @Test func noteModeOctaveRaisesThePitch() throws { + // A3 vs A4 — one octave up should roughly double the ring fundamental. + let a3: [Float] = try renderPluck { pedal in + pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6 + pedal.tuning = 1.0; pedal.note = 9.0; pedal.octave = 3.0 + } + let a4: [Float] = try renderPluck { pedal in + pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6 + pedal.tuning = 1.0; pedal.note = 9.0; pedal.octave = 4.0 + } + let f3: Double = fundamentalHz(a3, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 700.0) + let f4: Double = fundamentalHz(a4, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 700.0) + #expect(f4 > f3 * 1.5, "A4 should ring well above A3: a4 \(f4) vs a3 \(f3)") } @Test func presetRoundTripPreservesControls() throws { @@ -367,6 +406,9 @@ struct KarplusResonatorPedalTests { pedal.tone = 0.6 pedal.sensitivity = 0.3 pedal.voicing = 2.0 + pedal.tuning = 1.0 + pedal.note = 4.0 + pedal.octave = 5.0 let state: PedalState = pedal.captureState() let restored: KarplusResonatorPedal = KarplusResonatorPedal() @@ -377,6 +419,9 @@ struct KarplusResonatorPedalTests { #expect(restored.tone == 0.6) #expect(restored.sensitivity == 0.3) #expect(restored.voicing == 2.0) + #expect(restored.tuning == 1.0) + #expect(restored.note == 4.0) + #expect(restored.octave == 5.0) } @Test func registeredInBuiltInRegistry() throws {