// 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 } }