From eafc68d283b6da3d61121ee8cb31018674c7d78a Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 27 Jun 2026 20:50:22 -0700 Subject: [PATCH] Add Harmonizer pedal and a stepped selector-knob control Harmonizer: two granular PitchShift voices at fixed musical intervals (ratio 2^(semitones/12) via Exp), mixed under the dry signal with V1/V2/ Direct level knobs. Two interval "knob pickers" snap through octave, fifth, fourth, and minor/major third and sixth above and below. New reusable control: - PedalSelectorKnob (model) + PedalSelectorKnobView (rotary knob that snaps to labelled stops; drag up/down to step, shows the stop caption). - Pedal.effectSelectors hook; PedalView renders a selector row. - PedalState.selectorValues for preset round-trip (forward-compatible). Registered + PedalType.harmonizer + enclosure color + palette slot. Tests: build/non-silent, interval-change-changes-output, selector preset round-trip, registry. Full suite 213 passing. Co-Authored-By: Claude Opus 4.8 --- Sources/LyrebirdShoeGaze/Pedal.swift | 9 + .../LyrebirdShoeGaze/PedalSelectorKnob.swift | 68 +++++++ Sources/LyrebirdShoeGaze/PedalType.swift | 1 + .../Pedals/HarmonizerPedal.swift | 146 +++++++++++++++ .../Presets/Pedal+Preset.swift | 5 + .../Presets/PedalRegistry.swift | 1 + .../LyrebirdShoeGaze/Presets/PedalState.swift | 13 +- .../LyrebirdShoeGazeUI/PedalPaletteView.swift | 1 + .../PedalSelectorKnobView.swift | 126 +++++++++++++ Sources/LyrebirdShoeGazeUI/PedalView.swift | 18 ++ .../HarmonizerPedalTests.swift | 147 +++++++++++++++ docs/plans/1.2-new-pedals.md | 170 ++++++++++++++++++ 12 files changed, 703 insertions(+), 2 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/PedalSelectorKnob.swift create mode 100644 Sources/LyrebirdShoeGaze/Pedals/HarmonizerPedal.swift create mode 100644 Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift create mode 100644 Tests/LyrebirdShoeGazeTests/HarmonizerPedalTests.swift create mode 100644 docs/plans/1.2-new-pedals.md diff --git a/Sources/LyrebirdShoeGaze/Pedal.swift b/Sources/LyrebirdShoeGaze/Pedal.swift index fac8272..8f79c4c 100644 --- a/Sources/LyrebirdShoeGaze/Pedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedal.swift @@ -168,6 +168,15 @@ open class Pedal: SynthesizerBase { [] } + /// Effect-specific stepped "knob picker" controls for this pedal, rendered as a row of rotary + /// knobs that snap to labelled stops, beneath the knob grid. + /// + /// Override in subclasses to publish each discrete `@UIParam` parameter that reads best as a + /// knob that snaps through fixed positions (e.g. a harmony interval selector). Defaults to empty. + open var effectSelectors: [PedalSelectorKnob] { + [] + } + /// All knobs a generic UI should render for this pedal: effect-specific knobs /// first, then the common `mix` and `level` knobs. The `bypass` parameter is /// surfaced separately as a header toggle, not as a knob. diff --git a/Sources/LyrebirdShoeGaze/PedalSelectorKnob.swift b/Sources/LyrebirdShoeGaze/PedalSelectorKnob.swift new file mode 100644 index 0000000..76ff364 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/PedalSelectorKnob.swift @@ -0,0 +1,68 @@ +// PedalSelectorKnob.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdUI + +/// A UI-agnostic description of a knob that snaps to a fixed set of labelled stops. +/// +/// Where ``PedalKnob`` is a continuous rotary and ``PedalSwitch`` is a segmented strip, a +/// `PedalSelectorKnob` reads like a rotary knob but quantises to discrete positions — a knob picker. +/// Dragging rotates through the stops; the knob shows the current stop's caption. A `Pedal` +/// publishes an array of these via ``Pedal/effectSelectors`` so a generic pedalboard UI can render +/// a stepped knob per discrete parameter without knowing the concrete type. +/// +/// Each stop pairs a short caption with the exact `Double` written to the live ``UIParamNode`` when +/// that position is selected; the lit position is the stop whose `value` is nearest the node's +/// current value. +public struct PedalSelectorKnob { + + /// One labelled position of a ``PedalSelectorKnob``. + public struct Stop { + + /// Short caption shown under the knob when this position is selected (e.g. "M3", "Oct"). + public let title: String + + /// Value written to the node when this position is selected. + public let value: Double + + /// Creates a selector stop. + /// + /// - Parameters: + /// - title: Short caption shown when this position is selected. + /// - value: Value written to the node when this position is selected. + public init(title: String, value: Double) { + self.title = title + self.value = value + } + } + + /// Short label shown beneath the knob (e.g. "Voice 1"). + public let label: String + + /// The live parameter node the knob reads and writes. Pass `pedal.$paramName`. + public let node: UIParamNode + + /// Ordered stops the knob snaps through, from fully counter-clockwise to fully clockwise. Must + /// contain at least two. + public let stops: [Stop] + + /// Creates a selector-knob descriptor. + /// + /// - Parameters: + /// - label: Short label shown beneath the knob. + /// - node: The `UIParamNode` projected value of an `@UIParam` property (`pedal.$voice1`, …). + /// - stops: Ordered stops, CCW → CW. At least two. + public init( + label: String, + node: UIParamNode, + stops: [Stop] + ) { + precondition(stops.count >= 2, "PedalSelectorKnob requires at least two stops") + self.label = label + self.node = node + self.stops = stops + } +} diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index 559fac0..d641f76 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -76,4 +76,5 @@ public extension PedalType { // Pitch & octave static let octaveSplitter = PedalType("Octave Splitter") static let bassOctaver = PedalType("Bass Octaver") + static let harmonizer = PedalType("Harmonizer") } diff --git a/Sources/LyrebirdShoeGaze/Pedals/HarmonizerPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/HarmonizerPedal.swift new file mode 100644 index 0000000..8f04026 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/HarmonizerPedal.swift @@ -0,0 +1,146 @@ +// HarmonizerPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// Two-voice diatonic-interval harmonizer. +/// +/// Adds two pitch-shifted harmony voices at fixed musical intervals above or below the input, +/// mixed against the dry signal — an OC-2-style level layout (Voice 1 / Voice 2 / Direct) with a +/// knob picker selecting each voice's interval. +/// +/// Each voice is a granular `PitchShift` whose ratio is `2^(semitones/12)`, driven live from the +/// voice's interval selector. Intervals include minor and major thirds above and below, plus +/// fourths, fifths, and octaves. +/// +/// ## Knobs +/// - `voice1Level`: Voice 1 level in `[0, 1]`. +/// - `voice2Level`: Voice 2 level in `[0, 1]`. +/// - `direct`: Dry signal level in `[0, 1]`. +/// +/// ## Selectors (knob pickers) +/// - `voice1`: Voice 1 interval in semitones (snaps to musical intervals). +/// - `voice2`: Voice 2 interval in semitones. +public final class HarmonizerPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Two pitch-shifted harmony voices at intervals you pick, stacked under your note." + } + + // MARK: - Parameters + + /// Voice 1 interval in semitones. Snaps to musical-interval stops. + @UIParam public var voice1: Double = 4.0 + + /// Voice 2 interval in semitones. Snaps to musical-interval stops. + @UIParam public var voice2: Double = 7.0 + + /// Voice 1 level in `[0, 1]`. + @UIParam public var voice1Level: Double = 0.6 + + /// Voice 2 level in `[0, 1]`. + @UIParam public var voice2Level: Double = 0.45 + + /// Dry (direct) signal level in `[0, 1]`. + @UIParam public var direct: Double = 1.0 + + // MARK: - Constants + + /// Pedal blends internally via the level knobs, so the base wet/dry stays fully wet. + private static let defaultMix: Double = 1.0 + + /// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio`. + private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12 + + /// Granular pitch-shift window in seconds. Larger = smoother but more latency. + private let windowSize: Double = 0.1 + + // MARK: - Ranges + + private let levelRange: ClosedRange = 0.0 ... 1.0 + + // MARK: - Knobs + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "V1 Level", node: $voice1Level, range: levelRange), + PedalKnob(label: "V2 Level", node: $voice2Level, range: levelRange), + PedalKnob(label: "Direct", node: $direct, range: levelRange), + ] + } + + // MARK: - Selectors + + /// Musical-interval stops for the voice pickers, low to high. Values are semitones; captions are + /// short interval names (`m3`/`M3` = minor/major third, `4`/`5` = perfect fourth/fifth, + /// `8ve` = octave, `Uni` = unison). Minus = below the input. + private static let intervalStops: [PedalSelectorKnob.Stop] = [ + PedalSelectorKnob.Stop(title: "-8ve", value: -12.0), + PedalSelectorKnob.Stop(title: "-M6", value: -9.0), + PedalSelectorKnob.Stop(title: "-m6", value: -8.0), + PedalSelectorKnob.Stop(title: "-5", value: -7.0), + PedalSelectorKnob.Stop(title: "-4", value: -5.0), + PedalSelectorKnob.Stop(title: "-M3", value: -4.0), + PedalSelectorKnob.Stop(title: "-m3", value: -3.0), + PedalSelectorKnob.Stop(title: "Uni", value: 0.0), + PedalSelectorKnob.Stop(title: "m3", value: 3.0), + PedalSelectorKnob.Stop(title: "M3", value: 4.0), + PedalSelectorKnob.Stop(title: "4", value: 5.0), + PedalSelectorKnob.Stop(title: "5", value: 7.0), + PedalSelectorKnob.Stop(title: "m6", value: 8.0), + PedalSelectorKnob.Stop(title: "M6", value: 9.0), + PedalSelectorKnob.Stop(title: "8ve", value: 12.0), + ] + + public override var effectSelectors: [PedalSelectorKnob] { + [ + PedalSelectorKnob(label: "Voice 1", node: $voice1, stops: HarmonizerPedal.intervalStops), + PedalSelectorKnob(label: "Voice 2", node: $voice2, stops: HarmonizerPedal.intervalStops), + ] + } + + // MARK: - Init + + /// Creates a harmonizer pedal. + /// + /// - Parameters: + /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. + /// - outputBus: Audio bus index to write the output to. Defaults to `0`. + public init( + inputBus: Int = 0, + outputBus: Int = 0 + ) { + super.init( + name: "Harmonizer", + inputBus: inputBus, + outputBus: outputBus, + initialMix: HarmonizerPedal.defaultMix + ) + } + + // MARK: - Effect + + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + let voice1Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice1) + let voice2Signal: any ValidGeneratorInput = harmonyVoice(dry, semitones: $voice2) + + let directVoice: any ValidGeneratorInput = dry * $direct + let harmony1: any ValidGeneratorInput = voice1Signal * $voice1Level + let harmony2: any ValidGeneratorInput = voice2Signal * $voice2Level + return directVoice + harmony1 + harmony2 + } + + /// One pitch-shifted voice: ratio `2^(semitones/12)` via `Exp`, fed to a granular `PitchShift`. + private func harmonyVoice( + _ dry: any ValidGeneratorInput, + semitones: any ValidGeneratorInput + ) -> any ValidGeneratorInput { + let ratio: Exp.Audio = Exp.Audio(semitones * semitoneToRatioScale) + return PitchShift.Audio(input: dry, pitchRatio: ratio, windowSize: windowSize) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift index 76d4df2..54af6b7 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift @@ -19,11 +19,13 @@ extension Pedal { let values: [Double] = knobs.map { $0.node.value } let switchValues: [Double] = effectSwitches.map { $0.node.value } let sliderValues: [Double] = effectSliders.map { $0.node.value } + let selectorValues: [Double] = effectSelectors.map { $0.node.value } return PedalState( type: displayName, knobValues: values, switchValues: switchValues, sliderValues: sliderValues, + selectorValues: selectorValues, bypass: bypass ) } @@ -51,6 +53,9 @@ extension Pedal { for (slider, value) in zip(effectSliders, state.sliderValues) { slider.node.update(value) } + for (selector, value) in zip(effectSelectors, state.selectorValues) { + selector.node.update(value) + } bypass = state.bypass } } diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index 2b36334..f0febc2 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -45,6 +45,7 @@ public enum PedalRegistry { "Multi-Tap Delay": { MultiTapDelayPedal() }, "Octave Splitter": { OctaveUpSplitterPedal() }, "Bass Octaver": { BassOctaverPedal() }, + "Harmonizer": { HarmonizerPedal() }, "Ping-Pong": { PingPongDelayPedal() }, "Limiter": { LimiterPedal() }, "Noise Gate": { NoiseGatePedal() }, diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift index ea418f4..daa2293 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift @@ -30,6 +30,10 @@ public struct PedalState: Codable, Equatable { /// no sliders. Absent in presets saved before sliders existed — decodes to `[]`. public let sliderValues: [Double] + /// Selector-knob values in the same order as `Pedal.effectSelectors`. Empty for pedals with + /// no selectors. Absent in presets saved before selectors existed — decodes to `[]`. + public let selectorValues: [Double] + /// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed. public let bypass: Double @@ -40,18 +44,21 @@ public struct PedalState: Codable, Equatable { /// - knobValues: Current knob values in `Pedal.knobs` order. /// - switchValues: Current switch values in `Pedal.effectSwitches` 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. /// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed). public init( type: String, knobValues: [Double], switchValues: [Double] = [], sliderValues: [Double] = [], + selectorValues: [Double] = [], bypass: Double ) { self.type = type self.knobValues = knobValues self.switchValues = switchValues self.sliderValues = sliderValues + self.selectorValues = selectorValues self.bypass = bypass } @@ -60,17 +67,19 @@ public struct PedalState: Codable, Equatable { case knobValues case switchValues case sliderValues + case selectorValues case bypass } - /// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` - /// existed by defaulting the missing keys to an empty array. + /// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` / + /// `selectorValues` existed by defaulting the missing keys to an empty array. public init(from decoder: any Decoder) throws { let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) self.type = try container.decode(String.self, forKey: .type) self.knobValues = try container.decode([Double].self, forKey: .knobValues) self.switchValues = try container.decodeIfPresent([Double].self, forKey: .switchValues) ?? [] self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? [] + self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? [] self.bypass = try container.decode(Double.self, forKey: .bypass) } } diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift index 04aead2..84f41f1 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -54,6 +54,7 @@ public struct PedalPaletteView: View { "Overdrive", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", "Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Auto-Wah", "Mutant", "Ring Modulator", "Diffuser", "Bass Octaver", "Octave Splitter", + "Harmonizer", "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb", ] diff --git a/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift b/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift new file mode 100644 index 0000000..d9bfbba --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/PedalSelectorKnobView.swift @@ -0,0 +1,126 @@ +// PedalSelectorKnobView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGaze + +/// Renders a ``PedalSelectorKnob`` — a rotary knob that snaps to a fixed set of labelled stops. +/// +/// Visually matches `ParameterKnob` (same dial + indicator), but drag quantises to discrete +/// positions and the caption shows the current stop's title rather than a numeric value. Drag up to +/// advance clockwise through the stops, down to go back. +struct PedalSelectorKnobView: View { + + // MARK: - Layout constants + + private static let dialSize: CGFloat = 50 + private static let indicatorWidth: CGFloat = 2 + private static let indicatorHeight: CGFloat = 14 + private static let indicatorInset: CGFloat = 3 + private static let startAngle: Double = -135.0 + private static let totalArc: Double = 270.0 + /// Pixels of vertical drag per stop step. + private static let pixelsPerStep: CGFloat = 22 + private static let labelSpacing: CGFloat = 4 + + // MARK: - Input + + private let selector: PedalSelectorKnob + + // MARK: - Drag state + + @State private var dragStartIndex: Int = 0 + @State private var dragInProgress: Bool = false + + // MARK: - Init + + init(_ selector: PedalSelectorKnob) { + self.selector = selector + } + + // MARK: - Body + + var body: some View { + VStack(spacing: PedalSelectorKnobView.labelSpacing) { + dial + .frame(width: PedalSelectorKnobView.dialSize, height: PedalSelectorKnobView.dialSize) + .gesture(dragGesture) + Text(selector.label) + .font(.caption) + .foregroundStyle(Color.white) + Text(currentStop.title) + .font(.caption) + .foregroundStyle(Color.white) + } + } + + // MARK: - Dial + + private var dial: some View { + let count: Int = selector.stops.count + let normalised: Double = count > 1 ? Double(currentIndex) / Double(count - 1) : 0 + let rotation: Double = PedalSelectorKnobView.startAngle + normalised * PedalSelectorKnobView.totalArc + let offset: CGFloat = -(PedalSelectorKnobView.dialSize / 2 + - PedalSelectorKnobView.indicatorHeight / 2 + - PedalSelectorKnobView.indicatorInset) + + return ZStack { + Circle() + .fill(Color.lyrebirdControlBackground) + .overlay(Circle().stroke(Color.lyrebirdSeparator, lineWidth: 1)) + Rectangle() + .fill(Color.accentColor) + .frame( + width: PedalSelectorKnobView.indicatorWidth, + height: PedalSelectorKnobView.indicatorHeight + ) + .offset(y: offset) + .rotationEffect(.degrees(rotation)) + } + } + + // MARK: - Drag + + private var dragGesture: some Gesture { + DragGesture(minimumDistance: 1) + .onChanged { gesture in + if !dragInProgress { + dragInProgress = true + dragStartIndex = currentIndex + } + let delta: CGFloat = gesture.translation.height // down = positive + // Up should advance (increase index), so subtract the downward delta. + let steps: Int = Int((-delta / PedalSelectorKnobView.pixelsPerStep).rounded()) + let target: Int = min(max(dragStartIndex + steps, 0), selector.stops.count - 1) + let value: Double = selector.stops[target].value + if value != selector.node.value { + selector.node.update(value) + } + } + .onEnded { _ in dragInProgress = false } + } + + // MARK: - Helpers + + /// Index of the stop whose value is nearest the node's current value. + private var currentIndex: Int { + let value: Double = selector.node.value + var bestIndex: Int = 0 + var bestDistance: Double = .greatestFiniteMagnitude + for (index, stop) in selector.stops.enumerated() { + let distance: Double = abs(stop.value - value) + if distance < bestDistance { + bestDistance = distance + bestIndex = index + } + } + return bestIndex + } + + private var currentStop: PedalSelectorKnob.Stop { + selector.stops[currentIndex] + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index eda0df1..25d04ca 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -35,6 +35,7 @@ private func enclosureColor(for displayName: String) -> Color { case "Sustainer": return Color(red: 0.22, green: 0.46, blue: 0.30) // pine green case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle + case "Harmonizer": return Color(red: 0.52, green: 0.20, blue: 0.40) // wine / mauve default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray } } @@ -277,6 +278,7 @@ public struct PedalView: View { VStack(spacing: PedalView.sectionSpacing) { namePlate knobGrid + selectorRow switchRow sliderBank(sliders) Spacer(minLength: 0) @@ -371,6 +373,22 @@ public struct PedalView: View { } } + /// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid. + /// Renders nothing when the pedal publishes no selectors. + @ViewBuilder + private var selectorRow: some View { + let selectors: [PedalSelectorKnob] = pedal.effectSelectors + if !selectors.isEmpty { + HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) { + Spacer(minLength: 0) + ForEach(Array(selectors.enumerated()), id: \.offset) { pair in + PedalSelectorKnobView(pair.element) + } + Spacer(minLength: 0) + } + } + } + /// Row of segmented switches drawn from `pedal.effectSwitches`, one per row, beneath /// the knob grid. Renders nothing when the pedal publishes no switches. @ViewBuilder diff --git a/Tests/LyrebirdShoeGazeTests/HarmonizerPedalTests.swift b/Tests/LyrebirdShoeGazeTests/HarmonizerPedalTests.swift new file mode 100644 index 0000000..41d111e --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/HarmonizerPedalTests.swift @@ -0,0 +1,147 @@ +// HarmonizerPedalTests.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("HarmonizerPedal") +struct HarmonizerPedalTests { + + /// Renders the pedal through an NRT engine with the given configuration and returns the output. + private func render( + configure: (HarmonizerPedal) -> Void + ) throws -> [Float] { + let renderDuration: Double = 0.3 + let numAudioBuses: Int = 64 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: renderDuration, + numAudioBuses: numAudioBuses + ) + 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: HarmonizerPedal = HarmonizerPedal( + 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 stable window of two renders. + private func windowedSSD(_ a: [Float], _ b: [Float]) -> Double { + let skipSamples: Int = 4096 + let windowSize: Int = 2048 + guard a.count >= skipSamples + windowSize, + b.count >= skipSamples + windowSize else { return 0.0 } + let aWindow: ArraySlice = a[skipSamples..<(skipSamples + windowSize)] + let bWindow: ArraySlice = b[skipSamples..<(skipSamples + windowSize)] + return zip(aWindow, bWindow).reduce(0.0) { acc, pair in + let diff: Double = Double(pair.0 - pair.1) + return acc + diff * diff + } + } + + @Test func buildsAndProducesNonSilentOutput() throws { + let samples: [Float] = try render { pedal in + pedal.direct = 1.0 + pedal.voice1Level = 0.6 + pedal.voice2Level = 0.5 + } + #expect(!samples.isEmpty) + #expect(hasNonSilentOutput(samples), "harmonizer output was silent") + } + + @Test func changingVoiceIntervalChangesOutput() throws { + let third: [Float] = try render { pedal in + pedal.direct = 0.0 + pedal.voice1Level = 1.0 + pedal.voice2Level = 0.0 + pedal.voice1 = 3.0 // minor third up + } + let fifth: [Float] = try render { pedal in + pedal.direct = 0.0 + pedal.voice1Level = 1.0 + pedal.voice2Level = 0.0 + pedal.voice1 = 7.0 // perfect fifth up + } + #expect(hasNonSilentOutput(third), "minor-third voice was silent") + #expect(hasNonSilentOutput(fifth), "fifth voice was silent") + #expect(windowedSSD(third, fifth) > 0, "changing the interval did not change the output") + } + + @Test func harmonyVoicesDifferFromDirectOnly() throws { + let directOnly: [Float] = try render { pedal in + pedal.direct = 1.0 + pedal.voice1Level = 0.0 + pedal.voice2Level = 0.0 + } + let withVoices: [Float] = try render { pedal in + pedal.direct = 1.0 + pedal.voice1Level = 1.0 + pedal.voice2Level = 1.0 + } + #expect(hasNonSilentOutput(directOnly), "direct-only render was silent") + #expect(windowedSSD(directOnly, withVoices) > 0, "adding harmony voices did not change the output") + } + + @Test func exposesLevelKnobs() throws { + let pedal: HarmonizerPedal = HarmonizerPedal() + let labels: [String] = pedal.effectKnobs.map { $0.label } + #expect(labels == ["V1 Level", "V2 Level", "Direct"]) + } + + @Test func exposesTwoIntervalSelectors() throws { + let pedal: HarmonizerPedal = HarmonizerPedal() + let selectors: [PedalSelectorKnob] = pedal.effectSelectors + #expect(selectors.map { $0.label } == ["Voice 1", "Voice 2"]) + // Both minor- and major-thirds above and below must be available. + let titles: [String] = selectors.first?.stops.map { $0.title } ?? [] + #expect(titles.contains("m3")) + #expect(titles.contains("M3")) + #expect(titles.contains("-m3")) + #expect(titles.contains("-M3")) + } + + @Test func presetRoundTripPreservesIntervalsAndLevels() throws { + let pedal: HarmonizerPedal = HarmonizerPedal() + pedal.voice1 = -3.0 + pedal.voice2 = 12.0 + pedal.voice1Level = 0.3 + + let state: PedalState = pedal.captureState() + #expect(state.selectorValues == [-3.0, 12.0]) + + let restored: HarmonizerPedal = HarmonizerPedal() + restored.applyState(state) + #expect(restored.voice1 == -3.0) + #expect(restored.voice2 == 12.0) + #expect(restored.voice1Level == 0.3) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "Harmonizer") + #expect(pedal is HarmonizerPedal) + } +} diff --git a/docs/plans/1.2-new-pedals.md b/docs/plans/1.2-new-pedals.md new file mode 100644 index 0000000..0a64ef8 --- /dev/null +++ b/docs/plans/1.2-new-pedals.md @@ -0,0 +1,170 @@ +# 1.2 New Pedals — Plan + +Eight pedals targeted for 1.2 (Wah deferred — pending MIDI-control hardware). Grounded against the +Lyrebird generators actually available. Each entry lists the signal path, the generators used, +controls, channel kind, the per-pedal checklist (registry / `PedalType` / enclosure color / palette +order / tests), and effort. + +Effort legend: **S** = thin wrapper over existing generators; **M** = composite graph; **L** = +needs a new RT-safe generator first. + +Build order recommendation: Flanger → Vibrato → Distortion → Harmonizer → Rotary → Shimmer Reverb → +Reverse Delay → Bitcrusher. (Cheap/whole-cloth-available first; new-generator pedals last.) + +--- + +## 1. Flanger — **S** + +Lyrebird already ships `Flanger.Audio(input:delayTime:depth:rate:feedback:mix:sampleRate:maxDelayTime:)`. +Thin wrapper like `ModulationPedal`. + +- **Path:** `dry → Flanger.Audio → wet` (base `mix`/`level`/bypass handle blend). +- **Controls (knobs):** Rate (0.05–8 Hz), Depth (0–1), Feedback (0–0.95), Manual/center delay + (0.001–0.01 s, optional). Mix inherited. +- **Channel:** `.processor` (mono). A stereo `.widener` variant (two LFOs anti-phase, like + `ChorusPedal`) is a nice follow-up but not required. +- **Effort:** S. + +## 2. Vibrato — **S** + +Pitch wobble = a single swept delay line, fully wet (no dry blend). Mirrors `ChorusPedal.voice` but +`initialMix = 1.0` and one voice. + +- **Path:** `dry → DelayLine(delay: OscSin(rate, mul: depth, add: base)) → wet`, `mix = 1.0`. +- **Controls:** Rate (0.1–8 Hz), Depth (0.0005–0.006 s). (Expose Depth as "Depth"; keep mix locked + fully wet — vibrato is not a blend effect.) +- **Channel:** `.processor`. +- **Effort:** S. Distinct from Tremolo (amplitude) — document the difference in `summary`. + +## 3. Distortion — **S** + +Mid-gain clipper between Overdrive (soft) and Fuzz (extreme). Reuse the `Tanh.Audio` drive trick +from `BassOctaverPedal`, plus a tone tilt and output clamp. + +- **Path:** `dry → HPF(~80) → Tanh(mul: drive) → tone (RBJLowPass, freq from Tone knob) → Clip(-1,1) + → wet`. (Optionally `Waveshaper` with a fixed asymmetric table for more character.) +- **Controls:** Drive (1–50), Tone (500–6000 Hz), Level (inherited). Mix default 1.0. +- **Channel:** `.processor`. +- **Effort:** S. Pick clipping flavor at impl: `Tanh` (smooth), `Clip` (hard), or `Fold` (octave-y). + Recommend `Tanh` → `Clip` cascade. + +## 4. Harmonizer — **M** (user priority) + +Two pitch-shifted harmony voices at **fixed, user-picked interval ratios**, mixed under the dry +signal. Uses `PitchShift.Audio` (granular, real-time, mono, `pitchRatio` clamped 0.25–4.0). + +- **Path:** + ``` + dry ─┬───────────────────────────────── direct·directLevel + ├─ PitchShift(pitchRatio: r1) ····· × voice1Level + └─ PitchShift(pitchRatio: r2) ····· × voice2Level → sum + ``` +- **Interval ratios:** semitone → ratio `2^(n/12)`. Offer a musical set, e.g. + `-12, -7, -5, -3, 0, +3, +4, +5, +7, +12` semitones (octave/5th/4th/3rds). Map each option's + `value` to the ratio at build time. +- **Controls:** + - **Voice 1 Interval** + **Voice 2 Interval** — the "knob pickers" for fixed ratios. + - **Voice 1 Level**, **Voice 2 Level**, **Direct** (dry) level knobs (OC-2-style, like + `BassOctaverPedal`). +- **Picker control (decided):** add a new **`PedalSelectorKnob`** — a knob that snaps to labeled + stops. Reusable for future discrete-knob pedals. Interval stops must include minor- and major-3rd + **above and below**: `-12, -7, -5, -4, -3, 0, +3, +4, +5, +7, +12` semitones (m3 = ±3, M3 = ±4, + P4 = ±5, P5 = ±7, octave = ±12, 0 = unison/off). Each stop's value maps to ratio `2^(n/12)`. + Default voices: Voice 1 = +4 (M3 up), Voice 2 = +7 (P5 up). +- **Channel:** `.processor` (sum to mono). Optional `.widener` (pan the two voices L/R) as a follow-up. +- **Effort:** M. Watch granular latency/CPU with two `PitchShift` instances; verify under the + 512-block engine. Consider `windowSize` tuning per voice for smoothness. + +## 5. Rotary / Leslie — **M** + +Leslie = amplitude modulation (volume throb) + frequency modulation (Doppler pitch wobble) + +stereo spread, with a two-speed (Chorale/Tremolo) ramp. + +- **Path (per channel, `.widener`):** + `dry → DelayLine(delay: OscSin(rate, mul: depth, add: base)) → ×(0.5 + 0.5·OscSin(rate, phase))`, + left/right LFOs offset (≈180°) for rotating stereo image. AM and FM share the rotor `rate`. +- **Controls:** Speed switch (Chorale ≈0.8 Hz / Tremolo ≈6.5 Hz) via `PedalSwitch`; **Accel** knob + (ramp time between speeds); **Depth**/**Mix**. Acceleration ramp = a `Lag`/`Decay` on the rate + target so speed changes glide (authentic spin-up/down). +- **Alternative:** `PanAzDistance.Audio` gives real Doppler but outputs 4 channels — would need a + 4→2 downmix; the LFO-AM+FM approach above stays stereo and is simpler. Recommend the simple path + for 1.2. +- **Channel:** `.widener`. +- **Effort:** M. + +## 6. Shimmer Reverb — **M** (with caveat) + +Octave-up sparkle over a reverb tail. Built on an existing reverb (`PlateReverb` or `GVerb`) plus +`PitchShift(pitchRatio: 2.0)`. + +- **Caveat — no true regeneration:** Lyrebird's per-synth graph is an acyclic DAG, so a real + *regenerating* shimmer feedback loop (tail → pitch-up → back into tail) isn't expressible inside + one pedal. For 1.2 ship the **parallel** approximation: + ``` + dry ─┬─ Reverb ───────────────── tail + └─ PitchShift(×2) → Reverb → shimmer → blend + ``` + This gives the shimmer character without infinite regeneration. True regenerative shimmer needs a + bus-feedback structure (cross-block) or a new feedback-capable generator — note as a future item. +- **Controls:** Room/Decay, Shimmer amount (pitch-voice level), Damp, Mix. +- **Channel:** `.widener` (reverbs output stereo — keep L/R). +- **Effort:** M. Confirm which reverb `ReverbPedal` already uses to avoid duplication; pick the other + (or add an algorithm switch). + +## 7. Reverse Delay — **L** (needs new generator) + +No reverse-capable delay exists in Lyrebird. Add a new RT-safe generator (in ShoeGaze, or upstream +in Lyrebird Delays). + +- **New generator `ReverseDelay`:** pre-allocated segment buffer (max length fixed at init, no RT + alloc); record forward into a segment, play it back reversed; segment length = delay time; + optional feedback. Crossfade at segment boundaries to avoid clicks. Follow Lyrebird generator + rules (`GeneratorBase`, `_checkCount`, pre-allocated buffers, no RT alloc/locks). +- **Pedal path:** `dry → ReverseDelay(time, feedback) → wet`. +- **Controls:** Time (0.05–2 s), Feedback (0–0.9), Mix. +- **Channel:** `.processor`. +- **Effort:** L (generator + tests first, then the thin pedal). Run `lyrebird_external_review` on the + new generator for RT safety. + +## 8. Bitcrusher / Lo-Fi — **L** (needs new generators) + +No decimation/bit-reduction generators exist. Add two small RT-safe generators. + +- **New generators:** + - `SampleRateDecimate` — sample-and-hold at a reduced rate (hold last sample for N input samples; + rate or downsample-factor parameter). + - `BitReduce` — quantize amplitude to `2^bits` levels. + (Both trivial per-sample math, pre-allocated state only.) +- **Pedal path:** `dry → SampleRateDecimate(rate) → BitReduce(bits) → (optional RBJLowPass tone) → + wet`. +- **Controls:** Sample Rate / Downsample (knob), Bits (1–16, stepped), Tone, Mix. +- **Channel:** `.processor`. +- **Effort:** L (two generators + tests, then pedal). Consider contributing the generators upstream + to Lyrebird since they're broadly useful. + +--- + +## Cross-cutting checklist (every pedal) + +Per `CLAUDE.md` "Adding a new pedal": +1. `Sources/LyrebirdShoeGaze/Pedals/Pedal.swift` — subclass `Pedal`, override `effect`/ + `wideEffect`, `effectKnobs`/`effectSwitches`/`effectSliders`. +2. **`summary`** (mandatory, one line). +3. Register in `PedalRegistry.builtIn[""]`. +4. Add `PedalType.`. +5. Enclosure color in `PedalView.enclosureColor(for:)`. +6. Add to `PedalPaletteView.preferredOrder` (group with family: gain near Overdrive/Fuzz; modulation + near Chorus/Phaser; pitch near the octavers; delay/reverb near their families). +7. Tests in `Tests/LyrebirdShoeGazeTests/PedalTests.swift` — builds + non-silent, each param + measurably changes output, knob/switch list assertions, preset round-trip if it has + switches/sliders. +8. Use `PedalType` static members at call sites. + +## Decisions (resolved) + +- **Harmonizer picker:** new `PedalSelectorKnob` (stepped knob) with the ±3rd interval set above. + Build the Harmonizer first to evaluate the control. +- **New generators (Reverse Delay, Bitcrush):** land in the **ShoeGaze package** (self-contained; + no Lyrebird-release dependency for 1.2). +- **Shimmer:** scope a **true regenerative** version (cross-block bus feedback) rather than the + parallel approximation — larger, may slip 1.2.