diff --git a/README.md b/README.md index af64591..fdf2fb0 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ signal (no hardware needed) or on live guitar through an audio input. | Modulation | Tremolo, Phaser, Script Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator | | Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy, Poly Octave | | Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay, DL4 | -| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb, Granular Reverb, Freeze, FreezVerb | +| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb, Granular Reverb, FreezVerb, TunedVerb | | Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Karplus Resonator, Looper, Tape Looper | | Amp Model | Fullerton Reverb / Deluxe / Ivy League / Drive, California, Jazz Clean, British / Plexi / JTM / Bluesbreaker / Master / Dual, Chime / Chime Top Boost / 15 / Normal / Baby, Boutique Lead / OD, Cali Hi-Gain, Modern High-Gain, Command, Citrus, Sixties Combo, Magna Vibrato, Anaheim | | Cabinet | Cabinet (speaker-voice + microphone modeling) | diff --git a/Sources/LyrebirdShoeGaze/PedalType.swift b/Sources/LyrebirdShoeGaze/PedalType.swift index 02e4e74..f974736 100644 --- a/Sources/LyrebirdShoeGaze/PedalType.swift +++ b/Sources/LyrebirdShoeGaze/PedalType.swift @@ -123,8 +123,8 @@ public extension PedalType { static let springReverb = PedalType("Spring Reverb") static let reverseReverb = PedalType("Reverse Reverb") static let granularReverb = PedalType("Granular Reverb") - static let freeze = PedalType("Freeze") static let freezVerb = PedalType("FreezVerb") + static let tunedVerb = PedalType("TunedVerb") // Pitch & octave static let octaveSplitter = PedalType("Octave Splitter") diff --git a/Sources/LyrebirdShoeGaze/Pedals/FreezVerbPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/FreezVerbPedal.swift index 9a7d267..211b587 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/FreezVerbPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/FreezVerbPedal.swift @@ -4,113 +4,109 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT +import Foundation import LyrebirdSynth import LyrebirdUI -/// A spectral *filter-from-the-current-moment* reverb — press **Capture** and the spectrum playing -/// at that instant is locked in as a fixed filter, and everything you play afterwards is poured -/// through that frozen spectral shape into a big reverb. +/// A true freeze-and-hold — press **Freeze** and the sound playing at that instant is +/// captured and held as an infinite, smoothly-sustaining pad while you keep playing over it. /// -/// Where ``FreezePedal`` holds a snapshot as a *sounding* pad, this holds a snapshot as a -/// *filter*. A `SpectralCrossMap` masks the live spectrum bin-by-bin against a template taken from a -/// side-chain analysis of the input: while live, the template tracks what you play; press Capture and -/// the template freezes, so the captured moment becomes a fixed formant mask on your ongoing signal. -/// The masked result feeds a large `GVerb` room (fixed 120 m) for a cavernous tail, and a **Pan** -/// knob places the stereo wash anywhere across the field. +/// Unlike a feedback-tank "infinite reverb" (which just pushes a reverb's decay toward forever and +/// smears everything you play into the wash), this takes a genuine **spectral snapshot**: a +/// phase-vocoder (`SpectralFreeze`) locks the magnitude spectrum of the moment you engage it and +/// keeps each partial rotating at its own frequency, so the held chord sounds natural and glassy +/// rather than a static loop or a metallic ring. That frozen spectrum is then wrapped in a `FreeVerb` +/// tank for a diffuse, blooming space — the "reverb" half of the name. /// -/// Ported from the composer's `FilterFromCurrentMoment` process: the original drew its filter from a -/// random pointer into a time-stretched buffer and spatialised with ambisonics; here the filter is -/// captured straight off the live input by the footswitch, and the output is plain stereo via the -/// Pan knob. +/// The dry signal always passes straight through, so you solo or comp over the held pad; the frozen +/// wash is layered on top (the wet/dry Mix knob is hidden and the base `mix` stays fully wet). Press +/// Freeze again to release it — the pad fades out over **Rise** and live analysis resumes, ready for +/// the next snapshot. /// /// ## Knobs -/// - `time`: Reverb tail length (GVerb T60) in seconds. Range `[0.5, 12.0]`. -/// - `damp`: High-frequency damping of the tail. Range `[0, 1]`: `0` = bright, `1` = dark. -/// - `pan`: Stereo position of the wash. Range `[-1, +1]`: `-1` = hard left, `+1` = hard right. +/// - `verb`: Size of the reverb space wrapped around the frozen pad. Range `[0, 1]`: bigger = washier. +/// - `tone`: Brightness of the pad. Range `[0, 1]`: `0` = dark, `1` = bright. +/// - `rise`: Fade time in seconds as the freeze blooms in and releases out. Range `[0.02, 4.0]`. /// /// ## Transport -/// - `Capture`: latching footswitch — press to lock the current-moment spectrum as the filter, press -/// again to return to live tracking. +/// - `Freeze`: latching footswitch — press to snapshot and hold, press again to release. public final class FreezVerbPedal: Pedal { /// One-line description shown in the picker and info panel. public override var summary: String { - "Capture a moment's spectrum as a filter and pour your playing through it into a vast room." + "Snapshot the moment and hold it forever — a spectral freeze wrapped in a blooming wash." } - /// Mono in, stereo out: the reverb wash is panned across the field by the ``pan`` knob. - public override var channelKind: PedalChannelKind { .widener } + /// The pad is layered over the untouched dry signal, so a wet/dry Mix knob is meaningless — hide + /// it and keep the base `mix` fully wet. + public override var showsMixControl: Bool { false } // MARK: - Parameters - /// Reverb tail length (GVerb T60) in seconds. Range `[0.5, 12.0]`. - @UIParam public var time: Double = 6.0 + /// Size of the reverb space wrapped around the frozen pad. Range `[0, 1]`: bigger = washier. + @UIParam public var verb: Double = 0.7 - /// High-frequency damping of the tail. Range `[0, 1]`: `0` = bright, `1` = dark. - @UIParam public var damp: Double = 0.5 + /// Brightness of the pad. Range `[0, 1]`: `0` = dark, `1` = bright. + @UIParam public var tone: Double = 0.5 - /// Stereo position of the wash. Range `[-1, +1]`: `-1` = hard left, `+1` = hard right. - @UIParam public var pan: Double = 0.0 + /// Fade time in seconds as the freeze blooms in and releases out. Range `[0.02, 4.0]`. + @UIParam public var rise: Double = 0.4 // MARK: - Internal live state (read by the audio graph) - /// `1` while the filter is locked to a captured moment, else `0`. Drives the Capture footswitch - /// LED. Transport state — not a preset control, so neither captured nor restored. - @UIParam public var captured: Double = 0.0 + /// `1` while a snapshot is held, else `0`. Drives the pad's fade gate and the Freeze footswitch + /// LED. Transport state, not a preset control — captured neither by `captureState` nor restored. + @UIParam public var frozen: Double = 0.0 // MARK: - Constants - /// FFT frame size for the spectral cross-map. Matches the composer's original process — large - /// enough for a finely-resolved formant filter at the cost of latency on the wet path (the dry - /// path is never delayed). - private static let fftSize: Int = 4096 + /// FFT frame size for the phase-vocoder freeze. Larger = finer frequency resolution (smoother + /// held chords) at the cost of more latency on the wet path; the dry path is never delayed. + private static let fftSize: Int = 2048 - /// Samples between FFT hops (75% overlap at `fftSize` 4096). - private static let hopSize: Int = 1024 + /// Samples between FFT hops (75% overlap at `fftSize` 2048) — fine enough for a clean, artifact- + /// free resynthesis of the held spectrum. + private static let hopSize: Int = 512 - /// GVerb room size in metres — fixed, as in the original process. Large, for a cavernous tail. - private let roomSize: Double = 120.0 + /// FreeVerb is run fully wet on the pad; the pedal's own dry/wet balance is the `frozen` gate plus + /// the base `mix`, so the tank should contribute none of its own dry path. + private let verbMix: Double = 1.0 - /// Cross-map blend: `1.0` = full spectral bandpass mask (loud template bins pass, quiet bins are - /// attenuated). Matches the original process. - private let crossMapMode: Double = 1.0 - - /// GVerb dry level — kept at `0` so the wet path is pure reverb; the base `mix` provides the - /// dry/wet blend. - private let verbDryLevel: Double = 0.0 - - /// Gain folding GVerb's two decorrelated channels to mono before the pan — a conservative trim - /// (the channels are not identical) that leaves output headroom. + /// Gain folding FreeVerb's two decorrelated channels to mono — a conservative trim (the channels + /// are not identical) that leaves output headroom. private let stereoSumGain: Double = 0.5 + /// Floor on the release-fade delay, in seconds. On release the gate ramps down over `rise`, but we + /// keep the snapshot playing until the fade has essentially finished; this ensures even the + /// shortest `rise` still defers the return-to-live by a sensible minimum. + private static let minReleaseDefer: Double = 0.05 + // MARK: - Ranges - private let timeRange: ClosedRange = 0.5 ... 12.0 - private let dampRange: ClosedRange = 0.0 ... 1.0 - private let panRange: ClosedRange = -1.0 ... 1.0 + private let unitRange: ClosedRange = 0.0 ... 1.0 + private let riseRange: ClosedRange = 0.02 ... 4.0 - // MARK: - Live generator references (rebuilt each `wideEffect(_:)`) + // MARK: - Live generator references (rebuilt each `effect(_:)`) - /// The spectral cross-map the Capture footswitch locks. Recreated on every rebuild so the button - /// always acts on the current instance. - private var crossMap: SpectralCrossMap? + /// The live spectral-freeze processor the Freeze footswitch drives. Recreated on every graph + /// rebuild, so the button always acts on the current instance. + private var freezeProcessor: SpectralFreeze? - /// Mirror of the locked state, so a toggle knows which way to go and the LED survives a rebuild. - private var isCaptured: Bool = false + /// Mirror of the held state, so a toggle knows which way to go and the LED survives a rebuild. + private var isFrozen: Bool = false + + /// Bumped on every freeze, release, rebuild, and teardown. A pending deferred return-to-live + /// (``completeRelease(generation:)``) only acts when its captured generation still matches, so a + /// re-freeze (or any state change) during the release fade cancels it. + private var releaseGeneration: Int = 0 // MARK: - Knobs - public override var tempoSyncableParams: [TempoSyncableParam] { - [ - TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange), - ] - } - public override var effectKnobs: [PedalKnob] { [ - PedalKnob(label: "Time", node: $time, range: timeRange), - PedalKnob(label: "Damp", node: $damp, range: dampRange), - PedalKnob(label: "Pan", node: $pan, range: panRange), + PedalKnob(label: "Verb", node: $verb, range: unitRange), + PedalKnob(label: "Tone", node: $tone, range: unitRange), + PedalKnob(label: "Rise", node: $rise, range: riseRange), ] } @@ -119,34 +115,49 @@ public final class FreezVerbPedal: Pedal { public override var effectTransportButtons: [PedalButton] { [ PedalButton( - label: "Capture", - indicator: $captured, - dynamicLabel: { [weak self] in (self?.isCaptured ?? false) ? "Live" : "Capture" } - ) { [weak self] in self?.toggleCapture() } + label: "Freeze", + indicator: $frozen, + dynamicLabel: { [weak self] in (self?.isFrozen ?? false) ? "Release" : "Freeze" } + ) { [weak self] in self?.toggleFreeze() } ] } - /// `true` while a moment's spectrum is locked as the filter. Exposed for UI / tests. - public var holding: Bool { isCaptured } + /// `true` while a snapshot is held. Exposed for UI / tests. + public var holding: Bool { isFrozen } - /// Lock the current-moment spectrum as the filter, or return to live tracking. Latched by the - /// Capture footswitch. Before the graph is built `crossMap` is nil and only the latch/LED state - /// moves; `resetForRebuild()` then clears it on the next build so the two never drift apart. - public func toggleCapture() { - if isCaptured { - crossMap?.freeze = false - isCaptured = false - captured = 0.0 + /// Snapshot-and-hold, or release a held snapshot. Latched by the Freeze footswitch. + public func toggleFreeze() { + if isFrozen { + // Release: drop the gate (the pad fades over `rise`) but keep the snapshot *playing*, and + // only return the processor to live analysis once the fade has finished. If we unfroze now, + // the still-open fade would carry a live, FFT-delayed copy of the dry signal — combing + // against the undelayed dry. Deferring the unfreeze fades the actual held spectrum instead. + isFrozen = false + frozen = 0.0 + releaseGeneration += 1 + let generation: Int = releaseGeneration + let fadeSeconds: Double = max(rise, FreezVerbPedal.minReleaseDefer) + DispatchQueue.main.asyncAfter(deadline: .now() + fadeSeconds) { [weak self] in + self?.completeRelease(generation: generation) + } } else { - crossMap?.freeze = true - isCaptured = true - captured = 1.0 + releaseGeneration += 1 // cancel any pending deferred release + freezeProcessor?.freeze() + isFrozen = true + frozen = 1.0 // bloom the pad in over `rise` } } + /// Returns the processor to live analysis after a release fade, unless a newer freeze/release (or a + /// rebuild/teardown) has superseded this one. + private func completeRelease(generation: Int) { + guard generation == releaseGeneration, !isFrozen else { return } + freezeProcessor?.unfreeze() + } + // MARK: - Init - /// Creates a filter-from-the-current-moment FreezVerb. + /// Creates a freeze-and-hold pedal. /// /// - Parameters: /// - inputBus: Audio bus index to read the dry input from. Defaults to `0`. @@ -159,86 +170,76 @@ public final class FreezVerbPedal: Pedal { name: "FreezVerb", inputBus: inputBus, outputBus: outputBus, - initialMix: 0.4 + initialMix: 1.0 ) } // MARK: - Effect - public override func wideEffect( - _ dry: any ValidGeneratorInput - ) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) { - // `wideEffect()` re-runs on every add/rebuild. Start from a clean, live-tracking state so the - // button never holds a reference to a discarded cross-map. + public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { + // `effect()` re-runs on every add/rebuild. Start from a clean, released state so the button + // never holds a reference to a discarded freeze processor. resetForRebuild() - // Side-chain: a continuous analysis of the live input. While the cross-map is live it captures - // its filter template from this each hop; once the footswitch sets `freeze`, the last template - // is held and this side-chain is ignored — the captured moment becomes the fixed filter. - let sideChain: SpectralChain.Audio = SpectralChain.Audio( + // Phase-vocoder spectral freeze: live analysis until `freeze()` captures the current spectrum, + // then an infinite, naturally-rotating held pad regardless of further input. + let freeze: SpectralFreeze = SpectralFreeze(fftSize: FreezVerbPedal.fftSize) + freezeProcessor = freeze + let pad: SpectralChain.Audio = SpectralChain.Audio( input: dry, fftSize: FreezVerbPedal.fftSize, hopSize: FreezVerbPedal.hopSize, - analyzeOnly: true - ) - let map: SpectralCrossMap = SpectralCrossMap( - fftSize: FreezVerbPedal.fftSize, - normalization: .maxMagnitude - ) - map.mode = crossMapMode - crossMap = map - - // Main chain: the live input masked by the (tracking or captured) template. - let masked: SpectralChain.Audio = SpectralChain.Audio( - input: dry, - fftSize: FreezVerbPedal.fftSize, - hopSize: FreezVerbPedal.hopSize, - stages: [.dual(map, sideChain: sideChain)] + stages: [.mono(freeze)] ) - // A large room for a cavernous tail; `time` sets the T60, `damp` the brightness. - let reverb: GVerb.Audio = GVerb.Audio( - source: masked, - roomSize: roomSize, - reverbTime: $time, - damping: $damp, - dryLevel: verbDryLevel, + // Wrap the held spectrum in a diffuse reverb space. Tone brightens by *reducing* FreeVerb's + // damping (`damping = 1 − tone`): tone 1 = bright (little damping), tone 0 = dark. + let damping: any ValidGeneratorInput = 1.0 - $tone + let stereoVerb: FreeVerb.Audio = FreeVerb.Audio( + source: pad, + roomSize: $verb, + damping: damping, + mix: verbMix, sampleRate: sampleRate ) + let monoVerb: SumChannels.Audio = SumChannels.Audio(input: stereoVerb, mul: stereoSumGain) - // GVerb is natively stereo (two decorrelated channels); fold to mono, then pan the wash across - // the field with the Pan knob. - let monoWet: SumChannels.Audio = SumChannels.Audio(input: reverb, mul: stereoSumGain) - let panned: Pan2 = Pan2(input: monoWet, pan: $pan) - return (panned.left, panned.right) + // The pad is audible only while a snapshot is held; the gate ramps over `rise` so engaging or + // releasing the freeze blooms rather than clicks. Live analysis (gate 0) stays silent. + let gate: Lag.Control = Lag.Control(input: $frozen, time: $rise) + + // Dry always passes through; the frozen wash is layered on top. + return dry + (monoVerb * gate) } // MARK: - Lifecycle - /// Returns to live tracking when the engine stops. + /// Releases any held snapshot when the engine stops — a halted engine can't keep a pad rotating. public override func engineDidStop() { releaseHold() } - /// Returns to live tracking before this instance is discarded on a rig teardown. + /// Releases before this instance is discarded on a rig teardown. public override func rigWillTeardown() { releaseHold() } // MARK: - Helpers - /// Unlocks any captured filter and returns to live tracking. + /// Drops any held snapshot and returns the pad to silence. private func releaseHold() { - crossMap?.freeze = false - isCaptured = false - captured = 0.0 + releaseGeneration += 1 // cancel any pending deferred release + freezeProcessor?.unfreeze() + isFrozen = false + frozen = 0.0 } - /// Clears the live generator reference and the locked state so a graph rebuild starts fresh. - /// Called at the top of ``wideEffect(_:)``. + /// Clears the live generator reference and the held state so a graph rebuild starts fresh. + /// Called at the top of ``effect(_:)``. private func resetForRebuild() { - crossMap = nil - isCaptured = false - captured = 0.0 + releaseGeneration += 1 // cancel any pending deferred release against the old processor + freezeProcessor = nil + isFrozen = false + frozen = 0.0 } } diff --git a/Sources/LyrebirdShoeGaze/Pedals/FreezePedal.swift b/Sources/LyrebirdShoeGaze/Pedals/FreezePedal.swift deleted file mode 100644 index 2eba51a..0000000 --- a/Sources/LyrebirdShoeGaze/Pedals/FreezePedal.swift +++ /dev/null @@ -1,245 +0,0 @@ -// FreezePedal.swift -// Lyrebird -// -// Copyright (c) 2026 Joshua Parmenter / realizedsound -// SPDX-License-Identifier: MIT - -import Foundation -import LyrebirdSynth -import LyrebirdUI - -/// A true freeze-and-hold — press **Freeze** and the sound playing at that instant is -/// captured and held as an infinite, smoothly-sustaining pad while you keep playing over it. -/// -/// Unlike a feedback-tank "infinite reverb" (which just pushes a reverb's decay toward forever and -/// smears everything you play into the wash), this takes a genuine **spectral snapshot**: a -/// phase-vocoder (`SpectralFreeze`) locks the magnitude spectrum of the moment you engage it and -/// keeps each partial rotating at its own frequency, so the held chord sounds natural and glassy -/// rather than a static loop or a metallic ring. That frozen spectrum is then wrapped in a `FreeVerb` -/// tank for a diffuse, blooming space — the "reverb" half of the name. -/// -/// The dry signal always passes straight through, so you solo or comp over the held pad; the frozen -/// wash is layered on top (the wet/dry Mix knob is hidden and the base `mix` stays fully wet). Press -/// Freeze again to release it — the pad fades out over **Rise** and live analysis resumes, ready for -/// the next snapshot. -/// -/// ## Knobs -/// - `verb`: Size of the reverb space wrapped around the frozen pad. Range `[0, 1]`: bigger = washier. -/// - `tone`: Brightness of the pad. Range `[0, 1]`: `0` = dark, `1` = bright. -/// - `rise`: Fade time in seconds as the freeze blooms in and releases out. Range `[0.02, 4.0]`. -/// -/// ## Transport -/// - `Freeze`: latching footswitch — press to snapshot and hold, press again to release. -public final class FreezePedal: Pedal { - - /// One-line description shown in the picker and info panel. - public override var summary: String { - "Snapshot the moment and hold it forever — a spectral freeze wrapped in a blooming wash." - } - - /// The pad is layered over the untouched dry signal, so a wet/dry Mix knob is meaningless — hide - /// it and keep the base `mix` fully wet. - public override var showsMixControl: Bool { false } - - // MARK: - Parameters - - /// Size of the reverb space wrapped around the frozen pad. Range `[0, 1]`: bigger = washier. - @UIParam public var verb: Double = 0.7 - - /// Brightness of the pad. Range `[0, 1]`: `0` = dark, `1` = bright. - @UIParam public var tone: Double = 0.5 - - /// Fade time in seconds as the freeze blooms in and releases out. Range `[0.02, 4.0]`. - @UIParam public var rise: Double = 0.4 - - // MARK: - Internal live state (read by the audio graph) - - /// `1` while a snapshot is held, else `0`. Drives the pad's fade gate and the Freeze footswitch - /// LED. Transport state, not a preset control — captured neither by `captureState` nor restored. - @UIParam public var frozen: Double = 0.0 - - // MARK: - Constants - - /// FFT frame size for the phase-vocoder freeze. Larger = finer frequency resolution (smoother - /// held chords) at the cost of more latency on the wet path; the dry path is never delayed. - private static let fftSize: Int = 2048 - - /// Samples between FFT hops (75% overlap at `fftSize` 2048) — fine enough for a clean, artifact- - /// free resynthesis of the held spectrum. - private static let hopSize: Int = 512 - - /// FreeVerb is run fully wet on the pad; the pedal's own dry/wet balance is the `frozen` gate plus - /// the base `mix`, so the tank should contribute none of its own dry path. - private let verbMix: Double = 1.0 - - /// Gain folding FreeVerb's two decorrelated channels to mono — a conservative trim (the channels - /// are not identical) that leaves output headroom. - private let stereoSumGain: Double = 0.5 - - /// Floor on the release-fade delay, in seconds. On release the gate ramps down over `rise`, but we - /// keep the snapshot playing until the fade has essentially finished; this ensures even the - /// shortest `rise` still defers the return-to-live by a sensible minimum. - private static let minReleaseDefer: Double = 0.05 - - // MARK: - Ranges - - private let unitRange: ClosedRange = 0.0 ... 1.0 - private let riseRange: ClosedRange = 0.02 ... 4.0 - - // MARK: - Live generator references (rebuilt each `effect(_:)`) - - /// The live spectral-freeze processor the Freeze footswitch drives. Recreated on every graph - /// rebuild, so the button always acts on the current instance. - private var freezeProcessor: SpectralFreeze? - - /// Mirror of the held state, so a toggle knows which way to go and the LED survives a rebuild. - private var isFrozen: Bool = false - - /// Bumped on every freeze, release, rebuild, and teardown. A pending deferred return-to-live - /// (``completeRelease(generation:)``) only acts when its captured generation still matches, so a - /// re-freeze (or any state change) during the release fade cancels it. - private var releaseGeneration: Int = 0 - - // MARK: - Knobs - - public override var effectKnobs: [PedalKnob] { - [ - PedalKnob(label: "Verb", node: $verb, range: unitRange), - PedalKnob(label: "Tone", node: $tone, range: unitRange), - PedalKnob(label: "Rise", node: $rise, range: riseRange), - ] - } - - // MARK: - Transport - - public override var effectTransportButtons: [PedalButton] { - [ - PedalButton( - label: "Freeze", - indicator: $frozen, - dynamicLabel: { [weak self] in (self?.isFrozen ?? false) ? "Release" : "Freeze" } - ) { [weak self] in self?.toggleFreeze() } - ] - } - - /// `true` while a snapshot is held. Exposed for UI / tests. - public var holding: Bool { isFrozen } - - /// Snapshot-and-hold, or release a held snapshot. Latched by the Freeze footswitch. - public func toggleFreeze() { - if isFrozen { - // Release: drop the gate (the pad fades over `rise`) but keep the snapshot *playing*, and - // only return the processor to live analysis once the fade has finished. If we unfroze now, - // the still-open fade would carry a live, FFT-delayed copy of the dry signal — combing - // against the undelayed dry. Deferring the unfreeze fades the actual held spectrum instead. - isFrozen = false - frozen = 0.0 - releaseGeneration += 1 - let generation: Int = releaseGeneration - let fadeSeconds: Double = max(rise, FreezePedal.minReleaseDefer) - DispatchQueue.main.asyncAfter(deadline: .now() + fadeSeconds) { [weak self] in - self?.completeRelease(generation: generation) - } - } else { - releaseGeneration += 1 // cancel any pending deferred release - freezeProcessor?.freeze() - isFrozen = true - frozen = 1.0 // bloom the pad in over `rise` - } - } - - /// Returns the processor to live analysis after a release fade, unless a newer freeze/release (or a - /// rebuild/teardown) has superseded this one. - private func completeRelease(generation: Int) { - guard generation == releaseGeneration, !isFrozen else { return } - freezeProcessor?.unfreeze() - } - - // MARK: - Init - - /// Creates a freeze-and-hold 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: "Freeze", - inputBus: inputBus, - outputBus: outputBus, - initialMix: 1.0 - ) - } - - // MARK: - Effect - - public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput { - // `effect()` re-runs on every add/rebuild. Start from a clean, released state so the button - // never holds a reference to a discarded freeze processor. - resetForRebuild() - - // Phase-vocoder spectral freeze: live analysis until `freeze()` captures the current spectrum, - // then an infinite, naturally-rotating held pad regardless of further input. - let freeze: SpectralFreeze = SpectralFreeze(fftSize: FreezePedal.fftSize) - freezeProcessor = freeze - let pad: SpectralChain.Audio = SpectralChain.Audio( - input: dry, - fftSize: FreezePedal.fftSize, - hopSize: FreezePedal.hopSize, - stages: [.mono(freeze)] - ) - - // Wrap the held spectrum in a diffuse reverb space. Tone brightens by *reducing* FreeVerb's - // damping (`damping = 1 − tone`): tone 1 = bright (little damping), tone 0 = dark. - let damping: any ValidGeneratorInput = 1.0 - $tone - let stereoVerb: FreeVerb.Audio = FreeVerb.Audio( - source: pad, - roomSize: $verb, - damping: damping, - mix: verbMix, - sampleRate: sampleRate - ) - let monoVerb: SumChannels.Audio = SumChannels.Audio(input: stereoVerb, mul: stereoSumGain) - - // The pad is audible only while a snapshot is held; the gate ramps over `rise` so engaging or - // releasing the freeze blooms rather than clicks. Live analysis (gate 0) stays silent. - let gate: Lag.Control = Lag.Control(input: $frozen, time: $rise) - - // Dry always passes through; the frozen wash is layered on top. - return dry + (monoVerb * gate) - } - - // MARK: - Lifecycle - - /// Releases any held snapshot when the engine stops — a halted engine can't keep a pad rotating. - public override func engineDidStop() { - releaseHold() - } - - /// Releases before this instance is discarded on a rig teardown. - public override func rigWillTeardown() { - releaseHold() - } - - // MARK: - Helpers - - /// Drops any held snapshot and returns the pad to silence. - private func releaseHold() { - releaseGeneration += 1 // cancel any pending deferred release - freezeProcessor?.unfreeze() - isFrozen = false - frozen = 0.0 - } - - /// Clears the live generator reference and the held state so a graph rebuild starts fresh. - /// Called at the top of ``effect(_:)``. - private func resetForRebuild() { - releaseGeneration += 1 // cancel any pending deferred release against the old processor - freezeProcessor = nil - isFrozen = false - frozen = 0.0 - } -} diff --git a/Sources/LyrebirdShoeGaze/Pedals/TunedVerbPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/TunedVerbPedal.swift new file mode 100644 index 0000000..b7a80c2 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Pedals/TunedVerbPedal.swift @@ -0,0 +1,244 @@ +// TunedVerbPedal.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import LyrebirdSynth +import LyrebirdUI + +/// A spectral *filter-from-the-current-moment* reverb — press **Capture** and the spectrum playing +/// at that instant is locked in as a fixed filter, and everything you play afterwards is poured +/// through that frozen spectral shape into a big reverb. +/// +/// Where ``FreezVerbPedal`` holds a snapshot as a *sounding* pad, this holds a snapshot as a +/// *filter*. A `SpectralCrossMap` masks the live spectrum bin-by-bin against a template taken from a +/// side-chain analysis of the input: while live, the template tracks what you play; press Capture and +/// the template freezes, so the captured moment becomes a fixed formant mask on your ongoing signal. +/// The masked result feeds a large `GVerb` room (fixed 120 m) for a cavernous tail, and a **Pan** +/// knob places the stereo wash anywhere across the field. +/// +/// Ported from the composer's `FilterFromCurrentMoment` process: the original drew its filter from a +/// random pointer into a time-stretched buffer and spatialised with ambisonics; here the filter is +/// captured straight off the live input by the footswitch, and the output is plain stereo via the +/// Pan knob. +/// +/// ## Knobs +/// - `time`: Reverb tail length (GVerb T60) in seconds. Range `[0.5, 12.0]`. +/// - `damp`: High-frequency damping of the tail. Range `[0, 1]`: `0` = bright, `1` = dark. +/// - `pan`: Stereo position of the wash. Range `[-1, +1]`: `-1` = hard left, `+1` = hard right. +/// +/// ## Transport +/// - `Capture`: latching footswitch — press to lock the current-moment spectrum as the filter, press +/// again to return to live tracking. +public final class TunedVerbPedal: Pedal { + + /// One-line description shown in the picker and info panel. + public override var summary: String { + "Capture a moment's spectrum as a filter and pour your playing through it into a vast room." + } + + /// Mono in, stereo out: the reverb wash is panned across the field by the ``pan`` knob. + public override var channelKind: PedalChannelKind { .widener } + + // MARK: - Parameters + + /// Reverb tail length (GVerb T60) in seconds. Range `[0.5, 12.0]`. + @UIParam public var time: Double = 6.0 + + /// High-frequency damping of the tail. Range `[0, 1]`: `0` = bright, `1` = dark. + @UIParam public var damp: Double = 0.5 + + /// Stereo position of the wash. Range `[-1, +1]`: `-1` = hard left, `+1` = hard right. + @UIParam public var pan: Double = 0.0 + + // MARK: - Internal live state (read by the audio graph) + + /// `1` while the filter is locked to a captured moment, else `0`. Drives the Capture footswitch + /// LED. Transport state — not a preset control, so neither captured nor restored. + @UIParam public var captured: Double = 0.0 + + // MARK: - Constants + + /// FFT frame size for the spectral cross-map. Matches the composer's original process — large + /// enough for a finely-resolved formant filter at the cost of latency on the wet path (the dry + /// path is never delayed). + private static let fftSize: Int = 4096 + + /// Samples between FFT hops (75% overlap at `fftSize` 4096). + private static let hopSize: Int = 1024 + + /// GVerb room size in metres — fixed, as in the original process. Large, for a cavernous tail. + private let roomSize: Double = 120.0 + + /// Cross-map blend: `1.0` = full spectral bandpass mask (loud template bins pass, quiet bins are + /// attenuated). Matches the original process. + private let crossMapMode: Double = 1.0 + + /// GVerb dry level — kept at `0` so the wet path is pure reverb; the base `mix` provides the + /// dry/wet blend. + private let verbDryLevel: Double = 0.0 + + /// Gain folding GVerb's two decorrelated channels to mono before the pan — a conservative trim + /// (the channels are not identical) that leaves output headroom. + private let stereoSumGain: Double = 0.5 + + // MARK: - Ranges + + private let timeRange: ClosedRange = 0.5 ... 12.0 + private let dampRange: ClosedRange = 0.0 ... 1.0 + private let panRange: ClosedRange = -1.0 ... 1.0 + + // MARK: - Live generator references (rebuilt each `wideEffect(_:)`) + + /// The spectral cross-map the Capture footswitch locks. Recreated on every rebuild so the button + /// always acts on the current instance. + private var crossMap: SpectralCrossMap? + + /// Mirror of the locked state, so a toggle knows which way to go and the LED survives a rebuild. + private var isCaptured: Bool = false + + // MARK: - Knobs + + public override var tempoSyncableParams: [TempoSyncableParam] { + [ + TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange), + ] + } + + public override var effectKnobs: [PedalKnob] { + [ + PedalKnob(label: "Time", node: $time, range: timeRange), + PedalKnob(label: "Damp", node: $damp, range: dampRange), + PedalKnob(label: "Pan", node: $pan, range: panRange), + ] + } + + // MARK: - Transport + + public override var effectTransportButtons: [PedalButton] { + [ + PedalButton( + label: "Capture", + indicator: $captured, + dynamicLabel: { [weak self] in (self?.isCaptured ?? false) ? "Live" : "Capture" } + ) { [weak self] in self?.toggleCapture() } + ] + } + + /// `true` while a moment's spectrum is locked as the filter. Exposed for UI / tests. + public var holding: Bool { isCaptured } + + /// Lock the current-moment spectrum as the filter, or return to live tracking. Latched by the + /// Capture footswitch. Before the graph is built `crossMap` is nil and only the latch/LED state + /// moves; `resetForRebuild()` then clears it on the next build so the two never drift apart. + public func toggleCapture() { + if isCaptured { + crossMap?.freeze = false + isCaptured = false + captured = 0.0 + } else { + crossMap?.freeze = true + isCaptured = true + captured = 1.0 + } + } + + // MARK: - Init + + /// Creates a filter-from-the-current-moment TunedVerb. + /// + /// - 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: "TunedVerb", + inputBus: inputBus, + outputBus: outputBus, + initialMix: 0.4 + ) + } + + // MARK: - Effect + + public override func wideEffect( + _ dry: any ValidGeneratorInput + ) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) { + // `wideEffect()` re-runs on every add/rebuild. Start from a clean, live-tracking state so the + // button never holds a reference to a discarded cross-map. + resetForRebuild() + + // Side-chain: a continuous analysis of the live input. While the cross-map is live it captures + // its filter template from this each hop; once the footswitch sets `freeze`, the last template + // is held and this side-chain is ignored — the captured moment becomes the fixed filter. + let sideChain: SpectralChain.Audio = SpectralChain.Audio( + input: dry, + fftSize: TunedVerbPedal.fftSize, + hopSize: TunedVerbPedal.hopSize, + analyzeOnly: true + ) + let map: SpectralCrossMap = SpectralCrossMap( + fftSize: TunedVerbPedal.fftSize, + normalization: .maxMagnitude + ) + map.mode = crossMapMode + crossMap = map + + // Main chain: the live input masked by the (tracking or captured) template. + let masked: SpectralChain.Audio = SpectralChain.Audio( + input: dry, + fftSize: TunedVerbPedal.fftSize, + hopSize: TunedVerbPedal.hopSize, + stages: [.dual(map, sideChain: sideChain)] + ) + + // A large room for a cavernous tail; `time` sets the T60, `damp` the brightness. + let reverb: GVerb.Audio = GVerb.Audio( + source: masked, + roomSize: roomSize, + reverbTime: $time, + damping: $damp, + dryLevel: verbDryLevel, + sampleRate: sampleRate + ) + + // GVerb is natively stereo (two decorrelated channels); fold to mono, then pan the wash across + // the field with the Pan knob. + let monoWet: SumChannels.Audio = SumChannels.Audio(input: reverb, mul: stereoSumGain) + let panned: Pan2 = Pan2(input: monoWet, pan: $pan) + return (panned.left, panned.right) + } + + // MARK: - Lifecycle + + /// Returns to live tracking when the engine stops. + public override func engineDidStop() { + releaseHold() + } + + /// Returns to live tracking before this instance is discarded on a rig teardown. + public override func rigWillTeardown() { + releaseHold() + } + + // MARK: - Helpers + + /// Unlocks any captured filter and returns to live tracking. + private func releaseHold() { + crossMap?.freeze = false + isCaptured = false + captured = 0.0 + } + + /// Clears the live generator reference and the locked state so a graph rebuild starts fresh. + /// Called at the top of ``wideEffect(_:)``. + private func resetForRebuild() { + crossMap = nil + isCaptured = false + captured = 0.0 + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift index 8da513a..69ead28 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalRegistry.swift @@ -91,8 +91,8 @@ public enum PedalRegistry { "Spring Reverb": { SpringReverbPedal() }, "Reverse Reverb": { ReverseReverbPedal() }, "Granular Reverb": { GranularReverbPedal() }, - "Freeze": { FreezePedal() }, "FreezVerb": { FreezVerbPedal() }, + "TunedVerb": { TunedVerbPedal() }, "Limiter": { LimiterPedal() }, "Cabinet": { CabinetPedal() }, "Noise Gate": { NoiseGatePedal() }, diff --git a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift index d802887..ded0d5f 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalCategory.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalCategory.swift @@ -60,7 +60,7 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable { "Reverse Delay": .delay, "DL4": .delay, "Reverb": .reverb, "Shimmer Reverb": .reverb, "Plate Reverb": .reverb, "Room Reverb": .reverb, "Spring Reverb": .reverb, - "Reverse Reverb": .reverb, "Granular Reverb": .reverb, "Freeze": .reverb, "FreezVerb": .reverb, + "Reverse Reverb": .reverb, "Granular Reverb": .reverb, "FreezVerb": .reverb, "TunedVerb": .reverb, "Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture, "Karplus Resonator": .texture, "Tape Looper": .texture, ] diff --git a/Tests/LyrebirdShoeGazeTests/FreezVerbPedalTests.swift b/Tests/LyrebirdShoeGazeTests/FreezVerbPedalTests.swift index ece2ca6..d70f8e3 100644 --- a/Tests/LyrebirdShoeGazeTests/FreezVerbPedalTests.swift +++ b/Tests/LyrebirdShoeGazeTests/FreezVerbPedalTests.swift @@ -10,36 +10,14 @@ import LyrebirdSynth import LyrebirdUI @testable import LyrebirdShoeGaze -/// A source that crossfades between two tones under a `morph` parameter, so a test can capture the -/// filter on tone A, then switch to tone B and show the locked spectrum shapes B differently than -/// live tracking would. +/// A steady sine whose level can be muted mid-render via its `gain` parameter — lets a test silence +/// the live input while a snapshot is held, to prove the pad sustains from the freeze and not from +/// the ongoing signal. @MainActor -private final class TwoToneSource: SynthesizerBase { - private let targetBus: Int - private let freqA: Double - private let freqB: Double - /// `0` = tone A, `1` = tone B. - @UIParam var morph: Double = 0.0 - - init(targetBus: Int, freqA: Double, freqB: Double) { - self.targetBus = targetBus - self.freqA = freqA - self.freqB = freqB - super.init() - } - - override func build() { - let a: BinaryOpGenerator = OscSin.Audio(freq: freqA, mul: 0.5) * (1.0 - $morph) - let b: BinaryOpGenerator = OscSin.Audio(freq: freqB, mul: 0.5) * $morph - output(bus: targetBus, source: a + b) - } -} - -/// A steady sine for the non-silent / determinism / pan / bypass checks. -@MainActor -private final class TestSineSource: SynthesizerBase { +private final class GatedSineSource: SynthesizerBase { private let targetBus: Int private let freq: Double + @UIParam var gain: Double = 0.5 init(targetBus: Int, freq: Double) { self.targetBus = targetBus @@ -48,7 +26,7 @@ private final class TestSineSource: SynthesizerBase { } override func build() { - output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: 0.5)) + output(bus: targetBus, source: OscSin.Audio(freq: freq) * $gain) } } @@ -57,9 +35,9 @@ private final class TestSineSource: SynthesizerBase { struct FreezVerbPedalTests { private let sampleRate: Double = 44_100.0 - private let toneHz: Double = 220.0 + private let sineHz: Double = 220.0 - // MARK: - One-shot NRT render + // MARK: - One-shot NRT render (no mid-render control) private func render( duration: Double, @@ -73,13 +51,13 @@ struct FreezVerbPedalTests { defer { try? FileManager.default.removeItem(at: url) } let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) - let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) defer { engine.busAllocator.releaseAudioBus(srcBus) engine.busAllocator.releaseAudioBus(dstBus) } - let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: toneHz) + let source: GatedSineSource = GatedSineSource(targetBus: srcBus.index, freq: sineHz) let pedal: FreezVerbPedal = FreezVerbPedal(inputBus: srcBus.index, outputBus: dstBus.index) configure(pedal) let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) @@ -92,13 +70,15 @@ struct FreezVerbPedalTests { return readStereoCAF(url: url) } - // MARK: - Block-stepped render (mid-render capture / input morph) + // MARK: - Block-stepped render with mid-render freeze / mute control + /// Steps the engine block-by-block, invoking `onFrame` before each block so a test can engage the + /// freeze or mute the source at chosen frames. Returns the left output channel. private func stepRender( totalFrames: Int, blockSize: Int, configure: (FreezVerbPedal) -> Void, - onFrame: (_ frame: Int, _ source: TwoToneSource, _ pedal: FreezVerbPedal) -> Void + onFrame: (_ frame: Int, _ source: GatedSineSource, _ pedal: FreezVerbPedal) -> Void ) throws -> [Float] { let numAudioBuses: Int = 64 let numControlBuses: Int = 512 @@ -114,13 +94,13 @@ struct FreezVerbPedalTests { ) let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) - let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) defer { engine.busAllocator.releaseAudioBus(srcBus) engine.busAllocator.releaseAudioBus(dstBus) } - let source: TwoToneSource = TwoToneSource(targetBus: srcBus.index, freqA: 180.0, freqB: 900.0) + let source: GatedSineSource = GatedSineSource(targetBus: srcBus.index, freq: sineHz) let pedal: FreezVerbPedal = FreezVerbPedal(inputBus: srcBus.index, outputBus: dstBus.index) configure(pedal) let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index) @@ -151,84 +131,101 @@ struct FreezVerbPedalTests { let b: Int = min(hiFrame, samples.count) guard b > a else { return 0.0 } var sum: Double = 0.0 - for i: Int in a ..< b { let v: Double = Double(samples[i]); sum += v * v } + for i: Int in a ..< b { + let v: Double = Double(samples[i]) + sum += v * v + } return (sum / Double(b - a)).squareRoot() } - private func rmsDiff(_ a: [Float], _ b: [Float], loFrame: Int, hiFrame: Int) -> Double { - let lo: Int = max(0, loFrame) - let hi: Int = min(hiFrame, min(a.count, b.count)) - guard hi > lo else { return 0.0 } - var sum: Double = 0.0 - for i: Int in lo ..< hi { let d: Double = Double(a[i]) - Double(b[i]); sum += d * d } - return (sum / Double(hi - lo)).squareRoot() - } - private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double { let a: Int = max(1, lo) let b: Int = min(hi, x.count) guard b > a else { return 0.0 } var m: Double = 0.0 - for i: Int in a ..< b { let d: Double = abs(Double(x[i]) - Double(x[i - 1])); if d > m { m = d } } + for i: Int in a ..< b { + let d: Double = abs(Double(x[i]) - Double(x[i - 1])) + if d > m { m = d } + } return m } // MARK: - Behaviour @Test func buildsAndProducesNonSilentOutput() throws { - let out: [Float] = try render(duration: 0.8) { _ in } + // Unfrozen, the dry signal passes straight through — output is never silent. + let out: [Float] = try render(duration: 1.0) { _ in } #expect(!out.isEmpty) - #expect(hasNonSilentOutput(out), "FreezVerb output was silent") + #expect(hasNonSilentOutput(out), "Freeze output was silent") } @Test func renderIsDeterministic() throws { - let a: [Float] = try render(duration: 0.8) { pedal in pedal.time = 4.0; pedal.damp = 0.4 } - let b: [Float] = try render(duration: 0.8) { pedal in pedal.time = 4.0; pedal.damp = 0.4 } - #expect(a == b, "deterministic capture-reverb renders of the same setting should be bit-identical") + // No RNG anywhere in the graph, so two identical renders are bit-identical. + let a: [Float] = try render(duration: 1.0) { pedal in pedal.verb = 0.6; pedal.tone = 0.4 } + let b: [Float] = try render(duration: 1.0) { pedal in pedal.verb = 0.6; pedal.tone = 0.4 } + #expect(a == b, "deterministic freeze-reverb renders of the same setting should be bit-identical") } - @Test func panShiftsTheLeftLeg() throws { - // Fully wet, the output follows the panned wash. Hard left fills the left leg; hard right - // nearly empties it. (Tests exercise the left output leg; the right is board-wired live.) - let hardLeft: [Float] = try render(duration: 0.6) { pedal in pedal.mix = 1.0; pedal.pan = -1.0 } - let hardRight: [Float] = try render(duration: 0.6) { pedal in pedal.mix = 1.0; pedal.pan = 1.0 } - let leftRMS: Double = rms(hardLeft, loFrame: 0, hiFrame: hardLeft.count) - let rightRMS: Double = rms(hardRight, loFrame: 0, hiFrame: hardRight.count) - #expect(leftRMS > rightRMS * 3.0, - "panning hard left should fill the left leg far more than hard right: L \(leftRMS) vs R \(rightRMS)") - } - - @Test func captureLocksTheFilterSoAChangedInputIsShapedDifferently() throws { - // Capture the filter on tone A, then morph the input to tone B. A locked filter (shaped by A) - // masks B differently than a filter that keeps tracking the live input — so the two renders - // diverge once the input has changed. + @Test func snapshotSustainsAfterInputStops() throws { + // The defining behaviour: engage Freeze while a tone plays, then MUTE the input. A held + // spectral snapshot keeps ringing; without the freeze the pad gate is shut, so once the dry + // input is gone the output falls silent. Compare the two in the same late window. let blockSize: Int = 512 - let totalFrames: Int = Int(1.4 * sampleRate) - let captureFrame: Int = Int(0.4 * sampleRate) - let morphFrame: Int = Int(0.6 * sampleRate) - let windowLo: Int = Int(0.95 * sampleRate) - let windowHi: Int = Int(1.35 * sampleRate) + let totalFrames: Int = Int(1.6 * sampleRate) + let freezeFrame: Int = Int(0.45 * sampleRate) + let muteFrame: Int = Int(0.75 * sampleRate) + let windowLo: Int = Int(1.1 * sampleRate) + let windowHi: Int = Int(1.5 * sampleRate) - var captured: Bool = false - let locked: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in - pedal.mix = 1.0; pedal.time = 3.0 + let frozen: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in + pedal.verb = 0.6; pedal.tone = 0.5; pedal.rise = 0.05 } onFrame: { frame, source, pedal in - if frame >= captureFrame, !captured { pedal.toggleCapture(); captured = true } - if frame >= morphFrame { source.morph = 1.0 } // switch to tone B + if frame >= freezeFrame, !pedal.holding { pedal.toggleFreeze() } + if frame >= muteFrame { source.gain = 0.0 } } - let tracking: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in - pedal.mix = 1.0; pedal.time = 3.0 + let control: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in + pedal.verb = 0.6; pedal.tone = 0.5; pedal.rise = 0.05 } onFrame: { frame, source, _ in - // Never capture; morph at the same frame. - if frame >= morphFrame { source.morph = 1.0 } + // Never freeze; mute at the same frame. + if frame >= muteFrame { source.gain = 0.0 } } - let signal: Double = rms(tracking, loFrame: windowLo, hiFrame: windowHi) - let diff: Double = rmsDiff(locked, tracking, loFrame: windowLo, hiFrame: windowHi) - #expect(signal > 1.0e-4, "control render should be audible on tone B, got \(signal)") - #expect(diff > signal * 0.25, - "a captured filter should shape the changed input differently: diff \(diff) vs signal \(signal)") + let heldTail: Double = rms(frozen, loFrame: windowLo, hiFrame: windowHi) + let unfrozenTail: Double = rms(control, loFrame: windowLo, hiFrame: windowHi) + + #expect(heldTail > 1.0e-3, "a held snapshot should still ring after the input stops, tail RMS \(heldTail)") + #expect(heldTail > unfrozenTail * 10.0, + "frozen tail \(heldTail) should dwarf the unfrozen tail \(unfrozenTail) once the input is muted") + } + + @Test func releaseFadesThePadOut() throws { + // Freeze, mute the input, then release: after the Rise fade the held pad should fall away, + // leaving the late window far quieter than while it was held. + let blockSize: Int = 512 + let totalFrames: Int = Int(2.0 * sampleRate) + let freezeFrame: Int = Int(0.4 * sampleRate) + let muteFrame: Int = Int(0.7 * sampleRate) + let releaseFrame: Int = Int(1.1 * sampleRate) + let heldLo: Int = Int(0.95 * sampleRate) + let heldHi: Int = Int(1.05 * sampleRate) + let afterLo: Int = Int(1.7 * sampleRate) + let afterHi: Int = Int(1.95 * sampleRate) + + var froze: Bool = false + var released: Bool = false + let out: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in + pedal.verb = 0.5; pedal.tone = 0.5; pedal.rise = 0.1 + } onFrame: { frame, source, pedal in + if frame >= freezeFrame, !froze { pedal.toggleFreeze(); froze = true } + if frame >= muteFrame { source.gain = 0.0 } + if frame >= releaseFrame, froze, !released { pedal.toggleFreeze(); released = true } + } + + let heldRMS: Double = rms(out, loFrame: heldLo, hiFrame: heldHi) + let afterRMS: Double = rms(out, loFrame: afterLo, hiFrame: afterHi) + #expect(heldRMS > 1.0e-3, "pad should be audible while held, got \(heldRMS)") + #expect(afterRMS < heldRMS * 0.5, "releasing should fade the pad out: after \(afterRMS) vs held \(heldRMS)") } // MARK: - Bypass @@ -237,11 +234,12 @@ struct FreezVerbPedalTests { let blockSize: Int = 512 let totalFrames: Int = Int(0.6 * sampleRate) let flipFrame: Int = Int(0.35 * sampleRate) + // Steady-state window ends before the flip; a settle margin after it covers the fade tail. let steadyLo: Int = Int(0.22 * sampleRate) let steadyHi: Int = Int(0.33 * sampleRate) let settleMargin: Int = Int(0.045 * sampleRate) let left: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in - pedal.mix = 0.5 + pedal.verb = 0.5 } onFrame: { frame, _, pedal in if frame >= flipFrame { pedal.bypass = 1.0 } } @@ -258,49 +256,54 @@ struct FreezVerbPedalTests { @Test func exposesControls() throws { let pedal: FreezVerbPedal = FreezVerbPedal() - #expect(pedal.effectKnobs.map { $0.label } == ["Time", "Damp", "Pan"]) - #expect(pedal.effectTransportButtons.map { $0.label } == ["Capture"]) - #expect(pedal.channelKind == .widener) + #expect(pedal.effectKnobs.map { $0.label } == ["Verb", "Tone", "Rise"]) + #expect(pedal.effectTransportButtons.map { $0.label } == ["Freeze"]) + #expect(pedal.showsMixControl == false) } - @Test func captureTogglesHoldState() throws { + @Test func freezeTogglesHoldState() throws { + // The transport latch flips the held state without needing a running engine. let pedal: FreezVerbPedal = FreezVerbPedal() #expect(pedal.holding == false) - pedal.toggleCapture() + pedal.toggleFreeze() #expect(pedal.holding == true) - #expect(pedal.captured == 1.0) - pedal.toggleCapture() + #expect(pedal.frozen == 1.0) + pedal.toggleFreeze() #expect(pedal.holding == false) - #expect(pedal.captured == 0.0) + #expect(pedal.frozen == 0.0) } @Test func presetRoundTripPreservesControls() throws { let pedal: FreezVerbPedal = FreezVerbPedal() - pedal.time = 8.5 - pedal.damp = 0.7 - pedal.pan = -0.6 + pedal.verb = 0.33 + pedal.tone = 0.8 + pedal.rise = 1.5 let state: PedalState = pedal.captureState() let restored: FreezVerbPedal = FreezVerbPedal() restored.applyState(state) - #expect(restored.time == 8.5) - #expect(restored.damp == 0.7) - #expect(restored.pan == -0.6) + #expect(restored.verb == 0.33) + #expect(restored.tone == 0.8) + #expect(restored.rise == 1.5) } - @Test func capturedStateIsNotPersisted() throws { - // `captured` is transport state, not a preset control. + @Test func heldSnapshotIsNotPersisted() throws { + // `frozen` is transport state, not a preset control: a pedal captured mid-freeze must restore + // released, with no phantom pad blooming on load. let pedal: FreezVerbPedal = FreezVerbPedal() - pedal.toggleCapture() - #expect(pedal.captured == 1.0) + pedal.verb = 0.4 + pedal.toggleFreeze() + #expect(pedal.holding == true) + #expect(pedal.frozen == 1.0) let state: PedalState = pedal.captureState() let restored: FreezVerbPedal = FreezVerbPedal() restored.applyState(state) - #expect(restored.captured == 0.0, "a locked filter must not persist into a preset") + #expect(restored.frozen == 0.0, "a held snapshot must not persist into a preset") #expect(restored.holding == false) + #expect(restored.verb == 0.4) } @Test func registeredInBuiltInRegistry() throws { diff --git a/Tests/LyrebirdShoeGazeTests/FreezePedalTests.swift b/Tests/LyrebirdShoeGazeTests/FreezePedalTests.swift deleted file mode 100644 index 41313ef..0000000 --- a/Tests/LyrebirdShoeGazeTests/FreezePedalTests.swift +++ /dev/null @@ -1,313 +0,0 @@ -// FreezePedalTests.swift -// Lyrebird -// -// Copyright (c) 2026 Joshua Parmenter / realizedsound -// SPDX-License-Identifier: MIT - -import Testing -import Foundation -import LyrebirdSynth -import LyrebirdUI -@testable import LyrebirdShoeGaze - -/// A steady sine whose level can be muted mid-render via its `gain` parameter — lets a test silence -/// the live input while a snapshot is held, to prove the pad sustains from the freeze and not from -/// the ongoing signal. -@MainActor -private final class GatedSineSource: SynthesizerBase { - private let targetBus: Int - private let freq: Double - @UIParam var gain: Double = 0.5 - - init(targetBus: Int, freq: Double) { - self.targetBus = targetBus - self.freq = freq - super.init() - } - - override func build() { - output(bus: targetBus, source: OscSin.Audio(freq: freq) * $gain) - } -} - -@MainActor -@Suite("FreezePedal") -struct FreezePedalTests { - - private let sampleRate: Double = 44_100.0 - private let sineHz: Double = 220.0 - - // MARK: - One-shot NRT render (no mid-render control) - - private func render( - duration: Double, - configure: (FreezePedal) -> Void - ) throws -> [Float] { - let numAudioBuses: Int = 64 - let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( - duration: duration, - 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: GatedSineSource = GatedSineSource(targetBus: srcBus.index, freq: sineHz) - let pedal: FreezePedal = FreezePedal(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) - } - - // MARK: - Block-stepped render with mid-render freeze / mute control - - /// Steps the engine block-by-block, invoking `onFrame` before each block so a test can engage the - /// freeze or mute the source at chosen frames. Returns the left output channel. - private func stepRender( - totalFrames: Int, - blockSize: Int, - configure: (FreezePedal) -> Void, - onFrame: (_ frame: Int, _ source: GatedSineSource, _ pedal: FreezePedal) -> Void - ) throws -> [Float] { - let numAudioBuses: Int = 64 - let numControlBuses: Int = 512 - let driver: OfflineDriver = OfflineDriver() - let engine: SynthesisEngine = SynthesisEngine( - blockSize: blockSize, - sampleRate: sampleRate, - numOutputChannels: 2, - numInputChannels: 0, - numAudioBuses: numAudioBuses, - numControlBuses: numControlBuses, - driver: driver - ) - - 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: GatedSineSource = GatedSineSource(targetBus: srcBus.index, freq: sineHz) - let pedal: FreezePedal = FreezePedal(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() - - let noInput: [[Float]] = [] - var left: [Float] = [] - left.reserveCapacity(totalFrames) - var frame: Int = 0 - while frame < totalFrames { - onFrame(frame, source, pedal) - engine.processBlock(inputSamples: noInput) - left.append(contentsOf: engine.audioBuses[0]) - frame += blockSize - } - engine.stop() - return left - } - - // MARK: - Analysis - - private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double { - let a: Int = max(0, loFrame) - let b: Int = min(hiFrame, samples.count) - guard b > a else { return 0.0 } - var sum: Double = 0.0 - for i: Int in a ..< b { - let v: Double = Double(samples[i]) - sum += v * v - } - return (sum / Double(b - a)).squareRoot() - } - - private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double { - let a: Int = max(1, lo) - let b: Int = min(hi, x.count) - guard b > a else { return 0.0 } - var m: Double = 0.0 - for i: Int in a ..< b { - let d: Double = abs(Double(x[i]) - Double(x[i - 1])) - if d > m { m = d } - } - return m - } - - // MARK: - Behaviour - - @Test func buildsAndProducesNonSilentOutput() throws { - // Unfrozen, the dry signal passes straight through — output is never silent. - let out: [Float] = try render(duration: 1.0) { _ in } - #expect(!out.isEmpty) - #expect(hasNonSilentOutput(out), "Freeze output was silent") - } - - @Test func renderIsDeterministic() throws { - // No RNG anywhere in the graph, so two identical renders are bit-identical. - let a: [Float] = try render(duration: 1.0) { pedal in pedal.verb = 0.6; pedal.tone = 0.4 } - let b: [Float] = try render(duration: 1.0) { pedal in pedal.verb = 0.6; pedal.tone = 0.4 } - #expect(a == b, "deterministic freeze-reverb renders of the same setting should be bit-identical") - } - - @Test func snapshotSustainsAfterInputStops() throws { - // The defining behaviour: engage Freeze while a tone plays, then MUTE the input. A held - // spectral snapshot keeps ringing; without the freeze the pad gate is shut, so once the dry - // input is gone the output falls silent. Compare the two in the same late window. - let blockSize: Int = 512 - let totalFrames: Int = Int(1.6 * sampleRate) - let freezeFrame: Int = Int(0.45 * sampleRate) - let muteFrame: Int = Int(0.75 * sampleRate) - let windowLo: Int = Int(1.1 * sampleRate) - let windowHi: Int = Int(1.5 * sampleRate) - - let frozen: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in - pedal.verb = 0.6; pedal.tone = 0.5; pedal.rise = 0.05 - } onFrame: { frame, source, pedal in - if frame >= freezeFrame, !pedal.holding { pedal.toggleFreeze() } - if frame >= muteFrame { source.gain = 0.0 } - } - - let control: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in - pedal.verb = 0.6; pedal.tone = 0.5; pedal.rise = 0.05 - } onFrame: { frame, source, _ in - // Never freeze; mute at the same frame. - if frame >= muteFrame { source.gain = 0.0 } - } - - let heldTail: Double = rms(frozen, loFrame: windowLo, hiFrame: windowHi) - let unfrozenTail: Double = rms(control, loFrame: windowLo, hiFrame: windowHi) - - #expect(heldTail > 1.0e-3, "a held snapshot should still ring after the input stops, tail RMS \(heldTail)") - #expect(heldTail > unfrozenTail * 10.0, - "frozen tail \(heldTail) should dwarf the unfrozen tail \(unfrozenTail) once the input is muted") - } - - @Test func releaseFadesThePadOut() throws { - // Freeze, mute the input, then release: after the Rise fade the held pad should fall away, - // leaving the late window far quieter than while it was held. - let blockSize: Int = 512 - let totalFrames: Int = Int(2.0 * sampleRate) - let freezeFrame: Int = Int(0.4 * sampleRate) - let muteFrame: Int = Int(0.7 * sampleRate) - let releaseFrame: Int = Int(1.1 * sampleRate) - let heldLo: Int = Int(0.95 * sampleRate) - let heldHi: Int = Int(1.05 * sampleRate) - let afterLo: Int = Int(1.7 * sampleRate) - let afterHi: Int = Int(1.95 * sampleRate) - - var froze: Bool = false - var released: Bool = false - let out: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in - pedal.verb = 0.5; pedal.tone = 0.5; pedal.rise = 0.1 - } onFrame: { frame, source, pedal in - if frame >= freezeFrame, !froze { pedal.toggleFreeze(); froze = true } - if frame >= muteFrame { source.gain = 0.0 } - if frame >= releaseFrame, froze, !released { pedal.toggleFreeze(); released = true } - } - - let heldRMS: Double = rms(out, loFrame: heldLo, hiFrame: heldHi) - let afterRMS: Double = rms(out, loFrame: afterLo, hiFrame: afterHi) - #expect(heldRMS > 1.0e-3, "pad should be audible while held, got \(heldRMS)") - #expect(afterRMS < heldRMS * 0.5, "releasing should fade the pad out: after \(afterRMS) vs held \(heldRMS)") - } - - // MARK: - Bypass - - @Test func bypassSwitchIsClickFree() throws { - let blockSize: Int = 512 - let totalFrames: Int = Int(0.6 * sampleRate) - let flipFrame: Int = Int(0.35 * sampleRate) - // Steady-state window ends before the flip; a settle margin after it covers the fade tail. - let steadyLo: Int = Int(0.22 * sampleRate) - let steadyHi: Int = Int(0.33 * sampleRate) - let settleMargin: Int = Int(0.045 * sampleRate) - let left: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in - pedal.verb = 0.5 - } onFrame: { frame, _, pedal in - if frame >= flipFrame { pedal.bypass = 1.0 } - } - #expect(hasNonSilentOutput(left), "bypass-flip render was silent") - - let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi) - let fadeFrames: Int = Int(0.03 * sampleRate) - let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + settleMargin) - #expect(transStep <= steadyStep * 4.0, - "bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through") - } - - // MARK: - Wiring - - @Test func exposesControls() throws { - let pedal: FreezePedal = FreezePedal() - #expect(pedal.effectKnobs.map { $0.label } == ["Verb", "Tone", "Rise"]) - #expect(pedal.effectTransportButtons.map { $0.label } == ["Freeze"]) - #expect(pedal.showsMixControl == false) - } - - @Test func freezeTogglesHoldState() throws { - // The transport latch flips the held state without needing a running engine. - let pedal: FreezePedal = FreezePedal() - #expect(pedal.holding == false) - pedal.toggleFreeze() - #expect(pedal.holding == true) - #expect(pedal.frozen == 1.0) - pedal.toggleFreeze() - #expect(pedal.holding == false) - #expect(pedal.frozen == 0.0) - } - - @Test func presetRoundTripPreservesControls() throws { - let pedal: FreezePedal = FreezePedal() - pedal.verb = 0.33 - pedal.tone = 0.8 - pedal.rise = 1.5 - - let state: PedalState = pedal.captureState() - let restored: FreezePedal = FreezePedal() - restored.applyState(state) - - #expect(restored.verb == 0.33) - #expect(restored.tone == 0.8) - #expect(restored.rise == 1.5) - } - - @Test func heldSnapshotIsNotPersisted() throws { - // `frozen` is transport state, not a preset control: a pedal captured mid-freeze must restore - // released, with no phantom pad blooming on load. - let pedal: FreezePedal = FreezePedal() - pedal.verb = 0.4 - pedal.toggleFreeze() - #expect(pedal.holding == true) - #expect(pedal.frozen == 1.0) - - let state: PedalState = pedal.captureState() - let restored: FreezePedal = FreezePedal() - restored.applyState(state) - - #expect(restored.frozen == 0.0, "a held snapshot must not persist into a preset") - #expect(restored.holding == false) - #expect(restored.verb == 0.4) - } - - @Test func registeredInBuiltInRegistry() throws { - let pedal: Pedal? = PedalRegistry.makePedal(type: "Freeze") - #expect(pedal is FreezePedal) - } -} diff --git a/Tests/LyrebirdShoeGazeTests/TunedVerbPedalTests.swift b/Tests/LyrebirdShoeGazeTests/TunedVerbPedalTests.swift new file mode 100644 index 0000000..8b89d04 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/TunedVerbPedalTests.swift @@ -0,0 +1,310 @@ +// TunedVerbPedalTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +/// A source that crossfades between two tones under a `morph` parameter, so a test can capture the +/// filter on tone A, then switch to tone B and show the locked spectrum shapes B differently than +/// live tracking would. +@MainActor +private final class TwoToneSource: SynthesizerBase { + private let targetBus: Int + private let freqA: Double + private let freqB: Double + /// `0` = tone A, `1` = tone B. + @UIParam var morph: Double = 0.0 + + init(targetBus: Int, freqA: Double, freqB: Double) { + self.targetBus = targetBus + self.freqA = freqA + self.freqB = freqB + super.init() + } + + override func build() { + let a: BinaryOpGenerator = OscSin.Audio(freq: freqA, mul: 0.5) * (1.0 - $morph) + let b: BinaryOpGenerator = OscSin.Audio(freq: freqB, mul: 0.5) * $morph + output(bus: targetBus, source: a + b) + } +} + +/// A steady sine for the non-silent / determinism / pan / bypass checks. +@MainActor +private final class TestSineSource: SynthesizerBase { + private let targetBus: Int + private let freq: Double + + init(targetBus: Int, freq: Double) { + self.targetBus = targetBus + self.freq = freq + super.init() + } + + override func build() { + output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: 0.5)) + } +} + +@MainActor +@Suite("TunedVerbPedal") +struct TunedVerbPedalTests { + + private let sampleRate: Double = 44_100.0 + private let toneHz: Double = 220.0 + + // MARK: - One-shot NRT render + + private func render( + duration: Double, + configure: (TunedVerbPedal) -> Void + ) throws -> [Float] { + let numAudioBuses: Int = 64 + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: duration, + 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: 2) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: toneHz) + let pedal: TunedVerbPedal = TunedVerbPedal(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) + } + + // MARK: - Block-stepped render (mid-render capture / input morph) + + private func stepRender( + totalFrames: Int, + blockSize: Int, + configure: (TunedVerbPedal) -> Void, + onFrame: (_ frame: Int, _ source: TwoToneSource, _ pedal: TunedVerbPedal) -> Void + ) throws -> [Float] { + let numAudioBuses: Int = 64 + let numControlBuses: Int = 512 + let driver: OfflineDriver = OfflineDriver() + let engine: SynthesisEngine = SynthesisEngine( + blockSize: blockSize, + sampleRate: sampleRate, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: numAudioBuses, + numControlBuses: numControlBuses, + driver: driver + ) + + let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1) + let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2) + defer { + engine.busAllocator.releaseAudioBus(srcBus) + engine.busAllocator.releaseAudioBus(dstBus) + } + + let source: TwoToneSource = TwoToneSource(targetBus: srcBus.index, freqA: 180.0, freqB: 900.0) + let pedal: TunedVerbPedal = TunedVerbPedal(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() + + let noInput: [[Float]] = [] + var left: [Float] = [] + left.reserveCapacity(totalFrames) + var frame: Int = 0 + while frame < totalFrames { + onFrame(frame, source, pedal) + engine.processBlock(inputSamples: noInput) + left.append(contentsOf: engine.audioBuses[0]) + frame += blockSize + } + engine.stop() + return left + } + + // MARK: - Analysis + + private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double { + let a: Int = max(0, loFrame) + let b: Int = min(hiFrame, samples.count) + guard b > a else { return 0.0 } + var sum: Double = 0.0 + for i: Int in a ..< b { let v: Double = Double(samples[i]); sum += v * v } + return (sum / Double(b - a)).squareRoot() + } + + private func rmsDiff(_ a: [Float], _ b: [Float], loFrame: Int, hiFrame: Int) -> Double { + let lo: Int = max(0, loFrame) + let hi: Int = min(hiFrame, min(a.count, b.count)) + guard hi > lo else { return 0.0 } + var sum: Double = 0.0 + for i: Int in lo ..< hi { let d: Double = Double(a[i]) - Double(b[i]); sum += d * d } + return (sum / Double(hi - lo)).squareRoot() + } + + private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double { + let a: Int = max(1, lo) + let b: Int = min(hi, x.count) + guard b > a else { return 0.0 } + var m: Double = 0.0 + for i: Int in a ..< b { let d: Double = abs(Double(x[i]) - Double(x[i - 1])); if d > m { m = d } } + return m + } + + // MARK: - Behaviour + + @Test func buildsAndProducesNonSilentOutput() throws { + let out: [Float] = try render(duration: 0.8) { _ in } + #expect(!out.isEmpty) + #expect(hasNonSilentOutput(out), "TunedVerb output was silent") + } + + @Test func renderIsDeterministic() throws { + let a: [Float] = try render(duration: 0.8) { pedal in pedal.time = 4.0; pedal.damp = 0.4 } + let b: [Float] = try render(duration: 0.8) { pedal in pedal.time = 4.0; pedal.damp = 0.4 } + #expect(a == b, "deterministic capture-reverb renders of the same setting should be bit-identical") + } + + @Test func panShiftsTheLeftLeg() throws { + // Fully wet, the output follows the panned wash. Hard left fills the left leg; hard right + // nearly empties it. (Tests exercise the left output leg; the right is board-wired live.) + let hardLeft: [Float] = try render(duration: 0.6) { pedal in pedal.mix = 1.0; pedal.pan = -1.0 } + let hardRight: [Float] = try render(duration: 0.6) { pedal in pedal.mix = 1.0; pedal.pan = 1.0 } + let leftRMS: Double = rms(hardLeft, loFrame: 0, hiFrame: hardLeft.count) + let rightRMS: Double = rms(hardRight, loFrame: 0, hiFrame: hardRight.count) + #expect(leftRMS > rightRMS * 3.0, + "panning hard left should fill the left leg far more than hard right: L \(leftRMS) vs R \(rightRMS)") + } + + @Test func captureLocksTheFilterSoAChangedInputIsShapedDifferently() throws { + // Capture the filter on tone A, then morph the input to tone B. A locked filter (shaped by A) + // masks B differently than a filter that keeps tracking the live input — so the two renders + // diverge once the input has changed. + let blockSize: Int = 512 + let totalFrames: Int = Int(1.4 * sampleRate) + let captureFrame: Int = Int(0.4 * sampleRate) + let morphFrame: Int = Int(0.6 * sampleRate) + let windowLo: Int = Int(0.95 * sampleRate) + let windowHi: Int = Int(1.35 * sampleRate) + + var captured: Bool = false + let locked: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in + pedal.mix = 1.0; pedal.time = 3.0 + } onFrame: { frame, source, pedal in + if frame >= captureFrame, !captured { pedal.toggleCapture(); captured = true } + if frame >= morphFrame { source.morph = 1.0 } // switch to tone B + } + + let tracking: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in + pedal.mix = 1.0; pedal.time = 3.0 + } onFrame: { frame, source, _ in + // Never capture; morph at the same frame. + if frame >= morphFrame { source.morph = 1.0 } + } + + let signal: Double = rms(tracking, loFrame: windowLo, hiFrame: windowHi) + let diff: Double = rmsDiff(locked, tracking, loFrame: windowLo, hiFrame: windowHi) + #expect(signal > 1.0e-4, "control render should be audible on tone B, got \(signal)") + #expect(diff > signal * 0.25, + "a captured filter should shape the changed input differently: diff \(diff) vs signal \(signal)") + } + + // MARK: - Bypass + + @Test func bypassSwitchIsClickFree() throws { + let blockSize: Int = 512 + let totalFrames: Int = Int(0.6 * sampleRate) + let flipFrame: Int = Int(0.35 * sampleRate) + let steadyLo: Int = Int(0.22 * sampleRate) + let steadyHi: Int = Int(0.33 * sampleRate) + let settleMargin: Int = Int(0.045 * sampleRate) + let left: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in + pedal.mix = 0.5 + } onFrame: { frame, _, pedal in + if frame >= flipFrame { pedal.bypass = 1.0 } + } + #expect(hasNonSilentOutput(left), "bypass-flip render was silent") + + let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi) + let fadeFrames: Int = Int(0.03 * sampleRate) + let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + settleMargin) + #expect(transStep <= steadyStep * 4.0, + "bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through") + } + + // MARK: - Wiring + + @Test func exposesControls() throws { + let pedal: TunedVerbPedal = TunedVerbPedal() + #expect(pedal.effectKnobs.map { $0.label } == ["Time", "Damp", "Pan"]) + #expect(pedal.effectTransportButtons.map { $0.label } == ["Capture"]) + #expect(pedal.channelKind == .widener) + } + + @Test func captureTogglesHoldState() throws { + let pedal: TunedVerbPedal = TunedVerbPedal() + #expect(pedal.holding == false) + pedal.toggleCapture() + #expect(pedal.holding == true) + #expect(pedal.captured == 1.0) + pedal.toggleCapture() + #expect(pedal.holding == false) + #expect(pedal.captured == 0.0) + } + + @Test func presetRoundTripPreservesControls() throws { + let pedal: TunedVerbPedal = TunedVerbPedal() + pedal.time = 8.5 + pedal.damp = 0.7 + pedal.pan = -0.6 + + let state: PedalState = pedal.captureState() + let restored: TunedVerbPedal = TunedVerbPedal() + restored.applyState(state) + + #expect(restored.time == 8.5) + #expect(restored.damp == 0.7) + #expect(restored.pan == -0.6) + } + + @Test func capturedStateIsNotPersisted() throws { + // `captured` is transport state, not a preset control. + let pedal: TunedVerbPedal = TunedVerbPedal() + pedal.toggleCapture() + #expect(pedal.captured == 1.0) + + let state: PedalState = pedal.captureState() + let restored: TunedVerbPedal = TunedVerbPedal() + restored.applyState(state) + + #expect(restored.captured == 0.0, "a locked filter must not persist into a preset") + #expect(restored.holding == false) + } + + @Test func registeredInBuiltInRegistry() throws { + let pedal: Pedal? = PedalRegistry.makePedal(type: "TunedVerb") + #expect(pedal is TunedVerbPedal) + } +}